@jini-ai/platform 0.7.3-next.2 → 0.7.3-next.3

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 (136) hide show
  1. package/README.md +13 -0
  2. package/dist/download-lock.d.ts +3 -1
  3. package/dist/download-lock.js +4 -4
  4. package/dist/download-maintenance.js +6 -6
  5. package/dist/download-state.js +17 -14
  6. package/dist/download-store.d.ts +34 -10
  7. package/dist/download-store.js +24 -20
  8. package/dist/download-target.d.ts +6 -2
  9. package/dist/download-target.js +7 -7
  10. package/dist/download-transfer.js +18 -12
  11. package/dist/download.js +4 -4
  12. package/dist/fetch-with-timeout.d.ts +0 -53
  13. package/dist/fetch-with-timeout.js +56 -6
  14. package/dist/fs/directory-running-lock.d.ts +4 -0
  15. package/dist/fs/directory-running-lock.js +8 -1
  16. package/dist/fs/directory-workspace.d.ts +2 -1
  17. package/dist/fs/directory-workspace.js +2 -2
  18. package/dist/fs/durable-json.d.ts +3 -16
  19. package/dist/fs/durable-json.js +4 -2
  20. package/dist/fs/guarded-reader.d.ts +10 -0
  21. package/dist/fs/guarded-reader.js +34 -1
  22. package/dist/fs/index.d.ts +4 -0
  23. package/dist/fs/index.js +4 -0
  24. package/dist/fs/leased-directory-move.d.ts +49 -0
  25. package/dist/fs/leased-directory-move.js +31 -0
  26. package/dist/fs/owned-temp-root.d.ts +74 -0
  27. package/dist/fs/owned-temp-root.js +203 -0
  28. package/dist/fs/recent-directories.d.ts +2 -1
  29. package/dist/fs/resolve-directory-target.d.ts +33 -0
  30. package/dist/fs/resolve-directory-target.js +58 -0
  31. package/dist/fs/staged-file.d.ts +40 -0
  32. package/dist/fs/staged-file.js +75 -0
  33. package/dist/fs/strict-containment.d.ts +14 -0
  34. package/dist/fs/strict-containment.js +14 -0
  35. package/dist/image/png-encode.d.ts +41 -0
  36. package/dist/image/png-encode.js +96 -0
  37. package/dist/index.d.ts +3 -1
  38. package/dist/mail/email-template-agent-tools.d.ts +150 -0
  39. package/dist/mail/email-template-agent-tools.js +86 -0
  40. package/dist/mail/email-template-tool-registrations.d.ts +73 -0
  41. package/dist/mail/email-template-tool-registrations.js +66 -0
  42. package/dist/mail/feedback-route.d.ts +50 -0
  43. package/dist/mail/feedback-route.js +46 -0
  44. package/dist/mail/feedback-setup.d.ts +44 -0
  45. package/dist/mail/feedback-setup.js +53 -0
  46. package/dist/mail/feedback-sources.d.ts +67 -0
  47. package/dist/mail/feedback-sources.js +42 -0
  48. package/dist/mail/index.d.ts +10 -1
  49. package/dist/mail/index.js +4 -0
  50. package/dist/mail/mail-status.d.ts +32 -0
  51. package/dist/mail/mail-status.js +2 -0
  52. package/dist/mail/positional-purpose-gate.d.ts +14 -0
  53. package/dist/mail/positional-purpose-gate.js +18 -0
  54. package/dist/mail/purpose-gate-probe.d.ts +18 -0
  55. package/dist/mail/purpose-gate-probe.js +22 -0
  56. package/dist/mail/resolve-mailer.d.ts +13 -1
  57. package/dist/mail/resolve-mailer.js +11 -5
  58. package/dist/mail/sql/activity.repo.d.ts +20 -0
  59. package/dist/mail/sql/activity.repo.js +133 -0
  60. package/dist/mail/sql/attempts.repo.d.ts +17 -0
  61. package/dist/mail/sql/attempts.repo.js +32 -0
  62. package/dist/mail/sql/capture.repo.d.ts +69 -0
  63. package/dist/mail/sql/capture.repo.js +119 -0
  64. package/dist/mail/sql/feedback-inbox.repo.d.ts +12 -0
  65. package/dist/mail/sql/feedback-inbox.repo.js +32 -0
  66. package/dist/mail/sql/index.d.ts +12 -0
  67. package/dist/mail/sql/index.js +12 -0
  68. package/dist/mail/sql/ledger.repo.d.ts +29 -0
  69. package/dist/mail/sql/ledger.repo.js +57 -0
  70. package/dist/mail/sql/retention.d.ts +23 -0
  71. package/dist/mail/sql/retention.js +53 -0
  72. package/dist/mail/sql/site-feedback-route.d.ts +18 -0
  73. package/dist/mail/sql/site-feedback-route.js +22 -0
  74. package/dist/mail/sql/suppression-admin.repo.d.ts +11 -0
  75. package/dist/mail/sql/suppression-admin.repo.js +76 -0
  76. package/dist/mail/sql/suppression.repo.d.ts +10 -0
  77. package/dist/mail/sql/suppression.repo.js +33 -0
  78. package/dist/mail/test-send.d.ts +147 -0
  79. package/dist/mail/test-send.js +201 -0
  80. package/dist/mail/use-readiness.d.ts +104 -0
  81. package/dist/mail/use-readiness.js +140 -0
  82. package/dist/object-store/local-fs.js +34 -1
  83. package/dist/object-store/site/artifact-provider.d.ts +65 -0
  84. package/dist/object-store/site/artifact-provider.js +37 -0
  85. package/dist/object-store/site/registry.d.ts +110 -0
  86. package/dist/object-store/site/registry.js +93 -0
  87. package/dist/object-store/site/setting.d.ts +34 -0
  88. package/dist/object-store/site/setting.js +32 -0
  89. package/dist/process-probes.d.ts +11 -4
  90. package/dist/process-probes.js +3 -3
  91. package/dist/process-top-footprint.d.ts +1 -1
  92. package/dist/process.d.ts +3 -17
  93. package/dist/process.js +3 -2
  94. package/dist/retention/index.d.ts +6 -0
  95. package/dist/retention/index.js +6 -0
  96. package/dist/retention/measure-tree.d.ts +68 -0
  97. package/dist/retention/measure-tree.js +205 -0
  98. package/dist/retention/preview-store.d.ts +10 -0
  99. package/dist/retention/preview-store.js +26 -0
  100. package/dist/retention/routes.d.ts +23 -0
  101. package/dist/retention/routes.js +24 -0
  102. package/dist/retention/runner.d.ts +103 -0
  103. package/dist/retention/runner.js +164 -0
  104. package/dist/secrets/credential-sets/index.d.ts +1 -0
  105. package/dist/secrets/credential-sets/index.js +1 -0
  106. package/dist/secrets/credential-sets/store-vault-guards.d.ts +26 -0
  107. package/dist/secrets/credential-sets/store-vault-guards.js +30 -0
  108. package/dist/secrets/credential-sets/vault.service.d.ts +1 -1
  109. package/dist/secrets/index.d.ts +1 -1
  110. package/dist/secrets/index.js +1 -1
  111. package/dist/secrets/keyring.env.d.ts +1 -1
  112. package/dist/secrets/keyring.env.js +3 -5
  113. package/dist/secrets/keyring.memory.d.ts +4 -1
  114. package/dist/secrets/keyring.memory.js +4 -1
  115. package/dist/secrets/legacy-codecs.d.ts +381 -0
  116. package/dist/secrets/legacy-codecs.js +468 -0
  117. package/dist/secrets/legacy-owner.d.ts +3 -11
  118. package/dist/secrets/root-key/ensure.d.ts +154 -0
  119. package/dist/secrets/root-key/ensure.js +328 -0
  120. package/dist/secrets/root-key/files.d.ts +104 -0
  121. package/dist/secrets/root-key/files.js +166 -0
  122. package/dist/secrets/root-key/material.d.ts +132 -0
  123. package/dist/secrets/root-key/material.js +116 -0
  124. package/dist/secrets/root-key/ordered-keyring.d.ts +157 -0
  125. package/dist/secrets/root-key/ordered-keyring.js +104 -0
  126. package/dist/secrets/root-key/reconcile.d.ts +50 -0
  127. package/dist/secrets/root-key/reconcile.js +147 -0
  128. package/dist/secrets/root-key/site-keyring-errors.d.ts +78 -0
  129. package/dist/secrets/root-key/site-keyring-errors.js +37 -0
  130. package/dist/secrets/root-key/sources.d.ts +79 -0
  131. package/dist/secrets/root-key/sources.js +119 -0
  132. package/dist/secrets/secret-sealer.aesgcm.d.ts +50 -2
  133. package/dist/secrets/secret-sealer.aesgcm.js +107 -19
  134. package/dist/web/tool-registrations.d.ts +67 -0
  135. package/dist/web/tool-registrations.js +44 -0
  136. package/package.json +138 -6
