@mfdaves/okf-mcp 0.9.0 → 0.12.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (97) hide show
  1. package/CHANGELOG.md +69 -0
  2. package/README.md +176 -19
  3. package/bin/okf-mcp.js +6 -1
  4. package/okf/okf-mcp/policies/authoring-safety.md +11 -1
  5. package/package.json +17 -5
  6. package/server.json +2 -2
  7. package/src/assets.js +165 -73
  8. package/src/authoring/candidates.js +391 -0
  9. package/src/authoring/git-preflight.js +225 -0
  10. package/src/authoring/git-publish.js +776 -0
  11. package/src/authoring/live.js +789 -0
  12. package/src/authoring/paths.js +112 -0
  13. package/src/authoring/policy-hook.js +221 -0
  14. package/src/authoring/proposal-policy.js +137 -0
  15. package/src/authoring/receipts.js +329 -0
  16. package/src/authoring/render.js +38 -0
  17. package/src/authoring/shared.js +75 -0
  18. package/src/authoring/staging.js +216 -0
  19. package/src/authoring.js +386 -287
  20. package/src/cache/files.js +147 -0
  21. package/src/cache/lock.js +201 -0
  22. package/src/cache/paths.js +197 -0
  23. package/src/cache/store.js +703 -0
  24. package/src/catalog-text.js +19 -0
  25. package/src/cli.js +184 -151
  26. package/src/computation.js +99 -61
  27. package/src/context/assemble.js +567 -0
  28. package/src/context/cli-options.js +88 -0
  29. package/src/context/score.js +234 -0
  30. package/src/context/sections.js +274 -0
  31. package/src/embed/interface.js +160 -0
  32. package/src/embed/openai.js +715 -0
  33. package/src/embed/prepare.js +182 -0
  34. package/src/embed/units.js +96 -0
  35. package/src/git-source.js +112 -52
  36. package/src/graph.js +95 -37
  37. package/src/http-server.js +36 -17
  38. package/src/index.js +15 -0
  39. package/src/indexer/assemble.js +566 -0
  40. package/src/indexer/build.js +290 -0
  41. package/src/indexer/cache.js +81 -0
  42. package/src/indexer/edges.js +430 -0
  43. package/src/indexer/index.js +44 -0
  44. package/src/indexer/paths.js +178 -0
  45. package/src/indexer/resolve.js +282 -0
  46. package/src/indexer/update.js +720 -0
  47. package/src/indexer.js +3 -1068
  48. package/src/live-authoring.js +4 -2329
  49. package/src/markdown.js +21 -16
  50. package/src/mcp/registry.js +328 -0
  51. package/src/mcp/resources.js +45 -0
  52. package/src/mcp/server.js +472 -0
  53. package/src/mcp/tools/catalog.js +244 -0
  54. package/src/mcp/tools/computation.js +83 -0
  55. package/src/mcp/tools/context.js +133 -0
  56. package/src/mcp/tools/graph.js +167 -0
  57. package/src/mcp/tools/live-authoring.js +316 -0
  58. package/src/mcp/tools/migration.js +86 -0
  59. package/src/mcp/tools/producers.js +79 -0
  60. package/src/mcp/tools/proposals.js +213 -0
  61. package/src/mcp/tools/provenance.js +87 -0
  62. package/src/mcp/tools/remote.js +79 -0
  63. package/src/mcp/tools/search.js +242 -0
  64. package/src/mcp-server.js +3 -1611
  65. package/src/migration.js +431 -253
  66. package/src/parser.js +245 -130
  67. package/src/plugins.js +71 -48
  68. package/src/policy/write-policy.js +713 -0
  69. package/src/producer-publisher.js +195 -77
  70. package/src/producers.js +265 -101
  71. package/src/project.js +277 -93
  72. package/src/remote.js +96 -61
  73. package/src/search/cli-options.js +107 -0
  74. package/src/search/confidence.js +61 -0
  75. package/src/search/dense.js +304 -0
  76. package/src/search/embedding-cli.js +57 -0
  77. package/src/search/embedding-config.js +217 -0
  78. package/src/search/fusion.js +249 -0
  79. package/src/search/hybrid.js +526 -0
  80. package/src/search/languages.js +200 -0
  81. package/src/search/lexical.js +695 -0
  82. package/src/search/query.js +620 -0
  83. package/src/search/stem/among.js +43 -0
  84. package/src/search/stem/base-stemmer.js +311 -0
  85. package/src/search/stem/en-regions.js +456 -0
  86. package/src/search/stem/en-suffixes.js +664 -0
  87. package/src/search/stem/en-tables.js +176 -0
  88. package/src/search/stem/en.js +238 -0
  89. package/src/search/stem/it-regions.js +459 -0
  90. package/src/search/stem/it-suffixes.js +471 -0
  91. package/src/search/stem/it-tables.js +257 -0
  92. package/src/search/stem/it.js +155 -0
  93. package/src/search-index.js +2 -81
  94. package/src/search.js +2 -252
  95. package/src/store.js +134 -81
  96. package/src/v02.js +301 -105
  97. package/src/validation.js +24 -20
