@jini-ai/devops 0.6.15 → 0.6.17

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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,11 @@
1
1
  # @jini-ai/devops
2
2
 
3
+ ## 0.6.17
4
+
5
+ ### Patch Changes
6
+
7
+ - Version bump only.
8
+
3
9
  ## 0.6.13
4
10
 
5
11
  ### Patch Changes
package/README.md CHANGED
@@ -12,8 +12,8 @@ public subpath and permission boundary.
12
12
  | `./source-control` | Trusted provider catalogs, repository validation, export preview and commit orchestration. |
13
13
  | `./static-export` | Manifest/app/writer-driven static export, path transforms and route/asset failure summaries. |
14
14
  | `./static-export/node` | Explicit Node loopback app, artifact writer and theme-file inventory adapters. |
15
- | `./packaging/electron` | Dependency staging, archive byte verification, reachable-import, freshness and quiet-tree policies. |
16
- | `./packaging/electron/typescript` | Host-supplied TypeScript AST adapter; TypeScript is an optional peer. |
15
+ | `./packaging/electron` | Dependency staging, staged runtime closure checks, optional-peer contracts, archive byte verification, freshness and quiet-tree policies. |
16
+ | `./packaging/electron/typescript` | Host-supplied TypeScript AST adapter; TypeScript is a required peer. |
17
17
  | `./agent-jobs` | Bounded CLI jobs with resume, stdin prompts, raw logs and stream-based completion. |
18
18
  | `./checks/published-types` | Published type-surface, registry-drift, linked-package and captured-log checks. |
19
19
  | `./checks/coverage` | LCOV, floor, diff, disk-inventory and contamination/baseline policies. |
