@jini-ai/devops 0.5.5 → 0.6.10

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 (60) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/dist/agent-jobs/jobs.js +33 -26
  3. package/dist/agent-jobs/node.d.ts +14 -0
  4. package/dist/agent-jobs/node.js +8 -3
  5. package/dist/checks/coverage/diff.js +21 -10
  6. package/dist/checks/coverage/disk.js +20 -13
  7. package/dist/checks/coverage/integrity.js +44 -39
  8. package/dist/checks/hardwiring-node.js +89 -73
  9. package/dist/checks/hardwiring.d.ts +5 -0
  10. package/dist/checks/hardwiring.js +75 -48
  11. package/dist/checks/node.js +6 -1
  12. package/dist/checks/published-types/index.js +30 -15
  13. package/dist/core/artifact-store.d.ts +35 -0
  14. package/dist/core/artifact-store.js +2 -0
  15. package/dist/deploy/host-kit.d.ts +3 -0
  16. package/dist/deploy/index.d.ts +1 -0
  17. package/dist/deploy/node.d.ts +10 -0
  18. package/dist/deploy/node.js +11 -3
  19. package/dist/deploy/reachability.d.ts +2 -2
  20. package/dist/deploy/reachability.js +164 -117
  21. package/dist/dns/approval.d.ts +61 -0
  22. package/dist/dns/approval.js +48 -0
  23. package/dist/dns/contract.d.ts +206 -0
  24. package/dist/dns/contract.js +30 -0
  25. package/dist/dns/delegation.d.ts +36 -0
  26. package/dist/dns/delegation.js +44 -0
  27. package/dist/dns/index.d.ts +15 -0
  28. package/dist/dns/index.js +15 -0
  29. package/dist/dns/manual.d.ts +28 -0
  30. package/dist/dns/manual.js +140 -0
  31. package/dist/dns/node/index.d.ts +8 -0
  32. package/dist/dns/node/index.js +8 -0
  33. package/dist/dns/node/resolver.d.ts +35 -0
  34. package/dist/dns/node/resolver.js +155 -0
  35. package/dist/dns/node/udp.d.ts +27 -0
  36. package/dist/dns/node/udp.js +39 -0
  37. package/dist/dns/node/wire.d.ts +36 -0
  38. package/dist/dns/node/wire.js +90 -0
  39. package/dist/dns/plan.d.ts +34 -0
  40. package/dist/dns/plan.js +242 -0
  41. package/dist/dns/records.d.ts +67 -0
  42. package/dist/dns/records.js +144 -0
  43. package/dist/dns/registry.d.ts +26 -0
  44. package/dist/dns/registry.js +59 -0
  45. package/dist/dns/spf.d.ts +23 -0
  46. package/dist/dns/spf.js +35 -0
  47. package/dist/dns/verify.d.ts +61 -0
  48. package/dist/dns/verify.js +109 -0
  49. package/dist/local-dev/index.js +36 -20
  50. package/dist/packaging/electron/archive.d.ts +7 -4
  51. package/dist/packaging/electron/archive.js +32 -25
  52. package/dist/packaging/electron/imports.d.ts +1 -1
  53. package/dist/packaging/electron/imports.js +39 -23
  54. package/dist/packaging/electron/staging.js +68 -47
  55. package/dist/source-control/commit.js +36 -18
  56. package/dist/source-control/registry.js +95 -59
  57. package/dist/static-export/node-adapters.js +26 -17
  58. package/dist/static-export/runner.js +185 -103
  59. package/dist/static-export/transforms.js +26 -23
  60. package/package.json +19 -7
package/CHANGELOG.md CHANGED
@@ -1,5 +1,22 @@
1
1
  # @jini-ai/devops
2
2
 
3
+ ## 0.6.10
4
+
5
+ ### Patch Changes
6
+
7
+ - ea8d883: Preserve positional array-binding holes in hardwiring debt identities.
8
+ - e16a907: Stabilize hardwiring finding identities, reject parse errors, accept injected env defaults, and share installed-public-export inventory and debt adapters.
9
+ - Updated dependencies [22f0619]
10
+ - Updated dependencies [82ed2d3]
11
+ - Updated dependencies [5a3de86]
12
+ - @jini-ai/core@0.6.10
13
+
14
+ ## 0.5.6 — 2026-10-22
15
+
16
+ - 2026-10-22: node:dns authoritative resolver (./dns/node), IPv6 canonicalization and RRset checks in DNS verification, coverage.
17
+
18
+ - `./dns` (new): generic DNS contract kernel, lots D1–D3. RRset record model (structured MX/CAA, TXT 255-byte chunking, ALIAS, proxy flags, provider alias targets); `DnsProvider` with `capabilities.automatic`; pure `planDnsChanges` (preserve-by-default, only conflicting address records change, SPF merge never adds a second `v=spf1`, blockers for CNAME coexistence, apex CNAME without flattening, CAA excluding the target CA, partial/unknown inventory = zero changes) + sha-256 `fingerprintPlan`; `checkDelegation` (NS); authoritative-nameserver `verifyRequirements` with propagated/pending/mismatch/unknown and 30s→10min backoff, 48h cap; approval binding to workspace + provider account + zone + expiry (deletes human-only, apex/MX/delete non-rememberable); built-in `manual` provider with copyable instructions and delegated-subzone lookup; `createDnsProviderRegistry` on the shared provider registry. Apply engine/journal, vendor extraction = later lots.
19
+
3
20
  ## 0.5.5 — 2026-10-16
