@powerhousedao/clint 6.3.0-dev.8 → 6.4.0-next.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (93) hide show
  1. package/dist/build-DZIv63eB.mjs +77 -0
  2. package/dist/build-DZIv63eB.mjs.map +1 -0
  3. package/dist/{build-skills-BnqGyuCH.mjs → build-skills-BNEOn-cl.mjs} +15 -6
  4. package/dist/build-skills-BNEOn-cl.mjs.map +1 -0
  5. package/dist/dist--xzirmg-.mjs +655 -0
  6. package/dist/dist--xzirmg-.mjs.map +1 -0
  7. package/dist/glob-CGjvhxgW.mjs +48 -0
  8. package/dist/glob-CGjvhxgW.mjs.map +1 -0
  9. package/dist/index-C3-HSfKb.d.mts +389 -0
  10. package/dist/index-C3-HSfKb.d.mts.map +1 -0
  11. package/dist/index.d.mts +55 -303
  12. package/dist/index.d.mts.map +1 -1
  13. package/dist/index.mjs +7 -8
  14. package/dist/integrations/mastra/index.d.mts +248 -0
  15. package/dist/integrations/mastra/index.d.mts.map +1 -0
  16. package/dist/integrations/mastra/index.mjs +509 -0
  17. package/dist/integrations/mastra/index.mjs.map +1 -0
  18. package/dist/integrations/powerhouse/index.d.mts +4 -0
  19. package/dist/integrations/powerhouse/index.mjs +3 -0
  20. package/dist/markdown-BUeGwhbR.mjs +1588 -0
  21. package/dist/markdown-BUeGwhbR.mjs.map +1 -0
  22. package/dist/powerhouse-BDnj7kqd.mjs +1922 -0
  23. package/dist/powerhouse-BDnj7kqd.mjs.map +1 -0
  24. package/dist/{proxy-BFR8GScT.mjs → proxy-ji3EHzLn.mjs} +128 -28
  25. package/dist/proxy-ji3EHzLn.mjs.map +1 -0
  26. package/dist/remote-reactor-BQzq4yfO.mjs +69 -0
  27. package/dist/remote-reactor-BQzq4yfO.mjs.map +1 -0
  28. package/dist/{start-b7Mn2cxB.mjs → repl-Czb7u0x_.mjs} +6 -29
  29. package/dist/repl-Czb7u0x_.mjs.map +1 -0
  30. package/dist/runners/cli-runner.d.mts +339 -0
  31. package/dist/runners/cli-runner.d.mts.map +1 -0
  32. package/dist/runners/cli-runner.mjs +324 -0
  33. package/dist/runners/cli-runner.mjs.map +1 -0
  34. package/dist/runners/mastra-runner.d.mts +5 -3
  35. package/dist/runners/mastra-runner.d.mts.map +1 -1
  36. package/dist/runners/mastra-runner.mjs +10 -60
  37. package/dist/runners/mastra-runner.mjs.map +1 -1
  38. package/dist/runners/proxy-runner.d.mts +281 -0
  39. package/dist/runners/proxy-runner.d.mts.map +1 -0
  40. package/dist/runners/proxy-runner.mjs +91 -0
  41. package/dist/runners/proxy-runner.mjs.map +1 -0
  42. package/dist/schema-BEKAZGyT.mjs +47 -0
  43. package/dist/schema-BEKAZGyT.mjs.map +1 -0
  44. package/dist/{src-BebNN3xc.mjs → src-BehwgLP6.mjs} +395 -1481
  45. package/dist/src-BehwgLP6.mjs.map +1 -0
  46. package/dist/start-BHn9LIyX.mjs +37 -0
  47. package/dist/start-BHn9LIyX.mjs.map +1 -0
  48. package/dist/store-CxqB-OrX.mjs +101 -0
  49. package/dist/store-CxqB-OrX.mjs.map +1 -0
  50. package/dist/{stream-DVuufwIj.mjs → stream-BguHx7vC.mjs} +4 -2
  51. package/dist/{stream-DVuufwIj.mjs.map → stream-BguHx7vC.mjs.map} +1 -1
  52. package/dist/testing/index.d.mts +81 -0
  53. package/dist/testing/index.d.mts.map +1 -0
  54. package/dist/testing/index.mjs +131 -0
  55. package/dist/testing/index.mjs.map +1 -0
  56. package/dist/{types-CRkoD-Mm.d.mts → types-CF6GuPJd.d.mts} +241 -261
  57. package/dist/types-CF6GuPJd.d.mts.map +1 -0
  58. package/dist/types-CbHJ-ZnH.d.mts +60 -0
  59. package/dist/types-CbHJ-ZnH.d.mts.map +1 -0
  60. package/package.json +44 -25
  61. package/dist/build-skills-BnqGyuCH.mjs.map +0 -1
  62. package/dist/dist-CUltriBW.mjs +0 -1628
  63. package/dist/dist-CUltriBW.mjs.map +0 -1
  64. package/dist/drive-Bu9zoFrO.mjs +0 -85
  65. package/dist/drive-Bu9zoFrO.mjs.map +0 -1
  66. package/dist/esm-C1DOsF1a.mjs +0 -13140
  67. package/dist/esm-C1DOsF1a.mjs.map +0 -1
  68. package/dist/events-BnwGFTjv.mjs +0 -237
  69. package/dist/events-BnwGFTjv.mjs.map +0 -1
  70. package/dist/folders-BYO1Wqqb.mjs +0 -256
  71. package/dist/folders-BYO1Wqqb.mjs.map +0 -1
  72. package/dist/local-signer-EFzJV3bn.mjs +0 -128
  73. package/dist/local-signer-EFzJV3bn.mjs.map +0 -1
  74. package/dist/markdown-D-sP2zw_.mjs +0 -275
  75. package/dist/markdown-D-sP2zw_.mjs.map +0 -1
  76. package/dist/proxy-BFR8GScT.mjs.map +0 -1
  77. package/dist/proxy-routes-DP3ztsnS.mjs +0 -215
  78. package/dist/proxy-routes-DP3ztsnS.mjs.map +0 -1
  79. package/dist/reactor-C9VIUX1H.mjs +0 -51
  80. package/dist/reactor-C9VIUX1H.mjs.map +0 -1
  81. package/dist/runners/clint-runner.d.mts +0 -398
  82. package/dist/runners/clint-runner.d.mts.map +0 -1
  83. package/dist/runners/clint-runner.mjs +0 -519
  84. package/dist/runners/clint-runner.mjs.map +0 -1
  85. package/dist/services-9E-r0nWl.mjs +0 -999
  86. package/dist/services-9E-r0nWl.mjs.map +0 -1
  87. package/dist/src-BebNN3xc.mjs.map +0 -1
  88. package/dist/start-b7Mn2cxB.mjs.map +0 -1
  89. package/dist/subscriptions-CfiflAsI.mjs +0 -38
  90. package/dist/subscriptions-CfiflAsI.mjs.map +0 -1
  91. package/dist/switchboard-CyvOavqL.mjs +0 -57
  92. package/dist/switchboard-CyvOavqL.mjs.map +0 -1
  93. package/dist/types-CRkoD-Mm.d.mts.map +0 -1
