@dialecte/cli 0.6.0 → 0.8.0

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/dist/lookups.js CHANGED
@@ -324,40 +324,45 @@ var SHORT_SUMMARY_MAX_LENGTH = 120;
324
324
 
325
325
  // src/lib/api/read-api-indexes.ts
326
326
  function readApiIndexes(params) {
327
+ return apiIndexesOf({ files: apiIndexFilesOf(params) });
328
+ }
329
+ function apiIndexFilesOf(params) {
327
330
  const { cwd } = params;
328
- const skillFolders = [
329
- ...ownSkillFolders(cwd),
330
- ...discoverSkillSources({ cwd }).sources.map((source) => source.path)
331
- ];
331
+ const installed = existsSync2(join3(cwd, "package.json")) ? discoverSkillSources({ cwd }).sources.map((source) => source.path) : [];
332
+ return [...ownSkillFolders(cwd), ...installed].map((folder) => join3(folder, API_JSON_FOLDER, API_JSON_FILE)).filter((path) => existsSync2(path));
333
+ }
334
+ function apiIndexesOf(params) {
335
+ return firstPerPackage(params.files.map(readApiJson));
336
+ }
337
+ function firstPerPackage(indexes) {
332
338
  const byPackage = /* @__PURE__ */ new Map();
333
- for (const folder of skillFolders) {
334
- const path = join3(folder, API_JSON_FOLDER, API_JSON_FILE);
335
- if (!existsSync2(path)) continue;
336
- const index = readApiJson(path);
339
+ for (const index of indexes)
337
340
  if (!byPackage.has(index.package)) byPackage.set(index.package, index);
338
- }
339
341
  return [...byPackage.values()].sort(
340
342
  (left, right) => TEXT_COLLATOR.compare(left.package, right.package)
341
343
  );
342
344
  }