package/README.md CHANGED
@@ -233,6 +233,7 @@ vendor-shaped `NativeSmtpTransport` so the factory adapts the payload once. Poli
233
233
  | Subpath | API and required host ports/policy |
234
234
  | --- | --- |
235
235
  | `./secrets/legacy-owner` | `readLegacyOwnerBackup({ envelope, passphrase })` decodes a legacy `jini-owner-store` v1/v2 passphrase backup read-only; `openLegacyOwnerVault({ repo, keyFilePath }, { metaParsers })` is the legacy keyring + authorize policy (owner workspace, no principal, copyable kind; never generates a key) over a host-supplied `VaultRepoPort`; `readLegacyOwnerEntry({ vault, row })` is one decrypt whose every failure is the fixed `OwnerStoreRecoveryError`. Entries are `VaultArchiveEntry`. The SQL reads are `@jini-ai/db/owner-store`; the file wiring is `@jini-ai/server/owner-store`. |
236
+ | `./secrets/legacy-codecs` | Historical vault AAD builders (`build*Aad`), `legacyVaultAad({ record, legacy, formerCustomOwnerKey })` (decodes only known legacy lineages, fails closed), `legacyTargetProvider` and `normalizeLegacyVaultPayload({ record, legacy, plaintext, policy })` for recovering pre-vault rows. The host injects its own vault owner key and a `LegacyVaultPolicy` (publish catalog + token field). |
236
237
  | `./mail` | `createMailAdapterContext({ credential, kit }, { now, settings })` supplies a live clock and fresh empty settings by default; modules validate opaque per-install settings. |
237
238
  | `@jini-ai/analytics` (separate package) | `ingestHit({ input, deps }, { hooks, hash })`, `normalizeIngestContext({ input, dailySalt }, { hash })`, `deriveDailySalt({ rootKeySeed, workspaceId, utcDate, saltContext })`. The host supplies sink/config, host resolution, HKDF context, and privacy bounds. `LocalBufferSink({}, { initialHits })` is process-local. |
238
239
  | `@jini-ai/cms/trash` (separate package) | `createTrashService({ repo, adapters, transaction, idGen, entityPolicy }, { retentionDays, ...optional })`, `createTrashSweep({ repo, adapters, transaction, entityPolicy })`, and `startTrashSweeper({ sweep, clock, scheduler, leaseOwner }, optional)`. The host owns authorization, transactions, retention, scheduling, and adapters; follow-up hooks are in argument two. |
@@ -290,3 +291,15 @@ AES-GCM AAD. Renaming that persisted field requires a host adapter migration as
290
291
  Analytics is available from the standalone `@jini-ai/analytics` package; soft-delete and purge
291
292
  services are available from `@jini-ai/cms/trash`. Their platform subpaths and root namespaces
292
293
  have been removed.
