@lumeweb/sia-testing 0.0.0-stage → 0.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (90) hide show
  1. package/LICENSE +9 -0
  2. package/README.md +202 -2
  3. package/dist/esm/client.d.ts +8 -0
  4. package/dist/esm/client.js +6 -0
  5. package/dist/esm/http.d.ts +3 -0
  6. package/dist/esm/http.js +3 -0
  7. package/dist/esm/mock.d.ts +8 -0
  8. package/dist/esm/mock.js +7 -0
  9. package/dist/esm/model/index.js +509 -0
  10. package/dist/esm/model/state.js +188 -0
  11. package/dist/esm/msw.d.ts +2 -0
  12. package/dist/esm/msw.js +3 -0
  13. package/dist/esm/node.d.ts +4 -0
  14. package/dist/esm/node.js +4 -0
  15. package/dist/esm/node_modules/.pnpm/@noble_hashes@2.4.0/node_modules/@noble/hashes/_md.js +169 -0
  16. package/dist/esm/node_modules/.pnpm/@noble_hashes@2.4.0/node_modules/@noble/hashes/_u64.js +12 -0
  17. package/dist/esm/node_modules/.pnpm/@noble_hashes@2.4.0/node_modules/@noble/hashes/sha2.js +199 -0
  18. package/dist/esm/node_modules/.pnpm/@noble_hashes@2.4.0/node_modules/@noble/hashes/utils.js +220 -0
  19. package/dist/esm/sdk/abort.js +23 -0
  20. package/dist/esm/sdk/control.js +129 -0
  21. package/dist/esm/sdk/index.js +454 -0
  22. package/dist/esm/sdk/link.js +55 -0
  23. package/dist/esm/sdk/object.js +24 -0
  24. package/dist/esm/sdk/payload-store.d.ts +9 -0
  25. package/dist/esm/sdk/payload-store.js +67 -0
  26. package/dist/esm/sdk/state.js +74 -0
  27. package/dist/esm/testing/application-client.d.ts +8 -0
  28. package/dist/esm/testing/application-client.js +295 -0
  29. package/dist/esm/testing/application-metadata.js +17 -0
  30. package/dist/esm/testing/application-transport.js +363 -0
  31. package/dist/esm/testing/auth-client.d.ts +20 -0
  32. package/dist/esm/testing/auth-client.js +63 -0
  33. package/dist/esm/testing/authentication.js +48 -0
  34. package/dist/esm/testing/byte-view.js +28 -0
  35. package/dist/esm/testing/chunked-files.d.ts +12 -0
  36. package/dist/esm/testing/chunked-files.js +50 -0
  37. package/dist/esm/testing/client.d.ts +8 -0
  38. package/dist/esm/testing/client.js +105 -0
  39. package/dist/esm/testing/controls.d.ts +44 -0
  40. package/dist/esm/testing/controls.js +255 -0
  41. package/dist/esm/testing/diagnostics.js +55 -0
  42. package/dist/esm/testing/files.d.ts +9 -0
  43. package/dist/esm/testing/files.js +86 -0
  44. package/dist/esm/testing/http-body.js +33 -0
  45. package/dist/esm/testing/http.d.ts +14 -0
  46. package/dist/esm/testing/http.js +181 -0
  47. package/dist/esm/testing/live/agent.d.ts +1 -0
  48. package/dist/esm/testing/live/agent.js +211 -0
  49. package/dist/esm/testing/live/approval.js +42 -0
  50. package/dist/esm/testing/live/cleanup.js +74 -0
  51. package/dist/esm/testing/live/journal.js +180 -0
  52. package/dist/esm/testing/live/lease.js +56 -0
  53. package/dist/esm/testing/live/private-files.js +50 -0
  54. package/dist/esm/testing/live/process.js +208 -0
  55. package/dist/esm/testing/live/profile.js +214 -0
  56. package/dist/esm/testing/live/recovery.js +164 -0
  57. package/dist/esm/testing/live/resource-limits.js +9 -0
  58. package/dist/esm/testing/live/run.js +390 -0
  59. package/dist/esm/testing/live/session.js +93 -0
  60. package/dist/esm/testing/live/types.d.ts +8 -0
  61. package/dist/esm/testing/mock.d.ts +8 -0
  62. package/dist/esm/testing/mock.js +1364 -0
  63. package/dist/esm/testing/msw.d.ts +21 -0
  64. package/dist/esm/testing/msw.js +61 -0
  65. package/dist/esm/testing/mutations.d.ts +59 -0
  66. package/dist/esm/testing/mutations.js +58 -0
  67. package/dist/esm/testing/node-payload-store.js +353 -0
  68. package/dist/esm/testing/node.d.ts +40 -0
  69. package/dist/esm/testing/node.js +148 -0
  70. package/dist/esm/testing/owner-client.d.ts +9 -0
  71. package/dist/esm/testing/owner-client.js +101 -0
  72. package/dist/esm/testing/owner-shares.js +80 -0
  73. package/dist/esm/testing/packed.d.ts +46 -0
  74. package/dist/esm/testing/packed.js +326 -0
  75. package/dist/esm/testing/reader-lifetime.js +40 -0
  76. package/dist/esm/testing/reply-loss.js +14 -0
  77. package/dist/esm/testing/runtime.d.ts +7 -0
  78. package/dist/esm/testing/runtime.js +13 -0
  79. package/dist/esm/testing/sdk-upload.d.ts +45 -0
  80. package/dist/esm/testing/sdk-upload.js +198 -0
  81. package/dist/esm/testing/streaming-source.js +72 -0
  82. package/dist/esm/testing/transport.d.ts +22 -0
  83. package/dist/esm/testing/transport.js +238 -0
  84. package/dist/esm/testing/types.d.ts +276 -0
  85. package/dist/esm/vitest.d.ts +23 -0
  86. package/dist/esm/vitest.js +34 -0
  87. package/docs/live-auth.md +154 -0
  88. package/docs/live-runs.md +188 -0
  89. package/docs/mock-contracts.md +647 -0
  90. package/package.json +91 -3
