# ProductCraft SDKs: rules for coding agents

These rules teach a coding agent to use the ProductCraft SDKs for Auth, Mail, Waitlist, Social, Trawl, Flags, Notify, Platform. They are generated from the published packages (@productcraft/auth@1.4.0, @productcraft/mail@1.4.0, @productcraft/waitlist@2.1.0, @productcraft/social@1.6.0, @productcraft/trawl@1.4.0, @productcraft/flags@0.5.0, @productcraft/notify@0.1.0, @productcraft/platform-auth@1.3.0), so the methods below are the ones that exist. Get the latest copy: https://productcraft.co/docs/ai/rules?format=agents

## Rules for every ProductCraft SDK

1. **Use only the methods listed in this file.** Each product section ends with every resource and method its SDK has. If what you need is not there, call the typed escape hatch `<client>.client.GET("/v1/…")` with a path from the product's OpenAPI document. Never invent a method or an endpoint.
2. **Keys stay on the server.** A workspace API key (`pcft_live_…`) is read from `PRODUCTCRAFT_API_KEY` when you pass none. Never put it in `NEXT_PUBLIC_*` or any variable a bundler inlines into browser code. Set `PRODUCTCRAFT_WORKSPACE_ID` to skip the one lookup a client makes on a cold start.
3. **Field names are snake_case**, in request params and in responses, exactly as the examples below show (`display_name`, `workspace_id`). Do not camelCase them.
4. **Lists page by cursor.** `for await (const item of client.resource.list())` walks every page; `await client.resource.list().toArray({ maxItems: 500 })` collects a bounded number.
5. **Errors are classes.** Catch `NotFoundError`, `RateLimitError` and the other `APIError` subclasses exported by each package. Branch on `err.code` (a stable UPPER_SNAKE string) and log `err.requestId`.
6. **Writes are idempotent.** The SDK sends an `Idempotency-Key` on every write that supports one and reuses it on retry. When the same write can be retried from another process (a queue, a cron), pass your own: `{ idempotencyKey: "order-1234" }` as the last argument.
7. **Verify every webhook** with `<client>.webhooks.unwrap({ payload, headers })` on the **raw** request body (`await req.text()`, or `express.raw()`). Parsing the JSON first breaks the signature.
8. **Tests need no network.** `createMockFetch()` from `@productcraft/<product>/testing` answers every operation with its spec example: `new Mail({ apiKey: "test", workspaceId: "…", fetch: createMockFetch() })`. Mail sends in tests go to `success@simulator.amazonses.com`, never to made-up addresses.
9. **Docs are Markdown too.** Add `.md` to any https://productcraft.co/docs URL, or send `Accept: text/markdown`. The index is https://productcraft.co/llms.txt.
10. **To operate a workspace rather than write code** (read a delivery log, approve waitlist entries, look at a flag), connect the MCP server `https://mcp.productcraft.co/mcp`. A person approves what it may do in the browser; see https://productcraft.co/docs/ai.

## Auth: `@productcraft/auth` 1.4.0

Node.js / TypeScript client for **ProductCraft Auth**: sign-in, sign-up, sessions, profiles, MFA, passkeys and tenants for the end users of the apps you build, plus the admin API for those apps (end users, roles, permissions, API keys, M2M credentials, config, webhooks) and offline token verification.