294
+
295
+ ## Wiring
296
+
297
+
298
+ - `@jini-ai/platform/fs`: `resolveDirectoryTarget({ dirArg })` resolves a directory argument to the one real
299
+ target path (lexical, existing symlink, dangling symlink); `moveDirectoryUnderLeases({ from, to, ports })`
300
+ runs the creation-lock, source/target claim, relocate, release-both sequence. The host supplies the idleness
301
+ check, claims/release, destination preparation, the verified relocation and the refusal copy as `ports`.
302
+
303
+ - `@jini-ai/platform/image/png-encode` (node): `renderSolidColorPng({ width, height, color })` returns a real,
304
+ decodable 8-bit truecolor PNG `Buffer` of one solid color (dependency-free, `node:zlib` only). Hosts use it for
305
+ deterministic typed-image fixtures; it validates dimensions and channels and throws with the exact field named.
@@ -1,4 +1,6 @@
1
1
  import { type NormalizedTarget, type AcquiredLock } from './download-types.js';
2
2
  export declare function acquireLock(target: NormalizedTarget): Promise<AcquiredLock>;
3
- export declare function releaseLock(lock: AcquiredLock | null): Promise<void>;
3
+ export declare function releaseLock({ lock }: {
4
+ lock: AcquiredLock | null;
5
+ }, _optional?: Record<string, never>): Promise<void>;
4
6
  //# sourceMappingURL=download-lock.d.ts.map
@@ -6,7 +6,7 @@ import { isPlainObject, errorCode, readJson } from './download-store.js';
6
6
  const PID_REUSE_GRACE_MS = 1000;
7
7
  const PROCESS_STARTED_AT_MS = Date.now() - process.uptime() * 1000;
8
8
  function isDownloadLockFile(value) {
9
- if (!isPlainObject(value))
9
+ if (!isPlainObject({ value }))
10
10
  return false;
11
11
  const record = value;
12
12
  const validPid = typeof record.pid === "number" && Number.isInteger(record.pid) && record.pid > 0;
@@ -62,19 +62,19 @@ async function tryCreateLockFile(target) {
62
62
  return true;
63
63
  }
64
64
  catch (error) {
65
- if (errorCode(error) === "EEXIST")
65
+ if (errorCode({ error }) === "EEXIST")
66
66
  return false;
67
67
  throw error;
68
68
  }
69
69
  }
70
70
  async function clearStaleLock(target) {
71
- const lock = await readJson(target.lockPath);
71
+ const lock = await readJson({ path: target.lockPath });
72
72
  if (!isDownloadLockFile(lock) || isLockProcessAlive(lock))
73
73
  return false;
74
74
  await rm(target.lockPath, { force: true }).catch(() => undefined);
75
75
  return true;
76
76
  }
