@powerhousedao/reactor-attachments 6.2.3-dev.71 → 6.2.3-dev.73
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/client.js +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/dist/{null-attachment-transport-Cm_kb5ww.js → null-attachment-transport-BMa3MUA2.js} +2 -2
- package/dist/null-attachment-transport-BMa3MUA2.js.map +1 -0
- package/package.json +3 -3
- package/dist/null-attachment-transport-Cm_kb5ww.js.map +0 -1
package/dist/client.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
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";
|
|
2
|
-
import { a as RemoteAttachmentUpload, c as createFetchUploadTransport, d as parseAttachmentDownloadTarget, f as parseAttachmentUploadTarget, i as RemoteAttachmentUploadFactory, n as createRemoteAttachmentService, o as RemoteReservationStore, r as RemoteAttachmentStore, s as createXhrUploadTransport, t as NullAttachmentTransport, u as AttachmentService } from "./null-attachment-transport-
|
|
2
|
+
import { a as RemoteAttachmentUpload, c as createFetchUploadTransport, d as parseAttachmentDownloadTarget, f as parseAttachmentUploadTarget, i as RemoteAttachmentUploadFactory, n as createRemoteAttachmentService, o as RemoteReservationStore, r as RemoteAttachmentStore, s as createXhrUploadTransport, t as NullAttachmentTransport, u as AttachmentService } from "./null-attachment-transport-BMa3MUA2.js";
|
|
3
3
|
import { n as sha256HexOfBlob } from "./hash-BobbR4r4.js";
|
|
4
4
|
//#region src/concurrency.ts
|
|
5
5
|
/**
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","names":[],"sources":["../src/reserve-metadata.ts","../src/storage/kysely/types.ts","../src/storage/kysely/attachment-store.ts","../src/storage/kysely/reservation-store.ts","../src/storage/migrations/migrator.ts","../src/direct/direct-attachment-upload.ts","../src/direct/direct-attachment-upload-factory.ts","../src/direct/filesystem-attachment-backend.ts","../src/attachment-builder.ts","../src/reference-index/attachment-schema-compiler.ts","../src/read-models/attachment-reference/index-builder.ts","../src/read-models/attachment-reference/attachment-reference-read-model.ts","../src/read-models/attachment-reference/storage/types.ts","../src/read-models/attachment-reference/kysely-attachment-reference-store.ts","../src/read-models/attachment-reference/storage/migrations/migrator.ts","../src/storage/s3/config.ts","../src/storage/s3/keying.ts","../src/storage/s3/primitives.ts","../src/storage/s3/backend.ts","../src/storage/s3/upload-factory.ts"],"mappings":";;;;;;;;KAeY;EACV;EACA;EACA;;;;;;;;wBASc,wBAAwB,MAAM;;;UCzB7B;EACf;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;UAGe;EACf;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;UAGe;EACf,YAAY;EACZ,wBAAwB;;;;qBC4Cb,iCAAiC;mBAIzB;mBACA;mBACA;mBALF;EAEjB,YACmB,IAAI,OAAO,qBACX,WAAW,sBACX;EAGb,KAAK,MAAM,iBAAiB,QAAQ;EAgCpC,IAAI,MAAM,iBAAiB;EAU3B,IACJ,MAAM,gBACN,SAAS,aACT,sBACC,QAAQ;EA+CL,IACJ,MAAM,gBACN,UAAU,oBACV,MAAM,eAAe,cACpB;EAiDG,MAAM,MAAM,iBAAiB;EAyB7B,eAAe;UAYP;UAmBA;UAyCN;UAIA;UASA;;;;qBC3UG;qBAeA,kCAAkC;mBAI1B;mBAHF;EAEjB,YACmB,IAAI,OAAO,qBAC5B;EAKI,OAAO,SAAS,2BAA2B,QAAQ;EAwBnD,IAAI,wBAAwB,QAAQ;EAepC,OAAO,wBAAwB;EAS/B,cAAc,MAAK,OAAoB;;;;qBCtElC;UAEI;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O,yBACN;;;;UCtDY;EACf;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;UAGe;EACf,sBAAsB;;;;qBCoCX,0CAET,4BACA,6BACA;mBAE2B;EAA7B,YAA6B,IAAI,OAAO;EAElC,aAAa,oBAAoB,KAAK,gBAAgB;EAWtD,kBACJ,oBACA,KAAK,gBACJ;;;;;;;EAkBG,eACJ,4BACA,gBACC,QAAQ;EAsCL,cACJ,qBAAqB,6BACpB;EAyBG,gBAAgB,iCAAiC;;;;qBCxJ5C;qBACA;qBAEA;UAGI;EACf;EACA;EACA,QAAQ;;wBA0CY,iCACpB,IAAI,iBACJ,kBACC,QAAQ;wBAuBW,qCACpB,IAAI,iBACJ,kBACC,QAAQ;wBASW,sCACpB,IAAI,iBACJ,kBAA4C,kCAAA;;;qBC/FjC;qBACA;qBACA;qBACA;KAED;EACV;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;KAGU;EACN;;EACA;EAAY,IAAI;;KAEjB,cAAc,SAAS;wBA4EZ,4BAA4B;wBA2B5B,6BACd,MAAK,cACJ;;;wBClHa,sBAAsB,cAAc;wBAuBpC,kBAAkB;;;UCrBjB;EACf,KAAK,kBAAkB;;KAGb,eACV,gBACA,iBACA,6BACG;KAEA;EACH,SAAS;EACT,UAAU;EACV,YAAY;;qBASD;WAMA,QAAQ;WALV,QAAQ;WACR,SAAS;WACT,WAAW;EAEpB,YACW,QAAQ,oBACjB,eAAc;EAiBhB,uBAAuB;EAOvB,sBAAsB,cAAc;EAkBpC,sBAAsB;EAOtB,WAAW,eAAe;EAIpB,mBACJ,cACA,kBACA,sBACC,QAAQ;EAqBL,qBACJ,cACA,sBACC,QAAQ;;wBAkBG,6BACd,QAAQ,oBACR,eAAc,eACb;;;KClHS;EACV,SAAS;EACT,UAAU;EACV,YAAY;EACZ;EACA;;;
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":[],"sources":["../src/reserve-metadata.ts","../src/storage/kysely/types.ts","../src/storage/kysely/attachment-store.ts","../src/storage/kysely/reservation-store.ts","../src/storage/migrations/migrator.ts","../src/direct/direct-attachment-upload.ts","../src/direct/direct-attachment-upload-factory.ts","../src/direct/filesystem-attachment-backend.ts","../src/attachment-builder.ts","../src/reference-index/attachment-schema-compiler.ts","../src/read-models/attachment-reference/index-builder.ts","../src/read-models/attachment-reference/attachment-reference-read-model.ts","../src/read-models/attachment-reference/storage/types.ts","../src/read-models/attachment-reference/kysely-attachment-reference-store.ts","../src/read-models/attachment-reference/storage/migrations/migrator.ts","../src/storage/s3/config.ts","../src/storage/s3/keying.ts","../src/storage/s3/primitives.ts","../src/storage/s3/backend.ts","../src/storage/s3/upload-factory.ts"],"mappings":";;;;;;;;KAeY;EACV;EACA;EACA;;;;;;;;wBASc,wBAAwB,MAAM;;;UCzB7B;EACf;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;UAGe;EACf;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;UAGe;EACf,YAAY;EACZ,wBAAwB;;;;qBC4Cb,iCAAiC;mBAIzB;mBACA;mBACA;mBALF;EAEjB,YACmB,IAAI,OAAO,qBACX,WAAW,sBACX;EAGb,KAAK,MAAM,iBAAiB,QAAQ;EAgCpC,IAAI,MAAM,iBAAiB;EAU3B,IACJ,MAAM,gBACN,SAAS,aACT,sBACC,QAAQ;EA+CL,IACJ,MAAM,gBACN,UAAU,oBACV,MAAM,eAAe,cACpB;EAiDG,MAAM,MAAM,iBAAiB;EAyB7B,eAAe;UAYP;UAmBA;UAyCN;UAIA;UASA;;;;qBC3UG;qBAeA,kCAAkC;mBAI1B;mBAHF;EAEjB,YACmB,IAAI,OAAO,qBAC5B;EAKI,OAAO,SAAS,2BAA2B,QAAQ;EAwBnD,IAAI,wBAAwB,QAAQ;EAepC,OAAO,wBAAwB;EAS/B,cAAc,MAAK,OAAoB;;;;qBCtElC;UAEI;EACf;EACA;EACA,QAAQ;;wBAkBY,wBACpB,IAAI,aACJ,kBACC,QAAQ;;;qBCGE,kCA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BACC,QAAQ;EAWL,OAAO,MAAM,iBAAiB;EAoB9B,UAAU,QAAQ;;wBAaV,0BACd,IAAI,OAAO,qBACX,QAAQ,oBACR,eAAc,kCACb;;;qBC7JU,qCAAqC;EAChD,aAAa,aAAa,cAAc"}
|
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { a as parseRef, c as AttachmentPending, d as InvalidAttachmentMetadata, 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";
|
|
2
|
-
import { a as RemoteAttachmentUpload, c as createFetchUploadTransport, d as parseAttachmentDownloadTarget, f as parseAttachmentUploadTarget, i as RemoteAttachmentUploadFactory, l as isBlob, n as createRemoteAttachmentService, o as RemoteReservationStore, r as RemoteAttachmentStore, s as createXhrUploadTransport, t as NullAttachmentTransport, u as AttachmentService } from "./null-attachment-transport-
|
|
2
|
+
import { a as RemoteAttachmentUpload, c as createFetchUploadTransport, d as parseAttachmentDownloadTarget, f as parseAttachmentUploadTarget, i as RemoteAttachmentUploadFactory, l as isBlob, n as createRemoteAttachmentService, o as RemoteReservationStore, r as RemoteAttachmentStore, s as createXhrUploadTransport, t as NullAttachmentTransport, u as AttachmentService } from "./null-attachment-transport-BMa3MUA2.js";
|
|
3
3
|
import { t as AttachmentSchemaCompiler } from "./attachment-schema-compiler-rIaJpiHO.js";
|
|
4
4
|
import { dirname, join } from "node:path";
|
|
5
5
|
import { Migrator, sql } from "kysely";
|
|
@@ -1236,7 +1236,7 @@ function isObjectNotFound(error) {
|
|
|
1236
1236
|
function requireHashFirstReservation(reservation) {
|
|
1237
1237
|
if (reservation.clientHash === null) throw new Error("S3 attachment reservations require a client hash");
|
|
1238
1238
|
deriveS3AttachmentKey(reservation.clientHash, "validation");
|
|
1239
|
-
if (reservation.sizeBytes === null || !Number.isSafeInteger(reservation.sizeBytes) || reservation.sizeBytes
|
|
1239
|
+
if (reservation.sizeBytes === null || !Number.isSafeInteger(reservation.sizeBytes) || reservation.sizeBytes < 0) throw new Error("S3 attachment reservation sizeBytes must be a non-negative safe integer");
|
|
1240
1240
|
}
|
|
1241
1241
|
/** Server-only S3 capability. Callers complete authorization before download. */
|
|
1242
1242
|
var S3AttachmentBackend = class {
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["rowToHeader","up","down","up","down","up","down","up","down","up","down","up","down","migrations","migration001","migration002","migration003","migration004","migration005","migration006","ProgrammaticMigrationProvider","migration001","Buffer"],"sources":["../src/reserve-metadata.ts","../src/storage/fs/attachment-fs.ts","../src/storage/kysely/attachment-store.ts","../src/storage/kysely/reservation-store.ts","../src/storage/migrations/001_create_attachment_table.ts","../src/storage/migrations/002_create_reservation_table.ts","../src/storage/migrations/003_add_reservation_expires_at.ts","../src/storage/migrations/004_add_reservation_soft_delete.ts","../src/storage/migrations/005_add_reservation_active_index.ts","../src/storage/migrations/006_add_reservation_client_hash.ts","../src/storage/migrations/migrator.ts","../src/direct/direct-attachment-upload.ts","../src/direct/direct-attachment-upload-factory.ts","../src/direct/filesystem-attachment-backend.ts","../src/storage/s3/upload-factory.ts","../src/attachment-builder.ts","../src/read-models/attachment-reference/kysely-attachment-reference-store.ts","../src/read-models/attachment-reference/storage/migrations/001_create_attachment_reference_table.ts","../src/read-models/attachment-reference/storage/migrations/migrator.ts","../src/read-models/attachment-reference/index-builder.ts","../src/read-models/attachment-reference/attachment-reference-read-model.ts","../src/storage/s3/config.ts","../src/storage/s3/keying.ts","../src/storage/s3/primitives.ts","../src/storage/s3/backend.ts"],"sourcesContent":["import { InvalidAttachmentMetadata } from \"./errors.js\";\n\n// eslint-disable-next-line no-control-regex\nconst CONTROL_CHARS = /[\\x00-\\x1f\\x7f]/;\n// Characters a header value cannot carry: CTLs other than HTAB, DEL, and\n// anything above 0xFF.\n// eslint-disable-next-line no-control-regex\nconst NON_HEADER_CHARS = /[^\\t\\x20-\\x7e\\x80-\\xff]/;\n// RFC 6838 tokens, with optional `; param=value` (token or quoted-string).\nconst MIME_TYPE_PATTERN =\n /^[!#$%&'*+\\-.^_`|~\\w]+\\/[!#$%&'*+\\-.^_`|~\\w]+(?:[ \\t]*;[ \\t]*[!#$%&'*+\\-.^_`|~\\w]+=(?:[!#$%&'*+\\-.^_`|~\\w]+|\"(?:[^\"\\\\\\r\\n]|\\\\[^\\r\\n])*\"))*$/;\nconst MAX_FILENAME_LEN = 255;\nconst MAX_MIMETYPE_LEN = 255;\n\n/** The descriptive fields of a reservation, as a caller supplies them. */\nexport type ReserveMetadata = {\n mimeType: string;\n fileName: string;\n extension?: string | null;\n};\n\n/**\n * Validates reserve metadata with the rules the switchboard reserve route\n * applies.\n *\n * @throws InvalidAttachmentMetadata naming the first field that fails.\n */\nexport function validateReserveMetadata(meta: ReserveMetadata): void {\n const { mimeType, fileName, extension } = meta as Record<string, unknown>;\n if (\n typeof mimeType !== \"string\" ||\n mimeType.length === 0 ||\n mimeType.length > MAX_MIMETYPE_LEN ||\n NON_HEADER_CHARS.test(mimeType) ||\n !MIME_TYPE_PATTERN.test(mimeType)\n ) {\n throw new InvalidAttachmentMetadata(\"mimeType\");\n }\n if (\n typeof fileName !== \"string\" ||\n fileName.length === 0 ||\n fileName.length > MAX_FILENAME_LEN ||\n CONTROL_CHARS.test(fileName)\n ) {\n throw new InvalidAttachmentMetadata(\"fileName\");\n }\n if (typeof extension === \"string\") {\n if (extension.length === 0 || /[\\\\/]/.test(extension)) {\n throw new InvalidAttachmentMetadata(\"extension\");\n }\n } else if (extension !== undefined && extension !== null) {\n throw new InvalidAttachmentMetadata(\"extension\");\n }\n}\n","import { mkdir, rm, rename, access } from \"node:fs/promises\";\nimport { createReadStream, createWriteStream } from \"node:fs\";\nimport { createHash, randomUUID } from \"node:crypto\";\nimport { join, dirname } from \"node:path\";\nimport { Readable } from \"node:stream\";\nimport { finished } from \"node:stream/promises\";\nimport { SizeMismatch, UploadTooLarge } from \"../../errors.js\";\n\n/**\n * Compute the absolute storage path for an attachment hash.\n * Uses a 2-level directory fan-out to avoid millions of files\n * in a single directory: ab/cd/abcdef123456...\n */\nexport function storagePath(basePath: string, hash: string): string {\n return join(basePath, storageRelativePath(hash));\n}\n\n/**\n * Compute the relative storage path for an attachment hash.\n * This is what gets stored in the database's storage_path column.\n */\nexport function storageRelativePath(hash: string): string {\n return join(hash.slice(0, 2), hash.slice(2, 4), hash);\n}\n\n/**\n * Write a ReadableStream to disk. Creates parent directories as needed.\n *\n * Bytes are streamed to a uniquely-named temp file in the destination\n * directory and only atomically renamed onto the final path once the whole\n * stream has been written and flushed. The final path therefore never holds a\n * partial or torn file: a concurrent writer of the same content-addressed\n * path (e.g. two clients re-fetching the same evicted attachment) streams to\n * its own temp file, and the rename publishes the new content all at once. On\n * any failure the temp file is removed and the previous file (if any) is left\n * untouched.\n *\n * Returns the number of bytes written.\n */\n// createWriteStream opens the file lazily, so destroy() can return before the\n// open has even happened and the open then creates the file after the unlink\n// below has run. Wait for the stream to close first, or the failed write\n// leaves its temp file behind.\nasync function discardTempFile(\n writer: ReturnType<typeof createWriteStream>,\n tempPath: string,\n): Promise<void> {\n writer.destroy();\n try {\n await finished(writer, { error: false });\n } catch {\n // The stream is already closed, which is all this wait is for.\n }\n await rm(tempPath, { force: true });\n}\n\nexport async function writeAttachmentBytes(\n path: string,\n data: ReadableStream<Uint8Array>,\n): Promise<number> {\n await mkdir(dirname(path), { recursive: true });\n\n const tempPath = join(dirname(path), `${randomUUID()}.tmp`);\n const writer = createWriteStream(tempPath);\n const reader = data.getReader();\n let bytesWritten = 0;\n let caughtError: Error | undefined;\n // A destination error can land before the drain-wait below has an 'error'\n // listener attached -- failing to open the temp file, or an async write\n // error between chunks -- so hold one listener for the whole write. First\n // error wins: an already-recorded source failure is the one to report.\n const recordError = (err: unknown) => {\n caughtError ??= err instanceof Error ? err : new Error(String(err));\n };\n writer.on(\"error\", recordError);\n\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n // The destination is destroyed once it errors, so writing again would\n // return false and wait for a 'drain' that can never come.\n if (caughtError) break;\n bytesWritten += value.byteLength;\n const canContinue = writer.write(value);\n if (!canContinue) {\n await new Promise<void>((resolve, reject) => {\n const onDrain = () => {\n writer.off(\"error\", onError);\n resolve();\n };\n const onError = (err: Error) => {\n writer.off(\"drain\", onDrain);\n reject(err);\n };\n writer.once(\"drain\", onDrain);\n writer.once(\"error\", onError);\n });\n }\n }\n } catch (err) {\n recordError(err);\n } finally {\n reader.releaseLock();\n }\n\n if (caughtError) {\n await discardTempFile(writer, tempPath);\n throw caughtError;\n }\n\n try {\n await new Promise<void>((resolve, reject) => {\n writer.end((err?: Error | null) => {\n if (err) reject(err);\n else resolve();\n });\n writer.once(\"error\", reject);\n });\n await rename(tempPath, path);\n } catch (err) {\n await discardTempFile(writer, tempPath);\n throw err instanceof Error ? err : new Error(String(err));\n }\n\n return bytesWritten;\n}\n\n/**\n * Open a ReadableStream from a file on disk.\n */\nexport function readAttachmentStream(path: string): ReadableStream<Uint8Array> {\n const nodeStream = createReadStream(path);\n return Readable.toWeb(nodeStream) as ReadableStream<Uint8Array>;\n}\n\n/**\n * Delete a file from disk. No-op if the file does not exist.\n */\nexport async function deleteAttachmentBytes(path: string): Promise<void> {\n await rm(path, { force: true });\n}\n\n/**\n * Check whether a file exists on disk.\n */\nexport async function attachmentBytesExist(path: string): Promise<boolean> {\n try {\n await access(path);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Create a ReadableStream from an in-memory buffer.\n */\nexport function streamFromBuffer(data: Uint8Array): ReadableStream<Uint8Array> {\n return new ReadableStream({\n start(controller) {\n controller.enqueue(data);\n controller.close();\n },\n });\n}\n\n/**\n * Stream bytes to a temp file under `${basePath}/.tmp/` while computing the\n * SHA-256 hash, returning the temp path, hex hash, and total bytes written.\n *\n * Bytes are never buffered in memory beyond the current chunk. The caller is\n * responsible for renaming the temp file to its final hash-derived location\n * (or removing it if the content is a duplicate).\n *\n * If `maxBytes` is set and the input exceeds it, the temp file is removed and\n * `UploadTooLarge` is thrown.\n *\n * If `declaredSizeBytes` is set, the byte count is enforced as a contract:\n * mid-stream, the moment the count exceeds the declaration the reader is\n * released and `SizeMismatch` is thrown without consuming the rest of the\n * stream. At stream end, if the count does not equal the declaration,\n * `SizeMismatch` is thrown. Both the `maxBytes` and `declaredSizeBytes`\n * checks apply; `maxBytes` is evaluated first on each chunk.\n *\n * If `signal` aborts, the temp file is removed and the signal's reason is\n * thrown. Nothing partial is ever returned, so a cancelled transfer cannot be\n * committed.\n */\nexport async function streamHashAndWrite(\n basePath: string,\n data: ReadableStream<Uint8Array>,\n options: {\n maxBytes?: number;\n declaredSizeBytes?: number;\n signal?: AbortSignal;\n } = {},\n): Promise<{ tempPath: string; hash: string; sizeBytes: number }> {\n const { maxBytes, declaredSizeBytes, signal } = options;\n // Before the temp file exists: an already-aborted transfer leaves no trace.\n signal?.throwIfAborted();\n const tmpDir = join(basePath, \".tmp\");\n await mkdir(tmpDir, { recursive: true });\n const tempPath = join(tmpDir, randomUUID());\n\n const hasher = createHash(\"sha256\");\n const writer = createWriteStream(tempPath);\n const reader = data.getReader();\n // Cancelling the source is what makes an abort observable while a read is\n // stalled -- it resolves the pending read as `done`. The post-loop\n // `throwIfAborted` is what stops that resolution being mistaken for the end\n // of the stream, which would commit a truncated attachment.\n const onAbort = () => {\n reader.cancel(signal?.reason).catch(() => {});\n };\n signal?.addEventListener(\"abort\", onAbort, { once: true });\n let sizeBytes = 0;\n let caughtError: Error | undefined;\n\n try {\n for (;;) {\n signal?.throwIfAborted();\n const { done, value } = await reader.read();\n if (done) break;\n sizeBytes += value.byteLength;\n if (maxBytes !== undefined && sizeBytes > maxBytes) {\n throw new UploadTooLarge(maxBytes);\n }\n if (declaredSizeBytes !== undefined && sizeBytes > declaredSizeBytes) {\n throw new SizeMismatch(declaredSizeBytes, sizeBytes);\n }\n hasher.update(value);\n const canContinue = writer.write(value);\n if (!canContinue) {\n await new Promise<void>((resolve, reject) => {\n const onDrain = () => {\n writer.off(\"error\", onError);\n resolve();\n };\n const onError = (err: Error) => {\n writer.off(\"drain\", onDrain);\n reject(err);\n };\n writer.once(\"drain\", onDrain);\n writer.once(\"error\", onError);\n });\n }\n }\n signal?.throwIfAborted();\n } catch (err) {\n caughtError = err instanceof Error ? err : new Error(String(err));\n } finally {\n signal?.removeEventListener(\"abort\", onAbort);\n reader.releaseLock();\n }\n\n let endError: Error | undefined;\n try {\n await new Promise<void>((resolve, reject) => {\n writer.end((err?: Error | null) => {\n if (err) reject(err);\n else resolve();\n });\n writer.once(\"error\", reject);\n });\n } catch (err) {\n endError = err instanceof Error ? err : new Error(String(err));\n }\n\n if (caughtError) {\n await rm(tempPath, { force: true });\n throw caughtError;\n }\n if (endError) {\n await rm(tempPath, { force: true });\n throw endError;\n }\n\n if (declaredSizeBytes !== undefined && sizeBytes !== declaredSizeBytes) {\n await rm(tempPath, { force: true });\n throw new SizeMismatch(declaredSizeBytes, sizeBytes);\n }\n\n return {\n tempPath,\n hash: hasher.digest(\"hex\"),\n sizeBytes,\n };\n}\n","import { join } from \"node:path\";\nimport type { Kysely } from \"kysely\";\nimport { sql } from \"kysely\";\nimport type { AttachmentHash } from \"@powerhousedao/reactor\";\nimport type {\n IAttachmentStore,\n IAttachmentTransport,\n} from \"../../interfaces.js\";\nimport type {\n AttachmentHeader,\n AttachmentMetadata,\n AttachmentResponse,\n AttachmentStatus,\n} from \"../../types.js\";\nimport { AttachmentNotFound, AttachmentPending } from \"../../errors.js\";\nimport type { AttachmentDatabase, AttachmentRow } from \"./types.js\";\nimport {\n storageRelativePath,\n writeAttachmentBytes,\n readAttachmentStream,\n deleteAttachmentBytes,\n} from \"../fs/attachment-fs.js\";\n\nfunction rowToHeader(row: AttachmentRow): AttachmentHeader {\n return {\n hash: row.hash,\n mimeType: row.mime_type,\n fileName: row.file_name,\n sizeBytes: Number(row.size_bytes),\n extension: row.extension,\n status: row.status as AttachmentStatus,\n source: row.source as \"local\" | \"sync\",\n createdAtUtc: row.created_at_utc,\n lastAccessedAtUtc: row.last_accessed_at_utc,\n expiresAtUtc: null,\n };\n}\n\nfunction wrapStreamWithCleanup(\n source: ReadableStream<Uint8Array>,\n cleanup: () => void,\n): ReadableStream<Uint8Array> {\n let cleaned = false;\n const doCleanup = () => {\n if (!cleaned) {\n cleaned = true;\n cleanup();\n }\n };\n\n const reader = source.getReader();\n return new ReadableStream<Uint8Array>({\n async pull(controller) {\n try {\n const { done, value } = await reader.read();\n if (done) {\n doCleanup();\n controller.close();\n } else {\n controller.enqueue(value);\n }\n } catch (err) {\n doCleanup();\n controller.error(err);\n }\n },\n cancel() {\n doCleanup();\n reader.cancel().catch(() => {});\n },\n });\n}\n\nexport class KyselyAttachmentStore implements IAttachmentStore {\n private readonly activeReaders = new Map<string, number>();\n\n constructor(\n private readonly db: Kysely<AttachmentDatabase>,\n private readonly transport: IAttachmentTransport,\n private readonly basePath: string,\n ) {}\n\n async stat(hash: AttachmentHash): Promise<AttachmentHeader> {\n const row = await this.db\n .selectFrom(\"attachment\")\n .selectAll()\n .where(\"hash\", \"=\", hash)\n .executeTakeFirst();\n\n if (row) {\n return rowToHeader(row);\n }\n\n const now = new Date().toISOString();\n const pending = await this.findPendingReservation(hash, now);\n\n if (pending) {\n return {\n hash,\n mimeType: pending.mime_type,\n fileName: pending.file_name,\n sizeBytes: Number(pending.size_bytes),\n extension: pending.extension,\n status: \"pending\",\n source: \"local\",\n createdAtUtc: pending.created_at_utc,\n lastAccessedAtUtc: pending.created_at_utc,\n expiresAtUtc: pending.expires_at_utc,\n };\n }\n\n throw new AttachmentNotFound(hash);\n }\n\n async has(hash: AttachmentHash): Promise<boolean> {\n const row = await this.db\n .selectFrom(\"attachment\")\n .select(\"status\")\n .where(\"hash\", \"=\", hash)\n .executeTakeFirst();\n\n return row?.status === \"available\";\n }\n\n async get(\n hash: AttachmentHash,\n signal?: AbortSignal,\n documentId?: string,\n ): Promise<AttachmentResponse> {\n const row = await this.db\n .selectFrom(\"attachment\")\n .selectAll()\n .where(\"hash\", \"=\", hash)\n .executeTakeFirst();\n\n if (row) {\n if (row.status === \"evicted\") {\n return this.fetchRemote(hash, signal, documentId);\n }\n\n const now = new Date().toISOString();\n await this.db\n .updateTable(\"attachment\")\n .set({ last_accessed_at_utc: now })\n .where(\"hash\", \"=\", hash)\n .execute();\n\n const header = rowToHeader(row);\n header.lastAccessedAtUtc = now;\n\n this.acquireReader(hash);\n\n const fullPath = join(this.basePath, row.storage_path);\n const rawStream = readAttachmentStream(fullPath);\n const body = wrapStreamWithCleanup(rawStream, () =>\n this.releaseReader(hash),\n );\n\n return { header, body };\n }\n\n const now = new Date().toISOString();\n const pending = await this.findPendingReservation(hash, now);\n\n if (pending) {\n throw new AttachmentPending(hash, pending.expires_at_utc, {\n mimeType: pending.mime_type,\n fileName: pending.file_name,\n sizeBytes: pending.size_bytes,\n });\n }\n\n return this.fetchRemote(hash, signal, documentId);\n }\n\n async put(\n hash: AttachmentHash,\n metadata: AttachmentMetadata,\n data: ReadableStream<Uint8Array>,\n ): Promise<void> {\n const existing = await this.db\n .selectFrom(\"attachment\")\n .select([\"hash\", \"status\"])\n .where(\"hash\", \"=\", hash)\n .executeTakeFirst();\n\n if (existing?.status === \"available\") {\n await data.cancel();\n return;\n }\n\n const relPath = storageRelativePath(hash);\n const fullPath = join(this.basePath, relPath);\n await writeAttachmentBytes(fullPath, data);\n\n const now = new Date().toISOString();\n\n if (!existing) {\n await this.db\n .insertInto(\"attachment\")\n .values({\n hash,\n mime_type: metadata.mimeType,\n file_name: metadata.fileName,\n size_bytes: metadata.sizeBytes,\n extension: metadata.extension ?? null,\n status: \"available\",\n storage_path: relPath,\n source: \"sync\",\n created_at_utc: metadata.createdAtUtc,\n last_accessed_at_utc: now,\n })\n .onConflict((oc) => oc.column(\"hash\").doNothing())\n .execute();\n } else {\n await this.db\n .updateTable(\"attachment\")\n .set({\n status: \"available\",\n storage_path: relPath,\n last_accessed_at_utc: now,\n })\n .where(\"hash\", \"=\", hash)\n .where(\"status\", \"=\", \"evicted\")\n .execute();\n }\n }\n\n async evict(hash: AttachmentHash): Promise<void> {\n if (this.hasActiveReaders(hash)) {\n return;\n }\n\n const row = await this.db\n .selectFrom(\"attachment\")\n .select([\"storage_path\", \"status\"])\n .where(\"hash\", \"=\", hash)\n .executeTakeFirst();\n\n if (!row || row.status === \"evicted\") {\n return;\n }\n\n const fullPath = join(this.basePath, row.storage_path);\n await deleteAttachmentBytes(fullPath);\n\n await this.db\n .updateTable(\"attachment\")\n .set({ status: \"evicted\" })\n .where(\"hash\", \"=\", hash)\n .execute();\n }\n\n async storageUsed(): Promise<number> {\n const result = await this.db\n .selectFrom(\"attachment\")\n .select(sql<string>`COALESCE(SUM(size_bytes), 0)`.as(\"total\"))\n .where(\"status\", \"=\", \"available\")\n .executeTakeFirst();\n\n return Number(result?.total ?? 0);\n }\n\n // Private: remote re-fetch, pending reservation lookup and active reader tracking\n\n private async fetchRemote(\n hash: AttachmentHash,\n signal: AbortSignal | undefined,\n documentId: string | undefined,\n ): Promise<AttachmentResponse> {\n if (documentId === undefined) {\n throw new AttachmentNotFound(hash);\n }\n const remote = await this.transport.fetch(hash, documentId, signal);\n if (remote.kind === \"data\") {\n await this.put(hash, remote.response.metadata, remote.response.body);\n return this.get(hash, signal);\n }\n if (remote.kind === \"pending\") {\n throw new AttachmentPending(hash, remote.expiresAtUtc);\n }\n throw new AttachmentNotFound(hash);\n }\n\n private async findPendingReservation(\n hash: AttachmentHash,\n now: string,\n ): Promise<{\n mime_type: string;\n file_name: string;\n extension: string | null;\n size_bytes: number;\n created_at_utc: string;\n expires_at_utc: string;\n } | null> {\n const row = await this.db\n .selectFrom(\"attachment_reservation as r\")\n .leftJoin(\"attachment as a\", \"a.hash\", \"r.client_hash\")\n .select([\n \"r.mime_type\",\n \"r.file_name\",\n \"r.extension\",\n \"r.size_bytes\",\n \"r.created_at_utc\",\n \"r.expires_at_utc\",\n ])\n .where(\"r.client_hash\", \"=\", hash)\n .where(\"r.deleted_at_utc\", \"is\", null)\n .where(\"r.expires_at_utc\", \">\", now)\n .where(\"r.size_bytes\", \"is not\", null)\n .where(\"a.hash\", \"is\", null)\n .orderBy(\"r.expires_at_utc\", \"desc\")\n .executeTakeFirst();\n\n if (!row) return null;\n return {\n mime_type: row.mime_type,\n file_name: row.file_name,\n extension: row.extension,\n size_bytes: Number(row.size_bytes),\n created_at_utc: row.created_at_utc,\n expires_at_utc: row.expires_at_utc,\n };\n }\n\n private acquireReader(hash: string): void {\n this.activeReaders.set(hash, (this.activeReaders.get(hash) ?? 0) + 1);\n }\n\n private releaseReader(hash: string): void {\n const count = (this.activeReaders.get(hash) ?? 1) - 1;\n if (count <= 0) {\n this.activeReaders.delete(hash);\n } else {\n this.activeReaders.set(hash, count);\n }\n }\n\n private hasActiveReaders(hash: string): boolean {\n return (this.activeReaders.get(hash) ?? 0) > 0;\n }\n}\n","import { randomUUID } from \"node:crypto\";\nimport type { Kysely } from \"kysely\";\nimport type { IReservationStore } from \"../../interfaces.js\";\nimport type { Reservation, ReserveAttachmentOptions } from \"../../types.js\";\nimport { ReservationNotFound } from \"../../errors.js\";\nimport type { AttachmentDatabase, ReservationRow } from \"./types.js\";\n\nexport const DEFAULT_RESERVATION_TTL_MS = 24 * 60 * 60 * 1000;\n\nfunction rowToReservation(row: ReservationRow): Reservation {\n return {\n reservationId: row.reservation_id,\n mimeType: row.mime_type,\n fileName: row.file_name,\n extension: row.extension,\n createdAtUtc: row.created_at_utc,\n expiresAtUtc: row.expires_at_utc,\n clientHash: row.client_hash,\n sizeBytes: row.size_bytes !== null ? Number(row.size_bytes) : null,\n };\n}\n\nexport class KyselyReservationStore implements IReservationStore {\n private readonly ttlMs: number;\n\n constructor(\n private readonly db: Kysely<AttachmentDatabase>,\n ttlMs: number = DEFAULT_RESERVATION_TTL_MS,\n ) {\n this.ttlMs = ttlMs;\n }\n\n async create(options: ReserveAttachmentOptions): Promise<Reservation> {\n const reservationId = randomUUID();\n const nowMs = Date.now();\n const now = new Date(nowMs).toISOString();\n const expiresAt = new Date(nowMs + this.ttlMs).toISOString();\n\n const row = await this.db\n .insertInto(\"attachment_reservation\")\n .values({\n reservation_id: reservationId,\n mime_type: options.mimeType,\n file_name: options.fileName,\n extension: options.extension ?? null,\n created_at_utc: now,\n expires_at_utc: expiresAt,\n client_hash: options.clientHash ?? null,\n size_bytes: options.sizeBytes ?? null,\n })\n .returningAll()\n .executeTakeFirstOrThrow();\n\n return rowToReservation(row);\n }\n\n async get(reservationId: string): Promise<Reservation> {\n const row = await this.db\n .selectFrom(\"attachment_reservation\")\n .selectAll()\n .where(\"reservation_id\", \"=\", reservationId)\n .where(\"deleted_at_utc\", \"is\", null)\n .executeTakeFirst();\n\n if (!row) {\n throw new ReservationNotFound(reservationId);\n }\n\n return rowToReservation(row);\n }\n\n async delete(reservationId: string): Promise<void> {\n await this.db\n .updateTable(\"attachment_reservation\")\n .set({ deleted_at_utc: new Date().toISOString() })\n .where(\"reservation_id\", \"=\", reservationId)\n .where(\"deleted_at_utc\", \"is\", null)\n .execute();\n }\n\n async deleteExpired(now: Date = new Date()): Promise<number> {\n const nowIso = now.toISOString();\n const result = await this.db\n .updateTable(\"attachment_reservation\")\n .set({ deleted_at_utc: nowIso })\n .where(\"expires_at_utc\", \"<=\", nowIso)\n .where(\"deleted_at_utc\", \"is\", null)\n .executeTakeFirst();\n\n return Number(result.numUpdatedRows);\n }\n}\n","import type { Kysely } from \"kysely\";\n\nexport async function up(db: Kysely<any>): Promise<void> {\n await db.schema\n .createTable(\"attachment\")\n .addColumn(\"hash\", \"text\", (col) => col.primaryKey())\n .addColumn(\"mime_type\", \"text\", (col) => col.notNull())\n .addColumn(\"file_name\", \"text\", (col) => col.notNull())\n .addColumn(\"size_bytes\", \"bigint\", (col) => col.notNull())\n .addColumn(\"extension\", \"text\")\n .addColumn(\"status\", \"text\", (col) => col.notNull().defaultTo(\"available\"))\n .addColumn(\"storage_path\", \"text\", (col) => col.notNull())\n .addColumn(\"source\", \"text\", (col) => col.notNull().defaultTo(\"local\"))\n .addColumn(\"created_at_utc\", \"text\", (col) => col.notNull())\n .addColumn(\"last_accessed_at_utc\", \"text\", (col) => col.notNull())\n .execute();\n\n await db.schema\n .createIndex(\"idx_attachment_status\")\n .on(\"attachment\")\n .column(\"status\")\n .execute();\n\n // Compound index serves the LRU eviction query:\n // SELECT ... WHERE status = 'available' ORDER BY last_accessed_at_utc ASC\n // A partial index would be ideal but raw SQL doesn't respect withSchema().\n await db.schema\n .createIndex(\"idx_attachment_lru\")\n .on(\"attachment\")\n .columns([\"status\", \"last_accessed_at_utc\"])\n .execute();\n}\n\nexport async function down(db: Kysely<any>): Promise<void> {\n await db.schema.dropTable(\"attachment\").ifExists().execute();\n}\n","import type { Kysely } from \"kysely\";\n\nexport async function up(db: Kysely<any>): Promise<void> {\n await db.schema\n .createTable(\"attachment_reservation\")\n .addColumn(\"reservation_id\", \"text\", (col) => col.primaryKey())\n .addColumn(\"mime_type\", \"text\", (col) => col.notNull())\n .addColumn(\"file_name\", \"text\", (col) => col.notNull())\n .addColumn(\"extension\", \"text\")\n .addColumn(\"created_at_utc\", \"text\", (col) => col.notNull())\n .execute();\n}\n\nexport async function down(db: Kysely<any>): Promise<void> {\n await db.schema.dropTable(\"attachment_reservation\").ifExists().execute();\n}\n","import { sql, type Kysely } from \"kysely\";\n\nexport async function up(db: Kysely<any>): Promise<void> {\n await db.schema\n .alterTable(\"attachment_reservation\")\n .addColumn(\"expires_at_utc\", \"text\")\n .execute();\n\n await db\n .updateTable(\"attachment_reservation\")\n .set({ expires_at_utc: sql`created_at_utc` })\n .where(\"expires_at_utc\", \"is\", null)\n .execute();\n\n await db.schema\n .alterTable(\"attachment_reservation\")\n .alterColumn(\"expires_at_utc\", (col) => col.setNotNull())\n .execute();\n\n await db.schema\n .createIndex(\"idx_reservation_expires_at\")\n .on(\"attachment_reservation\")\n .column(\"expires_at_utc\")\n .execute();\n}\n\nexport async function down(db: Kysely<any>): Promise<void> {\n await db.schema.dropIndex(\"idx_reservation_expires_at\").ifExists().execute();\n\n await db.schema\n .alterTable(\"attachment_reservation\")\n .dropColumn(\"expires_at_utc\")\n .execute();\n}\n","import type { Kysely } from \"kysely\";\n\nexport async function up(db: Kysely<any>): Promise<void> {\n await db.schema\n .alterTable(\"attachment_reservation\")\n .addColumn(\"deleted_at_utc\", \"text\")\n .execute();\n}\n\nexport async function down(db: Kysely<any>): Promise<void> {\n await db.schema\n .alterTable(\"attachment_reservation\")\n .dropColumn(\"deleted_at_utc\")\n .execute();\n}\n","import { sql, type Kysely, type SqlBool } from \"kysely\";\n\nexport async function up(db: Kysely<any>): Promise<void> {\n await db.schema.dropIndex(\"idx_reservation_expires_at\").ifExists().execute();\n\n await db.schema\n .createIndex(\"idx_reservation_expires_at_active\")\n .on(\"attachment_reservation\")\n .column(\"expires_at_utc\")\n .where(sql<SqlBool>`deleted_at_utc IS NULL`)\n .execute();\n}\n\nexport async function down(db: Kysely<any>): Promise<void> {\n await db.schema\n .dropIndex(\"idx_reservation_expires_at_active\")\n .ifExists()\n .execute();\n\n await db.schema\n .createIndex(\"idx_reservation_expires_at\")\n .on(\"attachment_reservation\")\n .column(\"expires_at_utc\")\n .execute();\n}\n","import { sql, type Kysely } from \"kysely\";\n\nexport async function up(db: Kysely<any>): Promise<void> {\n await db.schema\n .alterTable(\"attachment_reservation\")\n .addColumn(\"client_hash\", \"text\")\n .execute();\n\n await db.schema\n .alterTable(\"attachment_reservation\")\n .addColumn(\"size_bytes\", \"bigint\")\n .execute();\n\n // Structural enforcement: size_bytes must be present whenever client_hash\n // is present. The expression references only the row's own columns so the\n // known withSchema() caveat (raw SQL table references are not schema-\n // qualified) does not apply here.\n await db.schema\n .alterTable(\"attachment_reservation\")\n .addCheckConstraint(\n \"attachment_reservation_hash_size_check\",\n sql`client_hash is null or size_bytes is not null`,\n )\n .execute();\n\n // Non-unique index. Partial unique indexes are not used here: raw SQL\n // index predicates do not respect withSchema() (see migration 001), and\n // uniqueness is deliberately not a requirement (concurrent reservations\n // for the same hash are permitted -- see the hash-first design doc).\n await db.schema\n .createIndex(\"idx_reservation_client_hash\")\n .on(\"attachment_reservation\")\n .column(\"client_hash\")\n .execute();\n}\n\nexport async function down(db: Kysely<any>): Promise<void> {\n await db.schema.dropIndex(\"idx_reservation_client_hash\").ifExists().execute();\n\n await db.schema\n .alterTable(\"attachment_reservation\")\n .dropColumn(\"size_bytes\")\n .execute();\n\n await db.schema\n .alterTable(\"attachment_reservation\")\n .dropColumn(\"client_hash\")\n .execute();\n}\n","import { Migrator, sql } from \"kysely\";\nimport type { MigrationProvider, Kysely } from \"kysely\";\n\nimport * as migration001 from \"./001_create_attachment_table.js\";\nimport * as migration002 from \"./002_create_reservation_table.js\";\nimport * as migration003 from \"./003_add_reservation_expires_at.js\";\nimport * as migration004 from \"./004_add_reservation_soft_delete.js\";\nimport * as migration005 from \"./005_add_reservation_active_index.js\";\nimport * as migration006 from \"./006_add_reservation_client_hash.js\";\n\nexport const ATTACHMENT_SCHEMA = \"attachments\";\n\nexport interface MigrationResult {\n success: boolean;\n migrationsExecuted: string[];\n error?: Error;\n}\n\nconst migrations = {\n \"001_create_attachment_table\": migration001,\n \"002_create_reservation_table\": migration002,\n \"003_add_reservation_expires_at\": migration003,\n \"004_add_reservation_soft_delete\": migration004,\n \"005_add_reservation_active_index\": migration005,\n \"006_add_reservation_client_hash\": migration006,\n};\n\nclass ProgrammaticMigrationProvider implements MigrationProvider {\n getMigrations() {\n return Promise.resolve(migrations);\n }\n}\n\nexport async function runAttachmentMigrations(\n db: Kysely<any>,\n schema: string = ATTACHMENT_SCHEMA,\n): Promise<MigrationResult> {\n try {\n await sql`CREATE SCHEMA IF NOT EXISTS ${sql.id(schema)}`.execute(db);\n } catch (error) {\n return {\n success: false,\n migrationsExecuted: [],\n error:\n error instanceof Error ? error : new Error(\"Failed to create schema\"),\n };\n }\n\n const migrator = new Migrator({\n db: db.withSchema(schema),\n provider: new ProgrammaticMigrationProvider(),\n migrationTableSchema: schema,\n });\n\n let error: unknown;\n let results: Awaited<ReturnType<typeof migrator.migrateToLatest>>[\"results\"];\n try {\n const result = await migrator.migrateToLatest();\n error = result.error;\n results = result.results;\n } catch (e) {\n error = e;\n results = [];\n }\n\n const migrationsExecuted =\n results?.map((result) => result.migrationName) ?? [];\n\n if (error) {\n return {\n success: false,\n migrationsExecuted,\n error:\n error instanceof Error ? error : new Error(\"Unknown migration error\"),\n };\n }\n\n return {\n success: true,\n migrationsExecuted,\n };\n}\n","import { mkdir, rename, rm } from \"node:fs/promises\";\nimport { dirname, join } from \"node:path\";\nimport type { Kysely } from \"kysely\";\nimport type { AttachmentRef } from \"@powerhousedao/reactor\";\nimport type { IAttachmentUpload, IReservationStore } from \"../interfaces.js\";\nimport type {\n AttachmentHeader,\n AttachmentSendOptions,\n AttachmentUploadResult,\n Reservation,\n} from \"../types.js\";\nimport type {\n AttachmentDatabase,\n AttachmentRow,\n} from \"../storage/kysely/types.js\";\nimport { HashMismatch } from \"../errors.js\";\nimport { createRef } from \"../ref.js\";\nimport {\n storageRelativePath,\n streamHashAndWrite,\n} from \"../storage/fs/attachment-fs.js\";\nimport type { AttachmentStatus } from \"../types.js\";\nimport { isBlob } from \"../blob.js\";\n\nfunction rowToHeader(row: AttachmentRow): AttachmentHeader {\n return {\n hash: row.hash,\n mimeType: row.mime_type,\n fileName: row.file_name,\n sizeBytes: Number(row.size_bytes),\n extension: row.extension,\n status: row.status as AttachmentStatus,\n source: row.source as \"local\" | \"sync\",\n createdAtUtc: row.created_at_utc,\n lastAccessedAtUtc: row.last_accessed_at_utc,\n expiresAtUtc: null,\n };\n}\n\nexport class DirectAttachmentUpload implements IAttachmentUpload {\n readonly reservationId: string;\n readonly ref: AttachmentRef | null;\n readonly expiresAtUtc: string;\n\n constructor(\n private readonly reservation: Reservation,\n private readonly db: Kysely<AttachmentDatabase>,\n private readonly basePath: string,\n private readonly reservations: IReservationStore,\n private readonly maxBytes?: number,\n ) {\n this.reservationId = reservation.reservationId;\n this.ref =\n reservation.clientHash != null ? createRef(reservation.clientHash) : null;\n this.expiresAtUtc = reservation.expiresAtUtc;\n }\n\n async send(\n data: ReadableStream<Uint8Array> | Blob,\n options?: AttachmentSendOptions,\n ): Promise<AttachmentUploadResult> {\n if (\n this.reservation.clientHash != null &&\n this.reservation.sizeBytes == null\n ) {\n throw new Error(\"hash-first reservation missing sizeBytes\");\n }\n // Stream bytes directly to a temp file while hashing. This caps memory\n // usage at one chunk regardless of payload size, and lets us enforce\n // `maxBytes` before either disk or memory grows unbounded.\n // When clientHash is present, declaredSizeBytes is enforced during the\n // stream: exceeding it aborts early, and a short stream fails at end.\n const declaredSizeBytes =\n this.reservation.clientHash != null\n ? (this.reservation.sizeBytes ?? undefined)\n : undefined;\n // The signal is honoured for the streaming write, the only part of this\n // send that can run long: a cancel there rejects and commits nothing.\n const { tempPath, hash, sizeBytes } = await streamHashAndWrite(\n this.basePath,\n isBlob(data) ? data.stream() : data,\n {\n maxBytes: this.maxBytes,\n declaredSizeBytes,\n ...(options?.signal ? { signal: options.signal } : {}),\n },\n );\n\n // Hash verification: if the client claimed a hash, compare before any\n // DB write or rename. On mismatch the temp file is removed and the\n // reservation is deliberately retained so the client can retry.\n if (\n this.reservation.clientHash != null &&\n hash !== this.reservation.clientHash\n ) {\n await rm(tempPath, { force: true });\n throw new HashMismatch(this.reservation.clientHash, hash);\n }\n\n try {\n const existing = await this.db\n .selectFrom(\"attachment\")\n .select([\"hash\", \"status\"])\n .where(\"hash\", \"=\", hash)\n .executeTakeFirst();\n\n if (existing?.status === \"available\") {\n // Dedup -- bytes already on disk, drop the temp file.\n await rm(tempPath, { force: true });\n } else {\n const relPath = storageRelativePath(hash);\n const fullPath = join(this.basePath, relPath);\n await mkdir(dirname(fullPath), { recursive: true });\n await rename(tempPath, fullPath);\n\n const now = new Date().toISOString();\n\n if (!existing) {\n await this.db\n .insertInto(\"attachment\")\n .values({\n hash,\n mime_type: this.reservation.mimeType,\n file_name: this.reservation.fileName,\n size_bytes: sizeBytes,\n extension: this.reservation.extension ?? null,\n status: \"available\",\n storage_path: relPath,\n source: \"local\",\n created_at_utc: now,\n last_accessed_at_utc: now,\n })\n .onConflict((oc) => oc.column(\"hash\").doNothing())\n .execute();\n } else {\n // Existing row was evicted — restore it\n await this.db\n .updateTable(\"attachment\")\n .set({\n status: \"available\",\n storage_path: relPath,\n source: \"local\",\n last_accessed_at_utc: now,\n })\n .where(\"hash\", \"=\", hash)\n .where(\"status\", \"=\", \"evicted\")\n .execute();\n }\n }\n } catch (err) {\n await rm(tempPath, { force: true });\n throw err;\n }\n\n await this.reservations.delete(this.reservationId);\n\n const row = await this.db\n .selectFrom(\"attachment\")\n .selectAll()\n .where(\"hash\", \"=\", hash)\n .executeTakeFirstOrThrow();\n\n return {\n hash,\n ref: createRef(hash),\n header: rowToHeader(row),\n };\n }\n}\n","import type { Kysely } from \"kysely\";\nimport type {\n IAttachmentUpload,\n IAttachmentUploadFactory,\n IReservationStore,\n} from \"../interfaces.js\";\nimport type { Reservation } from \"../types.js\";\nimport type { AttachmentDatabase } from \"../storage/kysely/types.js\";\nimport { DirectAttachmentUpload } from \"./direct-attachment-upload.js\";\n\nexport class DirectAttachmentUploadFactory implements IAttachmentUploadFactory {\n constructor(\n private readonly db: Kysely<AttachmentDatabase>,\n private readonly basePath: string,\n private readonly reservations: IReservationStore,\n private readonly maxBytes?: number,\n ) {}\n\n createUpload(reservation: Reservation): IAttachmentUpload {\n return new DirectAttachmentUpload(\n reservation,\n this.db,\n this.basePath,\n this.reservations,\n this.maxBytes,\n );\n }\n}\n","import type { AttachmentHash } from \"@powerhousedao/reactor\";\nimport type { IAttachmentBackend, IAttachmentStore } from \"../interfaces.js\";\nimport {\n parseAttachmentDownloadTarget,\n parseAttachmentUploadTarget,\n} from \"../targets.js\";\nimport type {\n AttachmentBackendHealth,\n AttachmentDownloadTarget,\n AttachmentUploadTarget,\n Reservation,\n} from \"../types.js\";\n\nexport type FilesystemAttachmentBackendConfig = {\n uploadTarget: (reservation: Reservation) => unknown;\n downloadTarget: (hash: AttachmentHash) => unknown;\n readiness?: () => boolean | Promise<boolean>;\n};\n\n/**\n * Filesystem keeps byte transfer behind Switchboard. URL construction stays\n * at the server edge, while this adapter validates that a filesystem backend\n * can never accidentally return a direct-provider target.\n */\nexport class FilesystemAttachmentBackend implements IAttachmentBackend {\n readonly kind = \"filesystem\" as const;\n\n constructor(\n private readonly store: Pick<IAttachmentStore, \"has\">,\n private readonly config: FilesystemAttachmentBackendConfig,\n ) {}\n\n async prepareUploadTarget(\n reservation: Reservation,\n ): Promise<AttachmentUploadTarget> {\n const target = parseAttachmentUploadTarget(\n await this.config.uploadTarget(reservation),\n );\n if (target.kind !== \"switchboard\") {\n throw new Error(\"Filesystem upload target must use Switchboard\");\n }\n return target;\n }\n\n async prepareDownloadTarget(\n hash: AttachmentHash,\n ): Promise<AttachmentDownloadTarget> {\n const target = parseAttachmentDownloadTarget(\n await this.config.downloadTarget(hash),\n );\n if (target.kind !== \"switchboard\") {\n throw new Error(\"Filesystem download target must use Switchboard\");\n }\n return target;\n }\n\n exists(hash: AttachmentHash): Promise<boolean> {\n return this.store.has(hash);\n }\n\n async health(): Promise<AttachmentBackendHealth> {\n return {\n kind: this.kind,\n ready: await (this.config.readiness?.() ?? true),\n };\n }\n}\n","import type { AttachmentRef } from \"@powerhousedao/reactor\";\nimport type {\n IAttachmentUpload,\n IAttachmentUploadFactory,\n} from \"../../interfaces.js\";\nimport { createRef } from \"../../ref.js\";\nimport type {\n AttachmentUploadResult,\n AttachmentUploadTarget,\n Reservation,\n} from \"../../types.js\";\nimport { isBlob } from \"../../blob.js\";\n\nclass S3AttachmentUpload implements IAttachmentUpload {\n readonly reservationId: string;\n readonly ref: AttachmentRef | null;\n readonly expiresAtUtc: string;\n readonly uploadTarget?: AttachmentUploadTarget;\n\n constructor(reservation: Reservation) {\n this.reservationId = reservation.reservationId;\n this.ref =\n reservation.clientHash === null\n ? null\n : createRef(reservation.clientHash);\n this.expiresAtUtc = reservation.expiresAtUtc;\n this.uploadTarget = reservation.uploadTarget;\n }\n\n // No `options`: this handle never transfers bytes, so there is no progress\n // to report and nothing for a signal to abort. Callers must use the\n // presigned target, which honours both.\n async send(\n data: ReadableStream<Uint8Array> | Blob,\n ): Promise<AttachmentUploadResult> {\n if (!isBlob(data)) await data.cancel().catch(() => {});\n throw new Error(\"S3 attachment upload must use the presigned target\");\n }\n}\n\nexport class S3AttachmentUploadFactory implements IAttachmentUploadFactory {\n createUpload(reservation: Reservation): IAttachmentUpload {\n return new S3AttachmentUpload(reservation);\n }\n}\n","import type { Kysely } from \"kysely\";\nimport type {\n IAttachmentBackend,\n IAttachmentTransport,\n IAttachmentUploadFactory,\n} from \"./interfaces.js\";\nimport type { AttachmentDatabase } from \"./storage/kysely/types.js\";\nimport { AttachmentService } from \"./attachment-service.js\";\nimport { KyselyAttachmentStore } from \"./storage/kysely/attachment-store.js\";\nimport { KyselyReservationStore } from \"./storage/kysely/reservation-store.js\";\nimport { DirectAttachmentUploadFactory } from \"./direct/direct-attachment-upload-factory.js\";\nimport {\n runAttachmentMigrations,\n ATTACHMENT_SCHEMA,\n} from \"./storage/migrations/migrator.js\";\nimport { NullAttachmentTransport } from \"./null-attachment-transport.js\";\nimport { S3AttachmentUploadFactory } from \"./storage/s3/upload-factory.js\";\n\nexport type AttachmentBuildResult = {\n service: AttachmentService;\n store: KyselyAttachmentStore;\n reservations: KyselyReservationStore;\n uploadFactory: IAttachmentUploadFactory;\n /** Selected direct-transfer backend, when startup configured one. */\n backend?: IAttachmentBackend;\n /** Stops the reservation sweep timer, if one was configured via withReservationSweepMs(). */\n destroy: () => void;\n};\n\nexport class AttachmentBuilder {\n private transport: IAttachmentTransport = new NullAttachmentTransport();\n private customUploadFactory?: IAttachmentUploadFactory;\n private maxUploadBytes?: number;\n private reservationSweepMs?: number;\n private backend?: IAttachmentBackend;\n\n constructor(\n private readonly db: Kysely<any>,\n private readonly storagePath: string,\n ) {}\n\n withTransport(transport: IAttachmentTransport): this {\n this.transport = transport;\n return this;\n }\n\n withUploadFactory(factory: IAttachmentUploadFactory): this {\n this.customUploadFactory = factory;\n return this;\n }\n\n withBackend(backend: IAttachmentBackend): this {\n this.backend = backend;\n return this;\n }\n\n withMaxUploadBytes(maxBytes: number): this {\n this.maxUploadBytes = maxBytes;\n return this;\n }\n\n /**\n * Configure a recurring sweep that deletes expired reservations.\n * The sweep calls reservations.deleteExpired() on the given interval.\n * When set, the built result's destroy() clears the timer.\n * Without this option no sweep runs -- deleteExpired() is never called\n * automatically. Call withReservationSweepMs in production to prevent\n * expired reservation rows from accumulating indefinitely.\n */\n withReservationSweepMs(intervalMs: number): this {\n this.reservationSweepMs = intervalMs;\n return this;\n }\n\n async build(): Promise<AttachmentBuildResult> {\n const result = await runAttachmentMigrations(this.db, ATTACHMENT_SCHEMA);\n if (!result.success && result.error) {\n throw result.error;\n }\n\n const scopedDb = this.db.withSchema(\n ATTACHMENT_SCHEMA,\n ) as Kysely<AttachmentDatabase>;\n\n const store = new KyselyAttachmentStore(\n scopedDb,\n this.transport,\n this.storagePath,\n );\n const reservations = new KyselyReservationStore(scopedDb);\n\n const uploadFactory =\n this.customUploadFactory ??\n (this.backend?.kind === \"s3\"\n ? new S3AttachmentUploadFactory()\n : new DirectAttachmentUploadFactory(\n scopedDb,\n this.storagePath,\n reservations,\n this.maxUploadBytes,\n ));\n\n const service = new AttachmentService(\n store,\n reservations,\n uploadFactory,\n this.backend,\n );\n\n let sweepTimer: ReturnType<typeof setInterval> | undefined;\n if (this.reservationSweepMs !== undefined) {\n const intervalMs = this.reservationSweepMs;\n sweepTimer = setInterval(() => {\n // Sweep failures are retried on the next interval; swallow to prevent\n // unhandled rejection from terminating the process.\n reservations.deleteExpired().catch(() => {});\n }, intervalMs);\n if (typeof sweepTimer.unref === \"function\") {\n sweepTimer.unref();\n }\n }\n\n const destroy = (): void => {\n if (sweepTimer !== undefined) {\n clearInterval(sweepTimer);\n sweepTimer = undefined;\n }\n };\n\n return {\n service,\n store,\n reservations,\n uploadFactory,\n ...(this.backend ? { backend: this.backend } : {}),\n destroy,\n };\n }\n}\n","import type { AttachmentRef } from \"@powerhousedao/reactor\";\nimport type { Kysely } from \"kysely\";\nimport { parseRef } from \"../../ref.js\";\nimport type { AttachmentReferenceDatabase } from \"./storage/types.js\";\nimport type {\n AttachmentReferenceInput,\n AttachmentReferencePageResult,\n IAttachmentReferenceReader,\n IAttachmentReferenceScanner,\n IAttachmentReferenceWriter,\n} from \"./types.js\";\n\n/** Keyset cursor: the `(document_id, attachment_ref)` pair the last page ended on. */\ntype ScanCursor = {\n documentId: string;\n ref: string;\n};\n\nfunction encodeCursor(cursor: ScanCursor): string {\n return JSON.stringify([cursor.documentId, cursor.ref]);\n}\n\nfunction decodeCursor(cursor: string): ScanCursor {\n let parsed: unknown;\n try {\n parsed = JSON.parse(cursor);\n } catch {\n // Malformed JSON is a bad cursor, not an uncaught SyntaxError leaking out\n // of a scan: report it as the named error the caller expects.\n throw new Error(\n `Invalid attachment reference scan cursor: ${JSON.stringify(cursor)}`,\n );\n }\n if (\n !Array.isArray(parsed) ||\n parsed.length !== 2 ||\n typeof parsed[0] !== \"string\" ||\n parsed[0] === \"\" ||\n typeof parsed[1] !== \"string\" ||\n parsed[1] === \"\"\n ) {\n throw new Error(\n `Invalid attachment reference scan cursor: ${JSON.stringify(cursor)}`,\n );\n }\n return { documentId: parsed[0], ref: parsed[1] };\n}\n\nexport class KyselyAttachmentReferenceStore\n implements\n IAttachmentReferenceReader,\n IAttachmentReferenceScanner,\n IAttachmentReferenceWriter\n{\n constructor(private readonly db: Kysely<AttachmentReferenceDatabase>) {}\n\n async hasReference(documentId: string, ref: AttachmentRef): Promise<boolean> {\n const row = await this.db\n .selectFrom(\"attachment_reference\")\n .select(\"document_id\")\n .where(\"document_id\", \"=\", documentId)\n .where(\"attachment_ref\", \"=\", ref)\n .executeTakeFirst();\n\n return row !== undefined;\n }\n\n async referencingScopes(\n documentId: string,\n ref: AttachmentRef,\n ): Promise<string[]> {\n const rows = await this.db\n .selectFrom(\"attachment_reference\")\n .select(\"scope\")\n .distinct()\n .where(\"document_id\", \"=\", documentId)\n .where(\"attachment_ref\", \"=\", ref)\n .execute();\n\n return rows.map((row) => row.scope);\n }\n\n /**\n * Keyset paging over the unique `(document_id, attachment_ref)` constraint,\n * rather than OFFSET: a scan that runs while the read model is still\n * indexing must not skip or repeat a row because rows appeared behind the\n * cursor. That is exactly the boot case the replicator's re-scan runs in.\n */\n async listReferences(\n cursor: string | undefined,\n limit: number,\n ): Promise<AttachmentReferencePageResult> {\n let query = this.db\n .selectFrom(\"attachment_reference\")\n .select([\"document_id\", \"attachment_ref\"])\n .orderBy(\"document_id\", \"asc\")\n .orderBy(\"attachment_ref\", \"asc\")\n .limit(limit);\n\n if (cursor !== undefined) {\n const after = decodeCursor(cursor);\n query = query.where((eb) =>\n eb.or([\n eb(\"document_id\", \">\", after.documentId),\n eb.and([\n eb(\"document_id\", \"=\", after.documentId),\n eb(\"attachment_ref\", \">\", after.ref),\n ]),\n ]),\n );\n }\n\n const rows = await query.execute();\n const last = rows.at(-1);\n return {\n references: rows.map((row) => ({\n documentId: row.document_id,\n ref: row.attachment_ref as AttachmentRef,\n })),\n nextCursor:\n rows.length === limit && last\n ? encodeCursor({\n documentId: last.document_id,\n ref: last.attachment_ref,\n })\n : undefined,\n };\n }\n\n async addReferences(\n references: readonly AttachmentReferenceInput[],\n ): Promise<void> {\n if (references.length === 0) {\n return;\n }\n\n await this.db\n .insertInto(\"attachment_reference\")\n .values(\n references.map((reference) => ({\n document_id: reference.documentId,\n attachment_ref: reference.ref,\n attachment_hash: parseRef(reference.ref).hash,\n first_operation_id: reference.operationId,\n branch: reference.branch,\n scope: reference.scope,\n first_seen_ordinal: reference.ordinal,\n created_at_utc: new Date().toISOString(),\n })),\n )\n .onConflict((oc) =>\n oc.columns([\"document_id\", \"attachment_ref\"]).doNothing(),\n )\n .execute();\n }\n\n async removeDocuments(documentIds: readonly string[]): Promise<void> {\n if (documentIds.length === 0) {\n return;\n }\n\n await this.db\n .deleteFrom(\"attachment_reference\")\n .where(\"document_id\", \"in\", [...documentIds])\n .execute();\n }\n}\n","import type { Kysely } from \"kysely\";\n\nexport async function up(db: Kysely<any>): Promise<void> {\n await db.schema\n .createTable(\"attachment_reference\")\n .addColumn(\"document_id\", \"text\", (col) => col.notNull())\n .addColumn(\"attachment_ref\", \"text\", (col) => col.notNull())\n .addColumn(\"attachment_hash\", \"text\", (col) => col.notNull())\n .addColumn(\"first_operation_id\", \"text\", (col) => col.notNull())\n .addColumn(\"branch\", \"text\", (col) => col.notNull())\n .addColumn(\"scope\", \"text\", (col) => col.notNull())\n .addColumn(\"first_seen_ordinal\", \"integer\", (col) => col.notNull())\n .addColumn(\"created_at_utc\", \"text\", (col) => col.notNull())\n .addUniqueConstraint(\"unique_attachment_reference_document_ref\", [\n \"document_id\",\n \"attachment_ref\",\n ])\n .execute();\n\n await db.schema\n .createIndex(\"idx_attachment_reference_ref\")\n .on(\"attachment_reference\")\n .column(\"attachment_ref\")\n .execute();\n\n await db.schema\n .createIndex(\"idx_attachment_reference_hash\")\n .on(\"attachment_reference\")\n .column(\"attachment_hash\")\n .execute();\n}\n\nexport async function down(db: Kysely<any>): Promise<void> {\n await db.schema.dropTable(\"attachment_reference\").ifExists().execute();\n}\n","import { Migrator, sql } from \"kysely\";\nimport type { Kysely, MigrationProvider } from \"kysely\";\nimport * as migration001 from \"./001_create_attachment_reference_table.js\";\n\nexport const ATTACHMENT_REFERENCE_SCHEMA = \"attachment_reference_read_model\";\nexport const ATTACHMENT_REFERENCE_MIGRATION_TABLE =\n \"kysely_migration_attachment_reference_read_model\";\nexport const ATTACHMENT_REFERENCE_MIGRATION_LOCK_TABLE =\n \"kysely_migration_attachment_reference_read_model_lock\";\n\nexport interface AttachmentReferenceMigrationResult {\n success: boolean;\n migrationsExecuted: string[];\n error?: Error;\n}\n\nconst migrations = {\n \"001_create_attachment_reference_table\": migration001,\n};\n\nclass ProgrammaticMigrationProvider implements MigrationProvider {\n getMigrations() {\n return Promise.resolve(migrations);\n }\n}\n\nfunction createMigrator(db: Kysely<unknown>, schema: string): Migrator {\n return new Migrator({\n db: db.withSchema(schema),\n provider: new ProgrammaticMigrationProvider(),\n migrationTableSchema: schema,\n migrationTableName: ATTACHMENT_REFERENCE_MIGRATION_TABLE,\n migrationLockTableName: ATTACHMENT_REFERENCE_MIGRATION_LOCK_TABLE,\n });\n}\n\nfunction toResult(\n error: unknown,\n results:\n | Awaited<ReturnType<Migrator[\"migrateToLatest\"]>>[\"results\"]\n | undefined,\n): AttachmentReferenceMigrationResult {\n const migrationsExecuted =\n results?.map((result) => result.migrationName) ?? [];\n if (error) {\n return {\n success: false,\n migrationsExecuted,\n error:\n error instanceof Error ? error : new Error(\"Unknown migration error\"),\n };\n }\n return { success: true, migrationsExecuted };\n}\n\nexport async function runAttachmentReferenceMigrations(\n db: Kysely<unknown>,\n schema: string = ATTACHMENT_REFERENCE_SCHEMA,\n): Promise<AttachmentReferenceMigrationResult> {\n try {\n await sql`CREATE SCHEMA IF NOT EXISTS ${sql.id(schema)}`.execute(db);\n } catch (error) {\n return {\n success: false,\n migrationsExecuted: [],\n error:\n error instanceof Error ? error : new Error(\"Failed to create schema\"),\n };\n }\n\n try {\n const { error, results } = await createMigrator(\n db,\n schema,\n ).migrateToLatest();\n return toResult(error, results);\n } catch (error) {\n return toResult(error, []);\n }\n}\n\nexport async function rollbackAttachmentReferenceMigration(\n db: Kysely<unknown>,\n schema: string = ATTACHMENT_REFERENCE_SCHEMA,\n): Promise<AttachmentReferenceMigrationResult> {\n try {\n const { error, results } = await createMigrator(db, schema).migrateDown();\n return toResult(error, results);\n } catch (error) {\n return toResult(error, []);\n }\n}\n\nexport async function getAttachmentReferenceMigrationStatus(\n db: Kysely<unknown>,\n schema: string = ATTACHMENT_REFERENCE_SCHEMA,\n) {\n return await createMigrator(db, schema).getMigrations();\n}\n","import type { Kysely } from \"kysely\";\nimport { KyselyAttachmentReferenceStore } from \"./kysely-attachment-reference-store.js\";\nimport type { AttachmentReferenceDatabase } from \"./storage/types.js\";\nimport {\n ATTACHMENT_REFERENCE_SCHEMA,\n runAttachmentReferenceMigrations,\n} from \"./storage/migrations/migrator.js\";\nimport type {\n IAttachmentReferenceReader,\n IAttachmentReferenceWriter,\n} from \"./types.js\";\n\nexport type AttachmentReferenceIndexBuildResult = {\n store: IAttachmentReferenceReader & IAttachmentReferenceWriter;\n};\n\nexport class AttachmentReferenceIndexBuilder {\n constructor(private readonly db: Kysely<unknown>) {}\n\n async build(): Promise<AttachmentReferenceIndexBuildResult> {\n const result = await runAttachmentReferenceMigrations(this.db);\n if (!result.success && result.error) {\n throw result.error;\n }\n\n const scopedDb = this.db.withSchema(\n ATTACHMENT_REFERENCE_SCHEMA,\n ) as Kysely<AttachmentReferenceDatabase>;\n const store = new KyselyAttachmentReferenceStore(scopedDb);\n return { store };\n }\n}\n","import {\n BaseReadModel,\n defaultReadModelIndexingConfig,\n type DocumentViewDatabase,\n type IConsistencyTracker,\n type IDocumentModelRegistry,\n type IOperationIndex,\n type IWriteCache,\n} from \"@powerhousedao/reactor\";\nimport {\n isPurgeMarker,\n type OperationWithContext,\n} from \"@powerhousedao/shared/document-model\";\nimport type { Kysely } from \"kysely\";\nimport type { IAttachmentSchemaCompiler } from \"../../reference-index/types.js\";\nimport type {\n AttachmentReferenceInput,\n IAttachmentReferenceWriter,\n} from \"./types.js\";\n\nexport const ATTACHMENT_REFERENCE_READ_MODEL_ID =\n \"attachment-reference-read-model\";\n\n/**\n * Indexes attachment references in chunks.\n *\n * Each reference row stands on its own and is written insert-or-do-nothing, so\n * a batch that commits in pieces exposes no partial structure, and re-indexing\n * the same range writes nothing new: the catch-up sweep needs no stream suffix.\n *\n * The rows live on another handle, so the purge fence is \"skip\": a tombstoned\n * id's operations are dropped at commit and its marker deletes its rows.\n */\nexport class AttachmentReferenceReadModel extends BaseReadModel {\n constructor(\n db: Kysely<DocumentViewDatabase>,\n operationIndex: IOperationIndex,\n writeCache: IWriteCache,\n consistencyTracker: IConsistencyTracker,\n private readonly documentModelRegistry: IDocumentModelRegistry,\n private readonly schemaCompiler: IAttachmentSchemaCompiler,\n private readonly referenceWriter: IAttachmentReferenceWriter,\n ) {\n super(db, operationIndex, writeCache, consistencyTracker, {\n readModelId: ATTACHMENT_REFERENCE_READ_MODEL_ID,\n rebuildStateOnInit: false,\n indexing: defaultReadModelIndexingConfig,\n replayStreamSuffix: false,\n purgeFence: \"skip\",\n });\n }\n\n protected override async commitOperations(\n items: OperationWithContext[],\n ): Promise<void> {\n const references: AttachmentReferenceInput[] = [];\n const purged = new Set<string>();\n\n for (const { operation, context } of items) {\n if (isPurgeMarker(operation)) {\n purged.add(context.documentId);\n continue;\n }\n if (operation.error !== undefined) continue;\n\n const module = this.documentModelRegistry.getModule(context.documentType);\n const extractor = this.schemaCompiler.forModuleAction(\n module,\n operation.action.type,\n );\n const refs = extractor.extract(operation.action);\n\n for (const ref of refs) {\n references.push({\n documentId: context.documentId,\n ref,\n operationId: operation.id,\n branch: context.branch,\n scope: context.scope,\n ordinal: context.ordinal,\n });\n }\n }\n\n if (references.length > 0) {\n await this.referenceWriter.addReferences(references);\n }\n if (purged.size > 0) {\n await this.referenceWriter.removeDocuments([...purged]);\n }\n }\n}\n","export const DEFAULT_S3_ATTACHMENT_PREFIX = \"attachments\";\nexport const DEFAULT_S3_UPLOAD_TTL_SECONDS = 900;\nexport const DEFAULT_S3_DOWNLOAD_TTL_SECONDS = 300;\nexport const MAX_S3_PRESIGN_TTL_SECONDS = 604_800;\n\nexport type S3AttachmentConfig = {\n endpoint: string;\n region: string;\n bucket: string;\n accessKeyId: string;\n secretAccessKey: string;\n prefix: string;\n forcePathStyle: boolean;\n uploadTtlSeconds: number;\n downloadTtlSeconds: number;\n};\n\nexport type AttachmentStorageConfig =\n | { kind: \"filesystem\" }\n | { kind: \"s3\"; s3: S3AttachmentConfig };\n\ntype Environment = Readonly<Record<string, string | undefined>>;\n\nfunction required(env: Environment, name: string): string {\n const value = env[name];\n if (value === undefined || value.trim().length === 0) {\n throw new Error(`${name} is required and must not be blank`);\n }\n if (value.trim() !== value) {\n throw new Error(`${name} must not have leading or trailing whitespace`);\n }\n return value;\n}\n\nconst LOOPBACK_HOSTNAMES = new Set([\"127.0.0.1\", \"localhost\", \"[::1]\"]);\n\n/** Plain HTTP is allowed only for loopback hosts (local S3 emulators). */\nfunction isLoopbackHost(endpoint: URL): boolean {\n return LOOPBACK_HOSTNAMES.has(endpoint.hostname.toLowerCase());\n}\n\nfunction parseEndpoint(value: string): string {\n const message =\n \"PH_ATTACHMENT_S3_ENDPOINT must be a valid HTTPS URL (HTTP is allowed only for loopback hosts)\";\n let endpoint: URL;\n try {\n endpoint = new URL(value);\n } catch {\n throw new Error(message);\n }\n const protocolAllowed =\n endpoint.protocol === \"https:\" ||\n (endpoint.protocol === \"http:\" && isLoopbackHost(endpoint));\n if (\n value.trim() !== value ||\n !protocolAllowed ||\n endpoint.username !== \"\" ||\n endpoint.password !== \"\" ||\n endpoint.search !== \"\" ||\n endpoint.hash !== \"\"\n ) {\n throw new Error(message);\n }\n return endpoint.toString().replace(/\\/$/, \"\");\n}\n\nfunction parseBoolean(\n env: Environment,\n name: string,\n defaultValue: boolean,\n): boolean {\n const value = env[name];\n if (value === undefined) return defaultValue;\n if (value === \"true\") return true;\n if (value === \"false\") return false;\n throw new Error(`${name} must be either true or false`);\n}\n\nfunction parseTtl(\n env: Environment,\n name: string,\n defaultValue: number,\n): number {\n const value = env[name];\n if (value === undefined) return defaultValue;\n if (!/^[1-9]\\d*$/.test(value)) {\n throw new Error(`${name} must be a positive integer`);\n }\n const seconds = Number(value);\n if (!Number.isSafeInteger(seconds) || seconds > MAX_S3_PRESIGN_TTL_SECONDS) {\n throw new Error(\n `${name} must be between 1 and ${MAX_S3_PRESIGN_TTL_SECONDS}`,\n );\n }\n return seconds;\n}\n\nexport function normalizeS3AttachmentPrefix(prefix: string): string {\n if (\n prefix.trim() !== prefix ||\n prefix.startsWith(\"/\") ||\n prefix.includes(\"\\\\\")\n ) {\n throw new Error(\"S3_ATTACHMENT_PREFIX is unsafe\");\n }\n const normalized = prefix.replace(/\\/+$/, \"\");\n if (normalized.length === 0) {\n throw new Error(\"S3_ATTACHMENT_PREFIX must not be blank\");\n }\n const segments = normalized.split(\"/\");\n if (\n segments.some(\n (segment) =>\n segment.length === 0 ||\n segment === \".\" ||\n segment === \"..\" ||\n !/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(segment),\n )\n ) {\n throw new Error(\"S3_ATTACHMENT_PREFIX contains an unsafe segment\");\n }\n return segments.join(\"/\");\n}\n\nexport function parseAttachmentStorageConfig(\n env: Environment = process.env,\n): AttachmentStorageConfig {\n const selector = env.PH_ATTACHMENT_STORAGE;\n if (selector === undefined || selector === \"filesystem\") {\n return { kind: \"filesystem\" };\n }\n if (selector !== \"s3\") {\n throw new Error(\"PH_ATTACHMENT_STORAGE must be either filesystem or s3\");\n }\n\n return {\n kind: \"s3\",\n s3: {\n endpoint: parseEndpoint(required(env, \"PH_ATTACHMENT_S3_ENDPOINT\")),\n region: required(env, \"PH_ATTACHMENT_S3_REGION\"),\n bucket: required(env, \"PH_ATTACHMENT_S3_BUCKET\"),\n accessKeyId: required(env, \"PH_ATTACHMENT_S3_ACCESS_KEY_ID\"),\n secretAccessKey: required(env, \"PH_ATTACHMENT_S3_SECRET_ACCESS_KEY\"),\n prefix: normalizeS3AttachmentPrefix(\n env.S3_ATTACHMENT_PREFIX ?? DEFAULT_S3_ATTACHMENT_PREFIX,\n ),\n forcePathStyle: parseBoolean(\n env,\n \"PH_ATTACHMENT_S3_FORCE_PATH_STYLE\",\n false,\n ),\n uploadTtlSeconds: parseTtl(\n env,\n \"PH_ATTACHMENT_S3_UPLOAD_TTL_SECONDS\",\n DEFAULT_S3_UPLOAD_TTL_SECONDS,\n ),\n downloadTtlSeconds: parseTtl(\n env,\n \"PH_ATTACHMENT_S3_DOWNLOAD_TTL_SECONDS\",\n DEFAULT_S3_DOWNLOAD_TTL_SECONDS,\n ),\n },\n };\n}\n","import { Buffer } from \"node:buffer\";\n\nconst SHA256_HEX = /^[0-9a-f]{64}$/;\n\nfunction validateHash(hash: string): void {\n if (!SHA256_HEX.test(hash)) {\n throw new Error(\n \"Attachment hash must be 64 lowercase hexadecimal characters\",\n );\n }\n}\n\nexport function deriveS3AttachmentKey(hash: string, prefix: string): string {\n validateHash(hash);\n // Imported lazily at the call boundary to keep this primitive's validation\n // identical to configuration parsing without accepting unnormalized input.\n if (\n prefix.startsWith(\"/\") ||\n prefix.endsWith(\"/\") ||\n prefix.includes(\"\\\\\") ||\n prefix\n .split(\"/\")\n .some(\n (segment) =>\n segment.length === 0 ||\n segment === \".\" ||\n segment === \"..\" ||\n !/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(segment),\n )\n ) {\n throw new Error(\"S3 attachment prefix must be normalized and safe\");\n }\n return `${prefix}/${hash.slice(0, 2)}/${hash.slice(2, 4)}/${hash}`;\n}\n\nexport function sha256HexToBase64(hash: string): string {\n validateHash(hash);\n return Buffer.from(hash, \"hex\").toString(\"base64\");\n}\n","import {\n GetObjectCommand,\n HeadObjectCommand,\n PutObjectCommand,\n S3Client,\n} from \"@aws-sdk/client-s3\";\nimport { getSignedUrl } from \"@aws-sdk/s3-request-presigner\";\nimport type {\n AttachmentDownloadTarget,\n AttachmentUploadTarget,\n} from \"../../types.js\";\nimport type { S3AttachmentConfig } from \"./config.js\";\nimport { deriveS3AttachmentKey, sha256HexToBase64 } from \"./keying.js\";\n\nexport interface S3CommandClient {\n send(command: object): Promise<unknown>;\n}\n\nexport type S3Presigner = (\n client: object,\n command: object,\n expiresInSeconds: number,\n) => Promise<string>;\n\ntype Dependencies = {\n client?: S3CommandClient;\n presign?: S3Presigner;\n now?: () => Date;\n};\n\nconst defaultPresigner: S3Presigner = (client, command, expiresInSeconds) =>\n getSignedUrl(client as S3Client, command as never, {\n expiresIn: expiresInSeconds,\n unhoistableHeaders: new Set([\"x-amz-checksum-sha256\"]),\n });\n\nexport class S3AttachmentPrimitives {\n readonly client: S3CommandClient;\n readonly presign: S3Presigner;\n readonly now: () => Date;\n\n constructor(\n readonly config: S3AttachmentConfig,\n dependencies: Dependencies = {},\n ) {\n this.client =\n dependencies.client ??\n new S3Client({\n endpoint: config.endpoint,\n region: config.region,\n forcePathStyle: config.forcePathStyle,\n credentials: {\n accessKeyId: config.accessKeyId,\n secretAccessKey: config.secretAccessKey,\n },\n });\n this.presign = dependencies.presign ?? defaultPresigner;\n this.now = dependencies.now ?? (() => new Date());\n }\n\n buildHeadObjectCommand(hash: string): object {\n return new HeadObjectCommand({\n Bucket: this.config.bucket,\n Key: deriveS3AttachmentKey(hash, this.config.prefix),\n });\n }\n\n buildPutObjectCommand(hash: string, mimeType: string): object {\n if (\n mimeType.trim().length === 0 ||\n mimeType.includes(\"\\r\") ||\n mimeType.includes(\"\\n\")\n ) {\n throw new Error(\n \"Attachment MIME type must not be blank or contain newlines\",\n );\n }\n return new PutObjectCommand({\n Bucket: this.config.bucket,\n Key: deriveS3AttachmentKey(hash, this.config.prefix),\n ContentType: mimeType,\n ChecksumSHA256: sha256HexToBase64(hash),\n });\n }\n\n buildGetObjectCommand(hash: string): object {\n return new GetObjectCommand({\n Bucket: this.config.bucket,\n Key: deriveS3AttachmentKey(hash, this.config.prefix),\n });\n }\n\n headObject(hash: string): Promise<unknown> {\n return this.client.send(this.buildHeadObjectCommand(hash));\n }\n\n async createUploadTarget(\n hash: string,\n mimeType: string,\n ttlSeconds = this.config.uploadTtlSeconds,\n ): Promise<AttachmentUploadTarget> {\n const checksum = sha256HexToBase64(hash);\n const url = await this.presign(\n this.client,\n this.buildPutObjectCommand(hash, mimeType),\n ttlSeconds,\n );\n return {\n kind: \"presigned-put\",\n method: \"PUT\",\n url,\n headers: {\n \"content-type\": mimeType,\n \"x-amz-checksum-sha256\": checksum,\n },\n expiresAtUtc: new Date(\n this.now().getTime() + ttlSeconds * 1_000,\n ).toISOString(),\n };\n }\n\n async createDownloadTarget(\n hash: string,\n ttlSeconds = this.config.downloadTtlSeconds,\n ): Promise<AttachmentDownloadTarget> {\n const url = await this.presign(\n this.client,\n this.buildGetObjectCommand(hash),\n ttlSeconds,\n );\n return {\n kind: \"presigned-get\",\n method: \"GET\",\n url,\n headers: {},\n expiresAtUtc: new Date(\n this.now().getTime() + ttlSeconds * 1_000,\n ).toISOString(),\n };\n }\n}\n\nexport function createS3AttachmentPrimitives(\n config: S3AttachmentConfig,\n dependencies: Dependencies = {},\n): S3AttachmentPrimitives {\n return new S3AttachmentPrimitives(config, dependencies);\n}\n","import type { AttachmentHash } from \"@powerhousedao/reactor\";\nimport type { Kysely } from \"kysely\";\nimport type { IAttachmentBackend } from \"../../interfaces.js\";\nimport type {\n AttachmentBackendHealth,\n AttachmentDownloadTarget,\n AttachmentUploadTarget,\n Reservation,\n} from \"../../types.js\";\nimport type { AttachmentDatabase } from \"../kysely/types.js\";\nimport type { S3AttachmentConfig } from \"./config.js\";\nimport { deriveS3AttachmentKey } from \"./keying.js\";\nimport {\n S3AttachmentPrimitives,\n type S3CommandClient,\n type S3Presigner,\n} from \"./primitives.js\";\n\nconst READINESS_PROBE_HASH = \"0\".repeat(64);\nconst OBJECT_NOT_FOUND_NAMES = new Set([\n \"NotFound\",\n \"NoSuchKey\",\n \"NoSuchObject\",\n]);\n\ntype ProviderError = {\n name?: unknown;\n code?: unknown;\n $metadata?: { httpStatusCode?: unknown };\n};\n\nexport type S3AttachmentBackendDependencies = {\n client?: S3CommandClient;\n presign?: S3Presigner;\n now?: () => Date;\n uploadTtlSeconds?: number;\n downloadTtlSeconds?: number;\n};\n\nfunction isObjectNotFound(error: unknown): boolean {\n if (typeof error !== \"object\" || error === null) return false;\n const providerError = error as ProviderError;\n if (providerError.$metadata?.httpStatusCode !== 404) return false;\n return [providerError.name, providerError.code].some(\n (code) => typeof code === \"string\" && OBJECT_NOT_FOUND_NAMES.has(code),\n );\n}\n\nfunction requireHashFirstReservation(\n reservation: Reservation,\n): asserts reservation is Reservation & {\n clientHash: AttachmentHash;\n sizeBytes: number;\n} {\n if (reservation.clientHash === null) {\n throw new Error(\"S3 attachment reservations require a client hash\");\n }\n deriveS3AttachmentKey(reservation.clientHash, \"validation\");\n if (\n reservation.sizeBytes === null ||\n !Number.isSafeInteger(reservation.sizeBytes) ||\n reservation.sizeBytes <= 0\n ) {\n throw new Error(\n \"S3 attachment reservation sizeBytes must be a positive safe integer\",\n );\n }\n}\n\n/** Server-only S3 capability. Callers complete authorization before download. */\nexport class S3AttachmentBackend implements IAttachmentBackend {\n readonly kind = \"s3\" as const;\n private readonly primitives: S3AttachmentPrimitives;\n private readonly now: () => Date;\n private readonly uploadTtlSeconds: number;\n private readonly downloadTtlSeconds: number;\n\n constructor(\n private readonly db: Kysely<AttachmentDatabase>,\n readonly config: S3AttachmentConfig,\n dependencies: S3AttachmentBackendDependencies = {},\n ) {\n this.primitives = new S3AttachmentPrimitives(config, dependencies);\n this.now = dependencies.now ?? (() => new Date());\n this.uploadTtlSeconds =\n dependencies.uploadTtlSeconds ?? config.uploadTtlSeconds;\n this.downloadTtlSeconds =\n dependencies.downloadTtlSeconds ?? config.downloadTtlSeconds;\n }\n\n async prepareUploadTarget(\n reservation: Reservation,\n ): Promise<AttachmentUploadTarget> {\n requireHashFirstReservation(reservation);\n const hash = reservation.clientHash;\n const now = this.now().toISOString();\n const storagePath = deriveS3AttachmentKey(hash, this.config.prefix);\n\n try {\n await this.db\n .insertInto(\"attachment\")\n .values({\n hash,\n mime_type: reservation.mimeType,\n file_name: reservation.fileName,\n size_bytes: reservation.sizeBytes,\n extension: reservation.extension,\n status: \"available\",\n storage_path: storagePath,\n source: \"local\",\n created_at_utc: reservation.createdAtUtc,\n last_accessed_at_utc: now,\n })\n .onConflict((conflict) =>\n conflict.column(\"hash\").doUpdateSet({\n mime_type: reservation.mimeType,\n file_name: reservation.fileName,\n size_bytes: reservation.sizeBytes,\n extension: reservation.extension,\n status: \"available\",\n storage_path: storagePath,\n last_accessed_at_utc: now,\n }),\n )\n .execute();\n } catch {\n throw new Error(\"S3 attachment metadata registration failed\");\n }\n\n let target: AttachmentUploadTarget;\n try {\n target = await this.primitives.createUploadTarget(\n hash,\n reservation.mimeType,\n this.uploadTtlSeconds,\n );\n } catch {\n throw new Error(\"S3 attachment upload target preparation failed\");\n }\n\n // Direct S3 completion is invisible to Switchboard; the existing sweep\n // expires this reservation normally.\n return target;\n }\n\n async prepareDownloadTarget(\n hash: AttachmentHash,\n ttlSeconds?: number,\n ): Promise<AttachmentDownloadTarget> {\n try {\n return await this.primitives.createDownloadTarget(\n hash,\n ttlSeconds ?? this.downloadTtlSeconds,\n );\n } catch {\n throw new Error(\"S3 attachment download target preparation failed\");\n }\n }\n\n async exists(hash: AttachmentHash): Promise<boolean> {\n const metadata = await this.db\n .selectFrom(\"attachment\")\n .select(\"hash\")\n .where(\"hash\", \"=\", hash)\n .executeTakeFirst();\n if (!metadata) return false;\n\n try {\n await this.primitives.headObject(hash);\n return true;\n } catch (error) {\n if (isObjectNotFound(error)) return false;\n // Provider errors may contain endpoints or signed request details, so the\n // raw cause intentionally must not cross this backend boundary.\n // eslint-disable-next-line preserve-caught-error\n throw new Error(\"S3 attachment existence check failed\");\n }\n }\n\n async health(): Promise<AttachmentBackendHealth> {\n try {\n await this.primitives.headObject(READINESS_PROBE_HASH);\n return { kind: this.kind, ready: true };\n } catch (error) {\n return {\n kind: this.kind,\n ready: isObjectNotFound(error),\n };\n }\n }\n}\n\nexport function createS3AttachmentBackend(\n db: Kysely<AttachmentDatabase>,\n config: S3AttachmentConfig,\n dependencies: S3AttachmentBackendDependencies = {},\n): S3AttachmentBackend {\n return new S3AttachmentBackend(db, config, dependencies);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;A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;AAEA,SAAgB,0BACd,IACA,QACA,eAAgD,CAAC,GAC5B;CACrB,OAAO,IAAI,oBAAoB,IAAI,QAAQ,YAAY;AACzD"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["rowToHeader","up","down","up","down","up","down","up","down","up","down","up","down","migrations","migration001","migration002","migration003","migration004","migration005","migration006","ProgrammaticMigrationProvider","migration001","Buffer"],"sources":["../src/reserve-metadata.ts","../src/storage/fs/attachment-fs.ts","../src/storage/kysely/attachment-store.ts","../src/storage/kysely/reservation-store.ts","../src/storage/migrations/001_create_attachment_table.ts","../src/storage/migrations/002_create_reservation_table.ts","../src/storage/migrations/003_add_reservation_expires_at.ts","../src/storage/migrations/004_add_reservation_soft_delete.ts","../src/storage/migrations/005_add_reservation_active_index.ts","../src/storage/migrations/006_add_reservation_client_hash.ts","../src/storage/migrations/migrator.ts","../src/direct/direct-attachment-upload.ts","../src/direct/direct-attachment-upload-factory.ts","../src/direct/filesystem-attachment-backend.ts","../src/storage/s3/upload-factory.ts","../src/attachment-builder.ts","../src/read-models/attachment-reference/kysely-attachment-reference-store.ts","../src/read-models/attachment-reference/storage/migrations/001_create_attachment_reference_table.ts","../src/read-models/attachment-reference/storage/migrations/migrator.ts","../src/read-models/attachment-reference/index-builder.ts","../src/read-models/attachment-reference/attachment-reference-read-model.ts","../src/storage/s3/config.ts","../src/storage/s3/keying.ts","../src/storage/s3/primitives.ts","../src/storage/s3/backend.ts"],"sourcesContent":["import { InvalidAttachmentMetadata } from \"./errors.js\";\n\n// eslint-disable-next-line no-control-regex\nconst CONTROL_CHARS = /[\\x00-\\x1f\\x7f]/;\n// Characters a header value cannot carry: CTLs other than HTAB, DEL, and\n// anything above 0xFF.\n// eslint-disable-next-line no-control-regex\nconst NON_HEADER_CHARS = /[^\\t\\x20-\\x7e\\x80-\\xff]/;\n// RFC 6838 tokens, with optional `; param=value` (token or quoted-string).\nconst MIME_TYPE_PATTERN =\n /^[!#$%&'*+\\-.^_`|~\\w]+\\/[!#$%&'*+\\-.^_`|~\\w]+(?:[ \\t]*;[ \\t]*[!#$%&'*+\\-.^_`|~\\w]+=(?:[!#$%&'*+\\-.^_`|~\\w]+|\"(?:[^\"\\\\\\r\\n]|\\\\[^\\r\\n])*\"))*$/;\nconst MAX_FILENAME_LEN = 255;\nconst MAX_MIMETYPE_LEN = 255;\n\n/** The descriptive fields of a reservation, as a caller supplies them. */\nexport type ReserveMetadata = {\n mimeType: string;\n fileName: string;\n extension?: string | null;\n};\n\n/**\n * Validates reserve metadata with the rules the switchboard reserve route\n * applies.\n *\n * @throws InvalidAttachmentMetadata naming the first field that fails.\n */\nexport function validateReserveMetadata(meta: ReserveMetadata): void {\n const { mimeType, fileName, extension } = meta as Record<string, unknown>;\n if (\n typeof mimeType !== \"string\" ||\n mimeType.length === 0 ||\n mimeType.length > MAX_MIMETYPE_LEN ||\n NON_HEADER_CHARS.test(mimeType) ||\n !MIME_TYPE_PATTERN.test(mimeType)\n ) {\n throw new InvalidAttachmentMetadata(\"mimeType\");\n }\n if (\n typeof fileName !== \"string\" ||\n fileName.length === 0 ||\n fileName.length > MAX_FILENAME_LEN ||\n CONTROL_CHARS.test(fileName)\n ) {\n throw new InvalidAttachmentMetadata(\"fileName\");\n }\n if (typeof extension === \"string\") {\n if (extension.length === 0 || /[\\\\/]/.test(extension)) {\n throw new InvalidAttachmentMetadata(\"extension\");\n }\n } else if (extension !== undefined && extension !== null) {\n throw new InvalidAttachmentMetadata(\"extension\");\n }\n}\n","import { mkdir, rm, rename, access } from \"node:fs/promises\";\nimport { createReadStream, createWriteStream } from \"node:fs\";\nimport { createHash, randomUUID } from \"node:crypto\";\nimport { join, dirname } from \"node:path\";\nimport { Readable } from \"node:stream\";\nimport { finished } from \"node:stream/promises\";\nimport { SizeMismatch, UploadTooLarge } from \"../../errors.js\";\n\n/**\n * Compute the absolute storage path for an attachment hash.\n * Uses a 2-level directory fan-out to avoid millions of files\n * in a single directory: ab/cd/abcdef123456...\n */\nexport function storagePath(basePath: string, hash: string): string {\n return join(basePath, storageRelativePath(hash));\n}\n\n/**\n * Compute the relative storage path for an attachment hash.\n * This is what gets stored in the database's storage_path column.\n */\nexport function storageRelativePath(hash: string): string {\n return join(hash.slice(0, 2), hash.slice(2, 4), hash);\n}\n\n/**\n * Write a ReadableStream to disk. Creates parent directories as needed.\n *\n * Bytes are streamed to a uniquely-named temp file in the destination\n * directory and only atomically renamed onto the final path once the whole\n * stream has been written and flushed. The final path therefore never holds a\n * partial or torn file: a concurrent writer of the same content-addressed\n * path (e.g. two clients re-fetching the same evicted attachment) streams to\n * its own temp file, and the rename publishes the new content all at once. On\n * any failure the temp file is removed and the previous file (if any) is left\n * untouched.\n *\n * Returns the number of bytes written.\n */\n// createWriteStream opens the file lazily, so destroy() can return before the\n// open has even happened and the open then creates the file after the unlink\n// below has run. Wait for the stream to close first, or the failed write\n// leaves its temp file behind.\nasync function discardTempFile(\n writer: ReturnType<typeof createWriteStream>,\n tempPath: string,\n): Promise<void> {\n writer.destroy();\n try {\n await finished(writer, { error: false });\n } catch {\n // The stream is already closed, which is all this wait is for.\n }\n await rm(tempPath, { force: true });\n}\n\nexport async function writeAttachmentBytes(\n path: string,\n data: ReadableStream<Uint8Array>,\n): Promise<number> {\n await mkdir(dirname(path), { recursive: true });\n\n const tempPath = join(dirname(path), `${randomUUID()}.tmp`);\n const writer = createWriteStream(tempPath);\n const reader = data.getReader();\n let bytesWritten = 0;\n let caughtError: Error | undefined;\n // A destination error can land before the drain-wait below has an 'error'\n // listener attached -- failing to open the temp file, or an async write\n // error between chunks -- so hold one listener for the whole write. First\n // error wins: an already-recorded source failure is the one to report.\n const recordError = (err: unknown) => {\n caughtError ??= err instanceof Error ? err : new Error(String(err));\n };\n writer.on(\"error\", recordError);\n\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n // The destination is destroyed once it errors, so writing again would\n // return false and wait for a 'drain' that can never come.\n if (caughtError) break;\n bytesWritten += value.byteLength;\n const canContinue = writer.write(value);\n if (!canContinue) {\n await new Promise<void>((resolve, reject) => {\n const onDrain = () => {\n writer.off(\"error\", onError);\n resolve();\n };\n const onError = (err: Error) => {\n writer.off(\"drain\", onDrain);\n reject(err);\n };\n writer.once(\"drain\", onDrain);\n writer.once(\"error\", onError);\n });\n }\n }\n } catch (err) {\n recordError(err);\n } finally {\n reader.releaseLock();\n }\n\n if (caughtError) {\n await discardTempFile(writer, tempPath);\n throw caughtError;\n }\n\n try {\n await new Promise<void>((resolve, reject) => {\n writer.end((err?: Error | null) => {\n if (err) reject(err);\n else resolve();\n });\n writer.once(\"error\", reject);\n });\n await rename(tempPath, path);\n } catch (err) {\n await discardTempFile(writer, tempPath);\n throw err instanceof Error ? err : new Error(String(err));\n }\n\n return bytesWritten;\n}\n\n/**\n * Open a ReadableStream from a file on disk.\n */\nexport function readAttachmentStream(path: string): ReadableStream<Uint8Array> {\n const nodeStream = createReadStream(path);\n return Readable.toWeb(nodeStream) as ReadableStream<Uint8Array>;\n}\n\n/**\n * Delete a file from disk. No-op if the file does not exist.\n */\nexport async function deleteAttachmentBytes(path: string): Promise<void> {\n await rm(path, { force: true });\n}\n\n/**\n * Check whether a file exists on disk.\n */\nexport async function attachmentBytesExist(path: string): Promise<boolean> {\n try {\n await access(path);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Create a ReadableStream from an in-memory buffer.\n */\nexport function streamFromBuffer(data: Uint8Array): ReadableStream<Uint8Array> {\n return new ReadableStream({\n start(controller) {\n controller.enqueue(data);\n controller.close();\n },\n });\n}\n\n/**\n * Stream bytes to a temp file under `${basePath}/.tmp/` while computing the\n * SHA-256 hash, returning the temp path, hex hash, and total bytes written.\n *\n * Bytes are never buffered in memory beyond the current chunk. The caller is\n * responsible for renaming the temp file to its final hash-derived location\n * (or removing it if the content is a duplicate).\n *\n * If `maxBytes` is set and the input exceeds it, the temp file is removed and\n * `UploadTooLarge` is thrown.\n *\n * If `declaredSizeBytes` is set, the byte count is enforced as a contract:\n * mid-stream, the moment the count exceeds the declaration the reader is\n * released and `SizeMismatch` is thrown without consuming the rest of the\n * stream. At stream end, if the count does not equal the declaration,\n * `SizeMismatch` is thrown. Both the `maxBytes` and `declaredSizeBytes`\n * checks apply; `maxBytes` is evaluated first on each chunk.\n *\n * If `signal` aborts, the temp file is removed and the signal's reason is\n * thrown. Nothing partial is ever returned, so a cancelled transfer cannot be\n * committed.\n */\nexport async function streamHashAndWrite(\n basePath: string,\n data: ReadableStream<Uint8Array>,\n options: {\n maxBytes?: number;\n declaredSizeBytes?: number;\n signal?: AbortSignal;\n } = {},\n): Promise<{ tempPath: string; hash: string; sizeBytes: number }> {\n const { maxBytes, declaredSizeBytes, signal } = options;\n // Before the temp file exists: an already-aborted transfer leaves no trace.\n signal?.throwIfAborted();\n const tmpDir = join(basePath, \".tmp\");\n await mkdir(tmpDir, { recursive: true });\n const tempPath = join(tmpDir, randomUUID());\n\n const hasher = createHash(\"sha256\");\n const writer = createWriteStream(tempPath);\n const reader = data.getReader();\n // Cancelling the source is what makes an abort observable while a read is\n // stalled -- it resolves the pending read as `done`. The post-loop\n // `throwIfAborted` is what stops that resolution being mistaken for the end\n // of the stream, which would commit a truncated attachment.\n const onAbort = () => {\n reader.cancel(signal?.reason).catch(() => {});\n };\n signal?.addEventListener(\"abort\", onAbort, { once: true });\n let sizeBytes = 0;\n let caughtError: Error | undefined;\n\n try {\n for (;;) {\n signal?.throwIfAborted();\n const { done, value } = await reader.read();\n if (done) break;\n sizeBytes += value.byteLength;\n if (maxBytes !== undefined && sizeBytes > maxBytes) {\n throw new UploadTooLarge(maxBytes);\n }\n if (declaredSizeBytes !== undefined && sizeBytes > declaredSizeBytes) {\n throw new SizeMismatch(declaredSizeBytes, sizeBytes);\n }\n hasher.update(value);\n const canContinue = writer.write(value);\n if (!canContinue) {\n await new Promise<void>((resolve, reject) => {\n const onDrain = () => {\n writer.off(\"error\", onError);\n resolve();\n };\n const onError = (err: Error) => {\n writer.off(\"drain\", onDrain);\n reject(err);\n };\n writer.once(\"drain\", onDrain);\n writer.once(\"error\", onError);\n });\n }\n }\n signal?.throwIfAborted();\n } catch (err) {\n caughtError = err instanceof Error ? err : new Error(String(err));\n } finally {\n signal?.removeEventListener(\"abort\", onAbort);\n reader.releaseLock();\n }\n\n let endError: Error | undefined;\n try {\n await new Promise<void>((resolve, reject) => {\n writer.end((err?: Error | null) => {\n if (err) reject(err);\n else resolve();\n });\n writer.once(\"error\", reject);\n });\n } catch (err) {\n endError = err instanceof Error ? err : new Error(String(err));\n }\n\n if (caughtError) {\n await rm(tempPath, { force: true });\n throw caughtError;\n }\n if (endError) {\n await rm(tempPath, { force: true });\n throw endError;\n }\n\n if (declaredSizeBytes !== undefined && sizeBytes !== declaredSizeBytes) {\n await rm(tempPath, { force: true });\n throw new SizeMismatch(declaredSizeBytes, sizeBytes);\n }\n\n return {\n tempPath,\n hash: hasher.digest(\"hex\"),\n sizeBytes,\n };\n}\n","import { join } from \"node:path\";\nimport type { Kysely } from \"kysely\";\nimport { sql } from \"kysely\";\nimport type { AttachmentHash } from \"@powerhousedao/reactor\";\nimport type {\n IAttachmentStore,\n IAttachmentTransport,\n} from \"../../interfaces.js\";\nimport type {\n AttachmentHeader,\n AttachmentMetadata,\n AttachmentResponse,\n AttachmentStatus,\n} from \"../../types.js\";\nimport { AttachmentNotFound, AttachmentPending } from \"../../errors.js\";\nimport type { AttachmentDatabase, AttachmentRow } from \"./types.js\";\nimport {\n storageRelativePath,\n writeAttachmentBytes,\n readAttachmentStream,\n deleteAttachmentBytes,\n} from \"../fs/attachment-fs.js\";\n\nfunction rowToHeader(row: AttachmentRow): AttachmentHeader {\n return {\n hash: row.hash,\n mimeType: row.mime_type,\n fileName: row.file_name,\n sizeBytes: Number(row.size_bytes),\n extension: row.extension,\n status: row.status as AttachmentStatus,\n source: row.source as \"local\" | \"sync\",\n createdAtUtc: row.created_at_utc,\n lastAccessedAtUtc: row.last_accessed_at_utc,\n expiresAtUtc: null,\n };\n}\n\nfunction wrapStreamWithCleanup(\n source: ReadableStream<Uint8Array>,\n cleanup: () => void,\n): ReadableStream<Uint8Array> {\n let cleaned = false;\n const doCleanup = () => {\n if (!cleaned) {\n cleaned = true;\n cleanup();\n }\n };\n\n const reader = source.getReader();\n return new ReadableStream<Uint8Array>({\n async pull(controller) {\n try {\n const { done, value } = await reader.read();\n if (done) {\n doCleanup();\n controller.close();\n } else {\n controller.enqueue(value);\n }\n } catch (err) {\n doCleanup();\n controller.error(err);\n }\n },\n cancel() {\n doCleanup();\n reader.cancel().catch(() => {});\n },\n });\n}\n\nexport class KyselyAttachmentStore implements IAttachmentStore {\n private readonly activeReaders = new Map<string, number>();\n\n constructor(\n private readonly db: Kysely<AttachmentDatabase>,\n private readonly transport: IAttachmentTransport,\n private readonly basePath: string,\n ) {}\n\n async stat(hash: AttachmentHash): Promise<AttachmentHeader> {\n const row = await this.db\n .selectFrom(\"attachment\")\n .selectAll()\n .where(\"hash\", \"=\", hash)\n .executeTakeFirst();\n\n if (row) {\n return rowToHeader(row);\n }\n\n const now = new Date().toISOString();\n const pending = await this.findPendingReservation(hash, now);\n\n if (pending) {\n return {\n hash,\n mimeType: pending.mime_type,\n fileName: pending.file_name,\n sizeBytes: Number(pending.size_bytes),\n extension: pending.extension,\n status: \"pending\",\n source: \"local\",\n createdAtUtc: pending.created_at_utc,\n lastAccessedAtUtc: pending.created_at_utc,\n expiresAtUtc: pending.expires_at_utc,\n };\n }\n\n throw new AttachmentNotFound(hash);\n }\n\n async has(hash: AttachmentHash): Promise<boolean> {\n const row = await this.db\n .selectFrom(\"attachment\")\n .select(\"status\")\n .where(\"hash\", \"=\", hash)\n .executeTakeFirst();\n\n return row?.status === \"available\";\n }\n\n async get(\n hash: AttachmentHash,\n signal?: AbortSignal,\n documentId?: string,\n ): Promise<AttachmentResponse> {\n const row = await this.db\n .selectFrom(\"attachment\")\n .selectAll()\n .where(\"hash\", \"=\", hash)\n .executeTakeFirst();\n\n if (row) {\n if (row.status === \"evicted\") {\n return this.fetchRemote(hash, signal, documentId);\n }\n\n const now = new Date().toISOString();\n await this.db\n .updateTable(\"attachment\")\n .set({ last_accessed_at_utc: now })\n .where(\"hash\", \"=\", hash)\n .execute();\n\n const header = rowToHeader(row);\n header.lastAccessedAtUtc = now;\n\n this.acquireReader(hash);\n\n const fullPath = join(this.basePath, row.storage_path);\n const rawStream = readAttachmentStream(fullPath);\n const body = wrapStreamWithCleanup(rawStream, () =>\n this.releaseReader(hash),\n );\n\n return { header, body };\n }\n\n const now = new Date().toISOString();\n const pending = await this.findPendingReservation(hash, now);\n\n if (pending) {\n throw new AttachmentPending(hash, pending.expires_at_utc, {\n mimeType: pending.mime_type,\n fileName: pending.file_name,\n sizeBytes: pending.size_bytes,\n });\n }\n\n return this.fetchRemote(hash, signal, documentId);\n }\n\n async put(\n hash: AttachmentHash,\n metadata: AttachmentMetadata,\n data: ReadableStream<Uint8Array>,\n ): Promise<void> {\n const existing = await this.db\n .selectFrom(\"attachment\")\n .select([\"hash\", \"status\"])\n .where(\"hash\", \"=\", hash)\n .executeTakeFirst();\n\n if (existing?.status === \"available\") {\n await data.cancel();\n return;\n }\n\n const relPath = storageRelativePath(hash);\n const fullPath = join(this.basePath, relPath);\n await writeAttachmentBytes(fullPath, data);\n\n const now = new Date().toISOString();\n\n if (!existing) {\n await this.db\n .insertInto(\"attachment\")\n .values({\n hash,\n mime_type: metadata.mimeType,\n file_name: metadata.fileName,\n size_bytes: metadata.sizeBytes,\n extension: metadata.extension ?? null,\n status: \"available\",\n storage_path: relPath,\n source: \"sync\",\n created_at_utc: metadata.createdAtUtc,\n last_accessed_at_utc: now,\n })\n .onConflict((oc) => oc.column(\"hash\").doNothing())\n .execute();\n } else {\n await this.db\n .updateTable(\"attachment\")\n .set({\n status: \"available\",\n storage_path: relPath,\n last_accessed_at_utc: now,\n })\n .where(\"hash\", \"=\", hash)\n .where(\"status\", \"=\", \"evicted\")\n .execute();\n }\n }\n\n async evict(hash: AttachmentHash): Promise<void> {\n if (this.hasActiveReaders(hash)) {\n return;\n }\n\n const row = await this.db\n .selectFrom(\"attachment\")\n .select([\"storage_path\", \"status\"])\n .where(\"hash\", \"=\", hash)\n .executeTakeFirst();\n\n if (!row || row.status === \"evicted\") {\n return;\n }\n\n const fullPath = join(this.basePath, row.storage_path);\n await deleteAttachmentBytes(fullPath);\n\n await this.db\n .updateTable(\"attachment\")\n .set({ status: \"evicted\" })\n .where(\"hash\", \"=\", hash)\n .execute();\n }\n\n async storageUsed(): Promise<number> {\n const result = await this.db\n .selectFrom(\"attachment\")\n .select(sql<string>`COALESCE(SUM(size_bytes), 0)`.as(\"total\"))\n .where(\"status\", \"=\", \"available\")\n .executeTakeFirst();\n\n return Number(result?.total ?? 0);\n }\n\n // Private: remote re-fetch, pending reservation lookup and active reader tracking\n\n private async fetchRemote(\n hash: AttachmentHash,\n signal: AbortSignal | undefined,\n documentId: string | undefined,\n ): Promise<AttachmentResponse> {\n if (documentId === undefined) {\n throw new AttachmentNotFound(hash);\n }\n const remote = await this.transport.fetch(hash, documentId, signal);\n if (remote.kind === \"data\") {\n await this.put(hash, remote.response.metadata, remote.response.body);\n return this.get(hash, signal);\n }\n if (remote.kind === \"pending\") {\n throw new AttachmentPending(hash, remote.expiresAtUtc);\n }\n throw new AttachmentNotFound(hash);\n }\n\n private async findPendingReservation(\n hash: AttachmentHash,\n now: string,\n ): Promise<{\n mime_type: string;\n file_name: string;\n extension: string | null;\n size_bytes: number;\n created_at_utc: string;\n expires_at_utc: string;\n } | null> {\n const row = await this.db\n .selectFrom(\"attachment_reservation as r\")\n .leftJoin(\"attachment as a\", \"a.hash\", \"r.client_hash\")\n .select([\n \"r.mime_type\",\n \"r.file_name\",\n \"r.extension\",\n \"r.size_bytes\",\n \"r.created_at_utc\",\n \"r.expires_at_utc\",\n ])\n .where(\"r.client_hash\", \"=\", hash)\n .where(\"r.deleted_at_utc\", \"is\", null)\n .where(\"r.expires_at_utc\", \">\", now)\n .where(\"r.size_bytes\", \"is not\", null)\n .where(\"a.hash\", \"is\", null)\n .orderBy(\"r.expires_at_utc\", \"desc\")\n .executeTakeFirst();\n\n if (!row) return null;\n return {\n mime_type: row.mime_type,\n file_name: row.file_name,\n extension: row.extension,\n size_bytes: Number(row.size_bytes),\n created_at_utc: row.created_at_utc,\n expires_at_utc: row.expires_at_utc,\n };\n }\n\n private acquireReader(hash: string): void {\n this.activeReaders.set(hash, (this.activeReaders.get(hash) ?? 0) + 1);\n }\n\n private releaseReader(hash: string): void {\n const count = (this.activeReaders.get(hash) ?? 1) - 1;\n if (count <= 0) {\n this.activeReaders.delete(hash);\n } else {\n this.activeReaders.set(hash, count);\n }\n }\n\n private hasActiveReaders(hash: string): boolean {\n return (this.activeReaders.get(hash) ?? 0) > 0;\n }\n}\n","import { randomUUID } from \"node:crypto\";\nimport type { Kysely } from \"kysely\";\nimport type { IReservationStore } from \"../../interfaces.js\";\nimport type { Reservation, ReserveAttachmentOptions } from \"../../types.js\";\nimport { ReservationNotFound } from \"../../errors.js\";\nimport type { AttachmentDatabase, ReservationRow } from \"./types.js\";\n\nexport const DEFAULT_RESERVATION_TTL_MS = 24 * 60 * 60 * 1000;\n\nfunction rowToReservation(row: ReservationRow): Reservation {\n return {\n reservationId: row.reservation_id,\n mimeType: row.mime_type,\n fileName: row.file_name,\n extension: row.extension,\n createdAtUtc: row.created_at_utc,\n expiresAtUtc: row.expires_at_utc,\n clientHash: row.client_hash,\n sizeBytes: row.size_bytes !== null ? Number(row.size_bytes) : null,\n };\n}\n\nexport class KyselyReservationStore implements IReservationStore {\n private readonly ttlMs: number;\n\n constructor(\n private readonly db: Kysely<AttachmentDatabase>,\n ttlMs: number = DEFAULT_RESERVATION_TTL_MS,\n ) {\n this.ttlMs = ttlMs;\n }\n\n async create(options: ReserveAttachmentOptions): Promise<Reservation> {\n const reservationId = randomUUID();\n const nowMs = Date.now();\n const now = new Date(nowMs).toISOString();\n const expiresAt = new Date(nowMs + this.ttlMs).toISOString();\n\n const row = await this.db\n .insertInto(\"attachment_reservation\")\n .values({\n reservation_id: reservationId,\n mime_type: options.mimeType,\n file_name: options.fileName,\n extension: options.extension ?? null,\n created_at_utc: now,\n expires_at_utc: expiresAt,\n client_hash: options.clientHash ?? null,\n size_bytes: options.sizeBytes ?? null,\n })\n .returningAll()\n .executeTakeFirstOrThrow();\n\n return rowToReservation(row);\n }\n\n async get(reservationId: string): Promise<Reservation> {\n const row = await this.db\n .selectFrom(\"attachment_reservation\")\n .selectAll()\n .where(\"reservation_id\", \"=\", reservationId)\n .where(\"deleted_at_utc\", \"is\", null)\n .executeTakeFirst();\n\n if (!row) {\n throw new ReservationNotFound(reservationId);\n }\n\n return rowToReservation(row);\n }\n\n async delete(reservationId: string): Promise<void> {\n await this.db\n .updateTable(\"attachment_reservation\")\n .set({ deleted_at_utc: new Date().toISOString() })\n .where(\"reservation_id\", \"=\", reservationId)\n .where(\"deleted_at_utc\", \"is\", null)\n .execute();\n }\n\n async deleteExpired(now: Date = new Date()): Promise<number> {\n const nowIso = now.toISOString();\n const result = await this.db\n .updateTable(\"attachment_reservation\")\n .set({ deleted_at_utc: nowIso })\n .where(\"expires_at_utc\", \"<=\", nowIso)\n .where(\"deleted_at_utc\", \"is\", null)\n .executeTakeFirst();\n\n return Number(result.numUpdatedRows);\n }\n}\n","import type { Kysely } from \"kysely\";\n\nexport async function up(db: Kysely<any>): Promise<void> {\n await db.schema\n .createTable(\"attachment\")\n .addColumn(\"hash\", \"text\", (col) => col.primaryKey())\n .addColumn(\"mime_type\", \"text\", (col) => col.notNull())\n .addColumn(\"file_name\", \"text\", (col) => col.notNull())\n .addColumn(\"size_bytes\", \"bigint\", (col) => col.notNull())\n .addColumn(\"extension\", \"text\")\n .addColumn(\"status\", \"text\", (col) => col.notNull().defaultTo(\"available\"))\n .addColumn(\"storage_path\", \"text\", (col) => col.notNull())\n .addColumn(\"source\", \"text\", (col) => col.notNull().defaultTo(\"local\"))\n .addColumn(\"created_at_utc\", \"text\", (col) => col.notNull())\n .addColumn(\"last_accessed_at_utc\", \"text\", (col) => col.notNull())\n .execute();\n\n await db.schema\n .createIndex(\"idx_attachment_status\")\n .on(\"attachment\")\n .column(\"status\")\n .execute();\n\n // Compound index serves the LRU eviction query:\n // SELECT ... WHERE status = 'available' ORDER BY last_accessed_at_utc ASC\n // A partial index would be ideal but raw SQL doesn't respect withSchema().\n await db.schema\n .createIndex(\"idx_attachment_lru\")\n .on(\"attachment\")\n .columns([\"status\", \"last_accessed_at_utc\"])\n .execute();\n}\n\nexport async function down(db: Kysely<any>): Promise<void> {\n await db.schema.dropTable(\"attachment\").ifExists().execute();\n}\n","import type { Kysely } from \"kysely\";\n\nexport async function up(db: Kysely<any>): Promise<void> {\n await db.schema\n .createTable(\"attachment_reservation\")\n .addColumn(\"reservation_id\", \"text\", (col) => col.primaryKey())\n .addColumn(\"mime_type\", \"text\", (col) => col.notNull())\n .addColumn(\"file_name\", \"text\", (col) => col.notNull())\n .addColumn(\"extension\", \"text\")\n .addColumn(\"created_at_utc\", \"text\", (col) => col.notNull())\n .execute();\n}\n\nexport async function down(db: Kysely<any>): Promise<void> {\n await db.schema.dropTable(\"attachment_reservation\").ifExists().execute();\n}\n","import { sql, type Kysely } from \"kysely\";\n\nexport async function up(db: Kysely<any>): Promise<void> {\n await db.schema\n .alterTable(\"attachment_reservation\")\n .addColumn(\"expires_at_utc\", \"text\")\n .execute();\n\n await db\n .updateTable(\"attachment_reservation\")\n .set({ expires_at_utc: sql`created_at_utc` })\n .where(\"expires_at_utc\", \"is\", null)\n .execute();\n\n await db.schema\n .alterTable(\"attachment_reservation\")\n .alterColumn(\"expires_at_utc\", (col) => col.setNotNull())\n .execute();\n\n await db.schema\n .createIndex(\"idx_reservation_expires_at\")\n .on(\"attachment_reservation\")\n .column(\"expires_at_utc\")\n .execute();\n}\n\nexport async function down(db: Kysely<any>): Promise<void> {\n await db.schema.dropIndex(\"idx_reservation_expires_at\").ifExists().execute();\n\n await db.schema\n .alterTable(\"attachment_reservation\")\n .dropColumn(\"expires_at_utc\")\n .execute();\n}\n","import type { Kysely } from \"kysely\";\n\nexport async function up(db: Kysely<any>): Promise<void> {\n await db.schema\n .alterTable(\"attachment_reservation\")\n .addColumn(\"deleted_at_utc\", \"text\")\n .execute();\n}\n\nexport async function down(db: Kysely<any>): Promise<void> {\n await db.schema\n .alterTable(\"attachment_reservation\")\n .dropColumn(\"deleted_at_utc\")\n .execute();\n}\n","import { sql, type Kysely, type SqlBool } from \"kysely\";\n\nexport async function up(db: Kysely<any>): Promise<void> {\n await db.schema.dropIndex(\"idx_reservation_expires_at\").ifExists().execute();\n\n await db.schema\n .createIndex(\"idx_reservation_expires_at_active\")\n .on(\"attachment_reservation\")\n .column(\"expires_at_utc\")\n .where(sql<SqlBool>`deleted_at_utc IS NULL`)\n .execute();\n}\n\nexport async function down(db: Kysely<any>): Promise<void> {\n await db.schema\n .dropIndex(\"idx_reservation_expires_at_active\")\n .ifExists()\n .execute();\n\n await db.schema\n .createIndex(\"idx_reservation_expires_at\")\n .on(\"attachment_reservation\")\n .column(\"expires_at_utc\")\n .execute();\n}\n","import { sql, type Kysely } from \"kysely\";\n\nexport async function up(db: Kysely<any>): Promise<void> {\n await db.schema\n .alterTable(\"attachment_reservation\")\n .addColumn(\"client_hash\", \"text\")\n .execute();\n\n await db.schema\n .alterTable(\"attachment_reservation\")\n .addColumn(\"size_bytes\", \"bigint\")\n .execute();\n\n // Structural enforcement: size_bytes must be present whenever client_hash\n // is present. The expression references only the row's own columns so the\n // known withSchema() caveat (raw SQL table references are not schema-\n // qualified) does not apply here.\n await db.schema\n .alterTable(\"attachment_reservation\")\n .addCheckConstraint(\n \"attachment_reservation_hash_size_check\",\n sql`client_hash is null or size_bytes is not null`,\n )\n .execute();\n\n // Non-unique index. Partial unique indexes are not used here: raw SQL\n // index predicates do not respect withSchema() (see migration 001), and\n // uniqueness is deliberately not a requirement (concurrent reservations\n // for the same hash are permitted -- see the hash-first design doc).\n await db.schema\n .createIndex(\"idx_reservation_client_hash\")\n .on(\"attachment_reservation\")\n .column(\"client_hash\")\n .execute();\n}\n\nexport async function down(db: Kysely<any>): Promise<void> {\n await db.schema.dropIndex(\"idx_reservation_client_hash\").ifExists().execute();\n\n await db.schema\n .alterTable(\"attachment_reservation\")\n .dropColumn(\"size_bytes\")\n .execute();\n\n await db.schema\n .alterTable(\"attachment_reservation\")\n .dropColumn(\"client_hash\")\n .execute();\n}\n","import { Migrator, sql } from \"kysely\";\nimport type { MigrationProvider, Kysely } from \"kysely\";\n\nimport * as migration001 from \"./001_create_attachment_table.js\";\nimport * as migration002 from \"./002_create_reservation_table.js\";\nimport * as migration003 from \"./003_add_reservation_expires_at.js\";\nimport * as migration004 from \"./004_add_reservation_soft_delete.js\";\nimport * as migration005 from \"./005_add_reservation_active_index.js\";\nimport * as migration006 from \"./006_add_reservation_client_hash.js\";\n\nexport const ATTACHMENT_SCHEMA = \"attachments\";\n\nexport interface MigrationResult {\n success: boolean;\n migrationsExecuted: string[];\n error?: Error;\n}\n\nconst migrations = {\n \"001_create_attachment_table\": migration001,\n \"002_create_reservation_table\": migration002,\n \"003_add_reservation_expires_at\": migration003,\n \"004_add_reservation_soft_delete\": migration004,\n \"005_add_reservation_active_index\": migration005,\n \"006_add_reservation_client_hash\": migration006,\n};\n\nclass ProgrammaticMigrationProvider implements MigrationProvider {\n getMigrations() {\n return Promise.resolve(migrations);\n }\n}\n\nexport async function runAttachmentMigrations(\n db: Kysely<any>,\n schema: string = ATTACHMENT_SCHEMA,\n): Promise<MigrationResult> {\n try {\n await sql`CREATE SCHEMA IF NOT EXISTS ${sql.id(schema)}`.execute(db);\n } catch (error) {\n return {\n success: false,\n migrationsExecuted: [],\n error:\n error instanceof Error ? error : new Error(\"Failed to create schema\"),\n };\n }\n\n const migrator = new Migrator({\n db: db.withSchema(schema),\n provider: new ProgrammaticMigrationProvider(),\n migrationTableSchema: schema,\n });\n\n let error: unknown;\n let results: Awaited<ReturnType<typeof migrator.migrateToLatest>>[\"results\"];\n try {\n const result = await migrator.migrateToLatest();\n error = result.error;\n results = result.results;\n } catch (e) {\n error = e;\n results = [];\n }\n\n const migrationsExecuted =\n results?.map((result) => result.migrationName) ?? [];\n\n if (error) {\n return {\n success: false,\n migrationsExecuted,\n error:\n error instanceof Error ? error : new Error(\"Unknown migration error\"),\n };\n }\n\n return {\n success: true,\n migrationsExecuted,\n };\n}\n","import { mkdir, rename, rm } from \"node:fs/promises\";\nimport { dirname, join } from \"node:path\";\nimport type { Kysely } from \"kysely\";\nimport type { AttachmentRef } from \"@powerhousedao/reactor\";\nimport type { IAttachmentUpload, IReservationStore } from \"../interfaces.js\";\nimport type {\n AttachmentHeader,\n AttachmentSendOptions,\n AttachmentUploadResult,\n Reservation,\n} from \"../types.js\";\nimport type {\n AttachmentDatabase,\n AttachmentRow,\n} from \"../storage/kysely/types.js\";\nimport { HashMismatch } from \"../errors.js\";\nimport { createRef } from \"../ref.js\";\nimport {\n storageRelativePath,\n streamHashAndWrite,\n} from \"../storage/fs/attachment-fs.js\";\nimport type { AttachmentStatus } from \"../types.js\";\nimport { isBlob } from \"../blob.js\";\n\nfunction rowToHeader(row: AttachmentRow): AttachmentHeader {\n return {\n hash: row.hash,\n mimeType: row.mime_type,\n fileName: row.file_name,\n sizeBytes: Number(row.size_bytes),\n extension: row.extension,\n status: row.status as AttachmentStatus,\n source: row.source as \"local\" | \"sync\",\n createdAtUtc: row.created_at_utc,\n lastAccessedAtUtc: row.last_accessed_at_utc,\n expiresAtUtc: null,\n };\n}\n\nexport class DirectAttachmentUpload implements IAttachmentUpload {\n readonly reservationId: string;\n readonly ref: AttachmentRef | null;\n readonly expiresAtUtc: string;\n\n constructor(\n private readonly reservation: Reservation,\n private readonly db: Kysely<AttachmentDatabase>,\n private readonly basePath: string,\n private readonly reservations: IReservationStore,\n private readonly maxBytes?: number,\n ) {\n this.reservationId = reservation.reservationId;\n this.ref =\n reservation.clientHash != null ? createRef(reservation.clientHash) : null;\n this.expiresAtUtc = reservation.expiresAtUtc;\n }\n\n async send(\n data: ReadableStream<Uint8Array> | Blob,\n options?: AttachmentSendOptions,\n ): Promise<AttachmentUploadResult> {\n if (\n this.reservation.clientHash != null &&\n this.reservation.sizeBytes == null\n ) {\n throw new Error(\"hash-first reservation missing sizeBytes\");\n }\n // Stream bytes directly to a temp file while hashing. This caps memory\n // usage at one chunk regardless of payload size, and lets us enforce\n // `maxBytes` before either disk or memory grows unbounded.\n // When clientHash is present, declaredSizeBytes is enforced during the\n // stream: exceeding it aborts early, and a short stream fails at end.\n const declaredSizeBytes =\n this.reservation.clientHash != null\n ? (this.reservation.sizeBytes ?? undefined)\n : undefined;\n // The signal is honoured for the streaming write, the only part of this\n // send that can run long: a cancel there rejects and commits nothing.\n const { tempPath, hash, sizeBytes } = await streamHashAndWrite(\n this.basePath,\n isBlob(data) ? data.stream() : data,\n {\n maxBytes: this.maxBytes,\n declaredSizeBytes,\n ...(options?.signal ? { signal: options.signal } : {}),\n },\n );\n\n // Hash verification: if the client claimed a hash, compare before any\n // DB write or rename. On mismatch the temp file is removed and the\n // reservation is deliberately retained so the client can retry.\n if (\n this.reservation.clientHash != null &&\n hash !== this.reservation.clientHash\n ) {\n await rm(tempPath, { force: true });\n throw new HashMismatch(this.reservation.clientHash, hash);\n }\n\n try {\n const existing = await this.db\n .selectFrom(\"attachment\")\n .select([\"hash\", \"status\"])\n .where(\"hash\", \"=\", hash)\n .executeTakeFirst();\n\n if (existing?.status === \"available\") {\n // Dedup -- bytes already on disk, drop the temp file.\n await rm(tempPath, { force: true });\n } else {\n const relPath = storageRelativePath(hash);\n const fullPath = join(this.basePath, relPath);\n await mkdir(dirname(fullPath), { recursive: true });\n await rename(tempPath, fullPath);\n\n const now = new Date().toISOString();\n\n if (!existing) {\n await this.db\n .insertInto(\"attachment\")\n .values({\n hash,\n mime_type: this.reservation.mimeType,\n file_name: this.reservation.fileName,\n size_bytes: sizeBytes,\n extension: this.reservation.extension ?? null,\n status: \"available\",\n storage_path: relPath,\n source: \"local\",\n created_at_utc: now,\n last_accessed_at_utc: now,\n })\n .onConflict((oc) => oc.column(\"hash\").doNothing())\n .execute();\n } else {\n // Existing row was evicted — restore it\n await this.db\n .updateTable(\"attachment\")\n .set({\n status: \"available\",\n storage_path: relPath,\n source: \"local\",\n last_accessed_at_utc: now,\n })\n .where(\"hash\", \"=\", hash)\n .where(\"status\", \"=\", \"evicted\")\n .execute();\n }\n }\n } catch (err) {\n await rm(tempPath, { force: true });\n throw err;\n }\n\n await this.reservations.delete(this.reservationId);\n\n const row = await this.db\n .selectFrom(\"attachment\")\n .selectAll()\n .where(\"hash\", \"=\", hash)\n .executeTakeFirstOrThrow();\n\n return {\n hash,\n ref: createRef(hash),\n header: rowToHeader(row),\n };\n }\n}\n","import type { Kysely } from \"kysely\";\nimport type {\n IAttachmentUpload,\n IAttachmentUploadFactory,\n IReservationStore,\n} from \"../interfaces.js\";\nimport type { Reservation } from \"../types.js\";\nimport type { AttachmentDatabase } from \"../storage/kysely/types.js\";\nimport { DirectAttachmentUpload } from \"./direct-attachment-upload.js\";\n\nexport class DirectAttachmentUploadFactory implements IAttachmentUploadFactory {\n constructor(\n private readonly db: Kysely<AttachmentDatabase>,\n private readonly basePath: string,\n private readonly reservations: IReservationStore,\n private readonly maxBytes?: number,\n ) {}\n\n createUpload(reservation: Reservation): IAttachmentUpload {\n return new DirectAttachmentUpload(\n reservation,\n this.db,\n this.basePath,\n this.reservations,\n this.maxBytes,\n );\n }\n}\n","import type { AttachmentHash } from \"@powerhousedao/reactor\";\nimport type { IAttachmentBackend, IAttachmentStore } from \"../interfaces.js\";\nimport {\n parseAttachmentDownloadTarget,\n parseAttachmentUploadTarget,\n} from \"../targets.js\";\nimport type {\n AttachmentBackendHealth,\n AttachmentDownloadTarget,\n AttachmentUploadTarget,\n Reservation,\n} from \"../types.js\";\n\nexport type FilesystemAttachmentBackendConfig = {\n uploadTarget: (reservation: Reservation) => unknown;\n downloadTarget: (hash: AttachmentHash) => unknown;\n readiness?: () => boolean | Promise<boolean>;\n};\n\n/**\n * Filesystem keeps byte transfer behind Switchboard. URL construction stays\n * at the server edge, while this adapter validates that a filesystem backend\n * can never accidentally return a direct-provider target.\n */\nexport class FilesystemAttachmentBackend implements IAttachmentBackend {\n readonly kind = \"filesystem\" as const;\n\n constructor(\n private readonly store: Pick<IAttachmentStore, \"has\">,\n private readonly config: FilesystemAttachmentBackendConfig,\n ) {}\n\n async prepareUploadTarget(\n reservation: Reservation,\n ): Promise<AttachmentUploadTarget> {\n const target = parseAttachmentUploadTarget(\n await this.config.uploadTarget(reservation),\n );\n if (target.kind !== \"switchboard\") {\n throw new Error(\"Filesystem upload target must use Switchboard\");\n }\n return target;\n }\n\n async prepareDownloadTarget(\n hash: AttachmentHash,\n ): Promise<AttachmentDownloadTarget> {\n const target = parseAttachmentDownloadTarget(\n await this.config.downloadTarget(hash),\n );\n if (target.kind !== \"switchboard\") {\n throw new Error(\"Filesystem download target must use Switchboard\");\n }\n return target;\n }\n\n exists(hash: AttachmentHash): Promise<boolean> {\n return this.store.has(hash);\n }\n\n async health(): Promise<AttachmentBackendHealth> {\n return {\n kind: this.kind,\n ready: await (this.config.readiness?.() ?? true),\n };\n }\n}\n","import type { AttachmentRef } from \"@powerhousedao/reactor\";\nimport type {\n IAttachmentUpload,\n IAttachmentUploadFactory,\n} from \"../../interfaces.js\";\nimport { createRef } from \"../../ref.js\";\nimport type {\n AttachmentUploadResult,\n AttachmentUploadTarget,\n Reservation,\n} from \"../../types.js\";\nimport { isBlob } from \"../../blob.js\";\n\nclass S3AttachmentUpload implements IAttachmentUpload {\n readonly reservationId: string;\n readonly ref: AttachmentRef | null;\n readonly expiresAtUtc: string;\n readonly uploadTarget?: AttachmentUploadTarget;\n\n constructor(reservation: Reservation) {\n this.reservationId = reservation.reservationId;\n this.ref =\n reservation.clientHash === null\n ? null\n : createRef(reservation.clientHash);\n this.expiresAtUtc = reservation.expiresAtUtc;\n this.uploadTarget = reservation.uploadTarget;\n }\n\n // No `options`: this handle never transfers bytes, so there is no progress\n // to report and nothing for a signal to abort. Callers must use the\n // presigned target, which honours both.\n async send(\n data: ReadableStream<Uint8Array> | Blob,\n ): Promise<AttachmentUploadResult> {\n if (!isBlob(data)) await data.cancel().catch(() => {});\n throw new Error(\"S3 attachment upload must use the presigned target\");\n }\n}\n\nexport class S3AttachmentUploadFactory implements IAttachmentUploadFactory {\n createUpload(reservation: Reservation): IAttachmentUpload {\n return new S3AttachmentUpload(reservation);\n }\n}\n","import type { Kysely } from \"kysely\";\nimport type {\n IAttachmentBackend,\n IAttachmentTransport,\n IAttachmentUploadFactory,\n} from \"./interfaces.js\";\nimport type { AttachmentDatabase } from \"./storage/kysely/types.js\";\nimport { AttachmentService } from \"./attachment-service.js\";\nimport { KyselyAttachmentStore } from \"./storage/kysely/attachment-store.js\";\nimport { KyselyReservationStore } from \"./storage/kysely/reservation-store.js\";\nimport { DirectAttachmentUploadFactory } from \"./direct/direct-attachment-upload-factory.js\";\nimport {\n runAttachmentMigrations,\n ATTACHMENT_SCHEMA,\n} from \"./storage/migrations/migrator.js\";\nimport { NullAttachmentTransport } from \"./null-attachment-transport.js\";\nimport { S3AttachmentUploadFactory } from \"./storage/s3/upload-factory.js\";\n\nexport type AttachmentBuildResult = {\n service: AttachmentService;\n store: KyselyAttachmentStore;\n reservations: KyselyReservationStore;\n uploadFactory: IAttachmentUploadFactory;\n /** Selected direct-transfer backend, when startup configured one. */\n backend?: IAttachmentBackend;\n /** Stops the reservation sweep timer, if one was configured via withReservationSweepMs(). */\n destroy: () => void;\n};\n\nexport class AttachmentBuilder {\n private transport: IAttachmentTransport = new NullAttachmentTransport();\n private customUploadFactory?: IAttachmentUploadFactory;\n private maxUploadBytes?: number;\n private reservationSweepMs?: number;\n private backend?: IAttachmentBackend;\n\n constructor(\n private readonly db: Kysely<any>,\n private readonly storagePath: string,\n ) {}\n\n withTransport(transport: IAttachmentTransport): this {\n this.transport = transport;\n return this;\n }\n\n withUploadFactory(factory: IAttachmentUploadFactory): this {\n this.customUploadFactory = factory;\n return this;\n }\n\n withBackend(backend: IAttachmentBackend): this {\n this.backend = backend;\n return this;\n }\n\n withMaxUploadBytes(maxBytes: number): this {\n this.maxUploadBytes = maxBytes;\n return this;\n }\n\n /**\n * Configure a recurring sweep that deletes expired reservations.\n * The sweep calls reservations.deleteExpired() on the given interval.\n * When set, the built result's destroy() clears the timer.\n * Without this option no sweep runs -- deleteExpired() is never called\n * automatically. Call withReservationSweepMs in production to prevent\n * expired reservation rows from accumulating indefinitely.\n */\n withReservationSweepMs(intervalMs: number): this {\n this.reservationSweepMs = intervalMs;\n return this;\n }\n\n async build(): Promise<AttachmentBuildResult> {\n const result = await runAttachmentMigrations(this.db, ATTACHMENT_SCHEMA);\n if (!result.success && result.error) {\n throw result.error;\n }\n\n const scopedDb = this.db.withSchema(\n ATTACHMENT_SCHEMA,\n ) as Kysely<AttachmentDatabase>;\n\n const store = new KyselyAttachmentStore(\n scopedDb,\n this.transport,\n this.storagePath,\n );\n const reservations = new KyselyReservationStore(scopedDb);\n\n const uploadFactory =\n this.customUploadFactory ??\n (this.backend?.kind === \"s3\"\n ? new S3AttachmentUploadFactory()\n : new DirectAttachmentUploadFactory(\n scopedDb,\n this.storagePath,\n reservations,\n this.maxUploadBytes,\n ));\n\n const service = new AttachmentService(\n store,\n reservations,\n uploadFactory,\n this.backend,\n );\n\n let sweepTimer: ReturnType<typeof setInterval> | undefined;\n if (this.reservationSweepMs !== undefined) {\n const intervalMs = this.reservationSweepMs;\n sweepTimer = setInterval(() => {\n // Sweep failures are retried on the next interval; swallow to prevent\n // unhandled rejection from terminating the process.\n reservations.deleteExpired().catch(() => {});\n }, intervalMs);\n if (typeof sweepTimer.unref === \"function\") {\n sweepTimer.unref();\n }\n }\n\n const destroy = (): void => {\n if (sweepTimer !== undefined) {\n clearInterval(sweepTimer);\n sweepTimer = undefined;\n }\n };\n\n return {\n service,\n store,\n reservations,\n uploadFactory,\n ...(this.backend ? { backend: this.backend } : {}),\n destroy,\n };\n }\n}\n","import type { AttachmentRef } from \"@powerhousedao/reactor\";\nimport type { Kysely } from \"kysely\";\nimport { parseRef } from \"../../ref.js\";\nimport type { AttachmentReferenceDatabase } from \"./storage/types.js\";\nimport type {\n AttachmentReferenceInput,\n AttachmentReferencePageResult,\n IAttachmentReferenceReader,\n IAttachmentReferenceScanner,\n IAttachmentReferenceWriter,\n} from \"./types.js\";\n\n/** Keyset cursor: the `(document_id, attachment_ref)` pair the last page ended on. */\ntype ScanCursor = {\n documentId: string;\n ref: string;\n};\n\nfunction encodeCursor(cursor: ScanCursor): string {\n return JSON.stringify([cursor.documentId, cursor.ref]);\n}\n\nfunction decodeCursor(cursor: string): ScanCursor {\n let parsed: unknown;\n try {\n parsed = JSON.parse(cursor);\n } catch {\n // Malformed JSON is a bad cursor, not an uncaught SyntaxError leaking out\n // of a scan: report it as the named error the caller expects.\n throw new Error(\n `Invalid attachment reference scan cursor: ${JSON.stringify(cursor)}`,\n );\n }\n if (\n !Array.isArray(parsed) ||\n parsed.length !== 2 ||\n typeof parsed[0] !== \"string\" ||\n parsed[0] === \"\" ||\n typeof parsed[1] !== \"string\" ||\n parsed[1] === \"\"\n ) {\n throw new Error(\n `Invalid attachment reference scan cursor: ${JSON.stringify(cursor)}`,\n );\n }\n return { documentId: parsed[0], ref: parsed[1] };\n}\n\nexport class KyselyAttachmentReferenceStore\n implements\n IAttachmentReferenceReader,\n IAttachmentReferenceScanner,\n IAttachmentReferenceWriter\n{\n constructor(private readonly db: Kysely<AttachmentReferenceDatabase>) {}\n\n async hasReference(documentId: string, ref: AttachmentRef): Promise<boolean> {\n const row = await this.db\n .selectFrom(\"attachment_reference\")\n .select(\"document_id\")\n .where(\"document_id\", \"=\", documentId)\n .where(\"attachment_ref\", \"=\", ref)\n .executeTakeFirst();\n\n return row !== undefined;\n }\n\n async referencingScopes(\n documentId: string,\n ref: AttachmentRef,\n ): Promise<string[]> {\n const rows = await this.db\n .selectFrom(\"attachment_reference\")\n .select(\"scope\")\n .distinct()\n .where(\"document_id\", \"=\", documentId)\n .where(\"attachment_ref\", \"=\", ref)\n .execute();\n\n return rows.map((row) => row.scope);\n }\n\n /**\n * Keyset paging over the unique `(document_id, attachment_ref)` constraint,\n * rather than OFFSET: a scan that runs while the read model is still\n * indexing must not skip or repeat a row because rows appeared behind the\n * cursor. That is exactly the boot case the replicator's re-scan runs in.\n */\n async listReferences(\n cursor: string | undefined,\n limit: number,\n ): Promise<AttachmentReferencePageResult> {\n let query = this.db\n .selectFrom(\"attachment_reference\")\n .select([\"document_id\", \"attachment_ref\"])\n .orderBy(\"document_id\", \"asc\")\n .orderBy(\"attachment_ref\", \"asc\")\n .limit(limit);\n\n if (cursor !== undefined) {\n const after = decodeCursor(cursor);\n query = query.where((eb) =>\n eb.or([\n eb(\"document_id\", \">\", after.documentId),\n eb.and([\n eb(\"document_id\", \"=\", after.documentId),\n eb(\"attachment_ref\", \">\", after.ref),\n ]),\n ]),\n );\n }\n\n const rows = await query.execute();\n const last = rows.at(-1);\n return {\n references: rows.map((row) => ({\n documentId: row.document_id,\n ref: row.attachment_ref as AttachmentRef,\n })),\n nextCursor:\n rows.length === limit && last\n ? encodeCursor({\n documentId: last.document_id,\n ref: last.attachment_ref,\n })\n : undefined,\n };\n }\n\n async addReferences(\n references: readonly AttachmentReferenceInput[],\n ): Promise<void> {\n if (references.length === 0) {\n return;\n }\n\n await this.db\n .insertInto(\"attachment_reference\")\n .values(\n references.map((reference) => ({\n document_id: reference.documentId,\n attachment_ref: reference.ref,\n attachment_hash: parseRef(reference.ref).hash,\n first_operation_id: reference.operationId,\n branch: reference.branch,\n scope: reference.scope,\n first_seen_ordinal: reference.ordinal,\n created_at_utc: new Date().toISOString(),\n })),\n )\n .onConflict((oc) =>\n oc.columns([\"document_id\", \"attachment_ref\"]).doNothing(),\n )\n .execute();\n }\n\n async removeDocuments(documentIds: readonly string[]): Promise<void> {\n if (documentIds.length === 0) {\n return;\n }\n\n await this.db\n .deleteFrom(\"attachment_reference\")\n .where(\"document_id\", \"in\", [...documentIds])\n .execute();\n }\n}\n","import type { Kysely } from \"kysely\";\n\nexport async function up(db: Kysely<any>): Promise<void> {\n await db.schema\n .createTable(\"attachment_reference\")\n .addColumn(\"document_id\", \"text\", (col) => col.notNull())\n .addColumn(\"attachment_ref\", \"text\", (col) => col.notNull())\n .addColumn(\"attachment_hash\", \"text\", (col) => col.notNull())\n .addColumn(\"first_operation_id\", \"text\", (col) => col.notNull())\n .addColumn(\"branch\", \"text\", (col) => col.notNull())\n .addColumn(\"scope\", \"text\", (col) => col.notNull())\n .addColumn(\"first_seen_ordinal\", \"integer\", (col) => col.notNull())\n .addColumn(\"created_at_utc\", \"text\", (col) => col.notNull())\n .addUniqueConstraint(\"unique_attachment_reference_document_ref\", [\n \"document_id\",\n \"attachment_ref\",\n ])\n .execute();\n\n await db.schema\n .createIndex(\"idx_attachment_reference_ref\")\n .on(\"attachment_reference\")\n .column(\"attachment_ref\")\n .execute();\n\n await db.schema\n .createIndex(\"idx_attachment_reference_hash\")\n .on(\"attachment_reference\")\n .column(\"attachment_hash\")\n .execute();\n}\n\nexport async function down(db: Kysely<any>): Promise<void> {\n await db.schema.dropTable(\"attachment_reference\").ifExists().execute();\n}\n","import { Migrator, sql } from \"kysely\";\nimport type { Kysely, MigrationProvider } from \"kysely\";\nimport * as migration001 from \"./001_create_attachment_reference_table.js\";\n\nexport const ATTACHMENT_REFERENCE_SCHEMA = \"attachment_reference_read_model\";\nexport const ATTACHMENT_REFERENCE_MIGRATION_TABLE =\n \"kysely_migration_attachment_reference_read_model\";\nexport const ATTACHMENT_REFERENCE_MIGRATION_LOCK_TABLE =\n \"kysely_migration_attachment_reference_read_model_lock\";\n\nexport interface AttachmentReferenceMigrationResult {\n success: boolean;\n migrationsExecuted: string[];\n error?: Error;\n}\n\nconst migrations = {\n \"001_create_attachment_reference_table\": migration001,\n};\n\nclass ProgrammaticMigrationProvider implements MigrationProvider {\n getMigrations() {\n return Promise.resolve(migrations);\n }\n}\n\nfunction createMigrator(db: Kysely<unknown>, schema: string): Migrator {\n return new Migrator({\n db: db.withSchema(schema),\n provider: new ProgrammaticMigrationProvider(),\n migrationTableSchema: schema,\n migrationTableName: ATTACHMENT_REFERENCE_MIGRATION_TABLE,\n migrationLockTableName: ATTACHMENT_REFERENCE_MIGRATION_LOCK_TABLE,\n });\n}\n\nfunction toResult(\n error: unknown,\n results:\n | Awaited<ReturnType<Migrator[\"migrateToLatest\"]>>[\"results\"]\n | undefined,\n): AttachmentReferenceMigrationResult {\n const migrationsExecuted =\n results?.map((result) => result.migrationName) ?? [];\n if (error) {\n return {\n success: false,\n migrationsExecuted,\n error:\n error instanceof Error ? error : new Error(\"Unknown migration error\"),\n };\n }\n return { success: true, migrationsExecuted };\n}\n\nexport async function runAttachmentReferenceMigrations(\n db: Kysely<unknown>,\n schema: string = ATTACHMENT_REFERENCE_SCHEMA,\n): Promise<AttachmentReferenceMigrationResult> {\n try {\n await sql`CREATE SCHEMA IF NOT EXISTS ${sql.id(schema)}`.execute(db);\n } catch (error) {\n return {\n success: false,\n migrationsExecuted: [],\n error:\n error instanceof Error ? error : new Error(\"Failed to create schema\"),\n };\n }\n\n try {\n const { error, results } = await createMigrator(\n db,\n schema,\n ).migrateToLatest();\n return toResult(error, results);\n } catch (error) {\n return toResult(error, []);\n }\n}\n\nexport async function rollbackAttachmentReferenceMigration(\n db: Kysely<unknown>,\n schema: string = ATTACHMENT_REFERENCE_SCHEMA,\n): Promise<AttachmentReferenceMigrationResult> {\n try {\n const { error, results } = await createMigrator(db, schema).migrateDown();\n return toResult(error, results);\n } catch (error) {\n return toResult(error, []);\n }\n}\n\nexport async function getAttachmentReferenceMigrationStatus(\n db: Kysely<unknown>,\n schema: string = ATTACHMENT_REFERENCE_SCHEMA,\n) {\n return await createMigrator(db, schema).getMigrations();\n}\n","import type { Kysely } from \"kysely\";\nimport { KyselyAttachmentReferenceStore } from \"./kysely-attachment-reference-store.js\";\nimport type { AttachmentReferenceDatabase } from \"./storage/types.js\";\nimport {\n ATTACHMENT_REFERENCE_SCHEMA,\n runAttachmentReferenceMigrations,\n} from \"./storage/migrations/migrator.js\";\nimport type {\n IAttachmentReferenceReader,\n IAttachmentReferenceWriter,\n} from \"./types.js\";\n\nexport type AttachmentReferenceIndexBuildResult = {\n store: IAttachmentReferenceReader & IAttachmentReferenceWriter;\n};\n\nexport class AttachmentReferenceIndexBuilder {\n constructor(private readonly db: Kysely<unknown>) {}\n\n async build(): Promise<AttachmentReferenceIndexBuildResult> {\n const result = await runAttachmentReferenceMigrations(this.db);\n if (!result.success && result.error) {\n throw result.error;\n }\n\n const scopedDb = this.db.withSchema(\n ATTACHMENT_REFERENCE_SCHEMA,\n ) as Kysely<AttachmentReferenceDatabase>;\n const store = new KyselyAttachmentReferenceStore(scopedDb);\n return { store };\n }\n}\n","import {\n BaseReadModel,\n defaultReadModelIndexingConfig,\n type DocumentViewDatabase,\n type IConsistencyTracker,\n type IDocumentModelRegistry,\n type IOperationIndex,\n type IWriteCache,\n} from \"@powerhousedao/reactor\";\nimport {\n isPurgeMarker,\n type OperationWithContext,\n} from \"@powerhousedao/shared/document-model\";\nimport type { Kysely } from \"kysely\";\nimport type { IAttachmentSchemaCompiler } from \"../../reference-index/types.js\";\nimport type {\n AttachmentReferenceInput,\n IAttachmentReferenceWriter,\n} from \"./types.js\";\n\nexport const ATTACHMENT_REFERENCE_READ_MODEL_ID =\n \"attachment-reference-read-model\";\n\n/**\n * Indexes attachment references in chunks.\n *\n * Each reference row stands on its own and is written insert-or-do-nothing, so\n * a batch that commits in pieces exposes no partial structure, and re-indexing\n * the same range writes nothing new: the catch-up sweep needs no stream suffix.\n *\n * The rows live on another handle, so the purge fence is \"skip\": a tombstoned\n * id's operations are dropped at commit and its marker deletes its rows.\n */\nexport class AttachmentReferenceReadModel extends BaseReadModel {\n constructor(\n db: Kysely<DocumentViewDatabase>,\n operationIndex: IOperationIndex,\n writeCache: IWriteCache,\n consistencyTracker: IConsistencyTracker,\n private readonly documentModelRegistry: IDocumentModelRegistry,\n private readonly schemaCompiler: IAttachmentSchemaCompiler,\n private readonly referenceWriter: IAttachmentReferenceWriter,\n ) {\n super(db, operationIndex, writeCache, consistencyTracker, {\n readModelId: ATTACHMENT_REFERENCE_READ_MODEL_ID,\n rebuildStateOnInit: false,\n indexing: defaultReadModelIndexingConfig,\n replayStreamSuffix: false,\n purgeFence: \"skip\",\n });\n }\n\n protected override async commitOperations(\n items: OperationWithContext[],\n ): Promise<void> {\n const references: AttachmentReferenceInput[] = [];\n const purged = new Set<string>();\n\n for (const { operation, context } of items) {\n if (isPurgeMarker(operation)) {\n purged.add(context.documentId);\n continue;\n }\n if (operation.error !== undefined) continue;\n\n const module = this.documentModelRegistry.getModule(context.documentType);\n const extractor = this.schemaCompiler.forModuleAction(\n module,\n operation.action.type,\n );\n const refs = extractor.extract(operation.action);\n\n for (const ref of refs) {\n references.push({\n documentId: context.documentId,\n ref,\n operationId: operation.id,\n branch: context.branch,\n scope: context.scope,\n ordinal: context.ordinal,\n });\n }\n }\n\n if (references.length > 0) {\n await this.referenceWriter.addReferences(references);\n }\n if (purged.size > 0) {\n await this.referenceWriter.removeDocuments([...purged]);\n }\n }\n}\n","export const DEFAULT_S3_ATTACHMENT_PREFIX = \"attachments\";\nexport const DEFAULT_S3_UPLOAD_TTL_SECONDS = 900;\nexport const DEFAULT_S3_DOWNLOAD_TTL_SECONDS = 300;\nexport const MAX_S3_PRESIGN_TTL_SECONDS = 604_800;\n\nexport type S3AttachmentConfig = {\n endpoint: string;\n region: string;\n bucket: string;\n accessKeyId: string;\n secretAccessKey: string;\n prefix: string;\n forcePathStyle: boolean;\n uploadTtlSeconds: number;\n downloadTtlSeconds: number;\n};\n\nexport type AttachmentStorageConfig =\n | { kind: \"filesystem\" }\n | { kind: \"s3\"; s3: S3AttachmentConfig };\n\ntype Environment = Readonly<Record<string, string | undefined>>;\n\nfunction required(env: Environment, name: string): string {\n const value = env[name];\n if (value === undefined || value.trim().length === 0) {\n throw new Error(`${name} is required and must not be blank`);\n }\n if (value.trim() !== value) {\n throw new Error(`${name} must not have leading or trailing whitespace`);\n }\n return value;\n}\n\nconst LOOPBACK_HOSTNAMES = new Set([\"127.0.0.1\", \"localhost\", \"[::1]\"]);\n\n/** Plain HTTP is allowed only for loopback hosts (local S3 emulators). */\nfunction isLoopbackHost(endpoint: URL): boolean {\n return LOOPBACK_HOSTNAMES.has(endpoint.hostname.toLowerCase());\n}\n\nfunction parseEndpoint(value: string): string {\n const message =\n \"PH_ATTACHMENT_S3_ENDPOINT must be a valid HTTPS URL (HTTP is allowed only for loopback hosts)\";\n let endpoint: URL;\n try {\n endpoint = new URL(value);\n } catch {\n throw new Error(message);\n }\n const protocolAllowed =\n endpoint.protocol === \"https:\" ||\n (endpoint.protocol === \"http:\" && isLoopbackHost(endpoint));\n if (\n value.trim() !== value ||\n !protocolAllowed ||\n endpoint.username !== \"\" ||\n endpoint.password !== \"\" ||\n endpoint.search !== \"\" ||\n endpoint.hash !== \"\"\n ) {\n throw new Error(message);\n }\n return endpoint.toString().replace(/\\/$/, \"\");\n}\n\nfunction parseBoolean(\n env: Environment,\n name: string,\n defaultValue: boolean,\n): boolean {\n const value = env[name];\n if (value === undefined) return defaultValue;\n if (value === \"true\") return true;\n if (value === \"false\") return false;\n throw new Error(`${name} must be either true or false`);\n}\n\nfunction parseTtl(\n env: Environment,\n name: string,\n defaultValue: number,\n): number {\n const value = env[name];\n if (value === undefined) return defaultValue;\n if (!/^[1-9]\\d*$/.test(value)) {\n throw new Error(`${name} must be a positive integer`);\n }\n const seconds = Number(value);\n if (!Number.isSafeInteger(seconds) || seconds > MAX_S3_PRESIGN_TTL_SECONDS) {\n throw new Error(\n `${name} must be between 1 and ${MAX_S3_PRESIGN_TTL_SECONDS}`,\n );\n }\n return seconds;\n}\n\nexport function normalizeS3AttachmentPrefix(prefix: string): string {\n if (\n prefix.trim() !== prefix ||\n prefix.startsWith(\"/\") ||\n prefix.includes(\"\\\\\")\n ) {\n throw new Error(\"S3_ATTACHMENT_PREFIX is unsafe\");\n }\n const normalized = prefix.replace(/\\/+$/, \"\");\n if (normalized.length === 0) {\n throw new Error(\"S3_ATTACHMENT_PREFIX must not be blank\");\n }\n const segments = normalized.split(\"/\");\n if (\n segments.some(\n (segment) =>\n segment.length === 0 ||\n segment === \".\" ||\n segment === \"..\" ||\n !/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(segment),\n )\n ) {\n throw new Error(\"S3_ATTACHMENT_PREFIX contains an unsafe segment\");\n }\n return segments.join(\"/\");\n}\n\nexport function parseAttachmentStorageConfig(\n env: Environment = process.env,\n): AttachmentStorageConfig {\n const selector = env.PH_ATTACHMENT_STORAGE;\n if (selector === undefined || selector === \"filesystem\") {\n return { kind: \"filesystem\" };\n }\n if (selector !== \"s3\") {\n throw new Error(\"PH_ATTACHMENT_STORAGE must be either filesystem or s3\");\n }\n\n return {\n kind: \"s3\",\n s3: {\n endpoint: parseEndpoint(required(env, \"PH_ATTACHMENT_S3_ENDPOINT\")),\n region: required(env, \"PH_ATTACHMENT_S3_REGION\"),\n bucket: required(env, \"PH_ATTACHMENT_S3_BUCKET\"),\n accessKeyId: required(env, \"PH_ATTACHMENT_S3_ACCESS_KEY_ID\"),\n secretAccessKey: required(env, \"PH_ATTACHMENT_S3_SECRET_ACCESS_KEY\"),\n prefix: normalizeS3AttachmentPrefix(\n env.S3_ATTACHMENT_PREFIX ?? DEFAULT_S3_ATTACHMENT_PREFIX,\n ),\n forcePathStyle: parseBoolean(\n env,\n \"PH_ATTACHMENT_S3_FORCE_PATH_STYLE\",\n false,\n ),\n uploadTtlSeconds: parseTtl(\n env,\n \"PH_ATTACHMENT_S3_UPLOAD_TTL_SECONDS\",\n DEFAULT_S3_UPLOAD_TTL_SECONDS,\n ),\n downloadTtlSeconds: parseTtl(\n env,\n \"PH_ATTACHMENT_S3_DOWNLOAD_TTL_SECONDS\",\n DEFAULT_S3_DOWNLOAD_TTL_SECONDS,\n ),\n },\n };\n}\n","import { Buffer } from \"node:buffer\";\n\nconst SHA256_HEX = /^[0-9a-f]{64}$/;\n\nfunction validateHash(hash: string): void {\n if (!SHA256_HEX.test(hash)) {\n throw new Error(\n \"Attachment hash must be 64 lowercase hexadecimal characters\",\n );\n }\n}\n\nexport function deriveS3AttachmentKey(hash: string, prefix: string): string {\n validateHash(hash);\n // Imported lazily at the call boundary to keep this primitive's validation\n // identical to configuration parsing without accepting unnormalized input.\n if (\n prefix.startsWith(\"/\") ||\n prefix.endsWith(\"/\") ||\n prefix.includes(\"\\\\\") ||\n prefix\n .split(\"/\")\n .some(\n (segment) =>\n segment.length === 0 ||\n segment === \".\" ||\n segment === \"..\" ||\n !/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(segment),\n )\n ) {\n throw new Error(\"S3 attachment prefix must be normalized and safe\");\n }\n return `${prefix}/${hash.slice(0, 2)}/${hash.slice(2, 4)}/${hash}`;\n}\n\nexport function sha256HexToBase64(hash: string): string {\n validateHash(hash);\n return Buffer.from(hash, \"hex\").toString(\"base64\");\n}\n","import {\n GetObjectCommand,\n HeadObjectCommand,\n PutObjectCommand,\n S3Client,\n} from \"@aws-sdk/client-s3\";\nimport { getSignedUrl } from \"@aws-sdk/s3-request-presigner\";\nimport type {\n AttachmentDownloadTarget,\n AttachmentUploadTarget,\n} from \"../../types.js\";\nimport type { S3AttachmentConfig } from \"./config.js\";\nimport { deriveS3AttachmentKey, sha256HexToBase64 } from \"./keying.js\";\n\nexport interface S3CommandClient {\n send(command: object): Promise<unknown>;\n}\n\nexport type S3Presigner = (\n client: object,\n command: object,\n expiresInSeconds: number,\n) => Promise<string>;\n\ntype Dependencies = {\n client?: S3CommandClient;\n presign?: S3Presigner;\n now?: () => Date;\n};\n\nconst defaultPresigner: S3Presigner = (client, command, expiresInSeconds) =>\n getSignedUrl(client as S3Client, command as never, {\n expiresIn: expiresInSeconds,\n unhoistableHeaders: new Set([\"x-amz-checksum-sha256\"]),\n });\n\nexport class S3AttachmentPrimitives {\n readonly client: S3CommandClient;\n readonly presign: S3Presigner;\n readonly now: () => Date;\n\n constructor(\n readonly config: S3AttachmentConfig,\n dependencies: Dependencies = {},\n ) {\n this.client =\n dependencies.client ??\n new S3Client({\n endpoint: config.endpoint,\n region: config.region,\n forcePathStyle: config.forcePathStyle,\n credentials: {\n accessKeyId: config.accessKeyId,\n secretAccessKey: config.secretAccessKey,\n },\n });\n this.presign = dependencies.presign ?? defaultPresigner;\n this.now = dependencies.now ?? (() => new Date());\n }\n\n buildHeadObjectCommand(hash: string): object {\n return new HeadObjectCommand({\n Bucket: this.config.bucket,\n Key: deriveS3AttachmentKey(hash, this.config.prefix),\n });\n }\n\n buildPutObjectCommand(hash: string, mimeType: string): object {\n if (\n mimeType.trim().length === 0 ||\n mimeType.includes(\"\\r\") ||\n mimeType.includes(\"\\n\")\n ) {\n throw new Error(\n \"Attachment MIME type must not be blank or contain newlines\",\n );\n }\n return new PutObjectCommand({\n Bucket: this.config.bucket,\n Key: deriveS3AttachmentKey(hash, this.config.prefix),\n ContentType: mimeType,\n ChecksumSHA256: sha256HexToBase64(hash),\n });\n }\n\n buildGetObjectCommand(hash: string): object {\n return new GetObjectCommand({\n Bucket: this.config.bucket,\n Key: deriveS3AttachmentKey(hash, this.config.prefix),\n });\n }\n\n headObject(hash: string): Promise<unknown> {\n return this.client.send(this.buildHeadObjectCommand(hash));\n }\n\n async createUploadTarget(\n hash: string,\n mimeType: string,\n ttlSeconds = this.config.uploadTtlSeconds,\n ): Promise<AttachmentUploadTarget> {\n const checksum = sha256HexToBase64(hash);\n const url = await this.presign(\n this.client,\n this.buildPutObjectCommand(hash, mimeType),\n ttlSeconds,\n );\n return {\n kind: \"presigned-put\",\n method: \"PUT\",\n url,\n headers: {\n \"content-type\": mimeType,\n \"x-amz-checksum-sha256\": checksum,\n },\n expiresAtUtc: new Date(\n this.now().getTime() + ttlSeconds * 1_000,\n ).toISOString(),\n };\n }\n\n async createDownloadTarget(\n hash: string,\n ttlSeconds = this.config.downloadTtlSeconds,\n ): Promise<AttachmentDownloadTarget> {\n const url = await this.presign(\n this.client,\n this.buildGetObjectCommand(hash),\n ttlSeconds,\n );\n return {\n kind: \"presigned-get\",\n method: \"GET\",\n url,\n headers: {},\n expiresAtUtc: new Date(\n this.now().getTime() + ttlSeconds * 1_000,\n ).toISOString(),\n };\n }\n}\n\nexport function createS3AttachmentPrimitives(\n config: S3AttachmentConfig,\n dependencies: Dependencies = {},\n): S3AttachmentPrimitives {\n return new S3AttachmentPrimitives(config, dependencies);\n}\n","import type { AttachmentHash } from \"@powerhousedao/reactor\";\nimport type { Kysely } from \"kysely\";\nimport type { IAttachmentBackend } from \"../../interfaces.js\";\nimport type {\n AttachmentBackendHealth,\n AttachmentDownloadTarget,\n AttachmentUploadTarget,\n Reservation,\n} from \"../../types.js\";\nimport type { AttachmentDatabase } from \"../kysely/types.js\";\nimport type { S3AttachmentConfig } from \"./config.js\";\nimport { deriveS3AttachmentKey } from \"./keying.js\";\nimport {\n S3AttachmentPrimitives,\n type S3CommandClient,\n type S3Presigner,\n} from \"./primitives.js\";\n\nconst READINESS_PROBE_HASH = \"0\".repeat(64);\nconst OBJECT_NOT_FOUND_NAMES = new Set([\n \"NotFound\",\n \"NoSuchKey\",\n \"NoSuchObject\",\n]);\n\ntype ProviderError = {\n name?: unknown;\n code?: unknown;\n $metadata?: { httpStatusCode?: unknown };\n};\n\nexport type S3AttachmentBackendDependencies = {\n client?: S3CommandClient;\n presign?: S3Presigner;\n now?: () => Date;\n uploadTtlSeconds?: number;\n downloadTtlSeconds?: number;\n};\n\nfunction isObjectNotFound(error: unknown): boolean {\n if (typeof error !== \"object\" || error === null) return false;\n const providerError = error as ProviderError;\n if (providerError.$metadata?.httpStatusCode !== 404) return false;\n return [providerError.name, providerError.code].some(\n (code) => typeof code === \"string\" && OBJECT_NOT_FOUND_NAMES.has(code),\n );\n}\n\nfunction requireHashFirstReservation(\n reservation: Reservation,\n): asserts reservation is Reservation & {\n clientHash: AttachmentHash;\n sizeBytes: number;\n} {\n if (reservation.clientHash === null) {\n throw new Error(\"S3 attachment reservations require a client hash\");\n }\n deriveS3AttachmentKey(reservation.clientHash, \"validation\");\n // A zero-byte object is a valid S3 object; an empty file is stored as one.\n if (\n reservation.sizeBytes === null ||\n !Number.isSafeInteger(reservation.sizeBytes) ||\n reservation.sizeBytes < 0\n ) {\n throw new Error(\n \"S3 attachment reservation sizeBytes must be a non-negative safe integer\",\n );\n }\n}\n\n/** Server-only S3 capability. Callers complete authorization before download. */\nexport class S3AttachmentBackend implements IAttachmentBackend {\n readonly kind = \"s3\" as const;\n private readonly primitives: S3AttachmentPrimitives;\n private readonly now: () => Date;\n private readonly uploadTtlSeconds: number;\n private readonly downloadTtlSeconds: number;\n\n constructor(\n private readonly db: Kysely<AttachmentDatabase>,\n readonly config: S3AttachmentConfig,\n dependencies: S3AttachmentBackendDependencies = {},\n ) {\n this.primitives = new S3AttachmentPrimitives(config, dependencies);\n this.now = dependencies.now ?? (() => new Date());\n this.uploadTtlSeconds =\n dependencies.uploadTtlSeconds ?? config.uploadTtlSeconds;\n this.downloadTtlSeconds =\n dependencies.downloadTtlSeconds ?? config.downloadTtlSeconds;\n }\n\n async prepareUploadTarget(\n reservation: Reservation,\n ): Promise<AttachmentUploadTarget> {\n requireHashFirstReservation(reservation);\n const hash = reservation.clientHash;\n const now = this.now().toISOString();\n const storagePath = deriveS3AttachmentKey(hash, this.config.prefix);\n\n try {\n await this.db\n .insertInto(\"attachment\")\n .values({\n hash,\n mime_type: reservation.mimeType,\n file_name: reservation.fileName,\n size_bytes: reservation.sizeBytes,\n extension: reservation.extension,\n status: \"available\",\n storage_path: storagePath,\n source: \"local\",\n created_at_utc: reservation.createdAtUtc,\n last_accessed_at_utc: now,\n })\n .onConflict((conflict) =>\n conflict.column(\"hash\").doUpdateSet({\n mime_type: reservation.mimeType,\n file_name: reservation.fileName,\n size_bytes: reservation.sizeBytes,\n extension: reservation.extension,\n status: \"available\",\n storage_path: storagePath,\n last_accessed_at_utc: now,\n }),\n )\n .execute();\n } catch {\n throw new Error(\"S3 attachment metadata registration failed\");\n }\n\n let target: AttachmentUploadTarget;\n try {\n target = await this.primitives.createUploadTarget(\n hash,\n reservation.mimeType,\n this.uploadTtlSeconds,\n );\n } catch {\n throw new Error(\"S3 attachment upload target preparation failed\");\n }\n\n // Direct S3 completion is invisible to Switchboard; the existing sweep\n // expires this reservation normally.\n return target;\n }\n\n async prepareDownloadTarget(\n hash: AttachmentHash,\n ttlSeconds?: number,\n ): Promise<AttachmentDownloadTarget> {\n try {\n return await this.primitives.createDownloadTarget(\n hash,\n ttlSeconds ?? this.downloadTtlSeconds,\n );\n } catch {\n throw new Error(\"S3 attachment download target preparation failed\");\n }\n }\n\n async exists(hash: AttachmentHash): Promise<boolean> {\n const metadata = await this.db\n .selectFrom(\"attachment\")\n .select(\"hash\")\n .where(\"hash\", \"=\", hash)\n .executeTakeFirst();\n if (!metadata) return false;\n\n try {\n await this.primitives.headObject(hash);\n return true;\n } catch (error) {\n if (isObjectNotFound(error)) return false;\n // Provider errors may contain endpoints or signed request details, so the\n // raw cause intentionally must not cross this backend boundary.\n // eslint-disable-next-line preserve-caught-error\n throw new Error(\"S3 attachment existence check failed\");\n }\n }\n\n async health(): Promise<AttachmentBackendHealth> {\n try {\n await this.primitives.headObject(READINESS_PROBE_HASH);\n return { kind: this.kind, ready: true };\n } catch (error) {\n return {\n kind: this.kind,\n ready: isObjectNotFound(error),\n };\n }\n }\n}\n\nexport function createS3AttachmentBackend(\n db: Kysely<AttachmentDatabase>,\n config: S3AttachmentConfig,\n dependencies: S3AttachmentBackendDependencies = {},\n): S3AttachmentBackend {\n return new S3AttachmentBackend(db, config, dependencies);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAGA,MAAM,gBAAgB;AAItB,MAAM,mBAAmB;AAEzB,MAAM,oBACJ;AACF,MAAM,mBAAmB;AACzB,MAAM,mBAAmB;;;;;;;AAezB,SAAgB,wBAAwB,MAA6B;CACnE,MAAM,EAAE,UAAU,UAAU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ENAMED
|
@@ -137,7 +137,7 @@ var AttachmentService = class {
|
|
|
137
137
|
async reserveHashFirst(options) {
|
|
138
138
|
const normalized = options.clientHash.toLowerCase();
|
|
139
139
|
if (!CLIENT_HASH_PATTERN.test(normalized)) throw new Error(`clientHash must be a 64-character lowercase hex string, got: ${options.clientHash}`);
|
|
140
|
-
if (options.sizeBytes === void 0 || !Number.
|
|
140
|
+
if (options.sizeBytes === void 0 || !Number.isSafeInteger(options.sizeBytes) || options.sizeBytes < 0) throw new Error("sizeBytes must be a non-negative safe integer when clientHash is provided");
|
|
141
141
|
const normalizedOptions = {
|
|
142
142
|
...options,
|
|
143
143
|
clientHash: normalized
|
|
@@ -771,4 +771,4 @@ var NullAttachmentTransport = class {
|
|
|
771
771
|
//#endregion
|
|
772
772
|
export { RemoteAttachmentUpload as a, createFetchUploadTransport as c, parseAttachmentDownloadTarget as d, parseAttachmentUploadTarget as f, RemoteAttachmentUploadFactory as i, isBlob as l, createRemoteAttachmentService as n, RemoteReservationStore as o, RemoteAttachmentStore as r, createXhrUploadTransport as s, NullAttachmentTransport as t, AttachmentService as u };
|
|
773
773
|
|
|
774
|
-
//# sourceMappingURL=null-attachment-transport-
|
|
774
|
+
//# sourceMappingURL=null-attachment-transport-BMa3MUA2.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"null-attachment-transport-BMa3MUA2.js","names":["isRecord","isRecord","isRecord"],"sources":["../src/targets.ts","../src/attachment-service.ts","../src/blob.ts","../src/switchboard/upload-transport.ts","../src/switchboard/xhr-upload-transport.ts","../src/switchboard/remote-reservation-store.ts","../src/switchboard/remote-attachment-upload.ts","../src/switchboard/remote-attachment-upload-factory.ts","../src/switchboard/remote-attachment-store.ts","../src/switchboard/create-remote-attachment-service.ts","../src/null-attachment-transport.ts"],"sourcesContent":["import type {\n AttachmentDownloadTarget,\n AttachmentTargetHeaders,\n AttachmentUploadTarget,\n} from \"./types.js\";\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction parseUrl(value: unknown): string {\n if (typeof value !== \"string\" || value.length === 0) {\n throw new Error(\"Attachment target URL must be a non-empty string\");\n }\n if (value.trim() !== value || hasForbiddenUrlWhitespace(value)) {\n throw new Error(\"Attachment target URL must not contain raw whitespace\");\n }\n let parsed: URL;\n try {\n parsed = new URL(value);\n } catch {\n throw new Error(\"Attachment target URL is invalid\");\n }\n if (\n (parsed.protocol !== \"http:\" && parsed.protocol !== \"https:\") ||\n parsed.username !== \"\" ||\n parsed.password !== \"\"\n ) {\n throw new Error(\n \"Attachment target URL must be HTTP(S) and must not contain credentials\",\n );\n }\n // Return the original string: presigned URLs are opaque and must never be\n // normalized, decoded, reordered, or otherwise reconstructed.\n return value;\n}\n\nfunction parseHeaders(value: unknown): AttachmentTargetHeaders {\n if (!isRecord(value)) {\n throw new Error(\"Attachment target headers must be an object\");\n }\n // A null prototype preserves valid names such as `__proto__` as ordinary\n // own properties instead of invoking Object.prototype setters.\n const headers = Object.create(null) as Record<string, string>;\n const headerName = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;\n for (const [name, headerValue] of Object.entries(value)) {\n if (!headerName.test(name)) {\n throw new Error(`Attachment target header name is invalid: ${name}`);\n }\n if (\n typeof headerValue !== \"string\" ||\n hasForbiddenHeaderCharacter(headerValue)\n ) {\n throw new Error(`Attachment target header value is invalid: ${name}`);\n }\n headers[name] = headerValue;\n }\n return headers;\n}\n\nfunction hasForbiddenHeaderCharacter(value: string): boolean {\n for (let index = 0; index < value.length; index++) {\n const code = value.charCodeAt(index);\n // Horizontal tab is valid field whitespace. Other C0 controls, DEL, and\n // especially CR/LF are forbidden to prevent header injection.\n if (code <= 8 || (code >= 10 && code <= 31) || code === 127 || code > 255) {\n return true;\n }\n }\n return false;\n}\n\nfunction hasForbiddenUrlWhitespace(value: string): boolean {\n for (let index = 0; index < value.length; index++) {\n const code = value.charCodeAt(index);\n // URL parsing may silently trim or percent-encode raw ASCII whitespace.\n // Reject it so the validated opaque string is exactly what Fetch receives.\n if (code <= 32 || code === 127) return true;\n }\n return false;\n}\n\nfunction parseExpiry(value: unknown, required: boolean): string | undefined {\n if (value === undefined && !required) return undefined;\n if (typeof value !== \"string\") {\n throw new Error(\"Attachment target expiry must be an ISO 8601 UTC string\");\n }\n const parsed = new Date(value);\n if (Number.isNaN(parsed.getTime()) || parsed.toISOString() !== value) {\n throw new Error(\"Attachment target expiry must be an ISO 8601 UTC string\");\n }\n return value;\n}\n\nexport function parseAttachmentUploadTarget(\n value: unknown,\n): AttachmentUploadTarget {\n if (!isRecord(value)) {\n throw new Error(\"Attachment upload target must be an object\");\n }\n const url = parseUrl(value.url);\n const headers = parseHeaders(value.headers);\n switch (value.kind) {\n case \"switchboard\":\n if (value.method !== \"PUT\") {\n throw new Error(\"Switchboard upload target method must be PUT\");\n }\n return {\n kind: \"switchboard\",\n method: \"PUT\",\n url,\n headers,\n ...(value.expiresAtUtc === undefined\n ? {}\n : { expiresAtUtc: parseExpiry(value.expiresAtUtc, false) }),\n };\n case \"presigned-put\":\n if (value.method !== \"PUT\") {\n throw new Error(\"Presigned upload target method must be PUT\");\n }\n return {\n kind: \"presigned-put\",\n method: \"PUT\",\n url,\n headers,\n expiresAtUtc: parseExpiry(value.expiresAtUtc, true)!,\n };\n default:\n throw new Error(\"Attachment upload target kind is unknown\");\n }\n}\n\nexport function parseAttachmentDownloadTarget(\n value: unknown,\n): AttachmentDownloadTarget {\n if (!isRecord(value)) {\n throw new Error(\"Attachment download target must be an object\");\n }\n const url = parseUrl(value.url);\n const headers = parseHeaders(value.headers);\n switch (value.kind) {\n case \"switchboard\":\n if (value.method !== \"GET\") {\n throw new Error(\"Switchboard download target method must be GET\");\n }\n return {\n kind: \"switchboard\",\n method: \"GET\",\n url,\n headers,\n ...(value.expiresAtUtc === undefined\n ? {}\n : { expiresAtUtc: parseExpiry(value.expiresAtUtc, false) }),\n };\n case \"presigned-get\":\n if (value.method !== \"GET\") {\n throw new Error(\"Presigned download target method must be GET\");\n }\n return {\n kind: \"presigned-get\",\n method: \"GET\",\n url,\n headers,\n expiresAtUtc: parseExpiry(value.expiresAtUtc, true)!,\n };\n default:\n throw new Error(\"Attachment download target kind is unknown\");\n }\n}\n","import type { AttachmentHash, AttachmentRef } from \"@powerhousedao/reactor\";\nimport {\n AttachmentAlreadyExists,\n AttachmentNotFound,\n AttachmentPending,\n} from \"./errors.js\";\nimport type {\n IAttachmentReader,\n IAttachmentBackend,\n IAttachmentService,\n IAttachmentUpload,\n IAttachmentUploadFactory,\n IReservationStore,\n} from \"./interfaces.js\";\nimport { createRef, parseRef } from \"./ref.js\";\nimport type {\n AttachmentDownloadOptions,\n AttachmentDownloadTarget,\n AttachmentDownloadTargetOptions,\n AttachmentHeader,\n AttachmentResponse,\n AttachmentStatOptions,\n ReserveAttachmentOptions,\n} from \"./types.js\";\n\nconst CLIENT_HASH_PATTERN = /^[a-f0-9]{64}$/;\n\nexport class AttachmentService implements IAttachmentService {\n constructor(\n private readonly store: IAttachmentReader,\n private readonly reservations: IReservationStore,\n private readonly uploadFactory: IAttachmentUploadFactory,\n private readonly backend?: IAttachmentBackend,\n ) {}\n\n async reserve(options: ReserveAttachmentOptions): Promise<IAttachmentUpload> {\n if (options.clientHash !== undefined) {\n return this.reserveHashFirst(options);\n }\n if (this.backend?.kind === \"s3\") {\n throw new Error(\"S3 attachment reservations require a client hash\");\n }\n const reservation = await this.reservations.create(options);\n return this.uploadFactory.createUpload(reservation);\n }\n\n async stat(\n ref: AttachmentRef,\n options?: AttachmentStatOptions,\n ): Promise<AttachmentHeader> {\n const { hash } = parseRef(ref);\n return options?.documentId === undefined\n ? this.store.stat(hash)\n : this.store.stat(hash, options.documentId);\n }\n\n async get(\n ref: AttachmentRef,\n options?: AbortSignal | AttachmentDownloadOptions,\n ): Promise<AttachmentResponse> {\n const { hash } = parseRef(ref);\n const normalized =\n options === undefined || options instanceof AbortSignal\n ? { signal: options }\n : options;\n return normalized.documentId === undefined\n ? this.store.get(hash, normalized.signal)\n : this.store.get(hash, normalized.signal, normalized.documentId);\n }\n\n getDownloadTarget(\n ref: AttachmentRef,\n options: AttachmentDownloadTargetOptions,\n ): Promise<AttachmentDownloadTarget> {\n const { hash } = parseRef(ref);\n const getTarget = this.store.getDownloadTarget?.bind(this.store);\n if (getTarget === undefined) {\n return Promise.reject(\n new Error(\n \"Download targets are not supported by this attachment store: only remote stores negotiate direct URLs\",\n ),\n );\n }\n return getTarget(hash, options);\n }\n\n private async reserveHashFirst(\n options: ReserveAttachmentOptions,\n ): Promise<IAttachmentUpload> {\n const normalized = options.clientHash!.toLowerCase() as AttachmentHash;\n if (!CLIENT_HASH_PATTERN.test(normalized)) {\n throw new Error(\n `clientHash must be a 64-character lowercase hex string, got: ${options.clientHash}`,\n );\n }\n // Zero is a real size: an empty file has a well-defined hash (the hash of\n // no bytes) and is stored like any other. Mail carries them, and refusing\n // one failed the whole step that tried to ingest the message.\n if (\n options.sizeBytes === undefined ||\n !Number.isSafeInteger(options.sizeBytes) ||\n options.sizeBytes < 0\n ) {\n throw new Error(\n \"sizeBytes must be a non-negative safe integer when clientHash is provided\",\n );\n }\n\n const normalizedOptions: ReserveAttachmentOptions = {\n ...options,\n clientHash: normalized,\n };\n\n let existingHeader: AttachmentHeader | null = null;\n try {\n existingHeader = await this.store.stat(normalized);\n } catch (err) {\n if (\n !(err instanceof AttachmentNotFound) &&\n !(err instanceof AttachmentPending)\n ) {\n throw err;\n }\n }\n\n if (existingHeader !== null) {\n if (this.backend?.kind === \"s3\") {\n if (await this.backend.exists(normalized)) {\n throw new AttachmentAlreadyExists(normalized, createRef(normalized));\n }\n } else if (existingHeader.status === \"available\") {\n throw new AttachmentAlreadyExists(normalized, createRef(normalized));\n }\n }\n\n const reservation = await this.reservations.create(normalizedOptions);\n if (this.backend?.kind !== \"s3\") {\n return this.uploadFactory.createUpload(reservation);\n }\n const uploadTarget = await this.backend.prepareUploadTarget(reservation);\n return this.uploadFactory.createUpload({ ...reservation, uploadTarget });\n }\n}\n","/** Tells a Blob from a stream by shape: `instanceof Blob` misses other realms and polyfills. */\nexport function isBlob(data: ReadableStream<Uint8Array> | Blob): data is Blob {\n return !(\"getReader\" in data);\n}\n","/**\n * The seam every attachment upload PUT goes through.\n *\n * It exists because `fetch` cannot report upload-side progress: there is no\n * event between \"request issued\" and \"response received\". Naming the transport\n * lets an implementation that *can* count bytes (see\n * `createXhrUploadTransport`) be substituted without the upload code knowing\n * which one it holds — and it is also the right seam for a future multipart\n * upload, which needs one request per part.\n */\n\n/**\n * Headers are forwarded VERBATIM. A presigned target's headers are part of a\n * signature: normalizing their casing, or adding so much as one header,\n * invalidates it.\n */\nexport type AttachmentUploadRequest = {\n url: string;\n method: \"PUT\";\n headers: Record<string, string>;\n body: Blob;\n /** Called with cumulative bytes handed to the socket, when observable. */\n onProgress?: (loaded: number, total: number) => void;\n signal?: AbortSignal;\n};\n\n/**\n * The only response surface the upload code reads. A real `Response`\n * satisfies this structurally, which is what lets the fetch transport be an\n * identity pass-through rather than an adapter.\n */\nexport type AttachmentUploadResponse = {\n readonly status: number;\n readonly statusText: string;\n readonly ok: boolean;\n json(): Promise<unknown>;\n};\n\nexport type AttachmentUploadTransport = (\n request: AttachmentUploadRequest,\n) => Promise<AttachmentUploadResponse>;\n\n/**\n * The default transport. Ignores `onProgress` — fetch has no upload-side\n * progress event, and silence is how a transport reports that bytes are\n * unobservable.\n */\nexport function createFetchUploadTransport(\n fetchFn: typeof fetch,\n): AttachmentUploadTransport {\n return (request) =>\n fetchFn(request.url, {\n method: request.method,\n headers: request.headers,\n body: request.body,\n ...(request.signal ? { signal: request.signal } : {}),\n });\n}\n","import {\n createFetchUploadTransport,\n type AttachmentUploadRequest,\n type AttachmentUploadResponse,\n type AttachmentUploadTransport,\n} from \"./upload-transport.js\";\n\nexport type XhrUploadTransportOptions = {\n /**\n * Used where `XMLHttpRequest` does not exist (Node). Defaults to the global\n * fetch, resolved at call time.\n */\n fetchFn?: typeof fetch;\n};\n\n/**\n * Upload transport backed by `XMLHttpRequest`, the only browser API that\n * reports upload-side byte progress (`xhr.upload.onprogress`). Everything else\n * about the request is identical to the fetch path.\n *\n * Capability detection happens **inside** the returned function, never at\n * module load: this module is reachable from the client entry, which is\n * executed in Node by the entrypoint tests, and Node has no\n * `XMLHttpRequest`. Detecting per call also means a test can install a fake on\n * `globalThis` without any module-registry reset.\n */\nexport function createXhrUploadTransport(\n options?: XhrUploadTransportOptions,\n): AttachmentUploadTransport {\n return (request) => {\n const XhrCtor = globalThis.XMLHttpRequest;\n if (typeof XhrCtor !== \"function\") {\n const fetchFn = options?.fetchFn ?? globalThis.fetch;\n return createFetchUploadTransport(fetchFn.bind(globalThis))(request);\n }\n return sendWithXhr(new XhrCtor(), request);\n };\n}\n\n/**\n * Mirrors fetch's observable behavior closely enough that\n * `RemoteAttachmentUpload` cannot tell the two apart:\n *\n * - `responseType` is left at `\"\"`, so a non-JSON 422 body still reaches the\n * caller's `json()` and fails there rather than being swallowed.\n * - status 0 never resolves. XHR reports 0 for network failure, CORS refusal\n * and abort alike; resolving it would fabricate a transfer error claiming\n * the provider answered 0.\n * - failures reject with fetch's error shapes: `TypeError` for network,\n * `AbortError` for abort.\n */\nfunction sendWithXhr(\n xhr: XMLHttpRequest,\n request: AttachmentUploadRequest,\n): Promise<AttachmentUploadResponse> {\n return new Promise<AttachmentUploadResponse>((resolve, reject) => {\n const signal = request.signal;\n let settled = false;\n\n const abortListener = () => xhr.abort();\n const detach = () => signal?.removeEventListener(\"abort\", abortListener);\n const succeed = (response: AttachmentUploadResponse) => {\n if (settled) return;\n settled = true;\n detach();\n resolve(response);\n };\n const fail = (error: Error) => {\n if (settled) return;\n settled = true;\n detach();\n reject(error);\n };\n\n if (signal?.aborted) {\n fail(abortError());\n return;\n }\n\n xhr.open(request.method, request.url, true);\n // Verbatim: a presigned target's headers are part of its signature.\n for (const [name, value] of Object.entries(request.headers)) {\n xhr.setRequestHeader(name, value);\n }\n\n // Attached before send(), and only when a caller is listening — merely\n // registering an upload listener forces a CORS preflight.\n if (request.onProgress) {\n xhr.upload.addEventListener(\"progress\", (event: ProgressEvent) => {\n if (!event.lengthComputable) return;\n request.onProgress?.(event.loaded, event.total);\n });\n }\n\n xhr.addEventListener(\"load\", () => {\n if (xhr.status === 0) {\n fail(networkError());\n return;\n }\n succeed(toResponse(xhr));\n });\n xhr.addEventListener(\"error\", () => fail(networkError()));\n xhr.addEventListener(\"timeout\", () => fail(networkError()));\n xhr.addEventListener(\"abort\", () => fail(abortError()));\n\n signal?.addEventListener(\"abort\", abortListener);\n xhr.send(request.body);\n });\n}\n\nfunction toResponse(xhr: XMLHttpRequest): AttachmentUploadResponse {\n return {\n status: xhr.status,\n statusText: xhr.statusText,\n ok: xhr.status >= 200 && xhr.status < 300,\n json: () => {\n try {\n return Promise.resolve(JSON.parse(xhr.responseText));\n } catch (err) {\n return Promise.reject(\n err instanceof Error ? err : new Error(String(err)),\n );\n }\n },\n };\n}\n\nfunction networkError(): TypeError {\n return new TypeError(\"Failed to fetch\");\n}\n\nfunction abortError(): DOMException {\n return new DOMException(\"The operation was aborted\", \"AbortError\");\n}\n","import type { AttachmentRef, JwtHandler } from \"@powerhousedao/reactor\";\nimport { AttachmentAlreadyExists, ReservationNotFound } from \"../errors.js\";\nimport type { IReservationStore } from \"../interfaces.js\";\nimport { createRef, parseRef } from \"../ref.js\";\nimport type { Reservation, ReserveAttachmentOptions } from \"../types.js\";\nimport { parseAttachmentUploadTarget } from \"../targets.js\";\nimport { buildAuthHeaders } from \"./build-auth-headers.js\";\nimport type { AttachmentUploadTransport } from \"./upload-transport.js\";\n\nexport type SwitchboardClientConfig = {\n remoteUrl: string;\n jwtHandler?: JwtHandler;\n fetchFn?: typeof fetch;\n /**\n * Transport for upload PUTs only, so a browser host can opt into\n * XMLHttpRequest and get real upload progress.\n *\n * An explicit `fetchFn` always wins over this. The precedence is\n * one-directional on purpose: under this rule, adding `uploadTransport` to a\n * config that already pins `fetchFn` is a provable no-op, whereas the\n * reverse rule would let `{ ...config, uploadTransport }` silently route the\n * largest request in the system around a test's mock and onto the network.\n */\n uploadTransport?: AttachmentUploadTransport;\n};\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction deriveExtension(fileName: string): string | null {\n const idx = fileName.lastIndexOf(\".\");\n if (idx <= 0 || idx === fileName.length - 1) return null;\n return fileName.slice(idx + 1).toLowerCase();\n}\n\nfunction isReservationBase(value: unknown): value is Record<string, unknown> & {\n reservationId: string;\n mimeType: string;\n fileName: string;\n extension: string | null;\n createdAtUtc: string;\n expiresAtUtc: string;\n} {\n if (!isRecord(value)) return false;\n if (typeof value.reservationId !== \"string\") return false;\n if (typeof value.mimeType !== \"string\") return false;\n if (typeof value.fileName !== \"string\") return false;\n if (value.extension !== null && typeof value.extension !== \"string\") {\n return false;\n }\n if (typeof value.createdAtUtc !== \"string\") return false;\n if (typeof value.expiresAtUtc !== \"string\") return false;\n return true;\n}\n\nfunction isReservation(value: unknown): value is Reservation {\n if (!isReservationBase(value)) return false;\n // clientHash and sizeBytes may be absent on responses from older\n // switchboards; treat missing as null (normalized below in get()).\n if (\n value.clientHash !== undefined &&\n value.clientHash !== null &&\n typeof value.clientHash !== \"string\"\n ) {\n return false;\n }\n if (\n value.sizeBytes !== undefined &&\n value.sizeBytes !== null &&\n typeof value.sizeBytes !== \"number\"\n ) {\n return false;\n }\n return true;\n}\n\nexport class RemoteReservationStore implements IReservationStore {\n private readonly remoteUrl: string;\n private readonly jwtHandler?: JwtHandler;\n private readonly fetchFn: typeof fetch;\n\n constructor(config: SwitchboardClientConfig) {\n this.remoteUrl = config.remoteUrl;\n this.jwtHandler = config.jwtHandler;\n this.fetchFn = (config.fetchFn ?? globalThis.fetch).bind(globalThis);\n }\n\n async create(options: ReserveAttachmentOptions): Promise<Reservation> {\n const url = `${this.remoteUrl}/attachments/reservations`;\n const authHeaders = await buildAuthHeaders(url, this.jwtHandler);\n const extension = options.extension ?? deriveExtension(options.fileName);\n\n const bodyObj: Record<string, unknown> = {\n mimeType: options.mimeType,\n fileName: options.fileName,\n extension,\n };\n if (options.clientHash !== undefined) {\n bodyObj.clientHash = options.clientHash;\n }\n if (options.sizeBytes !== undefined) {\n bodyObj.sizeBytes = options.sizeBytes;\n }\n\n const response = await this.fetchFn(url, {\n method: \"POST\",\n headers: { ...authHeaders, \"Content-Type\": \"application/json\" },\n body: JSON.stringify(bodyObj),\n });\n\n if (response.status === 409) {\n let body: unknown;\n try {\n body = await response.json();\n } catch {\n throw new Error(\n `Reservation create failed: ${response.status} ${response.statusText}`,\n );\n }\n if (\n isRecord(body) &&\n body.error === \"already_exists\" &&\n options.clientHash !== undefined\n ) {\n let ref: AttachmentRef;\n if (typeof body.ref === \"string\") {\n try {\n parseRef(body.ref as AttachmentRef);\n ref = body.ref as AttachmentRef;\n } catch {\n ref = createRef(options.clientHash);\n }\n } else {\n ref = createRef(options.clientHash);\n }\n throw new AttachmentAlreadyExists(options.clientHash, ref);\n }\n throw new Error(\n `Reservation create failed: ${response.status} ${response.statusText}`,\n );\n }\n\n if (!response.ok) {\n throw new Error(\n `Reservation create failed: ${response.status} ${response.statusText}`,\n );\n }\n\n let json: unknown;\n try {\n json = await response.json();\n } catch {\n throw new Error(\"Reservation create returned non-JSON response\");\n }\n if (\n typeof json !== \"object\" ||\n json === null ||\n typeof (json as Record<string, unknown>).reservationId !== \"string\" ||\n ((json as Record<string, unknown>).reservationId as string).length === 0\n ) {\n throw new Error(\n \"Reservation create returned a payload missing a non-empty reservationId string\",\n );\n }\n const body = json as {\n reservationId: string;\n ref?: string | null;\n createdAtUtc?: string;\n expiresAtUtc?: string;\n uploadTarget?: unknown;\n };\n // The server is the source of truth for both timestamps. We synthesize\n // only as a last-resort fallback for older switchboards that don't\n // include them in the response; in that case the client cannot know the\n // server's TTL, so expiresAtUtc is a best-effort placeholder.\n const now = new Date();\n return {\n reservationId: body.reservationId,\n mimeType: options.mimeType,\n fileName: options.fileName,\n extension,\n createdAtUtc: body.createdAtUtc ?? now.toISOString(),\n expiresAtUtc:\n body.expiresAtUtc ??\n new Date(now.getTime() + 24 * 60 * 60 * 1000).toISOString(),\n clientHash: options.clientHash ?? null,\n sizeBytes: options.sizeBytes ?? null,\n ...(body.uploadTarget === undefined\n ? {}\n : { uploadTarget: parseAttachmentUploadTarget(body.uploadTarget) }),\n };\n }\n\n async get(reservationId: string): Promise<Reservation> {\n const url = `${this.remoteUrl}/attachments/reservations/${encodeURIComponent(reservationId)}`;\n const authHeaders = await buildAuthHeaders(url, this.jwtHandler);\n\n const response = await this.fetchFn(url, { headers: authHeaders });\n\n if (response.status === 404) {\n throw new ReservationNotFound(reservationId);\n }\n if (!response.ok) {\n throw new Error(\n `Reservation get failed: ${response.status} ${response.statusText}`,\n );\n }\n\n let parsed: unknown;\n try {\n parsed = await response.json();\n } catch {\n throw new Error(\"Reservation get returned non-JSON response\");\n }\n if (!isReservation(parsed)) {\n throw new Error(\n \"Reservation get returned a payload that does not match the Reservation shape\",\n );\n }\n return {\n reservationId: parsed.reservationId,\n mimeType: parsed.mimeType,\n fileName: parsed.fileName,\n extension: parsed.extension,\n createdAtUtc: parsed.createdAtUtc,\n expiresAtUtc: parsed.expiresAtUtc,\n // Normalize fields that may be absent on older switchboard responses.\n clientHash: parsed.clientHash ?? null,\n sizeBytes: parsed.sizeBytes ?? null,\n ...(parsed.uploadTarget === undefined\n ? {}\n : {\n uploadTarget: parseAttachmentUploadTarget(parsed.uploadTarget),\n }),\n };\n }\n\n async delete(reservationId: string): Promise<void> {\n const url = `${this.remoteUrl}/attachments/reservations/${encodeURIComponent(reservationId)}`;\n const authHeaders = await buildAuthHeaders(url, this.jwtHandler);\n\n const response = await this.fetchFn(url, {\n method: \"DELETE\",\n headers: authHeaders,\n });\n\n // 2xx = success; 404 / 410 = already gone, treat as idempotent success.\n if (!response.ok && response.status !== 404 && response.status !== 410) {\n throw new Error(\n `Reservation delete failed: ${response.status} ${response.statusText}`,\n );\n }\n }\n\n // Sweeping is the server's responsibility; clients have no authority to\n // delete reservations on a remote switchboard.\n deleteExpired(): Promise<number> {\n return Promise.reject(\n new Error(\"RemoteReservationStore.deleteExpired is not supported\"),\n );\n }\n}\n","import type {\n AttachmentHash,\n AttachmentRef,\n JwtHandler,\n} from \"@powerhousedao/reactor\";\nimport {\n AttachmentTransferError,\n HashMismatch,\n SizeMismatch,\n} from \"../errors.js\";\nimport type { IAttachmentUpload } from \"../interfaces.js\";\nimport { createRef } from \"../ref.js\";\nimport type {\n AttachmentSendOptions,\n AttachmentUploadResult,\n AttachmentUploadTarget,\n Reservation,\n} from \"../types.js\";\nimport { buildAuthHeaders } from \"./build-auth-headers.js\";\nimport type { SwitchboardClientConfig } from \"./remote-reservation-store.js\";\nimport {\n createFetchUploadTransport,\n type AttachmentUploadTransport,\n} from \"./upload-transport.js\";\nimport { isBlob } from \"../blob.js\";\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/**\n * A Blob goes out untouched, so a File streams from disk. A stream is\n * buffered: browsers don't portably accept a ReadableStream request body.\n */\nasync function toBody(data: ReadableStream<Uint8Array> | Blob): Promise<Blob> {\n return isBlob(data) ? data : new Response(data).blob();\n}\n\nexport class RemoteAttachmentUpload implements IAttachmentUpload {\n readonly reservationId: string;\n readonly ref: AttachmentRef | null;\n readonly expiresAtUtc: string;\n readonly uploadTarget?: AttachmentUploadTarget;\n private readonly reservation: Reservation;\n private readonly remoteUrl: string;\n private readonly jwtHandler?: JwtHandler;\n private readonly uploadTransport: AttachmentUploadTransport;\n\n constructor(reservation: Reservation, config: SwitchboardClientConfig) {\n this.reservationId = reservation.reservationId;\n this.ref =\n reservation.clientHash !== null\n ? createRef(reservation.clientHash)\n : null;\n this.expiresAtUtc = reservation.expiresAtUtc;\n if (reservation.uploadTarget) {\n this.uploadTarget = reservation.uploadTarget;\n }\n this.reservation = reservation;\n this.remoteUrl = config.remoteUrl;\n this.jwtHandler = config.jwtHandler;\n // fetchFn wins: pinning fetch must not be silently overridden.\n this.uploadTransport = config.fetchFn\n ? createFetchUploadTransport(config.fetchFn.bind(globalThis))\n : (config.uploadTransport ??\n createFetchUploadTransport(globalThis.fetch.bind(globalThis)));\n }\n\n async send(\n data: ReadableStream<Uint8Array> | Blob,\n options?: AttachmentSendOptions,\n ): Promise<AttachmentUploadResult> {\n // Presigned targets bypass Switchboard entirely: bytes go straight to the\n // provider with the exact signed headers. Switchboard targets (and the\n // legacy no-target wire) keep the authenticated reservation PUT below.\n if (this.uploadTarget?.kind === \"presigned-put\") {\n return this.sendPresigned(this.uploadTarget, data, options);\n }\n const url = `${this.remoteUrl}/attachments/reservations/${this.reservationId}`;\n const authHeaders = await buildAuthHeaders(url, this.jwtHandler);\n\n const body = await toBody(data);\n\n // Always upload as octet-stream. The server reads the real mime type from\n // the reservation row; sending the user's mime type here (e.g. application/json)\n // would let Express body-parser drain the request body before our handler runs,\n // silently writing zero bytes.\n const response = await this.uploadTransport({\n url,\n method: \"PUT\",\n headers: { ...authHeaders, \"Content-Type\": \"application/octet-stream\" },\n body,\n ...(options?.onProgress\n ? {\n onProgress: (loaded: number, total: number) =>\n options.onProgress?.(loaded, total),\n }\n : {}),\n ...(options?.signal ? { signal: options.signal } : {}),\n });\n\n if (response.status === 422) {\n let errorBody: unknown;\n try {\n errorBody = await response.json();\n } catch {\n throw new Error(\n `Attachment upload failed: ${response.status} ${response.statusText}`,\n );\n }\n if (isRecord(errorBody)) {\n if (\n errorBody.error === \"hash_mismatch\" &&\n typeof errorBody.claimed === \"string\" &&\n typeof errorBody.actual === \"string\"\n ) {\n throw new HashMismatch(errorBody.claimed, errorBody.actual);\n }\n if (\n errorBody.error === \"size_mismatch\" &&\n typeof errorBody.declared === \"number\" &&\n typeof errorBody.actual === \"number\"\n ) {\n throw new SizeMismatch(errorBody.declared, errorBody.actual);\n }\n }\n throw new Error(\n `Attachment upload failed: ${response.status} ${response.statusText}`,\n );\n }\n\n if (!response.ok) {\n throw new Error(\n `Attachment upload failed: ${response.status} ${response.statusText}`,\n );\n }\n\n return (await response.json()) as AttachmentUploadResult;\n }\n\n /**\n * Direct provider upload: PUT the bytes to the presigned URL with exactly\n * the returned headers — never the Switchboard JWT — and treat any 2xx as\n * final success with no follow-up control request. The result is\n * synthesized from the hash-first reservation, which is the only path that\n * can produce a presigned target.\n */\n private async sendPresigned(\n target: AttachmentUploadTarget,\n data: ReadableStream<Uint8Array> | Blob,\n options?: AttachmentSendOptions,\n ): Promise<AttachmentUploadResult> {\n if (this.reservation.clientHash === null || this.ref === null) {\n throw new Error(\n \"Presigned upload targets require a hash-first reservation\",\n );\n }\n\n const body = await toBody(data);\n const response = await this.uploadTransport({\n url: target.url,\n method: target.method,\n headers: { ...target.headers },\n body,\n ...(options?.onProgress\n ? {\n onProgress: (loaded: number, total: number) =>\n options.onProgress?.(loaded, total),\n }\n : {}),\n ...(options?.signal ? { signal: options.signal } : {}),\n });\n if (!response.ok) {\n throw new AttachmentTransferError(\"presigned-put\", response.status);\n }\n\n const hash = this.reservation.clientHash as AttachmentHash;\n const now = new Date().toISOString();\n return {\n hash,\n ref: this.ref,\n header: {\n hash,\n mimeType: this.reservation.mimeType,\n fileName: this.reservation.fileName,\n sizeBytes: this.reservation.sizeBytes ?? body.size,\n extension: this.reservation.extension,\n status: \"available\",\n source: \"local\",\n createdAtUtc: this.reservation.createdAtUtc || now,\n lastAccessedAtUtc: now,\n expiresAtUtc: null,\n },\n };\n }\n}\n","import type {\n IAttachmentUpload,\n IAttachmentUploadFactory,\n} from \"../interfaces.js\";\nimport type { Reservation } from \"../types.js\";\nimport { RemoteAttachmentUpload } from \"./remote-attachment-upload.js\";\nimport type { SwitchboardClientConfig } from \"./remote-reservation-store.js\";\n\nexport class RemoteAttachmentUploadFactory implements IAttachmentUploadFactory {\n constructor(private readonly config: SwitchboardClientConfig) {}\n\n createUpload(reservation: Reservation): IAttachmentUpload {\n return new RemoteAttachmentUpload(reservation, this.config);\n }\n}\n","import type { AttachmentHash } from \"@powerhousedao/reactor\";\nimport type { JwtHandler } from \"@powerhousedao/reactor\";\nimport {\n AttachmentNotFound,\n AttachmentPending,\n AttachmentTransferError,\n} from \"../errors.js\";\nimport type { IAttachmentReader } from \"../interfaces.js\";\nimport { parseAttachmentDownloadTarget } from \"../targets.js\";\nimport type {\n AttachmentDownloadTarget,\n AttachmentDownloadTargetOptions,\n AttachmentHeader,\n AttachmentMetadata,\n AttachmentResponse,\n} from \"../types.js\";\nimport { buildAuthHeaders } from \"./build-auth-headers.js\";\nimport type { SwitchboardClientConfig } from \"./remote-reservation-store.js\";\n\nconst MISSING_DOCUMENT_ID =\n \"Remote attachment reads require the documentId whose operations reference the attachment\";\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction isAttachmentMetadata(value: unknown): value is AttachmentMetadata {\n if (!isRecord(value)) return false;\n if (typeof value.mimeType !== \"string\") return false;\n if (typeof value.fileName !== \"string\") return false;\n if (\n typeof value.sizeBytes !== \"number\" ||\n !Number.isFinite(value.sizeBytes) ||\n value.sizeBytes < 0\n ) {\n return false;\n }\n if (value.extension !== null && typeof value.extension !== \"string\") {\n return false;\n }\n if (typeof value.createdAtUtc !== \"string\") return false;\n if (\n value.lastAccessedAtUtc !== undefined &&\n typeof value.lastAccessedAtUtc !== \"string\"\n ) {\n return false;\n }\n return true;\n}\n\nfunction contentTypeFallback(response: Response): AttachmentMetadata {\n const contentLength = response.headers.get(\"Content-Length\");\n if (contentLength === null) {\n throw new Error(\n \"Switchboard response missing both Attachment-Metadata and Content-Length headers\",\n );\n }\n const sizeBytes = Number(contentLength);\n if (!Number.isInteger(sizeBytes) || sizeBytes < 0) {\n throw new Error(\n `Switchboard response has invalid Content-Length header: ${JSON.stringify(contentLength)}`,\n );\n }\n // Last-Modified is the closest legitimate signal we have for an original\n // creation time when Attachment-Metadata is absent. If that's missing too,\n // fall back to the response date (still server-attributed). This is\n // imperfect — Last-Modified reflects the most recent change, not the\n // original upload — but unlike sizeBytes there is no zero-equivalent\n // sentinel for a date, and downstream consumers expect a value.\n const lastModified = response.headers.get(\"Last-Modified\");\n const dateHeader = response.headers.get(\"Date\");\n const createdAtUtc = lastModified\n ? new Date(lastModified).toISOString()\n : dateHeader\n ? new Date(dateHeader).toISOString()\n : new Date().toISOString();\n\n return {\n // application/octet-stream is the RFC 2046 sentinel for \"unknown binary\",\n // and \"unknown\" is a non-real filename sentinel; neither is a fabricated\n // semantic value the way Content-Length=0 would be.\n mimeType:\n response.headers.get(\"Content-Type\") ?? \"application/octet-stream\",\n fileName: \"unknown\",\n sizeBytes,\n extension: null,\n createdAtUtc,\n lastAccessedAtUtc: createdAtUtc,\n };\n}\n\nfunction parseMetadata(response: Response): AttachmentMetadata {\n // Compute the fallback at most once; both the recovery path inside the\n // header parser and the outer \"no header / parse failed\" path share it.\n let fallbackCache: AttachmentMetadata | undefined;\n const fallback = (): AttachmentMetadata => {\n if (fallbackCache === undefined) {\n fallbackCache = contentTypeFallback(response);\n }\n return fallbackCache;\n };\n\n const metaHeader = response.headers.get(\"Attachment-Metadata\");\n if (metaHeader) {\n try {\n const parsed: unknown = JSON.parse(metaHeader);\n if (isRecord(parsed)) {\n if (parsed.extension === undefined) {\n parsed.extension = null;\n }\n // Older switchboards may omit these timestamps; fall back to the\n // Date/Last-Modified header so we never produce client-clock-stamped\n // values when the server has authority.\n if (parsed.createdAtUtc === undefined) {\n parsed.createdAtUtc = fallback().createdAtUtc;\n }\n if (parsed.lastAccessedAtUtc === undefined) {\n parsed.lastAccessedAtUtc = fallback().lastAccessedAtUtc;\n }\n }\n if (isAttachmentMetadata(parsed)) {\n return parsed;\n }\n } catch {\n // fall through to Content-Type fallback\n }\n }\n return fallback();\n}\n\ntype PendingInfo = {\n expiresAtUtc: string;\n mimeType: string;\n fileName: string;\n sizeBytes: number;\n};\n\ntype PartialPendingInfo = {\n expiresAtUtc: string;\n mimeType?: string;\n fileName?: string;\n sizeBytes?: number;\n};\n\nfunction parsePendingExpiry(response: Response): PartialPendingInfo | null {\n const header = response.headers.get(\"Attachment-Pending\");\n if (!header) return null;\n try {\n const parsed: unknown = JSON.parse(header);\n if (!isRecord(parsed)) return null;\n if (typeof parsed.expiresAtUtc !== \"string\") return null;\n const result: PartialPendingInfo = { expiresAtUtc: parsed.expiresAtUtc };\n if (typeof parsed.mimeType === \"string\") result.mimeType = parsed.mimeType;\n if (typeof parsed.fileName === \"string\") result.fileName = parsed.fileName;\n if (\n typeof parsed.sizeBytes === \"number\" &&\n Number.isFinite(parsed.sizeBytes) &&\n parsed.sizeBytes >= 0\n ) {\n result.sizeBytes = parsed.sizeBytes;\n }\n return result;\n } catch {\n return null;\n }\n}\n\nfunction parsePendingHeader(response: Response): PendingInfo | null {\n const partial = parsePendingExpiry(response);\n if (!partial) return null;\n if (\n typeof partial.mimeType !== \"string\" ||\n typeof partial.fileName !== \"string\" ||\n partial.sizeBytes === undefined\n ) {\n return null;\n }\n return {\n expiresAtUtc: partial.expiresAtUtc,\n mimeType: partial.mimeType,\n fileName: partial.fileName,\n sizeBytes: partial.sizeBytes,\n };\n}\n\nexport class RemoteAttachmentStore implements IAttachmentReader {\n private readonly remoteUrl: string;\n private readonly jwtHandler?: JwtHandler;\n private readonly fetchFn: typeof fetch;\n\n constructor(config: SwitchboardClientConfig) {\n this.remoteUrl = config.remoteUrl;\n this.jwtHandler = config.jwtHandler;\n this.fetchFn = (config.fetchFn ?? globalThis.fetch).bind(globalThis);\n }\n\n /**\n * Get attachment metadata. Normally returns a pending AttachmentHeader\n * (status: 'pending') when the server responds 202 with a full\n * Attachment-Pending header. When only expiresAtUtc is present in the\n * header (degraded wire), throws AttachmentPending instead -- the\n * AttachmentPending throw is the degraded-wire case.\n */\n async stat(\n hash: AttachmentHash,\n documentId?: string,\n ): Promise<AttachmentHeader> {\n // The server answers a hash-only HEAD 404; hash-first reserve relies on\n // that to leave the dedup decision to the server's 409.\n if (documentId === undefined) {\n throw new AttachmentNotFound(hash);\n }\n const url = `${this.remoteUrl}/attachments/${hash}?documentId=${encodeURIComponent(documentId)}`;\n const authHeaders = await buildAuthHeaders(url, this.jwtHandler);\n\n const response = await this.fetchFn(url, {\n method: \"HEAD\",\n headers: authHeaders,\n });\n\n if (response.status === 202) {\n const fullPending = parsePendingHeader(response);\n if (fullPending) {\n return buildPendingHeader(hash, fullPending);\n }\n const partial = parsePendingExpiry(response);\n if (partial) {\n throw new AttachmentPending(hash, partial.expiresAtUtc);\n }\n throw new Error(\n \"Attachment stat returned 202 with missing or malformed Attachment-Pending header\",\n );\n }\n\n if (response.status === 404) {\n throw new AttachmentNotFound(hash);\n }\n if (!response.ok) {\n throw new Error(\n `Attachment stat failed: ${response.status} ${response.statusText}`,\n );\n }\n\n const metadata = parseMetadata(response);\n return buildHeader(hash, metadata);\n }\n\n async get(\n hash: AttachmentHash,\n signal?: AbortSignal,\n documentId?: string,\n ): Promise<AttachmentResponse> {\n if (documentId === undefined) {\n throw new Error(MISSING_DOCUMENT_ID);\n }\n const target = await this.getDownloadTarget(hash, { documentId, signal });\n if (target.kind === \"presigned-get\") {\n return this.fetchPresigned(hash, target, signal);\n }\n return this.fetchAttachment(hash, target, signal);\n }\n\n /**\n * Asks Switchboard for an authorized download target. The request carries\n * the JWT; the response is runtime-validated before any byte transfer.\n * Public so callers can mint direct URLs (previews, share links) without\n * transferring bytes; `expiresIn` requests a caller-chosen lifetime.\n */\n async getDownloadTarget(\n hash: AttachmentHash,\n options: AttachmentDownloadTargetOptions,\n ): Promise<AttachmentDownloadTarget> {\n const { documentId, expiresIn, signal } = options;\n const expiry =\n expiresIn === undefined\n ? \"\"\n : `&expiresIn=${encodeURIComponent(String(expiresIn))}`;\n const url = `${this.remoteUrl}/attachments/${hash}/download-target?documentId=${encodeURIComponent(documentId)}${expiry}`;\n const headers = await buildAuthHeaders(url, this.jwtHandler);\n const response = await this.fetchFn(url, { signal, headers });\n\n if (response.status === 404) {\n throw new AttachmentNotFound(hash);\n }\n if (!response.ok) {\n throw new AttachmentTransferError(\"download-target\", response.status);\n }\n\n let body: unknown;\n try {\n body = await response.json();\n } catch {\n throw new AttachmentTransferError(\"download-target\");\n }\n return parseAttachmentDownloadTarget(body);\n }\n\n /**\n * Executes a presigned GET with exactly the returned headers and no JWT.\n * A provider 404 means the object is missing despite available metadata\n * (the accepted abandoned-upload trade-off) and surfaces as the same typed\n * not-found error callers already handle.\n */\n private async fetchPresigned(\n hash: AttachmentHash,\n target: AttachmentDownloadTarget,\n signal?: AbortSignal,\n ): Promise<AttachmentResponse> {\n const response = await this.fetchFn(target.url, {\n signal,\n headers: { ...target.headers },\n });\n if (response.status === 404) {\n throw new AttachmentNotFound(hash);\n }\n if (!response.ok) {\n throw new AttachmentTransferError(\"presigned-get\", response.status);\n }\n if (!response.body) {\n throw new Error(\"Response body is null\");\n }\n const metadata = parseMetadata(response);\n return { header: buildHeader(hash, metadata), body: response.body };\n }\n\n private async fetchAttachment(\n hash: AttachmentHash,\n target: AttachmentDownloadTarget,\n signal?: AbortSignal,\n ): Promise<AttachmentResponse> {\n const url = target.url;\n const authHeaders = await buildAuthHeaders(url, this.jwtHandler);\n const headers = { ...target.headers, ...authHeaders };\n\n const response = await this.fetchFn(url, { signal, headers });\n\n if (response.status === 202) {\n const pending = parsePendingExpiry(response);\n if (!pending) {\n throw new Error(\n \"Attachment fetch returned 202 with missing or malformed Attachment-Pending header\",\n );\n }\n throw new AttachmentPending(hash, pending.expiresAtUtc);\n }\n\n if (response.status === 404) {\n throw new AttachmentNotFound(hash);\n }\n if (!response.ok) {\n throw new Error(\n `Attachment fetch failed: ${response.status} ${response.statusText}`,\n );\n }\n if (!response.body) {\n throw new Error(\"Response body is null\");\n }\n\n const metadata = parseMetadata(response);\n return { header: buildHeader(hash, metadata), body: response.body };\n }\n}\n\nfunction buildHeader(\n hash: AttachmentHash,\n metadata: AttachmentMetadata,\n): AttachmentHeader {\n return {\n hash,\n mimeType: metadata.mimeType,\n fileName: metadata.fileName,\n sizeBytes: metadata.sizeBytes,\n extension: metadata.extension,\n status: \"available\",\n source: \"sync\",\n createdAtUtc: metadata.createdAtUtc,\n lastAccessedAtUtc: metadata.lastAccessedAtUtc ?? metadata.createdAtUtc,\n expiresAtUtc: null,\n };\n}\n\nfunction buildPendingHeader(\n hash: AttachmentHash,\n pending: PendingInfo,\n): AttachmentHeader {\n const now = new Date().toISOString();\n return {\n hash,\n mimeType: pending.mimeType,\n fileName: pending.fileName,\n sizeBytes: pending.sizeBytes,\n extension: null,\n status: \"pending\",\n source: \"sync\",\n createdAtUtc: now,\n lastAccessedAtUtc: now,\n expiresAtUtc: pending.expiresAtUtc,\n };\n}\n","import { AttachmentService } from \"../attachment-service.js\";\nimport type { IAttachmentService } from \"../interfaces.js\";\nimport { RemoteAttachmentStore } from \"./remote-attachment-store.js\";\nimport { RemoteAttachmentUploadFactory } from \"./remote-attachment-upload-factory.js\";\nimport {\n RemoteReservationStore,\n type SwitchboardClientConfig,\n} from \"./remote-reservation-store.js\";\n\nexport function createRemoteAttachmentService(\n config: SwitchboardClientConfig,\n): IAttachmentService {\n const reservations = new RemoteReservationStore(config);\n const uploadFactory = new RemoteAttachmentUploadFactory(config);\n const store = new RemoteAttachmentStore(config);\n return new AttachmentService(store, reservations, uploadFactory);\n}\n","import type { IAttachmentTransport } from \"./interfaces.js\";\nimport type { TransportFetchResult } from \"./types.js\";\n\n/**\n * No-op transport for deployments without remote sync.\n * fetch() always returns not-found, announce() and push() are no-ops.\n */\nexport class NullAttachmentTransport implements IAttachmentTransport {\n fetch(): Promise<TransportFetchResult> {\n return Promise.resolve({ kind: \"not-found\" });\n }\n\n announce(): Promise<void> {\n return Promise.resolve();\n }\n\n push(): Promise<void> {\n return Promise.resolve();\n }\n}\n"],"mappings":";;AAMA,SAASA,WAAS,OAAkD;CAClE,OAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,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M,eAAe,IAAI,uBAAuB,MAAM;CACtD,MAAM,gBAAgB,IAAI,8BAA8B,MAAM;CAE9D,OAAO,IAAI,kBAAkB,IADX,sBAAsB,MACX,GAAO,cAAc,aAAa;AACjE;;;;;;;ACTA,IAAa,0BAAb,MAAqE;CACnE,QAAuC;EACrC,OAAO,QAAQ,QAAQ,EAAE,MAAM,YAAY,CAAC;CAC9C;CAEA,WAA0B;EACxB,OAAO,QAAQ,QAAQ;CACzB;CAEA,OAAsB;EACpB,OAAO,QAAQ,QAAQ;CACzB;AACF"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@powerhousedao/reactor-attachments",
|
|
3
|
-
"version": "6.2.3-dev.
|
|
3
|
+
"version": "6.2.3-dev.73",
|
|
4
4
|
"license": "AGPL-3.0-only",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"repository": {
|
|
@@ -37,8 +37,8 @@
|
|
|
37
37
|
"@aws-sdk/s3-request-presigner": "3.1087.0",
|
|
38
38
|
"@noble/hashes": "^1.8.0",
|
|
39
39
|
"@powerhousedao/document-engineering": "1.40.5",
|
|
40
|
-
"@powerhousedao/reactor": "6.2.3-dev.
|
|
41
|
-
"@powerhousedao/shared": "6.2.3-dev.
|
|
40
|
+
"@powerhousedao/reactor": "6.2.3-dev.73",
|
|
41
|
+
"@powerhousedao/shared": "6.2.3-dev.73",
|
|
42
42
|
"change-case": "5.4.4",
|
|
43
43
|
"graphql": "^16",
|
|
44
44
|
"kysely": "0.28.16"
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"null-attachment-transport-Cm_kb5ww.js","names":["isRecord","isRecord","isRecord"],"sources":["../src/targets.ts","../src/attachment-service.ts","../src/blob.ts","../src/switchboard/upload-transport.ts","../src/switchboard/xhr-upload-transport.ts","../src/switchboard/remote-reservation-store.ts","../src/switchboard/remote-attachment-upload.ts","../src/switchboard/remote-attachment-upload-factory.ts","../src/switchboard/remote-attachment-store.ts","../src/switchboard/create-remote-attachment-service.ts","../src/null-attachment-transport.ts"],"sourcesContent":["import type {\n AttachmentDownloadTarget,\n AttachmentTargetHeaders,\n AttachmentUploadTarget,\n} from \"./types.js\";\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction parseUrl(value: unknown): string {\n if (typeof value !== \"string\" || value.length === 0) {\n throw new Error(\"Attachment target URL must be a non-empty string\");\n }\n if (value.trim() !== value || hasForbiddenUrlWhitespace(value)) {\n throw new Error(\"Attachment target URL must not contain raw whitespace\");\n }\n let parsed: URL;\n try {\n parsed = new URL(value);\n } catch {\n throw new Error(\"Attachment target URL is invalid\");\n }\n if (\n (parsed.protocol !== \"http:\" && parsed.protocol !== \"https:\") ||\n parsed.username !== \"\" ||\n parsed.password !== \"\"\n ) {\n throw new Error(\n \"Attachment target URL must be HTTP(S) and must not contain credentials\",\n );\n }\n // Return the original string: presigned URLs are opaque and must never be\n // normalized, decoded, reordered, or otherwise reconstructed.\n return value;\n}\n\nfunction parseHeaders(value: unknown): AttachmentTargetHeaders {\n if (!isRecord(value)) {\n throw new Error(\"Attachment target headers must be an object\");\n }\n // A null prototype preserves valid names such as `__proto__` as ordinary\n // own properties instead of invoking Object.prototype setters.\n const headers = Object.create(null) as Record<string, string>;\n const headerName = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;\n for (const [name, headerValue] of Object.entries(value)) {\n if (!headerName.test(name)) {\n throw new Error(`Attachment target header name is invalid: ${name}`);\n }\n if (\n typeof headerValue !== \"string\" ||\n hasForbiddenHeaderCharacter(headerValue)\n ) {\n throw new Error(`Attachment target header value is invalid: ${name}`);\n }\n headers[name] = headerValue;\n }\n return headers;\n}\n\nfunction hasForbiddenHeaderCharacter(value: string): boolean {\n for (let index = 0; index < value.length; index++) {\n const code = value.charCodeAt(index);\n // Horizontal tab is valid field whitespace. Other C0 controls, DEL, and\n // especially CR/LF are forbidden to prevent header injection.\n if (code <= 8 || (code >= 10 && code <= 31) || code === 127 || code > 255) {\n return true;\n }\n }\n return false;\n}\n\nfunction hasForbiddenUrlWhitespace(value: string): boolean {\n for (let index = 0; index < value.length; index++) {\n const code = value.charCodeAt(index);\n // URL parsing may silently trim or percent-encode raw ASCII whitespace.\n // Reject it so the validated opaque string is exactly what Fetch receives.\n if (code <= 32 || code === 127) return true;\n }\n return false;\n}\n\nfunction parseExpiry(value: unknown, required: boolean): string | undefined {\n if (value === undefined && !required) return undefined;\n if (typeof value !== \"string\") {\n throw new Error(\"Attachment target expiry must be an ISO 8601 UTC string\");\n }\n const parsed = new Date(value);\n if (Number.isNaN(parsed.getTime()) || parsed.toISOString() !== value) {\n throw new Error(\"Attachment target expiry must be an ISO 8601 UTC string\");\n }\n return value;\n}\n\nexport function parseAttachmentUploadTarget(\n value: unknown,\n): AttachmentUploadTarget {\n if (!isRecord(value)) {\n throw new Error(\"Attachment upload target must be an object\");\n }\n const url = parseUrl(value.url);\n const headers = parseHeaders(value.headers);\n switch (value.kind) {\n case \"switchboard\":\n if (value.method !== \"PUT\") {\n throw new Error(\"Switchboard upload target method must be PUT\");\n }\n return {\n kind: \"switchboard\",\n method: \"PUT\",\n url,\n headers,\n ...(value.expiresAtUtc === undefined\n ? {}\n : { expiresAtUtc: parseExpiry(value.expiresAtUtc, false) }),\n };\n case \"presigned-put\":\n if (value.method !== \"PUT\") {\n throw new Error(\"Presigned upload target method must be PUT\");\n }\n return {\n kind: \"presigned-put\",\n method: \"PUT\",\n url,\n headers,\n expiresAtUtc: parseExpiry(value.expiresAtUtc, true)!,\n };\n default:\n throw new Error(\"Attachment upload target kind is unknown\");\n }\n}\n\nexport function parseAttachmentDownloadTarget(\n value: unknown,\n): AttachmentDownloadTarget {\n if (!isRecord(value)) {\n throw new Error(\"Attachment download target must be an object\");\n }\n const url = parseUrl(value.url);\n const headers = parseHeaders(value.headers);\n switch (value.kind) {\n case \"switchboard\":\n if (value.method !== \"GET\") {\n throw new Error(\"Switchboard download target method must be GET\");\n }\n return {\n kind: \"switchboard\",\n method: \"GET\",\n url,\n headers,\n ...(value.expiresAtUtc === undefined\n ? {}\n : { expiresAtUtc: parseExpiry(value.expiresAtUtc, false) }),\n };\n case \"presigned-get\":\n if (value.method !== \"GET\") {\n throw new Error(\"Presigned download target method must be GET\");\n }\n return {\n kind: \"presigned-get\",\n method: \"GET\",\n url,\n headers,\n expiresAtUtc: parseExpiry(value.expiresAtUtc, true)!,\n };\n default:\n throw new Error(\"Attachment download target kind is unknown\");\n }\n}\n","import type { AttachmentHash, AttachmentRef } from \"@powerhousedao/reactor\";\nimport {\n AttachmentAlreadyExists,\n AttachmentNotFound,\n AttachmentPending,\n} from \"./errors.js\";\nimport type {\n IAttachmentReader,\n IAttachmentBackend,\n IAttachmentService,\n IAttachmentUpload,\n IAttachmentUploadFactory,\n IReservationStore,\n} from \"./interfaces.js\";\nimport { createRef, parseRef } from \"./ref.js\";\nimport type {\n AttachmentDownloadOptions,\n AttachmentDownloadTarget,\n AttachmentDownloadTargetOptions,\n AttachmentHeader,\n AttachmentResponse,\n AttachmentStatOptions,\n ReserveAttachmentOptions,\n} from \"./types.js\";\n\nconst CLIENT_HASH_PATTERN = /^[a-f0-9]{64}$/;\n\nexport class AttachmentService implements IAttachmentService {\n constructor(\n private readonly store: IAttachmentReader,\n private readonly reservations: IReservationStore,\n private readonly uploadFactory: IAttachmentUploadFactory,\n private readonly backend?: IAttachmentBackend,\n ) {}\n\n async reserve(options: ReserveAttachmentOptions): Promise<IAttachmentUpload> {\n if (options.clientHash !== undefined) {\n return this.reserveHashFirst(options);\n }\n if (this.backend?.kind === \"s3\") {\n throw new Error(\"S3 attachment reservations require a client hash\");\n }\n const reservation = await this.reservations.create(options);\n return this.uploadFactory.createUpload(reservation);\n }\n\n async stat(\n ref: AttachmentRef,\n options?: AttachmentStatOptions,\n ): Promise<AttachmentHeader> {\n const { hash } = parseRef(ref);\n return options?.documentId === undefined\n ? this.store.stat(hash)\n : this.store.stat(hash, options.documentId);\n }\n\n async get(\n ref: AttachmentRef,\n options?: AbortSignal | AttachmentDownloadOptions,\n ): Promise<AttachmentResponse> {\n const { hash } = parseRef(ref);\n const normalized =\n options === undefined || options instanceof AbortSignal\n ? { signal: options }\n : options;\n return normalized.documentId === undefined\n ? this.store.get(hash, normalized.signal)\n : this.store.get(hash, normalized.signal, normalized.documentId);\n }\n\n getDownloadTarget(\n ref: AttachmentRef,\n options: AttachmentDownloadTargetOptions,\n ): Promise<AttachmentDownloadTarget> {\n const { hash } = parseRef(ref);\n const getTarget = this.store.getDownloadTarget?.bind(this.store);\n if (getTarget === undefined) {\n return Promise.reject(\n new Error(\n \"Download targets are not supported by this attachment store: only remote stores negotiate direct URLs\",\n ),\n );\n }\n return getTarget(hash, options);\n }\n\n private async reserveHashFirst(\n options: ReserveAttachmentOptions,\n ): Promise<IAttachmentUpload> {\n const normalized = options.clientHash!.toLowerCase() as AttachmentHash;\n if (!CLIENT_HASH_PATTERN.test(normalized)) {\n throw new Error(\n `clientHash must be a 64-character lowercase hex string, got: ${options.clientHash}`,\n );\n }\n if (\n options.sizeBytes === undefined ||\n !Number.isInteger(options.sizeBytes) ||\n options.sizeBytes <= 0 ||\n !Number.isSafeInteger(options.sizeBytes)\n ) {\n throw new Error(\n \"sizeBytes must be a positive safe integer when clientHash is provided\",\n );\n }\n\n const normalizedOptions: ReserveAttachmentOptions = {\n ...options,\n clientHash: normalized,\n };\n\n let existingHeader: AttachmentHeader | null = null;\n try {\n existingHeader = await this.store.stat(normalized);\n } catch (err) {\n if (\n !(err instanceof AttachmentNotFound) &&\n !(err instanceof AttachmentPending)\n ) {\n throw err;\n }\n }\n\n if (existingHeader !== null) {\n if (this.backend?.kind === \"s3\") {\n if (await this.backend.exists(normalized)) {\n throw new AttachmentAlreadyExists(normalized, createRef(normalized));\n }\n } else if (existingHeader.status === \"available\") {\n throw new AttachmentAlreadyExists(normalized, createRef(normalized));\n }\n }\n\n const reservation = await this.reservations.create(normalizedOptions);\n if (this.backend?.kind !== \"s3\") {\n return this.uploadFactory.createUpload(reservation);\n }\n const uploadTarget = await this.backend.prepareUploadTarget(reservation);\n return this.uploadFactory.createUpload({ ...reservation, uploadTarget });\n }\n}\n","/** Tells a Blob from a stream by shape: `instanceof Blob` misses other realms and polyfills. */\nexport function isBlob(data: ReadableStream<Uint8Array> | Blob): data is Blob {\n return !(\"getReader\" in data);\n}\n","/**\n * The seam every attachment upload PUT goes through.\n *\n * It exists because `fetch` cannot report upload-side progress: there is no\n * event between \"request issued\" and \"response received\". Naming the transport\n * lets an implementation that *can* count bytes (see\n * `createXhrUploadTransport`) be substituted without the upload code knowing\n * which one it holds — and it is also the right seam for a future multipart\n * upload, which needs one request per part.\n */\n\n/**\n * Headers are forwarded VERBATIM. A presigned target's headers are part of a\n * signature: normalizing their casing, or adding so much as one header,\n * invalidates it.\n */\nexport type AttachmentUploadRequest = {\n url: string;\n method: \"PUT\";\n headers: Record<string, string>;\n body: Blob;\n /** Called with cumulative bytes handed to the socket, when observable. */\n onProgress?: (loaded: number, total: number) => void;\n signal?: AbortSignal;\n};\n\n/**\n * The only response surface the upload code reads. A real `Response`\n * satisfies this structurally, which is what lets the fetch transport be an\n * identity pass-through rather than an adapter.\n */\nexport type AttachmentUploadResponse = {\n readonly status: number;\n readonly statusText: string;\n readonly ok: boolean;\n json(): Promise<unknown>;\n};\n\nexport type AttachmentUploadTransport = (\n request: AttachmentUploadRequest,\n) => Promise<AttachmentUploadResponse>;\n\n/**\n * The default transport. Ignores `onProgress` — fetch has no upload-side\n * progress event, and silence is how a transport reports that bytes are\n * unobservable.\n */\nexport function createFetchUploadTransport(\n fetchFn: typeof fetch,\n): AttachmentUploadTransport {\n return (request) =>\n fetchFn(request.url, {\n method: request.method,\n headers: request.headers,\n body: request.body,\n ...(request.signal ? { signal: request.signal } : {}),\n });\n}\n","import {\n createFetchUploadTransport,\n type AttachmentUploadRequest,\n type AttachmentUploadResponse,\n type AttachmentUploadTransport,\n} from \"./upload-transport.js\";\n\nexport type XhrUploadTransportOptions = {\n /**\n * Used where `XMLHttpRequest` does not exist (Node). Defaults to the global\n * fetch, resolved at call time.\n */\n fetchFn?: typeof fetch;\n};\n\n/**\n * Upload transport backed by `XMLHttpRequest`, the only browser API that\n * reports upload-side byte progress (`xhr.upload.onprogress`). Everything else\n * about the request is identical to the fetch path.\n *\n * Capability detection happens **inside** the returned function, never at\n * module load: this module is reachable from the client entry, which is\n * executed in Node by the entrypoint tests, and Node has no\n * `XMLHttpRequest`. Detecting per call also means a test can install a fake on\n * `globalThis` without any module-registry reset.\n */\nexport function createXhrUploadTransport(\n options?: XhrUploadTransportOptions,\n): AttachmentUploadTransport {\n return (request) => {\n const XhrCtor = globalThis.XMLHttpRequest;\n if (typeof XhrCtor !== \"function\") {\n const fetchFn = options?.fetchFn ?? globalThis.fetch;\n return createFetchUploadTransport(fetchFn.bind(globalThis))(request);\n }\n return sendWithXhr(new XhrCtor(), request);\n };\n}\n\n/**\n * Mirrors fetch's observable behavior closely enough that\n * `RemoteAttachmentUpload` cannot tell the two apart:\n *\n * - `responseType` is left at `\"\"`, so a non-JSON 422 body still reaches the\n * caller's `json()` and fails there rather than being swallowed.\n * - status 0 never resolves. XHR reports 0 for network failure, CORS refusal\n * and abort alike; resolving it would fabricate a transfer error claiming\n * the provider answered 0.\n * - failures reject with fetch's error shapes: `TypeError` for network,\n * `AbortError` for abort.\n */\nfunction sendWithXhr(\n xhr: XMLHttpRequest,\n request: AttachmentUploadRequest,\n): Promise<AttachmentUploadResponse> {\n return new Promise<AttachmentUploadResponse>((resolve, reject) => {\n const signal = request.signal;\n let settled = false;\n\n const abortListener = () => xhr.abort();\n const detach = () => signal?.removeEventListener(\"abort\", abortListener);\n const succeed = (response: AttachmentUploadResponse) => {\n if (settled) return;\n settled = true;\n detach();\n resolve(response);\n };\n const fail = (error: Error) => {\n if (settled) return;\n settled = true;\n detach();\n reject(error);\n };\n\n if (signal?.aborted) {\n fail(abortError());\n return;\n }\n\n xhr.open(request.method, request.url, true);\n // Verbatim: a presigned target's headers are part of its signature.\n for (const [name, value] of Object.entries(request.headers)) {\n xhr.setRequestHeader(name, value);\n }\n\n // Attached before send(), and only when a caller is listening — merely\n // registering an upload listener forces a CORS preflight.\n if (request.onProgress) {\n xhr.upload.addEventListener(\"progress\", (event: ProgressEvent) => {\n if (!event.lengthComputable) return;\n request.onProgress?.(event.loaded, event.total);\n });\n }\n\n xhr.addEventListener(\"load\", () => {\n if (xhr.status === 0) {\n fail(networkError());\n return;\n }\n succeed(toResponse(xhr));\n });\n xhr.addEventListener(\"error\", () => fail(networkError()));\n xhr.addEventListener(\"timeout\", () => fail(networkError()));\n xhr.addEventListener(\"abort\", () => fail(abortError()));\n\n signal?.addEventListener(\"abort\", abortListener);\n xhr.send(request.body);\n });\n}\n\nfunction toResponse(xhr: XMLHttpRequest): AttachmentUploadResponse {\n return {\n status: xhr.status,\n statusText: xhr.statusText,\n ok: xhr.status >= 200 && xhr.status < 300,\n json: () => {\n try {\n return Promise.resolve(JSON.parse(xhr.responseText));\n } catch (err) {\n return Promise.reject(\n err instanceof Error ? err : new Error(String(err)),\n );\n }\n },\n };\n}\n\nfunction networkError(): TypeError {\n return new TypeError(\"Failed to fetch\");\n}\n\nfunction abortError(): DOMException {\n return new DOMException(\"The operation was aborted\", \"AbortError\");\n}\n","import type { AttachmentRef, JwtHandler } from \"@powerhousedao/reactor\";\nimport { AttachmentAlreadyExists, ReservationNotFound } from \"../errors.js\";\nimport type { IReservationStore } from \"../interfaces.js\";\nimport { createRef, parseRef } from \"../ref.js\";\nimport type { Reservation, ReserveAttachmentOptions } from \"../types.js\";\nimport { parseAttachmentUploadTarget } from \"../targets.js\";\nimport { buildAuthHeaders } from \"./build-auth-headers.js\";\nimport type { AttachmentUploadTransport } from \"./upload-transport.js\";\n\nexport type SwitchboardClientConfig = {\n remoteUrl: string;\n jwtHandler?: JwtHandler;\n fetchFn?: typeof fetch;\n /**\n * Transport for upload PUTs only, so a browser host can opt into\n * XMLHttpRequest and get real upload progress.\n *\n * An explicit `fetchFn` always wins over this. The precedence is\n * one-directional on purpose: under this rule, adding `uploadTransport` to a\n * config that already pins `fetchFn` is a provable no-op, whereas the\n * reverse rule would let `{ ...config, uploadTransport }` silently route the\n * largest request in the system around a test's mock and onto the network.\n */\n uploadTransport?: AttachmentUploadTransport;\n};\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction deriveExtension(fileName: string): string | null {\n const idx = fileName.lastIndexOf(\".\");\n if (idx <= 0 || idx === fileName.length - 1) return null;\n return fileName.slice(idx + 1).toLowerCase();\n}\n\nfunction isReservationBase(value: unknown): value is Record<string, unknown> & {\n reservationId: string;\n mimeType: string;\n fileName: string;\n extension: string | null;\n createdAtUtc: string;\n expiresAtUtc: string;\n} {\n if (!isRecord(value)) return false;\n if (typeof value.reservationId !== \"string\") return false;\n if (typeof value.mimeType !== \"string\") return false;\n if (typeof value.fileName !== \"string\") return false;\n if (value.extension !== null && typeof value.extension !== \"string\") {\n return false;\n }\n if (typeof value.createdAtUtc !== \"string\") return false;\n if (typeof value.expiresAtUtc !== \"string\") return false;\n return true;\n}\n\nfunction isReservation(value: unknown): value is Reservation {\n if (!isReservationBase(value)) return false;\n // clientHash and sizeBytes may be absent on responses from older\n // switchboards; treat missing as null (normalized below in get()).\n if (\n value.clientHash !== undefined &&\n value.clientHash !== null &&\n typeof value.clientHash !== \"string\"\n ) {\n return false;\n }\n if (\n value.sizeBytes !== undefined &&\n value.sizeBytes !== null &&\n typeof value.sizeBytes !== \"number\"\n ) {\n return false;\n }\n return true;\n}\n\nexport class RemoteReservationStore implements IReservationStore {\n private readonly remoteUrl: string;\n private readonly jwtHandler?: JwtHandler;\n private readonly fetchFn: typeof fetch;\n\n constructor(config: SwitchboardClientConfig) {\n this.remoteUrl = config.remoteUrl;\n this.jwtHandler = config.jwtHandler;\n this.fetchFn = (config.fetchFn ?? globalThis.fetch).bind(globalThis);\n }\n\n async create(options: ReserveAttachmentOptions): Promise<Reservation> {\n const url = `${this.remoteUrl}/attachments/reservations`;\n const authHeaders = await buildAuthHeaders(url, this.jwtHandler);\n const extension = options.extension ?? deriveExtension(options.fileName);\n\n const bodyObj: Record<string, unknown> = {\n mimeType: options.mimeType,\n fileName: options.fileName,\n extension,\n };\n if (options.clientHash !== undefined) {\n bodyObj.clientHash = options.clientHash;\n }\n if (options.sizeBytes !== undefined) {\n bodyObj.sizeBytes = options.sizeBytes;\n }\n\n const response = await this.fetchFn(url, {\n method: \"POST\",\n headers: { ...authHeaders, \"Content-Type\": \"application/json\" },\n body: JSON.stringify(bodyObj),\n });\n\n if (response.status === 409) {\n let body: unknown;\n try {\n body = await response.json();\n } catch {\n throw new Error(\n `Reservation create failed: ${response.status} ${response.statusText}`,\n );\n }\n if (\n isRecord(body) &&\n body.error === \"already_exists\" &&\n options.clientHash !== undefined\n ) {\n let ref: AttachmentRef;\n if (typeof body.ref === \"string\") {\n try {\n parseRef(body.ref as AttachmentRef);\n ref = body.ref as AttachmentRef;\n } catch {\n ref = createRef(options.clientHash);\n }\n } else {\n ref = createRef(options.clientHash);\n }\n throw new AttachmentAlreadyExists(options.clientHash, ref);\n }\n throw new Error(\n `Reservation create failed: ${response.status} ${response.statusText}`,\n );\n }\n\n if (!response.ok) {\n throw new Error(\n `Reservation create failed: ${response.status} ${response.statusText}`,\n );\n }\n\n let json: unknown;\n try {\n json = await response.json();\n } catch {\n throw new Error(\"Reservation create returned non-JSON response\");\n }\n if (\n typeof json !== \"object\" ||\n json === null ||\n typeof (json as Record<string, unknown>).reservationId !== \"string\" ||\n ((json as Record<string, unknown>).reservationId as string).length === 0\n ) {\n throw new Error(\n \"Reservation create returned a payload missing a non-empty reservationId string\",\n );\n }\n const body = json as {\n reservationId: string;\n ref?: string | null;\n createdAtUtc?: string;\n expiresAtUtc?: string;\n uploadTarget?: unknown;\n };\n // The server is the source of truth for both timestamps. We synthesize\n // only as a last-resort fallback for older switchboards that don't\n // include them in the response; in that case the client cannot know the\n // server's TTL, so expiresAtUtc is a best-effort placeholder.\n const now = new Date();\n return {\n reservationId: body.reservationId,\n mimeType: options.mimeType,\n fileName: options.fileName,\n extension,\n createdAtUtc: body.createdAtUtc ?? now.toISOString(),\n expiresAtUtc:\n body.expiresAtUtc ??\n new Date(now.getTime() + 24 * 60 * 60 * 1000).toISOString(),\n clientHash: options.clientHash ?? null,\n sizeBytes: options.sizeBytes ?? null,\n ...(body.uploadTarget === undefined\n ? {}\n : { uploadTarget: parseAttachmentUploadTarget(body.uploadTarget) }),\n };\n }\n\n async get(reservationId: string): Promise<Reservation> {\n const url = `${this.remoteUrl}/attachments/reservations/${encodeURIComponent(reservationId)}`;\n const authHeaders = await buildAuthHeaders(url, this.jwtHandler);\n\n const response = await this.fetchFn(url, { headers: authHeaders });\n\n if (response.status === 404) {\n throw new ReservationNotFound(reservationId);\n }\n if (!response.ok) {\n throw new Error(\n `Reservation get failed: ${response.status} ${response.statusText}`,\n );\n }\n\n let parsed: unknown;\n try {\n parsed = await response.json();\n } catch {\n throw new Error(\"Reservation get returned non-JSON response\");\n }\n if (!isReservation(parsed)) {\n throw new Error(\n \"Reservation get returned a payload that does not match the Reservation shape\",\n );\n }\n return {\n reservationId: parsed.reservationId,\n mimeType: parsed.mimeType,\n fileName: parsed.fileName,\n extension: parsed.extension,\n createdAtUtc: parsed.createdAtUtc,\n expiresAtUtc: parsed.expiresAtUtc,\n // Normalize fields that may be absent on older switchboard responses.\n clientHash: parsed.clientHash ?? null,\n sizeBytes: parsed.sizeBytes ?? null,\n ...(parsed.uploadTarget === undefined\n ? {}\n : {\n uploadTarget: parseAttachmentUploadTarget(parsed.uploadTarget),\n }),\n };\n }\n\n async delete(reservationId: string): Promise<void> {\n const url = `${this.remoteUrl}/attachments/reservations/${encodeURIComponent(reservationId)}`;\n const authHeaders = await buildAuthHeaders(url, this.jwtHandler);\n\n const response = await this.fetchFn(url, {\n method: \"DELETE\",\n headers: authHeaders,\n });\n\n // 2xx = success; 404 / 410 = already gone, treat as idempotent success.\n if (!response.ok && response.status !== 404 && response.status !== 410) {\n throw new Error(\n `Reservation delete failed: ${response.status} ${response.statusText}`,\n );\n }\n }\n\n // Sweeping is the server's responsibility; clients have no authority to\n // delete reservations on a remote switchboard.\n deleteExpired(): Promise<number> {\n return Promise.reject(\n new Error(\"RemoteReservationStore.deleteExpired is not supported\"),\n );\n }\n}\n","import type {\n AttachmentHash,\n AttachmentRef,\n JwtHandler,\n} from \"@powerhousedao/reactor\";\nimport {\n AttachmentTransferError,\n HashMismatch,\n SizeMismatch,\n} from \"../errors.js\";\nimport type { IAttachmentUpload } from \"../interfaces.js\";\nimport { createRef } from \"../ref.js\";\nimport type {\n AttachmentSendOptions,\n AttachmentUploadResult,\n AttachmentUploadTarget,\n Reservation,\n} from \"../types.js\";\nimport { buildAuthHeaders } from \"./build-auth-headers.js\";\nimport type { SwitchboardClientConfig } from \"./remote-reservation-store.js\";\nimport {\n createFetchUploadTransport,\n type AttachmentUploadTransport,\n} from \"./upload-transport.js\";\nimport { isBlob } from \"../blob.js\";\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/**\n * A Blob goes out untouched, so a File streams from disk. A stream is\n * buffered: browsers don't portably accept a ReadableStream request body.\n */\nasync function toBody(data: ReadableStream<Uint8Array> | Blob): Promise<Blob> {\n return isBlob(data) ? data : new Response(data).blob();\n}\n\nexport class RemoteAttachmentUpload implements IAttachmentUpload {\n readonly reservationId: string;\n readonly ref: AttachmentRef | null;\n readonly expiresAtUtc: string;\n readonly uploadTarget?: AttachmentUploadTarget;\n private readonly reservation: Reservation;\n private readonly remoteUrl: string;\n private readonly jwtHandler?: JwtHandler;\n private readonly uploadTransport: AttachmentUploadTransport;\n\n constructor(reservation: Reservation, config: SwitchboardClientConfig) {\n this.reservationId = reservation.reservationId;\n this.ref =\n reservation.clientHash !== null\n ? createRef(reservation.clientHash)\n : null;\n this.expiresAtUtc = reservation.expiresAtUtc;\n if (reservation.uploadTarget) {\n this.uploadTarget = reservation.uploadTarget;\n }\n this.reservation = reservation;\n this.remoteUrl = config.remoteUrl;\n this.jwtHandler = config.jwtHandler;\n // fetchFn wins: pinning fetch must not be silently overridden.\n this.uploadTransport = config.fetchFn\n ? createFetchUploadTransport(config.fetchFn.bind(globalThis))\n : (config.uploadTransport ??\n createFetchUploadTransport(globalThis.fetch.bind(globalThis)));\n }\n\n async send(\n data: ReadableStream<Uint8Array> | Blob,\n options?: AttachmentSendOptions,\n ): Promise<AttachmentUploadResult> {\n // Presigned targets bypass Switchboard entirely: bytes go straight to the\n // provider with the exact signed headers. Switchboard targets (and the\n // legacy no-target wire) keep the authenticated reservation PUT below.\n if (this.uploadTarget?.kind === \"presigned-put\") {\n return this.sendPresigned(this.uploadTarget, data, options);\n }\n const url = `${this.remoteUrl}/attachments/reservations/${this.reservationId}`;\n const authHeaders = await buildAuthHeaders(url, this.jwtHandler);\n\n const body = await toBody(data);\n\n // Always upload as octet-stream. The server reads the real mime type from\n // the reservation row; sending the user's mime type here (e.g. application/json)\n // would let Express body-parser drain the request body before our handler runs,\n // silently writing zero bytes.\n const response = await this.uploadTransport({\n url,\n method: \"PUT\",\n headers: { ...authHeaders, \"Content-Type\": \"application/octet-stream\" },\n body,\n ...(options?.onProgress\n ? {\n onProgress: (loaded: number, total: number) =>\n options.onProgress?.(loaded, total),\n }\n : {}),\n ...(options?.signal ? { signal: options.signal } : {}),\n });\n\n if (response.status === 422) {\n let errorBody: unknown;\n try {\n errorBody = await response.json();\n } catch {\n throw new Error(\n `Attachment upload failed: ${response.status} ${response.statusText}`,\n );\n }\n if (isRecord(errorBody)) {\n if (\n errorBody.error === \"hash_mismatch\" &&\n typeof errorBody.claimed === \"string\" &&\n typeof errorBody.actual === \"string\"\n ) {\n throw new HashMismatch(errorBody.claimed, errorBody.actual);\n }\n if (\n errorBody.error === \"size_mismatch\" &&\n typeof errorBody.declared === \"number\" &&\n typeof errorBody.actual === \"number\"\n ) {\n throw new SizeMismatch(errorBody.declared, errorBody.actual);\n }\n }\n throw new Error(\n `Attachment upload failed: ${response.status} ${response.statusText}`,\n );\n }\n\n if (!response.ok) {\n throw new Error(\n `Attachment upload failed: ${response.status} ${response.statusText}`,\n );\n }\n\n return (await response.json()) as AttachmentUploadResult;\n }\n\n /**\n * Direct provider upload: PUT the bytes to the presigned URL with exactly\n * the returned headers — never the Switchboard JWT — and treat any 2xx as\n * final success with no follow-up control request. The result is\n * synthesized from the hash-first reservation, which is the only path that\n * can produce a presigned target.\n */\n private async sendPresigned(\n target: AttachmentUploadTarget,\n data: ReadableStream<Uint8Array> | Blob,\n options?: AttachmentSendOptions,\n ): Promise<AttachmentUploadResult> {\n if (this.reservation.clientHash === null || this.ref === null) {\n throw new Error(\n \"Presigned upload targets require a hash-first reservation\",\n );\n }\n\n const body = await toBody(data);\n const response = await this.uploadTransport({\n url: target.url,\n method: target.method,\n headers: { ...target.headers },\n body,\n ...(options?.onProgress\n ? {\n onProgress: (loaded: number, total: number) =>\n options.onProgress?.(loaded, total),\n }\n : {}),\n ...(options?.signal ? { signal: options.signal } : {}),\n });\n if (!response.ok) {\n throw new AttachmentTransferError(\"presigned-put\", response.status);\n }\n\n const hash = this.reservation.clientHash as AttachmentHash;\n const now = new Date().toISOString();\n return {\n hash,\n ref: this.ref,\n header: {\n hash,\n mimeType: this.reservation.mimeType,\n fileName: this.reservation.fileName,\n sizeBytes: this.reservation.sizeBytes ?? body.size,\n extension: this.reservation.extension,\n status: \"available\",\n source: \"local\",\n createdAtUtc: this.reservation.createdAtUtc || now,\n lastAccessedAtUtc: now,\n expiresAtUtc: null,\n },\n };\n }\n}\n","import type {\n IAttachmentUpload,\n IAttachmentUploadFactory,\n} from \"../interfaces.js\";\nimport type { Reservation } from \"../types.js\";\nimport { RemoteAttachmentUpload } from \"./remote-attachment-upload.js\";\nimport type { SwitchboardClientConfig } from \"./remote-reservation-store.js\";\n\nexport class RemoteAttachmentUploadFactory implements IAttachmentUploadFactory {\n constructor(private readonly config: SwitchboardClientConfig) {}\n\n createUpload(reservation: Reservation): IAttachmentUpload {\n return new RemoteAttachmentUpload(reservation, this.config);\n }\n}\n","import type { AttachmentHash } from \"@powerhousedao/reactor\";\nimport type { JwtHandler } from \"@powerhousedao/reactor\";\nimport {\n AttachmentNotFound,\n AttachmentPending,\n AttachmentTransferError,\n} from \"../errors.js\";\nimport type { IAttachmentReader } from \"../interfaces.js\";\nimport { parseAttachmentDownloadTarget } from \"../targets.js\";\nimport type {\n AttachmentDownloadTarget,\n AttachmentDownloadTargetOptions,\n AttachmentHeader,\n AttachmentMetadata,\n AttachmentResponse,\n} from \"../types.js\";\nimport { buildAuthHeaders } from \"./build-auth-headers.js\";\nimport type { SwitchboardClientConfig } from \"./remote-reservation-store.js\";\n\nconst MISSING_DOCUMENT_ID =\n \"Remote attachment reads require the documentId whose operations reference the attachment\";\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction isAttachmentMetadata(value: unknown): value is AttachmentMetadata {\n if (!isRecord(value)) return false;\n if (typeof value.mimeType !== \"string\") return false;\n if (typeof value.fileName !== \"string\") return false;\n if (\n typeof value.sizeBytes !== \"number\" ||\n !Number.isFinite(value.sizeBytes) ||\n value.sizeBytes < 0\n ) {\n return false;\n }\n if (value.extension !== null && typeof value.extension !== \"string\") {\n return false;\n }\n if (typeof value.createdAtUtc !== \"string\") return false;\n if (\n value.lastAccessedAtUtc !== undefined &&\n typeof value.lastAccessedAtUtc !== \"string\"\n ) {\n return false;\n }\n return true;\n}\n\nfunction contentTypeFallback(response: Response): AttachmentMetadata {\n const contentLength = response.headers.get(\"Content-Length\");\n if (contentLength === null) {\n throw new Error(\n \"Switchboard response missing both Attachment-Metadata and Content-Length headers\",\n );\n }\n const sizeBytes = Number(contentLength);\n if (!Number.isInteger(sizeBytes) || sizeBytes < 0) {\n throw new Error(\n `Switchboard response has invalid Content-Length header: ${JSON.stringify(contentLength)}`,\n );\n }\n // Last-Modified is the closest legitimate signal we have for an original\n // creation time when Attachment-Metadata is absent. If that's missing too,\n // fall back to the response date (still server-attributed). This is\n // imperfect — Last-Modified reflects the most recent change, not the\n // original upload — but unlike sizeBytes there is no zero-equivalent\n // sentinel for a date, and downstream consumers expect a value.\n const lastModified = response.headers.get(\"Last-Modified\");\n const dateHeader = response.headers.get(\"Date\");\n const createdAtUtc = lastModified\n ? new Date(lastModified).toISOString()\n : dateHeader\n ? new Date(dateHeader).toISOString()\n : new Date().toISOString();\n\n return {\n // application/octet-stream is the RFC 2046 sentinel for \"unknown binary\",\n // and \"unknown\" is a non-real filename sentinel; neither is a fabricated\n // semantic value the way Content-Length=0 would be.\n mimeType:\n response.headers.get(\"Content-Type\") ?? \"application/octet-stream\",\n fileName: \"unknown\",\n sizeBytes,\n extension: null,\n createdAtUtc,\n lastAccessedAtUtc: createdAtUtc,\n };\n}\n\nfunction parseMetadata(response: Response): AttachmentMetadata {\n // Compute the fallback at most once; both the recovery path inside the\n // header parser and the outer \"no header / parse failed\" path share it.\n let fallbackCache: AttachmentMetadata | undefined;\n const fallback = (): AttachmentMetadata => {\n if (fallbackCache === undefined) {\n fallbackCache = contentTypeFallback(response);\n }\n return fallbackCache;\n };\n\n const metaHeader = response.headers.get(\"Attachment-Metadata\");\n if (metaHeader) {\n try {\n const parsed: unknown = JSON.parse(metaHeader);\n if (isRecord(parsed)) {\n if (parsed.extension === undefined) {\n parsed.extension = null;\n }\n // Older switchboards may omit these timestamps; fall back to the\n // Date/Last-Modified header so we never produce client-clock-stamped\n // values when the server has authority.\n if (parsed.createdAtUtc === undefined) {\n parsed.createdAtUtc = fallback().createdAtUtc;\n }\n if (parsed.lastAccessedAtUtc === undefined) {\n parsed.lastAccessedAtUtc = fallback().lastAccessedAtUtc;\n }\n }\n if (isAttachmentMetadata(parsed)) {\n return parsed;\n }\n } catch {\n // fall through to Content-Type fallback\n }\n }\n return fallback();\n}\n\ntype PendingInfo = {\n expiresAtUtc: string;\n mimeType: string;\n fileName: string;\n sizeBytes: number;\n};\n\ntype PartialPendingInfo = {\n expiresAtUtc: string;\n mimeType?: string;\n fileName?: string;\n sizeBytes?: number;\n};\n\nfunction parsePendingExpiry(response: Response): PartialPendingInfo | null {\n const header = response.headers.get(\"Attachment-Pending\");\n if (!header) return null;\n try {\n const parsed: unknown = JSON.parse(header);\n if (!isRecord(parsed)) return null;\n if (typeof parsed.expiresAtUtc !== \"string\") return null;\n const result: PartialPendingInfo = { expiresAtUtc: parsed.expiresAtUtc };\n if (typeof parsed.mimeType === \"string\") result.mimeType = parsed.mimeType;\n if (typeof parsed.fileName === \"string\") result.fileName = parsed.fileName;\n if (\n typeof parsed.sizeBytes === \"number\" &&\n Number.isFinite(parsed.sizeBytes) &&\n parsed.sizeBytes >= 0\n ) {\n result.sizeBytes = parsed.sizeBytes;\n }\n return result;\n } catch {\n return null;\n }\n}\n\nfunction parsePendingHeader(response: Response): PendingInfo | null {\n const partial = parsePendingExpiry(response);\n if (!partial) return null;\n if (\n typeof partial.mimeType !== \"string\" ||\n typeof partial.fileName !== \"string\" ||\n partial.sizeBytes === undefined\n ) {\n return null;\n }\n return {\n expiresAtUtc: partial.expiresAtUtc,\n mimeType: partial.mimeType,\n fileName: partial.fileName,\n sizeBytes: partial.sizeBytes,\n };\n}\n\nexport class RemoteAttachmentStore implements IAttachmentReader {\n private readonly remoteUrl: string;\n private readonly jwtHandler?: JwtHandler;\n private readonly fetchFn: typeof fetch;\n\n constructor(config: SwitchboardClientConfig) {\n this.remoteUrl = config.remoteUrl;\n this.jwtHandler = config.jwtHandler;\n this.fetchFn = (config.fetchFn ?? globalThis.fetch).bind(globalThis);\n }\n\n /**\n * Get attachment metadata. Normally returns a pending AttachmentHeader\n * (status: 'pending') when the server responds 202 with a full\n * Attachment-Pending header. When only expiresAtUtc is present in the\n * header (degraded wire), throws AttachmentPending instead -- the\n * AttachmentPending throw is the degraded-wire case.\n */\n async stat(\n hash: AttachmentHash,\n documentId?: string,\n ): Promise<AttachmentHeader> {\n // The server answers a hash-only HEAD 404; hash-first reserve relies on\n // that to leave the dedup decision to the server's 409.\n if (documentId === undefined) {\n throw new AttachmentNotFound(hash);\n }\n const url = `${this.remoteUrl}/attachments/${hash}?documentId=${encodeURIComponent(documentId)}`;\n const authHeaders = await buildAuthHeaders(url, this.jwtHandler);\n\n const response = await this.fetchFn(url, {\n method: \"HEAD\",\n headers: authHeaders,\n });\n\n if (response.status === 202) {\n const fullPending = parsePendingHeader(response);\n if (fullPending) {\n return buildPendingHeader(hash, fullPending);\n }\n const partial = parsePendingExpiry(response);\n if (partial) {\n throw new AttachmentPending(hash, partial.expiresAtUtc);\n }\n throw new Error(\n \"Attachment stat returned 202 with missing or malformed Attachment-Pending header\",\n );\n }\n\n if (response.status === 404) {\n throw new AttachmentNotFound(hash);\n }\n if (!response.ok) {\n throw new Error(\n `Attachment stat failed: ${response.status} ${response.statusText}`,\n );\n }\n\n const metadata = parseMetadata(response);\n return buildHeader(hash, metadata);\n }\n\n async get(\n hash: AttachmentHash,\n signal?: AbortSignal,\n documentId?: string,\n ): Promise<AttachmentResponse> {\n if (documentId === undefined) {\n throw new Error(MISSING_DOCUMENT_ID);\n }\n const target = await this.getDownloadTarget(hash, { documentId, signal });\n if (target.kind === \"presigned-get\") {\n return this.fetchPresigned(hash, target, signal);\n }\n return this.fetchAttachment(hash, target, signal);\n }\n\n /**\n * Asks Switchboard for an authorized download target. The request carries\n * the JWT; the response is runtime-validated before any byte transfer.\n * Public so callers can mint direct URLs (previews, share links) without\n * transferring bytes; `expiresIn` requests a caller-chosen lifetime.\n */\n async getDownloadTarget(\n hash: AttachmentHash,\n options: AttachmentDownloadTargetOptions,\n ): Promise<AttachmentDownloadTarget> {\n const { documentId, expiresIn, signal } = options;\n const expiry =\n expiresIn === undefined\n ? \"\"\n : `&expiresIn=${encodeURIComponent(String(expiresIn))}`;\n const url = `${this.remoteUrl}/attachments/${hash}/download-target?documentId=${encodeURIComponent(documentId)}${expiry}`;\n const headers = await buildAuthHeaders(url, this.jwtHandler);\n const response = await this.fetchFn(url, { signal, headers });\n\n if (response.status === 404) {\n throw new AttachmentNotFound(hash);\n }\n if (!response.ok) {\n throw new AttachmentTransferError(\"download-target\", response.status);\n }\n\n let body: unknown;\n try {\n body = await response.json();\n } catch {\n throw new AttachmentTransferError(\"download-target\");\n }\n return parseAttachmentDownloadTarget(body);\n }\n\n /**\n * Executes a presigned GET with exactly the returned headers and no JWT.\n * A provider 404 means the object is missing despite available metadata\n * (the accepted abandoned-upload trade-off) and surfaces as the same typed\n * not-found error callers already handle.\n */\n private async fetchPresigned(\n hash: AttachmentHash,\n target: AttachmentDownloadTarget,\n signal?: AbortSignal,\n ): Promise<AttachmentResponse> {\n const response = await this.fetchFn(target.url, {\n signal,\n headers: { ...target.headers },\n });\n if (response.status === 404) {\n throw new AttachmentNotFound(hash);\n }\n if (!response.ok) {\n throw new AttachmentTransferError(\"presigned-get\", response.status);\n }\n if (!response.body) {\n throw new Error(\"Response body is null\");\n }\n const metadata = parseMetadata(response);\n return { header: buildHeader(hash, metadata), body: response.body };\n }\n\n private async fetchAttachment(\n hash: AttachmentHash,\n target: AttachmentDownloadTarget,\n signal?: AbortSignal,\n ): Promise<AttachmentResponse> {\n const url = target.url;\n const authHeaders = await buildAuthHeaders(url, this.jwtHandler);\n const headers = { ...target.headers, ...authHeaders };\n\n const response = await this.fetchFn(url, { signal, headers });\n\n if (response.status === 202) {\n const pending = parsePendingExpiry(response);\n if (!pending) {\n throw new Error(\n \"Attachment fetch returned 202 with missing or malformed Attachment-Pending header\",\n );\n }\n throw new AttachmentPending(hash, pending.expiresAtUtc);\n }\n\n if (response.status === 404) {\n throw new AttachmentNotFound(hash);\n }\n if (!response.ok) {\n throw new Error(\n `Attachment fetch failed: ${response.status} ${response.statusText}`,\n );\n }\n if (!response.body) {\n throw new Error(\"Response body is null\");\n }\n\n const metadata = parseMetadata(response);\n return { header: buildHeader(hash, metadata), body: response.body };\n }\n}\n\nfunction buildHeader(\n hash: AttachmentHash,\n metadata: AttachmentMetadata,\n): AttachmentHeader {\n return {\n hash,\n mimeType: metadata.mimeType,\n fileName: metadata.fileName,\n sizeBytes: metadata.sizeBytes,\n extension: metadata.extension,\n status: \"available\",\n source: \"sync\",\n createdAtUtc: metadata.createdAtUtc,\n lastAccessedAtUtc: metadata.lastAccessedAtUtc ?? metadata.createdAtUtc,\n expiresAtUtc: null,\n };\n}\n\nfunction buildPendingHeader(\n hash: AttachmentHash,\n pending: PendingInfo,\n): AttachmentHeader {\n const now = new Date().toISOString();\n return {\n hash,\n mimeType: pending.mimeType,\n fileName: pending.fileName,\n sizeBytes: pending.sizeBytes,\n extension: null,\n status: \"pending\",\n source: \"sync\",\n createdAtUtc: now,\n lastAccessedAtUtc: now,\n expiresAtUtc: pending.expiresAtUtc,\n };\n}\n","import { AttachmentService } from \"../attachment-service.js\";\nimport type { IAttachmentService } from \"../interfaces.js\";\nimport { RemoteAttachmentStore } from \"./remote-attachment-store.js\";\nimport { RemoteAttachmentUploadFactory } from \"./remote-attachment-upload-factory.js\";\nimport {\n RemoteReservationStore,\n type SwitchboardClientConfig,\n} from \"./remote-reservation-store.js\";\n\nexport function createRemoteAttachmentService(\n config: SwitchboardClientConfig,\n): IAttachmentService {\n const reservations = new RemoteReservationStore(config);\n const uploadFactory = new RemoteAttachmentUploadFactory(config);\n const store = new RemoteAttachmentStore(config);\n return new AttachmentService(store, reservations, uploadFactory);\n}\n","import type { IAttachmentTransport } from \"./interfaces.js\";\nimport type { TransportFetchResult } from \"./types.js\";\n\n/**\n * No-op transport for deployments without remote sync.\n * fetch() always returns not-found, announce() and push() are no-ops.\n */\nexport class NullAttachmentTransport implements IAttachmentTransport {\n fetch(): Promise<TransportFetchResult> {\n return Promise.resolve({ kind: \"not-found\" });\n }\n\n announce(): Promise<void> {\n return Promise.resolve();\n }\n\n push(): Promise<void> {\n return Promise.resolve();\n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