4
21
 
5
22
  - Static export crawls `<video poster>` images and reports what it dropped (0de2f161).
@@ -1,38 +1,45 @@
1
1
  import path from 'node:path';
2
2
  const jsonDecoder = { decode: ({ line }) => JSON.parse(line) };
3
3
  function record(value) { return value !== null && typeof value === 'object' && !Array.isArray(value); }
4
+ /** Keyed by event type in a Map, so a `type` such as `constructor` never reaches a prototype member. */
5
+ const CODEX_EVENT_HANDLERS = new Map([
6
+ ['turn.completed', (state, event) => { state.completed = true; state.usage = event.usage ?? null; }],
7
+ ['turn.failed', (state, event) => { state.errors.push(`turn.failed: ${JSON.stringify(event.error ?? event)}`); }],
8
+ ['error', (state, event) => { state.errors.push(`error: ${event.message ?? JSON.stringify(event)}`); }],
9
+ ['item.completed', (state, event) => {
10
+ if (record(event.item) && event.item.type === 'agent_message')
11
+ state.lastMessage = typeof event.item.text === 'string' ? event.item.text : undefined;
12
+ }],
13
+ ]);
14
+ /** Undecodable and non-object lines carry no signal and are skipped. */
15
+ function decodeCodexEvent(required) {
16
+ let event;
17
+ try {
18
+ event = required.decoder.decode({ line: required.line });
19
+ }
20
+ catch {
21
+ return undefined;
22
+ }
23
+ return record(event) ? event : undefined;
24
+ }
4
25
  /** Original stream rule: exit status cannot replace completion, no errors, and a final message. */
5
26
  export function parseCodexRun({ jsonl }, optional = {}) {
6
- let completed = false;
7
- let lastMessage;
8
- let usage = null;
9
- const errors = [];
27
+ const state = { completed: false, lastMessage: undefined, usage: null, errors: [] };
28
+ const decoder = optional.decoder ?? jsonDecoder;
10
29
  for (const line of jsonl.split('\n')) {
11
- if (!line.trim())
12
- continue;
13
- let event;
14
- try {
15
- event = (optional.decoder ?? jsonDecoder).decode({ line });
16
- }
17
- catch {
18
- continue;
19
- }
20
- if (!record(event))
21
- continue;
22
- if (event.type === 'turn.completed') {
23
- completed = true;
24
- usage = event.usage ?? null;
25
- }
26
- else if (event.type === 'turn.failed')
27
- errors.push(`turn.failed: ${JSON.stringify(event.error ?? event)}`);
28
- else if (event.type === 'error')
29
- errors.push(`error: ${event.message ?? JSON.stringify(event)}`);
30
- else if (event.type === 'item.completed' && record(event.item) && event.item.type === 'agent_message')
31
- lastMessage = typeof event.item.text === 'string' ? event.item.text : undefined;
30
+ const event = line.trim() ? decodeCodexEvent({ line, decoder }) : undefined;
31
+ if (event)
32
+ CODEX_EVENT_HANDLERS.get(event.type)?.(state, event);
32
33
  }
34
+ return codexVerdict(state);
35
+ }
36
+ /** Errors outrank a missing completion, which outranks a missing final message. */
37
+ function codexVerdict({ completed, errors, lastMessage, usage }) {
33
38
  if (completed && errors.length === 0 && lastMessage)
34
39
  return { success: true, finalMessage: lastMessage.endsWith('\n') ? lastMessage : lastMessage + '\n', usage };
35
- return { success: false, reason: errors.length ? errors.join('\n') : !completed ? 'no turn.completed event' : 'no agent_message' };
40
+ if (errors.length)
41
+ return { success: false, reason: errors.join('\n') };
42
+ return { success: false, reason: completed ? 'no agent_message' : 'no turn.completed event' };
36
43
  }
