@powerhousedao/clint 6.4.0-next.0 → 6.4.0-next.2
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/{build-skills-BNEOn-cl.mjs → build-skills-Bpbbnin0.mjs} +2 -2
- package/dist/{build-skills-BNEOn-cl.mjs.map → build-skills-Bpbbnin0.mjs.map} +1 -1
- package/dist/{dist--xzirmg-.mjs → dist-Bd6hUl0J.mjs} +2 -2
- package/dist/{dist--xzirmg-.mjs.map → dist-Bd6hUl0J.mjs.map} +1 -1
- package/dist/{index-C3-HSfKb.d.mts → index-CfHcet4v.d.mts} +2 -2
- package/dist/{index-C3-HSfKb.d.mts.map → index-CfHcet4v.d.mts.map} +1 -1
- package/dist/index.d.mts +33 -3
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +3 -3
- package/dist/integrations/mastra/index.d.mts +1 -1
- package/dist/integrations/mastra/index.mjs.map +1 -1
- package/dist/integrations/powerhouse/index.d.mts +2 -2
- package/dist/integrations/powerhouse/index.mjs +2 -2
- package/dist/{powerhouse-BDnj7kqd.mjs → powerhouse-3XZmdY3_.mjs} +4 -4
- package/dist/{powerhouse-BDnj7kqd.mjs.map → powerhouse-3XZmdY3_.mjs.map} +1 -1
- package/dist/{remote-reactor-BQzq4yfO.mjs → remote-reactor-oBsHphPT.mjs} +2 -2
- package/dist/{remote-reactor-BQzq4yfO.mjs.map → remote-reactor-oBsHphPT.mjs.map} +1 -1
- package/dist/runners/cli-runner.d.mts +5 -1
- package/dist/runners/cli-runner.d.mts.map +1 -1
- package/dist/runners/cli-runner.mjs +24 -10
- package/dist/runners/cli-runner.mjs.map +1 -1
- package/dist/runners/mastra-runner.mjs +2 -2
- package/dist/{src-BehwgLP6.mjs → src-BmMd0Wl4.mjs} +161 -23
- package/dist/src-BmMd0Wl4.mjs.map +1 -0
- package/dist/testing/index.d.mts +2 -2
- package/dist/{types-CbHJ-ZnH.d.mts → types-3TnDjQ1w.d.mts} +2 -2
- package/dist/{types-CbHJ-ZnH.d.mts.map → types-3TnDjQ1w.d.mts.map} +1 -1
- package/dist/{types-CF6GuPJd.d.mts → types-DbQKfvWc.d.mts} +20 -1
- package/dist/types-DbQKfvWc.d.mts.map +1 -0
- package/package.json +13 -13
- package/dist/src-BehwgLP6.mjs.map +0 -1
- package/dist/types-CF6GuPJd.d.mts.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"powerhouse-BDnj7kqd.mjs","names":["isAttachmentAlreadyExists"],"sources":["../src/core/command.ts","../src/integrations/powerhouse/change-trigger.ts","../src/integrations/powerhouse/registry.ts","../src/integrations/powerhouse/subscriptions.ts","../src/integrations/powerhouse/drive.ts","../src/integrations/powerhouse/signing.ts","../src/integrations/powerhouse/writes.ts","../src/integrations/powerhouse/type-guard.ts","../src/integrations/powerhouse/folders.ts","../../reactor-attachments/dist/switchboard-attachment-transport-BH3ZAmxE.js","../../../node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/utils.js","../../../node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/_md.js","../../../node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/sha2.js","../../reactor-attachments/dist/hash-BobbR4r4.js","../../reactor-attachments/dist/client.js","../src/integrations/powerhouse/attachment.ts","../src/integrations/powerhouse/attachment-commands.ts","../src/integrations/powerhouse/index.ts"],"sourcesContent":["import type { z } from \"zod\";\nimport type { DocumentRegistry } from \"../integrations/powerhouse/types.js\";\nimport { getSchemaFields } from \"./schema.js\";\nimport type { Command } from \"./types.js\";\n\n/**\n * Define a command — the atomic unit of ph-clint.\n * Compatible with Mastra createTool() shape.\n */\nexport function defineCommand<\n TInput extends z.ZodType,\n TOutput = unknown,\n TConfig = Record<string, unknown>,\n R extends DocumentRegistry = any,\n>(\n options: Command<TInput, TOutput, TConfig, R>,\n): Command<TInput, TOutput, TConfig, R> {\n if (options.positional && options.positional.length > 0) {\n const fields = getSchemaFields(options.inputSchema);\n const fieldMap = new Map(fields.map((f) => [f.key, f]));\n const seen = new Set<string>();\n let sawOptional = false;\n for (const key of options.positional) {\n const field = fieldMap.get(key);\n if (!field) {\n throw new Error(\n `Command '${options.id}': positional field '${key}' is not in inputSchema`,\n );\n }\n if (seen.has(key)) {\n throw new Error(\n `Command '${options.id}': positional field '${key}' listed more than once`,\n );\n }\n seen.add(key);\n const isOptional = field.isOptional || field.hasDefault;\n if (sawOptional && !isOptional) {\n throw new Error(\n `Command '${options.id}': required positional '${key}' may not follow an optional positional`,\n );\n }\n if (isOptional) sawOptional = true;\n }\n }\n return options;\n}\n","/**\n * `createDocumentChangeTrigger` — typed helper that collapses the common\n * \"subscribe to document changes, coalesce, load docs, narrow, call onChange\"\n * pattern into a single definition.\n *\n * Supports watching one or multiple document types. When `documentId` is\n * provided, loads a single document (wrapped in an array). When omitted,\n * loads all matching documents via `client.find()`.\n *\n * The helper owns subscription setup, per-event filtering by documentType\n * (and optional literal documentId), the pending counter, initial\n * reconcile, document loading, and registry-driven type narrowing. Impl\n * code only writes the `onChange` handler (plus an optional `filter` and\n * an optional `documentId` resolver for impl-specific lookup).\n */\nimport type { DocumentRegistry, AnyRegistry } from \"./types.js\";\nimport type { Trigger, TriggerContext, WorkItem } from \"../../core/types.js\";\n\nexport interface DocumentChangeTriggerOptions<\n R extends DocumentRegistry,\n T extends keyof R & string,\n TConfig = Record<string, unknown>,\n TState extends { pending: number } = { pending: number },\n> {\n /** Unique trigger id for logging/routing. */\n id: string;\n\n /** The document type(s) to watch. Must be key(s) in the registry. */\n documentType: T | T[];\n\n /**\n * The specific document id (or a function that resolves one from context).\n * When omitted, the helper loads ALL documents of the watched type(s)\n * via `client.find()` and passes the full array to `onChange`.\n *\n * When a function is provided, it's resolved lazily on each poll. Returning\n * `undefined` skips the tick.\n */\n documentId?:\n | string\n | ((\n ctx: TriggerContext<TState, TConfig, R>,\n ) => Promise<string | undefined>);\n\n /**\n * Fire once on startup before any event arrives — useful for reconciling\n * against the current document state. Default: true.\n */\n initialReconcile?: boolean;\n\n /**\n * Optional predicate: called per-document after loading, before onChange.\n * Return false to exclude a document from the batch. If all documents\n * are filtered out, onChange is not called.\n */\n filter?: (\n doc: R[T][\"document\"],\n ctx: TriggerContext<TState, TConfig, R>,\n ) => boolean | Promise<boolean>;\n\n /**\n * User's change handler. Receives an array of loaded, type-narrowed\n * documents and the full trigger context. Returns a work item for the\n * routine loop to execute (or null to skip).\n */\n onChange: (\n docs: Array<R[T][\"document\"]>,\n ctx: TriggerContext<TState, TConfig, R>,\n ) => Promise<WorkItem | null>;\n\n /**\n * Call `onChange` even when zero documents are found. Default: false.\n * Useful for triggers that need to perform work (e.g. bootstrapping from\n * disk) regardless of whether any documents exist yet.\n */\n callOnEmpty?: boolean;\n\n /**\n * Optional initial state for the trigger's private slot. Defaults to\n * `{ pending: 0 }`. When supplied, the shape MUST include a `pending:\n * number` field — the helper bumps and drains it internally.\n */\n state?: () => TState;\n}\n\n/**\n * Build a Trigger that listens for document change events on the event bus,\n * coalesces them, loads matching documents, narrows to the registered type,\n * and hands them to the user's onChange handler.\n *\n * Runtime behavior:\n * 1. `setup()` subscribes to `powerhouse:document:changed`. For each event,\n * if any documentType matches (and, when `documentId` is a literal\n * string, the id also matches), bump the pending counter.\n * 2. If `initialReconcile !== false`, `setup()` bumps pending once on\n * startup so the first poll reconciles without waiting for an event.\n * 3. `poll()` returns null unless pending > 0. When pending > 0:\n * - If `documentId` is set: load single doc, wrap in `[doc]`\n * - If `documentId` is omitted: `find()` all docs of matching type(s)\n * Applies `filter` per-doc, then calls `onChange(docs, ctx)`.\n * 4. pending is reset to 0 at the start of each poll drain — multiple\n * events within a tick coalesce to one `onChange` call.\n */\nexport function createDocumentChangeTrigger<\n R extends DocumentRegistry = AnyRegistry,\n T extends keyof R & string = keyof R & string,\n TConfig = Record<string, unknown>,\n TState extends { pending: number } = { pending: number },\n>(\n options: DocumentChangeTriggerOptions<R, T, TConfig, TState>,\n): Trigger<TState, TConfig, R> {\n const initialReconcile = options.initialReconcile !== false;\n const types: T[] = Array.isArray(options.documentType)\n ? options.documentType\n : [options.documentType];\n\n return {\n id: options.id,\n type: \"condition\",\n state: options.state ?? (() => ({ pending: 0 }) as TState),\n\n async setup(ctx) {\n const log = ctx.context.log;\n const on = ctx.context.on;\n if (!on) {\n log?.debug(\n `[${options.id}] no event bus on CoreContext — poll-only mode`,\n );\n if (initialReconcile) ctx.state.pending = 1;\n return;\n }\n\n on(\"powerhouse:document:changed\", (payload) => {\n const documents = payload.documents ?? [];\n const matches = documents.some((d) =>\n types.includes(d.header?.documentType as T),\n );\n if (!matches) return;\n\n if (typeof options.documentId === \"string\") {\n const ids = documents.map((d) => d.header?.id);\n if (!ids.includes(options.documentId)) return;\n }\n\n ctx.state.pending += 1;\n log?.debug(\n `[${options.id}] queued change (pending=${ctx.state.pending})`,\n );\n });\n\n // Writes became possible (the agent's signer got its user): look at\n // every matching document again, since one skipped earlier for want of\n // a signature may be waiting.\n on(\"powerhouse:writes:ready\", () => {\n ctx.state.pending += 1;\n });\n\n if (initialReconcile) ctx.state.pending = 1;\n },\n\n async poll(ctx): Promise<WorkItem | null> {\n if (!ctx.state.pending) return null;\n ctx.state.pending = 0;\n\n const reactor = await ctx.reactor();\n if (!reactor) {\n ctx.context.log?.debug(\n `[${options.id}] no reactor available, skipping`,\n );\n return null;\n }\n\n let docs: Array<R[T][\"document\"]>;\n\n if (options.documentId) {\n // Single-doc path\n const docId =\n typeof options.documentId === \"function\"\n ? await options.documentId(ctx)\n : options.documentId;\n if (!docId) {\n ctx.context.log?.debug(\n `[${options.id}] no target document id resolved, skipping`,\n );\n return null;\n }\n const doc = await reactor.client.get<T>(docId);\n docs = [doc];\n } else {\n // Multi-doc path: find all matching documents.\n // The native Reactor SearchFilter uses `type` (singular string).\n // ph-clint's TypedReactorClient remaps to `documentTypes` (plural)\n // for type-safety, but the reactor ignores that field at runtime.\n // We pass `type` directly to the underlying IReactorClient.\n const allDocs: Array<R[T][\"document\"]> = [];\n for (const t of types) {\n const result = await reactor.client.find<T>({ type: t } as Parameters<\n typeof reactor.client.find<T>\n >[0]);\n const found = result?.results ?? [];\n allDocs.push(...(found as Array<R[T][\"document\"]>));\n }\n docs = allDocs;\n if (docs.length === 0 && !options.callOnEmpty) return null;\n }\n\n if (options.filter) {\n const filtered: Array<R[T][\"document\"]> = [];\n for (const doc of docs) {\n if (await options.filter(doc, ctx)) filtered.push(doc);\n }\n if (filtered.length === 0) return null;\n docs = filtered;\n }\n\n return options.onChange(docs, ctx);\n },\n };\n}\n","/**\n * DocumentRegistry construction + inference helpers.\n *\n * Impl projects build a registry with `defineRegistry([Module1, Module2] as const)`\n * to give the framework typed access to registered document models without\n * having to pass generic parameters at every call site.\n */\n\nimport type {\n DocumentModelModule,\n PHDocument,\n Action,\n PHBaseState,\n} from \"document-model\";\nimport type { DocumentRegistry, RegistryEntry } from \"./types.js\";\n\n/**\n * Extract the action union from a DocumentModelModule.\n *\n * `DocumentModelModule.actions` is `{ [actionName]: (input) => Action }` — the\n * return types of those creators form the module's action union.\n *\n * If a module's actions map isn't typed tightly enough (because the module\n * was annotated with `: DocumentModelModule<…>` instead of `satisfies`), the\n * union collapses to `Action`. Not a correctness problem — just a DX\n * degradation for that one module's execute/executeAsync narrowing.\n */\nexport type ActionOf<M> = M extends { actions: infer Actions }\n ? Actions extends Record<string, (...args: never[]) => infer A>\n ? A\n : Action\n : Action;\n\n/**\n * Infer a DocumentRegistry from a readonly tuple of DocumentModelModule instances.\n *\n * Literal inference requires each module's `documentModel.id` to be a literal\n * type. Phase 4 changes codegen to emit modules with `as const satisfies\n * DocumentModelModule<…>` so inference produces a typed registry. Modules\n * typed with `:` annotations erase `id` to `string` and produce a\n * single-keyed `{ [x: string]: RegistryEntry<...> }` registry — narrowing\n * still works when callers pass a literal `T`, but `keyof R & string`\n * collapses to `string` (no autocomplete for documentTypes lists).\n */\nexport type InferRegistry<T extends ReadonlyArray<DocumentModelModule<any>>> = {\n [\n M in T[number] as Extract<M[\"documentModel\"][\"global\"][\"id\"], string>\n ]: M extends DocumentModelModule<infer S>\n ? RegistryEntry<S, ActionOf<M>>\n : never;\n};\n\n/**\n * Build a DocumentRegistry from a tuple of DocumentModelModules.\n *\n * ```ts\n * const registry = defineRegistry([PhClintProject, DocumentDrive] as const);\n * // typeof registry:\n * // {\n * // 'powerhouse/ph-clint-project': RegistryEntry<PhClintProjectPHState, PhClintProjectAction>;\n * // 'powerhouse/document-drive': RegistryEntry<DocumentDrivePHState, DocumentDriveAction>;\n * // }\n * ```\n *\n * Runtime value is a plain object keyed by `documentModel.id`. Consumers can\n * introspect it to list registered types; Phase 3's\n * `createDocumentChangeTrigger` also uses it for runtime lookup.\n */\nexport function defineRegistry<\n const T extends ReadonlyArray<DocumentModelModule<any>>,\n>(modules: T): InferRegistry<T> {\n const out: Record<string, DocumentModelModule<any>> = {};\n for (const mod of modules) {\n out[mod.documentModel.global.id] = mod;\n }\n return out as unknown as InferRegistry<T>;\n}\n\n// Re-export for convenience so impl code can import from a single module.\nexport type { DocumentRegistry, RegistryEntry };\nexport type { PHDocument, Action, PHBaseState };\n","/**\n * Subscription bridge — maps Reactor document change events\n * to the ph-clint event bus.\n */\n\nimport type {\n IReactorClient,\n DocumentChangeEvent,\n SearchFilter,\n} from \"@powerhousedao/reactor\";\nimport type {\n SubscriptionConfig,\n DocumentRegistry,\n AnyRegistry,\n} from \"./types.js\";\nimport type { EmitFn } from \"../../core/types.js\";\n\n/**\n * Bridge Reactor document subscriptions to the ph-clint event bus.\n *\n * @param client - The reactor client (in-process or remote)\n * @param subscriptions - Filter configuration for which document changes to bridge\n * @param emit - Event bus emit function from CommandContext\n * @returns Unsubscribe function\n */\nexport function bridgeSubscriptions<R extends DocumentRegistry = AnyRegistry>(\n client: IReactorClient,\n subscriptions: SubscriptionConfig<R>,\n emit: EmitFn<R>,\n): () => void {\n // The runtime SearchFilter in @powerhousedao/reactor doesn't have\n // `documentTypes`; ph-clint's high-level SubscriptionConfig exposes it and\n // we forward it as an extra field. The Reactor currently ignores unknown\n // keys — this matches pre-existing behavior.\n const search: SearchFilter & { documentTypes?: string[] } = {};\n if (subscriptions.documentTypes) {\n search.documentTypes = subscriptions.documentTypes as string[];\n }\n\n return client.subscribe(search, (event: DocumentChangeEvent) => {\n try {\n switch (event.type) {\n case \"created\":\n for (const doc of event.documents ?? []) {\n emit(\"powerhouse:document:created\", {\n documentId: doc.header.id,\n documentType: doc.header.documentType as keyof R & string,\n });\n }\n break;\n case \"updated\":\n emit(\"powerhouse:document:changed\", {\n changeType: \"updated\",\n documents: event.documents as Array<\n R[keyof R & string][\"document\"]\n >,\n });\n break;\n case \"deleted\":\n for (const doc of event.documents ?? []) {\n emit(\"powerhouse:document:deleted\", { documentId: doc.header.id });\n }\n break;\n }\n } catch {\n // Don't crash the event bus on subscription handler errors\n }\n });\n}\n","/**\n * Drive management — find or create drives on startup.\n */\n\nimport type { PHBaseState, PHDocument } from \"document-model\";\nimport type { DriveConfig, EnsureDriveClient } from \"./types.js\";\n\nconst DRIVE_DOCUMENT_TYPE = \"powerhouse/document-drive\" as const;\n\n/**\n * Ensure a drive exists, matching by name. On first run, creates a new drive.\n * On subsequent runs, finds the existing one by name.\n *\n * Works on a client alone, in-process or remote: drives are documents of type\n * `powerhouse/document-drive`, listed with `client.find({ type })`, built\n * with `client.newDocument()` and created, already named, with one\n * `client.write.create()`. Those three are what both the in-process\n * `IReactorClient` and `GraphQLReactorClient` (which has no\n * `write.createEmpty` or `write.rename`) offer. A Cli passes its own\n * `ReactorContext.client` as it is (see `EnsureDriveClient`).\n *\n * @param client - The reactor client the drive is looked up and created with\n * @param driveConfig - Optional drive name/icon configuration and hooks\n * @returns The drive ID and name; `deferred` (and id '') when `canCreate`\n * held back a drive that does not exist yet\n */\nexport async function ensureDrive(\n client: EnsureDriveClient,\n driveConfig?: DriveConfig,\n): Promise<{ id: string; name: string; deferred?: boolean }> {\n const driveName = driveConfig?.name ?? \"default\";\n const wantedId = driveConfig?.id;\n const preferredEditor = driveConfig?.preferredEditor;\n\n // A host-resolved id (e.g. a pointer to a drive created earlier) wins.\n const resolved = await driveConfig?.resolveId?.(client);\n if (resolved) return { id: resolved, name: driveName };\n\n const matchByName = driveConfig?.matchByName !== false;\n const existing =\n wantedId || matchByName ? await findDrives(client) : ([] as PHDocument[]);\n if (existing.length) {\n // If a deterministic ID was requested, check if it already exists\n if (wantedId) {\n const match = existing.find((doc) => doc.header.id === wantedId);\n if (match) return { id: wantedId, name: driveName };\n }\n\n // Match by name\n for (const doc of matchByName ? existing : []) {\n const named = doc as unknown as {\n name?: string;\n header?: { name?: string };\n state?: { global?: { name?: string } };\n };\n const docName =\n named.name ?? named.header?.name ?? named.state?.global?.name;\n if (docName === driveName) {\n return { id: doc.header.id, name: driveName };\n }\n }\n // No name match — if default name and single drive, use it\n if (matchByName && driveName === \"default\" && existing.length === 1) {\n return { id: existing[0].header.id, name: driveName };\n }\n }\n\n if (driveConfig?.canCreate && !driveConfig.canCreate()) {\n return { id: \"\", name: driveName, deferred: true };\n }\n\n // Create the drive in one write, named in its global state and on its\n // header, as the switchboard's default drives\n // (apps/switchboard/src/utils.mts:181-201) and Connect's addDrive\n // (packages/reactor-browser/src/actions/drive.ts:143-184) are. `name` and\n // `meta` are mutable header fields, outside the derived id and header\n // signature of a v2-required drive. Only a legacy drive can take a chosen id.\n const doc = await client.newDocument(DRIVE_DOCUMENT_TYPE, {\n initialState: { global: { name: driveName } } as Partial<PHBaseState>,\n ...(wantedId ? { signaturePolicy: \"legacy\" as const, id: wantedId } : {}),\n });\n doc.header.name = driveName;\n if (preferredEditor) {\n doc.header.meta = { ...doc.header.meta, preferredEditor };\n }\n const created = await (await client.write.create(doc)).document();\n const driveId = created.header.id;\n\n await driveConfig?.onCreated?.(driveId);\n return { id: driveId, name: driveName };\n}\n\n/** Every drive document the client serves, across result pages. */\nasync function findDrives(client: EnsureDriveClient): Promise<PHDocument[]> {\n const drives: PHDocument[] = [];\n let page = await client.find({ type: DRIVE_DOCUMENT_TYPE });\n drives.push(...page.results);\n while (page.next) {\n page = await page.next();\n drives.push(...page.results);\n }\n return drives;\n}\n","/**\n * The agent's signer and the rules for what it may write.\n *\n * Client-agnostic: nothing here calls a reactor. A host that holds an\n * identity (a signer whose `user` is set once the owner has signed in or\n * delegated to it) wraps it with `createGatedSigner`, so a write that needs a\n * signature while the signer has no user is refused with\n * `SignerNotReadyError` instead of going out unsigned. `canWrite` answers,\n * without a reactor call, whether the agent may write a document right now;\n * triggers read it through `ReactorContext.writes` (see `writes.ts`).\n */\nimport type { SignaturePolicy } from \"@powerhousedao/shared/document-model\";\n\nexport type { SignaturePolicy };\n\n/** Structural slice of document-model's `ISigner` this module touches. */\nexport interface SignerLike {\n user?: { address: string; networkId?: string; chainId?: number };\n app?: { name?: string; key: string };\n signAction: (...args: never[]) => Promise<unknown>;\n}\n\n/** A document header as far as the write rules read it. */\nexport interface DocumentHeaderLike {\n header: {\n id: string;\n documentType?: string;\n protocolVersions?: Record<string, number> | null;\n };\n}\n\n/** The agent cannot sign yet: its signer has no user. */\nexport class SignerNotReadyError extends Error {\n constructor(what = \"this write\") {\n super(`The agent cannot sign ${what} yet: it has no signed-in identity.`);\n this.name = \"SignerNotReadyError\";\n }\n}\n\n/** True when the signer can sign as a user. */\nexport function signerReady(signer: SignerLike): boolean {\n return Boolean(signer.user?.address);\n}\n\n/** The policy a header carries (same rule as document-model's `signaturePolicyOf`). */\nexport function policyOfHeader(\n header: DocumentHeaderLike[\"header\"] | undefined,\n): SignaturePolicy {\n const version = header?.protocolVersions?.signature;\n return typeof version === \"number\" && version >= 2 ? \"v2-required\" : \"legacy\";\n}\n\n/**\n * The signer, refusing to sign while it has no user. Everything else is read\n * through to the live signer.\n */\nexport function createGatedSigner<S extends SignerLike>(signer: S): S {\n return new Proxy(signer, {\n get(target, prop, receiver) {\n if (prop === \"signAction\") {\n return async (...args: never[]) => {\n if (!signerReady(target)) throw new SignerNotReadyError();\n return target.signAction(...args);\n };\n }\n const value = Reflect.get(target, prop, receiver) as unknown;\n return typeof value === \"function\"\n ? (value as (...a: unknown[]) => unknown).bind(target)\n : value;\n },\n });\n}\n\nexport interface WriteRules {\n ready(): boolean;\n /**\n * `refuse`: the agent leaves legacy documents alone.\n * `sign-when-ready`: legacy documents are writable whether or not the\n * signer has a user.\n */\n legacyDocuments: \"refuse\" | \"sign-when-ready\";\n /** Which documents the agent acts on by itself. Only read by `canWrite`. */\n accepts?: (document: DocumentHeaderLike) => boolean;\n}\n\n/** Whether the agent may write `document` right now (no reactor call). */\nexport function canWrite(\n rules: WriteRules,\n document: DocumentHeaderLike,\n): boolean {\n if (rules.accepts && !rules.accepts(document)) return false;\n if (policyOfHeader(document.header) === \"v2-required\") return rules.ready();\n return rules.legacyDocuments !== \"refuse\";\n}\n","/**\n * `ReactorContext.writes` and the `powerhouse:writes:ready` event, built once\n * for whichever factory makes the reactor: `attachDefaultReactor`, or one\n * wrapping `attachRemoteReactor` in `configureReactor.create` (it hands the\n * returned `signer` to the client).\n */\nimport type { ISigner } from \"@powerhousedao/shared/document-model\";\nimport {\n SignerNotReadyError,\n canWrite,\n createGatedSigner,\n signerReady,\n type DocumentHeaderLike,\n type WriteRules,\n} from \"./signing.js\";\nimport type { ReactorWrites } from \"./types.js\";\n\nexport interface ReactorWritesOptions {\n /**\n * The agent's signer. Read on every write, so a signer whose `user` is set\n * later (a sign-in) takes effect without rebuilding the reactor. Without\n * one there is nothing to wait for: `ready()` is always true.\n */\n signer?: ISigner;\n /** See `WriteRules.legacyDocuments`. Default: `sign-when-ready`. */\n legacyDocuments?: WriteRules[\"legacyDocuments\"];\n /**\n * Which documents the agent acts on by itself (`writes.canWrite`, read by\n * triggers such as the chat watch). Writes the agent is asked to make\n * follow only the signature rules.\n */\n accepts?: (document: DocumentHeaderLike) => boolean;\n /**\n * Subscribe to changes of the signer's user; `powerhouse:writes:ready` is\n * emitted when writes become possible. Returns an unsubscribe function.\n */\n onSignerChange?: (listener: () => void) => () => void;\n /** Where `powerhouse:writes:ready` goes: the factory's `ctx.emit`. */\n emit?: (\n event: \"powerhouse:writes:ready\",\n data: Record<string, never>,\n ) => void;\n}\n\nexport interface ReactorWritesHandle {\n /** For `ReactorContext.writes`. */\n writes: ReactorWrites;\n /**\n * The signer to give the reactor client (`attachRemoteReactor({ signer })`),\n * resolved per push: the gated signer, or `SignerNotReadyError` while it\n * has no user. The resolver throws rather than returning undefined because\n * `GraphQLReactorClient` pushes unsigned when it gets no signer, and checks\n * `user` itself before it would call the gated `signAction`. Undefined\n * without a signer.\n *\n * Limit: the client resolves its signer before it knows the document, so\n * while there is no user this refuses a push to a legacy document too,\n * though `legacyDocuments: \"sign-when-ready\"` lets `canWrite` pass it.\n * Passing the target document to the resolver would lift it; until then\n * give a signer only where the documents written are v2.\n */\n signer?: () => ISigner;\n /** Stops watching the signer; call it from `ReactorContext.shutdown`. */\n stop(): void;\n}\n\n/** See {@link ReactorWritesOptions} and {@link ReactorWritesHandle}. */\nexport function createReactorWrites(\n options: ReactorWritesOptions = {},\n): ReactorWritesHandle {\n const source = options.signer;\n const rules: WriteRules = {\n ready: () => (source ? signerReady(source) : true),\n legacyDocuments: options.legacyDocuments ?? \"sign-when-ready\",\n accepts: options.accepts,\n };\n const writes: ReactorWrites = {\n ready: rules.ready,\n canWrite: (document) => canWrite(rules, document),\n };\n\n let signer: (() => ISigner) | undefined;\n if (source) {\n const gated = createGatedSigner(source);\n signer = () => {\n if (!signerReady(source)) throw new SignerNotReadyError();\n return gated;\n };\n }\n\n let wasReady = rules.ready();\n const unsubscribe = options.onSignerChange?.(() => {\n const now = rules.ready();\n if (now && !wasReady) options.emit?.(\"powerhouse:writes:ready\", {});\n wasReady = now;\n });\n\n return {\n writes,\n signer,\n stop: () => unsubscribe?.(),\n };\n}\n","import type { DocumentRegistry } from \"./types.js\";\n\n/**\n * Type guard for discriminated narrowing in multi-type onChange handlers.\n *\n * Usage:\n * onChange(docs, ctx) {\n * for (const doc of docs) {\n * if (isDocType(doc, 'powerhouse/ph-clint-project')) {\n * // doc is narrowed to R['powerhouse/ph-clint-project']['document']\n * }\n * }\n * }\n */\nexport function isDocType<\n R extends DocumentRegistry,\n T extends keyof R & string,\n>(doc: R[keyof R & string][\"document\"], type: T): doc is R[T][\"document\"] {\n return doc.header?.documentType === type;\n}\n","/**\n * FolderOperations — programmatic API for managing documents\n * in the agent's personal drive using the drive's internal node tree.\n *\n * Folders and file references are stored as nodes in the drive document's\n * `state.global.nodes` array, managed via ADD_FOLDER and ADD_FILE operations.\n * This is distinct from the parent-child document graph (addRelationship/getOutgoingRelationships).\n *\n * Also exports `createFolderCommands()` to auto-generate CLI commands\n * that wrap the folder operations.\n */\nimport { randomUUID } from \"node:crypto\";\nimport { z } from \"zod\";\nimport type { Action } from \"document-model\";\nimport type { TypedReactorClient } from \"./types.js\";\nimport type { FolderEntry, FolderOperations } from \"./types.js\";\nimport type { Command } from \"../../core/types.js\";\nimport type { Logger } from \"../../core/types.js\";\n\nconst TAG = \"[folders]\";\n\n/** Node shape from drive state.global.nodes */\ninterface DriveNode {\n id: string;\n name: string;\n kind: string;\n parentFolder?: string | null;\n documentType?: string;\n}\n\nfunction isFolder(node: DriveNode): boolean {\n return node.kind === \"folder\";\n}\n\n/**\n * Read the drive document's internal nodes array.\n */\nasync function getDriveNodes(\n client: TypedReactorClient<any>,\n driveId: string,\n): Promise<DriveNode[]> {\n const drive = (await client.get(driveId)) as any;\n return (drive?.state?.global?.nodes ?? []) as DriveNode[];\n}\n\n/**\n * Create a FolderOperations instance backed by the reactor client.\n *\n * Folders are nodes inside the drive document's `state.global.nodes` array,\n * created via `ADD_FOLDER` and `ADD_FILE` drive operations executed on the\n * personal drive. This is separate from the document relationship graph.\n * Only calls the remote `GraphQLReactorClient` has too are made, so the same\n * operations work on an in-process and on an attached reactor.\n */\nexport function createFolderOperations(\n client: TypedReactorClient<any>,\n personalDriveId: string,\n log?: Logger,\n): FolderOperations {\n /**\n * Lazy-load drive action creators from @powerhousedao/shared.\n * Kept lazy so that importing folders.ts doesn't pull in the entire\n * @powerhousedao/shared tree — which is an optional peer dependency\n * and won't be installed in non-Powerhouse projects.\n */\n let _driveActions: {\n addFolder: (input: {\n id: string;\n name: string;\n parentFolder: string | null;\n }) => Action;\n addFile: (input: {\n id: string;\n name: string;\n documentType: string;\n parentFolder: string | null;\n }) => Action;\n deleteNode: (input: { id: string }) => Action;\n } | null = null;\n\n async function getDriveActions() {\n if (!_driveActions) {\n const mod = (await import(\"@powerhousedao/shared/document-drive\")) as any;\n _driveActions = {\n addFolder: mod.addFolder,\n addFile: mod.addFile,\n deleteNode: mod.deleteNode,\n };\n }\n return _driveActions;\n }\n\n function splitPath(folderPath: string): string[] {\n return folderPath.split(\"/\").filter(Boolean);\n }\n\n /**\n * Find a folder node by name under a given parent in the drive's nodes.\n */\n function findFolderInNodes(\n nodes: DriveNode[],\n name: string,\n parentId: string | null,\n ): DriveNode | undefined {\n return nodes.find(\n (n) =>\n isFolder(n) && n.name === name && (n.parentFolder ?? null) === parentId,\n );\n }\n\n async function ensureFolder(folderPath: string): Promise<string> {\n const segments = splitPath(folderPath);\n let parentFolderId: string | null = null;\n\n for (const segment of segments) {\n const nodes = await getDriveNodes(client, personalDriveId);\n const existing = findFolderInNodes(nodes, segment, parentFolderId);\n\n if (existing) {\n log?.debug(\n `${TAG} ensureFolder segment \"${segment}\" → exists ${existing.id.slice(0, 8)}…`,\n );\n parentFolderId = existing.id;\n continue;\n }\n\n // Create folder node inside the drive via ADD_FOLDER operation\n const folderId = randomUUID();\n log?.debug(\n `${TAG} ensureFolder creating folder \"${segment}\" (${folderId.slice(0, 8)}…) ` +\n `under ${parentFolderId?.slice(0, 8) ?? \"root\"}`,\n );\n const actions = await getDriveActions();\n await (\n await client.write.execute(personalDriveId, \"main\", [\n actions.addFolder({\n id: folderId,\n name: segment,\n parentFolder: parentFolderId,\n }),\n ])\n ).document();\n parentFolderId = folderId;\n }\n\n return parentFolderId!;\n }\n\n async function addDocument(\n documentId: string,\n folderPath: string,\n name?: string,\n ): Promise<void> {\n log?.debug(\n `${TAG} addDocument ${documentId.slice(0, 8)}… to \"${folderPath}\" name=${name ?? \"(none)\"}`,\n );\n const folderId = await ensureFolder(folderPath);\n\n // Check if this document is already registered as a file node in the drive\n const nodes = await getDriveNodes(client, personalDriveId);\n const existingFile = nodes.find((n) => !isFolder(n) && n.id === documentId);\n if (existingFile) {\n log?.debug(\n `${TAG} addDocument ${documentId.slice(0, 8)}… already in drive as \"${existingFile.name}\"`,\n );\n return;\n }\n\n // Get the document to read its type\n const doc = (await client.get(documentId)) as any;\n const documentType =\n doc?.header?.documentType ?? doc?.documentType ?? \"unknown\";\n const displayName = name ?? doc?.header?.name ?? doc?.name ?? documentId;\n\n // Add file node to drive via ADD_FILE operation\n const actions = await getDriveActions();\n await (\n await client.write.execute(personalDriveId, \"main\", [\n actions.addFile({\n id: documentId,\n name: displayName,\n documentType,\n parentFolder: folderId,\n }),\n ])\n ).document();\n\n // Also establish the parent-child relationship in the document graph\n await (\n await client.write.addRelationship(personalDriveId, documentId, \"child\")\n ).document();\n\n if (name) {\n await (await client.write.rename(documentId, name)).document();\n }\n\n log?.debug(\n `${TAG} addDocument ${documentId.slice(0, 8)}… added as \"${displayName}\" in folder ${folderId.slice(0, 8)}…`,\n );\n }\n\n async function createDocument(\n documentType: string,\n folderPath: string,\n name?: string,\n ): Promise<{ documentId: string }> {\n log?.debug(\n `${TAG} createDocument type=${documentType} folder=\"${folderPath}\" name=${name ?? \"(none)\"}`,\n );\n const parentFolderId = await ensureFolder(folderPath);\n\n const doc = await client.newDocument(documentType, {\n parentIdentifier: personalDriveId,\n name,\n });\n const documentId = doc.header.id;\n\n // What `drives.addFile` does, in calls the remote client has too: the\n // document first, so the drive never names a file whose create failed;\n // then its file node and its place in the document graph.\n await (\n await client.write.create(doc)\n ).readable;\n const actions = await getDriveActions();\n await (\n await client.write.execute(personalDriveId, \"main\", [\n actions.addFile({\n id: documentId,\n name: doc.header.name || documentId,\n documentType: doc.header.documentType,\n parentFolder: parentFolderId,\n }),\n ])\n ).readable;\n await (\n await client.write.addRelationship(personalDriveId, documentId, \"child\")\n ).readable;\n\n log?.debug(\n `${TAG} createDocument ${documentId.slice(0, 8)}… created in folder ${parentFolderId.slice(0, 8)}…`,\n );\n return { documentId };\n }\n\n async function removeDocument(\n documentId: string,\n _folderPath?: string,\n ): Promise<void> {\n // Remove the file node from the drive via DELETE_NODE\n const actions = await getDriveActions();\n await (\n await client.write.execute(personalDriveId, \"main\", [\n actions.deleteNode({ id: documentId }),\n ])\n ).document();\n\n // Also remove the parent-child relationship\n await (\n await client.write.removeRelationship(\n personalDriveId,\n documentId,\n \"child\",\n )\n ).document();\n }\n\n async function resolveFolder(\n folderPath: string,\n ): Promise<string | undefined> {\n const segments = splitPath(folderPath);\n const nodes = await getDriveNodes(client, personalDriveId);\n let parentFolderId: string | null = null;\n\n for (const segment of segments) {\n const match = findFolderInNodes(nodes, segment, parentFolderId);\n if (!match) return undefined;\n parentFolderId = match.id;\n }\n\n return parentFolderId ?? undefined;\n }\n\n async function getDocument(documentId: string): Promise<unknown> {\n return client.get(documentId);\n }\n\n async function listFolder(folderPath?: string): Promise<FolderEntry[]> {\n let parentFolderId: string | null = null;\n\n if (folderPath) {\n const resolved = await resolveFolder(folderPath);\n if (!resolved) return [];\n parentFolderId = resolved;\n }\n\n const nodes = await getDriveNodes(client, personalDriveId);\n const prefix = folderPath ? folderPath.replace(/\\/+$/, \"\") : \"\";\n\n return nodes\n .filter((n) => (n.parentFolder ?? null) === parentFolderId)\n .map((n) => ({\n id: n.id,\n name: n.name,\n type: isFolder(n) ? (\"folder\" as const) : (\"document\" as const),\n documentType: isFolder(n) ? undefined : n.documentType,\n path: prefix ? `${prefix}/${n.name}` : n.name,\n }));\n }\n\n async function findByType(documentType: string): Promise<FolderEntry[]> {\n const nodes = await getDriveNodes(client, personalDriveId);\n return nodes\n .filter((n) => !isFolder(n) && n.documentType === documentType)\n .map((n) => ({\n id: n.id,\n name: n.name,\n type: \"document\" as const,\n documentType: n.documentType,\n path: n.name,\n }));\n }\n\n return {\n addDocument,\n createDocument,\n removeDocument,\n getDocument,\n listFolder,\n ensureFolder,\n findByType,\n };\n}\n\n// ── Folder command schemas ────────────────────────────────────────\n\nconst addDocumentSchema = z.object({\n documentId: z.string().describe(\"Document ID to add\"),\n folderPath: z.string().describe('Folder path (e.g. \"specs/my-project\")'),\n name: z.string().optional().describe(\"Display name for the document\"),\n});\n\nconst removeDocumentSchema = z.object({\n documentId: z.string().describe(\"Document ID to remove\"),\n folderPath: z.string().optional().describe(\"Folder path to remove from\"),\n});\n\nconst getDocumentSchema = z.object({\n documentId: z.string().describe(\"Document ID to retrieve\"),\n});\n\nconst listFolderSchema = z.object({\n folderPath: z.string().optional().describe(\"Folder path (root if omitted)\"),\n});\n\n/**\n * Auto-generate CLI commands that wrap FolderOperations.\n */\nexport function createFolderCommands(folderOps: FolderOperations): Command[] {\n const addDocument: Command<typeof addDocumentSchema> = {\n id: \"folders-add-document\",\n description: \"Add a document to the personal drive at a folder path\",\n inputSchema: addDocumentSchema,\n outputSchema: z.object({ text: z.string() }),\n execute: async (input) => {\n await folderOps.addDocument(\n input.documentId,\n input.folderPath,\n input.name,\n );\n return {\n text: `Added document ${input.documentId} to ${input.folderPath}`,\n };\n },\n };\n\n const removeDocument: Command<typeof removeDocumentSchema> = {\n id: \"folders-remove-document\",\n description: \"Remove a document from the personal drive\",\n inputSchema: removeDocumentSchema,\n outputSchema: z.object({ text: z.string() }),\n execute: async (input) => {\n await folderOps.removeDocument(input.documentId, input.folderPath);\n return { text: `Removed document ${input.documentId}` };\n },\n };\n\n const getDocument: Command<typeof getDocumentSchema> = {\n id: \"folders-get-document\",\n description: \"Get a document from the personal drive\",\n inputSchema: getDocumentSchema,\n outputSchema: z.object({ text: z.string(), data: z.unknown() }),\n execute: async (input) => {\n const doc = await folderOps.getDocument(input.documentId);\n return { text: JSON.stringify(doc, null, 2), data: doc };\n },\n };\n\n const listFolder: Command<typeof listFolderSchema> = {\n id: \"folders-ls\",\n description: \"List folder contents in the personal drive\",\n inputSchema: listFolderSchema,\n outputSchema: z.object({ text: z.string(), data: z.array(z.unknown()) }),\n execute: async (input) => {\n const entries = await folderOps.listFolder(input.folderPath);\n if (entries.length === 0) {\n return { text: \"Empty folder\", data: [] };\n }\n const lines = entries.map((e) => {\n const icon = e.type === \"folder\" ? \"[dir]\" : \"[doc]\";\n const typeInfo = e.documentType ? ` (${e.documentType})` : \"\";\n return ` ${icon} ${e.name}${typeInfo} ${e.id.slice(0, 8)}...`;\n });\n return { text: lines.join(\"\\n\"), data: entries };\n },\n };\n\n return [addDocument, removeDocument, getDocument, listFolder];\n}\n","//#region src/errors.ts\n/**\n* Thrown when an attachment ref or hash is not known to the store.\n*/\nvar AttachmentNotFound = class extends Error {\n\tconstructor(identifier) {\n\t\tsuper(`Attachment not found: ${identifier}`);\n\t\tthis.name = \"AttachmentNotFound\";\n\t}\n};\n/**\n* Thrown when a reservation ID is not found in the reservation store.\n*/\nvar ReservationNotFound = class extends Error {\n\tconstructor(reservationId) {\n\t\tsuper(`Reservation not found: ${reservationId}`);\n\t\tthis.name = \"ReservationNotFound\";\n\t}\n};\n/**\n* Thrown when an attachment ref string does not match the expected format.\n*/\nvar InvalidAttachmentRef = class extends Error {\n\tconstructor(ref) {\n\t\tsuper(`Invalid attachment ref: ${ref}`);\n\t\tthis.name = \"InvalidAttachmentRef\";\n\t}\n};\n/**\n* Thrown when reserve metadata (MIME type, file name or extension) is not\n* acceptable. Route handlers should map this to HTTP 400 Bad Request.\n*/\nvar InvalidAttachmentMetadata = class extends Error {\n\tfield;\n\tconstructor(field) {\n\t\tsuper(`Invalid attachment ${field}`);\n\t\tthis.name = \"InvalidAttachmentMetadata\";\n\t\tthis.field = field;\n\t}\n};\n/**\n* Thrown when an upload exceeds the configured maximum byte cap.\n* Route handlers should map this to HTTP 413 Payload Too Large.\n*/\nvar UploadTooLarge = class extends Error {\n\tmaxBytes;\n\tconstructor(maxBytes) {\n\t\tsuper(`Upload exceeds maximum size of ${maxBytes} bytes`);\n\t\tthis.name = \"UploadTooLarge\";\n\t\tthis.maxBytes = maxBytes;\n\t}\n};\n/**\n* Thrown by reserve() when the claimed hash is already available in the store.\n* The caller should use err.ref directly and upload nothing -- this is the\n* dedup fast path: duplicate content never leaves the client.\n*/\nvar AttachmentAlreadyExists = class extends Error {\n\thash;\n\tref;\n\tconstructor(hash, ref) {\n\t\tsuper(`Attachment already exists for hash: ${hash}`);\n\t\tthis.name = \"AttachmentAlreadyExists\";\n\t\tthis.hash = hash;\n\t\tthis.ref = ref;\n\t}\n};\n/**\n* Thrown by send() when the server-computed hash of the uploaded bytes\n* does not match the hash claimed at reservation time. Nothing is committed;\n* the reservation is retained so the client can retry with correct bytes.\n*/\nvar HashMismatch = class extends Error {\n\tclaimed;\n\tactual;\n\tconstructor(claimed, actual) {\n\t\tsuper(`Hash mismatch: claimed ${claimed} but computed ${actual}`);\n\t\tthis.name = \"HashMismatch\";\n\t\tthis.claimed = claimed;\n\t\tthis.actual = actual;\n\t}\n};\n/**\n* Thrown by send() when the uploaded byte count does not equal the\n* sizeBytes declared at reservation time. The handle may reject\n* mid-stream as soon as the count exceeds the declaration.\n* Nothing is committed; the reservation is retained for retry.\n*\n* \"actual\" is the byte count received from the stream before aborting --\n* it includes the chunk that crossed the declaration and can exceed bytes\n* persisted. On mid-stream aborts the true total is unknown; at least\n* \"actual\" bytes were sent.\n*/\nvar SizeMismatch = class extends Error {\n\tdeclared;\n\tactual;\n\tconstructor(declared, actual) {\n\t\tsuper(`Size mismatch: declared ${declared} bytes but received ${actual}`);\n\t\tthis.name = \"SizeMismatch\";\n\t\tthis.declared = declared;\n\t\tthis.actual = actual;\n\t}\n};\n/**\n* Thrown when a remote transfer step fails. Identifies the stage only; it\n* intentionally carries no URL, signature query, bucket key, or bearer\n* material so it is always safe to log or surface.\n*/\nvar AttachmentTransferError = class extends Error {\n\tstage;\n\tstatus;\n\tconstructor(stage, status) {\n\t\tsuper(status === void 0 ? `Attachment ${stage} request failed` : `Attachment ${stage} request failed with status ${status}`);\n\t\tthis.name = \"AttachmentTransferError\";\n\t\tthis.stage = stage;\n\t\tthis.status = status;\n\t}\n};\nvar AttachmentPending = class extends Error {\n\thash;\n\texpiresAtUtc;\n\tmetadata;\n\tconstructor(hash, expiresAtUtc, meta) {\n\t\tsuper(`Attachment pending upload for hash: ${hash}, expires: ${expiresAtUtc}`);\n\t\tthis.name = \"AttachmentPending\";\n\t\tthis.hash = hash;\n\t\tthis.expiresAtUtc = expiresAtUtc;\n\t\tthis.metadata = meta;\n\t}\n};\n//#endregion\n//#region src/ref.ts\nconst REF_PATTERN = /^attachment:\\/\\/v(\\d+):(.+)$/;\nconst DEFAULT_VERSION = 1;\nfunction parseRef(ref) {\n\tconst match = REF_PATTERN.exec(ref);\n\tif (!match) throw new InvalidAttachmentRef(ref);\n\treturn {\n\t\tversion: Number(match[1]),\n\t\thash: match[2]\n\t};\n}\nfunction createRef(hash, version = DEFAULT_VERSION) {\n\treturn `attachment://v${version}:${hash}`;\n}\n//#endregion\n//#region src/attachment-metadata.ts\nfunction isRecord(value) {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\nfunction isAttachmentMetadata(value) {\n\tif (!isRecord(value)) return false;\n\tif (typeof value.mimeType !== \"string\") return false;\n\tif (typeof value.fileName !== \"string\") return false;\n\tif (typeof value.sizeBytes !== \"number\" || !Number.isFinite(value.sizeBytes) || value.sizeBytes < 0) return false;\n\tif (value.extension !== null && typeof value.extension !== \"string\") return false;\n\tif (typeof value.createdAtUtc !== \"string\") return false;\n\tif (value.lastAccessedAtUtc !== void 0 && typeof value.lastAccessedAtUtc !== \"string\") return false;\n\treturn true;\n}\n//#endregion\n//#region src/switchboard/build-auth-headers.ts\nasync function buildAuthHeaders(url, jwtHandler) {\n\tconst headers = {};\n\tif (jwtHandler) {\n\t\tconst token = await jwtHandler(url);\n\t\tif (token) headers[\"Authorization\"] = `Bearer ${token}`;\n\t}\n\treturn headers;\n}\n//#endregion\n//#region src/switchboard/switchboard-attachment-transport.ts\nvar SwitchboardAttachmentTransport = class {\n\tremoteUrl;\n\tjwtHandler;\n\tfetchFn;\n\tconstructor(config) {\n\t\tthis.remoteUrl = config.remoteUrl;\n\t\tthis.jwtHandler = config.jwtHandler;\n\t\tthis.fetchFn = (config.fetchFn ?? globalThis.fetch).bind(globalThis);\n\t}\n\tasync fetch(hash, documentId, signal) {\n\t\tconst url = `${this.remoteUrl}/attachments/${hash}?documentId=${encodeURIComponent(documentId)}`;\n\t\tconst headers = await buildAuthHeaders(url, this.jwtHandler);\n\t\tconst response = await this.fetchFn(url, {\n\t\t\tsignal,\n\t\t\theaders\n\t\t});\n\t\tif (response.status === 202) {\n\t\t\tconst expiresAtUtc = this.parsePendingExpiry(response);\n\t\t\tif (!expiresAtUtc) throw new Error(\"Attachment fetch returned 202 with missing or malformed Attachment-Pending header\");\n\t\t\treturn {\n\t\t\t\tkind: \"pending\",\n\t\t\t\thash,\n\t\t\t\texpiresAtUtc,\n\t\t\t\tretryAfterMs: parseRetryAfterMs(response)\n\t\t\t};\n\t\t}\n\t\tif (response.status === 404) return { kind: \"not-found\" };\n\t\tif (!response.ok) throw new Error(`Attachment fetch failed: ${response.status} ${response.statusText}`);\n\t\tconst metadata = this.parseMetadataHeaders(response);\n\t\tconst body = response.body;\n\t\tif (!body) throw new Error(\"Response body is null\");\n\t\treturn {\n\t\t\tkind: \"data\",\n\t\t\tresponse: {\n\t\t\t\thash,\n\t\t\t\tmetadata,\n\t\t\t\tbody\n\t\t\t}\n\t\t};\n\t}\n\tasync announce(_hash) {}\n\tasync push(hash, remote, data) {\n\t\tconst url = `${remote}/attachments/${hash}`;\n\t\tconst headers = await buildAuthHeaders(url, this.jwtHandler);\n\t\tconst response = await this.fetchFn(url, {\n\t\t\tmethod: \"PUT\",\n\t\t\tbody: data,\n\t\t\theaders,\n\t\t\tduplex: \"half\"\n\t\t});\n\t\tif (!response.ok) throw new Error(`Attachment push failed: ${response.status} ${response.statusText}`);\n\t}\n\tparsePendingExpiry(response) {\n\t\tconst header = response.headers.get(\"Attachment-Pending\");\n\t\tif (!header) return null;\n\t\ttry {\n\t\t\tconst parsed = JSON.parse(header);\n\t\t\tif (!isRecord(parsed)) return null;\n\t\t\tif (typeof parsed.expiresAtUtc !== \"string\") return null;\n\t\t\treturn parsed.expiresAtUtc;\n\t\t} catch {\n\t\t\treturn null;\n\t\t}\n\t}\n\tparseMetadataHeaders(response) {\n\t\tlet fallbackCache;\n\t\tconst fallback = () => {\n\t\t\tif (fallbackCache === void 0) fallbackCache = contentTypeFallback(response);\n\t\t\treturn fallbackCache;\n\t\t};\n\t\tconst metaHeader = response.headers.get(\"Attachment-Metadata\");\n\t\tif (metaHeader) try {\n\t\t\tconst parsed = JSON.parse(metaHeader);\n\t\t\tif (isRecord(parsed)) {\n\t\t\t\tif (parsed.extension === void 0) parsed.extension = null;\n\t\t\t\tif (parsed.createdAtUtc === void 0) parsed.createdAtUtc = fallback().createdAtUtc;\n\t\t\t\tif (parsed.lastAccessedAtUtc === void 0) parsed.lastAccessedAtUtc = fallback().lastAccessedAtUtc;\n\t\t\t}\n\t\t\tif (isAttachmentMetadata(parsed)) return parsed;\n\t\t} catch {}\n\t\treturn fallback();\n\t}\n};\nconst DEFAULT_RETRY_AFTER_MS = 5e3;\nfunction parseRetryAfterMs(response) {\n\tconst retryAfter = response.headers.get(\"Retry-After\");\n\tif (!retryAfter) return DEFAULT_RETRY_AFTER_MS;\n\tconst seconds = Number(retryAfter);\n\tif (!Number.isFinite(seconds) || seconds < 0) return DEFAULT_RETRY_AFTER_MS;\n\treturn Math.round(seconds * 1e3);\n}\nfunction contentTypeFallback(response) {\n\tconst contentLength = response.headers.get(\"Content-Length\");\n\tif (contentLength === null) throw new Error(\"Switchboard response missing both Attachment-Metadata and Content-Length headers\");\n\tconst sizeBytes = Number(contentLength);\n\tif (!Number.isInteger(sizeBytes) || sizeBytes < 0) throw new Error(`Switchboard response has invalid Content-Length header: ${JSON.stringify(contentLength)}`);\n\tconst lastModified = response.headers.get(\"Last-Modified\");\n\tconst dateHeader = response.headers.get(\"Date\");\n\tconst createdAtUtc = lastModified ? new Date(lastModified).toISOString() : dateHeader ? new Date(dateHeader).toISOString() : (/* @__PURE__ */ new Date()).toISOString();\n\treturn {\n\t\tmimeType: response.headers.get(\"Content-Type\") ?? \"application/octet-stream\",\n\t\tfileName: \"unknown\",\n\t\tsizeBytes,\n\t\textension: null,\n\t\tcreatedAtUtc,\n\t\tlastAccessedAtUtc: createdAtUtc\n\t};\n}\n//#endregion\nexport { parseRef as a, AttachmentPending as c, InvalidAttachmentMetadata as d, InvalidAttachmentRef as f, UploadTooLarge as h, createRef as i, AttachmentTransferError as l, SizeMismatch as m, buildAuthHeaders as n, AttachmentAlreadyExists as o, ReservationNotFound as p, isAttachmentMetadata as r, AttachmentNotFound as s, SwitchboardAttachmentTransport as t, HashMismatch as u };\n\n//# sourceMappingURL=switchboard-attachment-transport-BH3ZAmxE.js.map","/**\n * Utilities for hex, bytes, CSPRNG.\n * @module\n */\n/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.\n// node.js versions earlier than v19 don't declare it in global scope.\n// For node.js, package.json#exports field mapping rewrites import\n// from `crypto` to `cryptoNode`, which imports native module.\n// Makes the utils un-importable in browsers without a bundler.\n// Once node.js 18 is deprecated (2025-04-30), we can just drop the import.\nimport { crypto } from '@noble/hashes/crypto';\n/** Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. */\nexport function isBytes(a) {\n return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');\n}\n/** Asserts something is positive integer. */\nexport function anumber(n) {\n if (!Number.isSafeInteger(n) || n < 0)\n throw new Error('positive integer expected, got ' + n);\n}\n/** Asserts something is Uint8Array. */\nexport function abytes(b, ...lengths) {\n if (!isBytes(b))\n throw new Error('Uint8Array expected');\n if (lengths.length > 0 && !lengths.includes(b.length))\n throw new Error('Uint8Array expected of length ' + lengths + ', got length=' + b.length);\n}\n/** Asserts something is hash */\nexport function ahash(h) {\n if (typeof h !== 'function' || typeof h.create !== 'function')\n throw new Error('Hash should be wrapped by utils.createHasher');\n anumber(h.outputLen);\n anumber(h.blockLen);\n}\n/** Asserts a hash instance has not been destroyed / finished */\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/** Asserts output is properly-sized byte array */\nexport function aoutput(out, instance) {\n abytes(out);\n const min = instance.outputLen;\n if (out.length < min) {\n throw new Error('digestInto() expects output buffer of length at least ' + min);\n }\n}\n/** Cast u8 / u16 / u32 to u8. */\nexport function u8(arr) {\n return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n/** Cast u8 / u16 / u32 to u32. */\nexport function u32(arr) {\n return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n}\n/** Zeroize a byte array. Warning: JS provides no guarantees. */\nexport function clean(...arrays) {\n for (let i = 0; i < arrays.length; i++) {\n arrays[i].fill(0);\n }\n}\n/** Create DataView of an array for easy byte-level manipulation. */\nexport function createView(arr) {\n return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n/** The rotate right (circular right shift) operation for uint32 */\nexport function rotr(word, shift) {\n return (word << (32 - shift)) | (word >>> shift);\n}\n/** The rotate left (circular left shift) operation for uint32 */\nexport function rotl(word, shift) {\n return (word << shift) | ((word >>> (32 - shift)) >>> 0);\n}\n/** Is current platform little-endian? Most are. Big-Endian platform: IBM */\nexport const isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();\n/** The byte swap operation for uint32 */\nexport function byteSwap(word) {\n return (((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff));\n}\n/** Conditionally byte swap if on a big-endian platform */\nexport const swap8IfBE = isLE\n ? (n) => n\n : (n) => byteSwap(n);\n/** @deprecated */\nexport const byteSwapIfBE = swap8IfBE;\n/** In place byte swap for Uint32Array */\nexport function byteSwap32(arr) {\n for (let i = 0; i < arr.length; i++) {\n arr[i] = byteSwap(arr[i]);\n }\n return arr;\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. Uses built-in function, when available.\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\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 * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex) {\n if (typeof hex !== 'string')\n throw new Error('hex string expected, got ' + typeof hex);\n // @ts-ignore\n if (hasHexBuiltin)\n return Uint8Array.fromHex(hex);\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2)\n throw new Error('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 Error('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 * Call of async fn will return Promise, which will be fullfiled only on\n * next scheduler queue processing step and this is exactly what we need.\n */\nexport const nextTick = async () => { };\n/** Returns control to thread each 'tick' ms to avoid blocking. */\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 * @example utf8ToBytes('abc') // Uint8Array.from([97, 98, 99])\n */\nexport function utf8ToBytes(str) {\n if (typeof str !== 'string')\n throw new Error('string expected');\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n/**\n * Converts bytes to string using UTF8 encoding.\n * @example bytesToUtf8(Uint8Array.from([97, 98, 99])) // 'abc'\n */\nexport function bytesToUtf8(bytes) {\n return new TextDecoder().decode(bytes);\n}\n/**\n * Normalizes (non-hex) string or Uint8Array to Uint8Array.\n * Warning: when Uint8Array is passed, it would NOT get copied.\n * Keep in mind for future mutable operations.\n */\nexport function toBytes(data) {\n if (typeof data === 'string')\n data = utf8ToBytes(data);\n abytes(data);\n return data;\n}\n/**\n * Helper for KDFs: consumes uint8array or string.\n * When string is passed, does utf8 decoding, using TextDecoder.\n */\nexport function kdfInputToBytes(data) {\n if (typeof data === 'string')\n data = utf8ToBytes(data);\n abytes(data);\n return data;\n}\n/** Copies several Uint8Arrays into one. */\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}\nexport function checkOpts(defaults, opts) {\n if (opts !== undefined && {}.toString.call(opts) !== '[object Object]')\n throw new Error('options should be object or undefined');\n const merged = Object.assign(defaults, opts);\n return merged;\n}\n/** For runtime check if class implements interface */\nexport class Hash {\n}\n/** Wraps hash function, creating an interface on top of it */\nexport function createHasher(hashCons) {\n const hashC = (msg) => hashCons().update(toBytes(msg)).digest();\n const tmp = hashCons();\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = () => hashCons();\n return hashC;\n}\nexport function createOptHasher(hashCons) {\n const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({});\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts) => hashCons(opts);\n return hashC;\n}\nexport function createXOFer(hashCons) {\n const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({});\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts) => hashCons(opts);\n return hashC;\n}\nexport const wrapConstructor = createHasher;\nexport const wrapConstructorWithOpts = createOptHasher;\nexport const wrapXOFConstructorWithOpts = createXOFer;\n/** Cryptographically secure PRNG. Uses internal OS-level `crypto.getRandomValues`. */\nexport function randomBytes(bytesLength = 32) {\n if (crypto && typeof crypto.getRandomValues === 'function') {\n return crypto.getRandomValues(new Uint8Array(bytesLength));\n }\n // Legacy Node.js compatibility\n if (crypto && typeof crypto.randomBytes === 'function') {\n return Uint8Array.from(crypto.randomBytes(bytesLength));\n }\n throw new Error('crypto.getRandomValues must be defined');\n}\n//# sourceMappingURL=utils.js.map","/**\n * Internal Merkle-Damgard hash utils.\n * @module\n */\nimport { Hash, abytes, aexists, aoutput, clean, createView, toBytes } from \"./utils.js\";\n/** Polyfill for Safari 14. https://caniuse.com/mdn-javascript_builtins_dataview_setbiguint64 */\nexport function setBigUint64(view, byteOffset, value, isLE) {\n if (typeof view.setBigUint64 === 'function')\n return view.setBigUint64(byteOffset, value, isLE);\n const _32n = BigInt(32);\n const _u32_max = BigInt(0xffffffff);\n const wh = Number((value >> _32n) & _u32_max);\n const wl = Number(value & _u32_max);\n const h = isLE ? 4 : 0;\n const l = isLE ? 0 : 4;\n view.setUint32(byteOffset + h, wh, isLE);\n view.setUint32(byteOffset + l, wl, isLE);\n}\n/** Choice: a ? b : c */\nexport function Chi(a, b, c) {\n return (a & b) ^ (~a & c);\n}\n/** Majority function, true if any two inputs is true. */\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 */\nexport class HashMD extends Hash {\n constructor(blockLen, outputLen, padOffset, isLE) {\n super();\n this.finished = false;\n this.length = 0;\n this.pos = 0;\n this.destroyed = false;\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 data = toBytes(data);\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: we have at least one block in input, cast it to view and process\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 // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that\n // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen.\n // So we just write lowest 64 bits of that value.\n setBigUint64(view, 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 should be fused in single op with modulo by JIT\n if (len % 4)\n throw new Error('_sha2: outputLen should 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 const res = buffer.slice(0, outputLen);\n this.destroy();\n return res;\n }\n _cloneInto(to) {\n to || (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 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. Bits 0..32 of frac part of sqrt of primes 2..19 */\nexport const SHA256_IV = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,\n]);\n/** Initial SHA224 state. Bits 32..64 of frac part of sqrt of primes 23..53 */\nexport const SHA224_IV = /* @__PURE__ */ Uint32Array.from([\n 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4,\n]);\n/** Initial SHA384 state. Bits 0..64 of frac part of sqrt of primes 23..53 */\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. Bits 0..64 of frac part of sqrt of primes 2..19 */\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","/**\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 [RFC 4634](https://datatracker.ietf.org/doc/html/rfc4634) and\n * [FIPS 180-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf).\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, rotr } from \"./utils.js\";\n/**\n * Round constants:\n * First 32 bits of fractional parts 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 temporary buffer. \"W\" comes straight from spec. */\nconst SHA256_W = /* @__PURE__ */ new Uint32Array(64);\nexport class SHA256 extends HashMD {\n constructor(outputLen = 32) {\n super(64, outputLen, 8, false);\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n this.A = SHA256_IV[0] | 0;\n this.B = SHA256_IV[1] | 0;\n this.C = SHA256_IV[2] | 0;\n this.D = SHA256_IV[3] | 0;\n this.E = SHA256_IV[4] | 0;\n this.F = SHA256_IV[5] | 0;\n this.G = SHA256_IV[6] | 0;\n this.H = SHA256_IV[7] | 0;\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 this.set(0, 0, 0, 0, 0, 0, 0, 0);\n clean(this.buffer);\n }\n}\nexport class SHA224 extends SHA256 {\n constructor() {\n super(28);\n this.A = SHA224_IV[0] | 0;\n this.B = SHA224_IV[1] | 0;\n this.C = SHA224_IV[2] | 0;\n this.D = SHA224_IV[3] | 0;\n this.E = SHA224_IV[4] | 0;\n this.F = SHA224_IV[5] | 0;\n this.G = SHA224_IV[6] | 0;\n this.H = SHA224_IV[7] | 0;\n }\n}\n// SHA2-512 is slower than sha256 in js because u64 operations are slow.\n// Round contants\n// First 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409\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 temporary buffers\nconst SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);\nconst SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);\nexport class SHA512 extends HashMD {\n constructor(outputLen = 64) {\n super(128, outputLen, 16, false);\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n // h -- high 32 bits, l -- low 32 bits\n this.Ah = SHA512_IV[0] | 0;\n this.Al = SHA512_IV[1] | 0;\n this.Bh = SHA512_IV[2] | 0;\n this.Bl = SHA512_IV[3] | 0;\n this.Ch = SHA512_IV[4] | 0;\n this.Cl = SHA512_IV[5] | 0;\n this.Dh = SHA512_IV[6] | 0;\n this.Dl = SHA512_IV[7] | 0;\n this.Eh = SHA512_IV[8] | 0;\n this.El = SHA512_IV[9] | 0;\n this.Fh = SHA512_IV[10] | 0;\n this.Fl = SHA512_IV[11] | 0;\n this.Gh = SHA512_IV[12] | 0;\n this.Gl = SHA512_IV[13] | 0;\n this.Hh = SHA512_IV[14] | 0;\n this.Hl = SHA512_IV[15] | 0;\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 // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_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 clean(this.buffer);\n this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);\n }\n}\nexport class SHA384 extends SHA512 {\n constructor() {\n super(48);\n this.Ah = SHA384_IV[0] | 0;\n this.Al = SHA384_IV[1] | 0;\n this.Bh = SHA384_IV[2] | 0;\n this.Bl = SHA384_IV[3] | 0;\n this.Ch = SHA384_IV[4] | 0;\n this.Cl = SHA384_IV[5] | 0;\n this.Dh = SHA384_IV[6] | 0;\n this.Dl = SHA384_IV[7] | 0;\n this.Eh = SHA384_IV[8] | 0;\n this.El = SHA384_IV[9] | 0;\n this.Fh = SHA384_IV[10] | 0;\n this.Fl = SHA384_IV[11] | 0;\n this.Gh = SHA384_IV[12] | 0;\n this.Gl = SHA384_IV[13] | 0;\n this.Hh = SHA384_IV[14] | 0;\n this.Hl = SHA384_IV[15] | 0;\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 `test/misc/sha2-gen-iv.js`.\n */\n/** SHA512/224 IV */\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/** SHA512/256 IV */\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]);\nexport class SHA512_224 extends SHA512 {\n constructor() {\n super(28);\n this.Ah = T224_IV[0] | 0;\n this.Al = T224_IV[1] | 0;\n this.Bh = T224_IV[2] | 0;\n this.Bl = T224_IV[3] | 0;\n this.Ch = T224_IV[4] | 0;\n this.Cl = T224_IV[5] | 0;\n this.Dh = T224_IV[6] | 0;\n this.Dl = T224_IV[7] | 0;\n this.Eh = T224_IV[8] | 0;\n this.El = T224_IV[9] | 0;\n this.Fh = T224_IV[10] | 0;\n this.Fl = T224_IV[11] | 0;\n this.Gh = T224_IV[12] | 0;\n this.Gl = T224_IV[13] | 0;\n this.Hh = T224_IV[14] | 0;\n this.Hl = T224_IV[15] | 0;\n }\n}\nexport class SHA512_256 extends SHA512 {\n constructor() {\n super(32);\n this.Ah = T256_IV[0] | 0;\n this.Al = T256_IV[1] | 0;\n this.Bh = T256_IV[2] | 0;\n this.Bl = T256_IV[3] | 0;\n this.Ch = T256_IV[4] | 0;\n this.Cl = T256_IV[5] | 0;\n this.Dh = T256_IV[6] | 0;\n this.Dl = T256_IV[7] | 0;\n this.Eh = T256_IV[8] | 0;\n this.El = T256_IV[9] | 0;\n this.Fh = T256_IV[10] | 0;\n this.Fl = T256_IV[11] | 0;\n this.Gh = T256_IV[12] | 0;\n this.Gl = T256_IV[13] | 0;\n this.Hh = T256_IV[14] | 0;\n this.Hl = T256_IV[15] | 0;\n }\n}\n/**\n * SHA2-256 hash function from RFC 4634.\n *\n * It is the fastest JS hash, even faster than Blake3.\n * To break sha256 using birthday attack, attackers need to try 2^128 hashes.\n * BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.\n */\nexport const sha256 = /* @__PURE__ */ createHasher(() => new SHA256());\n/** SHA2-224 hash function from RFC 4634 */\nexport const sha224 = /* @__PURE__ */ createHasher(() => new SHA224());\n/** SHA2-512 hash function from RFC 4634. */\nexport const sha512 = /* @__PURE__ */ createHasher(() => new SHA512());\n/** SHA2-384 hash function from RFC 4634. */\nexport const sha384 = /* @__PURE__ */ createHasher(() => new SHA384());\n/**\n * SHA2-512/256 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on [truncated SHA512](https://eprint.iacr.org/2010/548.pdf).\n */\nexport const sha512_256 = /* @__PURE__ */ createHasher(() => new SHA512_256());\n/**\n * SHA2-512/224 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on [truncated SHA512](https://eprint.iacr.org/2010/548.pdf).\n */\nexport const sha512_224 = /* @__PURE__ */ createHasher(() => new SHA512_224());\n//# sourceMappingURL=sha2.js.map","import { sha256 } from \"@noble/hashes/sha2.js\";\nimport { bytesToHex } from \"@noble/hashes/utils.js\";\nconst nodeCrypto = globalThis.process?.getBuiltinModule?.(\"node:crypto\");\n/** Native SHA-256 from node:crypto, or undefined outside Node. */\nfunction nodeSha256() {\n\tif (!nodeCrypto) return void 0;\n\tconst hash = nodeCrypto.createHash(\"sha256\");\n\treturn {\n\t\tupdate: (bytes) => void hash.update(bytes),\n\t\thex: () => hash.digest(\"hex\")\n\t};\n}\n/** SHA-256 in JavaScript, for browsers; about 10x slower than native. */\nfunction jsSha256() {\n\tconst hash = sha256.create();\n\treturn {\n\t\tupdate: (bytes) => void hash.update(bytes),\n\t\thex: () => bytesToHex(hash.digest())\n\t};\n}\n/**\n* Lowercase SHA-256 hex of `bytes` -- the `attachment://v1:` hash format\n* (`packages/reactor/src/attachments/types.ts`).\n*\n* WebCrypto, so the same code runs in Node and in a browser realm. There is no\n* streaming digest in WebCrypto, which is why verification happens over\n* collected bytes.\n*/\nasync function sha256Hex(bytes) {\n\tconst digest = await globalThis.crypto.subtle.digest(\"SHA-256\", digestable(bytes));\n\treturn Array.from(new Uint8Array(digest)).map((byte) => byte.toString(16).padStart(2, \"0\")).join(\"\");\n}\n/** WebCrypto refuses a SharedArrayBuffer-backed view, so only that one is copied. */\nfunction digestable(bytes) {\n\tif (typeof SharedArrayBuffer !== \"undefined\" && bytes.buffer instanceof SharedArrayBuffer) {\n\t\tconst copy = new Uint8Array(bytes.byteLength);\n\t\tcopy.set(bytes);\n\t\treturn copy;\n\t}\n\treturn bytes;\n}\n/** Same digest as `sha256Hex`, in bounded memory: natively in slices in Node, and in a\n* browser whole up to `oneShotMaxBytes`, then in JavaScript slices (no ~2 GB read). */\nasync function sha256HexOfBlob(blob, options) {\n\tconst chunkBytes = options?.chunkBytes ?? 8388608;\n\tif (!Number.isInteger(chunkBytes) || chunkBytes <= 0) throw new RangeError(\"chunkBytes must be a positive integer\");\n\toptions?.signal?.throwIfAborted();\n\tlet hasher = (options?.native ?? nodeSha256)();\n\tif (!hasher) {\n\t\tif (blob.size <= (options?.oneShotMaxBytes ?? 268435456)) return sha256Hex(new Uint8Array(await blob.arrayBuffer()));\n\t\thasher = jsSha256();\n\t}\n\tfor (let offset = 0; offset < blob.size; offset += chunkBytes) {\n\t\toptions?.signal?.throwIfAborted();\n\t\tconst chunk = blob.slice(offset, offset + chunkBytes);\n\t\thasher.update(new Uint8Array(await chunk.arrayBuffer()));\n\t}\n\treturn hasher.hex();\n}\n//#endregion\nexport { sha256HexOfBlob as n, sha256Hex as t };\n\n//# sourceMappingURL=hash-BobbR4r4.js.map","import { a as parseRef, c as AttachmentPending, f as InvalidAttachmentRef, h as UploadTooLarge, i as createRef, l as AttachmentTransferError, m as SizeMismatch, o as AttachmentAlreadyExists, p as ReservationNotFound, s as AttachmentNotFound, t as SwitchboardAttachmentTransport, u as HashMismatch } from \"./switchboard-attachment-transport-BH3ZAmxE.js\";\nimport { a as RemoteAttachmentUploadFactory, c as createXhrUploadTransport, f as AttachmentService, i as RemoteAttachmentStore, l as createFetchUploadTransport, m as parseAttachmentUploadTarget, n as NullAttachmentTransport, o as RemoteAttachmentUpload, p as parseAttachmentDownloadTarget, r as createRemoteAttachmentService, s as RemoteReservationStore, t as RoutingAttachmentService } from \"./routing-attachment-service-C88ryRgj.js\";\nimport { n as sha256HexOfBlob } from \"./hash-BobbR4r4.js\";\n//#region src/concurrency.ts\n/**\n* Runs `worker` over `items` with a hard upper bound on simultaneous\n* executions. Bounding starts (not just transfers) is what keeps memory flat:\n* an item's preprocessing (hashing/buffering) only begins when a slot frees.\n*/\nasync function runWithConcurrency(items, worker, options) {\n\tconst { concurrency, signal, onSettled } = options;\n\tif (!Number.isInteger(concurrency) || concurrency < 1) throw new Error(`concurrency must be a positive integer, got: ${concurrency}`);\n\tconst results = new Array(items.length);\n\tlet nextIndex = 0;\n\tasync function runLane() {\n\t\tfor (;;) {\n\t\t\tconst index = nextIndex++;\n\t\t\tif (index >= items.length) return;\n\t\t\tif (signal?.aborted) {\n\t\t\t\tresults[index] = {\n\t\t\t\t\tindex,\n\t\t\t\t\tstatus: \"rejected\",\n\t\t\t\t\terror: signalReason(signal)\n\t\t\t\t};\n\t\t\t\tonSettled?.(results[index]);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tconst value = await worker(items[index], index);\n\t\t\t\tresults[index] = {\n\t\t\t\t\tindex,\n\t\t\t\t\tstatus: \"fulfilled\",\n\t\t\t\t\tvalue\n\t\t\t\t};\n\t\t\t} catch (error) {\n\t\t\t\tresults[index] = {\n\t\t\t\t\tindex,\n\t\t\t\t\tstatus: \"rejected\",\n\t\t\t\t\terror\n\t\t\t\t};\n\t\t\t}\n\t\t\tonSettled?.(results[index]);\n\t\t}\n\t}\n\tconst lanes = Array.from({ length: Math.min(concurrency, items.length) }, () => runLane());\n\tawait Promise.all(lanes);\n\treturn results;\n}\nfunction signalReason(signal) {\n\treturn signal.reason ?? new DOMException(\"The operation was aborted\", \"AbortError\");\n}\n//#endregion\n//#region src/progress.ts\nconst DEFAULT_PROGRESS_THROTTLE_MS = 100;\n/**\n* Fraction in 0..1 for a progress event. Indeterminate and unknown-total\n* events read as 0 — a bar cannot honestly show a position it does not know.\n* A zero total is complete by definition (the dedup case moves no bytes).\n*/\nfunction progressFraction(progress) {\n\tif (progress.indeterminate) return 0;\n\tif (progress.total === void 0) return 0;\n\tif (progress.total === 0) return 1;\n\tconst fraction = progress.loaded / progress.total;\n\tif (fraction < 0) return 0;\n\treturn fraction > 1 ? 1 : fraction;\n}\n/**\n* Emits `AttachmentProgress` for one single-item operation, upholding:\n*\n* - **I1** exactly one terminal event (`done` or `error`) — never both, never twice.\n* - **I2** on `done`: `indeterminate === false`, `total` is a number, `loaded === total`.\n* - **I3** `loaded` is non-decreasing within a stage and resets to 0 on stage change.\n* - **I4** the terminal event bypasses the throttle unconditionally.\n* - **I5** `error` carries the last known `loaded`/`total`.\n*\n* Leading edge: the first `bytes()` after a `stage()` always emits, so a bar\n* leaves 0 immediately. There is deliberately no trailing-edge timer — it\n* would leak on throw, could fire after the terminal event and violate I1's\n* ordering, and is unnecessary because `finish()` always emits\n* `loaded === total`, making a dropped last intra-stage tick invisible.\n*/\nvar ProgressEmitter = class {\n\tlistener;\n\tthrottleMs;\n\tnow;\n\tcurrentStage;\n\tloaded = 0;\n\ttotal;\n\temittedBytesInStage = false;\n\tlastEmitAt = Number.NEGATIVE_INFINITY;\n\tsettled = false;\n\tconstructor(options) {\n\t\tthis.listener = options?.onProgress;\n\t\tthis.throttleMs = options?.throttleMs ?? 100;\n\t\tthis.now = options?.now ?? (() => Date.now());\n\t}\n\t/** True when a listener is attached; lets callers skip instrumentation entirely. */\n\tget active() {\n\t\treturn this.listener !== void 0;\n\t}\n\t/**\n\t* Enter a stage. Always emits and resets `loaded` to 0. Entry is always\n\t* indeterminate: no bytes have moved yet, and whether they can be observed\n\t* at all is only proven by a transport actually calling back.\n\t*/\n\tstage(stage, options) {\n\t\tif (this.settled) return;\n\t\tthis.currentStage = stage;\n\t\tthis.loaded = 0;\n\t\tthis.total = options?.total;\n\t\tthis.emittedBytesInStage = false;\n\t\tthis.emit({\n\t\t\tstage,\n\t\t\tloaded: 0,\n\t\t\ttotal: this.total,\n\t\t\tindeterminate: true\n\t\t});\n\t}\n\t/**\n\t* Report observed bytes within the current stage. Throttled by time, with\n\t* the first observation after a stage change always emitted.\n\t*/\n\tbytes(loaded, total) {\n\t\tif (this.settled || this.currentStage === void 0) return;\n\t\tif (total !== void 0) this.total = total;\n\t\tif (loaded > this.loaded) this.loaded = loaded;\n\t\tif (!!this.emittedBytesInStage && this.now() - this.lastEmitAt < this.throttleMs) return;\n\t\tthis.emittedBytesInStage = true;\n\t\tthis.emit({\n\t\t\tstage: this.currentStage,\n\t\t\tloaded: this.loaded,\n\t\t\ttotal: this.total,\n\t\t\tindeterminate: false\n\t\t});\n\t}\n\t/**\n\t* Terminal success. `total` defaults to the bytes actually seen so a stage\n\t* with no known denominator still satisfies I2.\n\t*/\n\tfinish(override) {\n\t\tif (this.settled) return;\n\t\tthis.settled = true;\n\t\tconst total = override?.total ?? this.total ?? this.loaded;\n\t\tconst loaded = override?.loaded ?? total;\n\t\tthis.emit({\n\t\t\tstage: \"done\",\n\t\t\tloaded,\n\t\t\ttotal,\n\t\t\tindeterminate: false,\n\t\t\t...override?.deduped ? { deduped: true } : {}\n\t\t});\n\t}\n\t/** Terminal success for a confirmed dedup: no bytes moved, and none needed to. */\n\tfinishDeduped() {\n\t\tthis.finish({\n\t\t\tloaded: 0,\n\t\t\ttotal: 0,\n\t\t\tdeduped: true\n\t\t});\n\t}\n\t/** Terminal failure, carrying the last known byte counts. */\n\tfail() {\n\t\tif (this.settled) return;\n\t\tthis.settled = true;\n\t\tthis.emit({\n\t\t\tstage: \"error\",\n\t\t\tloaded: this.loaded,\n\t\t\ttotal: this.total,\n\t\t\tindeterminate: false\n\t\t});\n\t}\n\temit(progress) {\n\t\tthis.lastEmitAt = this.now();\n\t\tthis.listener?.(progress);\n\t}\n};\n/**\n* Count bytes as a consumer reads them.\n*\n* Uses the manual-reader form rather than `pipeThrough`, whose internal queue\n* reads far ahead of the consumer and would make `loaded` overstate what was\n* actually received. `highWaterMark: 0` is load-bearing for the same reason:\n* at the default of 1 the wrapper pulls one chunk the instant it is\n* constructed, so a caller who never reads still sees bytes counted.\n*\n* `cancel` propagates to the source, which is what keeps reader refcounts\n* (e.g. `KyselyAttachmentStore`'s) correct. Cancelling is an abandonment, not\n* a completion, so it reports `onError` — never `onDone` — carrying the\n* cancel reason the way an `AbortSignal` carries its own, with the DOM's\n* default `AbortError` when the canceller gave none.\n*\n* Returns `source` unchanged when no hook is supplied, so a caller with no\n* listener pays nothing.\n*/\nfunction withByteProgress(source, hooks) {\n\tif (!hooks.onBytes && !hooks.onDone && !hooks.onError) return source;\n\tlet loaded = 0;\n\tlet cancelled = false;\n\tconst reader = source.getReader();\n\treturn new ReadableStream({\n\t\tasync pull(controller) {\n\t\t\ttry {\n\t\t\t\tconst { done, value } = await reader.read();\n\t\t\t\tif (cancelled) return;\n\t\t\t\tif (done) {\n\t\t\t\t\thooks.onDone?.();\n\t\t\t\t\tcontroller.close();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tloaded += value.byteLength;\n\t\t\t\thooks.onBytes?.(loaded);\n\t\t\t\tcontroller.enqueue(value);\n\t\t\t} catch (err) {\n\t\t\t\tif (cancelled) return;\n\t\t\t\thooks.onError?.(err);\n\t\t\t\tcontroller.error(err);\n\t\t\t}\n\t\t},\n\t\tcancel(reason) {\n\t\t\tcancelled = true;\n\t\t\treader.cancel(reason).catch(() => {});\n\t\t\thooks.onError?.(reason ?? abortError());\n\t\t}\n\t}, { highWaterMark: 0 });\n}\n/** What an `AbortSignal` carries when `abort()` is called with no reason. */\nfunction abortError() {\n\treturn new DOMException(\"The operation was aborted\", \"AbortError\");\n}\n//#endregion\n//#region src/client.ts\nconst DEFAULT_ATTACHMENT_BATCH_CONCURRENCY = 4;\n/**\n* Duck-typed dedup detection: bundlers (notably Vite dev pre-bundling) can\n* load two copies of this package's error classes, one for the service and\n* one for the client wrapper, making a plain instanceof check miss the\n* cross-copy throw. Name plus payload shape identifies the error reliably.\n*/\nfunction isAttachmentAlreadyExists(err) {\n\tif (err instanceof AttachmentAlreadyExists) return true;\n\treturn err instanceof Error && err.name === \"AttachmentAlreadyExists\" && typeof err.hash === \"string\" && typeof err.ref === \"string\";\n}\nfunction dedupedHeader(hash, options) {\n\tconst now = (/* @__PURE__ */ new Date()).toISOString();\n\treturn {\n\t\thash,\n\t\tmimeType: options.mimeType,\n\t\tfileName: options.fileName,\n\t\tsizeBytes: options.sizeBytes,\n\t\textension: options.extension ?? null,\n\t\tstatus: \"available\",\n\t\tsource: \"local\",\n\t\tcreatedAtUtc: now,\n\t\tlastAccessedAtUtc: now,\n\t\texpiresAtUtc: null\n\t};\n}\n/** Stamps an item's index onto its progress events. */\nfunction itemProgress(options, index) {\n\tif (!options?.onProgress && options?.throttleMs === void 0) return;\n\treturn {\n\t\t...options.onProgress ? { onProgress: (progress) => options.onProgress?.({\n\t\t\t...progress,\n\t\t\tindex\n\t\t}) } : {},\n\t\t...options.throttleMs !== void 0 ? { throttleMs: options.throttleMs } : {}\n\t};\n}\nfunction batchRunOptions(total, options) {\n\tconst onItemSettled = options?.onItemSettled;\n\tlet settled = 0;\n\tlet completed = 0;\n\tlet failed = 0;\n\treturn {\n\t\tconcurrency: options?.concurrency ?? 4,\n\t\t...options?.signal ? { signal: options.signal } : {},\n\t\t...onItemSettled ? { onSettled: (result) => {\n\t\t\tsettled += 1;\n\t\t\tif (result.status === \"fulfilled\") completed += 1;\n\t\t\telse failed += 1;\n\t\t\tonItemSettled({\n\t\t\t\tsettled,\n\t\t\t\tcompleted,\n\t\t\t\tfailed,\n\t\t\t\ttotal\n\t\t\t});\n\t\t} } : {}\n\t};\n}\nvar AttachmentClientImpl = class {\n\tservice;\n\tconstructor(service) {\n\t\tthis.service = service;\n\t}\n\tpreprocess(file, opts) {\n\t\treturn this.hashFile(file, opts);\n\t}\n\tasync hashFile(file, opts, signal) {\n\t\tconst hash = await sha256HexOfBlob(file, signal ? { signal } : void 0);\n\t\tconst ref = createRef(hash);\n\t\tconst sizeBytes = file.size;\n\t\treturn {\n\t\t\tref,\n\t\t\thash,\n\t\t\tsizeBytes,\n\t\t\toptions: {\n\t\t\t\tmimeType: opts?.mimeType ?? file.type,\n\t\t\t\tfileName: opts?.fileName ?? (file instanceof File ? file.name : \"attachment\"),\n\t\t\t\tclientHash: hash,\n\t\t\t\tsizeBytes,\n\t\t\t\t...opts?.documentId !== void 0 ? { documentId: opts.documentId } : {}\n\t\t\t},\n\t\t\tblob: file\n\t\t};\n\t}\n\t/**\n\t* Reserve, distinguishing a confirmed dedup from a live upload handle in the\n\t* type rather than with a flag: the two outcomes move a different number of\n\t* bytes, and every caller has to account for that.\n\t*/\n\tasync reserveOrDedup(options) {\n\t\ttry {\n\t\t\treturn {\n\t\t\t\tkind: \"handle\",\n\t\t\t\thandle: await this.service.reserve(options)\n\t\t\t};\n\t\t} catch (err) {\n\t\t\tif (!isAttachmentAlreadyExists(err)) throw err;\n\t\t\treturn {\n\t\t\t\tkind: \"deduped\",\n\t\t\t\tresult: {\n\t\t\t\t\thash: err.hash,\n\t\t\t\t\tref: err.ref,\n\t\t\t\t\theader: dedupedHeader(err.hash, options)\n\t\t\t\t}\n\t\t\t};\n\t\t}\n\t}\n\tasync reserve(options, send) {\n\t\tconst outcome = await this.reserveOrDedup(options);\n\t\tif (outcome.kind === \"deduped\") return outcome.result;\n\t\treturn send(outcome.handle);\n\t}\n\tasync upload(input, options) {\n\t\tconst emitter = new ProgressEmitter(options);\n\t\tconst signal = input.signal;\n\t\ttry {\n\t\t\tsignal?.throwIfAborted();\n\t\t\tlet preprocessed;\n\t\t\tif (\"preprocessed\" in input) preprocessed = input.preprocessed;\n\t\t\telse {\n\t\t\t\temitter.stage(\"hashing\", { total: input.file.size });\n\t\t\t\tpreprocessed = await this.hashFile(input.file, {\n\t\t\t\t\t...input.fileName !== void 0 ? { fileName: input.fileName } : {},\n\t\t\t\t\t...input.mimeType !== void 0 ? { mimeType: input.mimeType } : {},\n\t\t\t\t\t...input.documentId !== void 0 ? { documentId: input.documentId } : {}\n\t\t\t\t}, signal);\n\t\t\t}\n\t\t\tconst sizeBytes = preprocessed.sizeBytes;\n\t\t\tsignal?.throwIfAborted();\n\t\t\temitter.stage(\"reserving\");\n\t\t\tconst outcome = await this.reserveOrDedup(preprocessed.options);\n\t\t\tif (outcome.kind === \"deduped\") {\n\t\t\t\temitter.finishDeduped();\n\t\t\t\treturn outcome.result;\n\t\t\t}\n\t\t\tsignal?.throwIfAborted();\n\t\t\temitter.stage(\"uploading\", { total: sizeBytes });\n\t\t\tconst sendOptions = {\n\t\t\t\t...emitter.active ? { onProgress: (loaded, total) => emitter.bytes(loaded, total ?? sizeBytes) } : {},\n\t\t\t\t...signal ? { signal } : {}\n\t\t\t};\n\t\t\tconst result = await outcome.handle.send(preprocessed.blob, sendOptions);\n\t\t\temitter.finish();\n\t\t\treturn result;\n\t\t} catch (err) {\n\t\t\temitter.fail();\n\t\t\tthrow err;\n\t\t}\n\t}\n\t/**\n\t* The single site where download bytes are instrumented.\n\t*\n\t* It sits here, above the service, rather than in any store or transport:\n\t* one logical get can be several byte streams underneath (an evicted\n\t* attachment is fetched from the transport, written to disk, then re-read),\n\t* so counting lower down would double-count that path and still miss\n\t* local-filesystem reads. Wrapping what `service.get` returns covers the\n\t* presigned, switchboard, legacy and local paths by construction, and\n\t* `downloadBlob`/`saveAttachment`/`downloadObjectUrl` inherit it.\n\t*/\n\tasync getWithProgress(input, emitter) {\n\t\tconst { header, body } = await this.service.get(input.ref, {\n\t\t\tdocumentId: input.documentId,\n\t\t\tsignal: input.signal\n\t\t});\n\t\temitter.stage(\"downloading\", { total: header.sizeBytes });\n\t\tif (!emitter.active) return {\n\t\t\theader,\n\t\t\tbody\n\t\t};\n\t\treturn {\n\t\t\theader,\n\t\t\tbody: withByteProgress(body, {\n\t\t\t\tonBytes: (loaded) => emitter.bytes(loaded),\n\t\t\t\tonDone: () => emitter.finish(),\n\t\t\t\tonError: () => emitter.fail()\n\t\t\t})\n\t\t};\n\t}\n\tasync download(input, options) {\n\t\tconst emitter = new ProgressEmitter(options);\n\t\ttry {\n\t\t\tinput.signal?.throwIfAborted();\n\t\t\temitter.stage(\"requesting-download-target\");\n\t\t\treturn await this.getWithProgress(input, emitter);\n\t\t} catch (err) {\n\t\t\temitter.fail();\n\t\t\tthrow err;\n\t\t}\n\t}\n\tasync downloadBlob(input, options) {\n\t\tconst emitter = new ProgressEmitter(options);\n\t\ttry {\n\t\t\tinput.signal?.throwIfAborted();\n\t\t\temitter.stage(\"requesting-download-target\");\n\t\t\tconst { header, body } = await this.getWithProgress(input, emitter);\n\t\t\tconst reader = body.getReader();\n\t\t\tconst chunks = [];\n\t\t\tfor (;;) {\n\t\t\t\tconst { done, value } = await reader.read();\n\t\t\t\tif (done) break;\n\t\t\t\tchunks.push(value);\n\t\t\t}\n\t\t\tconst blob = new Blob(chunks, { type: options?.mimeType ?? header.mimeType });\n\t\t\temitter.finish();\n\t\t\treturn {\n\t\t\t\tblob,\n\t\t\t\theader\n\t\t\t};\n\t\t} catch (err) {\n\t\t\temitter.fail();\n\t\t\tthrow err;\n\t\t}\n\t}\n\tasync saveAttachment(input, options) {\n\t\tif (typeof document === \"undefined\") throw new Error(\"saveAttachment requires a browser environment; use downloadBlob elsewhere\");\n\t\tconst { blob, header } = await this.downloadBlob(input, options);\n\t\tconst url = URL.createObjectURL(blob);\n\t\ttry {\n\t\t\tconst anchor = document.createElement(\"a\");\n\t\t\tanchor.href = url;\n\t\t\tanchor.download = options?.fileName ?? header.fileName;\n\t\t\tanchor.click();\n\t\t} finally {\n\t\t\tURL.revokeObjectURL(url);\n\t\t}\n\t}\n\tasync downloadObjectUrl(input, options) {\n\t\tconst { blob, header } = await this.downloadBlob(input, options);\n\t\tconst url = URL.createObjectURL(blob);\n\t\tlet revoked = false;\n\t\treturn {\n\t\t\turl,\n\t\t\theader,\n\t\t\trevoke: () => {\n\t\t\t\tif (revoked) return;\n\t\t\t\trevoked = true;\n\t\t\t\tURL.revokeObjectURL(url);\n\t\t\t}\n\t\t};\n\t}\n\tasync getShareLink(input) {\n\t\tinput.signal?.throwIfAborted();\n\t\tconst target = await this.service.getDownloadTarget(input.ref, {\n\t\t\tdocumentId: input.documentId,\n\t\t\t...input.expiresIn !== void 0 ? { expiresIn: input.expiresIn } : {},\n\t\t\t...input.signal !== void 0 ? { signal: input.signal } : {}\n\t\t});\n\t\tif (target.kind !== \"presigned-get\") throw new Error(\"Public share links require a presigned-capable storage backend (S3); this server answered with an authenticated target\");\n\t\treturn {\n\t\t\turl: target.url,\n\t\t\texpiresAtUtc: target.expiresAtUtc\n\t\t};\n\t}\n\tuploadMany(inputs, options) {\n\t\treturn runWithConcurrency(inputs, (input, index) => this.upload(input, itemProgress(options, index)), batchRunOptions(inputs.length, options));\n\t}\n\t/**\n\t* `concurrency` bounds download-target negotiation, not simultaneous byte\n\t* transfer: each item resolves when its stream is handed over, and the bytes\n\t* move only as the caller reads. Byte progress makes that pre-existing\n\t* behavior visible; it does not change it.\n\t*/\n\tdownloadMany(inputs, options) {\n\t\treturn runWithConcurrency(inputs, (input, index) => this.download(input, itemProgress(options, index)), batchRunOptions(inputs.length, options));\n\t}\n};\nfunction createAttachmentClient(service) {\n\treturn new AttachmentClientImpl(service);\n}\n//#endregion\nexport { AttachmentAlreadyExists, AttachmentNotFound, AttachmentPending, AttachmentService, AttachmentTransferError, DEFAULT_ATTACHMENT_BATCH_CONCURRENCY, DEFAULT_PROGRESS_THROTTLE_MS, HashMismatch, InvalidAttachmentRef, NullAttachmentTransport, ProgressEmitter, RemoteAttachmentStore, RemoteAttachmentUpload, RemoteAttachmentUploadFactory, RemoteReservationStore, ReservationNotFound, RoutingAttachmentService, SizeMismatch, SwitchboardAttachmentTransport, UploadTooLarge, createAttachmentClient, createFetchUploadTransport, createRef, createRemoteAttachmentService, createXhrUploadTransport, parseAttachmentDownloadTarget, parseAttachmentUploadTarget, parseRef, progressFraction, runWithConcurrency, withByteProgress };\n\n//# sourceMappingURL=client.js.map","// Attachment-service accessor + file helpers shared by the attachment-* commands.\nimport { openAsBlob } from \"node:fs\";\nimport { extname } from \"node:path\";\nimport type { CommandContext } from \"../../core/types.js\";\nimport type { AttachmentRef, IAttachmentService } from \"./types.js\";\n\n/**\n * The attachment service of the run's reactor. Never builds the reactor for\n * it: only where the Cli serves (`folders` marks that) or where its reactor\n * is attached to a switchboard, which reaching builds nothing.\n */\nexport async function getAttachmentService(\n ctx: Pick<CommandContext, \"folders\" | \"reactor\" | \"reactorAttached\">,\n): Promise<IAttachmentService | undefined> {\n if (!ctx.folders && !ctx.reactorAttached) return undefined;\n const rc = await ctx.reactor?.();\n return rc?.attachments;\n}\n\nexport function attachmentsUnavailableMessage(): string {\n return (\n \"Attachments need a running reactor (daemon mode) on a switchboard the \" +\n \"Cli attached to. None is available in this context.\"\n );\n}\n\n// Type bridge; the ref format is validated server-side.\nexport function asRef(ref: string): AttachmentRef {\n return ref as AttachmentRef;\n}\n\n// Duck-typed: reactor-attachments duplicates this error across its `.` and `/client` bundles, so instanceof is unreliable.\nexport function isAttachmentAlreadyExists(\n err: unknown,\n): err is { ref: string; hash: string } {\n if (!(err instanceof Error)) return false;\n if (!(\"ref\" in err) || !(\"hash\" in err)) return false;\n return (\n err.constructor.name === \"AttachmentAlreadyExists\" ||\n /already exists/i.test(err.message)\n );\n}\n\n// Extension → MIME; falls back to octet-stream, override via mimeType.\nconst MIME_BY_EXT: Record<string, string> = {\n \".png\": \"image/png\",\n \".jpg\": \"image/jpeg\",\n \".jpeg\": \"image/jpeg\",\n \".gif\": \"image/gif\",\n \".webp\": \"image/webp\",\n \".svg\": \"image/svg+xml\",\n \".pdf\": \"application/pdf\",\n \".json\": \"application/json\",\n \".txt\": \"text/plain\",\n \".md\": \"text/markdown\",\n \".csv\": \"text/csv\",\n};\n\nexport function inferMimeType(filePath: string, override?: string): string {\n if (override) return override;\n return (\n MIME_BY_EXT[extname(filePath).toLowerCase()] ?? \"application/octet-stream\"\n );\n}\n\nexport async function fileToBlob(\n filePath: string,\n mimeType: string,\n): Promise<Blob> {\n return openAsBlob(filePath, { type: mimeType });\n}\n","// Shared attachment-* commands for reactor-backed ph-clint CLIs. Opt-in: spread\n// `...createAttachmentCommands()` into a CLI's `commands` array (like\n// `...createClaudeAuthCommands()`). They self-gate — outside a running reactor\n// they return an \"unavailable\" message rather than erroring.\nimport path from \"node:path\";\nimport { createWriteStream } from \"node:fs\";\nimport { Readable } from \"node:stream\";\nimport { pipeline } from \"node:stream/promises\";\nimport type { ReadableStream as NodeWebReadableStream } from \"node:stream/web\";\nimport { z } from \"zod\";\nimport {\n createAttachmentClient,\n type AttachmentUploadResult,\n} from \"@powerhousedao/reactor-attachments/client\";\nimport { defineCommand } from \"../../core/command.js\";\nimport type { Command } from \"../../core/types.js\";\nimport {\n asRef,\n attachmentsUnavailableMessage,\n fileToBlob,\n getAttachmentService,\n inferMimeType,\n isAttachmentAlreadyExists,\n} from \"./attachment.js\";\n\nconst documentIdSchema = z\n .string()\n .optional()\n .describe(\n \"Document whose operations reference the attachment. A switchboard serves an attachment only through such a document, so a read there needs it.\",\n );\n\nexport function createAttachmentCommands(): Command[] {\n const preprocess = defineCommand({\n id: \"attachment-preprocess\",\n description:\n \"Compute an attachment's content-addressed ref (attachment://v1:<sha256>) from a local file WITHOUT uploading. Embed the returned ref in a document action now, then send the bytes with attachment-upload for the same file after / in parallel with submitting the action.\",\n inputSchema: z.object({\n filePath: z\n .string()\n .describe(\n \"Path to the local file to reference (absolute, or relative to the workdir).\",\n ),\n mimeType: z\n .string()\n .optional()\n .describe(\"MIME type; inferred from the file extension when omitted.\"),\n fileName: z\n .string()\n .optional()\n .describe(\"Stored file name; defaults to the file's basename.\"),\n }),\n execute: async (input, context) => {\n const service = await getAttachmentService(context);\n if (!service) return { text: attachmentsUnavailableMessage() };\n\n const filePath = path.resolve(context.workdir, input.filePath);\n const mimeType = inferMimeType(filePath, input.mimeType);\n const fileName = input.fileName ?? path.basename(filePath);\n const blob = await fileToBlob(filePath, mimeType);\n\n const pre = await createAttachmentClient(service).preprocess(blob, {\n fileName,\n mimeType,\n });\n return {\n text:\n `ref: ${pre.ref}\\n` +\n `hash: ${pre.hash}\\n` +\n `sizeBytes: ${pre.sizeBytes}\\n` +\n `mimeType: ${mimeType}\\n` +\n `fileName: ${fileName}\\n` +\n `Not uploaded yet — embed this ref in the action, then run attachment-upload on the same file to send the bytes.`,\n };\n },\n });\n\n const upload = defineCommand({\n id: \"attachment-upload\",\n description:\n \"Upload a local file to the attachment store and return its content-addressed ref (attachment://v1:<sha256>). The ref is deterministic from the bytes and identical content dedups. Embed the ref in a document action; the action may be submitted before or after this upload.\",\n inputSchema: z.object({\n filePath: z\n .string()\n .describe(\n \"Path to the local file to upload (absolute, or relative to the workdir).\",\n ),\n mimeType: z\n .string()\n .optional()\n .describe(\"MIME type; inferred from the file extension when omitted.\"),\n fileName: z\n .string()\n .optional()\n .describe(\"Stored file name; defaults to the file's basename.\"),\n }),\n execute: async (input, context) => {\n const service = await getAttachmentService(context);\n if (!service) return { text: attachmentsUnavailableMessage() };\n\n const filePath = path.resolve(context.workdir, input.filePath);\n const mimeType = inferMimeType(filePath, input.mimeType);\n const fileName = input.fileName ?? path.basename(filePath);\n const blob = await fileToBlob(filePath, mimeType);\n\n const client = createAttachmentClient(service);\n const pre = await client.preprocess(blob, { fileName, mimeType });\n\n let result: AttachmentUploadResult;\n try {\n result = await client.reserve(pre.options, (handle) =>\n handle.send(pre.blob),\n );\n } catch (err) {\n // Dedup: client.reserve's instanceof catch can miss this across entry bundles, so recover via the deterministic ref.\n if (!isAttachmentAlreadyExists(err)) throw err;\n const header = await service.stat(pre.ref);\n result = { ref: pre.ref, hash: pre.hash, header };\n }\n\n return {\n text:\n `ref: ${result.ref}\\n` +\n `hash: ${result.hash}\\n` +\n `status: ${result.header.status}\\n` +\n `sizeBytes: ${result.header.sizeBytes}\\n` +\n `mimeType: ${result.header.mimeType}\\n` +\n `fileName: ${result.header.fileName}`,\n };\n },\n });\n\n const stat = defineCommand({\n id: \"attachment-stat\",\n description:\n \"Look up an attachment by ref (attachment://v1:<sha256>) and report its status + metadata. status='pending' = reserved but not yet uploaded; 'available' = stored; 'evicted' = metadata known, bytes reclaimed. On a switchboard, pass the documentId of a document whose operations reference the attachment.\",\n inputSchema: z.object({\n ref: z\n .string()\n .describe(\"Attachment ref, e.g. attachment://v1:<sha256hex>.\"),\n documentId: documentIdSchema,\n }),\n execute: async (input, context) => {\n const service = await getAttachmentService(context);\n if (!service) return { text: attachmentsUnavailableMessage() };\n\n try {\n const h = await service.stat(\n asRef(input.ref),\n ...readOptions(input.documentId),\n );\n return {\n text:\n `ref: ${input.ref}\\n` +\n `status: ${h.status}\\n` +\n `mimeType: ${h.mimeType}\\n` +\n `fileName: ${h.fileName}\\n` +\n `sizeBytes: ${h.sizeBytes}\\n` +\n `createdAtUtc: ${h.createdAtUtc}`,\n };\n } catch (err) {\n return {\n text:\n `Not found or error for ${input.ref}: ${(err as Error).message}` +\n documentIdHint(input.documentId),\n };\n }\n },\n });\n\n const get = defineCommand({\n id: \"attachment-get\",\n description:\n \"Download an attachment's bytes by ref (attachment://v1:<sha256>) to a local file. Errors if the attachment is still pending (bytes not yet uploaded). On a switchboard, pass the documentId of a document whose operations reference the attachment.\",\n inputSchema: z.object({\n ref: z\n .string()\n .describe(\"Attachment ref, e.g. attachment://v1:<sha256hex>.\"),\n outPath: z\n .string()\n .describe(\n \"Path to write the bytes to (absolute, or relative to the workdir).\",\n ),\n documentId: documentIdSchema,\n }),\n execute: async (input, context) => {\n const service = await getAttachmentService(context);\n if (!service) return { text: attachmentsUnavailableMessage() };\n\n const outPath = path.resolve(context.workdir, input.outPath);\n try {\n const res = await service.get(\n asRef(input.ref),\n ...readOptions(input.documentId),\n );\n const body = res.body as unknown as NodeWebReadableStream<Uint8Array>;\n await pipeline(Readable.fromWeb(body), createWriteStream(outPath));\n return {\n text:\n `Wrote ${res.header.sizeBytes} bytes to ${outPath}\\n` +\n `ref: ${input.ref}\\n` +\n `mimeType: ${res.header.mimeType}\\n` +\n `fileName: ${res.header.fileName}`,\n };\n } catch (err) {\n return {\n text:\n `Could not get ${input.ref}: ${(err as Error).message}` +\n documentIdHint(input.documentId),\n };\n }\n },\n });\n\n return [preprocess, upload, stat, get];\n}\n\n/** The read options for `documentId`; none without one, as before. */\nfunction readOptions(\n documentId: string | undefined,\n): [] | [{ documentId: string }] {\n return documentId === undefined ? [] : [{ documentId }];\n}\n\n/** Why a read without a document id fails on a switchboard. */\nfunction documentIdHint(documentId: string | undefined): string {\n return documentId === undefined\n ? \"\\nOn a switchboard an attachment is served only through a document \" +\n \"that references it: pass documentId.\"\n : \"\";\n}\n","/**\n * Powerhouse integration for ph-clint: a CLI's reactor is a client of a\n * RUNNING switchboard (`attachDefaultReactor`, which a host runner calls),\n * with its drives, change subscriptions, signing rules and attachment\n * service. clint starts no reactor, switchboard or Connect of its own.\n *\n * All Powerhouse imports are lazy — the library works without them installed.\n */\n\nexport type {\n ReactorContext,\n ReactorSetupContext,\n ReactorConfiguration,\n RemoteReactorConfig,\n RemoteReactorSource,\n DriveConfig,\n EnsureDriveClient,\n DriveEntry,\n FolderEntry,\n FolderOperations,\n SubscriptionConfig,\n DocumentRegistry,\n AnyRegistry,\n RegistryEntry,\n TypedReactorClient,\n TypedDocumentChangeEvent,\n ReactorWrites,\n IAttachmentService,\n AttachmentRef,\n AttachmentResponse,\n AttachmentUploadResult,\n ReserveAttachmentOptions,\n AttachmentHeader,\n} from \"./types.js\";\n\nexport type { InferRegistry, ActionOf } from \"./registry.js\";\nexport { defineRegistry } from \"./registry.js\";\n\nexport { bridgeSubscriptions } from \"./subscriptions.js\";\nexport { ensureDrive } from \"./drive.js\";\nexport { attachRemoteReactor } from \"./remote-reactor.js\";\nexport type {\n AttachRemoteReactorOptions,\n RemoteReactorAttachment,\n} from \"./remote-reactor.js\";\nexport {\n SignerNotReadyError,\n createGatedSigner,\n signerReady,\n policyOfHeader,\n} from \"./signing.js\";\nexport type { SignaturePolicy } from \"./signing.js\";\nexport { createReactorWrites } from \"./writes.js\";\nexport type { ReactorWritesOptions, ReactorWritesHandle } from \"./writes.js\";\nexport { createDocumentChangeTrigger } from \"./change-trigger.js\";\nexport type { DocumentChangeTriggerOptions } from \"./change-trigger.js\";\nexport { isDocType } from \"./type-guard.js\";\nexport { createFolderOperations, createFolderCommands } from \"./folders.js\";\nexport { createAttachmentCommands } from \"./attachment-commands.js\";\nexport {\n getAttachmentService,\n asRef,\n inferMimeType,\n fileToBlob,\n isAttachmentAlreadyExists,\n} from \"./attachment.js\";\n\nimport type { IReactorClient } from \"@powerhousedao/reactor\";\nimport { ensureDrive } from \"./drive.js\";\nimport { bridgeSubscriptions } from \"./subscriptions.js\";\nimport { createReactorWrites } from \"./writes.js\";\nimport type {\n ReactorContext,\n ReactorSetupContext,\n DriveEntry,\n DocumentRegistry,\n AnyRegistry,\n IAttachmentService,\n RemoteReactorConfig,\n RemoteReactorSource,\n TypedReactorClient,\n} from \"./types.js\";\n\n/**\n * Options for attachDefaultReactor(): where the switchboard is, how the\n * client signs and authenticates, and what the CLI's reactor holds there.\n */\nexport interface AttachDefaultReactorOptions<\n R extends DocumentRegistry = AnyRegistry,\n> extends RemoteReactorConfig<R> {\n /** A switchboard drive address, `<switchboard>/d/<slug>`; its GraphQL\n * endpoint or bare origin attach too, but name no drive. */\n url: string;\n}\n\n/**\n * The `ReactorConfiguration.remote` a runner attaches with: the config as\n * given, or the function's answer for this setup context. None: `{}`.\n */\nexport async function resolveRemoteReactorConfig<\n R extends DocumentRegistry = AnyRegistry,\n>(\n source: RemoteReactorSource<R> | undefined,\n setup: ReactorSetupContext<R>,\n): Promise<RemoteReactorConfig<R>> {\n if (typeof source === \"function\") return source(setup);\n return source ?? {};\n}\n\n/**\n * The attachment service of the switchboard at `endpoint`. Its\n * `/attachments/*` routes mount at the host root, so the origin is used.\n */\nasync function remoteAttachmentService(\n endpoint: string,\n jwtHandler: ((url: string) => Promise<string | undefined>) | undefined,\n): Promise<IAttachmentService> {\n const { createRemoteAttachmentService } =\n await import(\"@powerhousedao/reactor-attachments\");\n return createRemoteAttachmentService({\n remoteUrl: new URL(endpoint).origin,\n ...(jwtHandler ? { jwtHandler } : {}),\n });\n}\n\n/** The id of the drive a switchboard serves under `slug`. */\nasync function driveOfAddress(\n client: IReactorClient,\n slug: string,\n endpoint: string,\n): Promise<string> {\n try {\n return (await client.get(slug)).header.id;\n } catch (cause) {\n throw new Error(\n `The switchboard at ${endpoint} serves no drive \"${slug}\": the drive address must name one of its drives.`,\n { cause },\n );\n }\n}\n\n/**\n * Build a ReactorContext on a RUNNING switchboard, with the drives and\n * subscriptions the options ask for. The default drive is the first personal\n * drive the options ask for, else the first, else the one the address names.\n * The signer, its rules and its watch go to\n * `createReactorWrites`, which emits `powerhouse:writes:ready` on `ctx.emit`;\n * a signer change also reconnects the realtime socket with the current\n * bearer. Without `ctx.attachments` the context gets the switchboard's own\n * attachment service, authenticated by `ctx.attachmentJwtHandler`, else by\n * `tokenProvider`. `shutdown` releases only this process's side (the\n * bridged subscriptions, the signer watch, the client) and runs once.\n */\nexport async function attachDefaultReactor<\n R extends DocumentRegistry = AnyRegistry,\n>(\n ctx: ReactorSetupContext<R>,\n options: AttachDefaultReactorOptions<R>,\n): Promise<ReactorContext<R>> {\n const { attachRemoteReactor } = await import(\"./remote-reactor.js\");\n const { switchboardOfDrive } =\n await import(\"@powerhousedao/shared/host-tokens\");\n\n // A socket presents the credentials it opened with until it is replaced,\n // and the bearer follows the signer's user.\n let credentialsChanged = (): void => undefined;\n const { onSignerChange } = options;\n const handle = createReactorWrites({\n signer: options.signer,\n legacyDocuments: options.legacyDocuments,\n accepts: options.accepts,\n ...(onSignerChange\n ? {\n onSignerChange: (listener: () => void) =>\n onSignerChange(() => {\n credentialsChanged();\n listener();\n }),\n }\n : {}),\n ...(ctx.emit ? { emit: ctx.emit } : {}),\n });\n\n let attachment: Awaited<ReturnType<typeof attachRemoteReactor>>;\n try {\n attachment = await attachRemoteReactor({\n url: options.url,\n documentModels: options.documentModels ?? [],\n ...(handle.signer ? { signer: handle.signer } : {}),\n ...(options.tokenProvider\n ? { tokenProvider: options.tokenProvider }\n : {}),\n });\n } catch (error) {\n handle.stop();\n throw error;\n }\n const client = attachment.client as IReactorClient & {\n dispose?: () => void;\n notifyCredentialsChanged?: () => void;\n };\n credentialsChanged = () => client.notifyCredentialsChanged?.();\n\n const driveConfigs =\n options.drives ??\n (options.drive ? [{ ...options.drive, role: \"personal\" as const }] : []);\n const drives: DriveEntry[] = [];\n for (const cfg of driveConfigs) {\n const drive = await ensureDrive(client, cfg);\n // A drive the host creates later is not listed yet.\n if (drive.deferred) continue;\n drives.push({ id: drive.id, name: drive.name, role: cfg.role });\n }\n const personal = drives.find((d) => d.role === \"personal\");\n const addressed = switchboardOfDrive(options.url);\n let driveId = personal?.id ?? drives[0]?.id ?? \"\";\n let driveUrl =\n addressed && driveId ? `${addressed.base}/d/${driveId}` : undefined;\n if (!driveId && addressed) {\n driveId = await driveOfAddress(client, addressed.slug, attachment.endpoint);\n driveUrl = options.url;\n }\n\n let unsubscribe: (() => void) | undefined;\n if (options.subscriptions && ctx.emit) {\n unsubscribe = bridgeSubscriptions<R>(\n client,\n options.subscriptions,\n ctx.emit,\n );\n }\n\n const { tokenProvider } = options;\n const attachments =\n ctx.attachments ??\n (await remoteAttachmentService(\n attachment.endpoint,\n ctx.attachmentJwtHandler ?? (tokenProvider && (() => tokenProvider())),\n ));\n\n let stopped = false;\n const result: ReactorContext<R> = {\n client: client as unknown as TypedReactorClient<R>,\n driveId,\n personalDriveId: personal?.id,\n drives,\n switchboardUrl: attachment.endpoint,\n ...(driveUrl ? { driveUrl } : {}),\n attachments,\n writes: handle.writes,\n shutdown() {\n if (stopped) return Promise.resolve();\n stopped = true;\n unsubscribe?.();\n handle.stop();\n client.dispose?.();\n return Promise.resolve();\n },\n };\n\n ctx.emit?.(\"powerhouse:ready\", { driveId });\n\n return result;\n}\n"],"x_google_ignoreList":[10,11,12],"mappings":";;;;;;;;;;;;;;AASA,SAAgB,cAMd,SACsC;CACtC,IAAI,QAAQ,cAAc,QAAQ,WAAW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ACT,IAAI,SAAS,OAAO,QAAQ,QAAQ;GACpC,UAAU;GACV,cAAc;GACd,OAAO,KAAK;GACZ,OAAO,UAAU;GACjB,OAAO,QAAQ,QAAQ;EACzB;CACF;CAEA,IAAI,OAAO,oBAAoB,EAAE,QAAQ,CAAC;CAE1C,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"powerhouse-3XZmdY3_.mjs","names":["isAttachmentAlreadyExists"],"sources":["../src/core/command.ts","../src/integrations/powerhouse/change-trigger.ts","../src/integrations/powerhouse/registry.ts","../src/integrations/powerhouse/subscriptions.ts","../src/integrations/powerhouse/drive.ts","../src/integrations/powerhouse/signing.ts","../src/integrations/powerhouse/writes.ts","../src/integrations/powerhouse/type-guard.ts","../src/integrations/powerhouse/folders.ts","../../reactor-attachments/dist/switchboard-attachment-transport-BH3ZAmxE.js","../../../node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/utils.js","../../../node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/_md.js","../../../node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/sha2.js","../../reactor-attachments/dist/hash-BobbR4r4.js","../../reactor-attachments/dist/client.js","../src/integrations/powerhouse/attachment.ts","../src/integrations/powerhouse/attachment-commands.ts","../src/integrations/powerhouse/index.ts"],"sourcesContent":["import type { z } from \"zod\";\nimport type { DocumentRegistry } from \"../integrations/powerhouse/types.js\";\nimport { getSchemaFields } from \"./schema.js\";\nimport type { Command } from \"./types.js\";\n\n/**\n * Define a command — the atomic unit of ph-clint.\n * Compatible with Mastra createTool() shape.\n */\nexport function defineCommand<\n TInput extends z.ZodType,\n TOutput = unknown,\n TConfig = Record<string, unknown>,\n R extends DocumentRegistry = any,\n>(\n options: Command<TInput, TOutput, TConfig, R>,\n): Command<TInput, TOutput, TConfig, R> {\n if (options.positional && options.positional.length > 0) {\n const fields = getSchemaFields(options.inputSchema);\n const fieldMap = new Map(fields.map((f) => [f.key, f]));\n const seen = new Set<string>();\n let sawOptional = false;\n for (const key of options.positional) {\n const field = fieldMap.get(key);\n if (!field) {\n throw new Error(\n `Command '${options.id}': positional field '${key}' is not in inputSchema`,\n );\n }\n if (seen.has(key)) {\n throw new Error(\n `Command '${options.id}': positional field '${key}' listed more than once`,\n );\n }\n seen.add(key);\n const isOptional = field.isOptional || field.hasDefault;\n if (sawOptional && !isOptional) {\n throw new Error(\n `Command '${options.id}': required positional '${key}' may not follow an optional positional`,\n );\n }\n if (isOptional) sawOptional = true;\n }\n }\n return options;\n}\n","/**\n * `createDocumentChangeTrigger` — typed helper that collapses the common\n * \"subscribe to document changes, coalesce, load docs, narrow, call onChange\"\n * pattern into a single definition.\n *\n * Supports watching one or multiple document types. When `documentId` is\n * provided, loads a single document (wrapped in an array). When omitted,\n * loads all matching documents via `client.find()`.\n *\n * The helper owns subscription setup, per-event filtering by documentType\n * (and optional literal documentId), the pending counter, initial\n * reconcile, document loading, and registry-driven type narrowing. Impl\n * code only writes the `onChange` handler (plus an optional `filter` and\n * an optional `documentId` resolver for impl-specific lookup).\n */\nimport type { DocumentRegistry, AnyRegistry } from \"./types.js\";\nimport type { Trigger, TriggerContext, WorkItem } from \"../../core/types.js\";\n\nexport interface DocumentChangeTriggerOptions<\n R extends DocumentRegistry,\n T extends keyof R & string,\n TConfig = Record<string, unknown>,\n TState extends { pending: number } = { pending: number },\n> {\n /** Unique trigger id for logging/routing. */\n id: string;\n\n /** The document type(s) to watch. Must be key(s) in the registry. */\n documentType: T | T[];\n\n /**\n * The specific document id (or a function that resolves one from context).\n * When omitted, the helper loads ALL documents of the watched type(s)\n * via `client.find()` and passes the full array to `onChange`.\n *\n * When a function is provided, it's resolved lazily on each poll. Returning\n * `undefined` skips the tick.\n */\n documentId?:\n | string\n | ((\n ctx: TriggerContext<TState, TConfig, R>,\n ) => Promise<string | undefined>);\n\n /**\n * Fire once on startup before any event arrives — useful for reconciling\n * against the current document state. Default: true.\n */\n initialReconcile?: boolean;\n\n /**\n * Optional predicate: called per-document after loading, before onChange.\n * Return false to exclude a document from the batch. If all documents\n * are filtered out, onChange is not called.\n */\n filter?: (\n doc: R[T][\"document\"],\n ctx: TriggerContext<TState, TConfig, R>,\n ) => boolean | Promise<boolean>;\n\n /**\n * User's change handler. Receives an array of loaded, type-narrowed\n * documents and the full trigger context. Returns a work item for the\n * routine loop to execute (or null to skip).\n */\n onChange: (\n docs: Array<R[T][\"document\"]>,\n ctx: TriggerContext<TState, TConfig, R>,\n ) => Promise<WorkItem | null>;\n\n /**\n * Call `onChange` even when zero documents are found. Default: false.\n * Useful for triggers that need to perform work (e.g. bootstrapping from\n * disk) regardless of whether any documents exist yet.\n */\n callOnEmpty?: boolean;\n\n /**\n * Optional initial state for the trigger's private slot. Defaults to\n * `{ pending: 0 }`. When supplied, the shape MUST include a `pending:\n * number` field — the helper bumps and drains it internally.\n */\n state?: () => TState;\n}\n\n/**\n * Build a Trigger that listens for document change events on the event bus,\n * coalesces them, loads matching documents, narrows to the registered type,\n * and hands them to the user's onChange handler.\n *\n * Runtime behavior:\n * 1. `setup()` subscribes to `powerhouse:document:changed`. For each event,\n * if any documentType matches (and, when `documentId` is a literal\n * string, the id also matches), bump the pending counter.\n * 2. If `initialReconcile !== false`, `setup()` bumps pending once on\n * startup so the first poll reconciles without waiting for an event.\n * 3. `poll()` returns null unless pending > 0. When pending > 0:\n * - If `documentId` is set: load single doc, wrap in `[doc]`\n * - If `documentId` is omitted: `find()` all docs of matching type(s)\n * Applies `filter` per-doc, then calls `onChange(docs, ctx)`.\n * 4. pending is reset to 0 at the start of each poll drain — multiple\n * events within a tick coalesce to one `onChange` call.\n */\nexport function createDocumentChangeTrigger<\n R extends DocumentRegistry = AnyRegistry,\n T extends keyof R & string = keyof R & string,\n TConfig = Record<string, unknown>,\n TState extends { pending: number } = { pending: number },\n>(\n options: DocumentChangeTriggerOptions<R, T, TConfig, TState>,\n): Trigger<TState, TConfig, R> {\n const initialReconcile = options.initialReconcile !== false;\n const types: T[] = Array.isArray(options.documentType)\n ? options.documentType\n : [options.documentType];\n\n return {\n id: options.id,\n type: \"condition\",\n state: options.state ?? (() => ({ pending: 0 }) as TState),\n\n async setup(ctx) {\n const log = ctx.context.log;\n const on = ctx.context.on;\n if (!on) {\n log?.debug(\n `[${options.id}] no event bus on CoreContext — poll-only mode`,\n );\n if (initialReconcile) ctx.state.pending = 1;\n return;\n }\n\n on(\"powerhouse:document:changed\", (payload) => {\n const documents = payload.documents ?? [];\n const matches = documents.some((d) =>\n types.includes(d.header?.documentType as T),\n );\n if (!matches) return;\n\n if (typeof options.documentId === \"string\") {\n const ids = documents.map((d) => d.header?.id);\n if (!ids.includes(options.documentId)) return;\n }\n\n ctx.state.pending += 1;\n log?.debug(\n `[${options.id}] queued change (pending=${ctx.state.pending})`,\n );\n });\n\n // Writes became possible (the agent's signer got its user): look at\n // every matching document again, since one skipped earlier for want of\n // a signature may be waiting.\n on(\"powerhouse:writes:ready\", () => {\n ctx.state.pending += 1;\n });\n\n if (initialReconcile) ctx.state.pending = 1;\n },\n\n async poll(ctx): Promise<WorkItem | null> {\n if (!ctx.state.pending) return null;\n ctx.state.pending = 0;\n\n const reactor = await ctx.reactor();\n if (!reactor) {\n ctx.context.log?.debug(\n `[${options.id}] no reactor available, skipping`,\n );\n return null;\n }\n\n let docs: Array<R[T][\"document\"]>;\n\n if (options.documentId) {\n // Single-doc path\n const docId =\n typeof options.documentId === \"function\"\n ? await options.documentId(ctx)\n : options.documentId;\n if (!docId) {\n ctx.context.log?.debug(\n `[${options.id}] no target document id resolved, skipping`,\n );\n return null;\n }\n const doc = await reactor.client.get<T>(docId);\n docs = [doc];\n } else {\n // Multi-doc path: find all matching documents.\n // The native Reactor SearchFilter uses `type` (singular string).\n // ph-clint's TypedReactorClient remaps to `documentTypes` (plural)\n // for type-safety, but the reactor ignores that field at runtime.\n // We pass `type` directly to the underlying IReactorClient.\n const allDocs: Array<R[T][\"document\"]> = [];\n for (const t of types) {\n const result = await reactor.client.find<T>({ type: t } as Parameters<\n typeof reactor.client.find<T>\n >[0]);\n const found = result?.results ?? [];\n allDocs.push(...(found as Array<R[T][\"document\"]>));\n }\n docs = allDocs;\n if (docs.length === 0 && !options.callOnEmpty) return null;\n }\n\n if (options.filter) {\n const filtered: Array<R[T][\"document\"]> = [];\n for (const doc of docs) {\n if (await options.filter(doc, ctx)) filtered.push(doc);\n }\n if (filtered.length === 0) return null;\n docs = filtered;\n }\n\n return options.onChange(docs, ctx);\n },\n };\n}\n","/**\n * DocumentRegistry construction + inference helpers.\n *\n * Impl projects build a registry with `defineRegistry([Module1, Module2] as const)`\n * to give the framework typed access to registered document models without\n * having to pass generic parameters at every call site.\n */\n\nimport type {\n DocumentModelModule,\n PHDocument,\n Action,\n PHBaseState,\n} from \"document-model\";\nimport type { DocumentRegistry, RegistryEntry } from \"./types.js\";\n\n/**\n * Extract the action union from a DocumentModelModule.\n *\n * `DocumentModelModule.actions` is `{ [actionName]: (input) => Action }` — the\n * return types of those creators form the module's action union.\n *\n * If a module's actions map isn't typed tightly enough (because the module\n * was annotated with `: DocumentModelModule<…>` instead of `satisfies`), the\n * union collapses to `Action`. Not a correctness problem — just a DX\n * degradation for that one module's execute/executeAsync narrowing.\n */\nexport type ActionOf<M> = M extends { actions: infer Actions }\n ? Actions extends Record<string, (...args: never[]) => infer A>\n ? A\n : Action\n : Action;\n\n/**\n * Infer a DocumentRegistry from a readonly tuple of DocumentModelModule instances.\n *\n * Literal inference requires each module's `documentModel.id` to be a literal\n * type. Phase 4 changes codegen to emit modules with `as const satisfies\n * DocumentModelModule<…>` so inference produces a typed registry. Modules\n * typed with `:` annotations erase `id` to `string` and produce a\n * single-keyed `{ [x: string]: RegistryEntry<...> }` registry — narrowing\n * still works when callers pass a literal `T`, but `keyof R & string`\n * collapses to `string` (no autocomplete for documentTypes lists).\n */\nexport type InferRegistry<T extends ReadonlyArray<DocumentModelModule<any>>> = {\n [\n M in T[number] as Extract<M[\"documentModel\"][\"global\"][\"id\"], string>\n ]: M extends DocumentModelModule<infer S>\n ? RegistryEntry<S, ActionOf<M>>\n : never;\n};\n\n/**\n * Build a DocumentRegistry from a tuple of DocumentModelModules.\n *\n * ```ts\n * const registry = defineRegistry([PhClintProject, DocumentDrive] as const);\n * // typeof registry:\n * // {\n * // 'powerhouse/ph-clint-project': RegistryEntry<PhClintProjectPHState, PhClintProjectAction>;\n * // 'powerhouse/document-drive': RegistryEntry<DocumentDrivePHState, DocumentDriveAction>;\n * // }\n * ```\n *\n * Runtime value is a plain object keyed by `documentModel.id`. Consumers can\n * introspect it to list registered types; Phase 3's\n * `createDocumentChangeTrigger` also uses it for runtime lookup.\n */\nexport function defineRegistry<\n const T extends ReadonlyArray<DocumentModelModule<any>>,\n>(modules: T): InferRegistry<T> {\n const out: Record<string, DocumentModelModule<any>> = {};\n for (const mod of modules) {\n out[mod.documentModel.global.id] = mod;\n }\n return out as unknown as InferRegistry<T>;\n}\n\n// Re-export for convenience so impl code can import from a single module.\nexport type { DocumentRegistry, RegistryEntry };\nexport type { PHDocument, Action, PHBaseState };\n","/**\n * Subscription bridge — maps Reactor document change events\n * to the ph-clint event bus.\n */\n\nimport type {\n IReactorClient,\n DocumentChangeEvent,\n SearchFilter,\n} from \"@powerhousedao/reactor\";\nimport type {\n SubscriptionConfig,\n DocumentRegistry,\n AnyRegistry,\n} from \"./types.js\";\nimport type { EmitFn } from \"../../core/types.js\";\n\n/**\n * Bridge Reactor document subscriptions to the ph-clint event bus.\n *\n * @param client - The reactor client (in-process or remote)\n * @param subscriptions - Filter configuration for which document changes to bridge\n * @param emit - Event bus emit function from CommandContext\n * @returns Unsubscribe function\n */\nexport function bridgeSubscriptions<R extends DocumentRegistry = AnyRegistry>(\n client: IReactorClient,\n subscriptions: SubscriptionConfig<R>,\n emit: EmitFn<R>,\n): () => void {\n // The runtime SearchFilter in @powerhousedao/reactor doesn't have\n // `documentTypes`; ph-clint's high-level SubscriptionConfig exposes it and\n // we forward it as an extra field. The Reactor currently ignores unknown\n // keys — this matches pre-existing behavior.\n const search: SearchFilter & { documentTypes?: string[] } = {};\n if (subscriptions.documentTypes) {\n search.documentTypes = subscriptions.documentTypes as string[];\n }\n\n return client.subscribe(search, (event: DocumentChangeEvent) => {\n try {\n switch (event.type) {\n case \"created\":\n for (const doc of event.documents ?? []) {\n emit(\"powerhouse:document:created\", {\n documentId: doc.header.id,\n documentType: doc.header.documentType as keyof R & string,\n });\n }\n break;\n case \"updated\":\n emit(\"powerhouse:document:changed\", {\n changeType: \"updated\",\n documents: event.documents as Array<\n R[keyof R & string][\"document\"]\n >,\n });\n break;\n case \"deleted\":\n for (const doc of event.documents ?? []) {\n emit(\"powerhouse:document:deleted\", { documentId: doc.header.id });\n }\n break;\n }\n } catch {\n // Don't crash the event bus on subscription handler errors\n }\n });\n}\n","/**\n * Drive management — find or create drives on startup.\n */\n\nimport type { PHBaseState, PHDocument } from \"document-model\";\nimport type { DriveConfig, EnsureDriveClient } from \"./types.js\";\n\nconst DRIVE_DOCUMENT_TYPE = \"powerhouse/document-drive\" as const;\n\n/**\n * Ensure a drive exists, matching by name. On first run, creates a new drive.\n * On subsequent runs, finds the existing one by name.\n *\n * Works on a client alone, in-process or remote: drives are documents of type\n * `powerhouse/document-drive`, listed with `client.find({ type })`, built\n * with `client.newDocument()` and created, already named, with one\n * `client.write.create()`. Those three are what both the in-process\n * `IReactorClient` and `GraphQLReactorClient` (which has no\n * `write.createEmpty` or `write.rename`) offer. A Cli passes its own\n * `ReactorContext.client` as it is (see `EnsureDriveClient`).\n *\n * @param client - The reactor client the drive is looked up and created with\n * @param driveConfig - Optional drive name/icon configuration and hooks\n * @returns The drive ID and name; `deferred` (and id '') when `canCreate`\n * held back a drive that does not exist yet\n */\nexport async function ensureDrive(\n client: EnsureDriveClient,\n driveConfig?: DriveConfig,\n): Promise<{ id: string; name: string; deferred?: boolean }> {\n const driveName = driveConfig?.name ?? \"default\";\n const wantedId = driveConfig?.id;\n const preferredEditor = driveConfig?.preferredEditor;\n\n // A host-resolved id (e.g. a pointer to a drive created earlier) wins.\n const resolved = await driveConfig?.resolveId?.(client);\n if (resolved) return { id: resolved, name: driveName };\n\n const matchByName = driveConfig?.matchByName !== false;\n const existing =\n wantedId || matchByName ? await findDrives(client) : ([] as PHDocument[]);\n if (existing.length) {\n // If a deterministic ID was requested, check if it already exists\n if (wantedId) {\n const match = existing.find((doc) => doc.header.id === wantedId);\n if (match) return { id: wantedId, name: driveName };\n }\n\n // Match by name\n for (const doc of matchByName ? existing : []) {\n const named = doc as unknown as {\n name?: string;\n header?: { name?: string };\n state?: { global?: { name?: string } };\n };\n const docName =\n named.name ?? named.header?.name ?? named.state?.global?.name;\n if (docName === driveName) {\n return { id: doc.header.id, name: driveName };\n }\n }\n // No name match — if default name and single drive, use it\n if (matchByName && driveName === \"default\" && existing.length === 1) {\n return { id: existing[0].header.id, name: driveName };\n }\n }\n\n if (driveConfig?.canCreate && !driveConfig.canCreate()) {\n return { id: \"\", name: driveName, deferred: true };\n }\n\n // Create the drive in one write, named in its global state and on its\n // header, as the switchboard's default drives\n // (apps/switchboard/src/utils.mts:181-201) and Connect's addDrive\n // (packages/reactor-browser/src/actions/drive.ts:143-184) are. `name` and\n // `meta` are mutable header fields, outside the derived id and header\n // signature of a v2-required drive. Only a legacy drive can take a chosen id.\n const doc = await client.newDocument(DRIVE_DOCUMENT_TYPE, {\n initialState: { global: { name: driveName } } as Partial<PHBaseState>,\n ...(wantedId ? { signaturePolicy: \"legacy\" as const, id: wantedId } : {}),\n });\n doc.header.name = driveName;\n if (preferredEditor) {\n doc.header.meta = { ...doc.header.meta, preferredEditor };\n }\n const created = await (await client.write.create(doc)).document();\n const driveId = created.header.id;\n\n await driveConfig?.onCreated?.(driveId);\n return { id: driveId, name: driveName };\n}\n\n/** Every drive document the client serves, across result pages. */\nasync function findDrives(client: EnsureDriveClient): Promise<PHDocument[]> {\n const drives: PHDocument[] = [];\n let page = await client.find({ type: DRIVE_DOCUMENT_TYPE });\n drives.push(...page.results);\n while (page.next) {\n page = await page.next();\n drives.push(...page.results);\n }\n return drives;\n}\n","/**\n * The agent's signer and the rules for what it may write.\n *\n * Client-agnostic: nothing here calls a reactor. A host that holds an\n * identity (a signer whose `user` is set once the owner has signed in or\n * delegated to it) wraps it with `createGatedSigner`, so a write that needs a\n * signature while the signer has no user is refused with\n * `SignerNotReadyError` instead of going out unsigned. `canWrite` answers,\n * without a reactor call, whether the agent may write a document right now;\n * triggers read it through `ReactorContext.writes` (see `writes.ts`).\n */\nimport type { SignaturePolicy } from \"@powerhousedao/shared/document-model\";\n\nexport type { SignaturePolicy };\n\n/** Structural slice of document-model's `ISigner` this module touches. */\nexport interface SignerLike {\n user?: { address: string; networkId?: string; chainId?: number };\n app?: { name?: string; key: string };\n signAction: (...args: never[]) => Promise<unknown>;\n}\n\n/** A document header as far as the write rules read it. */\nexport interface DocumentHeaderLike {\n header: {\n id: string;\n documentType?: string;\n protocolVersions?: Record<string, number> | null;\n };\n}\n\n/** The agent cannot sign yet: its signer has no user. */\nexport class SignerNotReadyError extends Error {\n constructor(what = \"this write\") {\n super(`The agent cannot sign ${what} yet: it has no signed-in identity.`);\n this.name = \"SignerNotReadyError\";\n }\n}\n\n/** True when the signer can sign as a user. */\nexport function signerReady(signer: SignerLike): boolean {\n return Boolean(signer.user?.address);\n}\n\n/** The policy a header carries (same rule as document-model's `signaturePolicyOf`). */\nexport function policyOfHeader(\n header: DocumentHeaderLike[\"header\"] | undefined,\n): SignaturePolicy {\n const version = header?.protocolVersions?.signature;\n return typeof version === \"number\" && version >= 2 ? \"v2-required\" : \"legacy\";\n}\n\n/**\n * The signer, refusing to sign while it has no user. Everything else is read\n * through to the live signer.\n */\nexport function createGatedSigner<S extends SignerLike>(signer: S): S {\n return new Proxy(signer, {\n get(target, prop, receiver) {\n if (prop === \"signAction\") {\n return async (...args: never[]) => {\n if (!signerReady(target)) throw new SignerNotReadyError();\n return target.signAction(...args);\n };\n }\n const value = Reflect.get(target, prop, receiver) as unknown;\n return typeof value === \"function\"\n ? (value as (...a: unknown[]) => unknown).bind(target)\n : value;\n },\n });\n}\n\nexport interface WriteRules {\n ready(): boolean;\n /**\n * `refuse`: the agent leaves legacy documents alone.\n * `sign-when-ready`: legacy documents are writable whether or not the\n * signer has a user.\n */\n legacyDocuments: \"refuse\" | \"sign-when-ready\";\n /** Which documents the agent acts on by itself. Only read by `canWrite`. */\n accepts?: (document: DocumentHeaderLike) => boolean;\n}\n\n/** Whether the agent may write `document` right now (no reactor call). */\nexport function canWrite(\n rules: WriteRules,\n document: DocumentHeaderLike,\n): boolean {\n if (rules.accepts && !rules.accepts(document)) return false;\n if (policyOfHeader(document.header) === \"v2-required\") return rules.ready();\n return rules.legacyDocuments !== \"refuse\";\n}\n","/**\n * `ReactorContext.writes` and the `powerhouse:writes:ready` event, built once\n * for whichever factory makes the reactor: `attachDefaultReactor`, or one\n * wrapping `attachRemoteReactor` in `configureReactor.create` (it hands the\n * returned `signer` to the client).\n */\nimport type { ISigner } from \"@powerhousedao/shared/document-model\";\nimport {\n SignerNotReadyError,\n canWrite,\n createGatedSigner,\n signerReady,\n type DocumentHeaderLike,\n type WriteRules,\n} from \"./signing.js\";\nimport type { ReactorWrites } from \"./types.js\";\n\nexport interface ReactorWritesOptions {\n /**\n * The agent's signer. Read on every write, so a signer whose `user` is set\n * later (a sign-in) takes effect without rebuilding the reactor. Without\n * one there is nothing to wait for: `ready()` is always true.\n */\n signer?: ISigner;\n /** See `WriteRules.legacyDocuments`. Default: `sign-when-ready`. */\n legacyDocuments?: WriteRules[\"legacyDocuments\"];\n /**\n * Which documents the agent acts on by itself (`writes.canWrite`, read by\n * triggers such as the chat watch). Writes the agent is asked to make\n * follow only the signature rules.\n */\n accepts?: (document: DocumentHeaderLike) => boolean;\n /**\n * Subscribe to changes of the signer's user; `powerhouse:writes:ready` is\n * emitted when writes become possible. Returns an unsubscribe function.\n */\n onSignerChange?: (listener: () => void) => () => void;\n /** Where `powerhouse:writes:ready` goes: the factory's `ctx.emit`. */\n emit?: (\n event: \"powerhouse:writes:ready\",\n data: Record<string, never>,\n ) => void;\n}\n\nexport interface ReactorWritesHandle {\n /** For `ReactorContext.writes`. */\n writes: ReactorWrites;\n /**\n * The signer to give the reactor client (`attachRemoteReactor({ signer })`),\n * resolved per push: the gated signer, or `SignerNotReadyError` while it\n * has no user. The resolver throws rather than returning undefined because\n * `GraphQLReactorClient` pushes unsigned when it gets no signer, and checks\n * `user` itself before it would call the gated `signAction`. Undefined\n * without a signer.\n *\n * Limit: the client resolves its signer before it knows the document, so\n * while there is no user this refuses a push to a legacy document too,\n * though `legacyDocuments: \"sign-when-ready\"` lets `canWrite` pass it.\n * Passing the target document to the resolver would lift it; until then\n * give a signer only where the documents written are v2.\n */\n signer?: () => ISigner;\n /** Stops watching the signer; call it from `ReactorContext.shutdown`. */\n stop(): void;\n}\n\n/** See {@link ReactorWritesOptions} and {@link ReactorWritesHandle}. */\nexport function createReactorWrites(\n options: ReactorWritesOptions = {},\n): ReactorWritesHandle {\n const source = options.signer;\n const rules: WriteRules = {\n ready: () => (source ? signerReady(source) : true),\n legacyDocuments: options.legacyDocuments ?? \"sign-when-ready\",\n accepts: options.accepts,\n };\n const writes: ReactorWrites = {\n ready: rules.ready,\n canWrite: (document) => canWrite(rules, document),\n };\n\n let signer: (() => ISigner) | undefined;\n if (source) {\n const gated = createGatedSigner(source);\n signer = () => {\n if (!signerReady(source)) throw new SignerNotReadyError();\n return gated;\n };\n }\n\n let wasReady = rules.ready();\n const unsubscribe = options.onSignerChange?.(() => {\n const now = rules.ready();\n if (now && !wasReady) options.emit?.(\"powerhouse:writes:ready\", {});\n wasReady = now;\n });\n\n return {\n writes,\n signer,\n stop: () => unsubscribe?.(),\n };\n}\n","import type { DocumentRegistry } from \"./types.js\";\n\n/**\n * Type guard for discriminated narrowing in multi-type onChange handlers.\n *\n * Usage:\n * onChange(docs, ctx) {\n * for (const doc of docs) {\n * if (isDocType(doc, 'powerhouse/ph-clint-project')) {\n * // doc is narrowed to R['powerhouse/ph-clint-project']['document']\n * }\n * }\n * }\n */\nexport function isDocType<\n R extends DocumentRegistry,\n T extends keyof R & string,\n>(doc: R[keyof R & string][\"document\"], type: T): doc is R[T][\"document\"] {\n return doc.header?.documentType === type;\n}\n","/**\n * FolderOperations — programmatic API for managing documents\n * in the agent's personal drive using the drive's internal node tree.\n *\n * Folders and file references are stored as nodes in the drive document's\n * `state.global.nodes` array, managed via ADD_FOLDER and ADD_FILE operations.\n * This is distinct from the parent-child document graph (addRelationship/getOutgoingRelationships).\n *\n * Also exports `createFolderCommands()` to auto-generate CLI commands\n * that wrap the folder operations.\n */\nimport { randomUUID } from \"node:crypto\";\nimport { z } from \"zod\";\nimport type { Action } from \"document-model\";\nimport type { TypedReactorClient } from \"./types.js\";\nimport type { FolderEntry, FolderOperations } from \"./types.js\";\nimport type { Command } from \"../../core/types.js\";\nimport type { Logger } from \"../../core/types.js\";\n\nconst TAG = \"[folders]\";\n\n/** Node shape from drive state.global.nodes */\ninterface DriveNode {\n id: string;\n name: string;\n kind: string;\n parentFolder?: string | null;\n documentType?: string;\n}\n\nfunction isFolder(node: DriveNode): boolean {\n return node.kind === \"folder\";\n}\n\n/**\n * Read the drive document's internal nodes array.\n */\nasync function getDriveNodes(\n client: TypedReactorClient<any>,\n driveId: string,\n): Promise<DriveNode[]> {\n const drive = (await client.get(driveId)) as any;\n return (drive?.state?.global?.nodes ?? []) as DriveNode[];\n}\n\n/**\n * Create a FolderOperations instance backed by the reactor client.\n *\n * Folders are nodes inside the drive document's `state.global.nodes` array,\n * created via `ADD_FOLDER` and `ADD_FILE` drive operations executed on the\n * personal drive. This is separate from the document relationship graph.\n * Only calls the remote `GraphQLReactorClient` has too are made, so the same\n * operations work on an in-process and on an attached reactor.\n */\nexport function createFolderOperations(\n client: TypedReactorClient<any>,\n personalDriveId: string,\n log?: Logger,\n): FolderOperations {\n /**\n * Lazy-load drive action creators from @powerhousedao/shared.\n * Kept lazy so that importing folders.ts doesn't pull in the entire\n * @powerhousedao/shared tree — which is an optional peer dependency\n * and won't be installed in non-Powerhouse projects.\n */\n let _driveActions: {\n addFolder: (input: {\n id: string;\n name: string;\n parentFolder: string | null;\n }) => Action;\n addFile: (input: {\n id: string;\n name: string;\n documentType: string;\n parentFolder: string | null;\n }) => Action;\n deleteNode: (input: { id: string }) => Action;\n } | null = null;\n\n async function getDriveActions() {\n if (!_driveActions) {\n const mod = (await import(\"@powerhousedao/shared/document-drive\")) as any;\n _driveActions = {\n addFolder: mod.addFolder,\n addFile: mod.addFile,\n deleteNode: mod.deleteNode,\n };\n }\n return _driveActions;\n }\n\n function splitPath(folderPath: string): string[] {\n return folderPath.split(\"/\").filter(Boolean);\n }\n\n /**\n * Find a folder node by name under a given parent in the drive's nodes.\n */\n function findFolderInNodes(\n nodes: DriveNode[],\n name: string,\n parentId: string | null,\n ): DriveNode | undefined {\n return nodes.find(\n (n) =>\n isFolder(n) && n.name === name && (n.parentFolder ?? null) === parentId,\n );\n }\n\n async function ensureFolder(folderPath: string): Promise<string> {\n const segments = splitPath(folderPath);\n let parentFolderId: string | null = null;\n\n for (const segment of segments) {\n const nodes = await getDriveNodes(client, personalDriveId);\n const existing = findFolderInNodes(nodes, segment, parentFolderId);\n\n if (existing) {\n log?.debug(\n `${TAG} ensureFolder segment \"${segment}\" → exists ${existing.id.slice(0, 8)}…`,\n );\n parentFolderId = existing.id;\n continue;\n }\n\n // Create folder node inside the drive via ADD_FOLDER operation\n const folderId = randomUUID();\n log?.debug(\n `${TAG} ensureFolder creating folder \"${segment}\" (${folderId.slice(0, 8)}…) ` +\n `under ${parentFolderId?.slice(0, 8) ?? \"root\"}`,\n );\n const actions = await getDriveActions();\n await (\n await client.write.execute(personalDriveId, \"main\", [\n actions.addFolder({\n id: folderId,\n name: segment,\n parentFolder: parentFolderId,\n }),\n ])\n ).document();\n parentFolderId = folderId;\n }\n\n return parentFolderId!;\n }\n\n async function addDocument(\n documentId: string,\n folderPath: string,\n name?: string,\n ): Promise<void> {\n log?.debug(\n `${TAG} addDocument ${documentId.slice(0, 8)}… to \"${folderPath}\" name=${name ?? \"(none)\"}`,\n );\n const folderId = await ensureFolder(folderPath);\n\n // Check if this document is already registered as a file node in the drive\n const nodes = await getDriveNodes(client, personalDriveId);\n const existingFile = nodes.find((n) => !isFolder(n) && n.id === documentId);\n if (existingFile) {\n log?.debug(\n `${TAG} addDocument ${documentId.slice(0, 8)}… already in drive as \"${existingFile.name}\"`,\n );\n return;\n }\n\n // Get the document to read its type\n const doc = (await client.get(documentId)) as any;\n const documentType =\n doc?.header?.documentType ?? doc?.documentType ?? \"unknown\";\n const displayName = name ?? doc?.header?.name ?? doc?.name ?? documentId;\n\n // Add file node to drive via ADD_FILE operation\n const actions = await getDriveActions();\n await (\n await client.write.execute(personalDriveId, \"main\", [\n actions.addFile({\n id: documentId,\n name: displayName,\n documentType,\n parentFolder: folderId,\n }),\n ])\n ).document();\n\n // Also establish the parent-child relationship in the document graph\n await (\n await client.write.addRelationship(personalDriveId, documentId, \"child\")\n ).document();\n\n if (name) {\n await (await client.write.rename(documentId, name)).document();\n }\n\n log?.debug(\n `${TAG} addDocument ${documentId.slice(0, 8)}… added as \"${displayName}\" in folder ${folderId.slice(0, 8)}…`,\n );\n }\n\n async function createDocument(\n documentType: string,\n folderPath: string,\n name?: string,\n ): Promise<{ documentId: string }> {\n log?.debug(\n `${TAG} createDocument type=${documentType} folder=\"${folderPath}\" name=${name ?? \"(none)\"}`,\n );\n const parentFolderId = await ensureFolder(folderPath);\n\n const doc = await client.newDocument(documentType, {\n parentIdentifier: personalDriveId,\n name,\n });\n const documentId = doc.header.id;\n\n // What `drives.addFile` does, in calls the remote client has too: the\n // document first, so the drive never names a file whose create failed;\n // then its file node and its place in the document graph.\n await (\n await client.write.create(doc)\n ).readable;\n const actions = await getDriveActions();\n await (\n await client.write.execute(personalDriveId, \"main\", [\n actions.addFile({\n id: documentId,\n name: doc.header.name || documentId,\n documentType: doc.header.documentType,\n parentFolder: parentFolderId,\n }),\n ])\n ).readable;\n await (\n await client.write.addRelationship(personalDriveId, documentId, \"child\")\n ).readable;\n\n log?.debug(\n `${TAG} createDocument ${documentId.slice(0, 8)}… created in folder ${parentFolderId.slice(0, 8)}…`,\n );\n return { documentId };\n }\n\n async function removeDocument(\n documentId: string,\n _folderPath?: string,\n ): Promise<void> {\n // Remove the file node from the drive via DELETE_NODE\n const actions = await getDriveActions();\n await (\n await client.write.execute(personalDriveId, \"main\", [\n actions.deleteNode({ id: documentId }),\n ])\n ).document();\n\n // Also remove the parent-child relationship\n await (\n await client.write.removeRelationship(\n personalDriveId,\n documentId,\n \"child\",\n )\n ).document();\n }\n\n async function resolveFolder(\n folderPath: string,\n ): Promise<string | undefined> {\n const segments = splitPath(folderPath);\n const nodes = await getDriveNodes(client, personalDriveId);\n let parentFolderId: string | null = null;\n\n for (const segment of segments) {\n const match = findFolderInNodes(nodes, segment, parentFolderId);\n if (!match) return undefined;\n parentFolderId = match.id;\n }\n\n return parentFolderId ?? undefined;\n }\n\n async function getDocument(documentId: string): Promise<unknown> {\n return client.get(documentId);\n }\n\n async function listFolder(folderPath?: string): Promise<FolderEntry[]> {\n let parentFolderId: string | null = null;\n\n if (folderPath) {\n const resolved = await resolveFolder(folderPath);\n if (!resolved) return [];\n parentFolderId = resolved;\n }\n\n const nodes = await getDriveNodes(client, personalDriveId);\n const prefix = folderPath ? folderPath.replace(/\\/+$/, \"\") : \"\";\n\n return nodes\n .filter((n) => (n.parentFolder ?? null) === parentFolderId)\n .map((n) => ({\n id: n.id,\n name: n.name,\n type: isFolder(n) ? (\"folder\" as const) : (\"document\" as const),\n documentType: isFolder(n) ? undefined : n.documentType,\n path: prefix ? `${prefix}/${n.name}` : n.name,\n }));\n }\n\n async function findByType(documentType: string): Promise<FolderEntry[]> {\n const nodes = await getDriveNodes(client, personalDriveId);\n return nodes\n .filter((n) => !isFolder(n) && n.documentType === documentType)\n .map((n) => ({\n id: n.id,\n name: n.name,\n type: \"document\" as const,\n documentType: n.documentType,\n path: n.name,\n }));\n }\n\n return {\n addDocument,\n createDocument,\n removeDocument,\n getDocument,\n listFolder,\n ensureFolder,\n findByType,\n };\n}\n\n// ── Folder command schemas ────────────────────────────────────────\n\nconst addDocumentSchema = z.object({\n documentId: z.string().describe(\"Document ID to add\"),\n folderPath: z.string().describe('Folder path (e.g. \"specs/my-project\")'),\n name: z.string().optional().describe(\"Display name for the document\"),\n});\n\nconst removeDocumentSchema = z.object({\n documentId: z.string().describe(\"Document ID to remove\"),\n folderPath: z.string().optional().describe(\"Folder path to remove from\"),\n});\n\nconst getDocumentSchema = z.object({\n documentId: z.string().describe(\"Document ID to retrieve\"),\n});\n\nconst listFolderSchema = z.object({\n folderPath: z.string().optional().describe(\"Folder path (root if omitted)\"),\n});\n\n/**\n * Auto-generate CLI commands that wrap FolderOperations.\n */\nexport function createFolderCommands(folderOps: FolderOperations): Command[] {\n const addDocument: Command<typeof addDocumentSchema> = {\n id: \"folders-add-document\",\n description: \"Add a document to the personal drive at a folder path\",\n inputSchema: addDocumentSchema,\n outputSchema: z.object({ text: z.string() }),\n execute: async (input) => {\n await folderOps.addDocument(\n input.documentId,\n input.folderPath,\n input.name,\n );\n return {\n text: `Added document ${input.documentId} to ${input.folderPath}`,\n };\n },\n };\n\n const removeDocument: Command<typeof removeDocumentSchema> = {\n id: \"folders-remove-document\",\n description: \"Remove a document from the personal drive\",\n inputSchema: removeDocumentSchema,\n outputSchema: z.object({ text: z.string() }),\n execute: async (input) => {\n await folderOps.removeDocument(input.documentId, input.folderPath);\n return { text: `Removed document ${input.documentId}` };\n },\n };\n\n const getDocument: Command<typeof getDocumentSchema> = {\n id: \"folders-get-document\",\n description: \"Get a document from the personal drive\",\n inputSchema: getDocumentSchema,\n outputSchema: z.object({ text: z.string(), data: z.unknown() }),\n execute: async (input) => {\n const doc = await folderOps.getDocument(input.documentId);\n return { text: JSON.stringify(doc, null, 2), data: doc };\n },\n };\n\n const listFolder: Command<typeof listFolderSchema> = {\n id: \"folders-ls\",\n description: \"List folder contents in the personal drive\",\n inputSchema: listFolderSchema,\n outputSchema: z.object({ text: z.string(), data: z.array(z.unknown()) }),\n execute: async (input) => {\n const entries = await folderOps.listFolder(input.folderPath);\n if (entries.length === 0) {\n return { text: \"Empty folder\", data: [] };\n }\n const lines = entries.map((e) => {\n const icon = e.type === \"folder\" ? \"[dir]\" : \"[doc]\";\n const typeInfo = e.documentType ? ` (${e.documentType})` : \"\";\n return ` ${icon} ${e.name}${typeInfo} ${e.id.slice(0, 8)}...`;\n });\n return { text: lines.join(\"\\n\"), data: entries };\n },\n };\n\n return [addDocument, removeDocument, getDocument, listFolder];\n}\n","//#region src/errors.ts\n/**\n* Thrown when an attachment ref or hash is not known to the store.\n*/\nvar AttachmentNotFound = class extends Error {\n\tconstructor(identifier) {\n\t\tsuper(`Attachment not found: ${identifier}`);\n\t\tthis.name = \"AttachmentNotFound\";\n\t}\n};\n/**\n* Thrown when a reservation ID is not found in the reservation store.\n*/\nvar ReservationNotFound = class extends Error {\n\tconstructor(reservationId) {\n\t\tsuper(`Reservation not found: ${reservationId}`);\n\t\tthis.name = \"ReservationNotFound\";\n\t}\n};\n/**\n* Thrown when an attachment ref string does not match the expected format.\n*/\nvar InvalidAttachmentRef = class extends Error {\n\tconstructor(ref) {\n\t\tsuper(`Invalid attachment ref: ${ref}`);\n\t\tthis.name = \"InvalidAttachmentRef\";\n\t}\n};\n/**\n* Thrown when reserve metadata (MIME type, file name or extension) is not\n* acceptable. Route handlers should map this to HTTP 400 Bad Request.\n*/\nvar InvalidAttachmentMetadata = class extends Error {\n\tfield;\n\tconstructor(field) {\n\t\tsuper(`Invalid attachment ${field}`);\n\t\tthis.name = \"InvalidAttachmentMetadata\";\n\t\tthis.field = field;\n\t}\n};\n/**\n* Thrown when an upload exceeds the configured maximum byte cap.\n* Route handlers should map this to HTTP 413 Payload Too Large.\n*/\nvar UploadTooLarge = class extends Error {\n\tmaxBytes;\n\tconstructor(maxBytes) {\n\t\tsuper(`Upload exceeds maximum size of ${maxBytes} bytes`);\n\t\tthis.name = \"UploadTooLarge\";\n\t\tthis.maxBytes = maxBytes;\n\t}\n};\n/**\n* Thrown by reserve() when the claimed hash is already available in the store.\n* The caller should use err.ref directly and upload nothing -- this is the\n* dedup fast path: duplicate content never leaves the client.\n*/\nvar AttachmentAlreadyExists = class extends Error {\n\thash;\n\tref;\n\tconstructor(hash, ref) {\n\t\tsuper(`Attachment already exists for hash: ${hash}`);\n\t\tthis.name = \"AttachmentAlreadyExists\";\n\t\tthis.hash = hash;\n\t\tthis.ref = ref;\n\t}\n};\n/**\n* Thrown by send() when the server-computed hash of the uploaded bytes\n* does not match the hash claimed at reservation time. Nothing is committed;\n* the reservation is retained so the client can retry with correct bytes.\n*/\nvar HashMismatch = class extends Error {\n\tclaimed;\n\tactual;\n\tconstructor(claimed, actual) {\n\t\tsuper(`Hash mismatch: claimed ${claimed} but computed ${actual}`);\n\t\tthis.name = \"HashMismatch\";\n\t\tthis.claimed = claimed;\n\t\tthis.actual = actual;\n\t}\n};\n/**\n* Thrown by send() when the uploaded byte count does not equal the\n* sizeBytes declared at reservation time. The handle may reject\n* mid-stream as soon as the count exceeds the declaration.\n* Nothing is committed; the reservation is retained for retry.\n*\n* \"actual\" is the byte count received from the stream before aborting --\n* it includes the chunk that crossed the declaration and can exceed bytes\n* persisted. On mid-stream aborts the true total is unknown; at least\n* \"actual\" bytes were sent.\n*/\nvar SizeMismatch = class extends Error {\n\tdeclared;\n\tactual;\n\tconstructor(declared, actual) {\n\t\tsuper(`Size mismatch: declared ${declared} bytes but received ${actual}`);\n\t\tthis.name = \"SizeMismatch\";\n\t\tthis.declared = declared;\n\t\tthis.actual = actual;\n\t}\n};\n/**\n* Thrown when a remote transfer step fails. Identifies the stage only; it\n* intentionally carries no URL, signature query, bucket key, or bearer\n* material so it is always safe to log or surface.\n*/\nvar AttachmentTransferError = class extends Error {\n\tstage;\n\tstatus;\n\tconstructor(stage, status) {\n\t\tsuper(status === void 0 ? `Attachment ${stage} request failed` : `Attachment ${stage} request failed with status ${status}`);\n\t\tthis.name = \"AttachmentTransferError\";\n\t\tthis.stage = stage;\n\t\tthis.status = status;\n\t}\n};\nvar AttachmentPending = class extends Error {\n\thash;\n\texpiresAtUtc;\n\tmetadata;\n\tconstructor(hash, expiresAtUtc, meta) {\n\t\tsuper(`Attachment pending upload for hash: ${hash}, expires: ${expiresAtUtc}`);\n\t\tthis.name = \"AttachmentPending\";\n\t\tthis.hash = hash;\n\t\tthis.expiresAtUtc = expiresAtUtc;\n\t\tthis.metadata = meta;\n\t}\n};\n//#endregion\n//#region src/ref.ts\nconst REF_PATTERN = /^attachment:\\/\\/v(\\d+):(.+)$/;\nconst DEFAULT_VERSION = 1;\nfunction parseRef(ref) {\n\tconst match = REF_PATTERN.exec(ref);\n\tif (!match) throw new InvalidAttachmentRef(ref);\n\treturn {\n\t\tversion: Number(match[1]),\n\t\thash: match[2]\n\t};\n}\nfunction createRef(hash, version = DEFAULT_VERSION) {\n\treturn `attachment://v${version}:${hash}`;\n}\n//#endregion\n//#region src/attachment-metadata.ts\nfunction isRecord(value) {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\nfunction isAttachmentMetadata(value) {\n\tif (!isRecord(value)) return false;\n\tif (typeof value.mimeType !== \"string\") return false;\n\tif (typeof value.fileName !== \"string\") return false;\n\tif (typeof value.sizeBytes !== \"number\" || !Number.isFinite(value.sizeBytes) || value.sizeBytes < 0) return false;\n\tif (value.extension !== null && typeof value.extension !== \"string\") return false;\n\tif (typeof value.createdAtUtc !== \"string\") return false;\n\tif (value.lastAccessedAtUtc !== void 0 && typeof value.lastAccessedAtUtc !== \"string\") return false;\n\treturn true;\n}\n//#endregion\n//#region src/switchboard/build-auth-headers.ts\nasync function buildAuthHeaders(url, jwtHandler) {\n\tconst headers = {};\n\tif (jwtHandler) {\n\t\tconst token = await jwtHandler(url);\n\t\tif (token) headers[\"Authorization\"] = `Bearer ${token}`;\n\t}\n\treturn headers;\n}\n//#endregion\n//#region src/switchboard/switchboard-attachment-transport.ts\nvar SwitchboardAttachmentTransport = class {\n\tremoteUrl;\n\tjwtHandler;\n\tfetchFn;\n\tconstructor(config) {\n\t\tthis.remoteUrl = config.remoteUrl;\n\t\tthis.jwtHandler = config.jwtHandler;\n\t\tthis.fetchFn = (config.fetchFn ?? globalThis.fetch).bind(globalThis);\n\t}\n\tasync fetch(hash, documentId, signal) {\n\t\tconst url = `${this.remoteUrl}/attachments/${hash}?documentId=${encodeURIComponent(documentId)}`;\n\t\tconst headers = await buildAuthHeaders(url, this.jwtHandler);\n\t\tconst response = await this.fetchFn(url, {\n\t\t\tsignal,\n\t\t\theaders\n\t\t});\n\t\tif (response.status === 202) {\n\t\t\tconst expiresAtUtc = this.parsePendingExpiry(response);\n\t\t\tif (!expiresAtUtc) throw new Error(\"Attachment fetch returned 202 with missing or malformed Attachment-Pending header\");\n\t\t\treturn {\n\t\t\t\tkind: \"pending\",\n\t\t\t\thash,\n\t\t\t\texpiresAtUtc,\n\t\t\t\tretryAfterMs: parseRetryAfterMs(response)\n\t\t\t};\n\t\t}\n\t\tif (response.status === 404) return { kind: \"not-found\" };\n\t\tif (!response.ok) throw new Error(`Attachment fetch failed: ${response.status} ${response.statusText}`);\n\t\tconst metadata = this.parseMetadataHeaders(response);\n\t\tconst body = response.body;\n\t\tif (!body) throw new Error(\"Response body is null\");\n\t\treturn {\n\t\t\tkind: \"data\",\n\t\t\tresponse: {\n\t\t\t\thash,\n\t\t\t\tmetadata,\n\t\t\t\tbody\n\t\t\t}\n\t\t};\n\t}\n\tasync announce(_hash) {}\n\tasync push(hash, remote, data) {\n\t\tconst url = `${remote}/attachments/${hash}`;\n\t\tconst headers = await buildAuthHeaders(url, this.jwtHandler);\n\t\tconst response = await this.fetchFn(url, {\n\t\t\tmethod: \"PUT\",\n\t\t\tbody: data,\n\t\t\theaders,\n\t\t\tduplex: \"half\"\n\t\t});\n\t\tif (!response.ok) throw new Error(`Attachment push failed: ${response.status} ${response.statusText}`);\n\t}\n\tparsePendingExpiry(response) {\n\t\tconst header = response.headers.get(\"Attachment-Pending\");\n\t\tif (!header) return null;\n\t\ttry {\n\t\t\tconst parsed = JSON.parse(header);\n\t\t\tif (!isRecord(parsed)) return null;\n\t\t\tif (typeof parsed.expiresAtUtc !== \"string\") return null;\n\t\t\treturn parsed.expiresAtUtc;\n\t\t} catch {\n\t\t\treturn null;\n\t\t}\n\t}\n\tparseMetadataHeaders(response) {\n\t\tlet fallbackCache;\n\t\tconst fallback = () => {\n\t\t\tif (fallbackCache === void 0) fallbackCache = contentTypeFallback(response);\n\t\t\treturn fallbackCache;\n\t\t};\n\t\tconst metaHeader = response.headers.get(\"Attachment-Metadata\");\n\t\tif (metaHeader) try {\n\t\t\tconst parsed = JSON.parse(metaHeader);\n\t\t\tif (isRecord(parsed)) {\n\t\t\t\tif (parsed.extension === void 0) parsed.extension = null;\n\t\t\t\tif (parsed.createdAtUtc === void 0) parsed.createdAtUtc = fallback().createdAtUtc;\n\t\t\t\tif (parsed.lastAccessedAtUtc === void 0) parsed.lastAccessedAtUtc = fallback().lastAccessedAtUtc;\n\t\t\t}\n\t\t\tif (isAttachmentMetadata(parsed)) return parsed;\n\t\t} catch {}\n\t\treturn fallback();\n\t}\n};\nconst DEFAULT_RETRY_AFTER_MS = 5e3;\nfunction parseRetryAfterMs(response) {\n\tconst retryAfter = response.headers.get(\"Retry-After\");\n\tif (!retryAfter) return DEFAULT_RETRY_AFTER_MS;\n\tconst seconds = Number(retryAfter);\n\tif (!Number.isFinite(seconds) || seconds < 0) return DEFAULT_RETRY_AFTER_MS;\n\treturn Math.round(seconds * 1e3);\n}\nfunction contentTypeFallback(response) {\n\tconst contentLength = response.headers.get(\"Content-Length\");\n\tif (contentLength === null) throw new Error(\"Switchboard response missing both Attachment-Metadata and Content-Length headers\");\n\tconst sizeBytes = Number(contentLength);\n\tif (!Number.isInteger(sizeBytes) || sizeBytes < 0) throw new Error(`Switchboard response has invalid Content-Length header: ${JSON.stringify(contentLength)}`);\n\tconst lastModified = response.headers.get(\"Last-Modified\");\n\tconst dateHeader = response.headers.get(\"Date\");\n\tconst createdAtUtc = lastModified ? new Date(lastModified).toISOString() : dateHeader ? new Date(dateHeader).toISOString() : (/* @__PURE__ */ new Date()).toISOString();\n\treturn {\n\t\tmimeType: response.headers.get(\"Content-Type\") ?? \"application/octet-stream\",\n\t\tfileName: \"unknown\",\n\t\tsizeBytes,\n\t\textension: null,\n\t\tcreatedAtUtc,\n\t\tlastAccessedAtUtc: createdAtUtc\n\t};\n}\n//#endregion\nexport { parseRef as a, AttachmentPending as c, InvalidAttachmentMetadata as d, InvalidAttachmentRef as f, UploadTooLarge as h, createRef as i, AttachmentTransferError as l, SizeMismatch as m, buildAuthHeaders as n, AttachmentAlreadyExists as o, ReservationNotFound as p, isAttachmentMetadata as r, AttachmentNotFound as s, SwitchboardAttachmentTransport as t, HashMismatch as u };\n\n//# sourceMappingURL=switchboard-attachment-transport-BH3ZAmxE.js.map","/**\n * Utilities for hex, bytes, CSPRNG.\n * @module\n */\n/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.\n// node.js versions earlier than v19 don't declare it in global scope.\n// For node.js, package.json#exports field mapping rewrites import\n// from `crypto` to `cryptoNode`, which imports native module.\n// Makes the utils un-importable in browsers without a bundler.\n// Once node.js 18 is deprecated (2025-04-30), we can just drop the import.\nimport { crypto } from '@noble/hashes/crypto';\n/** Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. */\nexport function isBytes(a) {\n return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');\n}\n/** Asserts something is positive integer. */\nexport function anumber(n) {\n if (!Number.isSafeInteger(n) || n < 0)\n throw new Error('positive integer expected, got ' + n);\n}\n/** Asserts something is Uint8Array. */\nexport function abytes(b, ...lengths) {\n if (!isBytes(b))\n throw new Error('Uint8Array expected');\n if (lengths.length > 0 && !lengths.includes(b.length))\n throw new Error('Uint8Array expected of length ' + lengths + ', got length=' + b.length);\n}\n/** Asserts something is hash */\nexport function ahash(h) {\n if (typeof h !== 'function' || typeof h.create !== 'function')\n throw new Error('Hash should be wrapped by utils.createHasher');\n anumber(h.outputLen);\n anumber(h.blockLen);\n}\n/** Asserts a hash instance has not been destroyed / finished */\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/** Asserts output is properly-sized byte array */\nexport function aoutput(out, instance) {\n abytes(out);\n const min = instance.outputLen;\n if (out.length < min) {\n throw new Error('digestInto() expects output buffer of length at least ' + min);\n }\n}\n/** Cast u8 / u16 / u32 to u8. */\nexport function u8(arr) {\n return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n/** Cast u8 / u16 / u32 to u32. */\nexport function u32(arr) {\n return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n}\n/** Zeroize a byte array. Warning: JS provides no guarantees. */\nexport function clean(...arrays) {\n for (let i = 0; i < arrays.length; i++) {\n arrays[i].fill(0);\n }\n}\n/** Create DataView of an array for easy byte-level manipulation. */\nexport function createView(arr) {\n return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n/** The rotate right (circular right shift) operation for uint32 */\nexport function rotr(word, shift) {\n return (word << (32 - shift)) | (word >>> shift);\n}\n/** The rotate left (circular left shift) operation for uint32 */\nexport function rotl(word, shift) {\n return (word << shift) | ((word >>> (32 - shift)) >>> 0);\n}\n/** Is current platform little-endian? Most are. Big-Endian platform: IBM */\nexport const isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();\n/** The byte swap operation for uint32 */\nexport function byteSwap(word) {\n return (((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff));\n}\n/** Conditionally byte swap if on a big-endian platform */\nexport const swap8IfBE = isLE\n ? (n) => n\n : (n) => byteSwap(n);\n/** @deprecated */\nexport const byteSwapIfBE = swap8IfBE;\n/** In place byte swap for Uint32Array */\nexport function byteSwap32(arr) {\n for (let i = 0; i < arr.length; i++) {\n arr[i] = byteSwap(arr[i]);\n }\n return arr;\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. Uses built-in function, when available.\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\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 * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex) {\n if (typeof hex !== 'string')\n throw new Error('hex string expected, got ' + typeof hex);\n // @ts-ignore\n if (hasHexBuiltin)\n return Uint8Array.fromHex(hex);\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2)\n throw new Error('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 Error('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 * Call of async fn will return Promise, which will be fullfiled only on\n * next scheduler queue processing step and this is exactly what we need.\n */\nexport const nextTick = async () => { };\n/** Returns control to thread each 'tick' ms to avoid blocking. */\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 * @example utf8ToBytes('abc') // Uint8Array.from([97, 98, 99])\n */\nexport function utf8ToBytes(str) {\n if (typeof str !== 'string')\n throw new Error('string expected');\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n/**\n * Converts bytes to string using UTF8 encoding.\n * @example bytesToUtf8(Uint8Array.from([97, 98, 99])) // 'abc'\n */\nexport function bytesToUtf8(bytes) {\n return new TextDecoder().decode(bytes);\n}\n/**\n * Normalizes (non-hex) string or Uint8Array to Uint8Array.\n * Warning: when Uint8Array is passed, it would NOT get copied.\n * Keep in mind for future mutable operations.\n */\nexport function toBytes(data) {\n if (typeof data === 'string')\n data = utf8ToBytes(data);\n abytes(data);\n return data;\n}\n/**\n * Helper for KDFs: consumes uint8array or string.\n * When string is passed, does utf8 decoding, using TextDecoder.\n */\nexport function kdfInputToBytes(data) {\n if (typeof data === 'string')\n data = utf8ToBytes(data);\n abytes(data);\n return data;\n}\n/** Copies several Uint8Arrays into one. */\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}\nexport function checkOpts(defaults, opts) {\n if (opts !== undefined && {}.toString.call(opts) !== '[object Object]')\n throw new Error('options should be object or undefined');\n const merged = Object.assign(defaults, opts);\n return merged;\n}\n/** For runtime check if class implements interface */\nexport class Hash {\n}\n/** Wraps hash function, creating an interface on top of it */\nexport function createHasher(hashCons) {\n const hashC = (msg) => hashCons().update(toBytes(msg)).digest();\n const tmp = hashCons();\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = () => hashCons();\n return hashC;\n}\nexport function createOptHasher(hashCons) {\n const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({});\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts) => hashCons(opts);\n return hashC;\n}\nexport function createXOFer(hashCons) {\n const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({});\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts) => hashCons(opts);\n return hashC;\n}\nexport const wrapConstructor = createHasher;\nexport const wrapConstructorWithOpts = createOptHasher;\nexport const wrapXOFConstructorWithOpts = createXOFer;\n/** Cryptographically secure PRNG. Uses internal OS-level `crypto.getRandomValues`. */\nexport function randomBytes(bytesLength = 32) {\n if (crypto && typeof crypto.getRandomValues === 'function') {\n return crypto.getRandomValues(new Uint8Array(bytesLength));\n }\n // Legacy Node.js compatibility\n if (crypto && typeof crypto.randomBytes === 'function') {\n return Uint8Array.from(crypto.randomBytes(bytesLength));\n }\n throw new Error('crypto.getRandomValues must be defined');\n}\n//# sourceMappingURL=utils.js.map","/**\n * Internal Merkle-Damgard hash utils.\n * @module\n */\nimport { Hash, abytes, aexists, aoutput, clean, createView, toBytes } from \"./utils.js\";\n/** Polyfill for Safari 14. https://caniuse.com/mdn-javascript_builtins_dataview_setbiguint64 */\nexport function setBigUint64(view, byteOffset, value, isLE) {\n if (typeof view.setBigUint64 === 'function')\n return view.setBigUint64(byteOffset, value, isLE);\n const _32n = BigInt(32);\n const _u32_max = BigInt(0xffffffff);\n const wh = Number((value >> _32n) & _u32_max);\n const wl = Number(value & _u32_max);\n const h = isLE ? 4 : 0;\n const l = isLE ? 0 : 4;\n view.setUint32(byteOffset + h, wh, isLE);\n view.setUint32(byteOffset + l, wl, isLE);\n}\n/** Choice: a ? b : c */\nexport function Chi(a, b, c) {\n return (a & b) ^ (~a & c);\n}\n/** Majority function, true if any two inputs is true. */\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 */\nexport class HashMD extends Hash {\n constructor(blockLen, outputLen, padOffset, isLE) {\n super();\n this.finished = false;\n this.length = 0;\n this.pos = 0;\n this.destroyed = false;\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 data = toBytes(data);\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: we have at least one block in input, cast it to view and process\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 // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that\n // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen.\n // So we just write lowest 64 bits of that value.\n setBigUint64(view, 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 should be fused in single op with modulo by JIT\n if (len % 4)\n throw new Error('_sha2: outputLen should 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 const res = buffer.slice(0, outputLen);\n this.destroy();\n return res;\n }\n _cloneInto(to) {\n to || (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 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. Bits 0..32 of frac part of sqrt of primes 2..19 */\nexport const SHA256_IV = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,\n]);\n/** Initial SHA224 state. Bits 32..64 of frac part of sqrt of primes 23..53 */\nexport const SHA224_IV = /* @__PURE__ */ Uint32Array.from([\n 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4,\n]);\n/** Initial SHA384 state. Bits 0..64 of frac part of sqrt of primes 23..53 */\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. Bits 0..64 of frac part of sqrt of primes 2..19 */\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","/**\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 [RFC 4634](https://datatracker.ietf.org/doc/html/rfc4634) and\n * [FIPS 180-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf).\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, rotr } from \"./utils.js\";\n/**\n * Round constants:\n * First 32 bits of fractional parts 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 temporary buffer. \"W\" comes straight from spec. */\nconst SHA256_W = /* @__PURE__ */ new Uint32Array(64);\nexport class SHA256 extends HashMD {\n constructor(outputLen = 32) {\n super(64, outputLen, 8, false);\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n this.A = SHA256_IV[0] | 0;\n this.B = SHA256_IV[1] | 0;\n this.C = SHA256_IV[2] | 0;\n this.D = SHA256_IV[3] | 0;\n this.E = SHA256_IV[4] | 0;\n this.F = SHA256_IV[5] | 0;\n this.G = SHA256_IV[6] | 0;\n this.H = SHA256_IV[7] | 0;\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 this.set(0, 0, 0, 0, 0, 0, 0, 0);\n clean(this.buffer);\n }\n}\nexport class SHA224 extends SHA256 {\n constructor() {\n super(28);\n this.A = SHA224_IV[0] | 0;\n this.B = SHA224_IV[1] | 0;\n this.C = SHA224_IV[2] | 0;\n this.D = SHA224_IV[3] | 0;\n this.E = SHA224_IV[4] | 0;\n this.F = SHA224_IV[5] | 0;\n this.G = SHA224_IV[6] | 0;\n this.H = SHA224_IV[7] | 0;\n }\n}\n// SHA2-512 is slower than sha256 in js because u64 operations are slow.\n// Round contants\n// First 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409\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 temporary buffers\nconst SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);\nconst SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);\nexport class SHA512 extends HashMD {\n constructor(outputLen = 64) {\n super(128, outputLen, 16, false);\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n // h -- high 32 bits, l -- low 32 bits\n this.Ah = SHA512_IV[0] | 0;\n this.Al = SHA512_IV[1] | 0;\n this.Bh = SHA512_IV[2] | 0;\n this.Bl = SHA512_IV[3] | 0;\n this.Ch = SHA512_IV[4] | 0;\n this.Cl = SHA512_IV[5] | 0;\n this.Dh = SHA512_IV[6] | 0;\n this.Dl = SHA512_IV[7] | 0;\n this.Eh = SHA512_IV[8] | 0;\n this.El = SHA512_IV[9] | 0;\n this.Fh = SHA512_IV[10] | 0;\n this.Fl = SHA512_IV[11] | 0;\n this.Gh = SHA512_IV[12] | 0;\n this.Gl = SHA512_IV[13] | 0;\n this.Hh = SHA512_IV[14] | 0;\n this.Hl = SHA512_IV[15] | 0;\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 // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_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 clean(this.buffer);\n this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);\n }\n}\nexport class SHA384 extends SHA512 {\n constructor() {\n super(48);\n this.Ah = SHA384_IV[0] | 0;\n this.Al = SHA384_IV[1] | 0;\n this.Bh = SHA384_IV[2] | 0;\n this.Bl = SHA384_IV[3] | 0;\n this.Ch = SHA384_IV[4] | 0;\n this.Cl = SHA384_IV[5] | 0;\n this.Dh = SHA384_IV[6] | 0;\n this.Dl = SHA384_IV[7] | 0;\n this.Eh = SHA384_IV[8] | 0;\n this.El = SHA384_IV[9] | 0;\n this.Fh = SHA384_IV[10] | 0;\n this.Fl = SHA384_IV[11] | 0;\n this.Gh = SHA384_IV[12] | 0;\n this.Gl = SHA384_IV[13] | 0;\n this.Hh = SHA384_IV[14] | 0;\n this.Hl = SHA384_IV[15] | 0;\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 `test/misc/sha2-gen-iv.js`.\n */\n/** SHA512/224 IV */\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/** SHA512/256 IV */\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]);\nexport class SHA512_224 extends SHA512 {\n constructor() {\n super(28);\n this.Ah = T224_IV[0] | 0;\n this.Al = T224_IV[1] | 0;\n this.Bh = T224_IV[2] | 0;\n this.Bl = T224_IV[3] | 0;\n this.Ch = T224_IV[4] | 0;\n this.Cl = T224_IV[5] | 0;\n this.Dh = T224_IV[6] | 0;\n this.Dl = T224_IV[7] | 0;\n this.Eh = T224_IV[8] | 0;\n this.El = T224_IV[9] | 0;\n this.Fh = T224_IV[10] | 0;\n this.Fl = T224_IV[11] | 0;\n this.Gh = T224_IV[12] | 0;\n this.Gl = T224_IV[13] | 0;\n this.Hh = T224_IV[14] | 0;\n this.Hl = T224_IV[15] | 0;\n }\n}\nexport class SHA512_256 extends SHA512 {\n constructor() {\n super(32);\n this.Ah = T256_IV[0] | 0;\n this.Al = T256_IV[1] | 0;\n this.Bh = T256_IV[2] | 0;\n this.Bl = T256_IV[3] | 0;\n this.Ch = T256_IV[4] | 0;\n this.Cl = T256_IV[5] | 0;\n this.Dh = T256_IV[6] | 0;\n this.Dl = T256_IV[7] | 0;\n this.Eh = T256_IV[8] | 0;\n this.El = T256_IV[9] | 0;\n this.Fh = T256_IV[10] | 0;\n this.Fl = T256_IV[11] | 0;\n this.Gh = T256_IV[12] | 0;\n this.Gl = T256_IV[13] | 0;\n this.Hh = T256_IV[14] | 0;\n this.Hl = T256_IV[15] | 0;\n }\n}\n/**\n * SHA2-256 hash function from RFC 4634.\n *\n * It is the fastest JS hash, even faster than Blake3.\n * To break sha256 using birthday attack, attackers need to try 2^128 hashes.\n * BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.\n */\nexport const sha256 = /* @__PURE__ */ createHasher(() => new SHA256());\n/** SHA2-224 hash function from RFC 4634 */\nexport const sha224 = /* @__PURE__ */ createHasher(() => new SHA224());\n/** SHA2-512 hash function from RFC 4634. */\nexport const sha512 = /* @__PURE__ */ createHasher(() => new SHA512());\n/** SHA2-384 hash function from RFC 4634. */\nexport const sha384 = /* @__PURE__ */ createHasher(() => new SHA384());\n/**\n * SHA2-512/256 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on [truncated SHA512](https://eprint.iacr.org/2010/548.pdf).\n */\nexport const sha512_256 = /* @__PURE__ */ createHasher(() => new SHA512_256());\n/**\n * SHA2-512/224 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on [truncated SHA512](https://eprint.iacr.org/2010/548.pdf).\n */\nexport const sha512_224 = /* @__PURE__ */ createHasher(() => new SHA512_224());\n//# sourceMappingURL=sha2.js.map","import { sha256 } from \"@noble/hashes/sha2.js\";\nimport { bytesToHex } from \"@noble/hashes/utils.js\";\nconst nodeCrypto = globalThis.process?.getBuiltinModule?.(\"node:crypto\");\n/** Native SHA-256 from node:crypto, or undefined outside Node. */\nfunction nodeSha256() {\n\tif (!nodeCrypto) return void 0;\n\tconst hash = nodeCrypto.createHash(\"sha256\");\n\treturn {\n\t\tupdate: (bytes) => void hash.update(bytes),\n\t\thex: () => hash.digest(\"hex\")\n\t};\n}\n/** SHA-256 in JavaScript, for browsers; about 10x slower than native. */\nfunction jsSha256() {\n\tconst hash = sha256.create();\n\treturn {\n\t\tupdate: (bytes) => void hash.update(bytes),\n\t\thex: () => bytesToHex(hash.digest())\n\t};\n}\n/**\n* Lowercase SHA-256 hex of `bytes` -- the `attachment://v1:` hash format\n* (`packages/reactor/src/attachments/types.ts`).\n*\n* WebCrypto, so the same code runs in Node and in a browser realm. There is no\n* streaming digest in WebCrypto, which is why verification happens over\n* collected bytes.\n*/\nasync function sha256Hex(bytes) {\n\tconst digest = await globalThis.crypto.subtle.digest(\"SHA-256\", digestable(bytes));\n\treturn Array.from(new Uint8Array(digest)).map((byte) => byte.toString(16).padStart(2, \"0\")).join(\"\");\n}\n/** WebCrypto refuses a SharedArrayBuffer-backed view, so only that one is copied. */\nfunction digestable(bytes) {\n\tif (typeof SharedArrayBuffer !== \"undefined\" && bytes.buffer instanceof SharedArrayBuffer) {\n\t\tconst copy = new Uint8Array(bytes.byteLength);\n\t\tcopy.set(bytes);\n\t\treturn copy;\n\t}\n\treturn bytes;\n}\n/** Same digest as `sha256Hex`, in bounded memory: natively in slices in Node, and in a\n* browser whole up to `oneShotMaxBytes`, then in JavaScript slices (no ~2 GB read). */\nasync function sha256HexOfBlob(blob, options) {\n\tconst chunkBytes = options?.chunkBytes ?? 8388608;\n\tif (!Number.isInteger(chunkBytes) || chunkBytes <= 0) throw new RangeError(\"chunkBytes must be a positive integer\");\n\toptions?.signal?.throwIfAborted();\n\tlet hasher = (options?.native ?? nodeSha256)();\n\tif (!hasher) {\n\t\tif (blob.size <= (options?.oneShotMaxBytes ?? 268435456)) return sha256Hex(new Uint8Array(await blob.arrayBuffer()));\n\t\thasher = jsSha256();\n\t}\n\tfor (let offset = 0; offset < blob.size; offset += chunkBytes) {\n\t\toptions?.signal?.throwIfAborted();\n\t\tconst chunk = blob.slice(offset, offset + chunkBytes);\n\t\thasher.update(new Uint8Array(await chunk.arrayBuffer()));\n\t}\n\treturn hasher.hex();\n}\n//#endregion\nexport { sha256HexOfBlob as n, sha256Hex as t };\n\n//# sourceMappingURL=hash-BobbR4r4.js.map","import { a as parseRef, c as AttachmentPending, f as InvalidAttachmentRef, h as UploadTooLarge, i as createRef, l as AttachmentTransferError, m as SizeMismatch, o as AttachmentAlreadyExists, p as ReservationNotFound, s as AttachmentNotFound, t as SwitchboardAttachmentTransport, u as HashMismatch } from \"./switchboard-attachment-transport-BH3ZAmxE.js\";\nimport { a as RemoteAttachmentUploadFactory, c as createXhrUploadTransport, f as AttachmentService, i as RemoteAttachmentStore, l as createFetchUploadTransport, m as parseAttachmentUploadTarget, n as NullAttachmentTransport, o as RemoteAttachmentUpload, p as parseAttachmentDownloadTarget, r as createRemoteAttachmentService, s as RemoteReservationStore, t as RoutingAttachmentService } from \"./routing-attachment-service-C88ryRgj.js\";\nimport { n as sha256HexOfBlob } from \"./hash-BobbR4r4.js\";\n//#region src/concurrency.ts\n/**\n* Runs `worker` over `items` with a hard upper bound on simultaneous\n* executions. Bounding starts (not just transfers) is what keeps memory flat:\n* an item's preprocessing (hashing/buffering) only begins when a slot frees.\n*/\nasync function runWithConcurrency(items, worker, options) {\n\tconst { concurrency, signal, onSettled } = options;\n\tif (!Number.isInteger(concurrency) || concurrency < 1) throw new Error(`concurrency must be a positive integer, got: ${concurrency}`);\n\tconst results = new Array(items.length);\n\tlet nextIndex = 0;\n\tasync function runLane() {\n\t\tfor (;;) {\n\t\t\tconst index = nextIndex++;\n\t\t\tif (index >= items.length) return;\n\t\t\tif (signal?.aborted) {\n\t\t\t\tresults[index] = {\n\t\t\t\t\tindex,\n\t\t\t\t\tstatus: \"rejected\",\n\t\t\t\t\terror: signalReason(signal)\n\t\t\t\t};\n\t\t\t\tonSettled?.(results[index]);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tconst value = await worker(items[index], index);\n\t\t\t\tresults[index] = {\n\t\t\t\t\tindex,\n\t\t\t\t\tstatus: \"fulfilled\",\n\t\t\t\t\tvalue\n\t\t\t\t};\n\t\t\t} catch (error) {\n\t\t\t\tresults[index] = {\n\t\t\t\t\tindex,\n\t\t\t\t\tstatus: \"rejected\",\n\t\t\t\t\terror\n\t\t\t\t};\n\t\t\t}\n\t\t\tonSettled?.(results[index]);\n\t\t}\n\t}\n\tconst lanes = Array.from({ length: Math.min(concurrency, items.length) }, () => runLane());\n\tawait Promise.all(lanes);\n\treturn results;\n}\nfunction signalReason(signal) {\n\treturn signal.reason ?? new DOMException(\"The operation was aborted\", \"AbortError\");\n}\n//#endregion\n//#region src/progress.ts\nconst DEFAULT_PROGRESS_THROTTLE_MS = 100;\n/**\n* Fraction in 0..1 for a progress event. Indeterminate and unknown-total\n* events read as 0 — a bar cannot honestly show a position it does not know.\n* A zero total is complete by definition (the dedup case moves no bytes).\n*/\nfunction progressFraction(progress) {\n\tif (progress.indeterminate) return 0;\n\tif (progress.total === void 0) return 0;\n\tif (progress.total === 0) return 1;\n\tconst fraction = progress.loaded / progress.total;\n\tif (fraction < 0) return 0;\n\treturn fraction > 1 ? 1 : fraction;\n}\n/**\n* Emits `AttachmentProgress` for one single-item operation, upholding:\n*\n* - **I1** exactly one terminal event (`done` or `error`) — never both, never twice.\n* - **I2** on `done`: `indeterminate === false`, `total` is a number, `loaded === total`.\n* - **I3** `loaded` is non-decreasing within a stage and resets to 0 on stage change.\n* - **I4** the terminal event bypasses the throttle unconditionally.\n* - **I5** `error` carries the last known `loaded`/`total`.\n*\n* Leading edge: the first `bytes()` after a `stage()` always emits, so a bar\n* leaves 0 immediately. There is deliberately no trailing-edge timer — it\n* would leak on throw, could fire after the terminal event and violate I1's\n* ordering, and is unnecessary because `finish()` always emits\n* `loaded === total`, making a dropped last intra-stage tick invisible.\n*/\nvar ProgressEmitter = class {\n\tlistener;\n\tthrottleMs;\n\tnow;\n\tcurrentStage;\n\tloaded = 0;\n\ttotal;\n\temittedBytesInStage = false;\n\tlastEmitAt = Number.NEGATIVE_INFINITY;\n\tsettled = false;\n\tconstructor(options) {\n\t\tthis.listener = options?.onProgress;\n\t\tthis.throttleMs = options?.throttleMs ?? 100;\n\t\tthis.now = options?.now ?? (() => Date.now());\n\t}\n\t/** True when a listener is attached; lets callers skip instrumentation entirely. */\n\tget active() {\n\t\treturn this.listener !== void 0;\n\t}\n\t/**\n\t* Enter a stage. Always emits and resets `loaded` to 0. Entry is always\n\t* indeterminate: no bytes have moved yet, and whether they can be observed\n\t* at all is only proven by a transport actually calling back.\n\t*/\n\tstage(stage, options) {\n\t\tif (this.settled) return;\n\t\tthis.currentStage = stage;\n\t\tthis.loaded = 0;\n\t\tthis.total = options?.total;\n\t\tthis.emittedBytesInStage = false;\n\t\tthis.emit({\n\t\t\tstage,\n\t\t\tloaded: 0,\n\t\t\ttotal: this.total,\n\t\t\tindeterminate: true\n\t\t});\n\t}\n\t/**\n\t* Report observed bytes within the current stage. Throttled by time, with\n\t* the first observation after a stage change always emitted.\n\t*/\n\tbytes(loaded, total) {\n\t\tif (this.settled || this.currentStage === void 0) return;\n\t\tif (total !== void 0) this.total = total;\n\t\tif (loaded > this.loaded) this.loaded = loaded;\n\t\tif (!!this.emittedBytesInStage && this.now() - this.lastEmitAt < this.throttleMs) return;\n\t\tthis.emittedBytesInStage = true;\n\t\tthis.emit({\n\t\t\tstage: this.currentStage,\n\t\t\tloaded: this.loaded,\n\t\t\ttotal: this.total,\n\t\t\tindeterminate: false\n\t\t});\n\t}\n\t/**\n\t* Terminal success. `total` defaults to the bytes actually seen so a stage\n\t* with no known denominator still satisfies I2.\n\t*/\n\tfinish(override) {\n\t\tif (this.settled) return;\n\t\tthis.settled = true;\n\t\tconst total = override?.total ?? this.total ?? this.loaded;\n\t\tconst loaded = override?.loaded ?? total;\n\t\tthis.emit({\n\t\t\tstage: \"done\",\n\t\t\tloaded,\n\t\t\ttotal,\n\t\t\tindeterminate: false,\n\t\t\t...override?.deduped ? { deduped: true } : {}\n\t\t});\n\t}\n\t/** Terminal success for a confirmed dedup: no bytes moved, and none needed to. */\n\tfinishDeduped() {\n\t\tthis.finish({\n\t\t\tloaded: 0,\n\t\t\ttotal: 0,\n\t\t\tdeduped: true\n\t\t});\n\t}\n\t/** Terminal failure, carrying the last known byte counts. */\n\tfail() {\n\t\tif (this.settled) return;\n\t\tthis.settled = true;\n\t\tthis.emit({\n\t\t\tstage: \"error\",\n\t\t\tloaded: this.loaded,\n\t\t\ttotal: this.total,\n\t\t\tindeterminate: false\n\t\t});\n\t}\n\temit(progress) {\n\t\tthis.lastEmitAt = this.now();\n\t\tthis.listener?.(progress);\n\t}\n};\n/**\n* Count bytes as a consumer reads them.\n*\n* Uses the manual-reader form rather than `pipeThrough`, whose internal queue\n* reads far ahead of the consumer and would make `loaded` overstate what was\n* actually received. `highWaterMark: 0` is load-bearing for the same reason:\n* at the default of 1 the wrapper pulls one chunk the instant it is\n* constructed, so a caller who never reads still sees bytes counted.\n*\n* `cancel` propagates to the source, which is what keeps reader refcounts\n* (e.g. `KyselyAttachmentStore`'s) correct. Cancelling is an abandonment, not\n* a completion, so it reports `onError` — never `onDone` — carrying the\n* cancel reason the way an `AbortSignal` carries its own, with the DOM's\n* default `AbortError` when the canceller gave none.\n*\n* Returns `source` unchanged when no hook is supplied, so a caller with no\n* listener pays nothing.\n*/\nfunction withByteProgress(source, hooks) {\n\tif (!hooks.onBytes && !hooks.onDone && !hooks.onError) return source;\n\tlet loaded = 0;\n\tlet cancelled = false;\n\tconst reader = source.getReader();\n\treturn new ReadableStream({\n\t\tasync pull(controller) {\n\t\t\ttry {\n\t\t\t\tconst { done, value } = await reader.read();\n\t\t\t\tif (cancelled) return;\n\t\t\t\tif (done) {\n\t\t\t\t\thooks.onDone?.();\n\t\t\t\t\tcontroller.close();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tloaded += value.byteLength;\n\t\t\t\thooks.onBytes?.(loaded);\n\t\t\t\tcontroller.enqueue(value);\n\t\t\t} catch (err) {\n\t\t\t\tif (cancelled) return;\n\t\t\t\thooks.onError?.(err);\n\t\t\t\tcontroller.error(err);\n\t\t\t}\n\t\t},\n\t\tcancel(reason) {\n\t\t\tcancelled = true;\n\t\t\treader.cancel(reason).catch(() => {});\n\t\t\thooks.onError?.(reason ?? abortError());\n\t\t}\n\t}, { highWaterMark: 0 });\n}\n/** What an `AbortSignal` carries when `abort()` is called with no reason. */\nfunction abortError() {\n\treturn new DOMException(\"The operation was aborted\", \"AbortError\");\n}\n//#endregion\n//#region src/client.ts\nconst DEFAULT_ATTACHMENT_BATCH_CONCURRENCY = 4;\n/**\n* Duck-typed dedup detection: bundlers (notably Vite dev pre-bundling) can\n* load two copies of this package's error classes, one for the service and\n* one for the client wrapper, making a plain instanceof check miss the\n* cross-copy throw. Name plus payload shape identifies the error reliably.\n*/\nfunction isAttachmentAlreadyExists(err) {\n\tif (err instanceof AttachmentAlreadyExists) return true;\n\treturn err instanceof Error && err.name === \"AttachmentAlreadyExists\" && typeof err.hash === \"string\" && typeof err.ref === \"string\";\n}\nfunction dedupedHeader(hash, options) {\n\tconst now = (/* @__PURE__ */ new Date()).toISOString();\n\treturn {\n\t\thash,\n\t\tmimeType: options.mimeType,\n\t\tfileName: options.fileName,\n\t\tsizeBytes: options.sizeBytes,\n\t\textension: options.extension ?? null,\n\t\tstatus: \"available\",\n\t\tsource: \"local\",\n\t\tcreatedAtUtc: now,\n\t\tlastAccessedAtUtc: now,\n\t\texpiresAtUtc: null\n\t};\n}\n/** Stamps an item's index onto its progress events. */\nfunction itemProgress(options, index) {\n\tif (!options?.onProgress && options?.throttleMs === void 0) return;\n\treturn {\n\t\t...options.onProgress ? { onProgress: (progress) => options.onProgress?.({\n\t\t\t...progress,\n\t\t\tindex\n\t\t}) } : {},\n\t\t...options.throttleMs !== void 0 ? { throttleMs: options.throttleMs } : {}\n\t};\n}\nfunction batchRunOptions(total, options) {\n\tconst onItemSettled = options?.onItemSettled;\n\tlet settled = 0;\n\tlet completed = 0;\n\tlet failed = 0;\n\treturn {\n\t\tconcurrency: options?.concurrency ?? 4,\n\t\t...options?.signal ? { signal: options.signal } : {},\n\t\t...onItemSettled ? { onSettled: (result) => {\n\t\t\tsettled += 1;\n\t\t\tif (result.status === \"fulfilled\") completed += 1;\n\t\t\telse failed += 1;\n\t\t\tonItemSettled({\n\t\t\t\tsettled,\n\t\t\t\tcompleted,\n\t\t\t\tfailed,\n\t\t\t\ttotal\n\t\t\t});\n\t\t} } : {}\n\t};\n}\nvar AttachmentClientImpl = class {\n\tservice;\n\tconstructor(service) {\n\t\tthis.service = service;\n\t}\n\tpreprocess(file, opts) {\n\t\treturn this.hashFile(file, opts);\n\t}\n\tasync hashFile(file, opts, signal) {\n\t\tconst hash = await sha256HexOfBlob(file, signal ? { signal } : void 0);\n\t\tconst ref = createRef(hash);\n\t\tconst sizeBytes = file.size;\n\t\treturn {\n\t\t\tref,\n\t\t\thash,\n\t\t\tsizeBytes,\n\t\t\toptions: {\n\t\t\t\tmimeType: opts?.mimeType ?? file.type,\n\t\t\t\tfileName: opts?.fileName ?? (file instanceof File ? file.name : \"attachment\"),\n\t\t\t\tclientHash: hash,\n\t\t\t\tsizeBytes,\n\t\t\t\t...opts?.documentId !== void 0 ? { documentId: opts.documentId } : {}\n\t\t\t},\n\t\t\tblob: file\n\t\t};\n\t}\n\t/**\n\t* Reserve, distinguishing a confirmed dedup from a live upload handle in the\n\t* type rather than with a flag: the two outcomes move a different number of\n\t* bytes, and every caller has to account for that.\n\t*/\n\tasync reserveOrDedup(options) {\n\t\ttry {\n\t\t\treturn {\n\t\t\t\tkind: \"handle\",\n\t\t\t\thandle: await this.service.reserve(options)\n\t\t\t};\n\t\t} catch (err) {\n\t\t\tif (!isAttachmentAlreadyExists(err)) throw err;\n\t\t\treturn {\n\t\t\t\tkind: \"deduped\",\n\t\t\t\tresult: {\n\t\t\t\t\thash: err.hash,\n\t\t\t\t\tref: err.ref,\n\t\t\t\t\theader: dedupedHeader(err.hash, options)\n\t\t\t\t}\n\t\t\t};\n\t\t}\n\t}\n\tasync reserve(options, send) {\n\t\tconst outcome = await this.reserveOrDedup(options);\n\t\tif (outcome.kind === \"deduped\") return outcome.result;\n\t\treturn send(outcome.handle);\n\t}\n\tasync upload(input, options) {\n\t\tconst emitter = new ProgressEmitter(options);\n\t\tconst signal = input.signal;\n\t\ttry {\n\t\t\tsignal?.throwIfAborted();\n\t\t\tlet preprocessed;\n\t\t\tif (\"preprocessed\" in input) preprocessed = input.preprocessed;\n\t\t\telse {\n\t\t\t\temitter.stage(\"hashing\", { total: input.file.size });\n\t\t\t\tpreprocessed = await this.hashFile(input.file, {\n\t\t\t\t\t...input.fileName !== void 0 ? { fileName: input.fileName } : {},\n\t\t\t\t\t...input.mimeType !== void 0 ? { mimeType: input.mimeType } : {},\n\t\t\t\t\t...input.documentId !== void 0 ? { documentId: input.documentId } : {}\n\t\t\t\t}, signal);\n\t\t\t}\n\t\t\tconst sizeBytes = preprocessed.sizeBytes;\n\t\t\tsignal?.throwIfAborted();\n\t\t\temitter.stage(\"reserving\");\n\t\t\tconst outcome = await this.reserveOrDedup(preprocessed.options);\n\t\t\tif (outcome.kind === \"deduped\") {\n\t\t\t\temitter.finishDeduped();\n\t\t\t\treturn outcome.result;\n\t\t\t}\n\t\t\tsignal?.throwIfAborted();\n\t\t\temitter.stage(\"uploading\", { total: sizeBytes });\n\t\t\tconst sendOptions = {\n\t\t\t\t...emitter.active ? { onProgress: (loaded, total) => emitter.bytes(loaded, total ?? sizeBytes) } : {},\n\t\t\t\t...signal ? { signal } : {}\n\t\t\t};\n\t\t\tconst result = await outcome.handle.send(preprocessed.blob, sendOptions);\n\t\t\temitter.finish();\n\t\t\treturn result;\n\t\t} catch (err) {\n\t\t\temitter.fail();\n\t\t\tthrow err;\n\t\t}\n\t}\n\t/**\n\t* The single site where download bytes are instrumented.\n\t*\n\t* It sits here, above the service, rather than in any store or transport:\n\t* one logical get can be several byte streams underneath (an evicted\n\t* attachment is fetched from the transport, written to disk, then re-read),\n\t* so counting lower down would double-count that path and still miss\n\t* local-filesystem reads. Wrapping what `service.get` returns covers the\n\t* presigned, switchboard, legacy and local paths by construction, and\n\t* `downloadBlob`/`saveAttachment`/`downloadObjectUrl` inherit it.\n\t*/\n\tasync getWithProgress(input, emitter) {\n\t\tconst { header, body } = await this.service.get(input.ref, {\n\t\t\tdocumentId: input.documentId,\n\t\t\tsignal: input.signal\n\t\t});\n\t\temitter.stage(\"downloading\", { total: header.sizeBytes });\n\t\tif (!emitter.active) return {\n\t\t\theader,\n\t\t\tbody\n\t\t};\n\t\treturn {\n\t\t\theader,\n\t\t\tbody: withByteProgress(body, {\n\t\t\t\tonBytes: (loaded) => emitter.bytes(loaded),\n\t\t\t\tonDone: () => emitter.finish(),\n\t\t\t\tonError: () => emitter.fail()\n\t\t\t})\n\t\t};\n\t}\n\tasync download(input, options) {\n\t\tconst emitter = new ProgressEmitter(options);\n\t\ttry {\n\t\t\tinput.signal?.throwIfAborted();\n\t\t\temitter.stage(\"requesting-download-target\");\n\t\t\treturn await this.getWithProgress(input, emitter);\n\t\t} catch (err) {\n\t\t\temitter.fail();\n\t\t\tthrow err;\n\t\t}\n\t}\n\tasync downloadBlob(input, options) {\n\t\tconst emitter = new ProgressEmitter(options);\n\t\ttry {\n\t\t\tinput.signal?.throwIfAborted();\n\t\t\temitter.stage(\"requesting-download-target\");\n\t\t\tconst { header, body } = await this.getWithProgress(input, emitter);\n\t\t\tconst reader = body.getReader();\n\t\t\tconst chunks = [];\n\t\t\tfor (;;) {\n\t\t\t\tconst { done, value } = await reader.read();\n\t\t\t\tif (done) break;\n\t\t\t\tchunks.push(value);\n\t\t\t}\n\t\t\tconst blob = new Blob(chunks, { type: options?.mimeType ?? header.mimeType });\n\t\t\temitter.finish();\n\t\t\treturn {\n\t\t\t\tblob,\n\t\t\t\theader\n\t\t\t};\n\t\t} catch (err) {\n\t\t\temitter.fail();\n\t\t\tthrow err;\n\t\t}\n\t}\n\tasync saveAttachment(input, options) {\n\t\tif (typeof document === \"undefined\") throw new Error(\"saveAttachment requires a browser environment; use downloadBlob elsewhere\");\n\t\tconst { blob, header } = await this.downloadBlob(input, options);\n\t\tconst url = URL.createObjectURL(blob);\n\t\ttry {\n\t\t\tconst anchor = document.createElement(\"a\");\n\t\t\tanchor.href = url;\n\t\t\tanchor.download = options?.fileName ?? header.fileName;\n\t\t\tanchor.click();\n\t\t} finally {\n\t\t\tURL.revokeObjectURL(url);\n\t\t}\n\t}\n\tasync downloadObjectUrl(input, options) {\n\t\tconst { blob, header } = await this.downloadBlob(input, options);\n\t\tconst url = URL.createObjectURL(blob);\n\t\tlet revoked = false;\n\t\treturn {\n\t\t\turl,\n\t\t\theader,\n\t\t\trevoke: () => {\n\t\t\t\tif (revoked) return;\n\t\t\t\trevoked = true;\n\t\t\t\tURL.revokeObjectURL(url);\n\t\t\t}\n\t\t};\n\t}\n\tasync getShareLink(input) {\n\t\tinput.signal?.throwIfAborted();\n\t\tconst target = await this.service.getDownloadTarget(input.ref, {\n\t\t\tdocumentId: input.documentId,\n\t\t\t...input.expiresIn !== void 0 ? { expiresIn: input.expiresIn } : {},\n\t\t\t...input.signal !== void 0 ? { signal: input.signal } : {}\n\t\t});\n\t\tif (target.kind !== \"presigned-get\") throw new Error(\"Public share links require a presigned-capable storage backend (S3); this server answered with an authenticated target\");\n\t\treturn {\n\t\t\turl: target.url,\n\t\t\texpiresAtUtc: target.expiresAtUtc\n\t\t};\n\t}\n\tuploadMany(inputs, options) {\n\t\treturn runWithConcurrency(inputs, (input, index) => this.upload(input, itemProgress(options, index)), batchRunOptions(inputs.length, options));\n\t}\n\t/**\n\t* `concurrency` bounds download-target negotiation, not simultaneous byte\n\t* transfer: each item resolves when its stream is handed over, and the bytes\n\t* move only as the caller reads. Byte progress makes that pre-existing\n\t* behavior visible; it does not change it.\n\t*/\n\tdownloadMany(inputs, options) {\n\t\treturn runWithConcurrency(inputs, (input, index) => this.download(input, itemProgress(options, index)), batchRunOptions(inputs.length, options));\n\t}\n};\nfunction createAttachmentClient(service) {\n\treturn new AttachmentClientImpl(service);\n}\n//#endregion\nexport { AttachmentAlreadyExists, AttachmentNotFound, AttachmentPending, AttachmentService, AttachmentTransferError, DEFAULT_ATTACHMENT_BATCH_CONCURRENCY, DEFAULT_PROGRESS_THROTTLE_MS, HashMismatch, InvalidAttachmentRef, NullAttachmentTransport, ProgressEmitter, RemoteAttachmentStore, RemoteAttachmentUpload, RemoteAttachmentUploadFactory, RemoteReservationStore, ReservationNotFound, RoutingAttachmentService, SizeMismatch, SwitchboardAttachmentTransport, UploadTooLarge, createAttachmentClient, createFetchUploadTransport, createRef, createRemoteAttachmentService, createXhrUploadTransport, parseAttachmentDownloadTarget, parseAttachmentUploadTarget, parseRef, progressFraction, runWithConcurrency, withByteProgress };\n\n//# sourceMappingURL=client.js.map","// Attachment-service accessor + file helpers shared by the attachment-* commands.\nimport { openAsBlob } from \"node:fs\";\nimport { extname } from \"node:path\";\nimport type { CommandContext } from \"../../core/types.js\";\nimport type { AttachmentRef, IAttachmentService } from \"./types.js\";\n\n/**\n * The attachment service of the run's reactor. Never builds the reactor for\n * it: only where the Cli serves (`folders` marks that) or where its reactor\n * is attached to a switchboard, which reaching builds nothing.\n */\nexport async function getAttachmentService(\n ctx: Pick<CommandContext, \"folders\" | \"reactor\" | \"reactorAttached\">,\n): Promise<IAttachmentService | undefined> {\n if (!ctx.folders && !ctx.reactorAttached) return undefined;\n const rc = await ctx.reactor?.();\n return rc?.attachments;\n}\n\nexport function attachmentsUnavailableMessage(): string {\n return (\n \"Attachments need a running reactor (daemon mode) on a switchboard the \" +\n \"Cli attached to. None is available in this context.\"\n );\n}\n\n// Type bridge; the ref format is validated server-side.\nexport function asRef(ref: string): AttachmentRef {\n return ref as AttachmentRef;\n}\n\n// Duck-typed: reactor-attachments duplicates this error across its `.` and `/client` bundles, so instanceof is unreliable.\nexport function isAttachmentAlreadyExists(\n err: unknown,\n): err is { ref: string; hash: string } {\n if (!(err instanceof Error)) return false;\n if (!(\"ref\" in err) || !(\"hash\" in err)) return false;\n return (\n err.constructor.name === \"AttachmentAlreadyExists\" ||\n /already exists/i.test(err.message)\n );\n}\n\n// Extension → MIME; falls back to octet-stream, override via mimeType.\nconst MIME_BY_EXT: Record<string, string> = {\n \".png\": \"image/png\",\n \".jpg\": \"image/jpeg\",\n \".jpeg\": \"image/jpeg\",\n \".gif\": \"image/gif\",\n \".webp\": \"image/webp\",\n \".svg\": \"image/svg+xml\",\n \".pdf\": \"application/pdf\",\n \".json\": \"application/json\",\n \".txt\": \"text/plain\",\n \".md\": \"text/markdown\",\n \".csv\": \"text/csv\",\n};\n\nexport function inferMimeType(filePath: string, override?: string): string {\n if (override) return override;\n return (\n MIME_BY_EXT[extname(filePath).toLowerCase()] ?? \"application/octet-stream\"\n );\n}\n\nexport async function fileToBlob(\n filePath: string,\n mimeType: string,\n): Promise<Blob> {\n return openAsBlob(filePath, { type: mimeType });\n}\n","// Shared attachment-* commands for reactor-backed ph-clint CLIs. Opt-in: spread\n// `...createAttachmentCommands()` into a CLI's `commands` array (like\n// `...createClaudeAuthCommands()`). They self-gate — outside a running reactor\n// they return an \"unavailable\" message rather than erroring.\nimport path from \"node:path\";\nimport { createWriteStream } from \"node:fs\";\nimport { Readable } from \"node:stream\";\nimport { pipeline } from \"node:stream/promises\";\nimport type { ReadableStream as NodeWebReadableStream } from \"node:stream/web\";\nimport { z } from \"zod\";\nimport {\n createAttachmentClient,\n type AttachmentUploadResult,\n} from \"@powerhousedao/reactor-attachments/client\";\nimport { defineCommand } from \"../../core/command.js\";\nimport type { Command } from \"../../core/types.js\";\nimport {\n asRef,\n attachmentsUnavailableMessage,\n fileToBlob,\n getAttachmentService,\n inferMimeType,\n isAttachmentAlreadyExists,\n} from \"./attachment.js\";\n\nconst documentIdSchema = z\n .string()\n .optional()\n .describe(\n \"Document whose operations reference the attachment. A switchboard serves an attachment only through such a document, so a read there needs it.\",\n );\n\nexport function createAttachmentCommands(): Command[] {\n const preprocess = defineCommand({\n id: \"attachment-preprocess\",\n description:\n \"Compute an attachment's content-addressed ref (attachment://v1:<sha256>) from a local file WITHOUT uploading. Embed the returned ref in a document action now, then send the bytes with attachment-upload for the same file after / in parallel with submitting the action.\",\n inputSchema: z.object({\n filePath: z\n .string()\n .describe(\n \"Path to the local file to reference (absolute, or relative to the workdir).\",\n ),\n mimeType: z\n .string()\n .optional()\n .describe(\"MIME type; inferred from the file extension when omitted.\"),\n fileName: z\n .string()\n .optional()\n .describe(\"Stored file name; defaults to the file's basename.\"),\n }),\n execute: async (input, context) => {\n const service = await getAttachmentService(context);\n if (!service) return { text: attachmentsUnavailableMessage() };\n\n const filePath = path.resolve(context.workdir, input.filePath);\n const mimeType = inferMimeType(filePath, input.mimeType);\n const fileName = input.fileName ?? path.basename(filePath);\n const blob = await fileToBlob(filePath, mimeType);\n\n const pre = await createAttachmentClient(service).preprocess(blob, {\n fileName,\n mimeType,\n });\n return {\n text:\n `ref: ${pre.ref}\\n` +\n `hash: ${pre.hash}\\n` +\n `sizeBytes: ${pre.sizeBytes}\\n` +\n `mimeType: ${mimeType}\\n` +\n `fileName: ${fileName}\\n` +\n `Not uploaded yet — embed this ref in the action, then run attachment-upload on the same file to send the bytes.`,\n };\n },\n });\n\n const upload = defineCommand({\n id: \"attachment-upload\",\n description:\n \"Upload a local file to the attachment store and return its content-addressed ref (attachment://v1:<sha256>). The ref is deterministic from the bytes and identical content dedups. Embed the ref in a document action; the action may be submitted before or after this upload.\",\n inputSchema: z.object({\n filePath: z\n .string()\n .describe(\n \"Path to the local file to upload (absolute, or relative to the workdir).\",\n ),\n mimeType: z\n .string()\n .optional()\n .describe(\"MIME type; inferred from the file extension when omitted.\"),\n fileName: z\n .string()\n .optional()\n .describe(\"Stored file name; defaults to the file's basename.\"),\n }),\n execute: async (input, context) => {\n const service = await getAttachmentService(context);\n if (!service) return { text: attachmentsUnavailableMessage() };\n\n const filePath = path.resolve(context.workdir, input.filePath);\n const mimeType = inferMimeType(filePath, input.mimeType);\n const fileName = input.fileName ?? path.basename(filePath);\n const blob = await fileToBlob(filePath, mimeType);\n\n const client = createAttachmentClient(service);\n const pre = await client.preprocess(blob, { fileName, mimeType });\n\n let result: AttachmentUploadResult;\n try {\n result = await client.reserve(pre.options, (handle) =>\n handle.send(pre.blob),\n );\n } catch (err) {\n // Dedup: client.reserve's instanceof catch can miss this across entry bundles, so recover via the deterministic ref.\n if (!isAttachmentAlreadyExists(err)) throw err;\n const header = await service.stat(pre.ref);\n result = { ref: pre.ref, hash: pre.hash, header };\n }\n\n return {\n text:\n `ref: ${result.ref}\\n` +\n `hash: ${result.hash}\\n` +\n `status: ${result.header.status}\\n` +\n `sizeBytes: ${result.header.sizeBytes}\\n` +\n `mimeType: ${result.header.mimeType}\\n` +\n `fileName: ${result.header.fileName}`,\n };\n },\n });\n\n const stat = defineCommand({\n id: \"attachment-stat\",\n description:\n \"Look up an attachment by ref (attachment://v1:<sha256>) and report its status + metadata. status='pending' = reserved but not yet uploaded; 'available' = stored; 'evicted' = metadata known, bytes reclaimed. On a switchboard, pass the documentId of a document whose operations reference the attachment.\",\n inputSchema: z.object({\n ref: z\n .string()\n .describe(\"Attachment ref, e.g. attachment://v1:<sha256hex>.\"),\n documentId: documentIdSchema,\n }),\n execute: async (input, context) => {\n const service = await getAttachmentService(context);\n if (!service) return { text: attachmentsUnavailableMessage() };\n\n try {\n const h = await service.stat(\n asRef(input.ref),\n ...readOptions(input.documentId),\n );\n return {\n text:\n `ref: ${input.ref}\\n` +\n `status: ${h.status}\\n` +\n `mimeType: ${h.mimeType}\\n` +\n `fileName: ${h.fileName}\\n` +\n `sizeBytes: ${h.sizeBytes}\\n` +\n `createdAtUtc: ${h.createdAtUtc}`,\n };\n } catch (err) {\n return {\n text:\n `Not found or error for ${input.ref}: ${(err as Error).message}` +\n documentIdHint(input.documentId),\n };\n }\n },\n });\n\n const get = defineCommand({\n id: \"attachment-get\",\n description:\n \"Download an attachment's bytes by ref (attachment://v1:<sha256>) to a local file. Errors if the attachment is still pending (bytes not yet uploaded). On a switchboard, pass the documentId of a document whose operations reference the attachment.\",\n inputSchema: z.object({\n ref: z\n .string()\n .describe(\"Attachment ref, e.g. attachment://v1:<sha256hex>.\"),\n outPath: z\n .string()\n .describe(\n \"Path to write the bytes to (absolute, or relative to the workdir).\",\n ),\n documentId: documentIdSchema,\n }),\n execute: async (input, context) => {\n const service = await getAttachmentService(context);\n if (!service) return { text: attachmentsUnavailableMessage() };\n\n const outPath = path.resolve(context.workdir, input.outPath);\n try {\n const res = await service.get(\n asRef(input.ref),\n ...readOptions(input.documentId),\n );\n const body = res.body as unknown as NodeWebReadableStream<Uint8Array>;\n await pipeline(Readable.fromWeb(body), createWriteStream(outPath));\n return {\n text:\n `Wrote ${res.header.sizeBytes} bytes to ${outPath}\\n` +\n `ref: ${input.ref}\\n` +\n `mimeType: ${res.header.mimeType}\\n` +\n `fileName: ${res.header.fileName}`,\n };\n } catch (err) {\n return {\n text:\n `Could not get ${input.ref}: ${(err as Error).message}` +\n documentIdHint(input.documentId),\n };\n }\n },\n });\n\n return [preprocess, upload, stat, get];\n}\n\n/** The read options for `documentId`; none without one, as before. */\nfunction readOptions(\n documentId: string | undefined,\n): [] | [{ documentId: string }] {\n return documentId === undefined ? [] : [{ documentId }];\n}\n\n/** Why a read without a document id fails on a switchboard. */\nfunction documentIdHint(documentId: string | undefined): string {\n return documentId === undefined\n ? \"\\nOn a switchboard an attachment is served only through a document \" +\n \"that references it: pass documentId.\"\n : \"\";\n}\n","/**\n * Powerhouse integration for ph-clint: a CLI's reactor is a client of a\n * RUNNING switchboard (`attachDefaultReactor`, which a host runner calls),\n * with its drives, change subscriptions, signing rules and attachment\n * service. clint starts no reactor, switchboard or Connect of its own.\n *\n * All Powerhouse imports are lazy — the library works without them installed.\n */\n\nexport type {\n ReactorContext,\n ReactorSetupContext,\n ReactorConfiguration,\n RemoteReactorConfig,\n RemoteReactorSource,\n DriveConfig,\n EnsureDriveClient,\n DriveEntry,\n FolderEntry,\n FolderOperations,\n SubscriptionConfig,\n DocumentRegistry,\n AnyRegistry,\n RegistryEntry,\n TypedReactorClient,\n TypedDocumentChangeEvent,\n ReactorWrites,\n IAttachmentService,\n AttachmentRef,\n AttachmentResponse,\n AttachmentUploadResult,\n ReserveAttachmentOptions,\n AttachmentHeader,\n} from \"./types.js\";\n\nexport type { InferRegistry, ActionOf } from \"./registry.js\";\nexport { defineRegistry } from \"./registry.js\";\n\nexport { bridgeSubscriptions } from \"./subscriptions.js\";\nexport { ensureDrive } from \"./drive.js\";\nexport { attachRemoteReactor } from \"./remote-reactor.js\";\nexport type {\n AttachRemoteReactorOptions,\n RemoteReactorAttachment,\n} from \"./remote-reactor.js\";\nexport {\n SignerNotReadyError,\n createGatedSigner,\n signerReady,\n policyOfHeader,\n} from \"./signing.js\";\nexport type { SignaturePolicy } from \"./signing.js\";\nexport { createReactorWrites } from \"./writes.js\";\nexport type { ReactorWritesOptions, ReactorWritesHandle } from \"./writes.js\";\nexport { createDocumentChangeTrigger } from \"./change-trigger.js\";\nexport type { DocumentChangeTriggerOptions } from \"./change-trigger.js\";\nexport { isDocType } from \"./type-guard.js\";\nexport { createFolderOperations, createFolderCommands } from \"./folders.js\";\nexport { createAttachmentCommands } from \"./attachment-commands.js\";\nexport {\n getAttachmentService,\n asRef,\n inferMimeType,\n fileToBlob,\n isAttachmentAlreadyExists,\n} from \"./attachment.js\";\n\nimport type { IReactorClient } from \"@powerhousedao/reactor\";\nimport { ensureDrive } from \"./drive.js\";\nimport { bridgeSubscriptions } from \"./subscriptions.js\";\nimport { createReactorWrites } from \"./writes.js\";\nimport type {\n ReactorContext,\n ReactorSetupContext,\n DriveEntry,\n DocumentRegistry,\n AnyRegistry,\n IAttachmentService,\n RemoteReactorConfig,\n RemoteReactorSource,\n TypedReactorClient,\n} from \"./types.js\";\n\n/**\n * Options for attachDefaultReactor(): where the switchboard is, how the\n * client signs and authenticates, and what the CLI's reactor holds there.\n */\nexport interface AttachDefaultReactorOptions<\n R extends DocumentRegistry = AnyRegistry,\n> extends RemoteReactorConfig<R> {\n /** A switchboard drive address, `<switchboard>/d/<slug>`; its GraphQL\n * endpoint or bare origin attach too, but name no drive. */\n url: string;\n}\n\n/**\n * The `ReactorConfiguration.remote` a runner attaches with: the config as\n * given, or the function's answer for this setup context. None: `{}`.\n */\nexport async function resolveRemoteReactorConfig<\n R extends DocumentRegistry = AnyRegistry,\n>(\n source: RemoteReactorSource<R> | undefined,\n setup: ReactorSetupContext<R>,\n): Promise<RemoteReactorConfig<R>> {\n if (typeof source === \"function\") return source(setup);\n return source ?? {};\n}\n\n/**\n * The attachment service of the switchboard at `endpoint`. Its\n * `/attachments/*` routes mount at the host root, so the origin is used.\n */\nasync function remoteAttachmentService(\n endpoint: string,\n jwtHandler: ((url: string) => Promise<string | undefined>) | undefined,\n): Promise<IAttachmentService> {\n const { createRemoteAttachmentService } =\n await import(\"@powerhousedao/reactor-attachments\");\n return createRemoteAttachmentService({\n remoteUrl: new URL(endpoint).origin,\n ...(jwtHandler ? { jwtHandler } : {}),\n });\n}\n\n/** The id of the drive a switchboard serves under `slug`. */\nasync function driveOfAddress(\n client: IReactorClient,\n slug: string,\n endpoint: string,\n): Promise<string> {\n try {\n return (await client.get(slug)).header.id;\n } catch (cause) {\n throw new Error(\n `The switchboard at ${endpoint} serves no drive \"${slug}\": the drive address must name one of its drives.`,\n { cause },\n );\n }\n}\n\n/**\n * Build a ReactorContext on a RUNNING switchboard, with the drives and\n * subscriptions the options ask for. The default drive is the first personal\n * drive the options ask for, else the first, else the one the address names.\n * The signer, its rules and its watch go to\n * `createReactorWrites`, which emits `powerhouse:writes:ready` on `ctx.emit`;\n * a signer change also reconnects the realtime socket with the current\n * bearer. Without `ctx.attachments` the context gets the switchboard's own\n * attachment service, authenticated by `ctx.attachmentJwtHandler`, else by\n * `tokenProvider`. `shutdown` releases only this process's side (the\n * bridged subscriptions, the signer watch, the client) and runs once.\n */\nexport async function attachDefaultReactor<\n R extends DocumentRegistry = AnyRegistry,\n>(\n ctx: ReactorSetupContext<R>,\n options: AttachDefaultReactorOptions<R>,\n): Promise<ReactorContext<R>> {\n const { attachRemoteReactor } = await import(\"./remote-reactor.js\");\n const { switchboardOfDrive } =\n await import(\"@powerhousedao/shared/host-tokens\");\n\n // A socket presents the credentials it opened with until it is replaced,\n // and the bearer follows the signer's user.\n let credentialsChanged = (): void => undefined;\n const { onSignerChange } = options;\n const handle = createReactorWrites({\n signer: options.signer,\n legacyDocuments: options.legacyDocuments,\n accepts: options.accepts,\n ...(onSignerChange\n ? {\n onSignerChange: (listener: () => void) =>\n onSignerChange(() => {\n credentialsChanged();\n listener();\n }),\n }\n : {}),\n ...(ctx.emit ? { emit: ctx.emit } : {}),\n });\n\n let attachment: Awaited<ReturnType<typeof attachRemoteReactor>>;\n try {\n attachment = await attachRemoteReactor({\n url: options.url,\n documentModels: options.documentModels ?? [],\n ...(handle.signer ? { signer: handle.signer } : {}),\n ...(options.tokenProvider\n ? { tokenProvider: options.tokenProvider }\n : {}),\n });\n } catch (error) {\n handle.stop();\n throw error;\n }\n const client = attachment.client as IReactorClient & {\n dispose?: () => void;\n notifyCredentialsChanged?: () => void;\n };\n credentialsChanged = () => client.notifyCredentialsChanged?.();\n\n const driveConfigs =\n options.drives ??\n (options.drive ? [{ ...options.drive, role: \"personal\" as const }] : []);\n const drives: DriveEntry[] = [];\n for (const cfg of driveConfigs) {\n const drive = await ensureDrive(client, cfg);\n // A drive the host creates later is not listed yet.\n if (drive.deferred) continue;\n drives.push({ id: drive.id, name: drive.name, role: cfg.role });\n }\n const personal = drives.find((d) => d.role === \"personal\");\n const addressed = switchboardOfDrive(options.url);\n let driveId = personal?.id ?? drives[0]?.id ?? \"\";\n let driveUrl =\n addressed && driveId ? `${addressed.base}/d/${driveId}` : undefined;\n if (!driveId && addressed) {\n driveId = await driveOfAddress(client, addressed.slug, attachment.endpoint);\n driveUrl = options.url;\n }\n\n let unsubscribe: (() => void) | undefined;\n if (options.subscriptions && ctx.emit) {\n unsubscribe = bridgeSubscriptions<R>(\n client,\n options.subscriptions,\n ctx.emit,\n );\n }\n\n const { tokenProvider } = options;\n const attachments =\n ctx.attachments ??\n (await remoteAttachmentService(\n attachment.endpoint,\n ctx.attachmentJwtHandler ?? (tokenProvider && (() => tokenProvider())),\n ));\n\n let stopped = false;\n const result: ReactorContext<R> = {\n client: client as unknown as TypedReactorClient<R>,\n driveId,\n personalDriveId: personal?.id,\n drives,\n switchboardUrl: attachment.endpoint,\n ...(driveUrl ? { driveUrl } : {}),\n attachments,\n writes: handle.writes,\n shutdown() {\n if (stopped) return Promise.resolve();\n stopped = true;\n unsubscribe?.();\n handle.stop();\n client.dispose?.();\n return Promise.resolve();\n },\n };\n\n ctx.emit?.(\"powerhouse:ready\", { driveId });\n\n return result;\n}\n"],"x_google_ignoreList":[10,11,12],"mappings":";;;;;;;;;;;;;;AASA,SAAgB,cAMd,SACsC;CACtC,IAAI,QAAQ,cAAc,QAAQ,WAAW,SAAS,GAAG;EACvD,MAAM,SAAS,gBAAgB,QAAQ,WAAW;EAClD,MAAM,W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