@lumeweb/sia-testing 0.0.0-stage → 0.0.1

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 +210 -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 +90 -3
@@ -0,0 +1,148 @@
1
+ import { createNodePayloadOwner, validatePayloadLimits } from "./node-payload-store.js";
2
+ import { createMockNetworkWithPayloadOwner } from "../sdk/index.js";
3
+ import { limitedProfile, loadLiveProfile, profileDocument } from "./live/profile.js";
4
+ import { withLiveRun } from "./live/run.js";
5
+ import { recoverLiveRun } from "./live/recovery.js";
6
+ import { createMockSia, createMockSiaWithBackend } from "./mock.js";
7
+ import { createReadStream } from "node:fs";
8
+ import { mkdtemp } from "node:fs/promises";
9
+ import { tmpdir } from "node:os";
10
+ import { basename, join } from "node:path";
11
+ import { createHash } from "node:crypto";
12
+ import { fileURLToPath } from "node:url";
13
+ import { Readable } from "node:stream";
14
+
15
+ //#region src/testing/node.ts
16
+ /** Node owns a run's local adapters and fixture descriptors; the portable backend owns storage cleanup. */
17
+ const sessions = /* @__PURE__ */ new WeakMap();
18
+ async function fileFixture(path) {
19
+ const filename = typeof path === "string" ? path : fileURLToPath(path);
20
+ const hash = createHash("sha256");
21
+ let sizeBytes = 0;
22
+ const stream = createReadStream(filename);
23
+ try {
24
+ for await (const chunk of stream) {
25
+ const bytes = chunk;
26
+ sizeBytes += bytes.length;
27
+ if (sizeBytes > 16 * 1024 * 1024) throw new Error("Fixture exceeds 16 MiB");
28
+ hash.update(bytes);
29
+ }
30
+ } finally {
31
+ stream.destroy();
32
+ }
33
+ return Object.freeze({
34
+ name: basename(filename),
35
+ open: () => Readable.toWeb(createReadStream(filename)),
36
+ sha256: hash.digest("hex"),
37
+ sizeBytes
38
+ });
39
+ }
40
+ async function recoverSiaRun(options) {
41
+ const profile = await loadLiveProfile(options.backend.profileFile, options.backend.consent);
42
+ return recoverLiveRun({
43
+ journalFile: options.journalFile,
44
+ profile
45
+ });
46
+ }
47
+ async function withSiaRun(options, use) {
48
+ if (isLiveOptions(options)) {
49
+ const profile = limitedProfile(await loadLiveProfile(options.backend.profileFile, options.backend.consent), options.limits);
50
+ const journalFile = options.journalFile ?? join(await mkdtemp(join(tmpdir(), "sia-testing-run-")), "journal.jsonl");
51
+ let current;
52
+ return withLiveRun({
53
+ journalFile,
54
+ profile,
55
+ ...options.signal ? { signal: options.signal } : {},
56
+ beforeCleanup: async () => {
57
+ if (!current) return;
58
+ const session = sessions.get(current);
59
+ sessions.delete(current);
60
+ const errors = [];
61
+ for (const close of [...session?.resources ?? []].reverse()) try {
62
+ await close();
63
+ } catch (error) {
64
+ errors.push(error);
65
+ }
66
+ if (errors.length) throw new AggregateError(errors, "Application cleanup failed");
67
+ }
68
+ }, async (run) => {
69
+ current = run;
70
+ sessions.set(run, {
71
+ app: profileDocument(profile).app,
72
+ resources: []
73
+ });
74
+ return use(run);
75
+ });
76
+ }
77
+ if (options.backend.kind !== "mock") throw Object.assign(/* @__PURE__ */ new Error("Unsupported test backend"), { code: "invalid-input" });
78
+ const storage = options.backend.payloadStorage;
79
+ if (storage && storage.kind !== "temporary-files") throw new Error("Unsupported payload storage");
80
+ const budgets = storage ? validatePayloadLimits(storage.limits) : void 0;
81
+ if (budgets && options.limits?.maxLogicalUploadBytes !== void 0 && options.limits.maxLogicalUploadBytes !== budgets.maxLogicalUploadBytes) throw new Error("Run and payload logical budgets must match");
82
+ const mock = budgets ? createMockSiaWithBackend(options.backend.options, {
83
+ async create(model) {
84
+ const owner = await createNodePayloadOwner(budgets);
85
+ try {
86
+ return {
87
+ network: createMockNetworkWithPayloadOwner({ model }, owner),
88
+ owner
89
+ };
90
+ } catch (error) {
91
+ try {
92
+ await owner.close();
93
+ } catch (cleanup) {
94
+ throw new AggregateError([error, cleanup], "Backend construction and cleanup failed", { cause: cleanup });
95
+ }
96
+ throw error;
97
+ }
98
+ },
99
+ limits: budgets
100
+ }) : createMockSia(options.backend.options);
101
+ const failures = [];
102
+ let result;
103
+ try {
104
+ result = await mock.run({
105
+ app: options.backend.app,
106
+ ...options.limits && { limits: options.limits },
107
+ ...options.signal && { signal: options.signal }
108
+ }, async (run) => {
109
+ const session = {
110
+ app: options.backend.app,
111
+ resources: []
112
+ };
113
+ sessions.set(run, session);
114
+ const errors = [];
115
+ let value;
116
+ try {
117
+ value = await use(run);
118
+ } catch (error) {
119
+ errors.push(error);
120
+ }
121
+ for (const close of [...session.resources].reverse()) try {
122
+ await close();
123
+ } catch (error) {
124
+ errors.push(error);
125
+ }
126
+ sessions.delete(run);
127
+ if (errors.length === 1) throw errors[0];
128
+ if (errors.length) throw new AggregateError(errors, "Application and adapter cleanup failed");
129
+ return value;
130
+ });
131
+ } catch (error) {
132
+ failures.push(error);
133
+ }
134
+ try {
135
+ await mock.close();
136
+ } catch (error) {
137
+ failures.push(error);
138
+ }
139
+ if (failures.length === 1) throw failures[0];
140
+ if (failures.length) throw new AggregateError(failures, "Run and final close failed");
141
+ return result;
142
+ }
143
+ function isLiveOptions(options) {
144
+ return options.backend.kind === "live";
145
+ }
146
+
147
+ //#endregion
148
+ export { fileFixture, recoverSiaRun, withSiaRun };
@@ -0,0 +1,9 @@
1
+ import { OwnerSharePort } from "./types.js";
2
+ import { MockCredential } from "./runtime.js";
3
+ import { MockConnection } from "./transport.js";
4
+
5
+ //#region src/testing/owner-client.d.ts
6
+ /** Wire tokens become client-local handles so JSON copies cannot be passed back as references. */
7
+ declare function createMockOwnerShares(connection: MockConnection, credential: MockCredential): OwnerSharePort;
8
+ //#endregion
9
+ export { createMockOwnerShares };
@@ -0,0 +1,101 @@
1
+ import { domainError } from "./diagnostics.js";
2
+ import { createMockCalls, readObject } from "./client.js";
3
+
4
+ //#region src/testing/owner-client.ts
5
+ /** Owner clients retain opaque local references while authenticated connections carry wire tokens. */
6
+ /** Wire tokens become client-local handles so JSON copies cannot be passed back as references. */
7
+ function createMockOwnerShares(connection, credential) {
8
+ const { call, lifetime } = createMockCalls(connection, credential);
9
+ const tokens = /* @__PURE__ */ new WeakMap();
10
+ const references = /* @__PURE__ */ new Map();
11
+ const pending = /* @__PURE__ */ new Set();
12
+ let closing;
13
+ function execute(action) {
14
+ const promise = Promise.resolve().then(() => {
15
+ if (lifetime.signal.aborted) throw failure("closed");
16
+ return action();
17
+ });
18
+ pending.add(promise);
19
+ promise.then(() => pending.delete(promise), () => pending.delete(promise));
20
+ return promise;
21
+ }
22
+ function token(ref) {
23
+ const value = tokens.get(ref);
24
+ if (!value) throw failure("foreign-handle");
25
+ return value;
26
+ }
27
+ /** Reject malformed protocol data before it can acquire a local reference. */
28
+ function details(value) {
29
+ if (!isRecord(value) || typeof value.ref !== "string" || !/^[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/.test(value.ref) || typeof value.description !== "string" || !isRecord(value.statistics) || !integer(value.statistics.objectCount) || !integer(value.statistics.logicalBytes) || value.expiresAt !== void 0 && (typeof value.expiresAt !== "string" || !Number.isFinite(Date.parse(value.expiresAt)))) throw failure("invalid-input");
30
+ let ref = references.get(value.ref);
31
+ if (!ref) {
32
+ ref = Object.freeze(Object.create(null));
33
+ tokens.set(ref, value.ref);
34
+ references.set(value.ref, ref);
35
+ }
36
+ return {
37
+ description: value.description,
38
+ ref,
39
+ ...value.expiresAt === void 0 ? {} : { expiresAt: value.expiresAt },
40
+ statistics: {
41
+ logicalBytes: Number(value.statistics.logicalBytes),
42
+ objectCount: Number(value.statistics.objectCount)
43
+ }
44
+ };
45
+ }
46
+ async function page(operation, input, parse, ref) {
47
+ const { limit, offset, signal } = input;
48
+ if (!integer(offset)) throw domainError(operation, {
49
+ code: "invalid-input",
50
+ field: "offset"
51
+ });
52
+ if (!integer(limit) || limit === 0) throw domainError(operation, {
53
+ code: "invalid-input",
54
+ field: "limit"
55
+ });
56
+ const value = await (await call(operation, {
57
+ limit,
58
+ offset,
59
+ ...ref === void 0 ? {} : { ref: token(ref) }
60
+ }, signal)).json();
61
+ if (!isRecord(value) || !Array.isArray(value.items) || value.items.length > limit || !integer(value.nextOffset) || value.nextOffset !== offset + value.items.length || value.done !== value.items.length < limit) throw failure("invalid-input");
62
+ return {
63
+ done: value.done,
64
+ items: value.items.map(parse),
65
+ nextOffset: Number(value.nextOffset)
66
+ };
67
+ }
68
+ return {
69
+ close() {
70
+ lifetime.abort();
71
+ closing ??= Promise.allSettled([...pending]).then(() => {
72
+ references.clear();
73
+ });
74
+ return closing;
75
+ },
76
+ detail(ref, options = {}) {
77
+ const { signal } = options;
78
+ return execute(async () => details(await (await call("owner-share", { ref: token(ref) }, signal)).json()));
79
+ },
80
+ list(input) {
81
+ const pageInput = { ...input };
82
+ return execute(() => page("owner-shares", pageInput, details));
83
+ },
84
+ objects(ref, input) {
85
+ const pageInput = { ...input };
86
+ return execute(() => page("owner-share-objects", pageInput, readObject, ref));
87
+ }
88
+ };
89
+ }
90
+ function failure(code) {
91
+ return Object.assign(/* @__PURE__ */ new Error("Owner share request failed"), { code });
92
+ }
93
+ function integer(value) {
94
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
95
+ }
96
+ function isRecord(value) {
97
+ return !!value && typeof value === "object" && !Array.isArray(value);
98
+ }
99
+
100
+ //#endregion
101
+ export { createMockOwnerShares };
@@ -0,0 +1,80 @@
1
+ import { invalidInput } from "./diagnostics.js";
2
+
3
+ //#region src/testing/owner-shares.ts
4
+ /** Owner inspection joins held reads before their run can release its state. */
5
+ /** Track calls before their first microtask so immediate close still joins them. */
6
+ function createOwnerSharePort(input) {
7
+ const abort = new AbortController();
8
+ const pending = /* @__PURE__ */ new Set();
9
+ let closing;
10
+ function request(operation, signal, action) {
11
+ const callSignal = AbortSignal.any([
12
+ input.signal,
13
+ abort.signal,
14
+ ...signal ? [signal] : []
15
+ ]);
16
+ const promise = Promise.resolve().then(() => {
17
+ if (abort.signal.aborted) throw Object.assign(/* @__PURE__ */ new Error("Owner port is closed"), { code: "closed" });
18
+ input.authorize();
19
+ return input.track(async () => {
20
+ const receipt = await input.controls.begin(input.actor, operation, void 0, callSignal);
21
+ try {
22
+ callSignal.throwIfAborted();
23
+ input.authorize();
24
+ const value = await action();
25
+ receipt.status = "completed";
26
+ return value;
27
+ } catch (error) {
28
+ receipt.status = callSignal.aborted ? "cancelled" : "failed";
29
+ throw error;
30
+ }
31
+ });
32
+ });
33
+ pending.add(promise);
34
+ promise.then(() => pending.delete(promise), () => pending.delete(promise));
35
+ return promise;
36
+ }
37
+ return {
38
+ close() {
39
+ abort.abort();
40
+ closing ??= Promise.allSettled([...pending]).then(() => void 0);
41
+ return closing;
42
+ },
43
+ detail(ref, options = {}) {
44
+ return request("owner-share", options.signal, () => input.read.detail(ref));
45
+ },
46
+ list(page) {
47
+ const { limit, offset, signal } = page;
48
+ return request("owner-shares", signal, () => input.read.list({
49
+ limit,
50
+ offset
51
+ }));
52
+ },
53
+ objects(ref, page) {
54
+ const { limit, offset, signal } = page;
55
+ return request("owner-share-objects", signal, () => input.read.objects(ref, {
56
+ limit,
57
+ offset
58
+ }));
59
+ }
60
+ };
61
+ }
62
+ function ownerPage(items, { limit, offset }) {
63
+ validateOwnerPage({
64
+ limit,
65
+ offset
66
+ });
67
+ const rows = items.slice(offset, offset + limit);
68
+ return {
69
+ done: rows.length < limit,
70
+ items: rows,
71
+ nextOffset: offset + rows.length
72
+ };
73
+ }
74
+ function validateOwnerPage({ limit, offset }) {
75
+ if (!Number.isSafeInteger(offset) || offset < 0) throw invalidInput("offset", "offset must be a nonnegative safe integer");
76
+ if (!Number.isSafeInteger(limit) || limit <= 0) throw invalidInput("limit", "limit must be a positive safe integer");
77
+ }
78
+
79
+ //#endregion
80
+ export { createOwnerSharePort, ownerPage, validateOwnerPage };
@@ -0,0 +1,46 @@
1
+ import { ActorRef, BrowserAccess } from "./types.js";
2
+
3
+ //#region src/testing/packed.d.ts
4
+ declare const packedOwnership: unique symbol;
5
+ interface PackedAppKey {
6
+ readonly [packedOwnership]: "packed-key";
7
+ }
8
+ interface PackedObject {
9
+ id(): string;
10
+ readonly [packedOwnership]: "packed-object";
11
+ /** Validates ownership only; no sealed record or cryptographic proof is produced. */
12
+ seal(key: PackedAppKey): void;
13
+ updateMetadata(metadata: Uint8Array): void;
14
+ }
15
+ interface PackedOptions {
16
+ readonly dataShards?: number;
17
+ readonly maxBufferedSlabs?: number;
18
+ readonly parityShards?: number;
19
+ }
20
+ interface PackedSdk<P extends "browser" | "node"> {
21
+ appKey(): PackedAppKey;
22
+ close(): Promise<void>;
23
+ pinObject(object: PackedObject): Promise<void>;
24
+ updateObjectMetadata(object: PackedObject): Promise<void>;
25
+ uploadPacked(options?: PackedOptions): PackedUpload<P>;
26
+ }
27
+ interface PackedSdkOptions<P extends "browser" | "node"> {
28
+ readonly access: BrowserAccess;
29
+ readonly as: ActorRef;
30
+ readonly maxBytes: number;
31
+ readonly maxObjects: number;
32
+ readonly platform: P;
33
+ }
34
+ interface PackedUpload<P extends "browser" | "node"> {
35
+ add(stream: ReadableStream<Uint8Array>): Promise<P extends "node" ? bigint : number>;
36
+ cancel(): void;
37
+ dispose(): Promise<void>;
38
+ finalize(): Promise<PackedObject[]>;
39
+ }
40
+ /** Carries only original objects acknowledged before a later finalization failure. */
41
+ declare class PackedFinalizeError extends Error {
42
+ readonly objects: readonly PackedObject[];
43
+ constructor(cause: unknown, objects: readonly PackedObject[]);
44
+ }
45
+ //#endregion
46
+ export { PackedAppKey, PackedFinalizeError, PackedObject, PackedOptions, PackedSdk, PackedSdkOptions, PackedUpload };