Node.js SDKs.
Typed, generated from the live OpenAPI specs, MIT-licensed, server-side.
Every product on the ProductCraft platform ships an official Node.js / TypeScript SDK published to npm. The SDKs are generated from the same OpenAPI specs the API reference docs render from — so the types you see in your editor always match the wire shape in production.
Install
Pick one product or grab the umbrella
Install the per-product package when you only need one surface. Install the umbrella when you call more than one from the same backend — it pulls each per-product package as a dependency.
npm install @productcraft/auth
# or
pnpm add @productcraft/mail
# or
yarn add @productcraft/waitlistnpm install productcraftPackages
What's on npm
All packages live under the @productcraft scope. The umbrella is the unscoped 'productcraft' package.
@productcraft/auth
Customer auth & EndUsers: sign-in flows, OAuth (Apple, Google, GitHub), MFA, passkeys, sessions, roles, M2M, JWT verification with a built-in JWKS cache. 1.0 is generated like every other SDK: auth.consumer(slug).signin, auth.admin.app(id), auth.verifyToken, typed errors, retries and pagination (npm install @productcraft/auth).
@productcraft/mail
Transactional email on your own domain: raw HTML and template sends, domains with DKIM, the delivery log, contacts, broadcasts, suppression lists and signed webhooks. 1.0 is on the generated runtime: mail.emails.send / templates.send / domains.poll, typed errors, retries, automatic idempotency keys, pagination and webhooks.unwrap.
@productcraft/waitlist
Waitlist management: public-form signups, variants for A/B/n landing pages, referrals, leaderboard, approvals with invite-to-app, signed webhooks, CSV export. 1.0 is on the generated runtime: waitlist.lists.create / entries.bulk, a keyless waitlist.public({ workspace, waitlist }) client for browser forms, typed errors, retries and webhooks.unwrap.
@productcraft/social
Social infrastructure as an API: communities, posts, ranked feeds, stories with polls and close-friends, messaging, notifications, moderation. 1.1 adds the generated resource methods: social.community(id).as(actorId).posts.create(), typed errors, retries, pagination and webhooks.unwrap.
@productcraft/trawl
AI web extraction — submit a JSON Schema plus a natural-language description, a browser agent extracts schema-conforming data from the live web, delivered to a signed webhook. 1.0 is on the generated runtime: trawl.jobs.create / createAndPoll / retrieve, typed errors, retries, pagination, webhook verification and a mock fetch for tests.
@productcraft/flags
Feature flags and remote settings: FlagsClient downloads the config for one environment and evaluates every flag locally (polling or lazy, a cache and a bootstrap for outages, overrides, evaluation details, a synchronous snapshot), and the Flags management client covers projects, targeting, segments, SDK keys, history, webhooks and the ConfigCat import. Companions: @productcraft/flags-react, @productcraft/flags-openfeature and @productcraft/flags-engine.
@productcraft/notify
Notifications across an in-app inbox, email, web push, APNs and FCM: notify.notifications.send with idempotent retries, recipients and devices, preferences, notification types as code, recipient tokens for browsers and apps, channels, the message log and webhook verification. Companions for the browser: @productcraft/notify-js (framework-free inbox store, real-time updates, web push and a service worker) and @productcraft/notify-react (<NotifyInbox/>, <NotifyPreferences/>, hooks).
@productcraft/platform-auth
Your ProductCraft account and workspaces: members, invites, roles, IAM policies, workspace API keys, service activation and introspection. 1.0 is on the generated runtime: platform.workspaces.create / apiKeys.create / apiKeys.self, typed errors, retries and pagination. (For your own product users, use @productcraft/auth.)
@productcraft/auth-passport
Passport-JWT adapter for Auth. Plug an Auth ConsumerScope into a `passport-jwt` Strategy so existing Passport setups can verify Auth-issued tokens.
productcraft
All-in-one umbrella package. One install, one auth credential, one class with every surface attached (`pc.auth`, `pc.mail`, `pc.waitlist`, …). Install this when you call more than one ProductCraft API from the same backend.
Configuration
Credentials from the environment
On the server, omit auth and every client reads your workspace API key from PRODUCTCRAFT_API_KEY. An explicit auth always wins. Hosts are never read from the environment: override them in code with baseUrl.
auth.consumer() takes its app slug from PRODUCTCRAFT_AUTH_APP when you omit it, and never reads a credential from the environment. Routes that need an app key (PAK) on the consumer side take an explicit auth.
This is a server-only fallback. Never put a key in a NEXT_PUBLIC_* variable or anything else your bundler inlines into browser code.
PRODUCTCRAFT_API_KEY=pcft_live_... # workspace API key
PRODUCTCRAFT_AUTH_APP=my-app-slug # default slug for auth.consumer()Runtime
What every generated client does
Every package is generated from its API's spec onto the same runtime, so each client below behaves the same way. Node 20.3 or later (also Bun, Deno and edge runtimes), ESM and CommonJS.
Typed errors
Every failure is a class you can catch: one per status (BadRequestError, AuthenticationError, PermissionDeniedError, NotFoundError, ConflictError, RateLimitError, InternalServerError, …) under APIError, plus APIConnectionError and APITimeoutError for the network. Each carries status, code, errors[], requestId and docUrl, a link into the error code catalogue.
import { Trawl, APIError, RateLimitError } from "@productcraft/trawl";
const trawl = new Trawl();
try {
await trawl.jobs.retrieve("3f0c1a2b-4c5d-4e6f-8a9b-0c1d2e3f4a5b");
} catch (err) {
if (err instanceof RateLimitError) {
console.log("retry in", err.retryAfter, "s");
} else if (err instanceof APIError) {
// Every API error: status, code, request_id and a link to /docs/errors
console.log(err.status, err.code, err.requestId, err.docUrl);
} else {
throw err;
}
}Retries and timeouts
Network errors, 408, 429, 5xx and 409 IDEMPOTENCY_IN_PROGRESS are retried twice by default with exponential backoff and jitter, honouring Retry-After up to 60 seconds. A POST or PATCH without an idempotency key is never retried. Each attempt times out after 60 seconds; pass an AbortSignal for an overall deadline.
import { Trawl } from "@productcraft/trawl";
// Client-wide: 3 retries, 20 s per attempt
const trawl = new Trawl({ maxRetries: 3, timeout: 20_000 });
// Per request: no retries, 5 s overall deadline
await trawl.jobs.list({}, { maxRetries: 0, signal: AbortSignal.timeout(5_000) });Idempotency
Every operation that accepts an Idempotency-Key gets one automatically, reused on every retry, so a retried create never runs twice. Pass your own key to make a retry from another process or a queue safe as well.
import { Trawl } from "@productcraft/trawl";
const trawl = new Trawl();
// A key is generated for every create and reused on each retry.
// Pass your own to make a retry from another process safe too.
const job = await trawl.jobs.create(
{
description: "Extract the product title.",
json_schema: { type: "object", required: ["title"] },
},
{ idempotencyKey: "order-1234-extract" },
);Pagination
List methods return a page you can await, or walk with for await across every page. The SDK follows next_cursor while has_more is true.
import { Trawl } from "@productcraft/trawl";
const trawl = new Trawl();
// Every item across every page
for await (const job of trawl.jobs.list({ limit: 50 })) console.log(job.id);
// One page at a time
const page = await trawl.jobs.list();
if (page.hasNextPage()) await page.getNextPage();
// Collect, with a ceiling
const all = await trawl.jobs.list().toArray({ maxItems: 500 });Polling
Long-running resources get poll() and createAndPoll(): they retrieve until the status is terminal, honour Retry-After, and throw APITimeoutError after timeoutMs.
import { Trawl } from "@productcraft/trawl";
const trawl = new Trawl();
type Product = { title: string };
const done = await trawl.jobs.createAndPoll<Product>(
{
description: "Extract the product title.",
json_schema: { type: "object", required: ["title"] },
},
{ intervalMs: 2_000, timeoutMs: 600_000 },
);
console.log(done.status, done.result?.title);Webhooks
webhooks.unwrap() verifies the Standard Webhooks signature and returns a typed event. It needs the raw request body: a body your framework has already parsed as JSON no longer matches the signature. The secret comes from { secret }, the client's webhookSecret, or PRODUCTCRAFT_<PRODUCT>_WEBHOOK_SECRET.
import { Trawl } from "@productcraft/trawl";
// Secret from PRODUCTCRAFT_TRAWL_WEBHOOK_SECRET
const trawl = new Trawl();
export async function POST(req: Request) {
// Verify against the RAW body: never JSON.parse it first.
const event = await trawl.webhooks.unwrap({
payload: await req.text(),
headers: req.headers,
});
switch (event.type) {
case "job.succeeded":
console.log(event.data.job.id, event.data.job.result);
break;
case "job.failed":
console.log(event.data.job.id, event.data.job.error);
break;
default:
break; // credits.low and types added later
}
return new Response(null, { status: 204 });
}import express from "express";
import { Trawl } from "@productcraft/trawl";
const trawl = new Trawl(); // secret from PRODUCTCRAFT_TRAWL_WEBHOOK_SECRET
const app = express();
// express.raw keeps the body as bytes: a parsed body fails verification
app.post("/webhooks", express.raw({ type: "application/json" }), async (req, res) => {
const event = await trawl.webhooks.unwrap({ payload: req.body, headers: req.headers });
console.log(event.type);
res.sendStatus(204);
});import { Hono } from "hono";
import { Trawl } from "@productcraft/trawl";
const trawl = new Trawl();
const app = new Hono();
app.post("/webhooks", async (c) => {
const event = await trawl.webhooks.unwrap({
payload: await c.req.text(),
headers: c.req.raw.headers,
});
console.log(event.type);
return c.body(null, 204);
});Raw responses
Every returned object has a non-enumerable lastResponse (requestId, status, headers). .withResponse() adds the Response and the parsed rate-limit headers.
import { Trawl } from "@productcraft/trawl";
const trawl = new Trawl();
const id = "3f0c1a2b-4c5d-4e6f-8a9b-0c1d2e3f4a5b";
const job = await trawl.jobs.retrieve(id);
console.log(job.lastResponse.requestId);
const { data, response, requestId, rateLimit } = await trawl.jobs
.retrieve(id)
.withResponse();
console.log(data.status, response.status, requestId, rateLimit?.remaining);The .client escape hatch
.client stays on every package: the typed openapi-fetch client over the same credential and base URL, without retries. Use it for anything the resource methods do not cover. Code written against it before the generated methods keeps working.
import { Trawl } from "@productcraft/trawl";
const trawl = new Trawl();
// .client: the typed openapi-fetch client, same key and base URL,
// no retries. For anything the resource methods do not cover.
const { data, error } = await trawl.client.GET(
"/v1/workspaces/{workspace_id}/credits",
{ params: { path: { workspace_id: "9b2f6c1e-0d6a-4a63-9a43-2f1c3e4d5a6b" } } },
);
console.log(data, error);Testing
@productcraft/<product>/testing exports createMockFetch(), a fetch that answers every operation with its spec example. See Testing without side effects.
Quickstart
Hello, Auth
A minimum viable Auth integration through the BFF pattern. End-user routes on auth.consumer(slug) need no key; admin routes send your workspace API key, so keep that server-side and never embed it in a browser bundle.
import { Auth } from "@productcraft/auth";
declare const identityTokenFromAppleSdk: string;
declare const rawNonceClientGenerated: string;
// Consumer routes need no key (default slug: PRODUCTCRAFT_AUTH_APP)
const auth = new Auth();
const consumer = auth.consumer("my-app-slug");
// Email + password sign-in, discriminated on `result`
const signin = await consumer.signin({
identifier: "alice@example.com",
password: "...",
});
if (signin.result === "session") console.log(signin.access_token);
// Sign in with Apple (native iOS flow)
await consumer.signinWithProvider("apple", {
id_token: identityTokenFromAppleSdk,
nonce: rawNonceClientGenerated,
});
// Verify a token your client sent you
declare const bearer: string;
const claims = await auth.verifyToken(bearer, { app: "my-app-slug" });Umbrella
Hello, ProductCraft
Install productcraft when you call more than one ProductCraft API from the same backend. One auth credential is shared across all surfaces; per-surfacebaseUrl overrides are available for staging environments.
import { ProductCraft } from "productcraft";
// Reads PRODUCTCRAFT_API_KEY from the environment
// (Mail uses it; Auth's end-user sign-in never sends it)
const pc = new ProductCraft();
// Auth: sign in an end user
await pc.auth.consumer("my-app").signin({
identifier: "alice@example.com",
password: "...",
});
// Mail: send a template from the same backend. An Idempotency-Key
// is generated for you, so a retried send never mails twice.
await pc.mail.templates.send("welcome", {
from: "hello@yourbrand.com",
to: "alice@example.com",
data: { name: "Alice" },
});How they're built
Spec-driven, low maintenance
Every per-surface SDK regenerates from the live /docs-json OpenAPI spec of its API. A nightly CI job in clauderanelagh/productcraft-node refreshes the specs, regenerates the typed clients, and opens a PR with the diff. Merging triggers a Changesets release that publishes the affected packages to npm with provenance attestations.
What that means for you: the types in your editor always match what production accepts. New endpoints land in the SDK without you (or us) hand-rolling another binding.