37
44
  /** Construct argv without a shell; prompt content goes only on stdin. Effort is a TOML string. */
38
45
  export function buildCodexInvocation({ options, prompt }) {
@@ -5,8 +5,22 @@ export declare function createNodeAgentCliRunner({ env }: {
5
5
  }): AgentCliRunnerPort;
6
6
  /** Writes final/failed artifacts; raw logs are streamed by the CLI adapter. */
7
7
  export declare function createNodeJobFilesystem(_required: Record<string, never>): JobFilesystemPort;
8
+ /** The prompt directory as `readPromptJobs` sees it; the default reads the real filesystem. */
9
+ export interface PromptDirectoryPort {
10
+ list(required: {
11
+ directory: string;
12
+ }): Promise<readonly {
13
+ readonly name: string;
14
+ isFile(): boolean;
15
+ }[]>;
16
+ read(required: {
17
+ path: string;
18
+ }): Promise<string>;
19
+ }
8
20
  /** Read regular prompt files in stable order; duplicate basename IDs are rejected by runAgentJobs. */
9
21
  export declare function readPromptJobs({ directory }: {
10
22
  directory: string;
23
+ }, { files }?: {
24
+ files?: PromptDirectoryPort;
11
25
  }): Promise<AgentJob[]>;
12
26
  //# sourceMappingURL=node.d.ts.map
@@ -45,9 +45,14 @@ export function createNodeJobFilesystem(_required) {
45
45
  remove: async ({ path }) => { await rm(path, { force: true }); },
46
46
  };
47
47
  }
48
+ const nodePromptDirectory = {
49
+ list: ({ directory }) => readdir(directory, { withFileTypes: true }),
50
+ read: ({ path: file }) => readFile(file, 'utf8'),
51
+ };
48
52
  /** Read regular prompt files in stable order; duplicate basename IDs are rejected by runAgentJobs. */