@@ -79,6 +79,14 @@ export interface DeployPublishResult {
79
79
  */
80
80
  export interface DeployTarget {
81
81
  readonly id: string;
82
+ /** Resolve the destination before rendering public links. May provision the project's identity
83
+ * as part of an authorized publish; must not upload files or guess a deployment hostname.
84
+ * Optional for older adapters; without it, a host can publish a domainless copy with relative
85
+ * links and omit discovery metadata requiring a public URL, rather than use a locally saved domain.
86
+ */
87
+ resolvePublicUrl?(requiredArgs: {
88
+ projectName: string;
89
+ }, optionalArgs?: Record<string, never>): Promise<string>;
82
90
  publish(requiredArgs: DeployPublishInput, optionalArgs?: DeployPublishOptions): Promise<DeployPublishResult>;
83
91
  checkReachability(requiredArgs: {
84
92
  url: string;
@@ -6,4 +6,7 @@ export * from './imports.js';
6
6
  export * from './stability.js';
7
7
  export * from './node.js';
8
8
  export * from './asar-adapter.js';
9
+ export * from './optional-peers.js';
10
+ export * from './staged-closure.js';
11
+ export * from './staged-closure-node.js';
9
12
  //# sourceMappingURL=entry.d.ts.map
@@ -6,4 +6,7 @@ export * from './imports.js';
6
6
  export * from './stability.js';
7
7
  export * from './node.js';
8
8
  export * from './asar-adapter.js';
9
+ export * from './optional-peers.js';
10
+ export * from './staged-closure.js';
11
+ export * from './staged-closure-node.js';
9
12
  //# sourceMappingURL=entry.js.map
@@ -0,0 +1,22 @@
1
+ /** Manifest-owned opt-in contracts shared by source guards and staged-package checks. */
2
+ export interface OptionalPeerManifest {
3
+ name?: string;
4
+ dependencies?: Readonly<Record<string, string>>;
5
+ peerDependencies?: Readonly<Record<string, string>>;
6
+ peerDependenciesMeta?: Readonly<Record<string, {
7
+ optional?: boolean;
8
+ }>>;
9
+ jini?: {
10
+ optionalPeers?: Readonly<Record<string, string>>;
11
+ };
12
+ }
13
+ /** Only an explicit feature and actionable message authorize an optional runtime boundary. */
14
+ export declare function optionalPeerClassification({ manifest, name }: {
15
+ manifest: OptionalPeerManifest;
16
+ name: string;
17
+ }, _options?: Record<string, never>): string | undefined;
18
+ /** Classification is mandatory even when an optional peer happens to be installed locally. */
19
+ export declare function optionalPeerContractProblems({ manifest }: {
20
+ manifest: OptionalPeerManifest;
21
+ }, _options?: Record<string, never>): string[];
22
+ //# sourceMappingURL=optional-peers.d.ts.map
@@ -0,0 +1,16 @@
1
+ function isOptionalPeer({ manifest, name }) {
2
+ return Boolean(manifest.peerDependencies?.[name] && manifest.peerDependenciesMeta?.[name]?.optional === true);
3
+ }
4
+ /** Only an explicit feature and actionable message authorize an optional runtime boundary. */
5
+ export function optionalPeerClassification({ manifest, name }, _options = {}) {
6
+ const value = manifest.jini?.optionalPeers?.[name];
7
+ if (!isOptionalPeer({ manifest, name }))
8
+ return undefined;
9
+ return typeof value === 'string' && /^opt-in: \S.* [—–] \S.+/.test(value) ? value : undefined;
10
+ }
11
+ /** Classification is mandatory even when an optional peer happens to be installed locally. */
12
+ export function optionalPeerContractProblems({ manifest }, _options = {}) {
13
+ return Object.entries(manifest.peerDependenciesMeta ?? {}).filter(([name, meta]) => meta.optional === true && !optionalPeerClassification({ manifest, name }))
14
+ .map(([name]) => `unclassified optional peer ${name}; declare jini.optionalPeers with opt-in feature and user-facing message, or make it required`);
15
+ }
16
+ //# sourceMappingURL=optional-peers.js.map
@@ -80,6 +80,22 @@ export interface ImportReaderPort {
80
80
  file: string;
81
81
  source: string;
82
82
  }): readonly string[];
83
+ references?(required: {
84
+ file: string;
85
+ source: string;
86
+ }): readonly {
87
+ specifier: string;
88
+ kind: 'import' | 'require';
89
+ line: number;
90
+ deferred: boolean;
91
+ }[];
92
+ }
93
+ export interface RuntimeResolverPort {
94
+ resolve(required: {
95
+ fromFile: string;
96
+ specifier: string;
97
+ kind: 'import' | 'require';
98
+ }): string;
83
99
  }
84
100
  export interface ImportAliasPort {
85
101
  resolve(required: {
@@ -0,0 +1,7 @@
1
+ import type { RuntimeResolverPort } from './ports.js';
2
+ /** Native Node resolution preserves conditional exports, package imports and nested versions.
3
+ * The explicit flag enables Node's parent URL parameter; omitting it would resolve from this tool.
4
+ * No imported module is evaluated. The caller checks target containment and existence.
5
+ */
6
+ export declare function createNodeRuntimeResolver(_input: Record<string, never>, _options?: Record<string, never>): RuntimeResolverPort;
7
+ //# sourceMappingURL=staged-closure-node.d.ts.map
@@ -0,0 +1,17 @@
1
+ import { createRequire } from 'node:module';
2
+ import { fileURLToPath, pathToFileURL } from 'node:url';
3
+ /** Native Node resolution preserves conditional exports, package imports and nested versions.
4
+ * The explicit flag enables Node's parent URL parameter; omitting it would resolve from this tool.
5
+ * No imported module is evaluated. The caller checks target containment and existence.
6
+ */
7
+ export function createNodeRuntimeResolver(_input, _options = {}) {
8
+ if (!process.execArgv.includes('--experimental-import-meta-resolve'))
9
+ throw new Error('staged closure needs node --experimental-import-meta-resolve to resolve from each staged importer');
10
+ return { resolve({ fromFile, specifier, kind }) {
11
+ if (kind === 'require')
12
+ return createRequire(fromFile).resolve(specifier);
13
+ const resolve = import.meta.resolve;
14
+ return fileURLToPath(resolve(specifier, pathToFileURL(fromFile).href));
15
+ } };
16
+ }
17
+ //# sourceMappingURL=staged-closure-node.js.map
@@ -0,0 +1,27 @@
1
+ import type { PackagingFilesystemPort, ImportReaderPort, RuntimeResolverPort } from './ports.js';
2
+ export interface StagedClosureInput {
3
+ root: string;
4
+ /** Host runtime entry files or directories. All installed Jini dist files are also audited. */
5
+ scan: readonly string[];
6
+ /** Package roots sharing this resource tree, e.g. an extracted app.asar directory. */
7
+ packageRoots?: readonly string[];
8
+ fs: PackagingFilesystemPort;
9
+ imports: ImportReaderPort;
10
+ resolver: RuntimeResolverPort;
11
+ /** Native host modules supplied by the executable, e.g. Electron. Never package exceptions. */
12
+ hostModules?: ReadonlySet<string>;
13
+ }
14
+ export interface StagedClosureAudit {
15
+ problems: string[];
16
+ optIns: string[];
17
+ checked: number;
18
+ }
19
+ /**
20
+ * Audit literal runtime references from the staged tree only. All Jini dist files are roots,
21
+ * so deferred loads cannot disappear behind an unexercised feature or a try/catch.
22
+ * Missing peers are exempt only by their owning package's valid opt-in manifest contract.
23
+ * @throws on an invalid scan root, escaping package link, or a parser without runtime references.
24
+ * @complexity O(files + edges × Node resolution cost); each reached file is parsed once.
25
+ */
26
+ export declare function auditStagedClosure(input: StagedClosureInput, _options?: Record<string, never>): StagedClosureAudit;
27
+ //# sourceMappingURL=staged-closure.d.ts.map
@@ -0,0 +1,128 @@
1
+ import path from 'node:path';
2
+ import { isBuiltin } from 'node:module';
3
+ import { optionalPeerClassification } from './optional-peers.js';
4
+ const codeFile = (file) => /\.[cm]?[jt]sx?$/.test(file) && !/\.d\.[cm]?ts$/.test(file) && !/\.(?:test|spec)\.[cm]?[jt]sx?$/.test(file);
5
+ const inside = (root, target) => target === root || target.startsWith(root + path.sep);
6
+ const packageName = (specifier) => specifier.split('/').slice(0, specifier.startsWith('@') ? 2 : 1).join('/');
7
+ /** Scan trees once, never following a symlink outside the stage. O(files), O(files) output. */
8
+ function codeFiles(required) {
9
+ const { directory, root, fs } = required;
10
+ if (!fs.exists({ path: directory }))
11
+ return [];
12
+ if (!inside(root, fs.realpath({ path: directory })))
13
+ throw new Error(`staged scan escapes root: ${directory}`);
14
+ if (fs.stat({ path: directory }).kind === 'file')
15
+ return codeFile(directory) ? [fs.realpath({ path: directory })] : [];
16
+ return fs.entries({ path: directory }).flatMap(name => codeFiles({ directory: path.join(directory, name), root, fs }));
17
+ }
18
+ /** Enumerate nested production package trees, including nested versions and self-contained bundles. */
19
+ function jiniFiles(required) {
20
+ const { directory, root, fs } = required;
21
+ const modules = path.join(directory, 'node_modules');
22
+ if (!fs.exists({ path: modules }))
23
+ return [];
24
+ const packages = fs.entries({ path: modules }).filter(name => !name.startsWith('.')).flatMap(name => {
25
+ const entry = path.join(modules, name);
26
+ return name.startsWith('@') ? fs.entries({ path: entry }).map(child => path.join(entry, child)) : [entry];
27
+ });
28
+ return packages.flatMap(directory => {
29
+ if (!inside(root, fs.realpath({ path: directory })))
30
+ throw new Error(`staged package escapes root: ${directory}`);
31
+ const own = path.basename(path.dirname(directory)) === '@jini-ai'
32
+ ? codeFiles({ directory: path.join(directory, 'dist'), root, fs }) : [];
33
+ return [...own, ...jiniFiles({ directory, root, fs })];
34
+ });
35
+ }
36
+ function manifestOwner(required) {
37
+ const { file, root, fs } = required;
38
+ let directory = path.dirname(file);
39
+ while (inside(root, directory)) {
40
+ const manifest = path.join(directory, 'package.json');
41
+ if (fs.exists({ path: manifest }))
42
+ return JSON.parse(Buffer.from(fs.read({ path: manifest })).toString('utf8'));
43
+ if (directory === root)
44
+ break;
45
+ directory = path.dirname(directory);
46
+ }
47
+ return undefined;
48
+ }
49
+ function exemption(required) {
50
+ const { specifier } = required;
51
+ if (specifier.startsWith('.') || specifier.startsWith('#') || path.isAbsolute(specifier))
52
+ return undefined;
53
+ const manifest = manifestOwner(required);
54
+ if (!manifest?.name?.startsWith('@jini-ai/'))
55
+ return undefined;
56
+ return optionalPeerClassification({ manifest, name: packageName(specifier) });
57
+ }
58
+ /** Check one edge using Node's actual import/require conditions; ancestor resolution is rejected. */
59
+ function resolveEdge(required) {
60
+ const { input, file, specifier, kind } = required;
61
+ const target = input.resolver.resolve({ fromFile: file, specifier, kind });
62
+ const root = input.fs.realpath({ path: input.root });
63
+ if (!inside(root, target))
64
+ throw new Error('resolved outside the staged tree');
65
+ if (!input.fs.exists({ path: target }))
66
+ throw new Error('resolved target does not exist');
67
+ if (!inside(root, input.fs.realpath({ path: target })))
68
+ throw new Error('resolved symlink escapes the staged tree');
69
+ if (input.fs.stat({ path: target }).kind !== 'file')
70
+ throw new Error('resolved target is not a file');
71
+ return target;
72
+ }
73
+ /**
74
+ * Audit literal runtime references from the staged tree only. All Jini dist files are roots,
75
+ * so deferred loads cannot disappear behind an unexercised feature or a try/catch.
76
+ * Missing peers are exempt only by their owning package's valid opt-in manifest contract.
77
+ * @throws on an invalid scan root, escaping package link, or a parser without runtime references.
78
+ * @complexity O(files + edges × Node resolution cost); each reached file is parsed once.
79
+ */
80
+ export function auditStagedClosure(input, _options = {}) {
81
+ if (!input.imports.references)
82
+ throw new Error('staged closure requires an AST runtime-reference reader');
83
+ const root = input.fs.realpath({ path: input.root });
84
+ const queue = [...new Set([...input.scan.flatMap(directory => codeFiles({ directory, root, fs: input.fs })),
85
+ ...(input.packageRoots ?? [root]).flatMap(directory => jiniFiles({ directory, root, fs: input.fs }))])];
86
+ const seen = new Set();
87
+ const problems = [];
88
+ const optIns = [];
89
+ const stagedInput = { ...input, root };
90
+ function failure(file, specifier, location, error) {
91
+ const optIn = exemption({ file, specifier, root, fs: input.fs });
92
+ if (optIn)
93
+ optIns.push(`${location} (${optIn})`);
94
+ else
95
+ problems.push(`${location}: ${error instanceof Error ? error.message : String(error)}`);
96
+ }
97
+ function checkReference(file, ref) {
98
+ if (isBuiltin(ref.specifier) || input.hostModules?.has(ref.specifier))
99
+ return;
100
+ const location = `${path.relative(root, file)}:${ref.line} -> ${ref.specifier}`;
101
+ try {
102
+ const target = resolveEdge({ file, ...ref, input: stagedInput });
103
+ // Third-party packages own their optional internals. This contract audits Jini and host files.
104
+ const relative = path.relative(root, target).split(path.sep).join('/');
105
+ const lastModules = relative.lastIndexOf('node_modules/');
106
+ const owned = lastModules < 0 || /^@jini-ai\/[^/]+\/dist\//.test(relative.slice(lastModules + 'node_modules/'.length));
107
+ if (codeFile(target) && owned)
108
+ queue.push(target);
109
+ }
110
+ catch (error) {
111
+ failure(file, ref.specifier, location, error);
112
+ }
113
+ }
114
+ function scan(file) {
115
+ const source = Buffer.from(input.fs.read({ path: file })).toString('utf8');
116
+ for (const ref of input.imports.references({ file, source }))
117
+ checkReference(file, ref);
118
+ }
119
+ while (queue.length) {
120
+ const file = queue.pop();
121
+ if (seen.has(file))
122
+ continue;
123
+ seen.add(file);
124
+ scan(file);
125
+ }
126
+ return { problems, optIns, checked: seen.size };
127
+ }
128
+ //# sourceMappingURL=staged-closure.js.map
@@ -15,25 +15,48 @@ export declare function stageDir(required: {
15
15
  }, optional?: {
16
16
  dropNestedModules?: boolean;
17
17
  }): void;
18
- /** Plan the production closure first. Fail unresolved/conflicting versions before copying anything. */
18
+ /** Host policy selects runtime edges; the planner still owns resolution/version safety. */
19
+ interface DependencyOptions {
20
+ dependencies?: (required: {
21
+ packageDir: string;
22
+ fs: PackagingFilesystemPort;
23
+ }) => readonly string[];
24
+ }
25
+ /** Plan selected runtime edges before copying; unresolved/conflicting versions throw atomically.
26
+ * Supplied roots are already owned by the caller and are never copied through a back edge.
27
+ * @complexity O(packages + edges × ancestor depth) filesystem reads, O(packages) plan memory.
28
+ * @example stageTransitiveDependencies({ roots, outDir, excluded, fs, resolver });
29
+ */
19
30
  export declare function stageTransitiveDependencies(required: {
20
31
  roots: readonly string[];
21
32
  outDir: string;
22
33
  excluded: ReadonlySet<string>;
23
34
  fs: PackagingFilesystemPort;
24
35
  resolver: PackageResolverPort;
25
- }): number;
36
+ }, optional?: DependencyOptions): number;
26
37
  /** Enumerate real package roots, treating scoped directories as containers. */
27
38
  export declare function stagedPackageDirs({ modulesDir, fs }: {
28
39
  modulesDir: string;
29
40
  fs: PackagingFilesystemPort;
30
41
  }): string[];
31
- /** Check nested/hoisted dependencies only inside shipped modules; ancestors cannot fill gaps. */
42
+ /** Inventory every staged package, including nested scopes, and report missing declared edges.
43
+ * Hosts may select peers/optionals through the same policy seam as the staging planner.
44
+ * @returns Ordered package-to-dependency diagnostics, suitable for host-specific refusal messages.
45
+ * @throws Error if the staged modules tree is missing.
46
+ * @complexity O(packages + edges × ancestor depth) filesystem probes; O(packages + gaps) memory.
47
+ * @example missingClosureDependencies({ outDir, excluded, fs });
48
+ */
49
+ export declare function missingClosureDependencies(required: {
50
+ outDir: string;
51
+ excluded: ReadonlySet<string>;
52
+ fs: PackagingFilesystemPort;
53
+ }, optional?: DependencyOptions): string[];
54
+ /** Refuse incomplete nested/hoisted closures; checkout ancestors cannot fill shipped gaps. */
32
55
  export declare function assertClosureComplete(required: {
33
56
  outDir: string;
34
57
  excluded: ReadonlySet<string>;
35
58
  fs: PackagingFilesystemPort;
36
- }): void;
59
+ }, optional?: DependencyOptions): void;
37
60
  /** Share the existing workspace build/pack/rewritten-tarball implementation via a host binding. */
38
61
  export declare function stagePackedWorkspace(required: {
39
62
  repoRoot: string;
@@ -105,4 +128,5 @@ export declare function stageBundledNpm(required: {
105
128
  fileCount: number;
106
129
  bytes: number;
107
130
  };
131
+ export {};
108
132
  //# sourceMappingURL=staging.d.ts.map
@@ -47,6 +47,8 @@ function planDependency(plan, required) {
47
47
  if (isExcluded({ name, excluded }))
48
48
  return;
49
49
  const directory = resolveDependency({ from, name, fs, resolver });
50
+ if (plan.roots.has(directory))
51
+ return;
50
52
  const planned = { directory, version: manifest(directory, fs).version };
51
53
  const existing = staged.get(name);
52
54
  assertFlattenable({ name, planned, existing, destination: stagedPath(outDir, name), fs });
@@ -57,14 +59,18 @@ function planDependency(plan, required) {
57
59
  queue.push(directory);
58
60
  }
59
61
  }
60
- /** Plan the production closure first. Fail unresolved/conflicting versions before copying anything. */
61
- export function stageTransitiveDependencies(required) {
62
+ /** Plan selected runtime edges before copying; unresolved/conflicting versions throw atomically.
63
+ * Supplied roots are already owned by the caller and are never copied through a back edge.
64
+ * @complexity O(packages + edges × ancestor depth) filesystem reads, O(packages) plan memory.
65
+ * @example stageTransitiveDependencies({ roots, outDir, excluded, fs, resolver });
66
+ */
67
+ export function stageTransitiveDependencies(required, optional = {}) {
62
68
  const { roots, outDir, fs } = required;
63
69
  const visited = new Set(roots.map(root => fs.realpath({ path: root })));
64
- const plan = { ...required, staged: new Map(), visited, queue: [...visited] };
70
+ const plan = { ...required, staged: new Map(), roots: new Set(visited), visited, queue: [...visited] };
65
71
  for (let index = 0; index < plan.queue.length; index++) {
66
72
  const from = plan.queue[index];
67
- for (const name of declaredDependencies({ packageDir: from, fs }))
73
+ for (const name of (optional.dependencies ?? declaredDependencies)({ packageDir: from, fs }))
68
74
  planDependency(plan, { from, name });
69
75
  }
70
76
  let count = 0;
@@ -88,22 +94,51 @@ export function stagedPackageDirs({ modulesDir, fs }) {
88
94
  return fs.entries({ path: full }).map(scoped => path.join(full, scoped)).filter(dir => fs.exists({ path: path.join(dir, PACKAGE_JSON) }));
89
95
  });
90
96
  }
91
- /** Check nested/hoisted dependencies only inside shipped modules; ancestors cannot fill gaps. */
92
- export function assertClosureComplete(required) {
97
+ /** Resolve a dependency using Node's ancestor search, bounded to the shipped modules tree.
98
+ * Symlinks escaping the payload cannot satisfy an edge. O(ancestor depth) filesystem probes.
99
+ */
100
+ function shippedDependency({ directory, name, modulesDir, fs }, _optional = {}) {
101
+ const candidates = [];
102
+ for (let current = directory; current.startsWith(modulesDir + path.sep); current = path.dirname(current))
103
+ candidates.push(path.join(current, 'node_modules', name));
104
+ const found = [...candidates, path.join(modulesDir, name)].find(candidate => fs.exists({ path: path.join(candidate, PACKAGE_JSON) }));
105
+ if (!found)
106
+ return false;
107
+ const relative = path.relative(fs.realpath({ path: modulesDir }), fs.realpath({ path: found }));
108
+ return relative !== '..' && !relative.startsWith('..' + path.sep) && !path.isAbsolute(relative);
109
+ }
110
+ /** Inventory every staged package, including nested scopes, and report missing declared edges.
111
+ * Hosts may select peers/optionals through the same policy seam as the staging planner.
112
+ * @returns Ordered package-to-dependency diagnostics, suitable for host-specific refusal messages.
113
+ * @throws Error if the staged modules tree is missing.
114
+ * @complexity O(packages + edges × ancestor depth) filesystem probes; O(packages + gaps) memory.
115
+ * @example missingClosureDependencies({ outDir, excluded, fs });
116
+ */
117
+ export function missingClosureDependencies(required, optional = {}) {
93
118
  const { outDir, excluded, fs } = required;
94
119
  const modulesDir = path.join(outDir, 'node_modules');
95
- const missing = [];
96
120
  if (!fs.exists({ path: modulesDir }))
97
121
  throw new Error('staged node_modules tree is missing');
98
- // Hoisted beside the package, or nested inside it: the only two places a shipped require can land.
99
- const shipped = (directory, name) => fs.exists({ path: path.join(modulesDir, name, PACKAGE_JSON) }) || fs.exists({ path: path.join(directory, 'node_modules', name, PACKAGE_JSON) });
100
- for (const directory of stagedPackageDirs({ modulesDir, fs })) {
101
- for (const name of declaredDependencies({ packageDir: directory, fs })) {
122
+ const packages = stagedPackageDirs({ modulesDir, fs });
123
+ const missing = [], visited = new Set();
124
+ // Inventory nested packages even when no top-level dependency happens to reference them.
125
+ for (const directory of packages) {
126
+ const real = fs.realpath({ path: directory });
127
+ if (visited.has(real))
128
+ continue;
129
+ visited.add(real);
130
+ packages.push(...stagedPackageDirs({ modulesDir: path.join(directory, 'node_modules'), fs }));
131
+ for (const name of (optional.dependencies ?? declaredDependencies)({ packageDir: directory, fs })) {
102
132
  safePackageName(name);
103
- if (!isExcluded({ name, excluded }) && !shipped(directory, name))
133
+ if (!isExcluded({ name, excluded }) && !shippedDependency({ directory, name, modulesDir, fs }))
104
134
  missing.push(`${path.relative(modulesDir, directory)} -> ${name}`);
105
135
  }
106
136
  }
137
+ return missing;
138
+ }
139
+ /** Refuse incomplete nested/hoisted closures; checkout ancestors cannot fill shipped gaps. */
140
+ export function assertClosureComplete(required, optional = {}) {
141
+ const missing = missingClosureDependencies(required, optional);
107
142
  if (missing.length)
108
143
  throw new Error(`staged tree is missing ${missing.length} declared dependencies:\n ${missing.join('\n ')}`);
109
144
  }
@@ -1,7 +1,20 @@
1
1
  import type ts from 'typescript';
2
2
  import type { ImportReaderPort } from './ports.js';
3
- /** Bind the maintained TypeScript parser supplied by the host; no parser dependency at runtime. */
3
+ export interface RuntimeImportRef {
4
+ specifier: string;
5
+ kind: 'import' | 'require';
6
+ line: number;
7
+ deferred: boolean;
8
+ typeOnly?: boolean;
9
+ }
10
+ /** Read syntax with the host's maintained parser. No module is executed. O(source length). */
11
+ export declare function runtimeImportReferences({ compiler: c, file, source }: {
12
+ compiler: typeof ts;
13
+ file: string;
14
+ source: string;
15
+ }, _options?: Record<string, never>): RuntimeImportRef[];
16
+ /** Bind one parser owner for static, dynamic, CommonJS and createRequire references. */
4
17
  export declare function createTypeScriptImportReader({ compiler }: {
5
18
  compiler: typeof ts;
6
- }): ImportReaderPort;
19
+ }, _options?: Record<string, never>): ImportReaderPort;
7
20
  //# sourceMappingURL=typescript.d.ts.map
@@ -1,23 +1,103 @@
1
- /** Bind the maintained TypeScript parser supplied by the host; no parser dependency at runtime. */
2
- export function createTypeScriptImportReader({ compiler }) {
3
- return { imports({ file, source }) {
4
- const tree = compiler.createSourceFile(file, source, compiler.ScriptTarget.Latest, false, compiler.ScriptKind.JS);
5
- const found = [];
6
- function moduleSpecifierOf(node) {
7
- if (compiler.isImportDeclaration(node) || compiler.isExportDeclaration(node))
8
- return node.moduleSpecifier;
9
- if (compiler.isCallExpression(node) && node.expression.kind === compiler.SyntaxKind.ImportKeyword)
10
- return node.arguments[0];
11
- return undefined;
12
- }
13
- function visit(node) {
14
- const literal = moduleSpecifierOf(node);
15
- if (literal !== undefined && compiler.isStringLiteral(literal))
16
- found.push(literal.text);
17
- compiler.forEachChild(node, visit);
18
- }
19
- visit(tree);
20
- return found;
21
- } };
1
+ /** Read syntax with the host's maintained parser. No module is executed. O(source length). */
2
+ export function runtimeImportReferences({ compiler: c, file, source }, _options = {}) {
3
+ const tree = c.createSourceFile(file, source, c.ScriptTarget.Latest, true, file.endsWith('.tsx') ? c.ScriptKind.TSX : c.ScriptKind.TS);
4
+ const scopes = new Map();
5
+ const found = [];
6
+ function scopeOf(node) {
7
+ let parent = node.parent;
8
+ while (parent && !c.isBlock(parent) && !c.isFunctionLike(parent) && !c.isSourceFile(parent))
9
+ parent = parent.parent;
10
+ return parent ?? tree;
11
+ }
12
+ function lookup(node) {
13
+ let scope = scopeOf(node);
14
+ while (scope) {
15
+ const value = scopes.get(scope)?.get(node.text);
16
+ if (value)
17
+ return value;
18
+ scope = scope === tree ? undefined : scopeOf(scope);
19
+ }
20
+ if (node.text === 'require')
21
+ return 'require';
22
+ return node.text === 'createRequire' ? 'creator' : undefined;
23
+ }
24
+ function isCreator(node) {
25
+ if (c.isIdentifier(node))
26
+ return lookup(node) === 'creator';
27
+ return c.isPropertyAccessExpression(node) && node.name.text === 'createRequire';
28
+ }
29
+ function bind(node, name, value) {
30
+ const scope = scopeOf(node);
31
+ const values = scopes.get(scope) ?? new Map();
32
+ values.set(name, value);
33
+ scopes.set(scope, values);
34
+ }
35
+ function variableBinding(node) {
36
+ if (!c.isVariableDeclaration(node) || !c.isIdentifier(node.name))
37
+ return;
38
+ const init = node.initializer;
39
+ const value = init && c.isCallExpression(init) && isCreator(init.expression) ? 'require' : 'other';
40
+ bind(node, node.name.text, value);
41
+ }
42
+ function bindings(node) {
43
+ if (c.isImportSpecifier(node) && (node.propertyName ?? node.name).text === 'createRequire')
44
+ bind(node, node.name.text, 'creator');
45
+ if (c.isParameter(node) && c.isIdentifier(node.name))
46
+ bind(node, node.name.text, 'other');
47
+ variableBinding(node);
48
+ c.forEachChild(node, bindings);
49
+ }
50
+ bindings(tree);
51
+ function isRequire(node) {
52
+ if (c.isIdentifier(node))
53
+ return lookup(node) === 'require';
54
+ return c.isCallExpression(node) && isCreator(node.expression);
55
+ }
56
+ function inlineTypes(clause) {
57
+ if (!clause)
58
+ return false;
59
+ if (!c.isNamedImports(clause) && !c.isNamedExports(clause))
60
+ return false;
61
+ return clause.elements.length > 0 && clause.elements.every(e => e.isTypeOnly);
62
+ }
63
+ function erased(node) {
64
+ if (c.isImportDeclaration(node)) {
65
+ const clause = node.importClause;
66
+ return Boolean(clause?.isTypeOnly || (!clause?.name && inlineTypes(clause?.namedBindings)));
67
+ }
68
+ return node.isTypeOnly || inlineTypes(node.exportClause);
69
+ }
70
+ function callReference(node) {
71
+ if (node.expression.kind === c.SyntaxKind.ImportKeyword)
72
+ return { literal: node.arguments[0], kind: 'import' };
73
+ const call = node.expression;
74
+ if (isRequire(call))
75
+ return { literal: node.arguments[0], kind: 'require' };
76
+ if (c.isPropertyAccessExpression(call) && call.name.text === 'resolve' && isRequire(call.expression))
77
+ return { literal: node.arguments[0], kind: 'require' };
78
+ return undefined;
79
+ }
80
+ function reference(node) {
81
+ if (c.isImportDeclaration(node) || c.isExportDeclaration(node))
82
+ return { literal: node.moduleSpecifier, kind: 'import', typeOnly: erased(node) };
83
+ if (c.isImportEqualsDeclaration(node) && c.isExternalModuleReference(node.moduleReference))
84
+ return { literal: node.moduleReference.expression, kind: 'require', typeOnly: node.isTypeOnly };
85
+ return c.isCallExpression(node) ? callReference(node) : undefined;
86
+ }
87
+ function visit(node, deferred = false) {
88
+ const ref = reference(node);
89
+ if (ref?.literal && c.isStringLiteralLike(ref.literal))
90
+ found.push({ specifier: ref.literal.text, kind: ref.kind,
91
+ typeOnly: ref.typeOnly ?? false, line: tree.getLineAndCharacterOfPosition(node.getStart(tree)).line + 1, deferred });
92
+ const nested = deferred || c.isFunctionLike(node);
93
+ c.forEachChild(node, child => visit(child, nested));
94
+ }
95
+ visit(tree);
96
+ return found;
97
+ }
98
+ /** Bind one parser owner for static, dynamic, CommonJS and createRequire references. */
99
+ export function createTypeScriptImportReader({ compiler }, _options = {}) {
100
+ const references = ({ file, source }) => runtimeImportReferences({ compiler, file, source }).filter(ref => !ref.typeOnly);
101
+ return { references, imports: required => references(required).map(ref => ref.specifier) };
22
102
  }
23
103
  //# sourceMappingURL=typescript.js.map
@@ -1,5 +1,18 @@
1
1
  import { firstExportFailure } from '../core/export-failure-summary.js';
2
2
  import { validateCommitTarget } from './repository-target.js';
3
+ import { normalizeRepositoryFolder, prefixRepositoryPath } from './repository-path.js';
4
+ /** Folder validation precedes credentials, rendering and all provider effects. */
5
+ function folderError(required, optional = {}) {
6
+ try {
7
+ const folder = normalizeRepositoryFolder(required);
8
+ if (folder && optional.committing && required.supportsFolder !== true)
9
+ return 'This provider does not support folder commits.';
10
+ return null;
11
+ }
12
+ catch (error) {
13
+ return error.message;
14
+ }
15
+ }
3
16
  /** Normalize platform separators without changing the retained byte payload. */
4
17
  export function toCommitFile(required) {
5
18
  return { path: required.outputFile.replace(/\\/g, '/'), data: required.data };
@@ -13,7 +26,11 @@ async function exportIntoRunDirectory(input, claim) {
13
26
  const failure = firstExportFailure({ report });
14
27
  if (failure)
15
28
  return { ok: false, code: 'EXPORT_FAILED', message: `refused to commit: ${failure.count} ${failure.kind}(s) failed to export (first: '${failure.identifier}' — ${failure.reason})` };
16
- return { ok: true, files: [...report.routes.succeeded.map(toCommitFile), ...report.assets.succeeded.map(toCommitFile)] };
29
+ const files = [...report.routes.succeeded.map(toCommitFile), ...report.assets.succeeded.map(toCommitFile)];
30
+ // Validate every folder-relative path while export failures still use the safe outcome channel.
31
+ for (const file of files)
32
+ prefixRepositoryPath({ folder: input.folder, path: file.path });
33
+ return { ok: true, files };
17
34
  }
18
35
  catch (error) {
19
36
  return { ok: false, code: 'EXPORT_FAILED', message: `export failed before committing could start: ${input.describeError({ error })}` };
@@ -36,13 +53,13 @@ async function exportForCommit(input) {
36
53
  }
37
54
  /** Run a real fresh export, without credentials or repository I/O. */
38
55
  export async function previewCommitExport(required, optional = {}) {
39
- const error = validateCommitTarget(required, optional);
56
+ const error = validateCommitTarget(required, optional) ?? folderError(required);
40
57
  if (error)
41
58
  return { ok: false, code: 'INVALID_CONFIG', message: error };
42
59
  const exported = await exportForCommit(required);
43
60
  if (!exported.ok)
44
61
  return exported;
45
- return { ok: true, fileCount: exported.files.length, totalBytes: exported.files.reduce((sum, file) => sum + Buffer.byteLength(file.data), 0), paths: exported.files.map(file => file.path).sort().slice(0, 50) };
62
+ return { ok: true, fileCount: exported.files.length, totalBytes: exported.files.reduce((sum, file) => sum + Buffer.byteLength(file.data), 0), paths: exported.files.map(file => prefixRepositoryPath({ folder: required.folder, path: file.path })).sort().slice(0, 50) };
46
63
  }
47
64
  const PROVIDER_FAILURE_CODES = { 'repository-not-found': 'REPOSITORY_NOT_FOUND', 'no-changes': 'NO_CHANGES', diverged: 'DIVERGED_BRANCH', 'network-unreachable': 'NETWORK_UNREACHABLE', 'provider-error': 'PROVIDER_ERROR' };
48
65
  /** The credential must exist and belong to the requested provider; failures never reveal the token. */
@@ -64,7 +81,8 @@ async function resolveProviderCredential(required) {
64
81
  async function commitExportedFiles(required, optional) {
65
82
  const { args, token, files } = required;
66
83
  try {
67
- const result = await args.adapter.commitSite({ token, owner: args.owner, repo: args.repo, commitMessage: args.commitMessage, files }, optional.branch !== undefined ? { branch: optional.branch } : {});
84
+ const folder = normalizeRepositoryFolder(args);
85
+ const result = await args.adapter.commitSite({ token, owner: args.owner, repo: args.repo, commitMessage: args.commitMessage, files, ...(folder ? { folder } : {}) }, optional.branch !== undefined ? { branch: optional.branch } : {});
68
86
  if (!result.ok)
69
87
  return { ok: false, code: PROVIDER_FAILURE_CODES[result.code], message: result.message };
70
88
  return { ...result, owner: args.owner, repo: args.repo, divergedPaths: result.divergedPaths ?? [] };
@@ -75,7 +93,7 @@ async function commitExportedFiles(required, optional) {
75
93
  }
76
94
  /** Resolve one provider's credential, export into an isolated host-owned directory and commit once. */
77
95
  export async function commitSiteToSourceControl(required, optional = {}) {
78
- const configError = validateCommitTarget(required, optional);
96
+ const configError = validateCommitTarget(required, optional) ?? folderError(required, { committing: true });
79
97
  if (configError)
80
98
  return { ok: false, code: 'INVALID_CONFIG', message: configError };
81
99
  const resolved = await resolveProviderCredential(required);
@@ -1,6 +1,6 @@
1
1
  import type { HttpClientPort } from '@jini-ai/core/primitives';
2
2
  import type { ExportReport } from '../static-export/contracts.js';
3
- /** Repository-relative bytes, passed unchanged to the provider. */
3
+ /** Folder-relative bytes; the provider applies the destination prefix once. */
4
4
  export interface CommitFile {
5
5
  readonly path: string;
6
6
  readonly data: string | Buffer;
@@ -23,6 +23,7 @@ export interface CommitSiteInput {
23
23
  readonly token: string;
24
24
  readonly owner: string;
25
25
  readonly repo: string;
26
+ readonly folder?: string;
26
27
  readonly commitMessage: string;
27
28
  readonly files: readonly CommitFile[];
28
29
  }
@@ -152,6 +153,7 @@ export interface RepositoryTarget {
152
153
  }
153
154
  export type RepositoryTargetValidator = (required: RepositoryTarget) => string | null;
154
155
  export type SourceControlProvider = SourceControlProviderOperations & SourceControlHostFacts & {
156
+ readonly supportsFolder?: boolean;
155
157
  readonly validateTarget?: RepositoryTargetValidator;
156
158
  };
157
159
  export interface DescribedTransportError {
@@ -167,6 +169,11 @@ export type SourceControlFetchPort = (required: {
167
169
  init?: RequestInit;
168
170
  }) => Promise<Response>;
169
171
  export interface SourceControlProviderKit {
172
+ readonly repositoryPaths: {
173
+ normalizeFolder: typeof import('./repository-path.js').normalizeRepositoryFolder;
174
+ prefixPath: typeof import('./repository-path.js').prefixRepositoryPath;
175
+ contains: typeof import('./repository-path.js').repositoryPathContained;
176
+ };
170
177
  fetch(required: {
171
178
  url: string;
172
179
  init: RequestInit;
@@ -191,6 +198,7 @@ export interface SourceControlProviderModule {
191
198
  kit: SourceControlProviderKit;
192
199
  }): SourceControlProviderOperations;
193
200
  validateTarget?: RepositoryTargetValidator;
201
+ readonly supportsFolder?: boolean;
194
202
  }
195
203
  export interface SourceControlProviderDescriptor extends SourceControlHostFacts {
196
204
  readonly module: string;
@@ -274,6 +282,7 @@ export interface CommitLayoutPort {
274
282
  }): Promise<void>;
275
283
  }
276
284
  export interface CommitExportArgs {
285
+ folder?: string;
277
286
  workspaceId: string;
278
287
  owner: string;
279
288
  repo: string;
@@ -290,6 +299,7 @@ export interface CommitExportArgs {
290
299
  }): string;
291
300
  }
292
301
  export interface CommitOrchestrationArgs extends CommitExportArgs {
302
+ supportsFolder?: boolean;
293
303
  credentials: CredentialResolverPort;
294
304
  adapter: Pick<SourceControlProviderOperations, 'commitSite'>;
295
305
  }
@@ -3,4 +3,5 @@ export * from './repository-target.js';
3
3
  export * from './kit.js';
4
4
  export * from './registry.js';
5
5
  export * from './commit.js';
6
+ export * from './repository-path.js';
6
7
  //# sourceMappingURL=entry.d.ts.map
@@ -3,4 +3,5 @@ export * from './repository-target.js';
3
3
  export * from './kit.js';
4
4
  export * from './registry.js';
5
5
  export * from './commit.js';
6
+ export * from './repository-path.js';
6
7
  //# sourceMappingURL=entry.js.map
@@ -1,8 +1,10 @@
1
1
  import { assertNotRedirected, redirectGuardInit } from '../core/redirect-guard.js';
2
2
  import { DeployError } from '../core/deploy-types.js';
3
+ import { normalizeRepositoryFolder, prefixRepositoryPath, repositoryPathContained } from './repository-path.js';
3
4
  /** Build a kit without globals or a silently missing guarded HTTP client. */
4
5
  export function createSourceControlProviderKit(required, optional = {}) {
5
6
  return {
7
+ repositoryPaths: { normalizeFolder: normalizeRepositoryFolder, prefixPath: prefixRepositoryPath, contains: repositoryPathContained },
6
8
  fetch: ({ url, init }) => required.fetch({ url }, { init: optional.fetchRedirectPolicy === "caller" ? init : redirectGuardInit({ init }) }),
7
9
  redirectGuardInit: ({ init }) => redirectGuardInit({ init }),
8
10
  assertNotRedirected: ({ response, hostName }) => assertNotRedirected({ resp: response, providerLabel: hostName }),
@@ -40,6 +40,7 @@ export interface SharedLoadedProvider<Kit, Operations> {
40
40
  create(required: {
41
41
  kit: Kit;
42
42
  }): Operations;
43
+ supportsFolder?: boolean;
43
44
  validateTarget?: (required: {
44
45
  owner: string;
45
46
  repo: string;
@@ -50,6 +51,7 @@ export declare function buildLoadedSourceControlProvider<Kit, Operations>(requir
50
51
  loaded: SharedLoadedProvider<Kit, Operations>;
51
52
  kit: Kit;
52
53
  }, _optional?: {}): Operations & import('./contracts.js').SourceControlHostFacts & {
54
+ supportsFolder: boolean;
53
55
  validateTarget?: (required: {
54
56
  owner: string;
55
57
  repo: string;
@@ -108,6 +110,7 @@ export declare function buildSourceControlProvider<Kit = SourceControlProviderKi
108
110
  } | {
109
111
  ok: true;
110
112
  provider: Operations & import("./contracts.js").SourceControlHostFacts & {
113
+ supportsFolder: boolean;
111
114
  validateTarget?: (required: {
112
115
  owner: string;
113
116
  repo: string;
@@ -129,6 +132,7 @@ export interface BuildProvidersArgs {
129
132
  /** Build every enabled provider over the same guarded kit, in catalog order. */
130
133
  export declare function buildSourceControlProviders<Kit = SourceControlProviderKit, Operations = SourceControlProviderOperations, Registry extends SharedProviderRegistry<Kit, Operations> = SharedProviderRegistry<Kit, Operations>>(required: SharedBuildProviderArgs<Kit, Operations, Registry>, _optional?: {}): Promise<{
131
134
  providers: (Operations & import("./contracts.js").SourceControlHostFacts & {
135
+ supportsFolder: boolean;
132
136
  validateTarget?: (required: {
133
137
  owner: string;
134
138
  repo: string;
@@ -148,6 +152,7 @@ export declare function buildSourceControlProviderForApi<Kit = SourceControlProv
148
152
  }): Promise<{
149
153
  ok: true;
150
154
  provider: Operations & import("./contracts.js").SourceControlHostFacts & {
155
+ supportsFolder: boolean;
151
156
  validateTarget?: (required: {
152
157
  owner: string;
153
158
  repo: string;
@@ -1,7 +1,8 @@
1
+ import { repositoryPathContained } from './repository-path.js';
1
2
  function object(value) { return value !== null && typeof value === 'object' && !Array.isArray(value); }
2
3
  /** Shared relative-path rule: no backslash, colon or control character; no empty, `.` or `..` segment. */
3
4
  function safeRelativePath(value) {
4
- return !/[\\\x00-\x1f\x7f:]/.test(value) && value.split('/').every(segment => segment !== '' && segment !== '.' && segment !== '..');
5
+ return repositoryPathContained({ path: value });
5
6
  }
6
7
  /** True for `https://host[:port]` exactly — what `new URL(x).origin` gives back. @complexity O(1). */
7
8
  function httpsOrigin(value) {
@@ -92,6 +93,8 @@ export function sourceControlProviderModuleError({ value }, _optional = {}) {
92
93
  return 'its module has no create() function';
93
94
  if (value.validateTarget !== undefined && typeof value.validateTarget !== 'function')
94
95
  return "its module's validateTarget is not a function";
96
+ if (value.supportsFolder !== undefined && typeof value.supportsFolder !== 'boolean')
97
+ return "its module's supportsFolder is not a boolean";
95
98
  return null;
96
99
  }
97
100
  function byPluginId(a, b) {
@@ -157,7 +160,7 @@ export async function loadSourceControlProviderRegistry(required) {
157
160
  export function buildLoadedSourceControlProvider(required, _optional = {}) {
158
161
  const { loaded, kit } = required;
159
162
  const { id, label, apiOrigin, maxFileBytes, reservedPaths, workflowPaths } = loaded.descriptor;
160
- return { ...loaded.module.create({ kit }), ...(loaded.module.validateTarget ? { validateTarget: loaded.module.validateTarget } : {}), id, label, apiOrigin,
163
+ return { ...loaded.module.create({ kit }), supportsFolder: loaded.module.supportsFolder === true, ...(loaded.module.validateTarget ? { validateTarget: loaded.module.validateTarget } : {}), id, label, apiOrigin,
161
164
  ...(maxFileBytes !== undefined ? { maxFileBytes } : {}), ...(reservedPaths !== undefined ? { reservedPaths } : {}), ...(workflowPaths !== undefined ? { workflowPaths } : {}) };
162
165
  }
163
166
  /** Operator navigation/copy is supplied by the host, with no descriptor or product defaults. */
@@ -0,0 +1,28 @@
1
+ /** Invalid repository destinations fail before any provider I/O. */
2
+ export declare class RepositoryPathError extends Error {
3
+ }
4
+ /**
5
+ * Normalize a repository-relative folder, preserving root only when explicitly empty or omitted.
6
+ * @throws RepositoryPathError for malformed values, absolute paths, controls or traversal.
7
+ * @complexity O(folder length), no effects.
8
+ */
9
+ export declare function normalizeRepositoryFolder({ folder }: {
10
+ folder?: unknown;
11
+ }, _options?: {}): string;
12
+ /** Prefix one folder-relative file exactly once; rejects unsafe file paths before returning it.
13
+ * @throws RepositoryPathError for invalid folders or noncanonical file paths.
14
+ * @complexity O(folder + path length), no effects.
15
+ */
16
+ export declare function prefixRepositoryPath({ folder, path }: {
17
+ folder?: string | undefined;
18
+ path: string;
19
+ }, _options?: {}): string;
20
+ /** Exact directory-boundary containment for untrusted persisted repository paths.
21
+ * @returns False for malformed or noncanonical paths, including sibling prefix collisions.
22
+ * @complexity O(folder + path length), no effects.
23
+ */
24
+ export declare function repositoryPathContained({ folder, path }: {
25
+ folder?: string | undefined;
26
+ path: string;
27
+ }, _options?: {}): boolean;
28
+ //# sourceMappingURL=repository-path.d.ts.map
@@ -0,0 +1,52 @@
1
+ /** Invalid repository destinations fail before any provider I/O. */
2
+ export class RepositoryPathError extends Error {
3
+ }
4
+ /**
5
+ * Normalize a repository-relative folder, preserving root only when explicitly empty or omitted.
6
+ * @throws RepositoryPathError for malformed values, absolute paths, controls or traversal.
7
+ * @complexity O(folder length), no effects.
8
+ */
9
+ export function normalizeRepositoryFolder({ folder = '' }, _options = {}) {
10
+ if (typeof folder !== 'string')
11
+ throw new RepositoryPathError('Target folder must be a string.');
12
+ const value = folder.replaceAll('\\', '/');
13
+ if (value.startsWith('/') || /[:\x00-\x1f\x7f]/.test(value))
14
+ throw new RepositoryPathError('Target folder must be relative and contain no controls or drive prefix.');
15
+ const segments = value.split('/');
16
+ if (segments.some(segment => segment === '.' || segment === '..'))
17
+ throw new RepositoryPathError('Target folder cannot contain . or .. segments.');
18
+ return segments.filter(Boolean).join('/');
19
+ }
20
+ /** Canonical file paths cannot normalize into a different path or into repository root. */
21
+ function canonicalFilePath({ path }, _options = {}) {
22
+ try {
23
+ return path !== '' && normalizeRepositoryFolder({ folder: path }) === path;
24
+ }
25
+ catch {
26
+ return false;
27
+ }
28
+ }
29
+ /** Prefix one folder-relative file exactly once; rejects unsafe file paths before returning it.
30
+ * @throws RepositoryPathError for invalid folders or noncanonical file paths.
31
+ * @complexity O(folder + path length), no effects.
32
+ */
33
+ export function prefixRepositoryPath({ folder, path }, _options = {}) {
34
+ const normalized = normalizeRepositoryFolder({ folder });
35
+ if (!canonicalFilePath({ path }))
36
+ throw new RepositoryPathError('Repository file path must be a canonical relative path.');
37
+ return normalized ? `${normalized}/${path}` : path;
38
+ }
39
+ /** Exact directory-boundary containment for untrusted persisted repository paths.
40
+ * @returns False for malformed or noncanonical paths, including sibling prefix collisions.
41
+ * @complexity O(folder + path length), no effects.
42
+ */
43
+ export function repositoryPathContained({ folder, path }, _options = {}) {
44
+ try {
45
+ const normalized = normalizeRepositoryFolder({ folder });
46
+ return canonicalFilePath({ path }) && (normalized === '' || path.startsWith(`${normalized}/`));
47
+ }
48
+ catch {
49
+ return false;
50
+ }
51
+ }
52
+ //# sourceMappingURL=repository-path.js.map
@@ -3,13 +3,14 @@ export interface HtmlUrlLocation {
3
3
  end: number;
4
4
  kind: 'url' | 'srcset' | 'css' | 'action';
5
5
  attribute?: string;
6
+ identity?: boolean;
6
7
  }
7
8
  /** Source ranges from the workspace's HTML parser; no serialization can alter article content.
8
9
  * @complexity O(n + a log a) in HTML bytes and source attributes; iterative traversal avoids recursion limits. */
9
10
  export declare function htmlUrlLocations({ html }: {
10
11
  html: string;
11
12
  }, _optional?: {}): HtmlUrlLocation[];
12
- /** CSS, sitemap and manifest positions use their response format, never an HTML text scan. */
13
+ /** CSS, Markdown indexes, sitemap and manifest positions use their response format, never an HTML text scan. */
13
14
  export declare function exportUrlLocations({ body, contentType }: {
14
15
  body: string;
15
16
  contentType: string;
@@ -42,6 +42,14 @@ function styleLocations({ element }, _optional = {}) {
42
42
  return element.childNodes.flatMap(child => child.sourceCodeLocation
43
43
  ? [{ start: child.sourceCodeLocation.startOffset, end: child.sourceCodeLocation.endOffset, kind: 'css' }] : []);
44
44
  }
45
+ /** Canonical identity and feed discovery must remain absolute when a download relocates files. */
46
+ function isIdentityLink({ element }, _optional = {}) {
47
+ if (element.tagName !== 'link')
48
+ return false;
49
+ const rel = element.attrs.find(attr => attr.name === 'rel')?.value.toLowerCase().split(/\s+/) ?? [];
50
+ const type = element.attrs.find(attr => attr.name === 'type')?.value.toLowerCase();
51
+ return rel.includes('canonical') || (rel.includes('alternate') && (type === 'application/rss+xml' || type === 'application/atom+xml'));
52
+ }
45
53
  /** Collect one element's real URL/style positions, excluding lookalike strings in text and scripts. */
46
54
  function elementLocations({ element, html }, _optional = {}) {
47
55
  const locations = [];
@@ -52,7 +60,7 @@ function elementLocations({ element, html }, _optional = {}) {
52
60
  continue;
53
61
  const location = attributeLocation({ html, start: source.startOffset, end: source.endOffset, kind });
54
62
  if (location)
55
- locations.push({ ...location, attribute: attr.name });
63
+ locations.push({ ...location, attribute: attr.name, ...(isIdentityLink({ element }) ? { identity: true } : {}) });
56
64
  }
57
65
  locations.push(...styleLocations({ element }));
58
66
  return locations;
@@ -74,12 +82,23 @@ export function htmlUrlLocations({ html }, _optional = {}) {
74
82
  }
75
83
  return locations.sort((a, b) => a.start - b.start);
76
84
  }
77
- /** CSS, sitemap and manifest positions use their response format, never an HTML text scan. */
85
+ /** Generated llms indexes use one Markdown list link per line; prose stays untouched.
86
+ * @complexity O(body bytes), returning destination ranges only; no effects.
87
+ */
88
+ function markdownLinkLocations({ body }, _optional = {}) {
89
+ return [...body.matchAll(/^- \[[^\r\n]*\]\(([^)\r\n]*)\)/gm)].map(match => ({
90
+ start: match.index + match[0].length - match[1].length - 1,
91
+ end: match.index + match[0].length - 1, kind: 'url',
92
+ }));
93
+ }
94
+ /** CSS, Markdown indexes, sitemap and manifest positions use their response format, never an HTML text scan. */
78
95
  export function exportUrlLocations({ body, contentType }, _optional = {}) {
79
96
  if (/^text\/html\b/i.test(contentType))
80
97
  return htmlUrlLocations({ html: body });
81
98
  if (/^text\/css\b/i.test(contentType))
82
99
  return cssUrlTokens(body).map(({ start, end }) => ({ start, end, kind: 'css' }));
100
+ if (/^text\/markdown\b/i.test(contentType))
101
+ return markdownLinkLocations({ body });
83
102
  if (/\bxml\b/i.test(contentType))
84
103
  return [...body.matchAll(/<((?:[\w-]+:)?loc)>([^<]*)<\/\1>/g)].map(match => ({ start: match.index + match[1].length + 2, end: match.index + match[0].length - match[1].length - 3, kind: 'url' }));
85
104
  if (!/\bjson\b/i.test(contentType))
@@ -143,7 +143,8 @@ function assetFailureReason(required) {
143
143
  const { ctx, url, error } = required;
144
144
  return error instanceof ExportPathError && ctx.args.assetPathFailureReason !== undefined ? ctx.args.assetPathFailureReason : failureReason(ctx, url, error);
145
145
  }
146
- /** Fetches one asset; a crawled stylesheet's children join the queue without further crawling. */
146
+ /** Fetch one asset and queue its children, returning its physical output claim on success.
147
+ * Failed variants leave the destination available for another URL's retry. */
147
148
  async function fetchAndQueueAsset({ ctx, url, crawlCss, queue }, out) {
148
149
  const outcome = await fetchAsset({ ctx, url, crawlCss });
149
150
  if ('reason' in outcome) {
@@ -153,10 +154,11 @@ async function fetchAndQueueAsset({ ctx, url, crawlCss, queue }, out) {
153
154
  out.succeeded.push(outcome.asset);
154
155
  for (const child of outcome.children)
155
156
  queue.push({ url: child, crawlCss: false });
157
+ return outcome.asset.outputFile;
156
158
  }
157
159
  async function writeAssets(ctx, initial) {
158
160
  const succeeded = [], failed = [];
159
- const seen = new Set();
161
+ const seen = new Set(), written = new Set();
160
162
  const queue = initial.map(url => ({ url, crawlCss: true }));
161
163
  for (let index = 0; index < queue.length; index++) {
162
164
  const { url, crawlCss } = queue[index];
@@ -164,7 +166,12 @@ async function writeAssets(ctx, initial) {
164
166
  continue;
165
167
  seen.add(url);
166
168
  try {
167
- await fetchAndQueueAsset({ ctx, url, crawlCss, queue }, { succeeded, failed });
169
+ // Query/cache variants share one static filename; report exactly the file the writer owns.
170
+ if (written.has(outputFileForUrl({ url })))
171
+ continue;
172
+ const outputFile = await fetchAndQueueAsset({ ctx, url, crawlCss, queue }, { succeeded, failed });
173
+ if (outputFile !== undefined)
174
+ written.add(outputFile);
168
175
  }
169
176
  catch (error) {
170
177
  failed.push({ url, reason: assetFailureReason({ ctx, url, error }) });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jini-ai/devops",
3
- "version": "0.6.15",
3
+ "version": "0.6.17",
4
4
  "description": "DevOps capabilities for deployment, source control, and CI/CD, exposed through independent subpaths.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -35,6 +35,12 @@
35
35
  "shared": [
36
36
  "src/core/export-failure-summary.ts"
37
37
  ]
38
+ },
39
+ "optionalPeers": {
40
+ "parse5": "opt-in: html parsing; import @jini-ai/devops/static-export — HTML parsing could not load parse5. Install parse5 to enable this feature, or check its installed version and native binaries.",
41
+ "typescript": "opt-in: typescript source analysis — TypeScript source analysis could not load typescript. Install typescript to enable this feature, or check its installed version and native binaries.",
42
+ "@jini-ai/platform": "opt-in: platform-backed adapters; import @jini-ai/devops/deploy/node — Platform-backed adapters could not load @jini-ai/platform. Install @jini-ai/platform to enable this feature, or check its installed version and native binaries.",
43
+ "undici": "opt-in: custom http dispatchers; import @jini-ai/devops/deploy/node — Custom HTTP dispatchers could not load undici. Install undici to enable this feature, or check its installed version and native binaries."
38
44
  }
39
45
  },
40
46
  "type": "module",
@@ -148,12 +154,12 @@
148
154
  "@vitest/coverage-v8": "^2.1.9",
149
155
  "undici": "^7.25.0",
150
156
  "parse5": "7.3.0",
151
- "@jini-ai/daemon": "0.6.15",
152
- "@jini-ai/core": "^0.6.15",
153
- "@jini-ai/platform": "^0.6.15"
157
+ "@jini-ai/core": "^0.6.17",
158
+ "@jini-ai/platform": "^0.6.17",
159
+ "@jini-ai/daemon": "0.6.17"
154
160
  },
155
161
  "dependencies": {
156
- "@jini-ai/core": "^0.6.15"
162
+ "@jini-ai/core": "^0.6.17"
157
163
  },
158
164
  "peerDependencies": {
159
165
  "typescript": "^5.6.0",