@jini-ai/platform 0.7.2 → 0.7.3-next.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 (169) hide show
  1. package/CHANGELOG.md +2 -8
  2. package/README.md +16 -4
  3. package/dist/asset-cache.d.ts +13 -3
  4. package/dist/asset-cache.js +163 -154
  5. package/dist/blob-storage.d.ts +3 -32
  6. package/dist/blob-storage.js +1 -9
  7. package/dist/child-environment.d.ts +0 -16
  8. package/dist/child-environment.js +0 -25
  9. package/dist/command.d.ts +6 -11
  10. package/dist/command.js +8 -54
  11. package/dist/download-lock.d.ts +4 -0
  12. package/dist/download-lock.js +82 -0
  13. package/dist/download-maintenance.d.ts +5 -0
  14. package/dist/download-maintenance.js +82 -0
  15. package/dist/download-state.d.ts +8 -0
  16. package/dist/download-state.js +126 -0
  17. package/dist/download-store.d.ts +22 -0
  18. package/dist/download-store.js +174 -0
  19. package/dist/download-target.d.ts +10 -0
  20. package/dist/download-target.js +102 -0
  21. package/dist/download-transfer.d.ts +12 -0
  22. package/dist/download-transfer.js +174 -0
  23. package/dist/download-types.d.ts +162 -0
  24. package/dist/download-types.js +31 -0
  25. package/dist/download.d.ts +1 -89
  26. package/dist/download.js +8 -738
  27. package/dist/fetch-with-timeout.d.ts +7 -32
  28. package/dist/fetch-with-timeout.js +1 -77
  29. package/dist/fs/app-data-root.d.ts +28 -0
  30. package/dist/fs/app-data-root.js +35 -0
  31. package/dist/fs/atomic-write.js +1 -1
  32. package/dist/fs/boot-identity.d.ts +1 -4
  33. package/dist/fs/directory-delete-guard.d.ts +93 -0
  34. package/dist/fs/directory-delete-guard.js +148 -0
  35. package/dist/fs/directory-registry.js +45 -35
  36. package/dist/fs/directory-relocation.d.ts +82 -0
  37. package/dist/fs/directory-relocation.js +99 -0
  38. package/dist/fs/directory-running-lock.d.ts +1 -1
  39. package/dist/fs/directory-running-lock.js +24 -21
  40. package/dist/fs/directory-sync.js +1 -1
  41. package/dist/fs/directory-user-config.js +30 -3
  42. package/dist/fs/directory-workspace.d.ts +34 -30
  43. package/dist/fs/directory-workspace.js +70 -29
  44. package/dist/fs/durable-json.d.ts +6 -15
  45. package/dist/fs/durable-json.js +38 -35
  46. package/dist/fs/errno.d.ts +12 -3
  47. package/dist/fs/errno.js +5 -3
  48. package/dist/fs/file-lock.d.ts +3 -87
  49. package/dist/fs/file-lock.js +16 -30
  50. package/dist/fs/guarded-reader.js +335 -315
  51. package/dist/fs/index.d.ts +5 -0
  52. package/dist/fs/index.js +5 -0
  53. package/dist/fs/recent-directories.d.ts +46 -0
  54. package/dist/fs/recent-directories.js +68 -0
  55. package/dist/fs/remove-directory-tree.d.ts +20 -0
  56. package/dist/fs/remove-directory-tree.js +28 -0
  57. package/dist/fs/user-data-directories.js +2 -2
  58. package/dist/fs/workspace-directory.js +2 -1
  59. package/dist/fs.d.ts +16 -4
  60. package/dist/fs.js +4 -4
  61. package/dist/home-expansion.d.ts +7 -2
  62. package/dist/home-expansion.js +3 -3
  63. package/dist/http/guarded/client.d.ts +1 -2
  64. package/dist/http/guarded/client.js +2 -1
  65. package/dist/http/guarded/index.d.ts +0 -3
  66. package/dist/http/guarded/node-ports.d.ts +1 -1
  67. package/dist/http/guarded/transport.fetch.d.ts +2 -3
  68. package/dist/http/guarded/transport.fetch.js +64 -58
  69. package/dist/http.d.ts +3 -1
  70. package/dist/http.js +2 -2
  71. package/dist/index.d.ts +10 -11
  72. package/dist/index.js +7 -6
  73. package/dist/mail/activity/activity.d.ts +136 -0
  74. package/dist/mail/activity/activity.js +172 -0
  75. package/dist/mail/activity/ports.d.ts +113 -0
  76. package/dist/mail/activity/suppressions.d.ts +82 -0
  77. package/dist/mail/activity/suppressions.js +119 -0
  78. package/dist/mail/activity/vocabulary.d.ts +10 -0
  79. package/dist/mail/activity/vocabulary.js +8 -0
  80. package/dist/mail/builtin-providers.d.ts +12 -6
  81. package/dist/mail/builtin-providers.js +14 -11
  82. package/dist/mail/delivery-wrapper.js +2 -1
  83. package/dist/mail/email-sender-registry.d.ts +1 -1
  84. package/dist/mail/email-sender-registry.js +1 -1
  85. package/dist/mail/email-template-operations.d.ts +186 -0
  86. package/dist/mail/email-template-operations.js +226 -0
  87. package/dist/mail/email-template.d.ts +120 -0
  88. package/dist/mail/email-template.js +243 -0
  89. package/dist/mail/index.d.ts +4 -0
  90. package/dist/mail/index.js +3 -0
  91. package/dist/mail/prepare-sender-email.d.ts +1 -10
  92. package/dist/mail/prepare-sender-email.js +1 -11
  93. package/dist/mail/resolve-mailer.d.ts +2 -1
  94. package/dist/mail/resolve-mailer.js +5 -2
  95. package/dist/mail/senders.d.ts +0 -1
  96. package/dist/mail/senders.js +0 -1
  97. package/dist/mail/smtp.d.ts +1 -31
  98. package/dist/net/address.d.ts +1 -8
  99. package/dist/net/address.js +1 -18
  100. package/dist/net/index.d.ts +1 -1
  101. package/dist/net/index.js +1 -1
  102. package/dist/net/local-http-probe.js +1 -1
  103. package/dist/net/local-http-request.js +1 -1
  104. package/dist/process-probes.d.ts +36 -0
  105. package/dist/process-probes.js +151 -0
  106. package/dist/process-top-footprint.d.ts +7 -0
  107. package/dist/process-top-footprint.js +30 -0
  108. package/dist/process.d.ts +29 -31
  109. package/dist/process.js +18 -196
  110. package/dist/proxy-env.d.ts +12 -3
  111. package/dist/proxy-env.js +9 -8
  112. package/dist/resource-paths.d.ts +15 -3
  113. package/dist/resource-paths.js +7 -5
  114. package/dist/sandbox-env.d.ts +26 -5
  115. package/dist/sandbox-env.js +7 -7
  116. package/dist/secrets/credential-sets/contracts.d.ts +0 -1
  117. package/dist/secrets/credential-sets/contracts.js +0 -1
  118. package/dist/secrets/credential-sets/index.d.ts +2 -3
  119. package/dist/secrets/credential-sets/index.js +1 -1
  120. package/dist/secrets/credential-sets/provider-matches.d.ts +1 -1
  121. package/dist/secrets/credential-sets/provider-matches.js +1 -1
  122. package/dist/secrets/credential-sets/vault-archive.d.ts +1 -1
  123. package/dist/secrets/credential-sets/vault-archive.js +14 -8
  124. package/dist/secrets/credential-sets/vault.aad.d.ts +1 -1
  125. package/dist/secrets/credential-sets/vault.meta.d.ts +1 -1
  126. package/dist/secrets/credential-sets/vault.meta.js +1 -1
  127. package/dist/secrets/credential-sets/vault.repo.memory.d.ts +1 -1
  128. package/dist/secrets/credential-sets/vault.repo.memory.js +1 -1
  129. package/dist/secrets/credential-sets/vault.reseal-refused.d.ts +23 -0
  130. package/dist/secrets/credential-sets/vault.reseal-refused.js +36 -0
  131. package/dist/secrets/credential-sets/vault.service.d.ts +25 -5
  132. package/dist/secrets/credential-sets/vault.service.js +42 -8
  133. package/dist/secrets/index.d.ts +0 -3
  134. package/dist/secrets/index.js +5 -0
  135. package/dist/secrets/keyring.env.d.ts +1 -1
  136. package/dist/secrets/legacy-owner.d.ts +61 -0
  137. package/dist/secrets/legacy-owner.js +196 -0
  138. package/dist/secrets/root-key/decide.d.ts +89 -0
  139. package/dist/secrets/root-key/decide.js +60 -0
  140. package/dist/secrets/sealer-contract.d.ts +19 -0
  141. package/dist/secrets/sealer-contract.js +37 -0
  142. package/dist/secrets/secret-sealer.aesgcm.d.ts +1 -1
  143. package/dist/secrets/testing.d.ts +1 -0
  144. package/dist/secrets/testing.js +1 -0
  145. package/dist/shell.d.ts +4 -1
  146. package/dist/shell.js +1 -1
  147. package/dist/system.d.ts +6 -0
  148. package/dist/system.js +9 -0
  149. package/dist/terminal.d.ts +11 -96
  150. package/dist/terminal.js +80 -56
  151. package/dist/web/agent-tools.d.ts +107 -0
  152. package/dist/web/agent-tools.js +49 -0
  153. package/dist/web/index.d.ts +1 -0
  154. package/dist/web/index.js +1 -0
  155. package/package.json +38 -12
  156. package/dist/http/guarded/ports.d.ts +0 -56
  157. package/dist/http/guarded/types.d.ts +0 -8
  158. package/dist/http/guarded/types.js +0 -2
  159. package/dist/mail/email-sender.d.ts +0 -109
  160. package/dist/mail/email-sender.js +0 -10
  161. package/dist/net/endpoint-policy.d.ts +0 -39
  162. package/dist/net/endpoint-policy.js +0 -218
  163. package/dist/secrets/credential-sets/aad.d.ts +0 -7
  164. package/dist/secrets/credential-sets/aad.js +0 -7
  165. package/dist/secrets/credential-sets/repo.memory.d.ts +0 -44
  166. package/dist/secrets/credential-sets/repo.memory.js +0 -80
  167. package/dist/secrets/credential-sets/vault.types.d.ts +0 -27
  168. package/dist/secrets/credential-sets/vault.types.js +0 -49
  169. /package/dist/{http/guarded → mail/activity}/ports.js +0 -0