77
- export async function releaseLock(lock) {
77
+ export async function releaseLock({ lock }, _optional = {}) {
78
78
  if (lock == null)
79
79
  return;
80
80
  await rm(lock.path, { force: true }).catch(() => undefined);
@@ -7,12 +7,12 @@ import { ensureManagedBase, readManifest, pathExists } from './download-store.js
7
7
  const DEFAULT_PRUNE_OLDER_THAN_MS = 24 * 60 * 60 * 1000;
8
8
  export async function inspectManagedDownload(options) {
9
9
  const target = targetWithoutPayload(options);
10
- await ensureManagedBase(target.basePath);
11
- const rawManifest = await readManifest(target.manifestPath);
10
+ await ensureManagedBase({ basePath: target.basePath });
11
+ const rawManifest = await readManifest({ path: target.manifestPath });
12
12
  const manifest = rawManifest === "invalid" ? "unreadable" : rawManifest?.state ?? "missing";
13
13
  return {
14
14
  bucket: target.bucket,
15
- complete: await pathExists(target.finalPath),
15
+ complete: await pathExists({ path: target.finalPath }),
16
16
  fileName: target.fileName,
17
17
  manifest,
18
18
  path: target.finalPath,
@@ -23,7 +23,7 @@ export async function removeManagedDownload(options) {
23
23
  if (activeTargets.has(targetActiveKey(target))) {
24
24
  throw new ManagedDownloadError(MANAGED_DOWNLOAD_ERROR_CODES.TARGET_LOCKED, `download target is active: ${target.bucket}/${target.fileName}`);
25
25
  }
26
- await ensureManagedBase(target.basePath);
26
+ await ensureManagedBase({ basePath: target.basePath });
27
27
  await Promise.all([
28
28
  removePathBestEffort({ path: target.finalPath }),
29
29
  removePathBestEffort({ path: target.partialPath }, { recursive: false }),
@@ -55,8 +55,8 @@ async function removeEntriesOlderThan(root, olderThan) {
55
55
  return { removed, warnings };
56
56
  }
57
57
  export async function pruneManagedDownloads(options) {
58
- const basePath = normalizeBasePath(options.basePath);
59
- await ensureManagedBase(basePath);
58
+ const basePath = normalizeBasePath({ basePath: options.basePath });
59
+ await ensureManagedBase({ basePath });
60
60
  const olderThan = (options.now?.getTime() ?? Date.now()) - (options.olderThanMs ?? DEFAULT_PRUNE_OLDER_THAN_MS);
61
61
  const roots = [join(basePath, STATE_DIR), join(basePath, PARTIAL_DIR), join(basePath, LOCK_DIR)];
62
62
  let removed = 0;
@@ -10,9 +10,9 @@ async function suspiciousReset({ target }, _options = {}) {
10
10
  return { manifest: null, reset: true };
11
11
  }
12
12
  async function loadReusableState(target) {
13
- const manifest = await readManifest(target.manifestPath);
14
- const finalExists = await pathExists(target.finalPath);
15
- const partialExists = await pathExists(target.partialPath);
13
+ const manifest = await readManifest({ path: target.manifestPath });
14
+ const finalExists = await pathExists({ path: target.finalPath });
15
+ const partialExists = await pathExists({ path: target.partialPath });
16
16
  if (manifest === "invalid") {
17
17
  return await suspiciousReset({ target });
18
18
  }
@@ -33,10 +33,10 @@ async function reusableCompleteState(input) {
33
33
  const { manifest, target } = input;
34
34
  // A missing final file needs no separate check: hashing it rejects, which
35
35
  // maps to `null` and fails the checksum comparison into the same reset.
36
- const actual = await hashFile(target.finalPath, target.checksum.algorithm).catch(() => null);
36
+ const actual = await hashFile({ path: target.finalPath, algorithm: target.checksum.algorithm }).catch(() => null);
37
37
  if (actual !== target.checksum.value)
38
38
  return await suspiciousReset({ target });
39
- const bytes = await statFileSize(target.finalPath);
39
+ const bytes = await statFileSize({ path: target.finalPath });
40
40
  if (bytes == null)
41
41
  return await suspiciousReset({ target });
42
42
  return {
@@ -54,7 +54,7 @@ async function reusableCompleteState(input) {
54
54
  };
55
55
  }
56
56
  export async function runManagedDownload(target, options) {
57
- await ensureManagedBase(target.basePath);
57
+ await ensureManagedBase({ basePath: target.basePath });
58
58
  await pruneManagedDownloads({ basePath: target.basePath }).catch(() => undefined);
59
59
  const lock = await acquireLock(target);
60
60
  try {
@@ -63,7 +63,10 @@ export async function runManagedDownload(target, options) {
63
63
  return state.result;
64
64
  const download = await downloadWithRetries({ target, manifest: state.manifest, options });
65
65
  const bytes = await promoteVerifiedPartial({ target });
66
- await writeJson(target.manifestPath, createManifest({ target, state: "complete", patch: { totalBytes: download.totalBytes } }));
66
+ await writeJson({
67
+ path: target.manifestPath,
68
+ payload: createManifest({ target, state: "complete", patch: { totalBytes: download.totalBytes } }),
69
+ });
67
70
  return {
68
71
  bucket: target.bucket,
69
72
  bytes,
@@ -76,7 +79,7 @@ export async function runManagedDownload(target, options) {
76
79
  };
77
80
  }
78
81
  finally {
79
- await releaseLock(lock);
82
+ await releaseLock({ lock });
80
83
  }
81
84
  }
82
85
  /** Reload once after target cleanup, retaining the lock until the run finishes. */
@@ -87,7 +90,7 @@ async function loadStateAllowingOneReset({ target }, _options = {}) {
87
90
  // Whole-base cleanup used to remove the lock and require re-acquisition.
88
91
  // Keep it throughout target cleanup so another process cannot take it
89
92
  // before we write fresh state, or have its own lock deleted by our finally.
90
- await ensureManagedBase(target.basePath);
93
+ await ensureManagedBase({ basePath: target.basePath });
91
94
  const reloaded = await loadReusableState(target);
92
95
  if (reloaded.reset === true) {
93
96
  throw new ManagedDownloadError(MANAGED_DOWNLOAD_ERROR_CODES.STORE_CORRUPT, "download state kept resetting after target cleanup");
@@ -96,8 +99,8 @@ async function loadStateAllowingOneReset({ target }, _options = {}) {
96
99
  }
97
100
  /** Verify the downloaded partial's checksum, promote it to the final path, and return the final size. */
98
101
  async function promoteVerifiedPartial({ target }, _options = {}) {
99
- const actual = await hashFile(target.partialPath, target.checksum.algorithm).catch((error) => {
100
- throw new ManagedDownloadError(MANAGED_DOWNLOAD_ERROR_CODES.STORE_CORRUPT, `downloaded partial could not be hashed: ${errorMessage(error)}`);
102
+ const actual = await hashFile({ path: target.partialPath, algorithm: target.checksum.algorithm }).catch((error) => {
103
+ throw new ManagedDownloadError(MANAGED_DOWNLOAD_ERROR_CODES.STORE_CORRUPT, `downloaded partial could not be hashed: ${errorMessage({ error })}`);
101
104
  });
102
105
  if (actual !== target.checksum.value) {
103
106
  await resetOwnedTarget({ target }).catch(() => undefined);
@@ -107,8 +110,8 @@ async function promoteVerifiedPartial({ target }, _options = {}) {
107
110
  });
108
111
  }
109
112
  await mkdir(dirname(target.finalPath), { recursive: true });
110
- if (await pathExists(target.finalPath)) {
111
- const existing = await hashFile(target.finalPath, target.checksum.algorithm).catch(() => null);
113
+ if (await pathExists({ path: target.finalPath })) {
114
+ const existing = await hashFile({ path: target.finalPath, algorithm: target.checksum.algorithm }).catch(() => null);
112
115
  if (existing !== target.checksum.value) {
113
116
  await resetOwnedTarget({ target }).catch(() => undefined);
114
117
  throw new ManagedDownloadError(MANAGED_DOWNLOAD_ERROR_CODES.STORE_CORRUPT, "existing complete file did not match requested payload");
@@ -118,7 +121,7 @@ async function promoteVerifiedPartial({ target }, _options = {}) {
118
121
  else {
119
122
  await rename(target.partialPath, target.finalPath);
120
123
  }
121
- const bytes = await statFileSize(target.finalPath);
124
+ const bytes = await statFileSize({ path: target.finalPath });
122
125
  if (bytes == null)
123
126
  throw new ManagedDownloadError(MANAGED_DOWNLOAD_ERROR_CODES.STORE_CORRUPT, "complete file is missing after promotion");
124
127
  return bytes;
@@ -1,22 +1,46 @@
1
1
  import { type NormalizedTarget, type DownloadManifest } from './download-types.js';
2
- export declare function errorCode(error: unknown): string | null;
3
- export declare function errorMessage(error: unknown): string;
4
- export declare function pathExists(path: string): Promise<boolean>;
5
- export declare function readJson<T>(path: string): Promise<T | null>;
6
- export declare function writeJson(path: string, payload: unknown): Promise<void>;
7
- export declare function isPlainObject(value: unknown): value is Record<string, unknown>;
2
+ export declare function errorCode({ error }: {
3
+ error: unknown;
4
+ }, _optional?: Record<string, never>): string | null;
5
+ export declare function errorMessage({ error }: {
6
+ error: unknown;
7
+ }, _optional?: Record<string, never>): string;
8
+ export declare function pathExists({ path }: {
9
+ path: string;
10
+ }, _optional?: Record<string, never>): Promise<boolean>;
11
+ export declare function readJson<T>({ path }: {
12
+ path: string;
13
+ }, _optional?: Record<string, never>): Promise<T | null>;
14
+ export declare function writeJson({ path, payload }: {
15
+ path: string;
16
+ payload: unknown;
17
+ }, _optional?: Record<string, never>): Promise<void>;
18
+ export declare function isPlainObject(required: {
19
+ value: unknown;
20
+ }, _optional?: Record<string, never>): required is {
21
+ value: Record<string, unknown>;
22
+ };
8
23
  /** Clear only this target's data after rechecking store ownership; keep its lock held. */
9
24
  export declare function resetOwnedTarget({ target }: {
10
25
  target: NormalizedTarget;
11
26
  }, _options?: {}): Promise<void>;
12
- export declare function ensureManagedBase(basePath: string): Promise<void>;
13
- export declare function readManifest(path: string): Promise<DownloadManifest | "invalid" | null>;
27
+ export declare function ensureManagedBase({ basePath }: {
28
+ basePath: string;
29
+ }, _optional?: Record<string, never>): Promise<void>;
30
+ export declare function readManifest({ path }: {
31
+ path: string;
32
+ }, _optional?: Record<string, never>): Promise<DownloadManifest | "invalid" | null>;
14
33
  export declare function manifestMatchesTarget(manifest: DownloadManifest, target: NormalizedTarget): boolean;
15
34
  export declare function createManifest({ target, state, patch }: {
16
35
  target: NormalizedTarget;
17
36
  state: "complete" | "partial";
18
37
  patch?: Partial<Pick<DownloadManifest, "totalBytes" | "validators">> | undefined;
19
38
  }, _optional?: {}): DownloadManifest;
20
- export declare function hashFile(path: string, algorithm: "sha256" | "sha512"): Promise<string>;
21
- export declare function statFileSize(path: string): Promise<number | null>;
39
+ export declare function hashFile({ path, algorithm }: {
40
+ path: string;
41
+ algorithm: "sha256" | "sha512";
42
+ }, _optional?: Record<string, never>): Promise<string>;
43
+ export declare function statFileSize({ path }: {
44
+ path: string;
45
+ }, _optional?: Record<string, never>): Promise<number | null>;
22
46
  //# sourceMappingURL=download-store.d.ts.map
@@ -4,16 +4,16 @@ import { access, lstat, mkdir, readFile, readdir, rename, rm, stat, writeFile }
4
4
  import { dirname, join } from "node:path";
5
5
  import { pipeline } from "node:stream/promises";
6
6
  import { STORE_KIND, STORE_SCHEMA_VERSION, STORE_SENTINEL, ManagedDownloadError, MANAGED_DOWNLOAD_ERROR_CODES, STATE_DIR, PARTIAL_DIR, LOCK_DIR, MANIFEST_KIND, MANIFEST_SCHEMA_VERSION } from './download-types.js';
7
- export function errorCode(error) {
7
+ export function errorCode({ error }, _optional = {}) {
8
8
  if (typeof error !== "object" || error == null || !("code" in error))
9
9
  return null;
10
10
  const code = error.code;
11
11
  return code == null ? null : String(code);
12
12
  }
13
- export function errorMessage(error) {
13
+ export function errorMessage({ error }, _optional = {}) {
14
14
  return error instanceof Error ? error.message : String(error);
15
15
  }
16
- export async function pathExists(path) {
16
+ export async function pathExists({ path }, _optional = {}) {
17
17
  try {
18
18
  await access(path);
19
19
  return true;
@@ -22,7 +22,7 @@ export async function pathExists(path) {
22
22
  return false;
23
23
  }
24
24
  }
25
- export async function readJson(path) {
25
+ export async function readJson({ path }, _optional = {}) {
26
26
  try {
27
27
  return JSON.parse(await readFile(path, "utf8"));
28
28
  }
@@ -30,7 +30,7 @@ export async function readJson(path) {
30
30
  return null;
31
31
  }
32
32
  }
33
- export async function writeJson(path, payload) {
33
+ export async function writeJson({ path, payload }, _optional = {}) {
34
34
  await mkdir(dirname(path), { recursive: true });
35
35
  const tmp = `${path}.${process.pid}.${Date.now().toString(36)}.tmp`;
36
36
  await writeFile(tmp, `${JSON.stringify(payload, null, 2)}\n`, "utf8");
@@ -44,26 +44,30 @@ async function directoryIsEmpty(path) {
44
44
  // never carry the named string keys (`kind`, `algorithm`, `pid`, ...) each
45
45
  // guard goes on to require, so arrays are rejected without a separate
46
46
  // `Array.isArray` check.
47
- export function isPlainObject(value) {
47
+ export function isPlainObject(required, _optional = {}) {
48
+ const { value } = required;
48
49
  return typeof value === "object" && value != null;
49
50
  }
50
51
  function isStoreSentinel(value) {
51
- if (!isPlainObject(value))
52
+ if (!isPlainObject({ value }))
52
53
  return false;
53
54
  const record = value;
54
55
  return record.kind === STORE_KIND && record.schemaVersion === STORE_SCHEMA_VERSION && typeof record.createdAt === "string";
55
56
  }
56
57
  async function writeSentinel(basePath) {
57
- await writeJson(join(basePath, STORE_SENTINEL), {
58
- createdAt: new Date().toISOString(),
59
- kind: STORE_KIND,
60
- schemaVersion: STORE_SCHEMA_VERSION,
58
+ await writeJson({
59
+ path: join(basePath, STORE_SENTINEL),
60
+ payload: {
61
+ createdAt: new Date().toISOString(),
62
+ kind: STORE_KIND,
63
+ schemaVersion: STORE_SCHEMA_VERSION,
64
+ },
61
65
  });
62
66
  }
63
67
  /** Clear only this target's data after rechecking store ownership; keep its lock held. */
64
68
  export async function resetOwnedTarget({ target }, _options = {}) {
65
69
  const { basePath } = target;
66
- const sentinel = await readJson(join(basePath, STORE_SENTINEL));
70
+ const sentinel = await readJson({ path: join(basePath, STORE_SENTINEL) });
67
71
  if (!isStoreSentinel(sentinel)) {
68
72
  throw new ManagedDownloadError(MANAGED_DOWNLOAD_ERROR_CODES.STORE_NOT_OWNED, `download base is not owned: ${basePath}`);
69
73
  }
@@ -76,14 +80,14 @@ async function ensureStoreDirs(basePath) {
76
80
  await mkdir(join(basePath, PARTIAL_DIR), { recursive: true });
77
81
  await mkdir(join(basePath, LOCK_DIR), { recursive: true });
78
82
  }
79
- export async function ensureManagedBase(basePath) {
83
+ export async function ensureManagedBase({ basePath }, _optional = {}) {
80
84
  await mkdir(basePath, { recursive: true });
81
85
  const entry = await lstat(basePath);
82
86
  if (!entry.isDirectory() || entry.isSymbolicLink()) {
83
87
  throw new ManagedDownloadError(MANAGED_DOWNLOAD_ERROR_CODES.STORE_NOT_OWNED, `download base is not an owned directory: ${basePath}`);
84
88
  }
85
89
  const sentinelPath = join(basePath, STORE_SENTINEL);
86
- const sentinel = await readJson(sentinelPath);
90
+ const sentinel = await readJson({ path: sentinelPath });
87
91
  if (sentinel != null && !isStoreSentinel(sentinel)) {
88
92
  throw new ManagedDownloadError(MANAGED_DOWNLOAD_ERROR_CODES.STORE_NOT_OWNED, `download base has an invalid ownership marker: ${basePath}`);
89
93
  }
@@ -96,7 +100,7 @@ export async function ensureManagedBase(basePath) {
96
100
  await ensureStoreDirs(basePath);
97
101
  }
98
102
  function isChecksum(value) {
99
- if (!isPlainObject(value))
103
+ if (!isPlainObject({ value }))
100
104
  return false;
101
105
  const checksum = value;
102
106
  return ((checksum.algorithm === "sha256" || checksum.algorithm === "sha512") &&
@@ -112,7 +116,7 @@ const MANIFEST_STRING_FIELDS = [
112
116
  "updatedAt",
113
117
  ];
114
118
  function isManifest(value) {
115
- if (!isPlainObject(value))
119
+ if (!isPlainObject({ value }))
116
120
  return false;
117
121
  const record = value;
118
122
  const versionMatches = record.kind === MANIFEST_KIND && record.schemaVersion === MANIFEST_SCHEMA_VERSION;
@@ -122,13 +126,13 @@ function isManifest(value) {
122
126
  isChecksum(record.checksum) &&
123
127
  knownState);
124
128
  }
125
- export async function readManifest(path) {
129
+ export async function readManifest({ path }, _optional = {}) {
126
130
  try {
127
131
  const parsed = JSON.parse(await readFile(path, "utf8"));
128
132
  return isManifest(parsed) ? parsed : "invalid";
129
133
  }
130
134
  catch (error) {
131
- if (errorCode(error) === "ENOENT")
135
+ if (errorCode({ error }) === "ENOENT")
132
136
  return null;
133
137
  return "invalid";
134
138
  }
@@ -157,12 +161,12 @@ export function createManifest({ target, state, patch = {} }, _optional = {}) {
157
161
  ...patch,
158
162
  };
159
163
  }
160
- export async function hashFile(path, algorithm) {
164
+ export async function hashFile({ path, algorithm }, _optional = {}) {
161
165
  const hash = createHash(algorithm);
162
166
  await pipeline(createReadStream(path), hash);
163
167
  return hash.digest("hex");
164
168
  }
165
- export async function statFileSize(path) {
169
+ export async function statFileSize({ path }, _optional = {}) {
166
170
  try {
167
171
  const entry = await stat(path);
168
172
  return entry.isFile() ? entry.size : null;
@@ -1,7 +1,11 @@
1
1
  import { type ManagedDownloadOptions, type NormalizedTarget, type RemoveManagedDownloadOptions } from './download-types.js';
2
2
  export declare const activeTargets: Map<string, string>;
3
- export declare function digest(value: string): string;
4
- export declare function normalizeBasePath(basePath: string): string;
3
+ export declare function digest({ value }: {
4
+ value: string;
5
+ }, _optional?: Record<string, never>): string;
6
+ export declare function normalizeBasePath({ basePath }: {
7
+ basePath: string;
8
+ }, _optional?: Record<string, never>): string;
5
9
  export declare function targetFromOptions(options: Pick<ManagedDownloadOptions, "basePath" | "bucket" | "fileName" | "payload">): NormalizedTarget;
6
10
  export declare function activeKey(target: NormalizedTarget): string;
7
11
  export declare function targetActiveKey(target: NormalizedTarget): string;
@@ -4,7 +4,7 @@ import { pathContains } from "./fs.js";
4
4
  import { ManagedDownloadError, MANAGED_DOWNLOAD_ERROR_CODES, STATE_DIR, PARTIAL_DIR, LOCK_DIR } from './download-types.js';
5
5
  import { errorMessage } from './download-store.js';
6
6
  export const activeTargets = new Map();
7
- export function digest(value) {
7
+ export function digest({ value }, _optional = {}) {
8
8
  return createHash("sha256").update(value).digest("hex");
9
9
  }
10
10
  function normalizeChecksum(input) {
@@ -41,10 +41,10 @@ function normalizeUrl(value) {
41
41
  return url.toString();
42
42
  }
43
43
  catch (error) {
44
- throw new ManagedDownloadError(MANAGED_DOWNLOAD_ERROR_CODES.INVALID_TARGET, errorMessage(error));
44
+ throw new ManagedDownloadError(MANAGED_DOWNLOAD_ERROR_CODES.INVALID_TARGET, errorMessage({ error }));
45
45
  }
46
46
  }
47
- export function normalizeBasePath(basePath) {
47
+ export function normalizeBasePath({ basePath }, _optional = {}) {
48
48
  if (typeof basePath !== "string" || basePath.length === 0 || basePath.includes("\0")) {
49
49
  throw new ManagedDownloadError(MANAGED_DOWNLOAD_ERROR_CODES.INVALID_TARGET, "basePath must be a non-empty path");
50
50
  }
@@ -54,14 +54,14 @@ export function normalizeBasePath(basePath) {
54
54
  return resolve(basePath);
55
55
  }
56
56
  export function targetFromOptions(options) {
57
- const basePath = normalizeBasePath(options.basePath);
57
+ const basePath = normalizeBasePath({ basePath: options.basePath });
58
58
  const bucket = normalizeSegment(options.bucket, "bucket");
59
59
  const fileName = normalizeSegment(options.fileName, "fileName");
60
60
  const checksum = normalizeChecksum(options.payload.checksum);
61
61
  const url = normalizeUrl(options.payload.url);
62
- const urlDigest = digest(url);
63
- const identityDigest = digest(`${url}\0${checksum.algorithm}\0${checksum.value}`);
64
- const targetKey = digest(`${bucket}\0${fileName}`);
62
+ const urlDigest = digest({ value: url });
63
+ const identityDigest = digest({ value: `${url}\0${checksum.algorithm}\0${checksum.value}` });
64
+ const targetKey = digest({ value: `${bucket}\0${fileName}` });
65
65
  const finalPath = resolve(basePath, bucket, fileName);
66
66
  const manifestPath = resolve(basePath, STATE_DIR, `${targetKey}.json`);
67
67
  const partialPath = resolve(basePath, PARTIAL_DIR, `${targetKey}.partial`);
@@ -10,7 +10,7 @@ async function emitExistingProgress(path, totalBytes, emit) {
10
10
  // `acceptedResumeTotalBytes`) whose
11
11
  // last resort is arithmetic (`partialBytes + (contentLength(response) ??
12
12
  // 0)`) — never `undefined`.
13
- const existing = await statFileSize(path);
13
+ const existing = await statFileSize({ path });
14
14
  if (existing == null || existing <= 0)
15
15
  return;
16
16
  emit({ receivedBytes: existing, sessionReceivedBytes: 0, totalBytes });
@@ -98,7 +98,7 @@ function acceptedResumeTotalBytes(input) {
98
98
  }
99
99
  async function tryResumeDownload(input, options) {
100
100
  const { emit, fetchImpl, manifest, target } = input;
101
- const partialBytes = await statFileSize(target.partialPath);
101
+ const partialBytes = await statFileSize({ path: target.partialPath });
102
102
  if (partialBytes == null || partialBytes <= 0)
103
103
  return "restart";
104
104
  const response = await fetchImpl(target.url, {
@@ -108,12 +108,15 @@ async function tryResumeDownload(input, options) {
108
108
  if (totalBytes == null)
109
109
  return "restart";
110
110
  await emitExistingProgress(target.partialPath, totalBytes, emit);
111
- await writeJson(target.manifestPath, {
112
- ...manifest,
113
- state: "partial",
114
- totalBytes,
115
- updatedAt: new Date().toISOString(),
116
- validators: manifest.validators ?? validatorsFromResponse(response),
111
+ await writeJson({
112
+ path: target.manifestPath,
113
+ payload: {
114
+ ...manifest,
115
+ state: "partial",
116
+ totalBytes,
117
+ updatedAt: new Date().toISOString(),
118
+ validators: manifest.validators ?? validatorsFromResponse(response),
119
+ },
117
120
  });
118
121
  await writeResponseBodyToPartial(response, target, { emit, startBytes: partialBytes, totalBytes });
119
122
  return { resumed: true, totalBytes };
@@ -129,7 +132,10 @@ async function downloadFromZero(input, options) {
129
132
  throw new Error(`download request returned HTTP ${response.status}`);
130
133
  const totalBytes = contentLength(response);
131
134
  const validators = validatorsFromResponse(response);
132
- await writeJson(target.manifestPath, createManifest({ target, state: "partial", patch: { totalBytes, validators } }));
135
+ await writeJson({
136
+ path: target.manifestPath,
137
+ payload: createManifest({ target, state: "partial", patch: { totalBytes, validators } }),
138
+ });
133
139
  await writeResponseBodyToPartial(response, target, { emit, startBytes: 0, totalBytes });
134
140
  return { resumed: false, totalBytes };
135
141
  }
@@ -155,12 +161,12 @@ export async function downloadWithRetries({ target, manifest, options }, _option
155
161
  nextManifest = await manifestAfterFailedAttempt({ manifest: nextManifest, target });
156
162
  }
157
163
  }
158
- throw new ManagedDownloadError(MANAGED_DOWNLOAD_ERROR_CODES.NETWORK_EXHAUSTED, `download failed after ${options.maxAttempts} attempts: ${errorMessage(lastError)}`);
164
+ throw new ManagedDownloadError(MANAGED_DOWNLOAD_ERROR_CODES.NETWORK_EXHAUSTED, `download failed after ${options.maxAttempts} attempts: ${errorMessage({ error: lastError })}`);
159
165
  }
160
166
  /** After a failed attempt, mark any bytes already on disk as a resumable partial (best-effort persisted). */
161
167
  async function manifestAfterFailedAttempt(input) {
162
168
  const { manifest, target } = input;
163
- const partialBytes = await statFileSize(target.partialPath);
169
+ const partialBytes = await statFileSize({ path: target.partialPath });
164
170
  if (partialBytes == null || partialBytes <= 0)
165
171
  return manifest;
166
172
  const next = {
@@ -168,7 +174,7 @@ async function manifestAfterFailedAttempt(input) {
168
174
  state: "partial",
169
175
  updatedAt: new Date().toISOString(),
170
176
  };
171
- await writeJson(target.manifestPath, next).catch(() => undefined);
177
+ await writeJson({ path: target.manifestPath, payload: next }).catch(() => undefined);
172
178
  return next;
173
179
  }
174
180
  //# sourceMappingURL=download-transfer.js.map
package/dist/download.js CHANGED
@@ -127,16 +127,16 @@ export async function downloadCopyAndClear(options) {
127
127
  const lease = acquireCopyLease(target);
128
128
  try {
129
129
  const downloaded = await managedDownload(options);
130
- const existingOutput = await statFileSize(outputPath);
130
+ const existingOutput = await statFileSize({ path: outputPath });
131
131
  if (existingOutput != null) {
132
- const existingDigest = await hashFile(outputPath, target.checksum.algorithm).catch(() => null);
132
+ const existingDigest = await hashFile({ path: outputPath, algorithm: target.checksum.algorithm }).catch(() => null);
133
133
  if (existingDigest !== target.checksum.value) {
134
134
  throw new ManagedDownloadError(MANAGED_DOWNLOAD_ERROR_CODES.OUTPUT_CONFLICT, `output already exists with different bytes: ${outputPath}`);
135
135
  }
136
136
  }
137
137
  else {
138
138
  await atomicCopyFile({ sourcePath: downloaded.path, destinationPath: outputPath });
139
- const copiedDigest = await hashFile(outputPath, target.checksum.algorithm);
139
+ const copiedDigest = await hashFile({ path: outputPath, algorithm: target.checksum.algorithm });
140
140
  if (copiedDigest !== target.checksum.value) {
141
141
  throw new ManagedDownloadError(MANAGED_DOWNLOAD_ERROR_CODES.CHECKSUM_MISMATCH, "copied output checksum did not match requested payload");
142
142
  }
@@ -147,7 +147,7 @@ export async function downloadCopyAndClear(options) {
147
147
  cleanup = await requestClearAfterCopy(target);
148
148
  }
149
149
  catch (error) {
150
- cleanupWarning = errorMessage(error);
150
+ cleanupWarning = errorMessage({ error });
151
151
  }
152
152
  return {
153
153
  bytes: downloaded.bytes,
@@ -1,56 +1,3 @@
1
- /**
2
- * @module fetch-with-timeout
3
- *
4
- * The shared timeout wrapper for every outbound `fetch()` call this monorepo makes to a remote
5
- * service — see the 2026-08-16 Jini failure-mode audit, Finding 2: 101 raw `fetch()` call sites
6
- * repo-wide (corrected from the audit's own initial "67" — re-count before trusting any figure in
7
- * a handoff), across devops deploy providers, agent-runtime providers, media-provider dispatch,
8
- * github-client, and llm-provider, most already protected in some ad hoc way. A remote that accepts
9
- * the TCP connection but
10
- * never responds — a stalled load balancer, a provider having a bad day, a firewall black-holing the
11
- * request — leaves `await fetch(...)` unresolved forever; whatever awaits it hangs indefinitely, with
12
- * nothing to alert on. A hang like that is worse than a crash: a crash is loud.
13
- *
14
- * Deliberately ONE helper, not 67 call sites each hand-rolling a slightly different
15
- * `AbortController`/`setTimeout` idiom — a caller who already has their own `AbortSignal` (a
16
- * user-initiated cancel, a parent request's own deadline) can still supply it via `init.signal`;
17
- * `AbortSignal.any` composes it with the timeout so either one aborts the call, and the thrown
18
- * `FetchTimeoutError` vs. the caller's own abort reason stay distinguishable (see `fetchWithTimeout`'s
19
- * own doc).
20
- *
21
- * `FETCH_TIMEOUT_MS` gives call sites a small, documented, shared vocabulary instead of inventing a
22
- * number each time — a deploy-provider API call, an image byte-fetch, and a large asset upload
23
- * genuinely have different reasonable ceilings. `timeoutMs` is never hidden inside the helper as an
24
- * undocumented default with no parameter, though: every call site names one explicitly (usually one
25
- * of these constants), because a caller reading its own code should see the number, not have to go
26
- * find it.
27
- *
28
- * Deliberately excludes anything meant to stay open for a long time independent of transfer size —
29
- * Server-Sent Events, WebSockets, long-poll. None of the 67 flagged call sites are that shape (the
30
- * audit traced this: the repo's real streaming transports are `EventSource` on the browser side and
31
- * a hand-rolled SSE channel server-side, both entirely separate from `fetch()`), but a future caller
32
- * reaching for this helper for one of those would be reaching for the wrong tool — `AbortSignal.timeout`
33
- * bounds the WHOLE call, body included, so it would sever a deliberately long-lived stream partway
34
- * through exactly like the bug this fixes, just self-inflicted instead of accidental.
35
- *
36
- * **Also exported as its own subpath, `@jini-ai/platform/fetch-with-timeout`, deliberately.** This
37
- * module has zero imports of its own — no `node:*` builtin, no `undici` — unlike the package's root
38
- * barrel (`index.ts`), which re-exports sibling modules (`process.ts`, `fs.ts`, `terminal.ts`,
39
- * `asset-cache.ts`, …) that import `node:child_process`, `node:fs`, etc.; the asset-cache
40
- * dispatcher constructs its required `undici` dependency only when its synchronous factory is called.
41
- * Importing from the root barrel in browser-bundled code is silently fine in a *production* build
42
- * through Vite/Rollup — tree-shaking (this package sets `sideEffects: false`) proves the Node-only
43
- * re-exports are unused and drops them before the `node:*` imports are ever resolved — but it is
44
- * NOT fine in `vite dev` or any other unbundled-native-ESM serving mode: there is no tree-shaking on
45
- * that path, so the browser eagerly loads and evaluates every sibling the barrel re-exports, and
46
- * `process.ts`'s very first statement destructures `execFile`/`spawn` off `node:child_process` —
47
- * which Vite's dev server serves as a `Proxy` that throws on first property access. The whole module
48
- * graph fails to evaluate the instant anything imports the barrel, regardless of which export is
49
- * actually used. Verified empirically (`esbuild --bundle --platform=browser` on the barrel: 154
50
- * resolution errors; `vite build`: clean, 5.92kB, zero Node-only code in the output; `vite dev`
51
- * serving `index.js`: throws at import time) — see the 2026-08-17 Jini hardening report. Browser
52
- * call sites should import from this subpath, never the root barrel.
53
- */
54
1
  import type { TextReadOptions } from "@jini-ai/core/net";
55
2
  /** Thrown in place of the platform's generic abort error specifically when the timeout — not a
56
3
  * caller-supplied `init.signal` — is what ended the call, so a caller can tell "this took too long"