49
- export async function readPromptJobs({ directory }) {
50
- const entries = (await readdir(directory, { withFileTypes: true })).filter(entry => entry.isFile()).sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
51
- return Promise.all(entries.map(async (entry) => ({ id: path.parse(entry.name).name, prompt: await readFile(path.join(directory, entry.name), 'utf8') })));
53
+ export async function readPromptJobs({ directory }, { files = nodePromptDirectory } = {}) {
54
+ // Names within one directory are unique, so no two entries compare equal: the former `: 0` arm was unreachable.
55
+ const entries = (await files.list({ directory })).filter(entry => entry.isFile()).sort((a, b) => a.name < b.name ? -1 : 1);
56
+ return Promise.all(entries.map(async (entry) => ({ id: path.parse(entry.name).name, prompt: await files.read({ path: path.join(directory, entry.name) }) })));
52
57
  }
53
58
  //# sourceMappingURL=node.js.map
@@ -17,20 +17,31 @@ function tier(record, threshold, label) {
17
17
  const pctValue = pct({ hit: record.brh, found: record.brf });
18
18
  return { ok: pctValue >= threshold, pctValue, detail: `${pctValue.toFixed(2)}% branch` };
19
19
  }
20
- /** Evaluate two independent tiers; missing records differ from a known branchless source file. */
21
- export function evaluateFileTiers({ file, unitRec, integrationRec, thresholds }) {
20
+ function assertThresholds(thresholds) {
22
21
  for (const value of Object.values(thresholds))
23
22
  if (!Number.isFinite(value) || value < 0 || value > 100)
24
23
  throw new RangeError('tier thresholds must be percentages from 0 to 100');
24
+ }
25
+ /** The branch total both tiers agree on, or why no trustworthy total exists. */
26
+ function sharedBranchTotal(unitRec, integrationRec) {
25
27
  const brf = unitRec?.brf ?? integrationRec?.brf;
26
- if (brf === undefined || (unitRec && integrationRec && unitRec.brf !== integrationRec.brf)) {
27
- const detail = brf === undefined ? 'no coverage record on either tier' : 'inconsistent branch totals between tiers';
28
- return { file, unit: { ok: false, pctValue: 0, detail }, integration: { ok: false, pctValue: 0, detail }, ok: false };
29
- }
30
- if (brf === 0) {
31
- const result = { ok: true, pctValue: 100, detail: '0 branches in this file (vacuously passes both tiers)' };
32
- return { file, unit: { ...result }, integration: { ...result }, ok: true };
33
- }
28
+ if (brf === undefined)
29
+ return { failure: 'no coverage record on either tier' };
30
+ if (unitRec && integrationRec && unitRec.brf !== integrationRec.brf)
31
+ return { failure: 'inconsistent branch totals between tiers' };
32
+ return brf;
33
+ }
34
+ function bothTiers(file, result) {
35
+ return { file, unit: { ...result }, integration: { ...result }, ok: result.ok };
36
+ }
37
+ /** Evaluate two independent tiers; missing records differ from a known branchless source file. */
38
+ export function evaluateFileTiers({ file, unitRec, integrationRec, thresholds }) {
39
+ assertThresholds(thresholds);
40
+ const brf = sharedBranchTotal(unitRec, integrationRec);
41
+ if (typeof brf !== 'number')
42
+ return bothTiers(file, { ok: false, pctValue: 0, detail: brf.failure });
43
+ if (brf === 0)
44
+ return bothTiers(file, { ok: true, pctValue: 100, detail: '0 branches in this file (vacuously passes both tiers)' });
34
45
  const unit = tier(unitRec, thresholds.unit, 'unit');
35
46
  const integration = tier(integrationRec, thresholds.integration, 'integration');
36
47
  return { file, unit, integration, ok: unit.ok && integration.ok };
@@ -138,18 +138,15 @@ export function evaluateDiskArea({ area, onDisk, coverage }) {
138
138
  failures,
139
139
  };
140
140
  }
141
- /** One area's result, rendered. The unmeasured files are named on EVERY run — a gap nobody is told
142
- * about is the trap; a gap printed every run is a decision.
143
- * @complexity O(n). */
144
- export function formatDiskArea({ result, area }, optional = {}) {
145
- const lines = [` ${result.failures.length === 0 ? "OK " : "FAIL"} ${result.id}`];
146
- const floors = area.floors ?? {};
147
- for (const axis of ["line", "branch", "funcs"]) {
141
+ function axisLines(result, floors, noFloorMessage) {
142
+ return ["line", "branch", "funcs"].map((axis) => {
148
143
  const floor = floors[axis];
149
144
  const shown = `${result.actual[axis].toFixed(2)}%`;
150
- lines.push(` ${axis.padEnd(6)} ${shown.padStart(7)} ${typeof floor === "number" ? `(floor ${floor}%)` : (optional.noFloorMessage ?? "(no floor configured)")}`);
151
- }
152
- lines.push(` files: ${result.measuredCount} measured of ${result.onDiskCount} on disk`);
145
+ return ` ${axis.padEnd(6)} ${shown.padStart(7)} ${typeof floor === "number" ? `(floor ${floor}%)` : noFloorMessage}`;
146
+ });
147
+ }
148
+ function gapLines(result) {
149
+ const lines = [];
153
150
  if (result.unmeasured.length > 0) {
154
151
  lines.push(` UNMEASURED (${result.unmeasured.length}, known gap — no test loads these):`);
155
152
  for (const p of result.unmeasured)
@@ -158,8 +155,18 @@ export function formatDiskArea({ result, area }, optional = {}) {
158
155
  if (result.recovered.length > 0) {
159
156
  lines.push(` NOW COVERED, remove from knownUnmeasured: ${result.recovered.join(", ")}`);
160
157
  }
161
- for (const f of result.failures)
162
- lines.push(` ! ${f}`);
163
- return lines.join("\n");
158
+ return lines;
159
+ }
160
+ /** One area's result, rendered. The unmeasured files are named on EVERY run — a gap nobody is told
161
+ * about is the trap; a gap printed every run is a decision.
162
+ * @complexity O(n). */
163
+ export function formatDiskArea({ result, area }, optional = {}) {
164
+ return [
165
+ ` ${result.failures.length === 0 ? "OK " : "FAIL"} ${result.id}`,
166
+ ...axisLines(result, area.floors ?? {}, optional.noFloorMessage ?? "(no floor configured)"),
167
+ ` files: ${result.measuredCount} measured of ${result.onDiskCount} on disk`,
168
+ ...gapLines(result),
169
+ ...result.failures.map((f) => ` ! ${f}`),
170
+ ].join("\n");
164
171
  }
165
172
  //# sourceMappingURL=disk.js.map
@@ -77,54 +77,59 @@ export function isPureReExportBarrelSource({ sourceText }) {
77
77
  const remaining = withoutComments.replace(EXPORT_FROM_STATEMENT, "").trim();
78
78
  return remaining.length === 0;
79
79
  }
80
+ const BARREL_SKIP_REASON = 'pure re-export barrel (source is entirely `export ... from "...";` statements) -- its only ' +
81
+ "instrumented \"functions\" are esbuild's own CJS-interop wrapper helpers plus one lazy getter " +
82
+ 'per re-exported name, not a second merged coverage image; wrapper-name presence here is ' +
83
+ 'structurally guaranteed for any barrel, with or without Route A, so it carries no ' +
84
+ "contamination signal -- see this file's header";
85
+ /** The esbuild wrapper helper names present in a block's FNDA records, and their hit counts. */
86
+ function collectWrapperHits(fnda) {
87
+ const names = new Set();
88
+ const values = new Set();
89
+ for (const { name, hits } of fnda) {
90
+ if (WRAPPER_HELPER_NAMES.has(name)) {
91
+ names.add(name);
92
+ values.add(hits);
93
+ }
94
+ }
95
+ return { names, values };
96
+ }
97
+ /** The SEVERE suffix when the wrapper image also won the line-hit merge, otherwise undefined. */
98
+ function severeLineMergeReason(da, wrapperValues) {
99
+ // A tiny barrel can share hit counts by coincidence. Escalation requires enough DA records
100
+ // and a nonzero overlap with the wrapper's own counts; all-zero runs carry no merge signal.
101
+ if (da.length < MIN_DA_RECORDS_FOR_SEVERE_HEURISTIC)
102
+ return undefined;
103
+ const comparisonSet = new Set(wrapperValues);
104
+ comparisonSet.add(0);
105
+ const distinctDa = [...new Set(da)].sort((a, b) => a - b);
106
+ const extra = distinctDa.filter((value) => !comparisonSet.has(value));
107
+ const overlapHasRealSignal = distinctDa.some((value) => value !== 0 && comparisonSet.has(value));
108
+ if (extra.length > 0 || !overlapHasRealSignal)
109
+ return undefined;
110
+ const wrapperValuesSorted = [...wrapperValues].sort((a, b) => a - b);
111
+ return `. SEVERE: additionally, every one of this block's ${distinctDa.length} ` +
112
+ `distinct DA hit-count value(s) [${distinctDa.join(', ')}] matches a wrapper helper's own FNDA ` +
113
+ `hit-count [${wrapperValuesSorted.join(', ')}] (or 0) -- the wrapper image also won the line-hit ` +
114
+ `merge, so line coverage for this run is untrustworthy too, regardless of what LH:/LF: report`;
115
+ }
80
116
  /** Classify esbuild interop contamination using the host source classifier. */
81
117
  export function classifyBlock({ block, repoRoot, isFirstParty }, { sourceText } = {}) {
82
118
  const file = toRepoRelative({ sourceFile: block.file, repoRoot });
83
119
  if (!isFirstParty({ file }))
84
120
  return { file, status: 'skip', severe: false, reason: 'not a first-party source path' };
85
- if (sourceText !== undefined && isPureReExportBarrelSource({ sourceText })) {
86
- return {
87
- file, status: 'skip', severe: false,
88
- reason: 'pure re-export barrel (source is entirely `export ... from "...";` statements) -- its only ' +
89
- "instrumented \"functions\" are esbuild's own CJS-interop wrapper helpers plus one lazy getter " +
90
- 'per re-exported name, not a second merged coverage image; wrapper-name presence here is ' +
91
- 'structurally guaranteed for any barrel, with or without Route A, so it carries no ' +
92
- "contamination signal -- see this file's header",
93
- };
94
- }
95
- const wrapperNamesFound = new Set();
96
- const wrapperValues = new Set();
97
- for (const { name, hits } of block.fnda) {
98
- if (WRAPPER_HELPER_NAMES.has(name)) {
99
- wrapperNamesFound.add(name);
100
- wrapperValues.add(hits);
101
- }
102
- }
103
- if (wrapperNamesFound.size === 0)
121
+ if (sourceText !== undefined && isPureReExportBarrelSource({ sourceText }))
122
+ return { file, status: 'skip', severe: false, reason: BARREL_SKIP_REASON };
123
+ const wrapper = collectWrapperHits(block.fnda);
124
+ if (wrapper.names.size === 0)
104
125
  return { file, status: 'ok', severe: false, reason: 'no esbuild CJS-wrapper FNDA records in this block' };
105
126
  const fnSummary = block.fnf !== undefined && block.fnh !== undefined ? ` FNF:${block.fnf} FNH:${block.fnh}` : '';
106
- const contaminatedReason = `${wrapperNamesFound.size} esbuild CJS-wrapper helper record(s) [${[...wrapperNamesFound].sort().join(', ')}] ` +
127
+ const contaminatedReason = `${wrapper.names.size} esbuild CJS-wrapper helper record(s) [${[...wrapper.names].sort().join(', ')}] ` +
107
128
  `present in this block's FNDA records -- two coverage images (real ESM + CJS wrapper) were merged ` +
108
129
  `here.${fnSummary} function coverage for this run is untrustworthy`;
109
- // A tiny barrel can share hit counts by coincidence. Escalation requires enough DA records
110
- // and a nonzero overlap with the wrapper's own counts; all-zero runs carry no merge signal.
111
- if (block.da.length >= MIN_DA_RECORDS_FOR_SEVERE_HEURISTIC) {
112
- const comparisonSet = new Set(wrapperValues);
113
- comparisonSet.add(0);
114
- const distinctDa = [...new Set(block.da)].sort((a, b) => a - b);
115
- const extra = distinctDa.filter((value) => !comparisonSet.has(value));
116
- const overlapHasRealSignal = distinctDa.some((value) => value !== 0 && comparisonSet.has(value));
117
- if (extra.length === 0 && overlapHasRealSignal) {
118
- const wrapperValuesSorted = [...wrapperValues].sort((a, b) => a - b);
119
- return {
120
- file, status: 'contaminated', severe: true,
121
- reason: `${contaminatedReason}. SEVERE: additionally, every one of this block's ${distinctDa.length} ` +
122
- `distinct DA hit-count value(s) [${distinctDa.join(', ')}] matches a wrapper helper's own FNDA ` +
123
- `hit-count [${wrapperValuesSorted.join(', ')}] (or 0) -- the wrapper image also won the line-hit ` +
124
- `merge, so line coverage for this run is untrustworthy too, regardless of what LH:/LF: report`,
125
- };
126
- }
127
- }
130
+ const severeSuffix = severeLineMergeReason(block.da, wrapper.values);
131
+ if (severeSuffix !== undefined)
132
+ return { file, status: 'contaminated', severe: true, reason: `${contaminatedReason}${severeSuffix}` };
128
133
  return { file, status: 'contaminated', severe: false, reason: `${contaminatedReason}.` };
129
134
  }
130
135
  /** Evaluate supplied LCOV text and an optional host source reader, without disk I/O. */
@@ -4,7 +4,7 @@
4
4
  import { existsSync, readFileSync, readdirSync, writeFileSync } from 'node:fs';
5
5
  import { dirname, join, relative, resolve } from 'node:path';
6
6
  import { isBuiltin } from 'node:module';
7
- import { diffHardwiringDebt, HARDWIRING_RULES } from './hardwiring.js';
7
+ import { diffHardwiringDebt, HARDWIRING_RULES, syntaxError } from './hardwiring.js';
8
8
  /** Authored inventory excludes generated output, fixtures and tests. O(directory entries). */
9
9
  export function sourceFiles({ directory, declarations = false }, _options = {}) {
10
10
  const found = [];
@@ -35,24 +35,24 @@ export function createResolver({ root, compiler: c, runtime = false, aliases = {
35
35
  return (specifier, file) => {
36
36
  if (isBuiltin(specifier) || /\.(?:css|scss|sass|less|svg|png|jpg|woff2?|json)(?:\?|$)/.test(specifier))
37
37
  return undefined;
38
- for (const [prefix, directory] of Object.entries(aliases)) {
39
- if (specifier.startsWith(prefix)) {
40
- specifier = join(directory, specifier.slice(prefix.length));
41
- break;
42
- }
43
- }
44
- const resolved = c.resolveModuleName(specifier, file, options, host).resolvedModule?.resolvedFileName;
38
+ const resolved = c.resolveModuleName(aliased(specifier, aliases), file, options, host).resolvedModule?.resolvedFileName;
45
39
  if (!resolved)
46
40
  throw new Error(`Unresolved code import in ${relative(root, file)} (specifier omitted); refusing an incomplete public/plugin graph.`);
47
- // Prefer executable published JS over its paired declaration file for bundle reachability.
48
- if (resolved.endsWith('.d.ts')) {
49
- for (const candidate of [resolved.slice(0, -5) + '.js', resolved.slice(0, -5) + '.mjs'])
50
- if (existsSync(candidate))
51
- return candidate;
52
- }
53
- return resolved;
41
+ return executable(resolved);
54
42
  };
55
43
  }
44
+ /** The first matching host alias prefix wins. */
45
+ function aliased(specifier, aliases) {
46
+ const match = Object.entries(aliases).find(([prefix]) => specifier.startsWith(prefix));
47
+ return match ? join(match[1], specifier.slice(match[0].length)) : specifier;
48
+ }
49
+ /** Prefer executable published JS over its paired declaration file for bundle reachability. */
50
+ function executable(resolved) {
51
+ if (!resolved.endsWith('.d.ts'))
52
+ return resolved;
53
+ const stem = resolved.slice(0, -5);
54
+ return [stem + '.js', stem + '.mjs'].find(candidate => existsSync(candidate)) ?? resolved;
55
+ }
56
56
  /** Debt stops at dependency package ownership; authored apps/content keep file identities.
57
57
  * Realpaths can point at sibling workspace packages locally and node_modules in CI.
58
58
  * Normalize dependency ownership to the manifest name so publishing cannot move its waiver.
@@ -70,49 +70,88 @@ export function displayGraphFile({ file, root, authoredDirectories = ['apps', 'c
70
70
  }
71
71
  return relative(root, file).replaceAll('\\', '/');
72
72
  }
73
+ /** Export maps may expose wildcard entries; private declarations stay excluded. */
74
+ function wildcardTargets(file) {
75
+ // Only called for targets containing '*', so split always yields a prefix and a suffix.
76
+ const [prefix, suffix] = file.split('*');
77
+ return sourceFiles({ directory: dirname(prefix), declarations: true })
78
+ .filter(candidate => candidate.startsWith(prefix) && candidate.endsWith(suffix));
79
+ }
73
80
  /** Select installed public targets, favouring declarations without executing package code. */
74
81
  function publicTargets(directory, exports) {
75
82
  const targets = [];
76
- function select(value) {
77
- if (typeof value === 'string') {
78
- if (!value.startsWith('./'))
79
- throw new Error(`Invalid public export target in ${directory}.`);
80
- const file = resolve(directory, value);
81
- if (value.includes('*')) {
82
- const [prefix, suffix] = file.split('*');
83
- // Export maps may expose wildcard entries; private declarations stay excluded.
84
- const scanDir = dirname(prefix);
85
- for (const candidate of sourceFiles({ directory: scanDir, declarations: true })) {
86
- if (candidate.startsWith(prefix) && candidate.endsWith(suffix ?? ''))
87
- targets.push(candidate);
88
- }
89
- }
90
- else if (existsSync(file))
91
- targets.push(file);
92
- else
93
- throw new Error(`Missing installed public entry in ${directory}.`);
83
+ function selectPath(value) {
84
+ if (!value.startsWith('./'))
85
+ throw new Error(`Invalid public export target in ${directory}.`);
86
+ const file = resolve(directory, value);
87
+ if (value.includes('*'))
88
+ targets.push(...wildcardTargets(file));
89
+ else if (existsSync(file))
90
+ targets.push(file);
91
+ else
92
+ throw new Error(`Missing installed public entry in ${directory}.`);
93
+ }
94
+ function selectRecord(record) {
95
+ const entryKeys = Object.keys(record).filter(key => key.startsWith('.'));
96
+ if (entryKeys.length) {
97
+ for (const key of entryKeys)
98
+ select(record[key]);
99
+ return;
94
100
  }
101
+ const condition = ['types', 'import', 'default', 'node', 'browser', 'require'].find(key => record[key] !== undefined);
102
+ if (condition)
103
+ select(record[condition]);
104
+ }
105
+ function select(value) {
106
+ if (typeof value === 'string')
107
+ selectPath(value);
95
108
  else if (Array.isArray(value)) {
96
109
  const candidate = value.find(item => item !== null);
97
110
  if (candidate !== undefined)
98
111
  select(candidate);
99
112
  }
100
- else if (value && typeof value === 'object') {
101
- const record = value;
102
- const entryKeys = Object.keys(record).filter(key => key.startsWith('.'));
103
- if (entryKeys.length)
104
- for (const key of entryKeys)
105
- select(record[key]);
106
- else {
107
- const condition = ['types', 'import', 'default', 'node', 'browser', 'require'].find(key => record[key] !== undefined);
108
- if (condition)
109
- select(record[condition]);
110
- }
111
- }
113
+ else if (value && typeof value === 'object')
114
+ selectRecord(value);
112
115
  }
113
116
  select(exports);
114
117
  return targets;
115
118
  }
119
+ /** Packages without `exports` fall back to their legacy types/main entry, made package-relative. */
120
+ function legacyEntry({ types, main }) {
121
+ const legacy = types ?? main;
122
+ if (!legacy)
123
+ return undefined;
124
+ return legacy.startsWith('./') ? legacy : './' + legacy;
125
+ }
126
+ function packageEntries(directory) {
127
+ const manifest = join(directory, 'package.json');
128
+ if (!existsSync(manifest))
129
+ return [];
130
+ const data = JSON.parse(readFileSync(manifest, 'utf8'));
131
+ if (!data.name?.startsWith('@jini-ai/'))
132
+ return [];
133
+ return publicTargets(directory, data.exports ?? legacyEntry(data));
134
+ }
135
+ /** Parsing errors fail closed for every loaded file, including transitive declarations. */
136
+ function assertParsed(program) {
137
+ for (const file of program.getSourceFiles()) {
138
+ const failure = syntaxError({ tree: file, file: file.fileName });
139
+ if (failure)
140
+ throw failure;
141
+ }
142
+ }
143
+ function callableExports(c, checker, tree) {
144
+ const module = checker.getSymbolAtLocation(tree);
145
+ if (!module)
146
+ return [];
147
+ return checker.getExportsOfModule(module).filter((item) => {
148
+ const symbol = item.flags & c.SymbolFlags.Alias ? checker.getAliasedSymbol(item) : item;
149
+ // Interfaces with call signatures are types, not public runtime functions.
150
+ if (!(symbol.flags & c.SymbolFlags.Value))
151
+ return false;
152
+ return checker.getTypeOfSymbolAtLocation(symbol, symbol.valueDeclaration ?? tree).getCallSignatures().length > 0;
153
+ }).map((item) => item.name);
154
+ }
116
155
  /** HW5 reads only installed package export entries, including aliases and re-export barrels.
117
156
  * TypeScript's checker owns symbol resolution; no source checkout or private dist scan is used.
118
157
  * Parsing errors fail closed; this creates an analysis program without running a typecheck.
@@ -121,39 +160,16 @@ export function installedPublicFunctions({ root, compiler: c }, _options = {}) {
121
160
  const installed = join(root, 'node_modules/@jini-ai');
122
161
  if (!existsSync(installed))
123
162
  throw new Error('Jini export inventory unavailable; install the declared packages.');
124
- const entries = [];
125
- for (const item of readdirSync(installed)) {
126
- const directory = join(installed, item);
127
- const manifest = join(directory, 'package.json');
128
- if (!existsSync(manifest))
129
- continue;
130
- const data = JSON.parse(readFileSync(manifest, 'utf8'));
131
- if (!data.name?.startsWith('@jini-ai/'))
132
- continue;
133
- const legacy = data.types ?? data.main;
134
- entries.push(...publicTargets(directory, data.exports ?? (legacy?.startsWith("./") ? legacy : legacy ? "./" + legacy : undefined)));
135
- }
163
+ const entries = readdirSync(installed).flatMap(item => packageEntries(join(installed, item)));
136
164
  const program = c.createProgram(entries, { moduleResolution: c.ModuleResolutionKind.Bundler, module: c.ModuleKind.ESNext, allowJs: true, noEmit: true, skipLibCheck: true });
165
+ assertParsed(program);
137
166
  const checker = program.getTypeChecker();
138
167
  const found = new Set();
139
- for (const file of program.getSourceFiles()) {
140
- const diagnostics = file.parseDiagnostics;
141
- if (diagnostics.length)
142
- throw new Error(`Cannot parse ${file.fileName}: syntax error at line ${file.getLineAndCharacterOfPosition(diagnostics[0].start ?? 0).line + 1}.`);
143
- }
144
168
  for (const entry of entries) {
145
169
  const tree = program.getSourceFile(entry);
146
- const module = tree && checker.getSymbolAtLocation(tree);
147
- if (!module || !tree)
148
- continue;
149
- for (const item of checker.getExportsOfModule(module)) {
150
- const symbol = item.flags & c.SymbolFlags.Alias ? checker.getAliasedSymbol(item) : item;
151
- // Interfaces with call signatures are types, not public runtime functions.
152
- if (!(symbol.flags & c.SymbolFlags.Value))
153
- continue;
154
- if (checker.getTypeOfSymbolAtLocation(symbol, symbol.valueDeclaration ?? tree).getCallSignatures().length)
155
- found.add(item.name);
156
- }
170
+ if (tree)
171
+ for (const name of callableExports(c, checker, tree))
172
+ found.add(name);
157
173
  }
158
174
  if (!found.size)
159
175
  throw new Error('Jini export inventory is empty; refusing a vacuous duplication check.');
@@ -22,6 +22,11 @@ export interface HardwiringSource {
22
22
  pluginIdentity?: (file: string) => string | undefined;
23
23
  resolveImport?: (specifier: string, file: string) => string | undefined;
24
24
  }
25
+ /** Parse diagnostics can quote source literals; location is sufficient and does not expose secrets. */
26
+ export declare function syntaxError({ tree, file }: {
27
+ tree: ts.SourceFile;
28
+ file: string;
29
+ }, _options?: Record<string, never>): Error | undefined;
25
30
  export declare const HARDWIRING_RULES: readonly ["HW1-env-default", "HW2-vendor-adapter", "HW3-module-state", "HW4-injected-fetch", "HW5-jini-export", "HW6-boot-default", "HW7-public-react", "HW8-provider-url", "HW9-plugin-import"];
26
31
  /** Bind the installed compiler, keeping this optional parser out of the runtime dependency graph.
27
32
  * Inspection is O(n) AST nodes, plus lexical-scope scans for bare fetch calls; no external I/O.