@@ -0,0 +1,430 @@
1
+ "use strict";
2
+
3
+ const path = require("node:path");
4
+ const { normalizeSlashes, safeRelativePath } = require("../parser");
5
+ const { isExternalReference, isLocalAssetReference, mimeIsText } = require("../assets");
6
+ const { undeclaredRelationTypeMessage } = require("../catalog-text");
7
+
8
+ function documentAtPath(documentsByPath, pathUri) {
9
+ if (!documentsByPath || typeof documentsByPath.get !== "function") {
10
+ return null;
11
+ }
12
+ const document = documentsByPath.get(pathUri);
13
+ return document && document.pathUri === pathUri ? document : null;
14
+ }
15
+
16
+ function resolveIndexedLink(bundleId, resolved, href, documentsByPath) {
17
+ if (!documentsByPath || typeof documentsByPath.get !== "function") {
18
+ return resolved;
19
+ }
20
+ const directTarget = documentAtPath(documentsByPath, resolved.uri);
21
+ if (directTarget) {
22
+ return Object.assign({}, resolved, { uri: directTarget.uri });
23
+ }
24
+ const clean = String(href || "").split("#")[0];
25
+ if (!clean.endsWith("/") && path.posix.extname(resolved.path)) {
26
+ return resolved;
27
+ }
28
+ const indexPath = normalizeSlashes(path.posix.join(resolved.path, "index.md"));
29
+ const indexTarget = documentAtPath(documentsByPath, `okf://${bundleId}/${indexPath}`);
30
+ if (!indexTarget) {
31
+ return resolved;
32
+ }
33
+ return Object.assign({}, resolved, {
34
+ path: indexPath,
35
+ uri: indexTarget.uri,
36
+ });
37
+ }
38
+
39
+ function resolveLinkPath(bundle, fromPath, href, documentsByPath) {
40
+ const clean = String(href || "").split("#")[0];
41
+ if (
42
+ !clean ||
43
+ clean.startsWith("http://") ||
44
+ clean.startsWith("https://") ||
45
+ clean.startsWith("mailto:")
46
+ ) {
47
+ return null;
48
+ }
49
+ if (bundle.remote) {
50
+ const normalizedPath = clean.startsWith("/")
51
+ ? path.posix.normalize(clean.slice(1))
52
+ : path.posix.normalize(path.posix.join(path.posix.dirname(fromPath), clean));
53
+ const resolvedPath = normalizedPath === "." ? "" : normalizedPath.replace(/\/+$/g, "");
54
+ if (resolvedPath.startsWith("../") || resolvedPath === "..") {
55
+ return {
56
+ outsideRoot: true,
57
+ path: normalizeSlashes(clean),
58
+ uri: null,
59
+ };
60
+ }
61
+ return resolveIndexedLink(
62
+ bundle.id,
63
+ {
64
+ outsideRoot: false,
65
+ path: resolvedPath,
66
+ uri: `okf://${bundle.id}/${resolvedPath}`,
67
+ },
68
+ clean,
69
+ documentsByPath,
70
+ );
71
+ }
72
+ const base = clean.startsWith("/")
73
+ ? path.join(bundle.root, clean.slice(1))
74
+ : path.resolve(path.dirname(path.join(bundle.root, fromPath)), clean);
75
+ const relativePath = safeRelativePath(bundle.root, base);
76
+ if (relativePath === null) {
77
+ return {
78
+ outsideRoot: true,
79
+ path: normalizeSlashes(clean),
80
+ uri: null,
81
+ };
82
+ }
83
+ return resolveIndexedLink(
84
+ bundle.id,
85
+ {
86
+ outsideRoot: false,
87
+ path: relativePath,
88
+ uri: `okf://${bundle.id}/${relativePath}`,
89
+ },
90
+ clean,
91
+ documentsByPath,
92
+ );
93
+ }
94
+
95
+ function relationFrom(value, doc) {
96
+ if (typeof value === "string") {
97
+ const parts = value.trim().split(/\s+/);
98
+ if (parts.length === 1) {
99
+ return { type: "related_to", target: parts[0], source: doc.uri };
100
+ }
101
+ return { type: parts[0], target: parts.slice(1).join(" "), source: doc.uri };
102
+ }
103
+ if (value && typeof value === "object") {
104
+ return {
105
+ type: value.type || value.kind || "related_to",
106
+ target: value.target || value.to || "",
107
+ source: doc.uri,
108
+ label: value.label || value.text || "",
109
+ description: value.description || "",
110
+ };
111
+ }
112
+ return { type: "related_to", target: "", source: doc.uri };
113
+ }
114
+
115
+ function assetUri(bundle, relativePath) {
116
+ return `okf-asset://${bundle}/${normalizeSlashes(relativePath).split("/").map(encodeURIComponent).join("/")}`;
117
+ }
118
+
119
+ function relativeReferencePath(fromPath, reference) {
120
+ const raw = normalizeSlashes(String(reference || "").trim()).split("#")[0];
121
+ if (!raw || isExternalReference(raw)) {
122
+ return null;
123
+ }
124
+ const relative = raw.startsWith("/")
125
+ ? path.posix.normalize(raw.slice(1))
126
+ : path.posix.normalize(path.posix.join(path.posix.dirname(fromPath), raw));
127
+ if (
128
+ !relative ||
129
+ relative === "." ||
130
+ relative === ".." ||
131
+ relative.startsWith("../") ||
132
+ path.posix.isAbsolute(relative)
133
+ ) {
134
+ return null;
135
+ }
136
+ return normalizeSlashes(relative);
137
+ }
138
+
139
+ function semanticReferences(doc) {
140
+ const frontmatter = doc.frontmatter || {};
141
+ const references = [];
142
+ function add(kind, field, value, metadata) {
143
+ if (typeof value === "string" && value.trim()) {
144
+ references.push({ kind, field, value: value.trim(), metadata: metadata || null });
145
+ }
146
+ }
147
+ add("resource", "resource", frontmatter.resource);
148
+ const sources =
149
+ doc.signals && Array.isArray(doc.signals.sources)
150
+ ? doc.signals.sources
151
+ : Array.isArray(frontmatter.sources)
152
+ ? frontmatter.sources
153
+ : [];
154
+ sources.forEach((source, index) => {
155
+ if (source && typeof source === "object" && !Array.isArray(source)) {
156
+ add("source", `sources[${index}].resource`, source.resource, source);
157
+ }
158
+ });
159
+ add("computation", "computation", frontmatter.computation);
160
+ if (
161
+ frontmatter.executor &&
162
+ typeof frontmatter.executor === "object" &&
163
+ !Array.isArray(frontmatter.executor)
164
+ ) {
165
+ add("executor", "executor.resource", frontmatter.executor.resource);
166
+ }
167
+ if (
168
+ frontmatter.attester &&
169
+ typeof frontmatter.attester === "object" &&
170
+ !Array.isArray(frontmatter.attester)
171
+ ) {
172
+ add("attester", "attester.resource", frontmatter.attester.resource);
173
+ }
174
+ return references;
175
+ }
176
+
177
+ // Derives one document's outbound graph: Markdown link edges, typed relation
178
+ // edges, and standard semantic reference edges, with the warnings and errors
179
+ // they raise. Resolution goes only through `lookups` (Map-like objects with a
180
+ // `get` method keyed like the index maps), so a caller can observe exactly
181
+ // which keys a document's edges depend on.
182
+ function documentEdges(doc, bundle, lookups, config) {
183
+ const allowedRelationTypes = config.allowedRelationTypes;
184
+ const allowCustomRelationTypes = Boolean(config.allowCustomRelationTypes);
185
+ const { byPathUri, byUri, byConceptId, byAssetKey } = lookups;
186
+ const edges = [];
187
+ const warnings = [];
188
+ const errors = [];
189
+ const externalReferences = [];
190
+ const customRelationTypes = [];
191
+ doc.links.forEach((link) => {
192
+ const resolved = resolveLinkPath(bundle, doc.path, link.href, byPathUri);
193
+ if (!resolved) {
194
+ return;
195
+ }
196
+ if (resolved.outsideRoot) {
197
+ warnings.push({
198
+ code: "link_outside_root",
199
+ bundle: doc.bundle,
200
+ path: doc.path,
201
+ href: link.href,
202
+ message: "Markdown link resolves outside bundle root.",
203
+ });
204
+ return;
205
+ }
206
+ const target = documentAtPath(byPathUri, `okf://${doc.bundle}/${resolved.path}`);
207
+ const edge = {
208
+ source: doc.uri,
209
+ target: target ? target.uri : resolved.uri,
210
+ kind: "markdown_link",
211
+ text: link.text || "",
212
+ href: link.href,
213
+ broken: !target,
214
+ };
215
+ edges.push(edge);
216
+ if (!target) {
217
+ warnings.push({
218
+ code: "broken_link",
219
+ bundle: doc.bundle,
220
+ path: doc.path,
221
+ href: link.href,
222
+ target: resolved.path,
223
+ message: "Markdown link target does not exist in bundle.",
224
+ });
225
+ }
226
+ });
227
+ doc.relations
228
+ .map((relation) => relationFrom(relation, doc))
229
+ .forEach((relation, position) => {
230
+ const type = String(relation.type || "related_to");
231
+ const targetUri = String(relation.target || "").trim();
232
+ if (!targetUri) {
233
+ errors.push({
234
+ code: "missing_relation_target",
235
+ bundle: doc.bundle,
236
+ path: doc.path,
237
+ relationType: type,
238
+ message: "Relation has no target.",
239
+ });
240
+ return;
241
+ }
242
+ const safeCustomType = /^[A-Za-z0-9_.-]+$/.test(type);
243
+ if (!allowedRelationTypes.has(type) && !(allowCustomRelationTypes && safeCustomType)) {
244
+ errors.push({
245
+ code: "invalid_relation_type",
246
+ bundle: doc.bundle,
247
+ path: doc.path,
248
+ relationType: type,
249
+ message: undeclaredRelationTypeMessage(doc.path, position),
250
+ });
251
+ } else if (allowCustomRelationTypes && safeCustomType) {
252
+ customRelationTypes.push(type);
253
+ }
254
+ let targetDocument = byUri.get(targetUri) || null;
255
+ let internalTarget = targetUri.startsWith("okf://");
256
+ if (!targetDocument && !/^[A-Za-z][A-Za-z0-9+.-]*:/u.test(targetUri)) {
257
+ internalTarget = true;
258
+ const resolved = resolveLinkPath(bundle, doc.path, targetUri, byPathUri);
259
+ if (resolved && !resolved.outsideRoot) {
260
+ targetDocument = documentAtPath(byPathUri, `okf://${doc.bundle}/${resolved.path}`);
261
+ if (!targetDocument && !path.posix.extname(resolved.path)) {
262
+ targetDocument = documentAtPath(byPathUri, `okf://${doc.bundle}/${resolved.path}.md`);
263
+ }
264
+ }
265
+ if (!targetDocument) {
266
+ const normalizedTarget = normalizeSlashes(targetUri)
267
+ .replace(/^\/+/, "")
268
+ .replace(/\.md$/i, "");
269
+ const portableTarget = byConceptId.get(normalizedTarget);
270
+ if (portableTarget && portableTarget.bundle === doc.bundle) {
271
+ targetDocument = portableTarget;
272
+ }
273
+ }
274
+ }
275
+ const target =
276
+ targetDocument && !targetDocument.reserved && targetDocument.valid ? targetDocument : null;
277
+ const isExternal = !internalTarget;
278
+ if (isExternal) {
279
+ externalReferences.push(targetUri);
280
+ }
281
+ if (internalTarget && !target) {
282
+ errors.push({
283
+ code: "broken_relation",
284
+ bundle: doc.bundle,
285
+ path: doc.path,
286
+ target: targetUri,
287
+ relationType: type,
288
+ message: "Relation target does not resolve to a valid concept.",
289
+ });
290
+ }
291
+ edges.push({
292
+ source: doc.uri,
293
+ target: target ? target.uri : targetUri,
294
+ kind: "relation",
295
+ relationType: type,
296
+ text: relation.label || type,
297
+ description: relation.description || "",
298
+ broken: internalTarget && !target,
299
+ external: isExternal,
300
+ });
301
+ });
302
+ semanticReferences(doc).forEach((reference) => {
303
+ const rawTarget = reference.value;
304
+ let target = null;
305
+ let external = false;
306
+ let broken = false;
307
+ let resolvedAs = "opaque";
308
+ if (rawTarget.startsWith("okf://")) {
309
+ const targetDoc = byUri.get(rawTarget);
310
+ target = targetDoc ? targetDoc.uri : rawTarget;
311
+ const validTarget = Boolean(targetDoc && !targetDoc.reserved && targetDoc.valid);
312
+ broken = !validTarget;
313
+ resolvedAs = validTarget ? "concept" : targetDoc ? "invalid_concept" : "unresolved";
314
+ if (!validTarget) {
315
+ warnings.push({
316
+ code: "broken_semantic_reference",
317
+ severity: "warning",
318
+ layer: "project",
319
+ bundle: doc.bundle,
320
+ path: doc.path,
321
+ field: reference.field,
322
+ target: rawTarget,
323
+ edgeKind: reference.kind,
324
+ message: targetDoc
325
+ ? "Standard OKF semantic reference targets an invalid or reserved document."
326
+ : "Standard OKF semantic reference targets an unknown internal concept.",
327
+ });
328
+ }
329
+ } else if (isExternalReference(rawTarget)) {
330
+ target = rawTarget;
331
+ external = true;
332
+ resolvedAs = "external";
333
+ } else {
334
+ const targetPath = relativeReferencePath(doc.path, rawTarget);
335
+ const targetDoc = targetPath
336
+ ? documentAtPath(byPathUri, `okf://${doc.bundle}/${targetPath}`) ||
337
+ byUri.get(`okf://${doc.bundle}/${targetPath.replace(/\.md$/i, "")}`)
338
+ : null;
339
+ const targetAsset = targetPath ? byAssetKey.get(`${doc.bundle}\u0000${targetPath}`) : null;
340
+ if (targetDoc && !targetDoc.reserved && targetDoc.valid) {
341
+ target = targetDoc.uri;
342
+ resolvedAs = "concept";
343
+ } else if (targetDoc) {
344
+ target = targetDoc.uri;
345
+ broken = true;
346
+ resolvedAs = "invalid_concept";
347
+ } else if (targetAsset) {
348
+ target = targetAsset.uri;
349
+ resolvedAs = "asset";
350
+ } else {
351
+ target = rawTarget;
352
+ const opaqueSource =
353
+ reference.kind === "source" && !isLocalAssetReference(rawTarget, { allowBare: false });
354
+ external = opaqueSource;
355
+ broken = !opaqueSource;
356
+ resolvedAs = opaqueSource ? "opaque" : "unresolved";
357
+ }
358
+ }
359
+ if (broken && !rawTarget.startsWith("okf://")) {
360
+ warnings.push({
361
+ code: "broken_semantic_reference",
362
+ severity: "warning",
363
+ layer: "project",
364
+ bundle: doc.bundle,
365
+ path: doc.path,
366
+ field: reference.field,
367
+ target: rawTarget,
368
+ edgeKind: reference.kind,
369
+ message:
370
+ "Standard OKF semantic reference does not resolve to a valid local concept or indexed asset.",
371
+ });
372
+ }
373
+ if (external) {
374
+ externalReferences.push(target);
375
+ }
376
+ edges.push({
377
+ source: doc.uri,
378
+ target,
379
+ kind: reference.kind,
380
+ field: reference.field,
381
+ reference: rawTarget,
382
+ sourceEntry: reference.kind === "source" ? reference.metadata : undefined,
383
+ resolvedAs,
384
+ broken,
385
+ external,
386
+ });
387
+ });
388
+ return { edges, warnings, errors, externalReferences, customRelationTypes };
389
+ }
390
+
391
+ // Whether every asset or concept an attested computation contract needs is
392
+ // present and readable, judged from the contract's own semantic edges.
393
+ function contractAssetsReady(contract, contractEdges, byAssetUri) {
394
+ const requiredKinds =
395
+ contract.computation && contract.computation.mode === "file"
396
+ ? ["computation", "executor", "attester"]
397
+ : ["executor", "attester"];
398
+ return requiredKinds.every((kind) => {
399
+ const edge = contractEdges.find((entry) => entry.kind === kind);
400
+ if (!edge || edge.broken) {
401
+ return false;
402
+ }
403
+ if (kind === "computation") {
404
+ if (edge.resolvedAs !== "asset") {
405
+ return false;
406
+ }
407
+ const asset = byAssetUri.get(edge.target);
408
+ return Boolean(asset && (!mimeIsText(asset.mimeType) || asset.kind === "text"));
409
+ }
410
+ if (edge.resolvedAs === "concept") {
411
+ return true;
412
+ }
413
+ if (edge.resolvedAs !== "asset") {
414
+ return false;
415
+ }
416
+ const asset = byAssetUri.get(edge.target);
417
+ return Boolean(asset && (!mimeIsText(asset.mimeType) || asset.kind === "text"));
418
+ });
419
+ }
420
+
421
+ module.exports = {
422
+ assetUri,
423
+ contractAssetsReady,
424
+ documentAtPath,
425
+ documentEdges,
426
+ relationFrom,
427
+ relativeReferencePath,
428
+ resolveLinkPath,
429
+ semanticReferences,
430
+ };
@@ -0,0 +1,44 @@
1
+ "use strict";
2
+
3
+ // The indexer's public surface. build.js loads bundles and builds a complete
4
+ // index, edges.js derives one document's outbound graph, resolve.js turns
5
+ // locators into concepts, assemble.js registers documents and assembles the
6
+ // index object for both paths, update.js applies changes to an existing
7
+ // index and keeps derived views, and cache.js keeps one index current for a
8
+ // host that writes. Internal helpers stay on their modules; only the names
9
+ // listed here are part of the package API.
10
+ const build = require("./build");
11
+ const cache = require("./cache");
12
+ const edges = require("./edges");
13
+ const resolve = require("./resolve");
14
+ const update = require("./update");
15
+
16
+ module.exports = {
17
+ IndexCache: cache.IndexCache,
18
+ buildIndex: build.buildIndex,
19
+ buildProjectIndex: build.buildProjectIndex,
20
+ buildProjectIndexAsync: build.buildProjectIndexAsync,
21
+ attachProject: build.attachProject,
22
+ conceptSummary: resolve.conceptSummary,
23
+ conceptSignals: resolve.conceptSignals,
24
+ conceptIsGeneratedFile: resolve.conceptIsGeneratedFile,
25
+ conceptMatchSummary: resolve.conceptMatchSummary,
26
+ bundleAllowsPath: build.bundleAllowsPath,
27
+ bundleExcludesPath: build.bundleExcludesPath,
28
+ edgesBySource: update.edgesBySource,
29
+ findConceptMatches: resolve.findConceptMatches,
30
+ indexInputs: update.indexInputs,
31
+ indexUpdateStats: update.indexUpdateStats,
32
+ linkSets: update.linkSets,
33
+ loadProjectBundles: build.loadProjectBundles,
34
+ normalizeConceptTitle: resolve.normalizeConceptTitle,
35
+ parseBundleArg: build.parseBundleArg,
36
+ recoverConceptLocator: resolve.recoverConceptLocator,
37
+ refreshIndex: update.refreshIndex,
38
+ resolveLinkPath: edges.resolveLinkPath,
39
+ resolveConcept: resolve.resolveConcept,
40
+ semanticReferences: edges.semanticReferences,
41
+ sanitizeBundleId: build.sanitizeBundleId,
42
+ updateIndex: update.updateIndex,
43
+ validateIndex: build.validateIndex,
44
+ };
@@ -0,0 +1,178 @@
1
+ "use strict";
2
+
3
+ const fs = require("node:fs");
4
+ const path = require("node:path");
5
+ const { normalizeSlashes } = require("../parser");
6
+
7
+ function sanitizeBundleId(value, fallback) {
8
+ const raw = String(value || fallback || "bundle").trim();
9
+ return raw.replace(/[^A-Za-z0-9_.-]+/g, "-").replace(/^-+|-+$/g, "") || "bundle";
10
+ }
11
+
12
+ function parseBundleArg(arg, index) {
13
+ if (arg && typeof arg === "object") {
14
+ return {
15
+ id: sanitizeBundleId(arg.id, `bundle-${index + 1}`),
16
+ root: arg.remote ? "" : path.resolve(arg.root),
17
+ remote: Boolean(arg.remote),
18
+ remoteSource: arg.remoteSource || null,
19
+ documents: Array.isArray(arg.documents) ? arg.documents : [],
20
+ assets: Array.isArray(arg.assets) ? arg.assets : [],
21
+ include: Array.isArray(arg.include) ? arg.include : [],
22
+ exclude: Array.isArray(arg.exclude) ? arg.exclude : [],
23
+ };
24
+ }
25
+ const text = String(arg || "");
26
+ const eq = text.indexOf("=");
27
+ if (eq > 0) {
28
+ return {
29
+ id: sanitizeBundleId(text.slice(0, eq), `bundle-${index + 1}`),
30
+ root: path.resolve(text.slice(eq + 1)),
31
+ };
32
+ }
33
+ const root = path.resolve(text);
34
+ return {
35
+ id: sanitizeBundleId(path.basename(root), `bundle-${index + 1}`),
36
+ root,
37
+ };
38
+ }
39
+
40
+ function documentOverrideKey(bundleId, relativePath) {
41
+ return `${bundleId}\u0000${normalizeSlashes(relativePath)}`;
42
+ }
43
+
44
+ function uniqueBundleIds(bundles) {
45
+ return bundles.map((bundle) => {
46
+ const base = sanitizeBundleId(bundle.id);
47
+ return {
48
+ id: base,
49
+ root: bundle.remote ? "" : path.resolve(bundle.root),
50
+ remote: Boolean(bundle.remote),
51
+ remoteSource: bundle.remoteSource || null,
52
+ documents: Array.isArray(bundle.documents) ? bundle.documents : [],
53
+ assets: Array.isArray(bundle.assets) ? bundle.assets : [],
54
+ include: bundle.include || [],
55
+ exclude: bundle.exclude || [],
56
+ };
57
+ });
58
+ }
59
+
60
+ function escapeRegex(value) {
61
+ return String(value).replace(/[|\\{}()[\]^$+?.]/g, "\\$&");
62
+ }
63
+
64
+ function patternToRegex(pattern) {
65
+ const text = normalizeSlashes(pattern);
66
+ let source = "";
67
+ for (let index = 0; index < text.length; index += 1) {
68
+ const char = text[index];
69
+ if (char === "*") {
70
+ if (text[index + 1] === "*") {
71
+ if (text[index + 2] === "/") {
72
+ source += "(?:.*/)?";
73
+ index += 2;
74
+ } else {
75
+ source += ".*";
76
+ index += 1;
77
+ }
78
+ } else {
79
+ source += "[^/]*";
80
+ }
81
+ continue;
82
+ }
83
+ source += escapeRegex(char);
84
+ }
85
+ return new RegExp(`^${source}$`);
86
+ }
87
+
88
+ function matchesPattern(relativePath, pattern) {
89
+ const normalizedPath = normalizeSlashes(relativePath);
90
+ const normalizedPattern = normalizeSlashes(pattern);
91
+ if (!normalizedPattern) {
92
+ return false;
93
+ }
94
+ if (normalizedPath === normalizedPattern) {
95
+ return true;
96
+ }
97
+ if (normalizedPattern.endsWith("/")) {
98
+ return normalizedPath.startsWith(normalizedPattern);
99
+ }
100
+ if (normalizedPattern.includes("*")) {
101
+ return patternToRegex(normalizedPattern).test(normalizedPath);
102
+ }
103
+ return normalizedPath.startsWith(`${normalizedPattern}/`);
104
+ }
105
+
106
+ function bundleAllowsPath(bundle, relativePath) {
107
+ const include = Array.isArray(bundle.include) ? bundle.include : [];
108
+ const exclude = Array.isArray(bundle.exclude) ? bundle.exclude : [];
109
+ if (include.length && !include.some((pattern) => matchesPattern(relativePath, pattern))) {
110
+ return false;
111
+ }
112
+ if (exclude.some((pattern) => matchesPattern(relativePath, pattern))) {
113
+ return false;
114
+ }
115
+ return true;
116
+ }
117
+
118
+ function bundleExcludesPath(bundle, relativePath) {
119
+ const exclude = Array.isArray(bundle?.exclude) ? bundle.exclude : [];
120
+ return exclude.some((pattern) => matchesPattern(relativePath, pattern));
121
+ }
122
+
123
+ function walkMarkdown(root) {
124
+ const out = [];
125
+ if (!fs.existsSync(root)) {
126
+ return out;
127
+ }
128
+ const entries = fs.readdirSync(root, { withFileTypes: true });
129
+ entries.forEach((entry) => {
130
+ const full = path.join(root, entry.name);
131
+ if (entry.isDirectory()) {
132
+ out.push.apply(out, walkMarkdown(full));
133
+ return;
134
+ }
135
+ if (entry.isFile() && entry.name.toLowerCase().endsWith(".md")) {
136
+ out.push(full);
137
+ }
138
+ });
139
+ return out.sort();
140
+ }
141
+
142
+ // The absolute path of a bundle document in the form walkMarkdown reports it,
143
+ // so a document added without a walk sorts and compares like a walked one.
144
+ function documentAbsolutePath(bundle, relativePath) {
145
+ return path.join(bundle.root, ...normalizeSlashes(relativePath).split("/"));
146
+ }
147
+
148
+ // Size and mtime of a regular file at nanosecond precision, or null when
149
+ // there is no such file. A refresh compares these to tell a changed file
150
+ // from an unchanged one without reading it.
151
+ function fileStat(absolutePath) {
152
+ try {
153
+ const stat = fs.statSync(absolutePath, { bigint: true });
154
+ return stat.isFile() ? { size: Number(stat.size), mtimeNs: stat.mtimeNs } : null;
155
+ } catch {
156
+ return null;
157
+ }
158
+ }
159
+
160
+ function sameStat(left, right) {
161
+ if (!left || !right) {
162
+ return left === right;
163
+ }
164
+ return left.size === right.size && left.mtimeNs === right.mtimeNs;
165
+ }
166
+
167
+ module.exports = {
168
+ bundleAllowsPath,
169
+ bundleExcludesPath,
170
+ documentAbsolutePath,
171
+ documentOverrideKey,
172
+ fileStat,
173
+ sameStat,
174
+ parseBundleArg,
175
+ sanitizeBundleId,
176
+ uniqueBundleIds,
177
+ walkMarkdown,
178
+ };