@jini-ai/platform 0.7.1 → 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 (165) hide show
  1. package/CHANGELOG.md +2 -2
  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/vault.types.d.ts +0 -27
  164. package/dist/secrets/credential-sets/vault.types.js +0 -49
  165. /package/dist/{http/guarded → mail/activity}/ports.js +0 -0
@@ -0,0 +1,82 @@
1
+ export interface DirectoryRelocationSnapshot<Row> {
2
+ state: "ok" | "missing" | "unreadable";
3
+ rows: Row[];
4
+ dismissed: string[];
5
+ }
6
+ export interface DirectoryRelocationWrite<WriteRow> {
7
+ rows: WriteRow[];
8
+ dismissed: string[];
9
+ }
10
+ export interface DirectoryRelocationReport {
11
+ moved: Array<{
12
+ from: string;
13
+ to: string;
14
+ }>;
15
+ merged: string[];
16
+ }
17
+ export interface DirectoryRelocationRequired<WriteRow, Row extends WriteRow> {
18
+ read(required: Record<string, never>): DirectoryRelocationSnapshot<Row>;
19
+ update(required: {
20
+ change: (current: DirectoryRelocationSnapshot<Row>) => DirectoryRelocationWrite<WriteRow> | null;
21
+ }): unknown;
22
+ directoryOf(required: {
23
+ row: Row;
24
+ }): string;
25
+ recordedIdentityOf(required: {
26
+ row: Row;
27
+ }): string | null | undefined;
28
+ relocationIdentityOf(required: {
29
+ row: Row;
30
+ }): string | undefined;
31
+ classifyDirectory(required: {
32
+ directory: string;
33
+ }): string;
34
+ eligibleClassification: string;
35
+ readIdentity(required: {
36
+ directory: string;
37
+ }): string | null;
38
+ stamp(required: {
39
+ row: Row;
40
+ identity: string;
41
+ }): WriteRow;
42
+ move(required: {
43
+ row: Row;
44
+ directory: string;
45
+ identity: string;
46
+ }): WriteRow;
47
+ }
48
+ export interface DirectoryRelocationOptions {
49
+ searchRoots?: string[];
50
+ listChildren?: (required: {
51
+ root: string;
52
+ }) => string[];
53
+ }
54
+ /** Probe without locking, then recompute inside the host's locked update. Ordinary unchanged polls
55
+ * must not take a lock other instances would wait on. A concurrent adoption/heal must survive.
56
+ * @returns Only relocations/merges from the locked snapshot, never the stale unlocked probe.
57
+ * @complexity O(n*(n+r*c)) marker reads, O(n+r*c) space; no recursive enumeration. */
58
+ export declare function reconcileDirectoryRelocations<WriteRow, Row extends WriteRow>(ports: DirectoryRelocationRequired<WriteRow, Row>, { searchRoots, listChildren }?: DirectoryRelocationOptions): DirectoryRelocationReport;
59
+ export interface DirectoryRelocationGate<Row> {
60
+ shouldRun(required: {
61
+ file: {
62
+ rows: Row[];
63
+ dismissed: string[];
64
+ };
65
+ }, optional?: Record<string, never>): boolean;
66
+ }
67
+ /** Rows, full admission classifications and dismissals describe when something could have moved.
68
+ * The first poll runs; otherwise an idle minute still discovers a folder appearing elsewhere while
69
+ * its old path remains missing. Every four-second poll must not rescan all sibling markers.
70
+ * @complexity O(n) classifications per poll. */
71
+ export declare function createDirectoryRelocationGate<Row>({ directoryOf, classifyDirectory }: {
72
+ directoryOf: (required: {
73
+ row: Row;
74
+ }) => string;
75
+ classifyDirectory: (required: {
76
+ directory: string;
77
+ }) => string;
78
+ }, { now, maxIdleMs }?: {
79
+ now?: () => number;
80
+ maxIdleMs?: number;
81
+ }): DirectoryRelocationGate<Row>;
82
+ //# sourceMappingURL=directory-relocation.d.ts.map
@@ -0,0 +1,99 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { orFallbackSync } from "@jini-ai/core/errors/idioms";
4
+ /** Only immediate children are searched; an unreadable root contributes none. */
5
+ function childPathsOf({ root }, _optional = {}) {
6
+ return orFallbackSync({ work: () => fs.readdirSync(root).map(name => path.join(root, name)), fallback: [], step: "relocation-list-children" });
7
+ }
8
+ /** Guessing between copies is forbidden. Determine ambiguity BEFORE filtering dismissals:
9
+ * an operator removing one twin does not authorize choosing the other.
10
+ * @complexity O(n + r*c) tracked directories and immediate children of deduplicated roots. */
11
+ function relocationTarget({ row, context }, _optional = {}) {
12
+ const { ports } = context;
13
+ const directory = ports.directoryOf({ row });
14
+ // Recorded identity predates relocation stamps. Never infer identity from a folder's name;
15
+ // an invalid original folder can still retain a usable marker.
16
+ const identity = ports.recordedIdentityOf({ row }) ?? ports.relocationIdentityOf({ row }) ?? ports.readIdentity({ directory });
17
+ if (identity === null || identity === undefined)
18
+ return null;
19
+ const roots = new Set([path.dirname(directory), ...context.searchRoots]);
20
+ const candidates = new Set([...context.knownDirs, ...[...roots].flatMap(root => context.listChildren({ root }))]);
21
+ const matches = [...candidates].filter(dir => dir !== directory && ports.classifyDirectory({ directory: dir }) === ports.eligibleClassification && ports.readIdentity({ directory: dir }) === identity);
22
+ const [match] = matches;
23
+ if (matches.length !== 1 || match === undefined || context.dismissed.includes(match))
24
+ return null;
25
+ // The matching id travels with the target instead of being read from disk again.
26
+ return { dir: match, id: identity };
27
+ }
28
+ /** Stamp, repoint, merge or retain one row. The host owns provenance when stamping/moving. */
29
+ function planRow({ plan, row, context }, _optional = {}) {
30
+ const { ports } = context;
31
+ const directory = ports.directoryOf({ row });
32
+ if (ports.classifyDirectory({ directory }) === ports.eligibleClassification) {
33
+ const identity = ports.relocationIdentityOf({ row }) === undefined ? ports.readIdentity({ directory }) : null;
34
+ plan.changed ||= identity !== null;
35
+ plan.rows.push(identity === null ? row : ports.stamp({ row, identity }));
36
+ return;
37
+ }
38
+ const target = relocationTarget({ row, context });
39
+ if (target === null) {
40
+ plan.rows.push(row);
41
+ return;
42
+ }
43
+ plan.changed = true;
44
+ if (context.claimed.has(target.dir)) {
45
+ plan.report.merged.push(directory);
46
+ return;
47
+ }
48
+ context.claimed.add(target.dir);
49
+ plan.report.moved.push({ from: directory, to: target.dir });
50
+ plan.rows.push(ports.move({ row, directory: target.dir, identity: target.id }));
51
+ }
52
+ /** A damaged file stays untouched: a poll must never quarantine or overwrite its recovered rows. */
53
+ function planRelocations({ current, ports, searchRoots, listChildren }, _optional = {}) {
54
+ const plan = { rows: [], report: { moved: [], merged: [] }, changed: false };
55
+ if (current.state !== "ok")
56
+ return plan;
57
+ const context = {
58
+ ports, claimed: new Set(current.rows.map(row => ports.directoryOf({ row }))), dismissed: current.dismissed,
59
+ searchRoots, knownDirs: current.rows.map(row => ports.directoryOf({ row })), listChildren,
60
+ };
61
+ for (const row of current.rows)
62
+ planRow({ plan, row, context });
63
+ return plan;
64
+ }
65
+ /** Probe without locking, then recompute inside the host's locked update. Ordinary unchanged polls
66
+ * must not take a lock other instances would wait on. A concurrent adoption/heal must survive.
67
+ * @returns Only relocations/merges from the locked snapshot, never the stale unlocked probe.
68
+ * @complexity O(n*(n+r*c)) marker reads, O(n+r*c) space; no recursive enumeration. */
69
+ export function reconcileDirectoryRelocations(ports, { searchRoots = [], listChildren = childPathsOf } = {}) {
70
+ let report = { moved: [], merged: [] };
71
+ if (!planRelocations({ current: ports.read({}), ports, searchRoots, listChildren }).changed)
72
+ return report;
73
+ ports.update({ change: current => {
74
+ const plan = planRelocations({ current, ports, searchRoots, listChildren });
75
+ report = plan.report;
76
+ return plan.changed ? { rows: plan.rows, dismissed: current.dismissed } : null;
77
+ } });
78
+ return report;
79
+ }
80
+ /** Rows, full admission classifications and dismissals describe when something could have moved.
81
+ * The first poll runs; otherwise an idle minute still discovers a folder appearing elsewhere while
82
+ * its old path remains missing. Every four-second poll must not rescan all sibling markers.
83
+ * @complexity O(n) classifications per poll. */
84
+ export function createDirectoryRelocationGate({ directoryOf, classifyDirectory }, { now = Date.now, maxIdleMs = 60_000 } = {}) {
85
+ let lastPicture = null;
86
+ let lastRunAt = 0;
87
+ return {
88
+ shouldRun({ file }, _options = {}) {
89
+ const picture = [...file.rows.map(row => `${directoryOf({ row })}\u0000${classifyDirectory({ directory: directoryOf({ row }) })}`), "\u0000dismissed", ...file.dismissed].join("\n");
90
+ const at = now();
91
+ if (picture === lastPicture && at - lastRunAt < maxIdleMs)
92
+ return false;
93
+ lastPicture = picture;
94
+ lastRunAt = at;
95
+ return true;
96
+ },
97
+ };
98
+ }
99
+ //# sourceMappingURL=directory-relocation.js.map
@@ -1,4 +1,4 @@
1
- import { type BootIdentity } from "./boot-identity.js";
1
+ import { type BootIdentity } from "@jini-ai/core/contracts/runtime";
2
2
  import type { DurableJsonFile } from "./durable-json.js";