Every HTTP method, type, error class and mock is generated from the production OpenAPI spec. Upgrading from 0.x? See the [1.0 migration guide](https://github.com/clauderanelagh/productcraft-node/blob/main/docs/migrations/auth-1.0.0.md): every 0.6 and 0.8 method name still works as a deprecated alias.

### Install

```sh
npm install @productcraft/auth
```

Node 20.3 or later (ESM and CommonJS), Bun, Deno and edge runtimes. Or install the umbrella package for every product: `npm install productcraft`.

### Two scopes

| Scope | Who calls it | Credential |
|---|---|---|
| `auth.consumer(slug)`: sign-in, sign-up, refresh, `me`, MFA, passkeys, tenants | Your app's backend or browser, for its end users | Depends on the route (below) |
| `auth.admin.app(appId)` (alias `auth.app(appId)`): end users, roles, keys, config, webhooks | Your backend or tooling | A workspace API key (`PRODUCTCRAFT_API_KEY`) or a platform session |

`auth.consumer()` defaults its slug to `PRODUCTCRAFT_AUTH_APP` and never reads `PRODUCTCRAFT_API_KEY`: routes that act for an end user must not carry your workspace key by accident. Pass the credential a route needs explicitly. Each method's reference entry in [api.md](./api.md#credentials) names it, and a wrong one answers 401:

| `auth.consumer(slug)` routes | Credential | How to pass it |
|---|---|---|
| `signin`, `refresh`, `verifyEmail`, `resetPassword`, `passkey.*`, `mfa.*`, `oauth.token`, `verify.*`, `wellKnown.*` | None | `auth.consumer(slug)` |
| `me.*`, `switchTenant`, `tenantApiKeys` create/list/rotate/delete | The end user's access token | `new Auth({ auth: { type: "bearer", token: accessToken } }).consumer(slug)` |
| `users.*`, `roles.*`, `permissions.*` (your backend managing the app's users) | An app API key (`hdk_live_…`, from `admin.app(id).apiKeys.create`), an M2M token, or an end user whose role holds the permission. **Not** a workspace key | `new Auth({ auth: { type: "bearer", token: process.env.AUTH_APP_API_KEY } }).consumer(slug)` |
| `tenants.*`, `users.factors.*`, `tenantApiKeys.introspect`/`status`/`config`, `requestVerification`, `sendVerificationEmail`, `requestPasswordReset`, `sendPasswordResetEmail`, `signup` (when the app requires it) | A workspace API key | `new Auth({ auth: { type: "bearer", token: process.env.PRODUCTCRAFT_API_KEY } }).consumer(slug)` |

**`consumer(slug).users` or `admin.app(id).endUsers`?** Both manage the same end users. Use `admin.app(id).endUsers` (and `.roles`, `.permissions`, `.tenants`) from your own tooling with your workspace API key: it covers more (search, export, import, bulk changes, sessions). Use `consumer(slug).users` from your product's backend when it should hold only an app-scoped credential (an app API key or M2M token), never your workspace key.

### Quick start

A new app has sign-up turned off (`signup` answers 403 "Signup is disabled for this app"). Turn it on once, with your workspace API key:

```ts
import { Auth } from "@productcraft/auth";

const auth = new Auth(); // reads PRODUCTCRAFT_API_KEY
const created = await auth.apps.create({ slug: "my-app", display_name: "My App", workspace_id: "5d1e2f3a-4b5c-4d6e-8f9a-0b1c2d3e4f5a" });
await auth.admin.app(created.id).authConfig.update({ signup_enabled: true });
```

Then sign end users up and in:

```ts
import { Auth, AuthenticationError } from "@productcraft/auth";

const auth = new Auth();
const app = auth.consumer("my-app");

// Sign in an end user. `result` says whether MFA is still needed.
const session = await app.signin({ identifier: "ada@example.com", password: "correct horse battery staple" });
if (session.result === "session") {
  // Verify the access token offline against the app's JWKS (cached per app).
  const claims = await auth.verifyToken(session.access_token, { app: "my-app" });
  console.log(claims.sub);

  // Calls as the signed-in user carry their access token.
  const me = await new Auth({ auth: { type: "bearer", token: session.access_token } }).consumer("my-app").me.retrieve();
  console.log(me.email, me.email_verified_at);
}

try {
  await app.signin({ identifier: "ada@example.com", password: "wrong" });
} catch (err) {
  if (err instanceof AuthenticationError) console.log(err.code, err.requestId);
}
```

### Admin

```ts
import { Auth } from "@productcraft/auth";

// Reads PRODUCTCRAFT_API_KEY from the environment.
const auth = new Auth();
const admin = auth.admin.app("5d1e2f3a-4b5c-4d6e-8f9a-0b1c2d3e4f5a");

for await (const user of admin.endUsers.list({ limit: 100 })) {
  console.log(user.id, user.email);
}
const endpoint = await admin.webhooks.endpoints.create({ url: "https://api.acme.com/webhooks/auth" });
console.log(endpoint.signing_secret); // shown once
```

### Verifying tokens in your backend

`auth.verifyToken(jwt, { app })` (or `auth.consumer(slug).verifyToken(jwt)`) checks the signature against the app's JWKS, the expiry, the per-app issuer (`https://api.auth.productcraft.co/<slug>`) and the audience (the slug), and refuses refresh tokens (`JwtRefreshTokenError`). Every failure is a `JwtVerifyError` subclass. For Passport, use [`@productcraft/auth-passport`](https://www.npmjs.com/package/@productcraft/auth-passport).

### Passkeys (browser)

`auth.consumer(slug).passkeys` runs whole WebAuthn ceremonies in one call each: `enroll()`, `signIn()`, `completeMfaChallenge({ mfa_token })` and `stepUp()`. They need a browser at call time; importing is safe anywhere.

### Webhooks

`auth.webhooks.unwrap()` verifies the signature against the **raw** body and returns a typed `Auth.UnwrapWebhookEvent`. The secret comes from `{ secret }`, the client's `webhookSecret`, or `PRODUCTCRAFT_AUTH_WEBHOOK_SECRET`.

```ts
import { Auth } from "@productcraft/auth";
const auth = new Auth();
export async function POST(req: Request) {
  const event = await auth.webhooks.unwrap({ payload: await req.text(), headers: req.headers });
  switch (event.type) {
    case "app.slug_changed":
      console.log(event.data);
      break;
    default:
      break; // UnknownWebhookEvent: types added later
  }
  return new Response(null, { status: 204 });
}
```

### Every method

`new Auth()` has these resources and methods, and no others:

- `auth.admin.app(…)`: `clone`, `updateStatus`
- `auth.admin.app(…).apiKeys`: `create`, `delete`, `list`, `rotate`
- `auth.admin.app(…).auditLogs`: `export`, `list`
- `auth.admin.app(…).auditSink`: `disconnect`, `replace`, `retrieve`, `rotateSecret`, `setupStatus`, `test`, `update`
- `auth.admin.app(…).authConfig`: `providers.check`, `providers.delete`, `providers.list`, `providers.replace`, `providers.retrieve`, `providers.update`, `retrieve`, `update`
- `auth.admin.app(…).credentials`: `create`, `delete`, `list`, `retrieve`, `rotate`, `update`, `updateScopes`
- `auth.admin.app(…).customDomains`: `apply`, `check`, `create`, `delete`, `export`, `list`, `retrieve`
- `auth.admin.app(…).endUserInsights`: `retrieve`, `users.retrieve`
- `auth.admin.app(…).endUsers`: `bulkDelete`, `bulkRevokeSessions`, `bulkUpdateRole`, `bulkUpdateStatus`, `contacts.create`, `contacts.delete`, `contacts.list`, `contacts.promote`, `contacts.resendVerification`, `delete`, `export`, `imports.create`, `imports.retrieve`, `invites.create`, `invites.delete`, `invites.list`, `list`, `mfa.requireReenrollment`, `resendVerification`, `retrieve`, `sessions.revokeAll`, `update`, `updateRole`, `updateStatus`
- `auth.admin.app(…).members`: `delete`, `list`
- `auth.admin.app(…).notificationSettings`: `retrieve`, `update`
- `auth.admin.app(…).notifications`: `test`
- `auth.admin.app(…).permissions`: `create`, `delete`, `enforcement.list`, `list`
- `auth.admin.app(…).roles`: `assign`, `create`, `delete`, `list`, `permissions.list`, `retrieve`, `update`, `updatePermissions`
- `auth.admin.app(…).setupStatus`: `retrieve`
- `auth.admin.app(…).signInTests`: `create`, `retrieve`
- `auth.admin.app(…).tenantApiKeys`: `config.retrieve`, `config.update`, `delete`, `list`
- `auth.admin.app(…).tenants`: `create`, `delete`, `invites.create`, `invites.delete`, `invites.list`, `list`, `members.create`, `members.delete`, `members.list`, `members.update`, `retrieve`, `update`
- `auth.admin.app(…).unverifiedAccountExpiry`: `retrieve`, `run`
- `auth.admin.app(…).webauthnConfig`: `retrieve`, `update`
- `auth.admin.app(…).webhooks`: `endpoints.create`, `endpoints.delete`, `endpoints.list`, `endpoints.retrieve`, `endpoints.rotateSecret`, `endpoints.test`, `endpoints.update`, `eventTypes.list`, `events.list`, `events.replay`, `events.retrieve`
- `auth.apps`: `create`, `delete`, `list`, `retrieve`, `update`
- `auth.consumer(…)`: `acceptInvite`, `acceptTenantInvite`, `exchangeProviderCode`, `logout`, `refresh`, `requestPasswordReset`, `requestVerification`, `resetPassword`, `sendPasswordResetEmail`, `sendVerificationEmail`, `signin`, `signinWithProvider`, `signup`, `switchTenant`, `verifyEmail`
- `auth.consumer(…).me`: `activity.list`, `changePassword`, `contacts.create`, `contacts.delete`, `contacts.list`, `contacts.promote`, `deleteAccount`, `deleteAvatar`, `mfa.factors.create`, `mfa.factors.delete`, `mfa.factors.list`, `mfa.factors.verify`, `mfa.recoveryCodes.regenerate`, `mfa.stepUp.sendCode`, `mfa.stepUp.verify`, `mfa.stepUp.webauthn.options`, `permissions`, `retrieve`, `sessions.delete`, `sessions.list`, `tenantInvites.accept`, `tenants.list`, `update`, `uploadAvatar`
- `auth.consumer(…).mfa`: `enroll`, `recover`, `sendCode`, `verify`, `verifyEnrollment`, `webauthn.options`
- `auth.consumer(…).oauth`: `introspect`, `token`
- `auth.consumer(…).passkey`: `options`, `verify`
- `auth.consumer(…).permissions`: `create`, `delete`, `list`
- `auth.consumer(…).roles`: `create`, `delete`, `list`, `retrieve`, `update`, `updatePermissions`
- `auth.consumer(…).tenantApiKeys`: `config.retrieve`, `config.update`, `create`, `delete`, `introspect`, `list`, `rotate`, `status`
- `auth.consumer(…).tenants`: `create`, `delete`, `invites.create`, `invites.delete`, `invites.list`, `list`, `members.create`, `members.delete`, `members.list`, `members.update`, `retrieve`, `update`
- `auth.consumer(…).users`: `create`, `delete`, `factors.create`, `factors.delete`, `factors.list`, `list`, `retrieve`, `update`, `updateRole`, `updateStatus`
- `auth.consumer(…).verify`: `authorize`, `authorizeBatch`, `token`
- `auth.consumer(…).wellKnown`: `jwks`, `openidConfiguration`
- `auth.stats`: `me`, `retrieve`

### Docs

- Guides as Markdown: https://productcraft.co/docs/auth.md
- API reference: https://productcraft.co/docs/auth/api-reference.md
- OpenAPI document: https://api.auth.productcraft.co/docs-json

## Mail: `@productcraft/mail` 1.4.0

Node.js / TypeScript client for **ProductCraft Mail**: transactional email (raw HTML or templates), sending domains with DKIM, the per-recipient delivery log, contacts, segments, broadcasts, suppression lists and signed webhooks.

Every method, type, error class and mock is generated from the production OpenAPI spec. Upgrading from 0.x? See the [1.0 migration guide](https://github.com/clauderanelagh/productcraft-node/blob/main/docs/migrations/mail-1.0.0.md).

### Install

```sh
npm install @productcraft/mail
```

Node 20.3 or later, Bun, Deno and edge runtimes. Or install the umbrella package for every product: `npm install productcraft`.

### Quick start

```ts
import { Mail } from "@productcraft/mail";

// Reads PRODUCTCRAFT_API_KEY (and PRODUCTCRAFT_WORKSPACE_ID) from the environment.
const mail = new Mail({ workspaceId: "9b2f6c1e-0d6a-4a63-9a43-2f1c3e4d5a6b" });

// Send raw HTML (an Idempotency-Key is generated for you, so a retry never sends twice).
const email = await mail.emails.send({
  from: "Acme <hello@mail.acme.com>",
  to: "success@simulator.amazonses.com",
  subject: "Welcome",
  html: "<p>Thanks for signing up.</p>",
});
console.log(email.id);

// Or render a stored template with your data.
await mail.templates.send("welcome", { to: "success@simulator.amazonses.com", data: { first_name: "Ada" } });

// Walk the delivery log; pages are fetched as you iterate.
for await (const message of mail.messages.list({ status: ["bounced", "complained"] })) {
  console.log(message.id, message.status);
}
```

`workspaceId` is optional for workspace API keys: without it the client looks it up once per process (one extra request on a cold start). Pass it, or set `PRODUCTCRAFT_WORKSPACE_ID`, to skip the lookup. Bearer tokens must always pass it.

Nouns: `emails` is the call you made (send, batch, list, retrieve, metrics); `messages` is the per-recipient delivery log of what you sent (list, retrieve, body, export, erase); `received` is the mail your domains received, with its daily `timeline`. Exports, raw MIME and attachments resolve to the raw `Response` (`.text()`, `.arrayBuffer()`, `.body`).

### Credentials

Pass `apiKey` (a workspace key, `pcft_live_…`), or omit it and the client reads `PRODUCTCRAFT_API_KEY`. An explicit `auth: { type: "bearer", token }` works for platform user tokens. The environment fallback is server-only: never put a key in `NEXT_PUBLIC_*` or any variable a bundler inlines into browser code (a workspace key in a browser throws unless you set `dangerouslyAllowBrowser: true`).

Webhook signing secrets: Mail has a workspace default secret, per-domain secrets and one per endpoint. Pass all that apply as an array (`new Mail({ webhookSecret: [a, b] })` or `mail.webhooks.unwrap({ ..., secret: [a, b] })`); `unwrap` accepts the Standard Webhooks headers and the older `X-Mail-Signature` scheme.

### Webhooks

`mail.webhooks.unwrap()` verifies the signature against the **raw** body and returns a typed `Mail.UnwrapWebhookEvent`. The secret comes from `{ secret }`, the client's `webhookSecret`, or `PRODUCTCRAFT_MAIL_WEBHOOK_SECRET`.

```ts
import { Mail } from "@productcraft/mail";
const mail = new Mail();
export async function POST(req: Request) {
  const event = await mail.webhooks.unwrap({ payload: await req.text(), headers: req.headers });
  switch (event.type) {
    case "contact.created":
      console.log(event.data);
      break;
    default:
      break; // UnknownWebhookEvent: types added later
  }
  return new Response(null, { status: 204 });
}
```

### Every method

`new Mail()` has these resources and methods, and no others:

- `mail.brand`: `reset`, `retrieve`, `update`
- `mail.broadcasts`: `audience`, `cancel`, `clickedLinks.list`, `create`, `delete`, `duplicate`, `list`, `recipients.list`, `retrieve`, `send`, `settings.retrieve`, `settings.update`, `update`
- `mail.contacts`: `create`, `delete`, `imports.create`, `imports.list`, `imports.retrieve`, `list`, `properties.create`, `properties.delete`, `properties.list`, `properties.retrieve`, `properties.update`, `retrieve`, `segments.add`, `segments.delete`, `segments.list`, `topics.list`, `topics.update`, `update`
- `mail.deliverability`: `retrieve`
- `mail.domains`: `create`, `delete`, `dnsRecords.apply`, `dnsRecords.check`, `dnsRecords.export`, `dnsRecords.list`, `domainConnect.start`, `events.list`, `list`, `lookup`, `retrieve`, `shareLinks.create`, `shareLinks.delete`, `shareLinks.list`, `smtpConfig.reset`, `smtpConfig.retrieve`, `smtpConfig.update`, `smtpConfig.verifySaved`, `testSend`, `update`, `verify`
- `mail.emails`: `batch`, `list`, `metrics`, `retrieve`, `send`
- `mail.integrations`: `delete`, `github.connect`, `github.repos.branches.list`, `github.repos.list`, `github.settings.update`, `github.sync.create`, `github.sync.retrieve`, `list`, `retrieve`
- `mail.mailboxes`: `create`, `delete`, `list`, `messages.attachments.retrieve`, `messages.delete`, `messages.list`, `messages.raw`, `messages.read`, `messages.retrieve`, `retrieve`, `update`
- `mail.messages`: `body`, `erase`, `export`, `list`, `retrieve`, `settings.retrieve`, `settings.update`
- `mail.received`: `attachments.retrieve`, `delete`, `export`, `list`, `raw`, `read`, `retrieve`, `timeline`
- `mail.segments`: `contacts.list`, `create`, `delete`, `list`, `metrics`, `preview`, `retrieve`, `update`
- `mail.sendingDefaults`: `retrieve`, `update`
- `mail.smtpConfig`: `list`, `reset`, `retrieve`, `update`, `verify`, `verifySaved`
- `mail.stats`: `retrieve`
- `mail.suppression`: `create`, `delete`, `list`
- `mail.templates`: `create`, `delete`, `lint`, `list`, `preview`, `render`, `retrieve`, `send`, `sendBatch`, `tags.list`, `testSend`, `variables.list`
- `mail.topics`: `create`, `delete`, `list`, `retrieve`, `update`
- `mail.webhooks`: `attempts.list`, `endpoints.create`, `endpoints.delete`, `endpoints.list`, `endpoints.retrieve`, `endpoints.rotateSecret`, `endpoints.test`, `endpoints.update`, `eventTypes.list`, `events.list`, `events.replay`, `events.retrieve`

### Docs

- Guides as Markdown: https://productcraft.co/docs/mail.md
- API reference: https://productcraft.co/docs/mail/api-reference.md
- OpenAPI document: https://api.mail.productcraft.co/docs-json

## Waitlist: `@productcraft/waitlist` 2.1.0

Node.js / TypeScript client for **ProductCraft Waitlist**: waitlists with public signup forms, A/B and locale variants, referrals with position and leaderboard, an approval workflow with invite-to-app, CSV export, analytics and signed webhooks.

Every method, type, error class and mock is generated from the production OpenAPI spec. Upgrading from 1.x? See the [2.0 migration guide](https://github.com/clauderanelagh/productcraft-node/blob/main/docs/migrations/waitlist-2.0.0.md) (from 0.x: [1.0](https://github.com/clauderanelagh/productcraft-node/blob/main/docs/migrations/waitlist-1.0.0.md)).

### Install

```sh
npm install @productcraft/waitlist
```

Node 20.3 or later, Bun, Deno, edge runtimes and browsers (the public signup routes). Or install the umbrella package for every product: `npm install productcraft`.

### Quick start: a public signup form (no key, browser-safe)

```ts
import { Waitlist } from "@productcraft/waitlist";

// No API key: the public routes are anonymous and safe to call from a browser bundle.
const form = new Waitlist().public({ workspace: "acme", waitlist: "early-access" });

const info = await form.info.retrieve(); // display name, status, custom fields, active variant
const entry = await form.entries.create({
  email: "ada@example.com",
  name: "Ada Lovelace",
  referral_code: "ADA123", // optional: credits the person who shared their link
});
console.log(info.display_name, entry.position, entry.referral_code);

const { data: top } = await form.leaderboard.list();
```

`entries.create` carries an `Idempotency-Key`, so a retried submit never signs the same person up twice. If the waitlist has a reCAPTCHA site key (`info.recaptcha_site_key`), pass the `recaptcha_token` your page obtained.

### Quick start: manage waitlists (server, workspace key)

```ts
import { Waitlist } from "@productcraft/waitlist";

// Reads PRODUCTCRAFT_API_KEY (and PRODUCTCRAFT_WORKSPACE_ID) from the environment.
const waitlist = new Waitlist({ workspaceId: "9b2f6c1e-0d6a-4a63-9a43-2f1c3e4d5a6b" });

const list = await waitlist.lists.create({ display_name: "Beta", slug: "beta", status: "active" });

// Pages are fetched as you iterate.
for await (const entry of waitlist.lists.entries.list(list.id, { status: "pending" })) {
  console.log(entry.email, entry.position);
}

const { count } = await waitlist.lists.entries.count(list.id);
await waitlist.lists.entries.bulk(list.id, { ids: ["3f0c1a2b-4c5d-4e6f-8a9b-0c1d2e3f4a5b"], action: "approve" });
await waitlist.lists.updateStatus(list.id, { status: "closed" });

const csv = await waitlist.lists.entries.export(list.id); // a raw Response
console.log(count, await csv.text());
```

`waitlist.lists` is the waitlists themselves (the root namespace is named `lists` so it does not read `waitlist.waitlists`). `workspaceId` is optional for workspace API keys: without it the client looks it up once per process. Bearer tokens must always pass it.

### Credentials

Pass `apiKey` (a workspace key, `pcft_live_…`), or omit it and the client reads `PRODUCTCRAFT_API_KEY`. An explicit `auth: { type: "bearer", token }` works for platform user tokens. The environment fallback is server-only: never put a key in `NEXT_PUBLIC_*` or any variable a bundler inlines into browser code. A keyed client constructed in a browser throws unless you set `dangerouslyAllowBrowser: true`; the keyless `new Waitlist()` never does, and `public(…)` calls never send a credential even on a keyed client.

Webhook signing secrets: pass the endpoint's secret (or several, during a rotation) as `new Waitlist({ webhookSecret })` or `waitlist.webhooks.unwrap({ ..., secret })`; `unwrap` accepts the Standard Webhooks headers and the older `X-Waitlist-Signature` scheme.

### Webhooks

`waitlist.webhooks.unwrap()` verifies the signature against the **raw** body and returns a typed `Waitlist.UnwrapWebhookEvent`. The secret comes from `{ secret }`, the client's `webhookSecret`, or `PRODUCTCRAFT_WAITLIST_WEBHOOK_SECRET`.

```ts
import { Waitlist } from "@productcraft/waitlist";
const waitlist = new Waitlist();
export async function POST(req: Request) {
  const event = await waitlist.webhooks.unwrap({ payload: await req.text(), headers: req.headers });
  switch (event.type) {
    case "entry.approved":
      console.log(event.data);
      break;
    default:
      break; // UnknownWebhookEvent: types added later
  }
  return new Response(null, { status: 204 });
}
```

### Every method

`new Waitlist()` has these resources and methods, and no others:

- `waitlist.lists`: `analytics.retrieve`, `analytics.timeline`, `create`, `delete`, `entries.bulk`, `entries.count`, `entries.delete`, `entries.export`, `entries.inviteToApp`, `entries.list`, `entries.retrieve`, `entries.update`, `list`, `retrieve`, `testEntries.create`, `update`, `updateStatus`, `variants.create`, `variants.delete`, `variants.list`, `variants.update`
- `waitlist.public(…).entries`: `create`
- `waitlist.public(…).info`: `retrieve`
- `waitlist.public(…).leaderboard`: `list`
- `waitlist.settings`: `notifications.test`, `retrieve`, `update`
- `waitlist.stats`: `retrieve`
- `waitlist.webhooks`: `endpoints.create`, `endpoints.delete`, `endpoints.list`, `endpoints.retrieve`, `endpoints.rotateSecret`, `endpoints.test`, `endpoints.update`, `eventTypes.list`, `events.list`, `events.replay`, `events.retrieve`

### Docs

- Guides as Markdown: https://productcraft.co/docs/waitlist.md
- API reference: https://productcraft.co/docs/waitlist/api-reference.md
- OpenAPI document: https://api.waitlist.productcraft.co/docs-json

## Social: `@productcraft/social` 1.6.0

Node.js / TypeScript client for **ProductCraft Social**: communities, actors, posts and comments, ranked feeds, stories, the follow graph, direct conversations, notifications and moderation.

Every method, type, error class and mock is generated from the production OpenAPI spec. Coming from 1.0's raw `social.client.POST("/v1/…")` calls? `.client` still works unchanged; the [1.1 migration guide](https://github.com/clauderanelagh/productcraft-node/blob/main/docs/migrations/social-1.1.0.md) shows the resource method for every call shape.

### Install

```sh
npm install @productcraft/social
```

Node 20.3 or later, Bun, Deno and edge runtimes. Server-side only: your backend holds the workspace key (`pcft_live_…`) and calls Social on behalf of your users. Or install the umbrella package for every product: `npm install productcraft`.

### Quick start

```ts
import { Social } from "@productcraft/social";

// Reads PRODUCTCRAFT_API_KEY from the environment.
const social = new Social();

// Workspace-level: communities themselves (the workspace id is resolved from the key, or pass workspaceId).
const { id: communityId } = await social.communities.create({ display_name: "Founders Club", slug: "founders" });

// Community-level: bind the community once, then act as one of its actors.
const community = social.community(communityId);
const { actor } = await community.actors.create({ external_id: "user_123", display_name: "Ada" }); // upsert by your user id
const c = community.as(actor.id); // fills actor_id in every body or query that declares it

const post = await c.posts.create({ body: "Hello from the SDK" });
await c.posts.comments.create(post.id, { body: "First!" });
for await (const item of c.actors.feed.list(actor.id, { limit: 50 })) console.log(item);
```

### Two levels: workspace and community

| Calls on | Reach them through | Typical caller |
|---|---|---|
| Communities (create, list, analytics), moderation, workspace webhooks, stats | `social.communities.*`, `social.webhooks.*`, `social.stats` | Your admin tooling |
| Everything inside one community: actors, posts, comments, feeds, follows, conversations, notifications, community webhooks | `social.community(communityId).…` | Your product backend, per request |

`.as(actorId)` returns a copy of the community scope that fills `actor_id` (the acting user) wherever the API declares it. A call that passes its own `actor_id` wins:

```ts
import { Social } from "@productcraft/social";
declare const communityId: string, adaId: string, graceId: string, postId: string;
const social = new Social();

const asAda = social.community(communityId).as(adaId);
await asAda.follows.create({ dst_actor_id: graceId });                 // actor_id: adaId
await asAda.posts.reactions.create(postId, { type: "like", actor_id: graceId }); // explicit wins
const unread = await asAda.actors.notifications.unreadCount(adaId);
const dm = await asAda.conversations.create({ kind: "direct", recipient_actor_id: graceId });
await asAda.conversations.messages.create(dm.id, { body: "Hi Grace" });
```

Social's wire is snake_case and so are the request and response types: no re-casing. Positional arguments (`postId`, `actorId`) and client options are camelCase.

### Credentials

| Credential | Pass | Use it for |
|---|---|---|
| Workspace API key (`pcft_live_…`) | `apiKey`, or `PRODUCTCRAFT_API_KEY` in the environment | Your backend, for everything |
| Platform session (a signed-in person) | `auth: { type: "bearer", token }` plus `workspaceId` | Admin tooling acting as a console user |

An explicit `apiKey` or `auth` always wins over the environment. The environment fallback is server-only: never put a key in `NEXT_PUBLIC_*` or any variable a bundler inlines into browser code. A keyed client constructed in a browser throws unless you set `dangerouslyAllowBrowser: true`.

### Webhooks

`social.webhooks.unwrap()` verifies the signature against the **raw** body and returns a typed `Social.UnwrapWebhookEvent`. The secret comes from `{ secret }`, the client's `webhookSecret`, or `PRODUCTCRAFT_SOCIAL_WEBHOOK_SECRET`.

```ts
import { Social } from "@productcraft/social";
const social = new Social();
export async function POST(req: Request) {
  const event = await social.webhooks.unwrap({ payload: await req.text(), headers: req.headers });
  switch (event.type) {
    case "actor.updated":
      console.log(event.data);
      break;
    default:
      break; // UnknownWebhookEvent: types added later
  }
  return new Response(null, { status: 204 });
}
```

### Every method

`new Social()` has these resources and methods, and no others:

- `social.communities`: `actors.comments.list`, `actors.reactions.list`, `analytics`, `create`, `delete`, `list`, `moderation.actions.create`, `moderation.actors.shadowBan`, `moderation.actors.unshadowBan`, `moderation.audit.list`, `moderation.blockedTerms.create`, `moderation.blockedTerms.delete`, `moderation.blockedTerms.list`, `moderation.conversations.list`, `moderation.conversations.messages.list`, `moderation.flags.list`, `moderation.flags.resolve`, `moderation.shadowBanned.list`, `retrieve`, `update`, `webhooks.endpoints.create`, `webhooks.endpoints.delete`, `webhooks.endpoints.list`, `webhooks.endpoints.retrieve`, `webhooks.endpoints.rotateSecret`, `webhooks.endpoints.test`, `webhooks.endpoints.update`, `webhooks.eventTypes.list`, `webhooks.events.list`, `webhooks.events.replay`, `webhooks.events.retrieve`
- `social.community(…).actors`: `archived.list`, `assets.list`, `batch`, `blocks.list`, `bookmarks.list`, `byExternal.batch`, `byExternal.retrieve`, `closeFriends.list`, `counters`, `create`, `delete`, `dismissedSuggestions.list`, `drafts.list`, `feed.list`, `followRequests.list`, `followers.list`, `following.list`, `hashtagFollows.create`, `hashtagFollows.delete`, `hashtagFollows.list`, `hides.list`, `highlights.list`, `insights`, `list`, `mentions.list`, `mutedTerms.create`, `mutedTerms.delete`, `mutedTerms.list`, `mutes.list`, `notificationPrefs.list`, `notificationPrefs.update`, `notifications.list`, `notifications.markAllRead`, `notifications.unreadCount`, `notifications.update`, `postState`, `relationships.list`, `restricts.list`, `retrieve`, `scheduledPosts.list`, `storyTray.list`, `suggestedFollows.list`, `tagged.list`, `update`
- `social.community(…).assets`: `complete`, `create`, `delete`, `retrieve`
- `social.community(…).blocks`: `create`, `delete`
- `social.community(…).closeFriends`: `create`, `delete`
- `social.community(…).collections`: `create`, `delete`, `items.create`, `items.delete`, `items.list`, `items.update`, `list`, `retrieve`, `update`
- `social.community(…).connections`: `accept`, `create`, `delete`
- `social.community(…).conversations`: `create`, `delete`, `list`, `markRead`, `members.create`, `members.delete`, `members.update`, `messages.create`, `messages.delete`, `messages.list`, `messages.reactions.create`, `messages.reactions.delete`, `messages.reactions.list`, `messages.retrieve`, `messages.update`, `retrieve`, `unreadCount`, `update`
- `social.community(…).counters`: `list`
- `social.community(…).discoverFeed`: `list`
- `social.community(…).dismissedSuggestions`: `create`, `delete`
- `social.community(…).flags`: `create`, `list`
- `social.community(…).followRequests`: `approve`, `delete`
- `social.community(…).follows`: `batch`, `create`, `delete`
- `social.community(…).hashtags`: `list`, `posts.list`, `retrieve`
- `social.community(…).hides`: `create`, `delete`
- `social.community(…).lists`: `create`, `delete`, `feed.list`, `list`, `members.create`, `members.delete`, `members.list`, `retrieve`, `update`
- `social.community(…).mutes`: `create`, `delete`
- `social.community(…).posts`: `bookmark`, `comments.approve`, `comments.create`, `comments.delete`, `comments.list`, `comments.pin`, `comments.reactions.create`, `comments.reactions.delete`, `comments.reactions.list`, `comments.retrieve`, `comments.unpin`, `comments.update`, `create`, `delete`, `insights`, `list`, `pollResults`, `quotes.list`, `reactions.create`, `reactions.delete`, `reactions.list`, `recordImpressions`, `recordView`, `repost`, `reposts.list`, `retrieve`, `revisions.list`, `tags.approve`, `tags.delete`, `unbookmark`, `unrepost`, `update`, `viewers.list`, `voters.list`, `votes.create`, `votes.delete`, `votes.retrieve`
- `social.community(…).restricts`: `create`, `delete`
- `social.community(…).search`: `actors.list`, `hashtags.list`, `posts.list`
- `social.community(…).webhooks`: `endpoints.create`, `endpoints.delete`, `endpoints.list`, `endpoints.retrieve`, `endpoints.rotateSecret`, `endpoints.test`, `endpoints.update`, `eventTypes.list`, `events.list`, `events.replay`, `events.retrieve`
- `social.stats`: `retrieve`
- `social.webhooks`: `endpoints.create`, `endpoints.delete`, `endpoints.list`, `endpoints.retrieve`, `endpoints.rotateSecret`, `endpoints.test`, `endpoints.update`, `eventTypes.list`, `events.list`, `events.replay`, `events.retrieve`

### Docs

- Guides as Markdown: https://productcraft.co/docs/social.md
- API reference: https://productcraft.co/docs/social/api-reference.md
- OpenAPI document: https://api.social.productcraft.co/docs-json

## Trawl: `@productcraft/trawl` 1.4.0

Node.js / TypeScript client for **ProductCraft Trawl**, AI web extraction. Give Trawl a JSON Schema and a description of what you want (plus optional seed URLs); a browser agent reads the live web and returns data in the shape of your schema.

Every method, type, error class and mock is generated from the production OpenAPI spec. Upgrading from 0.x? See the [1.0 migration guide](https://github.com/clauderanelagh/productcraft-node/blob/main/docs/migrations/trawl-1.0.0.md).

### Install

```sh
npm install @productcraft/trawl
```

Node 20.3 or later, Bun, Deno and edge runtimes. Or install the umbrella package for every product: `npm install productcraft`.

### Quick start

```ts
import { Trawl } from "@productcraft/trawl";

// Reads PRODUCTCRAFT_API_KEY (and PRODUCTCRAFT_WORKSPACE_ID) from the environment.
const trawl = new Trawl({ workspaceId: "9b2f6c1e-0d6a-4a63-9a43-2f1c3e4d5a6b" });

type Tiers = { tiers: { name: string; price: string }[] };
const job = await trawl.jobs.createAndPoll<Tiers>({
  description: "The name and monthly price of each pricing tier",
  json_schema: {
    type: "object",
    properties: {
      tiers: {
        type: "array",
        items: { type: "object", properties: { name: { type: "string" }, price: { type: "string" } }, required: ["name", "price"] },
      },
    },
    required: ["tiers"],
  },
  suggested_urls: ["https://example.com/pricing"],
});

if (job.status === "succeeded") console.log(job.result?.tiers[0]?.name);
else console.log(job.status, job.error);
```

`workspaceId` is optional for workspace API keys: without it the client looks it up once per process (one extra request on a cold start). Pass it, or set `PRODUCTCRAFT_WORKSPACE_ID`, to skip the lookup. Bearer tokens must always pass it.

Job creation is rate-limited per workspace and each agent step uses one credit; a workspace with no credits gets `402`.

### Credentials

Pass `apiKey` (a workspace key, `pcft_live_…`), or omit it and the client reads `PRODUCTCRAFT_API_KEY`. An explicit `auth: { type: "bearer", token }` works for platform user tokens. The environment fallback is server-only: never put a key in `NEXT_PUBLIC_*` or any variable a bundler inlines into browser code (a workspace key in a browser throws unless you set `dangerouslyAllowBrowser: true`).

### Webhooks

`trawl.webhooks.unwrap()` verifies the signature against the **raw** body and returns a typed `Trawl.UnwrapWebhookEvent`. The secret comes from `{ secret }`, the client's `webhookSecret`, or `PRODUCTCRAFT_TRAWL_WEBHOOK_SECRET`.

```ts
import { Trawl } from "@productcraft/trawl";
const trawl = new Trawl();
export async function POST(req: Request) {
  const event = await trawl.webhooks.unwrap({ payload: await req.text(), headers: req.headers });
  switch (event.type) {
    case "credits.low":
      console.log(event.data);
      break;
    default:
      break; // UnknownWebhookEvent: types added later
  }
  return new Response(null, { status: 204 });
}
```

### Every method

`new Trawl()` has these resources and methods, and no others:

- `trawl.credits`: `retrieve`
- `trawl.jobs`: `cancel`, `create`, `list`, `retrieve`
- `trawl.stats`: `retrieve`
- `trawl.webhooks`: `endpoints.create`, `endpoints.delete`, `endpoints.list`, `endpoints.retrieve`, `endpoints.rotateSecret`, `endpoints.test`, `endpoints.update`, `eventTypes.list`, `events.list`, `events.replay`, `events.retrieve`

### Docs

- Guides as Markdown: https://productcraft.co/docs/trawl.md
- API reference: https://productcraft.co/docs/trawl/api-reference.md
- OpenAPI document: https://api.trawl.productcraft.co/docs-json

## Flags: `@productcraft/flags` 0.5.0

Feature flags and remote settings for Node.js, browsers and React Native, from [ProductCraft Flags](https://productcraft.co/docs/flags).

- **`FlagsClient`** downloads one small config JSON per environment and evaluates flags **locally** with [`@productcraft/flags-engine`](https://www.npmjs.com/package/@productcraft/flags-engine). User attributes never leave your app, and an evaluation is a function call, not a request.
- **`Flags`** is the management API client (projects, configs, environments, flags, targeting rules, segments, SDK keys, history, webhooks), generated from the production OpenAPI spec like every ProductCraft SDK.

Free during the preview. Requires Node.js 20.3 or later on the server; in a browser or React Native app, see [Browsers and React Native](#browsers-and-react-native).

```sh
npm install @productcraft/flags
```

### Evaluate flags

Create an SDK key in the console (**Flags > SDK keys**, one per config and environment), then:

```ts
import { FlagsClient } from "@productcraft/flags";

const flags = new FlagsClient({ sdkKey: process.env.PRODUCTCRAFT_FLAGS_SDK_KEY });

const user = { identifier: "user-123", email: "ada@example.com", country: "NL", custom: { plan: "pro" } };
if (await flags.getValue("new_checkout", false, user)) {
  // the new checkout
}
const banner = await flags.getValue("banner_text", "Welcome", user); // string
const limits = await flags.getJson<{ max: number }>("limits", { max: 5 }, user); // parsed JSON
```

The value's type follows your default: `false` gives a `boolean`, `"Welcome"` a `string`, `5` a `number`. An object, array or `null` default on a json setting returns the parsed value; a `null` default is allowed for every type. `getJson<T>()` always parses, and returns your default if the text is not JSON.

**`getValue` never throws** once the client is constructed. A network error, a bad response, an unknown key or a type mismatch returns your default and emits an `error` event. Only a missing or garbled SDK key throws (`ConfigurationError`, at construction).

#### The user

`{ identifier, email, country, custom }`, ConfigCat's shape. Flat attributes work too: `{ identifier: "u1", plan: "pro" }`. A rule on attribute `a` reads `custom[a]` first, then the top-level `a`. Percentage rollouts hash the setting with `identifier` (or the setting's percentage attribute), so a user keeps their bucket.

```ts
import { FlagsClient } from "@productcraft/flags";
const flags = new FlagsClient({ sdkKey: process.env.PRODUCTCRAFT_FLAGS_SDK_KEY });

flags.setDefaultUser({ identifier: "user-123" }); // or `defaultUser` in the options
await flags.getValue("new_checkout", false); // uses the default user
await flags.getValue("new_checkout", false, { identifier: "user-456" }); // replaces it as a whole (no merge)
```

Your own user type works as it is, no spread needed: any interface with `identifier` / `email` / `country` / `custom` (and any other attributes) is accepted (`UserInput`).

```ts
import { FlagsClient } from "@productcraft/flags";
const flags = new FlagsClient({ sdkKey: process.env.PRODUCTCRAFT_FLAGS_SDK_KEY });

interface AppUser {
  identifier: string;
  email?: string;
  plan: "free" | "pro";
}
declare const me: AppUser;
await flags.getValue("new_checkout", false, me);
```

A rule on an attribute the user does not have is skipped for that user (a soft miss, in `getValueDetails().warnings`). The client logs each such warning once per attribute for its lifetime, so anonymous traffic does not flood your logs; pass `logger: null` to log nothing.

Text comparisons are by codepoint with no Unicode normalisation: pass emails and names in **NFC** (`email.normalize("NFC")`), or two spellings of the same address can match different rules and buckets.

#### Why a value? Details, all values, snapshots

```ts
import { FlagsClient } from "@productcraft/flags";
const flags = new FlagsClient({ sdkKey: process.env.PRODUCTCRAFT_FLAGS_SDK_KEY });
const user = { identifier: "user-123" };

const d = await flags.getValueDetails("new_checkout", false, user);
console.log(d.value, d.reason, d.variant, d.ruleIndex, d.percentageIndex, d.errorCode, d.revision);

const all = await flags.getAllValues(user); // { key: value }, json settings parsed

await flags.waitForReady();
const snap = flags.snapshot(); // synchronous evaluation of the config held right now
snap.getValue("new_checkout", false, user);
```

`reason` is `STATIC`, `TARGETING_MATCH`, `SPLIT`, `DEFAULT` or `ERROR`, or `CACHED` / `STALE` when the value came from the cache or `bootstrap` before a download, or from an older config while downloads fail.

### Polling and propagation

| Mode | Behaviour |
|---|---|
| `{ mode: "auto", intervalSeconds: 60, maxInitWaitSeconds: 5 }` (default) | Downloads on a timer (minimum 30 s, ±10% jitter). The first `getValue` waits up to `maxInitWaitSeconds` for the first download, then serves the cache, `bootstrap` or your defaults. |
| `{ mode: "lazy", ttlSeconds: 60 }` | No timers. Downloads on use once the config is older than `ttlSeconds` (minimum 30 s), serving the held config while it refreshes. |
| `{ mode: "manual" }` | Downloads only when you call `forceRefresh()`. |

Downloads send `If-None-Match`, so an unchanged config costs a `304`. A change you save in the console reaches an auto-polling client within **interval × 1.1 + 5 s** (the jittered poll, plus up to 5 s for the delivery endpoint to pick up the publish): about 71 s at the default, 38 s at the 30 s minimum. A proxy or CDN of your own in front of the delivery URL may add up to 15 s (`s-maxage`). Call `forceRefresh()` to fetch now.

```ts
import { FlagsClient } from "@productcraft/flags";
const flags = new FlagsClient({ sdkKey: process.env.PRODUCTCRAFT_FLAGS_SDK_KEY, polling: { mode: "auto", intervalSeconds: 30 } });

flags.on("ready", (state) => console.log("flags", state));
flags.on("configChanged", (e) => console.log("config revision", e.revision));
flags.on("error", (err) => console.warn(err.code, err.message));
flags.on("evaluated", (d) => console.debug(d.key, d.value, d.reason));

await flags.forceRefresh();
flags.setOffline(); // stop all network access; evaluations keep working
flags.setOnline();
flags.close(); // stop timers (call it on shutdown)
```

`flags.state` is `initializing`, `ready`, `stale` (the last download failed; an older config is served), `unavailable` (the last download failed and no config was ever held: evaluations return your defaults), `key_invalid` (the key was revoked or expired: the client keeps the config it holds), `offline` or `closed`. Errors back off up to 4× the interval and honour `Retry-After`.

### Fail-safe: cache and bootstrap

What the client evaluates, in order: a fresh download, the last config it holds, your **cache** (read at start-up), your **`bootstrap`** config, and finally the default you pass to `getValue`. A full ProductCraft outage never turns your flags off when the cache or `bootstrap` is set up.

```ts
import { FlagsClient, type FlagsCache } from "@productcraft/flags";
import { readFileSync } from "node:fs";

declare const redis: { get(key: string): Promise<string | null>; set(key: string, value: string): Promise<unknown> };

// Any store with get/set: Redis, a KV namespace, a file. Keys never contain the SDK key.
const cache: FlagsCache = { get: (key) => redis.get(key), set: async (key, value) => void (await redis.set(key, value)) };

const flags = new FlagsClient({
  sdkKey: process.env.PRODUCTCRAFT_FLAGS_SDK_KEY,
  cache,
  // A config JSON shipped with your build (download it from the delivery URL in CI, or `snapshot().toJSON()`).
  bootstrap: readFileSync("flags-bootstrap.json", "utf8"),
});
```

The client refuses a download over 2 MiB, never moves back to an older revision of the config, and only follows delivery hints that point at `https://*.productcraft.co`.

#### Your own delivery host: `baseUrl`

By default the client downloads from `https://api.flags.productcraft.co` and then follows the delivery hosts the config itself names (`delivery.base_urls`). Set `baseUrl` when your servers must reach Flags somewhere else:

- **in-cluster or self-hosted**: the delivery service's internal address, when your pods cannot reach the public ingress (for example a load balancer that does not hairpin);
- **behind an egress proxy or your own CDN** in front of the delivery URL.

With `baseUrl` set, the client downloads only from that host and **ignores the config's `delivery.base_urls` hint**, so it never switches to a public host your network cannot reach. Everything else (polling, cache, bootstrap, fail-safe defaults) works the same.

```ts
import { FlagsClient } from "@productcraft/flags";

const flags = new FlagsClient({
  sdkKey: process.env.PRODUCTCRAFT_FLAGS_SDK_KEY,
  baseUrl: process.env.PRODUCTCRAFT_FLAGS_URL, // e.g. http://flags-api.flags.svc.cluster.local
});
```

### Serverless and edge functions

Timers do not survive between invocations, so use **lazy polling with the shared cache and `bootstrap`**: a cold start reads the cache (one Redis round trip, no download while the cached config is younger than `ttlSeconds`), and only one invocation per TTL downloads, with `If-None-Match`.

```ts
import { FlagsClient, type FlagsCache } from "@productcraft/flags";
declare const cache: FlagsCache;
declare const bootstrapConfig: object;

// Module scope: reused while the instance stays warm.
const flags = new FlagsClient({
  sdkKey: process.env.PRODUCTCRAFT_FLAGS_SDK_KEY,
  polling: { mode: "lazy", ttlSeconds: 60 },
  cache,
  bootstrap: bootstrapConfig,
});

export async function handler(event: { userId: string }) {
  const enabled = await flags.getValue("new_checkout", false, { identifier: event.userId });
  return { enabled };
}
```

### Overrides

Overrides set values locally: for local development, tests, or a kill switch you control from an environment variable.

```ts
import { FlagsClient } from "@productcraft/flags";

// From a map. `behaviour`: "local_over_remote" (default), "remote_over_local" or "local_only" (no downloads, no key needed).
const dev = new FlagsClient({ overrides: { values: { new_checkout: true, limits: { max: 50 } }, behaviour: "local_only" } });

// From a JSON file (Node only), reloaded on change with `watch: true`.
const local = new FlagsClient({ sdkKey: process.env.PRODUCTCRAFT_FLAGS_SDK_KEY, overrides: { file: "./flags.local.json", watch: true } });

// From an environment variable holding a JSON object (Node only): PRODUCTCRAFT_FLAGS_OVERRIDES='{"new_checkout": false}'
const ops = new FlagsClient({ sdkKey: process.env.PRODUCTCRAFT_FLAGS_SDK_KEY, overrides: { env: "PRODUCTCRAFT_FLAGS_OVERRIDES" } });
```

### Testing

`@productcraft/flags/testing` exports `createTestClient`: a `FlagsClient` with fixed values, no network and no timers, and `set()` to change a value mid-test.

```ts
import { describe, expect, it } from "vitest"; // or Jest: the same calls
import { createTestClient } from "@productcraft/flags/testing";

async function checkoutVersion(flags: { getValue(key: string, def: boolean): Promise<boolean> }) {
  return (await flags.getValue("new_checkout", false)) ? "v2" : "v1";
}

describe("checkout", () => {
  it("follows the new_checkout flag", async () => {
    const flags = createTestClient({ values: { new_checkout: true } });
    expect(await checkoutVersion(flags)).toBe("v2");
    flags.set("new_checkout", false); // emits configChanged
    expect(await checkoutVersion(flags)).toBe("v1");
  });
});
```

The same subpath exports `createMockFetch()` for the management client.

### Browsers and React Native

Bundlers that honour the `browser` or `react-native` export condition (Vite, webpack, esbuild, Rollup, Metro, Next.js client bundles) get a build of the same `FlagsClient` without the Node-only parts, so nothing changes in your code:

- **No `node:` import and no `process.env` read.** `overrides.file` and `overrides.env` are Node-only and report an `overrides` error; use `overrides.values`.
- **The browser HTTP cache revalidates the config.** A page sends no `If-None-Match` (it would force a CORS preflight on every poll); the delivery endpoint allows any origin.
- **Auto polling pauses while the tab is hidden** and downloads once when it is shown again.
- `cache` takes any `{ get, set }`, for example over `localStorage`, so a returning visitor starts with the last config.

```ts
import { FlagsClient } from "@productcraft/flags";

const store = { get: (k: string) => localStorage.getItem(k), set: (k: string, v: string) => localStorage.setItem(k, v) };
const flags = new FlagsClient({ sdkKey: "pcf_sdk_…", cache: store, defaultUser: { identifier: "user-123" } });
flags.on("configChanged", () => render());
const showBanner = await flags.getValue("show_banner", false);
declare function render(): void;
```

For React (hooks, a provider and SSR without a flash) use [`@productcraft/flags-react`](https://www.npmjs.com/package/@productcraft/flags-react). The management client `Flags` keeps refusing to run in a browser with a workspace key.

**A key used in a browser or mobile app makes its whole config public** (next section).

### Server and client configs

An SDK key can read its whole config: flag and segment keys (which can reveal what you are building) and every cleartext rule value. Keep server keys on the server. If a key ships in a browser or mobile app, that config is public: give client-side flags their own config with no internal rules. Confidential comparators hash their values, which hides them from casual reading but not from a determined attacker (the salt ships in the same JSON). Server-only and client key types are planned.

### Manage flags from code

`Flags` is the management API: workspace API key (`PRODUCTCRAFT_API_KEY`) or a platform session, policy-gated, with retries, idempotency keys, pagination and typed errors.

```ts
import { Flags } from "@productcraft/flags";

const flags = new Flags({ apiKey: process.env.PRODUCTCRAFT_API_KEY, workspaceId: "acme-corp" });
const project = await flags.projects.create({ name: "Storefront", environment_preset: "dev_staging_prod" });
for await (const p of flags.projects.list()) console.log(p.name);
```

### Migrating from ConfigCat

Import your ConfigCat product in the console (**Flags > Import from ConfigCat**): percentage rollouts keep their buckets because each imported flag's seed is its ConfigCat key. Before you swap the SDK, run [`examples/configcat-dual-run.mjs`](https://github.com/clauderanelagh/productcraft-node/blob/main/examples/configcat-dual-run.mjs): it evaluates the same users (synthetic, plus a file of your own) with both SDKs locally and prints every difference.

```sh
cd examples && npm install
node configcat-dual-run.mjs --configcat-key "$CONFIGCAT_SDK_KEY" --flags-key "$PRODUCTCRAFT_FLAGS_SDK_KEY" --users 1000 --users-file users.json
```

The user object has the same shape (`identifier`, `email`, `country`, `custom`); `getValueAsync(key, def, user)` becomes `getValue(key, def, user)`, `forceRefreshAsync()` becomes `forceRefresh()`, and `PollingMode.AutoPoll` becomes `{ mode: "auto" }`.

### Webhooks

`flags.webhooks.unwrap()` verifies the signature against the **raw** body and returns a typed `Flags.UnwrapWebhookEvent`. The secret comes from `{ secret }`, the client's `webhookSecret`, or `PRODUCTCRAFT_FLAGS_WEBHOOK_SECRET`.

```ts
import { Flags } from "@productcraft/flags";
const flags = new Flags();
export async function POST(req: Request) {
  const event = await flags.webhooks.unwrap({ payload: await req.text(), headers: req.headers });
  switch (event.type) {
    case "config.published":
      console.log(event.data);
      break;
    default:
      break; // UnknownWebhookEvent: types added later
  }
  return new Response(null, { status: 204 });
}
```

### Every method

`new Flags()` has these resources and methods, and no others:

- `flags.changes`: `retrieve`, `revert`
- `flags.configs`: `compare`, `delete`, `environments.copy`, `environments.evaluate`, `environments.revisions.list`, `environments.revisions.retrieve`, `environments.sdkKeys.endGracePeriod`, `environments.sdkKeys.list`, `environments.sdkKeys.reveal`, `environments.sdkKeys.rotate`, `environments.values.list`, `retrieve`, `settings.create`, `settings.list`, `update`
- `flags.imports`: `create`
- `flags.limits`: `retrieve`
- `flags.projects`: `changes.export`, `changes.list`, `configs.create`, `configs.list`, `create`, `delete`, `environments.create`, `environments.delete`, `environments.list`, `environments.retrieve`, `environments.update`, `list`, `retrieve`, `segments.create`, `segments.list`, `update`
- `flags.segments`: `delete`, `retrieve`, `revealConfidential`, `update`
- `flags.settings`: `delete`, `retrieve`, `update`, `values.replace`, `values.retrieve`, `values.revealConfidential`, `values.update`
- `flags.stats`: `retrieve`
- `flags.webhooks`: `endpoints.create`, `endpoints.delete`, `endpoints.list`, `endpoints.retrieve`, `endpoints.rotateSecret`, `endpoints.test`, `endpoints.update`, `eventTypes.list`, `events.list`, `events.replay`, `events.retrieve`

### Docs

- Guides as Markdown: https://productcraft.co/docs/flags.md
- API reference: https://productcraft.co/docs/flags/api-reference.md
- OpenAPI document: https://api.flags.productcraft.co/docs-json

## Notify: `@productcraft/notify` 0.1.0

Node.js / TypeScript client for **ProductCraft Notify**: one call notifies a user across an in-app inbox, email (sent through ProductCraft Mail), web push, APNs and FCM, with per-user preferences per category and channel, fallbacks, quiet hours, templates per channel and locale, delivery history and signed webhooks.

Notify does not replace your own push credentials: Apple and Google tie push to your developer accounts, so you upload your APNs key and Firebase service account once (stored encrypted, never returned). Notify takes care of what comes after: device tokens, pruning dead ones, per-platform payloads, retries, fallbacks and delivery feedback.

Every method, type, error class and mock is generated from the production OpenAPI spec. Notify is in preview.

### Install

```sh
npm install @productcraft/notify
```

Node 20.3 or later, Bun, Deno, edge runtimes and browsers (the `client({ token })` scope). Or install the umbrella package for every product: `npm install productcraft`.

### Quick start (your server)

```ts
import { Notify } from "@productcraft/notify";

// Reads PRODUCTCRAFT_API_KEY (and PRODUCTCRAFT_WORKSPACE_ID) from the environment.
const notify = new Notify({ workspaceId: "9b2f6c1e-0d6a-4a63-9a43-2f1c3e4d5a6b" });

// Tell Notify who the user is (your own user id is the key).
await notify.recipients.identify("user_123", { email: "ada@example.com", locale: "en" });

// Notify them: the notification type decides the channels, templates and fallback order.
const sent = await notify.notifications.send({
  type: "comment_created",
  recipients: ["user_123"],
  data: { author: "Grace", post_title: "Hello" },
});
// The result is `Notify.NotificationSendResponse`: the accepted notification, or the plan when
// you pass `dry_run: true` (nothing is stored or sent).
if ("id" in sent) console.log(sent.id, sent.status);
```

`notifications.send` always carries an `Idempotency-Key` (the SDK generates one per call and reuses it on retries; pass `{ idempotencyKey }` to tie it to your own event id).

### In the browser or an app: `notify.client({ token })`

Never ship an API key to a browser or an app. Your backend mints a short-lived **recipient token** for the signed-in user, and the client side calls Notify with only that token:

```ts
import { Notify } from "@productcraft/notify";

// Server: an endpoint that returns a token for the signed-in user.
const server = new Notify({ apiKey: process.env.PRODUCTCRAFT_API_KEY, workspaceId: "9b2f6c1e-0d6a-4a63-9a43-2f1c3e4d5a6b" });
const { token } = await server.recipientTokens.mint({ recipient: "user_123" });

// Browser or app: no API key, just the token.
const me = new Notify().client({ token });
const page = await me.inbox.list({ status: "unread" });
const ids = page.data.map((item) => item.id);
if (ids.length) await me.inbox.mark({ ids, action: "read" });
```

`client({ token })` sends `Authorization: Bearer <token>` and nothing else: no API key, no environment fallback. It refuses a `pcft_` key. Tokens expire (one hour by default); fetch a new one when a call fails with `RECIPIENT_TOKEN_EXPIRED`. For a stateful inbox with real-time updates, use `@productcraft/notify-js` or `@productcraft/notify-react` once they ship.

### Credentials

Pass `apiKey` (a workspace key, `pcft_live_…`), or omit it and the client reads `PRODUCTCRAFT_API_KEY`. The environment fallback is server-only: never put a key in `NEXT_PUBLIC_*` or any variable a bundler inlines into browser code (a workspace key in a browser throws unless you set `dangerouslyAllowBrowser: true`).

### Webhooks

`notify.webhooks.unwrap()` verifies the signature against the **raw** body and returns a typed `Notify.UnwrapWebhookEvent`. The secret comes from `{ secret }`, the client's `webhookSecret`, or `PRODUCTCRAFT_NOTIFY_WEBHOOK_SECRET`.

```ts
import { Notify } from "@productcraft/notify";
const notify = new Notify();
export async function POST(req: Request) {
  const event = await notify.webhooks.unwrap({ payload: await req.text(), headers: req.headers });
  switch (event.type) {
    case "credential.invalid":
      console.log(event.data);
      break;
    default:
      break; // UnknownWebhookEvent: types added later
  }
  return new Response(null, { status: 204 });
}
```

### Every method

`new Notify()` has these resources and methods, and no others:

- `notify.categories`: `create`, `delete`, `list`, `retrieve`, `update`
- `notify.channels`: `apns.deleteCredential`, `apns.uploadCredential`, `fcm.deleteCredential`, `fcm.uploadCredential`, `list`, `webpush.generateVapidKeys`, `webpush.importVapidKeys`, `webpush.retrieve`
- `notify.client(…).devices`: `delete`, `register`
- `notify.client(…).inbox`: `counts`, `interact`, `list`, `mark`
- `notify.client(…).preferences`: `retrieve`, `update`
- `notify.client(…).webpush`: `vapidPublicKey`
- `notify.deliveries`: `list`, `retrieve`
- `notify.export`: `retrieve`
- `notify.notificationTypes`: `archive`, `create`, `list`, `preview`, `replaceByKey`, `retrieve`, `templates.delete`, `templates.retrieve`, `templates.revert`, `templates.update`, `templates.versions`, `update`
- `notify.notifications`: `cancel`, `cancelByKey`, `list`, `retract`, `retrieve`, `send`
- `notify.recipientTokens`: `mint`
- `notify.recipients`: `bulkIdentify`, `delete`, `devices.create`, `devices.delete`, `devices.list`, `identify`, `inbox.list`, `list`, `preferences.replace`, `preferences.retrieve`, `preferences.update`, `retrieve`, `revokeTokens`, `timeline`, `update`
- `notify.settings`: `retrieve`, `revokeAllTokens`, `update`
- `notify.setupStatus`: `retrieve`
- `notify.stats`: `retrieve`
- `notify.webhooks`: `endpoints.create`, `endpoints.delete`, `endpoints.list`, `endpoints.retrieve`, `endpoints.rotateSecret`, `endpoints.test`, `endpoints.update`, `eventTypes.list`, `events.list`, `events.replay`, `events.retrieve`

### Docs

- Guides as Markdown: https://productcraft.co/docs/notify.md
- API reference: https://productcraft.co/docs/notify/api-reference.md
- OpenAPI document: https://api.notify.productcraft.co/docs-json

## Platform: `@productcraft/platform-auth` 1.3.0

Node.js / TypeScript client for the **ProductCraft Platform API**: workspaces, members and invites, roles and IAM policies, workspace API keys, service activation, audit logs, and the introspection endpoints every ProductCraft backend uses to resolve permissions.

Every method, type, error class and mock is generated from the production OpenAPI spec. Upgrading from 0.x? See the [1.0 migration guide](https://github.com/clauderanelagh/productcraft-node/blob/main/docs/migrations/platform-auth-1.0.0.md).

### Install

```sh
npm install @productcraft/platform-auth
```

Node 20.3 or later, Bun, Deno and edge runtimes. Server-side: it sends a workspace key or a platform session. Or install the umbrella package for every product: `npm install productcraft`.

### Which SDK do I want?

| If your goal is to … | Reach for |
|---|---|
| Sign in **your own end-users** in a product you build on ProductCraft | [`@productcraft/auth`](https://www.npmjs.com/package/@productcraft/auth) |
| Manage **your ProductCraft account and workspaces**: keys, members, roles, policies, services | **this package** |

Both have "auth" in the name. Platform owns the ProductCraft account you use to sign in to the console; Auth owns the end-users of the products you build. They are separate databases with separate signing keys.

### Quick start

```ts
import { PlatformAuth } from "@productcraft/platform-auth";

// Reads PRODUCTCRAFT_API_KEY from the environment.
const platform = new PlatformAuth();

// Which workspace and permissions does this key carry?
const me = await platform.apiKeys.self();
console.log(me.workspace_id, me.name, me.allowed);

// Workspace routes take the workspace slug as the first argument.
const ws = await platform.workspaces.retrieve("acme");

// Pages are fetched as you iterate.
for await (const member of platform.workspaces.members.list(ws.slug, { limit: 50 })) {
  console.log(member.account_id, member.role);
}
```

Platform routes name the workspace by **slug**, positionally (`platform.workspaces.members.list("acme")`). The one exception is `platform.stats.retrieve()`, which uses the workspace id: pass `workspaceId`, or let a workspace key resolve it once per process.

### Credentials

| Credential | Pass | Use it for |
|---|---|---|
| Workspace API key (`pcft_live_…`) | `apiKey`, or `PRODUCTCRAFT_API_KEY` in the environment | Backend reads and introspection for the workspace the key belongs to |
| Platform session (a signed-in person) | `auth: { type: "bearer", token }` | Administration: creating workspaces, minting and revoking keys, roles, policies, invites |

```ts
import { PlatformAuth } from "@productcraft/platform-auth";

const anon = new PlatformAuth();
const { access_token } = await anon.auth.signin({ identifier: "ada@example.com", password: process.env.PASSWORD!, session_duration: 3600 });
const admin = new PlatformAuth({ auth: { type: "bearer", token: access_token } });

const minted = await admin.workspaces.apiKeys.create("acme", { name: "Production mail", preset: "mail-send", expires_in_days: 90 });
console.log(minted.token); // shown once: store it in your secret manager
await admin.auth.logoutCurrent();
```

A workspace key cannot mint another key or reshape roles and policies; those calls need a person's session. An explicit `auth` always wins over the environment. The environment fallback is server-only: never put a key in `NEXT_PUBLIC_*` or any variable a bundler inlines into browser code. A keyed client constructed in a browser throws unless you set `dangerouslyAllowBrowser: true`.

### Introspection (for backends that accept workspace keys)

```ts
import { PlatformAuth } from "@productcraft/platform-auth";

// Resolve the key a request carried to its workspace and policy.
declare const incomingKey: string;
const caller = new PlatformAuth({ apiKey: incomingKey });
const { is_valid, workspace_id, policy } = await caller.introspect.apiKey();
```

### Every method

`new PlatformAuth()` has these resources and methods, and no others:

- `platform.account`: `erase`
- `platform.apiKeys`: `self`
- `platform.auth`: `logout`, `logoutCurrent`, `password.requestReset`, `password.reset`, `refresh`, `signin`, `signup`
- `platform.introspect`: `apiKey`, `retrieve`, `workspaces.retrieve`
- `platform.me`: `avatar.clear`, `avatar.upload`, `hiddenGuides.hide`, `hiddenGuides.list`, `hiddenGuides.reset`, `hiddenGuides.unhide`, `profile.update`, `retrieve`
- `platform.oauth`: `connections.delete`, `connections.list`, `workspaces.connections.delete`, `workspaces.connections.list`, `workspaces.connections.restore`
- `platform.sessions`: `delete`, `list`, `revokeOthers`
- `platform.stats`: `retrieve`
- `platform.verification`: `resend`, `verify`
- `platform.wellKnown`: `jwks`, `oauthAuthorizationServer`
- `platform.workspaces`: `apiKeys.create`, `apiKeys.delete`, `apiKeys.list`, `apiKeys.presets.list`, `apiKeys.preview`, `apiKeys.retrieve`, `apiKeys.rotate`, `apiKeys.update`, `apiKeys.updateBindings`, `auditFeed.list`, `auditLogs.export`, `auditLogs.list`, `avatar.clear`, `avatar.upload`, `create`, `delete`, `invites.accept`, `invites.create`, `invites.delete`, `invites.list`, `list`, `members.delete`, `members.list`, `members.updateRole`, `policies.actions.catalog`, `policies.create`, `policies.delete`, `policies.list`, `policies.retrieve`, `policies.update`, `retrieve`, `roles.create`, `roles.delete`, `roles.list`, `roles.retrieve`, `roles.update`, `services.disable`, `services.enable`, `services.list`, `services.updateSettings`, `update`

### Docs

- Guides as Markdown: https://productcraft.co/docs/platform.md
- API reference: https://productcraft.co/docs/platform/api-reference.md
- OpenAPI document: https://api.platform-auth.productcraft.co/docs-json
