@marktiderman/genesis-supabase 0.6.2 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/README.md +128 -7
  2. package/dist/blocks.d.ts +18 -1
  3. package/dist/blocks.js +1 -1
  4. package/dist/chunk-7SCMHKCR.js +33 -0
  5. package/dist/chunk-7SCMHKCR.js.map +1 -0
  6. package/dist/{chunk-ONBOLMXH.js → chunk-DYHH2G4A.js} +37 -3
  7. package/dist/chunk-DYHH2G4A.js.map +1 -0
  8. package/dist/chunk-XGAXPUFY.js +124 -0
  9. package/dist/chunk-XGAXPUFY.js.map +1 -0
  10. package/dist/{index-Ds0tO9WP.d.ts → index-D73YuwEY.d.ts} +4 -4
  11. package/dist/index.d.ts +2 -2
  12. package/dist/index.js +1 -1
  13. package/dist/index.js.map +1 -1
  14. package/dist/jobs.d.ts +3 -1
  15. package/dist/jobs.js +48 -34
  16. package/dist/jobs.js.map +1 -1
  17. package/dist/native.d.ts +2 -2
  18. package/dist/runner.d.ts +179 -0
  19. package/dist/runner.js +3 -0
  20. package/dist/runner.js.map +1 -0
  21. package/dist/web-handoff-path-C_EEl_BC.d.ts +16 -0
  22. package/dist/web-handoff-server.d.ts +225 -0
  23. package/dist/web-handoff-server.js +262 -0
  24. package/dist/web-handoff-server.js.map +1 -0
  25. package/dist/web-handoff.d.ts +133 -0
  26. package/dist/web-handoff.js +104 -0
  27. package/dist/web-handoff.js.map +1 -0
  28. package/migrations/0009_genesis_owner_access.sql +89 -0
  29. package/migrations/0014_genesis_feature_registry_hardening.sql +124 -0
  30. package/migrations/0015_genesis_web_handoff.sql +270 -0
  31. package/migrations/tests/0009_genesis_owner_access.test.sql +70 -0
  32. package/migrations/tests/0014_genesis_feature_registry_hardening.test.sql +54 -0
  33. package/migrations/tests/0015_genesis_web_handoff.test.sql +203 -0
  34. package/package.json +88 -3
  35. package/dist/chunk-ONBOLMXH.js.map +0 -1
