@abraca/resend 2.16.0 → 2.17.1
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/dist/abracadabra-resend.cjs +60 -24
- package/dist/abracadabra-resend.cjs.map +1 -1
- package/dist/abracadabra-resend.esm.js +60 -24
- package/dist/abracadabra-resend.esm.js.map +1 -1
- package/dist/index.d.ts +6 -1
- package/package.json +3 -3
- package/src/outbox-watcher.ts +96 -12
- package/src/server.ts +35 -19
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"abracadabra-resend.esm.js","names":["readEntry","u64.split","u64.rotrSH","u64.shrSH","u64.rotrSL","u64.shrSL","u64.rotrBH","u64.rotrBL","u64.add4L","u64.add4H","u64.add5L","u64.add5H","u64.add","u64.add3L","u64.add3H"],"sources":["../src/bootstrap.ts","../src/utils.ts","../src/inbound-server.ts","../src/render.ts","../src/outbox-watcher.ts","../src/resend-client.ts","../../../node_modules/@noble/hashes/utils.js","../../../node_modules/@noble/hashes/_md.js","../../../node_modules/@noble/hashes/_u64.js","../../../node_modules/@noble/hashes/sha2.js","../src/crypto.ts","../src/server.ts","../src/index.ts"],"sourcesContent":["/**\n * Find or create the Inbox + Outbox documents under the bound Space.\n *\n * Idempotent: any existing top-level doc labelled \"Inbox\" or \"Outbox\" is reused\n * as-is — the user is allowed to rename, recolor, or restructure these docs\n * after they're created. Missing columns under the Outbox kanban are filled in.\n */\nimport { makeEntryMap, toPlain } from \"@abraca/dabra\";\nimport * as Y from \"yjs\";\nimport type { AbracadabraResendServer } from \"./server.ts\";\n\nexport const INBOX_LABEL = \"Inbox\";\nexport const OUTBOX_LABEL = \"Outbox\";\n\nexport const OUTBOX_COLUMNS = [\"Draft\", \"Ready\", \"Sent\", \"Failed\"] as const;\nexport type OutboxColumn = (typeof OUTBOX_COLUMNS)[number];\n\nexport interface BootstrapResult {\n\tinboxId: string;\n\toutboxId: string;\n\tcolumns: Record<OutboxColumn, string>;\n}\n\ninterface TreeEntry {\n\tid: string;\n\tlabel: string;\n\tparentId: string | null;\n\torder: number;\n\ttype?: string;\n}\n\nfunction readEntries(\n\ttreeMap: Y.Map<any>,\n\tselfId: string | null,\n): TreeEntry[] {\n\tconst entries: TreeEntry[] = [];\n\ttreeMap.forEach((raw: any, id: string) => {\n\t\tif (selfId && id === selfId) return;\n\t\tconst value = toPlain(raw) as any;\n\t\tif (typeof value !== \"object\" || value === null) return;\n\t\tentries.push({\n\t\t\tid,\n\t\t\tlabel: typeof value.label === \"string\" ? value.label : \"Untitled\",\n\t\t\tparentId: value.parentId ?? null,\n\t\t\torder: typeof value.order === \"number\" ? value.order : 0,\n\t\t\ttype: typeof value.type === \"string\" ? value.type : undefined,\n\t\t});\n\t});\n\treturn entries;\n}\n\nasync function createDoc(\n\tserver: AbracadabraResendServer,\n\topts: {\n\t\tparentTreeId: string | null;\n\t\trestParentId: string;\n\t\tlabel: string;\n\t\ttype?: string;\n\t\tmeta?: Record<string, unknown>;\n\t\torder?: number;\n\t},\n): Promise<string> {\n\tconst treeMap = server.getTreeMap();\n\tconst rootDoc = server.rootDocument;\n\tif (!treeMap || !rootDoc) {\n\t\tthrow new Error(\"Cannot create doc — server is not connected.\");\n\t}\n\tconst id = crypto.randomUUID();\n\tconst now = Date.now();\n\n\t// Register the SQL row first so RBAC inheritance can walk\n\t// `documents.parent_id` (matches @abraca/mcp's create_document path).\n\tawait server.client.createChild(opts.restParentId, {\n\t\tchild_id: id,\n\t\tlabel: opts.label,\n\t\tdoc_type: opts.type,\n\t\tkind: \"page\",\n\t});\n\n\trootDoc.transact(() => {\n\t\ttreeMap.set(\n\t\t\tid,\n\t\t\tmakeEntryMap({\n\t\t\t\tlabel: opts.label,\n\t\t\t\tparentId: opts.parentTreeId,\n\t\t\t\torder: opts.order ?? now,\n\t\t\t\ttype: opts.type,\n\t\t\t\tmeta: opts.meta as any,\n\t\t\t\tcreatedAt: now,\n\t\t\t\tupdatedAt: now,\n\t\t\t}),\n\t\t);\n\t});\n\n\treturn id;\n}\n\nexport async function bootstrap(\n\tserver: AbracadabraResendServer,\n): Promise<BootstrapResult> {\n\tconst treeMap = server.getTreeMap();\n\tconst spaceDocId = server.spaceDocId;\n\tif (!treeMap || !spaceDocId) {\n\t\tthrow new Error(\"Cannot bootstrap — server is not connected.\");\n\t}\n\tconst entries = readEntries(treeMap, spaceDocId);\n\n\tconst topLevel = entries.filter((e) => e.parentId === null);\n\tconst existingInbox = topLevel.find(\n\t\t(e) => e.label.trim().toLowerCase() === INBOX_LABEL.toLowerCase(),\n\t);\n\tconst existingOutbox = topLevel.find(\n\t\t(e) => e.label.trim().toLowerCase() === OUTBOX_LABEL.toLowerCase(),\n\t);\n\n\t// ── Inbox ──────────────────────────────────────────────────────────────\n\tlet inboxId: string;\n\tif (existingInbox) {\n\t\tinboxId = existingInbox.id;\n\t\tconsole.error(\n\t\t\t`[abracadabra-resend] Inbox found: ${inboxId} (${existingInbox.label})`,\n\t\t);\n\t} else {\n\t\tinboxId = await createDoc(server, {\n\t\t\tparentTreeId: null,\n\t\t\trestParentId: spaceDocId,\n\t\t\tlabel: INBOX_LABEL,\n\t\t\ttype: \"gallery\",\n\t\t\tmeta: { icon: \"inbox\" },\n\t\t});\n\t\tconsole.error(`[abracadabra-resend] Inbox created: ${inboxId}`);\n\t}\n\n\t// ── Outbox ─────────────────────────────────────────────────────────────\n\tlet outboxId: string;\n\tif (existingOutbox) {\n\t\toutboxId = existingOutbox.id;\n\t\tconsole.error(\n\t\t\t`[abracadabra-resend] Outbox found: ${outboxId} (${existingOutbox.label})`,\n\t\t);\n\t} else {\n\t\toutboxId = await createDoc(server, {\n\t\t\tparentTreeId: null,\n\t\t\trestParentId: spaceDocId,\n\t\t\tlabel: OUTBOX_LABEL,\n\t\t\ttype: \"kanban\",\n\t\t\tmeta: { icon: \"send\" },\n\t\t});\n\t\tconsole.error(`[abracadabra-resend] Outbox created: ${outboxId}`);\n\t}\n\n\t// ── Outbox columns ─────────────────────────────────────────────────────\n\t// Re-read entries — we may have just created Inbox/Outbox.\n\tconst refreshedEntries = readEntries(treeMap, spaceDocId);\n\tconst existingColumns = refreshedEntries.filter(\n\t\t(e) => e.parentId === outboxId,\n\t);\n\n\tconst columns = {} as Record<OutboxColumn, string>;\n\tfor (const colLabel of OUTBOX_COLUMNS) {\n\t\tconst match = existingColumns.find(\n\t\t\t(e) => e.label.trim().toLowerCase() === colLabel.toLowerCase(),\n\t\t);\n\t\tif (match) {\n\t\t\tcolumns[colLabel] = match.id;\n\t\t\tcontinue;\n\t\t}\n\t\tconst id = await createDoc(server, {\n\t\t\tparentTreeId: outboxId,\n\t\t\trestParentId: outboxId,\n\t\t\tlabel: colLabel,\n\t\t\t// Kanban columns inherit view from the parent kanban — no type.\n\t\t\torder: Date.now() + OUTBOX_COLUMNS.indexOf(colLabel),\n\t\t});\n\t\tcolumns[colLabel] = id;\n\t\tconsole.error(\n\t\t\t`[abracadabra-resend] Outbox column \"${colLabel}\" created: ${id}`,\n\t\t);\n\t}\n\n\treturn { inboxId, outboxId, columns };\n}\n","/**\n * Wait for a provider's `synced` event with a timeout.\n *\n * The `isSynced` short-circuit is load-bearing: providers that already synced\n * (e.g. cached child providers returned from `loadChild`) won't re-emit\n * `synced`, so without the short-circuit every later op on that doc times out.\n */\nexport function waitForSync(\n\tprovider: {\n\t\tisSynced?: boolean;\n\t\ton(event: string, cb: () => void): void;\n\t\toff(event: string, cb: () => void): void;\n\t},\n\ttimeoutMs = 15000,\n): Promise<void> {\n\tif (provider.isSynced) return Promise.resolve();\n\n\treturn new Promise<void>((resolve, reject) => {\n\t\tconst timer = setTimeout(() => {\n\t\t\tprovider.off(\"synced\", handler);\n\t\t\treject(new Error(`Sync timed out after ${timeoutMs}ms`));\n\t\t}, timeoutMs);\n\n\t\tfunction handler() {\n\t\t\tclearTimeout(timer);\n\t\t\tprovider.off(\"synced\", handler);\n\t\t\tresolve();\n\t\t}\n\n\t\tprovider.on(\"synced\", handler);\n\t});\n}\n","/**\n * Inbound webhook HTTP server.\n *\n * Single POST route: `/inbound`. Verifies Svix signature, parses Resend Inbound\n * payload, creates a child doc under the Inbox, uploads attachments. Operator\n * is responsible for exposing the port publicly (tunnel / reverse proxy) and\n * configuring Resend Inbound to deliver here.\n */\nimport { makeEntryMap } from \"@abraca/dabra\";\nimport { populateYDocFromMarkdown as populateBody } from \"@abraca/convert\";\nimport { createHmac, timingSafeEqual } from \"node:crypto\";\nimport {\n\tcreateServer,\n\ttype IncomingMessage,\n\ttype Server,\n\ttype ServerResponse,\n} from \"node:http\";\nimport type { BootstrapResult } from \"./bootstrap.ts\";\nimport type { AbracadabraResendServer } from \"./server.ts\";\nimport { waitForSync } from \"./utils.ts\";\n\nexport interface InboundServerOptions {\n\tserver: AbracadabraResendServer;\n\tbootstrap: BootstrapResult;\n\tsecret: string;\n\tport?: number;\n\thost?: string;\n\t/** Reject deliveries whose timestamp is older than this many seconds. */\n\ttoleranceSeconds?: number;\n}\n\ninterface ResendInboundAttachment {\n\tfilename?: string;\n\tcontentType?: string;\n\tcontent?: string; // base64\n}\n\ninterface ResendInboundData {\n\tid?: string;\n\tfrom?: string | { email?: string; name?: string };\n\tto?: Array<string | { email?: string; name?: string }> | string;\n\tcc?: Array<string | { email?: string; name?: string }> | string;\n\tsubject?: string;\n\ttext?: string;\n\thtml?: string;\n\theaders?: Array<{ name: string; value: string }>;\n\tattachments?: ResendInboundAttachment[];\n\tcreated_at?: string;\n}\n\ninterface ResendInboundEnvelope {\n\ttype?: string;\n\tdata?: ResendInboundData;\n}\n\nfunction addr(v: unknown): string | undefined {\n\tif (typeof v === \"string\") return v.trim() || undefined;\n\tif (v && typeof v === \"object\") {\n\t\tconst obj = v as { email?: string; name?: string };\n\t\tif (typeof obj.email === \"string\") return obj.email.trim() || undefined;\n\t}\n\treturn undefined;\n}\n\nfunction addrList(v: unknown): string[] {\n\tif (Array.isArray(v))\n\t\treturn v.map(addr).filter((s): s is string => !!s);\n\tconst one = addr(v);\n\treturn one ? [one] : [];\n}\n\nfunction pickHeader(\n\theaders: Array<{ name: string; value: string }> | undefined,\n\tname: string,\n): string | undefined {\n\tif (!headers) return undefined;\n\tconst lower = name.toLowerCase();\n\tfor (const h of headers) {\n\t\tif (typeof h?.name === \"string\" && h.name.toLowerCase() === lower) {\n\t\t\treturn h.value;\n\t\t}\n\t}\n\treturn undefined;\n}\n\nfunction decodeSecret(secret: string): Buffer {\n\t// Resend / Svix webhook secrets are `whsec_<base64>`. The HMAC key is the\n\t// base64-decoded bytes after the prefix. Accept raw secrets too so the\n\t// operator can supply a hex/base64 key directly if their plan differs.\n\tconst stripped = secret.startsWith(\"whsec_\") ? secret.slice(6) : secret;\n\ttry {\n\t\treturn Buffer.from(stripped, \"base64\");\n\t} catch {\n\t\treturn Buffer.from(stripped);\n\t}\n}\n\nfunction constantTimeEquals(a: Buffer, b: Buffer): boolean {\n\tif (a.length !== b.length) return false;\n\treturn timingSafeEqual(a, b);\n}\n\n/**\n * Verify Svix-style signature. Headers carry `svix-id`, `svix-timestamp`,\n * `svix-signature` (space-separated `v1,<base64>` pairs). The signing input\n * is `${id}.${timestamp}.${body}` HMAC-SHA256 with the decoded secret.\n */\nfunction verifySignature(\n\tbody: string,\n\theaders: IncomingMessage[\"headers\"],\n\tsecret: Buffer,\n\ttoleranceSeconds: number,\n): { ok: true } | { ok: false; reason: string } {\n\tconst id = headers[\"svix-id\"];\n\tconst ts = headers[\"svix-timestamp\"];\n\tconst sig = headers[\"svix-signature\"];\n\tif (typeof id !== \"string\" || typeof ts !== \"string\" || typeof sig !== \"string\") {\n\t\treturn { ok: false, reason: \"missing Svix headers\" };\n\t}\n\tconst tsNum = Number(ts);\n\tif (!Number.isFinite(tsNum)) {\n\t\treturn { ok: false, reason: \"invalid svix-timestamp\" };\n\t}\n\tconst ageSec = Math.abs(Math.floor(Date.now() / 1000) - tsNum);\n\tif (ageSec > toleranceSeconds) {\n\t\treturn { ok: false, reason: `delivery too old (${ageSec}s)` };\n\t}\n\n\tconst toSign = `${id}.${ts}.${body}`;\n\tconst expected = createHmac(\"sha256\", secret).update(toSign).digest();\n\n\tconst candidates = sig.split(\" \").map((s) => s.trim()).filter(Boolean);\n\tfor (const candidate of candidates) {\n\t\tconst [version, value] = candidate.split(\",\");\n\t\tif (version !== \"v1\" || !value) continue;\n\t\tlet provided: Buffer;\n\t\ttry {\n\t\t\tprovided = Buffer.from(value, \"base64\");\n\t\t} catch {\n\t\t\tcontinue;\n\t\t}\n\t\tif (constantTimeEquals(expected, provided)) return { ok: true };\n\t}\n\treturn { ok: false, reason: \"signature mismatch\" };\n}\n\nfunction readBody(req: IncomingMessage, maxBytes = 25 * 1024 * 1024): Promise<string> {\n\treturn new Promise((resolve, reject) => {\n\t\tconst chunks: Buffer[] = [];\n\t\tlet size = 0;\n\t\treq.on(\"data\", (chunk: Buffer) => {\n\t\t\tsize += chunk.length;\n\t\t\tif (size > maxBytes) {\n\t\t\t\treject(new Error(`payload too large (>${maxBytes} bytes)`));\n\t\t\t\treq.destroy();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tchunks.push(chunk);\n\t\t});\n\t\treq.on(\"end\", () => resolve(Buffer.concat(chunks).toString(\"utf8\")));\n\t\treq.on(\"error\", reject);\n\t});\n}\n\nexport class InboundServer {\n\tprivate readonly server: AbracadabraResendServer;\n\tprivate readonly bootstrap: BootstrapResult;\n\tprivate readonly secret: Buffer;\n\tprivate readonly toleranceSeconds: number;\n\tprivate readonly port: number;\n\tprivate readonly host: string;\n\tprivate httpServer: Server | null = null;\n\t/** De-dupes redelivered webhooks. Svix may retry on transient failures. */\n\tprivate readonly seenSvixIds = new Set<string>();\n\n\tconstructor(opts: InboundServerOptions) {\n\t\tthis.server = opts.server;\n\t\tthis.bootstrap = opts.bootstrap;\n\t\tthis.secret = decodeSecret(opts.secret);\n\t\tthis.toleranceSeconds = opts.toleranceSeconds ?? 5 * 60;\n\t\tthis.port = opts.port ?? 0;\n\t\tthis.host = opts.host ?? \"0.0.0.0\";\n\t}\n\n\tasync start(): Promise<number> {\n\t\tthis.httpServer = createServer((req, res) => {\n\t\t\tvoid this.handle(req, res);\n\t\t});\n\t\tawait new Promise<void>((resolve, reject) => {\n\t\t\tthis.httpServer!.once(\"error\", reject);\n\t\t\tthis.httpServer!.listen(this.port, this.host, () => resolve());\n\t\t});\n\t\tconst address = this.httpServer.address();\n\t\tconst boundPort =\n\t\t\ttypeof address === \"object\" && address ? address.port : this.port;\n\t\tconsole.error(\n\t\t\t`[abracadabra-resend] Inbound server listening on http://${this.host}:${boundPort}/inbound`,\n\t\t);\n\t\treturn boundPort;\n\t}\n\n\tasync stop(): Promise<void> {\n\t\tif (!this.httpServer) return;\n\t\tawait new Promise<void>((resolve, reject) => {\n\t\t\tthis.httpServer!.close((err) => (err ? reject(err) : resolve()));\n\t\t});\n\t\tthis.httpServer = null;\n\t}\n\n\tprivate async handle(req: IncomingMessage, res: ServerResponse): Promise<void> {\n\t\ttry {\n\t\t\tif (req.method === \"GET\" && (req.url === \"/health\" || req.url === \"/\")) {\n\t\t\t\tres.writeHead(200, { \"content-type\": \"text/plain\" });\n\t\t\t\tres.end(\"ok\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (req.method !== \"POST\" || req.url !== \"/inbound\") {\n\t\t\t\tres.writeHead(404, { \"content-type\": \"text/plain\" });\n\t\t\t\tres.end(\"not found\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst body = await readBody(req);\n\t\t\tconst check = verifySignature(\n\t\t\t\tbody,\n\t\t\t\treq.headers,\n\t\t\t\tthis.secret,\n\t\t\t\tthis.toleranceSeconds,\n\t\t\t);\n\t\t\tif (!check.ok) {\n\t\t\t\tconsole.error(`[abracadabra-resend] inbound rejected: ${check.reason}`);\n\t\t\t\tres.writeHead(401, { \"content-type\": \"text/plain\" });\n\t\t\t\tres.end(\"unauthorized\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst svixId =\n\t\t\t\ttypeof req.headers[\"svix-id\"] === \"string\"\n\t\t\t\t\t? (req.headers[\"svix-id\"] as string)\n\t\t\t\t\t: null;\n\t\t\tif (svixId && this.seenSvixIds.has(svixId)) {\n\t\t\t\tres.writeHead(200, { \"content-type\": \"text/plain\" });\n\t\t\t\tres.end(\"duplicate\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (svixId) {\n\t\t\t\tthis.seenSvixIds.add(svixId);\n\t\t\t\tif (this.seenSvixIds.size > 5000) {\n\t\t\t\t\tconst first = this.seenSvixIds.values().next().value;\n\t\t\t\t\tif (first) this.seenSvixIds.delete(first);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tlet env: ResendInboundEnvelope;\n\t\t\ttry {\n\t\t\t\tenv = JSON.parse(body);\n\t\t\t} catch {\n\t\t\t\tres.writeHead(400, { \"content-type\": \"text/plain\" });\n\t\t\t\tres.end(\"invalid json\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst data = env?.data ?? (env as unknown as ResendInboundData);\n\t\t\tawait this.ingest(data);\n\n\t\t\tres.writeHead(200, { \"content-type\": \"text/plain\" });\n\t\t\tres.end(\"ok\");\n\t\t} catch (err: any) {\n\t\t\tconsole.error(\n\t\t\t\t`[abracadabra-resend] inbound handler error: ${err?.message ?? err}`,\n\t\t\t);\n\t\t\tres.writeHead(500, { \"content-type\": \"text/plain\" });\n\t\t\tres.end(\"error\");\n\t\t}\n\t}\n\n\tprivate async ingest(data: ResendInboundData): Promise<void> {\n\t\tawait this.server.ensureConnected();\n\t\tconst treeMap = this.server.getTreeMap();\n\t\tconst rootDoc = this.server.rootDocument;\n\t\tif (!treeMap || !rootDoc) {\n\t\t\tthrow new Error(\"Cannot ingest — server is not connected.\");\n\t\t}\n\n\t\tconst subjectRaw = typeof data.subject === \"string\" ? data.subject.trim() : \"\";\n\t\tconst subject = subjectRaw.length > 0 ? subjectRaw : \"(no subject)\";\n\t\tconst from = addr(data.from) ?? \"(unknown)\";\n\t\tconst to = addrList(data.to);\n\t\tconst cc = addrList(data.cc);\n\t\tconst inReplyTo = pickHeader(data.headers, \"In-Reply-To\");\n\t\tconst messageId =\n\t\t\tpickHeader(data.headers, \"Message-ID\") ?? data.id ?? null;\n\n\t\tconst inboxId = this.bootstrap.inboxId;\n\t\tconst id = crypto.randomUUID();\n\t\tconst now = Date.now();\n\n\t\tconst meta: Record<string, unknown> = {\n\t\t\ticon: \"mail\",\n\t\t\tfrom,\n\t\t\tto,\n\t\t\tcc: cc.length ? cc : undefined,\n\t\t\tsubject,\n\t\t\treceivedAt: now,\n\t\t\tmessageId,\n\t\t\tinReplyTo,\n\t\t};\n\t\tif (typeof data.html === \"string\" && data.html.length > 0) {\n\t\t\tmeta.html = data.html;\n\t\t}\n\n\t\t// SQL row first, then Yjs entry — RBAC cascade depends on it.\n\t\tawait this.server.client.createChild(inboxId, {\n\t\t\tchild_id: id,\n\t\t\tlabel: subject,\n\t\t\tdoc_type: \"doc\",\n\t\t\tkind: \"page\",\n\t\t});\n\n\t\trootDoc.transact(() => {\n\t\t\ttreeMap.set(\n\t\t\t\tid,\n\t\t\t\tmakeEntryMap({\n\t\t\t\t\tlabel: subject,\n\t\t\t\t\tparentId: inboxId,\n\t\t\t\t\torder: now,\n\t\t\t\t\ttype: \"doc\",\n\t\t\t\t\tmeta: meta as any,\n\t\t\t\t\tcreatedAt: now,\n\t\t\t\t\tupdatedAt: now,\n\t\t\t\t}),\n\t\t\t);\n\t\t});\n\n\t\t// Populate the body with the plain-text version (Resend always provides\n\t\t// one). Falls back to a notice when neither text nor html is present.\n\t\tconst provider = await this.server.getChildProvider(id);\n\t\tawait waitForSync(provider);\n\t\tconst fragment = provider.document.getXmlFragment(\"default\");\n\t\tconst body =\n\t\t\t(typeof data.text === \"string\" && data.text.length > 0\n\t\t\t\t? data.text\n\t\t\t\t: typeof data.html === \"string\" && data.html.length > 0\n\t\t\t\t\t? `<details><summary>HTML email (no text part)</summary>\\n\\n\\`\\`\\`html\\n${data.html}\\n\\`\\`\\`\\n</details>`\n\t\t\t\t\t: \"(empty body)\");\n\t\tpopulateBody(fragment, body, subject);\n\n\t\t// Attachments — base64 → Blob → REST upload. Store upload metadata back\n\t\t// on the doc so consumers can render previews / download.\n\t\tconst attached: Array<{\n\t\t\tid: string;\n\t\t\tfilename: string;\n\t\t\tcontentType?: string;\n\t\t\tsize: number;\n\t\t}> = [];\n\t\tconst attachments = Array.isArray(data.attachments) ? data.attachments : [];\n\t\tfor (const att of attachments) {\n\t\t\tif (typeof att?.content !== \"string\") continue;\n\t\t\tconst filename =\n\t\t\t\ttypeof att.filename === \"string\" && att.filename.length > 0\n\t\t\t\t\t? att.filename\n\t\t\t\t\t: \"attachment\";\n\t\t\ttry {\n\t\t\t\tconst bytes = Buffer.from(att.content, \"base64\");\n\t\t\t\tconst blob = new Blob([bytes], {\n\t\t\t\t\ttype: att.contentType ?? \"application/octet-stream\",\n\t\t\t\t});\n\t\t\t\tconst uploaded = await this.server.client.upload(id, blob, filename);\n\t\t\t\tconst uploadedId =\n\t\t\t\t\t(uploaded as { id?: string; uploadId?: string })?.id ??\n\t\t\t\t\t(uploaded as { uploadId?: string })?.uploadId ??\n\t\t\t\t\t\"\";\n\t\t\t\tattached.push({\n\t\t\t\t\tid: uploadedId,\n\t\t\t\t\tfilename,\n\t\t\t\t\tcontentType: att.contentType,\n\t\t\t\t\tsize: bytes.length,\n\t\t\t\t});\n\t\t\t} catch (err: any) {\n\t\t\t\tconsole.error(\n\t\t\t\t\t`[abracadabra-resend] attachment upload failed (${filename}): ${err?.message ?? err}`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\tif (attached.length > 0) {\n\t\t\tconst existingRaw = treeMap.get(id);\n\t\t\tif (existingRaw) {\n\t\t\t\tconst existingMeta =\n\t\t\t\t\t(typeof (existingRaw as any).toJSON === \"function\"\n\t\t\t\t\t\t? (existingRaw as any).toJSON()?.meta\n\t\t\t\t\t\t: (existingRaw as any).meta) ?? {};\n\t\t\t\trootDoc.transact(() => {\n\t\t\t\t\ttreeMap.set(\n\t\t\t\t\t\tid,\n\t\t\t\t\t\tmakeEntryMap({\n\t\t\t\t\t\t\tlabel: subject,\n\t\t\t\t\t\t\tparentId: inboxId,\n\t\t\t\t\t\t\torder: now,\n\t\t\t\t\t\t\ttype: \"doc\",\n\t\t\t\t\t\t\tmeta: { ...existingMeta, attachments: attached },\n\t\t\t\t\t\t\tcreatedAt: now,\n\t\t\t\t\t\t\tupdatedAt: Date.now(),\n\t\t\t\t\t\t}),\n\t\t\t\t\t);\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\n\t\tconsole.error(\n\t\t\t`[abracadabra-resend] inbound stored: \"${subject}\" from ${from} → doc ${id}`,\n\t\t);\n\t}\n}\n\n","/**\n * Render an outbox document to an email-ready payload.\n *\n * Reads addressing from the doc's tree-entry `meta` (to/cc/bcc/subject/from/\n * replyTo) and renders the body Y.XmlFragment via `@abraca/convert`'s\n * `yjsToHtml` — which already emits a complete `<!DOCTYPE html>` doc with the\n * doc label as `<h1>`, so the result is suitable as-is for Resend's `html`\n * field.\n */\nimport { yjsToHtml } from \"@abraca/convert\";\nimport { toPlain } from \"@abraca/dabra\";\nimport type { AbracadabraResendServer } from \"./server.ts\";\n\nexport interface EmailPayload {\n\tsubject: string;\n\thtml: string;\n\tto: string[];\n\tcc?: string[];\n\tbcc?: string[];\n\tfrom?: string;\n\treplyTo?: string;\n}\n\nexport class RenderError extends Error {\n\tconstructor(message: string) {\n\t\tsuper(message);\n\t\tthis.name = \"RenderError\";\n\t}\n}\n\nfunction asStringArray(value: unknown): string[] {\n\tif (Array.isArray(value)) {\n\t\treturn value\n\t\t\t.filter((v): v is string => typeof v === \"string\" && v.trim().length > 0)\n\t\t\t.map((v) => v.trim());\n\t}\n\tif (typeof value === \"string\" && value.trim().length > 0) {\n\t\t// Allow `to: \"alice@x.com, bob@y.com\"` as a convenience.\n\t\treturn value\n\t\t\t.split(\",\")\n\t\t\t.map((s) => s.trim())\n\t\t\t.filter((s) => s.length > 0);\n\t}\n\treturn [];\n}\n\nfunction asOptionalString(value: unknown): string | undefined {\n\treturn typeof value === \"string\" && value.trim().length > 0\n\t\t? value.trim()\n\t\t: undefined;\n}\n\ninterface OutboxEntry {\n\tlabel: string;\n\tmeta: Record<string, unknown>;\n}\n\nfunction readEntry(\n\tserver: AbracadabraResendServer,\n\tdocId: string,\n): OutboxEntry | null {\n\tconst treeMap = server.getTreeMap();\n\tif (!treeMap) return null;\n\tconst raw = treeMap.get(docId);\n\tif (!raw) return null;\n\tconst plain = toPlain(raw) as any;\n\tif (!plain || typeof plain !== \"object\") return null;\n\treturn {\n\t\tlabel: typeof plain.label === \"string\" ? plain.label : \"(no subject)\",\n\t\tmeta:\n\t\t\tplain.meta && typeof plain.meta === \"object\"\n\t\t\t\t? (plain.meta as Record<string, unknown>)\n\t\t\t\t: {},\n\t};\n}\n\nexport async function renderEmail(\n\tserver: AbracadabraResendServer,\n\tdocId: string,\n\tdefaultFrom: string,\n): Promise<EmailPayload> {\n\tconst entry = readEntry(server, docId);\n\tif (!entry) {\n\t\tthrow new RenderError(`Doc ${docId} has no tree entry.`);\n\t}\n\n\tconst to = asStringArray(entry.meta.to);\n\tif (to.length === 0) {\n\t\tthrow new RenderError(\n\t\t\t`Doc ${docId} has no recipients — set meta.to (array of email addresses).`,\n\t\t);\n\t}\n\tconst cc = asStringArray(entry.meta.cc);\n\tconst bcc = asStringArray(entry.meta.bcc);\n\tconst from = asOptionalString(entry.meta.from) ?? defaultFrom;\n\tconst replyTo = asOptionalString(entry.meta.replyTo);\n\tconst subject = asOptionalString(entry.meta.subject) ?? entry.label;\n\n\tconst provider = await server.getChildProvider(docId);\n\tconst fragment = provider.document.getXmlFragment(\"default\");\n\tconst html = yjsToHtml(fragment, subject);\n\n\treturn {\n\t\tsubject,\n\t\thtml,\n\t\tto,\n\t\tcc: cc.length ? cc : undefined,\n\t\tbcc: bcc.length ? bcc : undefined,\n\t\tfrom,\n\t\treplyTo,\n\t};\n}\n","/**\n * Outbox watcher. Observes the doc-tree map (deeply, so per-entry parentId\n * updates surface) and dispatches any doc that lands under the \"Ready\" column.\n *\n * Dispatch flow per doc:\n * render → resend.send → patch meta.resendId/sentAt → move to Sent\n * On failure:\n * patch meta.error/errorAt → move to Failed (left for human triage)\n *\n * Idempotency:\n * - `meta.resendId` already set → skip (recovers from a restart that landed\n * between Resend ack and the post-send move).\n * - In-flight `Set<docId>` prevents the same observe burst from double-firing.\n */\nimport { patchEntry, toPlain } from \"@abraca/dabra\";\nimport type * as Y from \"yjs\";\nimport type { BootstrapResult } from \"./bootstrap.ts\";\nimport { renderEmail, RenderError } from \"./render.ts\";\nimport type { ResendSender } from \"./resend-client.ts\";\nimport type { AbracadabraResendServer } from \"./server.ts\";\n\nexport interface OutboxWatcherOptions {\n\tserver: AbracadabraResendServer;\n\tsender: ResendSender;\n\tbootstrap: BootstrapResult;\n\tdefaultFrom: string;\n}\n\ninterface EntryView {\n\tid: string;\n\tlabel: string;\n\tparentId: string | null;\n\tmeta: Record<string, unknown>;\n}\n\nfunction readEntry(treeMap: Y.Map<any>, id: string): EntryView | null {\n\tconst raw = treeMap.get(id);\n\tif (!raw) return null;\n\tconst plain = toPlain(raw) as any;\n\tif (!plain || typeof plain !== \"object\") return null;\n\treturn {\n\t\tid,\n\t\tlabel: typeof plain.label === \"string\" ? plain.label : \"Untitled\",\n\t\tparentId: plain.parentId ?? null,\n\t\tmeta:\n\t\t\tplain.meta && typeof plain.meta === \"object\"\n\t\t\t\t? (plain.meta as Record<string, unknown>)\n\t\t\t\t: {},\n\t};\n}\n\nexport class OutboxWatcher {\n\tprivate readonly server: AbracadabraResendServer;\n\tprivate readonly sender: ResendSender;\n\tprivate readonly bootstrap: BootstrapResult;\n\tprivate readonly defaultFrom: string;\n\tprivate readonly inFlight = new Set<string>();\n\tprivate readonly handled = new Set<string>();\n\tprivate observer: ((events: Y.YEvent<any>[]) => void) | null = null;\n\tprivate treeMap: Y.Map<any> | null = null;\n\tprivate rootDoc: Y.Doc | null = null;\n\tprivate txHandler: ((tx: Y.Transaction) => void) | null = null;\n\n\tconstructor(opts: OutboxWatcherOptions) {\n\t\tthis.server = opts.server;\n\t\tthis.sender = opts.sender;\n\t\tthis.bootstrap = opts.bootstrap;\n\t\tthis.defaultFrom = opts.defaultFrom;\n\t}\n\n\tstart(): void {\n\t\tconst treeMap = this.server.getTreeMap();\n\t\tif (!treeMap) {\n\t\t\tthrow new Error(\"OutboxWatcher.start: server is not connected\");\n\t\t}\n\t\tthis.treeMap = treeMap;\n\n\t\tconst rootDoc = this.server.rootDocument;\n\t\tif (!rootDoc) {\n\t\t\tthrow new Error(\"OutboxWatcher.start: root doc not connected\");\n\t\t}\n\t\tthis.rootDoc = rootDoc;\n\n\t\t// Initial scan — pick up anything already in Ready before we attached.\n\t\tvoid this.scan(\"init\");\n\n\t\t// observeDeep on the tree map catches all the common edits (patchEntry\n\t\t// mutating a nested Y.Map, treeMap.set replacing an entry).\n\t\tconst obs = (events: Y.YEvent<any>[]) => {\n\t\t\tconsole.error(\n\t\t\t\t`[abracadabra-resend] observeDeep fired (${events.length} events)`,\n\t\t\t);\n\t\t\tvoid this.scan(\"observeDeep\");\n\t\t};\n\t\ttreeMap.observeDeep(obs);\n\t\tthis.observer = obs;\n\n\t\t// afterTransaction on the root Y.Doc fires for EVERY transaction applied\n\t\t// to the doc — local writes and updates dispatched into this doc.\n\t\tconst onTx = (tx: Y.Transaction) => {\n\t\t\tconst changed: string[] = [];\n\t\t\tfor (const [type, events] of tx.changedParentTypes.entries()) {\n\t\t\t\tconst name = (type as any)._item ? (type as any)._item.parentSub : type.constructor.name;\n\t\t\t\tconst keys = events.flatMap((ev: any) => Array.from(ev.keysChanged ?? []));\n\t\t\t\tchanged.push(`${name ?? \"type\"}[${keys.join(\",\")}]`);\n\t\t\t}\n\t\t\tconsole.error(\n\t\t\t\t`[abracadabra-resend] root afterTransaction (local=${tx.local}, origin=${String(tx.origin)}, changed=${changed.join(\" | \") || \"(none)\"})`,\n\t\t\t);\n\t\t\tvoid this.scan(\"afterTransaction\");\n\t\t};\n\t\trootDoc.on(\"afterTransaction\", onTx);\n\t\tthis.txHandler = onTx;\n\n\t\t// Belt-and-suspenders: subdocs. abracadabra-rs may route some space-tree\n\t\t// edits through subdoc payloads that don't fire transactions on the root\n\t\t// doc directly. Watch every subdoc's transactions too.\n\t\tconst onSubdocs = (changes: { added: Set<Y.Doc>; removed: Set<Y.Doc>; loaded: Set<Y.Doc> }) => {\n\t\t\tconsole.error(\n\t\t\t\t`[abracadabra-resend] subdocs: added=${changes.added.size} loaded=${changes.loaded.size}`,\n\t\t\t);\n\t\t\tfor (const sub of [...changes.added, ...changes.loaded]) {\n\t\t\t\tsub.on(\"afterTransaction\", (tx: Y.Transaction) => {\n\t\t\t\t\tconsole.error(\n\t\t\t\t\t\t`[abracadabra-resend] subdoc afterTransaction (guid=${sub.guid}, local=${tx.local})`,\n\t\t\t\t\t);\n\t\t\t\t\tvoid this.scan(\"subdoc\");\n\t\t\t\t});\n\t\t\t}\n\t\t};\n\t\trootDoc.on(\"subdocs\", onSubdocs);\n\n\t\t// Raw doc update — fires for every binary Yjs update applied to the doc,\n\t\t// from any origin. If THIS doesn't fire when a remote writer changes\n\t\t// state, the bridge's WS isn't delivering updates.\n\t\trootDoc.on(\"update\", (_update: Uint8Array, origin: unknown) => {\n\t\t\tconsole.error(\n\t\t\t\t`[abracadabra-resend] root update applied (origin=${String(origin)})`,\n\t\t\t);\n\t\t\tvoid this.scan(\"update\");\n\t\t});\n\n\t\tconsole.error(\n\t\t\t`[abracadabra-resend] Outbox watcher attached (ready column ${this.bootstrap.columns.Ready})`,\n\t\t);\n\t}\n\n\tstop(): void {\n\t\tif (this.rootDoc && this.txHandler) {\n\t\t\tthis.rootDoc.off(\"afterTransaction\", this.txHandler);\n\t\t}\n\t\tif (this.treeMap && this.observer) {\n\t\t\tthis.treeMap.unobserveDeep(this.observer);\n\t\t}\n\t\tthis.txHandler = null;\n\t\tthis.rootDoc = null;\n\t\tthis.observer = null;\n\t\tthis.treeMap = null;\n\t}\n\n\tprivate async scan(reason: string): Promise<void> {\n\t\tconst treeMap = this.treeMap;\n\t\tif (!treeMap) return;\n\t\tconst readyColId = this.bootstrap.columns.Ready;\n\t\tconst outboxId = this.bootstrap.outboxId;\n\t\tconst columnIds = new Set(Object.values(this.bootstrap.columns));\n\t\tconst candidates: EntryView[] = [];\n\t\tlet inReadyCount = 0;\n\t\tlet totalEntries = 0;\n\t\t// Dump every entry whose ancestor is Outbox so we can compare bridge\n\t\t// view vs cou-sh view.\n\t\tconst outboxSubtree: Array<{ id: string; label: string; parentId: string | null; under: string }> = [];\n\t\ttreeMap.forEach((_raw: any, id: string) => {\n\t\t\ttotalEntries++;\n\t\t\tconst e = readEntry(treeMap, id);\n\t\t\tif (!e) return;\n\t\t\t// classify under outbox: direct child of Outbox, or grandchild via a column\n\t\t\tif (e.parentId === outboxId || (e.parentId && columnIds.has(e.parentId))) {\n\t\t\t\toutboxSubtree.push({\n\t\t\t\t\tid,\n\t\t\t\t\tlabel: e.label,\n\t\t\t\t\tparentId: e.parentId,\n\t\t\t\t\tunder: e.parentId === outboxId ? \"Outbox\" :\n\t\t\t\t\t\te.parentId === this.bootstrap.columns.Draft ? \"Draft\" :\n\t\t\t\t\t\te.parentId === this.bootstrap.columns.Ready ? \"Ready\" :\n\t\t\t\t\t\te.parentId === this.bootstrap.columns.Sent ? \"Sent\" :\n\t\t\t\t\t\te.parentId === this.bootstrap.columns.Failed ? \"Failed\" : \"?\",\n\t\t\t\t});\n\t\t\t}\n\t\t\tif (e.parentId !== readyColId) return;\n\t\t\tinReadyCount++;\n\t\t\tif (this.inFlight.has(id) || this.handled.has(id)) return;\n\t\t\tif (typeof e.meta.resendId === \"string\" && e.meta.resendId.length > 0) {\n\t\t\t\tthis.handled.add(id);\n\t\t\t\tthis.moveTo(id, this.bootstrap.columns.Sent);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcandidates.push(e);\n\t\t});\n\t\tconsole.error(\n\t\t\t`[abracadabra-resend] scan(${reason}): ${totalEntries} entries, ${inReadyCount} in Ready, ${candidates.length} to dispatch | Outbox subtree (${outboxSubtree.length}): ${outboxSubtree.map((e) => `${e.under}:\"${e.label}\"`).join(\", \")}`,\n\t\t);\n\n\t\tfor (const entry of candidates) {\n\t\t\tthis.inFlight.add(entry.id);\n\t\t\tvoid this.dispatch(entry).finally(() => {\n\t\t\t\tthis.inFlight.delete(entry.id);\n\t\t\t});\n\t\t}\n\t}\n\n\tprivate async dispatch(entry: EntryView): Promise<void> {\n\t\tconst { id, label } = entry;\n\t\ttry {\n\t\t\tconst payload = await renderEmail(this.server, id, this.defaultFrom);\n\t\t\tconsole.error(\n\t\t\t\t`[abracadabra-resend] sending \"${payload.subject}\" → ${payload.to.join(\", \")} (doc=${id})`,\n\t\t\t);\n\t\t\tconst { id: resendId } = await this.sender.send(payload, {\n\t\t\t\t\"X-Abra-Doc-Id\": id,\n\t\t\t});\n\t\t\tthis.handled.add(id);\n\t\t\tthis.patchMeta(id, { resendId, sentAt: Date.now(), error: null });\n\t\t\tthis.moveTo(id, this.bootstrap.columns.Sent);\n\t\t\tconsole.error(\n\t\t\t\t`[abracadabra-resend] sent \"${payload.subject}\" (resend=${resendId}, doc=${id})`,\n\t\t\t);\n\t\t} catch (err: any) {\n\t\t\tthis.handled.add(id);\n\t\t\tconst message =\n\t\t\t\terr instanceof RenderError\n\t\t\t\t\t? err.message\n\t\t\t\t\t: err?.message\n\t\t\t\t\t\t? String(err.message)\n\t\t\t\t\t\t: String(err);\n\t\t\tconsole.error(\n\t\t\t\t`[abracadabra-resend] send failed for \"${label}\" (${id}): ${message}`,\n\t\t\t);\n\t\t\tthis.patchMeta(id, { error: message, errorAt: Date.now() });\n\t\t\tthis.moveTo(id, this.bootstrap.columns.Failed);\n\t\t}\n\t}\n\n\tprivate patchMeta(id: string, patch: Record<string, unknown>): void {\n\t\tconst treeMap = this.treeMap;\n\t\tconst rootDoc = this.server.rootDocument;\n\t\tif (!treeMap || !rootDoc) return;\n\t\tconst current = readEntry(treeMap, id);\n\t\tif (!current) return;\n\t\tconst nextMeta = { ...current.meta, ...patch };\n\t\tfor (const [k, v] of Object.entries(patch)) {\n\t\t\tif (v === null) delete nextMeta[k];\n\t\t}\n\t\trootDoc.transact(() => {\n\t\t\tpatchEntry(treeMap, id, {\n\t\t\t\tmeta: nextMeta,\n\t\t\t\tupdatedAt: Date.now(),\n\t\t\t});\n\t\t});\n\t}\n\n\tprivate moveTo(id: string, newParentId: string): void {\n\t\tconst treeMap = this.treeMap;\n\t\tconst rootDoc = this.server.rootDocument;\n\t\tif (!treeMap || !rootDoc) return;\n\t\tconst now = Date.now();\n\t\trootDoc.transact(() => {\n\t\t\tpatchEntry(treeMap, id, {\n\t\t\t\tparentId: newParentId,\n\t\t\t\torder: now,\n\t\t\t\tupdatedAt: now,\n\t\t\t});\n\t\t});\n\t\t// Best-effort registry reparent so REST/FTS sees the move too.\n\t\tvoid this.server.client\n\t\t\t.updateDocumentMeta(id, { parent_id: newParentId })\n\t\t\t.catch((e) => {\n\t\t\t\tconsole.error(\n\t\t\t\t\t`[abracadabra-resend] REST reparent failed for ${id}: ${e?.message ?? e}`,\n\t\t\t\t);\n\t\t\t});\n\t}\n}\n","/**\n * Thin wrapper around the official `resend` SDK. Kept separate so tests can\n * substitute a fake without mocking the SDK directly.\n */\nimport { Resend } from \"resend\";\nimport type { EmailPayload } from \"./render.ts\";\n\nexport interface SendResult {\n\tid: string;\n}\n\nexport interface ResendSender {\n\tsend(payload: EmailPayload, headers?: Record<string, string>): Promise<SendResult>;\n}\n\nexport class ResendClient implements ResendSender {\n\tprivate readonly resend: Resend;\n\n\tconstructor(apiKey: string) {\n\t\tthis.resend = new Resend(apiKey);\n\t}\n\n\tasync send(\n\t\tpayload: EmailPayload,\n\t\theaders?: Record<string, string>,\n\t): Promise<SendResult> {\n\t\tif (!payload.from) {\n\t\t\tthrow new Error(\"ResendClient.send: payload.from is required\");\n\t\t}\n\t\tconst { data, error } = await this.resend.emails.send({\n\t\t\tfrom: payload.from,\n\t\t\tto: payload.to,\n\t\t\tcc: payload.cc,\n\t\t\tbcc: payload.bcc,\n\t\t\tsubject: payload.subject,\n\t\t\thtml: payload.html,\n\t\t\treplyTo: payload.replyTo,\n\t\t\theaders,\n\t\t});\n\t\tif (error) {\n\t\t\tthrow new Error(\n\t\t\t\t`Resend rejected the message: ${error.message ?? JSON.stringify(error)}`,\n\t\t\t);\n\t\t}\n\t\tif (!data?.id) {\n\t\t\tthrow new Error(\"Resend returned no id for the dispatched message\");\n\t\t}\n\t\treturn { id: data.id };\n\t}\n}\n","/**\n * Checks if something is Uint8Array. Be careful: nodejs Buffer will return true.\n * @param a - value to test\n * @returns `true` when the value is a Uint8Array-compatible view.\n * @example\n * Check whether a value is a Uint8Array-compatible view.\n * ```ts\n * isBytes(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport function isBytes(a) {\n // Plain `instanceof Uint8Array` is too strict for some Buffer / proxy / cross-realm cases.\n // The fallback still requires a real ArrayBuffer view, so plain\n // JSON-deserialized `{ constructor: ... }` spoofing is rejected, and\n // `BYTES_PER_ELEMENT === 1` keeps the fallback on byte-oriented views.\n return (a instanceof Uint8Array ||\n (ArrayBuffer.isView(a) &&\n a.constructor.name === 'Uint8Array' &&\n 'BYTES_PER_ELEMENT' in a &&\n a.BYTES_PER_ELEMENT === 1));\n}\n/**\n * Asserts something is a non-negative integer.\n * @param n - number to validate\n * @param title - label included in thrown errors\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Validate a non-negative integer option.\n * ```ts\n * anumber(32, 'length');\n * ```\n */\nexport function anumber(n, title = '') {\n if (typeof n !== 'number') {\n const prefix = title && `\"${title}\" `;\n throw new TypeError(`${prefix}expected number, got ${typeof n}`);\n }\n if (!Number.isSafeInteger(n) || n < 0) {\n const prefix = title && `\"${title}\" `;\n throw new RangeError(`${prefix}expected integer >= 0, got ${n}`);\n }\n}\n/**\n * Asserts something is Uint8Array.\n * @param value - value to validate\n * @param length - optional exact length constraint\n * @param title - label included in thrown errors\n * @returns The validated byte array.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Validate that a value is a byte array.\n * ```ts\n * abytes(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport function abytes(value, length, title = '') {\n const bytes = isBytes(value);\n const len = value?.length;\n const needsLen = length !== undefined;\n if (!bytes || (needsLen && len !== length)) {\n const prefix = title && `\"${title}\" `;\n const ofLen = needsLen ? ` of length ${length}` : '';\n const got = bytes ? `length=${len}` : `type=${typeof value}`;\n const message = prefix + 'expected Uint8Array' + ofLen + ', got ' + got;\n if (!bytes)\n throw new TypeError(message);\n throw new RangeError(message);\n }\n return value;\n}\n/**\n * Copies bytes into a fresh Uint8Array.\n * Buffer-style slices can alias the same backing store, so callers that need ownership should copy.\n * @param bytes - source bytes to clone\n * @returns Freshly allocated copy of `bytes`.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Clone a byte array before mutating it.\n * ```ts\n * const copy = copyBytes(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport function copyBytes(bytes) {\n // `Uint8Array.from(...)` would also accept arrays / other typed arrays. Keep this helper strict\n // because callers use it at byte-validation boundaries before mutating the detached copy.\n return Uint8Array.from(abytes(bytes));\n}\n/**\n * Asserts something is a wrapped hash constructor.\n * @param h - hash constructor to validate\n * @throws On wrong argument types or invalid hash wrapper shape. {@link TypeError}\n * @throws On invalid hash metadata ranges or values. {@link RangeError}\n * @throws If the hash metadata allows empty outputs or block sizes. {@link Error}\n * @example\n * Validate a callable hash wrapper.\n * ```ts\n * import { ahash } from '@noble/hashes/utils.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * ahash(sha256);\n * ```\n */\nexport function ahash(h) {\n if (typeof h !== 'function' || typeof h.create !== 'function')\n throw new TypeError('Hash must wrapped by utils.createHasher');\n anumber(h.outputLen);\n anumber(h.blockLen);\n // HMAC and KDF callers treat these as real byte lengths; allowing zero lets fake wrappers pass\n // validation and can produce empty outputs instead of failing fast.\n if (h.outputLen < 1)\n throw new Error('\"outputLen\" must be >= 1');\n if (h.blockLen < 1)\n throw new Error('\"blockLen\" must be >= 1');\n}\n/**\n * Asserts a hash instance has not been destroyed or finished.\n * @param instance - hash instance to validate\n * @param checkFinished - whether to reject finalized instances\n * @throws If the hash instance has already been destroyed or finalized. {@link Error}\n * @example\n * Validate that a hash instance is still usable.\n * ```ts\n * import { aexists } from '@noble/hashes/utils.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const hash = sha256.create();\n * aexists(hash);\n * ```\n */\nexport function aexists(instance, checkFinished = true) {\n if (instance.destroyed)\n throw new Error('Hash instance has been destroyed');\n if (checkFinished && instance.finished)\n throw new Error('Hash#digest() has already been called');\n}\n/**\n * Asserts output is a sufficiently-sized byte array.\n * @param out - destination buffer\n * @param instance - hash instance providing output length\n * Oversized buffers are allowed; downstream code only promises to fill the first `outputLen` bytes.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Validate a caller-provided digest buffer.\n * ```ts\n * import { aoutput } from '@noble/hashes/utils.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const hash = sha256.create();\n * aoutput(new Uint8Array(hash.outputLen), hash);\n * ```\n */\nexport function aoutput(out, instance) {\n abytes(out, undefined, 'digestInto() output');\n const min = instance.outputLen;\n if (out.length < min) {\n throw new RangeError('\"digestInto() output\" expected to be of length >=' + min);\n }\n}\n/**\n * Casts a typed array view to Uint8Array.\n * @param arr - source typed array\n * @returns Uint8Array view over the same buffer.\n * @example\n * Reinterpret a typed array as bytes.\n * ```ts\n * u8(new Uint32Array([1, 2]));\n * ```\n */\nexport function u8(arr) {\n return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n/**\n * Casts a typed array view to Uint32Array.\n * `arr.byteOffset` must already be 4-byte aligned or the platform\n * Uint32Array constructor will throw.\n * @param arr - source typed array\n * @returns Uint32Array view over the same buffer.\n * @example\n * Reinterpret a byte array as 32-bit words.\n * ```ts\n * u32(new Uint8Array(8));\n * ```\n */\nexport function u32(arr) {\n return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n}\n/**\n * Zeroizes typed arrays in place. Warning: JS provides no guarantees.\n * @param arrays - arrays to overwrite with zeros\n * @example\n * Zeroize sensitive buffers in place.\n * ```ts\n * clean(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport function clean(...arrays) {\n for (let i = 0; i < arrays.length; i++) {\n arrays[i].fill(0);\n }\n}\n/**\n * Creates a DataView for byte-level manipulation.\n * @param arr - source typed array\n * @returns DataView over the same buffer region.\n * @example\n * Create a DataView over an existing buffer.\n * ```ts\n * createView(new Uint8Array(4));\n * ```\n */\nexport function createView(arr) {\n return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n/**\n * Rotate-right operation for uint32 values.\n * @param word - source word\n * @param shift - shift amount in bits\n * @returns Rotated word.\n * @example\n * Rotate a 32-bit word to the right.\n * ```ts\n * rotr(0x12345678, 8);\n * ```\n */\nexport function rotr(word, shift) {\n return (word << (32 - shift)) | (word >>> shift);\n}\n/**\n * Rotate-left operation for uint32 values.\n * @param word - source word\n * @param shift - shift amount in bits\n * @returns Rotated word.\n * @example\n * Rotate a 32-bit word to the left.\n * ```ts\n * rotl(0x12345678, 8);\n * ```\n */\nexport function rotl(word, shift) {\n return (word << shift) | ((word >>> (32 - shift)) >>> 0);\n}\n/** Whether the current platform is little-endian. */\nexport const isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();\n/**\n * Byte-swap operation for uint32 values.\n * @param word - source word\n * @returns Word with reversed byte order.\n * @example\n * Reverse the byte order of a 32-bit word.\n * ```ts\n * byteSwap(0x11223344);\n * ```\n */\nexport function byteSwap(word) {\n return (((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff));\n}\n/**\n * Conditionally byte-swaps one 32-bit word on big-endian platforms.\n * @param n - source word\n * @returns Original or byte-swapped word depending on platform endianness.\n * @example\n * Normalize a 32-bit word for host endianness.\n * ```ts\n * swap8IfBE(0x11223344);\n * ```\n */\nexport const swap8IfBE = isLE\n ? (n) => n\n : (n) => byteSwap(n) >>> 0;\n/**\n * Byte-swaps every word of a Uint32Array in place.\n * @param arr - array to mutate\n * @returns The same array after mutation; callers pass live state arrays here.\n * @example\n * Reverse the byte order of every word in place.\n * ```ts\n * byteSwap32(new Uint32Array([0x11223344]));\n * ```\n */\nexport function byteSwap32(arr) {\n for (let i = 0; i < arr.length; i++) {\n arr[i] = byteSwap(arr[i]);\n }\n return arr;\n}\n/**\n * Conditionally byte-swaps a Uint32Array on big-endian platforms.\n * @param u - array to normalize for host endianness\n * @returns Original or byte-swapped array depending on platform endianness.\n * On big-endian runtimes this mutates `u` in place via `byteSwap32(...)`.\n * @example\n * Normalize a word array for host endianness.\n * ```ts\n * swap32IfBE(new Uint32Array([0x11223344]));\n * ```\n */\nexport const swap32IfBE = isLE\n ? (u) => u\n : byteSwap32;\n// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\nconst hasHexBuiltin = /* @__PURE__ */ (() => \n// @ts-ignore\ntypeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));\n/**\n * Convert byte array to hex string.\n * Uses the built-in function when available and assumes it matches the tested\n * fallback semantics.\n * @param bytes - bytes to encode\n * @returns Lowercase hexadecimal string.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Convert bytes to lowercase hexadecimal.\n * ```ts\n * bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])); // 'cafe0123'\n * ```\n */\nexport function bytesToHex(bytes) {\n abytes(bytes);\n // @ts-ignore\n if (hasHexBuiltin)\n return bytes.toHex();\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };\nfunction asciiToBase16(ch) {\n if (ch >= asciis._0 && ch <= asciis._9)\n return ch - asciis._0; // '2' => 50-48\n if (ch >= asciis.A && ch <= asciis.F)\n return ch - (asciis.A - 10); // 'B' => 66-(65-10)\n if (ch >= asciis.a && ch <= asciis.f)\n return ch - (asciis.a - 10); // 'b' => 98-(97-10)\n return;\n}\n/**\n * Convert hex string to byte array. Uses built-in function, when available.\n * @param hex - hexadecimal string to decode\n * @returns Decoded bytes.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Decode lowercase hexadecimal into bytes.\n * ```ts\n * hexToBytes('cafe0123'); // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n * ```\n */\nexport function hexToBytes(hex) {\n if (typeof hex !== 'string')\n throw new TypeError('hex string expected, got ' + typeof hex);\n if (hasHexBuiltin) {\n try {\n return Uint8Array.fromHex(hex);\n }\n catch (error) {\n if (error instanceof SyntaxError)\n throw new RangeError(error.message);\n throw error;\n }\n }\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2)\n throw new RangeError('hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new RangeError('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163\n }\n return array;\n}\n/**\n * There is no setImmediate in browser and setTimeout is slow.\n * This yields to the Promise/microtask scheduler queue, not to timers or the\n * full macrotask event loop.\n * @example\n * Yield to the next scheduler tick.\n * ```ts\n * await nextTick();\n * ```\n */\nexport const nextTick = async () => { };\n/**\n * Returns control to the Promise/microtask scheduler every `tick`\n * milliseconds to avoid blocking long loops.\n * @param iters - number of loop iterations to run\n * @param tick - maximum time slice in milliseconds\n * @param cb - callback executed on each iteration\n * @example\n * Run a loop that periodically yields back to the event loop.\n * ```ts\n * await asyncLoop(2, 0, () => {});\n * ```\n */\nexport async function asyncLoop(iters, tick, cb) {\n let ts = Date.now();\n for (let i = 0; i < iters; i++) {\n cb(i);\n // Date.now() is not monotonic, so in case if clock goes backwards we return return control too\n const diff = Date.now() - ts;\n if (diff >= 0 && diff < tick)\n continue;\n await nextTick();\n ts += diff;\n }\n}\n/**\n * Converts string to bytes using UTF8 encoding.\n * Built-in doesn't validate input to be string: we do the check.\n * Non-ASCII details are delegated to the platform `TextEncoder`.\n * @param str - string to encode\n * @returns UTF-8 encoded bytes.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Encode a string as UTF-8 bytes.\n * ```ts\n * utf8ToBytes('abc'); // Uint8Array.from([97, 98, 99])\n * ```\n */\nexport function utf8ToBytes(str) {\n if (typeof str !== 'string')\n throw new TypeError('string expected');\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n/**\n * Helper for KDFs: consumes Uint8Array or string.\n * String inputs are UTF-8 encoded; byte-array inputs stay aliased to the caller buffer.\n * @param data - user-provided KDF input\n * @param errorTitle - label included in thrown errors\n * @returns Byte representation of the input.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Normalize KDF input to bytes.\n * ```ts\n * kdfInputToBytes('password');\n * ```\n */\nexport function kdfInputToBytes(data, errorTitle = '') {\n if (typeof data === 'string')\n return utf8ToBytes(data);\n return abytes(data, undefined, errorTitle);\n}\n/**\n * Copies several Uint8Arrays into one.\n * @param arrays - arrays to concatenate\n * @returns Concatenated byte array.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Concatenate multiple byte arrays.\n * ```ts\n * concatBytes(new Uint8Array([1]), new Uint8Array([2]));\n * ```\n */\nexport function concatBytes(...arrays) {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n abytes(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\n/**\n * Merges default options and passed options.\n * @param defaults - base option object\n * @param opts - user overrides\n * @returns Merged option object. The merge mutates `defaults` in place.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Merge user overrides onto default options.\n * ```ts\n * checkOpts({ dkLen: 32 }, { asyncTick: 10 });\n * ```\n */\nexport function checkOpts(defaults, opts) {\n if (opts !== undefined && {}.toString.call(opts) !== '[object Object]')\n throw new TypeError('options must be object or undefined');\n const merged = Object.assign(defaults, opts);\n return merged;\n}\n/**\n * Creates a callable hash function from a stateful class constructor.\n * @param hashCons - hash constructor or factory\n * @param info - optional metadata such as DER OID\n * @returns Frozen callable hash wrapper with `.create()`.\n * Wrapper construction eagerly calls `hashCons(undefined)` once to read\n * `outputLen` / `blockLen`, so constructor side effects happen at module\n * init time.\n * @example\n * Wrap a stateful hash constructor into a callable helper.\n * ```ts\n * import { createHasher } from '@noble/hashes/utils.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const wrapped = createHasher(sha256.create, { oid: sha256.oid });\n * wrapped(new Uint8Array([1]));\n * ```\n */\nexport function createHasher(hashCons, info = {}) {\n const hashC = (msg, opts) => hashCons(opts)\n .update(msg)\n .digest();\n const tmp = hashCons(undefined);\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.canXOF = tmp.canXOF;\n hashC.create = (opts) => hashCons(opts);\n Object.assign(hashC, info);\n return Object.freeze(hashC);\n}\n/**\n * Cryptographically secure PRNG backed by `crypto.getRandomValues`.\n * @param bytesLength - number of random bytes to generate\n * @returns Random bytes.\n * The platform `getRandomValues()` implementation still defines any\n * single-call length cap, and this helper rejects oversize requests\n * with a stable library `RangeError` instead of host-specific errors.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @throws If the current runtime does not provide `crypto.getRandomValues`. {@link Error}\n * @example\n * Generate a fresh random key or nonce.\n * ```ts\n * const key = randomBytes(16);\n * ```\n */\nexport function randomBytes(bytesLength = 32) {\n // Match the repo's other length-taking helpers instead of relying on Uint8Array coercion.\n anumber(bytesLength, 'bytesLength');\n const cr = typeof globalThis === 'object' ? globalThis.crypto : null;\n if (typeof cr?.getRandomValues !== 'function')\n throw new Error('crypto.getRandomValues must be defined');\n // Web Cryptography API Level 2 §10.1.1:\n // if `byteLength > 65536`, throw `QuotaExceededError`.\n // Keep the guard explicit so callers can see the quota in code\n // instead of discovering it by reading the spec or host errors.\n // This wrapper surfaces the same quota as a stable library RangeError.\n if (bytesLength > 65536)\n throw new RangeError(`\"bytesLength\" expected <= 65536, got ${bytesLength}`);\n return cr.getRandomValues(new Uint8Array(bytesLength));\n}\n/**\n * Creates OID metadata for NIST hashes with prefix `06 09 60 86 48 01 65 03 04 02`.\n * @param suffix - final OID byte for the selected hash.\n * The helper accepts any byte even though only the documented NIST hash\n * suffixes are meaningful downstream.\n * @returns Object containing the DER-encoded OID.\n * @example\n * Build OID metadata for a NIST hash.\n * ```ts\n * oidNist(0x01);\n * ```\n */\nexport const oidNist = (suffix) => ({\n // Current NIST hashAlgs suffixes used here fit in one DER subidentifier octet.\n // Larger suffix values would need base-128 OID encoding and a different length byte.\n oid: Uint8Array.from([0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, suffix]),\n});\n//# sourceMappingURL=utils.js.map","/**\n * Internal Merkle-Damgard hash utils.\n * @module\n */\nimport { abytes, aexists, aoutput, clean, createView, } from \"./utils.js\";\n/**\n * Shared 32-bit conditional boolean primitive reused by SHA-256, SHA-1, and MD5 `F`.\n * Returns bits from `b` when `a` is set, otherwise from `c`.\n * The XOR form is equivalent to MD5's `F(X,Y,Z) = XY v not(X)Z` because the masked terms never\n * set the same bit.\n * @param a - selector word\n * @param b - word chosen when selector bit is set\n * @param c - word chosen when selector bit is clear\n * @returns Mixed 32-bit word.\n * @example\n * Combine three words with the shared 32-bit choice primitive.\n * ```ts\n * Chi(0xffffffff, 0x12345678, 0x87654321);\n * ```\n */\nexport function Chi(a, b, c) {\n return (a & b) ^ (~a & c);\n}\n/**\n * Shared 32-bit majority primitive reused by SHA-256 and SHA-1.\n * Returns bits shared by at least two inputs.\n * @param a - first input word\n * @param b - second input word\n * @param c - third input word\n * @returns Mixed 32-bit word.\n * @example\n * Combine three words with the shared 32-bit majority primitive.\n * ```ts\n * Maj(0xffffffff, 0x12345678, 0x87654321);\n * ```\n */\nexport function Maj(a, b, c) {\n return (a & b) ^ (a & c) ^ (b & c);\n}\n/**\n * Merkle-Damgard hash construction base class.\n * Could be used to create MD5, RIPEMD, SHA1, SHA2.\n * Accepts only byte-aligned `Uint8Array` input, even when the underlying spec describes bit\n * strings with partial-byte tails.\n * @param blockLen - internal block size in bytes\n * @param outputLen - digest size in bytes\n * @param padOffset - trailing length field size in bytes\n * @param isLE - whether length and state words are encoded in little-endian\n * @example\n * Use a concrete subclass to get the shared Merkle-Damgard update/digest flow.\n * ```ts\n * import { _SHA1 } from '@noble/hashes/legacy.js';\n * const hash = new _SHA1();\n * hash.update(new Uint8Array([97, 98, 99]));\n * hash.digest();\n * ```\n */\nexport class HashMD {\n blockLen;\n outputLen;\n canXOF = false;\n padOffset;\n isLE;\n // For partial updates less than block size\n buffer;\n view;\n finished = false;\n length = 0;\n pos = 0;\n destroyed = false;\n constructor(blockLen, outputLen, padOffset, isLE) {\n this.blockLen = blockLen;\n this.outputLen = outputLen;\n this.padOffset = padOffset;\n this.isLE = isLE;\n this.buffer = new Uint8Array(blockLen);\n this.view = createView(this.buffer);\n }\n update(data) {\n aexists(this);\n abytes(data);\n const { view, buffer, blockLen } = this;\n const len = data.length;\n for (let pos = 0; pos < len;) {\n const take = Math.min(blockLen - this.pos, len - pos);\n // Fast path only when there is no buffered partial block: `take === blockLen` implies\n // `this.pos === 0`, so we can process full blocks directly from the input view.\n if (take === blockLen) {\n const dataView = createView(data);\n for (; blockLen <= len - pos; pos += blockLen)\n this.process(dataView, pos);\n continue;\n }\n buffer.set(data.subarray(pos, pos + take), this.pos);\n this.pos += take;\n pos += take;\n if (this.pos === blockLen) {\n this.process(view, 0);\n this.pos = 0;\n }\n }\n this.length += data.length;\n this.roundClean();\n return this;\n }\n digestInto(out) {\n aexists(this);\n aoutput(out, this);\n this.finished = true;\n // Padding\n // We can avoid allocation of buffer for padding completely if it\n // was previously not allocated here. But it won't change performance.\n const { buffer, view, blockLen, isLE } = this;\n let { pos } = this;\n // append the bit '1' to the message\n buffer[pos++] = 0b10000000;\n clean(this.buffer.subarray(pos));\n // we have less than padOffset left in buffer, so we cannot put length in\n // current block, need process it and pad again\n if (this.padOffset > blockLen - pos) {\n this.process(view, 0);\n pos = 0;\n }\n // Pad until full block byte with zeros\n for (let i = pos; i < blockLen; i++)\n buffer[i] = 0;\n // `padOffset` reserves the whole length field. For SHA-384/512 the high 64 bits stay zero from\n // the padding fill above, and JS will overflow before user input can make that half non-zero.\n // So we only need to write the low 64 bits here.\n view.setBigUint64(blockLen - 8, BigInt(this.length * 8), isLE);\n this.process(view, 0);\n const oview = createView(out);\n const len = this.outputLen;\n // NOTE: we do division by 4 later, which must be fused in single op with modulo by JIT\n if (len % 4)\n throw new Error('_sha2: outputLen must be aligned to 32bit');\n const outLen = len / 4;\n const state = this.get();\n if (outLen > state.length)\n throw new Error('_sha2: outputLen bigger than state');\n for (let i = 0; i < outLen; i++)\n oview.setUint32(4 * i, state[i], isLE);\n }\n digest() {\n const { buffer, outputLen } = this;\n this.digestInto(buffer);\n // Copy before destroy(): subclasses wipe `buffer` during cleanup, but `digest()` must return\n // fresh bytes to the caller.\n const res = buffer.slice(0, outputLen);\n this.destroy();\n return res;\n }\n _cloneInto(to) {\n to ||= new this.constructor();\n to.set(...this.get());\n const { blockLen, buffer, length, finished, destroyed, pos } = this;\n to.destroyed = destroyed;\n to.finished = finished;\n to.length = length;\n to.pos = pos;\n // Only partial-block bytes need copying: when `length % blockLen === 0`, `pos === 0` and\n // later `update()` / `digestInto()` overwrite `to.buffer` from the start before reading it.\n if (length % blockLen)\n to.buffer.set(buffer);\n return to;\n }\n clone() {\n return this._cloneInto();\n }\n}\n/**\n * Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.\n * Check out `test/misc/sha2-gen-iv.js` for recomputation guide.\n */\n/** Initial SHA256 state from RFC 6234 §6.1: the first 32 bits of the fractional parts of the\n * square roots of the first eight prime numbers. Exported as a shared table; callers must treat\n * it as read-only because constructors copy words from it by index. */\nexport const SHA256_IV = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,\n]);\n/** Initial SHA224 state `H(0)` from RFC 6234 §6.1. Exported as a shared table; callers must\n * treat it as read-only because constructors copy words from it by index. */\nexport const SHA224_IV = /* @__PURE__ */ Uint32Array.from([\n 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4,\n]);\n/** Initial SHA384 state from RFC 6234 §6.3: eight RFC 64-bit `H(0)` words stored as sixteen\n * big-endian 32-bit halves. Derived from the fractional parts of the square roots of the ninth\n * through sixteenth prime numbers. Exported as a shared table; callers must treat it as read-only\n * because constructors copy halves from it by index. */\nexport const SHA384_IV = /* @__PURE__ */ Uint32Array.from([\n 0xcbbb9d5d, 0xc1059ed8, 0x629a292a, 0x367cd507, 0x9159015a, 0x3070dd17, 0x152fecd8, 0xf70e5939,\n 0x67332667, 0xffc00b31, 0x8eb44a87, 0x68581511, 0xdb0c2e0d, 0x64f98fa7, 0x47b5481d, 0xbefa4fa4,\n]);\n/** Initial SHA512 state from RFC 6234 §6.3: eight RFC 64-bit `H(0)` words stored as sixteen\n * big-endian 32-bit halves. Derived from the fractional parts of the square roots of the first\n * eight prime numbers. Exported as a shared table; callers must treat it as read-only because\n * constructors copy halves from it by index. */\nexport const SHA512_IV = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xf3bcc908, 0xbb67ae85, 0x84caa73b, 0x3c6ef372, 0xfe94f82b, 0xa54ff53a, 0x5f1d36f1,\n 0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, 0x1f83d9ab, 0xfb41bd6b, 0x5be0cd19, 0x137e2179,\n]);\n//# sourceMappingURL=_md.js.map","const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);\nconst _32n = /* @__PURE__ */ BigInt(32);\n// Split bigint into two 32-bit halves. With `le=true`, returned fields become `{ h: low, l: high\n// }` to match little-endian word order rather than the property names.\nfunction fromBig(n, le = false) {\n if (le)\n return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };\n return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };\n}\n// Split bigint list into `[highWords, lowWords]` when `le=false`; with `le=true`, the first array\n// holds the low halves because `fromBig(...)` swaps the semantic meaning of `h` and `l`.\nfunction split(lst, le = false) {\n const len = lst.length;\n let Ah = new Uint32Array(len);\n let Al = new Uint32Array(len);\n for (let i = 0; i < len; i++) {\n const { h, l } = fromBig(lst[i], le);\n [Ah[i], Al[i]] = [h, l];\n }\n return [Ah, Al];\n}\n// Combine explicit `(high, low)` 32-bit halves into a bigint; `>>> 0` normalizes signed JS\n// bitwise results back to uint32 first, and little-endian callers must swap.\nconst toBig = (h, l) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);\n// High 32-bit half of a 64-bit logical right shift for `s` in `0..31`.\nconst shrSH = (h, _l, s) => h >>> s;\n// Low 32-bit half of a 64-bit logical right shift, valid for `s` in `1..31`.\nconst shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);\n// High 32-bit half of a 64-bit right rotate, valid for `s` in `1..31`.\nconst rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s));\n// Low 32-bit half of a 64-bit right rotate, valid for `s` in `1..31`.\nconst rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);\n// High 32-bit half of a 64-bit right rotate, valid for `s` in `33..63`; `32` uses `rotr32*`.\nconst rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32));\n// Low 32-bit half of a 64-bit right rotate, valid for `s` in `33..63`; `32` uses `rotr32*`.\nconst rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s));\n// High 32-bit half of a 64-bit right rotate for `s === 32`; this is just the swapped low half.\nconst rotr32H = (_h, l) => l;\n// Low 32-bit half of a 64-bit right rotate for `s === 32`; this is just the swapped high half.\nconst rotr32L = (h, _l) => h;\n// High 32-bit half of a 64-bit left rotate, valid for `s` in `1..31`.\nconst rotlSH = (h, l, s) => (h << s) | (l >>> (32 - s));\n// Low 32-bit half of a 64-bit left rotate, valid for `s` in `1..31`.\nconst rotlSL = (h, l, s) => (l << s) | (h >>> (32 - s));\n// High 32-bit half of a 64-bit left rotate, valid for `s` in `33..63`; `32` uses `rotr32*`.\nconst rotlBH = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s));\n// Low 32-bit half of a 64-bit left rotate, valid for `s` in `33..63`; `32` uses `rotr32*`.\nconst rotlBL = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s));\n// Add two split 64-bit words and return the split `{ h, l }` sum.\n// JS uses 32-bit signed integers for bitwise operations, so we cannot simply shift the carry out\n// of the low sum and instead use division.\nfunction add(Ah, Al, Bh, Bl) {\n const l = (Al >>> 0) + (Bl >>> 0);\n return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };\n}\n// Addition with more than 2 elements\n// Unmasked low-word accumulator for 3-way addition; pass the raw result into `add3H(...)`.\nconst add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);\n// High-word finalize step for 3-way addition; `low` must be the untruncated output of `add3L(...)`.\nconst add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;\n// Unmasked low-word accumulator for 4-way addition; pass the raw result into `add4H(...)`.\nconst add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);\n// High-word finalize step for 4-way addition; `low` must be the untruncated output of `add4L(...)`.\nconst add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;\n// Unmasked low-word accumulator for 5-way addition; pass the raw result into `add5H(...)`.\nconst add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);\n// High-word finalize step for 5-way addition; `low` must be the untruncated output of `add5L(...)`.\nconst add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;\n// prettier-ignore\nexport { add, add3H, add3L, add4H, add4L, add5H, add5L, fromBig, rotlBH, rotlBL, rotlSH, rotlSL, rotr32H, rotr32L, rotrBH, rotrBL, rotrSH, rotrSL, shrSH, shrSL, split, toBig };\n// Canonical grouped namespace for callers that prefer one object.\n// Named exports stay for direct imports.\n// prettier-ignore\nconst u64 = {\n fromBig, split, toBig,\n shrSH, shrSL,\n rotrSH, rotrSL, rotrBH, rotrBL,\n rotr32H, rotr32L,\n rotlSH, rotlSL, rotlBH, rotlBL,\n add, add3L, add3H, add4L, add4H, add5H, add5L,\n};\n// Default export mirrors named `u64` for compatibility with object-style imports.\nexport default u64;\n//# sourceMappingURL=_u64.js.map","/**\n * SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256.\n * SHA256 is the fastest hash implementable in JS, even faster than Blake3.\n * Check out {@link https://www.rfc-editor.org/rfc/rfc4634 | RFC 4634} and\n * {@link https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf | FIPS 180-4}.\n * @module\n */\nimport { Chi, HashMD, Maj, SHA224_IV, SHA256_IV, SHA384_IV, SHA512_IV } from \"./_md.js\";\nimport * as u64 from \"./_u64.js\";\nimport { clean, createHasher, oidNist, rotr } from \"./utils.js\";\n/**\n * SHA-224 / SHA-256 round constants from RFC 6234 §5.1: the first 32 bits\n * of the cube roots of the first 64 primes (2..311).\n */\n// prettier-ignore\nconst SHA256_K = /* @__PURE__ */ Uint32Array.from([\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2\n]);\n/** Reusable SHA-224 / SHA-256 message schedule buffer `W_t` from RFC 6234 §6.2 step 1. */\nconst SHA256_W = /* @__PURE__ */ new Uint32Array(64);\n/** Internal SHA-224 / SHA-256 compression engine from RFC 6234 §6.2. */\nclass SHA2_32B extends HashMD {\n constructor(outputLen) {\n super(64, outputLen, 8, false);\n }\n get() {\n const { A, B, C, D, E, F, G, H } = this;\n return [A, B, C, D, E, F, G, H];\n }\n // prettier-ignore\n set(A, B, C, D, E, F, G, H) {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n this.E = E | 0;\n this.F = F | 0;\n this.G = G | 0;\n this.H = H | 0;\n }\n process(view, offset) {\n // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4)\n SHA256_W[i] = view.getUint32(offset, false);\n for (let i = 16; i < 64; i++) {\n const W15 = SHA256_W[i - 15];\n const W2 = SHA256_W[i - 2];\n const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);\n const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);\n SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;\n }\n // Compression function main loop, 64 rounds\n let { A, B, C, D, E, F, G, H } = this;\n for (let i = 0; i < 64; i++) {\n const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);\n const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);\n const T2 = (sigma0 + Maj(A, B, C)) | 0;\n H = G;\n G = F;\n F = E;\n E = (D + T1) | 0;\n D = C;\n C = B;\n B = A;\n A = (T1 + T2) | 0;\n }\n // Add the compressed chunk to the current hash value\n A = (A + this.A) | 0;\n B = (B + this.B) | 0;\n C = (C + this.C) | 0;\n D = (D + this.D) | 0;\n E = (E + this.E) | 0;\n F = (F + this.F) | 0;\n G = (G + this.G) | 0;\n H = (H + this.H) | 0;\n this.set(A, B, C, D, E, F, G, H);\n }\n roundClean() {\n clean(SHA256_W);\n }\n destroy() {\n // HashMD callers route post-destroy usability through `destroyed`; zeroizing alone still leaves\n // update()/digest() callable on reused instances.\n this.destroyed = true;\n this.set(0, 0, 0, 0, 0, 0, 0, 0);\n clean(this.buffer);\n }\n}\n/** Internal SHA-256 hash class grounded in RFC 6234 §6.2. */\nexport class _SHA256 extends SHA2_32B {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n A = SHA256_IV[0] | 0;\n B = SHA256_IV[1] | 0;\n C = SHA256_IV[2] | 0;\n D = SHA256_IV[3] | 0;\n E = SHA256_IV[4] | 0;\n F = SHA256_IV[5] | 0;\n G = SHA256_IV[6] | 0;\n H = SHA256_IV[7] | 0;\n constructor() {\n super(32);\n }\n}\n/** Internal SHA-224 hash class grounded in RFC 6234 §6.2 and §8.5. */\nexport class _SHA224 extends SHA2_32B {\n A = SHA224_IV[0] | 0;\n B = SHA224_IV[1] | 0;\n C = SHA224_IV[2] | 0;\n D = SHA224_IV[3] | 0;\n E = SHA224_IV[4] | 0;\n F = SHA224_IV[5] | 0;\n G = SHA224_IV[6] | 0;\n H = SHA224_IV[7] | 0;\n constructor() {\n super(28);\n }\n}\n// SHA2-512 is slower than sha256 in js because u64 operations are slow.\n// SHA-384 / SHA-512 round constants from RFC 6234 §5.2:\n// 80 full 64-bit words split into high/low halves.\n// prettier-ignore\nconst K512 = /* @__PURE__ */ (() => u64.split([\n '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',\n '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',\n '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',\n '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',\n '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',\n '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',\n '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',\n '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',\n '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',\n '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',\n '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',\n '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',\n '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',\n '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',\n '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',\n '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',\n '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',\n '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',\n '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',\n '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'\n].map(n => BigInt(n))))();\nconst SHA512_Kh = /* @__PURE__ */ (() => K512[0])();\nconst SHA512_Kl = /* @__PURE__ */ (() => K512[1])();\n// Reusable high-half schedule buffer for the RFC 6234 §6.4 64-bit `W_t` words.\nconst SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);\n// Reusable low-half schedule buffer for the RFC 6234 §6.4 64-bit `W_t` words.\nconst SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);\n/** Internal SHA-384 / SHA-512 compression engine from RFC 6234 §6.4. */\nclass SHA2_64B extends HashMD {\n constructor(outputLen) {\n super(128, outputLen, 16, false);\n }\n // prettier-ignore\n get() {\n const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];\n }\n // prettier-ignore\n set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {\n this.Ah = Ah | 0;\n this.Al = Al | 0;\n this.Bh = Bh | 0;\n this.Bl = Bl | 0;\n this.Ch = Ch | 0;\n this.Cl = Cl | 0;\n this.Dh = Dh | 0;\n this.Dl = Dl | 0;\n this.Eh = Eh | 0;\n this.El = El | 0;\n this.Fh = Fh | 0;\n this.Fl = Fl | 0;\n this.Gh = Gh | 0;\n this.Gl = Gl | 0;\n this.Hh = Hh | 0;\n this.Hl = Hl | 0;\n }\n process(view, offset) {\n // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) {\n SHA512_W_H[i] = view.getUint32(offset);\n SHA512_W_L[i] = view.getUint32((offset += 4));\n }\n for (let i = 16; i < 80; i++) {\n // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)\n const W15h = SHA512_W_H[i - 15] | 0;\n const W15l = SHA512_W_L[i - 15] | 0;\n const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7);\n const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7);\n // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)\n const W2h = SHA512_W_H[i - 2] | 0;\n const W2l = SHA512_W_L[i - 2] | 0;\n const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6);\n const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6);\n // SHA512_W[i] = s0 + s1 + SHA512_W[i - 7] + SHA512_W[i - 16];\n const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);\n const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);\n SHA512_W_H[i] = SUMh | 0;\n SHA512_W_L[i] = SUMl | 0;\n }\n let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n // Compression function main loop, 80 rounds\n for (let i = 0; i < 80; i++) {\n // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)\n const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41);\n const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41);\n //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const CHIh = (Eh & Fh) ^ (~Eh & Gh);\n const CHIl = (El & Fl) ^ (~El & Gl);\n // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]\n // prettier-ignore\n const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);\n const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);\n const T1l = T1ll | 0;\n // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)\n const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39);\n const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39);\n const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);\n const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);\n Hh = Gh | 0;\n Hl = Gl | 0;\n Gh = Fh | 0;\n Gl = Fl | 0;\n Fh = Eh | 0;\n Fl = El | 0;\n ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));\n Dh = Ch | 0;\n Dl = Cl | 0;\n Ch = Bh | 0;\n Cl = Bl | 0;\n Bh = Ah | 0;\n Bl = Al | 0;\n const All = u64.add3L(T1l, sigma0l, MAJl);\n Ah = u64.add3H(All, T1h, sigma0h, MAJh);\n Al = All | 0;\n }\n // Add the compressed chunk to the current hash value\n ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));\n ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));\n ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));\n ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));\n ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));\n ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));\n ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));\n ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));\n this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);\n }\n roundClean() {\n clean(SHA512_W_H, SHA512_W_L);\n }\n destroy() {\n // HashMD callers route post-destroy usability through `destroyed`; zeroizing alone still leaves\n // update()/digest() callable on reused instances.\n this.destroyed = true;\n clean(this.buffer);\n this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);\n }\n}\n/** Internal SHA-512 hash class grounded in RFC 6234 §6.3 and §6.4. */\nexport class _SHA512 extends SHA2_64B {\n Ah = SHA512_IV[0] | 0;\n Al = SHA512_IV[1] | 0;\n Bh = SHA512_IV[2] | 0;\n Bl = SHA512_IV[3] | 0;\n Ch = SHA512_IV[4] | 0;\n Cl = SHA512_IV[5] | 0;\n Dh = SHA512_IV[6] | 0;\n Dl = SHA512_IV[7] | 0;\n Eh = SHA512_IV[8] | 0;\n El = SHA512_IV[9] | 0;\n Fh = SHA512_IV[10] | 0;\n Fl = SHA512_IV[11] | 0;\n Gh = SHA512_IV[12] | 0;\n Gl = SHA512_IV[13] | 0;\n Hh = SHA512_IV[14] | 0;\n Hl = SHA512_IV[15] | 0;\n constructor() {\n super(64);\n }\n}\n/** Internal SHA-384 hash class grounded in RFC 6234 §6.3 and §6.4. */\nexport class _SHA384 extends SHA2_64B {\n Ah = SHA384_IV[0] | 0;\n Al = SHA384_IV[1] | 0;\n Bh = SHA384_IV[2] | 0;\n Bl = SHA384_IV[3] | 0;\n Ch = SHA384_IV[4] | 0;\n Cl = SHA384_IV[5] | 0;\n Dh = SHA384_IV[6] | 0;\n Dl = SHA384_IV[7] | 0;\n Eh = SHA384_IV[8] | 0;\n El = SHA384_IV[9] | 0;\n Fh = SHA384_IV[10] | 0;\n Fl = SHA384_IV[11] | 0;\n Gh = SHA384_IV[12] | 0;\n Gl = SHA384_IV[13] | 0;\n Hh = SHA384_IV[14] | 0;\n Hl = SHA384_IV[15] | 0;\n constructor() {\n super(48);\n }\n}\n/**\n * Truncated SHA512/256 and SHA512/224.\n * SHA512_IV is XORed with 0xa5a5a5a5a5a5a5a5, then used as \"intermediary\" IV of SHA512/t.\n * Then t hashes string to produce result IV.\n * See the repo-side derivation recipe in `test/misc/sha2-gen-iv.js`.\n * These IV literals are checked against that script rather than a dedicated\n * local RFC section.\n */\n/** SHA-512/224 IV derived by the SHA-512/t recipe in `test/misc/sha2-gen-iv.js` and\n * stored as sixteen big-endian 32-bit halves. */\nconst T224_IV = /* @__PURE__ */ Uint32Array.from([\n 0x8c3d37c8, 0x19544da2, 0x73e19966, 0x89dcd4d6, 0x1dfab7ae, 0x32ff9c82, 0x679dd514, 0x582f9fcf,\n 0x0f6d2b69, 0x7bd44da8, 0x77e36f73, 0x04c48942, 0x3f9d85a8, 0x6a1d36c8, 0x1112e6ad, 0x91d692a1,\n]);\n/** SHA-512/256 IV derived by the SHA-512/t recipe in `test/misc/sha2-gen-iv.js` and\n * stored as sixteen big-endian 32-bit halves. */\nconst T256_IV = /* @__PURE__ */ Uint32Array.from([\n 0x22312194, 0xfc2bf72c, 0x9f555fa3, 0xc84c64c2, 0x2393b86b, 0x6f53b151, 0x96387719, 0x5940eabd,\n 0x96283ee2, 0xa88effe3, 0xbe5e1e25, 0x53863992, 0x2b0199fc, 0x2c85b8aa, 0x0eb72ddc, 0x81c52ca2,\n]);\n/** Internal SHA-512/224 hash class using the derived `T224_IV` and the shared\n * RFC 6234 §6.4 compression engine. */\nexport class _SHA512_224 extends SHA2_64B {\n Ah = T224_IV[0] | 0;\n Al = T224_IV[1] | 0;\n Bh = T224_IV[2] | 0;\n Bl = T224_IV[3] | 0;\n Ch = T224_IV[4] | 0;\n Cl = T224_IV[5] | 0;\n Dh = T224_IV[6] | 0;\n Dl = T224_IV[7] | 0;\n Eh = T224_IV[8] | 0;\n El = T224_IV[9] | 0;\n Fh = T224_IV[10] | 0;\n Fl = T224_IV[11] | 0;\n Gh = T224_IV[12] | 0;\n Gl = T224_IV[13] | 0;\n Hh = T224_IV[14] | 0;\n Hl = T224_IV[15] | 0;\n constructor() {\n super(28);\n }\n}\n/** Internal SHA-512/256 hash class using the derived `T256_IV` and the shared\n * RFC 6234 §6.4 compression engine. */\nexport class _SHA512_256 extends SHA2_64B {\n Ah = T256_IV[0] | 0;\n Al = T256_IV[1] | 0;\n Bh = T256_IV[2] | 0;\n Bl = T256_IV[3] | 0;\n Ch = T256_IV[4] | 0;\n Cl = T256_IV[5] | 0;\n Dh = T256_IV[6] | 0;\n Dl = T256_IV[7] | 0;\n Eh = T256_IV[8] | 0;\n El = T256_IV[9] | 0;\n Fh = T256_IV[10] | 0;\n Fl = T256_IV[11] | 0;\n Gh = T256_IV[12] | 0;\n Gl = T256_IV[13] | 0;\n Hh = T256_IV[14] | 0;\n Hl = T256_IV[15] | 0;\n constructor() {\n super(32);\n }\n}\n/**\n * SHA2-256 hash function from RFC 4634. In JS it's the fastest: even faster than Blake3. Some info:\n *\n * - Trying 2^128 hashes would get 50% chance of collision, using birthday attack.\n * - BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.\n * - Each sha256 hash is executing 2^18 bit operations.\n * - Good 2024 ASICs can do 200Th/sec with 3500 watts of power, corresponding to 2^36 hashes/joule.\n * @param msg - message bytes to hash\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-256.\n * ```ts\n * sha256(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha256 = /* @__PURE__ */ createHasher(() => new _SHA256(), \n/* @__PURE__ */ oidNist(0x01));\n/**\n * SHA2-224 hash function from RFC 4634.\n * @param msg - message bytes to hash\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-224.\n * ```ts\n * sha224(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha224 = /* @__PURE__ */ createHasher(() => new _SHA224(), \n/* @__PURE__ */ oidNist(0x04));\n/**\n * SHA2-512 hash function from RFC 4634.\n * @param msg - message bytes to hash\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-512.\n * ```ts\n * sha512(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha512 = /* @__PURE__ */ createHasher(() => new _SHA512(), \n/* @__PURE__ */ oidNist(0x03));\n/**\n * SHA2-384 hash function from RFC 4634.\n * @param msg - message bytes to hash\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-384.\n * ```ts\n * sha384(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha384 = /* @__PURE__ */ createHasher(() => new _SHA384(), \n/* @__PURE__ */ oidNist(0x02));\n/**\n * SHA2-512/256 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on {@link https://eprint.iacr.org/2010/548.pdf | truncated SHA512}.\n * @param msg - message bytes to hash\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-512/256.\n * ```ts\n * sha512_256(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha512_256 = /* @__PURE__ */ createHasher(() => new _SHA512_256(), \n/* @__PURE__ */ oidNist(0x06));\n/**\n * SHA2-512/224 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on {@link https://eprint.iacr.org/2010/548.pdf | truncated SHA512}.\n * @param msg - message bytes to hash\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-512/224.\n * ```ts\n * sha512_224(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha512_224 = /* @__PURE__ */ createHasher(() => new _SHA512_224(), \n/* @__PURE__ */ oidNist(0x05));\n//# sourceMappingURL=sha2.js.map","/**\n * Ed25519 key generation, persistence, and challenge signing for the Resend bridge.\n * Same shape as @abraca/mcp's crypto module; intentionally vendored so this package\n * doesn't depend on @abraca/mcp.\n */\nimport * as ed from \"@noble/ed25519\";\nimport { sha512 } from \"@noble/hashes/sha2.js\";\nimport { existsSync } from \"node:fs\";\nimport { mkdir, readFile, writeFile } from \"node:fs/promises\";\nimport { homedir } from \"node:os\";\nimport { dirname, join } from \"node:path\";\n\ned.hashes.sha512 = sha512;\ned.hashes.sha512Async = (m: Uint8Array) => Promise.resolve(sha512(m));\n\nconst DEFAULT_KEY_PATH = join(homedir(), \".abracadabra\", \"resend.key\");\n\nfunction toBase64url(bytes: Uint8Array): string {\n\treturn Buffer.from(bytes).toString(\"base64url\");\n}\n\nfunction fromBase64url(b64: string): Uint8Array {\n\treturn new Uint8Array(Buffer.from(b64, \"base64url\"));\n}\n\nexport interface AgentKeypair {\n\tprivateKey: Uint8Array;\n\tpublicKeyB64: string;\n}\n\nexport async function loadOrCreateKeypair(\n\tkeyPath?: string,\n): Promise<AgentKeypair> {\n\tconst path = keyPath || DEFAULT_KEY_PATH;\n\n\tif (existsSync(path)) {\n\t\tconst seed = await readFile(path);\n\t\tif (seed.length !== 32) {\n\t\t\tthrow new Error(\n\t\t\t\t`Invalid key file at ${path}: expected 32 bytes, got ${seed.length}`,\n\t\t\t);\n\t\t}\n\t\tconst privateKey = new Uint8Array(seed);\n\t\tconst publicKey = ed.getPublicKey(privateKey);\n\t\treturn { privateKey, publicKeyB64: toBase64url(publicKey) };\n\t}\n\n\tconst privateKey = ed.utils.randomSecretKey();\n\tconst publicKey = ed.getPublicKey(privateKey);\n\n\tconst dir = dirname(path);\n\tif (!existsSync(dir)) {\n\t\tawait mkdir(dir, { recursive: true, mode: 0o700 });\n\t}\n\tawait writeFile(path, Buffer.from(privateKey), { mode: 0o600 });\n\n\tconsole.error(`[abracadabra-resend] Generated new agent keypair at ${path}`);\n\tconsole.error(\n\t\t`[abracadabra-resend] Public key: ${toBase64url(publicKey)}`,\n\t);\n\n\treturn { privateKey, publicKeyB64: toBase64url(publicKey) };\n}\n\nexport function signChallenge(\n\tchallengeB64: string,\n\tprivateKey: Uint8Array,\n): string {\n\tconst challenge = fromBase64url(challengeB64);\n\tconst sig = ed.sign(challenge, privateKey);\n\treturn toBase64url(sig);\n}\n","/**\n * AbracadabraResendServer — connection lifecycle for the Resend bridge.\n *\n * Trimmed-down equivalent of @abraca/mcp's server: Ed25519 identity, login/\n * register, single-space binding, child-provider cache with idle eviction,\n * `ensureConnected` heal on dropped sockets / expired JWTs. No awareness,\n * no chat, no tool wiring — this is a daemon, not an agent.\n */\nimport type { DocumentMeta, ServerInfo } from \"@abraca/dabra\";\nimport {\n\tAbracadabraClient,\n\tAbracadabraProvider,\n\tKind,\n\tSERVER_ROOT_ID,\n\tWebSocketStatus,\n} from \"@abraca/dabra\";\nimport * as Y from \"yjs\";\nimport { loadOrCreateKeypair, signChallenge } from \"./crypto.ts\";\nimport { waitForSync } from \"./utils.ts\";\n\nexport interface ResendServerConfig {\n\turl: string;\n\tagentName?: string;\n\tkeyFile?: string;\n\tinviteCode?: string;\n\t/** Bind to this space id. When omitted, the first visible space is used. */\n\tspaceId?: string;\n}\n\ninterface SpaceConnection {\n\tdoc: Y.Doc;\n\tprovider: AbracadabraProvider;\n\tdocId: string;\n}\n\ninterface CachedProvider {\n\tprovider: AbracadabraProvider;\n\tlastAccessed: number;\n}\n\nconst IDLE_TIMEOUT_MS = 5 * 60 * 1000;\n\nexport class AbracadabraResendServer {\n\treadonly config: ResendServerConfig;\n\treadonly client: AbracadabraClient;\n\tprivate _serverInfo: ServerInfo | null = null;\n\tprivate _spaces: DocumentMeta[] = [];\n\tprivate _connection: SpaceConnection | null = null;\n\tprivate childCache = new Map<string, CachedProvider>();\n\tprivate evictionTimer: ReturnType<typeof setInterval> | null = null;\n\tprivate _userId: string | null = null;\n\tprivate _signFn: ((challenge: string) => Promise<string>) | null = null;\n\tprivate _reconnecting: Promise<void> | null = null;\n\n\tconstructor(config: ResendServerConfig) {\n\t\tthis.config = config;\n\t\tthis.client = new AbracadabraClient({\n\t\t\turl: config.url,\n\t\t\tpersistAuth: false,\n\t\t});\n\t}\n\n\tget agentName(): string {\n\t\treturn this.config.agentName || \"Resend Bridge\";\n\t}\n\n\tget serverInfo(): ServerInfo | null {\n\t\treturn this._serverInfo;\n\t}\n\n\tget spaceDocId(): string | null {\n\t\treturn this._connection?.docId ?? null;\n\t}\n\n\tget rootDocument(): Y.Doc | null {\n\t\treturn this._connection?.doc ?? null;\n\t}\n\n\tget rootProvider(): AbracadabraProvider | null {\n\t\treturn this._connection?.provider ?? null;\n\t}\n\n\tget userId(): string | null {\n\t\treturn this._userId;\n\t}\n\n\tget spaces(): DocumentMeta[] {\n\t\treturn this._spaces;\n\t}\n\n\t/** Authenticate, discover spaces, connect to the configured (or first) space. */\n\tasync connect(): Promise<void> {\n\t\tconst keypair = await loadOrCreateKeypair(this.config.keyFile);\n\t\tthis._userId = keypair.publicKeyB64;\n\t\tconst signFn = (challenge: string) =>\n\t\t\tPromise.resolve(signChallenge(challenge, keypair.privateKey));\n\t\tthis._signFn = signFn;\n\n\t\ttry {\n\t\t\tawait this.client.loginWithKey(keypair.publicKeyB64, signFn);\n\t\t} catch (err: any) {\n\t\t\tconst status = err?.status ?? err?.response?.status;\n\t\t\tconst msg = String(err?.message ?? \"\").toLowerCase();\n\t\t\tconst notRegistered =\n\t\t\t\tstatus === 404 ||\n\t\t\t\tstatus === 422 ||\n\t\t\t\t(status === 401 &&\n\t\t\t\t\t/not registered|user not found|no such user/.test(msg));\n\t\t\tif (!notRegistered) throw err;\n\t\t\tconsole.error(\n\t\t\t\t\"[abracadabra-resend] Key not registered, creating new account...\",\n\t\t\t);\n\t\t\tawait this.client.registerWithKey({\n\t\t\t\tpublicKey: keypair.publicKeyB64,\n\t\t\t\tusername: this.agentName.replace(/\\s+/g, \"-\").toLowerCase(),\n\t\t\t\tdisplayName: this.agentName,\n\t\t\t\tdeviceName: \"Resend Bridge\",\n\t\t\t\tinviteCode: this.config.inviteCode,\n\t\t\t});\n\t\t\tawait this.client.loginWithKey(keypair.publicKeyB64, signFn);\n\t\t}\n\t\tconsole.error(\n\t\t\t`[abracadabra-resend] Authenticated as ${this.agentName} (pubkey=${keypair.publicKeyB64})`,\n\t\t);\n\n\t\tthis._serverInfo = await this.client.serverInfo();\n\n\t\tconst roots = await this.client.listChildren();\n\t\tthis._spaces = roots.filter((d) => d.kind === Kind.Space);\n\n\t\tlet targetId = this.config.spaceId;\n\t\tif (targetId) {\n\t\t\tconst found =\n\t\t\t\tthis._spaces.find((s) => s.id === targetId) ??\n\t\t\t\troots.find((d) => d.id === targetId);\n\t\t\tif (!found) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Configured ABRA_SPACE_ID=${targetId} not found among server roots`,\n\t\t\t\t);\n\t\t\t}\n\t\t} else {\n\t\t\ttargetId = this._spaces[0]?.id ?? roots[0]?.id;\n\t\t\tif (!targetId) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`No entry point found: server has no top-level documents under ${SERVER_ROOT_ID}.`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\tconsole.error(`[abracadabra-resend] Binding to space ${targetId}`);\n\t\tawait this._connectToSpace(targetId);\n\t\tconsole.error(\"[abracadabra-resend] Space doc synced\");\n\n\t\tthis.evictionTimer = setInterval(() => this.evictIdle(), 60_000);\n\t}\n\n\tprivate async _connectToSpace(docId: string): Promise<SpaceConnection> {\n\t\tif (!this.client.isTokenValid() && this._signFn && this._userId) {\n\t\t\tconsole.error(\"[abracadabra-resend] JWT expired, re-authenticating...\");\n\t\t\tawait this.client.loginWithKey(this._userId, this._signFn);\n\t\t}\n\n\t\tconst doc = new Y.Doc({ guid: docId });\n\t\tconst provider = new AbracadabraProvider({\n\t\t\tname: docId,\n\t\t\tdocument: doc,\n\t\t\tclient: this.client,\n\t\t\tdisableOfflineStore: true,\n\t\t\tsubdocLoading: \"lazy\",\n\t\t});\n\n\t\tawait waitForSync(provider);\n\n\t\tprovider.awareness?.setLocalStateField(\"user\", {\n\t\t\tname: this.agentName,\n\t\t\tcolor: \"hsl(170, 70%, 45%)\",\n\t\t\tpublicKey: this._userId,\n\t\t\tisAgent: true,\n\t\t});\n\n\t\tconst conn: SpaceConnection = { doc, provider, docId };\n\t\tthis._connection = conn;\n\t\treturn conn;\n\t}\n\n\tprivate _wsConnected(provider: AbracadabraProvider): boolean {\n\t\treturn provider.connectionStatus === WebSocketStatus.Connected;\n\t}\n\n\t/**\n\t * Heal a dropped socket / expired JWT before tool ops. De-duped across\n\t * concurrent callers; best-effort (never throws — a failed heal falls\n\t * through to the caller's normal error handling).\n\t */\n\tasync ensureConnected(): Promise<void> {\n\t\tif (this._reconnecting) return this._reconnecting;\n\t\tthis._reconnecting = (async () => {\n\t\t\ttry {\n\t\t\t\tif (!this.client.isTokenValid() && this._signFn && this._userId) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait this.client.loginWithKey(this._userId, this._signFn);\n\t\t\t\t\t} catch (e) {\n\t\t\t\t\t\tconsole.error(\"[abracadabra-resend] Re-auth during heal failed:\", e);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tconst conn = this._connection;\n\t\t\t\tif (!conn) return;\n\t\t\t\tif (this._wsConnected(conn.provider)) return;\n\t\t\t\ttry {\n\t\t\t\t\tawait waitForSync(conn.provider, 6000);\n\t\t\t\t} catch {\n\t\t\t\t\t/* fall through to rebuild */\n\t\t\t\t}\n\t\t\t\tif (this._wsConnected(conn.provider)) return;\n\n\t\t\t\tconsole.error(\n\t\t\t\t\t\"[abracadabra-resend] Active connection dead — rebuilding…\",\n\t\t\t\t);\n\t\t\t\tconst docId = conn.docId;\n\t\t\t\ttry {\n\t\t\t\t\tconn.provider.destroy();\n\t\t\t\t} catch {\n\t\t\t\t\t/* already gone */\n\t\t\t\t}\n\t\t\t\tfor (const [, cached] of this.childCache) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tcached.provider.destroy();\n\t\t\t\t\t} catch {\n\t\t\t\t\t\t/* already gone */\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tthis.childCache.clear();\n\t\t\t\ttry {\n\t\t\t\t\tawait this._connectToSpace(docId);\n\t\t\t\t\tconsole.error(\"[abracadabra-resend] Space provider rebuilt + synced\");\n\t\t\t\t} catch (e) {\n\t\t\t\t\tconsole.error(\"[abracadabra-resend] Connection rebuild failed:\", e);\n\t\t\t\t}\n\t\t\t} finally {\n\t\t\t\tthis._reconnecting = null;\n\t\t\t}\n\t\t})();\n\t\treturn this._reconnecting;\n\t}\n\n\tgetTreeMap(): Y.Map<any> | null {\n\t\treturn this._connection?.doc.getMap(\"doc-tree\") ?? null;\n\t}\n\n\tasync getChildProvider(docId: string): Promise<AbracadabraProvider> {\n\t\tawait this.ensureConnected();\n\n\t\tconst cached = this.childCache.get(docId);\n\t\tif (\n\t\t\tcached &&\n\t\t\tcached.provider.connectionStatus !== WebSocketStatus.Disconnected\n\t\t) {\n\t\t\tcached.lastAccessed = Date.now();\n\t\t\treturn cached.provider;\n\t\t}\n\t\tif (cached) {\n\t\t\ttry {\n\t\t\t\tcached.provider.destroy();\n\t\t\t} catch {\n\t\t\t\t/* already gone */\n\t\t\t}\n\t\t\tthis.childCache.delete(docId);\n\t\t}\n\n\t\tconst root = this._connection?.provider;\n\t\tif (!root) throw new Error(\"Not connected. Call connect() first.\");\n\n\t\tif (!this.client.isTokenValid() && this._signFn && this._userId) {\n\t\t\tawait this.client.loginWithKey(this._userId, this._signFn);\n\t\t}\n\n\t\tconst childProvider = await root.loadChild(docId);\n\t\tawait waitForSync(childProvider);\n\n\t\tthis.childCache.set(docId, {\n\t\t\tprovider: childProvider,\n\t\t\tlastAccessed: Date.now(),\n\t\t});\n\n\t\treturn childProvider;\n\t}\n\n\tprivate evictIdle(): void {\n\t\tconst now = Date.now();\n\t\tfor (const [docId, cached] of this.childCache) {\n\t\t\tif (now - cached.lastAccessed > IDLE_TIMEOUT_MS) {\n\t\t\t\tcached.provider.destroy();\n\t\t\t\tthis.childCache.delete(docId);\n\t\t\t\tconsole.error(`[abracadabra-resend] Evicted idle provider: ${docId}`);\n\t\t\t}\n\t\t}\n\t}\n\n\tasync destroy(): Promise<void> {\n\t\tif (this.evictionTimer) {\n\t\t\tclearInterval(this.evictionTimer);\n\t\t\tthis.evictionTimer = null;\n\t\t}\n\t\tfor (const [, cached] of this.childCache) {\n\t\t\ttry {\n\t\t\t\tcached.provider.destroy();\n\t\t\t} catch {\n\t\t\t\t/* already gone */\n\t\t\t}\n\t\t}\n\t\tthis.childCache.clear();\n\t\tif (this._connection) {\n\t\t\ttry {\n\t\t\t\tthis._connection.provider.destroy();\n\t\t\t} catch {\n\t\t\t\t/* already gone */\n\t\t\t}\n\t\t\tthis._connection = null;\n\t\t}\n\t\tconsole.error(\"[abracadabra-resend] Shutdown complete\");\n\t}\n}\n","#!/usr/bin/env node\n/**\n * @abraca/resend — entry point.\n *\n * Environment variables:\n * ABRA_URL (required) — Abracadabra server URL\n * ABRA_SPACE_ID — Pin to a specific space (default: first visible)\n * ABRA_KEY_FILE — Ed25519 seed path (default ~/.abracadabra/resend.key)\n * ABRA_INVITE_CODE — Used only on first-run register\n * ABRA_AGENT_NAME — Display name (default \"Resend Bridge\")\n *\n * RESEND_API_KEY (required) — Resend API key\n * RESEND_FROM (required) — Default `from` address\n * RESEND_INBOUND_ENABLED — \"false\" to skip the webhook server (default true)\n * RESEND_INBOUND_PORT — Bind port for /inbound (default 0 = ephemeral)\n * RESEND_INBOUND_HOST — Bind host (default 0.0.0.0)\n * RESEND_INBOUND_SECRET — Required when inbound is enabled (Svix signing secret)\n */\nimport { bootstrap } from \"./bootstrap.ts\";\nimport { InboundServer } from \"./inbound-server.ts\";\nimport { OutboxWatcher } from \"./outbox-watcher.ts\";\nimport { ResendClient } from \"./resend-client.ts\";\nimport { AbracadabraResendServer } from \"./server.ts\";\n\nfunction required(name: string): string {\n\tconst value = process.env[name];\n\tif (!value || value.trim().length === 0) {\n\t\tconsole.error(`[abracadabra-resend] Missing required env var: ${name}`);\n\t\tprocess.exit(1);\n\t}\n\treturn value;\n}\n\nfunction boolEnv(name: string, fallback: boolean): boolean {\n\tconst v = process.env[name];\n\tif (v === undefined) return fallback;\n\tconst norm = v.trim().toLowerCase();\n\tif ([\"0\", \"false\", \"no\", \"off\", \"\"].includes(norm)) return false;\n\treturn true;\n}\n\nasync function main(): Promise<void> {\n\tconst url = required(\"ABRA_URL\");\n\tconst resendApiKey = required(\"RESEND_API_KEY\");\n\tconst defaultFrom = required(\"RESEND_FROM\");\n\n\tconst inboundEnabled = boolEnv(\"RESEND_INBOUND_ENABLED\", true);\n\tconst inboundSecret = inboundEnabled\n\t\t? required(\"RESEND_INBOUND_SECRET\")\n\t\t: process.env.RESEND_INBOUND_SECRET ?? \"\";\n\tconst inboundPort = process.env.RESEND_INBOUND_PORT\n\t\t? Number(process.env.RESEND_INBOUND_PORT)\n\t\t: 0;\n\tconst inboundHost = process.env.RESEND_INBOUND_HOST ?? \"0.0.0.0\";\n\n\tconst server = new AbracadabraResendServer({\n\t\turl,\n\t\tspaceId: process.env.ABRA_SPACE_ID,\n\t\tkeyFile: process.env.ABRA_KEY_FILE,\n\t\tinviteCode: process.env.ABRA_INVITE_CODE,\n\t\tagentName: process.env.ABRA_AGENT_NAME,\n\t});\n\n\ttry {\n\t\tawait server.connect();\n\t} catch (err: any) {\n\t\tconsole.error(`[abracadabra-resend] Failed to connect: ${err?.message ?? err}`);\n\t\tprocess.exit(1);\n\t}\n\n\tconst boot = await bootstrap(server);\n\tconsole.error(\n\t\t`[abracadabra-resend] Bootstrapped Inbox=${boot.inboxId} Outbox=${boot.outboxId}`,\n\t);\n\n\tconst sender = new ResendClient(resendApiKey);\n\tconst watcher = new OutboxWatcher({ server, sender, bootstrap: boot, defaultFrom });\n\twatcher.start();\n\n\tlet inbound: InboundServer | null = null;\n\tif (inboundEnabled) {\n\t\tinbound = new InboundServer({\n\t\t\tserver,\n\t\t\tbootstrap: boot,\n\t\t\tsecret: inboundSecret,\n\t\t\tport: Number.isFinite(inboundPort) ? inboundPort : 0,\n\t\t\thost: inboundHost,\n\t\t});\n\t\ttry {\n\t\t\tawait inbound.start();\n\t\t} catch (err: any) {\n\t\t\tconsole.error(\n\t\t\t\t`[abracadabra-resend] Inbound server failed to start: ${err?.message ?? err}`,\n\t\t\t);\n\t\t\tprocess.exit(1);\n\t\t}\n\t} else {\n\t\tconsole.error(\n\t\t\t\"[abracadabra-resend] Inbound disabled (RESEND_INBOUND_ENABLED=false)\",\n\t\t);\n\t}\n\n\tconsole.error(\"[abracadabra-resend] Ready.\");\n\n\tconst shutdown = async () => {\n\t\tconsole.error(\"[abracadabra-resend] Shutting down...\");\n\t\twatcher.stop();\n\t\tif (inbound) await inbound.stop();\n\t\tawait server.destroy();\n\t\tprocess.exit(0);\n\t};\n\tprocess.on(\"SIGINT\", shutdown);\n\tprocess.on(\"SIGTERM\", shutdown);\n}\n\nmain().catch((err) => {\n\tconsole.error(\"[abracadabra-resend] Fatal error:\", err);\n\tprocess.exit(1);\n});\n\nexport { AbracadabraResendServer } from \"./server.ts\";\nexport { bootstrap } from \"./bootstrap.ts\";\nexport { InboundServer } from \"./inbound-server.ts\";\nexport { OutboxWatcher } from \"./outbox-watcher.ts\";\nexport { ResendClient } from \"./resend-client.ts\";\nexport type { ResendSender, SendResult } from \"./resend-client.ts\";\nexport { renderEmail, RenderError } from \"./render.ts\";\nexport type { EmailPayload } from \"./render.ts\";\n"],"x_google_ignoreList":[6,7,8,9],"mappings":";;;;;;;;;;;;;;;;;;;;;AAWA,MAAa,cAAc;AAC3B,MAAa,eAAe;AAE5B,MAAa,iBAAiB;CAAC;CAAS;CAAS;CAAQ;CAAS;AAiBlE,SAAS,YACR,SACA,QACc;CACd,MAAM,UAAuB,EAAE;AAC/B,SAAQ,SAAS,KAAU,OAAe;AACzC,MAAI,UAAU,OAAO,OAAQ;EAC7B,MAAM,QAAQ,QAAQ,IAAI;AAC1B,MAAI,OAAO,UAAU,YAAY,UAAU,KAAM;AACjD,UAAQ,KAAK;GACZ;GACA,OAAO,OAAO,MAAM,UAAU,WAAW,MAAM,QAAQ;GACvD,UAAU,MAAM,YAAY;GAC5B,OAAO,OAAO,MAAM,UAAU,WAAW,MAAM,QAAQ;GACvD,MAAM,OAAO,MAAM,SAAS,WAAW,MAAM,OAAO;GACpD,CAAC;GACD;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AAI,QAAS,OAAM,QAAQ,MAAM;AACjC,QAAM,OAAO,SAAS;AACtB,UAAQ,KAAK,EAAE;;AAEhB,SAAQ,GAAG,UAAU,SAAS;AAC9B,SAAQ,GAAG,WAAW,SAAS;;AAGhC,MAAM,CAAC,OAAO,QAAQ;AACrB,SAAQ,MAAM,qCAAqC,IAAI;AACvD,SAAQ,KAAK,EAAE;EACd"}
|
|
1
|
+
{"version":3,"file":"abracadabra-resend.esm.js","names":["readEntry","u64.split","u64.rotrSH","u64.shrSH","u64.rotrSL","u64.shrSL","u64.rotrBH","u64.rotrBL","u64.add4L","u64.add4H","u64.add5L","u64.add5H","u64.add","u64.add3L","u64.add3H"],"sources":["../src/bootstrap.ts","../src/utils.ts","../src/inbound-server.ts","../src/render.ts","../src/outbox-watcher.ts","../src/resend-client.ts","../../../node_modules/@noble/hashes/utils.js","../../../node_modules/@noble/hashes/_md.js","../../../node_modules/@noble/hashes/_u64.js","../../../node_modules/@noble/hashes/sha2.js","../src/crypto.ts","../src/server.ts","../src/index.ts"],"sourcesContent":["/**\n * Find or create the Inbox + Outbox documents under the bound Space.\n *\n * Idempotent: any existing top-level doc labelled \"Inbox\" or \"Outbox\" is reused\n * as-is — the user is allowed to rename, recolor, or restructure these docs\n * after they're created. Missing columns under the Outbox kanban are filled in.\n */\nimport { makeEntryMap, toPlain } from \"@abraca/dabra\";\nimport * as Y from \"yjs\";\nimport type { AbracadabraResendServer } from \"./server.ts\";\n\nexport const INBOX_LABEL = \"Inbox\";\nexport const OUTBOX_LABEL = \"Outbox\";\n\nexport const OUTBOX_COLUMNS = [\"Draft\", \"Ready\", \"Sent\", \"Failed\"] as const;\nexport type OutboxColumn = (typeof OUTBOX_COLUMNS)[number];\n\nexport interface BootstrapResult {\n\tinboxId: string;\n\toutboxId: string;\n\tcolumns: Record<OutboxColumn, string>;\n}\n\ninterface TreeEntry {\n\tid: string;\n\tlabel: string;\n\tparentId: string | null;\n\torder: number;\n\ttype?: string;\n}\n\nfunction readEntries(\n\ttreeMap: Y.Map<any>,\n\tselfId: string | null,\n): TreeEntry[] {\n\tconst entries: TreeEntry[] = [];\n\ttreeMap.forEach((raw: any, id: string) => {\n\t\tif (selfId && id === selfId) return;\n\t\tconst value = toPlain(raw) as any;\n\t\tif (typeof value !== \"object\" || value === null) return;\n\t\tentries.push({\n\t\t\tid,\n\t\t\tlabel: typeof value.label === \"string\" ? value.label : \"Untitled\",\n\t\t\tparentId: value.parentId ?? null,\n\t\t\torder: typeof value.order === \"number\" ? value.order : 0,\n\t\t\ttype: typeof value.type === \"string\" ? value.type : undefined,\n\t\t});\n\t});\n\treturn entries;\n}\n\nasync function createDoc(\n\tserver: AbracadabraResendServer,\n\topts: {\n\t\tparentTreeId: string | null;\n\t\trestParentId: string;\n\t\tlabel: string;\n\t\ttype?: string;\n\t\tmeta?: Record<string, unknown>;\n\t\torder?: number;\n\t},\n): Promise<string> {\n\tconst treeMap = server.getTreeMap();\n\tconst rootDoc = server.rootDocument;\n\tif (!treeMap || !rootDoc) {\n\t\tthrow new Error(\"Cannot create doc — server is not connected.\");\n\t}\n\tconst id = crypto.randomUUID();\n\tconst now = Date.now();\n\n\t// Register the SQL row first so RBAC inheritance can walk\n\t// `documents.parent_id` (matches @abraca/mcp's create_document path).\n\tawait server.client.createChild(opts.restParentId, {\n\t\tchild_id: id,\n\t\tlabel: opts.label,\n\t\tdoc_type: opts.type,\n\t\tkind: \"page\",\n\t});\n\n\trootDoc.transact(() => {\n\t\ttreeMap.set(\n\t\t\tid,\n\t\t\tmakeEntryMap({\n\t\t\t\tlabel: opts.label,\n\t\t\t\tparentId: opts.parentTreeId,\n\t\t\t\torder: opts.order ?? now,\n\t\t\t\ttype: opts.type,\n\t\t\t\tmeta: opts.meta as any,\n\t\t\t\tcreatedAt: now,\n\t\t\t\tupdatedAt: now,\n\t\t\t}),\n\t\t);\n\t});\n\n\treturn id;\n}\n\nexport async function bootstrap(\n\tserver: AbracadabraResendServer,\n): Promise<BootstrapResult> {\n\tconst treeMap = server.getTreeMap();\n\tconst spaceDocId = server.spaceDocId;\n\tif (!treeMap || !spaceDocId) {\n\t\tthrow new Error(\"Cannot bootstrap — server is not connected.\");\n\t}\n\tconst entries = readEntries(treeMap, spaceDocId);\n\n\tconst topLevel = entries.filter((e) => e.parentId === null);\n\tconst existingInbox = topLevel.find(\n\t\t(e) => e.label.trim().toLowerCase() === INBOX_LABEL.toLowerCase(),\n\t);\n\tconst existingOutbox = topLevel.find(\n\t\t(e) => e.label.trim().toLowerCase() === OUTBOX_LABEL.toLowerCase(),\n\t);\n\n\t// ── Inbox ──────────────────────────────────────────────────────────────\n\tlet inboxId: string;\n\tif (existingInbox) {\n\t\tinboxId = existingInbox.id;\n\t\tconsole.error(\n\t\t\t`[abracadabra-resend] Inbox found: ${inboxId} (${existingInbox.label})`,\n\t\t);\n\t} else {\n\t\tinboxId = await createDoc(server, {\n\t\t\tparentTreeId: null,\n\t\t\trestParentId: spaceDocId,\n\t\t\tlabel: INBOX_LABEL,\n\t\t\ttype: \"gallery\",\n\t\t\tmeta: { icon: \"inbox\" },\n\t\t});\n\t\tconsole.error(`[abracadabra-resend] Inbox created: ${inboxId}`);\n\t}\n\n\t// ── Outbox ─────────────────────────────────────────────────────────────\n\tlet outboxId: string;\n\tif (existingOutbox) {\n\t\toutboxId = existingOutbox.id;\n\t\tconsole.error(\n\t\t\t`[abracadabra-resend] Outbox found: ${outboxId} (${existingOutbox.label})`,\n\t\t);\n\t} else {\n\t\toutboxId = await createDoc(server, {\n\t\t\tparentTreeId: null,\n\t\t\trestParentId: spaceDocId,\n\t\t\tlabel: OUTBOX_LABEL,\n\t\t\ttype: \"kanban\",\n\t\t\tmeta: { icon: \"send\" },\n\t\t});\n\t\tconsole.error(`[abracadabra-resend] Outbox created: ${outboxId}`);\n\t}\n\n\t// ── Outbox columns ─────────────────────────────────────────────────────\n\t// Re-read entries — we may have just created Inbox/Outbox.\n\tconst refreshedEntries = readEntries(treeMap, spaceDocId);\n\tconst existingColumns = refreshedEntries.filter(\n\t\t(e) => e.parentId === outboxId,\n\t);\n\n\tconst columns = {} as Record<OutboxColumn, string>;\n\tfor (const colLabel of OUTBOX_COLUMNS) {\n\t\tconst match = existingColumns.find(\n\t\t\t(e) => e.label.trim().toLowerCase() === colLabel.toLowerCase(),\n\t\t);\n\t\tif (match) {\n\t\t\tcolumns[colLabel] = match.id;\n\t\t\tcontinue;\n\t\t}\n\t\tconst id = await createDoc(server, {\n\t\t\tparentTreeId: outboxId,\n\t\t\trestParentId: outboxId,\n\t\t\tlabel: colLabel,\n\t\t\t// Kanban columns inherit view from the parent kanban — no type.\n\t\t\torder: Date.now() + OUTBOX_COLUMNS.indexOf(colLabel),\n\t\t});\n\t\tcolumns[colLabel] = id;\n\t\tconsole.error(\n\t\t\t`[abracadabra-resend] Outbox column \"${colLabel}\" created: ${id}`,\n\t\t);\n\t}\n\n\treturn { inboxId, outboxId, columns };\n}\n","/**\n * Wait for a provider's `synced` event with a timeout.\n *\n * The `isSynced` short-circuit is load-bearing: providers that already synced\n * (e.g. cached child providers returned from `loadChild`) won't re-emit\n * `synced`, so without the short-circuit every later op on that doc times out.\n */\nexport function waitForSync(\n\tprovider: {\n\t\tisSynced?: boolean;\n\t\ton(event: string, cb: () => void): void;\n\t\toff(event: string, cb: () => void): void;\n\t},\n\ttimeoutMs = 15000,\n): Promise<void> {\n\tif (provider.isSynced) return Promise.resolve();\n\n\treturn new Promise<void>((resolve, reject) => {\n\t\tconst timer = setTimeout(() => {\n\t\t\tprovider.off(\"synced\", handler);\n\t\t\treject(new Error(`Sync timed out after ${timeoutMs}ms`));\n\t\t}, timeoutMs);\n\n\t\tfunction handler() {\n\t\t\tclearTimeout(timer);\n\t\t\tprovider.off(\"synced\", handler);\n\t\t\tresolve();\n\t\t}\n\n\t\tprovider.on(\"synced\", handler);\n\t});\n}\n","/**\n * Inbound webhook HTTP server.\n *\n * Single POST route: `/inbound`. Verifies Svix signature, parses Resend Inbound\n * payload, creates a child doc under the Inbox, uploads attachments. Operator\n * is responsible for exposing the port publicly (tunnel / reverse proxy) and\n * configuring Resend Inbound to deliver here.\n */\nimport { makeEntryMap } from \"@abraca/dabra\";\nimport { populateYDocFromMarkdown as populateBody } from \"@abraca/convert\";\nimport { createHmac, timingSafeEqual } from \"node:crypto\";\nimport {\n\tcreateServer,\n\ttype IncomingMessage,\n\ttype Server,\n\ttype ServerResponse,\n} from \"node:http\";\nimport type { BootstrapResult } from \"./bootstrap.ts\";\nimport type { AbracadabraResendServer } from \"./server.ts\";\nimport { waitForSync } from \"./utils.ts\";\n\nexport interface InboundServerOptions {\n\tserver: AbracadabraResendServer;\n\tbootstrap: BootstrapResult;\n\tsecret: string;\n\tport?: number;\n\thost?: string;\n\t/** Reject deliveries whose timestamp is older than this many seconds. */\n\ttoleranceSeconds?: number;\n}\n\ninterface ResendInboundAttachment {\n\tfilename?: string;\n\tcontentType?: string;\n\tcontent?: string; // base64\n}\n\ninterface ResendInboundData {\n\tid?: string;\n\tfrom?: string | { email?: string; name?: string };\n\tto?: Array<string | { email?: string; name?: string }> | string;\n\tcc?: Array<string | { email?: string; name?: string }> | string;\n\tsubject?: string;\n\ttext?: string;\n\thtml?: string;\n\theaders?: Array<{ name: string; value: string }>;\n\tattachments?: ResendInboundAttachment[];\n\tcreated_at?: string;\n}\n\ninterface ResendInboundEnvelope {\n\ttype?: string;\n\tdata?: ResendInboundData;\n}\n\nfunction addr(v: unknown): string | undefined {\n\tif (typeof v === \"string\") return v.trim() || undefined;\n\tif (v && typeof v === \"object\") {\n\t\tconst obj = v as { email?: string; name?: string };\n\t\tif (typeof obj.email === \"string\") return obj.email.trim() || undefined;\n\t}\n\treturn undefined;\n}\n\nfunction addrList(v: unknown): string[] {\n\tif (Array.isArray(v))\n\t\treturn v.map(addr).filter((s): s is string => !!s);\n\tconst one = addr(v);\n\treturn one ? [one] : [];\n}\n\nfunction pickHeader(\n\theaders: Array<{ name: string; value: string }> | undefined,\n\tname: string,\n): string | undefined {\n\tif (!headers) return undefined;\n\tconst lower = name.toLowerCase();\n\tfor (const h of headers) {\n\t\tif (typeof h?.name === \"string\" && h.name.toLowerCase() === lower) {\n\t\t\treturn h.value;\n\t\t}\n\t}\n\treturn undefined;\n}\n\nfunction decodeSecret(secret: string): Buffer {\n\t// Resend / Svix webhook secrets are `whsec_<base64>`. The HMAC key is the\n\t// base64-decoded bytes after the prefix. Accept raw secrets too so the\n\t// operator can supply a hex/base64 key directly if their plan differs.\n\tconst stripped = secret.startsWith(\"whsec_\") ? secret.slice(6) : secret;\n\ttry {\n\t\treturn Buffer.from(stripped, \"base64\");\n\t} catch {\n\t\treturn Buffer.from(stripped);\n\t}\n}\n\nfunction constantTimeEquals(a: Buffer, b: Buffer): boolean {\n\tif (a.length !== b.length) return false;\n\treturn timingSafeEqual(a, b);\n}\n\n/**\n * Verify Svix-style signature. Headers carry `svix-id`, `svix-timestamp`,\n * `svix-signature` (space-separated `v1,<base64>` pairs). The signing input\n * is `${id}.${timestamp}.${body}` HMAC-SHA256 with the decoded secret.\n */\nfunction verifySignature(\n\tbody: string,\n\theaders: IncomingMessage[\"headers\"],\n\tsecret: Buffer,\n\ttoleranceSeconds: number,\n): { ok: true } | { ok: false; reason: string } {\n\tconst id = headers[\"svix-id\"];\n\tconst ts = headers[\"svix-timestamp\"];\n\tconst sig = headers[\"svix-signature\"];\n\tif (typeof id !== \"string\" || typeof ts !== \"string\" || typeof sig !== \"string\") {\n\t\treturn { ok: false, reason: \"missing Svix headers\" };\n\t}\n\tconst tsNum = Number(ts);\n\tif (!Number.isFinite(tsNum)) {\n\t\treturn { ok: false, reason: \"invalid svix-timestamp\" };\n\t}\n\tconst ageSec = Math.abs(Math.floor(Date.now() / 1000) - tsNum);\n\tif (ageSec > toleranceSeconds) {\n\t\treturn { ok: false, reason: `delivery too old (${ageSec}s)` };\n\t}\n\n\tconst toSign = `${id}.${ts}.${body}`;\n\tconst expected = createHmac(\"sha256\", secret).update(toSign).digest();\n\n\tconst candidates = sig.split(\" \").map((s) => s.trim()).filter(Boolean);\n\tfor (const candidate of candidates) {\n\t\tconst [version, value] = candidate.split(\",\");\n\t\tif (version !== \"v1\" || !value) continue;\n\t\tlet provided: Buffer;\n\t\ttry {\n\t\t\tprovided = Buffer.from(value, \"base64\");\n\t\t} catch {\n\t\t\tcontinue;\n\t\t}\n\t\tif (constantTimeEquals(expected, provided)) return { ok: true };\n\t}\n\treturn { ok: false, reason: \"signature mismatch\" };\n}\n\nfunction readBody(req: IncomingMessage, maxBytes = 25 * 1024 * 1024): Promise<string> {\n\treturn new Promise((resolve, reject) => {\n\t\tconst chunks: Buffer[] = [];\n\t\tlet size = 0;\n\t\treq.on(\"data\", (chunk: Buffer) => {\n\t\t\tsize += chunk.length;\n\t\t\tif (size > maxBytes) {\n\t\t\t\treject(new Error(`payload too large (>${maxBytes} bytes)`));\n\t\t\t\treq.destroy();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tchunks.push(chunk);\n\t\t});\n\t\treq.on(\"end\", () => resolve(Buffer.concat(chunks).toString(\"utf8\")));\n\t\treq.on(\"error\", reject);\n\t});\n}\n\nexport class InboundServer {\n\tprivate readonly server: AbracadabraResendServer;\n\tprivate readonly bootstrap: BootstrapResult;\n\tprivate readonly secret: Buffer;\n\tprivate readonly toleranceSeconds: number;\n\tprivate readonly port: number;\n\tprivate readonly host: string;\n\tprivate httpServer: Server | null = null;\n\t/** De-dupes redelivered webhooks. Svix may retry on transient failures. */\n\tprivate readonly seenSvixIds = new Set<string>();\n\n\tconstructor(opts: InboundServerOptions) {\n\t\tthis.server = opts.server;\n\t\tthis.bootstrap = opts.bootstrap;\n\t\tthis.secret = decodeSecret(opts.secret);\n\t\tthis.toleranceSeconds = opts.toleranceSeconds ?? 5 * 60;\n\t\tthis.port = opts.port ?? 0;\n\t\tthis.host = opts.host ?? \"0.0.0.0\";\n\t}\n\n\tasync start(): Promise<number> {\n\t\tthis.httpServer = createServer((req, res) => {\n\t\t\tvoid this.handle(req, res);\n\t\t});\n\t\tawait new Promise<void>((resolve, reject) => {\n\t\t\tthis.httpServer!.once(\"error\", reject);\n\t\t\tthis.httpServer!.listen(this.port, this.host, () => resolve());\n\t\t});\n\t\tconst address = this.httpServer.address();\n\t\tconst boundPort =\n\t\t\ttypeof address === \"object\" && address ? address.port : this.port;\n\t\tconsole.error(\n\t\t\t`[abracadabra-resend] Inbound server listening on http://${this.host}:${boundPort}/inbound`,\n\t\t);\n\t\treturn boundPort;\n\t}\n\n\tasync stop(): Promise<void> {\n\t\tif (!this.httpServer) return;\n\t\tawait new Promise<void>((resolve, reject) => {\n\t\t\tthis.httpServer!.close((err) => (err ? reject(err) : resolve()));\n\t\t});\n\t\tthis.httpServer = null;\n\t}\n\n\tprivate async handle(req: IncomingMessage, res: ServerResponse): Promise<void> {\n\t\ttry {\n\t\t\tif (req.method === \"GET\" && (req.url === \"/health\" || req.url === \"/\")) {\n\t\t\t\tres.writeHead(200, { \"content-type\": \"text/plain\" });\n\t\t\t\tres.end(\"ok\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (req.method !== \"POST\" || req.url !== \"/inbound\") {\n\t\t\t\tres.writeHead(404, { \"content-type\": \"text/plain\" });\n\t\t\t\tres.end(\"not found\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst body = await readBody(req);\n\t\t\tconst check = verifySignature(\n\t\t\t\tbody,\n\t\t\t\treq.headers,\n\t\t\t\tthis.secret,\n\t\t\t\tthis.toleranceSeconds,\n\t\t\t);\n\t\t\tif (!check.ok) {\n\t\t\t\tconsole.error(`[abracadabra-resend] inbound rejected: ${check.reason}`);\n\t\t\t\tres.writeHead(401, { \"content-type\": \"text/plain\" });\n\t\t\t\tres.end(\"unauthorized\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst svixId =\n\t\t\t\ttypeof req.headers[\"svix-id\"] === \"string\"\n\t\t\t\t\t? (req.headers[\"svix-id\"] as string)\n\t\t\t\t\t: null;\n\t\t\tif (svixId && this.seenSvixIds.has(svixId)) {\n\t\t\t\tres.writeHead(200, { \"content-type\": \"text/plain\" });\n\t\t\t\tres.end(\"duplicate\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (svixId) {\n\t\t\t\tthis.seenSvixIds.add(svixId);\n\t\t\t\tif (this.seenSvixIds.size > 5000) {\n\t\t\t\t\tconst first = this.seenSvixIds.values().next().value;\n\t\t\t\t\tif (first) this.seenSvixIds.delete(first);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tlet env: ResendInboundEnvelope;\n\t\t\ttry {\n\t\t\t\tenv = JSON.parse(body);\n\t\t\t} catch {\n\t\t\t\tres.writeHead(400, { \"content-type\": \"text/plain\" });\n\t\t\t\tres.end(\"invalid json\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst data = env?.data ?? (env as unknown as ResendInboundData);\n\t\t\tawait this.ingest(data);\n\n\t\t\tres.writeHead(200, { \"content-type\": \"text/plain\" });\n\t\t\tres.end(\"ok\");\n\t\t} catch (err: any) {\n\t\t\tconsole.error(\n\t\t\t\t`[abracadabra-resend] inbound handler error: ${err?.message ?? err}`,\n\t\t\t);\n\t\t\tres.writeHead(500, { \"content-type\": \"text/plain\" });\n\t\t\tres.end(\"error\");\n\t\t}\n\t}\n\n\tprivate async ingest(data: ResendInboundData): Promise<void> {\n\t\tawait this.server.ensureConnected();\n\t\tconst treeMap = this.server.getTreeMap();\n\t\tconst rootDoc = this.server.rootDocument;\n\t\tif (!treeMap || !rootDoc) {\n\t\t\tthrow new Error(\"Cannot ingest — server is not connected.\");\n\t\t}\n\n\t\tconst subjectRaw = typeof data.subject === \"string\" ? data.subject.trim() : \"\";\n\t\tconst subject = subjectRaw.length > 0 ? subjectRaw : \"(no subject)\";\n\t\tconst from = addr(data.from) ?? \"(unknown)\";\n\t\tconst to = addrList(data.to);\n\t\tconst cc = addrList(data.cc);\n\t\tconst inReplyTo = pickHeader(data.headers, \"In-Reply-To\");\n\t\tconst messageId =\n\t\t\tpickHeader(data.headers, \"Message-ID\") ?? data.id ?? null;\n\n\t\tconst inboxId = this.bootstrap.inboxId;\n\t\tconst id = crypto.randomUUID();\n\t\tconst now = Date.now();\n\n\t\tconst meta: Record<string, unknown> = {\n\t\t\ticon: \"mail\",\n\t\t\tfrom,\n\t\t\tto,\n\t\t\tcc: cc.length ? cc : undefined,\n\t\t\tsubject,\n\t\t\treceivedAt: now,\n\t\t\tmessageId,\n\t\t\tinReplyTo,\n\t\t};\n\t\tif (typeof data.html === \"string\" && data.html.length > 0) {\n\t\t\tmeta.html = data.html;\n\t\t}\n\n\t\t// SQL row first, then Yjs entry — RBAC cascade depends on it.\n\t\tawait this.server.client.createChild(inboxId, {\n\t\t\tchild_id: id,\n\t\t\tlabel: subject,\n\t\t\tdoc_type: \"doc\",\n\t\t\tkind: \"page\",\n\t\t});\n\n\t\trootDoc.transact(() => {\n\t\t\ttreeMap.set(\n\t\t\t\tid,\n\t\t\t\tmakeEntryMap({\n\t\t\t\t\tlabel: subject,\n\t\t\t\t\tparentId: inboxId,\n\t\t\t\t\torder: now,\n\t\t\t\t\ttype: \"doc\",\n\t\t\t\t\tmeta: meta as any,\n\t\t\t\t\tcreatedAt: now,\n\t\t\t\t\tupdatedAt: now,\n\t\t\t\t}),\n\t\t\t);\n\t\t});\n\n\t\t// Populate the body with the plain-text version (Resend always provides\n\t\t// one). Falls back to a notice when neither text nor html is present.\n\t\tconst provider = await this.server.getChildProvider(id);\n\t\tawait waitForSync(provider);\n\t\tconst fragment = provider.document.getXmlFragment(\"default\");\n\t\tconst body =\n\t\t\t(typeof data.text === \"string\" && data.text.length > 0\n\t\t\t\t? data.text\n\t\t\t\t: typeof data.html === \"string\" && data.html.length > 0\n\t\t\t\t\t? `<details><summary>HTML email (no text part)</summary>\\n\\n\\`\\`\\`html\\n${data.html}\\n\\`\\`\\`\\n</details>`\n\t\t\t\t\t: \"(empty body)\");\n\t\tpopulateBody(fragment, body, subject);\n\n\t\t// Attachments — base64 → Blob → REST upload. Store upload metadata back\n\t\t// on the doc so consumers can render previews / download.\n\t\tconst attached: Array<{\n\t\t\tid: string;\n\t\t\tfilename: string;\n\t\t\tcontentType?: string;\n\t\t\tsize: number;\n\t\t}> = [];\n\t\tconst attachments = Array.isArray(data.attachments) ? data.attachments : [];\n\t\tfor (const att of attachments) {\n\t\t\tif (typeof att?.content !== \"string\") continue;\n\t\t\tconst filename =\n\t\t\t\ttypeof att.filename === \"string\" && att.filename.length > 0\n\t\t\t\t\t? att.filename\n\t\t\t\t\t: \"attachment\";\n\t\t\ttry {\n\t\t\t\tconst bytes = Buffer.from(att.content, \"base64\");\n\t\t\t\tconst blob = new Blob([bytes], {\n\t\t\t\t\ttype: att.contentType ?? \"application/octet-stream\",\n\t\t\t\t});\n\t\t\t\tconst uploaded = await this.server.client.upload(id, blob, filename);\n\t\t\t\tconst uploadedId =\n\t\t\t\t\t(uploaded as { id?: string; uploadId?: string })?.id ??\n\t\t\t\t\t(uploaded as { uploadId?: string })?.uploadId ??\n\t\t\t\t\t\"\";\n\t\t\t\tattached.push({\n\t\t\t\t\tid: uploadedId,\n\t\t\t\t\tfilename,\n\t\t\t\t\tcontentType: att.contentType,\n\t\t\t\t\tsize: bytes.length,\n\t\t\t\t});\n\t\t\t} catch (err: any) {\n\t\t\t\tconsole.error(\n\t\t\t\t\t`[abracadabra-resend] attachment upload failed (${filename}): ${err?.message ?? err}`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\tif (attached.length > 0) {\n\t\t\tconst existingRaw = treeMap.get(id);\n\t\t\tif (existingRaw) {\n\t\t\t\tconst existingMeta =\n\t\t\t\t\t(typeof (existingRaw as any).toJSON === \"function\"\n\t\t\t\t\t\t? (existingRaw as any).toJSON()?.meta\n\t\t\t\t\t\t: (existingRaw as any).meta) ?? {};\n\t\t\t\trootDoc.transact(() => {\n\t\t\t\t\ttreeMap.set(\n\t\t\t\t\t\tid,\n\t\t\t\t\t\tmakeEntryMap({\n\t\t\t\t\t\t\tlabel: subject,\n\t\t\t\t\t\t\tparentId: inboxId,\n\t\t\t\t\t\t\torder: now,\n\t\t\t\t\t\t\ttype: \"doc\",\n\t\t\t\t\t\t\tmeta: { ...existingMeta, attachments: attached },\n\t\t\t\t\t\t\tcreatedAt: now,\n\t\t\t\t\t\t\tupdatedAt: Date.now(),\n\t\t\t\t\t\t}),\n\t\t\t\t\t);\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\n\t\tconsole.error(\n\t\t\t`[abracadabra-resend] inbound stored: \"${subject}\" from ${from} → doc ${id}`,\n\t\t);\n\t}\n}\n\n","/**\n * Render an outbox document to an email-ready payload.\n *\n * Reads addressing from the doc's tree-entry `meta` (to/cc/bcc/subject/from/\n * replyTo) and renders the body Y.XmlFragment via `@abraca/convert`'s\n * `yjsToHtml` — which already emits a complete `<!DOCTYPE html>` doc with the\n * doc label as `<h1>`, so the result is suitable as-is for Resend's `html`\n * field.\n */\nimport { yjsToHtml } from \"@abraca/convert\";\nimport { toPlain } from \"@abraca/dabra\";\nimport type { AbracadabraResendServer } from \"./server.ts\";\n\nexport interface EmailPayload {\n\tsubject: string;\n\thtml: string;\n\tto: string[];\n\tcc?: string[];\n\tbcc?: string[];\n\tfrom?: string;\n\treplyTo?: string;\n}\n\nexport class RenderError extends Error {\n\tconstructor(message: string) {\n\t\tsuper(message);\n\t\tthis.name = \"RenderError\";\n\t}\n}\n\nfunction asStringArray(value: unknown): string[] {\n\tif (Array.isArray(value)) {\n\t\treturn value\n\t\t\t.filter((v): v is string => typeof v === \"string\" && v.trim().length > 0)\n\t\t\t.map((v) => v.trim());\n\t}\n\tif (typeof value === \"string\" && value.trim().length > 0) {\n\t\t// Allow `to: \"alice@x.com, bob@y.com\"` as a convenience.\n\t\treturn value\n\t\t\t.split(\",\")\n\t\t\t.map((s) => s.trim())\n\t\t\t.filter((s) => s.length > 0);\n\t}\n\treturn [];\n}\n\nfunction asOptionalString(value: unknown): string | undefined {\n\treturn typeof value === \"string\" && value.trim().length > 0\n\t\t? value.trim()\n\t\t: undefined;\n}\n\ninterface OutboxEntry {\n\tlabel: string;\n\tmeta: Record<string, unknown>;\n}\n\nfunction readEntry(\n\tserver: AbracadabraResendServer,\n\tdocId: string,\n): OutboxEntry | null {\n\tconst treeMap = server.getTreeMap();\n\tif (!treeMap) return null;\n\tconst raw = treeMap.get(docId);\n\tif (!raw) return null;\n\tconst plain = toPlain(raw) as any;\n\tif (!plain || typeof plain !== \"object\") return null;\n\treturn {\n\t\tlabel: typeof plain.label === \"string\" ? plain.label : \"(no subject)\",\n\t\tmeta:\n\t\t\tplain.meta && typeof plain.meta === \"object\"\n\t\t\t\t? (plain.meta as Record<string, unknown>)\n\t\t\t\t: {},\n\t};\n}\n\nexport async function renderEmail(\n\tserver: AbracadabraResendServer,\n\tdocId: string,\n\tdefaultFrom: string,\n): Promise<EmailPayload> {\n\tconst entry = readEntry(server, docId);\n\tif (!entry) {\n\t\tthrow new RenderError(`Doc ${docId} has no tree entry.`);\n\t}\n\n\tconst to = asStringArray(entry.meta.to);\n\tif (to.length === 0) {\n\t\tthrow new RenderError(\n\t\t\t`Doc ${docId} has no recipients — set meta.to (array of email addresses).`,\n\t\t);\n\t}\n\tconst cc = asStringArray(entry.meta.cc);\n\tconst bcc = asStringArray(entry.meta.bcc);\n\tconst from = asOptionalString(entry.meta.from) ?? defaultFrom;\n\tconst replyTo = asOptionalString(entry.meta.replyTo);\n\tconst subject = asOptionalString(entry.meta.subject) ?? entry.label;\n\n\tconst provider = await server.getChildProvider(docId);\n\tconst fragment = provider.document.getXmlFragment(\"default\");\n\tconst html = yjsToHtml(fragment, subject);\n\n\treturn {\n\t\tsubject,\n\t\thtml,\n\t\tto,\n\t\tcc: cc.length ? cc : undefined,\n\t\tbcc: bcc.length ? bcc : undefined,\n\t\tfrom,\n\t\treplyTo,\n\t};\n}\n","/**\n * Outbox watcher. Observes the doc-tree map (deeply, so per-entry parentId\n * updates surface) and dispatches any doc that lands under the \"Ready\" column.\n *\n * Dispatch flow per doc:\n * render → resend.send → patch meta.resendId/sentAt → move to Sent\n * On failure:\n * patch meta.error/errorAt → move to Failed (left for human triage)\n *\n * Idempotency:\n * - `meta.resendId` already set → skip (recovers from a restart that landed\n * between Resend ack and the post-send move).\n * - In-flight `Set<docId>` prevents the same observe burst from double-firing.\n */\nimport { patchEntry, toPlain } from \"@abraca/dabra\";\nimport type * as Y from \"yjs\";\nimport type { BootstrapResult } from \"./bootstrap.ts\";\nimport { renderEmail, RenderError } from \"./render.ts\";\nimport type { ResendSender } from \"./resend-client.ts\";\nimport type { AbracadabraResendServer } from \"./server.ts\";\n\nexport interface OutboxWatcherOptions {\n\tserver: AbracadabraResendServer;\n\tsender: ResendSender;\n\tbootstrap: BootstrapResult;\n\tdefaultFrom: string;\n}\n\ninterface EntryView {\n\tid: string;\n\tlabel: string;\n\tparentId: string | null;\n\tmeta: Record<string, unknown>;\n}\n\nfunction readEntry(treeMap: Y.Map<any>, id: string): EntryView | null {\n\tconst raw = treeMap.get(id);\n\tif (!raw) return null;\n\tconst plain = toPlain(raw) as any;\n\tif (!plain || typeof plain !== \"object\") return null;\n\treturn {\n\t\tid,\n\t\tlabel: typeof plain.label === \"string\" ? plain.label : \"Untitled\",\n\t\tparentId: plain.parentId ?? null,\n\t\tmeta:\n\t\t\tplain.meta && typeof plain.meta === \"object\"\n\t\t\t\t? (plain.meta as Record<string, unknown>)\n\t\t\t\t: {},\n\t};\n}\n\nexport class OutboxWatcher {\n\tprivate readonly server: AbracadabraResendServer;\n\tprivate readonly sender: ResendSender;\n\tprivate readonly bootstrap: BootstrapResult;\n\tprivate readonly defaultFrom: string;\n\t// Transient mid-dispatch guard ONLY: holds ids whose send is in flight RIGHT\n\t// NOW, so a burst of observe events doesn't fire a second concurrent send\n\t// before `meta.resendId` lands. Cleared the instant a dispatch settles — it\n\t// is NEVER a durable \"already sent\" marker. The ONLY durable sent-state is\n\t// `meta.resendId` on the document (set on success); a failed send is durably\n\t// recorded by the move to the Failed column + `meta.error`. There is no\n\t// in-memory \"handled\" set: a card re-queued into Ready (resendId cleared) is\n\t// re-sent, and the bridge's view never diverges from the persisted tree.\n\tprivate readonly inFlight = new Set<string>();\n\tprivate observer: ((events: Y.YEvent<any>[]) => void) | null = null;\n\tprivate treeMap: Y.Map<any> | null = null;\n\tprivate rootDoc: Y.Doc | null = null;\n\tprivate txHandler: ((tx: Y.Transaction) => void) | null = null;\n\tprivate subdocsHandler:\n\t\t| ((changes: {\n\t\t\t\tadded: Set<Y.Doc>;\n\t\t\t\tremoved: Set<Y.Doc>;\n\t\t\t\tloaded: Set<Y.Doc>;\n\t\t }) => void)\n\t\t| null = null;\n\tprivate updateHandler:\n\t\t| ((update: Uint8Array, origin: unknown) => void)\n\t\t| null = null;\n\tprivate reconnectedHandler: (() => void) | null = null;\n\t// The provider we attached `reconnected` to, kept so stop() can detach.\n\tprivate reconnectProvider: { off(ev: string, cb: () => void): void } | null =\n\t\tnull;\n\t// Per-subdoc afterTransaction handlers. Tracked so we (a) detach them on\n\t// stop() and (b) never stack a second listener when the same subdoc reloads\n\t// (the old code re-`on`'d every subdoc on every `subdocs` event — an\n\t// unbounded listener leak that grew for the life of the daemon).\n\tprivate readonly subdocHandlers = new Map<\n\t\tY.Doc,\n\t\t(tx: Y.Transaction) => void\n\t>();\n\n\tconstructor(opts: OutboxWatcherOptions) {\n\t\tthis.server = opts.server;\n\t\tthis.sender = opts.sender;\n\t\tthis.bootstrap = opts.bootstrap;\n\t\tthis.defaultFrom = opts.defaultFrom;\n\t}\n\n\tstart(): void {\n\t\tconst treeMap = this.server.getTreeMap();\n\t\tif (!treeMap) {\n\t\t\tthrow new Error(\"OutboxWatcher.start: server is not connected\");\n\t\t}\n\t\tthis.treeMap = treeMap;\n\n\t\tconst rootDoc = this.server.rootDocument;\n\t\tif (!rootDoc) {\n\t\t\tthrow new Error(\"OutboxWatcher.start: root doc not connected\");\n\t\t}\n\t\tthis.rootDoc = rootDoc;\n\n\t\t// Initial scan — pick up anything already in Ready before we attached.\n\t\tvoid this.scan(\"init\");\n\n\t\t// observeDeep on the tree map catches all the common edits (patchEntry\n\t\t// mutating a nested Y.Map, treeMap.set replacing an entry).\n\t\tconst obs = (events: Y.YEvent<any>[]) => {\n\t\t\tconsole.error(\n\t\t\t\t`[abracadabra-resend] observeDeep fired (${events.length} events)`,\n\t\t\t);\n\t\t\tvoid this.scan(\"observeDeep\");\n\t\t};\n\t\ttreeMap.observeDeep(obs);\n\t\tthis.observer = obs;\n\n\t\t// afterTransaction on the root Y.Doc fires for EVERY transaction applied\n\t\t// to the doc — local writes and updates dispatched into this doc.\n\t\tconst onTx = (tx: Y.Transaction) => {\n\t\t\tconst changed: string[] = [];\n\t\t\tfor (const [type, events] of tx.changedParentTypes.entries()) {\n\t\t\t\tconst name = (type as any)._item ? (type as any)._item.parentSub : type.constructor.name;\n\t\t\t\tconst keys = events.flatMap((ev: any) => Array.from(ev.keysChanged ?? []));\n\t\t\t\tchanged.push(`${name ?? \"type\"}[${keys.join(\",\")}]`);\n\t\t\t}\n\t\t\tconsole.error(\n\t\t\t\t`[abracadabra-resend] root afterTransaction (local=${tx.local}, origin=${String(tx.origin)}, changed=${changed.join(\" | \") || \"(none)\"})`,\n\t\t\t);\n\t\t\tvoid this.scan(\"afterTransaction\");\n\t\t};\n\t\trootDoc.on(\"afterTransaction\", onTx);\n\t\tthis.txHandler = onTx;\n\n\t\t// Belt-and-suspenders: subdocs. abracadabra-rs may route some space-tree\n\t\t// edits through subdoc payloads that don't fire transactions on the root\n\t\t// doc directly. Watch every subdoc's transactions too — but dedup, so a\n\t\t// subdoc that loads/unloads/reloads doesn't accumulate listeners.\n\t\tconst onSubdocs = (changes: {\n\t\t\tadded: Set<Y.Doc>;\n\t\t\tremoved: Set<Y.Doc>;\n\t\t\tloaded: Set<Y.Doc>;\n\t\t}) => {\n\t\t\tconsole.error(\n\t\t\t\t`[abracadabra-resend] subdocs: added=${changes.added.size} loaded=${changes.loaded.size} removed=${changes.removed.size}`,\n\t\t\t);\n\t\t\tfor (const sub of changes.removed) {\n\t\t\t\tconst handler = this.subdocHandlers.get(sub);\n\t\t\t\tif (handler) {\n\t\t\t\t\tsub.off(\"afterTransaction\", handler);\n\t\t\t\t\tthis.subdocHandlers.delete(sub);\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (const sub of [...changes.added, ...changes.loaded]) {\n\t\t\t\tif (this.subdocHandlers.has(sub)) continue;\n\t\t\t\tconst handler = (tx: Y.Transaction) => {\n\t\t\t\t\tconsole.error(\n\t\t\t\t\t\t`[abracadabra-resend] subdoc afterTransaction (guid=${sub.guid}, local=${tx.local})`,\n\t\t\t\t\t);\n\t\t\t\t\tvoid this.scan(\"subdoc\");\n\t\t\t\t};\n\t\t\t\tsub.on(\"afterTransaction\", handler);\n\t\t\t\tthis.subdocHandlers.set(sub, handler);\n\t\t\t}\n\t\t};\n\t\trootDoc.on(\"subdocs\", onSubdocs);\n\t\tthis.subdocsHandler = onSubdocs;\n\n\t\t// Raw doc update — fires for every binary Yjs update applied to the doc,\n\t\t// from any origin. If THIS doesn't fire when a remote writer changes\n\t\t// state, the bridge's WS isn't delivering updates.\n\t\tconst onUpdate = (_update: Uint8Array, origin: unknown) => {\n\t\t\tconsole.error(\n\t\t\t\t`[abracadabra-resend] root update applied (origin=${String(origin)})`,\n\t\t\t);\n\t\t\tvoid this.scan(\"update\");\n\t\t};\n\t\trootDoc.on(\"update\", onUpdate);\n\t\tthis.updateHandler = onUpdate;\n\n\t\t// Re-scan whenever the provider's socket reconnects. The doc (and these\n\t\t// observers) survive a reconnect untouched, and the post-reconnect sync\n\t\t// re-fires them for anything that changed while we were offline — but an\n\t\t// explicit, idempotent catch-up scan guarantees we don't sit on a Ready\n\t\t// doc that landed during the outage.\n\t\tconst provider = this.server.rootProvider;\n\t\tif (provider && typeof (provider as any).on === \"function\") {\n\t\t\tconst onReconnected = () => {\n\t\t\t\tconsole.error(\"[abracadabra-resend] provider reconnected — re-scanning\");\n\t\t\t\tvoid this.scan(\"reconnected\");\n\t\t\t};\n\t\t\t(provider as any).on(\"reconnected\", onReconnected);\n\t\t\tthis.reconnectedHandler = onReconnected;\n\t\t\tthis.reconnectProvider = provider as any;\n\t\t}\n\n\t\tconsole.error(\n\t\t\t`[abracadabra-resend] Outbox watcher attached (ready column ${this.bootstrap.columns.Ready})`,\n\t\t);\n\t}\n\n\tstop(): void {\n\t\tif (this.rootDoc && this.txHandler) {\n\t\t\tthis.rootDoc.off(\"afterTransaction\", this.txHandler);\n\t\t}\n\t\tif (this.rootDoc && this.subdocsHandler) {\n\t\t\tthis.rootDoc.off(\"subdocs\", this.subdocsHandler);\n\t\t}\n\t\tif (this.rootDoc && this.updateHandler) {\n\t\t\tthis.rootDoc.off(\"update\", this.updateHandler);\n\t\t}\n\t\tfor (const [sub, handler] of this.subdocHandlers) {\n\t\t\tsub.off(\"afterTransaction\", handler);\n\t\t}\n\t\tthis.subdocHandlers.clear();\n\t\tif (this.treeMap && this.observer) {\n\t\t\tthis.treeMap.unobserveDeep(this.observer);\n\t\t}\n\t\tif (this.reconnectProvider && this.reconnectedHandler) {\n\t\t\tthis.reconnectProvider.off(\"reconnected\", this.reconnectedHandler);\n\t\t}\n\t\tthis.txHandler = null;\n\t\tthis.subdocsHandler = null;\n\t\tthis.updateHandler = null;\n\t\tthis.reconnectedHandler = null;\n\t\tthis.reconnectProvider = null;\n\t\tthis.rootDoc = null;\n\t\tthis.observer = null;\n\t\tthis.treeMap = null;\n\t}\n\n\tprivate async scan(reason: string): Promise<void> {\n\t\tconst treeMap = this.treeMap;\n\t\tif (!treeMap) return;\n\t\tconst readyColId = this.bootstrap.columns.Ready;\n\t\tconst outboxId = this.bootstrap.outboxId;\n\t\tconst columnIds = new Set(Object.values(this.bootstrap.columns));\n\t\tconst candidates: EntryView[] = [];\n\t\tlet inReadyCount = 0;\n\t\tlet totalEntries = 0;\n\t\t// Dump every entry whose ancestor is Outbox so we can compare bridge\n\t\t// view vs cou-sh view.\n\t\tconst outboxSubtree: Array<{ id: string; label: string; parentId: string | null; under: string }> = [];\n\t\ttreeMap.forEach((_raw: any, id: string) => {\n\t\t\ttotalEntries++;\n\t\t\tconst e = readEntry(treeMap, id);\n\t\t\tif (!e) return;\n\t\t\t// classify under outbox: direct child of Outbox, or grandchild via a column\n\t\t\tif (e.parentId === outboxId || (e.parentId && columnIds.has(e.parentId))) {\n\t\t\t\toutboxSubtree.push({\n\t\t\t\t\tid,\n\t\t\t\t\tlabel: e.label,\n\t\t\t\t\tparentId: e.parentId,\n\t\t\t\t\tunder: e.parentId === outboxId ? \"Outbox\" :\n\t\t\t\t\t\te.parentId === this.bootstrap.columns.Draft ? \"Draft\" :\n\t\t\t\t\t\te.parentId === this.bootstrap.columns.Ready ? \"Ready\" :\n\t\t\t\t\t\te.parentId === this.bootstrap.columns.Sent ? \"Sent\" :\n\t\t\t\t\t\te.parentId === this.bootstrap.columns.Failed ? \"Failed\" : \"?\",\n\t\t\t\t});\n\t\t\t}\n\t\t\tif (e.parentId !== readyColId) return;\n\t\t\tinReadyCount++;\n\t\t\t// Transient: a send for this id is already in flight in THIS process.\n\t\t\tif (this.inFlight.has(id)) return;\n\t\t\t// Durable: already sent (resendId persisted on the doc). Never re-send;\n\t\t\t// just reconcile its column to Sent. This is the single source of truth\n\t\t\t// for \"done\" — survives restarts, lives in document metadata.\n\t\t\tif (typeof e.meta.resendId === \"string\" && e.meta.resendId.length > 0) {\n\t\t\t\tthis.moveTo(id, this.bootstrap.columns.Sent);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcandidates.push(e);\n\t\t});\n\t\tconsole.error(\n\t\t\t`[abracadabra-resend] scan(${reason}): ${totalEntries} entries, ${inReadyCount} in Ready, ${candidates.length} to dispatch | Outbox subtree (${outboxSubtree.length}): ${outboxSubtree.map((e) => `${e.under}:\"${e.label}\"`).join(\", \")}`,\n\t\t);\n\n\t\tfor (const entry of candidates) {\n\t\t\tthis.inFlight.add(entry.id);\n\t\t\tvoid this.dispatch(entry).finally(() => {\n\t\t\t\tthis.inFlight.delete(entry.id);\n\t\t\t});\n\t\t}\n\t}\n\n\tprivate async dispatch(entry: EntryView): Promise<void> {\n\t\tconst { id, label } = entry;\n\t\ttry {\n\t\t\tconst payload = await renderEmail(this.server, id, this.defaultFrom);\n\t\t\tconsole.error(\n\t\t\t\t`[abracadabra-resend] sending \"${payload.subject}\" → ${payload.to.join(\", \")} (doc=${id})`,\n\t\t\t);\n\t\t\tconst { id: resendId } = await this.sender.send(payload, {\n\t\t\t\t\"X-Abra-Doc-Id\": id,\n\t\t\t});\n\t\t\t// Durable sent-marker: persisted on the doc, the only record of \"sent\".\n\t\t\tthis.patchMeta(id, { resendId, sentAt: Date.now(), error: null });\n\t\t\tthis.moveTo(id, this.bootstrap.columns.Sent);\n\t\t\tconsole.error(\n\t\t\t\t`[abracadabra-resend] sent \"${payload.subject}\" (resend=${resendId}, doc=${id})`,\n\t\t\t);\n\t\t} catch (err: any) {\n\t\t\t// Durable failure record: meta.error + the move to the Failed column\n\t\t\t// (below) — left for human triage. No in-memory marker.\n\t\t\tconst message =\n\t\t\t\terr instanceof RenderError\n\t\t\t\t\t? err.message\n\t\t\t\t\t: err?.message\n\t\t\t\t\t\t? String(err.message)\n\t\t\t\t\t\t: String(err);\n\t\t\tconsole.error(\n\t\t\t\t`[abracadabra-resend] send failed for \"${label}\" (${id}): ${message}`,\n\t\t\t);\n\t\t\tthis.patchMeta(id, { error: message, errorAt: Date.now() });\n\t\t\tthis.moveTo(id, this.bootstrap.columns.Failed);\n\t\t}\n\t}\n\n\tprivate patchMeta(id: string, patch: Record<string, unknown>): void {\n\t\tconst treeMap = this.treeMap;\n\t\tconst rootDoc = this.server.rootDocument;\n\t\tif (!treeMap || !rootDoc) return;\n\t\tconst current = readEntry(treeMap, id);\n\t\tif (!current) return;\n\t\tconst nextMeta = { ...current.meta, ...patch };\n\t\tfor (const [k, v] of Object.entries(patch)) {\n\t\t\tif (v === null) delete nextMeta[k];\n\t\t}\n\t\trootDoc.transact(() => {\n\t\t\tpatchEntry(treeMap, id, {\n\t\t\t\tmeta: nextMeta,\n\t\t\t\tupdatedAt: Date.now(),\n\t\t\t});\n\t\t});\n\t}\n\n\tprivate moveTo(id: string, newParentId: string): void {\n\t\tconst treeMap = this.treeMap;\n\t\tconst rootDoc = this.server.rootDocument;\n\t\tif (!treeMap || !rootDoc) return;\n\t\tconst now = Date.now();\n\t\trootDoc.transact(() => {\n\t\t\tpatchEntry(treeMap, id, {\n\t\t\t\tparentId: newParentId,\n\t\t\t\torder: now,\n\t\t\t\tupdatedAt: now,\n\t\t\t});\n\t\t});\n\t\t// Best-effort registry reparent so REST/FTS sees the move too.\n\t\tvoid this.server.client\n\t\t\t.updateDocumentMeta(id, { parent_id: newParentId })\n\t\t\t.catch((e) => {\n\t\t\t\tconsole.error(\n\t\t\t\t\t`[abracadabra-resend] REST reparent failed for ${id}: ${e?.message ?? e}`,\n\t\t\t\t);\n\t\t\t});\n\t}\n}\n","/**\n * Thin wrapper around the official `resend` SDK. Kept separate so tests can\n * substitute a fake without mocking the SDK directly.\n */\nimport { Resend } from \"resend\";\nimport type { EmailPayload } from \"./render.ts\";\n\nexport interface SendResult {\n\tid: string;\n}\n\nexport interface ResendSender {\n\tsend(payload: EmailPayload, headers?: Record<string, string>): Promise<SendResult>;\n}\n\nexport class ResendClient implements ResendSender {\n\tprivate readonly resend: Resend;\n\n\tconstructor(apiKey: string) {\n\t\tthis.resend = new Resend(apiKey);\n\t}\n\n\tasync send(\n\t\tpayload: EmailPayload,\n\t\theaders?: Record<string, string>,\n\t): Promise<SendResult> {\n\t\tif (!payload.from) {\n\t\t\tthrow new Error(\"ResendClient.send: payload.from is required\");\n\t\t}\n\t\tconst { data, error } = await this.resend.emails.send({\n\t\t\tfrom: payload.from,\n\t\t\tto: payload.to,\n\t\t\tcc: payload.cc,\n\t\t\tbcc: payload.bcc,\n\t\t\tsubject: payload.subject,\n\t\t\thtml: payload.html,\n\t\t\treplyTo: payload.replyTo,\n\t\t\theaders,\n\t\t});\n\t\tif (error) {\n\t\t\tthrow new Error(\n\t\t\t\t`Resend rejected the message: ${error.message ?? JSON.stringify(error)}`,\n\t\t\t);\n\t\t}\n\t\tif (!data?.id) {\n\t\t\tthrow new Error(\"Resend returned no id for the dispatched message\");\n\t\t}\n\t\treturn { id: data.id };\n\t}\n}\n","/**\n * Checks if something is Uint8Array. Be careful: nodejs Buffer will return true.\n * @param a - value to test\n * @returns `true` when the value is a Uint8Array-compatible view.\n * @example\n * Check whether a value is a Uint8Array-compatible view.\n * ```ts\n * isBytes(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport function isBytes(a) {\n // Plain `instanceof Uint8Array` is too strict for some Buffer / proxy / cross-realm cases.\n // The fallback still requires a real ArrayBuffer view, so plain\n // JSON-deserialized `{ constructor: ... }` spoofing is rejected, and\n // `BYTES_PER_ELEMENT === 1` keeps the fallback on byte-oriented views.\n return (a instanceof Uint8Array ||\n (ArrayBuffer.isView(a) &&\n a.constructor.name === 'Uint8Array' &&\n 'BYTES_PER_ELEMENT' in a &&\n a.BYTES_PER_ELEMENT === 1));\n}\n/**\n * Asserts something is a non-negative integer.\n * @param n - number to validate\n * @param title - label included in thrown errors\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Validate a non-negative integer option.\n * ```ts\n * anumber(32, 'length');\n * ```\n */\nexport function anumber(n, title = '') {\n if (typeof n !== 'number') {\n const prefix = title && `\"${title}\" `;\n throw new TypeError(`${prefix}expected number, got ${typeof n}`);\n }\n if (!Number.isSafeInteger(n) || n < 0) {\n const prefix = title && `\"${title}\" `;\n throw new RangeError(`${prefix}expected integer >= 0, got ${n}`);\n }\n}\n/**\n * Asserts something is Uint8Array.\n * @param value - value to validate\n * @param length - optional exact length constraint\n * @param title - label included in thrown errors\n * @returns The validated byte array.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Validate that a value is a byte array.\n * ```ts\n * abytes(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport function abytes(value, length, title = '') {\n const bytes = isBytes(value);\n const len = value?.length;\n const needsLen = length !== undefined;\n if (!bytes || (needsLen && len !== length)) {\n const prefix = title && `\"${title}\" `;\n const ofLen = needsLen ? ` of length ${length}` : '';\n const got = bytes ? `length=${len}` : `type=${typeof value}`;\n const message = prefix + 'expected Uint8Array' + ofLen + ', got ' + got;\n if (!bytes)\n throw new TypeError(message);\n throw new RangeError(message);\n }\n return value;\n}\n/**\n * Copies bytes into a fresh Uint8Array.\n * Buffer-style slices can alias the same backing store, so callers that need ownership should copy.\n * @param bytes - source bytes to clone\n * @returns Freshly allocated copy of `bytes`.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Clone a byte array before mutating it.\n * ```ts\n * const copy = copyBytes(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport function copyBytes(bytes) {\n // `Uint8Array.from(...)` would also accept arrays / other typed arrays. Keep this helper strict\n // because callers use it at byte-validation boundaries before mutating the detached copy.\n return Uint8Array.from(abytes(bytes));\n}\n/**\n * Asserts something is a wrapped hash constructor.\n * @param h - hash constructor to validate\n * @throws On wrong argument types or invalid hash wrapper shape. {@link TypeError}\n * @throws On invalid hash metadata ranges or values. {@link RangeError}\n * @throws If the hash metadata allows empty outputs or block sizes. {@link Error}\n * @example\n * Validate a callable hash wrapper.\n * ```ts\n * import { ahash } from '@noble/hashes/utils.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * ahash(sha256);\n * ```\n */\nexport function ahash(h) {\n if (typeof h !== 'function' || typeof h.create !== 'function')\n throw new TypeError('Hash must wrapped by utils.createHasher');\n anumber(h.outputLen);\n anumber(h.blockLen);\n // HMAC and KDF callers treat these as real byte lengths; allowing zero lets fake wrappers pass\n // validation and can produce empty outputs instead of failing fast.\n if (h.outputLen < 1)\n throw new Error('\"outputLen\" must be >= 1');\n if (h.blockLen < 1)\n throw new Error('\"blockLen\" must be >= 1');\n}\n/**\n * Asserts a hash instance has not been destroyed or finished.\n * @param instance - hash instance to validate\n * @param checkFinished - whether to reject finalized instances\n * @throws If the hash instance has already been destroyed or finalized. {@link Error}\n * @example\n * Validate that a hash instance is still usable.\n * ```ts\n * import { aexists } from '@noble/hashes/utils.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const hash = sha256.create();\n * aexists(hash);\n * ```\n */\nexport function aexists(instance, checkFinished = true) {\n if (instance.destroyed)\n throw new Error('Hash instance has been destroyed');\n if (checkFinished && instance.finished)\n throw new Error('Hash#digest() has already been called');\n}\n/**\n * Asserts output is a sufficiently-sized byte array.\n * @param out - destination buffer\n * @param instance - hash instance providing output length\n * Oversized buffers are allowed; downstream code only promises to fill the first `outputLen` bytes.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Validate a caller-provided digest buffer.\n * ```ts\n * import { aoutput } from '@noble/hashes/utils.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const hash = sha256.create();\n * aoutput(new Uint8Array(hash.outputLen), hash);\n * ```\n */\nexport function aoutput(out, instance) {\n abytes(out, undefined, 'digestInto() output');\n const min = instance.outputLen;\n if (out.length < min) {\n throw new RangeError('\"digestInto() output\" expected to be of length >=' + min);\n }\n}\n/**\n * Casts a typed array view to Uint8Array.\n * @param arr - source typed array\n * @returns Uint8Array view over the same buffer.\n * @example\n * Reinterpret a typed array as bytes.\n * ```ts\n * u8(new Uint32Array([1, 2]));\n * ```\n */\nexport function u8(arr) {\n return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n/**\n * Casts a typed array view to Uint32Array.\n * `arr.byteOffset` must already be 4-byte aligned or the platform\n * Uint32Array constructor will throw.\n * @param arr - source typed array\n * @returns Uint32Array view over the same buffer.\n * @example\n * Reinterpret a byte array as 32-bit words.\n * ```ts\n * u32(new Uint8Array(8));\n * ```\n */\nexport function u32(arr) {\n return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n}\n/**\n * Zeroizes typed arrays in place. Warning: JS provides no guarantees.\n * @param arrays - arrays to overwrite with zeros\n * @example\n * Zeroize sensitive buffers in place.\n * ```ts\n * clean(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport function clean(...arrays) {\n for (let i = 0; i < arrays.length; i++) {\n arrays[i].fill(0);\n }\n}\n/**\n * Creates a DataView for byte-level manipulation.\n * @param arr - source typed array\n * @returns DataView over the same buffer region.\n * @example\n * Create a DataView over an existing buffer.\n * ```ts\n * createView(new Uint8Array(4));\n * ```\n */\nexport function createView(arr) {\n return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n/**\n * Rotate-right operation for uint32 values.\n * @param word - source word\n * @param shift - shift amount in bits\n * @returns Rotated word.\n * @example\n * Rotate a 32-bit word to the right.\n * ```ts\n * rotr(0x12345678, 8);\n * ```\n */\nexport function rotr(word, shift) {\n return (word << (32 - shift)) | (word >>> shift);\n}\n/**\n * Rotate-left operation for uint32 values.\n * @param word - source word\n * @param shift - shift amount in bits\n * @returns Rotated word.\n * @example\n * Rotate a 32-bit word to the left.\n * ```ts\n * rotl(0x12345678, 8);\n * ```\n */\nexport function rotl(word, shift) {\n return (word << shift) | ((word >>> (32 - shift)) >>> 0);\n}\n/** Whether the current platform is little-endian. */\nexport const isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();\n/**\n * Byte-swap operation for uint32 values.\n * @param word - source word\n * @returns Word with reversed byte order.\n * @example\n * Reverse the byte order of a 32-bit word.\n * ```ts\n * byteSwap(0x11223344);\n * ```\n */\nexport function byteSwap(word) {\n return (((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff));\n}\n/**\n * Conditionally byte-swaps one 32-bit word on big-endian platforms.\n * @param n - source word\n * @returns Original or byte-swapped word depending on platform endianness.\n * @example\n * Normalize a 32-bit word for host endianness.\n * ```ts\n * swap8IfBE(0x11223344);\n * ```\n */\nexport const swap8IfBE = isLE\n ? (n) => n\n : (n) => byteSwap(n) >>> 0;\n/**\n * Byte-swaps every word of a Uint32Array in place.\n * @param arr - array to mutate\n * @returns The same array after mutation; callers pass live state arrays here.\n * @example\n * Reverse the byte order of every word in place.\n * ```ts\n * byteSwap32(new Uint32Array([0x11223344]));\n * ```\n */\nexport function byteSwap32(arr) {\n for (let i = 0; i < arr.length; i++) {\n arr[i] = byteSwap(arr[i]);\n }\n return arr;\n}\n/**\n * Conditionally byte-swaps a Uint32Array on big-endian platforms.\n * @param u - array to normalize for host endianness\n * @returns Original or byte-swapped array depending on platform endianness.\n * On big-endian runtimes this mutates `u` in place via `byteSwap32(...)`.\n * @example\n * Normalize a word array for host endianness.\n * ```ts\n * swap32IfBE(new Uint32Array([0x11223344]));\n * ```\n */\nexport const swap32IfBE = isLE\n ? (u) => u\n : byteSwap32;\n// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\nconst hasHexBuiltin = /* @__PURE__ */ (() => \n// @ts-ignore\ntypeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));\n/**\n * Convert byte array to hex string.\n * Uses the built-in function when available and assumes it matches the tested\n * fallback semantics.\n * @param bytes - bytes to encode\n * @returns Lowercase hexadecimal string.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Convert bytes to lowercase hexadecimal.\n * ```ts\n * bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])); // 'cafe0123'\n * ```\n */\nexport function bytesToHex(bytes) {\n abytes(bytes);\n // @ts-ignore\n if (hasHexBuiltin)\n return bytes.toHex();\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };\nfunction asciiToBase16(ch) {\n if (ch >= asciis._0 && ch <= asciis._9)\n return ch - asciis._0; // '2' => 50-48\n if (ch >= asciis.A && ch <= asciis.F)\n return ch - (asciis.A - 10); // 'B' => 66-(65-10)\n if (ch >= asciis.a && ch <= asciis.f)\n return ch - (asciis.a - 10); // 'b' => 98-(97-10)\n return;\n}\n/**\n * Convert hex string to byte array. Uses built-in function, when available.\n * @param hex - hexadecimal string to decode\n * @returns Decoded bytes.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Decode lowercase hexadecimal into bytes.\n * ```ts\n * hexToBytes('cafe0123'); // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n * ```\n */\nexport function hexToBytes(hex) {\n if (typeof hex !== 'string')\n throw new TypeError('hex string expected, got ' + typeof hex);\n if (hasHexBuiltin) {\n try {\n return Uint8Array.fromHex(hex);\n }\n catch (error) {\n if (error instanceof SyntaxError)\n throw new RangeError(error.message);\n throw error;\n }\n }\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2)\n throw new RangeError('hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new RangeError('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163\n }\n return array;\n}\n/**\n * There is no setImmediate in browser and setTimeout is slow.\n * This yields to the Promise/microtask scheduler queue, not to timers or the\n * full macrotask event loop.\n * @example\n * Yield to the next scheduler tick.\n * ```ts\n * await nextTick();\n * ```\n */\nexport const nextTick = async () => { };\n/**\n * Returns control to the Promise/microtask scheduler every `tick`\n * milliseconds to avoid blocking long loops.\n * @param iters - number of loop iterations to run\n * @param tick - maximum time slice in milliseconds\n * @param cb - callback executed on each iteration\n * @example\n * Run a loop that periodically yields back to the event loop.\n * ```ts\n * await asyncLoop(2, 0, () => {});\n * ```\n */\nexport async function asyncLoop(iters, tick, cb) {\n let ts = Date.now();\n for (let i = 0; i < iters; i++) {\n cb(i);\n // Date.now() is not monotonic, so in case if clock goes backwards we return return control too\n const diff = Date.now() - ts;\n if (diff >= 0 && diff < tick)\n continue;\n await nextTick();\n ts += diff;\n }\n}\n/**\n * Converts string to bytes using UTF8 encoding.\n * Built-in doesn't validate input to be string: we do the check.\n * Non-ASCII details are delegated to the platform `TextEncoder`.\n * @param str - string to encode\n * @returns UTF-8 encoded bytes.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Encode a string as UTF-8 bytes.\n * ```ts\n * utf8ToBytes('abc'); // Uint8Array.from([97, 98, 99])\n * ```\n */\nexport function utf8ToBytes(str) {\n if (typeof str !== 'string')\n throw new TypeError('string expected');\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n/**\n * Helper for KDFs: consumes Uint8Array or string.\n * String inputs are UTF-8 encoded; byte-array inputs stay aliased to the caller buffer.\n * @param data - user-provided KDF input\n * @param errorTitle - label included in thrown errors\n * @returns Byte representation of the input.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Normalize KDF input to bytes.\n * ```ts\n * kdfInputToBytes('password');\n * ```\n */\nexport function kdfInputToBytes(data, errorTitle = '') {\n if (typeof data === 'string')\n return utf8ToBytes(data);\n return abytes(data, undefined, errorTitle);\n}\n/**\n * Copies several Uint8Arrays into one.\n * @param arrays - arrays to concatenate\n * @returns Concatenated byte array.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Concatenate multiple byte arrays.\n * ```ts\n * concatBytes(new Uint8Array([1]), new Uint8Array([2]));\n * ```\n */\nexport function concatBytes(...arrays) {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n abytes(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\n/**\n * Merges default options and passed options.\n * @param defaults - base option object\n * @param opts - user overrides\n * @returns Merged option object. The merge mutates `defaults` in place.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Merge user overrides onto default options.\n * ```ts\n * checkOpts({ dkLen: 32 }, { asyncTick: 10 });\n * ```\n */\nexport function checkOpts(defaults, opts) {\n if (opts !== undefined && {}.toString.call(opts) !== '[object Object]')\n throw new TypeError('options must be object or undefined');\n const merged = Object.assign(defaults, opts);\n return merged;\n}\n/**\n * Creates a callable hash function from a stateful class constructor.\n * @param hashCons - hash constructor or factory\n * @param info - optional metadata such as DER OID\n * @returns Frozen callable hash wrapper with `.create()`.\n * Wrapper construction eagerly calls `hashCons(undefined)` once to read\n * `outputLen` / `blockLen`, so constructor side effects happen at module\n * init time.\n * @example\n * Wrap a stateful hash constructor into a callable helper.\n * ```ts\n * import { createHasher } from '@noble/hashes/utils.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const wrapped = createHasher(sha256.create, { oid: sha256.oid });\n * wrapped(new Uint8Array([1]));\n * ```\n */\nexport function createHasher(hashCons, info = {}) {\n const hashC = (msg, opts) => hashCons(opts)\n .update(msg)\n .digest();\n const tmp = hashCons(undefined);\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.canXOF = tmp.canXOF;\n hashC.create = (opts) => hashCons(opts);\n Object.assign(hashC, info);\n return Object.freeze(hashC);\n}\n/**\n * Cryptographically secure PRNG backed by `crypto.getRandomValues`.\n * @param bytesLength - number of random bytes to generate\n * @returns Random bytes.\n * The platform `getRandomValues()` implementation still defines any\n * single-call length cap, and this helper rejects oversize requests\n * with a stable library `RangeError` instead of host-specific errors.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @throws If the current runtime does not provide `crypto.getRandomValues`. {@link Error}\n * @example\n * Generate a fresh random key or nonce.\n * ```ts\n * const key = randomBytes(16);\n * ```\n */\nexport function randomBytes(bytesLength = 32) {\n // Match the repo's other length-taking helpers instead of relying on Uint8Array coercion.\n anumber(bytesLength, 'bytesLength');\n const cr = typeof globalThis === 'object' ? globalThis.crypto : null;\n if (typeof cr?.getRandomValues !== 'function')\n throw new Error('crypto.getRandomValues must be defined');\n // Web Cryptography API Level 2 §10.1.1:\n // if `byteLength > 65536`, throw `QuotaExceededError`.\n // Keep the guard explicit so callers can see the quota in code\n // instead of discovering it by reading the spec or host errors.\n // This wrapper surfaces the same quota as a stable library RangeError.\n if (bytesLength > 65536)\n throw new RangeError(`\"bytesLength\" expected <= 65536, got ${bytesLength}`);\n return cr.getRandomValues(new Uint8Array(bytesLength));\n}\n/**\n * Creates OID metadata for NIST hashes with prefix `06 09 60 86 48 01 65 03 04 02`.\n * @param suffix - final OID byte for the selected hash.\n * The helper accepts any byte even though only the documented NIST hash\n * suffixes are meaningful downstream.\n * @returns Object containing the DER-encoded OID.\n * @example\n * Build OID metadata for a NIST hash.\n * ```ts\n * oidNist(0x01);\n * ```\n */\nexport const oidNist = (suffix) => ({\n // Current NIST hashAlgs suffixes used here fit in one DER subidentifier octet.\n // Larger suffix values would need base-128 OID encoding and a different length byte.\n oid: Uint8Array.from([0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, suffix]),\n});\n//# sourceMappingURL=utils.js.map","/**\n * Internal Merkle-Damgard hash utils.\n * @module\n */\nimport { abytes, aexists, aoutput, clean, createView, } from \"./utils.js\";\n/**\n * Shared 32-bit conditional boolean primitive reused by SHA-256, SHA-1, and MD5 `F`.\n * Returns bits from `b` when `a` is set, otherwise from `c`.\n * The XOR form is equivalent to MD5's `F(X,Y,Z) = XY v not(X)Z` because the masked terms never\n * set the same bit.\n * @param a - selector word\n * @param b - word chosen when selector bit is set\n * @param c - word chosen when selector bit is clear\n * @returns Mixed 32-bit word.\n * @example\n * Combine three words with the shared 32-bit choice primitive.\n * ```ts\n * Chi(0xffffffff, 0x12345678, 0x87654321);\n * ```\n */\nexport function Chi(a, b, c) {\n return (a & b) ^ (~a & c);\n}\n/**\n * Shared 32-bit majority primitive reused by SHA-256 and SHA-1.\n * Returns bits shared by at least two inputs.\n * @param a - first input word\n * @param b - second input word\n * @param c - third input word\n * @returns Mixed 32-bit word.\n * @example\n * Combine three words with the shared 32-bit majority primitive.\n * ```ts\n * Maj(0xffffffff, 0x12345678, 0x87654321);\n * ```\n */\nexport function Maj(a, b, c) {\n return (a & b) ^ (a & c) ^ (b & c);\n}\n/**\n * Merkle-Damgard hash construction base class.\n * Could be used to create MD5, RIPEMD, SHA1, SHA2.\n * Accepts only byte-aligned `Uint8Array` input, even when the underlying spec describes bit\n * strings with partial-byte tails.\n * @param blockLen - internal block size in bytes\n * @param outputLen - digest size in bytes\n * @param padOffset - trailing length field size in bytes\n * @param isLE - whether length and state words are encoded in little-endian\n * @example\n * Use a concrete subclass to get the shared Merkle-Damgard update/digest flow.\n * ```ts\n * import { _SHA1 } from '@noble/hashes/legacy.js';\n * const hash = new _SHA1();\n * hash.update(new Uint8Array([97, 98, 99]));\n * hash.digest();\n * ```\n */\nexport class HashMD {\n blockLen;\n outputLen;\n canXOF = false;\n padOffset;\n isLE;\n // For partial updates less than block size\n buffer;\n view;\n finished = false;\n length = 0;\n pos = 0;\n destroyed = false;\n constructor(blockLen, outputLen, padOffset, isLE) {\n this.blockLen = blockLen;\n this.outputLen = outputLen;\n this.padOffset = padOffset;\n this.isLE = isLE;\n this.buffer = new Uint8Array(blockLen);\n this.view = createView(this.buffer);\n }\n update(data) {\n aexists(this);\n abytes(data);\n const { view, buffer, blockLen } = this;\n const len = data.length;\n for (let pos = 0; pos < len;) {\n const take = Math.min(blockLen - this.pos, len - pos);\n // Fast path only when there is no buffered partial block: `take === blockLen` implies\n // `this.pos === 0`, so we can process full blocks directly from the input view.\n if (take === blockLen) {\n const dataView = createView(data);\n for (; blockLen <= len - pos; pos += blockLen)\n this.process(dataView, pos);\n continue;\n }\n buffer.set(data.subarray(pos, pos + take), this.pos);\n this.pos += take;\n pos += take;\n if (this.pos === blockLen) {\n this.process(view, 0);\n this.pos = 0;\n }\n }\n this.length += data.length;\n this.roundClean();\n return this;\n }\n digestInto(out) {\n aexists(this);\n aoutput(out, this);\n this.finished = true;\n // Padding\n // We can avoid allocation of buffer for padding completely if it\n // was previously not allocated here. But it won't change performance.\n const { buffer, view, blockLen, isLE } = this;\n let { pos } = this;\n // append the bit '1' to the message\n buffer[pos++] = 0b10000000;\n clean(this.buffer.subarray(pos));\n // we have less than padOffset left in buffer, so we cannot put length in\n // current block, need process it and pad again\n if (this.padOffset > blockLen - pos) {\n this.process(view, 0);\n pos = 0;\n }\n // Pad until full block byte with zeros\n for (let i = pos; i < blockLen; i++)\n buffer[i] = 0;\n // `padOffset` reserves the whole length field. For SHA-384/512 the high 64 bits stay zero from\n // the padding fill above, and JS will overflow before user input can make that half non-zero.\n // So we only need to write the low 64 bits here.\n view.setBigUint64(blockLen - 8, BigInt(this.length * 8), isLE);\n this.process(view, 0);\n const oview = createView(out);\n const len = this.outputLen;\n // NOTE: we do division by 4 later, which must be fused in single op with modulo by JIT\n if (len % 4)\n throw new Error('_sha2: outputLen must be aligned to 32bit');\n const outLen = len / 4;\n const state = this.get();\n if (outLen > state.length)\n throw new Error('_sha2: outputLen bigger than state');\n for (let i = 0; i < outLen; i++)\n oview.setUint32(4 * i, state[i], isLE);\n }\n digest() {\n const { buffer, outputLen } = this;\n this.digestInto(buffer);\n // Copy before destroy(): subclasses wipe `buffer` during cleanup, but `digest()` must return\n // fresh bytes to the caller.\n const res = buffer.slice(0, outputLen);\n this.destroy();\n return res;\n }\n _cloneInto(to) {\n to ||= new this.constructor();\n to.set(...this.get());\n const { blockLen, buffer, length, finished, destroyed, pos } = this;\n to.destroyed = destroyed;\n to.finished = finished;\n to.length = length;\n to.pos = pos;\n // Only partial-block bytes need copying: when `length % blockLen === 0`, `pos === 0` and\n // later `update()` / `digestInto()` overwrite `to.buffer` from the start before reading it.\n if (length % blockLen)\n to.buffer.set(buffer);\n return to;\n }\n clone() {\n return this._cloneInto();\n }\n}\n/**\n * Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.\n * Check out `test/misc/sha2-gen-iv.js` for recomputation guide.\n */\n/** Initial SHA256 state from RFC 6234 §6.1: the first 32 bits of the fractional parts of the\n * square roots of the first eight prime numbers. Exported as a shared table; callers must treat\n * it as read-only because constructors copy words from it by index. */\nexport const SHA256_IV = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,\n]);\n/** Initial SHA224 state `H(0)` from RFC 6234 §6.1. Exported as a shared table; callers must\n * treat it as read-only because constructors copy words from it by index. */\nexport const SHA224_IV = /* @__PURE__ */ Uint32Array.from([\n 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4,\n]);\n/** Initial SHA384 state from RFC 6234 §6.3: eight RFC 64-bit `H(0)` words stored as sixteen\n * big-endian 32-bit halves. Derived from the fractional parts of the square roots of the ninth\n * through sixteenth prime numbers. Exported as a shared table; callers must treat it as read-only\n * because constructors copy halves from it by index. */\nexport const SHA384_IV = /* @__PURE__ */ Uint32Array.from([\n 0xcbbb9d5d, 0xc1059ed8, 0x629a292a, 0x367cd507, 0x9159015a, 0x3070dd17, 0x152fecd8, 0xf70e5939,\n 0x67332667, 0xffc00b31, 0x8eb44a87, 0x68581511, 0xdb0c2e0d, 0x64f98fa7, 0x47b5481d, 0xbefa4fa4,\n]);\n/** Initial SHA512 state from RFC 6234 §6.3: eight RFC 64-bit `H(0)` words stored as sixteen\n * big-endian 32-bit halves. Derived from the fractional parts of the square roots of the first\n * eight prime numbers. Exported as a shared table; callers must treat it as read-only because\n * constructors copy halves from it by index. */\nexport const SHA512_IV = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xf3bcc908, 0xbb67ae85, 0x84caa73b, 0x3c6ef372, 0xfe94f82b, 0xa54ff53a, 0x5f1d36f1,\n 0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, 0x1f83d9ab, 0xfb41bd6b, 0x5be0cd19, 0x137e2179,\n]);\n//# sourceMappingURL=_md.js.map","const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);\nconst _32n = /* @__PURE__ */ BigInt(32);\n// Split bigint into two 32-bit halves. With `le=true`, returned fields become `{ h: low, l: high\n// }` to match little-endian word order rather than the property names.\nfunction fromBig(n, le = false) {\n if (le)\n return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };\n return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };\n}\n// Split bigint list into `[highWords, lowWords]` when `le=false`; with `le=true`, the first array\n// holds the low halves because `fromBig(...)` swaps the semantic meaning of `h` and `l`.\nfunction split(lst, le = false) {\n const len = lst.length;\n let Ah = new Uint32Array(len);\n let Al = new Uint32Array(len);\n for (let i = 0; i < len; i++) {\n const { h, l } = fromBig(lst[i], le);\n [Ah[i], Al[i]] = [h, l];\n }\n return [Ah, Al];\n}\n// Combine explicit `(high, low)` 32-bit halves into a bigint; `>>> 0` normalizes signed JS\n// bitwise results back to uint32 first, and little-endian callers must swap.\nconst toBig = (h, l) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);\n// High 32-bit half of a 64-bit logical right shift for `s` in `0..31`.\nconst shrSH = (h, _l, s) => h >>> s;\n// Low 32-bit half of a 64-bit logical right shift, valid for `s` in `1..31`.\nconst shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);\n// High 32-bit half of a 64-bit right rotate, valid for `s` in `1..31`.\nconst rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s));\n// Low 32-bit half of a 64-bit right rotate, valid for `s` in `1..31`.\nconst rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);\n// High 32-bit half of a 64-bit right rotate, valid for `s` in `33..63`; `32` uses `rotr32*`.\nconst rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32));\n// Low 32-bit half of a 64-bit right rotate, valid for `s` in `33..63`; `32` uses `rotr32*`.\nconst rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s));\n// High 32-bit half of a 64-bit right rotate for `s === 32`; this is just the swapped low half.\nconst rotr32H = (_h, l) => l;\n// Low 32-bit half of a 64-bit right rotate for `s === 32`; this is just the swapped high half.\nconst rotr32L = (h, _l) => h;\n// High 32-bit half of a 64-bit left rotate, valid for `s` in `1..31`.\nconst rotlSH = (h, l, s) => (h << s) | (l >>> (32 - s));\n// Low 32-bit half of a 64-bit left rotate, valid for `s` in `1..31`.\nconst rotlSL = (h, l, s) => (l << s) | (h >>> (32 - s));\n// High 32-bit half of a 64-bit left rotate, valid for `s` in `33..63`; `32` uses `rotr32*`.\nconst rotlBH = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s));\n// Low 32-bit half of a 64-bit left rotate, valid for `s` in `33..63`; `32` uses `rotr32*`.\nconst rotlBL = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s));\n// Add two split 64-bit words and return the split `{ h, l }` sum.\n// JS uses 32-bit signed integers for bitwise operations, so we cannot simply shift the carry out\n// of the low sum and instead use division.\nfunction add(Ah, Al, Bh, Bl) {\n const l = (Al >>> 0) + (Bl >>> 0);\n return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };\n}\n// Addition with more than 2 elements\n// Unmasked low-word accumulator for 3-way addition; pass the raw result into `add3H(...)`.\nconst add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);\n// High-word finalize step for 3-way addition; `low` must be the untruncated output of `add3L(...)`.\nconst add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;\n// Unmasked low-word accumulator for 4-way addition; pass the raw result into `add4H(...)`.\nconst add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);\n// High-word finalize step for 4-way addition; `low` must be the untruncated output of `add4L(...)`.\nconst add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;\n// Unmasked low-word accumulator for 5-way addition; pass the raw result into `add5H(...)`.\nconst add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);\n// High-word finalize step for 5-way addition; `low` must be the untruncated output of `add5L(...)`.\nconst add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;\n// prettier-ignore\nexport { add, add3H, add3L, add4H, add4L, add5H, add5L, fromBig, rotlBH, rotlBL, rotlSH, rotlSL, rotr32H, rotr32L, rotrBH, rotrBL, rotrSH, rotrSL, shrSH, shrSL, split, toBig };\n// Canonical grouped namespace for callers that prefer one object.\n// Named exports stay for direct imports.\n// prettier-ignore\nconst u64 = {\n fromBig, split, toBig,\n shrSH, shrSL,\n rotrSH, rotrSL, rotrBH, rotrBL,\n rotr32H, rotr32L,\n rotlSH, rotlSL, rotlBH, rotlBL,\n add, add3L, add3H, add4L, add4H, add5H, add5L,\n};\n// Default export mirrors named `u64` for compatibility with object-style imports.\nexport default u64;\n//# sourceMappingURL=_u64.js.map","/**\n * SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256.\n * SHA256 is the fastest hash implementable in JS, even faster than Blake3.\n * Check out {@link https://www.rfc-editor.org/rfc/rfc4634 | RFC 4634} and\n * {@link https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf | FIPS 180-4}.\n * @module\n */\nimport { Chi, HashMD, Maj, SHA224_IV, SHA256_IV, SHA384_IV, SHA512_IV } from \"./_md.js\";\nimport * as u64 from \"./_u64.js\";\nimport { clean, createHasher, oidNist, rotr } from \"./utils.js\";\n/**\n * SHA-224 / SHA-256 round constants from RFC 6234 §5.1: the first 32 bits\n * of the cube roots of the first 64 primes (2..311).\n */\n// prettier-ignore\nconst SHA256_K = /* @__PURE__ */ Uint32Array.from([\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2\n]);\n/** Reusable SHA-224 / SHA-256 message schedule buffer `W_t` from RFC 6234 §6.2 step 1. */\nconst SHA256_W = /* @__PURE__ */ new Uint32Array(64);\n/** Internal SHA-224 / SHA-256 compression engine from RFC 6234 §6.2. */\nclass SHA2_32B extends HashMD {\n constructor(outputLen) {\n super(64, outputLen, 8, false);\n }\n get() {\n const { A, B, C, D, E, F, G, H } = this;\n return [A, B, C, D, E, F, G, H];\n }\n // prettier-ignore\n set(A, B, C, D, E, F, G, H) {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n this.E = E | 0;\n this.F = F | 0;\n this.G = G | 0;\n this.H = H | 0;\n }\n process(view, offset) {\n // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4)\n SHA256_W[i] = view.getUint32(offset, false);\n for (let i = 16; i < 64; i++) {\n const W15 = SHA256_W[i - 15];\n const W2 = SHA256_W[i - 2];\n const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);\n const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);\n SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;\n }\n // Compression function main loop, 64 rounds\n let { A, B, C, D, E, F, G, H } = this;\n for (let i = 0; i < 64; i++) {\n const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);\n const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);\n const T2 = (sigma0 + Maj(A, B, C)) | 0;\n H = G;\n G = F;\n F = E;\n E = (D + T1) | 0;\n D = C;\n C = B;\n B = A;\n A = (T1 + T2) | 0;\n }\n // Add the compressed chunk to the current hash value\n A = (A + this.A) | 0;\n B = (B + this.B) | 0;\n C = (C + this.C) | 0;\n D = (D + this.D) | 0;\n E = (E + this.E) | 0;\n F = (F + this.F) | 0;\n G = (G + this.G) | 0;\n H = (H + this.H) | 0;\n this.set(A, B, C, D, E, F, G, H);\n }\n roundClean() {\n clean(SHA256_W);\n }\n destroy() {\n // HashMD callers route post-destroy usability through `destroyed`; zeroizing alone still leaves\n // update()/digest() callable on reused instances.\n this.destroyed = true;\n this.set(0, 0, 0, 0, 0, 0, 0, 0);\n clean(this.buffer);\n }\n}\n/** Internal SHA-256 hash class grounded in RFC 6234 §6.2. */\nexport class _SHA256 extends SHA2_32B {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n A = SHA256_IV[0] | 0;\n B = SHA256_IV[1] | 0;\n C = SHA256_IV[2] | 0;\n D = SHA256_IV[3] | 0;\n E = SHA256_IV[4] | 0;\n F = SHA256_IV[5] | 0;\n G = SHA256_IV[6] | 0;\n H = SHA256_IV[7] | 0;\n constructor() {\n super(32);\n }\n}\n/** Internal SHA-224 hash class grounded in RFC 6234 §6.2 and §8.5. */\nexport class _SHA224 extends SHA2_32B {\n A = SHA224_IV[0] | 0;\n B = SHA224_IV[1] | 0;\n C = SHA224_IV[2] | 0;\n D = SHA224_IV[3] | 0;\n E = SHA224_IV[4] | 0;\n F = SHA224_IV[5] | 0;\n G = SHA224_IV[6] | 0;\n H = SHA224_IV[7] | 0;\n constructor() {\n super(28);\n }\n}\n// SHA2-512 is slower than sha256 in js because u64 operations are slow.\n// SHA-384 / SHA-512 round constants from RFC 6234 §5.2:\n// 80 full 64-bit words split into high/low halves.\n// prettier-ignore\nconst K512 = /* @__PURE__ */ (() => u64.split([\n '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',\n '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',\n '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',\n '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',\n '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',\n '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',\n '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',\n '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',\n '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',\n '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',\n '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',\n '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',\n '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',\n '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',\n '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',\n '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',\n '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',\n '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',\n '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',\n '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'\n].map(n => BigInt(n))))();\nconst SHA512_Kh = /* @__PURE__ */ (() => K512[0])();\nconst SHA512_Kl = /* @__PURE__ */ (() => K512[1])();\n// Reusable high-half schedule buffer for the RFC 6234 §6.4 64-bit `W_t` words.\nconst SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);\n// Reusable low-half schedule buffer for the RFC 6234 §6.4 64-bit `W_t` words.\nconst SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);\n/** Internal SHA-384 / SHA-512 compression engine from RFC 6234 §6.4. */\nclass SHA2_64B extends HashMD {\n constructor(outputLen) {\n super(128, outputLen, 16, false);\n }\n // prettier-ignore\n get() {\n const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];\n }\n // prettier-ignore\n set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {\n this.Ah = Ah | 0;\n this.Al = Al | 0;\n this.Bh = Bh | 0;\n this.Bl = Bl | 0;\n this.Ch = Ch | 0;\n this.Cl = Cl | 0;\n this.Dh = Dh | 0;\n this.Dl = Dl | 0;\n this.Eh = Eh | 0;\n this.El = El | 0;\n this.Fh = Fh | 0;\n this.Fl = Fl | 0;\n this.Gh = Gh | 0;\n this.Gl = Gl | 0;\n this.Hh = Hh | 0;\n this.Hl = Hl | 0;\n }\n process(view, offset) {\n // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) {\n SHA512_W_H[i] = view.getUint32(offset);\n SHA512_W_L[i] = view.getUint32((offset += 4));\n }\n for (let i = 16; i < 80; i++) {\n // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)\n const W15h = SHA512_W_H[i - 15] | 0;\n const W15l = SHA512_W_L[i - 15] | 0;\n const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7);\n const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7);\n // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)\n const W2h = SHA512_W_H[i - 2] | 0;\n const W2l = SHA512_W_L[i - 2] | 0;\n const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6);\n const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6);\n // SHA512_W[i] = s0 + s1 + SHA512_W[i - 7] + SHA512_W[i - 16];\n const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);\n const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);\n SHA512_W_H[i] = SUMh | 0;\n SHA512_W_L[i] = SUMl | 0;\n }\n let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n // Compression function main loop, 80 rounds\n for (let i = 0; i < 80; i++) {\n // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)\n const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41);\n const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41);\n //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const CHIh = (Eh & Fh) ^ (~Eh & Gh);\n const CHIl = (El & Fl) ^ (~El & Gl);\n // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]\n // prettier-ignore\n const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);\n const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);\n const T1l = T1ll | 0;\n // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)\n const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39);\n const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39);\n const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);\n const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);\n Hh = Gh | 0;\n Hl = Gl | 0;\n Gh = Fh | 0;\n Gl = Fl | 0;\n Fh = Eh | 0;\n Fl = El | 0;\n ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));\n Dh = Ch | 0;\n Dl = Cl | 0;\n Ch = Bh | 0;\n Cl = Bl | 0;\n Bh = Ah | 0;\n Bl = Al | 0;\n const All = u64.add3L(T1l, sigma0l, MAJl);\n Ah = u64.add3H(All, T1h, sigma0h, MAJh);\n Al = All | 0;\n }\n // Add the compressed chunk to the current hash value\n ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));\n ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));\n ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));\n ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));\n ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));\n ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));\n ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));\n ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));\n this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);\n }\n roundClean() {\n clean(SHA512_W_H, SHA512_W_L);\n }\n destroy() {\n // HashMD callers route post-destroy usability through `destroyed`; zeroizing alone still leaves\n // update()/digest() callable on reused instances.\n this.destroyed = true;\n clean(this.buffer);\n this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);\n }\n}\n/** Internal SHA-512 hash class grounded in RFC 6234 §6.3 and §6.4. */\nexport class _SHA512 extends SHA2_64B {\n Ah = SHA512_IV[0] | 0;\n Al = SHA512_IV[1] | 0;\n Bh = SHA512_IV[2] | 0;\n Bl = SHA512_IV[3] | 0;\n Ch = SHA512_IV[4] | 0;\n Cl = SHA512_IV[5] | 0;\n Dh = SHA512_IV[6] | 0;\n Dl = SHA512_IV[7] | 0;\n Eh = SHA512_IV[8] | 0;\n El = SHA512_IV[9] | 0;\n Fh = SHA512_IV[10] | 0;\n Fl = SHA512_IV[11] | 0;\n Gh = SHA512_IV[12] | 0;\n Gl = SHA512_IV[13] | 0;\n Hh = SHA512_IV[14] | 0;\n Hl = SHA512_IV[15] | 0;\n constructor() {\n super(64);\n }\n}\n/** Internal SHA-384 hash class grounded in RFC 6234 §6.3 and §6.4. */\nexport class _SHA384 extends SHA2_64B {\n Ah = SHA384_IV[0] | 0;\n Al = SHA384_IV[1] | 0;\n Bh = SHA384_IV[2] | 0;\n Bl = SHA384_IV[3] | 0;\n Ch = SHA384_IV[4] | 0;\n Cl = SHA384_IV[5] | 0;\n Dh = SHA384_IV[6] | 0;\n Dl = SHA384_IV[7] | 0;\n Eh = SHA384_IV[8] | 0;\n El = SHA384_IV[9] | 0;\n Fh = SHA384_IV[10] | 0;\n Fl = SHA384_IV[11] | 0;\n Gh = SHA384_IV[12] | 0;\n Gl = SHA384_IV[13] | 0;\n Hh = SHA384_IV[14] | 0;\n Hl = SHA384_IV[15] | 0;\n constructor() {\n super(48);\n }\n}\n/**\n * Truncated SHA512/256 and SHA512/224.\n * SHA512_IV is XORed with 0xa5a5a5a5a5a5a5a5, then used as \"intermediary\" IV of SHA512/t.\n * Then t hashes string to produce result IV.\n * See the repo-side derivation recipe in `test/misc/sha2-gen-iv.js`.\n * These IV literals are checked against that script rather than a dedicated\n * local RFC section.\n */\n/** SHA-512/224 IV derived by the SHA-512/t recipe in `test/misc/sha2-gen-iv.js` and\n * stored as sixteen big-endian 32-bit halves. */\nconst T224_IV = /* @__PURE__ */ Uint32Array.from([\n 0x8c3d37c8, 0x19544da2, 0x73e19966, 0x89dcd4d6, 0x1dfab7ae, 0x32ff9c82, 0x679dd514, 0x582f9fcf,\n 0x0f6d2b69, 0x7bd44da8, 0x77e36f73, 0x04c48942, 0x3f9d85a8, 0x6a1d36c8, 0x1112e6ad, 0x91d692a1,\n]);\n/** SHA-512/256 IV derived by the SHA-512/t recipe in `test/misc/sha2-gen-iv.js` and\n * stored as sixteen big-endian 32-bit halves. */\nconst T256_IV = /* @__PURE__ */ Uint32Array.from([\n 0x22312194, 0xfc2bf72c, 0x9f555fa3, 0xc84c64c2, 0x2393b86b, 0x6f53b151, 0x96387719, 0x5940eabd,\n 0x96283ee2, 0xa88effe3, 0xbe5e1e25, 0x53863992, 0x2b0199fc, 0x2c85b8aa, 0x0eb72ddc, 0x81c52ca2,\n]);\n/** Internal SHA-512/224 hash class using the derived `T224_IV` and the shared\n * RFC 6234 §6.4 compression engine. */\nexport class _SHA512_224 extends SHA2_64B {\n Ah = T224_IV[0] | 0;\n Al = T224_IV[1] | 0;\n Bh = T224_IV[2] | 0;\n Bl = T224_IV[3] | 0;\n Ch = T224_IV[4] | 0;\n Cl = T224_IV[5] | 0;\n Dh = T224_IV[6] | 0;\n Dl = T224_IV[7] | 0;\n Eh = T224_IV[8] | 0;\n El = T224_IV[9] | 0;\n Fh = T224_IV[10] | 0;\n Fl = T224_IV[11] | 0;\n Gh = T224_IV[12] | 0;\n Gl = T224_IV[13] | 0;\n Hh = T224_IV[14] | 0;\n Hl = T224_IV[15] | 0;\n constructor() {\n super(28);\n }\n}\n/** Internal SHA-512/256 hash class using the derived `T256_IV` and the shared\n * RFC 6234 §6.4 compression engine. */\nexport class _SHA512_256 extends SHA2_64B {\n Ah = T256_IV[0] | 0;\n Al = T256_IV[1] | 0;\n Bh = T256_IV[2] | 0;\n Bl = T256_IV[3] | 0;\n Ch = T256_IV[4] | 0;\n Cl = T256_IV[5] | 0;\n Dh = T256_IV[6] | 0;\n Dl = T256_IV[7] | 0;\n Eh = T256_IV[8] | 0;\n El = T256_IV[9] | 0;\n Fh = T256_IV[10] | 0;\n Fl = T256_IV[11] | 0;\n Gh = T256_IV[12] | 0;\n Gl = T256_IV[13] | 0;\n Hh = T256_IV[14] | 0;\n Hl = T256_IV[15] | 0;\n constructor() {\n super(32);\n }\n}\n/**\n * SHA2-256 hash function from RFC 4634. In JS it's the fastest: even faster than Blake3. Some info:\n *\n * - Trying 2^128 hashes would get 50% chance of collision, using birthday attack.\n * - BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.\n * - Each sha256 hash is executing 2^18 bit operations.\n * - Good 2024 ASICs can do 200Th/sec with 3500 watts of power, corresponding to 2^36 hashes/joule.\n * @param msg - message bytes to hash\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-256.\n * ```ts\n * sha256(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha256 = /* @__PURE__ */ createHasher(() => new _SHA256(), \n/* @__PURE__ */ oidNist(0x01));\n/**\n * SHA2-224 hash function from RFC 4634.\n * @param msg - message bytes to hash\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-224.\n * ```ts\n * sha224(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha224 = /* @__PURE__ */ createHasher(() => new _SHA224(), \n/* @__PURE__ */ oidNist(0x04));\n/**\n * SHA2-512 hash function from RFC 4634.\n * @param msg - message bytes to hash\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-512.\n * ```ts\n * sha512(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha512 = /* @__PURE__ */ createHasher(() => new _SHA512(), \n/* @__PURE__ */ oidNist(0x03));\n/**\n * SHA2-384 hash function from RFC 4634.\n * @param msg - message bytes to hash\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-384.\n * ```ts\n * sha384(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha384 = /* @__PURE__ */ createHasher(() => new _SHA384(), \n/* @__PURE__ */ oidNist(0x02));\n/**\n * SHA2-512/256 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on {@link https://eprint.iacr.org/2010/548.pdf | truncated SHA512}.\n * @param msg - message bytes to hash\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-512/256.\n * ```ts\n * sha512_256(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha512_256 = /* @__PURE__ */ createHasher(() => new _SHA512_256(), \n/* @__PURE__ */ oidNist(0x06));\n/**\n * SHA2-512/224 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on {@link https://eprint.iacr.org/2010/548.pdf | truncated SHA512}.\n * @param msg - message bytes to hash\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-512/224.\n * ```ts\n * sha512_224(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha512_224 = /* @__PURE__ */ createHasher(() => new _SHA512_224(), \n/* @__PURE__ */ oidNist(0x05));\n//# sourceMappingURL=sha2.js.map","/**\n * Ed25519 key generation, persistence, and challenge signing for the Resend bridge.\n * Same shape as @abraca/mcp's crypto module; intentionally vendored so this package\n * doesn't depend on @abraca/mcp.\n */\nimport * as ed from \"@noble/ed25519\";\nimport { sha512 } from \"@noble/hashes/sha2.js\";\nimport { existsSync } from \"node:fs\";\nimport { mkdir, readFile, writeFile } from \"node:fs/promises\";\nimport { homedir } from \"node:os\";\nimport { dirname, join } from \"node:path\";\n\ned.hashes.sha512 = sha512;\ned.hashes.sha512Async = (m: Uint8Array) => Promise.resolve(sha512(m));\n\nconst DEFAULT_KEY_PATH = join(homedir(), \".abracadabra\", \"resend.key\");\n\nfunction toBase64url(bytes: Uint8Array): string {\n\treturn Buffer.from(bytes).toString(\"base64url\");\n}\n\nfunction fromBase64url(b64: string): Uint8Array {\n\treturn new Uint8Array(Buffer.from(b64, \"base64url\"));\n}\n\nexport interface AgentKeypair {\n\tprivateKey: Uint8Array;\n\tpublicKeyB64: string;\n}\n\nexport async function loadOrCreateKeypair(\n\tkeyPath?: string,\n): Promise<AgentKeypair> {\n\tconst path = keyPath || DEFAULT_KEY_PATH;\n\n\tif (existsSync(path)) {\n\t\tconst seed = await readFile(path);\n\t\tif (seed.length !== 32) {\n\t\t\tthrow new Error(\n\t\t\t\t`Invalid key file at ${path}: expected 32 bytes, got ${seed.length}`,\n\t\t\t);\n\t\t}\n\t\tconst privateKey = new Uint8Array(seed);\n\t\tconst publicKey = ed.getPublicKey(privateKey);\n\t\treturn { privateKey, publicKeyB64: toBase64url(publicKey) };\n\t}\n\n\tconst privateKey = ed.utils.randomSecretKey();\n\tconst publicKey = ed.getPublicKey(privateKey);\n\n\tconst dir = dirname(path);\n\tif (!existsSync(dir)) {\n\t\tawait mkdir(dir, { recursive: true, mode: 0o700 });\n\t}\n\tawait writeFile(path, Buffer.from(privateKey), { mode: 0o600 });\n\n\tconsole.error(`[abracadabra-resend] Generated new agent keypair at ${path}`);\n\tconsole.error(\n\t\t`[abracadabra-resend] Public key: ${toBase64url(publicKey)}`,\n\t);\n\n\treturn { privateKey, publicKeyB64: toBase64url(publicKey) };\n}\n\nexport function signChallenge(\n\tchallengeB64: string,\n\tprivateKey: Uint8Array,\n): string {\n\tconst challenge = fromBase64url(challengeB64);\n\tconst sig = ed.sign(challenge, privateKey);\n\treturn toBase64url(sig);\n}\n","/**\n * AbracadabraResendServer — connection lifecycle for the Resend bridge.\n *\n * Trimmed-down equivalent of @abraca/mcp's server: Ed25519 identity, login/\n * register, single-space binding, child-provider cache with idle eviction,\n * `ensureConnected` heal on dropped sockets / expired JWTs. No awareness,\n * no chat, no tool wiring — this is a daemon, not an agent.\n */\nimport type { DocumentMeta, ServerInfo } from \"@abraca/dabra\";\nimport {\n\tAbracadabraClient,\n\tAbracadabraProvider,\n\tKind,\n\tSERVER_ROOT_ID,\n\tWebSocketStatus,\n} from \"@abraca/dabra\";\nimport * as Y from \"yjs\";\nimport { loadOrCreateKeypair, signChallenge } from \"./crypto.ts\";\nimport { waitForSync } from \"./utils.ts\";\n\nexport interface ResendServerConfig {\n\turl: string;\n\tagentName?: string;\n\tkeyFile?: string;\n\tinviteCode?: string;\n\t/** Bind to this space id. When omitted, the first visible space is used. */\n\tspaceId?: string;\n}\n\ninterface SpaceConnection {\n\tdoc: Y.Doc;\n\tprovider: AbracadabraProvider;\n\tdocId: string;\n}\n\ninterface CachedProvider {\n\tprovider: AbracadabraProvider;\n\tlastAccessed: number;\n}\n\nconst IDLE_TIMEOUT_MS = 5 * 60 * 1000;\n\nexport class AbracadabraResendServer {\n\treadonly config: ResendServerConfig;\n\treadonly client: AbracadabraClient;\n\tprivate _serverInfo: ServerInfo | null = null;\n\tprivate _spaces: DocumentMeta[] = [];\n\tprivate _connection: SpaceConnection | null = null;\n\tprivate childCache = new Map<string, CachedProvider>();\n\tprivate evictionTimer: ReturnType<typeof setInterval> | null = null;\n\tprivate heartbeatTimer: ReturnType<typeof setInterval> | null = null;\n\tprivate _userId: string | null = null;\n\tprivate _signFn: ((challenge: string) => Promise<string>) | null = null;\n\tprivate _reconnecting: Promise<void> | null = null;\n\n\tconstructor(config: ResendServerConfig) {\n\t\tthis.config = config;\n\t\tthis.client = new AbracadabraClient({\n\t\t\turl: config.url,\n\t\t\tpersistAuth: false,\n\t\t});\n\t}\n\n\tget agentName(): string {\n\t\treturn this.config.agentName || \"Resend Bridge\";\n\t}\n\n\tget serverInfo(): ServerInfo | null {\n\t\treturn this._serverInfo;\n\t}\n\n\tget spaceDocId(): string | null {\n\t\treturn this._connection?.docId ?? null;\n\t}\n\n\tget rootDocument(): Y.Doc | null {\n\t\treturn this._connection?.doc ?? null;\n\t}\n\n\tget rootProvider(): AbracadabraProvider | null {\n\t\treturn this._connection?.provider ?? null;\n\t}\n\n\tget userId(): string | null {\n\t\treturn this._userId;\n\t}\n\n\tget spaces(): DocumentMeta[] {\n\t\treturn this._spaces;\n\t}\n\n\t/** Authenticate, discover spaces, connect to the configured (or first) space. */\n\tasync connect(): Promise<void> {\n\t\tconst keypair = await loadOrCreateKeypair(this.config.keyFile);\n\t\tthis._userId = keypair.publicKeyB64;\n\t\tconst signFn = (challenge: string) =>\n\t\t\tPromise.resolve(signChallenge(challenge, keypair.privateKey));\n\t\tthis._signFn = signFn;\n\n\t\ttry {\n\t\t\tawait this.client.loginWithKey(keypair.publicKeyB64, signFn);\n\t\t} catch (err: any) {\n\t\t\tconst status = err?.status ?? err?.response?.status;\n\t\t\tconst msg = String(err?.message ?? \"\").toLowerCase();\n\t\t\tconst notRegistered =\n\t\t\t\tstatus === 404 ||\n\t\t\t\tstatus === 422 ||\n\t\t\t\t(status === 401 &&\n\t\t\t\t\t/not registered|user not found|no such user/.test(msg));\n\t\t\tif (!notRegistered) throw err;\n\t\t\tconsole.error(\n\t\t\t\t\"[abracadabra-resend] Key not registered, creating new account...\",\n\t\t\t);\n\t\t\tawait this.client.registerWithKey({\n\t\t\t\tpublicKey: keypair.publicKeyB64,\n\t\t\t\tusername: this.agentName.replace(/\\s+/g, \"-\").toLowerCase(),\n\t\t\t\tdisplayName: this.agentName,\n\t\t\t\tdeviceName: \"Resend Bridge\",\n\t\t\t\tinviteCode: this.config.inviteCode,\n\t\t\t});\n\t\t\tawait this.client.loginWithKey(keypair.publicKeyB64, signFn);\n\t\t}\n\t\tconsole.error(\n\t\t\t`[abracadabra-resend] Authenticated as ${this.agentName} (pubkey=${keypair.publicKeyB64})`,\n\t\t);\n\n\t\tthis._serverInfo = await this.client.serverInfo();\n\n\t\tconst roots = await this.client.listChildren();\n\t\tthis._spaces = roots.filter((d) => d.kind === Kind.Space);\n\n\t\tlet targetId = this.config.spaceId;\n\t\tif (targetId) {\n\t\t\tconst found =\n\t\t\t\tthis._spaces.find((s) => s.id === targetId) ??\n\t\t\t\troots.find((d) => d.id === targetId);\n\t\t\tif (!found) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Configured ABRA_SPACE_ID=${targetId} not found among server roots`,\n\t\t\t\t);\n\t\t\t}\n\t\t} else {\n\t\t\ttargetId = this._spaces[0]?.id ?? roots[0]?.id;\n\t\t\tif (!targetId) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`No entry point found: server has no top-level documents under ${SERVER_ROOT_ID}.`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\tconsole.error(`[abracadabra-resend] Binding to space ${targetId}`);\n\t\tawait this._connectToSpace(targetId);\n\t\tconsole.error(\"[abracadabra-resend] Space doc synced\");\n\n\t\tthis.evictionTimer = setInterval(() => this.evictIdle(), 60_000);\n\n\t\t// Connection heartbeat. The bridge is a long-running daemon that can sit\n\t\t// idle for hours; its JWT will expire and the socket can drop with no\n\t\t// dispatch to trigger a heal. `ensureConnected` is a no-op while healthy\n\t\t// (just refreshes the token if it's near expiry), and revives the socket\n\t\t// on the SAME doc — keeping the outbox watcher's observers alive — if it\n\t\t// died. This is what makes \"once connected, STAY connected\" true when idle.\n\t\tthis.heartbeatTimer = setInterval(() => {\n\t\t\tvoid this.ensureConnected();\n\t\t}, 30_000);\n\t}\n\n\tprivate async _connectToSpace(docId: string): Promise<SpaceConnection> {\n\t\tif (!this.client.isTokenValid() && this._signFn && this._userId) {\n\t\t\tconsole.error(\"[abracadabra-resend] JWT expired, re-authenticating...\");\n\t\t\tawait this.client.loginWithKey(this._userId, this._signFn);\n\t\t}\n\n\t\tconst doc = new Y.Doc({ guid: docId });\n\t\tconst provider = new AbracadabraProvider({\n\t\t\tname: docId,\n\t\t\tdocument: doc,\n\t\t\tclient: this.client,\n\t\t\tdisableOfflineStore: true,\n\t\t\tsubdocLoading: \"lazy\",\n\t\t});\n\n\t\tawait waitForSync(provider);\n\n\t\tprovider.awareness?.setLocalStateField(\"user\", {\n\t\t\tname: this.agentName,\n\t\t\tcolor: \"hsl(170, 70%, 45%)\",\n\t\t\tpublicKey: this._userId,\n\t\t\tisAgent: true,\n\t\t});\n\n\t\tconst conn: SpaceConnection = { doc, provider, docId };\n\t\tthis._connection = conn;\n\t\treturn conn;\n\t}\n\n\tprivate _wsConnected(provider: AbracadabraProvider): boolean {\n\t\treturn provider.connectionStatus === WebSocketStatus.Connected;\n\t}\n\n\t/**\n\t * Heal a dropped socket / expired JWT before tool ops. De-duped across\n\t * concurrent callers; best-effort (never throws — a failed heal falls\n\t * through to the caller's normal error handling).\n\t */\n\tasync ensureConnected(): Promise<void> {\n\t\tif (this._reconnecting) return this._reconnecting;\n\t\tthis._reconnecting = (async () => {\n\t\t\ttry {\n\t\t\t\tif (!this.client.isTokenValid() && this._signFn && this._userId) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait this.client.loginWithKey(this._userId, this._signFn);\n\t\t\t\t\t} catch (e) {\n\t\t\t\t\t\tconsole.error(\"[abracadabra-resend] Re-auth during heal failed:\", e);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tconst conn = this._connection;\n\t\t\t\tif (!conn) return;\n\t\t\t\tif (this._wsConnected(conn.provider)) return;\n\n\t\t\t\t// Give the SDK's own auto-reconnect a bounded window before forcing\n\t\t\t\t// one ourselves.\n\t\t\t\ttry {\n\t\t\t\t\tawait waitForSync(conn.provider, 6000);\n\t\t\t\t} catch {\n\t\t\t\t\t/* fall through to forced reconnect */\n\t\t\t\t}\n\t\t\t\tif (this._wsConnected(conn.provider)) return;\n\n\t\t\t\t// Still dead → force a reconnect on the SAME Y.Doc. Critically we do\n\t\t\t\t// NOT destroy + recreate the provider: the outbox watcher's\n\t\t\t\t// observeDeep / afterTransaction listeners are attached to THIS doc,\n\t\t\t\t// and swapping the doc out from under them is exactly what made the\n\t\t\t\t// bridge go silent (\"works until it doesn't\") after a drop. The doc\n\t\t\t\t// survives, observers keep firing, and step 1's token refresh lets\n\t\t\t\t// the recycled socket re-authenticate cleanly. Cached child providers\n\t\t\t\t// multiplex this same socket and re-sync on reopen, so we keep them.\n\t\t\t\tconsole.error(\n\t\t\t\t\t\"[abracadabra-resend] Socket dead — forcing reconnect on the same doc…\",\n\t\t\t\t);\n\t\t\t\tconn.provider.reconnect();\n\t\t\t\ttry {\n\t\t\t\t\tawait waitForSync(conn.provider, 10000);\n\t\t\t\t\tconsole.error(\"[abracadabra-resend] Reconnected + re-synced\");\n\t\t\t\t} catch (e) {\n\t\t\t\t\tconsole.error(\n\t\t\t\t\t\t\"[abracadabra-resend] Reconnect did not re-sync in time:\",\n\t\t\t\t\t\te,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t} finally {\n\t\t\t\tthis._reconnecting = null;\n\t\t\t}\n\t\t})();\n\t\treturn this._reconnecting;\n\t}\n\n\tgetTreeMap(): Y.Map<any> | null {\n\t\treturn this._connection?.doc.getMap(\"doc-tree\") ?? null;\n\t}\n\n\tasync getChildProvider(docId: string): Promise<AbracadabraProvider> {\n\t\tawait this.ensureConnected();\n\n\t\tconst cached = this.childCache.get(docId);\n\t\tif (\n\t\t\tcached &&\n\t\t\tcached.provider.connectionStatus !== WebSocketStatus.Disconnected\n\t\t) {\n\t\t\tcached.lastAccessed = Date.now();\n\t\t\treturn cached.provider;\n\t\t}\n\t\tif (cached) {\n\t\t\ttry {\n\t\t\t\tcached.provider.destroy();\n\t\t\t} catch {\n\t\t\t\t/* already gone */\n\t\t\t}\n\t\t\tthis.childCache.delete(docId);\n\t\t}\n\n\t\tconst root = this._connection?.provider;\n\t\tif (!root) throw new Error(\"Not connected. Call connect() first.\");\n\n\t\tif (!this.client.isTokenValid() && this._signFn && this._userId) {\n\t\t\tawait this.client.loginWithKey(this._userId, this._signFn);\n\t\t}\n\n\t\tconst childProvider = await root.loadChild(docId);\n\t\tawait waitForSync(childProvider);\n\n\t\tthis.childCache.set(docId, {\n\t\t\tprovider: childProvider,\n\t\t\tlastAccessed: Date.now(),\n\t\t});\n\n\t\treturn childProvider;\n\t}\n\n\tprivate evictIdle(): void {\n\t\tconst now = Date.now();\n\t\tfor (const [docId, cached] of this.childCache) {\n\t\t\tif (now - cached.lastAccessed > IDLE_TIMEOUT_MS) {\n\t\t\t\tcached.provider.destroy();\n\t\t\t\tthis.childCache.delete(docId);\n\t\t\t\tconsole.error(`[abracadabra-resend] Evicted idle provider: ${docId}`);\n\t\t\t}\n\t\t}\n\t}\n\n\tasync destroy(): Promise<void> {\n\t\tif (this.evictionTimer) {\n\t\t\tclearInterval(this.evictionTimer);\n\t\t\tthis.evictionTimer = null;\n\t\t}\n\t\tif (this.heartbeatTimer) {\n\t\t\tclearInterval(this.heartbeatTimer);\n\t\t\tthis.heartbeatTimer = null;\n\t\t}\n\t\tfor (const [, cached] of this.childCache) {\n\t\t\ttry {\n\t\t\t\tcached.provider.destroy();\n\t\t\t} catch {\n\t\t\t\t/* already gone */\n\t\t\t}\n\t\t}\n\t\tthis.childCache.clear();\n\t\tif (this._connection) {\n\t\t\ttry {\n\t\t\t\tthis._connection.provider.destroy();\n\t\t\t} catch {\n\t\t\t\t/* already gone */\n\t\t\t}\n\t\t\tthis._connection = null;\n\t\t}\n\t\tconsole.error(\"[abracadabra-resend] Shutdown complete\");\n\t}\n}\n","#!/usr/bin/env node\n/**\n * @abraca/resend — entry point.\n *\n * Environment variables:\n * ABRA_URL (required) — Abracadabra server URL\n * ABRA_SPACE_ID — Pin to a specific space (default: first visible)\n * ABRA_KEY_FILE — Ed25519 seed path (default ~/.abracadabra/resend.key)\n * ABRA_INVITE_CODE — Used only on first-run register\n * ABRA_AGENT_NAME — Display name (default \"Resend Bridge\")\n *\n * RESEND_API_KEY (required) — Resend API key\n * RESEND_FROM (required) — Default `from` address\n * RESEND_INBOUND_ENABLED — \"false\" to skip the webhook server (default true)\n * RESEND_INBOUND_PORT — Bind port for /inbound (default 0 = ephemeral)\n * RESEND_INBOUND_HOST — Bind host (default 0.0.0.0)\n * RESEND_INBOUND_SECRET — Required when inbound is enabled (Svix signing secret)\n */\nimport { bootstrap } from \"./bootstrap.ts\";\nimport { InboundServer } from \"./inbound-server.ts\";\nimport { OutboxWatcher } from \"./outbox-watcher.ts\";\nimport { ResendClient } from \"./resend-client.ts\";\nimport { AbracadabraResendServer } from \"./server.ts\";\n\nfunction required(name: string): string {\n\tconst value = process.env[name];\n\tif (!value || value.trim().length === 0) {\n\t\tconsole.error(`[abracadabra-resend] Missing required env var: ${name}`);\n\t\tprocess.exit(1);\n\t}\n\treturn value;\n}\n\nfunction boolEnv(name: string, fallback: boolean): boolean {\n\tconst v = process.env[name];\n\tif (v === undefined) return fallback;\n\tconst norm = v.trim().toLowerCase();\n\tif ([\"0\", \"false\", \"no\", \"off\", \"\"].includes(norm)) return false;\n\treturn true;\n}\n\nasync function main(): Promise<void> {\n\tconst url = required(\"ABRA_URL\");\n\tconst resendApiKey = required(\"RESEND_API_KEY\");\n\tconst defaultFrom = required(\"RESEND_FROM\");\n\n\tconst inboundEnabled = boolEnv(\"RESEND_INBOUND_ENABLED\", true);\n\tconst inboundSecret = inboundEnabled\n\t\t? required(\"RESEND_INBOUND_SECRET\")\n\t\t: process.env.RESEND_INBOUND_SECRET ?? \"\";\n\tconst inboundPort = process.env.RESEND_INBOUND_PORT\n\t\t? Number(process.env.RESEND_INBOUND_PORT)\n\t\t: 0;\n\tconst inboundHost = process.env.RESEND_INBOUND_HOST ?? \"0.0.0.0\";\n\n\tconst server = new AbracadabraResendServer({\n\t\turl,\n\t\tspaceId: process.env.ABRA_SPACE_ID,\n\t\tkeyFile: process.env.ABRA_KEY_FILE,\n\t\tinviteCode: process.env.ABRA_INVITE_CODE,\n\t\tagentName: process.env.ABRA_AGENT_NAME,\n\t});\n\n\ttry {\n\t\tawait server.connect();\n\t} catch (err: any) {\n\t\tconsole.error(`[abracadabra-resend] Failed to connect: ${err?.message ?? err}`);\n\t\tprocess.exit(1);\n\t}\n\n\tconst boot = await bootstrap(server);\n\tconsole.error(\n\t\t`[abracadabra-resend] Bootstrapped Inbox=${boot.inboxId} Outbox=${boot.outboxId}`,\n\t);\n\n\tconst sender = new ResendClient(resendApiKey);\n\tconst watcher = new OutboxWatcher({ server, sender, bootstrap: boot, defaultFrom });\n\twatcher.start();\n\n\tlet inbound: InboundServer | null = null;\n\tif (inboundEnabled) {\n\t\tinbound = new InboundServer({\n\t\t\tserver,\n\t\t\tbootstrap: boot,\n\t\t\tsecret: inboundSecret,\n\t\t\tport: Number.isFinite(inboundPort) ? inboundPort : 0,\n\t\t\thost: inboundHost,\n\t\t});\n\t\ttry {\n\t\t\tawait inbound.start();\n\t\t} catch (err: any) {\n\t\t\tconsole.error(\n\t\t\t\t`[abracadabra-resend] Inbound server failed to start: ${err?.message ?? err}`,\n\t\t\t);\n\t\t\tprocess.exit(1);\n\t\t}\n\t} else {\n\t\tconsole.error(\n\t\t\t\"[abracadabra-resend] Inbound disabled (RESEND_INBOUND_ENABLED=false)\",\n\t\t);\n\t}\n\n\tconsole.error(\"[abracadabra-resend] Ready.\");\n\n\tconst shutdown = async () => {\n\t\tconsole.error(\"[abracadabra-resend] Shutting down...\");\n\t\twatcher.stop();\n\t\tif (inbound) await inbound.stop();\n\t\tawait server.destroy();\n\t\tprocess.exit(0);\n\t};\n\tprocess.on(\"SIGINT\", shutdown);\n\tprocess.on(\"SIGTERM\", shutdown);\n}\n\nmain().catch((err) => {\n\tconsole.error(\"[abracadabra-resend] Fatal error:\", err);\n\tprocess.exit(1);\n});\n\nexport { AbracadabraResendServer } from \"./server.ts\";\nexport { bootstrap } from \"./bootstrap.ts\";\nexport { InboundServer } from \"./inbound-server.ts\";\nexport { OutboxWatcher } from \"./outbox-watcher.ts\";\nexport { ResendClient } from \"./resend-client.ts\";\nexport type { ResendSender, SendResult } from \"./resend-client.ts\";\nexport { renderEmail, RenderError } from \"./render.ts\";\nexport type { EmailPayload } from \"./render.ts\";\n"],"x_google_ignoreList":[6,7,8,9],"mappings":";;;;;;;;;;;;;;;;;;;;;AAWA,MAAa,cAAc;AAC3B,MAAa,eAAe;AAE5B,MAAa,iBAAiB;CA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