@jini-ai/devops 0.5.4 → 0.5.6

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 (62) hide show
  1. package/CHANGELOG.md +10 -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 +33 -26
  52. package/dist/packaging/electron/imports.d.ts +2 -2
  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/contracts.d.ts +9 -0
  58. package/dist/static-export/node-adapters.js +26 -17
  59. package/dist/static-export/runner.js +202 -65
  60. package/dist/static-export/transforms.d.ts +8 -1
  61. package/dist/static-export/transforms.js +44 -23
  62. package/package.json +23 -6
@@ -5,6 +5,24 @@ import { createServer } from 'node:http';
5
5
  import path from 'node:path';
6
6
  import { ExportPathError } from './contracts.js';
7
7
  import { safeRelativeOutputFile } from './transforms.js';
8
+ /** Create one directory level; an existing entry is left for the caller's lstat check. */
9
+ async function makeDirectory(directory) {
10
+ try {
11
+ await mkdir(directory);
12
+ }
13
+ catch (error) {
14
+ if (error.code !== 'EEXIST')
15
+ throw error;
16
+ }
17
+ }
18
+ /** True only for macOS's own /tmp or /var symlink into /private. */
19
+ async function isSystemTempAlias(current, info) {
20
+ // macOS exposes its system temporary roots through these fixed OS aliases. Arbitrary
21
+ // symlinks still fail closed; rejecting /var would reject Node's own tmpdir() output.
22
+ if (process.platform !== 'darwin' || (current !== '/tmp' && current !== '/var') || !info.isSymbolicLink())
23
+ return false;
24
+ return await realpath(current) === '/private' + current;
25
+ }
8
26
  /** Require regular directories at every ancestor. Hosts must use canonical absolute storage paths.
9
27
  * The storage hierarchy must be caller-owned; cross-process hostile ancestor swaps require host isolation.
10
28
  */
