@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,56 @@
1
+ import { privatePath } from "./private-files.js";
2
+ import { constants } from "node:fs";
3
+ import { lstat, open, unlink } from "node:fs/promises";
4
+ import { dirname } from "node:path";
5
+ import { randomUUID } from "node:crypto";
6
+
7
+ //#region src/testing/live/lease.ts
8
+ /** A private lease file prevents a run and recovery from mutating the same journal concurrently. */
9
+ async function acquireJournalLease(journalPath) {
10
+ const path = await privatePath(journalPath + ".lease");
11
+ const parent = await lstat(dirname(path));
12
+ if (!parent.isDirectory() || parent.uid !== process.getuid() || (parent.mode & 63) !== 0) throw failure("lease-invalid");
13
+ let file;
14
+ let code = "lease-invalid";
15
+ try {
16
+ file = await open(path, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 384);
17
+ } catch (error) {
18
+ if (error && typeof error === "object" && "code" in error && error.code === "EEXIST") code = "lease-busy";
19
+ }
20
+ if (!file) throw failure(code);
21
+ const owned = file;
22
+ const identity = await owned.stat();
23
+ try {
24
+ await owned.writeFile(JSON.stringify({
25
+ pid: process.pid,
26
+ token: randomUUID()
27
+ }));
28
+ await owned.sync();
29
+ } catch {
30
+ await owned.close();
31
+ throw failure("lease-invalid");
32
+ }
33
+ let release;
34
+ return Object.freeze({ release() {
35
+ release ??= (async () => {
36
+ try {
37
+ const current = await lstat(path);
38
+ if (current.dev !== identity.dev || current.ino !== identity.ino || current.nlink !== 1) throw failure("lease-uncertain");
39
+ await unlink(path);
40
+ } finally {
41
+ await owned.close();
42
+ }
43
+ })();
44
+ return release;
45
+ } });
46
+ }
47
+ function failure(code) {
48
+ return Object.assign(/* @__PURE__ */ new Error("Sia journal lease operation failed"), {
49
+ code,
50
+ phase: "journal",
51
+ uncertain: code === "lease-uncertain"
52
+ });
53
+ }
54
+
55
+ //#endregion
56
+ export { acquireJournalLease };
@@ -0,0 +1,50 @@
1
+ import { constants } from "node:fs";
2
+ import { access, open, realpath } from "node:fs/promises";
3
+ import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
4
+
5
+ //#region src/testing/live/private-files.ts
6
+ /** Credential-bearing files stay outside the checkout and are opened without following final symlinks. */
7
+ async function privatePath(path, workspaceRoot) {
8
+ if (!isAbsolute(path) || !process.getuid) throw new Error("Invalid private file path");
9
+ const actual = join(await realpath(dirname(path)), basename(path));
10
+ if (await checkoutRoot(dirname(actual))) throw new Error("Private file is inside a checkout");
11
+ const checkout = workspaceRoot === void 0 ? await checkoutRoot(process.cwd()) : await realpath(workspaceRoot);
12
+ if (checkout) {
13
+ const child = relative(checkout, actual);
14
+ if (child === "" || !isAbsolute(child) && child !== ".." && !child.startsWith(`..${sep}`)) throw new Error("Private file is inside the checkout");
15
+ }
16
+ return actual;
17
+ }
18
+ async function readPrivateBytes(path, maximum, workspaceRoot) {
19
+ const file = await open(await privatePath(path, workspaceRoot), constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
20
+ try {
21
+ return await readPrivateHandle(file, maximum);
22
+ } finally {
23
+ await file.close();
24
+ }
25
+ }
26
+ async function readPrivateHandle(file, maximum) {
27
+ const stat = await file.stat();
28
+ if (!stat.isFile() || stat.uid !== process.getuid() || stat.nlink !== 1 || (stat.mode & 63) !== 0 || stat.size > maximum) throw new Error("Invalid private file ownership or size");
29
+ const buffer = Buffer.alloc(maximum + 1);
30
+ let length = 0;
31
+ while (length < buffer.length) {
32
+ const result = await file.read(buffer, length, buffer.length - length, null);
33
+ if (!result.bytesRead) break;
34
+ length += result.bytesRead;
35
+ }
36
+ if (length > maximum) throw new Error("Private file exceeds its size limit");
37
+ return buffer.subarray(0, length);
38
+ }
39
+ async function checkoutRoot(directory) {
40
+ let current = resolve(directory);
41
+ for (;;) {
42
+ if (await access(join(current, ".git")).then(() => true, () => false)) return await realpath(current);
43
+ const parent = dirname(current);
44
+ if (parent === current) return void 0;
45
+ current = parent;
46
+ }
47
+ }
48
+
49
+ //#endregion
50
+ export { privatePath, readPrivateBytes, readPrivateHandle };
@@ -0,0 +1,208 @@
1
+ import { fork } from "node:child_process";
2
+
3
+ //#region src/testing/live/process.ts
4
+ /** Owned RPC processes are stopped before a timeout or cancellation is returned to the caller. */
5
+ function startOwnedProcess(options) {
6
+ if (!positive(options.deadlineMs) || !positive(options.cleanupDeadlineMs)) throw failure("invalid-input");
7
+ const environment = {};
8
+ for (const key of [
9
+ "PATH",
10
+ "HOME",
11
+ "TMPDIR",
12
+ "TEMP",
13
+ "TMP",
14
+ "LANG",
15
+ "SYSTEMROOT"
16
+ ]) if (process.env[key] !== void 0) environment[key] = process.env[key];
17
+ const child = fork(options.entrypoint, [], {
18
+ env: environment,
19
+ execArgv: [],
20
+ serialization: "advanced",
21
+ stdio: [
22
+ "ignore",
23
+ "ignore",
24
+ "ignore",
25
+ "ipc"
26
+ ]
27
+ });
28
+ const pending = /* @__PURE__ */ new Map();
29
+ let dead = false;
30
+ let closing = false;
31
+ let online = false;
32
+ let reason;
33
+ let stopped;
34
+ let ready;
35
+ let exited;
36
+ const readiness = new Promise((resolve) => {
37
+ ready = resolve;
38
+ });
39
+ const exit = new Promise((resolve) => {
40
+ exited = resolve;
41
+ });
42
+ function rejectAll(code) {
43
+ for (const [id, request] of pending) {
44
+ pending.delete(id);
45
+ clearTimeout(request.timer);
46
+ request.detach();
47
+ request.reject(failure(code));
48
+ }
49
+ }
50
+ function finish() {
51
+ if (dead) return;
52
+ dead = true;
53
+ closing = true;
54
+ ready();
55
+ rejectAll(reason ?? "agent-exit");
56
+ exited();
57
+ }
58
+ child.once("exit", finish);
59
+ child.on("error", () => {
60
+ if (child.pid === void 0) {
61
+ reason ??= "agent-start";
62
+ finish();
63
+ } else if (!closing) abort("agent-protocol");
64
+ });
65
+ child.on("disconnect", () => {
66
+ if (!closing && !dead) abort("agent-exit");
67
+ });
68
+ function stop(code = "closed") {
69
+ reason ??= code;
70
+ closing = true;
71
+ if (dead) return Promise.resolve();
72
+ if (stopped) return stopped;
73
+ stopped = new Promise((resolve, reject) => {
74
+ const force = setTimeout(() => child.kill("SIGKILL"), Math.min(200, Math.floor(options.cleanupDeadlineMs / 2)));
75
+ const deadline = setTimeout(() => {
76
+ rejectAll("agent-termination");
77
+ reject(failure("agent-termination"));
78
+ }, options.cleanupDeadlineMs);
79
+ exit.then(() => {
80
+ clearTimeout(force);
81
+ clearTimeout(deadline);
82
+ resolve();
83
+ });
84
+ child.kill("SIGTERM");
85
+ });
86
+ return stopped;
87
+ }
88
+ function abort(code) {
89
+ stop(code).catch(() => void 0);
90
+ }
91
+ child.on("message", (message) => {
92
+ if (closing || dead) return;
93
+ if (!message || typeof message !== "object" || Array.isArray(message) || !("type" in message)) {
94
+ abort("agent-protocol");
95
+ return;
96
+ }
97
+ if (message.type === "ready") {
98
+ if (online) {
99
+ abort("agent-protocol");
100
+ return;
101
+ }
102
+ online = true;
103
+ ready();
104
+ return;
105
+ }
106
+ if (!online) {
107
+ abort("agent-protocol");
108
+ return;
109
+ }
110
+ if (message.type === "event") {
111
+ if (!("requestId" in message) || typeof message.requestId !== "string" || !pending.has(message.requestId) || !("name" in message) || typeof message.name !== "string" || !("value" in message) || !options.onEvent) {
112
+ abort("agent-protocol");
113
+ return;
114
+ }
115
+ const event = {
116
+ name: message.name,
117
+ requestId: message.requestId,
118
+ value: message.value
119
+ };
120
+ Promise.resolve().then(() => options.onEvent(event)).catch(() => abort("agent-event"));
121
+ return;
122
+ }
123
+ if (!("id" in message) || typeof message.id !== "string") {
124
+ abort("agent-protocol");
125
+ return;
126
+ }
127
+ const request = pending.get(message.id);
128
+ if (!request) {
129
+ abort("agent-protocol");
130
+ return;
131
+ }
132
+ if (message.type === "error") {
133
+ const known = /* @__PURE__ */ new Set([
134
+ "approval-denied",
135
+ "authentication",
136
+ "denied",
137
+ "invalid-approval",
138
+ "invalid-input",
139
+ "missing-hosts",
140
+ "not-found",
141
+ "not-ready",
142
+ "quota",
143
+ "resource-error",
144
+ "sdk-error",
145
+ "sdk-version"
146
+ ]);
147
+ abort("code" in message && typeof message.code === "string" && known.has(message.code) ? message.code : "sdk-error");
148
+ return;
149
+ }
150
+ if (message.type !== "result" || !("value" in message)) {
151
+ abort("agent-protocol");
152
+ return;
153
+ }
154
+ pending.delete(message.id);
155
+ clearTimeout(request.timer);
156
+ request.detach();
157
+ request.resolve(message.value);
158
+ });
159
+ return {
160
+ close: () => stop(),
161
+ pid: child.pid ?? -1,
162
+ request(operation, value, call = {}) {
163
+ if (closing || dead) return Promise.reject(failure("closed"));
164
+ const deadline = call.deadlineMs ?? options.deadlineMs;
165
+ if (!positive(deadline) || !/^[a-z][a-z-]{0,63}$/.test(operation)) return Promise.reject(failure("invalid-input"));
166
+ const id = crypto.randomUUID();
167
+ return new Promise((resolve, reject) => {
168
+ const cancelled = () => abort("cancelled");
169
+ pending.set(id, {
170
+ detach: () => call.signal?.removeEventListener("abort", cancelled),
171
+ reject,
172
+ resolve,
173
+ timer: setTimeout(() => abort("deadline"), deadline)
174
+ });
175
+ call.signal?.addEventListener("abort", cancelled, { once: true });
176
+ if (call.signal?.aborted) cancelled();
177
+ readiness.then(() => {
178
+ if (closing || dead || !pending.has(id)) return;
179
+ try {
180
+ child.send({
181
+ id,
182
+ operation,
183
+ type: "request",
184
+ value
185
+ }, (error) => {
186
+ if (error) abort("agent-protocol");
187
+ });
188
+ } catch {
189
+ abort("agent-protocol");
190
+ }
191
+ });
192
+ });
193
+ }
194
+ };
195
+ }
196
+ function failure(code) {
197
+ return Object.assign(/* @__PURE__ */ new Error("Sia SDK process failed"), {
198
+ code,
199
+ phase: "execution",
200
+ uncertain: code === "agent-termination"
201
+ });
202
+ }
203
+ function positive(value) {
204
+ return Number.isSafeInteger(value) && value > 0 && value <= 12e4;
205
+ }
206
+
207
+ //#endregion
208
+ export { startOwnedProcess };
@@ -0,0 +1,214 @@
1
+ import { readPrivateBytes } from "./private-files.js";
2
+
3
+ //#region src/testing/live/profile.ts
4
+ /** Private profiles are opened without following the final link and never serialize their credentials. */
5
+ const profiles = /* @__PURE__ */ new WeakMap();
6
+ const defaults = {
7
+ cleanupDeadlineMs: 3e4,
8
+ deadlineMs: 12e4,
9
+ maxDecodedDownloadBytes: 32 * 1024 * 1024,
10
+ maxLogicalUploadBytes: 16 * 1024 * 1024,
11
+ maxObjects: 8,
12
+ maxObservedShardBytes: 64 * 1024 * 1024,
13
+ maxShares: 8
14
+ };
15
+ /** Cleanup reconnects with an acknowledged app key, so it never consumes a second preauthorization. */
16
+ function appKeyProfile(profile, appKeyHex, cleanup = false) {
17
+ if (!/^[a-f0-9]{64}$/.test(appKeyHex)) throw failure("invalid-profile");
18
+ const document = profileDocument(profile);
19
+ const reserve = Math.min(250, Math.floor(document.limits.cleanupDeadlineMs / 2));
20
+ const limits = cleanup ? Object.freeze({
21
+ ...document.limits,
22
+ cleanupDeadlineMs: Math.max(1, reserve),
23
+ deadlineMs: Math.max(1, document.limits.cleanupDeadlineMs - reserve)
24
+ }) : document.limits;
25
+ const derived = Object.freeze(Object.defineProperties(Object.create(null), {
26
+ [Symbol.for("nodejs.util.inspect.custom")]: { value: () => "[Sia live profile]" },
27
+ toJSON: { value: () => "[Sia live profile]" }
28
+ }));
29
+ profiles.set(derived, Object.freeze({
30
+ ...document,
31
+ auth: Object.freeze({
32
+ appKeyHex,
33
+ kind: "app-key"
34
+ }),
35
+ limits
36
+ }));
37
+ return derived;
38
+ }
39
+ function limitedProfile(profile, overrides) {
40
+ if (!overrides) return profile;
41
+ const document = profileDocument(profile);
42
+ const limits = { ...document.limits };
43
+ for (const [key, value] of Object.entries(overrides)) {
44
+ if (![
45
+ "maxLogicalUploadBytes",
46
+ "maxObjects",
47
+ "maxShares"
48
+ ].includes(key) || !Number.isSafeInteger(value) || value < 0 || value > document.limits[key]) throw failure("invalid-profile");
49
+ limits[key] = value;
50
+ }
51
+ const derived = Object.freeze(Object.defineProperties(Object.create(null), {
52
+ [Symbol.for("nodejs.util.inspect.custom")]: { value: () => "[Sia live profile]" },
53
+ toJSON: { value: () => "[Sia live profile]" }
54
+ }));
55
+ profiles.set(derived, Object.freeze({
56
+ ...document,
57
+ limits: Object.freeze(limits)
58
+ }));
59
+ return derived;
60
+ }
61
+ async function loadLiveProfile(path, consent, workspaceRoot) {
62
+ if (consent?.transfers !== true || consent.mutations !== true) throw failure("consent-required");
63
+ let approved;
64
+ try {
65
+ approved = endpoint(consent.apiBaseUrl);
66
+ } catch {
67
+ throw failure("consent-required");
68
+ }
69
+ let document;
70
+ try {
71
+ const bytes = await readPrivateBytes(path, 16384, workspaceRoot);
72
+ document = parse(JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes)));
73
+ } catch {
74
+ throw failure("invalid-profile");
75
+ }
76
+ if (document.apiBaseUrl !== approved) throw failure("consent-required");
77
+ const profile = Object.freeze(Object.defineProperties(Object.create(null), {
78
+ [Symbol.for("nodejs.util.inspect.custom")]: { value: () => "[Sia live profile]" },
79
+ toJSON: { value: () => "[Sia live profile]" }
80
+ }));
81
+ profiles.set(profile, document);
82
+ return profile;
83
+ }
84
+ function profileDocument(profile) {
85
+ const document = profiles.get(profile);
86
+ if (!document) throw failure("invalid-profile");
87
+ return document;
88
+ }
89
+ function endpoint(value) {
90
+ const url = new URL(text(value));
91
+ if (url.username || url.password || url.hash || url.search || url.protocol !== "https:" && !(url.protocol === "http:" && ["127.0.0.1", "[::1]"].includes(url.hostname))) throw failure("invalid-profile");
92
+ url.pathname = url.pathname.endsWith("/") ? url.pathname : url.pathname + "/";
93
+ return url.href;
94
+ }
95
+ function failure(code) {
96
+ return Object.assign(/* @__PURE__ */ new Error(code === "invalid-profile" ? "Invalid private Sia profile" : "Explicit Sia endpoint and transfer consent is required"), {
97
+ code,
98
+ phase: "configuration"
99
+ });
100
+ }
101
+ function hex(value) {
102
+ if (typeof value !== "string" || !/^[a-fA-F0-9]{64}$/.test(value)) throw failure("invalid-profile");
103
+ return value.toLowerCase();
104
+ }
105
+ function integer(value, minimum, maximum) {
106
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value < minimum || value > maximum) throw failure("invalid-profile");
107
+ return value;
108
+ }
109
+ function keys(value, allowed) {
110
+ if (Object.keys(value).some((key) => !allowed.includes(key))) throw failure("invalid-profile");
111
+ }
112
+ function parse(value) {
113
+ const input = record(value);
114
+ keys(input, [
115
+ "version",
116
+ "apiBaseUrl",
117
+ "app",
118
+ "encoding",
119
+ "limits",
120
+ "auth"
121
+ ]);
122
+ if (input.version !== 1) throw failure("invalid-profile");
123
+ const app = record(input.app);
124
+ keys(app, [
125
+ "id",
126
+ "name",
127
+ "description",
128
+ "serviceUrl"
129
+ ]);
130
+ const definition = Object.freeze({
131
+ description: text(app.description),
132
+ id: hex(app.id),
133
+ name: text(app.name),
134
+ serviceUrl: publicUrl(app.serviceUrl)
135
+ });
136
+ const encoding = record(input.encoding);
137
+ keys(encoding, [
138
+ "dataShards",
139
+ "parityShards",
140
+ "maxBufferedSlabs"
141
+ ]);
142
+ const coding = Object.freeze({
143
+ dataShards: integer(encoding.dataShards, 1, 255),
144
+ maxBufferedSlabs: integer(encoding.maxBufferedSlabs, 1, 8),
145
+ parityShards: integer(encoding.parityShards, 0, 254)
146
+ });
147
+ if (coding.dataShards + coding.parityShards > 255) throw failure("invalid-profile");
148
+ const auth = record(input.auth);
149
+ let authentication;
150
+ if (auth.kind === "app-key") {
151
+ keys(auth, ["kind", "appKeyHex"]);
152
+ authentication = {
153
+ appKeyHex: hex(auth.appKeyHex),
154
+ kind: "app-key"
155
+ };
156
+ } else if (auth.kind === "register") {
157
+ keys(auth, [
158
+ "kind",
159
+ "phrase",
160
+ "connectKey"
161
+ ]);
162
+ authentication = {
163
+ connectKey: text(auth.connectKey),
164
+ kind: "register",
165
+ phrase: text(auth.phrase)
166
+ };
167
+ } else if (auth.kind === "preauthorized") {
168
+ keys(auth, [
169
+ "kind",
170
+ "phrase",
171
+ "preauthorizedKeyHex"
172
+ ]);
173
+ authentication = {
174
+ kind: "preauthorized",
175
+ phrase: text(auth.phrase),
176
+ preauthorizedKeyHex: hex(auth.preauthorizedKeyHex)
177
+ };
178
+ } else throw failure("invalid-profile");
179
+ const limits = input.limits === void 0 ? {} : record(input.limits);
180
+ keys(limits, Object.keys(defaults));
181
+ const bounded = Object.freeze({
182
+ cleanupDeadlineMs: integer(limits.cleanupDeadlineMs ?? defaults.cleanupDeadlineMs, 1, 12e4),
183
+ deadlineMs: integer(limits.deadlineMs ?? defaults.deadlineMs, 1, 12e4),
184
+ maxDecodedDownloadBytes: integer(limits.maxDecodedDownloadBytes ?? defaults.maxDecodedDownloadBytes, 0, 64 * 1024 * 1024),
185
+ maxLogicalUploadBytes: integer(limits.maxLogicalUploadBytes ?? defaults.maxLogicalUploadBytes, 0, 16 * 1024 * 1024),
186
+ maxObjects: integer(limits.maxObjects ?? defaults.maxObjects, 0, 64),
187
+ maxObservedShardBytes: integer(limits.maxObservedShardBytes ?? defaults.maxObservedShardBytes, 0, 256 * 1024 * 1024),
188
+ maxShares: integer(limits.maxShares ?? defaults.maxShares, 0, 64)
189
+ });
190
+ return Object.freeze({
191
+ apiBaseUrl: endpoint(input.apiBaseUrl),
192
+ app: definition,
193
+ auth: Object.freeze(authentication),
194
+ encoding: coding,
195
+ limits: bounded,
196
+ version: 1
197
+ });
198
+ }
199
+ function publicUrl(value) {
200
+ const url = new URL(text(value));
201
+ if (!["http:", "https:"].includes(url.protocol) || url.username || url.password) throw failure("invalid-profile");
202
+ return url.href;
203
+ }
204
+ function record(value) {
205
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw failure("invalid-profile");
206
+ return value;
207
+ }
208
+ function text(value) {
209
+ if (typeof value !== "string" || !value.trim() || value.length > 4096) throw failure("invalid-profile");
210
+ return value;
211
+ }
212
+
213
+ //#endregion
214
+ export { appKeyProfile, limitedProfile, loadLiveProfile, profileDocument };
@@ -0,0 +1,164 @@
1
+ import { profileDocument } from "./profile.js";
2
+ import { resumeJournal } from "./journal.js";
3
+ import { acquireJournalLease } from "./lease.js";
4
+ import { cleanupKnownResources } from "./cleanup.js";
5
+
6
+ //#region src/testing/live/recovery.ts
7
+ /** Recovery uses acknowledged credentials and resource records, preserving creation outcomes it cannot identify. */
8
+ async function recoverLiveRun(options) {
9
+ const document = profileDocument(options.profile);
10
+ const lease = await acquireJournalLease(options.journalFile);
11
+ const errors = [];
12
+ let journal;
13
+ let recovered;
14
+ let uncertain = false;
15
+ try {
16
+ const resumed = await resumeJournal(options.journalFile);
17
+ journal = resumed.journal;
18
+ recovered = replay(resumed.snapshot);
19
+ if (recovered.header.apiBaseUrl !== document.apiBaseUrl || recovered.header.appId !== document.app.id) throw failure("journal-mismatch");
20
+ if (!recovered.appKeyHex && (recovered.objects.length || recovered.shares.length)) throw failure("journal-invalid");
21
+ if (recovered.appKeyHex) await cleanupKnownResources({
22
+ ...options.agentModule ? { agentModule: options.agentModule } : {},
23
+ appKeyHex: recovered.appKeyHex,
24
+ journal,
25
+ objects: recovered.objects,
26
+ profile: options.profile,
27
+ shares: recovered.shares
28
+ });
29
+ uncertain = recovered.unknownCreations > 0;
30
+ } catch (error) {
31
+ errors.push(error);
32
+ uncertain = true;
33
+ }
34
+ const summary = Object.freeze({
35
+ backend: "live",
36
+ cleanup: uncertain ? "uncertain" : "clean",
37
+ id: recovered?.header.runId ?? "unknown",
38
+ journalFile: options.journalFile,
39
+ logicalUploadedBytes: recovered?.objects.filter((object) => object.pinned).reduce((sum, object) => sum + object.sizeBytes, 0) ?? 0,
40
+ observedShardBytes: recovered?.observedShardBytes ?? 0
41
+ });
42
+ try {
43
+ if (recovered) await journal?.append({
44
+ cleanup: summary.cleanup,
45
+ kind: "complete"
46
+ });
47
+ } catch (error) {
48
+ errors.push(error);
49
+ uncertain = true;
50
+ }
51
+ try {
52
+ await journal?.close();
53
+ } catch (error) {
54
+ errors.push(error);
55
+ uncertain = true;
56
+ }
57
+ try {
58
+ await lease.release();
59
+ } catch (error) {
60
+ errors.push(error);
61
+ uncertain = true;
62
+ }
63
+ const finalSummary = uncertain && summary.cleanup === "clean" ? Object.freeze({
64
+ ...summary,
65
+ cleanup: "uncertain"
66
+ }) : summary;
67
+ if (uncertain && errors.length === 0) errors.push(failure("cleanup-uncertain"));
68
+ if (errors.length) throw Object.assign(new AggregateError(errors, "Sia live resource recovery failed"), { summary: finalSummary });
69
+ return finalSummary;
70
+ }
71
+ function failure(code) {
72
+ return Object.assign(/* @__PURE__ */ new Error("Sia live resource recovery failed"), {
73
+ code,
74
+ phase: "recovery"
75
+ });
76
+ }
77
+ function identifier(value, share = false) {
78
+ if (typeof value !== "string" || !(share ? /^(?:ed25519:)?[a-f0-9]{64}$/ : /^[a-f0-9]{64}$/).test(value)) throw failure("journal-invalid");
79
+ return value;
80
+ }
81
+ function record(value) {
82
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw failure("journal-invalid");
83
+ return value;
84
+ }
85
+ function replay(snapshot) {
86
+ const header = snapshot.records[0];
87
+ if (header?.kind !== "header") throw failure("journal-invalid");
88
+ const intents = /* @__PURE__ */ new Map();
89
+ const acknowledged = /* @__PURE__ */ new Set();
90
+ const failedWithoutEffect = /* @__PURE__ */ new Set();
91
+ const objects = /* @__PURE__ */ new Map();
92
+ const shares = /* @__PURE__ */ new Map();
93
+ let appKeyHex;
94
+ let observedShardBytes = 0;
95
+ for (const event of snapshot.records.slice(1)) if (event.kind === "auth") {
96
+ if (appKeyHex) throw failure("journal-invalid");
97
+ appKeyHex = event.appKeyHex;
98
+ } else if (event.kind === "intent") {
99
+ if (intents.has(event.id) || ![
100
+ "attach",
101
+ "create-share",
102
+ "delete",
103
+ "detach",
104
+ "pin",
105
+ "revoke",
106
+ "upload"
107
+ ].includes(event.operation)) throw failure("journal-invalid");
108
+ intents.set(event.id, event);
109
+ } else if (event.kind === "failure") {
110
+ if (!intents.has(event.id)) throw failure("journal-invalid");
111
+ if (!event.uncertain) failedWithoutEffect.add(event.id);
112
+ } else if (event.kind === "ack") {
113
+ const intent = intents.get(event.id);
114
+ if (!intent || acknowledged.has(event.id) || failedWithoutEffect.has(event.id)) throw failure("journal-invalid");
115
+ acknowledged.add(event.id);
116
+ if (intent.operation === "upload") {
117
+ const result = record(event.result);
118
+ const objectId = identifier(result.objectId);
119
+ if (objects.has(objectId) || typeof result.sealed !== "string" || !result.sealed || typeof result.sizeBytes !== "number" || !Number.isSafeInteger(result.sizeBytes) || result.sizeBytes < 0 || typeof result.observedShardBytes !== "number" || !Number.isSafeInteger(result.observedShardBytes) || result.observedShardBytes < observedShardBytes) throw failure("journal-invalid");
120
+ observedShardBytes = result.observedShardBytes;
121
+ objects.set(objectId, {
122
+ deleted: false,
123
+ objectId,
124
+ pinned: false,
125
+ sealed: result.sealed,
126
+ sizeBytes: result.sizeBytes
127
+ });
128
+ } else if (intent.operation === "create-share") {
129
+ const result = record(event.result);
130
+ const shareId = identifier(result.shareId, true);
131
+ if (shares.has(shareId) || typeof result.seedHex !== "string" || !/^[a-f0-9]{64}$/.test(result.seedHex)) throw failure("journal-invalid");
132
+ shares.set(shareId, {
133
+ revoked: false,
134
+ seedHex: result.seedHex,
135
+ shareId
136
+ });
137
+ } else {
138
+ const input = record(intent.input);
139
+ if (intent.operation === "pin" || intent.operation === "delete" || intent.operation === "attach" || intent.operation === "detach") {
140
+ const object = objects.get(identifier(input.objectId));
141
+ if (!object) throw failure("journal-invalid");
142
+ if (intent.operation === "pin") object.pinned = true;
143
+ if (intent.operation === "delete") object.deleted = true;
144
+ }
145
+ if (intent.operation === "revoke" || intent.operation === "attach" || intent.operation === "detach") {
146
+ const share = shares.get(identifier(input.shareId, true));
147
+ if (!share) throw failure("journal-invalid");
148
+ if (intent.operation === "revoke") share.revoked = true;
149
+ }
150
+ }
151
+ }
152
+ const unknownCreations = [...intents.values()].filter((intent) => (intent.operation === "upload" || intent.operation === "create-share") && !acknowledged.has(intent.id) && !failedWithoutEffect.has(intent.id)).length;
153
+ return {
154
+ appKeyHex,
155
+ header,
156
+ objects: [...objects.values()],
157
+ observedShardBytes,
158
+ shares: [...shares.values()],
159
+ unknownCreations
160
+ };
161
+ }
162
+
163
+ //#endregion
164
+ export { recoverLiveRun };