345
+ function parseApiJson(path) {
346
+ let value;
347
+ try {
348
+ value = JSON.parse(readFileSync2(path, "utf8"));
349
+ } catch (error) {
350
+ return { problem: error instanceof Error ? error.message : String(error) };
351
+ }
352
+ if (!isApiJson(value)) return { problem: "no package name or no method list" };
353
+ return { index: value };
354
+ }
343
355
  function ownSkillFolders(cwd) {
344
356
  const skillsRoot = join3(cwd, SKILLS_FOLDER);
345
357
  if (!existsSync2(skillsRoot)) return [];
346
358
  return readdirSync2(skillsRoot, { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => join3(skillsRoot, entry.name)).sort();
347
359
  }
348
360
  function readApiJson(path) {
349
- const fix = "reinstall the package, or run `dialecte skills generate` in its repository";
350
- let value;
351
- try {
352
- value = JSON.parse(readFileSync2(path, "utf8"));
353
- } catch (error) {
354
- throw new Error(
355
- `${path} is not a valid api index (${error instanceof Error ? error.message : String(error)}): ${fix}`
356
- );
357
- }
358
- if (!isApiJson(value))
359
- throw new Error(`${path} is not a valid api index (no package name or no method list): ${fix}`);
360
- return value;
361
+ const read = parseApiJson(path);
362
+ if ("index" in read) return read.index;
363
+ throw new Error(
364
+ `${path} is not a valid api index (${read.problem}): reinstall the package, or run \`dialecte skills generate\` in its repository`
365
+ );
361
366
  }
362
367
  function isApiJson(value) {
363
368
  return typeof value === "object" && value !== null && "package" in value && typeof value.package === "string" && "methods" in value && Array.isArray(value.methods);
@@ -523,6 +528,10 @@ import { basename as basename2, dirname as dirname3, isAbsolute as isAbsolute2,
523
528
  // src/lib/git.constants.ts
524
529
  var GIT_READ_ENVIRONMENT = { GIT_OPTIONAL_LOCKS: "0" };
525
530
 
531
+ // src/lib/worktree/worktree.constants.ts
532
+ var MINUTE_MS = 60 * 1e3;
533
+ var RECLAIM_DAY_MS = 24 * 60 * 60 * 1e3;
534
+
526
535
  // src/lib/git.ts
527
536
  function readGit(params) {
528
537
  const result = spawnSync("git", ["-c", "core.quotePath=false", ...params.args], {
@@ -558,12 +567,111 @@ function isInWorkTree(root) {
558
567
  return tryReadGit({ root, args: ["rev-parse", "--is-inside-work-tree"] })?.trim() === "true";
559
568
  }
560
569
 
561
- // src/lib/package-json.ts
570
+ // src/lib/gate/step-source.ts
562
571
  import { existsSync as existsSync3, readFileSync as readFileSync3 } from "fs";
563
572
  import { join as join5 } from "path";
573
+
574
+ // src/lib/gate/step-source.constants.ts
575
+ var DIALECTE_JSON_FILE = "dialecte.json";
576
+ var DIALECTE_JSON_SCHEMA = 1;
577
+ var DIALECTE_JSON_KEYS = ["schema", "gate"];
578
+ var INFERRED_TOOLS = [
579
+ {
580
+ label: "pyproject.toml + uv.lock",
581
+ files: ["pyproject.toml", "uv.lock"],
582
+ steps: {
583
+ fast: [{ name: "tests", run: "uv run pytest", counts: "tests" }],
584
+ full: [{ name: "tests", run: "uv run pytest", counts: "tests" }]
585
+ }
586
+ }
587
+ ];
588
+ var NO_STEP_SOURCE = 'no package.json and nothing to run: write a dialecte.json at the root ({ "gate": { "fast": [...], "full": [...] } }), or hold the files the gate infers its steps from: {tools}';
589
+ var INVALID_DIALECTE_JSON = "dialecte.json: {problem}";
590
+ var DIALECTE_JSON_PROBLEMS = {
591
+ notJson: "not valid JSON ({error})",
592
+ notAnObject: 'an object such as { "gate": { "fast": [...], "full": [...] } }',
593
+ unknownKey: 'unknown key "{key}" (only "schema" and "gate" are read)',
594
+ schema: '"schema" is 1',
595
+ gateNotAnObject: '"gate" is an object of step lists',
596
+ skip: '"gate.skip" opts out of a default npm step, and a repository without package.json has none: declare the lists instead',
597
+ missingList: 'no "{list}" list, and nothing to infer it from: declare it, or hold the files the gate infers its steps from: {tools}'
598
+ };
599
+
600
+ // src/lib/gate/step-source.ts
601
+ function readStepSource(root) {
602
+ const packagePath = join5(root, "package.json");
603
+ if (existsSync3(packagePath))
604
+ return {
605
+ origin: "package.json",
606
+ packageJson: JSON.parse(readFileSync3(packagePath, "utf8"))
607
+ };
608
+ const inferred = INFERRED_TOOLS.find(function holdsEveryFile(tool) {
609
+ return tool.files.every((file) => existsSync3(join5(root, file)));
610
+ });
611
+ const jsonPath = join5(root, DIALECTE_JSON_FILE);
612
+ if (!existsSync3(jsonPath))
613
+ return inferred ? {
614
+ origin: "inferred",
615
+ packageJson: gatePackageJson({
616
+ fast: [...inferred.steps.fast],
617
+ full: [...inferred.steps.full]
618
+ })
619
+ } : { refusal: NO_STEP_SOURCE.replace("{tools}", inferredToolsLabel()) };
620
+ const read = readDialecteJson(readFileSync3(jsonPath, "utf8"));
621
+ if ("refusal" in read) return read;
622
+ const gate = { ...read.gate };
623
+ for (const list of ["fast", "full"]) {
624
+ if (gate[list] !== void 0) continue;
625
+ if (inferred === void 0)
626
+ return {
627
+ refusal: INVALID_DIALECTE_JSON.replace(
628
+ "{problem}",
629
+ () => DIALECTE_JSON_PROBLEMS.missingList.replace("{list}", list).replace("{tools}", inferredToolsLabel())
630
+ )
631
+ };
632
+ gate[list] = [...inferred.steps[list]];
633
+ }
634
+ return { origin: "dialecte.json", packageJson: gatePackageJson(gate) };
635
+ }
636
+ function readDialecteJson(text) {
637
+ const problem = findDialecteJsonProblem(text);
638
+ return typeof problem === "string" ? { refusal: INVALID_DIALECTE_JSON.replace("{problem}", () => problem) } : problem;
639
+ }
640
+ function findDialecteJsonProblem(text) {
641
+ let value;
642
+ try {
643
+ value = JSON.parse(text);
644
+ } catch (error) {
645
+ return DIALECTE_JSON_PROBLEMS.notJson.replace("{error}", () => error.message);
646
+ }
647
+ if (!isObject(value)) return DIALECTE_JSON_PROBLEMS.notAnObject;
648
+ const unknownKey = Object.keys(value).find((key) => !DIALECTE_JSON_KEYS.includes(key));
649
+ if (unknownKey !== void 0)
650
+ return DIALECTE_JSON_PROBLEMS.unknownKey.replace("{key}", unknownKey);
651
+ if (value.schema !== void 0 && value.schema !== DIALECTE_JSON_SCHEMA)
652
+ return DIALECTE_JSON_PROBLEMS.schema;
653
+ if (value.gate !== void 0 && !isObject(value.gate))
654
+ return DIALECTE_JSON_PROBLEMS.gateNotAnObject;
655
+ if (isObject(value.gate) && value.gate.skip !== void 0) return DIALECTE_JSON_PROBLEMS.skip;
656
+ return value;
657
+ }
658
+ function isObject(value) {
659
+ return typeof value === "object" && value !== null && !Array.isArray(value);
660
+ }
661
+ function gatePackageJson(gate) {
662
+ return { dialecte: { gate } };
663
+ }
664
+ function inferredToolsLabel() {
665
+ return INFERRED_TOOLS.map(function toolLabel(tool) {
666
+ const commands = [...new Set(tool.steps.full.map((step) => step.run))];
667
+ return `${tool.label} (${commands.join(", ")})`;
668
+ }).join("; ");
669
+ }
670
+
671
+ // src/lib/package-json.ts
564
672
  function readPackageJson(root) {
565
- const path = join5(root, "package.json");
566
- return existsSync3(path) ? JSON.parse(readFileSync3(path, "utf8")) : {};
673
+ const source = readStepSource(root);
674
+ return "refusal" in source ? {} : source.packageJson;
567
675
  }
568
676
 
569
677
  // src/lib/process-alive.ts
@@ -763,6 +871,46 @@ import { join as join18 } from "path";
763
871
 
764
872
  // src/lib/tdd/tdd.constants.ts
765
873
  var TEST_FILE_PATTERN = /\.(test|spec)\.[cm]?[jt]sx?$/;
874
+ var NODE_EVENT_TYPES = {
875
+ start: "test:start",
876
+ pass: "test:pass",
877
+ fail: "test:fail",
878
+ stderr: "test:stderr"
879
+ };
880
+ var NODE_TEST_EVENT_TYPES = [
881
+ NODE_EVENT_TYPES.start,
882
+ NODE_EVENT_TYPES.pass,
883
+ NODE_EVENT_TYPES.fail
884
+ ];
885
+ var BASE_COPY_PYTEST_ARGUMENTS = [
886
+ "-c",
887
+ [
888
+ "import os, sys",
889
+ "folder = sys.argv[1]",
890
+ 'current = {"", os.getcwd(), folder}',
891
+ "sys.path[:] = [folder] + [entry for entry in sys.path if entry not in current]",
892
+ 'sys.argv = ["pytest"] + sys.argv[2:]',
893
+ "try:",
894
+ " import pytest",
895
+ "except ImportError:",
896
+ ' sys.exit("No module named pytest")',
897
+ "sys.exit(pytest.console_main())"
898
+ ].join("\n")
899
+ ];
900
+ var EDITABLE_PROBE_SCRIPT = [
901
+ "import json, sys",
902
+ "from importlib import metadata",
903
+ "try:",
904
+ " found = metadata.distribution(sys.argv[1])",
905
+ "except metadata.PackageNotFoundError:",
906
+ " sys.exit(0)",
907
+ 'direct = json.loads(found.read_text("direct_url.json") or "{}")',
908
+ "paths = [str(path) for path in (found.files or [])]",
909
+ 'editable = direct.get("dir_info", {}).get("editable") or any(',
910
+ ' "__editable__" in path or path.endswith(".pth") for path in paths',
911
+ ")",
912
+ 'print("editable" if editable else "installed")'
913
+ ].join("\n");
766
914
 
767
915
  // src/lib/discover.constants.ts
768
916
  import ts from "typescript";
@@ -1273,6 +1421,11 @@ import { existsSync as existsSync12, readFileSync as readFileSync9 } from "fs";
1273
1421
  import { dirname as dirname10, join as join16 } from "path";
1274
1422
  import { fileURLToPath } from "url";
1275
1423
  function readCliVersion(params = {}) {
1424
+ const folder = findPackageFolder(params);
1425
+ const { version } = JSON.parse(readFileSync9(join16(folder, "package.json"), "utf8"));
1426
+ return version;
1427
+ }
1428
+ function findPackageFolder(params = {}) {
1276
1429
  const startFolder = params.startFolder ?? dirname10(fileURLToPath(import.meta.url));
1277
1430
  let folder = startFolder;
1278
1431
  while (!existsSync12(join16(folder, "package.json"))) {
@@ -1281,8 +1434,7 @@ function readCliVersion(params = {}) {
1281
1434
  throw new Error(`no package.json above ${startFolder}: cannot read the cli version`);
1282
1435
  folder = parent;
1283
1436
  }
1284
- const { version } = JSON.parse(readFileSync9(join16(folder, "package.json"), "utf8"));
1285
- return version;
1437
+ return folder;
1286
1438
  }
1287
1439
 
1288
1440
  // src/lib/api/source-index.ts
@@ -2939,10 +3091,2162 @@ async function readSchemaDialectes(params) {
2939
3091
  }
2940
3092
  };
2941
3093
  }
3094
+
3095
+ // src/lib/knowledge/ask/load-standard-indexes.ts
3096
+ import { createHash as createHash5 } from "crypto";
3097
+ import { readFileSync as readFileSync18 } from "fs";
3098
+
3099
+ // src/lib/knowledge/standard/ensure-standard-index.ts
3100
+ import { createHash as createHash2 } from "crypto";
3101
+ import { existsSync as existsSync22, readdirSync as readdirSync11, readFileSync as readFileSync16, renameSync as renameSync5, rmSync as rmSync5 } from "fs";
3102
+ import { join as join27 } from "path";
3103
+
3104
+ // src/lib/progress/format-duration.ts
3105
+ function formatDuration(milliseconds) {
3106
+ const seconds = milliseconds / 1e3;
3107
+ if (seconds < 10) return `${seconds.toFixed(1)} s`;
3108
+ if (seconds < 60) return `${Math.floor(seconds)} s`;
3109
+ const minutes = Math.floor(seconds / 60);
3110
+ if (minutes < 60) return `${minutes} m ${Math.floor(seconds % 60)} s`;
3111
+ return `${Math.floor(minutes / 60)} h ${minutes % 60} m`;
3112
+ }
3113
+
3114
+ // src/lib/knowledge/standard/fill-message.constants.ts
3115
+ var PLACEHOLDER_PATTERN = /\{([^{}]+)\}/g;
3116
+
3117
+ // src/lib/knowledge/standard/fill-message.ts
3118
+ function fillMessage(params) {
3119
+ const { template, values } = params;
3120
+ return template.replace(
3121
+ PLACEHOLDER_PATTERN,
3122
+ function valueOf(placeholder, name) {
3123
+ return Object.hasOwn(values, name) ? values[name] : placeholder;
3124
+ }
3125
+ );
3126
+ }
3127
+
3128
+ // src/lib/knowledge/standard/standard-index.constants.ts
3129
+ var CAPTION_WORDS = {
3130
+ table: ["Ta", "ble"].join(""),
3131
+ figure: ["Fig", "ure"].join("")
3132
+ };
3133
+ var ANNEX_WORD = ["An", "nex"].join("");
3134
+ var CLAUSE_WORD = ["cla", "use"].join("");
3135
+ var SUBCLAUSE_PREFIX = "sub";
3136
+ function eitherCaseFirst(word) {
3137
+ return `[${word.charAt(0).toUpperCase()}${word.charAt(0).toLowerCase()}]${word.slice(1)}`;
3138
+ }
3139
+ var NUMBERED_HEADING_PATTERN = /^(\d+(?:\.\d+)*)\.?\s+(\S.*)$/u;
3140
+ var ANNEX_SUB_HEADING_PATTERN = /^([A-Z](?:\.\d+)+)\.?\s+(\S.*)$/u;
3141
+ var ANNEX_HEADING_PATTERN = new RegExp(
3142
+ `^${ANNEX_WORD}\\s+([A-Z])(?![\\p{L}\\p{N}_.])\\s*(.*)$`,
3143
+ "u"
3144
+ );
3145
+ var QUALIFIER_BEFORE_PATTERN = new RegExp("^\\(\\s*\\p{Ll}+\\s*\\)\\s*", "u");
3146
+ var QUALIFIER_AFTER_PATTERN = new RegExp("\\s*\\(\\s*\\p{Ll}+\\s*\\)$", "u");
3147
+ var CAPITAL_START_PATTERN = new RegExp("^\\p{Lu}", "u");
3148
+ var TITLE_LENGTH_LIMIT = 120;
3149
+ var TOP_LEVEL_NUMBER_LIMIT = 50;
3150
+ var TOP_LEVEL_JUMP_LIMIT = 3;
3151
+ var DIGITS_PATTERN = /^\d+$/;
3152
+ var LETTER_ORDER_BASE = 1e9;
3153
+ var DOT_LEADER_PATTERN = /\.{4,}|(?:\. ){3,}/;
3154
+ var DEFINITION_PATTERN = /^(\d+)((?:\.\d+)+)\.?(?:\s+(.*))?$/u;
3155
+ var TERMS_TITLE_PATTERN = /^terms(?![\p{L}\p{N}_])/iu;
3156
+ var CAPTION_PATTERN = new RegExp(
3157
+ `^(${CAPTION_WORDS.table}|${CAPTION_WORDS.figure})\\s+([A-Z]\\.\\d+|\\d+)(?:\\s*[-\\u2013\\u2014:.].*)?$`,
3158
+ "u"
3159
+ );
3160
+ var TABLE_SEPARATOR_ROW_PATTERN = /^\|?\s*:?-+:?\s*(?:\|\s*:?-+:?\s*)*\|?$/;
3161
+ var LEADING_MARKERS_PATTERN = /^(?:#+(?=\s|$)\s*|>\s*)+/;
3162
+ var HEADING_MARKER_PATTERN = /^#+(?=\s|$)/u;
3163
+ var LIST_ITEM_PATTERN = /^\d+\.\s/u;
3164
+ var WRAPPING_MARKERS = ["**", "__"];
3165
+ var FENCE_MARKER = "```";
3166
+ var TABLE_LINE_START = "|";
3167
+ var TABLE_ROW_START_PIPE_PATTERN = /^\|/;
3168
+ var TABLE_ROW_END_PIPE_PATTERN = /\|$/;
3169
+ var CODE_LINE_START = "<";
3170
+ var LETTER_SPACED_MINIMUM_TOKENS = 4;
3171
+ var LETTER_SPACED_MINIMUM_SHARE = 0.8;
3172
+ var WIDE_GAP_PATTERN = /\s{2,}/;
3173
+ var WHITESPACE_PATTERN = /\s+/;
3174
+ var NOISE_RUN_MINIMUM = 20;
3175
+ var REPEATED_MINIMUM_COUNT = 20;
3176
+ var REPEATED_MINIMUM_MEDIAN_GAP = 20;
3177
+ var REPEATED_MINIMUM_LENGTH = 2;
3178
+ var QUALITY_BLOCK_LINES = 1e3;
3179
+ var GOOD_NOISE_RATIO_LIMIT = 0.2;
3180
+ var POOR_NOISE_RATIO_LIMIT = 0.7;
3181
+ var CAPTION_LOOKBACK_LINES = 5;
3182
+ var SPLIT_WORD_END_PATTERN = new RegExp("\\p{L}-$", "u");
3183
+ var LOWER_CASE_START_PATTERN = new RegExp("^\\p{Ll}", "u");
3184
+ var CROSS_REFERENCE_PATTERN = new RegExp(
3185
+ [
3186
+ "(?<![\\p{L}\\p{N}_])(?:",
3187
+ `(?:${eitherCaseFirst(SUBCLAUSE_PREFIX)})?${eitherCaseFirst(CLAUSE_WORD)}\\s+(?<clause>[A-Z](?:\\.\\d+)+|\\d+(?:\\.\\d+)*)`,
3188
+ "|[Ss]ee\\s+(?<see>\\d+(?:\\.\\d+)+)",
3189
+ "|\\((?<parenthesised>\\d+\\.\\d+\\.\\d+(?:\\.\\d+)*)\\)",
3190
+ `|${eitherCaseFirst(CAPTION_WORDS.table)}\\s+(?<table>[A-Z]\\.\\d+|\\d+)(?![\\p{L}\\p{N}_])`,
3191
+ `|${eitherCaseFirst(ANNEX_WORD)}\\s+(?<annex>[A-Z])(?![\\p{L}\\p{N}_])`,
3192
+ ")"
3193
+ ].join(""),
3194
+ "gu"
3195
+ );
3196
+ var TABLE_TARGET_PREFIX = "table-";
3197
+ var DASH_PATTERN = /[‒–—−]/g;
3198
+ var SINGLE_QUOTE_PATTERN = /[‘’‚‛]/g;
3199
+ var DOUBLE_QUOTE_PATTERN = /[“”„‟]/g;
3200
+ var SOFT_HYPHEN_PATTERN = /­/g;
3201
+ var WHITESPACE_RUN_PATTERN = /\s+/g;
3202
+ var LINE_BREAK_PATTERN = /\r?\n/;
3203
+
3204
+ // src/lib/knowledge/standard/assess-quality.ts
3205
+ function assessQuality(params) {
3206
+ const { lines, noise, candidates, kept, repeatedLines } = params;
3207
+ const blocks = [];
3208
+ for (let start = 0; start < lines.length; start += QUALITY_BLOCK_LINES)
3209
+ blocks.push(blockOf({ noise, start, end: Math.min(start + QUALITY_BLOCK_LINES, lines.length) }));
3210
+ const droppedLines = noise.filter(Boolean).length;
3211
+ const blankLines = lines.filter((line) => line.kind === "blank").length;
3212
+ return {
3213
+ blocks,
3214
+ verdict: fileVerdictOf(blocks),
3215
+ readableLines: lines.length - blankLines - droppedLines,
3216
+ droppedLines,
3217
+ headingCandidatesKept: kept,
3218
+ headingCandidatesTurnedProse: candidates - kept,
3219
+ repeatedLines
3220
+ };
3221
+ }
3222
+ function blockOf(params) {
3223
+ const { noise, start, end } = params;
3224
+ const lines = end - start;
3225
+ const dropped = noise.slice(start, end).filter(Boolean).length;
3226
+ const noiseRatio = dropped / lines;
3227
+ return {
3228
+ from: start + 1,
3229
+ to: end,
3230
+ lines,
3231
+ dropped,
3232
+ noiseRatio,
3233
+ verdict: blockVerdictOf(noiseRatio)
3234
+ };
3235
+ }
3236
+ function blockVerdictOf(noiseRatio) {
3237
+ if (noiseRatio < GOOD_NOISE_RATIO_LIMIT) return "good";
3238
+ if (noiseRatio < POOR_NOISE_RATIO_LIMIT) return "poor";
3239
+ return "unreadable";
3240
+ }
3241
+ function fileVerdictOf(blocks) {
3242
+ if (blocks.every((block) => block.verdict === "good")) return "good";
3243
+ if (blocks.every((block) => block.verdict === "unreadable")) return "unreadable";
3244
+ return "partial";
3245
+ }
3246
+
3247
+ // src/lib/knowledge/standard/parse-caption.ts
3248
+ function parseCaption(content) {
3249
+ const match = CAPTION_PATTERN.exec(content);
3250
+ if (!match) return null;
3251
+ return { word: match[1] === CAPTION_WORDS.table ? "table" : "figure", number: match[2] };
3252
+ }
3253
+
3254
+ // src/lib/knowledge/standard/normalise-text.ts
3255
+ function normaliseText(text) {
3256
+ return text.normalize("NFKC").replace(SOFT_HYPHEN_PATTERN, "").replace(DASH_PATTERN, "-").replace(SINGLE_QUOTE_PATTERN, "'").replace(DOUBLE_QUOTE_PATTERN, '"').replace(WHITESPACE_RUN_PATTERN, " ").trim();
3257
+ }
3258
+
3259
+ // src/lib/knowledge/standard/parse-heading-candidate.ts
3260
+ function parseHeadingCandidate(params) {
3261
+ const { content, line } = params;
3262
+ const annex = ANNEX_HEADING_PATTERN.exec(content);
3263
+ if (annex) {
3264
+ const title = annex[2].replace(QUALIFIER_BEFORE_PATTERN, "").replace(QUALIFIER_AFTER_PATTERN, "");
3265
+ return candidateOf({ line, number: annex[1], title });
3266
+ }
3267
+ const numbered = NUMBERED_HEADING_PATTERN.exec(content) ?? ANNEX_SUB_HEADING_PATTERN.exec(content);
3268
+ if (!numbered) return null;
3269
+ return candidateOf({ line, number: numbered[1], title: numbered[2] });
3270
+ }
3271
+ function candidateOf(params) {
3272
+ const { line, number } = params;
3273
+ const title = params.title.trim();
3274
+ if (title.length === 0 || title.length >= TITLE_LENGTH_LIMIT) return null;
3275
+ if (!CAPITAL_START_PATTERN.test(title)) return null;
3276
+ const parts = number.split(".");
3277
+ const top = DIGITS_PATTERN.test(parts[0]) ? Number(parts[0]) : null;
3278
+ if (top !== null && top > TOP_LEVEL_NUMBER_LIMIT) return null;
3279
+ return {
3280
+ line,
3281
+ number,
3282
+ title: normaliseText(title),
3283
+ depth: parts.length,
3284
+ order: parts.map(orderOfPart),
3285
+ top
3286
+ };
3287
+ }
3288
+ function orderOfPart(part) {
3289
+ return DIGITS_PATTERN.test(part) ? Number(part) : LETTER_ORDER_BASE + part.charCodeAt(0);
3290
+ }
3291
+
3292
+ // src/lib/knowledge/standard/classify-standard-lines.ts
3293
+ function classifyStandardLines(params) {
3294
+ const asCandidates = classifyAll({ lines: params.lines, listItems: false });
3295
+ const otherStyle = asCandidates.some(
3296
+ (classified, index) => classified.candidate?.depth === 1 && classified.candidate.top !== null && (HEADING_MARKER_PATTERN.test(params.lines[index].trim()) || !LIST_ITEM_PATTERN.test(classified.content))
3297
+ );
3298
+ return otherStyle ? classifyAll({ lines: params.lines, listItems: true }) : asCandidates;
3299
+ }
3300
+ function classifyAll(params) {
3301
+ const classified = [];
3302
+ let state = {
3303
+ inFence: false,
3304
+ termsClause: null,
3305
+ listItems: params.listItems
3306
+ };
3307
+ for (const [index, original] of params.lines.entries()) {
3308
+ const next = classifyLine({ original, line: index + 1, state });
3309
+ classified.push(next.classified);
3310
+ state = next.state;
3311
+ }
3312
+ return classified;
3313
+ }
3314
+ function classifyLine(params) {
3315
+ const { line, state } = params;
3316
+ const trimmed = params.original.trim();
3317
+ if (state.inFence || trimmed.startsWith(FENCE_MARKER)) {
3318
+ const inFence = trimmed.startsWith(FENCE_MARKER) ? !state.inFence : state.inFence;
3319
+ return {
3320
+ classified: lineOf({ line, content: trimmed, kind: "code" }),
3321
+ state: { ...state, inFence }
3322
+ };
3323
+ }
3324
+ if (trimmed.startsWith(TABLE_LINE_START))
3325
+ return { classified: lineOf({ line, content: trimmed, kind: "table" }), state };
3326
+ if (trimmed.startsWith(CODE_LINE_START))
3327
+ return { classified: lineOf({ line, content: trimmed, kind: "code" }), state };
3328
+ const content = stripMarkdownMarkers(trimmed);
3329
+ if (content.length === 0) return { classified: lineOf({ line, content, kind: "blank" }), state };
3330
+ const listItems = state.listItems && !HEADING_MARKER_PATTERN.test(trimmed);
3331
+ const classified = classifyContent({ content, line, termsClause: state.termsClause, listItems });
3332
+ const settled = classified.kind === "prose" && !classified.listItem && isLetterSpaced(content) ? classifyRebuilt({ content: rebuildLetterSpaced(content), line, state, listItems }) : classified;
3333
+ if (settled.candidate?.depth !== 1) return { classified: settled, state };
3334
+ const termsClause = TERMS_TITLE_PATTERN.test(settled.candidate.title) ? settled.candidate.number : null;
3335
+ return { classified: settled, state: { ...state, termsClause } };
3336
+ }
3337
+ function classifyRebuilt(params) {
3338
+ const { content, line, state, listItems } = params;
3339
+ if (content.startsWith(CODE_LINE_START)) return lineOf({ line, content, kind: "code" });
3340
+ return classifyContent({ content, line, termsClause: state.termsClause, listItems });
3341
+ }
3342
+ function classifyContent(params) {
3343
+ const { content, line, termsClause } = params;
3344
+ if (DOT_LEADER_PATTERN.test(content) && isHeadingShaped(content))
3345
+ return lineOf({ line, content, kind: "toc" });
3346
+ if (parseCaption(content)) return lineOf({ line, content, kind: "caption" });
3347
+ if (termsClause !== null) {
3348
+ const definition = DEFINITION_PATTERN.exec(content);
3349
+ if (definition && definition[1] === termsClause)
3350
+ return {
3351
+ ...lineOf({ line, content, kind: "definition" }),
3352
+ definition: { number: `${definition[1]}${definition[2]}`, term: definition[3] ?? "" }
3353
+ };
3354
+ }
3355
+ const candidate = parseHeadingCandidate({ content, line });
3356
+ if (params.listItems && LIST_ITEM_PATTERN.test(content))
3357
+ return { ...lineOf({ line, content, kind: "prose" }), listItem: candidate !== null };
3358
+ if (candidate) return { ...lineOf({ line, content, kind: "heading" }), candidate };
3359
+ return lineOf({ line, content, kind: "prose" });
3360
+ }
3361
+ function lineOf(params) {
3362
+ return { ...params, candidate: null, definition: null, listItem: false };
3363
+ }
3364
+ function stripMarkdownMarkers(trimmed) {
3365
+ const unmarked = trimmed.replace(LEADING_MARKERS_PATTERN, "");
3366
+ for (const marker of WRAPPING_MARKERS)
3367
+ if (unmarked.length > marker.length * 2 && unmarked.startsWith(marker) && unmarked.endsWith(marker))
3368
+ return unmarked.slice(marker.length, -marker.length).trim();
3369
+ return unmarked;
3370
+ }
3371
+ function isHeadingShaped(content) {
3372
+ return ANNEX_HEADING_PATTERN.test(content) || NUMBERED_HEADING_PATTERN.test(content) || ANNEX_SUB_HEADING_PATTERN.test(content);
3373
+ }
3374
+ function isLetterSpaced(content) {
3375
+ const tokens = content.split(WHITESPACE_PATTERN);
3376
+ if (tokens.length < LETTER_SPACED_MINIMUM_TOKENS) return false;
3377
+ const single = tokens.filter((token) => token.length === 1).length;
3378
+ return single >= tokens.length * LETTER_SPACED_MINIMUM_SHARE;
3379
+ }
3380
+ function rebuildLetterSpaced(content) {
3381
+ return content.split(WIDE_GAP_PATTERN).map((word) => word.split(WHITESPACE_PATTERN).join("")).join(" ");
3382
+ }
3383
+
3384
+ // src/lib/knowledge/standard/find-repeated-lines.ts
3385
+ function findRepeatedLines(params) {
3386
+ const occurrences = /* @__PURE__ */ new Map();
3387
+ for (const [index, original] of params.lines.entries()) {
3388
+ const text = original.trim();
3389
+ if (text.length < REPEATED_MINIMUM_LENGTH) continue;
3390
+ const seen = occurrences.get(text);
3391
+ if (seen) seen.push(index + 1);
3392
+ else occurrences.set(text, [index + 1]);
3393
+ }
3394
+ const repeated = [];
3395
+ for (const [text, lineNumbers] of occurrences) {
3396
+ if (lineNumbers.length < REPEATED_MINIMUM_COUNT) continue;
3397
+ if (TABLE_SEPARATOR_ROW_PATTERN.test(text)) continue;
3398
+ const medianGap = lowerMedianGap(lineNumbers);
3399
+ if (medianGap < REPEATED_MINIMUM_MEDIAN_GAP) continue;
3400
+ repeated.push({ text, count: lineNumbers.length, length: text.length, medianGap });
3401
+ }
3402
+ return repeated.sort(
3403
+ (first, second) => second.count - first.count || (first.text < second.text ? -1 : first.text > second.text ? 1 : 0)
3404
+ );
3405
+ }
3406
+ function lowerMedianGap(lineNumbers) {
3407
+ const gaps = lineNumbers.slice(1).map((lineNumber, index) => lineNumber - lineNumbers[index]).sort((first, second) => first - second);
3408
+ return gaps[Math.floor((gaps.length - 1) / 2)];
3409
+ }
3410
+
3411
+ // src/lib/knowledge/standard/join-logical-lines.ts
3412
+ function joinLogicalLines(params) {
3413
+ const logicalLines = [];
3414
+ let paragraph = [];
3415
+ for (const [index, line] of params.lines.entries()) {
3416
+ if (params.noise[index]) continue;
3417
+ if (line.kind === "prose") {
3418
+ paragraph.push(line);
3419
+ continue;
3420
+ }
3421
+ if (paragraph.length > 0) logicalLines.push(paragraphOf(paragraph));
3422
+ paragraph = [];
3423
+ if (line.kind !== "blank")
3424
+ logicalLines.push({
3425
+ from: line.line,
3426
+ to: line.line,
3427
+ kind: line.kind,
3428
+ text: normaliseText(line.content)
3429
+ });
3430
+ }
3431
+ if (paragraph.length > 0) logicalLines.push(paragraphOf(paragraph));
3432
+ return logicalLines;
3433
+ }
3434
+ function paragraphOf(lines) {
3435
+ const pieces = [lines[0].content];
3436
+ for (const [index, line] of lines.entries()) {
3437
+ if (index === 0) continue;
3438
+ const previous = pieces[pieces.length - 1];
3439
+ if (SPLIT_WORD_END_PATTERN.test(previous) && LOWER_CASE_START_PATTERN.test(line.content))
3440
+ pieces[pieces.length - 1] = `${previous.slice(0, -1)}${line.content}`;
3441
+ else pieces.push(line.content);
3442
+ }
3443
+ const text = pieces.join(" ");
3444
+ return {
3445
+ from: lines[0].line,
3446
+ to: lines[lines.length - 1].line,
3447
+ kind: "prose",
3448
+ text: normaliseText(text)
3449
+ };
3450
+ }
3451
+
3452
+ // src/lib/knowledge/standard/mark-noise-lines.ts
3453
+ function markNoiseLines(params) {
3454
+ const runs = droppedRunsOf(params.lines);
3455
+ const dropped = params.lines.map(() => false);
3456
+ for (const run of runs) for (const index of run) dropped[index] = true;
3457
+ return {
3458
+ dropped,
3459
+ ranges: runs.map((run) => ({ from: run[0] + 1, to: run[run.length - 1] + 1 }))
3460
+ };
3461
+ }
3462
+ function droppedRunsOf(lines) {
3463
+ const runs = [];
3464
+ let run = [];
3465
+ for (const [index, line] of lines.entries()) {
3466
+ if (line.kind === "blank") continue;
3467
+ if (line.kind === "prose" && line.content.length === 1) {
3468
+ run.push(index);
3469
+ continue;
3470
+ }
3471
+ if (run.length >= NOISE_RUN_MINIMUM) runs.push(run);
3472
+ run = [];
3473
+ }
3474
+ if (run.length >= NOISE_RUN_MINIMUM) runs.push(run);
3475
+ return runs;
3476
+ }
3477
+
3478
+ // src/lib/knowledge/standard/holding-clause.ts
3479
+ function holdingClause(params) {
3480
+ const { headings, line } = params;
3481
+ let low = 0;
3482
+ let high = headings.length - 1;
3483
+ let found = null;
3484
+ while (low <= high) {
3485
+ const middle = low + high >> 1;
3486
+ if (headings[middle].from <= line) {
3487
+ found = headings[middle];
3488
+ low = middle + 1;
3489
+ } else high = middle - 1;
3490
+ }
3491
+ return found?.number ?? null;
3492
+ }
3493
+
3494
+ // src/lib/knowledge/standard/read-cross-references.ts
3495
+ function readCrossReferences(params) {
3496
+ const { lines, noise, headings, tables } = params;
3497
+ const headingNumbers = new Set(headings.map((heading) => heading.number));
3498
+ const tableTargets = new Set(
3499
+ tables.flatMap((table) => table.number === null ? [] : [TABLE_TARGET_PREFIX + table.number])
3500
+ );
3501
+ const references = [];
3502
+ for (const [index, line] of lines.entries()) {
3503
+ if (noise[index] || !isScanned(line)) continue;
3504
+ for (const target of targetsOf(normaliseText(line.content)))
3505
+ references.push({
3506
+ from: line.line,
3507
+ inClause: holdingClause({ headings, line: line.line }),
3508
+ target,
3509
+ resolved: headingNumbers.has(target) || tableTargets.has(target)
3510
+ });
3511
+ }
3512
+ return references;
3513
+ }
3514
+ function isScanned(line) {
3515
+ return line.kind === "prose" || line.kind === "definition" || line.kind === "table";
3516
+ }
3517
+ function targetsOf(text) {
3518
+ const targets = [];
3519
+ for (const match of text.matchAll(CROSS_REFERENCE_PATTERN)) {
3520
+ const { clause, see, parenthesised, table, annex } = match.groups ?? {};
3521
+ if (table !== void 0) targets.push(TABLE_TARGET_PREFIX + table);
3522
+ else {
3523
+ const target = clause ?? see ?? parenthesised ?? annex;
3524
+ if (target !== void 0) targets.push(target);
3525
+ }
3526
+ }
3527
+ return targets;
3528
+ }
3529
+
3530
+ // src/lib/knowledge/standard/read-definitions.ts
3531
+ function readDefinitions(params) {
3532
+ const { lines, noise } = params;
3533
+ const definitions = [];
3534
+ for (const [index, line] of lines.entries()) {
3535
+ if (!line.definition || noise[index]) continue;
3536
+ definitions.push({
3537
+ term: normaliseText(line.definition.term) || termBelow({ lines, noise, index }),
3538
+ number: line.definition.number,
3539
+ from: line.line,
3540
+ to: endOf({ lines, index })
3541
+ });
3542
+ }
3543
+ return definitions;
3544
+ }
3545
+ function termBelow(params) {
3546
+ const { lines, noise, index } = params;
3547
+ for (let next = index + 1; next < lines.length; next++)
3548
+ if (lines[next].kind !== "blank" && !noise[next]) return normaliseText(lines[next].content);
3549
+ return "";
3550
+ }
3551
+ function endOf(params) {
3552
+ const { lines, index } = params;
3553
+ for (let next = index + 1; next < lines.length; next++)
3554
+ if (lines[next].definition || lines[next].candidate?.depth === 1) return lines[next].line - 1;
3555
+ return lines.length;
3556
+ }
3557
+
3558
+ // src/lib/knowledge/standard/read-headings.ts
3559
+ function readHeadings(params) {
3560
+ const { fileId, kept, lineCount } = params;
3561
+ const ids = kept.map((candidate) => idOf({ fileId, candidate }));
3562
+ const lastIdAtDepth = /* @__PURE__ */ new Map();
3563
+ return kept.map((candidate, index) => {
3564
+ const parent = lastIdAtDepth.get(`${candidate.pass}:${candidate.depth - 1}`) ?? null;
3565
+ lastIdAtDepth.set(`${candidate.pass}:${candidate.depth}`, ids[index]);
3566
+ return {
3567
+ id: ids[index],
3568
+ number: candidate.number,
3569
+ title: candidate.title,
3570
+ from: candidate.line,
3571
+ to: endOf2({ kept, index, lineCount }),
3572
+ depth: candidate.depth,
3573
+ parent,
3574
+ pass: candidate.pass
3575
+ };
3576
+ });
3577
+ }
3578
+ function idOf(params) {
3579
+ const { fileId, candidate } = params;
3580
+ const suffix = candidate.pass === 1 ? "" : `~${candidate.pass}`;
3581
+ return `${fileId}#${candidate.number}${suffix}`;
3582
+ }
3583
+ function endOf2(params) {
3584
+ const { kept, index, lineCount } = params;
3585
+ const depth = kept[index].depth;
3586
+ for (let next = index + 1; next < kept.length; next++)
3587
+ if (kept[next].depth <= depth) return kept[next].line - 1;
3588
+ return lineCount;
3589
+ }
3590
+
3591
+ // src/lib/knowledge/standard/cells-of-row.ts
3592
+ function cellsOfRow(row) {
3593
+ const inner = row.trim().replace(TABLE_ROW_START_PIPE_PATTERN, "").replace(TABLE_ROW_END_PIPE_PATTERN, "");
3594
+ return inner.split(TABLE_LINE_START).map((cell) => cell.trim());
3595
+ }
3596
+
3597
+ // src/lib/knowledge/standard/find-caption-above.ts
3598
+ function findCaptionAbove(params) {
3599
+ const { logicalLines, start } = params;
3600
+ const first = Math.max(0, start - CAPTION_LOOKBACK_LINES);
3601
+ for (let index = start - 1; index >= first; index--) {
3602
+ const line = logicalLines[index];
3603
+ if (line.kind === "table") return null;
3604
+ if (line.kind !== "caption") continue;
3605
+ if (parseCaption(line.text)?.word === "table") return index;
3606
+ }
3607
+ return null;
3608
+ }
3609
+
3610
+ // src/lib/knowledge/standard/read-tables.ts
3611
+ function readTables(params) {
3612
+ const { fileId, logicalLines, headings } = params;
3613
+ const tables = [];
3614
+ let start = -1;
3615
+ for (const [index, line] of logicalLines.entries()) {
3616
+ if (line.kind !== "table") continue;
3617
+ if (start === -1) start = index;
3618
+ const next = logicalLines[index + 1];
3619
+ if (next?.kind === "table" && next.from === line.to + 1) continue;
3620
+ tables.push(
3621
+ tableOf({
3622
+ fileId,
3623
+ logicalLines,
3624
+ headings,
3625
+ start,
3626
+ end: index,
3627
+ position: tables.length + 1
3628
+ })
3629
+ );
3630
+ start = -1;
3631
+ }
3632
+ return tables;
3633
+ }
3634
+ function tableOf(params) {
3635
+ const { fileId, logicalLines, headings, start, end, position } = params;
3636
+ const rows = logicalLines.slice(start, end + 1);
3637
+ const captionIndex = findCaptionAbove({ logicalLines, start });
3638
+ const caption = captionIndex === null ? null : logicalLines[captionIndex].text;
3639
+ const header = rows.find((row) => !TABLE_SEPARATOR_ROW_PATTERN.test(row.text));
3640
+ return {
3641
+ id: `${fileId}#table-${position}`,
3642
+ caption,
3643
+ number: caption === null ? null : parseCaption(caption)?.number ?? null,
3644
+ from: rows[0].from,
3645
+ to: rows[rows.length - 1].to,
3646
+ clause: holdingClause({ headings, line: rows[0].from }),
3647
+ columns: header ? cellsOfRow(header.text) : []
3648
+ };
3649
+ }
3650
+
3651
+ // src/lib/knowledge/standard/select-headings.ts
3652
+ function selectHeadings(params) {
3653
+ return passesOf(params.candidates).flatMap(
3654
+ (pass, index) => longestSequence(pass).map((candidate) => ({ ...candidate, pass: index + 1 }))
3655
+ );
3656
+ }
3657
+ function passesOf(candidates) {
3658
+ const passes = [[]];
3659
+ let holdsOne = false;
3660
+ for (const candidate of candidates) {
3661
+ if (candidate.number === "1") {
3662
+ if (holdsOne) passes.push([]);
3663
+ holdsOne = true;
3664
+ }
3665
+ passes[passes.length - 1].push(candidate);
3666
+ }
3667
+ return passes;
3668
+ }
3669
+ function longestSequence(candidates) {
3670
+ if (candidates.length === 0) return [];
3671
+ const lengths = candidates.map(() => 1);
3672
+ for (let from = candidates.length - 1; from >= 0; from--)
3673
+ for (let to = from + 1; to < candidates.length; to++)
3674
+ if (lengths[to] + 1 > lengths[from] && isValidStep({ from: candidates[from], to: candidates[to] }))
3675
+ lengths[from] = lengths[to] + 1;
3676
+ const longest = lengths.reduce((maximum, length) => Math.max(maximum, length), 0);
3677
+ let current = lengths.indexOf(longest);
3678
+ const sequence = [candidates[current]];
3679
+ while (lengths[current] > 1) {
3680
+ const remaining = lengths[current] - 1;
3681
+ let next = current + 1;
3682
+ while (!(lengths[next] === remaining && isValidStep({ from: candidates[current], to: candidates[next] })))
3683
+ next++;
3684
+ sequence.push(candidates[next]);
3685
+ current = next;
3686
+ }
3687
+ return sequence;
3688
+ }
3689
+ function isValidStep(params) {
3690
+ const { from, to } = params;
3691
+ if (compareTreeOrder({ first: from.order, second: to.order }) >= 0) return false;
3692
+ if (to.depth > from.depth + 1) return false;
3693
+ if (from.top !== null && to.top !== null) return to.top - from.top <= TOP_LEVEL_JUMP_LIMIT;
3694
+ return true;
3695
+ }
3696
+ function compareTreeOrder(params) {
3697
+ const { first, second } = params;
3698
+ const shared = Math.min(first.length, second.length);
3699
+ for (let part = 0; part < shared; part++)
3700
+ if (first[part] !== second[part]) return first[part] - second[part];
3701
+ return first.length - second.length;
3702
+ }
3703
+
3704
+ // src/lib/knowledge/standard/index-standard-text.ts
3705
+ function indexStandardText(params) {
3706
+ const { fileId } = params;
3707
+ const originalLines = linesOf(params.text);
3708
+ const classified = classifyStandardLines({ lines: originalLines });
3709
+ const { dropped: noise, ranges: noiseRanges } = markNoiseLines({ lines: classified });
3710
+ const candidates = classified.flatMap(
3711
+ (line) => line.kind === "heading" && line.candidate ? [line.candidate] : []
3712
+ );
3713
+ const kept = selectHeadings({ candidates });
3714
+ const lines = settleLeftOutCandidates({
3715
+ lines: classified,
3716
+ keptLines: new Set(kept.map((candidate) => candidate.line))
3717
+ });
3718
+ const logicalLines = joinLogicalLines({ lines, noise });
3719
+ const headings = readHeadings({ fileId, kept, lineCount: lines.length });
3720
+ const tables = readTables({ fileId, logicalLines, headings });
3721
+ return {
3722
+ fileId,
3723
+ lineCount: lines.length,
3724
+ logicalLines,
3725
+ noiseRanges,
3726
+ headings,
3727
+ definitions: readDefinitions({ lines, noise }),
3728
+ tables,
3729
+ crossReferences: readCrossReferences({ lines, noise, headings, tables }),
3730
+ quality: assessQuality({
3731
+ lines,
3732
+ noise,
3733
+ // the list items a heading style turned prose are counted as candidates turned prose
3734
+ candidates: candidates.length + classified.filter((line) => line.listItem).length,
3735
+ kept: kept.length,
3736
+ repeatedLines: findRepeatedLines({ lines: originalLines })
3737
+ })
3738
+ };
3739
+ }
3740
+ function linesOf(text) {
3741
+ if (text.length === 0) return [];
3742
+ const lines = text.split(LINE_BREAK_PATTERN);
3743
+ return lines[lines.length - 1] === "" ? lines.slice(0, -1) : lines;
3744
+ }
3745
+ function settleLeftOutCandidates(params) {
3746
+ return params.lines.map(
3747
+ (line) => line.kind === "heading" && !params.keptLines.has(line.line) ? { ...line, kind: "prose" } : line
3748
+ );
3749
+ }
3750
+
3751
+ // src/lib/knowledge/standard/standard-search.constants.ts
3752
+ var WORD_TOKEN_PATTERN = /[A-Za-z0-9_]+/g;
3753
+ var WORD_PART_SEPARATOR = "_";
3754
+ var CAMEL_CASE_BOUNDARY_PATTERN = /(?<=[a-z0-9])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])/;
3755
+ var MINIMUM_WORD_LENGTH = 3;
3756
+ var LOWERCASE_WORD_PATTERN = /^[a-z]+$/u;
3757
+ var ACRONYM_PATTERN = /^(?=(?:\d*[A-Z]){2})[A-Z\d]+$/u;
3758
+ var ACRONYM_PLURAL_PATTERN = /^[A-Z\d]+s$/u;
3759
+ var STOP_WORDS2 = /* @__PURE__ */ new Set([
3760
+ "about",
3761
+ "above",
3762
+ "after",
3763
+ "again",
3764
+ "against",
3765
+ "all",
3766
+ "and",
3767
+ "any",
3768
+ "are",
3769
+ "because",
3770
+ "been",
3771
+ "before",
3772
+ "being",
3773
+ "below",
3774
+ "between",
3775
+ "both",
3776
+ "but",
3777
+ "can",
3778
+ "could",
3779
+ "did",
3780
+ "do",
3781
+ "does",
3782
+ "doing",
3783
+ "down",
3784
+ "during",
3785
+ "each",
3786
+ "few",
3787
+ "for",
3788
+ "from",
3789
+ "further",
3790
+ "had",
3791
+ "has",
3792
+ "have",
3793
+ "having",
3794
+ "her",
3795
+ "here",
3796
+ "hers",
3797
+ "him",
3798
+ "his",
3799
+ "how",
3800
+ "into",
3801
+ "its",
3802
+ "itself",
3803
+ "may",
3804
+ "might",
3805
+ "more",
3806
+ "most",
3807
+ "must",
3808
+ "nor",
3809
+ "not",
3810
+ "off",
3811
+ "once",
3812
+ "only",
3813
+ "onto",
3814
+ "other",
3815
+ "our",
3816
+ "ours",
3817
+ "out",
3818
+ "over",
3819
+ "own",
3820
+ "same",
3821
+ "shall",
3822
+ "she",
3823
+ "should",
3824
+ "some",
3825
+ "such",
3826
+ "than",
3827
+ "that",
3828
+ "the",
3829
+ "their",
3830
+ "theirs",
3831
+ "them",
3832
+ "then",
3833
+ "there",
3834
+ "these",
3835
+ "they",
3836
+ "this",
3837
+ "those",
3838
+ "through",
3839
+ "too",
3840
+ "under",
3841
+ "until",
3842
+ "upon",
3843
+ "very",
3844
+ "was",
3845
+ "were",
3846
+ "what",
3847
+ "when",
3848
+ "where",
3849
+ "which",
3850
+ "while",
3851
+ "who",
3852
+ "whom",
3853
+ "whose",
3854
+ "why",
3855
+ "will",
3856
+ "with",
3857
+ "within",
3858
+ "without",
3859
+ "would",
3860
+ "you",
3861
+ "your",
3862
+ "yours"
3863
+ ]);
3864
+ var PLURAL_IES_PATTERN = /ies$/;
3865
+ var PLURAL_IES_REPLACEMENT = "y";
3866
+ var PLURAL_ES_PATTERN = /(s|x|z|ch|sh)es$/;
3867
+ var PLURAL_ES_REPLACEMENT = "$1";
3868
+ var PLURAL_S_PATTERN = /([^sui])s$/;
3869
+ var PLURAL_S_REPLACEMENT = "$1";
3870
+ var PAST_IED_PATTERN = /ied$/u;
3871
+ var PAST_IED_REPLACEMENT = "y";
3872
+ var PROGRESSIVE_YING_PATTERN = /(?<=y)ing$/u;
3873
+ var INFLECTION_PATTERN = /(?:ing|ed)$/u;
3874
+ var STEM_MINIMUM_LENGTH = 3;
3875
+ var STEM_VOWEL_PATTERN = /[aeiouy]/u;
3876
+ var DOUBLED_CONSONANT_PATTERN = /([bcdfghjkmnpqrtvwx])\1$/u;
3877
+ var DOUBLED_CONSONANT_REPLACEMENT = "$1";
3878
+ var FINAL_E_PATTERN = /e$/u;
3879
+ var COMMON_WORD_SHARE = 0.05;
3880
+ var COMMON_WORD_WEIGHT_FACTOR = 10;
3881
+ var LINK_STRENGTHS = {
3882
+ heading: 3,
3883
+ caption: 3,
3884
+ definition: 2,
3885
+ cell: 2,
3886
+ text: 1
3887
+ };
3888
+ var SHORT_ATTRIBUTE_LENGTH = 3;
3889
+ var ATTRIBUTE_AT_SIGN = "@";
3890
+ var ATTRIBUTE_EQUAL_SIGN = "=";
3891
+ var TITLE_HIT_FACTOR = 2;
3892
+ var ABOUT_FACTOR = 2;
3893
+ var SCORE_DECIMALS = 2;
3894
+ var SLICE_LINE_CAP = 60;
3895
+ var DEFAULT_FIND_LIMIT2 = 10;
3896
+
3897
+ // src/lib/knowledge/standard/tag-links-of.ts
3898
+ function tagLinksOf(params) {
3899
+ const { files, units, lineUnits, vocabulary } = params;
3900
+ const rules = rulesOf(vocabulary);
3901
+ if (rules.size === 0) return {};
3902
+ const otherNames = [...rules.keys()].filter((name) => !isWholeWord(name));
3903
+ const found = /* @__PURE__ */ new Map();
3904
+ const definitionTerms = definitionTermLinesOf({ files });
3905
+ const lines = files.flatMap((file) => file.logicalLines);
3906
+ for (const [standardLine, line] of lines.entries()) {
3907
+ const unit = lineUnits[standardLine];
3908
+ const strength = strengthOf({
3909
+ line,
3910
+ unit: units[unit],
3911
+ standardLine,
3912
+ definitionTerms
3913
+ });
3914
+ for (const name of namesOfLine({ line, rules, otherNames })) {
3915
+ const byUnit = found.get(name) ?? /* @__PURE__ */ new Map();
3916
+ found.set(name, byUnit);
3917
+ const link = byUnit.get(unit);
3918
+ if (!link) byUnit.set(unit, { unit, strength, lines: [standardLine] });
3919
+ else {
3920
+ link.strength = Math.max(link.strength, strength);
3921
+ link.lines.push(standardLine);
3922
+ }
3923
+ }
3924
+ }
3925
+ const links = /* @__PURE__ */ Object.create(null);
3926
+ for (const [name, byUnit] of found) links[name] = [...byUnit.values()];
3927
+ return links;
3928
+ }
3929
+ function rulesOf(vocabulary) {
3930
+ const rules = /* @__PURE__ */ new Map();
3931
+ for (const value of vocabulary.values)
3932
+ rules.set(value, value.length < SHORT_ATTRIBUTE_LENGTH ? "cellOnly" : "anywhere");
3933
+ for (const attribute of vocabulary.attributes)
3934
+ rules.set(attribute, attribute.length < SHORT_ATTRIBUTE_LENGTH ? "attributeForms" : "anywhere");
3935
+ for (const tag of vocabulary.tags) rules.set(tag, "anywhere");
3936
+ return rules;
3937
+ }
3938
+ function definitionTermLinesOf(params) {
3939
+ const termLines = /* @__PURE__ */ new Set();
3940
+ let offset = 0;
3941
+ for (const file of params.files) {
3942
+ const indexOfFrom = new Map(file.logicalLines.map((line, index) => [line.from, index]));
3943
+ for (const definition of file.definitions) {
3944
+ const index = indexOfFrom.get(definition.from);
3945
+ if (index === void 0) continue;
3946
+ const onItsLine = file.logicalLines[index].text.includes(definition.term);
3947
+ termLines.add(offset + (onItsLine ? index : index + 1));
3948
+ }
3949
+ offset += file.logicalLines.length;
3950
+ }
3951
+ return termLines;
3952
+ }
3953
+ function strengthOf(params) {
3954
+ const { line, unit, standardLine, definitionTerms } = params;
3955
+ if (unit.titleLine === standardLine)
3956
+ return unit.kind === "table" ? LINK_STRENGTHS.caption : LINK_STRENGTHS.heading;
3957
+ if (definitionTerms.has(standardLine)) return LINK_STRENGTHS.definition;
3958
+ if (line.kind === "table") return LINK_STRENGTHS.cell;
3959
+ return LINK_STRENGTHS.text;
3960
+ }
3961
+ function namesOfLine(params) {
3962
+ const { line, rules, otherNames } = params;
3963
+ const names = /* @__PURE__ */ new Set();
3964
+ const text = line.text;
3965
+ for (const match of text.matchAll(WORD_TOKEN_PATTERN)) {
3966
+ const name = match[0];
3967
+ const rule = rules.get(name);
3968
+ if (rule === void 0 || rule === "cellOnly") continue;
3969
+ if (rule === "anywhere" || inAttributeForm({ text, start: match.index, name })) names.add(name);
3970
+ }
3971
+ for (const name of otherNames)
3972
+ if (rules.get(name) === "anywhere" && containsBounded({ text, name })) names.add(name);
3973
+ if (line.kind === "table" && !TABLE_SEPARATOR_ROW_PATTERN.test(text)) {
3974
+ for (const cell of cellsOfRow(text)) if (rules.has(cell)) names.add(cell);
3975
+ }
3976
+ return names;
3977
+ }
3978
+ function inAttributeForm(params) {
3979
+ const { text, start, name } = params;
3980
+ return text.charAt(start - 1) === ATTRIBUTE_AT_SIGN || text.charAt(start + name.length) === ATTRIBUTE_EQUAL_SIGN;
3981
+ }
3982
+ function isWholeWord(name) {
3983
+ const match = name.match(WORD_TOKEN_PATTERN);
3984
+ return match?.length === 1 && match[0] === name;
3985
+ }
3986
+ function containsBounded(params) {
3987
+ const { text, name } = params;
3988
+ let start = text.indexOf(name);
3989
+ while (start !== -1) {
3990
+ const before = text.charAt(start - 1);
3991
+ const after = text.charAt(start + name.length);
3992
+ if (!isWordCharacter(before) && !isWordCharacter(after)) return true;
3993
+ start = text.indexOf(name, start + 1);
3994
+ }
3995
+ return false;
3996
+ }
3997
+ function isWordCharacter(character) {
3998
+ return character !== "" && isWholeWord(character);
3999
+ }
4000
+
4001
+ // src/lib/knowledge/standard/units-of.ts
4002
+ function unitsOf(params) {
4003
+ const units = [];
4004
+ const lineUnits = [];
4005
+ let offset = 0;
4006
+ for (const file of params.files) {
4007
+ const fileUnits = fileUnitsOf({ file, offset });
4008
+ const base = units.length;
4009
+ for (const unit of fileUnits.units) units.push(unit);
4010
+ for (const unit of fileUnits.lineUnits) lineUnits.push(unit === -1 ? -1 : base + unit);
4011
+ offset += file.logicalLines.length;
4012
+ }
4013
+ return { units, lineUnits };
4014
+ }
4015
+ function fileUnitsOf(params) {
4016
+ const { file, offset } = params;
4017
+ const tables = tableUnitsOf({ file, offset });
4018
+ const units = [...tables.units, ...headingUnitsOf(file)];
4019
+ const headingUnits = new Map(
4020
+ file.headings.map((heading, index) => [heading.from, tables.units.length + index])
4021
+ );
4022
+ const lineUnits = [];
4023
+ let frontUnit = -1;
4024
+ let currentUnit = -1;
4025
+ for (const [index, line] of file.logicalLines.entries()) {
4026
+ const standardLine = offset + index;
4027
+ const headingUnit = line.kind === "heading" ? headingUnits.get(line.from) : void 0;
4028
+ if (headingUnit !== void 0) {
4029
+ currentUnit = headingUnit;
4030
+ units[headingUnit].titleLine = standardLine;
4031
+ }
4032
+ const tableUnit = tables.unitOfLine.get(index);
4033
+ if (tableUnit !== void 0)
4034
+ units[tableUnit] = extendUnit({ unit: units[tableUnit], standardLine });
4035
+ else if (currentUnit === -1) {
4036
+ units.push(frontUnitOf({ file, line: line.from }));
4037
+ frontUnit = units.length - 1;
4038
+ currentUnit = frontUnit;
4039
+ }
4040
+ if (currentUnit !== -1)
4041
+ units[currentUnit] = extendUnit({ unit: units[currentUnit], standardLine });
4042
+ if (currentUnit !== -1 && currentUnit === frontUnit) units[frontUnit].to = line.to;
4043
+ lineUnits.push(tableUnit ?? currentUnit);
4044
+ }
4045
+ return { units, lineUnits };
4046
+ }
4047
+ function headingUnitsOf(file) {
4048
+ return file.headings.map((heading, index) => {
4049
+ const next = file.headings[index + 1];
4050
+ return {
4051
+ fileId: file.fileId,
4052
+ kind: "clause",
4053
+ clause: heading.number,
4054
+ title: heading.title,
4055
+ target: heading.number,
4056
+ from: heading.from,
4057
+ to: next ? next.from - 1 : file.lineCount,
4058
+ firstLine: -1,
4059
+ lastLine: -1,
4060
+ titleLine: null
4061
+ };
4062
+ });
4063
+ }
4064
+ function tableUnitsOf(params) {
4065
+ const { file } = params;
4066
+ const indexOfFrom = new Map(file.logicalLines.map((line, index) => [line.from, index]));
4067
+ const units = [];
4068
+ const unitOfLine = /* @__PURE__ */ new Map();
4069
+ for (const table of file.tables) {
4070
+ const start = indexOfFrom.get(table.from);
4071
+ if (start === void 0) continue;
4072
+ const caption = findCaptionAbove({ logicalLines: file.logicalLines, start });
4073
+ const unit = units.length;
4074
+ units.push({
4075
+ fileId: file.fileId,
4076
+ kind: "table",
4077
+ clause: table.clause,
4078
+ title: table.caption,
4079
+ target: table.number === null ? null : TABLE_TARGET_PREFIX + table.number,
4080
+ from: file.logicalLines[caption ?? start].from,
4081
+ to: table.to,
4082
+ firstLine: -1,
4083
+ lastLine: -1,
4084
+ titleLine: caption === null ? null : params.offset + caption
4085
+ });
4086
+ if (caption !== null) unitOfLine.set(caption, unit);
4087
+ for (let index = start; index < file.logicalLines.length; index++) {
4088
+ if (file.logicalLines[index].from > table.to) break;
4089
+ unitOfLine.set(index, unit);
4090
+ }
4091
+ }
4092
+ return { units, unitOfLine };
4093
+ }
4094
+ function frontUnitOf(params) {
4095
+ return {
4096
+ fileId: params.file.fileId,
4097
+ kind: "front",
4098
+ clause: null,
4099
+ title: null,
4100
+ target: null,
4101
+ from: params.line,
4102
+ to: params.line,
4103
+ firstLine: -1,
4104
+ lastLine: -1,
4105
+ titleLine: null
4106
+ };
4107
+ }
4108
+ function extendUnit(params) {
4109
+ const { unit, standardLine } = params;
4110
+ return {
4111
+ ...unit,
4112
+ firstLine: unit.firstLine === -1 ? standardLine : unit.firstLine,
4113
+ lastLine: standardLine
4114
+ };
4115
+ }
4116
+
4117
+ // src/lib/knowledge/standard/word-keys-of.ts
4118
+ function wordKeysOf(params) {
4119
+ const { token, split } = params;
4120
+ const acronym = acronymOf(token);
4121
+ if (acronym !== void 0) return [acronym];
4122
+ const words = split ? [token, ...partsOf(token)] : [token];
4123
+ const keys = /* @__PURE__ */ new Set();
4124
+ for (const word of words) {
4125
+ const lower = word.toLowerCase();
4126
+ const partAcronym = acronymOf(word);
4127
+ if (partAcronym !== void 0) {
4128
+ keys.add(partAcronym);
4129
+ continue;
4130
+ }
4131
+ if (lower.length < MINIMUM_WORD_LENGTH || STOP_WORDS2.has(lower)) continue;
4132
+ keys.add(stemOf(lower));
4133
+ }
4134
+ return [...keys];
4135
+ }
4136
+ function acronymOf(word) {
4137
+ const acronym = ACRONYM_PLURAL_PATTERN.test(word) ? word.slice(0, -1) : word;
4138
+ return ACRONYM_PATTERN.test(acronym) ? acronym.toLowerCase() : void 0;
4139
+ }
4140
+ function partsOf(token) {
4141
+ const parts = token.split(WORD_PART_SEPARATOR).flatMap((part) => part.split(CAMEL_CASE_BOUNDARY_PATTERN));
4142
+ return parts.length > 1 ? parts : [];
4143
+ }
4144
+ function stemOf(word) {
4145
+ const singular = word.replace(PLURAL_IES_PATTERN, PLURAL_IES_REPLACEMENT).replace(PLURAL_ES_PATTERN, PLURAL_ES_REPLACEMENT).replace(PLURAL_S_PATTERN, PLURAL_S_REPLACEMENT);
4146
+ const uninflected = withoutInflection(singular);
4147
+ return FINAL_E_PATTERN.test(uninflected) && uninflected.length > STEM_MINIMUM_LENGTH ? uninflected.replace(FINAL_E_PATTERN, "") : uninflected;
4148
+ }
4149
+ function withoutInflection(word) {
4150
+ if (PAST_IED_PATTERN.test(word)) return word.replace(PAST_IED_PATTERN, PAST_IED_REPLACEMENT);
4151
+ if (PROGRESSIVE_YING_PATTERN.test(word)) return word.replace(PROGRESSIVE_YING_PATTERN, "");
4152
+ const rest = word.replace(INFLECTION_PATTERN, "");
4153
+ if (rest === word || rest.length < STEM_MINIMUM_LENGTH || !STEM_VOWEL_PATTERN.test(rest))
4154
+ return word;
4155
+ return rest.replace(DOUBLED_CONSONANT_PATTERN, DOUBLED_CONSONANT_REPLACEMENT);
4156
+ }
4157
+
4158
+ // src/lib/knowledge/standard/word-index-of.ts
4159
+ function wordIndexOf(params) {
4160
+ const stems = /* @__PURE__ */ Object.create(null);
4161
+ const keysOfToken = /* @__PURE__ */ new Map();
4162
+ let standardLine = 0;
4163
+ for (const file of params.files)
4164
+ for (const line of file.logicalLines) {
4165
+ const lineStems = /* @__PURE__ */ new Set();
4166
+ for (const match of line.text.matchAll(WORD_TOKEN_PATTERN)) {
4167
+ const token = match[0];
4168
+ const keys = keysOfToken.get(token) ?? wordKeysOf({ token, split: true });
4169
+ keysOfToken.set(token, keys);
4170
+ for (const key of keys) lineStems.add(key);
4171
+ }
4172
+ for (const stem2 of lineStems) {
4173
+ const lines = stems[stem2];
4174
+ if (lines) lines.push(standardLine);
4175
+ else stems[stem2] = [standardLine];
4176
+ }
4177
+ standardLine++;
4178
+ }
4179
+ return { logicalLineCount: standardLine, stems };
4180
+ }
4181
+
4182
+ // src/lib/knowledge/standard/search-index-of.ts
4183
+ function searchIndexOf(params) {
4184
+ const { files, vocabulary } = params;
4185
+ const { units, lineUnits } = unitsOf({ files });
4186
+ return {
4187
+ files,
4188
+ vocabulary,
4189
+ words: wordIndexOf({ files }),
4190
+ units,
4191
+ lineUnits,
4192
+ tagLinks: tagLinksOf({ files, units, lineUnits, vocabulary })
4193
+ };
4194
+ }
4195
+
4196
+ // src/lib/knowledge/standard/standard-cache.constants.ts
4197
+ var PACKAGE_MANIFEST = "package.json";
4198
+ var INSTALLED_HASH_LENGTH = 16;
4199
+ var INSTALLED_LIST_SEPARATOR = "\n";
4200
+ var INDEX_FORMAT = 2;
4201
+ var CACHE_LOCATION = {
4202
+ environmentVariable: "XDG_CACHE_HOME",
4203
+ homeVariable: "HOME",
4204
+ homeFolder: ".cache",
4205
+ toolFolder: "dialecte",
4206
+ standardFolder: "standard"
4207
+ };
4208
+ var INDEX_FILES = {
4209
+ manifest: "manifest.json",
4210
+ quality: "quality.json",
4211
+ headings: "headings.json",
4212
+ definitions: "definitions.json",
4213
+ tables: "tables.json",
4214
+ crossReferences: "crossrefs.json",
4215
+ words: "words.json"
4216
+ };
4217
+ var PER_FILE_PARTS = [
4218
+ "quality",
4219
+ "headings",
4220
+ "definitions",
4221
+ "tables",
4222
+ "crossReferences"
4223
+ ];
4224
+ var LINES_FOLDER = "lines";
4225
+ var LINES_EXTENSION = ".jsonl";
4226
+ var FILE_ID_SEPARATOR = "/";
4227
+ var TAGS_FILE_PREFIX = "tags-";
4228
+ var JSON_EXTENSION = ".json";
4229
+ var TEMPORARY_INFIX2 = ".tmp-";
4230
+ var ASIDE_INFIX = ".old-";
4231
+ var LEFT_FOLDER_PATTERN = /\.(?:tmp|old)-(\d+)$/u;
4232
+ var TARGET_TAKEN_CODES = ["ENOTEMPTY", "EEXIST"];
4233
+ var MISSING_ENTRY_CODE = "ENOENT";
4234
+ var PLACE_FAILED_MESSAGE = "cannot put the index in place: {code} renaming {from} to {to}; nothing kept";
4235
+ var BUILD_OUTCOMES = {
4236
+ built: "built",
4237
+ reused: "reused",
4238
+ aborted: "aborted",
4239
+ failed: "failed"
4240
+ };
4241
+ var FILE_CHANGED_MESSAGE = "{name} ({id}) changed while the index was built: nothing kept, run it again once the file is stable";
4242
+ var BUILD_STEP_NAME = "standard index";
4243
+
4244
+ // src/lib/knowledge/standard/standard-index-folder.ts
4245
+ import { existsSync as existsSync21, mkdirSync as mkdirSync6, readFileSync as readFileSync15, renameSync as renameSync4, writeFileSync as writeFileSync5 } from "fs";
4246
+ import { join as join26 } from "path";
4247
+ function writeIndexFolder(params) {
4248
+ const { folder, manifest, search } = params;
4249
+ mkdirSync6(join26(folder, LINES_FOLDER), { recursive: true });
4250
+ for (const file of search.files)
4251
+ writeFileSync5(
4252
+ linesPathOf({ folder, fileId: file.fileId }),
4253
+ file.logicalLines.map((line) => `${JSON.stringify(line)}
4254
+ `).join("")
4255
+ );
4256
+ const parts = {
4257
+ quality: perFile({
4258
+ files: search.files,
4259
+ value: (file) => ({ ...file.quality, noiseRanges: file.noiseRanges })
4260
+ }),
4261
+ headings: perFile({ files: search.files, value: (file) => file.headings }),
4262
+ definitions: perFile({ files: search.files, value: (file) => file.definitions }),
4263
+ tables: perFile({ files: search.files, value: (file) => file.tables }),
4264
+ crossReferences: perFile({ files: search.files, value: (file) => file.crossReferences })
4265
+ };
4266
+ for (const part of PER_FILE_PARTS)
4267
+ writeJson({ path: join26(folder, INDEX_FILES[part]), content: parts[part] });
4268
+ const words = {
4269
+ words: search.words,
4270
+ units: search.units,
4271
+ lineUnits: search.lineUnits
4272
+ };
4273
+ writeJson({ path: join26(folder, INDEX_FILES.words), content: words });
4274
+ writeJson({ path: join26(folder, INDEX_FILES.manifest), content: manifest });
4275
+ }
4276
+ function isCompleteIndexFolder(params) {
4277
+ return existsSync21(join26(params.folder, INDEX_FILES.manifest));
4278
+ }
4279
+ function readIndexFolder(params) {
4280
+ const { folder } = params;
4281
+ const manifest = readJson({ path: join26(folder, INDEX_FILES.manifest) });
4282
+ const parts = {
4283
+ quality: readJson({ path: join26(folder, INDEX_FILES.quality) }),
4284
+ headings: readJson({ path: join26(folder, INDEX_FILES.headings) }),
4285
+ definitions: readJson({ path: join26(folder, INDEX_FILES.definitions) }),
4286
+ tables: readJson({ path: join26(folder, INDEX_FILES.tables) }),
4287
+ crossReferences: readJson({ path: join26(folder, INDEX_FILES.crossReferences) })
4288
+ };
4289
+ const files = manifest.files.map((entry) => {
4290
+ const { noiseRanges, ...quality } = parts.quality[entry.id];
4291
+ return {
4292
+ fileId: entry.id,
4293
+ lineCount: entry.lines,
4294
+ logicalLines: readLines({ folder, fileId: entry.id }),
4295
+ noiseRanges,
4296
+ headings: parts.headings[entry.id],
4297
+ definitions: parts.definitions[entry.id],
4298
+ tables: parts.tables[entry.id],
4299
+ crossReferences: parts.crossReferences[entry.id],
4300
+ quality
4301
+ };
4302
+ });
4303
+ return { manifest, files, words: readJson({ path: join26(folder, INDEX_FILES.words) }) };
4304
+ }
4305
+ function tagsPathOf(params) {
4306
+ return join26(params.folder, `${TAGS_FILE_PREFIX}${params.installedHash}${JSON_EXTENSION}`);
4307
+ }
4308
+ function writeTagsFile(params) {
4309
+ const temporary = `${params.path}${TEMPORARY_INFIX2}${process.pid}`;
4310
+ writeJson({ path: temporary, content: params.content });
4311
+ renameSync4(temporary, params.path);
4312
+ }
4313
+ function readTagsFile(params) {
4314
+ return readJson({ path: params.path });
4315
+ }
4316
+ function linesPathOf(params) {
4317
+ const name = params.fileId.slice(params.fileId.indexOf(FILE_ID_SEPARATOR) + 1);
4318
+ return join26(params.folder, LINES_FOLDER, `${name}${LINES_EXTENSION}`);
4319
+ }
4320
+ function readLines(params) {
4321
+ return readFileSync15(linesPathOf(params), "utf8").split("\n").filter((line) => line !== "").map((line) => JSON.parse(line));
4322
+ }
4323
+ function perFile(params) {
4324
+ return Object.fromEntries(params.files.map((file) => [file.fileId, params.value(file)]));
4325
+ }
4326
+ function writeJson(params) {
4327
+ writeFileSync5(params.path, `${JSON.stringify(params.content)}
4328
+ `);
4329
+ }
4330
+ function readJson(params) {
4331
+ return JSON.parse(readFileSync15(params.path, "utf8"));
4332
+ }
4333
+
4334
+ // src/lib/knowledge/standard/ensure-standard-index.ts
4335
+ async function ensureStandardIndex(params) {
4336
+ const startedAt = Date.now();
4337
+ const { standard, installed } = params;
4338
+ const folder = join27(params.cacheRoot, CACHE_LOCATION.standardFolder, standard.id);
4339
+ const hashed = standard.files.map(hashedFileOf);
4340
+ const manifestHash = manifestHashOf({ hashed });
4341
+ const target = join27(folder, manifestHash);
4342
+ const ready = { standardId: standard.id, manifestHash, startedAt, target, installed };
4343
+ if (!params.rebuild && isCompleteIndexFolder({ folder: target }))
4344
+ return readyAnswer({ ...ready, state: "reused" });
4345
+ removeStaleTemporaryFolders({ folder });
4346
+ const temporary = `${target}${TEMPORARY_INFIX2}${process.pid}`;
4347
+ const step = params.progress?.start({ name: BUILD_STEP_NAME, detail: standard.id });
4348
+ let outcome = BUILD_OUTCOMES.failed;
4349
+ try {
4350
+ const built = await buildInto({ ...params, hashed, folder: temporary });
4351
+ if (built.kind === "aborted") {
4352
+ rmSync5(temporary, { recursive: true, force: true });
4353
+ outcome = BUILD_OUTCOMES.aborted;
4354
+ return built;
4355
+ }
4356
+ if (isCompleteIndexFolder({ folder: target }) && !params.rebuild) {
4357
+ rmSync5(temporary, { recursive: true, force: true });
4358
+ outcome = BUILD_OUTCOMES.reused;
4359
+ return readyAnswer({ ...ready, state: "reused" });
4360
+ }
4361
+ const placed = placeFolder({ temporary, target, replace: params.rebuild });
4362
+ if (placed.kind === "failed") return { kind: "aborted", message: placed.message };
4363
+ outcome = placed.kind === "taken" ? BUILD_OUTCOMES.reused : BUILD_OUTCOMES.built;
4364
+ if (placed.kind === "taken") return readyAnswer({ ...ready, state: "reused" });
4365
+ return readyAnswer({ ...ready, state: "built", search: built.search });
4366
+ } catch (error) {
4367
+ rmSync5(temporary, { recursive: true, force: true });
4368
+ throw error;
4369
+ } finally {
4370
+ step?.finish(
4371
+ `${BUILD_STEP_NAME} ${standard.id} ${outcome} ${formatDuration(Date.now() - startedAt)}`
4372
+ );
4373
+ }
4374
+ }
4375
+ function readyAnswer(params) {
4376
+ return {
4377
+ kind: "ready",
4378
+ index: {
4379
+ standardId: params.standardId,
4380
+ manifestHash: params.manifestHash,
4381
+ state: params.state,
4382
+ elapsed: Date.now() - params.startedAt,
4383
+ search: params.search ?? readSearchIndex({ folder: params.target, installed: params.installed })
4384
+ }
4385
+ };
4386
+ }
4387
+ function hashedFileOf(file) {
4388
+ const bytes = readFileSync16(file.path);
4389
+ return {
4390
+ id: file.id,
4391
+ name: file.name,
4392
+ path: file.path,
4393
+ size: bytes.length,
4394
+ sha256: sha256Of(bytes)
4395
+ };
4396
+ }
4397
+ function manifestHashOf(params) {
4398
+ const pairs = params.hashed.map((file) => [file.id, file.sha256]).sort(([left], [right]) => left < right ? -1 : 1);
4399
+ return sha256Of(JSON.stringify({ indexFormat: INDEX_FORMAT, files: pairs }));
4400
+ }
4401
+ async function buildInto(params) {
4402
+ const { hashed, installed } = params;
4403
+ const files = [];
4404
+ for (const file of hashed) {
4405
+ await nextTurn();
4406
+ const bytes = readFileSync16(file.path);
4407
+ params.afterFileRead?.({ path: file.path });
4408
+ if (sha256Of(bytes) !== file.sha256) return abortedBy(file);
4409
+ files.push(indexStandardText({ fileId: file.id, text: bytes.toString("utf8") }));
4410
+ }
4411
+ const search = searchIndexOf({ files, vocabulary: installed.vocabulary });
4412
+ const manifest = {
4413
+ files: hashed.map((file, index) => ({
4414
+ id: file.id,
4415
+ name: file.name,
4416
+ size: file.size,
4417
+ sha256: file.sha256,
4418
+ lines: files[index].lineCount
4419
+ })),
4420
+ built: (/* @__PURE__ */ new Date()).toISOString(),
4421
+ cliVersion: params.cliVersion,
4422
+ indexFormat: INDEX_FORMAT
4423
+ };
4424
+ writeIndexFolder({ folder: params.folder, manifest, search });
4425
+ if (installed.installedHash !== void 0)
4426
+ writeTagsFile({
4427
+ path: tagsPathOf({ folder: params.folder, installedHash: installed.installedHash }),
4428
+ content: { vocabulary: installed.vocabulary, tagLinks: search.tagLinks }
4429
+ });
4430
+ const moved = hashed.find((file) => sha256Of(readFileSync16(file.path)) !== file.sha256);
4431
+ return moved ? abortedBy(moved) : { kind: "built", search };
4432
+ }
4433
+ function placeFolder(params) {
4434
+ const { temporary, target } = params;
4435
+ const aside = params.replace ? moveAside({ temporary, target, aside: `${target}${ASIDE_INFIX}${process.pid}` }) : { kind: "moved", aside: void 0 };
4436
+ if (aside.kind === "failed") return aside;
4437
+ return placeInto({ temporary, target, aside: aside.aside });
4438
+ }
4439
+ function moveAside(params) {
4440
+ const { temporary, target, aside } = params;
4441
+ try {
4442
+ renameSync5(target, aside);
4443
+ return { kind: "moved", aside };
4444
+ } catch (error) {
4445
+ const code = error.code ?? String(error);
4446
+ if (code === MISSING_ENTRY_CODE) return { kind: "moved", aside: void 0 };
4447
+ rmSync5(temporary, { recursive: true, force: true });
4448
+ return {
4449
+ kind: "failed",
4450
+ message: fillMessage({
4451
+ template: PLACE_FAILED_MESSAGE,
4452
+ values: { code, from: target, to: aside }
4453
+ })
4454
+ };
4455
+ }
4456
+ }
4457
+ function placeInto(params) {
4458
+ const { temporary, target, aside } = params;
4459
+ try {
4460
+ renameSync5(temporary, target);
4461
+ } catch (error) {
4462
+ const code = error.code ?? String(error);
4463
+ rmSync5(temporary, { recursive: true, force: true });
4464
+ if (TARGET_TAKEN_CODES.includes(code)) {
4465
+ if (aside !== void 0) rmSync5(aside, { recursive: true, force: true });
4466
+ return { kind: "taken" };
4467
+ }
4468
+ if (aside !== void 0) renameSync5(aside, target);
4469
+ return {
4470
+ kind: "failed",
4471
+ message: fillMessage({
4472
+ template: PLACE_FAILED_MESSAGE,
4473
+ values: { code, from: temporary, to: target }
4474
+ })
4475
+ };
4476
+ }
4477
+ if (aside !== void 0) rmSync5(aside, { recursive: true, force: true });
4478
+ return { kind: "placed" };
4479
+ }
4480
+ function readSearchIndex(params) {
4481
+ const { folder, installed } = params;
4482
+ const { files, words } = readIndexFolder({ folder });
4483
+ const search = {
4484
+ files,
4485
+ vocabulary: installed.vocabulary,
4486
+ words: words.words,
4487
+ units: words.units,
4488
+ lineUnits: words.lineUnits,
4489
+ tagLinks: {}
4490
+ };
4491
+ if (installed.installedHash === void 0) return search;
4492
+ const path = tagsPathOf({ folder, installedHash: installed.installedHash });
4493
+ if (existsSync22(path)) return { ...search, tagLinks: readTagsFile({ path }).tagLinks };
4494
+ const tagLinks = tagLinksOf({
4495
+ files,
4496
+ units: words.units,
4497
+ lineUnits: words.lineUnits,
4498
+ vocabulary: installed.vocabulary
4499
+ });
4500
+ writeTagsFile({ path, content: { vocabulary: installed.vocabulary, tagLinks } });
4501
+ return { ...search, tagLinks };
4502
+ }
4503
+ function removeStaleTemporaryFolders(params) {
4504
+ if (!existsSync22(params.folder)) return;
4505
+ for (const name of readdirSync11(params.folder)) {
4506
+ const pid = LEFT_FOLDER_PATTERN.exec(name)?.[1];
4507
+ if (pid !== void 0 && !isProcessAlive(Number(pid)))
4508
+ rmSync5(join27(params.folder, name), { recursive: true, force: true });
4509
+ }
4510
+ }
4511
+ function abortedBy(file) {
4512
+ return {
4513
+ kind: "aborted",
4514
+ message: fillMessage({
4515
+ template: FILE_CHANGED_MESSAGE,
4516
+ values: { name: file.name, id: file.id }
4517
+ })
4518
+ };
4519
+ }
4520
+ function nextTurn() {
4521
+ return new Promise(function resolveOnNextTurn(resolve7) {
4522
+ setImmediate(resolve7);
4523
+ });
4524
+ }
4525
+ function sha256Of(content) {
4526
+ return createHash2("sha256").update(content).digest("hex");
4527
+ }
4528
+
4529
+ // src/lib/knowledge/standard/read-installed-vocabulary.ts
4530
+ import { createHash as createHash3 } from "crypto";
4531
+ import { existsSync as existsSync23 } from "fs";
4532
+ import { join as join28 } from "path";
4533
+ async function readInstalledVocabulary(params) {
4534
+ const { cwd, packageName: packageName2 } = params;
4535
+ const installed = existsSync23(join28(cwd, PACKAGE_MANIFEST)) ? (await loadDialectes({ cwd })).dialectes : [];
4536
+ const selected = packageName2 === void 0 ? installed : installed.filter((dialecte) => dialecte.packageName === packageName2);
4537
+ if (packageName2 !== void 0 && selected.length === 0)
4538
+ return {
4539
+ kind: "unknownPackage",
4540
+ name: packageName2,
4541
+ installed: installed.map((dialecte) => dialecte.packageName).sort()
4542
+ };
4543
+ return { kind: "read", installed: vocabularyOf({ cwd, dialectes: selected }) };
4544
+ }
4545
+ function vocabularyOf(params) {
4546
+ const { cwd, dialectes } = params;
4547
+ if (dialectes.length === 0) return emptyInstalledVocabulary();
4548
+ const tags = /* @__PURE__ */ new Set();
4549
+ const attributes = /* @__PURE__ */ new Set();
4550
+ const values = /* @__PURE__ */ new Set();
4551
+ for (const { config, readers } of dialectes) {
4552
+ for (const tag of config.elements) tags.add(tag);
4553
+ for (const definition of Object.values(config.definition))
4554
+ for (const attribute of definition.attributes.sequence) {
4555
+ attributes.add(attribute);
4556
+ const datatype = definition.attributes.details[attribute]?.type;
4557
+ for (const value of readers.enumeratedValues(datatype)) values.add(value);
4558
+ }
4559
+ }
4560
+ const packages = dialectes.map((dialecte) => `${dialecte.packageName}@${versionOf({ cwd, dialecte })}`).sort();
4561
+ return {
4562
+ vocabulary: {
4563
+ tags: [...tags].sort(),
4564
+ attributes: [...attributes].sort(),
4565
+ values: [...values].sort()
4566
+ },
4567
+ packages,
4568
+ installedHash: createHash3("sha256").update(packages.join(INSTALLED_LIST_SEPARATOR)).digest("hex").slice(0, INSTALLED_HASH_LENGTH)
4569
+ };
4570
+ }
4571
+ function versionOf(params) {
4572
+ const own = readManifest(params.cwd);
4573
+ const folder = own?.name === params.dialecte.packageName ? params.cwd : findInstalledPackage({ cwd: params.cwd, name: params.dialecte.packageName });
4574
+ return (folder === void 0 ? void 0 : readManifest(folder)?.version) ?? "";
4575
+ }
4576
+ function emptyInstalledVocabulary() {
4577
+ return {
4578
+ vocabulary: { tags: [], attributes: [], values: [] },
4579
+ packages: [],
4580
+ installedHash: void 0
4581
+ };
4582
+ }
4583
+
4584
+ // src/lib/knowledge/standard/read-standard-input.ts
4585
+ import { existsSync as existsSync25, readdirSync as readdirSync12, realpathSync as realpathSync5, statSync as statSync7 } from "fs";
4586
+ import { join as join30 } from "path";
4587
+
4588
+ // src/lib/standard/read-standard-root.ts
4589
+ import { resolve as resolve6 } from "path";
4590
+
4591
+ // src/lib/standard/standard.constants.ts
4592
+ var STANDARD_ENVIRONMENT_VARIABLE = "DIALECTE_STANDARD";
4593
+
4594
+ // src/lib/standard/read-standard-root.ts
4595
+ function readStandardRoot(params = {}) {
4596
+ const value = (params.environment ?? process.env)[STANDARD_ENVIRONMENT_VARIABLE];
4597
+ return value ? resolve6(value) : void 0;
4598
+ }
4599
+
4600
+ // src/lib/knowledge/standard/standard-input.constants.ts
4601
+ var HIDDEN_NAME_START = ".";
4602
+ var STANDARD_FILE_EXTENSION = ".md";
4603
+ var GIT_ENTRY2 = ".git";
4604
+ var STANDARD_LAYOUT = "set DIALECTE_STANDARD to one root folder holding one folder per standard, each holding its .md files: <root>/<standard id>/<file>.md (the folder name is the standard id); keep it outside every repository";
4605
+ var INPUT_MESSAGES = {
4606
+ notSet: "no standard configured: DIALECTE_STANDARD is not set",
4607
+ missing: "DIALECTE_STANDARD names {path}, which does not exist",
4608
+ notFolder: "DIALECTE_STANDARD names {path}, a file, not a root folder",
4609
+ noStandard: "the root {path} holds no standard folder",
4610
+ topLevelFiles: "the root {path} holds .md files directly: {names}",
4611
+ workTree: "{path} is inside a git work tree ({top}): the standard and its index never live in a repository",
4612
+ folderCollision: "two standard folders have the same id: {names}",
4613
+ fileCollision: "two files of the standard {id} have the same id: {names}",
4614
+ unknownStandard: "no standard folder {id} in {path} - known: {known}"
4615
+ };
4616
+ var NAME_LIST_SEPARATOR = ", ";
4617
+
4618
+ // src/lib/knowledge/standard/standard-names-answer-of.ts
4619
+ function namesAnswerOf(params) {
4620
+ const byId2 = /* @__PURE__ */ new Map();
4621
+ for (const named of [...params.named].sort(compareNames)) {
4622
+ const known = byId2.get(named.id);
4623
+ if (known !== void 0) return { kind: "collision", names: [known, named.name] };
4624
+ byId2.set(named.id, named.name);
4625
+ }
4626
+ return {
4627
+ kind: "kept",
4628
+ kept: [...params.named].sort((left, right) => compareText(left.id, right.id))
4629
+ };
4630
+ }
4631
+ function compareNames(left, right) {
4632
+ return compareText(left.name, right.name);
4633
+ }
4634
+ function compareText(left, right) {
4635
+ if (left === right) return 0;
4636
+ return left < right ? -1 : 1;
4637
+ }
4638
+
4639
+ // src/lib/knowledge/standard/standard-files-of.ts
4640
+ function standardFilesOf(params) {
4641
+ return namesAnswerOf({
4642
+ named: params.entries.filter(
4643
+ (entry) => entry.kind === "file" && !entry.name.startsWith(HIDDEN_NAME_START) && entry.name.endsWith(STANDARD_FILE_EXTENSION)
4644
+ ).map((entry) => ({
4645
+ id: `${params.standardId}/${entry.name.slice(0, -STANDARD_FILE_EXTENSION.length).toLowerCase()}`,
4646
+ name: entry.name
4647
+ }))
4648
+ });
4649
+ }
4650
+
4651
+ // src/lib/knowledge/standard/standard-folders-of.ts
4652
+ function standardFoldersOf(params) {
4653
+ return namesAnswerOf({
4654
+ named: params.entries.filter((entry) => entry.kind === "folder" && !entry.name.startsWith(HIDDEN_NAME_START)).map((entry) => ({ id: entry.name.toLowerCase(), name: entry.name }))
4655
+ });
4656
+ }
4657
+
4658
+ // src/lib/knowledge/standard/work-tree-holding.ts
4659
+ import { existsSync as existsSync24, realpathSync as realpathSync4 } from "fs";
4660
+ import { dirname as dirname12, join as join29 } from "path";
4661
+ function workTreeHolding(params) {
4662
+ let folder = realpathSync4(nearestExisting(params.path));
4663
+ for (; ; ) {
4664
+ if (existsSync24(join29(folder, GIT_ENTRY2))) return folder;
4665
+ const parent = dirname12(folder);
4666
+ if (parent === folder) return void 0;
4667
+ folder = parent;
4668
+ }
4669
+ }
4670
+ function nearestExisting(path) {
4671
+ let existing = path;
4672
+ while (!existsSync24(existing)) existing = dirname12(existing);
4673
+ return existing;
4674
+ }
4675
+
4676
+ // src/lib/knowledge/standard/read-standard-input.ts
4677
+ function readStandardInput(params) {
4678
+ const root = readStandardRoot({ environment: params.environment });
4679
+ const rootRefusal = refusalOfRoot({ root });
4680
+ if (rootRefusal !== void 0 || root === void 0)
4681
+ return refused(rootRefusal ?? INPUT_MESSAGES.notSet, STANDARD_LAYOUT);
4682
+ const workTree = workTreeRefusal({ path: root });
4683
+ if (workTree) return refused(workTree);
4684
+ const entries = entriesOf({ folder: root });
4685
+ const topLevelFiles = entries.filter((entry) => entry.kind === "file" && entry.name.endsWith(STANDARD_FILE_EXTENSION)).filter((entry) => !entry.name.startsWith(HIDDEN_NAME_START)).map((entry) => entry.name).sort();
4686
+ if (topLevelFiles.length > 0)
4687
+ return refused(
4688
+ fillMessage({
4689
+ template: INPUT_MESSAGES.topLevelFiles,
4690
+ values: { path: root, names: topLevelFiles.join(NAME_LIST_SEPARATOR) }
4691
+ }),
4692
+ STANDARD_LAYOUT
4693
+ );
4694
+ const folders = standardFoldersOf({ entries });
4695
+ if (folders.kind === "collision")
4696
+ return refused(
4697
+ fillMessage({
4698
+ template: INPUT_MESSAGES.folderCollision,
4699
+ values: { names: folders.names.join(NAME_LIST_SEPARATOR) }
4700
+ })
4701
+ );
4702
+ if (folders.kept.length === 0)
4703
+ return refused(
4704
+ fillMessage({ template: INPUT_MESSAGES.noStandard, values: { path: root } }),
4705
+ STANDARD_LAYOUT
4706
+ );
4707
+ const known = folders.kept.map((folder) => folder.id);
4708
+ const wanted = params.standardId?.toLowerCase();
4709
+ const chosen = folders.kept.filter((folder) => wanted === void 0 || folder.id === wanted);
4710
+ if (chosen.length === 0 && wanted !== void 0)
4711
+ return refused(
4712
+ fillMessage({
4713
+ template: INPUT_MESSAGES.unknownStandard,
4714
+ values: { id: wanted, path: root, known: known.join(NAME_LIST_SEPARATOR) || "none" }
4715
+ })
4716
+ );
4717
+ const selected = [];
4718
+ for (const named of chosen) {
4719
+ const folder = join30(root, named.name);
4720
+ const folderRefusal = workTreeRefusal({ path: folder });
4721
+ if (folderRefusal) return refused(folderRefusal);
4722
+ const files = standardFilesOf({ standardId: named.id, entries: entriesOf({ folder }) });
4723
+ if (files.kind === "collision")
4724
+ return refused(
4725
+ fillMessage({
4726
+ template: INPUT_MESSAGES.fileCollision,
4727
+ values: { id: named.id, names: files.names.join(NAME_LIST_SEPARATOR) }
4728
+ })
4729
+ );
4730
+ selected.push({
4731
+ ...named,
4732
+ folder,
4733
+ files: files.kept.map((file) => ({ ...file, path: join30(folder, file.name) }))
4734
+ });
4735
+ }
4736
+ return { kind: "input", input: { root, known, selected } };
4737
+ }
4738
+ function workTreeRefusal(params) {
4739
+ const top = workTreeHolding({ path: params.path });
4740
+ return top === void 0 ? void 0 : fillMessage({ template: INPUT_MESSAGES.workTree, values: { path: params.path, top } });
4741
+ }
4742
+ function refusalOfRoot(params) {
4743
+ const { root } = params;
4744
+ if (root === void 0) return INPUT_MESSAGES.notSet;
4745
+ if (!existsSync25(root))
4746
+ return fillMessage({ template: INPUT_MESSAGES.missing, values: { path: root } });
4747
+ if (!statSync7(root).isDirectory())
4748
+ return fillMessage({ template: INPUT_MESSAGES.notFolder, values: { path: root } });
4749
+ return void 0;
4750
+ }
4751
+ function entriesOf(params) {
4752
+ return readdirSync12(params.folder).flatMap((name) => {
4753
+ const path = join30(params.folder, name);
4754
+ if (!existsSync25(path)) return [];
4755
+ const stats = statSync7(realpathSync5(path));
4756
+ if (stats.isDirectory()) return [{ name, kind: "folder" }];
4757
+ return stats.isFile() ? [{ name, kind: "file" }] : [];
4758
+ });
4759
+ }
4760
+ function refused(message, layout) {
4761
+ return layout === void 0 ? { kind: "refused", message } : { kind: "refused", message, layout };
4762
+ }
4763
+
4764
+ // src/lib/knowledge/standard/standard-cache-root.ts
4765
+ import { homedir } from "os";
4766
+ import { join as join31 } from "path";
4767
+ function standardCacheRoot(params) {
4768
+ const { environment } = params;
4769
+ const cacheHome = environment[CACHE_LOCATION.environmentVariable];
4770
+ const base = cacheHome ? cacheHome : join31(environment[CACHE_LOCATION.homeVariable] || homedir(), CACHE_LOCATION.homeFolder);
4771
+ return join31(base, CACHE_LOCATION.toolFolder);
4772
+ }
4773
+
4774
+ // src/lib/knowledge/standard/standard-files-key.ts
4775
+ import { createHash as createHash4 } from "crypto";
4776
+ import { readFileSync as readFileSync17 } from "fs";
4777
+
4778
+ // src/lib/stable-json.ts
4779
+ function stableJson(value) {
4780
+ if (Array.isArray(value)) return `[${arrayItemsJson(value).join(",")}]`;
4781
+ if (typeof value === "object" && value !== null) {
4782
+ if (!isPlainObject(value)) throw notPlainJson({ found: describeObject(value) });
4783
+ const members = Object.entries(value).filter(([, member]) => member !== void 0).sort(byKeyCodeUnits).map(([key, member]) => `${JSON.stringify(key)}:${stableJson(member)}`);
4784
+ return `{${members.join(",")}}`;
4785
+ }
4786
+ if (typeof value === "function" || typeof value === "symbol" || typeof value === "bigint")
4787
+ throw notPlainJson({ found: `a ${typeof value}` });
4788
+ return JSON.stringify(value) ?? "null";
4789
+ }
4790
+ function arrayItemsJson(items) {
4791
+ const written = [];
4792
+ for (let index = 0; index < items.length; index++) {
4793
+ if (!(index in items)) throw notPlainJson({ found: `a sparse array (no item at ${index})` });
4794
+ const item = items[index];
4795
+ written.push(item === void 0 ? "null" : stableJson(item));
4796
+ }
4797
+ return written;
4798
+ }
4799
+ function isPlainObject(value) {
4800
+ const prototype = Object.getPrototypeOf(value);
4801
+ return prototype === Object.prototype || prototype === null;
4802
+ }
4803
+ function describeObject(value) {
4804
+ const name = value.constructor?.name;
4805
+ return typeof name === "string" && name !== "" ? `a ${name}` : "an object with a prototype";
4806
+ }
4807
+ function notPlainJson(params) {
4808
+ return new TypeError(`stableJson: not plain JSON data: ${params.found}`);
4809
+ }
4810
+ function byKeyCodeUnits([first], [second]) {
4811
+ return first < second ? -1 : first > second ? 1 : 0;
4812
+ }
4813
+
4814
+ // src/lib/knowledge/standard/standard-files-key.constants.ts
4815
+ var STANDARD_FILES_KEY_PREFIX = "sha256:";
4816
+
4817
+ // src/lib/knowledge/standard/standard-files-key.ts
4818
+ function standardFilesKey(params) {
4819
+ const pairs = params.files.map((file) => [file.id, file.sha256]).sort(([first], [second]) => first < second ? -1 : first > second ? 1 : 0);
4820
+ return `${STANDARD_FILES_KEY_PREFIX}${sha256Of2(stableJson(pairs))}`;
4821
+ }
4822
+ function sha256Of2(content) {
4823
+ return createHash4("sha256").update(content).digest("hex");
4824
+ }
4825
+
4826
+ // src/lib/knowledge/ask/ask.constants.ts
4827
+ var SLOT_NAME = "[^\\s?@]+";
4828
+ var SLOT_CODE = "[^\\s?]+";
4829
+ var SLOT_REST = ".+?";
4830
+ var SLOT_PLACEHOLDER_PATTERNS = {
4831
+ "<T>": `(?<tag#>${SLOT_NAME})(?:\\s+(?:under|in)\\s+(?<parent#>${SLOT_NAME}))?`,
4832
+ "<A>": `(?:(?<tag#a>${SLOT_NAME})@(?<attribute#a>${SLOT_NAME})|@?(?<attribute#b>${SLOT_NAME})(?:\\s+on\\s+(?<tag#b>${SLOT_NAME}))?)`,
4833
+ "<C>": `(?<code#>${SLOT_CODE})`,
4834
+ "<rest>": `(?<rest#>${SLOT_REST})`
4835
+ };
4836
+ var SETUP_HASH_ALGORITHM = "sha256";
4837
+ var SETUP_HASH_ENCODING = "hex";
4838
+ var IN_WORD_HYPHEN_PATTERN = new RegExp("(?<=\\p{L})-(?=\\p{L})", "gu");
4839
+ var REPORT_VERDICTS = [
4840
+ "yes",
4841
+ "no",
4842
+ "depends",
4843
+ "value",
4844
+ "not-in-text"
4845
+ ];
4846
+ var NOT_KNOWN_VERDICT = "not-known";
4847
+ var OUTSIDE_VERDICTS = [
4848
+ ...REPORT_VERDICTS,
4849
+ NOT_KNOWN_VERDICT
4850
+ ];
4851
+ var UPPER_CASE_PATTERN = new RegExp("\\p{Lu}", "u");
4852
+ var CLAIM_MAX_HELD_MS = 10 * 60 * 1e3;
4853
+
4854
+ // src/lib/knowledge/ask/selected-folders-of.ts
4855
+ function selectedFoldersOf(params) {
4856
+ const { environment, standardIds } = params;
4857
+ if (standardIds === void 0) {
4858
+ const input = readStandardInput({ environment });
4859
+ return input.kind === "refused" ? input : { kind: "selected", folders: input.input.selected };
4860
+ }
4861
+ const folders = /* @__PURE__ */ new Map();
4862
+ for (const standardId of standardIds) {
4863
+ const input = readStandardInput({ environment, standardId });
4864
+ if (input.kind === "refused") return input;
4865
+ for (const folder of input.input.selected) folders.set(folder.id, folder);
4866
+ }
4867
+ return { kind: "selected", folders: [...folders.values()].sort(byId) };
4868
+ }
4869
+ function isReadableFolder(params) {
4870
+ return params.folder.files.length > 0;
4871
+ }
4872
+ function byId(first, second) {
4873
+ return first.id < second.id ? -1 : first.id > second.id ? 1 : 0;
4874
+ }
4875
+
4876
+ // src/lib/knowledge/ask/load-standard-indexes.ts
4877
+ async function loadStandardIndexes(params) {
4878
+ const { environment } = params;
4879
+ const selected = selectedFoldersOf({ environment, standardIds: params.standardIds });
4880
+ if (selected.kind === "refused") return selected;
4881
+ const cacheRoot = standardCacheRoot({ environment });
4882
+ const cacheRefusal = workTreeRefusal({ path: cacheRoot });
4883
+ if (cacheRefusal) return { kind: "refused", message: cacheRefusal };
4884
+ const vocabulary = await vocabularyOf2(params);
4885
+ if (vocabulary.kind === "unknownPackage") return vocabulary;
4886
+ const { installed } = vocabulary;
4887
+ const vocabularyRefusal = params.checkVocabulary?.({ installed });
4888
+ if (vocabularyRefusal) return { kind: "refused", message: vocabularyRefusal };
4889
+ const cliVersion = readCliVersion();
4890
+ const loaded = {
4891
+ kind: "loaded",
4892
+ standard: { kind: "documents", indexes: [], folders: [] },
4893
+ ready: [],
4894
+ skipped: [],
4895
+ manifest: [],
4896
+ installed,
4897
+ originalLines: /* @__PURE__ */ new Map()
4898
+ };
4899
+ for (const standard of selected.folders) {
4900
+ if (!isReadableFolder({ folder: standard })) {
4901
+ loaded.skipped.push(standard);
4902
+ continue;
4903
+ }
4904
+ const answer = await ensureStandardIndex({
4905
+ standard,
4906
+ cacheRoot,
4907
+ installed,
4908
+ rebuild: params.rebuild ?? false,
4909
+ cliVersion,
4910
+ progress: params.progress,
4911
+ afterFileRead: params.afterFileRead
4912
+ });
4913
+ if (answer.kind === "aborted") return answer;
4914
+ loaded.ready.push(answer.index);
4915
+ loaded.standard.indexes.push(answer.index.search);
4916
+ const read = filesReadOf({ standard, search: answer.index.search });
4917
+ const manifest = read.map((entry) => entry.manifest);
4918
+ loaded.manifest.push(...manifest);
4919
+ for (const entry of read) loaded.originalLines.set(entry.manifest.id, entry.lines);
4920
+ loaded.standard.folders.push({ id: standard.id, files: standardFilesKey({ files: manifest }) });
4921
+ }
4922
+ return loaded;
4923
+ }
4924
+ function filesReadOf(params) {
4925
+ return params.standard.files.map(function fileReadOf(file) {
4926
+ const bytes = readFileSync18(file.path);
4927
+ return {
4928
+ manifest: {
4929
+ id: file.id,
4930
+ sha256: createHash5(SETUP_HASH_ALGORITHM).update(bytes).digest(SETUP_HASH_ENCODING),
4931
+ lines: params.search.files.find((index) => index.fileId === file.id)?.lineCount ?? 0
4932
+ },
4933
+ lines: bytes.toString("utf8").split(LINE_BREAK_PATTERN)
4934
+ };
4935
+ });
4936
+ }
4937
+ async function vocabularyOf2(params) {
4938
+ if (params.readVocabulary === false)
4939
+ return { kind: "read", installed: emptyInstalledVocabulary() };
4940
+ return readInstalledVocabulary({ cwd: params.cwd, packageName: params.packageName });
4941
+ }
4942
+
4943
+ // src/lib/knowledge/standard/cap-slice-range.ts
4944
+ function capSliceRange(params) {
4945
+ const { lines, noiseRanges, first, last, windowFirst } = params;
4946
+ if (countedLines({ from: lines[first].from, to: lines[last].to, noiseRanges }) <= SLICE_LINE_CAP)
4947
+ return { first, last };
4948
+ let end = windowFirst;
4949
+ while (end < last && countedLines({ from: lines[windowFirst].from, to: lines[end + 1].to, noiseRanges }) <= SLICE_LINE_CAP)
4950
+ end++;
4951
+ return { first: windowFirst, last: end };
4952
+ }
4953
+ function countedLines(params) {
4954
+ const { from, to, noiseRanges } = params;
4955
+ let count = to - from + 1;
4956
+ for (const range of noiseRanges) {
4957
+ const overlap = Math.min(to, range.to) - Math.max(from, range.from) + 1;
4958
+ if (overlap > 0) count -= overlap;
4959
+ }
4960
+ return count;
4961
+ }
4962
+
4963
+ // src/lib/knowledge/standard/round-score.ts
4964
+ function roundScore(score) {
4965
+ const scale = 10 ** SCORE_DECIMALS;
4966
+ return Math.round(score * scale) / scale;
4967
+ }
4968
+
4969
+ // src/lib/knowledge/standard/best-window-of.ts
4970
+ function bestWindowOf(params) {
4971
+ const { lines, noiseRanges, contributions, titleLine } = params;
4972
+ const hits = bodyHitsOf({ contributions, titleLine });
4973
+ if (hits.length === 0) return null;
4974
+ const lastHit = hits[hits.length - 1].line;
4975
+ const counts = contributions.map(() => 0);
4976
+ let held = 0;
4977
+ let sum = 0;
4978
+ let next = 0;
4979
+ let best = null;
4980
+ let bestSum = -1;
4981
+ for (let start = 0; start < hits.length; ) {
4982
+ const first = hits[start].line;
4983
+ const end = capSliceRange({ lines, noiseRanges, first, last: lastHit, windowFirst: first }).last;
4984
+ for (; next < hits.length && hits[next].line <= end; next++) {
4985
+ const { term } = hits[next];
4986
+ if (counts[term]++ === 0) {
4987
+ held++;
4988
+ sum += contributions[term].contribution;
4989
+ }
4990
+ }
4991
+ const rounded = roundScore(sum);
4992
+ if (rounded > bestSum) {
4993
+ best = { first, last: hits[next - 1].line };
4994
+ bestSum = rounded;
4995
+ }
4996
+ if (held === contributions.length || end >= lastHit) break;
4997
+ for (; start < next && hits[start].line === first; start++) {
4998
+ const { term } = hits[start];
4999
+ if (--counts[term] === 0) {
5000
+ held--;
5001
+ sum -= contributions[term].contribution;
5002
+ }
5003
+ }
5004
+ }
5005
+ return best;
5006
+ }
5007
+ function bodyHitsOf(params) {
5008
+ return params.contributions.flatMap(
5009
+ (contribution, term) => contribution.lines.filter((line) => line !== params.titleLine).map((line) => ({ line, term }))
5010
+ ).sort((left, right) => left.line - right.line);
5011
+ }
5012
+
5013
+ // src/lib/knowledge/standard/query-terms-of.ts
5014
+ function queryTermsOf(params) {
5015
+ const { query, about, names } = params;
5016
+ const terms = [];
5017
+ const seen = /* @__PURE__ */ new Set();
5018
+ const aboutKey = about === void 0 ? null : keyOf({ kind: "name", key: about });
5019
+ for (const match of normaliseText(query).matchAll(WORD_TOKEN_PATTERN)) {
5020
+ const typed = match[0];
5021
+ const term = termOf({ typed, names });
5022
+ if (!term) continue;
5023
+ const key = keyOf(term);
5024
+ if (seen.has(key) || key === aboutKey) continue;
5025
+ seen.add(key);
5026
+ terms.push(term);
5027
+ }
5028
+ if (about !== void 0)
5029
+ terms.push({ typed: about, kind: "name", key: about, factor: ABOUT_FACTOR });
5030
+ return terms;
5031
+ }
5032
+ function termOf(params) {
5033
+ const { typed, names } = params;
5034
+ if (names.has(typed) && !isOrdinaryWord(typed))
5035
+ return { typed, kind: "name", key: typed, factor: 1 };
5036
+ const [stem2] = wordKeysOf({ token: typed, split: false });
5037
+ return stem2 === void 0 ? null : { typed, kind: "word", key: stem2, factor: 1 };
5038
+ }
5039
+ function isOrdinaryWord(name) {
5040
+ return name.length >= MINIMUM_WORD_LENGTH && LOWERCASE_WORD_PATTERN.test(name);
5041
+ }
5042
+ function keyOf(term) {
5043
+ return `${term.kind}:${term.key}`;
5044
+ }
5045
+
5046
+ // src/lib/knowledge/standard/score-units.ts
5047
+ function scoreUnits(params) {
5048
+ const { index, terms } = params;
5049
+ const scores = /* @__PURE__ */ new Map();
5050
+ for (const [termIndex, term] of terms.entries()) {
5051
+ const { hits, weight } = term.kind === "word" ? wordHits({ index, stem: term.key }) : nameHits({ index, name: term.key });
5052
+ for (const hit of hits) {
5053
+ const titleLine = index.units[hit.unit].titleLine;
5054
+ const titleFactor = titleLine !== null && hit.lines.includes(titleLine) ? TITLE_HIT_FACTOR : 1;
5055
+ const score = scores.get(hit.unit) ?? emptyScore({ unit: hit.unit, termCount: terms.length });
5056
+ scores.set(hit.unit, score);
5057
+ const contribution = titleFactor * term.factor / weight;
5058
+ score.score += contribution;
5059
+ score.termsHit[termIndex] = true;
5060
+ score.contributions.push({ term: termIndex, contribution, lines: hit.lines });
5061
+ for (const line of hit.lines) score.hitLines.push(line);
5062
+ }
5063
+ }
5064
+ return [...scores.values()];
5065
+ }
5066
+ function wordHits(params) {
5067
+ const { words, lineUnits } = params.index;
5068
+ const lines = Object.hasOwn(words.stems, params.stem) ? words.stems[params.stem] : [];
5069
+ const byUnit = /* @__PURE__ */ new Map();
5070
+ for (const line of lines) {
5071
+ const unit = lineUnits[line];
5072
+ const hit = byUnit.get(unit);
5073
+ if (hit) hit.lines.push(line);
5074
+ else byUnit.set(unit, { unit, lines: [line] });
5075
+ }
5076
+ return {
5077
+ hits: [...byUnit.values()],
5078
+ weight: frequencyWeight({ lineCount: lines.length, logicalLineCount: words.logicalLineCount })
5079
+ };
5080
+ }
5081
+ function nameHits(params) {
5082
+ const { tagLinks, words } = params.index;
5083
+ const links = Object.hasOwn(tagLinks, params.name) ? tagLinks[params.name] : [];
5084
+ const lineCount = links.reduce((count, link) => count + link.lines.length, 0);
5085
+ return {
5086
+ hits: links.map((link) => ({ unit: link.unit, lines: link.lines })),
5087
+ weight: frequencyWeight({ lineCount, logicalLineCount: words.logicalLineCount })
5088
+ };
5089
+ }
5090
+ function frequencyWeight(params) {
5091
+ const { lineCount, logicalLineCount } = params;
5092
+ const common = lineCount > COMMON_WORD_SHARE * logicalLineCount;
5093
+ return (1 + Math.log(1 + lineCount)) * (common ? COMMON_WORD_WEIGHT_FACTOR : 1);
5094
+ }
5095
+ function emptyScore(params) {
5096
+ return {
5097
+ unit: params.unit,
5098
+ score: 0,
5099
+ termsHit: Array.from({ length: params.termCount }, () => false),
5100
+ hitLines: [],
5101
+ contributions: []
5102
+ };
5103
+ }
5104
+
5105
+ // src/lib/knowledge/standard/find-in-standard.ts
5106
+ function findInStandard(params) {
5107
+ const { indexes, query, about } = params;
5108
+ const limit = params.limit ?? DEFAULT_FIND_LIMIT2;
5109
+ const names = new Set(
5110
+ indexes.flatMap((index) => [
5111
+ ...index.vocabulary.tags,
5112
+ ...index.vocabulary.attributes,
5113
+ ...index.vocabulary.values
5114
+ ])
5115
+ );
5116
+ const terms = queryTermsOf({ query, about, names });
5117
+ if (terms.length === 0) return [];
5118
+ const standards = indexes.map((index) => ({
5119
+ index,
5120
+ lines: index.files.flatMap((file) => file.logicalLines),
5121
+ noiseRanges: new Map(index.files.map((file) => [file.fileId, file.noiseRanges]))
5122
+ }));
5123
+ const direct = standards.flatMap(
5124
+ (searched, standard) => scoreUnits({ index: searched.index, terms }).map((score) => ({
5125
+ slice: directSliceOf({ searched, score, terms }),
5126
+ standard,
5127
+ unit: score.unit
5128
+ }))
5129
+ ).sort(compareRanked).slice(0, limit);
5130
+ const linked = linkedSlicesOf({ standards, direct, limit });
5131
+ return [...direct, ...linked].map((ranked) => ranked.slice);
5132
+ }
5133
+ function directSliceOf(params) {
5134
+ const { searched, score, terms } = params;
5135
+ const unit = searched.index.units[score.unit];
5136
+ const noiseRanges = searched.noiseRanges.get(unit.fileId) ?? [];
5137
+ const window = bestWindowOf({
5138
+ lines: searched.lines,
5139
+ noiseRanges,
5140
+ contributions: score.contributions,
5141
+ titleLine: unit.titleLine
5142
+ });
5143
+ const range = window ? capSliceRange({
5144
+ lines: searched.lines,
5145
+ noiseRanges,
5146
+ ...hitSliceBounds({ searched, noiseRanges, score, unit, window })
5147
+ }) : (
5148
+ // a unit hit only in its heading title or caption: the slice runs through its body, so it cites text
5149
+ capSliceRange({
5150
+ lines: searched.lines,
5151
+ noiseRanges,
5152
+ first: unit.firstLine,
5153
+ last: unit.lastLine,
5154
+ windowFirst: unit.firstLine
5155
+ })
5156
+ );
5157
+ return {
5158
+ file: unit.fileId,
5159
+ from: searched.lines[range.first].from,
5160
+ to: searched.lines[range.last].to,
5161
+ clause: unit.clause,
5162
+ title: unit.title,
5163
+ score: roundScore(score.score),
5164
+ terms: terms.filter((_term, index) => score.termsHit[index]).map((term) => term.typed),
5165
+ linked: false
5166
+ };
5167
+ }
5168
+ function hitSliceBounds(params) {
5169
+ const { searched, noiseRanges, score, unit, window } = params;
5170
+ const last = score.hitLines.reduce((latest, line) => Math.max(latest, line), window.last);
5171
+ const fromCaption = unit.kind === "table" && capSliceRange({
5172
+ lines: searched.lines,
5173
+ noiseRanges,
5174
+ first: unit.firstLine,
5175
+ last: window.last,
5176
+ windowFirst: unit.firstLine
5177
+ }).last === window.last;
5178
+ const first = fromCaption ? unit.firstLine : window.first;
5179
+ return { first, last, windowFirst: first };
5180
+ }
5181
+ function compareRanked(left, right) {
5182
+ if (left.slice.score !== right.slice.score) return right.slice.score - left.slice.score;
5183
+ if (left.slice.file !== right.slice.file) return left.slice.file < right.slice.file ? -1 : 1;
5184
+ return left.slice.from - right.slice.from;
5185
+ }
5186
+ function linkedSlicesOf(params) {
5187
+ const { standards, direct, limit } = params;
5188
+ const given = new Set(direct.map((ranked) => `${ranked.standard}:${ranked.unit}`));
5189
+ const targets = /* @__PURE__ */ new Map();
5190
+ const files = /* @__PURE__ */ new Map();
5191
+ const linked = [];
5192
+ for (const ranked of direct) {
5193
+ const searched = standards[ranked.standard];
5194
+ const filesById = files.get(ranked.standard) ?? filesOf(searched);
5195
+ const unitOfTarget = targets.get(ranked.standard) ?? targetsOf2(searched);
5196
+ files.set(ranked.standard, filesById);
5197
+ targets.set(ranked.standard, unitOfTarget);
5198
+ const file = filesById.get(ranked.slice.file);
5199
+ for (const reference of file?.crossReferences ?? []) {
5200
+ if (linked.length === limit) return linked;
5201
+ if (!reference.resolved) continue;
5202
+ if (reference.from < ranked.slice.from || reference.from > ranked.slice.to) continue;
5203
+ const unit = unitOfTarget.get(`${ranked.slice.file}#${reference.target}`);
5204
+ if (unit === void 0 || given.has(`${ranked.standard}:${unit}`)) continue;
5205
+ given.add(`${ranked.standard}:${unit}`);
5206
+ linked.push({ slice: linkedSliceOf({ searched, unit }), standard: ranked.standard, unit });
5207
+ }
5208
+ }
5209
+ return linked;
5210
+ }
5211
+ function linkedSliceOf(params) {
5212
+ const { searched } = params;
5213
+ const unit = searched.index.units[params.unit];
5214
+ const range = capSliceRange({
5215
+ lines: searched.lines,
5216
+ noiseRanges: searched.noiseRanges.get(unit.fileId) ?? [],
5217
+ first: unit.firstLine,
5218
+ last: unit.lastLine,
5219
+ windowFirst: unit.firstLine
5220
+ });
5221
+ return {
5222
+ file: unit.fileId,
5223
+ from: searched.lines[range.first].from,
5224
+ to: searched.lines[range.last].to,
5225
+ clause: unit.clause,
5226
+ title: unit.title,
5227
+ score: 0,
5228
+ terms: [],
5229
+ linked: true
5230
+ };
5231
+ }
5232
+ function targetsOf2(searched) {
5233
+ const unitOfTarget = /* @__PURE__ */ new Map();
5234
+ for (const [index, unit] of searched.index.units.entries()) {
5235
+ if (unit.target === null) continue;
5236
+ const key = `${unit.fileId}#${unit.target}`;
5237
+ if (!unitOfTarget.has(key)) unitOfTarget.set(key, index);
5238
+ }
5239
+ return unitOfTarget;
5240
+ }
5241
+ function filesOf(searched) {
5242
+ return new Map(searched.index.files.map((file) => [file.fileId, file]));
5243
+ }
2942
5244
  export {
2943
5245
  answerMembers,
2944
5246
  answerSchema,
2945
5247
  describeElement,
5248
+ findInStandard,
5249
+ loadStandardIndexes,
2946
5250
  packagesText,
2947
5251
  readApiIndexes,
2948
5252
  readCliVersion,