@@ -12,25 +30,16 @@ async function ensureDirectory({ directory, label }, optional = {}) {
12
30
  if (!path.isAbsolute(directory))
13
31
  throw new ExportPathError(`${label} path must be absolute.`);
14
32
  const resolved = path.resolve(directory);
15
- const segments = resolved.slice(path.parse(resolved).root.length).split(path.sep).filter(Boolean);
16
- let current = path.parse(resolved).root;
17
- for (const segment of segments) {
33
+ const { root } = path.parse(resolved);
34
+ let current = root;
35
+ for (const segment of resolved.slice(root.length).split(path.sep).filter(Boolean)) {
18
36
  current = path.join(current, segment);
19
- if (optional.create) {
20
- try {
21
- await mkdir(current);
22
- }
23
- catch (error) {
24
- if (error.code !== 'EEXIST')
25
- throw error;
26
- }
27
- }
37
+ if (optional.create)
38
+ await makeDirectory(current);
28
39
  const info = await lstat(current);
29
- // macOS exposes its system temporary roots through these fixed OS aliases. Arbitrary
30
- // symlinks still fail closed; rejecting /var would reject Node's own tmpdir() output.
31
- const systemAlias = process.platform === 'darwin' && (current === '/tmp' || current === '/var')
32
- && info.isSymbolicLink() && await realpath(current) === '/private' + current;
33
- if (!systemAlias && (!info.isDirectory() || info.isSymbolicLink()))
40
+ if (await isSystemTempAlias(current, info))
41
+ continue;
42
+ if (!info.isDirectory() || info.isSymbolicLink())
34
43
  throw new ExportPathError(`${label} path must be a regular directory.`);
35
44
  }
36
45
  }
@@ -1,5 +1,5 @@
1
1
  import { ExportPathError } from "./contracts.js";
2
- import { extractAssetUrls, extractCssUrls, normalizeBasePath, outputFileForUrl, redirectOutcomeFor, renderRedirectStub, rewriteRouteBodyForBasePath, safeRelativeOutputFile } from './transforms.js';
2
+ import { extractAssetUrls, extractHtmlReferences, extractCssUrls, normalizeBasePath, outputFileForUrl, redirectOutcomeFor, renderRedirectStub, rewriteRouteBodyForBasePath, safeRelativeOutputFile } from './transforms.js';
3
3
  const BASE_PATH_REWRITE_WARNING = "base-path rewriting is a best-effort TEXT rewrite over already-rendered responses — it cannot rewrite a path a theme's own JavaScript constructs at runtime from a string (same category of gap as the unreferenced-theme-file warning, just invisible to this rewrite instead of to the asset crawl).";
4
4
  async function request(ctx, url) {
5
5
  // Redirects are observed, never followed off the caller's app, for routes and assets alike.
@@ -10,46 +10,75 @@ function failureReason(ctx, url, error) {
10
10
  return `GET ${ctx.baseUrl}${url} timed out after ${ctx.timeoutMs}ms`;
11
11
  return `GET ${ctx.baseUrl}${url} failed: ${ctx.args.describeError({ error })}`;
12
12
  }
13
+ async function redirectBody(required) {
14
+ const { ctx, route, response } = required;
15
+ const decision = redirectOutcomeFor({ status: response.status, locationHeader: response.headers.get('location') }, route.redirectTarget !== undefined ? { manifestTarget: route.redirectTarget } : {});
16
+ if (decision.kind === 'failed')
17
+ return { reason: decision.reason };
18
+ const body = ctx.args.security.transformHtml({ html: renderRedirectStub({ location: decision.location }, { basePath: ctx.basePath }) });
19
+ await response.body?.cancel();
20
+ return { body, contentType: 'text/html; charset=utf-8' };
21
+ }
22
+ /** The error-page probe accepts what the host's policy accepts; every other content route needs a 200. */
23
+ function statusAccepted(required) {
24
+ const { ctx, route, status } = required;
25
+ return route.kind === 'not-found' ? ctx.args.errorPage.acceptStatus({ status }) : status === 200;
26
+ }
27
+ function statusRejection(required) {
28
+ const { ctx, route, status } = required;
29
+ if (route.kind !== 'not-found')
30
+ return `expected 200, got ${status}`;
31
+ return ctx.args.errorPage.rejectionReason?.({ status }) ?? `expected an accepted response for the error-page probe, got ${status}`;
32
+ }
33
+ async function contentBody(required) {
34
+ const { ctx, route, response } = required;
35
+ const contentType = response.headers.get('content-type');
36
+ if (!statusAccepted({ ctx, route, status: response.status })) {
37
+ await response.body?.cancel();
38
+ return { reason: statusRejection({ ctx, route, status: response.status }) };
39
+ }
40
+ const rawBody = await response.text();
41
+ let body = rewriteRouteBodyForBasePath({ path: route.path, body: rawBody, basePath: ctx.basePath });
42
+ if (route.kind === 'not-found' || /^text\/html\b/i.test(contentType ?? ''))
43
+ body = ctx.args.security.transformHtml({ html: body });
44
+ // The error page is written but never crawled for assets or further routes.
45
+ return { body, contentType, ...(route.kind !== 'not-found' ? { crawlHtml: rawBody } : {}) };
46
+ }
13
47
  async function writeRoute(ctx, route) {
14
48
  // Validate the request path even when the error-page policy supplies a different artifact path.
15
49
  const regularOutput = outputFileForUrl({ url: route.path }, { contentRoute: route.kind !== 'well-known' });
16
50
  const outputFile = route.kind === 'not-found' ? safeRelativeOutputFile({ value: ctx.args.errorPage.outputFile }) : regularOutput;
17
51
  const response = await request(ctx, route.path);
18
- let body;
19
- let rawBody;
20
- let contentType = response.headers.get('content-type');
21
- if (route.kind === 'redirect') {
22
- const decision = redirectOutcomeFor({ status: response.status, locationHeader: response.headers.get('location') }, { ...(route.redirectTarget !== undefined ? { manifestTarget: route.redirectTarget } : {}) });
23
- if (decision.kind === 'failed')
24
- return { reason: decision.reason };
25
- body = ctx.args.security.transformHtml({ html: renderRedirectStub({ location: decision.location }, { basePath: ctx.basePath }) });
26
- contentType = 'text/html; charset=utf-8';
27
- await response.body?.cancel();
28
- }
29
- else {
30
- if (route.kind === 'not-found' ? !ctx.args.errorPage.acceptStatus({ status: response.status }) : response.status !== 200) {
31
- await response.body?.cancel();
32
- return { reason: route.kind === 'not-found' ? (ctx.args.errorPage.rejectionReason?.({ status: response.status }) ?? `expected an accepted response for the error-page probe, got ${response.status}`) : `expected 200, got ${response.status}` };
33
- }
34
- rawBody = await response.text();
35
- body = rewriteRouteBodyForBasePath({ path: route.path, body: rawBody, basePath: ctx.basePath });
36
- if (route.kind === 'not-found' || /^text\/html\b/i.test(contentType ?? ''))
37
- body = ctx.args.security.transformHtml({ html: body });
38
- }
39
- await ctx.args.writer.write({ outputDir: ctx.args.outputDir, outputFile, data: body });
40
- return { route: { path: route.path, kind: route.kind, outputFile, data: body, contentType }, ...(rawBody !== undefined && route.kind !== 'not-found' ? { crawlHtml: rawBody } : {}) };
52
+ const outcome = route.kind === 'redirect' ? await redirectBody({ ctx, route, response }) : await contentBody({ ctx, route, response });
53
+ if ('reason' in outcome)
54
+ return outcome;
55
+ await ctx.args.writer.write({ outputDir: ctx.args.outputDir, outputFile, data: outcome.body });
56
+ return { route: { path: route.path, kind: route.kind, outputFile, data: outcome.body, contentType: outcome.contentType }, ...(outcome.crawlHtml !== undefined ? { crawlHtml: outcome.crawlHtml } : {}) };
41
57
  }
42
58
  /** Most routes `discoverRoutes` may add to one export; the rest are reported as skipped. */
43
59
  const MAX_DISCOVERED_ROUTES = 2000;
60
+ /** Append newly discovered routes once each, up to the cap; the rest are reported as skipped. */
61
+ function enqueueDiscovered(required) {
62
+ const { state } = required;
63
+ for (const next of required.routes) {
64
+ if (state.queued.has(next.path))
65
+ continue;
66
+ state.queued.add(next.path);
67
+ if (state.discovered >= MAX_DISCOVERED_ROUTES) {
68
+ state.skipped.push({ reason: 'discovered-route-cap', detail: `${next.path} (over ${MAX_DISCOVERED_ROUTES} discovered routes)` });
69
+ continue;
70
+ }
71
+ state.discovered += 1;
72
+ state.queue.push(next);
73
+ }
74
+ }
44
75
  async function writeRoutes(ctx, routes) {
45
- const succeeded = [], failed = [], skipped = [];
76
+ const succeeded = [], failed = [];
46
77
  const assets = new Set();
47
78
  // A queue, not a loop over the manifest: discovered routes are appended and scanned in turn.
48
- const queue = [...routes];
49
- const queued = new Set(routes.map(route => route.path));
50
- let discovered = 0;
51
- for (let index = 0; index < queue.length; index++) {
52
- const route = queue[index];
79
+ const state = { queue: [...routes], queued: new Set(routes.map(route => route.path)), discovered: 0, skipped: [] };
80
+ for (let index = 0; index < state.queue.length; index++) {
81
+ const route = state.queue[index];
53
82
  try {
54
83
  const outcome = await writeRoute(ctx, route);
55
84
  if ('reason' in outcome) {
@@ -57,27 +86,42 @@ async function writeRoutes(ctx, routes) {
57
86
  continue;
58
87
  }
59
88
  succeeded.push(outcome.route);
60
- if (outcome.crawlHtml === undefined)
89
+ const html = outcome.crawlHtml;
90
+ if (html === undefined)
61
91
  continue;
62
- for (const url of extractAssetUrls({ html: outcome.crawlHtml, prefixes: ctx.args.assetUrlPrefixes }))
92
+ for (const url of extractAssetUrls({ html, prefixes: ctx.args.assetUrlPrefixes }))
63
93
  assets.add(url);
64
- for (const next of ctx.args.discoverRoutes?.({ path: route.path, html: outcome.crawlHtml }) ?? []) {
65
- if (queued.has(next.path))
66
- continue;
67
- queued.add(next.path);
68
- if (discovered >= MAX_DISCOVERED_ROUTES) {
69
- skipped.push({ reason: 'discovered-route-cap', detail: `${next.path} (over ${MAX_DISCOVERED_ROUTES} discovered routes)` });
70
- continue;
71
- }
72
- discovered += 1;
73
- queue.push(next);
74
- }
94
+ enqueueDiscovered({ state, routes: ctx.args.discoverRoutes?.({ path: route.path, html }) ?? [] });
75
95
  }
76
96
  catch (error) {
77
97
  failed.push({ path: route.path, kind: route.kind, reason: failureReason(ctx, route.path, error) });
78
98
  }
79
99
  }
80
- return { succeeded, failed, assets, skipped };
100
+ return { succeeded, failed, assets, skipped: state.skipped };
101
+ }
102
+ async function fetchAsset(required) {
103
+ const { ctx, url } = required;
104
+ const outputFile = outputFileForUrl({ url });
105
+ const response = await request(ctx, url);
106
+ if (!response.ok) {
107
+ await response.body?.cancel();
108
+ return { reason: `GET ${url} -> ${response.status}` };
109
+ }
110
+ const data = Buffer.from(await response.arrayBuffer());
111
+ const contentType = response.headers.get('content-type');
112
+ await ctx.args.writer.write({ outputDir: ctx.args.outputDir, outputFile, data });
113
+ return { url, outputFile, data, contentType };
114
+ }
115
+ /** Only a stylesheet reached from HTML is scanned: one CSS hop, never recursive. */
116
+ function stylesheetChildren(required) {
117
+ const { ctx, asset } = required;
118
+ if (!required.crawlCss || !asset.url.split('?')[0].endsWith('.css'))
119
+ return [];
120
+ return extractCssUrls({ css: asset.data.toString('utf8'), cssUrl: asset.url, prefixes: ctx.args.assetUrlPrefixes });
121
+ }
122
+ function assetFailureReason(required) {
123
+ const { ctx, url, error } = required;
124
+ return error instanceof ExportPathError && ctx.args.assetPathFailureReason !== undefined ? ctx.args.assetPathFailureReason : failureReason(ctx, url, error);
81
125
  }
82
126
  async function writeAssets(ctx, initial) {
83
127
  const succeeded = [], failed = [];
@@ -89,24 +133,17 @@ async function writeAssets(ctx, initial) {
89
133
  continue;
90
134
  seen.add(url);
91
135
  try {
92
- const outputFile = outputFileForUrl({ url });
93
- const response = await request(ctx, url);
94
- if (!response.ok) {
95
- await response.body?.cancel();
96
- failed.push({ url, reason: `GET ${url} -> ${response.status}` });
136
+ const outcome = await fetchAsset({ ctx, url });
137
+ if ('reason' in outcome) {
138
+ failed.push({ url, reason: outcome.reason });
97
139
  continue;
98
140
  }
99
- const data = Buffer.from(await response.arrayBuffer());
100
- const contentType = response.headers.get('content-type');
101
- await ctx.args.writer.write({ outputDir: ctx.args.outputDir, outputFile, data });
102
- succeeded.push({ url, outputFile, data, contentType });
103
- if (crawlCss && url.split('?')[0].endsWith('.css')) {
104
- for (const child of extractCssUrls({ css: data.toString('utf8'), cssUrl: url, prefixes: ctx.args.assetUrlPrefixes }))
105
- queue.push({ url: child, crawlCss: false });
106
- }
141
+ succeeded.push(outcome);
142
+ for (const child of stylesheetChildren({ ctx, asset: outcome, crawlCss }))
143
+ queue.push({ url: child, crawlCss: false });
107
144
  }
108
145
  catch (error) {
109
- failed.push({ url, reason: error instanceof ExportPathError && ctx.args.assetPathFailureReason !== undefined ? ctx.args.assetPathFailureReason : failureReason(ctx, url, error) });
146
+ failed.push({ url, reason: assetFailureReason({ ctx, url, error }) });
110
147
  }
111
148
  }
112
149
  return { succeeded, failed };
@@ -127,25 +164,125 @@ async function unreferenced(ctx, manifest, assets) {
127
164
  }
128
165
  return [...await ctx.args.assetSource.listThemeFiles({ theme })].filter(file => !accounted.has(file)).sort();
129
166
  }
167
+ /** Most dropped references retained per export. */
168
+ const MAX_DROPPED_REFERENCES = 200;
169
+ /** Site path normalization shared by written outputs and references: no trailing slashes, root as '/'. */
170
+ function pathNormalizer(required) {
171
+ return url => new URL(url, required.origin).pathname.replace(/\/+$/, '') || '/';
172
+ }
173
+ /** Every path this run wrote: artifact paths (and index.html directory aliases), route paths except the error-page probe, and asset URLs. */
174
+ function writtenPaths(required) {
175
+ const { routes, assets, normalize } = required;
176
+ const written = new Set();
177
+ for (const item of [...routes, ...assets]) {
178
+ const file = '/' + item.outputFile;
179
+ written.add(normalize(file));
180
+ if (file.endsWith('/index.html'))
181
+ written.add(normalize(file.slice(0, -10)));
182
+ }
183
+ for (const route of routes)
184
+ if (route.kind !== 'not-found')
185
+ written.add(normalize(route.path));
186
+ for (const asset of assets)
187
+ written.add(normalize(asset.url));
188
+ return written;
189
+ }
190
+ function isHtmlRoute(route) {
191
+ return /^text\/html\b/i.test(route.contentType ?? '') || route.outputFile.endsWith('.html');
192
+ }
193
+ /** Fragments are always skipped; empty and query-only values are skipped unless they are form actions (which post to the page itself). */
194
+ function isSkippedReference(required) {
195
+ const { value, attribute } = required;
196
+ return ((!value || value.startsWith('?')) && attribute !== 'action') || value.startsWith('#');
197
+ }
198
+ /** The same-origin site path a reference names, base path stripped; undefined when unparseable or off-site. */
199
+ function referencedPath(required) {
200
+ const { scan, value, page } = required;
201
+ let url;
202
+ try {
203
+ url = new URL(value, scan.origin + scan.basePath + page);
204
+ }
205
+ catch {
206
+ return undefined;
207
+ }
208
+ if (url.origin !== scan.origin)
209
+ return undefined;
210
+ let pathname = url.pathname;
211
+ if (scan.basePath && (pathname === scan.basePath || pathname.startsWith(scan.basePath + '/')))
212
+ pathname = pathname.slice(scan.basePath.length) || '/';
213
+ return scan.normalize(pathname);
214
+ }
215
+ /** A reference this export cannot serve: a form action (needs a server) or a link to a path nothing wrote. */
216
+ function droppedReference(required) {
217
+ const { scan, page, reference } = required;
218
+ const value = reference.url.trim();
219
+ if (isSkippedReference({ value, attribute: reference.attribute }))
220
+ return undefined;
221
+ const url = referencedPath({ scan, value, page });
222
+ if (url === undefined)
223
+ return undefined;
224
+ const reason = reference.attribute === 'action' ? 'needs-server' : 'not-exported';
225
+ if (reason === 'not-exported' && scan.written.has(url))
226
+ return undefined;
227
+ return { page, url, attribute: reference.attribute, reason };
228
+ }
229
+ /** Dedupe per page + URL; a form replaces an earlier link to the same URL, and new keys stop at the cap. */
230
+ function recordDrop(required) {
231
+ const { dropped, drop } = required;
232
+ const key = drop.page + '\n' + drop.url;
233
+ if (dropped.has(key)) {
234
+ if (drop.reason === 'needs-server')
235
+ dropped.set(key, drop);
236
+ }
237
+ else if (dropped.size < MAX_DROPPED_REFERENCES)
238
+ dropped.set(key, drop);
239
+ }
240
+ /** Compare written HTML with this run's outputs only; no requests or filesystem reads.
241
+ * At most 200 drops are retained. O(output count + scanned HTML bytes) time; output paths plus
242
+ * at most 200 dedupe keys are retained. Forms take precedence over links to the same URL.
243
+ */
244
+ function droppedReferences(required) {
245
+ const origin = required.baseUrl;
246
+ const normalize = pathNormalizer({ origin });
247
+ const scan = { origin, basePath: required.basePath, normalize, written: writtenPaths({ routes: required.routes, assets: required.assets, normalize }) };
248
+ const dropped = new Map();
249
+ for (const route of required.routes.filter(isHtmlRoute)) {
250
+ for (const reference of extractHtmlReferences({ html: route.data })) {
251
+ const drop = droppedReference({ scan, page: route.path, reference });
252
+ if (drop)
253
+ recordDrop({ dropped, drop });
254
+ }
255
+ }
256
+ return [...dropped.values()];
257
+ }
258
+ /** The app session's origin. Anything but a bare http(s) origin without credentials is refused. */
259
+ function sessionOrigin(required) {
260
+ const origin = new URL(required.baseUrl);
261
+ if (!['http:', 'https:'].includes(origin.protocol) || origin.username || origin.password || origin.pathname !== '/' || origin.search || origin.hash)
262
+ throw new Error('App session baseUrl must be an HTTP origin without credentials.');
263
+ return origin.origin;
264
+ }
265
+ function fetchTimeout(required) {
266
+ const timeoutMs = required.fetchTimeoutMs ?? 30_000;
267
+ if (!Number.isSafeInteger(timeoutMs) || timeoutMs <= 0)
268
+ throw new RangeError('fetchTimeoutMs must be a positive integer');
269
+ return timeoutMs;
270
+ }
130
271
  /** Drive the caller's actual app, retaining exact written bytes and reporting each failed item.
131
272
  * Startup/output/inventory errors throw; an opened app always closes. No singleton state is used.
132
273
  */
133
274
  export async function exportSite(required, optional = {}) {
134
275
  const basePath = normalizeBasePath({ raw: optional.basePath ?? '' });
135
- const timeoutMs = optional.fetchTimeoutMs ?? 30_000;
136
- if (!Number.isSafeInteger(timeoutMs) || timeoutMs <= 0)
137
- throw new RangeError('fetchTimeoutMs must be a positive integer');
276
+ const timeoutMs = fetchTimeout({ fetchTimeoutMs: optional.fetchTimeoutMs });
138
277
  await required.writer.prepare({ outputDir: required.outputDir }, { clean: optional.clean ?? false });
139
278
  const manifest = await required.manifest.build({});
140
279
  const session = await required.app.open({});
141
280
  try {
142
- const origin = new URL(session.baseUrl);
143
- if (!['http:', 'https:'].includes(origin.protocol) || origin.username || origin.password || origin.pathname !== '/' || origin.search || origin.hash)
144
- throw new Error('App session baseUrl must be an HTTP origin without credentials.');
145
- const ctx = { args: required, baseUrl: origin.origin, basePath, timeoutMs };
281
+ const ctx = { args: required, baseUrl: sessionOrigin({ baseUrl: session.baseUrl }), basePath, timeoutMs };
146
282
  const routes = await writeRoutes(ctx, manifest.routes);
147
283
  const assets = await writeAssets(ctx, [...routes.assets]);
148
284
  return { outputDir: required.outputDir, routes: { succeeded: routes.succeeded, failed: routes.failed }, assets, skippedManifestEntries: [...manifest.skipped, ...routes.skipped],
285
+ droppedReferences: droppedReferences({ routes: routes.succeeded, assets: assets.succeeded, basePath, baseUrl: ctx.baseUrl }),
149
286
  unreferencedThemeFiles: await unreferenced(ctx, manifest, assets.succeeded), ...(basePath ? { basePath, basePathRewriteWarning: BASE_PATH_REWRITE_WARNING } : {}) };
150
287
  }
151
288
  finally {
@@ -28,7 +28,14 @@ export declare function renderRedirectStub(required: {
28
28
  }, optional?: {
29
29
  basePath?: string;
30
30
  }): string;
31
- /** Quoted href/src/srcset scan, preserving data-URL commas and ignoring external references. */
31
+ /** HTML URL attributes; form actions are diagnostic references, never crawled as assets. */
32
+ export declare function extractHtmlReferences(required: {
33
+ html: string;
34
+ }, _optional?: Record<string, never>): Generator<{
35
+ url: string;
36
+ attribute: string;
37
+ }>;
38
+ /** Shared href/src/srcset/poster scan, preserving data-URL commas and ignoring external references. */
32
39
  export declare function extractAssetUrls(required: {
33
40
  html: string;
34
41
  prefixes: readonly string[];
@@ -1,10 +1,15 @@
1
1
  import { ExportPathError } from './contracts.js';
2
+ // Crawling and rewriting must recognize the same URL attributes.
3
+ const HTML_URL_ATTRIBUTES = ['href', 'src', 'srcset', 'poster'];
4
+ const HTML_URL_REWRITE = new RegExp(`\\b(${HTML_URL_ATTRIBUTES.join('|')})=(["'])([^"']*)\\2`, 'g');
5
+ const HTML_URL_SCAN = new RegExp(`\\b(${HTML_URL_ATTRIBUTES.join('|')})=(["'])([^"']+)\\2`, 'g');
2
6
  function escapeHtml(value) { return value.replace(/[&<>"']/g, char => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[char]); }
3
7
  function safeHref(value) {
4
8
  const href = value.trim();
5
9
  if (href.startsWith('#') || /^https?:\/\//i.test(href) || /^mailto:/i.test(href))
6
10
  return href;
7
11
  if (href.startsWith('/')) {
12
+ // eslint-disable-next-line sonarjs/no-clear-text-protocols -- Reserved .invalid sentinel used only for local URL resolution/origin comparison; never fetched.
8
13
  try {
9
14
  if (new URL(href, 'http://export-safehref.invalid/').origin === 'http://export-safehref.invalid')
10
15
  return href;
@@ -34,27 +39,33 @@ function prefix(value, basePath) {
34
39
  return value;
35
40
  return basePath + value;
36
41
  }
42
+ /** First index at or after `index` whose character fails `test` (or the end of `value`). */
43
+ function skipWhile(value, index, test) {
44
+ while (index < value.length && test(value[index]))
45
+ index++;
46
+ return index;
47
+ }
37
48
  function srcsetRanges(value) {
38
49
  const ranges = [];
39
50
  let index = 0;
40
51
  while (index < value.length) {
41
- while (index < value.length && /[\s,]/.test(value[index]))
42
- index++;
43
- const start = index;
44
- while (index < value.length && !/\s/.test(value[index]))
45
- index++;
52
+ const start = skipWhile(value, index, char => /[\s,]/.test(char));
53
+ index = skipWhile(value, start, char => !/\s/.test(char));
46
54
  let end = index;
47
55
  while (end > start && value[end - 1] === ',')
48
56
  end--;
49
57
  if (end > start)
50
58
  ranges.push({ start, end });
51
- if (end < index)
52
- continue;
53
- while (index < value.length && value[index] !== ',')
54
- index++;
59
+ // A URL ending in commas ends its candidate; otherwise skip its descriptor up to the next comma.
60
+ if (end === index)
61
+ index = skipWhile(value, index, char => char !== ',');
55
62
  }
56
63
  return ranges;
57
64
  }
65
+ /** One attribute's URL values: each srcset candidate URL, or the whole value for any other attribute. */
66
+ function attributeUrls(attribute, value) {
67
+ return attribute === 'srcset' ? srcsetRanges(value).map(({ start, end }) => value.slice(start, end)) : [value];
68
+ }
58
69
  /** A route path naming a `.json` file (e.g. a see-more JSON batch): written as that file, not `<path>/index.html`. */
59
70
  function isJsonRoute(path) {
60
71
  return /\.json$/i.test(path.split(/[?#]/)[0]);
@@ -71,9 +82,7 @@ function rewriteJson(body, basePath) {
71
82
  return JSON.stringify(parsed, (key, value) => (typeof value === 'string' && (key === 'href' || key === 'url' || key === 'src') ? prefix(value, basePath) : value));
72
83
  }
73
84
  function rewriteHtml(html, basePath) {
74
- if (!basePath)
75
- return html;
76
- return html.replace(/\b(href|src|srcset)=(["'])([^"']*)\2/g, (_match, attr, quote, value) => {
85
+ return html.replace(HTML_URL_REWRITE, (_match, attr, quote, value) => {
77
86
  if (attr !== 'srcset')
78
87
  return `${attr}=${quote}${prefix(value, basePath)}${quote}`;
79
88
  for (const { start, end } of srcsetRanges(value).reverse())
@@ -109,21 +118,31 @@ export function renderRedirectStub(required, optional = {}) {
109
118
  const safeTarget = escapeHtml(safeHref(location));
110
119
  return `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta http-equiv="refresh" content="0; url=${safeTarget}"><link rel="canonical" href="${safeTarget}"><title>Redirecting…</title></head><body>Redirecting to <a href="${safeTarget}">${escapeHtml(location)}</a>.</body></html>\n`;
111
120
  }
112
- /** Quoted href/src/srcset scan, preserving data-URL commas and ignoring external references. */
113
- export function extractAssetUrls(required) {
114
- const found = new Set();
115
- for (const match of required.html.matchAll(/\b(href|src|srcset)=(["'])([^"']+)\2/g)) {
116
- const value = match[3];
117
- const values = match[1] === 'srcset' ? srcsetRanges(value).map(({ start, end }) => value.slice(start, end)) : [value];
118
- for (const url of values)
119
- if (!url.startsWith('//') && required.prefixes.some(prefix => url.startsWith(prefix)))
120
- found.add(url.split('#')[0]);
121
+ /** HTML URL attributes; form actions are diagnostic references, never crawled as assets. */
122
+ export function* extractHtmlReferences(required, _optional = {}) {
123
+ const references = [...required.html.matchAll(HTML_URL_SCAN)]
124
+ .filter(match => required.html[match.index - 1] !== '-')
125
+ .map(match => ({ index: match.index, attribute: match[1], value: match[3] }));
126
+ for (const match of required.html.matchAll(/<form\b[^>]*?\baction=(["'])([^"']*)\1/g)) {
127
+ references.push({ index: match.index, attribute: 'action', value: match[2] });
121
128
  }
129
+ for (const { attribute, value } of references.sort((a, b) => a.index - b.index)) {
130
+ for (const url of attributeUrls(attribute, value))
131
+ yield { url, attribute };
132
+ }
133
+ }
134
+ /** Shared href/src/srcset/poster scan, preserving data-URL commas and ignoring external references. */
135
+ export function extractAssetUrls(required) {
136
+ const candidates = [];
137
+ for (const match of required.html.matchAll(HTML_URL_SCAN))
138
+ candidates.push(...attributeUrls(match[1], match[3]));
122
139
  // JSON link fields too (a see-more JSON batch's covers), as `rewriteJson` prefixes them.
123
- for (const [, url = ''] of required.html.matchAll(/"(?:href|src|url)"\s*:\s*"([^"\\]+)"/g)) {
140
+ for (const [, url = ''] of required.html.matchAll(/"(?:href|src|url)"\s*:\s*"([^"\\]+)"/g))
141
+ candidates.push(url);
142
+ const found = new Set();
143
+ for (const url of candidates)
124
144
  if (!url.startsWith('//') && required.prefixes.some(prefix => url.startsWith(prefix)))
125
145
  found.add(url.split('#')[0]);
126
- }
127
146
  return [...found];
128
147
  }
129
148
  /** A single CSS hop, resolved against the stylesheet URL and restricted to the same synthetic origin. */
@@ -134,12 +153,14 @@ export function extractCssUrls(required) {
134
153
  if (!ref || ref.startsWith('data:'))
135
154
  continue;
136
155
  let resolved;
156
+ // eslint-disable-next-line sonarjs/no-clear-text-protocols -- Reserved .invalid sentinel used only for local URL resolution/origin comparison; never fetched.
137
157
  try {
138
158
  resolved = new URL(ref, 'http://export-local.invalid' + required.cssUrl);
139
159
  }
140
160
  catch {
141
161
  continue;
142
162
  }
163
+ // eslint-disable-next-line sonarjs/no-clear-text-protocols -- Reserved .invalid sentinel used only for local URL resolution/origin comparison; never fetched.
143
164
  if (resolved.origin !== 'http://export-local.invalid')
144
165
  continue;
145
166
  if (required.prefixes.some(prefix => resolved.pathname.startsWith(prefix)))
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jini-ai/devops",
3
- "version": "0.5.4",
3
+ "version": "0.5.6",
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": {
@@ -26,7 +26,14 @@
26
26
  "./checks/node": "node",
27
27
  "./local-dev": "node",
28
28
  "./deploy/node": "node",
29
- "./static-export/failure-summary": "universal"
29
+ "./static-export/failure-summary": "universal",
30
+ "./dns": "node",
31
+ "./dns/node": "node"
32
+ },
33
+ "isolation": {
34
+ "shared": [
35
+ "src/core/export-failure-summary.ts"
36
+ ]
30
37
  }
31
38
  },
32
39
  "type": "module",
@@ -103,6 +110,16 @@
103
110
  "types": "./dist/core/export-failure-summary.d.ts",
104
111
  "import": "./dist/core/export-failure-summary.js",
105
112
  "default": "./dist/core/export-failure-summary.js"
113
+ },
114
+ "./dns": {
115
+ "types": "./dist/dns/index.d.ts",
116
+ "import": "./dist/dns/index.js",
117
+ "default": "./dist/dns/index.js"
118
+ },
119
+ "./dns/node": {
120
+ "types": "./dist/dns/node/index.d.ts",
121
+ "import": "./dist/dns/node/index.js",
122
+ "default": "./dist/dns/node/index.js"
106
123
  }
107
124
  },
108
125
  "files": [
@@ -124,12 +141,12 @@
124
141
  "devDependencies": {
125
142
  "@vitest/coverage-v8": "^2.1.9",
126
143
  "undici": "^7.25.0",
127
- "@jini-ai/daemon": "0.6.1",
128
- "@jini-ai/platform": "^0.5.3",
129
- "@jini-ai/core": "^0.4.3"
144
+ "@jini-ai/core": "^0.4.9",
145
+ "@jini-ai/platform": "^0.5.10",
146
+ "@jini-ai/daemon": "0.6.9"
130
147
  },
131
148
  "dependencies": {
132
- "@jini-ai/core": "^0.4.3"
149
+ "@jini-ai/core": "^0.4.9"
133
150
  },
134
151
  "peerDependencies": {
135
152
  "typescript": "^5.6.0",