3
3
  export interface DirectoryRunningRecord {
4
4
  pid: number;
@@ -1,31 +1,34 @@
1
1
  import { fromEarlierBoot } from "./boot-identity.js";
2
+ import {} from "@jini-ai/core/contracts/runtime";
3
+ /** Validate the holder before probing liveness; unreadable/unknown identities fail closed.
4
+ * A malformed address is recoverable only after proving this holder cannot own the DB. O(1).
5
+ */
6
+ function readRunningOwner({ file }) {
7
+ const result = file.read({});
8
+ if (result.state === "missing")
9
+ return null;
10
+ if (result.state !== "ok")
11
+ throw new Error("The running lock is unreadable; refusing to open this directory's database.");
12
+ const record = result.value;
13
+ if (!validRunningOwner(record))
14
+ throw new Error("The running lock is invalid; refusing to open this directory's database.");
15
+ return record;
16
+ }
17
+ /** Release still requires a complete valid record and its token, even for a dead holder. O(1). */
18
+ function readRunningRecord({ file }) {
19
+ const record = readRunningOwner({ file });
20
+ if (record && !validRunningRecord(record))
21
+ throw new Error("The running lock is invalid; refusing to open this directory's database.");
22
+ return record;
23
+ }
2
24
  /** A process lease is distinct from the brief file lock protecting its read/modify/write.
3
25
  * Only proven process death permits stale cleanup. Release/update require the unique claim token.
4
26
  * A zero port means boot is in progress and must still prevent a second database owner.
5
27
  * @complexity O(1) bounded JSON I/O and one liveness probe, plus the file lock wait.
6
28
  */
7
29
  export function createDirectoryRunningLock({ file, isAlive, remove }, { bootIdentity } = {}) {
8
- /** Validate the holder before probing liveness; unreadable/unknown identities fail closed.
9
- * A malformed address is recoverable only after proving this holder cannot own the DB. O(1).
10
- */
11
- function readOwner() {
12
- const result = file.read({});
13
- if (result.state === "missing")
14
- return null;
15
- if (result.state !== "ok")
16
- throw new Error("The running lock is unreadable; refusing to open this directory's database.");
17
- const record = result.value;
18
- if (!validRunningOwner(record))
19
- throw new Error("The running lock is invalid; refusing to open this directory's database.");
20
- return record;
21
- }
22
- /** Release still requires a complete valid record and its token, even for a dead holder. O(1). */
23
- function readRecord() {
24
- const record = readOwner();
25
- if (record && !validRunningRecord(record))
26
- throw new Error("The running lock is invalid; refusing to open this directory's database.");
27
- return record;
28
- }
30
+ const readOwner = () => readRunningOwner({ file });
31
+ const readRecord = () => readRunningRecord({ file });
29
32
  function readLive(cleanup = true) {
30
33
  const record = readOwner();
31
34
  if (!record)
@@ -13,7 +13,7 @@ function listDirectoriesOrEmpty(root) { try {
13
13
  return fs.readdirSync(root);
14
14
  }
15
15
  catch (error) {
16
- return fallbackIfMissing(error, []);
16
+ return fallbackIfMissing({ error, fallback: [] });
17
17
  } }
18
18
  function macRoots({ homeDir, documents }, { paths, exists, listDirectories }) {
19
19
  const cloud = paths.join(homeDir, "Library", "Mobile Documents", "com~apple~CloudDocs");
@@ -3,6 +3,7 @@ import { createHash } from "node:crypto";
3
3
  import { resolveDirectoryHome } from "./directory-home.js";
4
4
  import { resolveUserDataDirectories } from "./user-data-directories.js";
5
5
  import { detectDirectorySync } from "./directory-sync.js";
6
+ import { createConsoleLogger } from '@jini-ai/core/primitives';
6
7
  /** An expected settings refusal whose message is safe to show to the caller.
7
8
  * Filesystem and persistence failures retain their original errors for private diagnostics.
8
9
  */
@@ -31,7 +32,7 @@ function markerBackup(source, namedBackup) {
31
32
  * changing placement controls new databases, never silently moves or abandons existing ones.
32
33
  * @complexity O(n) canonicalizations for n roots; DB lookup probes three fixed locations.
33
34
  */
34
- export function createDirectoryUserConfig({ homeDir, defaultFolder, envName, policy, fileAt, canonicalPath, exists, isDirectory, removeFile }, { env = process.env, cwd = process.cwd(), report = console.warn, ...directoryOptions } = {}) {
35
+ export function createDirectoryUserConfig({ homeDir, defaultFolder, envName, policy, fileAt, canonicalPath, exists, isDirectory, removeFile }, { env = process.env, cwd = process.cwd(), report = (message) => createConsoleLogger({ prefix: '' }).warn({ message }), ...directoryOptions } = {}) {
35
36
  const directories = resolveUserDataDirectories({ homeDir, appName: policy.appName }, { ...directoryOptions, env });
36
37
  const paths = directoryOptions.platform === "win32" ? path.win32 : path;
37
38
  const defaultHome = paths.join(directories.documents, defaultFolder, policy.defaultSubfolder ?? "");
@@ -41,6 +42,16 @@ export function createDirectoryUserConfig({ homeDir, defaultFolder, envName, pol
41
42
  const expand = (value) => canonicalPath({ path: resolveDirectoryHome({ homeDir, defaultFolder, envName, env: {}, setting: value }, { cwd, ...(directoryOptions.platform ? { platform: directoryOptions.platform } : {}) }) });
42
43
  const distinct = (values) => [...new Set(values.map(expand))];
43
44
  const legacyHomes = distinct(legacyHomePaths);
45
+ const syncProvider = (sitesHome) => detectDirectorySync({ dir: sitesHome, homeDir, documents: directories.documents }, { ...directoryOptions, env, canonicalPath });
46
+ const context = { homeDir, defaultFolder, envName, policy, fileAt, canonicalPath, exists, isDirectory, removeFile,
47
+ env, report, directories, paths, defaultHome, localHome, filePath, file, expand, distinct, legacyHomes, syncProvider };
48
+ const stored = createUserConfigStore(context);
49
+ const read = createUserConfigReader(context, stored);
50
+ const { update, updateRoots } = createUserConfigMutations(context, { stored, read });
51
+ const databasePath = createUserConfigDatabasePaths(context, read);
52
+ return { read, update, updateRoots, databasePath, filePath, ...directories, ...createUserConfigViews(context, { stored, read }) };
53
+ }
54
+ function createUserConfigStore({ file, filePath, report }) {
44
55
  function stored(locked = false) {
45
56
  const result = file.read({});
46
57
  if (result.state === "missing")
@@ -62,7 +73,9 @@ export function createDirectoryUserConfig({ homeDir, defaultFolder, envName, pol
62
73
  }
63
74
  return {};
64
75
  }
65
- const syncProvider = (sitesHome) => detectDirectorySync({ dir: sitesHome, homeDir, documents: directories.documents }, { ...directoryOptions, env, canonicalPath });
76
+ return stored;
77
+ }
78
+ function createUserConfigReader({ defaultHome, expand, legacyHomes, paths, policy, env, envName, syncProvider, distinct }, stored) {
66
79
  function read(_required, _options = {}) {
67
80
  const saved = stored();
68
81
  // Old default pointers follow the owner-selected nesting rule; arbitrary custom homes and
@@ -78,6 +91,9 @@ export function createDirectoryUserConfig({ homeDir, defaultFolder, envName, pol
78
91
  // Saved roots are extras; policy roots remain implicit unless the environment overrides them.
79
92
  return fromEnv !== undefined ? fromEnv.split(",").map((root) => root.trim()).filter(Boolean) : [...(policy.sourceRoots ?? []), ...(saved.siteRoots ?? [])];
80
93
  }
94
+ return read;
95
+ }
96
+ function createUserConfigValidation({ expand, exists, isDirectory, env, envName, policy, distinct }) {
81
97
  // Prefer explicit settings, never coerce an existing regular file into a directory.
82
98
  function assertDirectories(checked) {
83
99
  for (const directory of [checked.sitesHome, ...(checked.siteRoots ?? [])]) {
@@ -104,6 +120,11 @@ export function createDirectoryUserConfig({ homeDir, defaultFolder, envName, pol
104
120
  delete next.siteRoots;
105
121
  return next;
106
122
  }
123
+ return { assertDirectories, assertNotOverridden, merged };
124
+ }
125
+ function createUserConfigMutations(context, { stored, read }) {
126
+ const { file, removeFile, filePath, distinct, policy } = context;
127
+ const { assertDirectories, assertNotOverridden, merged } = createUserConfigValidation(context);
107
128
  function update({ patch }, { transform } = {}) {
108
129
  // Compute incremental root changes inside the same lock as the write: a sibling process's
109
130
  // added root must not disappear because this caller previously read an older array.
@@ -129,6 +150,9 @@ export function createDirectoryUserConfig({ homeDir, defaultFolder, envName, pol
129
150
  return { siteRoots: distinct([...(saved.siteRoots ?? []), ...add]).filter((root) => !excluded.has(root) && !protectedRoots.has(root)) };
130
151
  } });
131
152
  }
153
+ return { update, updateRoots };
154
+ }
155
+ function createUserConfigDatabasePaths({ fileAt, exists, report, directories }, read) {
132
156
  // A move journal is written before copying; the old name stays authoritative until verification
133
157
  // retires it. Recovery never guesses from two DB sizes/timestamps or asks users to delete data.
134
158
  function moveMarker(source, candidates) {
@@ -187,7 +211,10 @@ export function createDirectoryUserConfig({ homeDir, defaultFolder, envName, pol
187
211
  return path.join(path.dirname(databasePath({ dir, id, filename: "content.db" })), filename);
188
212
  return read({}).databases === "inSite" ? inSite : appData;
189
213
  }
190
- return { read, update, updateRoots, databasePath, filePath, ...directories,
214
+ return databasePath;
215
+ }
216
+ function createUserConfigViews({ distinct, legacyHomes, exists, isDirectory, policy, env, paths, directories, canonicalPath, syncProvider, localHome }, { stored, read }) {
217
+ return {
191
218
  // Discovery/catalog callers list real old homes. Pointer normalization and creation admission
192
219
  // may inspect the supported spellings even before their directories have been created.
193
220
  legacyHomes: (_required, { includeMissing = false } = {}) => distinct(legacyHomes).filter((root) => includeMissing || (exists(root) && isDirectory(root))),
@@ -21,15 +21,42 @@ export declare function createNodeDirectoryWorkspace({ homeDir, defaultFolder, e
21
21
  fixtureIdPattern: RegExp;
22
22
  temporaryRoots?: readonly string[];
23
23
  };
24
- }, { env, cwd, ports, canonicalPath, ...directoryOptions }?: UserDirectoryOptions & {
24
+ }, { env, cwd, report, ports, canonicalPath, ...directoryOptions }?: UserDirectoryOptions & {
25
25
  env?: NodeJS.ProcessEnv;
26
26
  cwd?: string;
27
+ report?: DurableJsonPorts['report'];
27
28
  ports?: DurableJsonPorts;
28
29
  canonicalPath?: (required: {
29
30
  path: string;
30
31
  }) => string;
31
32
  }): {
32
- homeDir: string;
33
+ running: ({ path: dir }: {
34
+ path: string;
35
+ }, _options?: {}) => import("./directory-running-lock.js").DirectoryRunningLock;
36
+ claim({ path: dir, app, port, scheme }: {
37
+ path: string;
38
+ app: string;
39
+ port?: number;
40
+ scheme?: "http" | "https";
41
+ }, _options?: {}): {
42
+ acquired: boolean;
43
+ record: import("./directory-running-lock.js").DirectoryRunningRecord;
44
+ };
45
+ registry: (_required: Record<string, never>, _options?: {}) => DirectoryRegistry;
46
+ home: (_required: Record<string, never>, _options?: {}) => string;
47
+ setHome({ path: dir }: {
48
+ path: string;
49
+ }, _options?: {}): string;
50
+ /** Commit a verified move's catalog and every injected path reference as one locked unit.
51
+ * Uses the registry owner to preserve identity/collision rules; settings retain env precedence.
52
+ * @complexity O(total catalog/reference bytes), with rollback snapshots in memory.
53
+ */
54
+ relocate({ from, to, entry, references }: {
55
+ from: string;
56
+ to: string;
57
+ entry: import("./directory-registry.js").DirectoryRecord;
58
+ references?: readonly DurableJsonChange[];
59
+ }, _options?: {}): void;
33
60
  config: (_required: Record<string, never>, _options?: {}) => {
34
61
  defaultRoots: string[];
35
62
  extraRoots: string[];
@@ -101,43 +128,20 @@ export declare function createNodeDirectoryWorkspace({ homeDir, defaultFolder, e
101
128
  */
102
129
  homeAvailable: (_required: Record<string, never>, _options?: {}) => boolean;
103
130
  legacyHomes: (_required: Record<string, never>, _options?: {}) => string[];
104
- /** Commit a verified move's catalog and every injected path reference as one locked unit.
105
- * Uses the registry owner to preserve identity/collision rules; settings retain env precedence.
106
- * @complexity O(total catalog/reference bytes), with rollback snapshots in memory.
107
- */
108
- relocate({ from, to, entry, references }: {
109
- from: string;
110
- to: string;
111
- entry: import("./directory-registry.js").DirectoryRecord;
112
- references?: readonly DurableJsonChange[];
113
- }, _options?: {}): void;
114
- home: (_required: Record<string, never>, _options?: {}) => string;
115
- setHome({ path: dir }: {
116
- path: string;
117
- }, _options?: {}): string;
118
- registry: (_required: Record<string, never>, _options?: {}) => DirectoryRegistry;
119
- running: ({ path: dir }: {
120
- path: string;
121
- }, _options?: {}) => import("./directory-running-lock.js").DirectoryRunningLock;
122
- claim({ path: dir, app, port, scheme }: {
123
- path: string;
124
- app: string;
125
- port?: number;
126
- scheme?: "http" | "https";
127
- }, _options?: {}): {
128
- acquired: boolean;
129
- record: import("./directory-running-lock.js").DirectoryRunningRecord;
130
- };
131
+ homeDir: string;
131
132
  };
132
133
  /** Canonicalize existing ancestors without creating the selected directory.
133
134
  * The default canonicalizer of {@link createNodeDirectoryWorkspace}. `realpath` is the native
134
135
  * resolver by default; it is injectable so a missing filesystem root (an unmounted Windows drive)
135
136
  * can be exercised on any host. A missing root resolves to its absolute form.
137
+ * `fallbackOnAnyError` opts into best-effort ancestor resolution for erase containment; other
138
+ * callers still propagate failures other than ENOENT.
136
139
  * @complexity O(d) realpath probes for d path segments.
137
140
  */
138
141
  export declare function canonicalNodeDirectory({ path: dir }: {
139
142
  path: string;
140
- }, { realpath }?: {
143
+ }, { realpath, fallbackOnAnyError }?: {
141
144
  realpath?: (dir: string) => string;
145
+ fallbackOnAnyError?: boolean;
142
146
  }): string;
143
147
  //# sourceMappingURL=directory-workspace.d.ts.map
@@ -10,14 +10,19 @@ import { createDirectoryRunningLock } from "./directory-running-lock.js";
10
10
  import { fallbackIfMissing } from "./errno.js";
11
11
  /** Migration id recorded once the old per-app catalogs are merged into the shared registry. */
12
12
  const APP_DATA_CATALOG_MIGRATION = "app-data-catalog-v1";
13
+ /** An injected reporter replaces the ports' own for every lane of this workspace. */
14
+ function reportingPorts({ ports, report }, _optional = {}) {
15
+ return report ? { ...ports, report } : ports;
16
+ }
13
17
  /** Node assembly only. Policy modules receive explicit filesystem, clock and process ports.
14
18
  * Settings live outside the selected home so changing the setting never loses the pointer.
15
19
  * Reading a missing home/catalog does not create it. Opt-in registry recovery may prune known
16
20
  * pollution on load; read-only hosts omit that policy. Mutations use the durable JSON owner.
17
21
  * @complexity O(n) registry records, O(1) settings/lease operations.
18
22
  */
19
- export function createNodeDirectoryWorkspace({ homeDir, defaultFolder, envName, settingsFile, registryName, runningName, userConfig, registryRecovery }, { env = process.env, cwd = process.cwd(), ports = createNodeDurableJsonPorts({}), canonicalPath = canonicalNodeDirectory, ...directoryOptions } = {}) {
20
- const fileAt = (filePath) => createDurableJsonFile({ ...ports, filePath, notices: {
23
+ export function createNodeDirectoryWorkspace({ homeDir, defaultFolder, envName, settingsFile, registryName, runningName, userConfig, registryRecovery }, { env = process.env, cwd = process.cwd(), report, ports = createNodeDurableJsonPorts({}, { report }), canonicalPath = canonicalNodeDirectory, ...directoryOptions } = {}) {
24
+ const sink = reportingPorts({ ports, report }).report;
25
+ const fileAt = (filePath) => createDurableJsonFile({ ...ports, report: sink, filePath, notices: {
21
26
  prefix: "Directory workspace", lockTimeout: ({ lockPath }) => `Timed out waiting for file lock: ${lockPath}`,
22
27
  } }, { staleMs: Infinity });
23
28
  const config = userConfig ? createDirectoryUserConfig({ homeDir, defaultFolder, envName, policy: userConfig,
@@ -26,21 +31,39 @@ export function createNodeDirectoryWorkspace({ homeDir, defaultFolder, envName,
26
31
  return true;
27
32
  }
28
33
  catch (error) {
29
- return fallbackIfMissing(error, false);
34
+ return fallbackIfMissing({ error, fallback: false });
30
35
  } },
31
- }, { env, cwd, report: (message) => ports.report.error({ message }), ...directoryOptions }) : undefined;
36
+ }, { env, cwd, report: (message) => sink.error({ message }), ...directoryOptions }) : undefined;
32
37
  const settings = fileAt(config?.filePath ?? settingsFile);
33
- function readSetting() {
34
- const read = settings.read({});
35
- if (read.state === "missing")
36
- return undefined;
37
- if (read.state !== "ok" || typeof read.value?.home !== "string")
38
- throw new Error("The directory home setting is unreadable.");
39
- return read.value.home;
40
- }
41
- const legacyHome = () => canonicalPath({ path: resolveDirectoryHome({ homeDir, defaultFolder, envName, env, setting: env[envName] === undefined ? readSetting() : undefined }, { cwd }) });
38
+ const legacyHome = () => canonicalPath({ path: resolveDirectoryHome({ homeDir, defaultFolder, envName, env, setting: env[envName] === undefined ? readSetting(settings) : undefined }, { cwd }) });
42
39
  const home = () => config?.read({}).sitesHome ?? legacyHome();
43
40
  const fixturePattern = registryRecovery ? new RegExp(registryRecovery.fixtureIdPattern.source, registryRecovery.fixtureIdPattern.flags.replace(/[gy]/g, "")) : undefined;
41
+ const context = { homeDir, defaultFolder, envName, settingsFile, registryName, runningName, userConfig, registryRecovery,
42
+ env, cwd, ports: reportingPorts({ ports, report }), canonicalPath, directoryOptions, fileAt, config, settings, home, fixturePattern };
43
+ const atHome = createWorkspaceCatalogReader(context);
44
+ const oldCatalogs = createLegacyWorkspaceCatalogReader(context);
45
+ // One lease adapter for both the app-data and the site-local (legacy) lease locations.
46
+ const runningLockAt = (filePath) => createDirectoryRunningLock({ file: fileAt(filePath), isAlive: ports.process.isAlive,
47
+ remove: () => ports.filesystem.rmSync(filePath, { force: true }) }, { ...(ports.process.bootIdentity ? { bootIdentity: ports.process.bootIdentity } : {}) });
48
+ const registry = createWorkspaceRegistry(context, { atHome, oldCatalogs });
49
+ return {
50
+ homeDir,
51
+ ...createWorkspaceConfigAccess(context),
52
+ ...createWorkspaceRelocation(context, oldCatalogs),
53
+ ...createWorkspaceHomeAccess(context),
54
+ registry: (_required, _options = {}) => registry,
55
+ ...createWorkspaceRunningAccess(context, runningLockAt),
56
+ };
57
+ }
58
+ function readSetting(settings) {
59
+ const read = settings.read({});
60
+ if (read.state === "missing")
61
+ return undefined;
62
+ if (read.state !== "ok" || typeof read.value?.home !== "string")
63
+ throw new Error("The directory home setting is unreadable.");
64
+ return read.value.home;
65
+ }
66
+ function createWorkspaceCatalogReader({ fileAt, config, home, registryName, canonicalPath, registryRecovery, homeDir, fixturePattern, ports }) {
44
67
  const atHome = () => createDirectoryRegistry({ file: fileAt(path.join(config?.appData ?? home(), registryName)), canonicalPath }, registryRecovery ? {
45
68
  discard: ({ entry }) => {
46
69
  const absolute = canonicalPath({ path: entry.path });
@@ -64,11 +87,14 @@ export function createNodeDirectoryWorkspace({ homeDir, defaultFolder, envName,
64
87
  return false;
65
88
  }
66
89
  catch (error) {
67
- return fallbackIfMissing(error, true);
90
+ return fallbackIfMissing({ error, fallback: true });
68
91
  }
69
92
  },
70
93
  reportDiscarded: ({ entries }) => ports.report.error({ message: `Directory workspace: removed ${entries.length} test/temporary catalog entries: ${entries.map((entry) => entry.id).join(", ")}` }),
71
94
  } : {});
95
+ return atHome;
96
+ }
97
+ function createLegacyWorkspaceCatalogReader({ directoryOptions, config, userConfig, fileAt, homeDir, defaultFolder, envName, cwd, home, registryName, canonicalPath }) {
72
98
  // Read old catalogs without modifying sites. Import only under the settings lane on a mutation;
73
99
  // dry-run and startup discovery can inspect the old state without creating app-data files.
74
100
  const oldCatalogs = () => {
@@ -88,6 +114,9 @@ export function createNodeDirectoryWorkspace({ homeDir, defaultFolder, envName,
88
114
  const expandedHome = resolveDirectoryHome({ homeDir, defaultFolder, envName, env: {}, setting: oldHome }, { cwd, ...directoryOptions });
89
115
  return [...new Set([expandedHome, ...config.legacyHomes({}), home()])].map((root) => createDirectoryRegistry({ file: fileAt(path.join(root, registryName)), canonicalPath }));
90
116
  };
117
+ return oldCatalogs;
118
+ }
119
+ function createWorkspaceRegistry({ settings, config, canonicalPath }, { atHome, oldCatalogs }) {
91
120
  const importOldCatalog = () => {
92
121
  const current = atHome();
93
122
  if (!config || current.hasMigration({ migration: APP_DATA_CATALOG_MIGRATION }))
@@ -95,9 +124,6 @@ export function createNodeDirectoryWorkspace({ homeDir, defaultFolder, envName,
95
124
  const previous = oldCatalogs();
96
125
  current.merge({ entries: previous.flatMap((catalog) => catalog.list({})), migrations: previous.flatMap((catalog) => catalog.migrations({})), migration: APP_DATA_CATALOG_MIGRATION });
97
126
  };
98
- // One lease adapter for both the app-data and the site-local (legacy) lease locations.
99
- const runningLockAt = (filePath) => createDirectoryRunningLock({ file: fileAt(filePath), isAlive: ports.process.isAlive,
100
- remove: () => ports.filesystem.rmSync(filePath, { force: true }) }, { ...(ports.process.bootIdentity ? { bootIdentity: ports.process.bootIdentity } : {}) });
101
127
  const mutate = (operation) => settings.withLock({ critical: () => { importOldCatalog(); return operation(); } });
102
128
  // Serialize pointer changes with catalog mutations. A caller that obtained a registry before
103
129
  // settings changed must still write into the current home, never strand a late registration.
@@ -116,8 +142,10 @@ export function createNodeDirectoryWorkspace({ homeDir, defaultFolder, envName,
116
142
  remove: (required, options = {}) => mutate(() => atHome().remove(required, options)),
117
143
  relocate: (required, options = {}) => mutate(() => atHome().relocate(required, options)),
118
144
  };
145
+ return registry;
146
+ }
147
+ function createWorkspaceConfigAccess({ config, home, ports, env, envName, userConfig }) {
119
148
  return {
120
- homeDir,
121
149
  config: (_required, _options = {}) => thisConfig(),
122
150
  updateConfig: (required, options = {}) => {
123
151
  if (!config)
@@ -147,10 +175,20 @@ export function createNodeDirectoryWorkspace({ homeDir, defaultFolder, envName,
147
175
  return ports.filesystem.statSync(parent).isDirectory();
148
176
  }
149
177
  catch (error) {
150
- return fallbackIfMissing(error, false);
178
+ return fallbackIfMissing({ error, fallback: false });
151
179
  }
152
180
  },
153
181
  legacyHomes: (_required, _options = {}) => config?.legacyHomes({}) ?? [],
182
+ };
183
+ function thisConfig() {
184
+ if (!config)
185
+ throw new Error("User config policy is not configured.");
186
+ return { ...config.read({}), defaultRoots: config.defaultRoots({}), extraRoots: config.extraRoots({}), configPath: config.filePath, appData: config.appData, warning: config.syncWarning({}),
187
+ overrides: { sitesHome: env[envName] !== undefined, siteRoots: env[userConfig.rootsEnvName] !== undefined } };
188
+ }
189
+ }
190
+ function createWorkspaceRelocation({ config, canonicalPath, home, fileAt, ports, homeDir, defaultFolder, envName, cwd, directoryOptions, userConfig, registryName }, oldCatalogs) {
191
+ return {
154
192
  /** Commit a verified move's catalog and every injected path reference as one locked unit.
155
193
  * Uses the registry owner to preserve identity/collision rules; settings retain env precedence.
156
194
  * @complexity O(total catalog/reference bytes), with rollback snapshots in memory.
@@ -198,6 +236,10 @@ export function createNodeDirectoryWorkspace({ homeDir, defaultFolder, envName,
198
236
  } }, ...references,
199
237
  ] });
200
238
  },
239
+ };
240
+ }
241
+ function createWorkspaceHomeAccess({ env, envName, config, home, canonicalPath, homeDir, defaultFolder, cwd, settings, fileAt, registryName }) {
242
+ return {
201
243
  home: (_required, _options = {}) => home(),
202
244
  setHome({ path: dir }, _options = {}) {
203
245
  if (env[envName] !== undefined)
@@ -215,7 +257,10 @@ export function createNodeDirectoryWorkspace({ homeDir, defaultFolder, envName,
215
257
  } });
216
258
  return home();
217
259
  },
218
- registry: (_required, _options = {}) => registry,
260
+ };
261
+ }
262
+ function createWorkspaceRunningAccess({ canonicalPath, runningName, config, settings, ports }, runningLockAt) {
263
+ return {
219
264
  running: ({ path: dir }, _options = {}) => {
220
265
  const legacyPath = path.join(canonicalPath({ path: dir }), runningName);
221
266
  const current = runningLockAt(config?.runningPath({ dir }) ?? legacyPath);
@@ -241,30 +286,26 @@ export function createNodeDirectoryWorkspace({ homeDir, defaultFolder, envName,
241
286
  return lock.claim({ record: { pid: ports.process.pid, port, app, scheme, started: new Date(ports.clock.nowMs()).toISOString(), token: randomUUID() } });
242
287
  },
243
288
  };
244
- function thisConfig() {
245
- if (!config)
246
- throw new Error("User config policy is not configured.");
247
- return { ...config.read({}), defaultRoots: config.defaultRoots({}), extraRoots: config.extraRoots({}), configPath: config.filePath, appData: config.appData, warning: config.syncWarning({}),
248
- overrides: { sitesHome: env[envName] !== undefined, siteRoots: env[userConfig.rootsEnvName] !== undefined } };
249
- }
250
289
  }
251
290
  /** Canonicalize existing ancestors without creating the selected directory.
252
291
  * The default canonicalizer of {@link createNodeDirectoryWorkspace}. `realpath` is the native
253
292
  * resolver by default; it is injectable so a missing filesystem root (an unmounted Windows drive)
254
293
  * can be exercised on any host. A missing root resolves to its absolute form.
294
+ * `fallbackOnAnyError` opts into best-effort ancestor resolution for erase containment; other
295
+ * callers still propagate failures other than ENOENT.
255
296
  * @complexity O(d) realpath probes for d path segments.
256
297
  */
257
- export function canonicalNodeDirectory({ path: dir }, { realpath = fs.realpathSync } = {}) {
298
+ export function canonicalNodeDirectory({ path: dir }, { realpath = fs.realpathSync, fallbackOnAnyError = false } = {}) {
258
299
  try {
259
300
  return realpath(dir);
260
301
  }
261
302
  catch (error) {
262
- if (error.code !== "ENOENT")
303
+ if (!fallbackOnAnyError && error.code !== "ENOENT")
263
304
  throw error;
264
305
  // Resolve the nearest existing ancestor too: a not-yet-created home may sit below a
265
306
  // symlink (notably /var on macOS) and must compare equal before and after creation.
266
307
  const absolute = path.resolve(dir), parent = path.dirname(absolute);
267
- return parent === absolute ? absolute : path.join(canonicalNodeDirectory({ path: parent }, { realpath }), path.basename(absolute));
308
+ return parent === absolute ? absolute : path.join(canonicalNodeDirectory({ path: parent }, { realpath, fallbackOnAnyError }), path.basename(absolute));
268
309
  }
269
310
  }
270
311
  //# sourceMappingURL=directory-workspace.js.map