package/dist/download.js CHANGED
@@ -7,662 +7,16 @@
7
7
  * primitives (`atomicCopyFile`, `pathContains`, `removePathBestEffort`, `isProcessAlive`) — no
8
8
  * other cross-module dependency.
9
9
  */
10
- import { createHash } from "node:crypto";
11
- import { createReadStream, createWriteStream } from "node:fs";
12
- import { access, lstat, mkdir, readFile, readdir, rename, rm, stat, writeFile, } from "node:fs/promises";
13
- import { dirname, isAbsolute, join, resolve } from "node:path";
14
- import { Readable, Transform } from "node:stream";
15
- import { pipeline } from "node:stream/promises";
16
- import { atomicCopyFile, pathContains, removePathBestEffort } from "./fs.js";
17
- import { isProcessAlive } from "./process.js";
18
- const STORE_SENTINEL = ".jini-download-root.json";
19
- const STATE_DIR = ".state";
20
- const PARTIAL_DIR = ".partial";
21
- const LOCK_DIR = ".locks";
22
- const STORE_SCHEMA_VERSION = 1;
23
- const MANIFEST_SCHEMA_VERSION = 1;
24
- const STORE_KIND = "jini-managed-download-root";
25
- const MANIFEST_KIND = "jini-managed-download";
10
+ import { resolve } from "node:path";
11
+ import { atomicCopyFile } from "./fs.js";
12
+ import { ManagedDownloadError, MANAGED_DOWNLOAD_ERROR_CODES } from './download-types.js';
13
+ import { targetFromOptions, activeKey, targetActiveKey, activeTargets } from './download-target.js';
14
+ import { runManagedDownload } from './download-state.js';
15
+ import { removeManagedDownload } from './download-maintenance.js';
16
+ import { statFileSize, hashFile, errorMessage } from './download-store.js';
26
17
  const DEFAULT_MAX_ATTEMPTS = 3;
