tempest-react-sdk 0.77.0 → 0.78.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.
- package/bin/lib/alias/collect.mjs +20 -3
- package/bin/lib/alias/index.mjs +12 -1
- package/bin/lib/alias/index.test.mjs +24 -0
- package/bin/lib/css/analyze.test.mjs +21 -1
- package/bin/lib/css/collect.mjs +14 -0
- package/bin/lib/css/extract.mjs +63 -5
- package/bin/lib/css/extract.test.mjs +110 -1
- package/bin/lib/css/fix.e2e.test.mjs +50 -0
- package/bin/lib/css/index.mjs +6 -1
- package/bin/lib/fs/contain.mjs +50 -0
- package/bin/lib/icons/generate.mjs +28 -3
- package/bin/lib/icons/generate.test.mjs +57 -1
- package/bin/lib/openapi/escape.mjs +20 -6
- package/bin/lib/openapi/generate.encode.test.mjs +120 -0
- package/bin/lib/openapi/generate.hostile.test.mjs +38 -9
- package/bin/lib/openapi/generate.mjs +41 -6
- package/bin/lib/openapi/generate.test.mjs +7 -2
- package/bin/lib/openapi/schema-to-zod.mjs +5 -3
- package/bin/tempest-gen.test.mjs +188 -0
- package/bin/tempest.mjs +120 -44
- package/dist/auth/create-tempest-auth.cjs +1 -1
- package/dist/auth/create-tempest-auth.cjs.map +1 -1
- package/dist/auth/create-tempest-auth.js +186 -113
- package/dist/auth/create-tempest-auth.js.map +1 -1
- package/dist/br/pix.cjs +1 -1
- package/dist/br/pix.cjs.map +1 -1
- package/dist/br/pix.js +30 -27
- package/dist/br/pix.js.map +1 -1
- package/dist/br.d.ts +11 -4
- package/dist/components/CodeBlock/CodeBlock.cjs +1 -1
- package/dist/components/CodeBlock/CodeBlock.cjs.map +1 -1
- package/dist/components/CodeBlock/CodeBlock.js +1 -1
- package/dist/components/CodeBlock/CodeBlock.js.map +1 -1
- package/dist/components/CodeBlock/tokenize.cjs +1 -1
- package/dist/components/CodeBlock/tokenize.cjs.map +1 -1
- package/dist/components/CodeBlock/tokenize.js +54 -25
- package/dist/components/CodeBlock/tokenize.js.map +1 -1
- package/dist/components/Markdown/markdown-parse.cjs +6 -6
- package/dist/components/Markdown/markdown-parse.cjs.map +1 -1
- package/dist/components/Markdown/markdown-parse.js +91 -74
- package/dist/components/Markdown/markdown-parse.js.map +1 -1
- package/dist/http/resumable-upload.cjs +1 -1
- package/dist/http/resumable-upload.cjs.map +1 -1
- package/dist/http/resumable-upload.js +141 -105
- package/dist/http/resumable-upload.js.map +1 -1
- package/dist/http/retry.cjs +1 -1
- package/dist/http/retry.cjs.map +1 -1
- package/dist/http/retry.js +5 -6
- package/dist/http/retry.js.map +1 -1
- package/dist/sw/background-sync.cjs +1 -1
- package/dist/sw/background-sync.cjs.map +1 -1
- package/dist/sw/background-sync.js +32 -31
- package/dist/sw/background-sync.js.map +1 -1
- package/dist/sw/credential-headers.cjs.map +1 -1
- package/dist/sw/credential-headers.js.map +1 -1
- package/dist/sw.d.ts +46 -8
- package/dist/telemetry/app-error-reporter.cjs +1 -1
- package/dist/telemetry/app-error-reporter.cjs.map +1 -1
- package/dist/telemetry/app-error-reporter.js +1 -1
- package/dist/telemetry/app-error-reporter.js.map +1 -1
- package/dist/tempest-react-sdk.cjs +1 -1
- package/dist/tempest-react-sdk.d.ts +214 -12
- package/dist/tempest-react-sdk.js +119 -119
- package/dist/utils/csv.cjs +3 -3
- package/dist/utils/csv.cjs.map +1 -1
- package/dist/utils/csv.js +11 -10
- package/dist/utils/csv.js.map +1 -1
- package/dist/{telemetry/app-error-owner.cjs → utils/owner-fingerprint.cjs} +2 -2
- package/dist/utils/owner-fingerprint.cjs.map +1 -0
- package/dist/{telemetry/app-error-owner.js → utils/owner-fingerprint.js} +3 -3
- package/dist/utils/owner-fingerprint.js.map +1 -0
- package/dist/vite/tempest-csp.cjs +2 -2
- package/dist/vite/tempest-csp.cjs.map +1 -1
- package/dist/vite/tempest-csp.js +69 -58
- package/dist/vite/tempest-csp.js.map +1 -1
- package/dist/vite.d.ts +5 -3
- package/package.json +1 -1
- package/dist/telemetry/app-error-owner.cjs.map +0 -1
- package/dist/telemetry/app-error-owner.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"background-sync.js","names":[],"sources":["../../src/sw/background-sync.ts"],"sourcesContent":["/**\n * Background-sync helper: queue failed mutating requests (POST/PUT/PATCH/DELETE)\n * while offline and replay them when connectivity returns. A dependency-free\n * take on Workbox's `BackgroundSyncPlugin`, backed by a tiny IndexedDB queue.\n *\n * Import inside your `sw.ts`. Uses the Background Sync API (`registration.sync`)\n * when available, and also replays opportunistically on the next request as a\n * fallback for browsers without it (e.g. Safari).\n *\n * Credential headers (`Authorization` and the rest of\n * {@link DEFAULT_CREDENTIAL_HEADERS}) are never written to IndexedDB: the queue\n * outlives the session, and a stored bearer stayed readable after logout and was\n * replayed with the old identity (reproduced in Chromium 153, 11/10/2026). On\n * replay the worker asks the open pages for the *current* credentials — see\n * {@link provideBackgroundSyncCredentials} — or a custom `beforeReplay` hook.\n * Credentials carried in the URL or the body are out of reach and are stored\n * as sent.\n *\n * @example\n * import { installBackgroundSync } from \"tempest-react-sdk/sw\";\n *\n * installBackgroundSync({ match: (url) => url.pathname.startsWith(\"/api/\") });\n */\nimport { isDevBuild } from \"../utils/dev-mode\";\nimport { DEFAULT_CREDENTIAL_HEADERS, credentialHeaderSet } from \"./credential-headers\";\n\ninterface SyncEventLike {\n tag: string;\n waitUntil(promise: Promise<unknown>): void;\n}\n\ninterface BgFetchEventLike {\n request: Request;\n /** Id of the window client that issued the request, when there is one. */\n clientId?: string;\n respondWith(response: Response | Promise<Response>): void;\n waitUntil(promise: Promise<unknown>): void;\n}\n\ninterface PeriodicSyncEventLike {\n tag: string;\n waitUntil(promise: Promise<unknown>): void;\n}\n\n/** Minimal shape of a window client the worker can message. */\ninterface WindowClientLike {\n postMessage(message: unknown, transfer: Transferable[]): void;\n}\n\ninterface BgSwGlobal {\n registration: { sync?: { register(tag: string): Promise<void> } };\n clients?: {\n matchAll(options: { type: \"window\" }): Promise<readonly WindowClientLike[]>;\n get(id: string): Promise<WindowClientLike | undefined>;\n };\n addEventListener(type: \"sync\", listener: (event: SyncEventLike) => void): void;\n addEventListener(type: \"fetch\", listener: (event: BgFetchEventLike) => void): void;\n addEventListener(type: \"periodicsync\", listener: (event: PeriodicSyncEventLike) => void): void;\n}\n\nfunction getSwScope(): BgSwGlobal {\n return globalThis as unknown as BgSwGlobal;\n}\n\n/**\n * How an entry is tied to whoever queued it:\n * - `\"bound\"`: the issuing page reported a principal (or `null` for nobody);\n * the entry only goes out while the same one is signed in.\n * - `\"unbound\"`: the issuing page answered without `getPrincipal`.\n * - `\"unknown\"`: nobody could say — no issuing tab, no answer, an error, or an\n * entry written before owners existed. Fails closed.\n *\n * While the worker is still asking, the stored state is `\"pending\"`, which a\n * replay never sees: it waits, then reads a stamp that never came as `\"unknown\"`.\n */\nexport type BackgroundSyncOwnerState = \"bound\" | \"unbound\" | \"unknown\";\n\n/** A serialized request stored in the queue. */\ninterface QueuedRequest {\n id?: number;\n url: string;\n method: string;\n headers: [string, string][];\n body: ArrayBuffer | null;\n timestamp: number;\n /** The original `credentials` mode, so cookie-based APIs replay with cookies. */\n credentials?: RequestCredentials;\n /** Lower-cased names of the credential headers removed before persisting. */\n strippedHeaders?: string[];\n /** Absent on entries written before 0.77 — read as `\"unknown\"`. */\n ownerState?: BackgroundSyncOwnerState | \"pending\";\n /** Fingerprint of the principal under `\"bound\"`; `null` for \"nobody signed in\". */\n owner?: string | null;\n}\n\n/** Default IndexedDB database name (and sync tag) of the background-sync queue. */\nconst DEFAULT_QUEUE_NAME = \"tempest-bg-sync\";\n\n/**\n * Schema version of the queue database. Version 2 adds the `meta` store (the\n * clear epoch) and migrates version-1 entries, scrubbing their plaintext\n * credential headers on first open.\n */\nconst DB_VERSION = 2;\nconst STORE = \"requests\";\nconst META = \"meta\";\nconst EPOCH_KEY = \"epoch\";\n\n/**\n * `type` of the message the worker posts to window clients to ask about a queued\n * request. Answered by {@link provideBackgroundSyncCredentials}.\n */\nexport const BACKGROUND_SYNC_CREDENTIALS_MESSAGE = \"tempest:bg-sync-credentials\";\n\n/** How long the worker waits for the window clients to answer, in milliseconds. */\nconst CREDENTIALS_TIMEOUT_MS = 3000;\n\n/**\n * How long a replay waits on an entry whose owner is still being stamped. Past\n * it (the worker died mid-question), the owner is read as `\"unknown\"`.\n */\nconst OWNER_STAMP_GRACE_MS = CREDENTIALS_TIMEOUT_MS * 2;\n\n/** What a queued request looked like when it was stored, passed to `beforeReplay`. */\nexport interface BackgroundSyncReplayContext {\n /** Epoch milliseconds of the original failed attempt. */\n queuedAt: number;\n /** Lower-cased credential header names stripped before the entry was stored. */\n strippedHeaders: readonly string[];\n /** How the entry is tied to its owner. */\n ownerState: BackgroundSyncOwnerState;\n /** Owner fingerprint under `\"bound\"` (`null` for nobody); `undefined` otherwise. */\n owner: string | null | undefined;\n}\n\n/** The request a window client is asked about, as sent by the worker. */\nexport interface BackgroundSyncCredentialsRequest {\n /** Absolute URL of the queued request. */\n url: string;\n /** HTTP method of the queued request. */\n method: string;\n /**\n * `\"enqueue\"` when the worker only wants the owner of a request that just\n * failed; `\"replay\"` when it is about to send it and needs the credentials.\n */\n phase: \"enqueue\" | \"replay\";\n}\n\n/**\n * Resolve the credentials for a queued request: a header record to apply, or\n * `null` when there is no session (the entry is then dropped).\n */\nexport type BackgroundSyncCredentialsProvider = (\n request: BackgroundSyncCredentialsRequest,\n) => Record<string, string> | null | Promise<Record<string, string> | null>;\n\n/** Options for {@link provideBackgroundSyncCredentials}. */\nexport interface ProvideBackgroundSyncCredentialsOptions {\n /**\n * Who is signed in right now — a stable, non-secret id such as the user id;\n * `null`/`undefined` when nobody is. Read when a request is queued and again\n * when it is replayed: an entry is only sent while the same principal is\n * signed in, and dropped otherwise, so a mutation queued by one account is\n * never sent with another account's credentials even when the app forgets\n * `clearSessionData()` on logout. Only a SHA-256 fingerprint reaches the\n * queue, never the value itself. A throw is answered as an explicit error,\n * which leaves the owner unknown (fail closed).\n */\n getPrincipal?: () => string | null | undefined | Promise<string | null | undefined>;\n}\n\n/** Options for {@link installBackgroundSync}. */\nexport interface InstallBackgroundSyncOptions {\n /**\n * Which requests to queue on failure. A `RegExp` against the URL or a\n * predicate. Only non-`GET` requests are ever considered. Default: all\n * non-`GET` requests.\n */\n match?: RegExp | ((url: URL, request: Request) => boolean);\n /** IndexedDB database name, also used as the sync tag. Default `tempest-bg-sync`. */\n queueName?: string;\n /** Drop queued requests older than this (minutes) on replay. Default `1440` (24h). */\n maxRetentionMinutes?: number;\n /**\n * Also drain the queue on the `periodicsync` event carrying this tag,\n * complementing the one-off `sync` replay so long-pending mutations retry\n * even without a fresh navigation. Register the periodic sync from the main\n * thread with {@link registerPeriodicSync}. Default `${queueName}-periodic`.\n */\n periodicSyncTag?: string;\n /**\n * Header names stripped before a request is persisted — and stripped again on\n * replay, so entries written by an older version never go out with the\n * credential they stored. Default {@link DEFAULT_CREDENTIAL_HEADERS}; extend it\n * for a custom credential header (`[...DEFAULT_CREDENTIAL_HEADERS,\n * \"x-tenant-key\"]`). Passing `[]` restores the pre-0.77 behavior of\n * persisting and replaying every header, credentials included.\n */\n credentialHeaders?: readonly string[];\n /**\n * Prepare each queued request right before it is replayed: return the\n * request to send (typically with the current credentials applied) or\n * `null` to drop the entry for good. A thrown error keeps the entry pending.\n * The context carries the entry's owner, so a custom hook can apply the\n * same rule as the default.\n *\n * Default: an entry with no stripped credentials and no bound owner is\n * replayed as-is. The others ask every open window client in parallel (see\n * {@link provideBackgroundSyncCredentials}) and pick the answer that fits:\n * - `\"bound\"`: the answer whose owner matches; none among valid answers →\n * dropped, never sent anonymously or as somebody else;\n * - `\"unknown\"`: only an answer without a principal (an app that does not use\n * `getPrincipal`); every answer has one → dropped;\n * - `\"unbound\"`: any answer, preferring one without a principal.\n * Then `null` headers drop a credentialed entry, an answer that lacks one of\n * the stripped headers keeps it pending, and only the stripped names are\n * re-applied. No valid answer at all keeps it pending until\n * `maxRetentionMinutes` (and warns once per replay in development builds).\n */\n beforeReplay?: (\n request: Request,\n context: BackgroundSyncReplayContext,\n ) => Request | null | Promise<Request | null>;\n}\n\n/**\n * Move credential headers out of a header list.\n *\n * @returns The remaining headers and the lower-cased names removed.\n */\nfunction splitHeaders(\n headers: Iterable<[string, string]>,\n credentialHeaders: ReadonlySet<string>,\n): { kept: [string, string][]; stripped: string[] } {\n const kept: [string, string][] = [];\n const stripped: string[] = [];\n for (const [name, value] of headers) {\n if (credentialHeaders.has(name.toLowerCase())) stripped.push(name.toLowerCase());\n else kept.push([name, value]);\n }\n return { kept, stripped };\n}\n\n/**\n * Scrub version-1 entries during the upgrade: their credential headers were\n * stored in plaintext, so they are removed from disk on the first open, recorded\n * as stripped, and the owner is marked unknown.\n */\nfunction migrateLegacyEntries(store: IDBObjectStore, credentialHeaders: ReadonlySet<string>): void {\n const cursorRequest = store.openCursor();\n cursorRequest.onsuccess = () => {\n const cursor = cursorRequest.result;\n if (!cursor) return;\n const entry = cursor.value as QueuedRequest;\n const { kept, stripped } = splitHeaders(entry.headers, credentialHeaders);\n cursor.update({\n ...entry,\n headers: kept,\n strippedHeaders: [...new Set([...(entry.strippedHeaders ?? []), ...stripped])],\n ownerState: entry.ownerState ?? \"unknown\",\n });\n cursor.continue();\n };\n}\n\nfunction openQueueDb(\n name: string,\n credentialHeaders: ReadonlySet<string> = credentialHeaderSet(),\n): Promise<IDBDatabase> {\n return new Promise((resolve, reject) => {\n const request = indexedDB.open(name, DB_VERSION);\n request.onupgradeneeded = (event) => {\n const db = request.result;\n if (!db.objectStoreNames.contains(STORE)) {\n db.createObjectStore(STORE, { keyPath: \"id\", autoIncrement: true });\n } else if (event.oldVersion < 2 && request.transaction) {\n migrateLegacyEntries(request.transaction.objectStore(STORE), credentialHeaders);\n }\n if (!db.objectStoreNames.contains(META)) db.createObjectStore(META);\n };\n request.onsuccess = () => {\n const db = request.result;\n db.onversionchange = () => db.close();\n resolve(db);\n };\n request.onerror = () => reject(request.error);\n });\n}\n\nfunction txDone(tx: IDBTransaction): Promise<void> {\n return new Promise((resolve, reject) => {\n tx.oncomplete = () => resolve();\n tx.onerror = () => reject(tx.error);\n tx.onabort = () => reject(tx.error);\n });\n}\n\n/** The current clear epoch: bumped by every {@link clearBackgroundSyncQueue}. */\nasync function readEpoch(name: string, credentialHeaders: ReadonlySet<string>): Promise<number> {\n const db = await openQueueDb(name, credentialHeaders);\n const tx = db.transaction(META, \"readonly\");\n const get = tx.objectStore(META).get(EPOCH_KEY);\n await txDone(tx);\n db.close();\n return (get.result as number | undefined) ?? 0;\n}\n\n/**\n * Add an entry unless the queue was cleared since `epoch` was read — checked in\n * the same transaction as the write, so a logout that lands while the request\n * is still failing never lets it into the next session's queue.\n *\n * @returns The new entry's key, or `undefined` when the clear won.\n */\nasync function enqueue(\n name: string,\n entry: QueuedRequest,\n epoch: number,\n credentialHeaders: ReadonlySet<string>,\n): Promise<number | undefined> {\n const db = await openQueueDb(name, credentialHeaders);\n const tx = db.transaction([STORE, META], \"readwrite\");\n let id: number | undefined;\n const current = tx.objectStore(META).get(EPOCH_KEY);\n current.onsuccess = () => {\n if (((current.result as number | undefined) ?? 0) !== epoch) return;\n const add = tx.objectStore(STORE).add(entry);\n add.onsuccess = () => {\n id = add.result as number;\n };\n };\n await txDone(tx);\n db.close();\n return id;\n}\n\n/**\n * Record how an entry is owned. A no-op when the entry is already gone\n * (replayed, or the queue was cleared).\n */\nasync function stampOwner(\n name: string,\n id: number,\n ownerState: BackgroundSyncOwnerState,\n owner: string | null | undefined,\n): Promise<void> {\n const db = await openQueueDb(name);\n const tx = db.transaction(STORE, \"readwrite\");\n const store = tx.objectStore(STORE);\n const get = store.get(id);\n get.onsuccess = () => {\n const entry = get.result as QueuedRequest | undefined;\n if (!entry) return;\n entry.ownerState = ownerState;\n if (ownerState === \"bound\") entry.owner = owner ?? null;\n store.put(entry);\n };\n await txDone(tx);\n db.close();\n}\n\nasync function readAll(\n name: string,\n credentialHeaders: ReadonlySet<string>,\n): Promise<QueuedRequest[]> {\n const db = await openQueueDb(name, credentialHeaders);\n const tx = db.transaction(STORE, \"readonly\");\n const all = await new Promise<QueuedRequest[]>((resolve, reject) => {\n const req = tx.objectStore(STORE).getAll();\n req.onsuccess = () => resolve(req.result as QueuedRequest[]);\n req.onerror = () => reject(req.error);\n });\n db.close();\n return all;\n}\n\n/** Whether an entry is still in the queue — `false` once it was cleared. */\nasync function stillQueued(name: string, id: number): Promise<boolean> {\n const db = await openQueueDb(name);\n const tx = db.transaction(STORE, \"readonly\");\n const count = tx.objectStore(STORE).count(id);\n await txDone(tx);\n db.close();\n return count.result > 0;\n}\n\nasync function remove(name: string, id: number): Promise<void> {\n const db = await openQueueDb(name);\n const tx = db.transaction(STORE, \"readwrite\");\n tx.objectStore(STORE).delete(id);\n await txDone(tx);\n db.close();\n}\n\n/**\n * Serialize a request for the queue, leaving out every credential header and\n * recording which ones were present.\n */\nasync function serializeRequest(\n request: Request,\n timestamp: number,\n credentialHeaders: ReadonlySet<string>,\n ownerState: QueuedRequest[\"ownerState\"],\n): Promise<QueuedRequest> {\n const buffer = await request.clone().arrayBuffer();\n const { kept, stripped } = splitHeaders(request.headers.entries(), credentialHeaders);\n return {\n url: request.url,\n method: request.method,\n headers: kept,\n body: buffer.byteLength > 0 ? buffer : null,\n timestamp,\n credentials: request.credentials,\n strippedHeaders: stripped,\n ownerState,\n };\n}\n\n/**\n * Rebuild a stored request, stripping credential headers once more so an entry\n * that still holds one (a custom `credentialHeaders` the migration did not know)\n * never replays it.\n */\nfunction deserializeRequest(\n entry: QueuedRequest,\n credentialHeaders: ReadonlySet<string>,\n): { request: Request; strippedHeaders: string[] } {\n const { kept, stripped } = splitHeaders(entry.headers, credentialHeaders);\n return {\n request: new Request(entry.url, {\n method: entry.method,\n headers: kept,\n body: entry.body ?? undefined,\n credentials: entry.credentials,\n }),\n strippedHeaders: [...new Set([...(entry.strippedHeaders ?? []), ...stripped])],\n };\n}\n\n/** A window client's parsed answer. */\ninterface ClientAnswer {\n headers: Record<string, string> | null;\n /** Whether the page has `getPrincipal`. */\n hasPrincipal: boolean;\n owner: string | null;\n}\n\n/**\n * Ask one window client about a queued request over a `MessageChannel`.\n *\n * @returns The parsed answer, or `undefined` when the client stayed silent until\n * `deadline`, answered `{ error: true }`, or answered something unrecognizable.\n */\nasync function askClient(\n client: WindowClientLike,\n request: BackgroundSyncCredentialsRequest,\n deadline: Promise<void>,\n): Promise<ClientAnswer | undefined> {\n const channel = new MessageChannel();\n const answer = await Promise.race([\n new Promise<unknown>((resolve) => {\n channel.port1.onmessage = (event: MessageEvent) => resolve(event.data);\n client.postMessage({ type: BACKGROUND_SYNC_CREDENTIALS_MESSAGE, ...request }, [\n channel.port2,\n ]);\n }),\n deadline.then(() => undefined),\n ]);\n channel.port1.close();\n if (answer === null || typeof answer !== \"object\" || !(\"headers\" in answer)) return undefined;\n const { headers, owner } = answer as { headers: unknown; owner?: unknown };\n const hasPrincipal = \"owner\" in answer;\n if (hasPrincipal && typeof owner !== \"string\" && owner !== null) return undefined;\n return {\n headers:\n headers !== null && typeof headers === \"object\"\n ? (headers as Record<string, string>)\n : null,\n hasPrincipal,\n owner: hasPrincipal ? (owner as string | null) : null,\n };\n}\n\n/** A deadline shared by every client asked in one round. */\nfunction startDeadline(): { promise: Promise<void>; cancel: () => void } {\n let timer: ReturnType<typeof setTimeout> | undefined;\n const promise = new Promise<void>((resolve) => {\n timer = setTimeout(resolve, CREDENTIALS_TIMEOUT_MS);\n });\n return { promise, cancel: () => clearTimeout(timer) };\n}\n\n/**\n * Ask every open window client in parallel, under one shared deadline.\n *\n * @returns Every valid answer; empty when nobody answered.\n */\nasync function askAllClients(\n sw: BgSwGlobal,\n request: BackgroundSyncCredentialsRequest,\n): Promise<ClientAnswer[]> {\n const clients = (await sw.clients?.matchAll({ type: \"window\" })) ?? [];\n if (clients.length === 0) return [];\n const deadline = startDeadline();\n const answers = await Promise.all(\n clients.map((client) => askClient(client, request, deadline.promise)),\n );\n deadline.cancel();\n return answers.filter((answer): answer is ClientAnswer => answer !== undefined);\n}\n\n/** State of one replay pass: answers cached per URL + method, and the warning flag. */\ninterface ReplayRun {\n ask(request: Request): Promise<ClientAnswer[]>;\n warnNoAnswer(): void;\n}\n\nfunction createReplayRun(sw: BgSwGlobal): ReplayRun {\n const answers = new Map<string, Promise<ClientAnswer[]>>();\n let warned = false;\n return {\n ask(request) {\n const key = `${request.method} ${request.url}`;\n let pending = answers.get(key);\n if (!pending) {\n pending = askAllClients(sw, {\n url: request.url,\n method: request.method,\n phase: \"replay\",\n });\n answers.set(key, pending);\n }\n return pending;\n },\n warnNoAnswer() {\n if (warned || !isDevBuild()) return;\n warned = true;\n console.warn(\n \"[tempest-react-sdk/sw] background-sync: a queued request needs the current \" +\n \"credentials, and no open page answered. Call \" +\n \"provideBackgroundSyncCredentials() in the page; the entry stays pending.\",\n );\n },\n };\n}\n\n/** Pick the answer an entry may be replayed with, per its owner state. */\nfunction chooseAnswer(\n answers: readonly ClientAnswer[],\n context: BackgroundSyncReplayContext,\n): ClientAnswer | undefined {\n switch (context.ownerState) {\n case \"bound\":\n return answers.find((answer) => answer.hasPrincipal && answer.owner === context.owner);\n case \"unknown\":\n return answers.find((answer) => !answer.hasPrincipal);\n case \"unbound\":\n return answers.find((answer) => !answer.hasPrincipal) ?? answers[0];\n }\n}\n\n/**\n * The default `beforeReplay` (rules on {@link InstallBackgroundSyncOptions}).\n *\n * @throws {Error} When no page answered, or the chosen answer lacks a stripped\n * header — the entry stays pending.\n */\nasync function defaultBeforeReplay(\n run: ReplayRun,\n request: Request,\n context: BackgroundSyncReplayContext,\n): Promise<Request | null> {\n const credentialed = context.strippedHeaders.length > 0;\n if (!credentialed && context.ownerState !== \"bound\") return request;\n const answers = await run.ask(request);\n if (answers.length === 0) {\n run.warnNoAnswer();\n throw new Error(\"background-sync: no client answered\");\n }\n const chosen = chooseAnswer(answers, context);\n if (!chosen) return null;\n if (!credentialed) return request;\n if (chosen.headers === null) return null;\n const provided = new Map(\n Object.entries(chosen.headers).map(([name, value]) => [name.toLowerCase(), value]),\n );\n if (context.strippedHeaders.some((name) => !provided.has(name))) {\n throw new Error(\"background-sync: the answer lacks a stripped credential header\");\n }\n const headers = new Headers(request.headers);\n for (const name of context.strippedHeaders) headers.set(name, provided.get(name) as string);\n return new Request(request, { headers });\n}\n\n/** Everything {@link replayQueue} needs besides the clock. */\ninterface ReplayConfig {\n sw: BgSwGlobal;\n name: string;\n maxRetentionMs: number;\n credentialHeaders: ReadonlySet<string>;\n beforeReplay?: InstallBackgroundSyncOptions[\"beforeReplay\"];\n}\n\n/**\n * Replay every queued request once. Entries that succeed, are stale, get a 4xx\n * (a client error that will not fix itself) or that the preparation rejects with\n * `null` are removed; entries that fail again — network error, 5xx, or a\n * preparation that throws — are kept, and so is an entry whose owner is still\n * being stamped (for up to {@link OWNER_STAMP_GRACE_MS}). Each entry is checked\n * against the store right before it is sent, so a queue cleared mid-replay stops\n * the replay. Throws if any entry is still pending, so a `sync` handler keeps\n * the sync registered.\n */\nasync function replayQueue(config: ReplayConfig, now: number): Promise<void> {\n const { sw, name, maxRetentionMs, credentialHeaders, beforeReplay } = config;\n const run = createReplayRun(sw);\n const prepare =\n beforeReplay ??\n ((request: Request, context: BackgroundSyncReplayContext) =>\n defaultBeforeReplay(run, request, context));\n const entries = await readAll(name, credentialHeaders);\n let pending = 0;\n\n for (const entry of entries) {\n if (entry.id === undefined) continue;\n if (now - entry.timestamp > maxRetentionMs) {\n await remove(name, entry.id);\n continue;\n }\n const state = entry.ownerState ?? \"unknown\";\n if (state === \"pending\" && now - entry.timestamp < OWNER_STAMP_GRACE_MS) {\n pending += 1;\n continue;\n }\n const ownerState: BackgroundSyncOwnerState = state === \"pending\" ? \"unknown\" : state;\n try {\n const { request: stored, strippedHeaders } = deserializeRequest(\n entry,\n credentialHeaders,\n );\n const request = await prepare(stored, {\n queuedAt: entry.timestamp,\n strippedHeaders,\n ownerState,\n owner: ownerState === \"bound\" ? (entry.owner ?? null) : undefined,\n });\n if (!(await stillQueued(name, entry.id))) continue;\n if (request === null) {\n await remove(name, entry.id);\n continue;\n }\n const response = await fetch(request);\n if (response.ok || (response.status >= 400 && response.status < 500)) {\n await remove(name, entry.id);\n } else {\n pending += 1;\n }\n } catch {\n pending += 1;\n }\n }\n\n if (pending > 0) throw new Error(`background-sync: ${pending} request(s) still pending`);\n}\n\n/**\n * The replay in flight per queue. `sync`, `periodicsync` and the Safari fallback\n * can fire together; sharing one pass keeps a mutation from being sent twice.\n */\nconst replaysInFlight = new Map<string, Promise<void>>();\n\nfunction drainQueue(config: ReplayConfig): Promise<void> {\n const running = replaysInFlight.get(config.name);\n if (running) return running;\n const pass = replayQueue(config, Date.now()).finally(() => {\n replaysInFlight.delete(config.name);\n });\n replaysInFlight.set(config.name, pass);\n return pass;\n}\n\nfunction matches(\n match: InstallBackgroundSyncOptions[\"match\"],\n url: URL,\n request: Request,\n): boolean {\n if (!match) return true;\n return typeof match === \"function\" ? match(url, request) : match.test(url.href);\n}\n\n/**\n * Ask the issuing page who owns a just-queued entry and record it.\n *\n * @returns Resolves once the owner is stamped; never rejects.\n */\nasync function stampFromIssuer(\n name: string,\n id: number,\n issuer: WindowClientLike,\n request: Request,\n): Promise<void> {\n const deadline = startDeadline();\n const answer = await askClient(\n issuer,\n { url: request.url, method: request.method, phase: \"enqueue\" },\n deadline.promise,\n );\n deadline.cancel();\n const state: BackgroundSyncOwnerState = !answer\n ? \"unknown\"\n : answer.hasPrincipal\n ? \"bound\"\n : \"unbound\";\n await stampOwner(name, id, state, answer?.owner);\n}\n\n/**\n * Install the background-sync queue: on a failed mutating request, the request\n * is serialized to IndexedDB (without its credential headers) and a sync is\n * registered; the original fetch still rejects (so your app can show an offline\n * state), and the request is replayed later when the network returns.\n *\n * Right after queueing, the worker asks the page that issued the request who is\n * signed in (`getPrincipal` on {@link provideBackgroundSyncCredentials}) and\n * stamps the entry with that owner, without delaying the rejection. The work is\n * handed to `event.waitUntil` synchronously, so the worker stays alive for it\n * in every engine. Without the Background Sync API (every non-Chromium\n * browser), the queue is drained opportunistically whenever a `GET` goes\n * through the worker.\n *\n * @tempest-limits empty-catch — `registration.sync.register` is unavailable on\n * every non-Chromium browser and fails on a revoked background-sync permission.\n * The entry is already durable in IndexedDB at that point, and the queue is also\n * drained opportunistically on the next successful request, so losing the OS-level\n * wakeup degrades *when* the replay happens, not *whether* it happens.\n */\nexport function installBackgroundSync(options: InstallBackgroundSyncOptions = {}): void {\n const sw = getSwScope();\n const {\n match,\n queueName = DEFAULT_QUEUE_NAME,\n maxRetentionMinutes = 1440,\n periodicSyncTag = `${options.queueName ?? DEFAULT_QUEUE_NAME}-periodic`,\n credentialHeaders = DEFAULT_CREDENTIAL_HEADERS,\n beforeReplay,\n } = options;\n const stripped = credentialHeaderSet(credentialHeaders);\n const replay: ReplayConfig = {\n sw,\n name: queueName,\n maxRetentionMs: maxRetentionMinutes * 60 * 1000,\n credentialHeaders: stripped,\n beforeReplay,\n };\n\n sw.addEventListener(\"fetch\", (event) => {\n const request = event.request;\n if (request.method === \"GET\" || request.method === \"HEAD\") return;\n\n const url = new URL(request.url);\n if (!matches(match, url, request)) return;\n\n const epoch = readEpoch(queueName, stripped);\n epoch.catch(() => undefined);\n const attempt = fetch(request.clone());\n const queued = attempt.then(\n () => undefined,\n async () => {\n const issuer = event.clientId ? await sw.clients?.get(event.clientId) : undefined;\n const entry = await serializeRequest(\n request,\n Date.now(),\n stripped,\n issuer ? \"pending\" : \"unknown\",\n );\n const id = await enqueue(queueName, entry, await epoch, stripped);\n if (id === undefined) return undefined;\n try {\n await sw.registration.sync?.register(queueName);\n } catch {\n /* empty */\n }\n return issuer ? { id, issuer } : undefined;\n },\n );\n event.respondWith(\n attempt.catch(async (error: unknown) => {\n await queued;\n throw error;\n }),\n );\n event.waitUntil(\n queued\n .then((stamp) =>\n stamp ? stampFromIssuer(queueName, stamp.id, stamp.issuer, request) : undefined,\n )\n .catch(() => undefined),\n );\n });\n\n sw.addEventListener(\"sync\", (event) => {\n if (event.tag !== queueName) return;\n event.waitUntil(drainQueue(replay));\n });\n\n sw.addEventListener(\"periodicsync\", (event) => {\n if (event.tag !== periodicSyncTag) return;\n event.waitUntil(drainQueue(replay).catch(() => undefined));\n });\n\n sw.addEventListener(\"fetch\", (event) => {\n if (sw.registration.sync) return;\n if (event.request.method !== \"GET\") return;\n event.waitUntil(drainQueue(replay).catch(() => undefined));\n });\n}\n\n/**\n * Empty the background-sync queue — every request still waiting to be replayed —\n * and bump its clear epoch. Call it on logout (or use `clearSessionData()`, which\n * also clears the runtime caches) so mutations made under one session are never\n * replayed under the next.\n *\n * Works from the page and from the worker, and reaches work already in flight\n * in the worker: a replay checks each entry right before sending it, and a\n * request still failing when the queue is cleared is not written afterwards.\n *\n * @param queueName - The `queueName` given to {@link installBackgroundSync}.\n * Default `tempest-bg-sync`.\n * @returns `true` once the queue is empty; `false` when IndexedDB is\n * unavailable (SSR, old browsers).\n *\n * @example\n * import { clearBackgroundSyncQueue } from \"tempest-react-sdk/sw\";\n *\n * await clearBackgroundSyncQueue();\n */\nexport async function clearBackgroundSyncQueue(\n queueName: string = DEFAULT_QUEUE_NAME,\n): Promise<boolean> {\n if (typeof indexedDB === \"undefined\") return false;\n const db = await openQueueDb(queueName);\n const tx = db.transaction([STORE, META], \"readwrite\");\n tx.objectStore(STORE).clear();\n const meta = tx.objectStore(META);\n const current = meta.get(EPOCH_KEY);\n current.onsuccess = () => {\n meta.put(((current.result as number | undefined) ?? 0) + 1, EPOCH_KEY);\n };\n await txDone(tx);\n db.close();\n return true;\n}\n\n/**\n * One-way fingerprint of a principal: hex SHA-256, so the queue can compare\n * owners without ever holding the id itself.\n *\n * @returns The fingerprint, or `null` when nobody is signed in.\n */\nasync function ownerFingerprint(principal: string | null | undefined): Promise<string | null> {\n if (principal === null || principal === undefined || principal === \"\") return null;\n const digest = await crypto.subtle.digest(\n \"SHA-256\",\n new TextEncoder().encode(`tempest-bg-sync:${principal}`),\n );\n return [...new Uint8Array(digest)].map((byte) => byte.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\n/**\n * Answer the worker's questions about queued requests (see `beforeReplay` on\n * {@link installBackgroundSync}). Install it once in every page, next to your\n * auth setup; it reads the token at replay time, so the queue never has to store\n * it. Without it, a queued request that carried a credential header is never\n * replayed.\n *\n * `getHeaders` must return **every** credential header the app sends (the worker\n * keeps an entry pending when one it stripped is missing), or `null` when there\n * is no session — the worker then drops the entry instead of replaying it\n * anonymously. A throw from `getHeaders` or `getPrincipal` is answered as an\n * explicit `{ error: true }`. The worker only applies headers whose names the\n * original request carried, so returning `Authorization` for every URL never\n * leaks it to a URL that did not receive it in the first place.\n *\n * Pass `getPrincipal` to bind each entry to whoever queued it: the worker asks\n * the issuing tab right after queueing, asks every tab again before replaying,\n * and drops the entry when no signed-in tab is its owner.\n *\n * @param getHeaders - Resolves the headers for one queued request at replay.\n * @param options - `getPrincipal` binds entries to their owner.\n * @returns A function that removes the listener. A no-op outside the browser.\n *\n * @example\n * import { provideBackgroundSyncCredentials } from \"tempest-react-sdk/sw\";\n *\n * const stop = provideBackgroundSyncCredentials(\n * () => {\n * const token = localStorage.getItem(\"token\");\n * return token ? { Authorization: `Bearer ${token}` } : null;\n * },\n * { getPrincipal: () => localStorage.getItem(\"userId\") },\n * );\n */\nexport function provideBackgroundSyncCredentials(\n getHeaders: BackgroundSyncCredentialsProvider,\n options: ProvideBackgroundSyncCredentialsOptions = {},\n): () => void {\n if (typeof navigator === \"undefined\" || !navigator.serviceWorker) return () => undefined;\n const container = navigator.serviceWorker;\n const { getPrincipal } = options;\n const onMessage = (event: MessageEvent): void => {\n const data = event.data as Partial<BackgroundSyncCredentialsRequest> & { type?: unknown };\n const port = event.ports[0];\n if (data?.type !== BACKGROUND_SYNC_CREDENTIALS_MESSAGE || !port) return;\n const request: BackgroundSyncCredentialsRequest = {\n url: String(data.url),\n method: String(data.method),\n phase: data.phase === \"enqueue\" ? \"enqueue\" : \"replay\",\n };\n void (async () => {\n try {\n const headers = request.phase === \"enqueue\" ? null : await getHeaders(request);\n const answer: { headers: Record<string, string> | null; owner?: string | null } = {\n headers,\n };\n if (getPrincipal) answer.owner = await ownerFingerprint(await getPrincipal());\n port.postMessage(answer);\n } catch {\n port.postMessage({ error: true });\n }\n })();\n };\n container.addEventListener(\"message\", onMessage);\n return () => container.removeEventListener(\"message\", onMessage);\n}\n"],"mappings":";;;AA4DA,SAAS,IAAyB;CAC9B,OAAO;AACX;AAkCA,IAAM,IAAqB,mBAOrB,IAAa,GACb,IAAQ,YACR,IAAO,QACP,IAAY,SAML,IAAsC,+BAG7C,IAAyB,KAMzB,IAAuB,IAAyB;AA6GtD,SAAS,EACL,GACA,GACgD;CAChD,IAAM,IAA2B,CAAC,GAC5B,IAAqB,CAAC;CAC5B,KAAK,IAAM,CAAC,GAAM,MAAU,GACxB,AAAI,EAAkB,IAAI,EAAK,YAAY,CAAC,IAAG,EAAS,KAAK,EAAK,YAAY,CAAC,IAC1E,EAAK,KAAK,CAAC,GAAM,CAAK,CAAC;CAEhC,OAAO;EAAE;EAAM;CAAS;AAC5B;AAOA,SAAS,EAAqB,GAAuB,GAA8C;CAC/F,IAAM,IAAgB,EAAM,WAAW;CACvC,EAAc,kBAAkB;EAC5B,IAAM,IAAS,EAAc;EAC7B,IAAI,CAAC,GAAQ;EACb,IAAM,IAAQ,EAAO,OACf,EAAE,SAAM,gBAAa,EAAa,EAAM,SAAS,CAAiB;EAOxE,AANA,EAAO,OAAO;GACV,GAAG;GACH,SAAS;GACT,iBAAiB,CAAC,mBAAG,IAAI,IAAI,CAAC,GAAI,EAAM,mBAAmB,CAAC,GAAI,GAAG,CAAQ,CAAC,CAAC;GAC7E,YAAY,EAAM,cAAc;EACpC,CAAC,GACD,EAAO,SAAS;CACpB;AACJ;AAEA,SAAS,EACL,GACA,IAAyC,EAAoB,GACzC;CACpB,OAAO,IAAI,SAAS,GAAS,MAAW;EACpC,IAAM,IAAU,UAAU,KAAK,GAAM,CAAU;EAe/C,AAdA,EAAQ,mBAA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UAAU,eAAe,aAAa,KAAA;CAC/E,IAAM,IAAY,UAAU,eACtB,EAAE,oBAAiB,GACnB,KAAa,MAA8B;EAC7C,IAAM,IAAO,EAAM,MACb,IAAO,EAAM,MAAM;EACzB,IAAI,GAAM,SAAA,iCAAgD,CAAC,GAAM;EACjE,IAAM,IAA4C;GAC9C,KAAK,OAAO,EAAK,GAAG;GACpB,QAAQ,OAAO,EAAK,MAAM;GAC1B,OAAO,EAAK,UAAU,YAAY,YAAY;EAClD;EACA,CAAM,YAAY;GACd,IAAI;IAEA,IAAM,IAA4E,EAC9E,SAFY,EAAQ,UAAU,YAAY,OAAO,MAAM,EAAW,CAAO,EAG7E;IAEA,AADI,MAAc,EAAO,QAAQ,MAAM,EAAiB,MAAM,EAAa,CAAC,IAC5E,EAAK,YAAY,CAAM;GAC3B,QAAQ;IACJ,EAAK,YAAY,EAAE,OAAO,GAAK,CAAC;GACpC;EACJ,EAAA,CAAG;CACP;CAEA,OADA,EAAU,iBAAiB,WAAW,CAAS,SAClC,EAAU,oBAAoB,WAAW,CAAS;AACnE"}
|
|
1
|
+
{"version":3,"file":"background-sync.js","names":[],"sources":["../../src/sw/background-sync.ts"],"sourcesContent":["/**\n * Background-sync helper: queue failed mutating requests (POST/PUT/PATCH/DELETE)\n * while offline and replay them when connectivity returns. A dependency-free\n * take on Workbox's `BackgroundSyncPlugin`, backed by a tiny IndexedDB queue.\n *\n * Import inside your `sw.ts`. Uses the Background Sync API (`registration.sync`)\n * when available, and also replays opportunistically on the next request as a\n * fallback for browsers without it (e.g. Safari).\n *\n * Credential headers (`Authorization` and the rest of\n * {@link DEFAULT_CREDENTIAL_HEADERS}) are never written to IndexedDB: the queue\n * outlives the session, and a stored bearer stayed readable after logout and was\n * replayed with the old identity (reproduced in Chromium 153, 11/10/2026). On\n * replay the worker asks the open pages for the *current* credentials — see\n * {@link provideBackgroundSyncCredentials} — or a custom `beforeReplay` hook.\n * Credentials carried in the URL or the body are out of reach and are stored\n * as sent.\n *\n * @example\n * import { installBackgroundSync } from \"tempest-react-sdk/sw\";\n *\n * installBackgroundSync({ match: (url) => url.pathname.startsWith(\"/api/\") });\n */\nimport { isDevBuild } from \"../utils/dev-mode\";\nimport { DEFAULT_CREDENTIAL_HEADERS, credentialHeaderSet } from \"./credential-headers\";\n\ninterface SyncEventLike {\n tag: string;\n waitUntil(promise: Promise<unknown>): void;\n}\n\ninterface BgFetchEventLike {\n request: Request;\n /** Id of the window client that issued the request, when there is one. */\n clientId?: string;\n respondWith(response: Response | Promise<Response>): void;\n waitUntil(promise: Promise<unknown>): void;\n}\n\ninterface PeriodicSyncEventLike {\n tag: string;\n waitUntil(promise: Promise<unknown>): void;\n}\n\n/** Minimal shape of a window client the worker can message. */\ninterface WindowClientLike {\n postMessage(message: unknown, transfer: Transferable[]): void;\n}\n\ninterface BgSwGlobal {\n registration: { sync?: { register(tag: string): Promise<void> } };\n clients?: {\n matchAll(options: { type: \"window\" }): Promise<readonly WindowClientLike[]>;\n get(id: string): Promise<WindowClientLike | undefined>;\n };\n addEventListener(type: \"sync\", listener: (event: SyncEventLike) => void): void;\n addEventListener(type: \"fetch\", listener: (event: BgFetchEventLike) => void): void;\n addEventListener(type: \"periodicsync\", listener: (event: PeriodicSyncEventLike) => void): void;\n}\n\nfunction getSwScope(): BgSwGlobal {\n return globalThis as unknown as BgSwGlobal;\n}\n\n/**\n * How an entry is tied to whoever queued it:\n * - `\"bound\"`: the issuing page reported a principal (or `null` for nobody);\n * the entry only goes out while the same one is signed in.\n * - `\"unbound\"`: the issuing page answered without `getPrincipal`.\n * - `\"unknown\"`: nobody could say — no issuing tab, no answer, an error, or an\n * entry written before owners existed. Fails closed, with or without stripped\n * credentials: a cookie session rides along on the replay, so an entry with no\n * credential header is checked like any other.\n *\n * While the worker is still asking, the stored state is `\"pending\"`, which a\n * replay never sees: it waits, then reads a stamp that never came as `\"unknown\"`.\n */\nexport type BackgroundSyncOwnerState = \"bound\" | \"unbound\" | \"unknown\";\n\n/**\n * How the default `beforeReplay` treats an `\"unknown\"` owner on an entry that\n * carried no credential header:\n * - `\"strict\"` (default): it asks the open pages like any other entry — replayed\n * only when every answer lacks a principal, dropped as soon as one answer has\n * one, pending while nobody answers.\n * - `\"lenient\"`: it is replayed as-is, without asking (the behavior up to 0.77.0).\n *\n * An entry with stripped credentials always asks, under either policy.\n */\nexport type BackgroundSyncOwnerPolicy = \"strict\" | \"lenient\";\n\n/** A serialized request stored in the queue. */\ninterface QueuedRequest {\n id?: number;\n url: string;\n method: string;\n headers: [string, string][];\n body: ArrayBuffer | null;\n timestamp: number;\n /** The original `credentials` mode, so cookie-based APIs replay with cookies. */\n credentials?: RequestCredentials;\n /** Lower-cased names of the credential headers removed before persisting. */\n strippedHeaders?: string[];\n /** Absent on entries written before 0.77 — read as `\"unknown\"`. */\n ownerState?: BackgroundSyncOwnerState | \"pending\";\n /** Fingerprint of the principal under `\"bound\"`; `null` for \"nobody signed in\". */\n owner?: string | null;\n}\n\n/** Default IndexedDB database name (and sync tag) of the background-sync queue. */\nconst DEFAULT_QUEUE_NAME = \"tempest-bg-sync\";\n\n/**\n * Schema version of the queue database. Version 2 adds the `meta` store (the\n * clear epoch) and migrates version-1 entries, scrubbing their plaintext\n * credential headers on first open.\n */\nconst DB_VERSION = 2;\nconst STORE = \"requests\";\nconst META = \"meta\";\nconst EPOCH_KEY = \"epoch\";\n\n/**\n * `type` of the message the worker posts to window clients to ask about a queued\n * request. Answered by {@link provideBackgroundSyncCredentials}.\n */\nexport const BACKGROUND_SYNC_CREDENTIALS_MESSAGE = \"tempest:bg-sync-credentials\";\n\n/** How long the worker waits for the window clients to answer, in milliseconds. */\nconst CREDENTIALS_TIMEOUT_MS = 3000;\n\n/**\n * How long a replay waits on an entry whose owner is still being stamped. Past\n * it (the worker died mid-question), the owner is read as `\"unknown\"`.\n */\nconst OWNER_STAMP_GRACE_MS = CREDENTIALS_TIMEOUT_MS * 2;\n\n/** What a queued request looked like when it was stored, passed to `beforeReplay`. */\nexport interface BackgroundSyncReplayContext {\n /** Epoch milliseconds of the original failed attempt. */\n queuedAt: number;\n /** Lower-cased credential header names stripped before the entry was stored. */\n strippedHeaders: readonly string[];\n /** How the entry is tied to its owner. */\n ownerState: BackgroundSyncOwnerState;\n /** Owner fingerprint under `\"bound\"` (`null` for nobody); `undefined` otherwise. */\n owner: string | null | undefined;\n}\n\n/** The request a window client is asked about, as sent by the worker. */\nexport interface BackgroundSyncCredentialsRequest {\n /** Absolute URL of the queued request. */\n url: string;\n /** HTTP method of the queued request. */\n method: string;\n /**\n * `\"enqueue\"` when the worker only wants the owner of a request that just\n * failed; `\"replay\"` when it is about to send it and needs the credentials.\n */\n phase: \"enqueue\" | \"replay\";\n}\n\n/**\n * Resolve the credentials for a queued request: a header record to apply, or\n * `null` when there is no session (the entry is then dropped).\n */\nexport type BackgroundSyncCredentialsProvider = (\n request: BackgroundSyncCredentialsRequest,\n) => Record<string, string> | null | Promise<Record<string, string> | null>;\n\n/** Options for {@link provideBackgroundSyncCredentials}. */\nexport interface ProvideBackgroundSyncCredentialsOptions {\n /**\n * Who is signed in right now — a stable, non-secret id such as the user id;\n * `null`/`undefined` when nobody is. Read when a request is queued and again\n * when it is replayed: an entry is only sent while the same principal is\n * signed in, and dropped otherwise, so a mutation queued by one account is\n * never sent with another account's credentials even when the app forgets\n * `clearSessionData()` on logout. Only a SHA-256 fingerprint reaches the\n * queue, never the value itself. A throw is answered as an explicit error,\n * which leaves the owner unknown (fail closed).\n */\n getPrincipal?: () => string | null | undefined | Promise<string | null | undefined>;\n}\n\n/** Options for {@link installBackgroundSync}. */\nexport interface InstallBackgroundSyncOptions {\n /**\n * Which requests to queue on failure. A `RegExp` against the URL or a\n * predicate. Only non-`GET` requests are ever considered. Default: all\n * non-`GET` requests.\n */\n match?: RegExp | ((url: URL, request: Request) => boolean);\n /** IndexedDB database name, also used as the sync tag. Default `tempest-bg-sync`. */\n queueName?: string;\n /** Drop queued requests older than this (minutes) on replay. Default `1440` (24h). */\n maxRetentionMinutes?: number;\n /**\n * Also drain the queue on the `periodicsync` event carrying this tag,\n * complementing the one-off `sync` replay so long-pending mutations retry\n * even without a fresh navigation. Register the periodic sync from the main\n * thread with {@link registerPeriodicSync}. Default `${queueName}-periodic`.\n */\n periodicSyncTag?: string;\n /**\n * Header names stripped before a request is persisted — and stripped again on\n * replay, so entries written by an older version never go out with the\n * credential they stored. Default {@link DEFAULT_CREDENTIAL_HEADERS}; extend it\n * for a custom credential header (`[...DEFAULT_CREDENTIAL_HEADERS,\n * \"x-tenant-key\"]`). Passing `[]` restores the pre-0.77 behavior of\n * persisting and replaying every header, credentials included.\n */\n credentialHeaders?: readonly string[];\n /**\n * Prepare each queued request right before it is replayed: return the\n * request to send (typically with the current credentials applied) or\n * `null` to drop the entry for good. A thrown error keeps the entry pending.\n * The context carries the entry's owner, so a custom hook can apply the\n * same rule as the default.\n *\n * Default: only an `\"unbound\"` entry with no stripped credentials (and, under\n * `ownerPolicy: \"lenient\"`, an `\"unknown\"` one) is replayed as-is, without\n * asking. Every other entry — credentialed or not —\n * asks every open window client in parallel (see\n * {@link provideBackgroundSyncCredentials}) and picks the answer that fits:\n * - `\"bound\"`: the answer whose owner matches; none among valid answers →\n * dropped, never sent anonymously or as somebody else;\n * - `\"unknown\"`: only when every answer lacks a principal (an app that does\n * not use `getPrincipal`); a single answer with one → dropped, since a\n * stale tab without `getPrincipal` says nothing about who is signed in\n * next to it. This holds for an entry\n * with no credential header too, since the browser attaches the cookies of\n * whoever is signed in at replay time;\n * - `\"unbound\"`: any answer, preferring one without a principal.\n * Then `null` headers drop a credentialed entry, an answer that lacks one of\n * the stripped headers keeps it pending, and only the stripped names are\n * re-applied. No valid answer at all keeps it pending until\n * `maxRetentionMinutes` (and warns once per replay in development builds) —\n * so a page that never calls {@link provideBackgroundSyncCredentials} leaves\n * every entry it queued `\"unknown\"`, and none of them is replayed.\n */\n /**\n * How an `\"unknown\"` owner is handled on an entry with no stripped\n * credentials (see {@link BackgroundSyncOwnerPolicy}). Default `\"strict\"`.\n *\n * `\"lenient\"` restores the replay-as-is of 0.77.0 and earlier for an app without sign-in,\n * where no page ever reports a principal. Do not use it with a cookie\n * session: the browser attaches on replay the cookie of whoever is signed in\n * at that moment, so a mutation queued by A whose owner was never stamped\n * (issuing tab closed, empty `clientId`, stamp lost, legacy entry) goes out\n * with B's session. Entries with stripped credentials ask the pages either\n * way. Ignored when a custom `beforeReplay` is given.\n */\n ownerPolicy?: BackgroundSyncOwnerPolicy;\n beforeReplay?: (\n request: Request,\n context: BackgroundSyncReplayContext,\n ) => Request | null | Promise<Request | null>;\n}\n\n/**\n * Move credential headers out of a header list.\n *\n * @returns The remaining headers and the lower-cased names removed.\n */\nfunction splitHeaders(\n headers: Iterable<[string, string]>,\n credentialHeaders: ReadonlySet<string>,\n): { kept: [string, string][]; stripped: string[] } {\n const kept: [string, string][] = [];\n const stripped: string[] = [];\n for (const [name, value] of headers) {\n if (credentialHeaders.has(name.toLowerCase())) stripped.push(name.toLowerCase());\n else kept.push([name, value]);\n }\n return { kept, stripped };\n}\n\n/**\n * Scrub version-1 entries during the upgrade: their credential headers were\n * stored in plaintext, so they are removed from disk on the first open, recorded\n * as stripped, and the owner is marked unknown.\n */\nfunction migrateLegacyEntries(store: IDBObjectStore, credentialHeaders: ReadonlySet<string>): void {\n const cursorRequest = store.openCursor();\n cursorRequest.onsuccess = () => {\n const cursor = cursorRequest.result;\n if (!cursor) return;\n const entry = cursor.value as QueuedRequest;\n const { kept, stripped } = splitHeaders(entry.headers, credentialHeaders);\n cursor.update({\n ...entry,\n headers: kept,\n strippedHeaders: [...new Set([...(entry.strippedHeaders ?? []), ...stripped])],\n ownerState: entry.ownerState ?? \"unknown\",\n });\n cursor.continue();\n };\n}\n\nfunction openQueueDb(\n name: string,\n credentialHeaders: ReadonlySet<string> = credentialHeaderSet(),\n): Promise<IDBDatabase> {\n return new Promise((resolve, reject) => {\n const request = indexedDB.open(name, DB_VERSION);\n request.onupgradeneeded = (event) => {\n const db = request.result;\n if (!db.objectStoreNames.contains(STORE)) {\n db.createObjectStore(STORE, { keyPath: \"id\", autoIncrement: true });\n } else if (event.oldVersion < 2 && request.transaction) {\n migrateLegacyEntries(request.transaction.objectStore(STORE), credentialHeaders);\n }\n if (!db.objectStoreNames.contains(META)) db.createObjectStore(META);\n };\n request.onsuccess = () => {\n const db = request.result;\n db.onversionchange = () => db.close();\n resolve(db);\n };\n request.onerror = () => reject(request.error);\n });\n}\n\nfunction txDone(tx: IDBTransaction): Promise<void> {\n return new Promise((resolve, reject) => {\n tx.oncomplete = () => resolve();\n tx.onerror = () => reject(tx.error);\n tx.onabort = () => reject(tx.error);\n });\n}\n\n/** The current clear epoch: bumped by every {@link clearBackgroundSyncQueue}. */\nasync function readEpoch(name: string, credentialHeaders: ReadonlySet<string>): Promise<number> {\n const db = await openQueueDb(name, credentialHeaders);\n const tx = db.transaction(META, \"readonly\");\n const get = tx.objectStore(META).get(EPOCH_KEY);\n await txDone(tx);\n db.close();\n return (get.result as number | undefined) ?? 0;\n}\n\n/**\n * Add an entry unless the queue was cleared since `epoch` was read — checked in\n * the same transaction as the write, so a logout that lands while the request\n * is still failing never lets it into the next session's queue.\n *\n * @returns The new entry's key, or `undefined` when the clear won.\n */\nasync function enqueue(\n name: string,\n entry: QueuedRequest,\n epoch: number,\n credentialHeaders: ReadonlySet<string>,\n): Promise<number | undefined> {\n const db = await openQueueDb(name, credentialHeaders);\n const tx = db.transaction([STORE, META], \"readwrite\");\n let id: number | undefined;\n const current = tx.objectStore(META).get(EPOCH_KEY);\n current.onsuccess = () => {\n if (((current.result as number | undefined) ?? 0) !== epoch) return;\n const add = tx.objectStore(STORE).add(entry);\n add.onsuccess = () => {\n id = add.result as number;\n };\n };\n await txDone(tx);\n db.close();\n return id;\n}\n\n/**\n * Record how an entry is owned. A no-op when the entry is already gone\n * (replayed, or the queue was cleared).\n */\nasync function stampOwner(\n name: string,\n id: number,\n ownerState: BackgroundSyncOwnerState,\n owner: string | null | undefined,\n): Promise<void> {\n const db = await openQueueDb(name);\n const tx = db.transaction(STORE, \"readwrite\");\n const store = tx.objectStore(STORE);\n const get = store.get(id);\n get.onsuccess = () => {\n const entry = get.result as QueuedRequest | undefined;\n if (!entry) return;\n entry.ownerState = ownerState;\n if (ownerState === \"bound\") entry.owner = owner ?? null;\n store.put(entry);\n };\n await txDone(tx);\n db.close();\n}\n\nasync function readAll(\n name: string,\n credentialHeaders: ReadonlySet<string>,\n): Promise<QueuedRequest[]> {\n const db = await openQueueDb(name, credentialHeaders);\n const tx = db.transaction(STORE, \"readonly\");\n const all = await new Promise<QueuedRequest[]>((resolve, reject) => {\n const req = tx.objectStore(STORE).getAll();\n req.onsuccess = () => resolve(req.result as QueuedRequest[]);\n req.onerror = () => reject(req.error);\n });\n db.close();\n return all;\n}\n\n/** Whether an entry is still in the queue — `false` once it was cleared. */\nasync function stillQueued(name: string, id: number): Promise<boolean> {\n const db = await openQueueDb(name);\n const tx = db.transaction(STORE, \"readonly\");\n const count = tx.objectStore(STORE).count(id);\n await txDone(tx);\n db.close();\n return count.result > 0;\n}\n\nasync function remove(name: string, id: number): Promise<void> {\n const db = await openQueueDb(name);\n const tx = db.transaction(STORE, \"readwrite\");\n tx.objectStore(STORE).delete(id);\n await txDone(tx);\n db.close();\n}\n\n/**\n * Serialize a request for the queue, leaving out every credential header and\n * recording which ones were present.\n */\nasync function serializeRequest(\n request: Request,\n timestamp: number,\n credentialHeaders: ReadonlySet<string>,\n ownerState: QueuedRequest[\"ownerState\"],\n): Promise<QueuedRequest> {\n const buffer = await request.clone().arrayBuffer();\n const { kept, stripped } = splitHeaders(request.headers.entries(), credentialHeaders);\n return {\n url: request.url,\n method: request.method,\n headers: kept,\n body: buffer.byteLength > 0 ? buffer : null,\n timestamp,\n credentials: request.credentials,\n strippedHeaders: stripped,\n ownerState,\n };\n}\n\n/**\n * Rebuild a stored request, stripping credential headers once more so an entry\n * that still holds one (a custom `credentialHeaders` the migration did not know)\n * never replays it.\n */\nfunction deserializeRequest(\n entry: QueuedRequest,\n credentialHeaders: ReadonlySet<string>,\n): { request: Request; strippedHeaders: string[] } {\n const { kept, stripped } = splitHeaders(entry.headers, credentialHeaders);\n return {\n request: new Request(entry.url, {\n method: entry.method,\n headers: kept,\n body: entry.body ?? undefined,\n credentials: entry.credentials,\n }),\n strippedHeaders: [...new Set([...(entry.strippedHeaders ?? []), ...stripped])],\n };\n}\n\n/** A window client's parsed answer. */\ninterface ClientAnswer {\n headers: Record<string, string> | null;\n /** Whether the page has `getPrincipal`. */\n hasPrincipal: boolean;\n owner: string | null;\n}\n\n/**\n * Ask one window client about a queued request over a `MessageChannel`.\n *\n * @returns The parsed answer, or `undefined` when the client stayed silent until\n * `deadline`, answered `{ error: true }`, or answered something unrecognizable.\n */\nasync function askClient(\n client: WindowClientLike,\n request: BackgroundSyncCredentialsRequest,\n deadline: Promise<void>,\n): Promise<ClientAnswer | undefined> {\n const channel = new MessageChannel();\n const answer = await Promise.race([\n new Promise<unknown>((resolve) => {\n channel.port1.onmessage = (event: MessageEvent) => resolve(event.data);\n client.postMessage({ type: BACKGROUND_SYNC_CREDENTIALS_MESSAGE, ...request }, [\n channel.port2,\n ]);\n }),\n deadline.then(() => undefined),\n ]);\n channel.port1.close();\n if (answer === null || typeof answer !== \"object\" || !(\"headers\" in answer)) return undefined;\n const { headers, owner } = answer as { headers: unknown; owner?: unknown };\n const hasPrincipal = \"owner\" in answer;\n if (hasPrincipal && typeof owner !== \"string\" && owner !== null) return undefined;\n return {\n headers:\n headers !== null && typeof headers === \"object\"\n ? (headers as Record<string, string>)\n : null,\n hasPrincipal,\n owner: hasPrincipal ? (owner as string | null) : null,\n };\n}\n\n/** A deadline shared by every client asked in one round. */\nfunction startDeadline(): { promise: Promise<void>; cancel: () => void } {\n let timer: ReturnType<typeof setTimeout> | undefined;\n const promise = new Promise<void>((resolve) => {\n timer = setTimeout(resolve, CREDENTIALS_TIMEOUT_MS);\n });\n return { promise, cancel: () => clearTimeout(timer) };\n}\n\n/**\n * Ask every open window client in parallel, under one shared deadline.\n *\n * @returns Every valid answer; empty when nobody answered.\n */\nasync function askAllClients(\n sw: BgSwGlobal,\n request: BackgroundSyncCredentialsRequest,\n): Promise<ClientAnswer[]> {\n const clients = (await sw.clients?.matchAll({ type: \"window\" })) ?? [];\n if (clients.length === 0) return [];\n const deadline = startDeadline();\n const answers = await Promise.all(\n clients.map((client) => askClient(client, request, deadline.promise)),\n );\n deadline.cancel();\n return answers.filter((answer): answer is ClientAnswer => answer !== undefined);\n}\n\n/** State of one replay pass: answers cached per URL + method, and the warning flag. */\ninterface ReplayRun {\n ask(request: Request): Promise<ClientAnswer[]>;\n warnNoAnswer(): void;\n}\n\nfunction createReplayRun(sw: BgSwGlobal): ReplayRun {\n const answers = new Map<string, Promise<ClientAnswer[]>>();\n let warned = false;\n return {\n ask(request) {\n const key = `${request.method} ${request.url}`;\n let pending = answers.get(key);\n if (!pending) {\n pending = askAllClients(sw, {\n url: request.url,\n method: request.method,\n phase: \"replay\",\n });\n answers.set(key, pending);\n }\n return pending;\n },\n warnNoAnswer() {\n if (warned || !isDevBuild()) return;\n warned = true;\n console.warn(\n \"[tempest-react-sdk/sw] background-sync: a queued request needs an open page \" +\n \"to confirm who is signed in or to supply the current credentials, and no \" +\n \"open page answered. Call \" +\n \"provideBackgroundSyncCredentials() in the page; the entry stays pending.\",\n );\n },\n };\n}\n\n/**\n * Pick the answer an entry may be replayed with, per its owner state.\n *\n * An `\"unknown\"` owner replays only when every valid answer lacks a principal:\n * one tab reporting a principal (even `null`) is enough to drop it, because a\n * principal-less answer — say a tab still running a bundle from before the app\n * adopted `getPrincipal` — says nothing about whose cookie the replay carries.\n */\nfunction chooseAnswer(\n answers: readonly ClientAnswer[],\n context: BackgroundSyncReplayContext,\n): ClientAnswer | undefined {\n switch (context.ownerState) {\n case \"bound\":\n return answers.find((answer) => answer.hasPrincipal && answer.owner === context.owner);\n case \"unknown\":\n return answers.every((answer) => !answer.hasPrincipal) ? answers[0] : undefined;\n case \"unbound\":\n return answers.find((answer) => !answer.hasPrincipal) ?? answers[0];\n }\n}\n\n/**\n * The default `beforeReplay` (rules on {@link InstallBackgroundSyncOptions}).\n *\n * @throws {Error} When no page answered, or the chosen answer lacks a stripped\n * header — the entry stays pending.\n */\nasync function defaultBeforeReplay(\n run: ReplayRun,\n request: Request,\n context: BackgroundSyncReplayContext,\n ownerPolicy: BackgroundSyncOwnerPolicy,\n): Promise<Request | null> {\n const credentialed = context.strippedHeaders.length > 0;\n const unchecked =\n context.ownerState === \"unbound\" ||\n (ownerPolicy === \"lenient\" && context.ownerState === \"unknown\");\n if (!credentialed && unchecked) return request;\n const answers = await run.ask(request);\n if (answers.length === 0) {\n run.warnNoAnswer();\n throw new Error(\"background-sync: no client answered\");\n }\n const chosen = chooseAnswer(answers, context);\n if (!chosen) return null;\n if (!credentialed) return request;\n if (chosen.headers === null) return null;\n const provided = new Map(\n Object.entries(chosen.headers).map(([name, value]) => [name.toLowerCase(), value]),\n );\n if (context.strippedHeaders.some((name) => !provided.has(name))) {\n throw new Error(\"background-sync: the answer lacks a stripped credential header\");\n }\n const headers = new Headers(request.headers);\n for (const name of context.strippedHeaders) headers.set(name, provided.get(name) as string);\n return new Request(request, { headers });\n}\n\n/** Everything {@link replayQueue} needs besides the clock. */\ninterface ReplayConfig {\n sw: BgSwGlobal;\n name: string;\n maxRetentionMs: number;\n credentialHeaders: ReadonlySet<string>;\n beforeReplay?: InstallBackgroundSyncOptions[\"beforeReplay\"];\n ownerPolicy: BackgroundSyncOwnerPolicy;\n}\n\n/**\n * Replay every queued request once. Entries that succeed, are stale, get a 4xx\n * (a client error that will not fix itself) or that the preparation rejects with\n * `null` are removed; entries that fail again — network error, 5xx, or a\n * preparation that throws — are kept, and so is an entry whose owner is still\n * being stamped (for up to {@link OWNER_STAMP_GRACE_MS}). Each entry is checked\n * against the store right before it is sent, so a queue cleared mid-replay stops\n * the replay. Throws if any entry is still pending, so a `sync` handler keeps\n * the sync registered.\n */\nasync function replayQueue(config: ReplayConfig, now: number): Promise<void> {\n const { sw, name, maxRetentionMs, credentialHeaders, beforeReplay, ownerPolicy } = config;\n const run = createReplayRun(sw);\n const prepare =\n beforeReplay ??\n ((request: Request, context: BackgroundSyncReplayContext) =>\n defaultBeforeReplay(run, request, context, ownerPolicy));\n const entries = await readAll(name, credentialHeaders);\n let pending = 0;\n\n for (const entry of entries) {\n if (entry.id === undefined) continue;\n if (now - entry.timestamp > maxRetentionMs) {\n await remove(name, entry.id);\n continue;\n }\n const state = entry.ownerState ?? \"unknown\";\n if (state === \"pending\" && now - entry.timestamp < OWNER_STAMP_GRACE_MS) {\n pending += 1;\n continue;\n }\n const ownerState: BackgroundSyncOwnerState = state === \"pending\" ? \"unknown\" : state;\n try {\n const { request: stored, strippedHeaders } = deserializeRequest(\n entry,\n credentialHeaders,\n );\n const request = await prepare(stored, {\n queuedAt: entry.timestamp,\n strippedHeaders,\n ownerState,\n owner: ownerState === \"bound\" ? (entry.owner ?? null) : undefined,\n });\n if (!(await stillQueued(name, entry.id))) continue;\n if (request === null) {\n await remove(name, entry.id);\n continue;\n }\n const response = await fetch(request);\n if (response.ok || (response.status >= 400 && response.status < 500)) {\n await remove(name, entry.id);\n } else {\n pending += 1;\n }\n } catch {\n pending += 1;\n }\n }\n\n if (pending > 0) throw new Error(`background-sync: ${pending} request(s) still pending`);\n}\n\n/**\n * The replay in flight per queue. `sync`, `periodicsync` and the Safari fallback\n * can fire together; sharing one pass keeps a mutation from being sent twice.\n */\nconst replaysInFlight = new Map<string, Promise<void>>();\n\nfunction drainQueue(config: ReplayConfig): Promise<void> {\n const running = replaysInFlight.get(config.name);\n if (running) return running;\n const pass = replayQueue(config, Date.now()).finally(() => {\n replaysInFlight.delete(config.name);\n });\n replaysInFlight.set(config.name, pass);\n return pass;\n}\n\nfunction matches(\n match: InstallBackgroundSyncOptions[\"match\"],\n url: URL,\n request: Request,\n): boolean {\n if (!match) return true;\n return typeof match === \"function\" ? match(url, request) : match.test(url.href);\n}\n\n/**\n * Ask the issuing page who owns a just-queued entry and record it.\n *\n * @returns Resolves once the owner is stamped; never rejects.\n */\nasync function stampFromIssuer(\n name: string,\n id: number,\n issuer: WindowClientLike,\n request: Request,\n): Promise<void> {\n const deadline = startDeadline();\n const answer = await askClient(\n issuer,\n { url: request.url, method: request.method, phase: \"enqueue\" },\n deadline.promise,\n );\n deadline.cancel();\n const state: BackgroundSyncOwnerState = !answer\n ? \"unknown\"\n : answer.hasPrincipal\n ? \"bound\"\n : \"unbound\";\n await stampOwner(name, id, state, answer?.owner);\n}\n\n/**\n * Install the background-sync queue: on a failed mutating request, the request\n * is serialized to IndexedDB (without its credential headers) and a sync is\n * registered; the original fetch still rejects (so your app can show an offline\n * state), and the request is replayed later when the network returns.\n *\n * Right after queueing, the worker asks the page that issued the request who is\n * signed in (`getPrincipal` on {@link provideBackgroundSyncCredentials}) and\n * stamps the entry with that owner, without delaying the rejection. The work is\n * handed to `event.waitUntil` synchronously, so the worker stays alive for it\n * in every engine. Without the Background Sync API (every non-Chromium\n * browser), the queue is drained opportunistically whenever a `GET` goes\n * through the worker.\n *\n * @tempest-limits empty-catch — `registration.sync.register` is unavailable on\n * every non-Chromium browser and fails on a revoked background-sync permission.\n * The entry is already durable in IndexedDB at that point, and the queue is also\n * drained opportunistically on the next successful request, so losing the OS-level\n * wakeup degrades *when* the replay happens, not *whether* it happens.\n */\nexport function installBackgroundSync(options: InstallBackgroundSyncOptions = {}): void {\n const sw = getSwScope();\n const {\n match,\n queueName = DEFAULT_QUEUE_NAME,\n maxRetentionMinutes = 1440,\n periodicSyncTag = `${options.queueName ?? DEFAULT_QUEUE_NAME}-periodic`,\n credentialHeaders = DEFAULT_CREDENTIAL_HEADERS,\n beforeReplay,\n ownerPolicy = \"strict\",\n } = options;\n const stripped = credentialHeaderSet(credentialHeaders);\n const replay: ReplayConfig = {\n sw,\n name: queueName,\n maxRetentionMs: maxRetentionMinutes * 60 * 1000,\n credentialHeaders: stripped,\n beforeReplay,\n ownerPolicy,\n };\n\n sw.addEventListener(\"fetch\", (event) => {\n const request = event.request;\n if (request.method === \"GET\" || request.method === \"HEAD\") return;\n\n const url = new URL(request.url);\n if (!matches(match, url, request)) return;\n\n const epoch = readEpoch(queueName, stripped);\n epoch.catch(() => undefined);\n const attempt = fetch(request.clone());\n const queued = attempt.then(\n () => undefined,\n async () => {\n const issuer = event.clientId ? await sw.clients?.get(event.clientId) : undefined;\n const entry = await serializeRequest(\n request,\n Date.now(),\n stripped,\n issuer ? \"pending\" : \"unknown\",\n );\n const id = await enqueue(queueName, entry, await epoch, stripped);\n if (id === undefined) return undefined;\n try {\n await sw.registration.sync?.register(queueName);\n } catch {\n /* empty */\n }\n return issuer ? { id, issuer } : undefined;\n },\n );\n event.respondWith(\n attempt.catch(async (error: unknown) => {\n await queued;\n throw error;\n }),\n );\n event.waitUntil(\n queued\n .then((stamp) =>\n stamp ? stampFromIssuer(queueName, stamp.id, stamp.issuer, request) : undefined,\n )\n .catch(() => undefined),\n );\n });\n\n sw.addEventListener(\"sync\", (event) => {\n if (event.tag !== queueName) return;\n event.waitUntil(drainQueue(replay));\n });\n\n sw.addEventListener(\"periodicsync\", (event) => {\n if (event.tag !== periodicSyncTag) return;\n event.waitUntil(drainQueue(replay).catch(() => undefined));\n });\n\n sw.addEventListener(\"fetch\", (event) => {\n if (sw.registration.sync) return;\n if (event.request.method !== \"GET\") return;\n event.waitUntil(drainQueue(replay).catch(() => undefined));\n });\n}\n\n/**\n * Empty the background-sync queue — every request still waiting to be replayed —\n * and bump its clear epoch. Call it on logout (or use `clearSessionData()`, which\n * also clears the runtime caches) so mutations made under one session are never\n * replayed under the next.\n *\n * Works from the page and from the worker, and reaches work already in flight\n * in the worker: a replay checks each entry right before sending it, and a\n * request still failing when the queue is cleared is not written afterwards.\n *\n * @param queueName - The `queueName` given to {@link installBackgroundSync}.\n * Default `tempest-bg-sync`.\n * @returns `true` once the queue is empty; `false` when IndexedDB is\n * unavailable (SSR, old browsers).\n *\n * @example\n * import { clearBackgroundSyncQueue } from \"tempest-react-sdk/sw\";\n *\n * await clearBackgroundSyncQueue();\n */\nexport async function clearBackgroundSyncQueue(\n queueName: string = DEFAULT_QUEUE_NAME,\n): Promise<boolean> {\n if (typeof indexedDB === \"undefined\") return false;\n const db = await openQueueDb(queueName);\n const tx = db.transaction([STORE, META], \"readwrite\");\n tx.objectStore(STORE).clear();\n const meta = tx.objectStore(META);\n const current = meta.get(EPOCH_KEY);\n current.onsuccess = () => {\n meta.put(((current.result as number | undefined) ?? 0) + 1, EPOCH_KEY);\n };\n await txDone(tx);\n db.close();\n return true;\n}\n\n/**\n * One-way fingerprint of a principal: hex SHA-256, so the queue can compare\n * owners without ever holding the id itself.\n *\n * @returns The fingerprint, or `null` when nobody is signed in.\n */\nasync function ownerFingerprint(principal: string | null | undefined): Promise<string | null> {\n if (principal === null || principal === undefined || principal === \"\") return null;\n const digest = await crypto.subtle.digest(\n \"SHA-256\",\n new TextEncoder().encode(`tempest-bg-sync:${principal}`),\n );\n return [...new Uint8Array(digest)].map((byte) => byte.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\n/**\n * Answer the worker's questions about queued requests (see `beforeReplay` on\n * {@link installBackgroundSync}). Install it once in every page, next to your\n * auth setup; it reads the token at replay time, so the queue never has to store\n * it. Without it, a queued request that carried a credential header is never\n * replayed.\n *\n * `getHeaders` must return **every** credential header the app sends (the worker\n * keeps an entry pending when one it stripped is missing), or `null` when there\n * is no session — the worker then drops the entry instead of replaying it\n * anonymously. A throw from `getHeaders` or `getPrincipal` is answered as an\n * explicit `{ error: true }`. The worker only applies headers whose names the\n * original request carried, so returning `Authorization` for every URL never\n * leaks it to a URL that did not receive it in the first place.\n *\n * Pass `getPrincipal` to bind each entry to whoever queued it: the worker asks\n * the issuing tab right after queueing, asks every tab again before replaying,\n * and drops the entry when no signed-in tab is its owner.\n *\n * @param getHeaders - Resolves the headers for one queued request at replay.\n * @param options - `getPrincipal` binds entries to their owner.\n * @returns A function that removes the listener. A no-op outside the browser.\n *\n * @example\n * import { provideBackgroundSyncCredentials } from \"tempest-react-sdk/sw\";\n *\n * const stop = provideBackgroundSyncCredentials(\n * () => {\n * const token = localStorage.getItem(\"token\");\n * return token ? { Authorization: `Bearer ${token}` } : null;\n * },\n * { getPrincipal: () => localStorage.getItem(\"userId\") },\n * );\n */\nexport function provideBackgroundSyncCredentials(\n getHeaders: BackgroundSyncCredentialsProvider,\n options: ProvideBackgroundSyncCredentialsOptions = {},\n): () => void {\n if (typeof navigator === \"undefined\" || !navigator.serviceWorker) return () => undefined;\n const container = navigator.serviceWorker;\n const { getPrincipal } = options;\n const onMessage = (event: MessageEvent): void => {\n const data = event.data as Partial<BackgroundSyncCredentialsRequest> & { type?: unknown };\n const port = event.ports[0];\n if (data?.type !== BACKGROUND_SYNC_CREDENTIALS_MESSAGE || !port) return;\n const request: BackgroundSyncCredentialsRequest = {\n url: String(data.url),\n method: String(data.method),\n phase: data.phase === \"enqueue\" ? \"enqueue\" : \"replay\",\n };\n void (async () => {\n try {\n const headers = request.phase === \"enqueue\" ? null : await getHeaders(request);\n const answer: { headers: Record<string, string> | null; owner?: string | null } = {\n headers,\n };\n if (getPrincipal) answer.owner = await ownerFingerprint(await getPrincipal());\n port.postMessage(answer);\n } catch {\n port.postMessage({ error: true });\n }\n })();\n };\n container.addEventListener(\"message\", onMessage);\n return () => container.removeEventListener(\"message\", onMessage);\n}\n"],"mappings":";;;AA4DA,SAAS,IAAyB;CAC9B,OAAO;AACX;AAgDA,IAAM,IAAqB,mBAOrB,IAAa,GACb,IAAQ,YACR,IAAO,QACP,IAAY,SAML,IAAsC,+BAG7C,IAAyB,KAMzB,IAAuB,IAAyB;AAkItD,SAAS,EACL,GACA,GACgD;CAChD,IAAM,IAA2B,CAAC,GAC5B,IAAqB,CAAC;CAC5B,KAAK,IAAM,CAAC,GAAM,MAAU,GACxB,AAAI,EAAkB,IAAI,EAAK,YAAY,CAAC,IAAG,EAAS,KAAK,EAAK,YAAY,C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a,CAAC,IAC5E,EAAK,YAAY,CAAM;GAC3B,QAAQ;IACJ,EAAK,YAAY,EAAE,OAAO,GAAK,CAAC;GACpC;EACJ,EAAA,CAAG;CACP;CAEA,OADA,EAAU,iBAAiB,WAAW,CAAS,SAClC,EAAU,oBAAoB,WAAW,CAAS;AACnE"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"credential-headers.cjs","names":[],"sources":["../../src/sw/credential-headers.ts"],"sourcesContent":["/**\n * Header names treated as credentials by the service-worker helpers: never\n * persisted by `installBackgroundSync`, and a request carrying any of them\n * bypasses `installRuntimeCache` unless the route opts in. `Cookie` and\n * `Proxy-Authorization` are listed for completeness although the browser\n * forbids scripts from setting them — a cookie session is invisible to the\n * worker
|
|
1
|
+
{"version":3,"file":"credential-headers.cjs","names":[],"sources":["../../src/sw/credential-headers.ts"],"sourcesContent":["/**\n * Header names treated as credentials by the service-worker helpers: never\n * persisted by `installBackgroundSync`, and a request carrying any of them\n * bypasses `installRuntimeCache` unless the route opts in. `Cookie` and\n * `Proxy-Authorization` are listed for completeness although the browser\n * forbids scripts from setting them — a cookie session is invisible to the\n * worker. The runtime cache therefore depends on `Cache-Control` and\n * `clearSessionData()`; the background-sync queue checks the entry's owner\n * through `getPrincipal` whether or not a credential header was stripped, and\n * `clearSessionData()` still backs that check up.\n */\nexport const DEFAULT_CREDENTIAL_HEADERS: readonly string[] = [\n \"authorization\",\n \"proxy-authorization\",\n \"cookie\",\n \"x-api-key\",\n \"x-auth-token\",\n \"x-csrf-token\",\n \"x-xsrf-token\",\n];\n\n/**\n * Lower-case a list of header names into a set for case-insensitive lookups.\n *\n * @param names - Header names, any case. Default {@link DEFAULT_CREDENTIAL_HEADERS}.\n * @returns The lower-cased set.\n */\nexport function credentialHeaderSet(\n names: readonly string[] = DEFAULT_CREDENTIAL_HEADERS,\n): ReadonlySet<string> {\n return new Set(names.map((name) => name.toLowerCase()));\n}\n"],"mappings":"AAWA,IAAa,EAAgD,CACzD,gBACA,sBACA,SACA,YACA,eACA,eACA,cACJ,EAQA,SAAgB,EACZ,EAA2B,EACR,CACnB,OAAO,IAAI,IAAI,EAAM,IAAK,GAAS,EAAK,YAAY,CAAC,CAAC,CAC1D"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"credential-headers.js","names":[],"sources":["../../src/sw/credential-headers.ts"],"sourcesContent":["/**\n * Header names treated as credentials by the service-worker helpers: never\n * persisted by `installBackgroundSync`, and a request carrying any of them\n * bypasses `installRuntimeCache` unless the route opts in. `Cookie` and\n * `Proxy-Authorization` are listed for completeness although the browser\n * forbids scripts from setting them — a cookie session is invisible to the\n * worker
|
|
1
|
+
{"version":3,"file":"credential-headers.js","names":[],"sources":["../../src/sw/credential-headers.ts"],"sourcesContent":["/**\n * Header names treated as credentials by the service-worker helpers: never\n * persisted by `installBackgroundSync`, and a request carrying any of them\n * bypasses `installRuntimeCache` unless the route opts in. `Cookie` and\n * `Proxy-Authorization` are listed for completeness although the browser\n * forbids scripts from setting them — a cookie session is invisible to the\n * worker. The runtime cache therefore depends on `Cache-Control` and\n * `clearSessionData()`; the background-sync queue checks the entry's owner\n * through `getPrincipal` whether or not a credential header was stripped, and\n * `clearSessionData()` still backs that check up.\n */\nexport const DEFAULT_CREDENTIAL_HEADERS: readonly string[] = [\n \"authorization\",\n \"proxy-authorization\",\n \"cookie\",\n \"x-api-key\",\n \"x-auth-token\",\n \"x-csrf-token\",\n \"x-xsrf-token\",\n];\n\n/**\n * Lower-case a list of header names into a set for case-insensitive lookups.\n *\n * @param names - Header names, any case. Default {@link DEFAULT_CREDENTIAL_HEADERS}.\n * @returns The lower-cased set.\n */\nexport function credentialHeaderSet(\n names: readonly string[] = DEFAULT_CREDENTIAL_HEADERS,\n): ReadonlySet<string> {\n return new Set(names.map((name) => name.toLowerCase()));\n}\n"],"mappings":";AAWA,IAAa,IAAgD;CACzD;CACA;CACA;CACA;CACA;CACA;CACA;AACJ;AAQA,SAAgB,EACZ,IAA2B,GACR;CACnB,OAAO,IAAI,IAAI,EAAM,KAAK,MAAS,EAAK,YAAY,CAAC,CAAC;AAC1D"}
|
package/dist/sw.d.ts
CHANGED
|
@@ -23,13 +23,27 @@ export declare interface BackgroundSyncCredentialsRequest {
|
|
|
23
23
|
phase: "enqueue" | "replay";
|
|
24
24
|
}
|
|
25
25
|
|
|
26
|
+
/**
|
|
27
|
+
* How the default `beforeReplay` treats an `"unknown"` owner on an entry that
|
|
28
|
+
* carried no credential header:
|
|
29
|
+
* - `"strict"` (default): it asks the open pages like any other entry — replayed
|
|
30
|
+
* only when every answer lacks a principal, dropped as soon as one answer has
|
|
31
|
+
* one, pending while nobody answers.
|
|
32
|
+
* - `"lenient"`: it is replayed as-is, without asking (the behavior up to 0.77.0).
|
|
33
|
+
*
|
|
34
|
+
* An entry with stripped credentials always asks, under either policy.
|
|
35
|
+
*/
|
|
36
|
+
export declare type BackgroundSyncOwnerPolicy = "strict" | "lenient";
|
|
37
|
+
|
|
26
38
|
/**
|
|
27
39
|
* How an entry is tied to whoever queued it:
|
|
28
40
|
* - `"bound"`: the issuing page reported a principal (or `null` for nobody);
|
|
29
41
|
* the entry only goes out while the same one is signed in.
|
|
30
42
|
* - `"unbound"`: the issuing page answered without `getPrincipal`.
|
|
31
43
|
* - `"unknown"`: nobody could say — no issuing tab, no answer, an error, or an
|
|
32
|
-
* entry written before owners existed. Fails closed
|
|
44
|
+
* entry written before owners existed. Fails closed, with or without stripped
|
|
45
|
+
* credentials: a cookie session rides along on the replay, so an entry with no
|
|
46
|
+
* credential header is checked like any other.
|
|
33
47
|
*
|
|
34
48
|
* While the worker is still asking, the stored state is `"pending"`, which a
|
|
35
49
|
* replay never sees: it waits, then reads a stamp that never came as `"unknown"`.
|
|
@@ -169,7 +183,10 @@ export declare function createPartialResponse(request: Request, response: Respon
|
|
|
169
183
|
* bypasses `installRuntimeCache` unless the route opts in. `Cookie` and
|
|
170
184
|
* `Proxy-Authorization` are listed for completeness although the browser
|
|
171
185
|
* forbids scripts from setting them — a cookie session is invisible to the
|
|
172
|
-
* worker
|
|
186
|
+
* worker. The runtime cache therefore depends on `Cache-Control` and
|
|
187
|
+
* `clearSessionData()`; the background-sync queue checks the entry's owner
|
|
188
|
+
* through `getPrincipal` whether or not a credential header was stripped, and
|
|
189
|
+
* `clearSessionData()` still backs that check up.
|
|
173
190
|
*/
|
|
174
191
|
export declare const DEFAULT_CREDENTIAL_HEADERS: readonly string[];
|
|
175
192
|
|
|
@@ -248,19 +265,40 @@ export declare interface InstallBackgroundSyncOptions {
|
|
|
248
265
|
* The context carries the entry's owner, so a custom hook can apply the
|
|
249
266
|
* same rule as the default.
|
|
250
267
|
*
|
|
251
|
-
* Default: an entry with no stripped credentials and
|
|
252
|
-
*
|
|
253
|
-
*
|
|
268
|
+
* Default: only an `"unbound"` entry with no stripped credentials (and, under
|
|
269
|
+
* `ownerPolicy: "lenient"`, an `"unknown"` one) is replayed as-is, without
|
|
270
|
+
* asking. Every other entry — credentialed or not —
|
|
271
|
+
* asks every open window client in parallel (see
|
|
272
|
+
* {@link provideBackgroundSyncCredentials}) and picks the answer that fits:
|
|
254
273
|
* - `"bound"`: the answer whose owner matches; none among valid answers →
|
|
255
274
|
* dropped, never sent anonymously or as somebody else;
|
|
256
|
-
* - `"unknown"`: only
|
|
257
|
-
* `getPrincipal`);
|
|
275
|
+
* - `"unknown"`: only when every answer lacks a principal (an app that does
|
|
276
|
+
* not use `getPrincipal`); a single answer with one → dropped, since a
|
|
277
|
+
* stale tab without `getPrincipal` says nothing about who is signed in
|
|
278
|
+
* next to it. This holds for an entry
|
|
279
|
+
* with no credential header too, since the browser attaches the cookies of
|
|
280
|
+
* whoever is signed in at replay time;
|
|
258
281
|
* - `"unbound"`: any answer, preferring one without a principal.
|
|
259
282
|
* Then `null` headers drop a credentialed entry, an answer that lacks one of
|
|
260
283
|
* the stripped headers keeps it pending, and only the stripped names are
|
|
261
284
|
* re-applied. No valid answer at all keeps it pending until
|
|
262
|
-
* `maxRetentionMinutes` (and warns once per replay in development builds)
|
|
285
|
+
* `maxRetentionMinutes` (and warns once per replay in development builds) —
|
|
286
|
+
* so a page that never calls {@link provideBackgroundSyncCredentials} leaves
|
|
287
|
+
* every entry it queued `"unknown"`, and none of them is replayed.
|
|
288
|
+
*/
|
|
289
|
+
/**
|
|
290
|
+
* How an `"unknown"` owner is handled on an entry with no stripped
|
|
291
|
+
* credentials (see {@link BackgroundSyncOwnerPolicy}). Default `"strict"`.
|
|
292
|
+
*
|
|
293
|
+
* `"lenient"` restores the replay-as-is of 0.77.0 and earlier for an app without sign-in,
|
|
294
|
+
* where no page ever reports a principal. Do not use it with a cookie
|
|
295
|
+
* session: the browser attaches on replay the cookie of whoever is signed in
|
|
296
|
+
* at that moment, so a mutation queued by A whose owner was never stamped
|
|
297
|
+
* (issuing tab closed, empty `clientId`, stamp lost, legacy entry) goes out
|
|
298
|
+
* with B's session. Entries with stripped credentials ask the pages either
|
|
299
|
+
* way. Ignored when a custom `beforeReplay` is given.
|
|
263
300
|
*/
|
|
301
|
+
ownerPolicy?: BackgroundSyncOwnerPolicy;
|
|
264
302
|
beforeReplay?: (request: Request, context: BackgroundSyncReplayContext) => Request | null | Promise<Request | null>;
|
|
265
303
|
}
|
|
266
304
|
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=require("../utils/dev-mode.cjs"),t=require("
|
|
1
|
+
const e=require("../utils/dev-mode.cjs"),t=require("../utils/owner-fingerprint.cjs"),n=require("./app-error-queue.cjs"),r=require("./app-error-schema.cjs"),i=require("./app-error-transport.cjs"),a=require("./describe-app-error.cjs");var o=!1;function s(t){o||t.foreignReports!==`drop`||t.getPrincipal===void 0&&e.isDevBuild()&&(o=!0,console.warn('[tempest-react-sdk] createAppErrorReporter({ foreignReports: "drop" }) needs `getPrincipal`: without it the reporter cannot prove a queued report belongs to someone else, so it drops nothing and those reports go out anonymously. Pass `getPrincipal` to make "drop" take effect.'))}function c(){try{return typeof localStorage>`u`?null:localStorage}catch{return null}}function l(e){try{return e?.()??{}}catch{return{}}}function u(e){try{return t.ownerFingerprint(`p`,e())}catch{return null}}function d(e,n){let r=e?{owner:u(e)}:{};return typeof n==`string`||n===null?{session:t.ownerFingerprint(`t`,n),...r}:n.then(e=>({session:t.ownerFingerprint(`t`,e),...r}))}function f(e){let{endpoint:o,getToken:f,getPrincipal:p,device:m,autoFlush:h=!0}=e;s(e);let g=p!==void 0&&e.foreignReports===`drop`,_=n.createAppErrorQueue(e.storage===void 0?c():e.storage,e.storageKey??`tempest:app-errors`,e.maxEntries??50),v=null,y=0,b=null,x=new Set,S=0,C=async()=>{let n=e.fetch??globalThis.fetch.bind(globalThis);await Promise.all(x);let r=await i.readToken(f),a=t.ownerFingerprint(`t`,r),s=p?u(p):null,c=S,l={sent:0,dropped:0,pending:0,retryAfterMs:null};for(let e of _.entries()){if(!_.has(e))continue;if(g&&(e.owner==null||e.owner!==s)){_.remove(e),l.dropped+=1;continue}let t=e.session!=null&&e.session===a?r:null,u=await i.sendOne(n,o,t,e);if(S!==c||u.kind===`stop`)break;if(u.kind===`wait`){l.retryAfterMs=u.ms,y=Date.now()+u.ms,b??=setTimeout(()=>{b=null,w()},u.ms);break}_.remove(e),l[u.kind===`sent`?`sent`:`dropped`]+=1}return l.pending=_.entries().length,l},w=()=>(v??=C().finally(()=>{v=null}),v),T=()=>h&&Date.now()>=y&&(typeof navigator>`u`||navigator.onLine!==!1),E=()=>{T()&&w()};return h&&typeof window<`u`&&window.addEventListener(`online`,E),{report(e,t){let n=a.describeAppError(e,t),o=r.fitAppErrorReport({...l(m),...n}),s=d(p,i.readToken(f));if(!(s instanceof Promise)){_.push(o,s),T()&&w();return}let c=S,u=s.then(e=>{x.delete(u),S===c&&(_.push(o,e),T()&&w())});x.add(u)},flush:w,pending:()=>_.entries(),clear(){S+=1,_.clear()},dispose(){typeof window<`u`&&window.removeEventListener(`online`,E),b&&clearTimeout(b),b=null}}}exports.createAppErrorReporter=f;
|
|
2
2
|
//# sourceMappingURL=app-error-reporter.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"app-error-reporter.cjs","names":[],"sources":["../../src/telemetry/app-error-reporter.ts"],"sourcesContent":["import { appErrorOwner } from \"./app-error-owner\";\nimport { createAppErrorQueue } from \"./app-error-queue\";\nimport type { AppErrorQueueEntry, AppErrorQueueStorage, AppErrorStamp } from \"./app-error-queue\";\nimport { fitAppErrorReport } from \"./app-error-schema\";\nimport type { AppErrorDeviceSchema } from \"./app-error-schema\";\nimport { readToken, sendOne } from \"./app-error-transport\";\nimport { describeAppError } from \"./describe-app-error\";\nimport { isDevBuild } from \"../utils/dev-mode\";\n\n/** Options for {@link createAppErrorReporter}. */\nexport interface CreateAppErrorReporterOptions {\n /** Full URL of the backend route, e.g. `${API_URL}/api/app-errors`. */\n endpoint: string;\n /**\n * Current access token, if any. Optional on purpose: the route is public,\n * and an error raised before login — or with a stale session — still has\n * to get through. A token that throws or resolves empty sends anonymously.\n */\n getToken?: () => string | null | undefined | Promise<string | null | undefined>;\n /**\n * Who is signed in right now — a stable, non-secret id such as the user id.\n * Read **when the error is reported**, and stored in the queue only as a\n * one-way fingerprint (`entry.owner`). A non-string (an `async` getter\n * from untyped JS, an object) or a getter that throws reads as nobody.\n *\n * It never grants the bearer. The bearer goes out only when the token at\n * send time is the very token that was in force at report time (its\n * fingerprint is `entry.session`): the principal and the token come from\n * two sources, and a principal store that lags behind a login would\n * otherwise send A's report with B's token. The principal only tells\n * {@link CreateAppErrorReporterOptions.foreignReports} `\"drop\"` whose\n * report is whose.\n */\n getPrincipal?: () => string | number | null | undefined;\n /**\n * What to do with a queued report that cannot go out with the current\n * bearer — raised under another token, or queued before 0.77.0. Default\n * `\"anonymous\"`.\n *\n * - `\"anonymous\"` — send it without `Authorization`. The route is public,\n * so the error still reaches the backend; it is only not attributed to\n * anybody. This includes the user's own reports raised before a token\n * refresh: attribution is lost, never misplaced.\n * - `\"drop\"` — discard every report not proven to be the current\n * principal's: another principal, nobody, or unknown (no principal at\n * report time, a legacy entry, or nobody signed in now). For apps where\n * a previous user's error text must not leave the device after they\n * signed out. **Needs `getPrincipal`**: without it the only identity is\n * the token fingerprint, and a refresh changes it, so a mismatch is no\n * proof the report is someone else's — the reporter then sends\n * anonymously instead of destroying the user's own reports.\n *\n * Never is a report sent with a bearer other than the one it was raised\n * under: that would credit the previous user's error to whoever signed in\n * next.\n */\n foreignReports?: \"anonymous\" | \"drop\";\n /**\n * Device facts, read **when the error is reported**, not when it is sent —\n * a report queued offline on `1.4.0` must not go out labelled `1.5.0`.\n */\n device?: () => AppErrorDeviceSchema;\n /** Where the queue persists. Defaults to `localStorage`; `null` keeps it in memory. */\n storage?: AppErrorQueueStorage | null;\n /** Storage key. Default `\"tempest:app-errors\"`. */\n storageKey?: string;\n /** Ceiling on distinct waiting reports; the oldest is evicted. Default `50`. */\n maxEntries?: number;\n /** `fetch` to send with. Defaults to the global one. */\n fetch?: typeof fetch;\n /** Send on every report and when the browser goes `online`. Default `true`. */\n autoFlush?: boolean;\n}\n\n/** What one {@link AppErrorReporter.flush} did. */\nexport interface AppErrorFlushResult {\n /** Reports the backend accepted. */\n sent: number;\n /** Reports the backend refused for good (a 4xx other than 408/429) and were dropped. */\n dropped: number;\n /** Reports still waiting. */\n pending: number;\n /** Milliseconds the backend asked to wait (429 `Retry-After`), or `null`. */\n retryAfterMs: number | null;\n}\n\n/** The reporter {@link createAppErrorReporter} returns. */\nexport interface AppErrorReporter {\n /** Queue an error with optional context, and try to send it. Never throws. */\n report: (error: unknown, context?: Record<string, unknown>) => void;\n /** Drain the queue now. Concurrent calls share one run. */\n flush: () => Promise<AppErrorFlushResult>;\n /**\n * The waiting entries, oldest first. With an async `getToken` and no\n * `getPrincipal`, a report joins them once its token resolves — `flush()`\n * waits for that, `pending()` does not.\n */\n pending: () => AppErrorQueueEntry[];\n /**\n * Drop every waiting report. Call it on logout when reports raised in that\n * session should not outlive it; even without it, a report never leaves\n * with the next user's bearer.\n *\n * It also stops a flush in flight before its next send (the one already on\n * the wire cannot be recalled), and discards reports still waiting for an\n * async `getToken` to stamp them — both would otherwise refill the queue or\n * keep sending what the logout meant to forget.\n */\n clear: () => void;\n /** Remove the `online` listener and the retry timer. */\n dispose: () => void;\n}\n\n/** Set once the warning has printed, so every reporter built after it stays quiet. */\nlet warnedDropWithoutPrincipal = false;\n\n/**\n * Reset the warn-once latch. Test-only: the latch is module state, so a suite\n * asserting the warning more than once would otherwise see it only the first time.\n */\nexport function resetDropWithoutPrincipalWarning(): void {\n warnedDropWithoutPrincipal = false;\n}\n\n/**\n * Warn once, in development, that `foreignReports: \"drop\"` was asked for\n * without the `getPrincipal` it needs.\n *\n * Without a principal the only identity is the token fingerprint, which a\n * refresh changes, so the reporter cannot tell a foreign report from the\n * user's own and sends them anonymously instead of dropping them. The option\n * type-checks either way, so nothing else would tell the app its privacy\n * choice is not in force.\n *\n * @param options - The reporter's options.\n */\nfunction warnOnDropWithoutPrincipal(options: CreateAppErrorReporterOptions): void {\n if (warnedDropWithoutPrincipal || options.foreignReports !== \"drop\") return;\n if (options.getPrincipal !== undefined || !isDevBuild()) return;\n warnedDropWithoutPrincipal = true;\n console.warn(\n '[tempest-react-sdk] createAppErrorReporter({ foreignReports: \"drop\" }) needs ' +\n \"`getPrincipal`: without it the reporter cannot prove a queued report belongs \" +\n \"to someone else, so it drops nothing and those reports go out anonymously. \" +\n 'Pass `getPrincipal` to make \"drop\" take effect.',\n );\n}\n\n/**\n * Pick the default store, guarding hosts where touching `localStorage` throws.\n *\n * @returns `localStorage`, or `null` when there is none.\n */\nfunction defaultStorage(): AppErrorQueueStorage | null {\n try {\n return typeof localStorage === \"undefined\" ? null : localStorage;\n } catch {\n return null;\n }\n}\n\n/**\n * Read the device facts, reporting without them when the getter throws.\n *\n * @param device - The caller's getter.\n * @returns The facts, or an empty object.\n */\nfunction readDevice(device: CreateAppErrorReporterOptions[\"device\"]): AppErrorDeviceSchema {\n try {\n return device?.() ?? {};\n } catch {\n return {};\n }\n}\n\n/**\n * Fingerprint whoever `getPrincipal` says is signed in.\n *\n * @param getPrincipal - The app's principal getter.\n * @returns The owner, or `null` when nobody is signed in or the getter throws.\n */\nfunction principalOwner(getPrincipal: () => unknown): string | null {\n try {\n return appErrorOwner(\"p\", getPrincipal());\n } catch {\n return null;\n }\n}\n\n/**\n * Stamp a report being raised now with its session and, when given, principal.\n *\n * @param getPrincipal - The app's principal getter, read synchronously.\n * @param token - The token read now, or a promise of it.\n * @returns The stamp, or a promise of it when the token is still arriving.\n */\nfunction stampNow(\n getPrincipal: CreateAppErrorReporterOptions[\"getPrincipal\"],\n token: string | null | Promise<string | null>,\n): AppErrorStamp | Promise<AppErrorStamp> {\n const owner = getPrincipal ? { owner: principalOwner(getPrincipal) } : {};\n if (typeof token === \"string\" || token === null) {\n return { session: appErrorOwner(\"t\", token), ...owner };\n }\n return token.then((value) => ({ session: appErrorOwner(\"t\", value), ...owner }));\n}\n\n/**\n * Report client errors to a Tempest backend's `POST /api/app-errors`, surviving\n * the offline stretches where field errors actually happen.\n *\n * The client half of `tempest-fastapi-sdk`'s `app_errors` module. An error is\n * described ({@link describeAppError}), stamped with the device facts of that\n * moment, fitted to the backend's column limits and queued in `localStorage`\n * before anything goes over the network — so a report raised with no signal is\n * sent when the browser comes back `online`, not lost.\n *\n * What each answer does to the queue:\n *\n * - **2xx** — removed.\n * - **429** — kept; sending pauses for `Retry-After`, then resumes on its own.\n * - **5xx, 408, network failure** — kept; the next report, `online` event or\n * `flush()` retries.\n * - **any other 4xx** — dropped: the backend will refuse that body forever, and\n * keeping it would block every report queued behind it.\n *\n * Each report is stamped with a one-way fingerprint of the token in force when\n * it was raised, and goes out with a bearer only when the token at send time is\n * that same one — never with the token of whoever signed in next. The queue\n * never stores a token. `clear()` also stops a flush in flight and discards\n * reports still waiting for an async token.\n *\n * @example\n * import { createAppErrorReporter } from \"tempest-react-sdk\";\n *\n * const reporter = createAppErrorReporter({\n * endpoint: `${import.meta.env.VITE_API_URL}/api/app-errors`,\n * getToken: () => sessionStorage.getItem(\"access_token\"),\n * device: () => ({ platform: \"web\", app_version: \"1.4.0\" }),\n * });\n *\n * reporter.report(new Error(\"crop failed\"), { step: \"crop\", size: 0 });\n *\n * @param options - Endpoint, token and device getters, storage and limits.\n * @returns The reporter.\n */\nexport function createAppErrorReporter(options: CreateAppErrorReporterOptions): AppErrorReporter {\n const { endpoint, getToken, getPrincipal, device, autoFlush = true } = options;\n warnOnDropWithoutPrincipal(options);\n const strict = getPrincipal !== undefined && options.foreignReports === \"drop\";\n const queue = createAppErrorQueue(\n options.storage === undefined ? defaultStorage() : options.storage,\n options.storageKey ?? \"tempest:app-errors\",\n options.maxEntries ?? 50,\n );\n let running: Promise<AppErrorFlushResult> | null = null;\n let pausedUntil = 0;\n let timer: ReturnType<typeof setTimeout> | null = null;\n const stamping = new Set<Promise<void>>();\n let generation = 0;\n\n const drain = async (): Promise<AppErrorFlushResult> => {\n const send = options.fetch ?? globalThis.fetch.bind(globalThis);\n await Promise.all(stamping);\n const token = await readToken(getToken);\n const session = appErrorOwner(\"t\", token);\n const current = getPrincipal ? principalOwner(getPrincipal) : null;\n const started = generation;\n const result: AppErrorFlushResult = { sent: 0, dropped: 0, pending: 0, retryAfterMs: null };\n for (const entry of queue.entries()) {\n if (!queue.has(entry)) continue;\n if (strict && (entry.owner == null || entry.owner !== current)) {\n queue.remove(entry);\n result.dropped += 1;\n continue;\n }\n const bearer = entry.session != null && entry.session === session ? token : null;\n const outcome = await sendOne(send, endpoint, bearer, entry);\n if (generation !== started) break;\n if (outcome.kind === \"stop\") break;\n if (outcome.kind === \"wait\") {\n result.retryAfterMs = outcome.ms;\n pausedUntil = Date.now() + outcome.ms;\n timer ??= setTimeout(() => {\n timer = null;\n void flush();\n }, outcome.ms);\n break;\n }\n queue.remove(entry);\n result[outcome.kind === \"sent\" ? \"sent\" : \"dropped\"] += 1;\n }\n result.pending = queue.entries().length;\n return result;\n };\n\n const flush = (): Promise<AppErrorFlushResult> => {\n running ??= drain().finally(() => {\n running = null;\n });\n return running;\n };\n\n const shouldSend = (): boolean =>\n autoFlush &&\n Date.now() >= pausedUntil &&\n (typeof navigator === \"undefined\" || navigator.onLine !== false);\n\n const onOnline = (): void => {\n if (shouldSend()) void flush();\n };\n if (autoFlush && typeof window !== \"undefined\") window.addEventListener(\"online\", onOnline);\n\n return {\n report(error, context) {\n const description = describeAppError(error, context);\n const report = fitAppErrorReport({ ...readDevice(device), ...description });\n const stamp = stampNow(getPrincipal, readToken(getToken));\n if (!(stamp instanceof Promise)) {\n queue.push(report, stamp);\n if (shouldSend()) void flush();\n return;\n }\n const raisedIn = generation;\n const stamped = stamp.then((value) => {\n stamping.delete(stamped);\n if (generation !== raisedIn) return;\n queue.push(report, value);\n if (shouldSend()) void flush();\n });\n stamping.add(stamped);\n },\n flush,\n pending: () => queue.entries(),\n clear() {\n generation += 1;\n queue.clear();\n },\n dispose() {\n if (typeof window !== \"undefined\") window.removeEventListener(\"online\", onOnline);\n if (timer) clearTimeout(timer);\n timer = null;\n },\n };\n}\n"],"mappings":"gOAkHA,IAAI,EAA6B,GAsBjC,SAAS,EAA2B,EAA8C,CAC1E,GAA8B,EAAQ,iBAAmB,QACzD,EAAQ,eAAiB,IAAA,IAAc,EAAA,WAAW,IACtD,EAA6B,GAC7B,QAAQ,KACJ,sRAIJ,EACJ,CAOA,SAAS,GAA8C,CACnD,GAAI,CACA,OAAO,OAAO,aAAiB,IAAc,KAAO,YACxD,MAAQ,CACJ,OAAO,IACX,CACJ,CAQA,SAAS,EAAW,EAAuE,CACvF,GAAI,CACA,OAAO,IAAS,GAAK,CAAC,CAC1B,MAAQ,CACJ,MAAO,CAAC,CACZ,CACJ,CAQA,SAAS,EAAe,EAA4C,CAChE,GAAI,CACA,OAAO,EAAA,cAAc,IAAK,EAAa,CAAC,CAC5C,MAAQ,CACJ,OAAO,IACX,CACJ,CASA,SAAS,EACL,EACA,EACsC,CACtC,IAAM,EAAQ,EAAe,CAAE,MAAO,E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
1
|
+
{"version":3,"file":"app-error-reporter.cjs","names":[],"sources":["../../src/telemetry/app-error-reporter.ts"],"sourcesContent":["import { ownerFingerprint } from \"@/utils/owner-fingerprint\";\nimport { createAppErrorQueue } from \"./app-error-queue\";\nimport type { AppErrorQueueEntry, AppErrorQueueStorage, AppErrorStamp } from \"./app-error-queue\";\nimport { fitAppErrorReport } from \"./app-error-schema\";\nimport type { AppErrorDeviceSchema } from \"./app-error-schema\";\nimport { readToken, sendOne } from \"./app-error-transport\";\nimport { describeAppError } from \"./describe-app-error\";\nimport { isDevBuild } from \"../utils/dev-mode\";\n\n/** Options for {@link createAppErrorReporter}. */\nexport interface CreateAppErrorReporterOptions {\n /** Full URL of the backend route, e.g. `${API_URL}/api/app-errors`. */\n endpoint: string;\n /**\n * Current access token, if any. Optional on purpose: the route is public,\n * and an error raised before login — or with a stale session — still has\n * to get through. A token that throws or resolves empty sends anonymously.\n */\n getToken?: () => string | null | undefined | Promise<string | null | undefined>;\n /**\n * Who is signed in right now — a stable, non-secret id such as the user id.\n * Read **when the error is reported**, and stored in the queue only as a\n * one-way fingerprint (`entry.owner`). A non-string (an `async` getter\n * from untyped JS, an object) or a getter that throws reads as nobody.\n *\n * It never grants the bearer. The bearer goes out only when the token at\n * send time is the very token that was in force at report time (its\n * fingerprint is `entry.session`): the principal and the token come from\n * two sources, and a principal store that lags behind a login would\n * otherwise send A's report with B's token. The principal only tells\n * {@link CreateAppErrorReporterOptions.foreignReports} `\"drop\"` whose\n * report is whose.\n */\n getPrincipal?: () => string | number | null | undefined;\n /**\n * What to do with a queued report that cannot go out with the current\n * bearer — raised under another token, or queued before 0.77.0. Default\n * `\"anonymous\"`.\n *\n * - `\"anonymous\"` — send it without `Authorization`. The route is public,\n * so the error still reaches the backend; it is only not attributed to\n * anybody. This includes the user's own reports raised before a token\n * refresh: attribution is lost, never misplaced.\n * - `\"drop\"` — discard every report not proven to be the current\n * principal's: another principal, nobody, or unknown (no principal at\n * report time, a legacy entry, or nobody signed in now). For apps where\n * a previous user's error text must not leave the device after they\n * signed out. **Needs `getPrincipal`**: without it the only identity is\n * the token fingerprint, and a refresh changes it, so a mismatch is no\n * proof the report is someone else's — the reporter then sends\n * anonymously instead of destroying the user's own reports.\n *\n * Never is a report sent with a bearer other than the one it was raised\n * under: that would credit the previous user's error to whoever signed in\n * next.\n */\n foreignReports?: \"anonymous\" | \"drop\";\n /**\n * Device facts, read **when the error is reported**, not when it is sent —\n * a report queued offline on `1.4.0` must not go out labelled `1.5.0`.\n */\n device?: () => AppErrorDeviceSchema;\n /** Where the queue persists. Defaults to `localStorage`; `null` keeps it in memory. */\n storage?: AppErrorQueueStorage | null;\n /** Storage key. Default `\"tempest:app-errors\"`. */\n storageKey?: string;\n /** Ceiling on distinct waiting reports; the oldest is evicted. Default `50`. */\n maxEntries?: number;\n /** `fetch` to send with. Defaults to the global one. */\n fetch?: typeof fetch;\n /** Send on every report and when the browser goes `online`. Default `true`. */\n autoFlush?: boolean;\n}\n\n/** What one {@link AppErrorReporter.flush} did. */\nexport interface AppErrorFlushResult {\n /** Reports the backend accepted. */\n sent: number;\n /** Reports the backend refused for good (a 4xx other than 408/429) and were dropped. */\n dropped: number;\n /** Reports still waiting. */\n pending: number;\n /** Milliseconds the backend asked to wait (429 `Retry-After`), or `null`. */\n retryAfterMs: number | null;\n}\n\n/** The reporter {@link createAppErrorReporter} returns. */\nexport interface AppErrorReporter {\n /** Queue an error with optional context, and try to send it. Never throws. */\n report: (error: unknown, context?: Record<string, unknown>) => void;\n /** Drain the queue now. Concurrent calls share one run. */\n flush: () => Promise<AppErrorFlushResult>;\n /**\n * The waiting entries, oldest first. With an async `getToken` and no\n * `getPrincipal`, a report joins them once its token resolves — `flush()`\n * waits for that, `pending()` does not.\n */\n pending: () => AppErrorQueueEntry[];\n /**\n * Drop every waiting report. Call it on logout when reports raised in that\n * session should not outlive it; even without it, a report never leaves\n * with the next user's bearer.\n *\n * It also stops a flush in flight before its next send (the one already on\n * the wire cannot be recalled), and discards reports still waiting for an\n * async `getToken` to stamp them — both would otherwise refill the queue or\n * keep sending what the logout meant to forget.\n */\n clear: () => void;\n /** Remove the `online` listener and the retry timer. */\n dispose: () => void;\n}\n\n/** Set once the warning has printed, so every reporter built after it stays quiet. */\nlet warnedDropWithoutPrincipal = false;\n\n/**\n * Reset the warn-once latch. Test-only: the latch is module state, so a suite\n * asserting the warning more than once would otherwise see it only the first time.\n */\nexport function resetDropWithoutPrincipalWarning(): void {\n warnedDropWithoutPrincipal = false;\n}\n\n/**\n * Warn once, in development, that `foreignReports: \"drop\"` was asked for\n * without the `getPrincipal` it needs.\n *\n * Without a principal the only identity is the token fingerprint, which a\n * refresh changes, so the reporter cannot tell a foreign report from the\n * user's own and sends them anonymously instead of dropping them. The option\n * type-checks either way, so nothing else would tell the app its privacy\n * choice is not in force.\n *\n * @param options - The reporter's options.\n */\nfunction warnOnDropWithoutPrincipal(options: CreateAppErrorReporterOptions): void {\n if (warnedDropWithoutPrincipal || options.foreignReports !== \"drop\") return;\n if (options.getPrincipal !== undefined || !isDevBuild()) return;\n warnedDropWithoutPrincipal = true;\n console.warn(\n '[tempest-react-sdk] createAppErrorReporter({ foreignReports: \"drop\" }) needs ' +\n \"`getPrincipal`: without it the reporter cannot prove a queued report belongs \" +\n \"to someone else, so it drops nothing and those reports go out anonymously. \" +\n 'Pass `getPrincipal` to make \"drop\" take effect.',\n );\n}\n\n/**\n * Pick the default store, guarding hosts where touching `localStorage` throws.\n *\n * @returns `localStorage`, or `null` when there is none.\n */\nfunction defaultStorage(): AppErrorQueueStorage | null {\n try {\n return typeof localStorage === \"undefined\" ? null : localStorage;\n } catch {\n return null;\n }\n}\n\n/**\n * Read the device facts, reporting without them when the getter throws.\n *\n * @param device - The caller's getter.\n * @returns The facts, or an empty object.\n */\nfunction readDevice(device: CreateAppErrorReporterOptions[\"device\"]): AppErrorDeviceSchema {\n try {\n return device?.() ?? {};\n } catch {\n return {};\n }\n}\n\n/**\n * Fingerprint whoever `getPrincipal` says is signed in.\n *\n * @param getPrincipal - The app's principal getter.\n * @returns The owner, or `null` when nobody is signed in or the getter throws.\n */\nfunction principalOwner(getPrincipal: () => unknown): string | null {\n try {\n return ownerFingerprint(\"p\", getPrincipal());\n } catch {\n return null;\n }\n}\n\n/**\n * Stamp a report being raised now with its session and, when given, principal.\n *\n * @param getPrincipal - The app's principal getter, read synchronously.\n * @param token - The token read now, or a promise of it.\n * @returns The stamp, or a promise of it when the token is still arriving.\n */\nfunction stampNow(\n getPrincipal: CreateAppErrorReporterOptions[\"getPrincipal\"],\n token: string | null | Promise<string | null>,\n): AppErrorStamp | Promise<AppErrorStamp> {\n const owner = getPrincipal ? { owner: principalOwner(getPrincipal) } : {};\n if (typeof token === \"string\" || token === null) {\n return { session: ownerFingerprint(\"t\", token), ...owner };\n }\n return token.then((value) => ({ session: ownerFingerprint(\"t\", value), ...owner }));\n}\n\n/**\n * Report client errors to a Tempest backend's `POST /api/app-errors`, surviving\n * the offline stretches where field errors actually happen.\n *\n * The client half of `tempest-fastapi-sdk`'s `app_errors` module. An error is\n * described ({@link describeAppError}), stamped with the device facts of that\n * moment, fitted to the backend's column limits and queued in `localStorage`\n * before anything goes over the network — so a report raised with no signal is\n * sent when the browser comes back `online`, not lost.\n *\n * What each answer does to the queue:\n *\n * - **2xx** — removed.\n * - **429** — kept; sending pauses for `Retry-After`, then resumes on its own.\n * - **5xx, 408, network failure** — kept; the next report, `online` event or\n * `flush()` retries.\n * - **any other 4xx** — dropped: the backend will refuse that body forever, and\n * keeping it would block every report queued behind it.\n *\n * Each report is stamped with a one-way fingerprint of the token in force when\n * it was raised, and goes out with a bearer only when the token at send time is\n * that same one — never with the token of whoever signed in next. The queue\n * never stores a token. `clear()` also stops a flush in flight and discards\n * reports still waiting for an async token.\n *\n * @example\n * import { createAppErrorReporter } from \"tempest-react-sdk\";\n *\n * const reporter = createAppErrorReporter({\n * endpoint: `${import.meta.env.VITE_API_URL}/api/app-errors`,\n * getToken: () => sessionStorage.getItem(\"access_token\"),\n * device: () => ({ platform: \"web\", app_version: \"1.4.0\" }),\n * });\n *\n * reporter.report(new Error(\"crop failed\"), { step: \"crop\", size: 0 });\n *\n * @param options - Endpoint, token and device getters, storage and limits.\n * @returns The reporter.\n */\nexport function createAppErrorReporter(options: CreateAppErrorReporterOptions): AppErrorReporter {\n const { endpoint, getToken, getPrincipal, device, autoFlush = true } = options;\n warnOnDropWithoutPrincipal(options);\n const strict = getPrincipal !== undefined && options.foreignReports === \"drop\";\n const queue = createAppErrorQueue(\n options.storage === undefined ? defaultStorage() : options.storage,\n options.storageKey ?? \"tempest:app-errors\",\n options.maxEntries ?? 50,\n );\n let running: Promise<AppErrorFlushResult> | null = null;\n let pausedUntil = 0;\n let timer: ReturnType<typeof setTimeout> | null = null;\n const stamping = new Set<Promise<void>>();\n let generation = 0;\n\n const drain = async (): Promise<AppErrorFlushResult> => {\n const send = options.fetch ?? globalThis.fetch.bind(globalThis);\n await Promise.all(stamping);\n const token = await readToken(getToken);\n const session = ownerFingerprint(\"t\", token);\n const current = getPrincipal ? principalOwner(getPrincipal) : null;\n const started = generation;\n const result: AppErrorFlushResult = { sent: 0, dropped: 0, pending: 0, retryAfterMs: null };\n for (const entry of queue.entries()) {\n if (!queue.has(entry)) continue;\n if (strict && (entry.owner == null || entry.owner !== current)) {\n queue.remove(entry);\n result.dropped += 1;\n continue;\n }\n const bearer = entry.session != null && entry.session === session ? token : null;\n const outcome = await sendOne(send, endpoint, bearer, entry);\n if (generation !== started) break;\n if (outcome.kind === \"stop\") break;\n if (outcome.kind === \"wait\") {\n result.retryAfterMs = outcome.ms;\n pausedUntil = Date.now() + outcome.ms;\n timer ??= setTimeout(() => {\n timer = null;\n void flush();\n }, outcome.ms);\n break;\n }\n queue.remove(entry);\n result[outcome.kind === \"sent\" ? \"sent\" : \"dropped\"] += 1;\n }\n result.pending = queue.entries().length;\n return result;\n };\n\n const flush = (): Promise<AppErrorFlushResult> => {\n running ??= drain().finally(() => {\n running = null;\n });\n return running;\n };\n\n const shouldSend = (): boolean =>\n autoFlush &&\n Date.now() >= pausedUntil &&\n (typeof navigator === \"undefined\" || navigator.onLine !== false);\n\n const onOnline = (): void => {\n if (shouldSend()) void flush();\n };\n if (autoFlush && typeof window !== \"undefined\") window.addEventListener(\"online\", onOnline);\n\n return {\n report(error, context) {\n const description = describeAppError(error, context);\n const report = fitAppErrorReport({ ...readDevice(device), ...description });\n const stamp = stampNow(getPrincipal, readToken(getToken));\n if (!(stamp instanceof Promise)) {\n queue.push(report, stamp);\n if (shouldSend()) void flush();\n return;\n }\n const raisedIn = generation;\n const stamped = stamp.then((value) => {\n stamping.delete(stamped);\n if (generation !== raisedIn) return;\n queue.push(report, value);\n if (shouldSend()) void flush();\n });\n stamping.add(stamped);\n },\n flush,\n pending: () => queue.entries(),\n clear() {\n generation += 1;\n queue.clear();\n },\n dispose() {\n if (typeof window !== \"undefined\") window.removeEventListener(\"online\", onOnline);\n if (timer) clearTimeout(timer);\n timer = null;\n },\n };\n}\n"],"mappings":"yOAkHA,IAAI,EAA6B,GAsBjC,SAAS,EAA2B,EAA8C,CAC1E,GAA8B,EAAQ,iBAAmB,QACzD,EAAQ,eAAiB,IAAA,IAAc,EAAA,WAAW,IACtD,EAA6B,GAC7B,QAAQ,KACJ,sRAIJ,EACJ,CAOA,SAAS,GAA8C,CACnD,GAAI,CACA,OAAO,OAAO,aAAiB,IAAc,KAAO,YACxD,MAAQ,CACJ,OAAO,IACX,CACJ,CAQA,SAAS,EAAW,EAAuE,CACvF,GAAI,CACA,OAAO,IAAS,GAAK,CAAC,CAC1B,MAAQ,CACJ,MAAO,CAAC,CACZ,CACJ,CAQA,SAAS,EAAe,EAA4C,CAChE,GAAI,CACA,OAAO,EAAA,iBAAiB,IAAK,EAAa,CAAC,CAC/C,MAAQ,CACJ,OAAO,IACX,CACJ,CASA,SAAS,EACL,EACA,EACsC,CACtC,IAAM,EAAQ,EAAe,CAAE,MAAO,EAAe,CAAY,CAAE,EAAI,CAAC,E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|
|
1
1
|
import { isDevBuild as e } from "../utils/dev-mode.js";
|
|
2
|
-
import {
|
|
2
|
+
import { ownerFingerprint as t } from "../utils/owner-fingerprint.js";
|
|
3
3
|
import { createAppErrorQueue as n } from "./app-error-queue.js";
|
|
4
4
|
import { fitAppErrorReport as r } from "./app-error-schema.js";
|
|
5
5
|
import { readToken as i, sendOne as a } from "./app-error-transport.js";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"app-error-reporter.js","names":[],"sources":["../../src/telemetry/app-error-reporter.ts"],"sourcesContent":["import { appErrorOwner } from \"./app-error-owner\";\nimport { createAppErrorQueue } from \"./app-error-queue\";\nimport type { AppErrorQueueEntry, AppErrorQueueStorage, AppErrorStamp } from \"./app-error-queue\";\nimport { fitAppErrorReport } from \"./app-error-schema\";\nimport type { AppErrorDeviceSchema } from \"./app-error-schema\";\nimport { readToken, sendOne } from \"./app-error-transport\";\nimport { describeAppError } from \"./describe-app-error\";\nimport { isDevBuild } from \"../utils/dev-mode\";\n\n/** Options for {@link createAppErrorReporter}. */\nexport interface CreateAppErrorReporterOptions {\n /** Full URL of the backend route, e.g. `${API_URL}/api/app-errors`. */\n endpoint: string;\n /**\n * Current access token, if any. Optional on purpose: the route is public,\n * and an error raised before login — or with a stale session — still has\n * to get through. A token that throws or resolves empty sends anonymously.\n */\n getToken?: () => string | null | undefined | Promise<string | null | undefined>;\n /**\n * Who is signed in right now — a stable, non-secret id such as the user id.\n * Read **when the error is reported**, and stored in the queue only as a\n * one-way fingerprint (`entry.owner`). A non-string (an `async` getter\n * from untyped JS, an object) or a getter that throws reads as nobody.\n *\n * It never grants the bearer. The bearer goes out only when the token at\n * send time is the very token that was in force at report time (its\n * fingerprint is `entry.session`): the principal and the token come from\n * two sources, and a principal store that lags behind a login would\n * otherwise send A's report with B's token. The principal only tells\n * {@link CreateAppErrorReporterOptions.foreignReports} `\"drop\"` whose\n * report is whose.\n */\n getPrincipal?: () => string | number | null | undefined;\n /**\n * What to do with a queued report that cannot go out with the current\n * bearer — raised under another token, or queued before 0.77.0. Default\n * `\"anonymous\"`.\n *\n * - `\"anonymous\"` — send it without `Authorization`. The route is public,\n * so the error still reaches the backend; it is only not attributed to\n * anybody. This includes the user's own reports raised before a token\n * refresh: attribution is lost, never misplaced.\n * - `\"drop\"` — discard every report not proven to be the current\n * principal's: another principal, nobody, or unknown (no principal at\n * report time, a legacy entry, or nobody signed in now). For apps where\n * a previous user's error text must not leave the device after they\n * signed out. **Needs `getPrincipal`**: without it the only identity is\n * the token fingerprint, and a refresh changes it, so a mismatch is no\n * proof the report is someone else's — the reporter then sends\n * anonymously instead of destroying the user's own reports.\n *\n * Never is a report sent with a bearer other than the one it was raised\n * under: that would credit the previous user's error to whoever signed in\n * next.\n */\n foreignReports?: \"anonymous\" | \"drop\";\n /**\n * Device facts, read **when the error is reported**, not when it is sent —\n * a report queued offline on `1.4.0` must not go out labelled `1.5.0`.\n */\n device?: () => AppErrorDeviceSchema;\n /** Where the queue persists. Defaults to `localStorage`; `null` keeps it in memory. */\n storage?: AppErrorQueueStorage | null;\n /** Storage key. Default `\"tempest:app-errors\"`. */\n storageKey?: string;\n /** Ceiling on distinct waiting reports; the oldest is evicted. Default `50`. */\n maxEntries?: number;\n /** `fetch` to send with. Defaults to the global one. */\n fetch?: typeof fetch;\n /** Send on every report and when the browser goes `online`. Default `true`. */\n autoFlush?: boolean;\n}\n\n/** What one {@link AppErrorReporter.flush} did. */\nexport interface AppErrorFlushResult {\n /** Reports the backend accepted. */\n sent: number;\n /** Reports the backend refused for good (a 4xx other than 408/429) and were dropped. */\n dropped: number;\n /** Reports still waiting. */\n pending: number;\n /** Milliseconds the backend asked to wait (429 `Retry-After`), or `null`. */\n retryAfterMs: number | null;\n}\n\n/** The reporter {@link createAppErrorReporter} returns. */\nexport interface AppErrorReporter {\n /** Queue an error with optional context, and try to send it. Never throws. */\n report: (error: unknown, context?: Record<string, unknown>) => void;\n /** Drain the queue now. Concurrent calls share one run. */\n flush: () => Promise<AppErrorFlushResult>;\n /**\n * The waiting entries, oldest first. With an async `getToken` and no\n * `getPrincipal`, a report joins them once its token resolves — `flush()`\n * waits for that, `pending()` does not.\n */\n pending: () => AppErrorQueueEntry[];\n /**\n * Drop every waiting report. Call it on logout when reports raised in that\n * session should not outlive it; even without it, a report never leaves\n * with the next user's bearer.\n *\n * It also stops a flush in flight before its next send (the one already on\n * the wire cannot be recalled), and discards reports still waiting for an\n * async `getToken` to stamp them — both would otherwise refill the queue or\n * keep sending what the logout meant to forget.\n */\n clear: () => void;\n /** Remove the `online` listener and the retry timer. */\n dispose: () => void;\n}\n\n/** Set once the warning has printed, so every reporter built after it stays quiet. */\nlet warnedDropWithoutPrincipal = false;\n\n/**\n * Reset the warn-once latch. Test-only: the latch is module state, so a suite\n * asserting the warning more than once would otherwise see it only the first time.\n */\nexport function resetDropWithoutPrincipalWarning(): void {\n warnedDropWithoutPrincipal = false;\n}\n\n/**\n * Warn once, in development, that `foreignReports: \"drop\"` was asked for\n * without the `getPrincipal` it needs.\n *\n * Without a principal the only identity is the token fingerprint, which a\n * refresh changes, so the reporter cannot tell a foreign report from the\n * user's own and sends them anonymously instead of dropping them. The option\n * type-checks either way, so nothing else would tell the app its privacy\n * choice is not in force.\n *\n * @param options - The reporter's options.\n */\nfunction warnOnDropWithoutPrincipal(options: CreateAppErrorReporterOptions): void {\n if (warnedDropWithoutPrincipal || options.foreignReports !== \"drop\") return;\n if (options.getPrincipal !== undefined || !isDevBuild()) return;\n warnedDropWithoutPrincipal = true;\n console.warn(\n '[tempest-react-sdk] createAppErrorReporter({ foreignReports: \"drop\" }) needs ' +\n \"`getPrincipal`: without it the reporter cannot prove a queued report belongs \" +\n \"to someone else, so it drops nothing and those reports go out anonymously. \" +\n 'Pass `getPrincipal` to make \"drop\" take effect.',\n );\n}\n\n/**\n * Pick the default store, guarding hosts where touching `localStorage` throws.\n *\n * @returns `localStorage`, or `null` when there is none.\n */\nfunction defaultStorage(): AppErrorQueueStorage | null {\n try {\n return typeof localStorage === \"undefined\" ? null : localStorage;\n } catch {\n return null;\n }\n}\n\n/**\n * Read the device facts, reporting without them when the getter throws.\n *\n * @param device - The caller's getter.\n * @returns The facts, or an empty object.\n */\nfunction readDevice(device: CreateAppErrorReporterOptions[\"device\"]): AppErrorDeviceSchema {\n try {\n return device?.() ?? {};\n } catch {\n return {};\n }\n}\n\n/**\n * Fingerprint whoever `getPrincipal` says is signed in.\n *\n * @param getPrincipal - The app's principal getter.\n * @returns The owner, or `null` when nobody is signed in or the getter throws.\n */\nfunction principalOwner(getPrincipal: () => unknown): string | null {\n try {\n return appErrorOwner(\"p\", getPrincipal());\n } catch {\n return null;\n }\n}\n\n/**\n * Stamp a report being raised now with its session and, when given, principal.\n *\n * @param getPrincipal - The app's principal getter, read synchronously.\n * @param token - The token read now, or a promise of it.\n * @returns The stamp, or a promise of it when the token is still arriving.\n */\nfunction stampNow(\n getPrincipal: CreateAppErrorReporterOptions[\"getPrincipal\"],\n token: string | null | Promise<string | null>,\n): AppErrorStamp | Promise<AppErrorStamp> {\n const owner = getPrincipal ? { owner: principalOwner(getPrincipal) } : {};\n if (typeof token === \"string\" || token === null) {\n return { session: appErrorOwner(\"t\", token), ...owner };\n }\n return token.then((value) => ({ session: appErrorOwner(\"t\", value), ...owner }));\n}\n\n/**\n * Report client errors to a Tempest backend's `POST /api/app-errors`, surviving\n * the offline stretches where field errors actually happen.\n *\n * The client half of `tempest-fastapi-sdk`'s `app_errors` module. An error is\n * described ({@link describeAppError}), stamped with the device facts of that\n * moment, fitted to the backend's column limits and queued in `localStorage`\n * before anything goes over the network — so a report raised with no signal is\n * sent when the browser comes back `online`, not lost.\n *\n * What each answer does to the queue:\n *\n * - **2xx** — removed.\n * - **429** — kept; sending pauses for `Retry-After`, then resumes on its own.\n * - **5xx, 408, network failure** — kept; the next report, `online` event or\n * `flush()` retries.\n * - **any other 4xx** — dropped: the backend will refuse that body forever, and\n * keeping it would block every report queued behind it.\n *\n * Each report is stamped with a one-way fingerprint of the token in force when\n * it was raised, and goes out with a bearer only when the token at send time is\n * that same one — never with the token of whoever signed in next. The queue\n * never stores a token. `clear()` also stops a flush in flight and discards\n * reports still waiting for an async token.\n *\n * @example\n * import { createAppErrorReporter } from \"tempest-react-sdk\";\n *\n * const reporter = createAppErrorReporter({\n * endpoint: `${import.meta.env.VITE_API_URL}/api/app-errors`,\n * getToken: () => sessionStorage.getItem(\"access_token\"),\n * device: () => ({ platform: \"web\", app_version: \"1.4.0\" }),\n * });\n *\n * reporter.report(new Error(\"crop failed\"), { step: \"crop\", size: 0 });\n *\n * @param options - Endpoint, token and device getters, storage and limits.\n * @returns The reporter.\n */\nexport function createAppErrorReporter(options: CreateAppErrorReporterOptions): AppErrorReporter {\n const { endpoint, getToken, getPrincipal, device, autoFlush = true } = options;\n warnOnDropWithoutPrincipal(options);\n const strict = getPrincipal !== undefined && options.foreignReports === \"drop\";\n const queue = createAppErrorQueue(\n options.storage === undefined ? defaultStorage() : options.storage,\n options.storageKey ?? \"tempest:app-errors\",\n options.maxEntries ?? 50,\n );\n let running: Promise<AppErrorFlushResult> | null = null;\n let pausedUntil = 0;\n let timer: ReturnType<typeof setTimeout> | null = null;\n const stamping = new Set<Promise<void>>();\n let generation = 0;\n\n const drain = async (): Promise<AppErrorFlushResult> => {\n const send = options.fetch ?? globalThis.fetch.bind(globalThis);\n await Promise.all(stamping);\n const token = await readToken(getToken);\n const session = appErrorOwner(\"t\", token);\n const current = getPrincipal ? principalOwner(getPrincipal) : null;\n const started = generation;\n const result: AppErrorFlushResult = { sent: 0, dropped: 0, pending: 0, retryAfterMs: null };\n for (const entry of queue.entries()) {\n if (!queue.has(entry)) continue;\n if (strict && (entry.owner == null || entry.owner !== current)) {\n queue.remove(entry);\n result.dropped += 1;\n continue;\n }\n const bearer = entry.session != null && entry.session === session ? token : null;\n const outcome = await sendOne(send, endpoint, bearer, entry);\n if (generation !== started) break;\n if (outcome.kind === \"stop\") break;\n if (outcome.kind === \"wait\") {\n result.retryAfterMs = outcome.ms;\n pausedUntil = Date.now() + outcome.ms;\n timer ??= setTimeout(() => {\n timer = null;\n void flush();\n }, outcome.ms);\n break;\n }\n queue.remove(entry);\n result[outcome.kind === \"sent\" ? \"sent\" : \"dropped\"] += 1;\n }\n result.pending = queue.entries().length;\n return result;\n };\n\n const flush = (): Promise<AppErrorFlushResult> => {\n running ??= drain().finally(() => {\n running = null;\n });\n return running;\n };\n\n const shouldSend = (): boolean =>\n autoFlush &&\n Date.now() >= pausedUntil &&\n (typeof navigator === \"undefined\" || navigator.onLine !== false);\n\n const onOnline = (): void => {\n if (shouldSend()) void flush();\n };\n if (autoFlush && typeof window !== \"undefined\") window.addEventListener(\"online\", onOnline);\n\n return {\n report(error, context) {\n const description = describeAppError(error, context);\n const report = fitAppErrorReport({ ...readDevice(device), ...description });\n const stamp = stampNow(getPrincipal, readToken(getToken));\n if (!(stamp instanceof Promise)) {\n queue.push(report, stamp);\n if (shouldSend()) void flush();\n return;\n }\n const raisedIn = generation;\n const stamped = stamp.then((value) => {\n stamping.delete(stamped);\n if (generation !== raisedIn) return;\n queue.push(report, value);\n if (shouldSend()) void flush();\n });\n stamping.add(stamped);\n },\n flush,\n pending: () => queue.entries(),\n clear() {\n generation += 1;\n queue.clear();\n },\n dispose() {\n if (typeof window !== \"undefined\") window.removeEventListener(\"online\", onOnline);\n if (timer) clearTimeout(timer);\n timer = null;\n },\n };\n}\n"],"mappings":";;;;;;;AAkHA,IAAI,IAA6B;AAsBjC,SAAS,EAA2B,GAA8C;CAC1E,KAA8B,EAAQ,mBAAmB,UACzD,EAAQ,iBAAiB,KAAA,KAAc,EAAW,MACtD,IAA6B,IAC7B,QAAQ,KACJ,0RAIJ;AACJ;AAOA,SAAS,IAA8C;CACnD,IAAI;EACA,OAAO,OAAO,eAAiB,MAAc,OAAO;CACxD,QAAQ;EACJ,OAAO;CACX;AACJ;AAQA,SAAS,EAAW,GAAuE;CACvF,IAAI;EACA,OAAO,IAAS,KAAK,CAAC;CAC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EACA;EACA,eAAe,EAAM,QAAQ;EAC7B,QAAQ;GAEJ,AADA,KAAc,GACd,EAAM,MAAM;EAChB;EACA,UAAU;GAGN,AAFI,OAAO,SAAW,OAAa,OAAO,oBAAoB,UAAU,CAAQ,GAC5E,KAAO,aAAa,CAAK,GAC7B,IAAQ;EACZ;CACJ;AACJ"}
|
|
1
|
+
{"version":3,"file":"app-error-reporter.js","names":[],"sources":["../../src/telemetry/app-error-reporter.ts"],"sourcesContent":["import { ownerFingerprint } from \"@/utils/owner-fingerprint\";\nimport { createAppErrorQueue } from \"./app-error-queue\";\nimport type { AppErrorQueueEntry, AppErrorQueueStorage, AppErrorStamp } from \"./app-error-queue\";\nimport { fitAppErrorReport } from \"./app-error-schema\";\nimport type { AppErrorDeviceSchema } from \"./app-error-schema\";\nimport { readToken, sendOne } from \"./app-error-transport\";\nimport { describeAppError } from \"./describe-app-error\";\nimport { isDevBuild } from \"../utils/dev-mode\";\n\n/** Options for {@link createAppErrorReporter}. */\nexport interface CreateAppErrorReporterOptions {\n /** Full URL of the backend route, e.g. `${API_URL}/api/app-errors`. */\n endpoint: string;\n /**\n * Current access token, if any. Optional on purpose: the route is public,\n * and an error raised before login — or with a stale session — still has\n * to get through. A token that throws or resolves empty sends anonymously.\n */\n getToken?: () => string | null | undefined | Promise<string | null | undefined>;\n /**\n * Who is signed in right now — a stable, non-secret id such as the user id.\n * Read **when the error is reported**, and stored in the queue only as a\n * one-way fingerprint (`entry.owner`). A non-string (an `async` getter\n * from untyped JS, an object) or a getter that throws reads as nobody.\n *\n * It never grants the bearer. The bearer goes out only when the token at\n * send time is the very token that was in force at report time (its\n * fingerprint is `entry.session`): the principal and the token come from\n * two sources, and a principal store that lags behind a login would\n * otherwise send A's report with B's token. The principal only tells\n * {@link CreateAppErrorReporterOptions.foreignReports} `\"drop\"` whose\n * report is whose.\n */\n getPrincipal?: () => string | number | null | undefined;\n /**\n * What to do with a queued report that cannot go out with the current\n * bearer — raised under another token, or queued before 0.77.0. Default\n * `\"anonymous\"`.\n *\n * - `\"anonymous\"` — send it without `Authorization`. The route is public,\n * so the error still reaches the backend; it is only not attributed to\n * anybody. This includes the user's own reports raised before a token\n * refresh: attribution is lost, never misplaced.\n * - `\"drop\"` — discard every report not proven to be the current\n * principal's: another principal, nobody, or unknown (no principal at\n * report time, a legacy entry, or nobody signed in now). For apps where\n * a previous user's error text must not leave the device after they\n * signed out. **Needs `getPrincipal`**: without it the only identity is\n * the token fingerprint, and a refresh changes it, so a mismatch is no\n * proof the report is someone else's — the reporter then sends\n * anonymously instead of destroying the user's own reports.\n *\n * Never is a report sent with a bearer other than the one it was raised\n * under: that would credit the previous user's error to whoever signed in\n * next.\n */\n foreignReports?: \"anonymous\" | \"drop\";\n /**\n * Device facts, read **when the error is reported**, not when it is sent —\n * a report queued offline on `1.4.0` must not go out labelled `1.5.0`.\n */\n device?: () => AppErrorDeviceSchema;\n /** Where the queue persists. Defaults to `localStorage`; `null` keeps it in memory. */\n storage?: AppErrorQueueStorage | null;\n /** Storage key. Default `\"tempest:app-errors\"`. */\n storageKey?: string;\n /** Ceiling on distinct waiting reports; the oldest is evicted. Default `50`. */\n maxEntries?: number;\n /** `fetch` to send with. Defaults to the global one. */\n fetch?: typeof fetch;\n /** Send on every report and when the browser goes `online`. Default `true`. */\n autoFlush?: boolean;\n}\n\n/** What one {@link AppErrorReporter.flush} did. */\nexport interface AppErrorFlushResult {\n /** Reports the backend accepted. */\n sent: number;\n /** Reports the backend refused for good (a 4xx other than 408/429) and were dropped. */\n dropped: number;\n /** Reports still waiting. */\n pending: number;\n /** Milliseconds the backend asked to wait (429 `Retry-After`), or `null`. */\n retryAfterMs: number | null;\n}\n\n/** The reporter {@link createAppErrorReporter} returns. */\nexport interface AppErrorReporter {\n /** Queue an error with optional context, and try to send it. Never throws. */\n report: (error: unknown, context?: Record<string, unknown>) => void;\n /** Drain the queue now. Concurrent calls share one run. */\n flush: () => Promise<AppErrorFlushResult>;\n /**\n * The waiting entries, oldest first. With an async `getToken` and no\n * `getPrincipal`, a report joins them once its token resolves — `flush()`\n * waits for that, `pending()` does not.\n */\n pending: () => AppErrorQueueEntry[];\n /**\n * Drop every waiting report. Call it on logout when reports raised in that\n * session should not outlive it; even without it, a report never leaves\n * with the next user's bearer.\n *\n * It also stops a flush in flight before its next send (the one already on\n * the wire cannot be recalled), and discards reports still waiting for an\n * async `getToken` to stamp them — both would otherwise refill the queue or\n * keep sending what the logout meant to forget.\n */\n clear: () => void;\n /** Remove the `online` listener and the retry timer. */\n dispose: () => void;\n}\n\n/** Set once the warning has printed, so every reporter built after it stays quiet. */\nlet warnedDropWithoutPrincipal = false;\n\n/**\n * Reset the warn-once latch. Test-only: the latch is module state, so a suite\n * asserting the warning more than once would otherwise see it only the first time.\n */\nexport function resetDropWithoutPrincipalWarning(): void {\n warnedDropWithoutPrincipal = false;\n}\n\n/**\n * Warn once, in development, that `foreignReports: \"drop\"` was asked for\n * without the `getPrincipal` it needs.\n *\n * Without a principal the only identity is the token fingerprint, which a\n * refresh changes, so the reporter cannot tell a foreign report from the\n * user's own and sends them anonymously instead of dropping them. The option\n * type-checks either way, so nothing else would tell the app its privacy\n * choice is not in force.\n *\n * @param options - The reporter's options.\n */\nfunction warnOnDropWithoutPrincipal(options: CreateAppErrorReporterOptions): void {\n if (warnedDropWithoutPrincipal || options.foreignReports !== \"drop\") return;\n if (options.getPrincipal !== undefined || !isDevBuild()) return;\n warnedDropWithoutPrincipal = true;\n console.warn(\n '[tempest-react-sdk] createAppErrorReporter({ foreignReports: \"drop\" }) needs ' +\n \"`getPrincipal`: without it the reporter cannot prove a queued report belongs \" +\n \"to someone else, so it drops nothing and those reports go out anonymously. \" +\n 'Pass `getPrincipal` to make \"drop\" take effect.',\n );\n}\n\n/**\n * Pick the default store, guarding hosts where touching `localStorage` throws.\n *\n * @returns `localStorage`, or `null` when there is none.\n */\nfunction defaultStorage(): AppErrorQueueStorage | null {\n try {\n return typeof localStorage === \"undefined\" ? null : localStorage;\n } catch {\n return null;\n }\n}\n\n/**\n * Read the device facts, reporting without them when the getter throws.\n *\n * @param device - The caller's getter.\n * @returns The facts, or an empty object.\n */\nfunction readDevice(device: CreateAppErrorReporterOptions[\"device\"]): AppErrorDeviceSchema {\n try {\n return device?.() ?? {};\n } catch {\n return {};\n }\n}\n\n/**\n * Fingerprint whoever `getPrincipal` says is signed in.\n *\n * @param getPrincipal - The app's principal getter.\n * @returns The owner, or `null` when nobody is signed in or the getter throws.\n */\nfunction principalOwner(getPrincipal: () => unknown): string | null {\n try {\n return ownerFingerprint(\"p\", getPrincipal());\n } catch {\n return null;\n }\n}\n\n/**\n * Stamp a report being raised now with its session and, when given, principal.\n *\n * @param getPrincipal - The app's principal getter, read synchronously.\n * @param token - The token read now, or a promise of it.\n * @returns The stamp, or a promise of it when the token is still arriving.\n */\nfunction stampNow(\n getPrincipal: CreateAppErrorReporterOptions[\"getPrincipal\"],\n token: string | null | Promise<string | null>,\n): AppErrorStamp | Promise<AppErrorStamp> {\n const owner = getPrincipal ? { owner: principalOwner(getPrincipal) } : {};\n if (typeof token === \"string\" || token === null) {\n return { session: ownerFingerprint(\"t\", token), ...owner };\n }\n return token.then((value) => ({ session: ownerFingerprint(\"t\", value), ...owner }));\n}\n\n/**\n * Report client errors to a Tempest backend's `POST /api/app-errors`, surviving\n * the offline stretches where field errors actually happen.\n *\n * The client half of `tempest-fastapi-sdk`'s `app_errors` module. An error is\n * described ({@link describeAppError}), stamped with the device facts of that\n * moment, fitted to the backend's column limits and queued in `localStorage`\n * before anything goes over the network — so a report raised with no signal is\n * sent when the browser comes back `online`, not lost.\n *\n * What each answer does to the queue:\n *\n * - **2xx** — removed.\n * - **429** — kept; sending pauses for `Retry-After`, then resumes on its own.\n * - **5xx, 408, network failure** — kept; the next report, `online` event or\n * `flush()` retries.\n * - **any other 4xx** — dropped: the backend will refuse that body forever, and\n * keeping it would block every report queued behind it.\n *\n * Each report is stamped with a one-way fingerprint of the token in force when\n * it was raised, and goes out with a bearer only when the token at send time is\n * that same one — never with the token of whoever signed in next. The queue\n * never stores a token. `clear()` also stops a flush in flight and discards\n * reports still waiting for an async token.\n *\n * @example\n * import { createAppErrorReporter } from \"tempest-react-sdk\";\n *\n * const reporter = createAppErrorReporter({\n * endpoint: `${import.meta.env.VITE_API_URL}/api/app-errors`,\n * getToken: () => sessionStorage.getItem(\"access_token\"),\n * device: () => ({ platform: \"web\", app_version: \"1.4.0\" }),\n * });\n *\n * reporter.report(new Error(\"crop failed\"), { step: \"crop\", size: 0 });\n *\n * @param options - Endpoint, token and device getters, storage and limits.\n * @returns The reporter.\n */\nexport function createAppErrorReporter(options: CreateAppErrorReporterOptions): AppErrorReporter {\n const { endpoint, getToken, getPrincipal, device, autoFlush = true } = options;\n warnOnDropWithoutPrincipal(options);\n const strict = getPrincipal !== undefined && options.foreignReports === \"drop\";\n const queue = createAppErrorQueue(\n options.storage === undefined ? defaultStorage() : options.storage,\n options.storageKey ?? \"tempest:app-errors\",\n options.maxEntries ?? 50,\n );\n let running: Promise<AppErrorFlushResult> | null = null;\n let pausedUntil = 0;\n let timer: ReturnType<typeof setTimeout> | null = null;\n const stamping = new Set<Promise<void>>();\n let generation = 0;\n\n const drain = async (): Promise<AppErrorFlushResult> => {\n const send = options.fetch ?? globalThis.fetch.bind(globalThis);\n await Promise.all(stamping);\n const token = await readToken(getToken);\n const session = ownerFingerprint(\"t\", token);\n const current = getPrincipal ? principalOwner(getPrincipal) : null;\n const started = generation;\n const result: AppErrorFlushResult = { sent: 0, dropped: 0, pending: 0, retryAfterMs: null };\n for (const entry of queue.entries()) {\n if (!queue.has(entry)) continue;\n if (strict && (entry.owner == null || entry.owner !== current)) {\n queue.remove(entry);\n result.dropped += 1;\n continue;\n }\n const bearer = entry.session != null && entry.session === session ? token : null;\n const outcome = await sendOne(send, endpoint, bearer, entry);\n if (generation !== started) break;\n if (outcome.kind === \"stop\") break;\n if (outcome.kind === \"wait\") {\n result.retryAfterMs = outcome.ms;\n pausedUntil = Date.now() + outcome.ms;\n timer ??= setTimeout(() => {\n timer = null;\n void flush();\n }, outcome.ms);\n break;\n }\n queue.remove(entry);\n result[outcome.kind === \"sent\" ? \"sent\" : \"dropped\"] += 1;\n }\n result.pending = queue.entries().length;\n return result;\n };\n\n const flush = (): Promise<AppErrorFlushResult> => {\n running ??= drain().finally(() => {\n running = null;\n });\n return running;\n };\n\n const shouldSend = (): boolean =>\n autoFlush &&\n Date.now() >= pausedUntil &&\n (typeof navigator === \"undefined\" || navigator.onLine !== false);\n\n const onOnline = (): void => {\n if (shouldSend()) void flush();\n };\n if (autoFlush && typeof window !== \"undefined\") window.addEventListener(\"online\", onOnline);\n\n return {\n report(error, context) {\n const description = describeAppError(error, context);\n const report = fitAppErrorReport({ ...readDevice(device), ...description });\n const stamp = stampNow(getPrincipal, readToken(getToken));\n if (!(stamp instanceof Promise)) {\n queue.push(report, stamp);\n if (shouldSend()) void flush();\n return;\n }\n const raisedIn = generation;\n const stamped = stamp.then((value) => {\n stamping.delete(stamped);\n if (generation !== raisedIn) return;\n queue.push(report, value);\n if (shouldSend()) void flush();\n });\n stamping.add(stamped);\n },\n flush,\n pending: () => queue.entries(),\n clear() {\n generation += 1;\n queue.clear();\n },\n dispose() {\n if (typeof window !== \"undefined\") window.removeEventListener(\"online\", onOnline);\n if (timer) clearTimeout(timer);\n timer = null;\n },\n };\n}\n"],"mappings":";;;;;;;AAkHA,IAAI,IAA6B;AAsBjC,SAAS,EAA2B,GAA8C;CAC1E,KAA8B,EAAQ,mBAAmB,UACzD,EAAQ,iBAAiB,KAAA,KAAc,EAAW,MACtD,IAA6B,IAC7B,QAAQ,KACJ,0RAIJ;AACJ;AAOA,SAAS,IAA8C;CACnD,IAAI;EACA,OAAO,OAAO,eAAiB,MAAc,OAAO;CACxD,QAAQ;EACJ,OAAO;CACX;AACJ;AAQA,SAAS,EAAW,GAAuE;CACvF,IAAI;EACA,OAAO,IAAS,KAAK,CAAC;CAC1B,QAAQ;EACJ,OAAO,CAAC;CACZ;AACJ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