package/d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ACrB,IAAA,IAAA,CAAK,OAAO,KAAA,CAAM,IAAA;AAAA,EACpB;AACF;AASO,SAAS,KAAQ,MAAA,EAAiF;AACvG,EAAA,IAAI,OAAO,KAAA,EAAO,MAAM,IAAI,kBAAA,CAAmB,OAAO,KAAK,CAAA;AAC3D,EAAA,OAAO,MAAA,CAAO,IAAA;AAChB;AAwCA,eAAsB,eAAA,CAAgB,MAAA,EAA6B,OAAA,GAAkC,EAAC,EAAkB;AACtH,EAAA,IAAA,CAAM,MAAM,MAAA,CAAO,GAAA,CAAI,mBAAmB,CAAgF,CAAA;AAC1H,EAAA,MAAM,SAAS,OAAA,CAAQ,iBAAA;AAEvB,EAAA,IAAI,MAAA,IAAU,MAAA,CAAO,SAAA,EAAW,MAAM,uBAAuB,EAAE,SAAA,EAAW,MAAA,CAAO,SAAA,EAAU,EAAG,OAAO,MAAA,KAAW,QAAA,GAAW,SAAS,qBAAqB,CAAA;AAEzJ,EAAA,MAAM,OAAO,IAAA,CAAK,OAAA,CAAQ,EAAE,KAAA,EAAO,SAAS,CAAA;AAC9C","file":"index.js","sourcesContent":["/**\n * The app's side of Sign in with Apple token revocation: hand the sign-in's\n * authorization code to the `genesis-apple-revoke` Edge Function (it keeps\n * Apple's refresh token server-side), and ask it to revoke after the account\n * is deleted. The function and its migration ship in this package; see the\n * README (\"Revoking Apple's tokens\").\n */\n\n/** The Edge Function's default name, as shipped in `functions/genesis-apple-revoke`. */\nexport const APPLE_REVOKE_FUNCTION = \"genesis-apple-revoke\";\n\n/** The store call waits on Apple's token endpoint (10 s timeout in the function). */\nconst STORE_TIMEOUT_MS = 20_000;\n/** The function answers the revoke call at once and works in the background; don't hold the delete screen for longer. */\nconst REVOKE_TIMEOUT_MS = 5_000;\n\n/** The parts of a Supabase client these helpers use. A `SupabaseClient` fits. */\nexport interface FunctionsClient {\n functions: {\n // Loose on purpose, so any supabase-js version's `invoke` fits.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n invoke: (name: string, options?: any) => PromiseLike<{ data: unknown; error: unknown }>;\n };\n}\n\n/** @stability Beta */\nexport interface StoreAppleTokenOptions {\n /** `authorizationCode` from `signInWithApple`'s result. Single-use, valid for five minutes: send it straight after sign-in. */\n authorizationCode: string;\n /** The client id the code was issued for: your bundle id on iOS. Must be in the function's APPLE_CLIENT_IDS; default its first. */\n clientId?: string;\n /** The Edge Function's name. Default `genesis-apple-revoke`. */\n functionName?: string;\n}\n\n/** @stability Beta */\nexport type StoreAppleTokenResult = { ok: true } | { ok: false; error: Error };\n\n/**\n * After a Sign in with Apple, sends the authorization code to the Edge\n * Function, which exchanges it for Apple's refresh token and keeps it where\n * only the server reads it, so deleting the account can revoke it. Call it\n * with the session from that sign-in. Never throws: the person is signed in\n * either way, so log a failure rather than showing it.\n *\n * @stability Beta\n */\nexport async function storeAppleToken(client: FunctionsClient, { authorizationCode, clientId, functionName = APPLE_REVOKE_FUNCTION }: StoreAppleTokenOptions): Promise<StoreAppleTokenResult> {\n try {\n const { error } = await client.functions.invoke(functionName, { body: { action: \"store\", code: authorizationCode, ...(clientId ? { clientId } : {}) }, timeout: STORE_TIMEOUT_MS });\n if (error) return { ok: false, error: error instanceof Error ? error : new Error(String((error as { message?: unknown }).message ?? error)) };\n return { ok: true };\n } catch (error) {\n return { ok: false, error: error instanceof Error ? error : new Error(String(error)) };\n }\n}\n\n/**\n * Asks the Edge Function to revoke the tokens of deleted accounts now, rather\n * than at its next scheduled run. Never throws and never fails the caller:\n * the account is already gone and the queue keeps the token until a run\n * succeeds.\n */\nexport async function requestAppleRevocation(client: FunctionsClient, functionName = APPLE_REVOKE_FUNCTION): Promise<boolean> {\n try {\n const { error } = await client.functions.invoke(functionName, { body: { action: \"revoke\" }, timeout: REVOKE_TIMEOUT_MS });\n return !error;\n } catch {\n return false;\n }\n}\n","/**\n * Tenant features: the client half of `migrations/0004_genesis_tenant_features.sql`.\n * A tenant's admins turn a shipped feature off (or back on) for their tenant,\n * with a reason; its members read which ids are off and hide them.\n *\n * Exposure only: a switch hides a feature, it never grants or denies access\n * to data (that is RLS) and never sells it (that is an entitlement).\n */\n// A cycle with ./index, used only inside the functions.\nimport { must, type PostgrestErrorLike } from \"./index\";\n\n/** The parts of a Supabase client these helpers use. A `SupabaseClient` fits. */\nexport interface TenantFeaturesClient {\n // Loose on purpose: a client typed by an app's Database narrows `rpc`'s\n // function names, and the app's generated types may not list these yet.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n rpc: (fn: any, ...rest: any[]) => PromiseLike<{ data: unknown; error: PostgrestErrorLike | null }>;\n}\n\ntype RpcResult = { data: unknown; error: null } | { data: null; error: PostgrestErrorLike };\n\n/** Which features a tenant has turned off. A feature not in `off` is on. @stability Beta */\nexport interface TenantFeatures {\n readonly tenantId: string;\n readonly off: ReadonlySet<string>;\n isOn(featureId: string): boolean;\n}\n\n/**\n * The features `tenantId` has turned off, for one of its members (or\n * admins): `tenant_features_off`. Throws a `SupabaseQueryError` (`42501`)\n * for anyone else, so a refusal is never mistaken for \"everything on\".\n *\n * ```ts\n * const features = await tenantFeatures(supabase, teamId);\n * if (features.isOn(\"chat\")) showChatTab();\n * ```\n *\n * @stability Beta\n */\nexport async function tenantFeatures(client: TenantFeaturesClient, tenantId: string): Promise<TenantFeatures> {\n const data = must((await client.rpc(\"tenant_features_off\", { tenant: tenantId })) as RpcResult);\n const off = new Set(Array.isArray(data) ? data.filter((id): id is string => typeof id === \"string\") : []);\n return Object.freeze({ tenantId, off, isOn: (featureId: string) => !off.has(featureId) });\n}\n\n/** @stability Beta */\nexport interface SetTenantFeatureInput {\n tenantId: string;\n featureId: string;\n enabled: boolean;\n /** Why, in at most 500 characters. Required: it goes in the history. */\n reason: string;\n}\n\n/**\n * Turn a feature on or off for a tenant: `set_tenant_feature`. Only the\n * tenant's admins (the app's `private.genesis_tenant_admin` hook); throws a\n * `SupabaseQueryError` otherwise (`42501`), for a blank reason (`22023`) or\n * a malformed feature id (`23514`).\n *\n * @stability Beta\n */\nexport async function setTenantFeature(client: TenantFeaturesClient, input: SetTenantFeatureInput): Promise<void> {\n must(\n (await client.rpc(\"set_tenant_feature\", {\n tenant: input.tenantId,\n feature: input.featureId,\n enabled: input.enabled,\n reason: input.reason,\n })) as RpcResult,\n );\n}\n\n/** One switch a tenant has set. @stability Beta */\nexport interface TenantFeatureSetting {\n feature_id: string;\n enabled: boolean;\n reason: string;\n updated_by: string | null;\n updated_at: string;\n}\n\n/** Every switch a tenant has set, with its reason, for its admins: `tenant_feature_settings`. @stability Beta */\nexport async function tenantFeatureSettings(client: TenantFeaturesClient, tenantId: string): Promise<TenantFeatureSetting[]> {\n return (must((await client.rpc(\"tenant_feature_settings\", { tenant: tenantId })) as RpcResult) ?? []) as TenantFeatureSetting[];\n}\n\n/** One change to a tenant's switches. `enabled` is null when a switch row was deleted (back to on). @stability Beta */\nexport interface TenantFeatureChange {\n feature_id: string;\n enabled: boolean | null;\n reason: string | null;\n /** The person, or null for the service role, a migration, or a person since deleted. */\n changed_by: string | null;\n changed_role: string;\n changed_at: string;\n}\n\n/** A tenant's history of changes, newest first (at most `maxRows`, 1 to 1000, default 100), for its admins. @stability Beta */\nexport async function tenantFeatureHistory(\n client: TenantFeaturesClient,\n tenantId: string,\n options: { maxRows?: number } = {},\n): Promise<TenantFeatureChange[]> {\n const args = options.maxRows === undefined ? { tenant: tenantId } : { tenant: tenantId, max_rows: options.maxRows };\n return (must((await client.rpc(\"tenant_feature_history\", args)) as RpcResult) ?? []) as TenantFeatureChange[];\n}\n","/**\n * The feature registry in the database: the client half of\n * `migrations/0008_genesis_feature_registry.sql`. The server syncs the code\n * registry on deploy; anyone building the gate's snapshot reads a tenant's\n * runtime state in one call.\n */\n// A cycle with ./index, used only inside the functions.\nimport { must, type PostgrestErrorLike } from \"./index\";\n\n/** The parts of a Supabase client these helpers use. A `SupabaseClient` fits. */\nexport interface FeatureRegistryClient {\n // Loose on purpose, as in tenant-features: an app's generated types may not list these yet.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n rpc: (\n fn: any,\n ...rest: any[]\n ) => PromiseLike<{ data: unknown; error: PostgrestErrorLike | null }>;\n}\n\ntype RpcResult =\n { data: unknown; error: null } | { data: null; error: PostgrestErrorLike };\n\n/** A flag value as the database hands it out: the JSON an OpenFeature flag can hold. @stability Beta */\nexport type FlagStateValue = boolean | string | number | { readonly [key: string]: unknown };\n\n/**\n * A tenant's runtime state for the gate, shaped to spread into a\n * `GateContext`: `{ platform, ...await featureGateState(client, tenantId) }`.\n *\n * @stability Beta\n */\nexport interface FeatureGateState {\n /** Feature ids the tenant switched off. */\n off: string[];\n /** Feature ids the tenant holds an active entitlement for. */\n entitlements: string[];\n /** Flag values for the tenant (platform values applied), by flag name. */\n flags: Record<string, FlagStateValue>;\n}\n\nconst strings = (value: unknown): string[] =>\n Array.isArray(value)\n ? value.filter((v): v is string => typeof v === \"string\")\n : [];\n\n/**\n * A tenant's switches, entitlements and flag values: `feature_gate_state`.\n * Works with a signed-in person's client (for tenants they belong to) or the\n * service key. Throws a `SupabaseQueryError` (`42501`) for anyone else, so a\n * refusal is never mistaken for \"nothing set\".\n *\n * @stability Beta\n */\nexport async function featureGateState(client: FeatureRegistryClient, tenantId: string): Promise<FeatureGateState> {\n const data = must((await client.rpc(\"feature_gate_state\", { tenant: tenantId })) as RpcResult);\n // Anything but the expected shape is an error, never \"nothing set\": an empty answer would turn\n // switched-off features back on.\n if (!data || typeof data !== \"object\" || Array.isArray(data)) throw new TypeError(\"feature_gate_state returned no state\");\n const { off, entitled, flags } = data as Record<string, unknown>;\n if (!Array.isArray(off) || !Array.isArray(entitled) || !flags || typeof flags !== \"object\" || Array.isArray(flags)) {\n throw new TypeError(\"feature_gate_state returned an unexpected shape\");\n }\n const values: Record<string, FlagStateValue> = {};\n for (const [key, value] of Object.entries(flags as Record<string, unknown>)) {\n if (typeof value === \"boolean\" || typeof value === \"string\" || typeof value === \"number\") values[key] = value;\n else if (value && typeof value === \"object\" && !Array.isArray(value)) values[key] = value as { [key: string]: unknown };\n }\n return { off: strings(off), entitlements: strings(entitled), flags: values };\n}\n\n/** `features.json` as `genesis features build` writes it. @stability Beta */\nexport interface FeatureRegistryDocument {\n features: readonly ({ id: string } & Record<string, unknown>)[];\n flags?: Readonly<Record<string, Record<string, unknown>>>;\n}\n\n/** @stability Beta */\nexport interface SyncFeatureRegistryOptions {\n /**\n * When this deployment started serving, in milliseconds (`Date.now()` at server start), not its\n * build time: an instant rollback to an older build then syncs as the newest. Older versions\n * than the last sync are refused.\n */\n version: number;\n /** Allow a registry that drops more than a fifth of the features (at least 3). Default false. */\n allowShrink?: boolean;\n}\n\n/** JSON with object keys sorted, so the hash doesn't depend on key order. */\nfunction canonical(value: unknown): string {\n if (Array.isArray(value)) return `[${value.map(canonical).join(\",\")}]`;\n if (value && typeof value === \"object\") {\n const entries = Object.entries(value as Record<string, unknown>).filter(\n ([, v]) => v !== undefined,\n );\n return `{${entries\n .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))\n .map(([k, v]) => `${JSON.stringify(k)}:${canonical(v)}`)\n .join(\",\")}}`;\n }\n return JSON.stringify(value) ?? \"null\";\n}\n\nasync function sha256(text: string): Promise<string> {\n const digest = await globalThis.crypto.subtle.digest(\n \"SHA-256\",\n new TextEncoder().encode(text),\n );\n return Array.from(new Uint8Array(digest), (b) =>\n b.toString(16).padStart(2, \"0\"),\n ).join(\"\");\n}\n\n/**\n * Copy the registry into the database: `sync_feature_registry`. Call it with\n * the service key when a production deployment starts serving, never from a\n * preview. Returns false when the database already has this registry or a\n * newer one; throws (`22023`) for an empty registry or one that drops most\n * features, unless `allowShrink`.\n *\n * ```ts\n * import registry from \"../features.json\";\n * if (process.env.VERCEL_ENV === \"production\") await syncFeatureRegistry(admin, registry, { version: Date.now() });\n * ```\n *\n * @stability Beta\n */\nexport async function syncFeatureRegistry(\n client: FeatureRegistryClient,\n document: FeatureRegistryDocument,\n options: SyncFeatureRegistryOptions,\n): Promise<boolean> {\n if (!Number.isSafeInteger(options.version) || options.version < 0) {\n throw new TypeError(\n \"syncFeatureRegistry: version must be a non-negative integer\",\n );\n }\n const features = [...document.features];\n const flags = Object.entries(document.flags ?? {}).map(([key, flag]) => ({\n key,\n ...flag,\n }));\n const hash = await sha256(canonical({ features, flags }));\n return (\n must(\n (await client.rpc(\"sync_feature_registry\", {\n version: options.version,\n hash,\n features,\n flags,\n allow_shrink: options.allowShrink ?? false,\n })) as RpcResult,\n ) === true\n );\n}\n","/**\n * Supabase for Genesis apps. Platform-neutral: web, React Native and the\n * server import it. Native-only helpers (Keychain storage, foreground\n * refresh, reinstall wipe) are on `@marktiderman/genesis-supabase/native`.\n */\nimport { AuthInvalidJwtError, createClient, type SupabaseClient, type SupabaseClientOptions } from \"@supabase/supabase-js\";\nimport { APPLE_REVOKE_FUNCTION, requestAppleRevocation, type FunctionsClient } from \"./apple-tokens\";\nimport { assertPkceCrypto, claimsViaServer, installWebCrypto, isDigestOnlyPolyfill, type ExpoCryptoLike } from \"./web-crypto\";\n\nexport type { ExpoCryptoLike } from \"./web-crypto\";\nexport {\n APPLE_REVOKE_FUNCTION,\n requestAppleRevocation,\n storeAppleToken,\n type FunctionsClient,\n type StoreAppleTokenOptions,\n type StoreAppleTokenResult,\n} from \"./apple-tokens\";\n\n/** The async key-value store Supabase auth keeps its session in. */\nexport interface SessionStorage {\n getItem(key: string): Promise<string | null>;\n setItem(key: string, value: string): Promise<void>;\n removeItem(key: string): Promise<void>;\n}\n\n/** @stability Beta */\nexport interface GenesisSupabaseOptions {\n url: string;\n /** The publishable (anon) key. Never the secret key in an app. */\n publishableKey: string;\n /** Where the session lives. Native: `keychainStorage(SecureStore)`. Web: leave out for supabase-js's own default. */\n storage?: SessionStorage;\n /** `\"native\"` sets the React Native defaults (no session from the URL). Default `\"web\"`. */\n platform?: \"web\" | \"native\";\n /**\n * Read a session from the URL after an OAuth redirect. Default: `true` on\n * web, `false` on native, where the app hands the redirect URL to\n * `exchangeCodeForSession` itself.\n */\n detectSessionInUrl?: boolean;\n /**\n * `expo-crypto` (`import * as ExpoCrypto from \"expo-crypto\"`), on native.\n * Hermes has no `crypto.subtle`, and without it supabase-js sends the PKCE\n * challenge as \"plain\"; this installs `crypto.getRandomValues` and a SHA-256\n * `crypto.subtle.digest` from it (real WebCrypto is kept), so the challenge\n * is S256. A PKCE client made where there is neither throws in development\n * and logs an error in a release build. With the polyfill in place,\n * `auth.getClaims` always has the server check the token (`getUser`), as\n * supabase-js does where WebCrypto is missing: the polyfill can hash but\n * not verify a signature.\n */\n crypto?: ExpoCryptoLike;\n /** Anything else for supabase-js, merged last. */\n options?: SupabaseClientOptions<\"public\">;\n}\n\n/**\n * A Supabase client with Genesis's defaults: PKCE sign-in (the code flow, not\n * tokens in a redirect URL, with an S256 challenge: pass `crypto` on native),\n * a persisted session that refreshes itself, and\n * the session storage you pass.\n *\n * @stability Beta\n */\nexport function createGenesisSupabase<Database = unknown>({\n url,\n publishableKey,\n storage,\n platform = \"web\",\n detectSessionInUrl = platform === \"web\",\n crypto,\n options = {},\n}: GenesisSupabaseOptions): SupabaseClient<Database> {\n if (crypto) installWebCrypto(crypto);\n // The PKCE flow needs WebCrypto for an S256 challenge; never let it fall back to \"plain\" quietly.\n if ((options.auth?.flowType ?? \"pkce\") === \"pkce\") assertPkceCrypto();\n // supabase-js's generics over the schema don't survive being forwarded, so the\n // options are built untyped and the client is typed by the caller's Database.\n const client = createClient(url, publishableKey, {\n ...options,\n auth: {\n flowType: \"pkce\",\n persistSession: true,\n autoRefreshToken: true,\n detectSessionInUrl,\n ...(storage ? { storage } : {}),\n ...options.auth,\n },\n });\n if (isDigestOnlyPolyfill()) {\n const auth = client.auth;\n auth.getClaims = claimsViaServer(auth, (message) => new AuthInvalidJwtError(message)) as typeof auth.getClaims;\n }\n return client as unknown as SupabaseClient<Database>;\n}\n\n/** What a Supabase or PostgREST error carries. */\nexport interface PostgrestErrorLike {\n message: string;\n code?: string;\n details?: string | null;\n hint?: string | null;\n}\n\n/**\n * A failed query, with the database's `code` (`23505` unique violation,\n * `42501` permission denied, `PGRST116` no rows…), `details` and `hint`, so a\n * caller can tell an RLS refusal from a conflict. The original error is the\n * `cause`.\n *\n * @stability Beta\n */\nexport class SupabaseQueryError extends Error {\n override name = \"SupabaseQueryError\";\n readonly code?: string;\n readonly details?: string | null;\n readonly hint?: string | null;\n constructor(error: PostgrestErrorLike) {\n super(error.message, { cause: error });\n this.code = error.code;\n this.details = error.details;\n this.hint = error.hint;\n }\n}\n\n/**\n * The data, or a thrown {@link SupabaseQueryError}: for query results where an\n * error should fail the caller (a TanStack Query `queryFn`). The return type\n * keeps `null` when the query can return no row (`.maybeSingle()`).\n *\n * @stability Beta\n */\nexport function must<T>(result: { data: T; error: null } | { data: null; error: PostgrestErrorLike }): T {\n if (result.error) throw new SupabaseQueryError(result.error);\n return result.data as T;\n}\n\n/** The parts of a Supabase client {@link deleteMyAccount} uses. A `SupabaseClient` fits. */\nexport interface DeleteAccountClient {\n // Loose on purpose: a client typed by an app's Database narrows `rpc`'s\n // function names, and the app's generated types may not list this one yet.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n rpc: (fn: any, ...rest: any[]) => PromiseLike<{ data: unknown; error: PostgrestErrorLike | null }>;\n auth: { signOut(options?: { scope?: \"global\" | \"local\" | \"others\" }): Promise<unknown> };\n /** Needed only with `revokeAppleTokens`. */\n functions?: FunctionsClient[\"functions\"];\n}\n\n/** @stability Beta */\nexport interface DeleteMyAccountOptions {\n /**\n * After the delete, ask the `genesis-apple-revoke` Edge Function to revoke\n * the person's Sign in with Apple tokens now (`true`, or the function's\n * name). Best effort: the delete has already queued them and the\n * function's schedule retries, so a failure here never fails the call.\n */\n revokeAppleTokens?: boolean | string;\n}\n\n/**\n * In-app account deletion (App Store Review Guideline 5.1.1(v)), on web and\n * native: calls the `delete_my_account` RPC (this package's\n * `migrations/0001_genesis_account_deletion.sql`), which deletes the login\n * and, through the app's `on delete cascade` foreign keys, its data; then\n * clears the session on this device. Throws a {@link SupabaseQueryError} when\n * the database refuses (`42501`: not signed in) and keeps the session then.\n *\n * With Sign in with Apple, ship the `genesis-apple-revoke` function and\n * migration 0003 and pass `{ revokeAppleTokens: true }`: App Review requires\n * the person's Apple tokens to be revoked.\n *\n * Put it behind a confirmation; see the README.\n *\n * @stability Beta\n */\nexport async function deleteMyAccount(client: DeleteAccountClient, options: DeleteMyAccountOptions = {}): Promise<void> {\n must((await client.rpc(\"delete_my_account\")) as { data: unknown; error: null } | { data: null; error: PostgrestErrorLike });\n const revoke = options.revokeAppleTokens;\n // The function needs no login (it works through the queue the delete just filled), so this runs after it.\n if (revoke && client.functions) await requestAppleRevocation({ functions: client.functions }, typeof revoke === \"string\" ? revoke : APPLE_REVOKE_FUNCTION);\n // The login is gone and its refresh tokens with it: only this device's copy is left to clear.\n await client.auth.signOut({ scope: \"local\" });\n}\nexport {\n tenantFeatures,\n setTenantFeature,\n tenantFeatureSettings,\n tenantFeatureHistory,\n type SetTenantFeatureInput,\n type TenantFeatureChange,\n type TenantFeatureSetting,\n type TenantFeatures,\n type TenantFeaturesClient,\n} from \"./tenant-features\";\nexport {\n featureGateState,\n syncFeatureRegistry,\n type FeatureGateState,\n type FlagStateValue,\n type FeatureRegistryClient,\n type FeatureRegistryDocument,\n type SyncFeatureRegistryOptions,\n} from \"./feature-registry\";\nexport { accountBlock, featureMirrorBlock, jobsBlock, tenantFeaturesBlock } from \"./blocks\";\n"]}
1
+ {"version":3,"sources":["../src/apple-tokens.ts","../src/tenant-features.ts","../src/feature-registry.ts","../src/index.ts"],"names":[],"mappings":";;;;;AASO,IAAM,qBAAA,GAAwB;AAGrC,IAAM,gBAAA,GAAmB,GAAA;AAEzB,IAAM,iBAAA,GAAoB,GAAA;AAiC1B,eAAsB,gBAAgB,MAAA,EAAyB,EAAE,mBAAmB,QAAA,EAAU,YAAA,GAAe,uBAAsB,EAA2D;AAC5L,EAAA,IAAI;AACF,IAAA,MAAM,EAAE,KAAA,EAAM,GAAI,MAAM,MAAA,CAAO,UAAU,MAAA,C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AQ,iBAAA;AAEvB,EAAA,IAAI,MAAA,IAAU,MAAA,CAAO,SAAA,EAAW,MAAM,uBAAuB,EAAE,SAAA,EAAW,MAAA,CAAO,SAAA,EAAU,EAAG,OAAO,MAAA,KAAW,QAAA,GAAW,SAAS,qBAAqB,CAAA;AAEzJ,EAAA,MAAM,OAAO,IAAA,CAAK,OAAA,CAAQ,EAAE,KAAA,EAAO,SAAS,CAAA;AAC9C","file":"index.js","sourcesContent":["/**\n * The app's side of Sign in with Apple token revocation: hand the sign-in's\n * authorization code to the `genesis-apple-revoke` Edge Function (it keeps\n * Apple's refresh token server-side), and ask it to revoke after the account\n * is deleted. The function and its migration ship in this package; see the\n * README (\"Revoking Apple's tokens\").\n */\n\n/** The Edge Function's default name, as shipped in `functions/genesis-apple-revoke`. */\nexport const APPLE_REVOKE_FUNCTION = \"genesis-apple-revoke\";\n\n/** The store call waits on Apple's token endpoint (10 s timeout in the function). */\nconst STORE_TIMEOUT_MS = 20_000;\n/** The function answers the revoke call at once and works in the background; don't hold the delete screen for longer. */\nconst REVOKE_TIMEOUT_MS = 5_000;\n\n/** The parts of a Supabase client these helpers use. A `SupabaseClient` fits. */\nexport interface FunctionsClient {\n functions: {\n // Loose on purpose, so any supabase-js version's `invoke` fits.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n invoke: (name: string, options?: any) => PromiseLike<{ data: unknown; error: unknown }>;\n };\n}\n\n/** @stability Beta */\nexport interface StoreAppleTokenOptions {\n /** `authorizationCode` from `signInWithApple`'s result. Single-use, valid for five minutes: send it straight after sign-in. */\n authorizationCode: string;\n /** The client id the code was issued for: your bundle id on iOS. Must be in the function's APPLE_CLIENT_IDS; default its first. */\n clientId?: string;\n /** The Edge Function's name. Default `genesis-apple-revoke`. */\n functionName?: string;\n}\n\n/** @stability Beta */\nexport type StoreAppleTokenResult = { ok: true } | { ok: false; error: Error };\n\n/**\n * After a Sign in with Apple, sends the authorization code to the Edge\n * Function, which exchanges it for Apple's refresh token and keeps it where\n * only the server reads it, so deleting the account can revoke it. Call it\n * with the session from that sign-in. Never throws: the person is signed in\n * either way, so log a failure rather than showing it.\n *\n * @stability Beta\n */\nexport async function storeAppleToken(client: FunctionsClient, { authorizationCode, clientId, functionName = APPLE_REVOKE_FUNCTION }: StoreAppleTokenOptions): Promise<StoreAppleTokenResult> {\n try {\n const { error } = await client.functions.invoke(functionName, { body: { action: \"store\", code: authorizationCode, ...(clientId ? { clientId } : {}) }, timeout: STORE_TIMEOUT_MS });\n if (error) return { ok: false, error: error instanceof Error ? error : new Error(String((error as { message?: unknown }).message ?? error)) };\n return { ok: true };\n } catch (error) {\n return { ok: false, error: error instanceof Error ? error : new Error(String(error)) };\n }\n}\n\n/**\n * Asks the Edge Function to revoke the tokens of deleted accounts now, rather\n * than at its next scheduled run. Never throws and never fails the caller:\n * the account is already gone and the queue keeps the token until a run\n * succeeds.\n */\nexport async function requestAppleRevocation(client: FunctionsClient, functionName = APPLE_REVOKE_FUNCTION): Promise<boolean> {\n try {\n const { error } = await client.functions.invoke(functionName, { body: { action: \"revoke\" }, timeout: REVOKE_TIMEOUT_MS });\n return !error;\n } catch {\n return false;\n }\n}\n","/**\n * Tenant features: the client half of `migrations/0004_genesis_tenant_features.sql`.\n * A tenant's admins turn a shipped feature off (or back on) for their tenant,\n * with a reason; its members read which ids are off and hide them.\n *\n * Exposure only: a switch hides a feature, it never grants or denies access\n * to data (that is RLS) and never sells it (that is an entitlement).\n */\n// A cycle with ./index, used only inside the functions.\nimport { must, type PostgrestErrorLike } from \"./index\";\n\n/** The parts of a Supabase client these helpers use. A `SupabaseClient` fits. */\nexport interface TenantFeaturesClient {\n // Loose on purpose: a client typed by an app's Database narrows `rpc`'s\n // function names, and the app's generated types may not list these yet.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n rpc: (fn: any, ...rest: any[]) => PromiseLike<{ data: unknown; error: PostgrestErrorLike | null }>;\n}\n\ntype RpcResult = { data: unknown; error: null } | { data: null; error: PostgrestErrorLike };\n\n/** Which features a tenant has turned off. A feature not in `off` is on. @stability Beta */\nexport interface TenantFeatures {\n readonly tenantId: string;\n readonly off: ReadonlySet<string>;\n isOn(featureId: string): boolean;\n}\n\n/**\n * The features `tenantId` has turned off, for one of its members (or\n * admins): `tenant_features_off`. Throws a `SupabaseQueryError` (`42501`)\n * for anyone else, so a refusal is never mistaken for \"everything on\".\n *\n * ```ts\n * const features = await tenantFeatures(supabase, teamId);\n * if (features.isOn(\"chat\")) showChatTab();\n * ```\n *\n * @stability Beta\n */\nexport async function tenantFeatures(client: TenantFeaturesClient, tenantId: string): Promise<TenantFeatures> {\n const data = must((await client.rpc(\"tenant_features_off\", { tenant: tenantId })) as RpcResult);\n const off = new Set(Array.isArray(data) ? data.filter((id): id is string => typeof id === \"string\") : []);\n return Object.freeze({ tenantId, off, isOn: (featureId: string) => !off.has(featureId) });\n}\n\n/** @stability Beta */\nexport interface SetTenantFeatureInput {\n tenantId: string;\n featureId: string;\n enabled: boolean;\n /** Why, in at most 500 characters. Required: it goes in the history. */\n reason: string;\n}\n\n/**\n * Turn a feature on or off for a tenant: `set_tenant_feature`. Only the\n * tenant's admins (the app's `private.genesis_tenant_admin` hook); throws a\n * `SupabaseQueryError` otherwise (`42501`), for a blank reason (`22023`) or\n * a malformed feature id (`23514`).\n *\n * @stability Beta\n */\nexport async function setTenantFeature(client: TenantFeaturesClient, input: SetTenantFeatureInput): Promise<void> {\n must(\n (await client.rpc(\"set_tenant_feature\", {\n tenant: input.tenantId,\n feature: input.featureId,\n enabled: input.enabled,\n reason: input.reason,\n })) as RpcResult,\n );\n}\n\n/** One switch a tenant has set. @stability Beta */\nexport interface TenantFeatureSetting {\n feature_id: string;\n enabled: boolean;\n reason: string;\n updated_by: string | null;\n updated_at: string;\n}\n\n/** Every switch a tenant has set, with its reason, for its admins: `tenant_feature_settings`. @stability Beta */\nexport async function tenantFeatureSettings(client: TenantFeaturesClient, tenantId: string): Promise<TenantFeatureSetting[]> {\n return (must((await client.rpc(\"tenant_feature_settings\", { tenant: tenantId })) as RpcResult) ?? []) as TenantFeatureSetting[];\n}\n\n/** One change to a tenant's switches. `enabled` is null when a switch row was deleted (back to on). @stability Beta */\nexport interface TenantFeatureChange {\n feature_id: string;\n enabled: boolean | null;\n reason: string | null;\n /** The person, or null for the service role, a migration, or a person since deleted. */\n changed_by: string | null;\n changed_role: string;\n changed_at: string;\n}\n\n/** A tenant's history of changes, newest first (at most `maxRows`, 1 to 1000, default 100), for its admins. @stability Beta */\nexport async function tenantFeatureHistory(\n client: TenantFeaturesClient,\n tenantId: string,\n options: { maxRows?: number } = {},\n): Promise<TenantFeatureChange[]> {\n const args = options.maxRows === undefined ? { tenant: tenantId } : { tenant: tenantId, max_rows: options.maxRows };\n return (must((await client.rpc(\"tenant_feature_history\", args)) as RpcResult) ?? []) as TenantFeatureChange[];\n}\n","/**\n * The feature registry in the database: the client half of\n * `migrations/0008_genesis_feature_registry.sql`. The server syncs the code\n * registry on deploy; anyone building the gate's snapshot reads a tenant's\n * runtime state in one call.\n */\n// A cycle with ./index, used only inside the functions.\nimport { must, type PostgrestErrorLike } from \"./index\";\n\n/** The parts of a Supabase client these helpers use. A `SupabaseClient` fits. */\nexport interface FeatureRegistryClient {\n // Loose on purpose, as in tenant-features: an app's generated types may not list these yet.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n rpc: (\n fn: any,\n ...rest: any[]\n ) => PromiseLike<{ data: unknown; error: PostgrestErrorLike | null }>;\n}\n\ntype RpcResult =\n { data: unknown; error: null } | { data: null; error: PostgrestErrorLike };\n\n/** A flag value as the database hands it out: the JSON an OpenFeature flag can hold. @stability Beta */\nexport type FlagStateValue = boolean | string | number | { readonly [key: string]: unknown };\n\n/**\n * A tenant's runtime state for the gate, shaped to spread into a\n * `GateContext`: `{ platform, ...await featureGateState(client, tenantId) }`.\n *\n * @stability Beta\n */\nexport interface FeatureGateState {\n /** Feature ids the tenant switched off. */\n off: string[];\n /** Feature ids the tenant holds an active entitlement for. */\n entitlements: string[];\n /** Flag values for the tenant (platform values applied), by flag name. */\n flags: Record<string, FlagStateValue>;\n}\n\nconst strings = (value: unknown): string[] =>\n Array.isArray(value)\n ? value.filter((v): v is string => typeof v === \"string\")\n : [];\n\n/**\n * A tenant's switches, entitlements and flag values: `feature_gate_state`.\n * Works with a signed-in person's client (for tenants they belong to) or the\n * service key. Throws a `SupabaseQueryError` (`42501`) for anyone else, so a\n * refusal is never mistaken for \"nothing set\".\n *\n * @stability Beta\n */\nexport async function featureGateState(client: FeatureRegistryClient, tenantId: string): Promise<FeatureGateState> {\n const data = must((await client.rpc(\"feature_gate_state\", { tenant: tenantId })) as RpcResult);\n // Anything but the expected shape is an error, never \"nothing set\": an empty answer would turn\n // switched-off features back on.\n if (!data || typeof data !== \"object\" || Array.isArray(data)) throw new TypeError(\"feature_gate_state returned no state\");\n const { off, entitled, flags } = data as Record<string, unknown>;\n if (!Array.isArray(off) || !Array.isArray(entitled) || !flags || typeof flags !== \"object\" || Array.isArray(flags)) {\n throw new TypeError(\"feature_gate_state returned an unexpected shape\");\n }\n const values: Record<string, FlagStateValue> = {};\n for (const [key, value] of Object.entries(flags as Record<string, unknown>)) {\n if (typeof value === \"boolean\" || typeof value === \"string\" || typeof value === \"number\") values[key] = value;\n else if (value && typeof value === \"object\" && !Array.isArray(value)) values[key] = value as { [key: string]: unknown };\n }\n return { off: strings(off), entitlements: strings(entitled), flags: values };\n}\n\n/** `features.json` as `genesis features build` writes it. @stability Beta */\nexport interface FeatureRegistryDocument {\n features: readonly ({ id: string } & Record<string, unknown>)[];\n flags?: Readonly<Record<string, Record<string, unknown>>>;\n}\n\n/** @stability Beta */\nexport interface SyncFeatureRegistryOptions {\n /**\n * This build's version: an increasing number such as the build time in milliseconds, so an old\n * production deployment (Vercel keeps VERCEL_ENV=production on every one) can't sync over a newer\n * one. Older versions than the last sync are refused.\n */\n version: number;\n /** Allow a registry that drops more than a fifth of the features (at least 3). Default false. */\n allowShrink?: boolean;\n}\n\n/** JSON with object keys sorted, so the hash doesn't depend on key order. */\nfunction canonical(value: unknown): string {\n if (Array.isArray(value)) return `[${value.map(canonical).join(\",\")}]`;\n if (value && typeof value === \"object\") {\n const entries = Object.entries(value as Record<string, unknown>).filter(\n ([, v]) => v !== undefined,\n );\n return `{${entries\n .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))\n .map(([k, v]) => `${JSON.stringify(k)}:${canonical(v)}`)\n .join(\",\")}}`;\n }\n return JSON.stringify(value) ?? \"null\";\n}\n\nasync function sha256(text: string): Promise<string> {\n const digest = await globalThis.crypto.subtle.digest(\n \"SHA-256\",\n new TextEncoder().encode(text),\n );\n return Array.from(new Uint8Array(digest), (b) =>\n b.toString(16).padStart(2, \"0\"),\n ).join(\"\");\n}\n\n/**\n * Copy the registry into the database: `sync_feature_registry`. Call it with\n * the service key when a production deployment starts serving, never from a\n * preview. Returns false when the database already has this registry or a\n * newer one; throws (`22023`) for an empty registry or one that drops most\n * features, unless `allowShrink`.\n *\n * ```ts\n * import registry from \"../features.json\";\n * if (process.env.VERCEL_ENV === \"production\") await syncFeatureRegistry(admin, registry, { version: BUILD_TIME });\n * ```\n *\n * @stability Beta\n */\nexport async function syncFeatureRegistry(\n client: FeatureRegistryClient,\n document: FeatureRegistryDocument,\n options: SyncFeatureRegistryOptions,\n): Promise<boolean> {\n if (!Number.isSafeInteger(options.version) || options.version < 0) {\n throw new TypeError(\n \"syncFeatureRegistry: version must be a non-negative integer\",\n );\n }\n const features = [...document.features];\n const flags = Object.entries(document.flags ?? {}).map(([key, flag]) => ({\n key,\n ...flag,\n }));\n const hash = await sha256(canonical({ features, flags }));\n return (\n must(\n (await client.rpc(\"sync_feature_registry\", {\n version: options.version,\n hash,\n features,\n flags,\n allow_shrink: options.allowShrink ?? false,\n })) as RpcResult,\n ) === true\n );\n}\n","/**\n * Supabase for Genesis apps. Platform-neutral: web, React Native and the\n * server import it. Native-only helpers (Keychain storage, foreground\n * refresh, reinstall wipe) are on `@marktiderman/genesis-supabase/native`.\n */\nimport { AuthInvalidJwtError, createClient, type SupabaseClient, type SupabaseClientOptions } from \"@supabase/supabase-js\";\nimport { APPLE_REVOKE_FUNCTION, requestAppleRevocation, type FunctionsClient } from \"./apple-tokens\";\nimport { assertPkceCrypto, claimsViaServer, installWebCrypto, isDigestOnlyPolyfill, type ExpoCryptoLike } from \"./web-crypto\";\n\nexport type { ExpoCryptoLike } from \"./web-crypto\";\nexport {\n APPLE_REVOKE_FUNCTION,\n requestAppleRevocation,\n storeAppleToken,\n type FunctionsClient,\n type StoreAppleTokenOptions,\n type StoreAppleTokenResult,\n} from \"./apple-tokens\";\n\n/** The async key-value store Supabase auth keeps its session in. */\nexport interface SessionStorage {\n getItem(key: string): Promise<string | null>;\n setItem(key: string, value: string): Promise<void>;\n removeItem(key: string): Promise<void>;\n}\n\n/** @stability Beta */\nexport interface GenesisSupabaseOptions {\n url: string;\n /** The publishable (anon) key. Never the secret key in an app. */\n publishableKey: string;\n /** Where the session lives. Native: `keychainStorage(SecureStore)`. Web: leave out for supabase-js's own default. */\n storage?: SessionStorage;\n /** `\"native\"` sets the React Native defaults (no session from the URL). Default `\"web\"`. */\n platform?: \"web\" | \"native\";\n /**\n * Read a session from the URL after an OAuth redirect. Default: `true` on\n * web, `false` on native, where the app hands the redirect URL to\n * `exchangeCodeForSession` itself.\n */\n detectSessionInUrl?: boolean;\n /**\n * `expo-crypto` (`import * as ExpoCrypto from \"expo-crypto\"`), on native.\n * Hermes has no `crypto.subtle`, and without it supabase-js sends the PKCE\n * challenge as \"plain\"; this installs `crypto.getRandomValues` and a SHA-256\n * `crypto.subtle.digest` from it (real WebCrypto is kept), so the challenge\n * is S256. A PKCE client made where there is neither throws in development\n * and logs an error in a release build. With the polyfill in place,\n * `auth.getClaims` always has the server check the token (`getUser`), as\n * supabase-js does where WebCrypto is missing: the polyfill can hash but\n * not verify a signature.\n */\n crypto?: ExpoCryptoLike;\n /** Anything else for supabase-js, merged last. */\n options?: SupabaseClientOptions<\"public\">;\n}\n\n/**\n * A Supabase client with Genesis's defaults: PKCE sign-in (the code flow, not\n * tokens in a redirect URL, with an S256 challenge: pass `crypto` on native),\n * a persisted session that refreshes itself, and\n * the session storage you pass.\n *\n * @stability Beta\n */\nexport function createGenesisSupabase<Database = unknown>({\n url,\n publishableKey,\n storage,\n platform = \"web\",\n detectSessionInUrl = platform === \"web\",\n crypto,\n options = {},\n}: GenesisSupabaseOptions): SupabaseClient<Database> {\n if (crypto) installWebCrypto(crypto);\n // The PKCE flow needs WebCrypto for an S256 challenge; never let it fall back to \"plain\" quietly.\n if ((options.auth?.flowType ?? \"pkce\") === \"pkce\") assertPkceCrypto();\n // supabase-js's generics over the schema don't survive being forwarded, so the\n // options are built untyped and the client is typed by the caller's Database.\n const client = createClient(url, publishableKey, {\n ...options,\n auth: {\n flowType: \"pkce\",\n persistSession: true,\n autoRefreshToken: true,\n detectSessionInUrl,\n ...(storage ? { storage } : {}),\n ...options.auth,\n },\n });\n if (isDigestOnlyPolyfill()) {\n const auth = client.auth;\n auth.getClaims = claimsViaServer(auth, (message) => new AuthInvalidJwtError(message)) as typeof auth.getClaims;\n }\n return client as unknown as SupabaseClient<Database>;\n}\n\n/** What a Supabase or PostgREST error carries. */\nexport interface PostgrestErrorLike {\n message: string;\n code?: string;\n details?: string | null;\n hint?: string | null;\n}\n\n/**\n * A failed query, with the database's `code` (`23505` unique violation,\n * `42501` permission denied, `PGRST116` no rows…), `details` and `hint`, so a\n * caller can tell an RLS refusal from a conflict. The original error is the\n * `cause`.\n *\n * @stability Beta\n */\nexport class SupabaseQueryError extends Error {\n override name = \"SupabaseQueryError\";\n readonly code?: string;\n readonly details?: string | null;\n readonly hint?: string | null;\n constructor(error: PostgrestErrorLike) {\n super(error.message, { cause: error });\n this.code = error.code;\n this.details = error.details;\n this.hint = error.hint;\n }\n}\n\n/**\n * The data, or a thrown {@link SupabaseQueryError}: for query results where an\n * error should fail the caller (a TanStack Query `queryFn`). The return type\n * keeps `null` when the query can return no row (`.maybeSingle()`).\n *\n * @stability Beta\n */\nexport function must<T>(result: { data: T; error: null } | { data: null; error: PostgrestErrorLike }): T {\n if (result.error) throw new SupabaseQueryError(result.error);\n return result.data as T;\n}\n\n/** The parts of a Supabase client {@link deleteMyAccount} uses. A `SupabaseClient` fits. */\nexport interface DeleteAccountClient {\n // Loose on purpose: a client typed by an app's Database narrows `rpc`'s\n // function names, and the app's generated types may not list this one yet.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n rpc: (fn: any, ...rest: any[]) => PromiseLike<{ data: unknown; error: PostgrestErrorLike | null }>;\n auth: { signOut(options?: { scope?: \"global\" | \"local\" | \"others\" }): Promise<unknown> };\n /** Needed only with `revokeAppleTokens`. */\n functions?: FunctionsClient[\"functions\"];\n}\n\n/** @stability Beta */\nexport interface DeleteMyAccountOptions {\n /**\n * After the delete, ask the `genesis-apple-revoke` Edge Function to revoke\n * the person's Sign in with Apple tokens now (`true`, or the function's\n * name). Best effort: the delete has already queued them and the\n * function's schedule retries, so a failure here never fails the call.\n */\n revokeAppleTokens?: boolean | string;\n}\n\n/**\n * In-app account deletion (App Store Review Guideline 5.1.1(v)), on web and\n * native: calls the `delete_my_account` RPC (this package's\n * `migrations/0001_genesis_account_deletion.sql`), which deletes the login\n * and, through the app's `on delete cascade` foreign keys, its data; then\n * clears the session on this device. Throws a {@link SupabaseQueryError} when\n * the database refuses (`42501`: not signed in) and keeps the session then.\n *\n * With Sign in with Apple, ship the `genesis-apple-revoke` function and\n * migration 0003 and pass `{ revokeAppleTokens: true }`: App Review requires\n * the person's Apple tokens to be revoked.\n *\n * Put it behind a confirmation; see the README.\n *\n * @stability Beta\n */\nexport async function deleteMyAccount(client: DeleteAccountClient, options: DeleteMyAccountOptions = {}): Promise<void> {\n must((await client.rpc(\"delete_my_account\")) as { data: unknown; error: null } | { data: null; error: PostgrestErrorLike });\n const revoke = options.revokeAppleTokens;\n // The function needs no login (it works through the queue the delete just filled), so this runs after it.\n if (revoke && client.functions) await requestAppleRevocation({ functions: client.functions }, typeof revoke === \"string\" ? revoke : APPLE_REVOKE_FUNCTION);\n // The login is gone and its refresh tokens with it: only this device's copy is left to clear.\n await client.auth.signOut({ scope: \"local\" });\n}\nexport {\n tenantFeatures,\n setTenantFeature,\n tenantFeatureSettings,\n tenantFeatureHistory,\n type SetTenantFeatureInput,\n type TenantFeatureChange,\n type TenantFeatureSetting,\n type TenantFeatures,\n type TenantFeaturesClient,\n} from \"./tenant-features\";\nexport {\n featureGateState,\n syncFeatureRegistry,\n type FeatureGateState,\n type FlagStateValue,\n type FeatureRegistryClient,\n type FeatureRegistryDocument,\n type SyncFeatureRegistryOptions,\n} from \"./feature-registry\";\nexport { accountBlock, featureMirrorBlock, jobsBlock, ownerAccessBlock, tenantFeaturesBlock } from \"./blocks\";\n"]}
package/dist/jobs.d.ts CHANGED
@@ -120,7 +120,9 @@ declare function defaultBackoff(attempt: number): number;
120
120
  * Claim due jobs of the handled kinds, run them, and settle each: done, a