27
- const DEFAULT_PRUNE_OLDER_THAN_MS = 24 * 60 * 60 * 1000;
28
- const PID_REUSE_GRACE_MS = 1000;
29
- const PROCESS_STARTED_AT_MS = Date.now() - process.uptime() * 1000;
30
- export const MANAGED_DOWNLOAD_ERROR_CODES = Object.freeze({
31
- ABORTED: "aborted",
32
- CHECKSUM_MISMATCH: "checksum-mismatch",
33
- INVALID_TARGET: "invalid-target",
34
- NETWORK_EXHAUSTED: "network-exhausted",
35
- OUTPUT_CONFLICT: "output-conflict",
36
- STORE_CORRUPT: "store-corrupt",
37
- STORE_NOT_OWNED: "store-not-owned",
38
- TARGET_CONFLICT: "target-conflict",
39
- TARGET_LOCKED: "target-locked",
40
- });
41
- export class ManagedDownloadError extends Error {
42
- code;
43
- details;
44
- constructor(code, message, details) {
45
- super(message);
46
- this.name = "ManagedDownloadError";
47
- this.code = code;
48
- if (details !== undefined)
49
- this.details = details;
50
- }
51
- }
52
18
  const activeTasks = new Map();
53
- const activeTargets = new Map();
54
19
  const copyLeases = new Map();
