@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,647 @@
1
+ # Mock application contracts
2
+
3
+ Use these contracts when testing writes or transport adapters. For complete runnable setup, see the [Vitest tests](../README.md).
4
+
5
+ ## Inspect mock shares as their owner
6
+
7
+ Inside a `mock.run({ app }, async (run) => { ... })` callback, use owner access rather than recipient access:
8
+
9
+ ```ts
10
+ const share = await run.shares.create({ objects: [], description: "Reading list" });
11
+ const owner = mock.ownerShares({ access: run.ownerAccess, as: mock.actor("owner UI") });
12
+ try {
13
+ const page = await owner.list({ offset: 0, limit: 10 });
14
+ const row = page.items[0]!;
15
+ console.log((await owner.detail(row.ref)).description);
16
+ console.log((await owner.objects(row.ref, { offset: 0, limit: 10 })).items);
17
+ } finally {
18
+ await owner.close();
19
+ }
20
+ ```
21
+
22
+ `description` is a mock-only fixture option; live managed shares retain their existing interface. Owner details report current attachment count and logical payload bytes, not slab sizes or physical storage usage. Contents return detached metadata copies. Expired shares remain inspectable by owners, while recipients lose fresh access. Revoked shares disappear from the catalogue and stale references fail.
23
+
24
+ For the same reads over an owned HTTP or MSW endpoint:
25
+
26
+ ```ts
27
+ import { createMockOwnerShares } from "@lumeweb/sia-testing/client";
28
+
29
+ const connection = endpoint.connection({ access: run.ownerAccess, as: mock.actor("owner HTTP") });
30
+ const owner = createMockOwnerShares(connection, connection.credential);
31
+ try {
32
+ console.log(await owner.list({ offset: 0, limit: 10 }));
33
+ } finally {
34
+ await owner.close();
35
+ }
36
+ ```
37
+
38
+ References are opaque runtime-owned handles, not share IDs or recipient credentials. Direct references belong to their mock run. Transport references belong to the authenticated connection and local client that materialized them; copied JSON and references from another client cannot be used as handles. Wire tokens alone grant no authority. Recipient and registration connections cannot upgrade to owner inspection by substituting an owner key.
39
+
40
+ Pages are current reads, not snapshots across edits. Ordering is deterministic for unchanged state. Offsets must be nonnegative safe integers and limits positive safe integers. Responses contain at most the requested limit, subject to the run's fixture allowances. `nextOffset` advances by the returned item count; `done` is true when fewer than `limit` items are returned, so an exactly full final page needs an empty follow-up page. `list`, `detail` and `objects` accept an abort signal. Repeated `close()` is safe, cancels held requests and joins pending calls. Run cleanup cancels retained ports before releasing state. Owner reads use the finite actor-selected `owner-shares`, `owner-share` and `owner-share-objects` controls.
41
+
42
+ ## Driver diagnostics
43
+
44
+ `actor(label)` keeps the label as driver-visible diagnostic text. Request receipts
45
+ from `history()`, `hold.started()` and `hold.cancelled()` include `actorLabel` for
46
+ reads and mutations. Labels grant no authority: actors with equal labels remain
47
+ distinct, and selectors require the original actor reference. Choose labels that
48
+ can appear in test failure reports; do not put credentials or private data in them.
49
+ History retains the latest 256 requests in start order. A held request can leave
50
+ history before it finishes; its hold still returns labelled snapshots.
51
+
52
+ Invalid fault `times` and invalid link rates or latency throw errors with
53
+ `code: "invalid-input"`. Page validation messages identify `offset` or `limit`.
54
+ Fetch domain errors include the local operation and a known invalid field when
55
+ available, without forwarding callback messages or request values. Error codes
56
+ remain available on the error's `code` property; narrow an unknown error before
57
+ reading that property.
58
+
59
+ Closing the loopback listener rejects new backend dispatch and cancels pending
60
+ owned requests. It preserves already-started response delivery. If cancellation
61
+ can still deliver a domain response, the caller receives `code: "closed"`.
62
+ A mutation cancelled before its effect retains `committed: false`; cancellation
63
+ cannot undo an effect that already committed. Closing the listener does not close
64
+ other direct ports in the run. Caller aborts and client close keep native cancellation behavior.
65
+ Actual response loss remains a native Fetch error, including lost pin replies;
66
+ cleanup failures can still reject with `AggregateError`. The package does not
67
+ retry or publish events in response to errors.
68
+
69
+ ## Application writes (mock only)
70
+
71
+ `mock.application({ access: run.ownerAccess, as: actor })` returns an
72
+ `ApplicationPort`. Give that port to application code; keep the run and
73
+ `mock.publish` in the test driver. Managed `run.objects.upload` still uploads
74
+ and pins in one call.
75
+
76
+ See the complete [manual-clock test](../README.md#publish-application-writes).
77
+
78
+ `writer.pin(object, { metadata, signal })` optionally replaces committed metadata.
79
+ The byte view is copied once at invocation, before holds or transport dispatch.
80
+ Metadata must be a `Uint8Array` of at most 1024 bytes. Omission and explicit
81
+ `undefined` preserve the current committed bytes, including on repin; empty bytes
82
+ clear them. Membership, replacement bytes and the committed receipt change in one
83
+ synchronous effect. Before that effect, owner reads see the prior value (or no
84
+ object on a first pin). A failed or cancelled attempt before commit preserves it.
85
+ A lost reply after commit retains the replacement. Concurrent attempts follow
86
+ commit order; omission cannot reset another attempt's committed replacement.
87
+ `inspect` reports membership only and cannot identify a concurrent metadata
88
+ commit. Publication, event fields and second-based coalescing remain unchanged.
89
+ This is synthetic application metadata, not native encrypted object metadata.
90
+
91
+ `inspect` reads `"missing"`, `"uploaded"` or `"pinned"` from owned state;
92
+ `delete` accepts only an application's original object reference. Fixture
93
+ handles, copied references and foreign-run references grant no write authority.
94
+ Deleting a pending upload discards only its owned slab; deleting a pinned object
95
+ queues a tombstone. All pending and acknowledged payloads belong to the run.
96
+
97
+ `mutationFaults.hold` is one-shot. `mutationFaults.fail(selector, { code,
98
+ times })` accepts `denied` or `unavailable` and a positive finite integer count.
99
+ Both target `upload`, `pin` or `delete` at `beforeCommit`. Selectors may name an
100
+ owned actor and application object (upload has no object yet). Holds expose
101
+ `started()`, `cancelled()` and `release()`. Receipts record `committed` separately
102
+ from settlement, without source bytes, file names or private metadata.
103
+ Cancellation or rejection before commit changes no payload or model state;
104
+ closing a direct port cancels and joins its sources and holds. Cancellation after
105
+ an effect does not undo it. No automatic write retries or idempotency promise
106
+ is provided.
107
+
108
+ ### Lost mutation acknowledgements
109
+
110
+ `mock.mutationFaults.loseReply(selector, { times })` drops acknowledgement after
111
+ a successful upload, pin, delete, share Add, Remove or End commits. `MutationReplySelector`
112
+ and the source-compatible `PinReplySelector` are exported from `mock`. Every
113
+ selector requires the original actor; `times` is a positive safe integer.
114
+ For `operation: "pin" | "delete"`, an optional `object` must be an original
115
+ backend reference from a direct application port. HTTP and MSW object references
116
+ are client-local, so those clients use actor/operation selection.
117
+ For `operation: "share-add" | "share-remove" | "share-end"`, optional `share`
118
+ selects an original driver grant across all its installations. Another grant for
119
+ the same share does not match. Share selectors accept neither objects nor IDs.
120
+ Selectors and options are snapshotted when installed.
121
+ For `operation: "upload"`, neither `object` nor `share` is accepted. Read reply
122
+ losses are unsupported. Rejection or cancellation before the effect and
123
+ successful no-ops leave the fault armed.
124
+
125
+ ```ts
126
+ const known = await writer.upload({ file, name: file.name, metadata: new Uint8Array() });
127
+ mock.mutationFaults.loseReply({ actor, operation: "pin" }, { times: 1 });
128
+ try {
129
+ await writer.pin(known);
130
+ } catch (error) {
131
+ // A direct port rejects with code "unavailable". Fetch clients get a network error.
132
+ const state = await writer.inspect(known);
133
+ if (state !== "pinned") throw error;
134
+ }
135
+ // The application has reconciled the pin; no event exists until the driver publishes.
136
+ const unpublished = await writer.events({ cursor: null, limit: 10 });
137
+ ```
138
+
139
+ Inspection confirms the object's current state without publication or driver
140
+ receipts. It does not report which earlier call committed. HTTP sends a deliberately
141
+ incomplete response prefix before destroying the owned connection to prevent
142
+ browser POST replay; MSW returns a network failure. Native Fetch errors retain
143
+ their platform's class and fields. Nothing retries, resends or rolls back
144
+ the mutation. Driver receipts may record `committed: true` with a failed caller outcome;
145
+ those receipts are not an application recovery API. Explicit publication keeps
146
+ the same event-coalescing behavior as an acknowledged pin.
147
+
148
+ A lost upload acknowledgement can reject without returning any application
149
+ object. Collected bytes, explicit metadata and committed logical-byte charges
150
+ remain owned by the run. Upload does not pin, create a catalogue row or queue an
151
+ account object event; explicit publication cannot reveal the staged upload.
152
+ Inspection requires an original application handle. Neither a generated ID in a
153
+ driver receipt, a copied object nor a fresh client can recover that missing
154
+ handle. The outcome stays unknown to the application. Another explicit upload
155
+ is a new attempt, not a retry with deduplication. Port close joins work without
156
+ discarding committed uploads; run cleanup discards unpinned payloads and clears
157
+ their records and metadata.
158
+
159
+ Upload `beforeCommit` holds and failures run after source collection and hash
160
+ verification. Validation and allowance rejection before collection open no
161
+ source. The local SDK stages payloads and synchronously completes application
162
+ record, metadata, accounting and receipt bookkeeping before Promise observers.
163
+ Post-effect cancellation does not release the committed byte reservation.
164
+
165
+ After a lost delete reply, retain the original application object and explicitly
166
+ call `writer.inspect(object)`; committed deletion reports `"missing"`. Staged
167
+ discard creates no event. Pinned deletion removes membership, metadata and payload
168
+ and queues the existing tombstone for explicit publication. Deletion refunds
169
+ neither committed bytes nor object attempts.
170
+
171
+ After lost Add or Remove replies, explicitly call
172
+ `writer.shares.inspect(ref, object.id)` to inspect current selected membership.
173
+ After lost End, inspect lifecycle with `writer.shares.inspect(ref, null)`; a valid
174
+ grant reports `"ended"` without restoring recipient access. A later mutation can
175
+ change membership before inspection, so inspection does not prove which request
176
+ won. Withdrawing the grant denies inspection and leaves the caller's outcome
177
+ unknown. No automatic inspection or resend occurs.
178
+
179
+ Application uploads allow files up to 16 MiB, metadata up to 1024 bytes and names
180
+ up to 1024 UTF-8 bytes. Run object-attempt and logical-byte allowances are
181
+ reserved before the source opens. Application uploads that fail before the
182
+ effect release active byte reservations; object attempts stay charged. Committed
183
+ bytes stay charged after lost acknowledgement, cancellation or deletion. Managed fixture allowance behavior is unchanged.
184
+
185
+ Events use the run's existing account feed, including managed fixture events.
186
+ Use a fresh run or explicitly published fixture cursor as your baseline.
187
+ Pages accept limits from 1 to 1000. A cursor is `{ after, id }`, with a canonical
188
+ whole-second ISO timestamp and a lowercase 64-character hexadecimal object ID.
189
+ Continuation is exclusive in timestamp/ID order. `nextCursor` is the last row,
190
+ or the input cursor on an empty page; a full page has `done: false` and may need
191
+ an empty continuation. Publication coalesces each object's current event and
192
+ requires a later clock second after a prior publication. Later publication can
193
+ move a lower-ID object past an older cursor. Publication targets only the
194
+ owner-authenticated run; it never acknowledges an application ledger.
195
+
196
+ ### Recreate clients against a retained mock backend
197
+
198
+ Retain acknowledged object IDs and event cursors as application data. Close the
199
+ original clients, keep the same run and backend open, then create new clients
200
+ with valid access. Use `mock.reader({ access, as })` directly, or
201
+ `createMockReader(connection, credential)` from `@lumeweb/sia-testing/client`
202
+ with a new HTTP/MSW connection. `reader.object(id)` returns current pinned
203
+ membership, metadata and size; `reader.download({ id })` reads the bytes. These
204
+ reads can reconcile a known pin whose reply was lost without repeating a write.
205
+ They do not identify which concurrent request committed. An unpinned or deleted
206
+ object has no readable row. Recipient reads still require current share access;
207
+ revocation denies fresh reads.
208
+
209
+ `ApplicationPort.events({ cursor, limit })` accepts a retained cursor on a new
210
+ authorized client. Events require explicit driver publication, so an absent event
211
+ does not establish that a pin failed. Read current membership and metadata through
212
+ the reader rather than treating an old event or receipt as current state.
213
+
214
+ Readable IDs, rows, cursors and diagnostic receipts never create mutation handles.
215
+ Direct application object references belong to the run and can be used by another
216
+ owner-authorized direct port in that run, even after the originating port closes.
217
+ Fetch application references belong to their local client; a recreated client
218
+ rejects the old references. Packed objects and keys belong to their SDK session.
219
+ Retained packed IDs can locate authorized reads after SDK close, but a new SDK
220
+ cannot mutate the old objects. Preserve every acknowledged packed identity;
221
+ reading one pinned result does not establish that all results were pinned.
222
+ Unknown uploads without an acknowledged handle remain unknown; owner enumeration
223
+ is not a handle recovery method.
224
+
225
+ This supports client recreation within one retained mock run. It does not prove
226
+ backend restart durability, browser reload persistence, native SDK behavior or
227
+ consumer checkpoint policy.
228
+
229
+ ### Fetch-backed application ports
230
+
231
+ Import `createMockApplication` from `@lumeweb/sia-testing/client` and pass a
232
+ connection from the existing HTTP or MSW endpoint plus the application's current
233
+ credential. The same scoped dispatcher implements these ports; this protocol
234
+ is not native Indexd compatibility. Publication remains a test-driver action.
235
+
236
+ The upload client obtains a private, authenticated one-use admission before
237
+ opening `file`. It then buffers at most the admitted file size, checks its hash,
238
+ and sends raw bytes, without base64 expansion or streaming Fetch request bodies.
239
+ The server counts the incoming stream independently of `Content-Length` and
240
+ rejects oversize or incomplete bodies before any upload effect. File bodies have
241
+ the same admitted logical/raw limit of 16 MiB; other routes retain their
242
+ 16,384-byte body limit. Admissions expire after 30 seconds of real time. They
243
+ cannot be replayed or moved between connections or credentials.
244
+
245
+ Close the client port before leaving the backend run when immediate local source
246
+ teardown matters. Client close cancels and joins its collector; its original
247
+ admission deadline also cancels collection. Backend run or endpoint close
248
+ invalidates admissions and joins backend-owned work, but cannot synchronously
249
+ stop JavaScript collecting a file in a remote client. A client left open can
250
+ collect only until its admission deadline and cannot commit with an invalidated
251
+ token. HTTP server close and MSW endpoint `close()` invalidate outstanding
252
+ admissions; the application never receives fixture or publication controls.
253
+ Application endpoint close also cancels and joins its active dispatches, including
254
+ held mutations and admission JSON reads.
255
+
256
+ Object selectors accept only backend-owned references returned by a direct
257
+ `mock.application` port, as in the example above. HTTP/MSW clients materialize
258
+ client-local references; those references, JSON copies and foreign mock handles
259
+ cannot arm backend object controls. For a transport client, allocate an actor
260
+ per binding and select its next operation instead:
261
+
262
+ ```ts
263
+ const hold = mock.mutationFaults.hold({ actor, operation: "pin", stage: "beforeCommit" });
264
+ const pinning = writer.pin(pending); // writer may be an HTTP or MSW client
265
+ await hold.started();
266
+ hold.release();
267
+ await pinning;
268
+ ```
269
+
270
+ | Operation | Direct mock port | HTTP/MSW client |
271
+ | ---------------------------------------- | ------------------------- | ------------------------------- |
272
+ | Upload, pin, inspect, delete, events | Supported | Supported |
273
+ | Finite actor/operation mutation controls | Supported | Supported |
274
+ | Backend object selector | Original direct reference | Client-local reference rejected |
275
+ | Publication | Test driver only | No publication route |
276
+
277
+ ### Loopback response lifetime
278
+
279
+ The listener returned by `startMockServer` closes gracefully: cancelling backend
280
+ work does not cancel buffered JSON already being delivered. A successful backend
281
+ request can finish before its response body reaches the caller. If a raw HTTP client leaves that
282
+ body unread, listener close can remain pending until the peer drains or
283
+ disconnects. Close does not guarantee that every response flushes, or join
284
+ unrelated JavaScript in a remote client. Streaming producers can still react to
285
+ the request's abort signal.
286
+
287
+ Before awaiting listener close, close the client port or consume or cancel raw
288
+ responses. The Fetch-backed ports consume JSON response bodies; their `close()`
289
+ aborts pending Fetch calls. For a raw Fetch response, consume its body or cancel
290
+ `response.body`; if the stream is locked, cancel its reader instead. For Node
291
+ `http`, drain the response with `resume()` or destroy the response and client.
292
+ Playwright consumers must close their contexts before the listener. External
293
+ clients remain responsible for their own response lifetimes.
294
+
295
+ ## Connect applications
296
+
297
+ `endpoint.connection({ access, as })` materializes a fake mock credential for an application adapter. Pass the application's current credential to `createMockReader`; a recipient endpoint rejects owner-key substitution. `createMockAuth` accepts the connection's credential or an explicit credential. Requests use the driver's approval state rather than injecting connected UI state.
298
+
299
+ Playwright tests compose `/node` `withSiaRun` with `/http` `startMockServer` and their own contexts. Install `endpoint.connection({ access, as }).credential` before navigation. Close contexts before the endpoint, then return from the managed run. Do not put credentials in test configuration.
300
+
301
+ `/vitest` exports `createSiaTest`, a native Vitest `TestAPI<SiaTestFixtures>`. Each test requesting `sia` owns a fresh portable `MockRun`; fixture extension uses Vitest's `test.extend`. The runner signal and optional external signal cancel owned mock work. A shared external signal cancels all its users. The fixture does not own pages, listeners or arbitrary caller promises.
302
+
303
+ The low-level fixture, model, and SDK exports and the `/msw/node` wrapper are not available. There are no compatibility aliases.
304
+
305
+ ## Edit an explicitly granted share
306
+
307
+ Share edits are mock-only. The driver issues a grant for one share and one
308
+ original actor, then installs it on an application or endpoint connection:
309
+
310
+ ```ts
311
+ const actor = mock.actor("share editor");
312
+ const share = await run.shares.create({ objects: [] });
313
+ const grant = await run.shares.grant(share, {
314
+ as: actor,
315
+ label: "reading-list",
316
+ operations: ["add", "remove", "end"],
317
+ });
318
+ const app = mock.application({
319
+ access: run.ownerAccess,
320
+ as: actor,
321
+ shareGrants: [grant],
322
+ });
323
+ const [target] = await app.shares.targets();
324
+ const object = await app.upload({ file, metadata: new Uint8Array() });
325
+ await app.pin(object);
326
+ await app.shares.add(target!.ref, object);
327
+ await app.shares.remove(target!.ref, object.id);
328
+ await app.shares.end(target!.ref);
329
+ const ended = await app.shares.inspect(target!.ref, null);
330
+ // ended is { state: "ended", contains: null }.
331
+ await app.close();
332
+ ```
333
+
334
+ `ApplicationPort.shares` provides `targets(options?)`,
335
+ `inspect(ref, objectId: string | null, options?)`, `add(ref, object, options?)`,
336
+ `remove(ref, objectId, options?)`, and `end(ref, options?)`. Each options object
337
+ accepts `signal?: AbortSignal`. Targets contain a client-bound opaque `ref`, the
338
+ driver's `label`, an operations snapshot, and an optional canonical ISO
339
+ `expiresAt`. Owner share refs remain read-only and cannot authorize edits.
340
+ Copied refs, fixture handles, IDs, and receipts do not grant mutation authority.
341
+ Omitting `shareGrants` installs no authority. Labels must differ within an
342
+ installed set; labels do not authorize requests.
343
+
344
+ `grant` requires nonempty, unique operations from `add`, `remove`, and `end`.
345
+ It snapshots the operations and optional `expiresAt: Date`. An explicit deadline
346
+ must be finite and future; without one the grant lasts until withdrawal or run
347
+ cleanup. Issuance requires an active share and the original actor. A grant can
348
+ be installed on several clients for its actor. `run.shares.revokeGrant(grant)`
349
+ withdraws only that grant from every installation and is a no-op when repeated.
350
+ It does not revoke the share or other grants.
351
+
352
+ Add requires a genuine, pinned, undeleted application object in the same run.
353
+ It never pins or changes metadata. Direct ports retain their existing run-scoped
354
+ object acceptance; Fetch object handles remain client-local. Remove's ID selects
355
+ membership under the grant and grants no object access. End revokes recipient
356
+ access without deleting owned payloads or changing sibling shares. Already-open
357
+ download streams keep their existing behavior.
358
+
359
+ Inspection requires a valid grant, even after End. It returns `active`, `expired`,
360
+ or `ended`, with current membership as `contains` for a supplied object ID.
361
+ Lifecycle-only inspection and ended shares return `contains: null`. Expired
362
+ shares remain inspectable but reject mutations. End takes precedence over share
363
+ expiry; repeated End with valid End permission succeeds without a change.
364
+ Revoked or deadline-reached grants deny inspection and mutations and disappear
365
+ from targets. An ended share stays in the roster while its grant is valid.
366
+
367
+ Before-effect mutation selectors support `share-add`, `share-remove`, and
368
+ `share-end`; read selectors support `share-targets` and `share-inspect`.
369
+ `share-inspect` and share mutations can select the original driver grant with
370
+ `share: grant`, across all installations. Diagnostic share IDs are not selectors.
371
+ Calls validate before controls and recheck authority, lifecycle, cancellation,
372
+ and Add's object eligibility after a hold. No-op calls still pass through controls.
373
+ Receipts report `committed: true` only when membership or revocation changes;
374
+ repeated Add, absent Remove, and repeated End report false without rewriting
375
+ timestamps. Effects, fixture state, and receipt attribution finish synchronously.
376
+ Share edits create no account object events and do not publish.
377
+
378
+ For HTTP or MSW, pass `shareGrants` to the existing `endpoint.connection` call.
379
+ Application code receives only its connection and credential and uses
380
+ `createMockApplication(connection, credential)`. First targets establishes a
381
+ private session; subsequent calls reuse it. Each application instance has its
382
+ own refs, even on one connection. A raw holder of a credential and a complete
383
+ session token has bearer authority; sessions do not isolate browser processes.
384
+ Client close aborts and joins local requests and discards local share refs,
385
+ without remotely revoking bearer tokens. Run cleanup aborts and joins its work
386
+ and removes only its entries; endpoint close joins all remaining work and
387
+ releases registrations. A lost first targets reply can leave an unreferenced
388
+ session until run or endpoint cleanup. Calls do not retry or recover sessions
389
+ automatically.
390
+
391
+ ## Direct SDK 0.2 upload simulation
392
+
393
+ `mock.uploadSdk({ access: run.ownerAccess, as: actor, maxBytes })` provides a
394
+ small, direct SDK-shaped upload surface. Import `MockPinnedObject` from `mock`
395
+ and pass a fresh handle to `sdk.upload(handle, stream)`. The input handle is
396
+ freed when upload starts; the returned handle can be pinned with
397
+ `sdk.pinObject(handle)` and must be freed by its caller. `appKey().publicKey()`
398
+ returns a synthetic account label, not a cryptographic key. Close the SDK to
399
+ join its application port before ending the run. Run cleanup also closes an
400
+ unclosed SDK and reports source cancellation failures.
401
+
402
+ ```ts
403
+ const sdk = mock.uploadSdk({
404
+ access: run.ownerAccess,
405
+ as: mock.actor("uploader"),
406
+ maxBytes: 1024,
407
+ });
408
+ try {
409
+ const draft = new MockPinnedObject();
410
+ draft.updateMetadata(Uint8Array.of(7));
411
+ const object = await sdk.upload(draft, new Blob([Uint8Array.of(1)]).stream());
412
+ try {
413
+ await sdk.pinObject(object);
414
+ } finally {
415
+ object.free();
416
+ }
417
+ } finally {
418
+ await sdk.close();
419
+ }
420
+ ```
421
+
422
+ The upload collects at most `maxBytes` (from 1 through 16 MiB) before calling
423
+ the owned application port, which applies the run's upload limits and fault
424
+ controls. Metadata is copied before the source opens and again when pin starts;
425
+ a metadata change on the returned handle is included in that pin. `free()`
426
+ invalidates a local handle without deleting its staged or pinned object.
427
+ An uploaded handle from another SDK is not a fresh upload input.
428
+ `mutationFaults` for `upload` and `pin`, including lost replies, retain their
429
+ application-port behavior. The run owns unpublished object data and cleans it
430
+ up after the test. Source overflow cancels the source before any upload effect.
431
+
432
+ This mock accepts `dataShards`, `parityShards` and `onShardUploaded`. After a
433
+ successful staged upload, it reports one synthetic callback for each encoded
434
+ shard, using the SDK's sector size and zero elapsed time. The mock requires a
435
+ positive `dataShards`, nonnegative `parityShards` and a combined count at most 255. It sends no callback when staging fails, and it does not simulate host
436
+ transfers, shard retries or callback timing during upload. Other upload options
437
+ reject as unsupported.
438
+ This mock does not encrypt, upload to hosts, seal handles, resume uploads or
439
+ replace a native SDK 0.2 binding with a full `Sdk` implementation. A lost upload reply can leave an inaccessible staged
440
+ object; a lost pin reply can leave a readable pinned object.
441
+
442
+ ## Direct SDK-shaped packed simulation
443
+
444
+ `mock.packedSdk({ access, as, platform, maxBytes, maxObjects })` uses original
445
+ owner access and actor capabilities. `platform` is `"node"` or `"browser"`;
446
+ `add(stream)` returns `Promise<bigint>` or `Promise<number>` respectively,
447
+ matching that part of SDK 0.2.0. The handle from `uploadPacked(options?)` is
448
+ synchronous. The supported options are positive safe integer `dataShards`,
449
+ `parityShards` and `maxBufferedSlabs`. They validate caller configuration;
450
+ they do not change simulated storage layout. Host progress callbacks are
451
+ unsupported and reject before admission.
452
+
453
+ ```ts
454
+ const sdk = mock.packedSdk({
455
+ access: run.ownerAccess,
456
+ as: mock.actor("packed writer"),
457
+ platform: "browser",
458
+ maxBytes: 1024,
459
+ maxObjects: 1,
460
+ });
461
+ try {
462
+ const packed = sdk.uploadPacked({ dataShards: 1, parityShards: 1 });
463
+ await packed.add(
464
+ new ReadableStream<Uint8Array>({
465
+ start(controller) {
466
+ controller.enqueue(Uint8Array.of(1, 2));
467
+ controller.close();
468
+ },
469
+ }),
470
+ );
471
+ for (const object of await packed.finalize()) {
472
+ object.updateMetadata(Uint8Array.of(7));
473
+ await sdk.updateObjectMetadata(object);
474
+ await sdk.pinObject(object);
475
+ object.seal(sdk.appKey());
476
+ }
477
+ } finally {
478
+ await sdk.close();
479
+ }
480
+ ```
481
+
482
+ Each successful add produces one independently pinnable object, including a
483
+ zero-byte input. No adds produces no objects. IDs use the run identity and
484
+ reserved object ordinal; repeated equal inputs do not alias. Sources are
485
+ collected in memory with an aggregate maximum of 16 MiB. This path does not
486
+ prove bounded-memory streaming, real slabs, encryption, host transfer or native
487
+ packed correctness. It is available only on the direct mock; HTTP and MSW do
488
+ not expose SDK-shaped packed calls.
489
+
490
+ Each `uploadPacked` reserves `maxBytes` and `maxObjects` against the same run
491
+ allowances as application and managed uploads before it locks a source. Invalid
492
+ configuration, owner access and exhausted run admission read no source. Object
493
+ attempts are not refunded, including empty or failed finalization. Finalization
494
+ and disposal release unused byte reservations; acknowledged uploaded bytes
495
+ remain charged. Failed adds consume no object slot within that packed handle.
496
+ Source byte overflow fails and cancels the source. This does not raise existing
497
+ application limits or change managed mock metadata (uncapped) or managed live
498
+ metadata (16384 bytes).
499
+
500
+ `updateMetadata(Uint8Array)` copies up to 1024 bytes locally. This deliberately
501
+ accepts a wider input than native Node's `Buffer` signature. No native-shaped
502
+ `metadata()` method is exposed. `updateObjectMetadata` snapshots local bytes at
503
+ invocation and commits through the existing object store; reads through the
504
+ owner reader return detached copies after pinning. Local changes alone do not
505
+ change stored metadata. Concurrent metadata calls follow commit order.
506
+ Publication remains explicit.
507
+
508
+ `mutationFaults` accepts `packed-add`, `packed-finalize` and `metadata` with
509
+ `stage: "beforeCommit"` and optional original actor. Add controls run after
510
+ collection, finalize controls run before each result's staging (once for an
511
+ empty batch), and metadata controls run before the metadata effect. Existing
512
+ `pin` holds, failures and reply losses also apply. These selectors do not accept
513
+ packed object IDs as authority. Existing application upload `beforeCommit`
514
+ still runs after collection and hashing.
515
+
516
+ Only one add or finalize may run per upload; overlap rejects with `code: "busy"`.
517
+ A failed add permits another add. Finalize is one-shot, including failure.
518
+ If finalization fails after staging results, `PackedFinalizeError.objects`
519
+ contains the original acknowledged object capabilities and `cause` retains the
520
+ original failure. A failure before any result propagates unchanged. No rollback,
521
+ retry or publication runs automatically. The caller may pin acknowledged partial
522
+ objects explicitly while the SDK session remains open.
523
+
524
+ `cancel()` interrupts reads and held work. `dispose()` cancels and joins that
525
+ upload, releases its buffers and unused byte reservation, and retains source
526
+ cancellation errors. `sdk.close()` does the same for every unfinished upload
527
+ and joins metadata and pin calls. Neither deletes acknowledged objects. Run
528
+ cleanup closes sessions and then deletes run-owned resources; it continues after
529
+ source cleanup errors and reports them. Closing one session does not close its
530
+ siblings. A source failure plus a cancellation failure is an `AggregateError`
531
+ containing both actual errors.
532
+
533
+ Packed objects and app keys belong to their original SDK session. Copies,
534
+ read records, guessed IDs, diagnostics and keys from sibling sessions cannot
535
+ mutate or seal. `seal(key)` validates the original object and key and returns
536
+ `void`. It does not create a sealed record, signature, encryption proof or
537
+ recovery capability. Code needing sealed output is unsupported by this mock.
538
+ The surface is not assignable to full native nominal classes. Package checks
539
+ separately check the consumed Node/browser 0.2.0 signatures and the intentional
540
+ seal output omission; no compatibility with SDK 0.0.12 is established.
541
+
542
+ ### Chunked fixtures and collection controls
543
+
544
+ `chunkedFixture({ name, sizeBytes, chunkSizeBytes, pattern })`, exported by
545
+ `mock` and `node`, repeats a snapshotted nonempty byte pattern by absolute
546
+ position. Each open generates detached chunks on pull without prefetching.
547
+ Output generation uses output-chunk-sized working storage. Incremental SHA-256
548
+ hashing reuses a block of at most 65,536 bytes independently of output chunk
549
+ size, plus the pattern and hash state. Fixture construction still hashes the
550
+ actual bytes synchronously before its promise resolves. Size must be a safe
551
+ integer from zero through 16 MiB; chunk size and pattern length are limited to 1 through 65,536 bytes.
552
+ These limits apply to this fixture constructor only. Existing byte and file
553
+ fixture policies are unchanged.
554
+
555
+ ```ts
556
+ const file = await chunkedFixture({
557
+ name: "pattern",
558
+ sizeBytes: 7,
559
+ chunkSizeBytes: 3,
560
+ pattern: Uint8Array.of(1, 2),
561
+ });
562
+ const hold = mock.mutationFaults.hold({
563
+ actor,
564
+ operation: "upload",
565
+ stage: "collect",
566
+ afterBytes: 2,
567
+ });
568
+ const pending = writer.upload({ file, metadata: new Uint8Array() });
569
+ const receipt = await hold.started(); // bytes is 3 for this direct producer
570
+ hold.release();
571
+ await pending;
572
+ ```
573
+
574
+ Collection selectors require an owned actor, operation `upload` or `packed-add`,
575
+ and a nonnegative safe-integer `afterBytes`. Existing finite `fail` options
576
+ apply. Unknown and cross-stage fields reject before arming. Zero opens the
577
+ source but holds or fails before the first read. Positive thresholds match the
578
+ first validated, copied whole-chunk boundary reaching or exceeding the count.
579
+ An oversized chunk may already have been read; thresholds do not split chunks.
580
+ EOF below a threshold leaves the fault armed. A reached failure consumes one
581
+ configured occurrence. Validation, admission, source and hash failures leave
582
+ unreached faults armed. Empty chunks do not increase the accepted byte count.
583
+
584
+ The collector awaits controls before another read. Producer-owned chunk bytes
585
+ are copied before that wait. Caller, port, packed session or run cancellation
586
+ cancels the owned reader and joins producer cleanup; cleanup failures are
587
+ reported separately from repeated errors of an already errored reader.
588
+ `started()` and `cancelled()` expose snapshots with `stage: "collect"`, accepted
589
+ bytes and a stable receipt ID. Collection receipts stay outside `history()`;
590
+ its existing effect receipts remain unchanged and have different IDs.
591
+ `beforeCommit` still runs after full collection and hash checking where the
592
+ upload descriptor has a hash. No failed collection stages objects, metadata or
593
+ events. Attempts remain charged; uncommitted byte reservations are released.
594
+
595
+ Application uploads still buffer up to the existing 16 MiB limit. Fetch clients
596
+ collect and hash the original file before sending. HTTP and MSW controls affect
597
+ the admitted backend request body, so they cannot pace or cancel that original
598
+ client producer retroactively. Transport chunk boundaries can differ from file
599
+ chunk boundaries. Packed SDK simulation remains direct-only. These fixtures do
600
+ not establish end-to-end streaming, native upload behavior or browser producer
601
+ backpressure. Observation deadlines do not cancel owned work.
602
+
603
+ ## Direct Node temporary-file payloads
604
+
605
+ `withSiaRun` from `/node` accepts `backend.payloadStorage` with kind
606
+ `temporary-files` and required `limits`: `maxObjectBytes`,
607
+ `maxLogicalUploadBytes`, `maxRetainedBytes`, and `maxUploadAttempts`.
608
+ The ceilings are 64 MiB per object, 128 MiB cumulative logical uploads,
609
+ 128 MiB retained reservation, and 16 admitted source acquisitions per run.
610
+ An explicit run logical allowance must equal the storage logical allowance.
611
+ Omitting storage options preserves buffered mode and its existing defaults.
612
+
613
+ This mode supports direct application calls and packed SDK sessions with
614
+ `platform: "node"`. HTTP, MSW and browser-shaped packed
615
+ sessions reject. Fixture factory limits, metadata policies, authority and
616
+ mock slab layout do not change. This is Node simulation, not native packing,
617
+ streaming Fetch or browser storage.
618
+
619
+ Application and packed sources use bounded temporary spools and incremental
620
+ SHA-256. Each source view and its backing ArrayBuffer must be at most 64 KiB;
621
+ shared, resizable and detached backing storage rejects. Every admitted source,
622
+ including each failed or empty packed add, spends an attempt. Each source is
623
+ limited to 131072 chunks, including empty chunks. One upload reservation
624
+ (including an idle packed handle) and two download descriptor leases may be
625
+ active. Managed uploads remain buffered, but acquire the same physical
626
+ admission before source opening. Their buffers and uncapped managed metadata
627
+ are excluded from the bounded streaming-payload claim.
628
+
629
+ Retained capacity includes incomplete files, uncommitted inputs, unused packed
630
+ allowance and failed-removal residue. Logical committed bytes are cumulative;
631
+ deleting an object does not refund them. Serialization in temporary-file mode
632
+ always rejects. Buffered V1 snapshots remain supported in buffered mode.
633
+
634
+ Explicit cancel, disposal and close join owned work. No automatic operation,
635
+ download or idle deadline is added. Uncooperative source cancellation can keep
636
+ close pending. A rejected descriptor close retains its lease and makes that
637
+ run reject new uploads/downloads; other runs remain independent. Failed unlink
638
+ retains its entry and reservation, including an empty file. Cleanup attempts
639
+ independent resources and reports original failures and residue rather than a
640
+ clean summary. Physical operations are not automatically retried. Catching a
641
+ cleanup error does not make final run cleanup clean.
642
+
643
+ The backend owns a fresh private temporary root and random filenames, assumes
644
+ a trusted temporary parent and operating-system account, and accepts no caller
645
+ root or user paths. There is no crash recovery or residue sweep. Payload byte
646
+ quotas do not measure filesystem overhead, page cache, caller buffers or total
647
+ process memory.