121
121
  * retry after backoff, or failed. One job's failure, or a failure to record
122
122
  * it, never stops the others; only a failed claim throws. Nothing about a
123
- * payload is logged.
123
+ * payload is logged. It runs on the shared engine (`createRunner` from
124
+ * `/runner`): the queue's claim and settle are its store, each kind's handler
125
+ * its sender, and the queue itself decides when a job is out of attempts.
124
126
  *
125
127
  * @stability Beta
126
128
  */
package/dist/jobs.js CHANGED
@@ -1,3 +1,5 @@
1
+ import { createRunner } from './chunk-XGAXPUFY.js';
2
+
1
3
  // src/jobs.ts
2
4
  var JobsError = class extends Error {
3
5
  code;
@@ -36,29 +38,11 @@ function messageOf(error) {
36
38
  }
37
39
  async function runJobs(client, options) {
38
40
  const kinds = Object.keys(options.handlers);
39
- const report = { claimed: 0, done: 0, retried: 0, failed: 0, stale: 0, unsettled: 0 };
40
- if (kinds.length === 0) return report;
41
+ const empty = { claimed: 0, done: 0, retried: 0, failed: 0, stale: 0, unsettled: 0 };
42
+ if (kinds.length === 0) return empty;
41
43
  const backoff = options.backoff ?? defaultBackoff;
42
44
  const log = options.log ?? ((line) => console.error(line));
43
- const claimed = await call(client, "genesis_jobs_claim", {
44
- p_kinds: kinds,
45
- p_limit: options.limit ?? 25,
46
- p_lease_seconds: options.leaseSeconds ?? 300
47
- }) ?? [];
48
- report.claimed = claimed.length;
49
- const settle = async (job, outcome, retryAfter, error) => {
50
- const ok = await call(client, "genesis_jobs_settle", {
51
- p_id: job.id,
52
- p_claim_id: job.claim_id,
53
- p_outcome: outcome,
54
- p_retry_after_seconds: retryAfter,
55
- p_error: error
56
- });
57
- if (!ok) report.stale++;
58
- else if (outcome === "done") report.done++;
59
- else if (outcome === "retry") report.retried++;
60
- else report.failed++;
61
- };
45
+ const settles = /* @__PURE__ */ new WeakMap();
62
46
  const outcomeOf = async (job) => {
63
47
  const handler = options.handlers[job.kind];
64
48
  const { claim_id: _claim, ...seen } = job;
@@ -76,21 +60,51 @@ async function runJobs(client, options) {
76
60
  return error instanceof PermanentJobError ? ["failed", null, message] : ["retry", backoff(job.attempt), message];
77
61
  }
78
62
  };
79
- const runOne = async (job) => {
80
- const [outcome, retryAfter, error] = await outcomeOf(job);
81
- try {
82
- await settle(job, outcome, retryAfter, error);
83
- } catch (failure) {
84
- report.unsettled++;
85
- log(`[jobs] ${job.kind} ${job.id}: could not record ${outcome}: ${messageOf(failure)}`);
86
- }
63
+ const resultOf = ([outcome, retryAfter, error]) => {
64
+ if (outcome === "done") return { ok: true };
65
+ if (outcome === "failed") return { ok: false, retryable: false, error: error ?? "failed" };
66
+ return { ok: false, retryable: true, retryAfterSeconds: retryAfter ?? 0, error: error ?? "retry" };
87
67
  };
88
- const queue = [...claimed];
89
- const workers = Array.from({ length: Math.max(1, Math.min(options.concurrency ?? 4, queue.length)) }, async () => {
90
- for (let job = queue.shift(); job; job = queue.shift()) await runOne(job);
68
+ const runner = createRunner({
69
+ claim: async ({ limit }) => await call(client, "genesis_jobs_claim", {
70
+ p_kinds: kinds,
71
+ p_limit: limit,
72
+ p_lease_seconds: options.leaseSeconds ?? 300
73
+ }) ?? [],
74
+ send: async ([job]) => {
75
+ const settle = await outcomeOf(job);
76
+ settles.set(job, settle);
77
+ return [resultOf(settle)];
78
+ },
79
+ record: async (job) => {
80
+ const [outcome, retryAfter, error] = settles.get(job);
81
+ try {
82
+ const ok = await call(client, "genesis_jobs_settle", {
83
+ p_id: job.id,
84
+ p_claim_id: job.claim_id,
85
+ p_outcome: outcome,
86
+ p_retry_after_seconds: retryAfter,
87
+ p_error: error
88
+ });
89
+ return Boolean(ok);
90
+ } catch (failure) {
91
+ log(`[jobs] ${job.kind} ${job.id}: could not record ${outcome}: ${messageOf(failure)}`);
92
+ throw failure;
93
+ }
94
+ },
95
+ concurrency: options.concurrency ?? 4,
96
+ maxAttempts: Number.POSITIVE_INFINITY,
97
+ maxDeferrals: Number.POSITIVE_INFINITY
91
98
  });
92
- await Promise.all(workers);
93
- return report;
99
+ const report = await runner.run({ limit: options.limit ?? 25 });
100
+ return {
101
+ claimed: report.claimed,
102
+ done: report.sent,
103
+ retried: report.retrying + report.deferred,
104
+ failed: report.failed,
105
+ stale: report.stale,
106
+ unsettled: report.unrecorded
107
+ };
94
108
  }
95
109
  var encoder = new TextEncoder();
96
110
  async function digest(value) {
package/dist/jobs.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/jobs.ts"],"names":[],"mappings":";AAsCO,IAAM,SAAA,GAAN,cAAwB,KAAA,CAAM;AAAA,EAC1B,IAAA;AAAA,EACT,WAAA,CAAY,SAAiB,IAAA,EAAe;AAC1C,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,WAAA;AACZ,IAAA,IAAA,CAAK,IAAA,GAAO,IAAA;AAAA,EACd;AACF;AAEA,eAAe,IAAA,CAAQ,MAAA,EAAoB,EAAA,EAAY,IAAA,EAA2C;AAChG,EAAA,MAAM,EAAE,MAAM,KAAA,EAAM,GAAI,MAAM,MAAA,CAAO,GAAA,CAAI,IAAI,IAAI,CA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AAA,CAAQ,IAAA,CAAK,GAAG,CAAA,GAAI,MAAA;AAChG,IAAA,IAAI,CAAC,GAAA,EAAK,OAAO,QAAA,CAAS,IAAA,CAAK,EAAE,KAAA,EAAO,cAAA,EAAe,EAAG,EAAE,MAAA,EAAQ,GAAA,EAAK,CAAA;AAEzE,IAAA,IAAI;AACF,MAAA,MAAM,SAAU,MAAM,GAAA,CAAI,EAAE,OAAA,EAAS,IAAA,EAAM,CAAA,IAAM,IAAA;AACjD,MAAA,OAAO,QAAA,CAAS,IAAA,CAAK,MAAA,GAAS,EAAE,GAAA,EAAK,EAAA,EAAI,IAAA,EAAK,GAAI,EAAE,GAAA,EAAK,MAAA,EAAQ,CAAA;AAAA,IACnE,SAAS,KAAA,EAAO;AACd,MAAA,GAAA,CAAI,UAAU,GAAG,CAAA,EAAA,EAAK,SAAA,CAAU,KAAK,CAAC,CAAA,CAAE,CAAA;AACxC,MAAA,OAAO,QAAA,CAAS,IAAA,CAAK,EAAE,GAAA,EAAK,KAAA,EAAO,uCAAsC,EAAG,EAAE,MAAA,EAAQ,GAAA,EAAK,CAAA;AAAA,IAC7F;AAAA,EACF,CAAA;AACF","file":"jobs.js","sourcesContent":["/**\n * `@marktiderman/genesis-supabase/jobs`: the server half of\n * `migrations/0007_genesis_jobs.sql`. Server only (it takes the service-role\n * client and the job secret); never import it into browser or app code.\n *\n * - `enqueueJob`: queue work from server code (triggers enqueue in SQL).\n * - `runJobs`: claim due jobs, run each kind's handler, settle each one, with\n * backoff on failure. Never throws for one job's failure.\n * - `createJobsHandler`: the app's one job route. It checks the request is\n * signed for the job (`genesis_schedule_job` signs; the secret never\n * travels) or carries the bearer secret (a platform cron, a person), with a\n * previous secret accepted while you rotate it, and runs the named job.\n *\n * ```ts\n * // src/routes/api/jobs/$job.ts (any server route that hands over a Request)\n * const handle = createJobsHandler({\n * secret: process.env.GENESIS_JOBS_SECRET,\n * previousSecret: process.env.GENESIS_JOBS_SECRET_PREVIOUS,\n * jobs: {\n * queue: () => runJobs(admin, { handlers: { \"email.digest\": sendDigest } }),\n * cleanup: () => removeQueuedFiles(admin),\n * },\n * });\n * export const POST = ({ request, params }) => handle(request, params.job);\n * ```\n *\n * @packageDocumentation\n */\n\n/** The parts of a Supabase client these helpers use: a service-role `SupabaseClient` fits. */\nexport interface JobsClient {\n // Loose on purpose: a client typed by an app's Database narrows `rpc`'s\n // function names, and the app's generated types may not list these yet.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n rpc: (fn: any, ...rest: any[]) => PromiseLike<{ data: unknown; error: { message: string; code?: string } | null }>;\n}\n\n/** A failure from the queue's own functions (not from a handler). */\nexport class JobsError extends Error {\n readonly code: string | undefined;\n constructor(message: string, code?: string) {\n super(message);\n this.name = \"JobsError\";\n this.code = code;\n }\n}\n\nasync function call<T>(client: JobsClient, fn: string, args: Record<string, unknown>): Promise<T> {\n const { data, error } = await client.rpc(fn, args);\n if (error) throw new JobsError(`${fn}: ${error.message}`, error.code);\n return data as T;\n}\n\n/** @stability Beta */\nexport interface EnqueueOptions {\n /** Run no earlier than this. Default now. */\n runAfter?: Date;\n /** One job per kind and key while it is queued or running: a repeat returns the queued job's id. */\n idempotencyKey?: string;\n /** Attempts before it fails for good, 1 to 100. Default 8. */\n maxAttempts?: number;\n}\n\n/**\n * Queue one job of `kind` (`\"email.digest\"`, lowercase) with a JSON object\n * payload. Returns the job's id. Payloads are readable by the service role:\n * put ids in them, never secrets.\n *\n * @stability Beta\n */\nexport function enqueueJob(client: JobsClient, kind: string, payload: Record<string, unknown> = {}, options: EnqueueOptions = {}): Promise<string> {\n return call<string>(client, \"genesis_job_enqueue\", {\n p_kind: kind,\n p_payload: payload,\n p_run_after: options.runAfter?.toISOString() ?? null,\n p_idempotency_key: options.idempotencyKey ?? null,\n p_max_attempts: options.maxAttempts ?? 8,\n });\n}\n\n/** One claimed job, as a handler sees it. @stability Beta */\nexport interface Job<Payload = Record<string, unknown>> {\n id: string;\n kind: string;\n payload: Payload;\n /** This attempt's number, from 1. */\n attempt: number;\n /** An earlier attempt's lease ran out: it may have done the work. Handlers that can look first, do. */\n redelivery: boolean;\n}\n\n/**\n * What a handler can return. Nothing (or `{ done: true }`) is done. Throwing\n * retries with backoff; throw a `PermanentJobError` (or return\n * `{ failed }`) to stop.\n *\n * @stability Beta\n */\nexport type JobOutcome =\n | void\n | { done: true }\n | { retryAfterSeconds: number; error?: string }\n | { failed: string };\n\n/** Thrown by a handler for a failure that won't get better with a retry (a bad payload, a 4xx). @stability Beta */\nexport class PermanentJobError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"PermanentJobError\";\n }\n}\n\n// Handlers are keyed by kind, so each takes its own payload type.\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type JobHandler = (job: Job<any>) => Promise<JobOutcome> | JobOutcome;\n\n/** @stability Beta */\nexport interface RunJobsOptions {\n /** Kind → handler. Only these kinds are claimed. */\n handlers: Readonly<Record<string, JobHandler>>;\n /** Jobs claimed in this run. Default 25. */\n limit?: number;\n /** How long a claim holds a job; a handler must finish inside it. Default 300. */\n leaseSeconds?: number;\n /** Jobs run at once. Default 4. */\n concurrency?: number;\n /** Seconds before retry `attempt` (from 1). Default 30 s doubling, jittered, at most an hour. */\n backoff?: (attempt: number) => number;\n /** Where one line per failed job goes (kind, id, attempt, the error's message). Default console.error. */\n log?: (line: string) => void;\n}\n\n/** @stability Beta */\nexport interface RunJobsReport {\n claimed: number;\n done: number;\n retried: number;\n failed: number;\n /** Settles refused because the lease ran out first (another run has the job). */\n stale: number;\n /** Settles that failed (the database unreachable): those jobs come back when their lease runs out. */\n unsettled: number;\n}\n\n/** 30 s, doubling per attempt, ±20% jitter, at most an hour. */\nexport function defaultBackoff(attempt: number): number {\n const base = Math.min(3600, 30 * 2 ** Math.max(0, attempt - 1));\n return Math.round(base * (0.8 + Math.random() * 0.4));\n}\n\nfunction messageOf(error: unknown): string {\n return (error instanceof Error ? `${error.name}: ${error.message}` : String(error)).slice(0, 1000);\n}\n\n/**\n * Claim due jobs of the handled kinds, run them, and settle each: done, a\n * retry after backoff, or failed. One job's failure, or a failure to record\n * it, never stops the others; only a failed claim throws. Nothing about a\n * payload is logged.\n *\n * @stability Beta\n */\nexport async function runJobs(client: JobsClient, options: RunJobsOptions): Promise<RunJobsReport> {\n const kinds = Object.keys(options.handlers);\n const report: RunJobsReport = { claimed: 0, done: 0, retried: 0, failed: 0, stale: 0, unsettled: 0 };\n if (kinds.length === 0) return report;\n const backoff = options.backoff ?? defaultBackoff;\n const log = options.log ?? ((line: string) => console.error(line));\n\n type Claimed = Job & { claim_id: string };\n const claimed =\n (await call<Claimed[] | null>(client, \"genesis_jobs_claim\", {\n p_kinds: kinds,\n p_limit: options.limit ?? 25,\n p_lease_seconds: options.leaseSeconds ?? 300,\n })) ?? [];\n report.claimed = claimed.length;\n\n const settle = async (job: Claimed, outcome: \"done\" | \"retry\" | \"failed\", retryAfter: number | null, error: string | null) => {\n const ok = await call<boolean>(client, \"genesis_jobs_settle\", {\n p_id: job.id,\n p_claim_id: job.claim_id,\n p_outcome: outcome,\n p_retry_after_seconds: retryAfter,\n p_error: error,\n });\n if (!ok) report.stale++;\n else if (outcome === \"done\") report.done++;\n else if (outcome === \"retry\") report.retried++;\n else report.failed++;\n };\n\n type Settle = [\"done\" | \"retry\" | \"failed\", number | null, string | null];\n\n // What the handler says, as a settle. Only the handler runs inside this try.\n const outcomeOf = async (job: Claimed): Promise<Settle> => {\n const handler = options.handlers[job.kind];\n const { claim_id: _claim, ...seen } = job;\n try {\n const outcome = handler ? await handler(seen) : { failed: `no handler for ${job.kind}` };\n if (outcome && \"failed\" in outcome) {\n log(`[jobs] ${job.kind} ${job.id} attempt ${job.attempt} failed: ${outcome.failed}`);\n return [\"failed\", null, outcome.failed.slice(0, 1000)];\n }\n if (outcome && \"retryAfterSeconds\" in outcome) return [\"retry\", Math.max(0, Math.round(outcome.retryAfterSeconds)), outcome.error ?? null];\n return [\"done\", null, null];\n } catch (error) {\n const message = messageOf(error);\n log(`[jobs] ${job.kind} ${job.id} attempt ${job.attempt}: ${message}`);\n return error instanceof PermanentJobError ? [\"failed\", null, message] : [\"retry\", backoff(job.attempt), message];\n }\n };\n\n const runOne = async (job: Claimed) => {\n const [outcome, retryAfter, error] = await outcomeOf(job);\n try {\n await settle(job, outcome, retryAfter, error);\n } catch (failure) {\n // The queue didn't take the outcome: the lease runs out and the job comes back as a\n // redelivery. The other jobs in this run carry on.\n report.unsettled++;\n log(`[jobs] ${job.kind} ${job.id}: could not record ${outcome}: ${messageOf(failure)}`);\n }\n };\n\n const queue = [...claimed];\n const workers = Array.from({ length: Math.max(1, Math.min(options.concurrency ?? 4, queue.length)) }, async () => {\n for (let job = queue.shift(); job; job = queue.shift()) await runOne(job);\n });\n await Promise.all(workers);\n return report;\n}\n\nconst encoder = new TextEncoder();\n\nasync function digest(value: string): Promise<Uint8Array> {\n return new Uint8Array(await crypto.subtle.digest(\"SHA-256\", encoder.encode(value)));\n}\n\nfunction sameBytes(a: Uint8Array, b: Uint8Array): boolean {\n let diff = a.length ^ b.length;\n for (let i = 0; i < a.length && i < b.length; i++) diff |= a[i]! ^ b[i]!;\n return diff === 0;\n}\n\n/** @stability Beta */\nexport interface VerifyJobRequestOptions {\n /** The job secret. Unset refuses every request (500). */\n secret: string | undefined;\n /** The secret before a rotation, accepted too. Remove it once every caller has the new one. */\n previousSecret?: string | undefined;\n /** How far a signed request's time may be from now, in seconds. Default 300. */\n maxSkewSeconds?: number;\n /** Now, in seconds (for tests). */\n now?: () => number;\n}\n\nconst hex = (bytes: ArrayBuffer) => Array.from(new Uint8Array(bytes), (b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n\nasync function hmacHex(secret: string, message: string): Promise<string> {\n const key = await crypto.subtle.importKey(\"raw\", encoder.encode(secret), { name: \"HMAC\", hash: \"SHA-256\" }, false, [\"sign\"]);\n return hex(await crypto.subtle.sign(\"HMAC\", key, encoder.encode(message)));\n}\n\n/**\n * The `Authorization` value a scheduler sends for `job`: `GenesisJob\n * t=<unix seconds>,sig=<hex HMAC-SHA256 of \"<t>.<job>\">`. What\n * `genesis_schedule_job` sends; for calling a job route from your own code.\n *\n * @stability Beta\n */\nexport async function signJobRequest(secret: string, job: string, now: number = Math.floor(Date.now() / 1000)): Promise<string> {\n return `GenesisJob t=${now},sig=${await hmacHex(secret, `${now}.${job}`)}`;\n}\n\n/**\n * Checks a request's `Authorization` in constant time against the secret and\n * the previous one. Two forms: `GenesisJob t=…,sig=…`, signed for `job` within\n * `maxSkewSeconds` (what schedules send: the secret never travels), or\n * `Bearer <secret>` (a platform cron, a person). The scheme's case and extra\n * spaces don't matter. Returns `null` when it passes, else the response to\n * send: 401, or 500 when no secret is configured.\n *\n * @stability Beta\n */\nexport async function verifyJobRequest(request: Request, options: VerifyJobRequestOptions, job?: string): Promise<Response | null> {\n if (!options.secret) return Response.json({ error: \"The job secret is not configured.\" }, { status: 500 });\n const secrets = [options.secret, ...(options.previousSecret ? [options.previousSecret] : [])];\n const header = (request.headers.get(\"authorization\") ?? \"\").trim();\n const unauthorized = () => Response.json({ error: \"Unauthorized.\" }, { status: 401 });\n\n const bearer = /^bearer\\s+([^\\s,]+)$/i.exec(header)?.[1];\n if (bearer) {\n const given = await digest(bearer);\n let ok = false;\n for (const secret of secrets) ok = sameBytes(given, await digest(secret)) || ok;\n return ok ? null : unauthorized();\n }\n\n const signed = /^genesisjob\\s+t=(\\d{1,12})\\s*,\\s*sig=([0-9a-f]{64})$/i.exec(header);\n if (signed && job) {\n const t = Number(signed[1]);\n const now = options.now?.() ?? Math.floor(Date.now() / 1000);\n if (Math.abs(now - t) > (options.maxSkewSeconds ?? 300)) return unauthorized();\n const given = await digest(signed[2]!.toLowerCase());\n let ok = false;\n for (const secret of secrets) ok = sameBytes(given, await digest(await hmacHex(secret, `${t}.${job}`))) || ok;\n return ok ? null : unauthorized();\n }\n return unauthorized();\n}\n\n/**\n * One named job a route can run. Its return value (JSON) is the response's `result` for a\n * bearer call; a signed call (a schedule) gets `{ job, ok: true }` and its `body` is always `{}`.\n *\n * @stability Beta\n */\nexport type NamedJob = (context: { request: Request; body: Record<string, unknown> }) => Promise<unknown> | unknown;\n\n/** @stability Beta */\nexport interface JobsHandlerOptions extends VerifyJobRequestOptions {\n /** Job name (`\"digests\"`, as `genesis_schedule_job` names it) → what it runs. */\n jobs: Readonly<Record<string, NamedJob>>;\n /** Where a job's failure goes (name and the error's message). Default console.error. */\n log?: (line: string) => void;\n}\n\nconst JOB_NAME = /^[a-z][a-z0-9]*([-_][a-z0-9]+)*$/;\n\n/**\n * The app's job route: checks the request is signed for (or carries the\n * secret of) the job named by the route (`name`, e.g. a path param), the\n * body's `job`, or the URL's last segment, then runs it. GET and POST (platform crons send GET). Answers 401, 404 for an\n * unknown job, 405, 200 with the job's result, or 500 with no detail.\n *\n * @stability Beta\n */\nexport function createJobsHandler(options: JobsHandlerOptions): (request: Request, name?: string) => Promise<Response> {\n const log = options.log ?? ((line: string) => console.error(line));\n return async (request, name) => {\n if (request.method !== \"GET\" && request.method !== \"POST\") {\n return Response.json({ error: \"Use GET or POST.\" }, { status: 405, headers: { Allow: \"GET, POST\" } });\n }\n // A signed call (a schedule) is signed for the job name only, so nothing else it carries is\n // trusted: its body is ignored, and its response carries no result (pg_net keeps responses\n // in net._http_response, which other roles may read).\n const signed = /^genesisjob\\s/i.test((request.headers.get(\"authorization\") ?? \"\").trim());\n const raw = request.method === \"POST\" && !signed ? await request.clone().json().catch(() => null) : null;\n const body = raw && typeof raw === \"object\" && !Array.isArray(raw) ? (raw as Record<string, unknown>) : {};\n const job = name ?? (typeof body[\"job\"] === \"string\" ? body[\"job\"] : new URL(request.url).pathname.split(\"/\").filter(Boolean).at(-1));\n\n // The signature is for one job name, so check it against the name the route will run.\n const refused = await verifyJobRequest(request, options, job);\n if (refused) return refused;\n\n const run = job && JOB_NAME.test(job) && Object.hasOwn(options.jobs, job) ? options.jobs[job] : undefined;\n if (!run) return Response.json({ error: \"No such job.\" }, { status: 404 });\n\n try {\n const result = (await run({ request, body })) ?? null;\n return Response.json(signed ? { job, ok: true } : { job, result });\n } catch (error) {\n log(`[jobs] ${job}: ${messageOf(error)}`);\n return Response.json({ job, error: \"The job failed; see the server log.\" }, { status: 500 });\n }\n };\n}\n"]}
1
+ {"version":3,"sources":["../src/jobs.ts"],"names":[],"mappings":";;;AAwCO,IAAM,SAAA,GAAN,cAAwB,KAAA,CAAM;AAAA,EAC1B,IAAA;AAAA,EACT,WAAA,CAAY,SAAiB,IAAA,EAAe;AAC1C,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,WAAA;AACZ,IAAA,IAAA,CAAK,IAAA,GAAO,IAAA;AAAA,EACd;AACF;AAEA,eAAe,IAAA,CAAQ,MAAA,EAAoB,EAAA,EAAY,IAAA,EAA2C;AAChG,EAAA,MAAM,EAAE,MAAM,KAAA,EAAM,GAAI,MAAM,MAAA,CAAO,GAAA,CAAI,IAAI,IAAI,CAAA;AACjD,EAAA,IAAI,KAAA,EAAO,MAAM,IAAI,SAAA,CAAU,CAAA,EAAG,EAAE,CAAA,EAAA,EAAK,KAAA,CAAM,OAAO,CAAA,CAAA,EAAI,KAAA,CAAM,IAAI,CAAA;AACpE,EAAA,OAAO,IAAA;AACT;AAmBO,SAAS,UAAA,CAAW,QAAoB,IAAA,EAAc,OAAA,GAAmC,EAAC,EAAG,OAAA,GAA0B,EAAC,EAAoB;AACjJ,EAAA,OAAO,IAAA,CAAa,QAAQ,qBAAA,EAAuB;AAAA,IACjD,MAAA,EAAQ,IAAA;AAAA,IACR,SAAA,EAAW,OAAA;AAAA,IACX,WAAA,EAAa,OAAA,CAAQ,QAAA,EAAU,WAAA,EAAY,IAAK,IAAA;AAAA,IAChD,iBAAA,EAAmB,QAAQ,cAAA,IAAkB,IAAA;AAAA,IAC7C,cAAA,EAAgB,QAAQ,WAAA,IAAe;AAAA,GACxC,CAAA;AACH;AA2BO,IAAM,iBAAA,GAAN,cAAgC,KAAA,C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,OAAA,EAAS,IAAA,EAAM,CAAA,IAAM,IAAA;AACjD,MAAA,OAAO,QAAA,CAAS,IAAA,CAAK,MAAA,GAAS,EAAE,GAAA,EAAK,EAAA,EAAI,IAAA,EAAK,GAAI,EAAE,GAAA,EAAK,MAAA,EAAQ,CAAA;AAAA,IACnE,SAAS,KAAA,EAAO;AACd,MAAA,GAAA,CAAI,UAAU,GAAG,CAAA,EAAA,EAAK,SAAA,CAAU,KAAK,CAAC,CAAA,CAAE,CAAA;AACxC,MAAA,OAAO,QAAA,CAAS,IAAA,CAAK,EAAE,GAAA,EAAK,KAAA,EAAO,uCAAsC,EAAG,EAAE,MAAA,EAAQ,GAAA,EAAK,CAAA;AAAA,IAC7F;AAAA,EACF,CAAA;AACF","file":"jobs.js","sourcesContent":["/**\n * `@marktiderman/genesis-supabase/jobs`: the server half of\n * `migrations/0007_genesis_jobs.sql`. Server only (it takes the service-role\n * client and the job secret); never import it into browser or app code.\n *\n * - `enqueueJob`: queue work from server code (triggers enqueue in SQL).\n * - `runJobs`: claim due jobs, run each kind's handler, settle each one, with\n * backoff on failure. Never throws for one job's failure.\n * - `createJobsHandler`: the app's one job route. It checks the request is\n * signed for the job (`genesis_schedule_job` signs; the secret never\n * travels) or carries the bearer secret (a platform cron, a person), with a\n * previous secret accepted while you rotate it, and runs the named job.\n *\n * ```ts\n * // src/routes/api/jobs/$job.ts (any server route that hands over a Request)\n * const handle = createJobsHandler({\n * secret: process.env.GENESIS_JOBS_SECRET,\n * previousSecret: process.env.GENESIS_JOBS_SECRET_PREVIOUS,\n * jobs: {\n * queue: () => runJobs(admin, { handlers: { \"email.digest\": sendDigest } }),\n * cleanup: () => removeQueuedFiles(admin),\n * },\n * });\n * export const POST = ({ request, params }) => handle(request, params.job);\n * ```\n *\n * @packageDocumentation\n */\n\nimport { createRunner, type JobResult as EngineResult } from \"./runner\";\n\n/** The parts of a Supabase client these helpers use: a service-role `SupabaseClient` fits. */\nexport interface JobsClient {\n // Loose on purpose: a client typed by an app's Database narrows `rpc`'s\n // function names, and the app's generated types may not list these yet.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n rpc: (fn: any, ...rest: any[]) => PromiseLike<{ data: unknown; error: { message: string; code?: string } | null }>;\n}\n\n/** A failure from the queue's own functions (not from a handler). */\nexport class JobsError extends Error {\n readonly code: string | undefined;\n constructor(message: string, code?: string) {\n super(message);\n this.name = \"JobsError\";\n this.code = code;\n }\n}\n\nasync function call<T>(client: JobsClient, fn: string, args: Record<string, unknown>): Promise<T> {\n const { data, error } = await client.rpc(fn, args);\n if (error) throw new JobsError(`${fn}: ${error.message}`, error.code);\n return data as T;\n}\n\n/** @stability Beta */\nexport interface EnqueueOptions {\n /** Run no earlier than this. Default now. */\n runAfter?: Date;\n /** One job per kind and key while it is queued or running: a repeat returns the queued job's id. */\n idempotencyKey?: string;\n /** Attempts before it fails for good, 1 to 100. Default 8. */\n maxAttempts?: number;\n}\n\n/**\n * Queue one job of `kind` (`\"email.digest\"`, lowercase) with a JSON object\n * payload. Returns the job's id. Payloads are readable by the service role:\n * put ids in them, never secrets.\n *\n * @stability Beta\n */\nexport function enqueueJob(client: JobsClient, kind: string, payload: Record<string, unknown> = {}, options: EnqueueOptions = {}): Promise<string> {\n return call<string>(client, \"genesis_job_enqueue\", {\n p_kind: kind,\n p_payload: payload,\n p_run_after: options.runAfter?.toISOString() ?? null,\n p_idempotency_key: options.idempotencyKey ?? null,\n p_max_attempts: options.maxAttempts ?? 8,\n });\n}\n\n/** One claimed job, as a handler sees it. @stability Beta */\nexport interface Job<Payload = Record<string, unknown>> {\n id: string;\n kind: string;\n payload: Payload;\n /** This attempt's number, from 1. */\n attempt: number;\n /** An earlier attempt's lease ran out: it may have done the work. Handlers that can look first, do. */\n redelivery: boolean;\n}\n\n/**\n * What a handler can return. Nothing (or `{ done: true }`) is done. Throwing\n * retries with backoff; throw a `PermanentJobError` (or return\n * `{ failed }`) to stop.\n *\n * @stability Beta\n */\nexport type JobOutcome =\n | void\n | { done: true }\n | { retryAfterSeconds: number; error?: string }\n | { failed: string };\n\n/** Thrown by a handler for a failure that won't get better with a retry (a bad payload, a 4xx). @stability Beta */\nexport class PermanentJobError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"PermanentJobError\";\n }\n}\n\n// Handlers are keyed by kind, so each takes its own payload type.\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type JobHandler = (job: Job<any>) => Promise<JobOutcome> | JobOutcome;\n\n/** @stability Beta */\nexport interface RunJobsOptions {\n /** Kind → handler. Only these kinds are claimed. */\n handlers: Readonly<Record<string, JobHandler>>;\n /** Jobs claimed in this run. Default 25. */\n limit?: number;\n /** How long a claim holds a job; a handler must finish inside it. Default 300. */\n leaseSeconds?: number;\n /** Jobs run at once. Default 4. */\n concurrency?: number;\n /** Seconds before retry `attempt` (from 1). Default 30 s doubling, jittered, at most an hour. */\n backoff?: (attempt: number) => number;\n /** Where one line per failed job goes (kind, id, attempt, the error's message). Default console.error. */\n log?: (line: string) => void;\n}\n\n/** @stability Beta */\nexport interface RunJobsReport {\n claimed: number;\n done: number;\n retried: number;\n failed: number;\n /** Settles refused because the lease ran out first (another run has the job). */\n stale: number;\n /** Settles that failed (the database unreachable): those jobs come back when their lease runs out. */\n unsettled: number;\n}\n\n/** 30 s, doubling per attempt, ±20% jitter, at most an hour. */\nexport function defaultBackoff(attempt: number): number {\n const base = Math.min(3600, 30 * 2 ** Math.max(0, attempt - 1));\n return Math.round(base * (0.8 + Math.random() * 0.4));\n}\n\nfunction messageOf(error: unknown): string {\n return (error instanceof Error ? `${error.name}: ${error.message}` : String(error)).slice(0, 1000);\n}\n\n/**\n * Claim due jobs of the handled kinds, run them, and settle each: done, a\n * retry after backoff, or failed. One job's failure, or a failure to record\n * it, never stops the others; only a failed claim throws. Nothing about a\n * payload is logged. It runs on the shared engine (`createRunner` from\n * `/runner`): the queue's claim and settle are its store, each kind's handler\n * its sender, and the queue itself decides when a job is out of attempts.\n *\n * @stability Beta\n */\nexport async function runJobs(client: JobsClient, options: RunJobsOptions): Promise<RunJobsReport> {\n const kinds = Object.keys(options.handlers);\n const empty: RunJobsReport = { claimed: 0, done: 0, retried: 0, failed: 0, stale: 0, unsettled: 0 };\n if (kinds.length === 0) return empty;\n const backoff = options.backoff ?? defaultBackoff;\n const log = options.log ?? ((line: string) => console.error(line));\n\n type Claimed = Job & { claim_id: string };\n type Settle = [\"done\" | \"retry\" | \"failed\", number | null, string | null];\n // The settle each job's handler asked for, exactly as the queue takes it. The engine's own\n // outcome only decides which count it lands in; the queue keeps the attempts and backoff.\n const settles = new WeakMap<Claimed, Settle>();\n\n // What the handler says, as a settle. Only the handler runs inside this try.\n const outcomeOf = async (job: Claimed): Promise<Settle> => {\n const handler = options.handlers[job.kind];\n const { claim_id: _claim, ...seen } = job;\n try {\n const outcome = handler ? await handler(seen) : { failed: `no handler for ${job.kind}` };\n if (outcome && \"failed\" in outcome) {\n log(`[jobs] ${job.kind} ${job.id} attempt ${job.attempt} failed: ${outcome.failed}`);\n return [\"failed\", null, outcome.failed.slice(0, 1000)];\n }\n if (outcome && \"retryAfterSeconds\" in outcome) return [\"retry\", Math.max(0, Math.round(outcome.retryAfterSeconds)), outcome.error ?? null];\n return [\"done\", null, null];\n } catch (error) {\n const message = messageOf(error);\n log(`[jobs] ${job.kind} ${job.id} attempt ${job.attempt}: ${message}`);\n return error instanceof PermanentJobError ? [\"failed\", null, message] : [\"retry\", backoff(job.attempt), message];\n }\n };\n\n const resultOf = ([outcome, retryAfter, error]: Settle): EngineResult => {\n if (outcome === \"done\") return { ok: true };\n if (outcome === \"failed\") return { ok: false, retryable: false, error: error ?? \"failed\" };\n // Every retry is a deferral to the engine (with no attempt or deferral cap below), so it\n // never gives up a job or computes a backoff of its own: the queue does both.\n return { ok: false, retryable: true, retryAfterSeconds: retryAfter ?? 0, error: error ?? \"retry\" };\n };\n\n const runner = createRunner<Claimed>({\n claim: async ({ limit }) =>\n (await call<Claimed[] | null>(client, \"genesis_jobs_claim\", {\n p_kinds: kinds,\n p_limit: limit,\n p_lease_seconds: options.leaseSeconds ?? 300,\n })) ?? [],\n send: async ([job]) => {\n const settle = await outcomeOf(job!);\n settles.set(job!, settle);\n return [resultOf(settle)];\n },\n record: async (job) => {\n const [outcome, retryAfter, error] = settles.get(job)!;\n try {\n // Anything but true is a settle the queue refused (the lease ran out): stale.\n const ok = await call<boolean | null>(client, \"genesis_jobs_settle\", {\n p_id: job.id,\n p_claim_id: job.claim_id,\n p_outcome: outcome,\n p_retry_after_seconds: retryAfter,\n p_error: error,\n });\n return Boolean(ok);\n } catch (failure) {\n // The queue didn't take the outcome: the lease runs out and the job comes back as a\n // redelivery. The other jobs in this run carry on.\n log(`[jobs] ${job.kind} ${job.id}: could not record ${outcome}: ${messageOf(failure)}`);\n throw failure;\n }\n },\n concurrency: options.concurrency ?? 4,\n maxAttempts: Number.POSITIVE_INFINITY,\n maxDeferrals: Number.POSITIVE_INFINITY,\n });\n\n const report = await runner.run({ limit: options.limit ?? 25 });\n return {\n claimed: report.claimed,\n done: report.sent,\n retried: report.retrying + report.deferred,\n failed: report.failed,\n stale: report.stale,\n unsettled: report.unrecorded,\n };\n}\n\nconst encoder = new TextEncoder();\n\nasync function digest(value: string): Promise<Uint8Array> {\n return new Uint8Array(await crypto.subtle.digest(\"SHA-256\", encoder.encode(value)));\n}\n\nfunction sameBytes(a: Uint8Array, b: Uint8Array): boolean {\n let diff = a.length ^ b.length;\n for (let i = 0; i < a.length && i < b.length; i++) diff |= a[i]! ^ b[i]!;\n return diff === 0;\n}\n\n/** @stability Beta */\nexport interface VerifyJobRequestOptions {\n /** The job secret. Unset refuses every request (500). */\n secret: string | undefined;\n /** The secret before a rotation, accepted too. Remove it once every caller has the new one. */\n previousSecret?: string | undefined;\n /** How far a signed request's time may be from now, in seconds. Default 300. */\n maxSkewSeconds?: number;\n /** Now, in seconds (for tests). */\n now?: () => number;\n}\n\nconst hex = (bytes: ArrayBuffer) => Array.from(new Uint8Array(bytes), (b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n\nasync function hmacHex(secret: string, message: string): Promise<string> {\n const key = await crypto.subtle.importKey(\"raw\", encoder.encode(secret), { name: \"HMAC\", hash: \"SHA-256\" }, false, [\"sign\"]);\n return hex(await crypto.subtle.sign(\"HMAC\", key, encoder.encode(message)));\n}\n\n/**\n * The `Authorization` value a scheduler sends for `job`: `GenesisJob\n * t=<unix seconds>,sig=<hex HMAC-SHA256 of \"<t>.<job>\">`. What\n * `genesis_schedule_job` sends; for calling a job route from your own code.\n *\n * @stability Beta\n */\nexport async function signJobRequest(secret: string, job: string, now: number = Math.floor(Date.now() / 1000)): Promise<string> {\n return `GenesisJob t=${now},sig=${await hmacHex(secret, `${now}.${job}`)}`;\n}\n\n/**\n * Checks a request's `Authorization` in constant time against the secret and\n * the previous one. Two forms: `GenesisJob t=…,sig=…`, signed for `job` within\n * `maxSkewSeconds` (what schedules send: the secret never travels), or\n * `Bearer <secret>` (a platform cron, a person). The scheme's case and extra\n * spaces don't matter. Returns `null` when it passes, else the response to\n * send: 401, or 500 when no secret is configured.\n *\n * @stability Beta\n */\nexport async function verifyJobRequest(request: Request, options: VerifyJobRequestOptions, job?: string): Promise<Response | null> {\n if (!options.secret) return Response.json({ error: \"The job secret is not configured.\" }, { status: 500 });\n const secrets = [options.secret, ...(options.previousSecret ? [options.previousSecret] : [])];\n const header = (request.headers.get(\"authorization\") ?? \"\").trim();\n const unauthorized = () => Response.json({ error: \"Unauthorized.\" }, { status: 401 });\n\n const bearer = /^bearer\\s+([^\\s,]+)$/i.exec(header)?.[1];\n if (bearer) {\n const given = await digest(bearer);\n let ok = false;\n for (const secret of secrets) ok = sameBytes(given, await digest(secret)) || ok;\n return ok ? null : unauthorized();\n }\n\n const signed = /^genesisjob\\s+t=(\\d{1,12})\\s*,\\s*sig=([0-9a-f]{64})$/i.exec(header);\n if (signed && job) {\n const t = Number(signed[1]);\n const now = options.now?.() ?? Math.floor(Date.now() / 1000);\n if (Math.abs(now - t) > (options.maxSkewSeconds ?? 300)) return unauthorized();\n const given = await digest(signed[2]!.toLowerCase());\n let ok = false;\n for (const secret of secrets) ok = sameBytes(given, await digest(await hmacHex(secret, `${t}.${job}`))) || ok;\n return ok ? null : unauthorized();\n }\n return unauthorized();\n}\n\n/**\n * One named job a route can run. Its return value (JSON) is the response's `result` for a\n * bearer call; a signed call (a schedule) gets `{ job, ok: true }` and its `body` is always `{}`.\n *\n * @stability Beta\n */\nexport type NamedJob = (context: { request: Request; body: Record<string, unknown> }) => Promise<unknown> | unknown;\n\n/** @stability Beta */\nexport interface JobsHandlerOptions extends VerifyJobRequestOptions {\n /** Job name (`\"digests\"`, as `genesis_schedule_job` names it) → what it runs. */\n jobs: Readonly<Record<string, NamedJob>>;\n /** Where a job's failure goes (name and the error's message). Default console.error. */\n log?: (line: string) => void;\n}\n\nconst JOB_NAME = /^[a-z][a-z0-9]*([-_][a-z0-9]+)*$/;\n\n/**\n * The app's job route: checks the request is signed for (or carries the\n * secret of) the job named by the route (`name`, e.g. a path param), the\n * body's `job`, or the URL's last segment, then runs it. GET and POST (platform crons send GET). Answers 401, 404 for an\n * unknown job, 405, 200 with the job's result, or 500 with no detail.\n *\n * @stability Beta\n */\nexport function createJobsHandler(options: JobsHandlerOptions): (request: Request, name?: string) => Promise<Response> {\n const log = options.log ?? ((line: string) => console.error(line));\n return async (request, name) => {\n if (request.method !== \"GET\" && request.method !== \"POST\") {\n return Response.json({ error: \"Use GET or POST.\" }, { status: 405, headers: { Allow: \"GET, POST\" } });\n }\n // A signed call (a schedule) is signed for the job name only, so nothing else it carries is\n // trusted: its body is ignored, and its response carries no result (pg_net keeps responses\n // in net._http_response, which other roles may read).\n const signed = /^genesisjob\\s/i.test((request.headers.get(\"authorization\") ?? \"\").trim());\n const raw = request.method === \"POST\" && !signed ? await request.clone().json().catch(() => null) : null;\n const body = raw && typeof raw === \"object\" && !Array.isArray(raw) ? (raw as Record<string, unknown>) : {};\n const job = name ?? (typeof body[\"job\"] === \"string\" ? body[\"job\"] : new URL(request.url).pathname.split(\"/\").filter(Boolean).at(-1));\n\n // The signature is for one job name, so check it against the name the route will run.\n const refused = await verifyJobRequest(request, options, job);\n if (refused) return refused;\n\n const run = job && JOB_NAME.test(job) && Object.hasOwn(options.jobs, job) ? options.jobs[job] : undefined;\n if (!run) return Response.json({ error: \"No such job.\" }, { status: 404 });\n\n try {\n const result = (await run({ request, body })) ?? null;\n return Response.json(signed ? { job, ok: true } : { job, result });\n } catch (error) {\n log(`[jobs] ${job}: ${messageOf(error)}`);\n return Response.json({ job, error: \"The job failed; see the server log.\" }, { status: 500 });\n }\n };\n}\n"]}
package/dist/native.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { S as SessionStorage } from './index-Ds0tO9WP.js';
2
- export { E as ExpoCryptoLike, W as WebCryptoSource, a as assertPkceCrypto, h as hasPkceCrypto, i as installWebCrypto, b as isDigestOnlyPolyfill } from './index-Ds0tO9WP.js';
1
+ import { S as SessionStorage } from './index-D73YuwEY.js';
2
+ export { E as ExpoCryptoLike, W as WebCryptoSource, a as assertPkceCrypto, h as hasPkceCrypto, i as installWebCrypto, b as isDigestOnlyPolyfill } from './index-D73YuwEY.js';
3
3
  import { Session, SupabaseClient, User } from '@supabase/supabase-js';
4
4
  import './blocks.js';
5
5
  import '@marktiderman/genesis-features/blocks';
@@ -0,0 +1,179 @@
1
+ /**
2
+ * `@marktiderman/genesis-supabase/runner`: the one outbox engine. Claim a
3
+ * batch of due jobs, send them (grouped, so a destination that takes many at
4
+ * once gets one request), and record what happened. No dependencies: no
5
+ * `@supabase/supabase-js` and no Node built-ins, so a package can bundle it.
6
+ *
7
+ * The store is the caller's (a SQL outbox claimed with SKIP LOCKED, a
8
+ * queue): `claim` hands over leased jobs and `record` takes back outcomes.
9
+ * The engine owns the rest: turning each send result into an outcome with a
10
+ * retry time, jittered backoff, the deferral cap, and never throwing for one
11
+ * job's failure. It runs the background-job queue (`runJobs` in `/jobs`),
12
+ * genesis-notifications' push and email channels, and genesis-forms'
13
+ * destinations (Sheets, webhooks), each with its own claim. It knows nothing
14
+ * about recipients: preferences, windows and caps are the notifier's.
15
+ *
16
+ * Outcomes:
17
+ * - `sent`: delivered (or already there, on a redelivery: `alreadyThere`).
18
+ * - `filtered`: the sender decided it doesn't apply; nothing sent, nothing to retry.
19
+ * - `skipped`: deliberately not sent (`notSent`: a reason safe to store); never retried.
20
+ * - `retry`: a retryable failure. With the service's own Retry-After it is
21
+ * deferred without counting an attempt (`counted: false`), until
22
+ * `maxDeferrals`; otherwise it backs off by attempt (`counted: true`), until
23
+ * `maxAttempts`.
24
+ * - `failed`: permanent, or out of attempts. With `disable: true` the receiver
25
+ * asked to be switched off (a 410 Gone): stop sending to it.
26
+ *
27
+ * It never logs content, addresses or secrets: only what `label` gives and
28
+ * the senders' safe error messages.
29
+ *
30
+ * @packageDocumentation
31
+ */
32
+ /** One claimed job. Extend it with what your sender needs. */
33
+ interface RunnerJob {
34
+ /** Stable across retries (an idempotency key is made from it). */
35
+ id: string;
36
+ /** This attempt's number, from 1. */
37
+ attempt: number;
38
+ /** Deferrals so far (outcomes with `counted: false`); pass it back so `maxDeferrals` holds. Default 0. */
39
+ deferrals?: number | undefined;
40
+ /** An earlier attempt may have gone through (its lease ran out): senders that can look first do. */
41
+ redelivery?: boolean | undefined;
42
+ }
43
+ /** What a sender says about one job. */
44
+ type JobResult = {
45
+ ok: true;
46
+ /** Deliberately sent nothing; the reason, safe to store. Recorded as `skipped`. */
47
+ notSent?: string | undefined;
48
+ /** It was already there (a redelivery), so nothing was sent this time. */
49
+ alreadyThere?: boolean | undefined;
50
+ } | JobFailure;
51
+ interface JobFailure {
52
+ ok: false;
53
+ /** The same request may succeed later (rate limited, the service down, a timeout). */
54
+ retryable: boolean;
55
+ /** The service said when to come back: retry after this many seconds, without counting an attempt. */
56
+ retryAfterSeconds?: number | undefined;
57
+ status?: number | undefined;
58
+ /** The receiver asked to be switched off. Always with `retryable: false`. */
59
+ disable?: true | undefined;
60
+ /** Safe to store and log: never secrets, content or addresses. */
61
+ error: string;
62
+ }
63
+ type JobOutcome = {
64
+ status: "sent";
65
+ alreadyThere?: boolean;
66
+ } | {
67
+ status: "filtered";
68
+ } | {
69
+ status: "skipped";
70
+ reason: string;
71
+ } | {
72
+ status: "retry";
73
+ error: string;
74
+ retryAt: Date;
75
+ retryAfterSeconds: number;
76
+ /** Whether this attempt counts toward `maxAttempts`. False when the service said when to come back. */
77
+ counted: boolean;
78
+ httpStatus?: number;
79
+ } | {
80
+ status: "failed";
81
+ error: string;
82
+ httpStatus?: number;
83
+ disable?: true;
84
+ };
85
+ interface RunReport {
86
+ claimed: number;
87
+ sent: number;
88
+ filtered: number;
89
+ skipped: number;
90
+ /** Retryable failures, backed off by attempt. */
91
+ retrying: number;
92
+ /** Retryable failures the service said when to retry; no attempt used. */
93
+ deferred: number;
94
+ failed: number;
95
+ /** Recorded after the claim was lost (`record` resolved false). */
96
+ stale: number;
97
+ /** `record` threw. */
98
+ unrecorded: number;
99
+ }
100
+ interface ClaimRequest<Filter> {
101
+ limit: number;
102
+ filter?: Filter | undefined;
103
+ }
104
+ interface SendContext {
105
+ signal?: AbortSignal | undefined;
106
+ }
107
+ interface RunnerOptions<J extends RunnerJob, Filter = undefined> {
108
+ /** Claims up to `limit` due jobs, each leased so no other runner sends it meanwhile. */
109
+ claim(request: ClaimRequest<Filter>): Promise<readonly J[]>;
110
+ /**
111
+ * Sends one group of jobs (those with the same `group` key) and resolves one
112
+ * result per job, in order, or `"filtered"`. A throw fails the whole group
113
+ * with a retryable error.
114
+ */
115
+ send(group: readonly J[], context: SendContext): Promise<readonly (JobResult | "filtered")[]>;
116
+ /** Jobs with the same key are sent together. Default: each job alone. */
117
+ group?: ((job: J) => string) | undefined;
118
+ /**
119
+ * Records an outcome. Resolve `false` when the claim was no longer held: it
120
+ * is counted as stale. A rejection is counted as unrecorded; the lease runs
121
+ * out and the job comes back on its own.
122
+ */
123
+ record(job: J, outcome: JobOutcome): Promise<void | boolean>;
124
+ now?: (() => number) | undefined;
125
+ /** Safe lines (ids, kinds, short reasons). Default: nothing is logged. */
126
+ log?: ((message: string) => void) | undefined;
127
+ /** How a job is named in a log line, capitalised ("Delivery d1 (email)"). Default `Job <id>`. */
128
+ label?: ((job: J) => string) | undefined;
129
+ /** How a job is named when recording it failed ("delivery d1"). Default `job <id>`. */
130
+ recordLabel?: ((job: J) => string) | undefined;
131
+ /** Jobs claimed per run. Default 25. */
132
+ batchSize?: number | undefined;
133
+ /** Groups sent (and their outcomes recorded) at once. Default: every group at once. */
134
+ concurrency?: number | undefined;
135
+ /** Counted attempts before a retryable failure is given up. Default 8. */
136
+ maxAttempts?: number | undefined;
137
+ /** Deferrals allowed before a further one counts as an attempt. Default 24. */
138
+ maxDeferrals?: number | undefined;
139
+ /** Seconds to wait after a counted failed attempt. Default `defaultBackoff`. */
140
+ backoff?: ((attempt: number) => number) | undefined;
141
+ }
142
+ interface RunOptions<Filter> {
143
+ filter?: Filter | undefined;
144
+ /** Overrides `batchSize` for this run. */
145
+ limit?: number | undefined;
146
+ /** Aborts the sends in flight. */
147
+ signal?: AbortSignal | undefined;
148
+ }
149
+ interface Runner<Filter = undefined> {
150
+ /** One claim, its sends and their records. Never rejects for a job's failure; a failing `claim` rejects. */
151
+ run(options?: RunOptions<Filter>): Promise<RunReport>;
152
+ }
153
+ declare const DEFAULT_MAX_ATTEMPTS = 8;
154
+ declare const DEFAULT_MAX_DEFERRALS = 24;
155
+ declare const DEFAULT_BATCH_SIZE = 25;
156
+ /**
157
+ * 5 minutes, quadrupling each attempt, at most 24 hours: 5m, 20m, 80m, 5h20m,
158
+ * 21h20m, then 24h; about 3 days across 8 attempts. Each wait is jittered by
159
+ * up to ±20%, so jobs that failed together don't all come back at once.
160
+ */
161
+ declare function defaultBackoff(attempt: number, random?: () => number): number;
162
+ /** Turns a send result into an outcome for a job on its `attempt`. */
163
+ declare function jobOutcome(result: JobResult, attempt: number, options?: {
164
+ now?: number | undefined;
165
+ maxAttempts?: number | undefined;
166
+ backoff?: ((attempt: number) => number) | undefined;
167
+ deferrals?: number | undefined;
168
+ maxDeferrals?: number | undefined;
169
+ }): JobOutcome;
170
+ /** A thrown error as a retryable failure with a safe message. */
171
+ declare function failureOf(error: unknown): JobFailure;
172
+ /**
173
+ * The runner.
174
+ *
175
+ * @stability Beta
176
+ */
177
+ declare function createRunner<J extends RunnerJob, Filter = undefined>(options: RunnerOptions<J, Filter>): Runner<Filter>;
178
+
179
+ export { type ClaimRequest, DEFAULT_BATCH_SIZE, DEFAULT_MAX_ATTEMPTS, DEFAULT_MAX_DEFERRALS, type JobFailure, type JobOutcome, type JobResult, type RunOptions, type RunReport, type Runner, type RunnerJob, type RunnerOptions, type SendContext, createRunner, defaultBackoff, failureOf, jobOutcome };
package/dist/runner.js ADDED
@@ -0,0 +1,3 @@
1
+ export { DEFAULT_BATCH_SIZE, DEFAULT_MAX_ATTEMPTS, DEFAULT_MAX_DEFERRALS, createRunner, defaultBackoff, failureOf, jobOutcome } from './chunk-XGAXPUFY.js';
2
+ //# sourceMappingURL=runner.js.map
3
+ //# sourceMappingURL=runner.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"names":[],"mappings":"","file":"runner.js"}
@@ -0,0 +1,16 @@
1
+ /**
2
+ * The one check for a web handoff's destination, used before a link is minted
3
+ * and again after the person is signed in: the path must stay on the app's
4
+ * own origin. Shared by `/web-handoff` (the page) and `/web-handoff/server`.
5
+ */
6
+ /**
7
+ * `value` as a path on this app (`/clients/1/forms?tab=questions`), normalized, or `null` when it
8
+ * could leave the origin or isn't a path: anything without a single leading `/`, `//host`,
9
+ * `/\host`, a scheme (`javascript:`, `https:`), whitespace or control characters, and the same
10
+ * tricks percent-encoded (`/%2F%2Fhost`, `/%5Chost`, `/%09/host`, up to three layers).
11
+ *
12
+ * @stability Beta
13
+ */
14
+ declare function appRelativePath(value: unknown): string | null;
15
+
16
+ export { appRelativePath as a };