55
- function errorCode(error) {
56
- if (typeof error !== "object" || error == null || !("code" in error))
57
- return null;
58
- const code = error.code;
59
- return code == null ? null : String(code);
60
- }
61
- function errorMessage(error) {
62
- return error instanceof Error ? error.message : String(error);
63
- }
64
- function digest(value) {
65
- return createHash("sha256").update(value).digest("hex");
66
- }
67
- function normalizeChecksum(input) {
68
- if (input.algorithm !== "sha256" && input.algorithm !== "sha512") {
69
- throw new ManagedDownloadError(MANAGED_DOWNLOAD_ERROR_CODES.INVALID_TARGET, `unsupported checksum algorithm: ${String(input.algorithm)}`);
70
- }
71
- const value = input.value.trim().toLowerCase();
72
- const expectedLength = input.algorithm === "sha256" ? 64 : 128;
73
- if (!new RegExp(`^[0-9a-f]{${expectedLength}}$`).test(value)) {
74
- throw new ManagedDownloadError(MANAGED_DOWNLOAD_ERROR_CODES.INVALID_TARGET, `${input.algorithm} checksum must be ${expectedLength} hex characters`);
75
- }
76
- return { algorithm: input.algorithm, value };
77
- }
78
- const DOT_SEGMENTS = new Set([".", ".."]);
79
- function normalizeSegment(value, label) {
80
- if (typeof value !== "string" || value.length === 0) {
81
- throw new ManagedDownloadError(MANAGED_DOWNLOAD_ERROR_CODES.INVALID_TARGET, `${label} must be a non-empty string`);
82
- }
83
- // `:` blocks a Windows drive-relative segment (e.g. "C:foo") — win32's
84
- // `isAbsolute`/`[\\/]` checks above don't reject it, but `path.win32.resolve`
85
- // treats it as a real drive reference, which can escape `basePath` onto a
86
- // different drive entirely.
87
- if (DOT_SEGMENTS.has(value) || value.includes("\0") || /[:\\/]/.test(value) || isAbsolute(value)) {
88
- throw new ManagedDownloadError(MANAGED_DOWNLOAD_ERROR_CODES.INVALID_TARGET, `${label} must be a safe single path segment`);
89
- }
90
- return value;
91
- }
92
- function normalizeUrl(value) {
93
- try {
94
- const url = new URL(value);
95
- if (url.protocol !== "http:" && url.protocol !== "https:") {
96
- throw new Error("only http and https URLs are supported");
97
- }
98
- return url.toString();
99
- }
100
- catch (error) {
101
- throw new ManagedDownloadError(MANAGED_DOWNLOAD_ERROR_CODES.INVALID_TARGET, errorMessage(error));
102
- }
103
- }
104
- function normalizeBasePath(basePath) {
105
- if (typeof basePath !== "string" || basePath.length === 0 || basePath.includes("\0")) {
106
- throw new ManagedDownloadError(MANAGED_DOWNLOAD_ERROR_CODES.INVALID_TARGET, "basePath must be a non-empty path");
107
- }
108
- // `path.resolve()` always returns an absolute path by contract (resolving
109
- // against `process.cwd()` when given a relative input), so this can never
110
- // be false for any string input.
111
- return resolve(basePath);
112
- }
113
- function targetFromOptions(options) {
114
- const basePath = normalizeBasePath(options.basePath);
115
- const bucket = normalizeSegment(options.bucket, "bucket");
116
- const fileName = normalizeSegment(options.fileName, "fileName");
117
- const checksum = normalizeChecksum(options.payload.checksum);
118
- const url = normalizeUrl(options.payload.url);
119
- const urlDigest = digest(url);
120
- const identityDigest = digest(`${url}\0${checksum.algorithm}\0${checksum.value}`);
121
- const targetKey = digest(`${bucket}\0${fileName}`);
122
- const finalPath = resolve(basePath, bucket, fileName);
123
- const manifestPath = resolve(basePath, STATE_DIR, `${targetKey}.json`);
124
- const partialPath = resolve(basePath, PARTIAL_DIR, `${targetKey}.partial`);
125
- const lockPath = resolve(basePath, LOCK_DIR, `${targetKey}.lock`);
126
- // Real, reachable guard — NOT dead code: `normalizeSegment` only rejects a
127
- // segment that is *exactly* "." or "..", not one that merely starts with
128
- // ".." (e.g. "..evil" is a syntactically ordinary filename, not a parent
129
- // reference), so `pathContains`'s own naive `!rel.startsWith("..")` string
130
- // check (see fs.ts) flags such a segment as escaping even though
131
- // `path.resolve` never actually walked upward. Empirically verified this
132
- // session: a 300k-segment fuzz found ~0.2% of `normalizeSegment`-valid
133
- // segments (every one starting with literal "..") trip this exact guard —
134
- // see archived provenance ledger's 2026-07-22 entry and this file's own test for a
135
- // concrete example (bucket "..evil").
136
- for (const path of [finalPath, manifestPath, partialPath, lockPath]) {
137
- if (!pathContains(basePath, path)) {
138
- throw new ManagedDownloadError(MANAGED_DOWNLOAD_ERROR_CODES.INVALID_TARGET, "resolved managed download path escaped basePath");
139
- }
140
- }
141
- return { basePath, bucket, checksum, fileName, finalPath, identityDigest, lockPath, manifestPath, partialPath, targetKey, url, urlDigest };
142
- }
143
- async function pathExists(path) {
144
- try {
145
- await access(path);
146
- return true;
147
- }
148
- catch {
149
- return false;
150
- }
151
- }
152
- async function readJson(path) {
153
- try {
154
- return JSON.parse(await readFile(path, "utf8"));
155
- }
156
- catch {
157
- return null;
158
- }
159
- }
160
- async function writeJson(path, payload) {
161
- await mkdir(dirname(path), { recursive: true });
162
- const tmp = `${path}.${process.pid}.${Date.now().toString(36)}.tmp`;
163
- await writeFile(tmp, `${JSON.stringify(payload, null, 2)}\n`, "utf8");
164
- await rename(tmp, path);
165
- }
166
- async function directoryIsEmpty(path) {
167
- const entries = await readdir(path);
168
- return entries.length === 0;
169
- }
170
- // Every caller feeds this a `JSON.parse` result, and a parsed JSON array can
171
- // never carry the named string keys (`kind`, `algorithm`, `pid`, ...) each
172
- // guard goes on to require, so arrays are rejected without a separate
173
- // `Array.isArray` check.
174
- function isPlainObject(value) {
175
- return typeof value === "object" && value != null;
176
- }
177
- function isStoreSentinel(value) {
178
- if (!isPlainObject(value))
179
- return false;
180
- const record = value;
181
- return record.kind === STORE_KIND && record.schemaVersion === STORE_SCHEMA_VERSION && typeof record.createdAt === "string";
182
- }
183
- async function writeSentinel(basePath) {
184
- await writeJson(join(basePath, STORE_SENTINEL), {
185
- createdAt: new Date().toISOString(),
186
- kind: STORE_KIND,
187
- schemaVersion: STORE_SCHEMA_VERSION,
188
- });
189
- }
190
- /** Clear only this target's data after rechecking store ownership; keep its lock held. */
191
- async function resetOwnedTarget({ target }, _options = {}) {
192
- const { basePath } = target;
193
- const sentinel = await readJson(join(basePath, STORE_SENTINEL));
194
- if (!isStoreSentinel(sentinel)) {
195
- throw new ManagedDownloadError(MANAGED_DOWNLOAD_ERROR_CODES.STORE_NOT_OWNED, `download base is not owned: ${basePath}`);
196
- }
197
- for (const path of [target.finalPath, target.partialPath, target.manifestPath]) {
198
- await rm(path, { force: true }).catch(() => undefined);
199
- }
200
- }
201
- async function ensureStoreDirs(basePath) {
202
- await mkdir(join(basePath, STATE_DIR), { recursive: true });
203
- await mkdir(join(basePath, PARTIAL_DIR), { recursive: true });
204
- await mkdir(join(basePath, LOCK_DIR), { recursive: true });
205
- }
206
- async function ensureManagedBase(basePath) {
207
- await mkdir(basePath, { recursive: true });
208
- const entry = await lstat(basePath);
209
- if (!entry.isDirectory() || entry.isSymbolicLink()) {
210
- throw new ManagedDownloadError(MANAGED_DOWNLOAD_ERROR_CODES.STORE_NOT_OWNED, `download base is not an owned directory: ${basePath}`);
211
- }
212
- const sentinelPath = join(basePath, STORE_SENTINEL);
213
- const sentinel = await readJson(sentinelPath);
214
- if (sentinel != null && !isStoreSentinel(sentinel)) {
215
- throw new ManagedDownloadError(MANAGED_DOWNLOAD_ERROR_CODES.STORE_NOT_OWNED, `download base has an invalid ownership marker: ${basePath}`);
216
- }
217
- if (sentinel == null) {
218
- if (!(await directoryIsEmpty(basePath))) {
219
- throw new ManagedDownloadError(MANAGED_DOWNLOAD_ERROR_CODES.STORE_NOT_OWNED, `download base is not empty and has no ownership marker: ${basePath}`);
220
- }
221
- await writeSentinel(basePath);
222
- }
223
- await ensureStoreDirs(basePath);
224
- }
225
- function isChecksum(value) {
226
- if (!isPlainObject(value))
227
- return false;
228
- const checksum = value;
229
- return ((checksum.algorithm === "sha256" || checksum.algorithm === "sha512") &&
230
- typeof checksum.value === "string");
231
- }
232
- const MANIFEST_STRING_FIELDS = [
233
- "bucket",
234
- "fileName",
235
- "targetKey",
236
- "identityDigest",
237
- "urlDigest",
238
- "createdAt",
239
- "updatedAt",
240
- ];
241
- function isManifest(value) {
242
- if (!isPlainObject(value))
243
- return false;
244
- const record = value;
245
- const versionMatches = record.kind === MANIFEST_KIND && record.schemaVersion === MANIFEST_SCHEMA_VERSION;
246
- const knownState = record.state === "complete" || record.state === "partial";
247
- return (versionMatches &&
248
- MANIFEST_STRING_FIELDS.every((field) => typeof record[field] === "string") &&
249
- isChecksum(record.checksum) &&
250
- knownState);
251
- }
252
- function isDownloadLockFile(value) {
253
- if (!isPlainObject(value))
254
- return false;
255
- const record = value;
256
- const validPid = typeof record.pid === "number" && Number.isInteger(record.pid) && record.pid > 0;
257
- const validStartedAt = record.processStartedAt == null || typeof record.processStartedAt === "string";
258
- return typeof record.createdAt === "string" && validPid && validStartedAt;
259
- }
260
- function parseTimeMs(value) {
261
- if (value == null)
262
- return null;
263
- const parsed = Date.parse(value);
264
- return Number.isFinite(parsed) ? parsed : null;
265
- }
266
- function lockBelongsToCurrentProcess(lock) {
267
- // Its only caller (`isLockProcessAlive`) already gates this call behind
268
- // `lock.pid === process.pid`, so that comparison can never be true here —
269
- // no redundant re-check.
270
- const ownerStartedAtMs = parseTimeMs(lock.processStartedAt);
271
- if (ownerStartedAtMs != null)
272
- return ownerStartedAtMs >= PROCESS_STARTED_AT_MS - PID_REUSE_GRACE_MS;
273
- // Older locks only carried a pid. If Windows reuses that pid for this
274
- // process, a lock that predates this process start is definitely stale.
275
- const lockCreatedAtMs = parseTimeMs(lock.createdAt);
276
- return lockCreatedAtMs == null || lockCreatedAtMs >= PROCESS_STARTED_AT_MS - PID_REUSE_GRACE_MS;
277
- }
278
- function isLockProcessAlive(lock) {
279
- if (!isProcessAlive(lock.pid))
280
- return false;
281
- if (lock.pid === process.pid)
282
- return lockBelongsToCurrentProcess(lock);
283
- return true;
284
- }
285
- async function readManifest(path) {
286
- try {
287
- const parsed = JSON.parse(await readFile(path, "utf8"));
288
- return isManifest(parsed) ? parsed : "invalid";
289
- }
290
- catch (error) {
291
- if (errorCode(error) === "ENOENT")
292
- return null;
293
- return "invalid";
294
- }
295
- }
296
- const MANIFEST_IDENTITY_FIELDS = ["bucket", "fileName", "targetKey", "identityDigest", "urlDigest"];
297
- function manifestMatchesTarget(manifest, target) {
298
- const identityMatches = MANIFEST_IDENTITY_FIELDS.every((field) => manifest[field] === target[field]);
299
- const checksumMatches = manifest.checksum.algorithm === target.checksum.algorithm &&
300
- manifest.checksum.value.toLowerCase() === target.checksum.value;
301
- return identityMatches && checksumMatches;
302
- }
303
- function createManifest(target, state, patch = {}) {
304
- const now = new Date().toISOString();
305
- return {
306
- bucket: target.bucket,
307
- checksum: target.checksum,
308
- createdAt: now,
309
- fileName: target.fileName,
310
- identityDigest: target.identityDigest,
311
- kind: MANIFEST_KIND,
312
- schemaVersion: MANIFEST_SCHEMA_VERSION,
313
- state,
314
- targetKey: target.targetKey,
315
- updatedAt: now,
316
- urlDigest: target.urlDigest,
317
- ...patch,
318
- };
319
- }
320
- async function hashFile(path, algorithm) {
321
- const hash = createHash(algorithm);
322
- await pipeline(createReadStream(path), hash);
323
- return hash.digest("hex");
324
- }
325
- async function statFileSize(path) {
326
- try {
327
- const entry = await stat(path);
328
- return entry.isFile() ? entry.size : null;
329
- }
330
- catch {
331
- return null;
332
- }
333
- }
334
- async function emitExistingProgress(path, totalBytes, emit) {
335
- // `totalBytes` is required (not `number | undefined`): its only real call
336
- // site (`tryResumeDownload`) always resolves one, via a `??` chain (in
337
- // `acceptedResumeTotalBytes`) whose
338
- // last resort is arithmetic (`partialBytes + (contentLength(response) ??
339
- // 0)`) — never `undefined`.
340
- const existing = await statFileSize(path);
341
- if (existing == null || existing <= 0)
342
- return;
343
- emit({ receivedBytes: existing, sessionReceivedBytes: 0, totalBytes });
344
- }
345
- function contentLength(response) {
346
- const raw = response.headers.get("content-length");
347
- if (raw == null)
348
- return undefined;
349
- const parsed = Number(raw);
350
- return Number.isFinite(parsed) && parsed >= 0 ? parsed : undefined;
351
- }
352
- function validatorsFromResponse(response) {
353
- const etag = response.headers.get("etag") ?? undefined;
354
- const lastModified = response.headers.get("last-modified") ?? undefined;
355
- return etag == null && lastModified == null ? undefined : { ...(etag == null ? {} : { etag }), ...(lastModified == null ? {} : { lastModified }) };
356
- }
357
- function validatorsConflict(saved, response) {
358
- if (saved == null)
359
- return false;
360
- const etag = response.headers.get("etag") ?? undefined;
361
- const lastModified = response.headers.get("last-modified") ?? undefined;
362
- if (saved.etag != null && etag != null && saved.etag !== etag)
363
- return true;
364
- if (saved.lastModified != null && lastModified != null && saved.lastModified !== lastModified)
365
- return true;
366
- return false;
367
- }
368
- function parseContentRange(value) {
369
- if (value == null)
370
- return null;
371
- const match = /^bytes\s+(\d+)-(\d+)\/(\d+|\*)$/i.exec(value.trim());
372
- // Every group in the pattern is mandatory, so a match always carries all three.
373
- if (match == null)
374
- return null;
375
- // `\d+` always parses to an integer — except a digit run long enough to
376
- // overflow to Infinity, which `Number.isInteger` rejects.
377
- const start = Number(match[1]);
378
- const end = Number(match[2]);
379
- if (!Number.isInteger(start) || !Number.isInteger(end) || end < start)
380
- return null;
381
- if (match[3] === "*")
382
- return { start, end };
383
- const totalBytes = Number(match[3]);
384
- if (!Number.isInteger(totalBytes) || totalBytes <= end)
385
- return null;
386
- return { start, end, totalBytes };
387
- }
388
- async function writeResponseBodyToPartial(response, target, options) {
389
- if (response.body == null)
390
- throw new Error("download response did not include a body");
391
- let receivedBytes = options.startBytes;
392
- let sessionReceivedBytes = 0;
393
- const meter = new Transform({
394
- transform(chunk, _encoding, callback) {
395
- receivedBytes += chunk.byteLength;
396
- sessionReceivedBytes += chunk.byteLength;
397
- options.emit({
398
- receivedBytes,
399
- sessionReceivedBytes,
400
- ...(options.totalBytes == null ? {} : { totalBytes: options.totalBytes }),
401
- });
402
- callback(null, chunk);
403
- },
404
- });
405
- await pipeline(Readable.fromWeb(response.body), meter, createWriteStream(target.partialPath, { flags: options.startBytes > 0 ? "a" : "w" }));
406
- }
407
- function resumeRequestHeaders(input, options) {
408
- const etag = input.manifest.validators?.etag;
409
- return {
410
- ...(options.requestHeaders ?? {}),
411
- ...(etag == null ? {} : { "If-Range": etag }),
412
- Range: `bytes=${input.partialBytes}-`,
413
- };
414
- }
415
- /** The resumed total size, or `null` when the response cannot continue the saved partial. */
416
- function acceptedResumeTotalBytes(input) {
417
- const { manifest, partialBytes, response } = input;
418
- if (response.status !== 206)
419
- return null;
420
- const range = parseContentRange(response.headers.get("content-range"));
421
- if (range == null || range.start !== partialBytes || validatorsConflict(manifest.validators, response)) {
422
- return null;
423
- }
424
- return range.totalBytes ?? manifest.totalBytes ?? partialBytes + (contentLength(response) ?? 0);
425
- }
426
- async function tryResumeDownload(input, options) {
427
- const { emit, fetchImpl, manifest, target } = input;
428
- const partialBytes = await statFileSize(target.partialPath);
429
- if (partialBytes == null || partialBytes <= 0)
430
- return "restart";
431
- const response = await fetchImpl(target.url, {
432
- headers: resumeRequestHeaders({ manifest, partialBytes }, options),
433
- });
434
- const totalBytes = acceptedResumeTotalBytes({ manifest, partialBytes, response });
435
- if (totalBytes == null)
436
- return "restart";
437
- await emitExistingProgress(target.partialPath, totalBytes, emit);
438
- await writeJson(target.manifestPath, {
439
- ...manifest,
440
- state: "partial",
441
- totalBytes,
442
- updatedAt: new Date().toISOString(),
443
- validators: manifest.validators ?? validatorsFromResponse(response),
444
- });
445
- await writeResponseBodyToPartial(response, target, { emit, startBytes: partialBytes, totalBytes });
446
- return { resumed: true, totalBytes };
447
- }
448
- async function downloadFromZero(input, options) {
449
- const { emit, fetchImpl, target } = input;
450
- const { requestHeaders } = options;
451
- await rm(target.partialPath, { force: true }).catch(() => undefined);
452
- const response = await fetchImpl(target.url, {
453
- ...(requestHeaders == null ? {} : { headers: requestHeaders }),
454
- });
455
- if (!response.ok)
456
- throw new Error(`download request returned HTTP ${response.status}`);
457
- const totalBytes = contentLength(response);
458
- const validators = validatorsFromResponse(response);
459
- await writeJson(target.manifestPath, createManifest(target, "partial", { totalBytes, validators }));
460
- await writeResponseBodyToPartial(response, target, { emit, startBytes: 0, totalBytes });
461
- return { resumed: false, totalBytes };
462
- }
463
- async function downloadWithRetries(target, manifest, options) {
464
- let lastError;
465
- let nextManifest = manifest;
466
- const deps = { emit: options.emit, fetchImpl: options.fetchImpl };
467
- for (let attempt = 1; attempt <= options.maxAttempts; attempt += 1) {
468
- try {
469
- const resume = nextManifest?.state === "partial"
470
- ? await tryResumeDownload({ ...deps, manifest: nextManifest, target }, options)
471
- : null;
472
- if (resume !== null && resume !== "restart")
473
- return resume;
474
- if (resume === "restart") {
475
- await rm(target.partialPath, { force: true }).catch(() => undefined);
476
- nextManifest = null;
477
- }
478
- return await downloadFromZero({ ...deps, target }, options);
479
- }
480
- catch (error) {
481
- lastError = error;
482
- nextManifest = await manifestAfterFailedAttempt({ manifest: nextManifest, target });
483
- }
484
- }
485
- throw new ManagedDownloadError(MANAGED_DOWNLOAD_ERROR_CODES.NETWORK_EXHAUSTED, `download failed after ${options.maxAttempts} attempts: ${errorMessage(lastError)}`);
486
- }
487
- /** After a failed attempt, mark any bytes already on disk as a resumable partial (best-effort persisted). */
488
- async function manifestAfterFailedAttempt(input) {
489
- const { manifest, target } = input;
490
- const partialBytes = await statFileSize(target.partialPath);
491
- if (partialBytes == null || partialBytes <= 0)
492
- return manifest;
493
- const next = {
494
- ...(manifest ?? createManifest(target, "partial")),
495
- state: "partial",
496
- updatedAt: new Date().toISOString(),
497
- };
498
- await writeJson(target.manifestPath, next).catch(() => undefined);
499
- return next;
500
- }
501
- async function acquireLock(target) {
502
- await mkdir(dirname(target.lockPath), { recursive: true });
503
- // At most two create attempts: the second only after the first hit an
504
- // existing lock that `clearStaleLock` proved stale and removed; a second
505
- // EEXIST is real contention. (This was formerly a `for (;;)` loop whose
506
- // fall-through branch V8 instrumented but no path could take — see archived
507
- // provenance ledger's 2026-07-22 entry; the straight-line form has none.)
508
- if (await tryCreateLockFile(target))
509
- return { path: target.lockPath };
510
- if (await clearStaleLock(target) && await tryCreateLockFile(target))
511
- return { path: target.lockPath };
512
- throw new ManagedDownloadError(MANAGED_DOWNLOAD_ERROR_CODES.TARGET_LOCKED, `download target is locked: ${target.bucket}/${target.fileName}`);
513
- }
514
- /** Exclusively create the lock file; `false` when one already exists, any other failure is rethrown. */
515
- async function tryCreateLockFile(target) {
516
- try {
517
- await writeFile(target.lockPath, `${JSON.stringify({
518
- createdAt: new Date().toISOString(),
519
- pid: process.pid,
520
- processStartedAt: new Date(PROCESS_STARTED_AT_MS).toISOString(),
521
- })}\n`, { flag: "wx" });
522
- return true;
523
- }
524
- catch (error) {
525
- if (errorCode(error) === "EEXIST")
526
- return false;
527
- throw error;
528
- }
529
- }
530
- async function clearStaleLock(target) {
531
- const lock = await readJson(target.lockPath);
532
- if (!isDownloadLockFile(lock) || isLockProcessAlive(lock))
533
- return false;
534
- await rm(target.lockPath, { force: true }).catch(() => undefined);
535
- return true;
536
- }
537
- async function releaseLock(lock) {
538
- if (lock == null)
539
- return;
540
- await rm(lock.path, { force: true }).catch(() => undefined);
541
- }
542
- async function suspiciousReset({ target }, _options = {}) {
543
- await resetOwnedTarget({ target });
544
- return { manifest: null, reset: true };
545
- }
546
- async function loadReusableState(target) {
547
- const manifest = await readManifest(target.manifestPath);
548
- const finalExists = await pathExists(target.finalPath);
549
- const partialExists = await pathExists(target.partialPath);
550
- if (manifest === "invalid") {
551
- return await suspiciousReset({ target });
552
- }
553
- if (manifest == null) {
554
- return finalExists || partialExists ? await suspiciousReset({ target }) : { manifest: null };
555
- }
556
- if (!manifestMatchesTarget(manifest, target)) {
557
- return await suspiciousReset({ target });
558
- }
559
- if (manifest.state === "complete")
560
- return await reusableCompleteState({ manifest, target });
561
- if (!partialExists)
562
- return await suspiciousReset({ target });
563
- return { manifest };
564
- }
565
- /** Reuse a complete download only when its final file exists and still hashes to the requested checksum. */
566
- async function reusableCompleteState(input) {
567
- const { manifest, target } = input;
568
- // A missing final file needs no separate check: hashing it rejects, which
569
- // maps to `null` and fails the checksum comparison into the same reset.
570
- const actual = await hashFile(target.finalPath, target.checksum.algorithm).catch(() => null);
571
- if (actual !== target.checksum.value)
572
- return await suspiciousReset({ target });
573
- const bytes = await statFileSize(target.finalPath);
574
- if (bytes == null)
575
- return await suspiciousReset({ target });
576
- return {
577
- manifest,
578
- result: {
579
- bucket: target.bucket,
580
- bytes,
581
- checksum: target.checksum,
582
- fileName: target.fileName,
583
- path: target.finalPath,
584
- reusedComplete: true,
585
- resumed: false,
586
- urlDigest: target.urlDigest,
587
- },
588
- };
589
- }
590
- async function runManagedDownload(target, options) {
591
- await ensureManagedBase(target.basePath);
592
- await pruneManagedDownloads({ basePath: target.basePath }).catch(() => undefined);
593
- const lock = await acquireLock(target);
594
- try {
595
- const state = await loadStateAllowingOneReset({ target });
596
- if (state.result != null)
597
- return state.result;
598
- const download = await downloadWithRetries(target, state.manifest, options);
599
- const bytes = await promoteVerifiedPartial({ target });
600
- await writeJson(target.manifestPath, createManifest(target, "complete", { totalBytes: download.totalBytes }));
601
- return {
602
- bucket: target.bucket,
603
- bytes,
604
- checksum: target.checksum,
605
- fileName: target.fileName,
606
- path: target.finalPath,
607
- reusedComplete: false,
608
- resumed: download.resumed,
609
- urlDigest: target.urlDigest,
610
- };
611
- }
612
- finally {
613
- await releaseLock(lock);
614
- }
615
- }
616
- /** Reload once after target cleanup, retaining the lock until the run finishes. */
617
- async function loadStateAllowingOneReset({ target }, _options = {}) {
618
- const state = await loadReusableState(target);
619
- if (state.reset !== true)
620
- return state;
621
- // Whole-base cleanup used to remove the lock and require re-acquisition.
622
- // Keep it throughout target cleanup so another process cannot take it
623
- // before we write fresh state, or have its own lock deleted by our finally.
624
- await ensureManagedBase(target.basePath);
625
- const reloaded = await loadReusableState(target);
626
- if (reloaded.reset === true) {
627
- throw new ManagedDownloadError(MANAGED_DOWNLOAD_ERROR_CODES.STORE_CORRUPT, "download state kept resetting after target cleanup");
628
- }
629
- return reloaded;
630
- }
631
- /** Verify the downloaded partial's checksum, promote it to the final path, and return the final size. */
632
- async function promoteVerifiedPartial({ target }, _options = {}) {
633
- const actual = await hashFile(target.partialPath, target.checksum.algorithm).catch((error) => {
634
- throw new ManagedDownloadError(MANAGED_DOWNLOAD_ERROR_CODES.STORE_CORRUPT, `downloaded partial could not be hashed: ${errorMessage(error)}`);
635
- });
636
- if (actual !== target.checksum.value) {
637
- await resetOwnedTarget({ target }).catch(() => undefined);
638
- throw new ManagedDownloadError(MANAGED_DOWNLOAD_ERROR_CODES.CHECKSUM_MISMATCH, "downloaded file checksum did not match requested payload", {
639
- actual,
640
- expected: target.checksum.value,
641
- });
642
- }
643
- await mkdir(dirname(target.finalPath), { recursive: true });
644
- if (await pathExists(target.finalPath)) {
645
- const existing = await hashFile(target.finalPath, target.checksum.algorithm).catch(() => null);
646
- if (existing !== target.checksum.value) {
647
- await resetOwnedTarget({ target }).catch(() => undefined);
648
- throw new ManagedDownloadError(MANAGED_DOWNLOAD_ERROR_CODES.STORE_CORRUPT, "existing complete file did not match requested payload");
649
- }
650
- await rm(target.partialPath, { force: true }).catch(() => undefined);
651
- }
652
- else {
653
- await rename(target.partialPath, target.finalPath);
654
- }
655
- const bytes = await statFileSize(target.finalPath);
656
- if (bytes == null)
657
- throw new ManagedDownloadError(MANAGED_DOWNLOAD_ERROR_CODES.STORE_CORRUPT, "complete file is missing after promotion");
658
- return bytes;
659
- }
660
- function activeKey(target) {
661
- return `${target.basePath}\0${target.targetKey}\0${target.identityDigest}`;
662
- }
663
- function targetActiveKey(target) {
664
- return `${target.basePath}\0${target.targetKey}`;
665
- }
666
20
  function waitForTask(task, options) {
667
21
  return new Promise((resolveWait, rejectWait) => {
668
22
  if (options.signal?.aborted) {
@@ -781,7 +135,7 @@ export async function downloadCopyAndClear(options) {
781
135
  }
782
136
  }
783
137
  else {
784
- await atomicCopyFile(downloaded.path, outputPath);
138
+ await atomicCopyFile({ sourcePath: downloaded.path, destinationPath: outputPath });
785
139
  const copiedDigest = await hashFile(outputPath, target.checksum.algorithm);
786
140
  if (copiedDigest !== target.checksum.value) {
787
141
  throw new ManagedDownloadError(MANAGED_DOWNLOAD_ERROR_CODES.CHECKSUM_MISMATCH, "copied output checksum did not match requested payload");
@@ -808,88 +162,4 @@ export async function downloadCopyAndClear(options) {
808
162
  await releaseCopyLease(lease);
809
163
  }
810
164
  }
811
- /** Resolve a target's paths for callers (inspect/remove) that have no payload; the placeholder never reaches the network. */
812
- function targetWithoutPayload(options) {
813
- return targetFromOptions({
814
- ...options,
815
- payload: {
816
- checksum: { algorithm: "sha256", value: "0".repeat(64) },
817
- url: "https://example.invalid/",
818
- },
819
- });
820
- }
821
- export async function inspectManagedDownload(options) {
822
- const target = targetWithoutPayload(options);
823
- await ensureManagedBase(target.basePath);
824
- const rawManifest = await readManifest(target.manifestPath);
825
- const manifest = rawManifest === "invalid" ? "unreadable" : rawManifest?.state ?? "missing";
826
- return {
827
- bucket: target.bucket,
828
- complete: await pathExists(target.finalPath),
829
- fileName: target.fileName,
830
- manifest,
831
- path: target.finalPath,
832
- };
833
- }
834
- export async function removeManagedDownload(options) {
835
- const target = targetWithoutPayload(options);
836
- if (activeTargets.has(targetActiveKey(target))) {
837
- throw new ManagedDownloadError(MANAGED_DOWNLOAD_ERROR_CODES.TARGET_LOCKED, `download target is active: ${target.bucket}/${target.fileName}`);
838
- }
839
- await ensureManagedBase(target.basePath);
840
- await Promise.all([
841
- removePathBestEffort(target.finalPath),
842
- removePathBestEffort(target.partialPath, { recursive: false }),
843
- removePathBestEffort(target.manifestPath, { recursive: false }),
844
- removePathBestEffort(target.lockPath, { recursive: false }),
845
- ]);
846
- const bucketPath = join(target.basePath, target.bucket);
847
- const entries = await readdir(bucketPath).catch(() => null);
848
- if (entries != null && entries.length === 0)
849
- await rm(bucketPath, { force: true, recursive: true }).catch(() => undefined);
850
- return { removed: true };
851
- }
852
- async function removeEntriesOlderThan(root, olderThan) {
853
- const warnings = [];
854
- let removed = 0;
855
- const entries = await readdir(root, { withFileTypes: true }).catch(() => []);
856
- for (const entry of entries) {
857
- const path = join(root, entry.name);
858
- const info = await stat(path).catch(() => null);
859
- if (info == null || info.mtimeMs > olderThan)
860
- continue;
861
- const result = await removePathBestEffort(path);
862
- // A successful removal never carries an error, so the two checks are exclusive.
863
- if (result.removed)
864
- removed += 1;
865
- if (result.error != null)
866
- warnings.push(result.error);
867
- }
868
- return { removed, warnings };
869
- }
870
- export async function pruneManagedDownloads(options) {
871
- const basePath = normalizeBasePath(options.basePath);
872
- await ensureManagedBase(basePath);
873
- const olderThan = (options.now?.getTime() ?? Date.now()) - (options.olderThanMs ?? DEFAULT_PRUNE_OLDER_THAN_MS);
874
- const roots = [join(basePath, STATE_DIR), join(basePath, PARTIAL_DIR), join(basePath, LOCK_DIR)];
875
- let removed = 0;
876
- const warnings = [];
877
- for (const root of roots) {
878
- const result = await removeEntriesOlderThan(root, olderThan);
879
- removed += result.removed;
880
- warnings.push(...result.warnings);
881
- }
882
- const bucketEntries = await readdir(basePath, { withFileTypes: true }).catch(() => []);
883
- for (const entry of bucketEntries) {
884
- if (!entry.isDirectory() || entry.name.startsWith("."))
885
- continue;
886
- const result = await removeEntriesOlderThan(join(basePath, entry.name), olderThan);
887
- removed += result.removed;
888
- warnings.push(...result.warnings);
889
- const remaining = await readdir(join(basePath, entry.name)).catch(() => null);
890
- if (remaining != null && remaining.length === 0)
891
- await rm(join(basePath, entry.name), { force: true, recursive: true }).catch(() => undefined);
892
- }
893
- return { removed, warnings };
894
- }
895
165
  //# sourceMappingURL=download.js.map