@@ -0,0 +1,1364 @@
1
+ import { boundedByteView } from "./byte-view.js";
2
+ import { createIndexdModel } from "../model/index.js";
3
+ import { withAbort } from "../sdk/abort.js";
4
+ import { createMockNetwork } from "../sdk/index.js";
5
+ import { bytesFixture, digest, readFixture } from "./files.js";
6
+ import { collectPayload } from "./streaming-source.js";
7
+ import { snapshotApplicationMetadata } from "./application-metadata.js";
8
+ import { createPackedSdk } from "./packed.js";
9
+ import { createUploadSdk } from "./sdk-upload.js";
10
+ import { invalidInput } from "./diagnostics.js";
11
+ import { createRequestControls } from "./controls.js";
12
+ import { createMutationControls } from "./mutations.js";
13
+ import { createOwnerSharePort, ownerPage, validateOwnerPage } from "./owner-shares.js";
14
+ import { createMockAuthentication, fixturePhrase } from "./authentication.js";
15
+ import { registerRuntime } from "./runtime.js";
16
+
17
+ //#region src/testing/mock.ts
18
+ /** Managed mock runs bind readers to owner or recipient access and clean only their own fixtures. */
19
+ /** Store ownership is per run so closing one account cannot reset another active run. */
20
+ function createMockSia(options = {}) {
21
+ return createMockSiaWithBackend(options);
22
+ }
23
+ function createMockSiaWithBackend(options = {}, payloadFactory) {
24
+ const start = options.clock && options.clock !== "realtime" ? Date.parse(options.clock.start) : void 0;
25
+ if (start !== void 0 && !Number.isFinite(start)) throw failure("invalid-input", "Invalid mock clock");
26
+ let elapsed = 0;
27
+ let closed = false;
28
+ const now = () => new Date(start === void 0 ? Date.now() : start + elapsed);
29
+ const active = /* @__PURE__ */ new Set();
30
+ const actors = /* @__PURE__ */ new WeakMap();
31
+ const actorLabel = (actor) => actors.get(actor);
32
+ const records = [];
33
+ const controls = createRequestControls(records, actorLabel);
34
+ const credentials = /* @__PURE__ */ new Map();
35
+ const grants = /* @__PURE__ */ new WeakMap();
36
+ const objects = /* @__PURE__ */ new WeakMap();
37
+ const applicationObjects = /* @__PURE__ */ new WeakMap();
38
+ const shareGrants = /* @__PURE__ */ new WeakMap();
39
+ const mutations = createMutationControls((selector) => {
40
+ if (selector.stage !== "beforeCommit" && selector.stage !== "collect" || selector.stage === "collect" && (!selector.actor || !["packed-add", "upload"].includes(selector.operation) || !Number.isSafeInteger(selector.afterBytes) || selector.afterBytes < 0) || Object.keys(selector).some((key) => !(selector.stage === "collect" ? [
41
+ "actor",
42
+ "operation",
43
+ "stage",
44
+ "afterBytes"
45
+ ] : selector.operation.startsWith("share-") ? [
46
+ "actor",
47
+ "operation",
48
+ "stage",
49
+ "share"
50
+ ] : ["delete", "pin"].includes(selector.operation) ? [
51
+ "actor",
52
+ "operation",
53
+ "stage",
54
+ "object"
55
+ ] : [
56
+ "actor",
57
+ "operation",
58
+ "stage"
59
+ ]).includes(key)) || ![
60
+ "delete",
61
+ "metadata",
62
+ "packed-add",
63
+ "packed-finalize",
64
+ "pin",
65
+ "share-add",
66
+ "share-end",
67
+ "share-remove",
68
+ "upload"
69
+ ].includes(selector.operation)) throw failure("invalid-input", "Invalid mutation selector");
70
+ if (selector.actor && !actors.has(selector.actor)) throw failure("foreign-handle", "Unknown actor");
71
+ validateShareSelector(selector);
72
+ if (selector.object && !applicationObjects.has(selector.object)) throw failure("foreign-handle", "Unknown application object");
73
+ }, records, (selector) => {
74
+ if (![
75
+ "delete",
76
+ "pin",
77
+ "share-add",
78
+ "share-end",
79
+ "share-remove",
80
+ "upload"
81
+ ].includes(selector.operation) || !selector.actor || Object.keys(selector).some((key) => !(selector.operation.startsWith("share-") ? [
82
+ "actor",
83
+ "share",
84
+ "operation"
85
+ ] : selector.operation === "upload" ? ["actor", "operation"] : [
86
+ "actor",
87
+ "object",
88
+ "operation"
89
+ ]).includes(key))) throw failure("invalid-input", "Invalid mutation reply selector");
90
+ if (!actors.has(selector.actor)) throw failure("foreign-handle", "Unknown actor");
91
+ if (selector.share !== void 0 && !shareGrants.has(selector.share)) throw failure("foreign-handle", "Unknown share grant");
92
+ validateShareSelector(selector);
93
+ if (selector.object !== void 0 && !applicationObjects.has(selector.object)) throw failure("foreign-handle", "Unknown application object");
94
+ }, actorLabel);
95
+ const shares = /* @__PURE__ */ new WeakMap();
96
+ const ownerReferences = /* @__PURE__ */ new WeakMap();
97
+ /** Read projections must not let callers mutate the fixture's stored metadata. */
98
+ function describe(context, id) {
99
+ const record = context.objects.get(id);
100
+ if (!record || record.deleted || !context.network.model.object(context.id, id)) throw failure("not-found", "Object is missing");
101
+ return {
102
+ id,
103
+ metadata: new Uint8Array(record.metadata),
104
+ sizeBytes: record.handle.sizeBytes
105
+ };
106
+ }
107
+ function environmentOpen() {
108
+ if (closed) throw failure("closed", "Mock environment is closed");
109
+ }
110
+ function access(context, key, registration = false) {
111
+ const value = Object.freeze(Object.defineProperties(Object.create(null), {
112
+ [Symbol.for("nodejs.util.inspect.custom")]: { value: () => "[Sia test access]" },
113
+ toJSON: { value: () => "[Sia test access]" }
114
+ }));
115
+ const credential = {
116
+ keyHex: identifier(),
117
+ kind: registration ? "registration" : key === null ? "app-key" : "sharing-key"
118
+ };
119
+ grants.set(value, {
120
+ context,
121
+ credential,
122
+ key
123
+ });
124
+ credentials.set(credential.keyHex, value);
125
+ context.credentials.add(credential.keyHex);
126
+ return value;
127
+ }
128
+ function ownedObject(context, handle) {
129
+ const value = objects.get(handle);
130
+ if (!value || value.context !== context) throw failure("foreign-handle", "Object does not belong to this run");
131
+ return value.record;
132
+ }
133
+ function ownedShare(context, handle) {
134
+ const value = shares.get(handle);
135
+ if (!value || value.context !== context) throw failure("foreign-handle", "Sharing key does not belong to this run");
136
+ return value.record;
137
+ }
138
+ function attach(context, share, object) {
139
+ const sharing = ownedShare(context, share);
140
+ const record = ownedObject(context, object);
141
+ if (sharing.revoked) throw failure("denied", "Sharing key is unavailable");
142
+ if (record.deleted) throw failure("not-found", "Object is missing");
143
+ context.network.model.attachSharedObject(context.id, share.id, {
144
+ dataSignature: "mock",
145
+ encryptedDataKey: "mock",
146
+ objectID: object.id
147
+ });
148
+ }
149
+ /** Pending fixture work must settle before its payload store is released. */
150
+ function cleanup(context) {
151
+ if (context.cleanup) return context.cleanup;
152
+ context.state = "closing";
153
+ context.abort.abort();
154
+ context.cleanup = (async () => {
155
+ const transport = await Promise.allSettled([...context.transportCleanup].map((close) => close()));
156
+ for (const result of transport) if (result.status === "rejected" && !context.cleanupErrors.includes(result.reason)) context.cleanupErrors.push(result.reason);
157
+ context.transportCleanup.clear();
158
+ await Promise.allSettled([...context.pending]);
159
+ const errors = [...context.cleanupErrors];
160
+ for (const record of context.shares.values()) {
161
+ if (record.revoked) continue;
162
+ try {
163
+ context.network.model.revokeSharingKey(context.id, record.handle.id);
164
+ record.revoked = true;
165
+ } catch (error) {
166
+ errors.push(error);
167
+ }
168
+ }
169
+ for (const record of context.objects.values()) {
170
+ try {
171
+ if (context.network.model.object(context.id, record.handle.id)) await context.sdk.deleteObject(record.handle.id);
172
+ else if (!record.deleted) await context.network.discardUpload(context.id, record.handle.id);
173
+ record.deleted = true;
174
+ } catch (error) {
175
+ errors.push(error);
176
+ }
177
+ record.metadata = /* @__PURE__ */ new Uint8Array();
178
+ }
179
+ if (context.payload) try {
180
+ await context.payload.owner.close();
181
+ } catch (error) {
182
+ errors.push(error);
183
+ }
184
+ context.network.model.reset();
185
+ context.sdk = void 0;
186
+ context.network = void 0;
187
+ for (const key of context.credentials) credentials.delete(key);
188
+ context.credentials.clear();
189
+ context.objects.clear();
190
+ context.shares.clear();
191
+ context.state = "closed";
192
+ active.delete(context);
193
+ if (errors.length) throw new AggregateError(errors, "Mock cleanup failed");
194
+ })();
195
+ return context.cleanup;
196
+ }
197
+ function validateShareSelector(selector) {
198
+ if (selector.share) {
199
+ const value = shareGrants.get(selector.share);
200
+ if (!value) throw failure("foreign-handle", "Unknown share grant");
201
+ open(value.context);
202
+ if (selector.actor && selector.actor !== value.actor) throw failure("foreign-handle", "Grant actor does not match");
203
+ if (![
204
+ "share-add",
205
+ "share-end",
206
+ "share-inspect",
207
+ "share-remove"
208
+ ].includes(selector.operation)) throw failure("invalid-input", "Invalid share selector");
209
+ }
210
+ if (selector.operation.startsWith("share-") && selector.object) throw failure("invalid-input", "Invalid share selector");
211
+ }
212
+ function grantAvailable(value) {
213
+ return !value.revoked && value.context.state === "open" && (!value.expiresAt || now().getTime() < Date.parse(value.expiresAt));
214
+ }
215
+ function installedGrants(handle, actor, input) {
216
+ const owner = grants.get(handle);
217
+ if (!owner || owner.key !== null || owner.credential.kind !== "app-key") throw failure("denied", "Owner access is unavailable");
218
+ open(owner.context);
219
+ const labels = /* @__PURE__ */ new Set();
220
+ return input.map((handle) => {
221
+ const value = shareGrants.get(handle);
222
+ if (!value || value.context !== owner.context || value.actor !== actor) throw failure("foreign-handle", "Unknown share grant");
223
+ if (!grantAvailable(value)) throw failure("denied", "Share grant is unavailable");
224
+ if (labels.has(value.label)) throw failure("invalid-input", "Duplicate grant label");
225
+ labels.add(value.label);
226
+ return {
227
+ handle,
228
+ value
229
+ };
230
+ });
231
+ }
232
+ function validateReadSelector(selector) {
233
+ validateShareSelector(selector);
234
+ if (selector.actor && !actors.has(selector.actor)) throw failure("foreign-handle", "Unknown actor");
235
+ if (selector.object && !objects.has(selector.object)) throw failure("foreign-handle", "Unknown fixture object");
236
+ if ([
237
+ "delete",
238
+ "events",
239
+ "inspect",
240
+ "pin",
241
+ "share-add",
242
+ "share-end",
243
+ "share-remove",
244
+ "upload"
245
+ ].includes(selector.operation)) throw failure("invalid-input", "Read control required");
246
+ }
247
+ function createApplication(handle, actor, bindings) {
248
+ environmentOpen();
249
+ if (!actors.has(actor)) throw failure("foreign-handle", "Unknown actor");
250
+ const shareRefs = /* @__PURE__ */ new WeakMap();
251
+ const targets = bindings.map((binding) => {
252
+ const ref = Object.freeze(Object.create(null));
253
+ shareRefs.set(ref, binding);
254
+ return {
255
+ label: binding.value.label,
256
+ operations: [...binding.value.operations],
257
+ ref,
258
+ ...binding.value.expiresAt ? { expiresAt: binding.value.expiresAt } : {}
259
+ };
260
+ });
261
+ const grant = grants.get(handle);
262
+ const abort = new AbortController();
263
+ const pending = /* @__PURE__ */ new Set();
264
+ let closing;
265
+ const cleanupErrors = [];
266
+ function authorize() {
267
+ if (abort.signal.aborted) throw failure("closed", "Application port is closed");
268
+ if (!grant || grant.key !== null || grant.credential.kind !== "app-key") throw failure("denied", "Owner access is unavailable");
269
+ open(grant.context);
270
+ return grant.context;
271
+ }
272
+ function owned(context, object) {
273
+ const value = applicationObjects.get(object);
274
+ if (!value || value.context !== context) throw failure("foreign-handle", "Unknown application object");
275
+ return value.record;
276
+ }
277
+ function call(signal, action, prepare) {
278
+ const callSignal = AbortSignal.any([
279
+ abort.signal,
280
+ ...grant ? [grant.context.signal] : [],
281
+ ...signal ? [signal] : []
282
+ ]);
283
+ let preparationError;
284
+ let preparationFailed = false;
285
+ const promise = Promise.resolve().then(() => {
286
+ if (preparationFailed) throw preparationError;
287
+ callSignal.throwIfAborted();
288
+ const context = authorize();
289
+ return track(context, () => action(context, callSignal));
290
+ });
291
+ pending.add(promise);
292
+ try {
293
+ prepare?.();
294
+ } catch (error) {
295
+ preparationFailed = true;
296
+ preparationError = error;
297
+ }
298
+ promise.then(() => pending.delete(promise), () => {
299
+ pending.delete(promise);
300
+ });
301
+ return promise;
302
+ }
303
+ async function mutate(_context, signal, operation, objectId, action) {
304
+ const receipt = await mutations.begin(actor, operation, objectId, signal);
305
+ try {
306
+ signal.throwIfAborted();
307
+ authorize();
308
+ const value = await action(receipt);
309
+ mutations.afterCommit(receipt);
310
+ receipt.status = "completed";
311
+ return value;
312
+ } catch (error) {
313
+ receipt.status = signal.aborted ? "cancelled" : "failed";
314
+ throw error;
315
+ }
316
+ }
317
+ function shareAuthority(context, ref, operation) {
318
+ const binding = shareRefs.get(ref);
319
+ if (!binding) throw failure("foreign-handle", "Unknown application share");
320
+ const value = binding.value;
321
+ if (value.context !== context || !grantAvailable(value)) throw failure("denied", "Share grant is unavailable");
322
+ if (operation && !value.operations.includes(operation)) throw failure("denied", "Share operation is unavailable");
323
+ return binding;
324
+ }
325
+ function lifecycle(context, value) {
326
+ if (value.share.revoked) return "ended";
327
+ const expiry = context.network.model.getSharingKey(context.id, value.share.handle.id).expiresAt;
328
+ return expiry && now().getTime() >= Date.parse(expiry) ? "expired" : "active";
329
+ }
330
+ function objectId(id) {
331
+ if (id !== null && (typeof id !== "string" || !/^[a-f0-9]{64}$/.test(id))) throw failure("invalid-input", "Invalid object ID");
332
+ }
333
+ function shareMutation(ref, operation, signal, object, selectedId) {
334
+ return call(signal, async (context, signal) => {
335
+ const binding = shareAuthority(context, ref, operation);
336
+ if (operation === "remove") {
337
+ if (selectedId === null) throw failure("invalid-input", "Invalid object ID");
338
+ objectId(selectedId);
339
+ }
340
+ const record = operation === "add" ? owned(context, object) : void 0;
341
+ const check = () => {
342
+ signal.throwIfAborted();
343
+ authorize();
344
+ shareAuthority(context, ref, operation);
345
+ const state = lifecycle(context, binding.value);
346
+ if (state === "expired" || state === "ended" && operation !== "end") throw failure("denied", "Sharing key is unavailable");
347
+ if (record && (record.deleted || !context.network.model.object(context.id, record.handle.id))) throw failure("denied", "Add requires a pinned object");
348
+ return state;
349
+ };
350
+ check();
351
+ const id = record?.handle.id ?? selectedId;
352
+ const receipt = await mutations.begin(actor, `share-${operation}`, id, signal, {
353
+ grant: binding.handle,
354
+ id: binding.value.share.handle.id
355
+ });
356
+ try {
357
+ const state = check();
358
+ const model = context.network.model;
359
+ const shareId = binding.value.share.handle.id;
360
+ if (operation === "end") {
361
+ if (state !== "ended") {
362
+ model.revokeSharingKey(context.id, shareId);
363
+ binding.value.share.revoked = true;
364
+ receipt.committed = true;
365
+ }
366
+ } else {
367
+ const contains = model.hasOwnedSharedObject(context.id, shareId, id);
368
+ if (operation === "add" && !contains) {
369
+ model.attachSharedObject(context.id, shareId, {
370
+ dataSignature: "mock",
371
+ encryptedDataKey: "mock",
372
+ objectID: id
373
+ });
374
+ receipt.committed = true;
375
+ } else if (operation === "remove" && contains) {
376
+ model.detachSharedObject(context.id, shareId, id);
377
+ receipt.committed = true;
378
+ }
379
+ }
380
+ mutations.afterCommit(receipt);
381
+ receipt.status = "completed";
382
+ } catch (error) {
383
+ receipt.status = signal.aborted ? "cancelled" : "failed";
384
+ throw error;
385
+ }
386
+ });
387
+ }
388
+ return {
389
+ close() {
390
+ abort.abort();
391
+ return closing ??= Promise.allSettled([...pending]).then(() => {
392
+ if (cleanupErrors.length) throw new AggregateError(cleanupErrors, "Application source cleanup failed");
393
+ });
394
+ },
395
+ delete(object, options = {}) {
396
+ return call(options.signal, async (context, signal) => {
397
+ const record = owned(context, object);
398
+ await mutate(context, signal, "delete", record.handle.id, async (receipt) => {
399
+ while (record.deletion) await withAbort(record.deletion.catch(() => void 0), signal);
400
+ signal.throwIfAborted();
401
+ authorize();
402
+ if (record.deleted) return;
403
+ const deletion = record.deletion = (async () => {
404
+ const complete = () => {
405
+ receipt.committed = true;
406
+ record.deleted = true;
407
+ record.metadata = /* @__PURE__ */ new Uint8Array();
408
+ };
409
+ if (context.network.model.object(context.id, record.handle.id)) await context.sdk.deleteObject(record.handle.id, {
410
+ prepareCommit: () => {
411
+ authorize();
412
+ return complete;
413
+ },
414
+ signal
415
+ });
416
+ else {
417
+ const retirement = context.network.discardUpload(context.id, record.handle.id);
418
+ complete();
419
+ await retirement;
420
+ }
421
+ })();
422
+ try {
423
+ await deletion;
424
+ } finally {
425
+ if (record.deletion === deletion) delete record.deletion;
426
+ }
427
+ });
428
+ });
429
+ },
430
+ events(input) {
431
+ return call(input.signal, (context) => {
432
+ const { cursor, limit } = input;
433
+ if (!Number.isSafeInteger(limit) || limit < 1 || limit > 1e3) throw invalidInput("limit", "limit must be an integer from 1 to 1000");
434
+ if (cursor !== null && (!cursor || typeof cursor.after !== "string" || !/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.000Z$/.test(cursor.after) || !Number.isFinite(Date.parse(cursor.after)) || new Date(cursor.after).toISOString() !== cursor.after || typeof cursor.id !== "string" || !/^[a-f0-9]{64}$/.test(cursor.id))) throw invalidInput("cursor", "Invalid event cursor");
435
+ const events = context.network.model.objectEvents(context.id).map((row) => ({
436
+ deleted: row.deleted,
437
+ id: row.key,
438
+ updatedAt: row.updatedAt
439
+ })).sort((a, b) => a.updatedAt.localeCompare(b.updatedAt) || a.id.localeCompare(b.id)).filter((row) => !cursor || row.updatedAt > cursor.after || row.updatedAt === cursor.after && row.id > cursor.id).slice(0, limit);
440
+ const last = events.at(-1);
441
+ return {
442
+ done: events.length < limit,
443
+ events,
444
+ nextCursor: last ? {
445
+ after: last.updatedAt,
446
+ id: last.id
447
+ } : cursor
448
+ };
449
+ });
450
+ },
451
+ inspect(object, options = {}) {
452
+ return call(options.signal, (context) => {
453
+ const record = owned(context, object);
454
+ return record.deleted ? "missing" : context.network.model.object(context.id, record.handle.id) ? "pinned" : "uploaded";
455
+ });
456
+ },
457
+ pin(object, options = {}) {
458
+ let metadata;
459
+ return call(options.signal, async (context, signal) => {
460
+ const record = owned(context, object);
461
+ if (record.deleted) throw failure("not-found", "Object is missing");
462
+ await mutate(context, signal, "pin", record.handle.id, async (receipt) => {
463
+ if (record.deleted) throw failure("not-found", "Object is missing");
464
+ await context.sdk.pinObject({ id: () => record.handle.id }, {
465
+ prepareCommit: () => {
466
+ if (record.deleted) throw failure("not-found", "Object is missing");
467
+ return () => {
468
+ if (metadata !== void 0) record.metadata = metadata;
469
+ receipt.committed = true;
470
+ };
471
+ },
472
+ signal
473
+ });
474
+ });
475
+ }, () => {
476
+ const source = options.metadata;
477
+ if (source !== void 0) metadata = snapshotApplicationMetadata(source);
478
+ });
479
+ },
480
+ shares: {
481
+ add(ref, object, options = {}) {
482
+ return shareMutation(ref, "add", options.signal, object);
483
+ },
484
+ end(ref, options = {}) {
485
+ return shareMutation(ref, "end", options.signal);
486
+ },
487
+ inspect(ref, id, options = {}) {
488
+ return call(options.signal, async (context, signal) => {
489
+ const binding = shareAuthority(context, ref);
490
+ objectId(id);
491
+ const receipt = await controls.begin(actor, "share-inspect", id ?? void 0, signal, {
492
+ grant: binding.handle,
493
+ id: binding.value.share.handle.id
494
+ });
495
+ try {
496
+ signal.throwIfAborted();
497
+ authorize();
498
+ shareAuthority(context, ref);
499
+ const state = lifecycle(context, binding.value);
500
+ const contains = state === "ended" || id === null ? null : context.network.model.hasOwnedSharedObject(context.id, binding.value.share.handle.id, id);
501
+ receipt.status = "completed";
502
+ return {
503
+ contains,
504
+ state
505
+ };
506
+ } catch (error) {
507
+ receipt.status = signal.aborted ? "cancelled" : "failed";
508
+ throw error;
509
+ }
510
+ });
511
+ },
512
+ remove(ref, id, options = {}) {
513
+ return shareMutation(ref, "remove", options.signal, void 0, id);
514
+ },
515
+ targets(options = {}) {
516
+ return call(options.signal, async (_context, signal) => {
517
+ const receipt = await controls.begin(actor, "share-targets", void 0, signal);
518
+ try {
519
+ signal.throwIfAborted();
520
+ authorize();
521
+ const result = targets.filter((_, index) => grantAvailable(bindings[index].value)).map((target) => ({
522
+ ...target,
523
+ operations: [...target.operations]
524
+ }));
525
+ receipt.status = "completed";
526
+ return result;
527
+ } catch (error) {
528
+ receipt.status = signal.aborted ? "cancelled" : "failed";
529
+ throw error;
530
+ }
531
+ });
532
+ }
533
+ },
534
+ upload(input) {
535
+ return call(input.signal, async (context, signal) => {
536
+ const file = {
537
+ name: input.file.name,
538
+ open: input.file.open.bind(input.file),
539
+ sha256: input.file.sha256,
540
+ sizeBytes: input.file.sizeBytes
541
+ };
542
+ let name = input.name;
543
+ if (name === void 0) name = file.name;
544
+ const metadata = snapshotApplicationMetadata(input.metadata);
545
+ integer(file.sizeBytes);
546
+ if (typeof name !== "string" || !name || name.length > 1024 || new TextEncoder().encode(name).length > 1024 || file.sizeBytes > (context.payload ? payloadFactory.limits.maxObjectBytes : 16 * 1024 * 1024) || !/^[0-9a-f]{64}$/.test(file.sha256)) throw failure("invalid-input", "Invalid application upload");
547
+ if (context.objectAttempts >= context.limits.maxObjects || file.sizeBytes > context.limits.maxLogicalUploadBytes - context.reservedBytes) throw failure("limit", "Run upload allowance exceeded");
548
+ const reservation = context.payload?.owner.reserveUpload(file.sizeBytes);
549
+ context.objectAttempts++;
550
+ context.reservedBytes += file.sizeBytes;
551
+ let committed = false;
552
+ let collected;
553
+ let result;
554
+ const failures = [];
555
+ try {
556
+ const bytes = await mutations.collect(actor, "upload", signal, (checkpoint) => context.payload ? reservation.admitSource(file.sizeBytes).then((spool) => collectPayload(file.open, spool, signal, checkpoint, (error) => {
557
+ cleanupErrors.push(error);
558
+ context.cleanupErrors.push(error);
559
+ }, file)) : readFixture(file, signal, checkpoint, (error) => {
560
+ cleanupErrors.push(error);
561
+ context.cleanupErrors.push(error);
562
+ }));
563
+ collected = bytes;
564
+ result = await mutate(context, signal, "upload", void 0, async (receipt) => {
565
+ const id = identifier();
566
+ let object;
567
+ const uploadOptions = {
568
+ id,
569
+ prepareCommit: () => {
570
+ signal.throwIfAborted();
571
+ authorize();
572
+ const record = {
573
+ deleted: false,
574
+ handle: Object.freeze({
575
+ id,
576
+ sha256: file.sha256,
577
+ sizeBytes: bytes.length
578
+ }),
579
+ metadata
580
+ };
581
+ object = Object.freeze({ id });
582
+ const binding = {
583
+ context,
584
+ record
585
+ };
586
+ return () => {
587
+ context.objects.set(id, record);
588
+ applicationObjects.set(object, binding);
589
+ context.uploadedBytes += bytes.length;
590
+ committed = true;
591
+ receipt.committed = true;
592
+ receipt.objectId = id;
593
+ };
594
+ },
595
+ signal
596
+ };
597
+ if (context.payload) await context.payload.network.createSdk({ accountId: context.id }).uploadPayload(bytes, uploadOptions);
598
+ else await context.sdk.upload(bytes, uploadOptions);
599
+ return object;
600
+ });
601
+ } catch (error) {
602
+ failures.push(error);
603
+ }
604
+ if (!committed) {
605
+ context.reservedBytes -= file.sizeBytes;
606
+ try {
607
+ if (collected && context.payload) await context.payload.owner.discardUncommitted(collected);
608
+ } catch (error) {
609
+ failures.push(error);
610
+ cleanupErrors.push(error);
611
+ context.cleanupErrors.push(error);
612
+ }
613
+ }
614
+ try {
615
+ reservation?.release();
616
+ } catch (error) {
617
+ failures.push(error);
618
+ cleanupErrors.push(error);
619
+ context.cleanupErrors.push(error);
620
+ }
621
+ if (failures.length === 1) throw failures[0];
622
+ if (failures.length) throw new AggregateError(failures, "Application upload and payload cleanup failed");
623
+ return result;
624
+ });
625
+ }
626
+ };
627
+ }
628
+ const environment = {
629
+ actor(label) {
630
+ environmentOpen();
631
+ if (!label.trim()) throw failure("invalid-input", "Actor label must not be empty");
632
+ const actor = Object.freeze({});
633
+ actors.set(actor, label);
634
+ return actor;
635
+ },
636
+ advanceTime(milliseconds) {
637
+ environmentOpen();
638
+ if (start === void 0) throw failure("invalid-input", "Advancing time requires a manual clock");
639
+ integer(milliseconds);
640
+ if (!Number.isFinite(new Date(start + elapsed + milliseconds).getTime())) throw failure("invalid-input", "Mock clock is outside the date range");
641
+ elapsed += milliseconds;
642
+ },
643
+ application({ access: handle, as: actor, shareGrants: installed = [] }) {
644
+ return createApplication(handle, actor, installed.length ? installedGrants(handle, actor, installed) : []);
645
+ },
646
+ async close() {
647
+ closed = true;
648
+ const errors = (await Promise.allSettled([...active].map(cleanup))).flatMap((result) => result.status === "rejected" ? [result.reason] : []);
649
+ if (errors.length) throw new AggregateError(errors, "Mock environment cleanup failed");
650
+ },
651
+ faults: {
652
+ fail(selector, options) {
653
+ selector = { ...selector };
654
+ validateReadSelector(selector);
655
+ controls.control.fail(selector, options);
656
+ },
657
+ hold(selector) {
658
+ selector = { ...selector };
659
+ validateReadSelector(selector);
660
+ return controls.control.hold(selector);
661
+ },
662
+ setLink(actor, input) {
663
+ if (!actors.has(actor)) throw failure("foreign-handle", "Unknown actor");
664
+ controls.control.setLink(actor, input);
665
+ }
666
+ },
667
+ history: controls.history,
668
+ mutationFaults: mutations.control,
669
+ ownerShares({ access: handle, as: actor }) {
670
+ environmentOpen();
671
+ if (!actors.has(actor)) throw failure("invalid-input", "Unknown mock actor");
672
+ const grant = grants.get(handle);
673
+ function authorize() {
674
+ if (grant && grant.context.state !== "open") throw failure("closed", "Run is closed");
675
+ if (!grant || grant.credential.kind !== "app-key" || grant.key !== null) throw failure("denied", "Owner access is unavailable");
676
+ return grant.context;
677
+ }
678
+ function project(ref) {
679
+ const context = authorize();
680
+ const identity = ownerReferences.get(ref);
681
+ if (!identity || identity.contextId !== context.id) throw failure("foreign-handle", "Share reference does not belong to this run");
682
+ const record = context.shares.get(identity.shareId);
683
+ if (!record || record.revoked) throw failure("not-found", "Sharing key is missing");
684
+ const key = context.network.model.getSharingKey(context.id, identity.shareId);
685
+ return {
686
+ context,
687
+ ids: context.network.model.listOwnedSharedObjects(context.id, identity.shareId).map((attachment) => attachment.objectID).sort((a, b) => a.localeCompare(b)),
688
+ key
689
+ };
690
+ }
691
+ function details(ref) {
692
+ const { context, ids, key } = project(ref);
693
+ return {
694
+ description: key.description,
695
+ ref,
696
+ ...key.expiresAt === void 0 ? {} : { expiresAt: key.expiresAt },
697
+ statistics: {
698
+ logicalBytes: ids.reduce((bytes, id) => bytes + context.objects.get(id).handle.sizeBytes, 0),
699
+ objectCount: ids.length
700
+ }
701
+ };
702
+ }
703
+ return createOwnerSharePort({
704
+ actor,
705
+ authorize,
706
+ controls,
707
+ read: {
708
+ detail(ref) {
709
+ return Promise.resolve(details(ref));
710
+ },
711
+ list(page) {
712
+ validateOwnerPage(page);
713
+ const context = authorize();
714
+ const selected = ownerPage(context.network.model.listSharingKeys(context.id).sort((a, b) => a.publicKey.localeCompare(b.publicKey)), page);
715
+ return Promise.resolve({
716
+ ...selected,
717
+ items: selected.items.map((key) => details(context.shares.get(key.publicKey).ownerRef))
718
+ });
719
+ },
720
+ objects(ref, page) {
721
+ validateOwnerPage(page);
722
+ const { context, ids } = project(ref);
723
+ const selected = ownerPage(ids, page);
724
+ return Promise.resolve({
725
+ ...selected,
726
+ items: selected.items.map((id) => describe(context, id))
727
+ });
728
+ }
729
+ },
730
+ signal: grant?.context.signal ?? new AbortController().signal,
731
+ track: (action) => track(authorize(), action)
732
+ });
733
+ },
734
+ packedSdk(input) {
735
+ environmentOpen();
736
+ const { access: handle, as: actor, maxBytes, maxObjects, platform } = input;
737
+ if (!actors.has(actor)) throw failure("foreign-handle", "Unknown actor");
738
+ const grant = grants.get(handle);
739
+ if (!grant || grant.key !== null || grant.credential.kind !== "app-key") throw failure("denied", "Owner access is unavailable");
740
+ const context = grant.context;
741
+ const authorize = () => {
742
+ environmentOpen();
743
+ open(context);
744
+ };
745
+ authorize();
746
+ if (!["browser", "node"].includes(platform) || !Number.isSafeInteger(maxBytes) || maxBytes < 1 || maxBytes > (context.payload ? payloadFactory.limits.maxLogicalUploadBytes : 16 * 1024 * 1024) || !Number.isSafeInteger(maxObjects) || maxObjects < 1) throw failure("invalid-input", "Invalid packed allowance");
747
+ if (context.payload && platform !== "node") throw failure("unsupported", "Temporary-file packed storage requires Node platform");
748
+ return createPackedSdk({
749
+ access: handle,
750
+ as: actor,
751
+ maxBytes,
752
+ maxObjects,
753
+ platform
754
+ }, {
755
+ afterCommit: (receipt) => mutations.afterCommit(receipt),
756
+ authorize,
757
+ before: (operation, signal, id) => mutations.begin(actor, operation, id, signal),
758
+ cleanupError(error) {
759
+ if (!context.cleanupErrors.includes(error)) context.cleanupErrors.push(error);
760
+ },
761
+ collect: (signal, work) => mutations.collect(actor, "packed-add", signal, work),
762
+ metadata(id, bytes) {
763
+ authorize();
764
+ const record = context.objects.get(id);
765
+ if (record.deleted) throw failure("not-found", "Object is missing");
766
+ record.metadata = bytes;
767
+ },
768
+ async pin(id, signal) {
769
+ await context.sdk.pinObject({ id: () => id }, { signal });
770
+ },
771
+ register: (close) => {
772
+ context.transportCleanup.add(close);
773
+ return () => {
774
+ context.transportCleanup.delete(close);
775
+ };
776
+ },
777
+ reserve() {
778
+ authorize();
779
+ if (context.objectAttempts + maxObjects > context.limits.maxObjects || maxBytes > context.limits.maxLogicalUploadBytes - context.reservedBytes) throw failure("limit", "Run upload allowance exceeded");
780
+ const physical = context.payload?.owner.reserveUpload(maxBytes);
781
+ const sequence = context.objectAttempts;
782
+ context.objectAttempts += maxObjects;
783
+ context.reservedBytes += maxBytes;
784
+ let committed = 0;
785
+ let ordinal = 0;
786
+ let released = false;
787
+ return {
788
+ release() {
789
+ if (released) return;
790
+ released = true;
791
+ physical?.release();
792
+ context.reservedBytes -= maxBytes - committed;
793
+ },
794
+ ...physical ? {
795
+ admit: (remaining) => physical.admitSource(Math.min(remaining, payloadFactory.limits.maxObjectBytes)),
796
+ discard: (token) => context.payload.owner.discardUncommitted(token)
797
+ } : {},
798
+ async stage(bytes, signal, onCommit) {
799
+ const id = await digest(new TextEncoder().encode(`${context.id}:packed:${sequence + ordinal++}`));
800
+ const sha256 = context.payload ? bytes.sha256 : await digest(bytes);
801
+ const uploadOptions = {
802
+ id,
803
+ prepareCommit() {
804
+ signal.throwIfAborted();
805
+ authorize();
806
+ const handle = Object.freeze({
807
+ id,
808
+ sha256,
809
+ sizeBytes: bytes.length
810
+ });
811
+ const record = {
812
+ deleted: false,
813
+ handle,
814
+ metadata: /* @__PURE__ */ new Uint8Array()
815
+ };
816
+ return () => {
817
+ context.objects.set(id, record);
818
+ objects.set(handle, {
819
+ context,
820
+ record
821
+ });
822
+ context.uploadedBytes += bytes.length;
823
+ committed += bytes.length;
824
+ onCommit?.(id);
825
+ };
826
+ },
827
+ signal
828
+ };
829
+ if (context.payload) await context.payload.network.createSdk({ accountId: context.id }).uploadPayload(bytes, uploadOptions);
830
+ else await context.sdk.upload(bytes, uploadOptions);
831
+ return id;
832
+ }
833
+ };
834
+ },
835
+ signal: context.signal,
836
+ track: (work) => track(context, work)
837
+ });
838
+ },
839
+ async publish({ access: handle }) {
840
+ const grant = grants.get(handle);
841
+ if (!grant || grant.key !== null || grant.credential.kind !== "app-key") throw failure("denied", "Owner access is unavailable");
842
+ return track(grant.context, () => {
843
+ grant.context.network.model.publishObjectEvents();
844
+ });
845
+ },
846
+ reader({ access: handle, as: actor }) {
847
+ environmentOpen();
848
+ if (!actors.has(actor)) throw failure("invalid-input", "Unknown mock actor");
849
+ const grant = grants.get(handle);
850
+ if (grant && grant.context.state !== "open") throw failure("closed", "Run is closed");
851
+ const abort = new AbortController();
852
+ const signal = grant ? AbortSignal.any([grant.context.signal, abort.signal]) : abort.signal;
853
+ function authorize(id) {
854
+ if (abort.signal.aborted || grant && grant.context.state !== "open") throw failure("closed", "Reader is closed");
855
+ if (!grant) throw failure("denied", "Read access is unavailable");
856
+ const { context, key } = grant;
857
+ if (grant.credential.kind === "registration") throw failure("denied", "Read access is unavailable");
858
+ if (key !== null) try {
859
+ if (id === void 0) context.network.model.sharedStats(key, key);
860
+ else context.network.model.sharedObject(key, key, id);
861
+ } catch {
862
+ throw failure("denied", "Read access is unavailable");
863
+ }
864
+ return context;
865
+ }
866
+ const streams = /* @__PURE__ */ new Set();
867
+ const pendingDownloads = /* @__PURE__ */ new Set();
868
+ const closeErrors = [];
869
+ let closing;
870
+ const reader = {
871
+ close() {
872
+ if (closing) return closing;
873
+ abort.abort();
874
+ if (!grant?.context.payload) return Promise.resolve();
875
+ closing = (async () => {
876
+ await Promise.allSettled(pendingDownloads);
877
+ await Promise.allSettled(Array.from(streams, (stream) => grant.context.payload.network.closeDownload(stream)));
878
+ streams.clear();
879
+ if (closeErrors.length) throw new AggregateError(closeErrors, "Reader descriptor cleanup failed");
880
+ })();
881
+ closing.catch(() => void 0);
882
+ return closing;
883
+ },
884
+ download(object, range = {}) {
885
+ const operation = (async () => {
886
+ const id = object.id;
887
+ const context = authorize(id);
888
+ describe(context, id);
889
+ const { length, offset, signal: inputSignal } = range;
890
+ if (offset !== void 0) integer(offset, "offset");
891
+ if (length !== void 0) integer(length, "length");
892
+ const callSignal = inputSignal ? AbortSignal.any([signal, inputSignal]) : signal;
893
+ const request = await controls.begin(actor, "download", id, callSignal);
894
+ try {
895
+ authorize(id);
896
+ const body = await context.sdk.download({ id: () => id }, {
897
+ ...offset === void 0 ? {} : { offset },
898
+ ...length === void 0 ? {} : { length },
899
+ signal: callSignal
900
+ });
901
+ if (context.payload) {
902
+ streams.add(body);
903
+ context.payload.network.downloadDone(body).then(() => streams.delete(body), (error) => {
904
+ streams.delete(body);
905
+ closeErrors.push(error);
906
+ });
907
+ }
908
+ return controls.observe(request, body, callSignal);
909
+ } catch (error) {
910
+ request.status = callSignal.aborted ? "cancelled" : "failed";
911
+ throw error;
912
+ }
913
+ })();
914
+ pendingDownloads.add(operation);
915
+ operation.then(() => pendingDownloads.delete(operation), () => pendingDownloads.delete(operation));
916
+ return operation;
917
+ },
918
+ async object(id, options = {}) {
919
+ const context = authorize(id);
920
+ describe(context, id);
921
+ const callSignal = options.signal ? AbortSignal.any([signal, options.signal]) : signal;
922
+ const request = await controls.begin(actor, "object", id, callSignal);
923
+ try {
924
+ await context.sdk.object(id, { signal: callSignal });
925
+ authorize(id);
926
+ const object = describe(context, id);
927
+ request.status = "completed";
928
+ return object;
929
+ } catch (error) {
930
+ request.status = callSignal.aborted ? "cancelled" : "failed";
931
+ throw error;
932
+ }
933
+ },
934
+ objects({ limit, offset, signal: externalSignal }) {
935
+ return Promise.resolve().then(async () => {
936
+ const context = authorize();
937
+ const request = await controls.begin(actor, "objects", void 0, externalSignal ? AbortSignal.any([signal, externalSignal]) : signal);
938
+ try {
939
+ authorize();
940
+ integer(offset, "offset");
941
+ integer(limit, "limit");
942
+ if (limit === 0) throw invalidInput("limit", "limit must be positive");
943
+ const rows = (grant.key === null ? [...context.objects.values()].filter((record) => !record.deleted && context.network.model.object(context.id, record.handle.id)).map((record) => record.handle.id) : context.network.model.listRecipientObjects(grant.key, grant.key).map((record) => record.objectID)).slice(offset, offset + limit).map((id) => describe(context, id));
944
+ request.status = "completed";
945
+ return {
946
+ done: rows.length < limit,
947
+ nextOffset: offset + rows.length,
948
+ objects: rows
949
+ };
950
+ } catch (error) {
951
+ request.status = signal.aborted ? "cancelled" : "failed";
952
+ throw error;
953
+ }
954
+ });
955
+ }
956
+ };
957
+ if (grant?.context.payload) grant.context.transportCleanup.add(() => reader.close());
958
+ return reader;
959
+ },
960
+ async run(runOptions, use) {
961
+ environmentOpen();
962
+ validateOptions(runOptions);
963
+ const limits = {
964
+ maxLogicalUploadBytes: payloadFactory?.limits.maxLogicalUploadBytes ?? 16 * 1024 * 1024,
965
+ maxObjects: 8,
966
+ maxShares: 8,
967
+ ...runOptions.limits
968
+ };
969
+ for (const value of Object.values(limits)) integer(value);
970
+ if (payloadFactory && limits.maxLogicalUploadBytes !== payloadFactory.limits.maxLogicalUploadBytes) throw failure("invalid-input", "Run and payload logical budgets must match");
971
+ const model = createIndexdModel({
972
+ eventPublication: "manual",
973
+ now,
974
+ ...options.quotaBytes === void 0 ? {} : { quotaBytes: options.quotaBytes }
975
+ });
976
+ const payload = payloadFactory ? await payloadFactory.create(model) : void 0;
977
+ const network = payload?.network ?? createMockNetwork({ model });
978
+ const id = identifier();
979
+ network.model.createAccount({ publicKey: id });
980
+ const abort = new AbortController();
981
+ const context = {
982
+ abort,
983
+ cleanupErrors: [],
984
+ credentials: /* @__PURE__ */ new Set(),
985
+ id,
986
+ limits,
987
+ network,
988
+ objectAttempts: 0,
989
+ objects: /* @__PURE__ */ new Map(),
990
+ ...payload ? { payload } : {},
991
+ pending: /* @__PURE__ */ new Set(),
992
+ reservedBytes: 0,
993
+ sdk: network.createSdk({ accountId: id }),
994
+ shareAttempts: 0,
995
+ shares: /* @__PURE__ */ new Map(),
996
+ signal: runOptions.signal ? AbortSignal.any([abort.signal, runOptions.signal]) : abort.signal,
997
+ state: "open",
998
+ transportCleanup: /* @__PURE__ */ new Set(),
999
+ uploadedBytes: 0
1000
+ };
1001
+ active.add(context);
1002
+ const ownerAccess = access(context, null);
1003
+ const registrationAccess = access(context, null, true);
1004
+ const authentication = createMockAuthentication(runOptions.app, () => ({ ...grants.get(ownerAccess).credential }), now, context.signal);
1005
+ context.authentication = authentication;
1006
+ const run = {
1007
+ auth: {
1008
+ approve: authentication.approve,
1009
+ deny: authentication.deny,
1010
+ fixturePhrase,
1011
+ kind: "approval",
1012
+ registrationAccess
1013
+ },
1014
+ backend: "mock",
1015
+ id,
1016
+ mock: environment,
1017
+ objects: {
1018
+ async delete(handle) {
1019
+ return track(context, async () => {
1020
+ const record = ownedObject(context, handle);
1021
+ if (record.deleted) return;
1022
+ const deletion = record.deletion ??= context.sdk.deleteObject(handle.id, { signal: context.signal }).then(() => {
1023
+ record.deleted = true;
1024
+ record.metadata = /* @__PURE__ */ new Uint8Array();
1025
+ });
1026
+ try {
1027
+ await deletion;
1028
+ } finally {
1029
+ if (record.deletion === deletion) delete record.deletion;
1030
+ }
1031
+ });
1032
+ },
1033
+ async inspect(handle) {
1034
+ return track(context, () => {
1035
+ ownedObject(context, handle);
1036
+ return context.network.model.object(id, handle.id) ? "present" : "missing";
1037
+ });
1038
+ },
1039
+ async upload(input) {
1040
+ return track(context, async () => {
1041
+ const file = {
1042
+ name: input.file.name,
1043
+ open: input.file.open.bind(input.file),
1044
+ sha256: input.file.sha256,
1045
+ sizeBytes: input.file.sizeBytes
1046
+ };
1047
+ let name = input.name;
1048
+ if (name === void 0) name = file.name;
1049
+ integer(file.sizeBytes);
1050
+ if (typeof name !== "string" || !name || !/^[0-9a-f]{64}$/.test(file.sha256)) throw failure("invalid-input", "Invalid upload descriptor");
1051
+ const suppliedMetadata = input.metadata;
1052
+ let metadataView;
1053
+ try {
1054
+ metadataView = boundedByteView(suppliedMetadata, Infinity);
1055
+ } catch {
1056
+ throw failure("invalid-input", "Invalid upload descriptor");
1057
+ }
1058
+ if (context.objectAttempts >= limits.maxObjects || file.sizeBytes > limits.maxLogicalUploadBytes - context.reservedBytes) throw failure("limit", "Run upload allowance exceeded");
1059
+ if (context.payload && file.sizeBytes > payloadFactory.limits.maxObjectBytes) throw failure("limit", "Payload object allowance exceeded");
1060
+ const reservation = context.payload?.owner.reserveUpload(file.sizeBytes);
1061
+ context.objectAttempts++;
1062
+ context.reservedBytes += file.sizeBytes;
1063
+ const metadata = new Uint8Array(metadataView);
1064
+ if (context.payload) {
1065
+ const errors = [];
1066
+ let token;
1067
+ let committed = false;
1068
+ let result;
1069
+ let spool;
1070
+ try {
1071
+ spool = await reservation.admitSource(file.sizeBytes);
1072
+ const bytes = await readFixture(file, context.signal, void 0, (error) => {
1073
+ context.cleanupErrors.push(error);
1074
+ }, "bounded-payload");
1075
+ for (let offset = 0; offset < bytes.length; offset += 65536) await spool.append(new Uint8Array(bytes.subarray(offset, Math.min(offset + 65536, bytes.length))));
1076
+ token = await spool.finish();
1077
+ open(context);
1078
+ const handle = Object.freeze({
1079
+ id: identifier(),
1080
+ sha256: token.sha256,
1081
+ sizeBytes: token.length
1082
+ });
1083
+ const record = {
1084
+ deleted: false,
1085
+ handle,
1086
+ metadata
1087
+ };
1088
+ const uploaded = await context.payload.network.createSdk({ accountId: context.id }).uploadPayload(token, {
1089
+ id: handle.id,
1090
+ prepareCommit() {
1091
+ open(context);
1092
+ return () => {
1093
+ context.objects.set(handle.id, record);
1094
+ objects.set(handle, {
1095
+ context,
1096
+ record
1097
+ });
1098
+ context.uploadedBytes += handle.sizeBytes;
1099
+ committed = true;
1100
+ };
1101
+ },
1102
+ signal: context.signal
1103
+ });
1104
+ await context.sdk.pinObject(uploaded, { signal: context.signal });
1105
+ result = handle;
1106
+ } catch (error) {
1107
+ errors.push(error);
1108
+ }
1109
+ if (!committed) try {
1110
+ if (token) await context.payload.owner.retire(token);
1111
+ else await spool?.discard();
1112
+ } catch (error) {
1113
+ errors.push(error);
1114
+ }
1115
+ try {
1116
+ reservation.release();
1117
+ } catch (error) {
1118
+ errors.push(error);
1119
+ }
1120
+ if (errors.length === 1) throw errors[0];
1121
+ if (errors.length) throw new AggregateError(errors, "Managed upload and payload cleanup failed");
1122
+ return result;
1123
+ }
1124
+ const bytes = await readFixture(file, context.signal);
1125
+ open(context);
1126
+ const handle = Object.freeze({
1127
+ id: identifier(),
1128
+ sha256: file.sha256,
1129
+ sizeBytes: bytes.byteLength
1130
+ });
1131
+ const record = {
1132
+ deleted: false,
1133
+ handle,
1134
+ metadata
1135
+ };
1136
+ context.objects.set(handle.id, record);
1137
+ objects.set(handle, {
1138
+ context,
1139
+ record
1140
+ });
1141
+ const uploaded = await context.sdk.upload(bytes, {
1142
+ id: handle.id,
1143
+ signal: context.signal
1144
+ });
1145
+ context.uploadedBytes += bytes.byteLength;
1146
+ await context.sdk.pinObject(uploaded, { signal: context.signal });
1147
+ return handle;
1148
+ });
1149
+ }
1150
+ },
1151
+ ownerAccess,
1152
+ shares: {
1153
+ async attach(share, object) {
1154
+ return track(context, () => attach(context, share, object));
1155
+ },
1156
+ async create(input) {
1157
+ return track(context, () => {
1158
+ const description = input.description ?? "";
1159
+ if (typeof description !== "string") throw failure("invalid-input", "Invalid share description");
1160
+ for (const object of input.objects) if (ownedObject(context, object).deleted) throw failure("not-found", "Object is missing");
1161
+ if (input.expiresAt && (!Number.isFinite(input.expiresAt.getTime()) || input.expiresAt <= now())) throw failure("invalid-input", "Sharing expiry must be in the future");
1162
+ if (context.shareAttempts >= limits.maxShares) throw failure("limit", "Run sharing allowance exceeded");
1163
+ context.shareAttempts++;
1164
+ const key = identifier();
1165
+ const handle = Object.freeze({
1166
+ access: access(context, key),
1167
+ id: key
1168
+ });
1169
+ context.network.model.createSharingKey(id, {
1170
+ description,
1171
+ nonce: identifier(),
1172
+ publicKey: key,
1173
+ ...input.expiresAt ? { expiresAt: input.expiresAt.toISOString() } : {}
1174
+ });
1175
+ const ownerRef = Object.freeze(Object.create(null));
1176
+ const record = {
1177
+ handle,
1178
+ ownerRef,
1179
+ revoked: false
1180
+ };
1181
+ ownerReferences.set(ownerRef, {
1182
+ contextId: id,
1183
+ shareId: key
1184
+ });
1185
+ context.shares.set(key, record);
1186
+ shares.set(handle, {
1187
+ context,
1188
+ record
1189
+ });
1190
+ for (const object of input.objects) attach(context, handle, object);
1191
+ return handle;
1192
+ });
1193
+ },
1194
+ async detach(share, object) {
1195
+ return track(context, () => {
1196
+ ownedShare(context, share);
1197
+ ownedObject(context, object);
1198
+ context.network.model.detachSharedObject(id, share.id, object.id);
1199
+ });
1200
+ },
1201
+ async grant(share, input) {
1202
+ return track(context, () => {
1203
+ const record = ownedShare(context, share);
1204
+ if (!actors.has(input.as)) throw failure("foreign-handle", "Unknown actor");
1205
+ const expiry = context.network.model.getSharingKey(id, share.id).expiresAt;
1206
+ if (record.revoked || expiry && now().getTime() >= Date.parse(expiry)) throw failure("denied", "Sharing key is unavailable");
1207
+ const operations = [...input.operations];
1208
+ const deadline = input.expiresAt?.getTime();
1209
+ if (typeof input.label !== "string" || !input.label.trim() || !operations.length || new Set(operations).size !== operations.length || operations.some((op) => ![
1210
+ "add",
1211
+ "end",
1212
+ "remove"
1213
+ ].includes(op)) || deadline !== void 0 && (!Number.isFinite(deadline) || deadline <= now().getTime())) throw failure("invalid-input", "Invalid share grant");
1214
+ const handle = Object.freeze(Object.create(null));
1215
+ shareGrants.set(handle, {
1216
+ actor: input.as,
1217
+ context,
1218
+ label: input.label,
1219
+ operations,
1220
+ revoked: false,
1221
+ share: record,
1222
+ ...deadline === void 0 ? {} : { expiresAt: new Date(deadline).toISOString() }
1223
+ });
1224
+ return handle;
1225
+ });
1226
+ },
1227
+ async revoke(share) {
1228
+ return track(context, () => {
1229
+ const record = ownedShare(context, share);
1230
+ if (!record.revoked) context.network.model.revokeSharingKey(id, share.id);
1231
+ record.revoked = true;
1232
+ });
1233
+ },
1234
+ async revokeGrant(handle) {
1235
+ return track(context, () => {
1236
+ const value = shareGrants.get(handle);
1237
+ if (!value || value.context !== context) throw failure("foreign-handle", "Unknown share grant");
1238
+ value.revoked = true;
1239
+ });
1240
+ }
1241
+ }
1242
+ };
1243
+ let failed = false;
1244
+ let cause;
1245
+ let value;
1246
+ try {
1247
+ context.signal.throwIfAborted();
1248
+ value = await use(run);
1249
+ context.signal.throwIfAborted();
1250
+ } catch (error) {
1251
+ failed = true;
1252
+ cause = error;
1253
+ }
1254
+ let cleanupFailed = false;
1255
+ let cleanupError;
1256
+ try {
1257
+ await cleanup(context);
1258
+ } catch (error) {
1259
+ cleanupFailed = true;
1260
+ cleanupError = error;
1261
+ }
1262
+ if (cleanupFailed) {
1263
+ if (failed) throw new AggregateError([cause, cleanupError], "Run and cleanup failed", { cause: cleanupError });
1264
+ throw cleanupError;
1265
+ }
1266
+ if (failed) throw cause;
1267
+ return {
1268
+ summary: {
1269
+ backend: "mock",
1270
+ cleanup: "clean",
1271
+ id,
1272
+ logicalUploadedBytes: context.uploadedBytes
1273
+ },
1274
+ value
1275
+ };
1276
+ },
1277
+ uploadSdk({ access, as, maxBytes }) {
1278
+ environmentOpen();
1279
+ if (!Number.isSafeInteger(maxBytes) || maxBytes < 1 || maxBytes > 16 * 1024 * 1024) throw failure("invalid-input", "Invalid upload byte allowance");
1280
+ const grant = grants.get(access);
1281
+ if (!grant || grant.key !== null || grant.credential.kind !== "app-key") throw failure("denied", "Owner access is unavailable");
1282
+ return createUploadSdk(environment.application({
1283
+ access,
1284
+ as
1285
+ }), maxBytes, `ed25519:${grant.context.id}`, (close) => {
1286
+ grant.context.transportCleanup.add(close);
1287
+ return () => {
1288
+ grant.context.transportCleanup.delete(close);
1289
+ };
1290
+ }, (error) => {
1291
+ if (!grant.context.cleanupErrors.includes(error)) grant.context.cleanupErrors.push(error);
1292
+ });
1293
+ }
1294
+ };
1295
+ registerRuntime(environment, {
1296
+ assertTransport() {
1297
+ if (payloadFactory) throw failure("unsupported", "Temporary-file payload storage supports direct Node calls only");
1298
+ },
1299
+ authenticate(credential) {
1300
+ environmentOpen();
1301
+ const handle = credentials.get(credential.keyHex);
1302
+ const grant = handle && grants.get(handle);
1303
+ if (!handle || !grant || grant.context.state !== "open" || grant.credential.kind !== credential.kind) throw failure("denied", "Read access is unavailable");
1304
+ return handle;
1305
+ },
1306
+ authentication(credential, operation, input, baseUrl) {
1307
+ const handle = credentials.get(credential.keyHex);
1308
+ const grant = handle && grants.get(handle);
1309
+ if (!grant || grant.context.state !== "open" || grant.credential.kind !== credential.kind) throw failure("denied", "Authentication access is unavailable");
1310
+ if (operation === "auth-connected" && credential.kind === "app-key") return input.keyHex === credential.keyHex ? { ...credential } : null;
1311
+ if (credential.kind !== "registration") throw failure("denied", "Authentication access is unavailable");
1312
+ return grant.context.authentication.execute(operation, input, baseUrl);
1313
+ },
1314
+ credential(handle) {
1315
+ environmentOpen();
1316
+ const grant = grants.get(handle);
1317
+ if (!grant || grant.context.state !== "open") throw failure("denied", "Read access is unavailable");
1318
+ return { ...grant.credential };
1319
+ },
1320
+ installShareGrants(handle, actor, installed) {
1321
+ const bindings = installed.length ? installedGrants(handle, actor, installed) : [];
1322
+ return () => createApplication(handle, actor, bindings);
1323
+ },
1324
+ onRunCleanup(handle, close) {
1325
+ const value = grants.get(handle);
1326
+ if (!value) throw failure("denied", "Owner access is unavailable");
1327
+ open(value.context);
1328
+ value.context.transportCleanup.add(close);
1329
+ return () => {
1330
+ value.context.transportCleanup.delete(close);
1331
+ };
1332
+ }
1333
+ });
1334
+ return environment;
1335
+ }
1336
+ function failure(code, message) {
1337
+ return Object.assign(new Error(message), { code });
1338
+ }
1339
+ function identifier() {
1340
+ return [...crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(32))].map((byte) => byte.toString(16).padStart(2, "0")).join("");
1341
+ }
1342
+ function integer(value, field) {
1343
+ if (!Number.isSafeInteger(value) || value < 0) throw field ? invalidInput(field, `${field} must be a nonnegative safe integer`) : failure("invalid-input", "Expected a nonnegative safe integer");
1344
+ }
1345
+ function open(context) {
1346
+ if (context.state !== "open") throw failure("closed", "Run is closed");
1347
+ context.signal.throwIfAborted();
1348
+ }
1349
+ /** Reservations happen synchronously before the first await, so parallel calls share the same allowance. */
1350
+ function track(context, action) {
1351
+ open(context);
1352
+ const promise = (async () => action())();
1353
+ context.pending.add(promise);
1354
+ promise.then(() => context.pending.delete(promise), () => context.pending.delete(promise));
1355
+ return promise;
1356
+ }
1357
+ function validateOptions(options) {
1358
+ if (!/^[0-9a-f]{64}$/.test(options.app.id) || !options.app.name || !options.app.description) throw failure("invalid-input", "Invalid application definition");
1359
+ const url = new URL(options.app.serviceUrl);
1360
+ if (!["http:", "https:"].includes(url.protocol) || url.username || url.password) throw failure("invalid-input", "Invalid application service URL");
1361
+ }
1362
+
1363
+ //#endregion
1364
+ export { bytesFixture, createMockSia, createMockSiaWithBackend };