@@ -0,0 +1,655 @@
1
+ import { _ as buildAuthHeaders, d as AttachmentPending, f as AttachmentTransferError, g as SizeMismatch, h as ReservationNotFound, l as AttachmentAlreadyExists, p as HashMismatch, u as AttachmentNotFound, v as createRef, y as parseRef } from "./powerhouse-BDnj7kqd.mjs";
2
+ import "node:fs";
3
+ import "node:path";
4
+ import "node:crypto";
5
+ import "node:fs/promises";
6
+ import "node:stream";
7
+ import "@powerhousedao/reactor";
8
+ import "@powerhousedao/shared/document-model";
9
+ //#region ../reactor-attachments/dist/routing-attachment-service-C88ryRgj.js
10
+ function isRecord$3(value) {
11
+ return typeof value === "object" && value !== null && !Array.isArray(value);
12
+ }
13
+ function parseUrl(value) {
14
+ if (typeof value !== "string" || value.length === 0) throw new Error("Attachment target URL must be a non-empty string");
15
+ if (value.trim() !== value || hasForbiddenUrlWhitespace(value)) throw new Error("Attachment target URL must not contain raw whitespace");
16
+ let parsed;
17
+ try {
18
+ parsed = new URL(value);
19
+ } catch {
20
+ throw new Error("Attachment target URL is invalid");
21
+ }
22
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:" || parsed.username !== "" || parsed.password !== "") throw new Error("Attachment target URL must be HTTP(S) and must not contain credentials");
23
+ return value;
24
+ }
25
+ function parseHeaders(value) {
26
+ if (!isRecord$3(value)) throw new Error("Attachment target headers must be an object");
27
+ const headers = Object.create(null);
28
+ const headerName = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
29
+ for (const [name, headerValue] of Object.entries(value)) {
30
+ if (!headerName.test(name)) throw new Error(`Attachment target header name is invalid: ${name}`);
31
+ if (typeof headerValue !== "string" || hasForbiddenHeaderCharacter(headerValue)) throw new Error(`Attachment target header value is invalid: ${name}`);
32
+ headers[name] = headerValue;
33
+ }
34
+ return headers;
35
+ }
36
+ function hasForbiddenHeaderCharacter(value) {
37
+ for (let index = 0; index < value.length; index++) {
38
+ const code = value.charCodeAt(index);
39
+ if (code <= 8 || code >= 10 && code <= 31 || code === 127 || code > 255) return true;
40
+ }
41
+ return false;
42
+ }
43
+ function hasForbiddenUrlWhitespace(value) {
44
+ for (let index = 0; index < value.length; index++) {
45
+ const code = value.charCodeAt(index);
46
+ if (code <= 32 || code === 127) return true;
47
+ }
48
+ return false;
49
+ }
50
+ function parseExpiry(value, required) {
51
+ if (value === void 0 && !required) return void 0;
52
+ if (typeof value !== "string") throw new Error("Attachment target expiry must be an ISO 8601 UTC string");
53
+ const parsed = new Date(value);
54
+ if (Number.isNaN(parsed.getTime()) || parsed.toISOString() !== value) throw new Error("Attachment target expiry must be an ISO 8601 UTC string");
55
+ return value;
56
+ }
57
+ function parseAttachmentUploadTarget(value) {
58
+ if (!isRecord$3(value)) throw new Error("Attachment upload target must be an object");
59
+ const url = parseUrl(value.url);
60
+ const headers = parseHeaders(value.headers);
61
+ switch (value.kind) {
62
+ case "switchboard":
63
+ if (value.method !== "PUT") throw new Error("Switchboard upload target method must be PUT");
64
+ return {
65
+ kind: "switchboard",
66
+ method: "PUT",
67
+ url,
68
+ headers,
69
+ ...value.expiresAtUtc === void 0 ? {} : { expiresAtUtc: parseExpiry(value.expiresAtUtc, false) }
70
+ };
71
+ case "presigned-put":
72
+ if (value.method !== "PUT") throw new Error("Presigned upload target method must be PUT");
73
+ return {
74
+ kind: "presigned-put",
75
+ method: "PUT",
76
+ url,
77
+ headers,
78
+ expiresAtUtc: parseExpiry(value.expiresAtUtc, true)
79
+ };
80
+ default: throw new Error("Attachment upload target kind is unknown");
81
+ }
82
+ }
83
+ function parseAttachmentDownloadTarget(value) {
84
+ if (!isRecord$3(value)) throw new Error("Attachment download target must be an object");
85
+ const url = parseUrl(value.url);
86
+ const headers = parseHeaders(value.headers);
87
+ switch (value.kind) {
88
+ case "switchboard":
89
+ if (value.method !== "GET") throw new Error("Switchboard download target method must be GET");
90
+ return {
91
+ kind: "switchboard",
92
+ method: "GET",
93
+ url,
94
+ headers,
95
+ ...value.expiresAtUtc === void 0 ? {} : { expiresAtUtc: parseExpiry(value.expiresAtUtc, false) }
96
+ };
97
+ case "presigned-get":
98
+ if (value.method !== "GET") throw new Error("Presigned download target method must be GET");
99
+ return {
100
+ kind: "presigned-get",
101
+ method: "GET",
102
+ url,
103
+ headers,
104
+ expiresAtUtc: parseExpiry(value.expiresAtUtc, true)
105
+ };
106
+ default: throw new Error("Attachment download target kind is unknown");
107
+ }
108
+ }
109
+ const CLIENT_HASH_PATTERN = /^[a-f0-9]{64}$/;
110
+ var AttachmentService = class {
111
+ store;
112
+ reservations;
113
+ uploadFactory;
114
+ backend;
115
+ constructor(store, reservations, uploadFactory, backend) {
116
+ this.store = store;
117
+ this.reservations = reservations;
118
+ this.uploadFactory = uploadFactory;
119
+ this.backend = backend;
120
+ }
121
+ async reserve(options) {
122
+ if (options.clientHash !== void 0) return this.reserveHashFirst(options);
123
+ if (this.backend?.kind === "s3") throw new Error("S3 attachment reservations require a client hash");
124
+ const reservation = await this.reservations.create(options);
125
+ return this.uploadFactory.createUpload(reservation);
126
+ }
127
+ async stat(ref, options) {
128
+ const { hash } = parseRef(ref);
129
+ return options?.documentId === void 0 ? this.store.stat(hash) : this.store.stat(hash, options.documentId);
130
+ }
131
+ async get(ref, options) {
132
+ const { hash } = parseRef(ref);
133
+ const normalized = options === void 0 || options instanceof AbortSignal ? { signal: options } : options;
134
+ return normalized.documentId === void 0 ? this.store.get(hash, normalized.signal) : this.store.get(hash, normalized.signal, normalized.documentId);
135
+ }
136
+ getDownloadTarget(ref, options) {
137
+ const { hash } = parseRef(ref);
138
+ const getTarget = this.store.getDownloadTarget?.bind(this.store);
139
+ if (getTarget === void 0) return Promise.reject(/* @__PURE__ */ new Error("Download targets are not supported by this attachment store: only remote stores negotiate direct URLs"));
140
+ return getTarget(hash, options);
141
+ }
142
+ async reserveHashFirst(options) {
143
+ const normalized = options.clientHash.toLowerCase();
144
+ if (!CLIENT_HASH_PATTERN.test(normalized)) throw new Error(`clientHash must be a 64-character lowercase hex string, got: ${options.clientHash}`);
145
+ 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");
146
+ const normalizedOptions = {
147
+ ...options,
148
+ clientHash: normalized
149
+ };
150
+ let existingHeader = null;
151
+ try {
152
+ existingHeader = await this.store.stat(normalized);
153
+ } catch (err) {
154
+ if (!(err instanceof AttachmentNotFound) && !(err instanceof AttachmentPending)) throw err;
155
+ }
156
+ if (existingHeader !== null) {
157
+ if (this.backend?.kind === "s3") {
158
+ if (await this.backend.exists(normalized)) throw new AttachmentAlreadyExists(normalized, createRef(normalized));
159
+ } else if (existingHeader.status === "available") throw new AttachmentAlreadyExists(normalized, createRef(normalized));
160
+ }
161
+ const reservation = await this.reservations.create(normalizedOptions);
162
+ if (this.backend?.kind !== "s3") return this.uploadFactory.createUpload(reservation);
163
+ const uploadTarget = await this.backend.prepareUploadTarget(reservation);
164
+ return this.uploadFactory.createUpload({
165
+ ...reservation,
166
+ uploadTarget
167
+ });
168
+ }
169
+ };
170
+ /** Tells a Blob from a stream by shape: `instanceof Blob` misses other realms and polyfills. */
171
+ function isBlob(data) {
172
+ return !("getReader" in data);
173
+ }
174
+ /**
175
+ * The default transport. Ignores `onProgress` — fetch has no upload-side
176
+ * progress event, and silence is how a transport reports that bytes are
177
+ * unobservable.
178
+ */
179
+ function createFetchUploadTransport(fetchFn) {
180
+ return (request) => fetchFn(request.url, {
181
+ method: request.method,
182
+ headers: request.headers,
183
+ body: request.body,
184
+ ...request.signal ? { signal: request.signal } : {}
185
+ });
186
+ }
187
+ function isRecord$2(value) {
188
+ return typeof value === "object" && value !== null && !Array.isArray(value);
189
+ }
190
+ function deriveExtension(fileName) {
191
+ const idx = fileName.lastIndexOf(".");
192
+ if (idx <= 0 || idx === fileName.length - 1) return null;
193
+ return fileName.slice(idx + 1).toLowerCase();
194
+ }
195
+ function isReservationBase(value) {
196
+ if (!isRecord$2(value)) return false;
197
+ if (typeof value.reservationId !== "string") return false;
198
+ if (typeof value.mimeType !== "string") return false;
199
+ if (typeof value.fileName !== "string") return false;
200
+ if (value.extension !== null && typeof value.extension !== "string") return false;
201
+ if (typeof value.createdAtUtc !== "string") return false;
202
+ if (typeof value.expiresAtUtc !== "string") return false;
203
+ return true;
204
+ }
205
+ function isReservation(value) {
206
+ if (!isReservationBase(value)) return false;
207
+ if (value.clientHash !== void 0 && value.clientHash !== null && typeof value.clientHash !== "string") return false;
208
+ if (value.sizeBytes !== void 0 && value.sizeBytes !== null && typeof value.sizeBytes !== "number") return false;
209
+ return true;
210
+ }
211
+ var RemoteReservationStore = class {
212
+ remoteUrl;
213
+ jwtHandler;
214
+ fetchFn;
215
+ constructor(config) {
216
+ this.remoteUrl = config.remoteUrl;
217
+ this.jwtHandler = config.jwtHandler;
218
+ this.fetchFn = (config.fetchFn ?? globalThis.fetch).bind(globalThis);
219
+ }
220
+ async create(options) {
221
+ const url = `${this.remoteUrl}/attachments/reservations`;
222
+ const authHeaders = await buildAuthHeaders(url, this.jwtHandler);
223
+ const extension = options.extension ?? deriveExtension(options.fileName);
224
+ const bodyObj = {
225
+ mimeType: options.mimeType,
226
+ fileName: options.fileName,
227
+ extension
228
+ };
229
+ if (options.clientHash !== void 0) bodyObj.clientHash = options.clientHash;
230
+ if (options.sizeBytes !== void 0) bodyObj.sizeBytes = options.sizeBytes;
231
+ const response = await this.fetchFn(url, {
232
+ method: "POST",
233
+ headers: {
234
+ ...authHeaders,
235
+ "Content-Type": "application/json"
236
+ },
237
+ body: JSON.stringify(bodyObj)
238
+ });
239
+ if (response.status === 409) {
240
+ let body;
241
+ try {
242
+ body = await response.json();
243
+ } catch {
244
+ throw new Error(`Reservation create failed: ${response.status} ${response.statusText}`);
245
+ }
246
+ if (isRecord$2(body) && body.error === "already_exists" && options.clientHash !== void 0) {
247
+ let ref;
248
+ if (typeof body.ref === "string") try {
249
+ parseRef(body.ref);
250
+ ref = body.ref;
251
+ } catch {
252
+ ref = createRef(options.clientHash);
253
+ }
254
+ else ref = createRef(options.clientHash);
255
+ throw new AttachmentAlreadyExists(options.clientHash, ref);
256
+ }
257
+ throw new Error(`Reservation create failed: ${response.status} ${response.statusText}`);
258
+ }
259
+ if (!response.ok) throw new Error(`Reservation create failed: ${response.status} ${response.statusText}`);
260
+ let json;
261
+ try {
262
+ json = await response.json();
263
+ } catch {
264
+ throw new Error("Reservation create returned non-JSON response");
265
+ }
266
+ if (typeof json !== "object" || json === null || typeof json.reservationId !== "string" || json.reservationId.length === 0) throw new Error("Reservation create returned a payload missing a non-empty reservationId string");
267
+ const body = json;
268
+ const now = /* @__PURE__ */ new Date();
269
+ return {
270
+ reservationId: body.reservationId,
271
+ mimeType: options.mimeType,
272
+ fileName: options.fileName,
273
+ extension,
274
+ createdAtUtc: body.createdAtUtc ?? now.toISOString(),
275
+ expiresAtUtc: body.expiresAtUtc ?? new Date(now.getTime() + 864e5).toISOString(),
276
+ clientHash: options.clientHash ?? null,
277
+ sizeBytes: options.sizeBytes ?? null,
278
+ ...body.uploadTarget === void 0 ? {} : { uploadTarget: parseAttachmentUploadTarget(body.uploadTarget) }
279
+ };
280
+ }
281
+ async get(reservationId) {
282
+ const url = `${this.remoteUrl}/attachments/reservations/${encodeURIComponent(reservationId)}`;
283
+ const authHeaders = await buildAuthHeaders(url, this.jwtHandler);
284
+ const response = await this.fetchFn(url, { headers: authHeaders });
285
+ if (response.status === 404) throw new ReservationNotFound(reservationId);
286
+ if (!response.ok) throw new Error(`Reservation get failed: ${response.status} ${response.statusText}`);
287
+ let parsed;
288
+ try {
289
+ parsed = await response.json();
290
+ } catch {
291
+ throw new Error("Reservation get returned non-JSON response");
292
+ }
293
+ if (!isReservation(parsed)) throw new Error("Reservation get returned a payload that does not match the Reservation shape");
294
+ return {
295
+ reservationId: parsed.reservationId,
296
+ mimeType: parsed.mimeType,
297
+ fileName: parsed.fileName,
298
+ extension: parsed.extension,
299
+ createdAtUtc: parsed.createdAtUtc,
300
+ expiresAtUtc: parsed.expiresAtUtc,
301
+ clientHash: parsed.clientHash ?? null,
302
+ sizeBytes: parsed.sizeBytes ?? null,
303
+ ...parsed.uploadTarget === void 0 ? {} : { uploadTarget: parseAttachmentUploadTarget(parsed.uploadTarget) }
304
+ };
305
+ }
306
+ async delete(reservationId) {
307
+ const url = `${this.remoteUrl}/attachments/reservations/${encodeURIComponent(reservationId)}`;
308
+ const authHeaders = await buildAuthHeaders(url, this.jwtHandler);
309
+ const response = await this.fetchFn(url, {
310
+ method: "DELETE",
311
+ headers: authHeaders
312
+ });
313
+ if (!response.ok && response.status !== 404 && response.status !== 410) throw new Error(`Reservation delete failed: ${response.status} ${response.statusText}`);
314
+ }
315
+ deleteExpired() {
316
+ return Promise.reject(/* @__PURE__ */ new Error("RemoteReservationStore.deleteExpired is not supported"));
317
+ }
318
+ };
319
+ function isRecord$1(value) {
320
+ return typeof value === "object" && value !== null && !Array.isArray(value);
321
+ }
322
+ /**
323
+ * A Blob goes out untouched, so a File streams from disk. A stream is
324
+ * buffered: browsers don't portably accept a ReadableStream request body.
325
+ */
326
+ async function toBody(data) {
327
+ return isBlob(data) ? data : new Response(data).blob();
328
+ }
329
+ var RemoteAttachmentUpload = class {
330
+ reservationId;
331
+ ref;
332
+ expiresAtUtc;
333
+ uploadTarget;
334
+ reservation;
335
+ remoteUrl;
336
+ jwtHandler;
337
+ uploadTransport;
338
+ constructor(reservation, config) {
339
+ this.reservationId = reservation.reservationId;
340
+ this.ref = reservation.clientHash !== null ? createRef(reservation.clientHash) : null;
341
+ this.expiresAtUtc = reservation.expiresAtUtc;
342
+ if (reservation.uploadTarget) this.uploadTarget = reservation.uploadTarget;
343
+ this.reservation = reservation;
344
+ this.remoteUrl = config.remoteUrl;
345
+ this.jwtHandler = config.jwtHandler;
346
+ this.uploadTransport = config.fetchFn ? createFetchUploadTransport(config.fetchFn.bind(globalThis)) : config.uploadTransport ?? createFetchUploadTransport(globalThis.fetch.bind(globalThis));
347
+ }
348
+ async send(data, options) {
349
+ if (this.uploadTarget?.kind === "presigned-put") return this.sendPresigned(this.uploadTarget, data, options);
350
+ const url = `${this.remoteUrl}/attachments/reservations/${this.reservationId}`;
351
+ const authHeaders = await buildAuthHeaders(url, this.jwtHandler);
352
+ const body = await toBody(data);
353
+ const response = await this.uploadTransport({
354
+ url,
355
+ method: "PUT",
356
+ headers: {
357
+ ...authHeaders,
358
+ "Content-Type": "application/octet-stream"
359
+ },
360
+ body,
361
+ ...options?.onProgress ? { onProgress: (loaded, total) => options.onProgress?.(loaded, total) } : {},
362
+ ...options?.signal ? { signal: options.signal } : {}
363
+ });
364
+ if (response.status === 422) {
365
+ let errorBody;
366
+ try {
367
+ errorBody = await response.json();
368
+ } catch {
369
+ throw new Error(`Attachment upload failed: ${response.status} ${response.statusText}`);
370
+ }
371
+ if (isRecord$1(errorBody)) {
372
+ if (errorBody.error === "hash_mismatch" && typeof errorBody.claimed === "string" && typeof errorBody.actual === "string") throw new HashMismatch(errorBody.claimed, errorBody.actual);
373
+ if (errorBody.error === "size_mismatch" && typeof errorBody.declared === "number" && typeof errorBody.actual === "number") throw new SizeMismatch(errorBody.declared, errorBody.actual);
374
+ }
375
+ throw new Error(`Attachment upload failed: ${response.status} ${response.statusText}`);
376
+ }
377
+ if (!response.ok) throw new Error(`Attachment upload failed: ${response.status} ${response.statusText}`);
378
+ return await response.json();
379
+ }
380
+ /**
381
+ * Direct provider upload: PUT the bytes to the presigned URL with exactly
382
+ * the returned headers — never the Switchboard JWT — and treat any 2xx as
383
+ * final success with no follow-up control request. The result is
384
+ * synthesized from the hash-first reservation, which is the only path that
385
+ * can produce a presigned target.
386
+ */
387
+ async sendPresigned(target, data, options) {
388
+ if (this.reservation.clientHash === null || this.ref === null) throw new Error("Presigned upload targets require a hash-first reservation");
389
+ const body = await toBody(data);
390
+ const response = await this.uploadTransport({
391
+ url: target.url,
392
+ method: target.method,
393
+ headers: { ...target.headers },
394
+ body,
395
+ ...options?.onProgress ? { onProgress: (loaded, total) => options.onProgress?.(loaded, total) } : {},
396
+ ...options?.signal ? { signal: options.signal } : {}
397
+ });
398
+ if (!response.ok) throw new AttachmentTransferError("presigned-put", response.status);
399
+ const hash = this.reservation.clientHash;
400
+ const now = (/* @__PURE__ */ new Date()).toISOString();
401
+ return {
402
+ hash,
403
+ ref: this.ref,
404
+ header: {
405
+ hash,
406
+ mimeType: this.reservation.mimeType,
407
+ fileName: this.reservation.fileName,
408
+ sizeBytes: this.reservation.sizeBytes ?? body.size,
409
+ extension: this.reservation.extension,
410
+ status: "available",
411
+ source: "local",
412
+ createdAtUtc: this.reservation.createdAtUtc || now,
413
+ lastAccessedAtUtc: now,
414
+ expiresAtUtc: null
415
+ }
416
+ };
417
+ }
418
+ };
419
+ var RemoteAttachmentUploadFactory = class {
420
+ config;
421
+ constructor(config) {
422
+ this.config = config;
423
+ }
424
+ createUpload(reservation) {
425
+ return new RemoteAttachmentUpload(reservation, this.config);
426
+ }
427
+ };
428
+ const MISSING_DOCUMENT_ID = "Remote attachment reads require the documentId whose operations reference the attachment";
429
+ function isRecord(value) {
430
+ return typeof value === "object" && value !== null && !Array.isArray(value);
431
+ }
432
+ function isAttachmentMetadata(value) {
433
+ if (!isRecord(value)) return false;
434
+ if (typeof value.mimeType !== "string") return false;
435
+ if (typeof value.fileName !== "string") return false;
436
+ if (typeof value.sizeBytes !== "number" || !Number.isFinite(value.sizeBytes) || value.sizeBytes < 0) return false;
437
+ if (value.extension !== null && typeof value.extension !== "string") return false;
438
+ if (typeof value.createdAtUtc !== "string") return false;
439
+ if (value.lastAccessedAtUtc !== void 0 && typeof value.lastAccessedAtUtc !== "string") return false;
440
+ return true;
441
+ }
442
+ function contentTypeFallback(response) {
443
+ const contentLength = response.headers.get("Content-Length");
444
+ if (contentLength === null) throw new Error("Switchboard response missing both Attachment-Metadata and Content-Length headers");
445
+ const sizeBytes = Number(contentLength);
446
+ if (!Number.isInteger(sizeBytes) || sizeBytes < 0) throw new Error(`Switchboard response has invalid Content-Length header: ${JSON.stringify(contentLength)}`);
447
+ const lastModified = response.headers.get("Last-Modified");
448
+ const dateHeader = response.headers.get("Date");
449
+ const createdAtUtc = lastModified ? new Date(lastModified).toISOString() : dateHeader ? new Date(dateHeader).toISOString() : (/* @__PURE__ */ new Date()).toISOString();
450
+ return {
451
+ mimeType: response.headers.get("Content-Type") ?? "application/octet-stream",
452
+ fileName: "unknown",
453
+ sizeBytes,
454
+ extension: null,
455
+ createdAtUtc,
456
+ lastAccessedAtUtc: createdAtUtc
457
+ };
458
+ }
459
+ function parseMetadata(response) {
460
+ let fallbackCache;
461
+ const fallback = () => {
462
+ if (fallbackCache === void 0) fallbackCache = contentTypeFallback(response);
463
+ return fallbackCache;
464
+ };
465
+ const metaHeader = response.headers.get("Attachment-Metadata");
466
+ if (metaHeader) try {
467
+ const parsed = JSON.parse(metaHeader);
468
+ if (isRecord(parsed)) {
469
+ if (parsed.extension === void 0) parsed.extension = null;
470
+ if (parsed.createdAtUtc === void 0) parsed.createdAtUtc = fallback().createdAtUtc;
471
+ if (parsed.lastAccessedAtUtc === void 0) parsed.lastAccessedAtUtc = fallback().lastAccessedAtUtc;
472
+ }
473
+ if (isAttachmentMetadata(parsed)) return parsed;
474
+ } catch {}
475
+ return fallback();
476
+ }
477
+ function parsePendingExpiry(response) {
478
+ const header = response.headers.get("Attachment-Pending");
479
+ if (!header) return null;
480
+ try {
481
+ const parsed = JSON.parse(header);
482
+ if (!isRecord(parsed)) return null;
483
+ if (typeof parsed.expiresAtUtc !== "string") return null;
484
+ const result = { expiresAtUtc: parsed.expiresAtUtc };
485
+ if (typeof parsed.mimeType === "string") result.mimeType = parsed.mimeType;
486
+ if (typeof parsed.fileName === "string") result.fileName = parsed.fileName;
487
+ if (typeof parsed.sizeBytes === "number" && Number.isFinite(parsed.sizeBytes) && parsed.sizeBytes >= 0) result.sizeBytes = parsed.sizeBytes;
488
+ return result;
489
+ } catch {
490
+ return null;
491
+ }
492
+ }
493
+ function parsePendingHeader(response) {
494
+ const partial = parsePendingExpiry(response);
495
+ if (!partial) return null;
496
+ if (typeof partial.mimeType !== "string" || typeof partial.fileName !== "string" || partial.sizeBytes === void 0) return null;
497
+ return {
498
+ expiresAtUtc: partial.expiresAtUtc,
499
+ mimeType: partial.mimeType,
500
+ fileName: partial.fileName,
501
+ sizeBytes: partial.sizeBytes
502
+ };
503
+ }
504
+ var RemoteAttachmentStore = class {
505
+ remoteUrl;
506
+ jwtHandler;
507
+ fetchFn;
508
+ constructor(config) {
509
+ this.remoteUrl = config.remoteUrl;
510
+ this.jwtHandler = config.jwtHandler;
511
+ this.fetchFn = (config.fetchFn ?? globalThis.fetch).bind(globalThis);
512
+ }
513
+ /**
514
+ * Get attachment metadata. Normally returns a pending AttachmentHeader
515
+ * (status: 'pending') when the server responds 202 with a full
516
+ * Attachment-Pending header. When only expiresAtUtc is present in the
517
+ * header (degraded wire), throws AttachmentPending instead -- the
518
+ * AttachmentPending throw is the degraded-wire case.
519
+ */
520
+ async stat(hash, documentId) {
521
+ if (documentId === void 0) throw new AttachmentNotFound(hash);
522
+ const url = `${this.remoteUrl}/attachments/${hash}?documentId=${encodeURIComponent(documentId)}`;
523
+ const authHeaders = await buildAuthHeaders(url, this.jwtHandler);
524
+ const response = await this.fetchFn(url, {
525
+ method: "HEAD",
526
+ headers: authHeaders
527
+ });
528
+ if (response.status === 202) {
529
+ const fullPending = parsePendingHeader(response);
530
+ if (fullPending) return buildPendingHeader(hash, fullPending);
531
+ const partial = parsePendingExpiry(response);
532
+ if (partial) throw new AttachmentPending(hash, partial.expiresAtUtc);
533
+ throw new Error("Attachment stat returned 202 with missing or malformed Attachment-Pending header");
534
+ }
535
+ if (response.status === 404) throw new AttachmentNotFound(hash);
536
+ if (!response.ok) throw new Error(`Attachment stat failed: ${response.status} ${response.statusText}`);
537
+ return buildHeader(hash, parseMetadata(response));
538
+ }
539
+ async get(hash, signal, documentId) {
540
+ if (documentId === void 0) throw new Error(MISSING_DOCUMENT_ID);
541
+ const target = await this.getDownloadTarget(hash, {
542
+ documentId,
543
+ signal
544
+ });
545
+ if (target.kind === "presigned-get") return this.fetchPresigned(hash, target, signal);
546
+ return this.fetchAttachment(hash, target, signal);
547
+ }
548
+ /**
549
+ * Asks Switchboard for an authorized download target. The request carries
550
+ * the JWT; the response is runtime-validated before any byte transfer.
551
+ * Public so callers can mint direct URLs (previews, share links) without
552
+ * transferring bytes; `expiresIn` requests a caller-chosen lifetime.
553
+ */
554
+ async getDownloadTarget(hash, options) {
555
+ const { documentId, expiresIn, signal } = options;
556
+ const expiry = expiresIn === void 0 ? "" : `&expiresIn=${encodeURIComponent(String(expiresIn))}`;
557
+ const url = `${this.remoteUrl}/attachments/${hash}/download-target?documentId=${encodeURIComponent(documentId)}${expiry}`;
558
+ const headers = await buildAuthHeaders(url, this.jwtHandler);
559
+ const response = await this.fetchFn(url, {
560
+ signal,
561
+ headers
562
+ });
563
+ if (response.status === 404) throw new AttachmentNotFound(hash);
564
+ if (!response.ok) throw new AttachmentTransferError("download-target", response.status);
565
+ let body;
566
+ try {
567
+ body = await response.json();
568
+ } catch {
569
+ throw new AttachmentTransferError("download-target");
570
+ }
571
+ return parseAttachmentDownloadTarget(body);
572
+ }
573
+ /**
574
+ * Executes a presigned GET with exactly the returned headers and no JWT.
575
+ * A provider 404 means the object is missing despite available metadata
576
+ * (the accepted abandoned-upload trade-off) and surfaces as the same typed
577
+ * not-found error callers already handle.
578
+ */
579
+ async fetchPresigned(hash, target, signal) {
580
+ const response = await this.fetchFn(target.url, {
581
+ signal,
582
+ headers: { ...target.headers }
583
+ });
584
+ if (response.status === 404) throw new AttachmentNotFound(hash);
585
+ if (!response.ok) throw new AttachmentTransferError("presigned-get", response.status);
586
+ if (!response.body) throw new Error("Response body is null");
587
+ return {
588
+ header: buildHeader(hash, parseMetadata(response)),
589
+ body: response.body
590
+ };
591
+ }
592
+ async fetchAttachment(hash, target, signal) {
593
+ const url = target.url;
594
+ const authHeaders = await buildAuthHeaders(url, this.jwtHandler);
595
+ const headers = {
596
+ ...target.headers,
597
+ ...authHeaders
598
+ };
599
+ const response = await this.fetchFn(url, {
600
+ signal,
601
+ headers
602
+ });
603
+ if (response.status === 202) {
604
+ const pending = parsePendingExpiry(response);
605
+ if (!pending) throw new Error("Attachment fetch returned 202 with missing or malformed Attachment-Pending header");
606
+ throw new AttachmentPending(hash, pending.expiresAtUtc);
607
+ }
608
+ if (response.status === 404) throw new AttachmentNotFound(hash);
609
+ if (!response.ok) throw new Error(`Attachment fetch failed: ${response.status} ${response.statusText}`);
610
+ if (!response.body) throw new Error("Response body is null");
611
+ return {
612
+ header: buildHeader(hash, parseMetadata(response)),
613
+ body: response.body
614
+ };
615
+ }
616
+ };
617
+ function buildHeader(hash, metadata) {
618
+ return {
619
+ hash,
620
+ mimeType: metadata.mimeType,
621
+ fileName: metadata.fileName,
622
+ sizeBytes: metadata.sizeBytes,
623
+ extension: metadata.extension,
624
+ status: "available",
625
+ source: "sync",
626
+ createdAtUtc: metadata.createdAtUtc,
627
+ lastAccessedAtUtc: metadata.lastAccessedAtUtc ?? metadata.createdAtUtc,
628
+ expiresAtUtc: null
629
+ };
630
+ }
631
+ function buildPendingHeader(hash, pending) {
632
+ const now = (/* @__PURE__ */ new Date()).toISOString();
633
+ return {
634
+ hash,
635
+ mimeType: pending.mimeType,
636
+ fileName: pending.fileName,
637
+ sizeBytes: pending.sizeBytes,
638
+ extension: null,
639
+ status: "pending",
640
+ source: "sync",
641
+ createdAtUtc: now,
642
+ lastAccessedAtUtc: now,
643
+ expiresAtUtc: pending.expiresAtUtc
644
+ };
645
+ }
646
+ function createRemoteAttachmentService(config) {
647
+ const reservations = new RemoteReservationStore(config);
648
+ const uploadFactory = new RemoteAttachmentUploadFactory(config);
649
+ return new AttachmentService(new RemoteAttachmentStore(config), reservations, uploadFactory);
650
+ }
651
+ "0".repeat(64);
652
+ //#endregion
653
+ export { createRemoteAttachmentService };
654
+
655
+ //# sourceMappingURL=dist--xzirmg-.mjs.map