@descent-vtt/spec-graph 0.13.1 → 0.14.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.
@@ -1 +1 @@
1
- {"version":3,"file":"config.js","sourceRoot":"","sources":["../src/config.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AAEH,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AAEnD,OAAO,EAAE,YAAY,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AACnD,OAAO,EAAE,mBAAmB,EAAoB,MAAM,oBAAoB,CAAC;AAC3E,OAAO,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AACtC,OAAO,EAAE,aAAa,EAA8C,MAAM,YAAY,CAAC;AAEvF,8EAA8E;AAC9E,MAAM,CAAC,MAAM,YAAY,GAAsB,MAAM,CAAC,MAAM,CAAC;IAC3D,kBAAkB;IAClB,wBAAwB;CACzB,CAAC,CAAC;AAEH,kEAAkE;AAClE,MAAM,CAAC,MAAM,kBAAkB,GAAG,YAAY,CAAC;AAkE/C,MAAM,KAAK,GAAiB,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,IAAI,EAAE,QAAQ,EAAE,EAAE,EAAE,CAAC;AAEvE;;;;;;GAMG;AACH,MAAM,UAAU,UAAU,CAAC,IAAY,EAAE,IAAI,GAA6B,WAAW;IACnF,KAAK,MAAM,IAAI,IAAI,YAAY,EAAE,CAAC;QAChC,MAAM,GAAG,GAAG,OAAO,CAAC,IAAI,EAAE,GAAG,IAAI,IAAI,IAAI,EAAE,CAAC,CAAC;QAC7C,IAAI,GAAG,KAAK,IAAI;YAAE,SAAS;QAC3B,OAAO,WAAW,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC;IAChC,CAAC;IAED,2EAA2E;IAC3E,sEAAsE;IACtE,0EAA0E;IAC1E,MAAM,GAAG,GAAG,OAAO,CAAC,IAAI,EAAE,GAAG,I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,CAAC,CAAC,IAAI,CAAC;AAC9D,CAAC;AAED,SAAS,WAAW,CAAC,IAAY;IAC/B,OAAO,YAAY,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC;AACpC,CAAC","sourcesContent":["/**\n * Repository configuration.\n *\n * Three ADRs left the same open question: `--ignore-ref` patterns, include\n * globs and rule severities all belong to a repository rather than to whoever\n * typed the command, and an npm script was doing that job by accumulating\n * flags. A CI invocation carrying eight `--ignore-ref` arguments is a\n * configuration file that has not admitted what it is.\n *\n * The format is JSON, parsed with `JSON.parse`. That is not a shortcut - it is\n * the reason this file exists at all. spec-graph has no runtime dependencies,\n * and a YAML or TOML reader would be the largest thing in the package, to read\n * a file with nine keys in it.\n *\n * Every key but `rules` and `maxRelated` mirrors a flag, and a flag always\n * wins. Configuration is where a team writes down what is true of the\n * repository; a flag is where somebody overrides it for one run.\n */\n\nimport { existsSync, readFileSync } from 'node:fs';\n\nimport { dirnamePosix, toPosix } from './paths.js';\nimport { compileProjectRules, type ProjectRule } from './project-rules.js';\nimport { RULE_IDS } from './rules.js';\nimport { isProjectRule, type AnyRuleId, type RuleId, type Severity } from './types.js';\n\n/** File names looked for, in order. The first that exists is the one used. */\nexport const CONFIG_FILES: readonly string[] = Object.freeze([\n '.spec-graph.json',\n 'spec-graph.config.json',\n]);\n\n/** The `package.json` key read when no config file is present. */\nexport const CONFIG_PACKAGE_KEY = 'spec-graph';\n\nexport interface SpecGraphConfig {\n readonly patterns?: readonly string[] | undefined;\n readonly ignore?: readonly string[] | undefined;\n readonly ignoreReferences?: readonly string[] | undefined;\n /**\n * Families a bare identifier in prose may name.\n *\n * When set, `ADR-0099` is only ever read as a citation if `ADR` is listed.\n * Everything else in prose stays prose.\n */\n readonly families?: readonly string[] | undefined;\n /** Families that are never citations, whatever else the corpus contains. */\n readonly ignoreFamilies?: readonly string[] | undefined;\n /**\n * Files that are logs of what was decided rather than decisions themselves.\n *\n * Journals, changelogs, minutes. Their links are still checked; their\n * obligations and lifecycle are not. See ADR-0011.\n */\n readonly historyPatterns?: readonly string[] | undefined;\n /** Path to the accepted-debt baseline, relative to the root. See ADR-0012. */\n readonly baseline?: string | undefined;\n /** Fail when a baseline entry no longer occurs. See ADR-0012. */\n readonly ratchet?: boolean | undefined;\n readonly severities?: Partial<Record<AnyRuleId, Severity>> | undefined;\n readonly strict?: boolean | undefined;\n readonly maxRelated?: number | undefined;\n /**\n * Conventions this repository checks that spec-graph does not.\n *\n * A selector, a sentence and a severity. Compiled here rather than carried as\n * raw JSON, so a rule that cannot run is reported at load time next to every\n * other configuration problem - and not as a rule that quietly finds nothing.\n * See ADR-0016.\n */\n readonly rules?: readonly ProjectRule[] | undefined;\n}\n\nexport interface LoadedConfig {\n readonly config: SpecGraphConfig;\n /** Where it came from, for `--verbose` and for error messages. */\n readonly source: string | null;\n /** Keys that were present but unusable. Reported, never silently dropped. */\n readonly problems: readonly string[];\n}\n\nexport interface DiscoveredConfig extends LoadedConfig {\n /**\n * The directory the configuration was found in.\n *\n * This is the root of the run. Every path in spec-graph is relative to it -\n * node identities, baseline keys, SARIF locations - so the configuration file\n * naming the repository is the same statement as the repository having a\n * root. See ADR-0018.\n */\n readonly root: string;\n}\n\n/** Injected so discovery can be tested without a directory tree. */\nexport interface DiscoveryIO {\n readonly read?: ((path: string) => string) | undefined;\n readonly exists?: ((path: string) => boolean) | undefined;\n}\n\nconst EMPTY: LoadedConfig = { config: {}, source: null, problems: [] };\n\n/**\n * Reads configuration from a directory.\n *\n * Never throws, and never decides. Every problem is collected and handed back\n * whole, so the reader sees all of them at once rather than the first; what a\n * problem costs is the caller's to say, and the CLI stops on one.\n */\nexport function loadConfig(root: string, read: (path: string) => string = defaultRead): LoadedConfig {\n for (const name of CONFIG_FILES) {\n const raw = tryRead(read, `${root}/${name}`);\n if (raw === null) continue;\n return parseConfig(raw, name);\n }\n\n // The first two returns are the third one's answer given early: no file is\n // `JSON.parse(null)`, which is `null`, and a parse that failed leaves\n // `parsed` undefined - neither is a record. Their mutants are equivalent.\n const pkg = tryRead(read, `${root}/package.json`);\n if (pkg === null) return EMPTY;\n let parsed: unknown;\n try {\n parsed = JSON.parse(pkg);\n } catch {\n return EMPTY;\n }\n if (!isRecord(parsed)) return EMPTY;\n const section = parsed[CONFIG_PACKAGE_KEY];\n if (section === undefined) return EMPTY;\n if (!isRecord(section)) {\n return { config: {}, source: `package.json`, problems: [`package.json: \"${CONFIG_PACKAGE_KEY}\" must be an object`] };\n }\n return readFields(section, `package.json#${CONFIG_PACKAGE_KEY}`);\n}\n\n/**\n * Finds the configuration by walking up from a directory.\n *\n * A monorepo is invoked from inside a package - `packages/auth`, or\n * `docs/architecture` - and reading configuration from the working directory\n * meant that the same repository checked differently depending on where\n * somebody stood in it. ADR-0010 worried that discovery would make a run\n * depend on where it started. It does the opposite: because the directory\n * holding the configuration becomes the root, a run from anywhere inside the\n * repository produces byte-identical output to a run from the top.\n *\n * The walk stops at the repository, which is a directory holding `.git`.\n * Above that is somebody else's checkout or a home directory, and a run that\n * silently picked up a configuration file nobody in the repository can see\n * would be worse than no discovery at all. See ADR-0018.\n */\nexport function discoverConfig(from: string, io: DiscoveryIO = {}): DiscoveredConfig {\n const read = io.read ?? defaultRead;\n const exists = io.exists ?? existsSync;\n const start = toPosix(from).replace(/\\/+$/, '');\n\n let directory = start;\n for (;;) {\n const loaded = loadConfig(directory, read);\n if (loaded.source !== null) return { ...loaded, root: directory };\n if (exists(`${directory}/.git`)) break;\n const parent = dirnamePosix(directory);\n // A path with no separator left in it gives back `''`, and stopping there is\n // what keeps a relative start from going on to read `/.spec-graph.json`,\n // which is what a file name joined to `''` spells. The second guard is true\n // only when the directory is `''` already, and then so is the first: its\n // mutant is equivalent. It stays so the loop still ends if the parent of a\n // path is ever spelled as Node's `dirname` spells it, `.` for `.`.\n if (parent === '' || parent === directory) break;\n directory = parent;\n }\n return { ...EMPTY, root: start };\n}\n\n/** Parses config text. Exported so the shape can be tested without a disk. */\nexport function parseConfig(raw: string, source: string): LoadedConfig {\n let parsed: unknown;\n try {\n parsed = JSON.parse(withoutBom(raw));\n } catch (error) {\n return { config: {}, source, problems: [`${source} is not valid JSON: ${(error as Error).message}`] };\n }\n if (!isRecord(parsed)) return { config: {}, source, problems: [`${source} must contain a JSON object`] };\n return readFields(parsed, source);\n}\n\nfunction readFields(raw: Record<string, unknown>, source: string): LoadedConfig {\n const problems: string[] = [];\n const config: {\n -readonly [K in keyof SpecGraphConfig]: SpecGraphConfig[K];\n } = {};\n\n const strings = (key: keyof SpecGraphConfig): readonly string[] | undefined => {\n const value = raw[key];\n if (value === undefined) return undefined;\n if (!Array.isArray(value) || value.some((entry) => typeof entry !== 'string')) {\n problems.push(`${source}: \"${key}\" must be an array of strings`);\n return undefined;\n }\n return value as string[];\n };\n\n config.patterns = strings('patterns');\n config.ignore = strings('ignore');\n config.ignoreReferences = strings('ignoreReferences');\n config.families = strings('families');\n config.ignoreFamilies = strings('ignoreFamilies');\n config.historyPatterns = strings('historyPatterns');\n\n if (raw['baseline'] !== undefined) {\n if (typeof raw['baseline'] !== 'string' || raw['baseline'].trim().length === 0) {\n problems.push(`${source}: \"baseline\" must be a path`);\n } else {\n config.baseline = raw['baseline'];\n }\n }\n\n if (raw['strict'] !== undefined) {\n if (typeof raw['strict'] !== 'boolean') problems.push(`${source}: \"strict\" must be true or false`);\n else config.strict = raw['strict'];\n }\n\n if (raw['ratchet'] !== undefined) {\n if (typeof raw['ratchet'] !== 'boolean') problems.push(`${source}: \"ratchet\" must be true or false`);\n else config.ratchet = raw['ratchet'];\n }\n\n if (raw['maxRelated'] !== undefined) {\n const value = raw['maxRelated'];\n // `Number.isInteger` is false for anything but a number, so the `typeof`\n // only narrows the type for `value < 0`, and its mutant is equivalent.\n if (typeof value !== 'number' || !Number.isInteger(value) || value < 0) {\n problems.push(`${source}: \"maxRelated\" must be a non-negative whole number`);\n } else {\n config.maxRelated = value;\n }\n }\n\n if (raw['severities'] !== undefined) {\n const value = raw['severities'];\n if (!isRecord(value)) {\n problems.push(`${source}: \"severities\" must be an object of rule to severity`);\n } else {\n const severities: Partial<Record<AnyRuleId, Severity>> = {};\n for (const [rule, level] of Object.entries(value)) {\n // A project rule is named here by its full id, `project:no-drafts`, the\n // same spelling `--rule` takes and a report prints. Whether one exists\n // is checked below, once both halves of the file have been read.\n if (!RULE_IDS.includes(rule as RuleId) && !isProjectRule(rule as AnyRuleId)) {\n problems.push(`${source}: unknown rule \"${rule}\" in \"severities\"`);\n continue;\n }\n if (level !== 'error' && level !== 'warn' && level !== 'info' && level !== 'off') {\n problems.push(`${source}: \"severities.${rule}\" must be error, warn, info or off`);\n continue;\n }\n severities[rule as AnyRuleId] = level;\n }\n config.severities = severities;\n }\n }\n\n const compiled = raw['rules'] === undefined ? null : compileProjectRules(raw['rules'], source);\n if (compiled !== null) {\n problems.push(...compiled.problems);\n config.rules = compiled.rules;\n }\n\n // A severity naming a project rule that nothing defines is a line that will\n // never do anything, and reading like it does is the one thing a\n // configuration file must not be allowed to do. (A fallback seeded with\n // something that is not a rule defines no id, so that mutant is equivalent.)\n const defined = new Set<string>((compiled?.rules ?? []).map((rule) => rule.id));\n for (const rule of Object.keys(config.severities ?? {})) {\n if (!isProjectRule(rule as AnyRuleId) || defined.has(rule)) continue;\n problems.push(`${source}: \"severities.${rule}\" names no rule in \"rules\"`);\n }\n\n for (const key of Object.keys(raw)) {\n if (!KNOWN_KEYS.has(key)) problems.push(`${source}: unknown key \"${key}\"`);\n }\n\n return { config, source, problems };\n}\n\nconst KNOWN_KEYS: ReadonlySet<string> = new Set([\n 'patterns',\n 'ignore',\n 'ignoreReferences',\n 'families',\n 'ignoreFamilies',\n 'historyPatterns',\n 'baseline',\n 'ratchet',\n 'rules',\n 'severities',\n 'strict',\n 'maxRelated',\n // Tolerated so an editor can be pointed at a schema without being told off.\n '$schema',\n]);\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction tryRead(read: (path: string) => string, path: string): string | null {\n try {\n return withoutBom(read(path));\n } catch {\n return null;\n }\n}\n\n/**\n * Drops a leading byte-order mark.\n *\n * `JSON.parse` rejects one, and several Windows editors write one by default -\n * a config that silently stops applying because of an invisible first character\n * is the worst kind of configuration bug.\n */\nfunction withoutBom(text: string): string {\n return text.charCodeAt(0) === 0xfeff ? text.slice(1) : text;\n}\n\nfunction defaultRead(path: string): string {\n return readFileSync(path, 'utf8');\n}\n"]}
1
+ {"version":3,"file":"config.js","sourceRoot":"","sources":["../src/config.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AAEH,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AAEnD,OAAO,EAAE,YAAY,EAAE,MAAM,eAAe,CAAC;AAC7C,OAAO,EAAE,YAAY,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AACnD,OAAO,EAAE,mBAAmB,EAAoB,MAAM,oBAAoB,CAAC;AAC3E,OAAO,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AACtC,OAAO,EAAE,aAAa,EAA8C,MAAM,YAAY,CAAC;AAEvF,8EAA8E;AAC9E,MAAM,CAAC,MAAM,YAAY,GAAsB,MAAM,CAAC,MAAM,CAAC;IAC3D,kBAAkB;IAClB,wBAAwB;CACzB,CAAC,CAAC;AAEH,kEAAkE;AAClE,MAAM,CAAC,MAAM,kBAAkB,GAAG,YAAY,CAAC;AAkE/C,MAAM,KAAK,GAAiB,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,IAAI,EAAE,QAAQ,EAAE,EAAE,EAAE,CAAC;AAEvE;;;;;;;;;;;GAWG;AACH,MAAM,UAAU,UAAU,CAAC,IAAY,EAAE,IAAI,GAA6B,WAAW;IACnF,KAAK,MAAM,IAAI,IAAI,YAAY,EAAE,CAAC;QAChC,IAAI,GAAW,CAAC;QAChB,IAAI,CAAC;YACH,GAAG,GAAG,IAAI,CAAC,GAAG,IAAI,IAAI,IAAI,EAAE,CAAC,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AC,UAAU,CAAC,GAAG,CAAC,GAAG,CAAC;YAAE,QAAQ,CAAC,IAAI,CAAC,GAAG,MAAM,kBAAkB,GAAG,GAAG,CAAC,CAAC;IAC7E,CAAC;IAED,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,CAAC;AACtC,CAAC;AAED,MAAM,UAAU,GAAwB,IAAI,GAAG,CAAC;IAC9C,UAAU;IACV,QAAQ;IACR,kBAAkB;IAClB,UAAU;IACV,gBAAgB;IAChB,iBAAiB;IACjB,UAAU;IACV,SAAS;IACT,OAAO;IACP,YAAY;IACZ,QAAQ;IACR,YAAY;IACZ,4EAA4E;IAC5E,SAAS;CACV,CAAC,CAAC;AAEH,SAAS,QAAQ,CAAC,KAAc;IAC9B,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AAC9E,CAAC;AAED,SAAS,OAAO,CAAC,IAA8B,EAAE,IAAY;IAC3D,IAAI,CAAC;QACH,OAAO,UAAU,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC;IAChC,CAAC;IAAC,MAAM,CAAC;QACP,mEAAmE;QACnE,sEAAsE;QACtE,kDAAkD;QAClD,OAAO,IAAI,CAAC;IACd,CAAC;AACH,CAAC;AAED;;;;;;GAMG;AACH,SAAS,UAAU,CAAC,IAAY;IAC9B,OAAO,IAAI,CAAC,UAAU,CAAC,CAAC,CAAC,KAAK,MAAM,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC;AAC9D,CAAC;AAED,SAAS,WAAW,CAAC,IAAY;IAC/B,OAAO,YAAY,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC;AACpC,CAAC","sourcesContent":["/**\n * Repository configuration.\n *\n * Three ADRs left the same open question: `--ignore-ref` patterns, include\n * globs and rule severities all belong to a repository rather than to whoever\n * typed the command, and an npm script was doing that job by accumulating\n * flags. A CI invocation carrying eight `--ignore-ref` arguments is a\n * configuration file that has not admitted what it is.\n *\n * The format is JSON, parsed with `JSON.parse`. That is not a shortcut - it is\n * the reason this file exists at all. spec-graph has no runtime dependencies,\n * and a YAML or TOML reader would be the largest thing in the package, to read\n * a file with nine keys in it.\n *\n * Every key but `rules` and `maxRelated` mirrors a flag, and a flag always\n * wins. Configuration is where a team writes down what is true of the\n * repository; a flag is where somebody overrides it for one run.\n */\n\nimport { existsSync, readFileSync } from 'node:fs';\n\nimport { isFamilyName } from './identity.js';\nimport { dirnamePosix, toPosix } from './paths.js';\nimport { compileProjectRules, type ProjectRule } from './project-rules.js';\nimport { RULE_IDS } from './rules.js';\nimport { isProjectRule, type AnyRuleId, type RuleId, type Severity } from './types.js';\n\n/** File names looked for, in order. The first that exists is the one used. */\nexport const CONFIG_FILES: readonly string[] = Object.freeze([\n '.spec-graph.json',\n 'spec-graph.config.json',\n]);\n\n/** The `package.json` key read when no config file is present. */\nexport const CONFIG_PACKAGE_KEY = 'spec-graph';\n\nexport interface SpecGraphConfig {\n readonly patterns?: readonly string[] | undefined;\n readonly ignore?: readonly string[] | undefined;\n readonly ignoreReferences?: readonly string[] | undefined;\n /**\n * Families a bare identifier in prose may name.\n *\n * When set, `ADR-0099` is only ever read as a citation if `ADR` is listed.\n * Everything else in prose stays prose.\n */\n readonly families?: readonly string[] | undefined;\n /** Families that are never citations, whatever else the corpus contains. */\n readonly ignoreFamilies?: readonly string[] | undefined;\n /**\n * Files that are logs of what was decided rather than decisions themselves.\n *\n * Journals, changelogs, minutes. Their links are still checked; their\n * obligations and lifecycle are not. See ADR-0011.\n */\n readonly historyPatterns?: readonly string[] | undefined;\n /** Path to the accepted-debt baseline, relative to the root. See ADR-0012. */\n readonly baseline?: string | undefined;\n /** Fail when a baseline entry no longer occurs. See ADR-0012. */\n readonly ratchet?: boolean | undefined;\n readonly severities?: Partial<Record<AnyRuleId, Severity>> | undefined;\n readonly strict?: boolean | undefined;\n readonly maxRelated?: number | undefined;\n /**\n * Conventions this repository checks that spec-graph does not.\n *\n * A selector, a sentence and a severity. Compiled here rather than carried as\n * raw JSON, so a rule that cannot run is reported at load time next to every\n * other configuration problem - and not as a rule that quietly finds nothing.\n * See ADR-0016.\n */\n readonly rules?: readonly ProjectRule[] | undefined;\n}\n\nexport interface LoadedConfig {\n readonly config: SpecGraphConfig;\n /** Where it came from, for `--verbose` and for error messages. */\n readonly source: string | null;\n /** Keys that were present but unusable. Reported, never silently dropped. */\n readonly problems: readonly string[];\n}\n\nexport interface DiscoveredConfig extends LoadedConfig {\n /**\n * The directory the configuration was found in.\n *\n * This is the root of the run. Every path in spec-graph is relative to it -\n * node identities, baseline keys, SARIF locations - so the configuration file\n * naming the repository is the same statement as the repository having a\n * root. See ADR-0018.\n */\n readonly root: string;\n}\n\n/** Injected so discovery can be tested without a directory tree. */\nexport interface DiscoveryIO {\n readonly read?: ((path: string) => string) | undefined;\n readonly exists?: ((path: string) => boolean) | undefined;\n}\n\nconst EMPTY: LoadedConfig = { config: {}, source: null, problems: [] };\n\n/**\n * Reads configuration from a directory.\n *\n * Never throws, and never decides. Every problem is collected and handed back\n * whole, so the reader sees all of them at once rather than the first; what a\n * problem costs is the caller's to say, and the CLI stops on one.\n *\n * A configuration file that is there and cannot be read is a problem like one\n * that does not parse. Passed over as absent, a directory of that name or a\n * file the run may not open left the run on defaults, or on the configuration\n * of a directory above, with nothing said.\n */\nexport function loadConfig(root: string, read: (path: string) => string = defaultRead): LoadedConfig {\n for (const name of CONFIG_FILES) {\n let raw: string;\n try {\n raw = read(`${root}/${name}`);\n } catch (error) {\n // Nothing by that name: ENOENT, or ENOTDIR where a directory above is a\n // file. A reader handed in by a caller says the same with an error that\n // has no code.\n const code = (error as { code?: unknown }).code;\n if (code === undefined || code === 'ENOENT' || code === 'ENOTDIR') continue;\n return { config: {}, source: name, problems: [`${name} cannot be read: ${(error as Error).message}`] };\n }\n return parseConfig(raw, name);\n }\n\n // The first two returns are the third one's answer given early: no file is\n // `JSON.parse(null)`, which is `null`, and a parse that failed leaves\n // `parsed` undefined - neither is a record. Their mutants are equivalent.\n const pkg = tryRead(read, `${root}/package.json`);\n if (pkg === null) return EMPTY;\n let parsed: unknown;\n try {\n parsed = JSON.parse(pkg);\n } catch {\n return EMPTY;\n }\n if (!isRecord(parsed)) return EMPTY;\n const section = parsed[CONFIG_PACKAGE_KEY];\n if (section === undefined) return EMPTY;\n if (!isRecord(section)) {\n return { config: {}, source: `package.json`, problems: [`package.json: \"${CONFIG_PACKAGE_KEY}\" must be an object`] };\n }\n return readFields(section, `package.json#${CONFIG_PACKAGE_KEY}`);\n}\n\n/**\n * Finds the configuration by walking up from a directory.\n *\n * A monorepo is invoked from inside a package - `packages/auth`, or\n * `docs/architecture` - and reading configuration from the working directory\n * meant that the same repository checked differently depending on where\n * somebody stood in it. ADR-0010 worried that discovery would make a run\n * depend on where it started. It does the opposite: because the directory\n * holding the configuration becomes the root, a run from anywhere inside the\n * repository produces byte-identical output to a run from the top.\n *\n * The walk stops at the repository, which is a directory holding `.git`.\n * Above that is somebody else's checkout or a home directory, and a run that\n * silently picked up a configuration file nobody in the repository can see\n * would be worse than no discovery at all. See ADR-0018.\n */\nexport function discoverConfig(from: string, io: DiscoveryIO = {}): DiscoveredConfig {\n const read = io.read ?? defaultRead;\n const exists = io.exists ?? existsSync;\n const start = toPosix(from).replace(/\\/+$/, '');\n\n let directory = start;\n for (;;) {\n const loaded = loadConfig(directory, read);\n if (loaded.source !== null) return { ...loaded, root: directory };\n if (exists(`${directory}/.git`)) break;\n const parent = dirnamePosix(directory);\n // A path with no separator left in it gives back `''`, and stopping there is\n // what keeps a relative start from going on to read `/.spec-graph.json`,\n // which is what a file name joined to `''` spells. The second guard is true\n // only when the directory is `''` already, and then so is the first: its\n // mutant is equivalent. It stays so the loop still ends if the parent of a\n // path is ever spelled as Node's `dirname` spells it, `.` for `.`.\n if (parent === '' || parent === directory) break;\n directory = parent;\n }\n return { ...EMPTY, root: start };\n}\n\n/** Parses config text. Exported so the shape can be tested without a disk. */\nexport function parseConfig(raw: string, source: string): LoadedConfig {\n let parsed: unknown;\n try {\n parsed = JSON.parse(withoutBom(raw));\n } catch (error) {\n return { config: {}, source, problems: [`${source} is not valid JSON: ${(error as Error).message}`] };\n }\n if (!isRecord(parsed)) return { config: {}, source, problems: [`${source} must contain a JSON object`] };\n return readFields(parsed, source);\n}\n\nfunction readFields(raw: Record<string, unknown>, source: string): LoadedConfig {\n const problems: string[] = [];\n const config: {\n -readonly [K in keyof SpecGraphConfig]: SpecGraphConfig[K];\n } = {};\n\n const strings = (key: keyof SpecGraphConfig): readonly string[] | undefined => {\n const value = raw[key];\n if (value === undefined) return undefined;\n if (!Array.isArray(value) || value.some((entry) => typeof entry !== 'string')) {\n problems.push(`${source}: \"${key}\" must be an array of strings`);\n return undefined;\n }\n return value as string[];\n };\n\n config.patterns = strings('patterns');\n config.ignore = strings('ignore');\n config.ignoreReferences = strings('ignoreReferences');\n // A name no family has matches no citation. Alone in \"families\" it leaves\n // every citation as prose, and in \"ignoreFamilies\" it is a line that reads\n // as applied and does nothing.\n const families = (key: 'families' | 'ignoreFamilies'): readonly string[] | undefined => {\n const names = strings(key);\n for (const name of names ?? []) {\n if (!isFamilyName(name)) problems.push(`${source}: \"${key}\" must be family names, such as \"ADR\", and \"${name}\" is not one`);\n }\n return names;\n };\n\n config.families = families('families');\n config.ignoreFamilies = families('ignoreFamilies');\n config.historyPatterns = strings('historyPatterns');\n\n if (raw['baseline'] !== undefined) {\n if (typeof raw['baseline'] !== 'string' || raw['baseline'].trim().length === 0) {\n problems.push(`${source}: \"baseline\" must be a path`);\n } else {\n config.baseline = raw['baseline'];\n }\n }\n\n if (raw['strict'] !== undefined) {\n if (typeof raw['strict'] !== 'boolean') problems.push(`${source}: \"strict\" must be true or false`);\n else config.strict = raw['strict'];\n }\n\n if (raw['ratchet'] !== undefined) {\n if (typeof raw['ratchet'] !== 'boolean') problems.push(`${source}: \"ratchet\" must be true or false`);\n else config.ratchet = raw['ratchet'];\n }\n\n if (raw['maxRelated'] !== undefined) {\n const value = raw['maxRelated'];\n // `Number.isInteger` is false for anything but a number, so the `typeof`\n // only narrows the type for `value < 0`, and its mutant is equivalent.\n if (typeof value !== 'number' || !Number.isInteger(value) || value < 0) {\n problems.push(`${source}: \"maxRelated\" must be a non-negative whole number`);\n } else {\n config.maxRelated = value;\n }\n }\n\n if (raw['severities'] !== undefined) {\n const value = raw['severities'];\n if (!isRecord(value)) {\n problems.push(`${source}: \"severities\" must be an object of rule to severity`);\n } else {\n const severities: Partial<Record<AnyRuleId, Severity>> = {};\n for (const [rule, level] of Object.entries(value)) {\n // A project rule is named here by its full id, `project:no-drafts`, the\n // same spelling `--rule` takes and a report prints. Whether one exists\n // is checked below, once both halves of the file have been read.\n if (!RULE_IDS.includes(rule as RuleId) && !isProjectRule(rule as AnyRuleId)) {\n problems.push(`${source}: unknown rule \"${rule}\" in \"severities\"`);\n continue;\n }\n if (level !== 'error' && level !== 'warn' && level !== 'info' && level !== 'off') {\n problems.push(`${source}: \"severities.${rule}\" must be error, warn, info or off`);\n continue;\n }\n severities[rule as AnyRuleId] = level;\n }\n config.severities = severities;\n }\n }\n\n const compiled = raw['rules'] === undefined ? null : compileProjectRules(raw['rules'], source);\n if (compiled !== null) {\n problems.push(...compiled.problems);\n config.rules = compiled.rules;\n }\n\n // A severity naming a project rule that nothing defines is a line that will\n // never do anything, and reading like it does is the one thing a\n // configuration file must not be allowed to do. (A fallback seeded with\n // something that is not a rule defines no id, so that mutant is equivalent.)\n const defined = new Set<string>((compiled?.rules ?? []).map((rule) => rule.id));\n for (const rule of Object.keys(config.severities ?? {})) {\n if (!isProjectRule(rule as AnyRuleId) || defined.has(rule)) continue;\n problems.push(`${source}: \"severities.${rule}\" names no rule in \"rules\"`);\n }\n\n for (const key of Object.keys(raw)) {\n if (!KNOWN_KEYS.has(key)) problems.push(`${source}: unknown key \"${key}\"`);\n }\n\n return { config, source, problems };\n}\n\nconst KNOWN_KEYS: ReadonlySet<string> = new Set([\n 'patterns',\n 'ignore',\n 'ignoreReferences',\n 'families',\n 'ignoreFamilies',\n 'historyPatterns',\n 'baseline',\n 'ratchet',\n 'rules',\n 'severities',\n 'strict',\n 'maxRelated',\n // Tolerated so an editor can be pointed at a schema without being told off.\n '$schema',\n]);\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction tryRead(read: (path: string) => string, path: string): string | null {\n try {\n return withoutBom(read(path));\n } catch {\n // package.json is the one file still read this way, and its reader\n // passes over a text that does not parse as it does over no file: the\n // mutant that answers nothing here is equivalent.\n return null;\n }\n}\n\n/**\n * Drops a leading byte-order mark.\n *\n * `JSON.parse` rejects one, and several Windows editors write one by default -\n * a config that silently stops applying because of an invisible first character\n * is the worst kind of configuration bug.\n */\nfunction withoutBom(text: string): string {\n return text.charCodeAt(0) === 0xfeff ? text.slice(1) : text;\n}\n\nfunction defaultRead(path: string): string {\n return readFileSync(path, 'utf8');\n}\n"]}
package/dist/glob.js CHANGED
@@ -355,8 +355,9 @@ export async function walkFiles(options) {
355
355
  const ignores = options.ignore ?? [];
356
356
  // The empty pattern is no directory's name, so it goes to the dialect, which
357
357
  // refuses it as it refuses an empty include: a pattern that names nothing is
358
- // a typo or an unset variable, and was an ignore that ignored nothing.
359
- const plainName = (pattern) => pattern.length > 0 && !isGlob(pattern) && !pattern.includes('/') && !pattern.startsWith('!');
358
+ // a typo or an unset variable, and was an ignore that ignored nothing. So
359
+ // does a blank one, which was read as a directory called " ".
360
+ const plainName = (pattern) => pattern.trim().length > 0 && !isGlob(pattern) && !pattern.includes('/') && !pattern.startsWith('!');
360
361
  // A `!` before a name gives the name back, as a `.gitignore` line does, and
361
362
  // the last bare entry to name a directory decides whether it is pruned. It
362
363
  // was read as a directory called `!docs`, so `--ignore docs --ignore "!docs"`
package/dist/glob.js.map CHANGED
@@ -1 +1 @@
1
-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n * The patterns are the `path` dialect every spec-* tool reads, from spec-core:\n * `**`, `*`, `?`, `{a,b}`, `[abc]` and `[!a-z]`, matched against whole\n * repository-relative POSIX paths by an automaton that cannot backtrack, with\n * case respected on every host (ADR-0022). What stays here is spec-graph's own:\n * how a list with `!` entries in it reads, which directories a walk never\n * enters, and how a reference target - which is not a path - is matched.\n */\n\nimport type { Dirent } from 'node:fs';\nimport { readdir, realpath, stat } from 'node:fs/promises';\n\nimport { isAbsolutePath, joinPosix, toPosix } from './paths.js';\nimport {\n compileGlob as compileFamilyGlob,\n GlobError,\n isGlobSyntax,\n parseGlob,\n parseGlobList,\n rebaseGlob,\n type Glob,\n type GlobList,\n type GlobOptions as FamilyGlobOptions,\n type RegexMatcher,\n} from './vendor/spec-core/pattern/index.js';\n\n/** Directories skipped unless a pattern explicitly names them. */\nexport const DEFAULT_IGNORED_DIRECTORIES: readonly string[] = Object.freeze([\n '.git',\n '.hg',\n '.svn',\n '.cache',\n '.next',\n '.nuxt',\n '.turbo',\n '.venv',\n 'node_modules',\n 'bower_components',\n 'vendor',\n 'dist',\n 'build',\n 'out',\n 'target',\n 'coverage',\n '__pycache__',\n]);\n\n/** Files larger than this are skipped: a specification is not a binary. */\nexport const MAX_FILE_SIZE = 4 * 1024 * 1024;\n\nexport interface WalkedFile {\n /** Repository-relative POSIX path. */\n readonly path: string;\n /** Absolute host path, for reading. */\n readonly absolute: string;\n readonly size: number;\n}\n\nexport interface WalkOptions {\n readonly root: string;\n readonly patterns: readonly string[];\n readonly ignore?: readonly string[] | undefined;\n readonly maxFileSize?: number | undefined;\n /**\n * Follow links. Off by default: a link can lead out of the repository. A\n * link back into a directory the walk is inside is never followed.\n */\n readonly followSymlinks?: boolean | undefined;\n}\n\n/**\n * How a path pattern is read everywhere in spec-graph.\n *\n * A literal names a file or a directory and everything beneath it, which is\n * what `--ignore docs/drafts` has always meant. A `\\` is a separator, because a\n * pattern typed on a Windows shell arrives with them and spec-graph has always\n * read them that way; it cannot also be an escape.\n */\nconst PATH: FamilyGlobOptions = { dialect: 'path', caseSensitive: true, literal: 'either', backslash: 'separator' };\n\n/** True when the string contains glob syntax rather than being a literal path. */\nexport function isGlob(pattern: string): boolean {\n return isGlobSyntax(pattern);\n}\n\n/**\n * Compiles a glob to an anchored regular expression, in the dialect spec-graph\n * read before it adopted spec-core's.\n *\n * @deprecated Nothing matches with this. It stays for callers who want a\n * `RegExp`, and as the record of the old reading that `tests/glob.test.ts`\n * holds every difference against, each one named in ADR-0022. It no longer\n * folds case on Windows alone: an answer must not depend on the host.\n */\nexport function globToRegExp(pattern: string): RegExp {\n return new RegExp(`^${globSource(pattern)}$`);\n}\n\nexport interface GlobOptions {\n /** Fold case. Off unless asked for, on every host. */\n readonly ignoreCase?: boolean | undefined;\n}\n\n/**\n * Compiles one glob to a matcher over whole repository-relative paths.\n *\n * A pattern with no glob syntax names that path and nothing beneath it; a bare\n * directory meaning its contents is a reading of {@link createGlobMatcher}'s.\n * Throws a `GlobError` that names the glob as it was written.\n *\n * Matching is linear in the path whatever the pattern. It was not always: a\n * glob's stars are not nested, but each is a `[^/]*` to `RegExp`, and a subject\n * that fails is divided between them every way there is - `*-*-*-x` took two\n * minutes over a 10,000-character reference target (ADR-0017).\n */\nexport function compileGlob(pattern: string, options: GlobOptions = {}): RegexMatcher {\n // `literal: 'file'` is the dialect's reading of any value but `directory`\n // and `either`, so a mutant that blanks it reads the same. It is spelled out\n // because what an unknown value means is spec-core's to change.\n const glob = compileFamilyGlob(pattern, { ...PATH, literal: 'file', caseSensitive: options.ignoreCase !== true });\n return { test: (path) => glob.match(path), size: glob.automaton.kinds.length };\n}\n\n/** The expression a glob stood for before 0.9.0, before anchors and flags. */\nfunction globSource(pattern: string): string {\n let source = '';\n let i = 0;\n const braces: number[] = [];\n\n while (i < pattern.length) {\n const ch = pattern[i] as string;\n\n if (ch === '*') {\n const doubled = pattern[i + 1] === '*';\n if (doubled) {\n const slashAfter = pattern[i + 2] === '/';\n // `a/**/b` must also match `a/b`, so the separator is folded in.\n source += slashAfter ? '(?:.*/)?' : '.*';\n i += slashAfter ? 3 : 2;\n } else {\n source += '[^/]*';\n i += 1;\n }\n continue;\n }\n\n if (ch === '?') {\n source += '[^/]';\n i += 1;\n continue;\n }\n\n if (ch === '[') {\n const close = pattern.indexOf(']', i + 1);\n if (close === -1) {\n source += '\\\\[';\n i += 1;\n continue;\n }\n const body = pattern.slice(i + 1, close);\n source += `[${body.startsWith('!') ? `^${escapeClass(body.slice(1))}` : escapeClass(body)}]`;\n i = close + 1;\n continue;\n }\n\n if (ch === '{') {\n braces.push(source.length);\n source += '(?:';\n i += 1;\n continue;\n }\n if (ch === '}' && braces.length > 0) {\n braces.pop();\n source += ')';\n i += 1;\n continue;\n }\n if (ch === ',' && braces.length > 0) {\n source += '|';\n i += 1;\n continue;\n }\n\n source += ch.replace(/[.+^${}()|[\\]\\\\]/g, '\\\\$&');\n i += 1;\n }\n\n // Otherwise reported as an unmatched parenthesis, in a glob that has none.\n if (braces.length > 0) throw new Error(`invalid glob \"${pattern}\": unclosed \"{\"`);\n return source;\n}\n\nfunction escapeClass(body: string): string {\n return body.replace(/[\\\\^\\]]/g, '\\\\$&');\n}\n\nexport interface GlobMatcher {\n (path: string): boolean;\n}\n\n/** Compiles a list of path patterns, or throws naming the one that is not a glob. */\nfunction pathList(patterns: readonly string[]): GlobList {\n const parsed = parseGlobList(patterns, PATH);\n if (!parsed.ok) throw new Error(`invalid glob ${parsed.error}`);\n return parsed.list;\n}\n\n/**\n * Builds a matcher from include patterns, honouring `!` negations.\n *\n * Later patterns win, so `docs/**\\/*.md` followed by `!docs/drafts/**` reads the\n * way a `.gitignore` does. A pattern with no glob syntax in it names a file, or\n * a directory and everything beneath it; `docs/` names only what is beneath.\n */\nexport function createGlobMatcher(patterns: readonly string[]): GlobMatcher {\n const list = pathList(patterns);\n return (path: string): boolean => list.match(path);\n}\n\n/**\n * A list entry typed in `directory`, below the root, rewritten to read from the\n * root, or refused naming the entry as it was typed (ADR-0018).\n *\n * Each brace alternative is rebased as that text written alone would be, so\n * `{/docs,x}` typed in `sub` is `{/docs,sub/x}`: a leading `/` roots it\n * wherever it was typed. A leading `..` climbs out of `directory`, and one past\n * the root is refused, as is a directory whose name a pattern would read as\n * syntax.\n */\nexport function rebasePattern(entry: string, directory: string): string {\n const rebased = rebaseGlob(entry, directory, PATH);\n if (!rebased.ok) throw new GlobError(entry, rebased.error);\n return rebased.pattern;\n}\n\n/**\n * Each dot in a reference pattern that may begin a segment, which is escaped:\n * a `.` or `..` segment then reads as the name it is, one or two dots, where\n * the dialect would drop the one and refuse the other.\n *\n * Braces expand before segments are read, so a dot written beside a brace or a\n * comma may begin a segment of an alternative: `docs/{.,x}` is `docs/.` or\n * `docs/x`, `.{/gone.md,x}` is `./gone.md` or `.x`, and `{docs/,x/}.` ends in a\n * segment `.` either way. An escaped dot is the same character as a dot in a\n * name, so escaping one that begins `.x`, or the braces leave inside a name as\n * in `a{.,b}`, reads the same, and nothing needs to tell those apart:\n * escaping each whole `.` or `..` segment instead reads each of 43,069\n * generated patterns the same, refusals included (ADR-0022).\n */\nconst SEGMENT_DOT = /(?<=^|[/{,}])\\./g;\n\n/**\n * How a reference target is matched. Every option is spelled out, though the\n * dialect reads `{}` the same way today: its defaults are spec-core's to\n * change, and this reading is spec-graph's to keep. A mutant that drops one,\n * or all of them, is equivalent until then.\n */\nconst TARGET: FamilyGlobOptions = { dialect: 'path', caseSensitive: false, literal: 'file' };\n\n/**\n * A refusal of a reference pattern in the words it was typed in.\n *\n * The dialect writes its advice for a `**` inside a name from the text it was\n * given, and that text held a `\\` before each dot {@link SEGMENT_DOT} escaped:\n * `../notes/**.md` was told `\\.\\./notes/**\\/*.md`. Given the pattern again with\n * a character it does not hold in place of each of those dots, the dialect\n * refuses it for the same reason, since both are one literal character and\n * neither is a direction, and each stand-in is read back as the dot it was.\n * Counting down from U+E000 would find a stand-in as well, among the\n * surrogates, so that mutant is equivalent.\n */\nfunction asTyped(typed: string, reason: string): string {\n let point = 0xe000;\n while (typed.includes(String.fromCodePoint(point))) point += 1;\n const stand = String.fromCodePoint(point);\n const again = parseGlob(typed.replace(SEGMENT_DOT, stand), TARGET);\n // Stand-ins and escaped dots compile or fail alike, so `again` never\n // compiles here, and a mutant that reads it as compiled is equivalent.\n return again.ok ? reason : again.error.replaceAll(stand, '.');\n}\n\n/**\n * Builds a predicate over reference *targets*, not paths.\n *\n * Separate from {@link createGlobMatcher} on purpose. That one is\n * path-oriented: a bare name there is a directory and everything under it. A\n * reference target has no such structure - `trap 55` is a name, not a location\n * - so a bare pattern matches it literally and nothing else.\n *\n * Case is ignored, on every platform, because a citation's spelling is the\n * author's and not the filesystem's. The fold is simple case mapping, one code\n * point at a time and without a locale, so every host gives the same answer:\n * U+00B5 (micro sign) and U+03BC (mu) stay two targets, as they have been since\n * a Windows-only `i` flag made them one there (ADR-0017).\n *\n * A target is text a document holds rather than a path on this host, and two\n * things follow. A `\\` escapes the character after it: there is no Windows\n * separator to allow for. And a `.` or `..` segment is text, in a brace\n * alternative as anywhere else: in a path the dialect drops the one and\n * refuses the other as climbing out of the root, but `../../notes/gone.md` is\n * a link somebody wrote and may want left alone. A pattern that is refused is\n * named, and advised, as it was typed.\n */\nexport function createReferenceFilter(patterns: readonly string[]): (target: string) => boolean {\n // A blank pattern reaches the dialect, which refuses it, as every pattern\n // spec-graph reads is refused when it names nothing. It used to be dropped,\n // so an unset variable in `--ignore-ref \"$TAGS\"` went unnoticed.\n const globs: Glob[] = patterns.map((pattern) => {\n const typed = pattern.trim();\n const parsed = parseGlob(typed.replace(SEGMENT_DOT, '\\\\.'), TARGET);\n if (!parsed.ok) throw new GlobError(pattern, asTyped(typed, parsed.error));\n return parsed.glob;\n });\n return (target: string): boolean => {\n const value = target.trim();\n return globs.some((glob) => glob.match(value));\n };\n}\n\n/**\n * The literal directory a pattern's matches all sit under, or `''` for the root.\n *\n * `{docs,specs}/**` has two, and this is the directory they share; the walk\n * itself starts at each.\n */\nexport function globBase(pattern: string): string {\n const { glob } = pathList([pattern]).entries[0] as { readonly glob: Glob };\n const bases = glob.bases.map((base) => base.split('/'));\n const shared = bases[0] as string[];\n let length = shared.length;\n for (const base of bases) {\n let same = 0;\n // `<=` would read one past the end, where both sides are undefined and\n // equal, and slice the same prefix: an equivalent mutant, left untested.\n while (same < length && base[same] === shared[same]) same += 1;\n length = same;\n }\n return shared.slice(0, length).join('/');\n}\n\n/**\n * Whether a base names directories the walk from the root would reach, each\n * with exactly that spelling and none a link it would not follow.\n *\n * A walk starts where a pattern's literal prefix points rather than at the\n * root, and on a filesystem that ignores case, `readdir('Docs')` lists `docs`.\n * Every file under it would come back spelled `Docs/...` - a node id, a\n * baseline key - and `Docs/**` would find it on Windows and macOS and nothing\n * on Linux. Asking each parent for the name gives git's answer on every host. A\n * base with an empty segment is rooted at `/`, which is never inside the root.\n *\n * Reading a directory by its path follows every link in the path, so\n * `docs/linked/*.md` was read through the link `docs/linked`, which the walk\n * from the root passes over. Asking each parent for the entry says which it\n * is, and a base beyond a link is left as silently as the walk leaves the link.\n *\n * Where links are followed, the answer is the real path of each directory\n * above the base, the root included, for the walk to tell a cycle by; a base\n * beyond a link back into one of them is one the walk from the root never\n * reaches, and is left the same way. Where they are not, it is empty and never\n * read, so a mutant that fills it anyway is equivalent. `null` is a base the\n * walk does not start at.\n */\nasync function reachable(root: string, base: string, followSymlinks: boolean | undefined): Promise<Set<string> | null> {\n const above = new Set<string>();\n if (base.length === 0) return above;\n let directory = root;\n for (const segment of base.split('/')) {\n let entries: Dirent[];\n try {\n entries = await readdir(directory, { withFileTypes: true });\n } catch {\n // Answering a set here would change nothing a test can see: the walk\n // would then read a directory beneath this one, fail the same way, and\n // find nothing.\n return null;\n }\n const entry = entries.find((candidate) => candidate.name === segment);\n if (entry === undefined || (entry.isSymbolicLink() && !followSymlinks)) return null;\n if (followSymlinks) {\n // The directory was just listed, so asking for its real path fails only\n // where it went in between, and the walk would find nothing there: a\n // mutant that answers otherwise is equivalent.\n const real = await realpath(directory).catch(() => null);\n if (real === null || above.has(real)) return null;\n above.add(real);\n }\n directory = `${directory}/${segment}`;\n }\n return above;\n}\n\n/**\n * Walks the tree and returns every file matching the patterns.\n *\n * Directories are pruned as early as possible: a repository with a 2 GB\n * `node_modules` should cost nothing to scan.\n */\nexport async function walkFiles(options: WalkOptions): Promise<WalkedFile[]> {\n const root = toPosix(options.root).replace(/\\/+$/, '');\n const patterns = pathList(options.patterns);\n const maxSize = options.maxFileSize ?? MAX_FILE_SIZE;\n\n // Ignores come in two shapes and both are documented. A bare name prunes any\n // directory called that, at any depth, the way a `.gitignore` line does.\n // Anything carrying a separator or glob syntax is matched against the\n // repository-relative path, which is what `--ignore \"docs/drafts/**\"` means -\n // and treating that as a directory name silently excluded nothing at all.\n // A mutant that defaults this to `['Stryker was here']` prunes directories of\n // that name, which no repository has: equivalent, and left untested.\n const ignores = options.ignore ?? [];\n // The empty pattern is no directory's name, so it goes to the dialect, which\n // refuses it as it refuses an empty include: a pattern that names nothing is\n // a typo or an unset variable, and was an ignore that ignored nothing.\n const plainName = (pattern: string): boolean =>\n pattern.length > 0 && !isGlob(pattern) && !pattern.includes('/') && !pattern.startsWith('!');\n // A `!` before a name gives the name back, as a `.gitignore` line does, and\n // the last bare entry to name a directory decides whether it is pruned. It\n // was read as a directory called `!docs`, so `--ignore docs --ignore \"!docs\"`\n // pruned `docs` and said nothing. The default list is a list of names too,\n // and gives way to one: `--ignore \"!vendor\"` reads every `vendor`. A `!` alone\n // or before another is no name, and goes to the dialect, which refuses both.\n const bare = (pattern: string): boolean => plainName(pattern) || (pattern.startsWith('!') && plainName(pattern.slice(1)));\n const named = new Map<string, boolean>();\n for (const pattern of ignores.filter(bare)) {\n const negated = pattern.startsWith('!');\n named.set(negated ? pattern.slice(1) : pattern, !negated);\n }\n const skippedByDefault = new Set(DEFAULT_IGNORED_DIRECTORIES);\n const ignoreList = pathList(ignores.filter((pattern) => !bare(pattern)));\n const excluded = (path: string): boolean => ignoreList.match(path);\n\n // Only walk the directories the patterns can possibly reach: each pattern's\n // literal prefix, one per brace alternative. A negated pattern adds none: it\n // takes files back, and starting a walk at its prefix would enter what the\n // walk skips - `!node_modules/**/*.txt` beside `**/*.md` would read every\n // Markdown file in `node_modules`. No positive pattern at all walks nothing,\n // which is the answer.\n const bases = new Set<string>();\n // The paths a positive pattern names outright: `docs/vendor`, or each literal\n // a brace expands to. Such a name may be a file, so its walk starts in the\n // directory above, which pruned `vendor` on its way in: `docs/vendor` found\n // nothing where `docs/vendor/` read the directory. The default list gives way\n // to the directory a pattern names as it gives way to one a pattern starts\n // inside. A negated name adds none, for the reason it adds no base.\n const literals = new Set<string>();\n for (const entry of patterns.entries) {\n if (entry.negated) continue;\n for (const base of entry.glob.bases) bases.add(base);\n // The dialect is what knows a literal when it reads one, so each pattern\n // is compiled a second time to be told of them. That glob is thrown away:\n // the reading answered here decides nothing, and a mutant that changes it\n // is equivalent.\n parseGlob(entry.glob.source, {\n ...PATH,\n literal: (path) => {\n literals.add(path);\n return 'either';\n },\n });\n }\n // Every base is walked, even one inside another, because the outer walk\n // prunes `vendor` and the rest of the default list on its way down, and a\n // pattern that starts inside one of those is read from there. Dropping the\n // inner base as already covered meant `docs/**/*.md` beside\n // `docs/vendor/specs/*.md` found less than the second pattern alone. An\n // `--ignore` is not overruled that way: it is the user's. A walk that starts\n // at a base never passed through the directories above it, so each of them,\n // and the base, is asked what the walk from the root would have asked on its\n // way down. A bare name prunes at any depth - `--ignore adr` still takes out\n // `adr/`, which the default `adr/**/*.md` starts inside - and a path takes\n // out what it matches, so under `--ignore \"docs/*\"` `docs/drafts/**/*.md`\n // finds what `docs/**/*.md` finds, which is nothing there. The root is not\n // asked, as the walk from it never asks: `*` matches the empty path, and\n // `**/*.md` under `--ignore \"*\" --ignore \"!{docs,specs}\"` would read nothing\n // where it reads those two.\n const startable = (base: string): boolean => {\n if (base.length === 0) return true;\n const segments = base.split('/');\n return !segments.some((segment, i) => named.get(segment) === true || excluded(segments.slice(0, i + 1).join('/')));\n };\n // Whether the walk leaves a directory it meets, asked of a followed link to\n // one as well: a link called `node_modules`, which pnpm writes, or one an\n // `--ignore` names, is the directory it leads to under that name and path,\n // and was entered whatever they were. Pruning a whole subtree is an\n // optimisation; a pattern that only matches the files inside it is still\n // honoured when they are filtered. A bare `--ignore` name prunes a directory\n // a pattern names as well: only the default list gives way, to a pattern and\n // to a `!` before its name.\n const pruned = (name: string, path: string): boolean =>\n (named.get(name) ?? (skippedByDefault.has(name) && !literals.has(path))) || excluded(path);\n const out = new Map<string, WalkedFile>();\n // Where two walks overlap, whichever reaches a directory first reads it and\n // the other stops there. Reading it twice would find the same files under\n // the same keys, so the two mutants that drop this are equivalent.\n const visited = new Set<string>();\n // Where links are followed, the real path of each directory from the root to\n // the one being read. A link whose real path is among them leads back into a\n // directory the walk is inside, and following it read the same files again\n // under a longer path each time round, until the host refused the path: on\n // Windows, 64 copies of each. It is passed over as silently as a link is\n // when links are not followed. A link to anywhere else is followed, one to a\n // directory the walk has already read beside this one included, since only\n // a directory on the way here can make a cycle. The walks run one at a time,\n // so one set serves them all. Only a followed link can make a cycle, so with\n // links not followed no real path is asked for, and a mutant that asks finds\n // none: equivalent.\n let inside = new Set<string>();\n\n const walk = async (relative: string): Promise<void> => {\n const absolute = relative.length === 0 ? root : `${root}/${relative}`;\n if (visited.has(absolute)) return;\n visited.add(absolute);\n if (!options.followSymlinks) return read(relative, absolute);\n // A directory with no real path is one that cannot be listed either, so\n // a mutant that reads it rather than returning reads nothing more.\n const real = await realpath(absolute).catch(() => null);\n if (real === null || inside.has(real)) return;\n inside.add(real);\n await read(relative, absolute);\n inside.delete(real);\n };\n\n const read = async (relative: string, absolute: string): Promise<void> => {\n let entries;\n try {\n entries = await readdir(absolute, { withFileTypes: true });\n } catch {\n // An unreadable directory is not a reason to fail the whole run.\n return;\n }\n\n for (const entry of entries) {\n const child = relative.length === 0 ? entry.name : `${relative}/${entry.name}`;\n\n if (entry.isDirectory()) {\n if (!pruned(entry.name, child)) await walk(child);\n continue;\n }\n\n if (entry.isSymbolicLink()) {\n if (!options.followSymlinks) continue;\n try {\n const info = await stat(`${root}/${child}`);\n if (info.isDirectory()) {\n if (!pruned(entry.name, child)) await walk(child);\n continue;\n }\n if (!patterns.match(child) || excluded(child) || info.size > maxSize) continue;\n out.set(child, { path: child, absolute: `${root}/${child}`, size: info.size });\n } catch {\n // A link to nothing has nothing to read.\n }\n continue;\n }\n\n if (!entry.isFile()) continue;\n if (!patterns.match(child) || excluded(child)) continue;\n\n try {\n const info = await stat(`${root}/${child}`);\n if (info.size > maxSize) continue;\n out.set(child, { path: child, absolute: `${root}/${child}`, size: info.size });\n } catch {\n // Gone between the listing and the look: there is nothing to read.\n }\n }\n };\n\n for (const base of bases) {\n const above = startable(base) ? await reachable(root, base, options.followSymlinks) : null;\n if (above === null) continue;\n inside = above;\n await walk(base);\n }\n\n // No two paths are equal, since they are the keys of `out`, so the order\n // needs only `<`, and `<=` would read the same.\n return [...out.values()].sort((a, b) => (a.path < b.path ? -1 : 1));\n}\n\n/**\n * Resolves a repository-relative path against the root, in POSIX form.\n *\n * An absolute path already names one place, and joining it under the root names\n * another: `--baseline /tmp/b.json` read `<root>/tmp/b.json`, found nothing\n * there, and accepted nothing without saying so.\n */\nexport function underRoot(root: string, relative: string): string {\n if (isAbsolutePath(relative)) return toPosix(relative);\n return joinPosix(toPosix(root), relative);\n}\n"]}
1
+ {"version":3,"file":"glob.js","sourceRoot":"","sources":["../src/glob.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAGH,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAE,IAAI,EAAE,MAAM,kBAAkB,CAAC;AAE3D,OAAO,EAAE,cAAc,EAAE,SAAS,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AAChE,OAAO,EACL,WAAW,IAAI,iBAAiB,EAChC,SAAS,EACT,YAAY,EACZ,SAAS,EACT,aAAa,EACb,UAAU,GAKX,MAAM,qCAAqC,CAAC;AAE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CAAC;QACH,CAAC;IACH,CAAC,CAAC;IAEF,KAAK,MAAM,IAAI,IAAI,KAAK,EAAE,CAAC;QACzB,MAAM,KAAK,GAAG,SAAS,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,MAAM,SAAS,CAAC,IAAI,EAAE,IAAI,EAAE,OAAO,CAAC,cAAc,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC;QAC3F,IAAI,KAAK,KAAK,IAAI;YAAE,SAAS;QAC7B,MAAM,GAAG,KAAK,CAAC;QACf,MAAM,IAAI,CAAC,IAAI,CAAC,CAAC;IACnB,CAAC;IAED,yEAAyE;IACzE,gDAAgD;IAChD,OAAO,CAAC,GAAG,GAAG,CAAC,MAAM,EAAE,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,IAAI,GAAG,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;AACtE,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,SAAS,CAAC,IAAY,EAAE,QAAgB;IACtD,IAAI,cAAc,CAAC,QAAQ,CAAC;QAAE,OAAO,OAAO,CAAC,QAAQ,CAAC,CAAC;IACvD,OAAO,SAAS,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE,QAAQ,CAAC,CAAC;AAC5C,CAAC","sourcesContent":["/**\n * Pattern matching and directory walking.\n *\n * The patterns are the `path` dialect every spec-* tool reads, from spec-core:\n * `**`, `*`, `?`, `{a,b}`, `[abc]` and `[!a-z]`, matched against whole\n * repository-relative POSIX paths by an automaton that cannot backtrack, with\n * case respected on every host (ADR-0022). What stays here is spec-graph's own:\n * how a list with `!` entries in it reads, which directories a walk never\n * enters, and how a reference target - which is not a path - is matched.\n */\n\nimport type { Dirent } from 'node:fs';\nimport { readdir, realpath, stat } from 'node:fs/promises';\n\nimport { isAbsolutePath, joinPosix, toPosix } from './paths.js';\nimport {\n compileGlob as compileFamilyGlob,\n GlobError,\n isGlobSyntax,\n parseGlob,\n parseGlobList,\n rebaseGlob,\n type Glob,\n type GlobList,\n type GlobOptions as FamilyGlobOptions,\n type RegexMatcher,\n} from './vendor/spec-core/pattern/index.js';\n\n/** Directories skipped unless a pattern explicitly names them. */\nexport const DEFAULT_IGNORED_DIRECTORIES: readonly string[] = Object.freeze([\n '.git',\n '.hg',\n '.svn',\n '.cache',\n '.next',\n '.nuxt',\n '.turbo',\n '.venv',\n 'node_modules',\n 'bower_components',\n 'vendor',\n 'dist',\n 'build',\n 'out',\n 'target',\n 'coverage',\n '__pycache__',\n]);\n\n/** Files larger than this are skipped: a specification is not a binary. */\nexport const MAX_FILE_SIZE = 4 * 1024 * 1024;\n\nexport interface WalkedFile {\n /** Repository-relative POSIX path. */\n readonly path: string;\n /** Absolute host path, for reading. */\n readonly absolute: string;\n readonly size: number;\n}\n\nexport interface WalkOptions {\n readonly root: string;\n readonly patterns: readonly string[];\n readonly ignore?: readonly string[] | undefined;\n readonly maxFileSize?: number | undefined;\n /**\n * Follow links. Off by default: a link can lead out of the repository. A\n * link back into a directory the walk is inside is never followed.\n */\n readonly followSymlinks?: boolean | undefined;\n}\n\n/**\n * How a path pattern is read everywhere in spec-graph.\n *\n * A literal names a file or a directory and everything beneath it, which is\n * what `--ignore docs/drafts` has always meant. A `\\` is a separator, because a\n * pattern typed on a Windows shell arrives with them and spec-graph has always\n * read them that way; it cannot also be an escape.\n */\nconst PATH: FamilyGlobOptions = { dialect: 'path', caseSensitive: true, literal: 'either', backslash: 'separator' };\n\n/** True when the string contains glob syntax rather than being a literal path. */\nexport function isGlob(pattern: string): boolean {\n return isGlobSyntax(pattern);\n}\n\n/**\n * Compiles a glob to an anchored regular expression, in the dialect spec-graph\n * read before it adopted spec-core's.\n *\n * @deprecated Nothing matches with this. It stays for callers who want a\n * `RegExp`, and as the record of the old reading that `tests/glob.test.ts`\n * holds every difference against, each one named in ADR-0022. It no longer\n * folds case on Windows alone: an answer must not depend on the host.\n */\nexport function globToRegExp(pattern: string): RegExp {\n return new RegExp(`^${globSource(pattern)}$`);\n}\n\nexport interface GlobOptions {\n /** Fold case. Off unless asked for, on every host. */\n readonly ignoreCase?: boolean | undefined;\n}\n\n/**\n * Compiles one glob to a matcher over whole repository-relative paths.\n *\n * A pattern with no glob syntax names that path and nothing beneath it; a bare\n * directory meaning its contents is a reading of {@link createGlobMatcher}'s.\n * Throws a `GlobError` that names the glob as it was written.\n *\n * Matching is linear in the path whatever the pattern. It was not always: a\n * glob's stars are not nested, but each is a `[^/]*` to `RegExp`, and a subject\n * that fails is divided between them every way there is - `*-*-*-x` took two\n * minutes over a 10,000-character reference target (ADR-0017).\n */\nexport function compileGlob(pattern: string, options: GlobOptions = {}): RegexMatcher {\n // `literal: 'file'` is the dialect's reading of any value but `directory`\n // and `either`, so a mutant that blanks it reads the same. It is spelled out\n // because what an unknown value means is spec-core's to change.\n const glob = compileFamilyGlob(pattern, { ...PATH, literal: 'file', caseSensitive: options.ignoreCase !== true });\n return { test: (path) => glob.match(path), size: glob.automaton.kinds.length };\n}\n\n/** The expression a glob stood for before 0.9.0, before anchors and flags. */\nfunction globSource(pattern: string): string {\n let source = '';\n let i = 0;\n const braces: number[] = [];\n\n while (i < pattern.length) {\n const ch = pattern[i] as string;\n\n if (ch === '*') {\n const doubled = pattern[i + 1] === '*';\n if (doubled) {\n const slashAfter = pattern[i + 2] === '/';\n // `a/**/b` must also match `a/b`, so the separator is folded in.\n source += slashAfter ? '(?:.*/)?' : '.*';\n i += slashAfter ? 3 : 2;\n } else {\n source += '[^/]*';\n i += 1;\n }\n continue;\n }\n\n if (ch === '?') {\n source += '[^/]';\n i += 1;\n continue;\n }\n\n if (ch === '[') {\n const close = pattern.indexOf(']', i + 1);\n if (close === -1) {\n source += '\\\\[';\n i += 1;\n continue;\n }\n const body = pattern.slice(i + 1, close);\n source += `[${body.startsWith('!') ? `^${escapeClass(body.slice(1))}` : escapeClass(body)}]`;\n i = close + 1;\n continue;\n }\n\n if (ch === '{') {\n braces.push(source.length);\n source += '(?:';\n i += 1;\n continue;\n }\n if (ch === '}' && braces.length > 0) {\n braces.pop();\n source += ')';\n i += 1;\n continue;\n }\n if (ch === ',' && braces.length > 0) {\n source += '|';\n i += 1;\n continue;\n }\n\n source += ch.replace(/[.+^${}()|[\\]\\\\]/g, '\\\\$&');\n i += 1;\n }\n\n // Otherwise reported as an unmatched parenthesis, in a glob that has none.\n if (braces.length > 0) throw new Error(`invalid glob \"${pattern}\": unclosed \"{\"`);\n return source;\n}\n\nfunction escapeClass(body: string): string {\n return body.replace(/[\\\\^\\]]/g, '\\\\$&');\n}\n\nexport interface GlobMatcher {\n (path: string): boolean;\n}\n\n/** Compiles a list of path patterns, or throws naming the one that is not a glob. */\nfunction pathList(patterns: readonly string[]): GlobList {\n const parsed = parseGlobList(patterns, PATH);\n if (!parsed.ok) throw new Error(`invalid glob ${parsed.error}`);\n return parsed.list;\n}\n\n/**\n * Builds a matcher from include patterns, honouring `!` negations.\n *\n * Later patterns win, so `docs/**\\/*.md` followed by `!docs/drafts/**` reads the\n * way a `.gitignore` does. A pattern with no glob syntax in it names a file, or\n * a directory and everything beneath it; `docs/` names only what is beneath.\n */\nexport function createGlobMatcher(patterns: readonly string[]): GlobMatcher {\n const list = pathList(patterns);\n return (path: string): boolean => list.match(path);\n}\n\n/**\n * A list entry typed in `directory`, below the root, rewritten to read from the\n * root, or refused naming the entry as it was typed (ADR-0018).\n *\n * Each brace alternative is rebased as that text written alone would be, so\n * `{/docs,x}` typed in `sub` is `{/docs,sub/x}`: a leading `/` roots it\n * wherever it was typed. A leading `..` climbs out of `directory`, and one past\n * the root is refused, as is a directory whose name a pattern would read as\n * syntax.\n */\nexport function rebasePattern(entry: string, directory: string): string {\n const rebased = rebaseGlob(entry, directory, PATH);\n if (!rebased.ok) throw new GlobError(entry, rebased.error);\n return rebased.pattern;\n}\n\n/**\n * Each dot in a reference pattern that may begin a segment, which is escaped:\n * a `.` or `..` segment then reads as the name it is, one or two dots, where\n * the dialect would drop the one and refuse the other.\n *\n * Braces expand before segments are read, so a dot written beside a brace or a\n * comma may begin a segment of an alternative: `docs/{.,x}` is `docs/.` or\n * `docs/x`, `.{/gone.md,x}` is `./gone.md` or `.x`, and `{docs/,x/}.` ends in a\n * segment `.` either way. An escaped dot is the same character as a dot in a\n * name, so escaping one that begins `.x`, or the braces leave inside a name as\n * in `a{.,b}`, reads the same, and nothing needs to tell those apart:\n * escaping each whole `.` or `..` segment instead reads each of 43,069\n * generated patterns the same, refusals included (ADR-0022).\n */\nconst SEGMENT_DOT = /(?<=^|[/{,}])\\./g;\n\n/**\n * How a reference target is matched. Every option is spelled out, though the\n * dialect reads `{}` the same way today: its defaults are spec-core's to\n * change, and this reading is spec-graph's to keep. A mutant that drops one,\n * or all of them, is equivalent until then.\n */\nconst TARGET: FamilyGlobOptions = { dialect: 'path', caseSensitive: false, literal: 'file' };\n\n/**\n * A refusal of a reference pattern in the words it was typed in.\n *\n * The dialect writes its advice for a `**` inside a name from the text it was\n * given, and that text held a `\\` before each dot {@link SEGMENT_DOT} escaped:\n * `../notes/**.md` was told `\\.\\./notes/**\\/*.md`. Given the pattern again with\n * a character it does not hold in place of each of those dots, the dialect\n * refuses it for the same reason, since both are one literal character and\n * neither is a direction, and each stand-in is read back as the dot it was.\n * Counting down from U+E000 would find a stand-in as well, among the\n * surrogates, so that mutant is equivalent.\n */\nfunction asTyped(typed: string, reason: string): string {\n let point = 0xe000;\n while (typed.includes(String.fromCodePoint(point))) point += 1;\n const stand = String.fromCodePoint(point);\n const again = parseGlob(typed.replace(SEGMENT_DOT, stand), TARGET);\n // Stand-ins and escaped dots compile or fail alike, so `again` never\n // compiles here, and a mutant that reads it as compiled is equivalent.\n return again.ok ? reason : again.error.replaceAll(stand, '.');\n}\n\n/**\n * Builds a predicate over reference *targets*, not paths.\n *\n * Separate from {@link createGlobMatcher} on purpose. That one is\n * path-oriented: a bare name there is a directory and everything under it. A\n * reference target has no such structure - `trap 55` is a name, not a location\n * - so a bare pattern matches it literally and nothing else.\n *\n * Case is ignored, on every platform, because a citation's spelling is the\n * author's and not the filesystem's. The fold is simple case mapping, one code\n * point at a time and without a locale, so every host gives the same answer:\n * U+00B5 (micro sign) and U+03BC (mu) stay two targets, as they have been since\n * a Windows-only `i` flag made them one there (ADR-0017).\n *\n * A target is text a document holds rather than a path on this host, and two\n * things follow. A `\\` escapes the character after it: there is no Windows\n * separator to allow for. And a `.` or `..` segment is text, in a brace\n * alternative as anywhere else: in a path the dialect drops the one and\n * refuses the other as climbing out of the root, but `../../notes/gone.md` is\n * a link somebody wrote and may want left alone. A pattern that is refused is\n * named, and advised, as it was typed.\n */\nexport function createReferenceFilter(patterns: readonly string[]): (target: string) => boolean {\n // A blank pattern reaches the dialect, which refuses it, as every pattern\n // spec-graph reads is refused when it names nothing. It used to be dropped,\n // so an unset variable in `--ignore-ref \"$TAGS\"` went unnoticed.\n const globs: Glob[] = patterns.map((pattern) => {\n const typed = pattern.trim();\n const parsed = parseGlob(typed.replace(SEGMENT_DOT, '\\\\.'), TARGET);\n if (!parsed.ok) throw new GlobError(pattern, asTyped(typed, parsed.error));\n return parsed.glob;\n });\n return (target: string): boolean => {\n const value = target.trim();\n return globs.some((glob) => glob.match(value));\n };\n}\n\n/**\n * The literal directory a pattern's matches all sit under, or `''` for the root.\n *\n * `{docs,specs}/**` has two, and this is the directory they share; the walk\n * itself starts at each.\n */\nexport function globBase(pattern: string): string {\n const { glob } = pathList([pattern]).entries[0] as { readonly glob: Glob };\n const bases = glob.bases.map((base) => base.split('/'));\n const shared = bases[0] as string[];\n let length = shared.length;\n for (const base of bases) {\n let same = 0;\n // `<=` would read one past the end, where both sides are undefined and\n // equal, and slice the same prefix: an equivalent mutant, left untested.\n while (same < length && base[same] === shared[same]) same += 1;\n length = same;\n }\n return shared.slice(0, length).join('/');\n}\n\n/**\n * Whether a base names directories the walk from the root would reach, each\n * with exactly that spelling and none a link it would not follow.\n *\n * A walk starts where a pattern's literal prefix points rather than at the\n * root, and on a filesystem that ignores case, `readdir('Docs')` lists `docs`.\n * Every file under it would come back spelled `Docs/...` - a node id, a\n * baseline key - and `Docs/**` would find it on Windows and macOS and nothing\n * on Linux. Asking each parent for the name gives git's answer on every host. A\n * base with an empty segment is rooted at `/`, which is never inside the root.\n *\n * Reading a directory by its path follows every link in the path, so\n * `docs/linked/*.md` was read through the link `docs/linked`, which the walk\n * from the root passes over. Asking each parent for the entry says which it\n * is, and a base beyond a link is left as silently as the walk leaves the link.\n *\n * Where links are followed, the answer is the real path of each directory\n * above the base, the root included, for the walk to tell a cycle by; a base\n * beyond a link back into one of them is one the walk from the root never\n * reaches, and is left the same way. Where they are not, it is empty and never\n * read, so a mutant that fills it anyway is equivalent. `null` is a base the\n * walk does not start at.\n */\nasync function reachable(root: string, base: string, followSymlinks: boolean | undefined): Promise<Set<string> | null> {\n const above = new Set<string>();\n if (base.length === 0) return above;\n let directory = root;\n for (const segment of base.split('/')) {\n let entries: Dirent[];\n try {\n entries = await readdir(directory, { withFileTypes: true });\n } catch {\n // Answering a set here would change nothing a test can see: the walk\n // would then read a directory beneath this one, fail the same way, and\n // find nothing.\n return null;\n }\n const entry = entries.find((candidate) => candidate.name === segment);\n if (entry === undefined || (entry.isSymbolicLink() && !followSymlinks)) return null;\n if (followSymlinks) {\n // The directory was just listed, so asking for its real path fails only\n // where it went in between, and the walk would find nothing there: a\n // mutant that answers otherwise is equivalent.\n const real = await realpath(directory).catch(() => null);\n if (real === null || above.has(real)) return null;\n above.add(real);\n }\n directory = `${directory}/${segment}`;\n }\n return above;\n}\n\n/**\n * Walks the tree and returns every file matching the patterns.\n *\n * Directories are pruned as early as possible: a repository with a 2 GB\n * `node_modules` should cost nothing to scan.\n */\nexport async function walkFiles(options: WalkOptions): Promise<WalkedFile[]> {\n const root = toPosix(options.root).replace(/\\/+$/, '');\n const patterns = pathList(options.patterns);\n const maxSize = options.maxFileSize ?? MAX_FILE_SIZE;\n\n // Ignores come in two shapes and both are documented. A bare name prunes any\n // directory called that, at any depth, the way a `.gitignore` line does.\n // Anything carrying a separator or glob syntax is matched against the\n // repository-relative path, which is what `--ignore \"docs/drafts/**\"` means -\n // and treating that as a directory name silently excluded nothing at all.\n // A mutant that defaults this to `['Stryker was here']` prunes directories of\n // that name, which no repository has: equivalent, and left untested.\n const ignores = options.ignore ?? [];\n // The empty pattern is no directory's name, so it goes to the dialect, which\n // refuses it as it refuses an empty include: a pattern that names nothing is\n // a typo or an unset variable, and was an ignore that ignored nothing. So\n // does a blank one, which was read as a directory called \" \".\n const plainName = (pattern: string): boolean =>\n pattern.trim().length > 0 && !isGlob(pattern) && !pattern.includes('/') && !pattern.startsWith('!');\n // A `!` before a name gives the name back, as a `.gitignore` line does, and\n // the last bare entry to name a directory decides whether it is pruned. It\n // was read as a directory called `!docs`, so `--ignore docs --ignore \"!docs\"`\n // pruned `docs` and said nothing. The default list is a list of names too,\n // and gives way to one: `--ignore \"!vendor\"` reads every `vendor`. A `!` alone\n // or before another is no name, and goes to the dialect, which refuses both.\n const bare = (pattern: string): boolean => plainName(pattern) || (pattern.startsWith('!') && plainName(pattern.slice(1)));\n const named = new Map<string, boolean>();\n for (const pattern of ignores.filter(bare)) {\n const negated = pattern.startsWith('!');\n named.set(negated ? pattern.slice(1) : pattern, !negated);\n }\n const skippedByDefault = new Set(DEFAULT_IGNORED_DIRECTORIES);\n const ignoreList = pathList(ignores.filter((pattern) => !bare(pattern)));\n const excluded = (path: string): boolean => ignoreList.match(path);\n\n // Only walk the directories the patterns can possibly reach: each pattern's\n // literal prefix, one per brace alternative. A negated pattern adds none: it\n // takes files back, and starting a walk at its prefix would enter what the\n // walk skips - `!node_modules/**/*.txt` beside `**/*.md` would read every\n // Markdown file in `node_modules`. No positive pattern at all walks nothing,\n // which is the answer.\n const bases = new Set<string>();\n // The paths a positive pattern names outright: `docs/vendor`, or each literal\n // a brace expands to. Such a name may be a file, so its walk starts in the\n // directory above, which pruned `vendor` on its way in: `docs/vendor` found\n // nothing where `docs/vendor/` read the directory. The default list gives way\n // to the directory a pattern names as it gives way to one a pattern starts\n // inside. A negated name adds none, for the reason it adds no base.\n const literals = new Set<string>();\n for (const entry of patterns.entries) {\n if (entry.negated) continue;\n for (const base of entry.glob.bases) bases.add(base);\n // The dialect is what knows a literal when it reads one, so each pattern\n // is compiled a second time to be told of them. That glob is thrown away:\n // the reading answered here decides nothing, and a mutant that changes it\n // is equivalent.\n parseGlob(entry.glob.source, {\n ...PATH,\n literal: (path) => {\n literals.add(path);\n return 'either';\n },\n });\n }\n // Every base is walked, even one inside another, because the outer walk\n // prunes `vendor` and the rest of the default list on its way down, and a\n // pattern that starts inside one of those is read from there. Dropping the\n // inner base as already covered meant `docs/**/*.md` beside\n // `docs/vendor/specs/*.md` found less than the second pattern alone. An\n // `--ignore` is not overruled that way: it is the user's. A walk that starts\n // at a base never passed through the directories above it, so each of them,\n // and the base, is asked what the walk from the root would have asked on its\n // way down. A bare name prunes at any depth - `--ignore adr` still takes out\n // `adr/`, which the default `adr/**/*.md` starts inside - and a path takes\n // out what it matches, so under `--ignore \"docs/*\"` `docs/drafts/**/*.md`\n // finds what `docs/**/*.md` finds, which is nothing there. The root is not\n // asked, as the walk from it never asks: `*` matches the empty path, and\n // `**/*.md` under `--ignore \"*\" --ignore \"!{docs,specs}\"` would read nothing\n // where it reads those two.\n const startable = (base: string): boolean => {\n if (base.length === 0) return true;\n const segments = base.split('/');\n return !segments.some((segment, i) => named.get(segment) === true || excluded(segments.slice(0, i + 1).join('/')));\n };\n // Whether the walk leaves a directory it meets, asked of a followed link to\n // one as well: a link called `node_modules`, which pnpm writes, or one an\n // `--ignore` names, is the directory it leads to under that name and path,\n // and was entered whatever they were. Pruning a whole subtree is an\n // optimisation; a pattern that only matches the files inside it is still\n // honoured when they are filtered. A bare `--ignore` name prunes a directory\n // a pattern names as well: only the default list gives way, to a pattern and\n // to a `!` before its name.\n const pruned = (name: string, path: string): boolean =>\n (named.get(name) ?? (skippedByDefault.has(name) && !literals.has(path))) || excluded(path);\n const out = new Map<string, WalkedFile>();\n // Where two walks overlap, whichever reaches a directory first reads it and\n // the other stops there. Reading it twice would find the same files under\n // the same keys, so the two mutants that drop this are equivalent.\n const visited = new Set<string>();\n // Where links are followed, the real path of each directory from the root to\n // the one being read. A link whose real path is among them leads back into a\n // directory the walk is inside, and following it read the same files again\n // under a longer path each time round, until the host refused the path: on\n // Windows, 64 copies of each. It is passed over as silently as a link is\n // when links are not followed. A link to anywhere else is followed, one to a\n // directory the walk has already read beside this one included, since only\n // a directory on the way here can make a cycle. The walks run one at a time,\n // so one set serves them all. Only a followed link can make a cycle, so with\n // links not followed no real path is asked for, and a mutant that asks finds\n // none: equivalent.\n let inside = new Set<string>();\n\n const walk = async (relative: string): Promise<void> => {\n const absolute = relative.length === 0 ? root : `${root}/${relative}`;\n if (visited.has(absolute)) return;\n visited.add(absolute);\n if (!options.followSymlinks) return read(relative, absolute);\n // A directory with no real path is one that cannot be listed either, so\n // a mutant that reads it rather than returning reads nothing more.\n const real = await realpath(absolute).catch(() => null);\n if (real === null || inside.has(real)) return;\n inside.add(real);\n await read(relative, absolute);\n inside.delete(real);\n };\n\n const read = async (relative: string, absolute: string): Promise<void> => {\n let entries;\n try {\n entries = await readdir(absolute, { withFileTypes: true });\n } catch {\n // An unreadable directory is not a reason to fail the whole run.\n return;\n }\n\n for (const entry of entries) {\n const child = relative.length === 0 ? entry.name : `${relative}/${entry.name}`;\n\n if (entry.isDirectory()) {\n if (!pruned(entry.name, child)) await walk(child);\n continue;\n }\n\n if (entry.isSymbolicLink()) {\n if (!options.followSymlinks) continue;\n try {\n const info = await stat(`${root}/${child}`);\n if (info.isDirectory()) {\n if (!pruned(entry.name, child)) await walk(child);\n continue;\n }\n if (!patterns.match(child) || excluded(child) || info.size > maxSize) continue;\n out.set(child, { path: child, absolute: `${root}/${child}`, size: info.size });\n } catch {\n // A link to nothing has nothing to read.\n }\n continue;\n }\n\n if (!entry.isFile()) continue;\n if (!patterns.match(child) || excluded(child)) continue;\n\n try {\n const info = await stat(`${root}/${child}`);\n if (info.size > maxSize) continue;\n out.set(child, { path: child, absolute: `${root}/${child}`, size: info.size });\n } catch {\n // Gone between the listing and the look: there is nothing to read.\n }\n }\n };\n\n for (const base of bases) {\n const above = startable(base) ? await reachable(root, base, options.followSymlinks) : null;\n if (above === null) continue;\n inside = above;\n await walk(base);\n }\n\n // No two paths are equal, since they are the keys of `out`, so the order\n // needs only `<`, and `<=` would read the same.\n return [...out.values()].sort((a, b) => (a.path < b.path ? -1 : 1));\n}\n\n/**\n * Resolves a repository-relative path against the root, in POSIX form.\n *\n * An absolute path already names one place, and joining it under the root names\n * another: `--baseline /tmp/b.json` read `<root>/tmp/b.json`, found nothing\n * there, and accepted nothing without saying so.\n */\nexport function underRoot(root: string, relative: string): string {\n if (isAbsolutePath(relative)) return toPosix(relative);\n return joinPosix(toPosix(root), relative);\n}\n"]}
@@ -78,6 +78,18 @@ export declare function parsePrefixedRef(value: string): {
78
78
  family: string;
79
79
  number: number;
80
80
  } | null;
81
+ /**
82
+ * Whether a family can have this name, spaces around it aside.
83
+ *
84
+ * Asked of the reader of identifiers itself, with a number put after the
85
+ * name, so the two cannot drift apart: a name is a family's when an
86
+ * identifier written with it is read as that family. `--family` and
87
+ * `families` take a name on trust and compare it to what that reader finds,
88
+ * so one it can never find - an empty one, `ADR,RFC`, `ADR-0001` - matched
89
+ * nothing, and as the only name on an allowlist it turned every citation
90
+ * into prose and the check off with it (ADR-0010).
91
+ */
92
+ export declare function isFamilyName(value: string): boolean;
81
93
  /** Parses a bare `7` or `#0007`, or returns `null`. */
82
94
  export declare function parseBareRef(value: string): number | null;
83
95
  /** True when a reference target names a location rather than an identifier. */
package/dist/identity.js CHANGED
@@ -213,6 +213,21 @@ export function parsePrefixedRef(value) {
213
213
  return null;
214
214
  return { family: match[1].toUpperCase(), number: Number.parseInt(match[2], 10) };
215
215
  }
216
+ /**
217
+ * Whether a family can have this name, spaces around it aside.
218
+ *
219
+ * Asked of the reader of identifiers itself, with a number put after the
220
+ * name, so the two cannot drift apart: a name is a family's when an
221
+ * identifier written with it is read as that family. `--family` and
222
+ * `families` take a name on trust and compare it to what that reader finds,
223
+ * so one it can never find - an empty one, `ADR,RFC`, `ADR-0001` - matched
224
+ * nothing, and as the only name on an allowlist it turned every citation
225
+ * into prose and the check off with it (ADR-0010).
226
+ */
227
+ export function isFamilyName(value) {
228
+ const name = value.trim();
229
+ return parsePrefixedRef(`${name}-0`)?.family === name.toUpperCase();
230
+ }
216
231
  /** Parses a bare `7` or `#0007`, or returns `null`. */
217
232
  export function parseBareRef(value) {
218
233
  const match = BARE_NUMBER.exec(value.trim());
@@ -1 +1 @@
1
- {"version":3,"file":"identity.js","sourceRoot":"","sources":["../src/identity.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH;;;;;;GAMG;AACH,MAAM,kBAAkB,GAAgC,IAAI,GAAG,CAAC;IAC9D,CAAC,KAAK,EAAE,KAAK,CAAC;IACd,CAAC,MAAM,EAAE,KAAK,CAAC;IACf,CAAC,wBAAwB,EAAE,KAAK,CAAC;IACjC,CAAC,kBAAkB,EAAE,KAAK,CAAC;IAC3B,CAAC,WAAW,EAAE,KAAK,CAAC;IACpB,CAAC,KAAK,EAAE,KAAK,CAAC;IACd,CAAC,MAAM,EAAE,KAAK,CAAC;IACf,CAAC,KAAK,EAAE,KAAK,CAAC;IACd,CAAC,MAAM,EAAE,KAAK,CAAC;IACf,CAAC,cAAc,EAAE,KAAK,CAAC;IACvB,CAAC,UAAU,EAAE,UAAU,CAAC;IACxB,CAAC,WAAW,EAAE,UAAU,CAAC;IACzB,CAAC,QAAQ,EAAE,QAAQ,CAAC;IACpB,CAAC,SAAS,EAAE,QAAQ,CAAC;IACrB,CAAC,KAAK,EAAE,KAAK,CAAC;IACd,CAAC,MAAM,EAAE,KAAK,CAAC;IACf,CAAC,MAAM,EAAE,MAAM,CAAC;IAChB,CAAC,OAA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,CAAC,KAAK,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC;IAC9C,CAAC;IACD,OAAO,IAAI,CAAC;AACd,CAAC","sourcesContent":["/**\n * Document identity and reference normalisation.\n *\n * Foreign-key validation across a corpus of Markdown only works if `ADR-7`,\n * `ADR-0007`, `adr 7`, `[[0007-sharding]]` and `../adr/0007-sharding.md` are\n * understood to name the same document. Getting that wrong in either direction\n * is fatal: too strict and every real repository drowns in false \"broken\n * reference\" findings, too loose and `RFC 7` silently resolves to `ADR-7`.\n *\n * The resolution here is deliberately asymmetric. **Textual aliases** (`adr-7`)\n * are global, because a prefix already names the family. **Bare numbers** (`7`,\n * `#0007`) are resolved only within the citing document's own family, because a\n * repository with both `adr/0007` and `rfc/0007` is normal and guessing between\n * them would be worse than reporting nothing.\n */\n\n/**\n * Directory names that name a specification family, mapped to a canonical prefix.\n *\n * A map, because a directory is named by whoever made it and an object answers\n * to more names than it was given: `docs/constructor/` was a family, of no\n * prefix, and the run that read a document in it ended there.\n */\nconst FAMILY_DIRECTORIES: ReadonlyMap<string, string> = new Map([\n ['adr', 'ADR'],\n ['adrs', 'ADR'],\n ['architecture-decisions', 'ADR'],\n ['decision-records', 'ADR'],\n ['decisions', 'ADR'],\n ['rfc', 'RFC'],\n ['rfcs', 'RFC'],\n ['kep', 'KEP'],\n ['keps', 'KEP'],\n ['enhancements', 'KEP'],\n ['proposal', 'PROPOSAL'],\n ['proposals', 'PROPOSAL'],\n ['design', 'DESIGN'],\n ['designs', 'DESIGN'],\n ['prd', 'PRD'],\n ['prds', 'PRD'],\n ['spec', 'SPEC'],\n ['specs', 'SPEC'],\n]);\n\n/** Front-matter keys that may carry an explicit identifier, in preference order. */\nexport const ID_KEYS: readonly string[] = ['id', 'adr', 'adr-id', 'rfc', 'rfc-id', 'kep-number', 'number', 'slug'];\n\n/** `ADR-0007`, `KEP 1234`, `rfc2119`: a family prefix followed by a number. */\nconst PREFIXED_ID = /^([A-Za-z][A-Za-z0-9_]{0,15}?)[\\s._-]*(\\d{1,6})$/;\n/** A bare number, optionally hash-prefixed: `7`, `#0007`. */\nconst BARE_NUMBER = /^#?(\\d{1,6})$/;\n\nexport interface DocumentIdentity {\n /** The canonical id: `ADR-0007`, or a path when nothing better exists. */\n readonly id: string;\n /** Family prefix, upper-cased. `null` when the document is not numbered. */\n readonly family: string | null;\n /** Sequence number without leading zeros. `null` when not numbered. */\n readonly number: number | null;\n /** Every lower-cased spelling that should resolve to this document. */\n readonly aliases: readonly string[];\n}\n\nexport interface IdentityInput {\n /** Repository-relative POSIX path. */\n readonly path: string;\n /** An id declared by a directive or front matter, if any. */\n readonly declaredId: string | null;\n /** Extra aliases declared by a directive or front matter. */\n readonly declaredAliases: readonly string[];\n /** The document H1, if any. */\n readonly heading: string | null;\n /**\n * Whether this identity is the file's own. Default true.\n *\n * A specification that is a *region* of a file must not claim the file's\n * path: the file already answers to it, and two nodes answering to one path\n * would make every link to that file ambiguous. The file's *name* is the same\n * claim spelled differently, so a region does not read a number out of it\n * either: every row of a register kept in `0042-open-issues.md` answered to\n * ADR-0042, and so did the file.\n */\n readonly includePathAliases?: boolean | undefined;\n}\n\n/** An id has to be a name. Punctuation alone is what a bad parse leaves behind. */\nexport const HAS_LETTER_OR_DIGIT = /[\\p{L}\\p{N}]/u;\n\n/**\n * Derives a document's canonical id and every alias that should reach it.\n *\n * Evidence is used in order of how deliberate it is: an explicit declaration,\n * then the file name, then the H1. The first two both *name* the document, so a\n * declaration that carries no number still takes the number from the file name\n * beside it - `slug: sharding-the-write-path` in `0007-sharding.md` is ADR-0007.\n * A title only *describes* it, so it is read as a name only where nothing else\n * has given one. A losing declaration or file name still contributes aliases,\n * so a reference written in either form resolves; a title that lost does not,\n * because the identifier it opens with belongs to the document it is about.\n */\nexport function identify(input: IdentityInput): DocumentIdentity {\n // A declaration carrying no letter or digit is discarded rather than honoured.\n // `<!-- @spec-node id=\\\"ADR-9\\\" -->`, written inside a JavaScript string in a\n // worked example, parses its bare value as a lone backslash - and a document\n // whose id is `\\` collides with every other one that made the same mistake,\n // exports as invalid Mermaid, and names itself in findings a reader cannot act\n // on. There is nothing to gain by taking such a value seriously. The null\n // check is for the type: `test(null)` reads the word \"null\" and passes, and\n // the value it would keep is null anyway.\n const declaredId = input.declaredId !== null && HAS_LETTER_OR_DIGIT.test(input.declaredId) ? input.declaredId : null;\n // What the flag decides, named for what it means: the file's path and its\n // name are one claim, and a region makes neither of them.\n const ownsFile = input.includePathAliases !== false;\n const stem = fileStem(input.path);\n const directoryFamily = familyFromPath(input.path);\n const aliases = new Set<string>();\n\n const add = (value: string | null | undefined): void => {\n if (!value) return;\n const key = normaliseRef(value);\n if (key.length > 0) aliases.add(key);\n };\n\n // Only a spelling that yields a number decides anything below, so only those\n // are kept. `digits` is the number as it was written there.\n const candidates: { family: string | null; number: number; digits: string }[] = [];\n\n const consider = (raw: string | null, allowBare: boolean): void => {\n if (!raw) return;\n const cleaned = raw.trim();\n const prefixed = PREFIXED_ID.exec(cleaned);\n if (prefixed) {\n const digits = prefixed[2] as string;\n candidates.push({ family: (prefixed[1] as string).toUpperCase(), number: Number.parseInt(digits, 10), digits });\n return;\n }\n const bare = BARE_NUMBER.exec(cleaned);\n if (bare && allowBare) {\n const digits = bare[1] as string;\n candidates.push({ family: directoryFamily, number: Number.parseInt(digits, 10), digits });\n }\n };\n\n consider(declaredId, true);\n // `0007-sharding-the-write-path.md` and `kep-1234-foo.md` both start with the\n // identifier; take the leading token rather than the whole stem. Only for the\n // file's own identity: the name names the file, and a region reading its\n // number is the collision ADR-0009 forbids, reached by a second route.\n if (ownsFile) consider(leadingToken(stem), true);\n\n // A title is prose *about* a document, so it names one only where nothing has\n // named it yet, and where it does not it registers no alias either - an alias\n // is the same mistake one step removed, landing on a document that is real.\n // A number disqualifies it, because a different number in a title is about a\n // different document; so does being a region, because a row's id column\n // exists to hold an identifier while its title cell is prose about the rest\n // of the corpus. `| OI-V-05 | ADR-040's enforcement point has no browser\n // test |` became ADR-040, collided with the real one and left the issue with\n // no node at all: 27 of 232 rows of one register, nine inventing a `STAGE-1`\n // nobody had written. A *file* keeps the looser reading deliberately - there\n // the two cases are one shape, `slug:` holds a URL segment rather than an id,\n // and `slug: sharding` under `# ADR-0007` has to stay ADR-0007. See the fifth\n // asymmetry in ADR-0004 for what that costs and why it is not guessed at.\n //\n // Considered last, it names the document only where nothing before it gave\n // a number: only the first candidate is read. A title that does name it\n // supplies the number, and the spellings of that number registered below\n // include the title's own. `false` decides nothing, since an identifier a\n // heading opens with always starts with letters; it says a bare number in a\n // title would name nothing.\n consider(ownsFile ? headingId(input.heading) : null, false);\n\n const numbered = candidates[0];\n const family = numbered?.family ?? directoryFamily;\n const number = numbered?.number ?? null;\n\n let id: string;\n if (numbered !== undefined && family !== null) {\n // Written as the number was written where it was found, which is the local\n // zero-padding convention: an id read from the H1 of `sharding.md` still\n // renders as ADR-0007, not ADR-7, and one declared as `S3-0012` stays that.\n id = `${family}-${numbered.digits}`;\n } else if (declaredId) {\n id = declaredId.trim();\n } else if (number !== null) {\n // Numbered but with no family to prefix - a Rust RFC in `text/0001-foo.md`,\n // say. The file stem is a far better identity than a bare \"1\": it is what\n // people actually type, and it stays unique across the repository.\n //\n // A file's stem is never empty - `.md` is its own - so this fallback, and\n // with it the difference between this branch and the next, is reached only\n // by a caller identifying an empty path.\n id = stem.length > 0 ? stem : String(number);\n } else {\n id = stem.length > 0 ? stem : input.path;\n }\n\n add(id);\n if (ownsFile) {\n add(stem);\n add(input.path);\n add(stripExtension(input.path));\n }\n add(declaredId);\n for (const alias of input.declaredAliases) add(alias);\n\n if (numbered !== undefined) {\n const spellings = numberSpellings(numbered.number, numbered.digits);\n if (family !== null) {\n // Every spelling a human might type. `normaliseRef` folds separators, so\n // `adr-7`, `adr 7` and `adr7` collapse to one key; the padding variants do\n // not, and each needs registering.\n for (const digits of spellings) add(`${family}-${digits}`);\n } else {\n // With no family there is only one number space in the repository, so a\n // bare `0001` is unambiguous and worth resolving.\n for (const digits of spellings) add(digits);\n }\n }\n\n return { id, family, number, aliases: [...aliases] };\n}\n\n/**\n * Folds a reference to its lookup key.\n *\n * Case, separators and surrounding punctuation carry no meaning in a citation,\n * so `ADR-0007`, `adr 0007` and `Adr_0007` all become `adr0007`.\n */\nexport function normaliseRef(value: string): string {\n // The separators go last and take every space with them, so nothing is left\n // to trim. `+` only saves work: each separator is removed either way.\n return value\n .trim()\n .toLowerCase()\n .replace(/^[#<([]+|[)\\]>.,;:]+$/g, '')\n .replace(/[\\s._-]+/g, '');\n}\n\n/** Splits a `target#anchor` reference. */\nexport function splitAnchor(target: string): { target: string; anchor: string | null } {\n const hash = target.indexOf('#');\n if (hash === -1) return { target, anchor: null };\n // A leading `#` leaves the target empty: an anchor in the citing document.\n return { target: target.slice(0, hash), anchor: target.slice(hash + 1) };\n}\n\n/** Parses `ADR-0007` into its family and number, or returns `null`. */\nexport function parsePrefixedRef(value: string): { family: string; number: number } | null {\n const match = PREFIXED_ID.exec(value.trim().replace(/^[#([]+/, ''));\n if (!match) return null;\n return { family: (match[1] as string).toUpperCase(), number: Number.parseInt(match[2] as string, 10) };\n}\n\n/** Parses a bare `7` or `#0007`, or returns `null`. */\nexport function parseBareRef(value: string): number | null {\n const match = BARE_NUMBER.exec(value.trim());\n return match ? Number.parseInt(match[1] as string, 10) : null;\n}\n\n/** True when a reference target names a location rather than an identifier. */\nexport function looksLikePath(target: string): boolean {\n return target.includes('/') || DOCUMENT_EXTENSION.test(target);\n}\n\nconst DOCUMENT_EXTENSION = /\\.(md|markdown|mdx|txt|rst|adoc|asciidoc)$/i;\n\n/**\n * True when a path-like target could name a specification.\n *\n * A specification linking to `../../src/rules.ts` is citing source code, which\n * is a different tool's job. Treating it as a dangling specification reference\n * would report an error on one of the most ordinary things a design document\n * does, so targets carrying a non-document extension are not references at all.\n *\n * A dotfile is such a target too - `../.nvmrc` names a file whose extension is\n * its whole name - and so is a file whose extension is long: `arch.excalidraw`\n * is a drawing, not an identifier with a dot in it (ADR-0006).\n */\nexport function isDocumentTarget(target: string): boolean {\n const withoutAnchor = splitAnchor(target).target;\n const base = withoutAnchor.slice(withoutAnchor.lastIndexOf('/') + 1);\n const dot = base.lastIndexOf('.');\n // No extension: a directory, or an extensionless spec such as `rfcs/0007`.\n // Said outright rather than left to the test below, which would refuse the\n // last character `slice(-1)` handed it and answer the same.\n if (dot === -1) return true;\n const extension = base.slice(dot);\n // Only a file extension disqualifies a target, and one starts with a letter.\n // An identifier like `v1.2` or `ADR-0007.1` keeps its dot and is still\n // resolved as an id. The extension starts at the last dot and holds no\n // other, so the leading anchor decides nothing; it says the dot is where the\n // extension begins.\n if (!/^\\.[A-Za-z][A-Za-z0-9]*$/.test(extension)) return true;\n return DOCUMENT_EXTENSION.test(base);\n}\n\n/** True when a reference target points outside the repository. */\nexport function isExternal(target: string): boolean {\n return /^[a-z][a-z0-9+.-]*:/i.test(target) && !/^[a-z]:[\\\\/]/i.test(target);\n}\n\n/** The family prefix implied by a document's directory, if any. */\nexport function familyFromPath(posixPath: string): string | null {\n const segments = posixPath.toLowerCase().split('/');\n // Nearest enclosing directory wins: `docs/rfcs/adr/0007.md` is an ADR.\n for (let i = segments.length - 2; i >= 0; i -= 1) {\n const found = FAMILY_DIRECTORIES.get(segments[i] as string);\n if (found) return found;\n }\n return null;\n}\n\n/* -------------------------------------------------------------------------- */\n/* Internals */\n/* -------------------------------------------------------------------------- */\n\nfunction fileStem(posixPath: string): string {\n const base = posixPath.slice(posixPath.lastIndexOf('/') + 1);\n const dot = base.lastIndexOf('.');\n const stem = dot > 0 ? base.slice(0, dot) : base;\n // `docs/adr/0007-sharding/README.md` is identified by its directory - but a\n // README at the repository root has no directory to be named after, and must\n // keep its own name. A repository-relative path never starts with `/`, so\n // `slash > 0` and `slash >= 0` agree on every path this is given.\n const slash = posixPath.lastIndexOf('/');\n if (slash > 0 && /^(readme|index)$/i.test(stem)) {\n const parent = posixPath.slice(0, slash);\n return parent.slice(parent.lastIndexOf('/') + 1);\n }\n return stem;\n}\n\nfunction stripExtension(posixPath: string): string {\n const dot = posixPath.lastIndexOf('.');\n const slash = posixPath.lastIndexOf('/');\n return dot > slash ? posixPath.slice(0, dot) : posixPath;\n}\n\n/**\n * `kep-1234-foo` -> `kep-1234`; `0007-sharding` -> `0007`; `sharding` -> `sharding`.\n *\n * The `$` alternatives decide nothing: a stem that is the identifier alone is\n * handed back whole by the last line, and parses the same. They say that an\n * identifier may end the name as well as open it.\n */\nfunction leadingToken(stem: string): string {\n const prefixed = /^([A-Za-z]{1,15}[\\s._-]?\\d{1,6})(?:[\\s._-]|$)/.exec(stem);\n if (prefixed) return prefixed[1] as string;\n const bare = /^(\\d{1,6})(?:[\\s._-]|$)/.exec(stem);\n if (bare) return bare[1] as string;\n return stem;\n}\n\n/** `# ADR-0007: Sharding the write path` -> `ADR-0007`. */\nfunction headingId(heading: string | null): string | null {\n // Only saves the call: `exec` would read null as the word \"null\", and\n // neither that nor an empty heading holds a number.\n if (!heading) return null;\n const match = /^\\s*([A-Za-z]{1,15}[\\s._-]?\\d{1,6})\\b/.exec(heading);\n return match ? (match[1] as string) : null;\n}\n\n/**\n * Zero-padded spellings a citation might reasonably use: the number as it was\n * written, unpadded, and padded to three and to four digits.\n */\nfunction numberSpellings(number: number, written: string): string[] {\n const unpadded = String(number);\n return [...new Set([written, unpadded, unpadded.padStart(3, '0'), unpadded.padStart(4, '0')])];\n}\n\n/**\n * True when two folded spellings are one edit apart.\n *\n * One edit, not two, and a transposition counts as one: `supercedesby` for\n * `supercededby` is a slip of the finger, `categories` for `dependencies` is a\n * different word. Written out rather than as a distance matrix because the\n * answer is a yes or a no and the bound is one - the general algorithm would be\n * more code, not less.\n */\nexport function withinOneEdit(a: string, b: string): boolean {\n // The loop bounds are not boundaries: one step past the end of equal-length\n // strings compares undefined with undefined and continues, and one past the\n // end of the shorter compares nothing with the last character of the longer\n // and finds the two empty remainders equal - both the answer the loop's exit\n // gives. Nor does `<` against `<=` below matter: equal lengths never get there.\n if (a === b) return false;\n if (a.length === b.length) {\n let first = -1;\n for (let i = 0; i < a.length; i += 1) {\n if (a[i] === b[i]) continue;\n if (first === -1) {\n first = i;\n continue;\n }\n // A second difference is allowed only if the two are a swapped pair, and\n // only if there is no third.\n return first === i - 1 && a[first] === b[i] && a[i] === b[first] && a.slice(i + 1) === b.slice(i + 1);\n }\n return true;\n }\n const [short, long] = a.length < b.length ? [a, b] : [b, a];\n if (long.length - short.length !== 1) return false;\n for (let i = 0; i < short.length; i += 1) {\n if (short[i] === long[i]) continue;\n return short.slice(i) === long.slice(i + 1);\n }\n return true;\n}\n"]}
1
+ {"version":3,"file":"identity.js","sourceRoot":"","sources":["../src/identity.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH;;;;;;GAMG;AACH,MAAM,kBAAkB,GAAgC,IAAI,GAAG,CAAC;IAC9D,CAAC,KAAK,EAAE,KAAK,CAAC;IACd,CAAC,MAAM,EAAE,KAAK,CAAC;IACf,CAAC,wBAAwB,EAAE,KAAK,CAAC;IACjC,CAAC,kBAAkB,EAAE,KAAK,CAAC;IAC3B,CAAC,WAAW,EAAE,KAAK,CAAC;IACpB,CAAC,KAAK,EAAE,KAAK,CAAC;IACd,CAAC,MAAM,EAAE,KAAK,CAAC;IACf,CAAC,KAAK,EAAE,KAAK,CAAC;IACd,CAAC,MAAM,EAAE,KAAK,CAAC;IACf,CAAC,cAAc,EAAE,KAAK,CAAC;IACvB,CAAC,UAAU,EAAE,UAAU,CAAC;IACxB,CAAC,WAAW,EAAE,UAAU,CAAC;IACzB,CAAC,QAAQ,EAAE,QAAQ,CAAC;IACpB,CAAC,SAAS,EAAE,QAAQ,CAAC;IACrB,CAAC,KAAK,EAAE,KAAK,CAAC;IACd,CAAC,MAAM,EAAE,KAAK,CAAC;IACf,CAAC,MAAM,EAAE,MAAM,CAAC;IAChB,CAAC,OAAO,EAAE,MAAM,CAAC;CAClB,CAAC,CAAC;AAEH,oFAAoF;AACpF,MAAM,CAAC,MAAM,OAAO,GAAs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zC,IAAI,KAAK,CAAC,CAAC,CAAC,KAAK,IAAI,CAAC,CAAC,CAAC;YAAE,SAAS;QACnC,OAAO,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC,KAAK,IAAI,CAAC,KAAK,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC;IAC9C,CAAC;IACD,OAAO,IAAI,CAAC;AACd,CAAC","sourcesContent":["/**\n * Document identity and reference normalisation.\n *\n * Foreign-key validation across a corpus of Markdown only works if `ADR-7`,\n * `ADR-0007`, `adr 7`, `[[0007-sharding]]` and `../adr/0007-sharding.md` are\n * understood to name the same document. Getting that wrong in either direction\n * is fatal: too strict and every real repository drowns in false \"broken\n * reference\" findings, too loose and `RFC 7` silently resolves to `ADR-7`.\n *\n * The resolution here is deliberately asymmetric. **Textual aliases** (`adr-7`)\n * are global, because a prefix already names the family. **Bare numbers** (`7`,\n * `#0007`) are resolved only within the citing document's own family, because a\n * repository with both `adr/0007` and `rfc/0007` is normal and guessing between\n * them would be worse than reporting nothing.\n */\n\n/**\n * Directory names that name a specification family, mapped to a canonical prefix.\n *\n * A map, because a directory is named by whoever made it and an object answers\n * to more names than it was given: `docs/constructor/` was a family, of no\n * prefix, and the run that read a document in it ended there.\n */\nconst FAMILY_DIRECTORIES: ReadonlyMap<string, string> = new Map([\n ['adr', 'ADR'],\n ['adrs', 'ADR'],\n ['architecture-decisions', 'ADR'],\n ['decision-records', 'ADR'],\n ['decisions', 'ADR'],\n ['rfc', 'RFC'],\n ['rfcs', 'RFC'],\n ['kep', 'KEP'],\n ['keps', 'KEP'],\n ['enhancements', 'KEP'],\n ['proposal', 'PROPOSAL'],\n ['proposals', 'PROPOSAL'],\n ['design', 'DESIGN'],\n ['designs', 'DESIGN'],\n ['prd', 'PRD'],\n ['prds', 'PRD'],\n ['spec', 'SPEC'],\n ['specs', 'SPEC'],\n]);\n\n/** Front-matter keys that may carry an explicit identifier, in preference order. */\nexport const ID_KEYS: readonly string[] = ['id', 'adr', 'adr-id', 'rfc', 'rfc-id', 'kep-number', 'number', 'slug'];\n\n/** `ADR-0007`, `KEP 1234`, `rfc2119`: a family prefix followed by a number. */\nconst PREFIXED_ID = /^([A-Za-z][A-Za-z0-9_]{0,15}?)[\\s._-]*(\\d{1,6})$/;\n/** A bare number, optionally hash-prefixed: `7`, `#0007`. */\nconst BARE_NUMBER = /^#?(\\d{1,6})$/;\n\nexport interface DocumentIdentity {\n /** The canonical id: `ADR-0007`, or a path when nothing better exists. */\n readonly id: string;\n /** Family prefix, upper-cased. `null` when the document is not numbered. */\n readonly family: string | null;\n /** Sequence number without leading zeros. `null` when not numbered. */\n readonly number: number | null;\n /** Every lower-cased spelling that should resolve to this document. */\n readonly aliases: readonly string[];\n}\n\nexport interface IdentityInput {\n /** Repository-relative POSIX path. */\n readonly path: string;\n /** An id declared by a directive or front matter, if any. */\n readonly declaredId: string | null;\n /** Extra aliases declared by a directive or front matter. */\n readonly declaredAliases: readonly string[];\n /** The document H1, if any. */\n readonly heading: string | null;\n /**\n * Whether this identity is the file's own. Default true.\n *\n * A specification that is a *region* of a file must not claim the file's\n * path: the file already answers to it, and two nodes answering to one path\n * would make every link to that file ambiguous. The file's *name* is the same\n * claim spelled differently, so a region does not read a number out of it\n * either: every row of a register kept in `0042-open-issues.md` answered to\n * ADR-0042, and so did the file.\n */\n readonly includePathAliases?: boolean | undefined;\n}\n\n/** An id has to be a name. Punctuation alone is what a bad parse leaves behind. */\nexport const HAS_LETTER_OR_DIGIT = /[\\p{L}\\p{N}]/u;\n\n/**\n * Derives a document's canonical id and every alias that should reach it.\n *\n * Evidence is used in order of how deliberate it is: an explicit declaration,\n * then the file name, then the H1. The first two both *name* the document, so a\n * declaration that carries no number still takes the number from the file name\n * beside it - `slug: sharding-the-write-path` in `0007-sharding.md` is ADR-0007.\n * A title only *describes* it, so it is read as a name only where nothing else\n * has given one. A losing declaration or file name still contributes aliases,\n * so a reference written in either form resolves; a title that lost does not,\n * because the identifier it opens with belongs to the document it is about.\n */\nexport function identify(input: IdentityInput): DocumentIdentity {\n // A declaration carrying no letter or digit is discarded rather than honoured.\n // `<!-- @spec-node id=\\\"ADR-9\\\" -->`, written inside a JavaScript string in a\n // worked example, parses its bare value as a lone backslash - and a document\n // whose id is `\\` collides with every other one that made the same mistake,\n // exports as invalid Mermaid, and names itself in findings a reader cannot act\n // on. There is nothing to gain by taking such a value seriously. The null\n // check is for the type: `test(null)` reads the word \"null\" and passes, and\n // the value it would keep is null anyway.\n const declaredId = input.declaredId !== null && HAS_LETTER_OR_DIGIT.test(input.declaredId) ? input.declaredId : null;\n // What the flag decides, named for what it means: the file's path and its\n // name are one claim, and a region makes neither of them.\n const ownsFile = input.includePathAliases !== false;\n const stem = fileStem(input.path);\n const directoryFamily = familyFromPath(input.path);\n const aliases = new Set<string>();\n\n const add = (value: string | null | undefined): void => {\n if (!value) return;\n const key = normaliseRef(value);\n if (key.length > 0) aliases.add(key);\n };\n\n // Only a spelling that yields a number decides anything below, so only those\n // are kept. `digits` is the number as it was written there.\n const candidates: { family: string | null; number: number; digits: string }[] = [];\n\n const consider = (raw: string | null, allowBare: boolean): void => {\n if (!raw) return;\n const cleaned = raw.trim();\n const prefixed = PREFIXED_ID.exec(cleaned);\n if (prefixed) {\n const digits = prefixed[2] as string;\n candidates.push({ family: (prefixed[1] as string).toUpperCase(), number: Number.parseInt(digits, 10), digits });\n return;\n }\n const bare = BARE_NUMBER.exec(cleaned);\n if (bare && allowBare) {\n const digits = bare[1] as string;\n candidates.push({ family: directoryFamily, number: Number.parseInt(digits, 10), digits });\n }\n };\n\n consider(declaredId, true);\n // `0007-sharding-the-write-path.md` and `kep-1234-foo.md` both start with the\n // identifier; take the leading token rather than the whole stem. Only for the\n // file's own identity: the name names the file, and a region reading its\n // number is the collision ADR-0009 forbids, reached by a second route.\n if (ownsFile) consider(leadingToken(stem), true);\n\n // A title is prose *about* a document, so it names one only where nothing has\n // named it yet, and where it does not it registers no alias either - an alias\n // is the same mistake one step removed, landing on a document that is real.\n // A number disqualifies it, because a different number in a title is about a\n // different document; so does being a region, because a row's id column\n // exists to hold an identifier while its title cell is prose about the rest\n // of the corpus. `| OI-V-05 | ADR-040's enforcement point has no browser\n // test |` became ADR-040, collided with the real one and left the issue with\n // no node at all: 27 of 232 rows of one register, nine inventing a `STAGE-1`\n // nobody had written. A *file* keeps the looser reading deliberately - there\n // the two cases are one shape, `slug:` holds a URL segment rather than an id,\n // and `slug: sharding` under `# ADR-0007` has to stay ADR-0007. See the fifth\n // asymmetry in ADR-0004 for what that costs and why it is not guessed at.\n //\n // Considered last, it names the document only where nothing before it gave\n // a number: only the first candidate is read. A title that does name it\n // supplies the number, and the spellings of that number registered below\n // include the title's own. `false` decides nothing, since an identifier a\n // heading opens with always starts with letters; it says a bare number in a\n // title would name nothing.\n consider(ownsFile ? headingId(input.heading) : null, false);\n\n const numbered = candidates[0];\n const family = numbered?.family ?? directoryFamily;\n const number = numbered?.number ?? null;\n\n let id: string;\n if (numbered !== undefined && family !== null) {\n // Written as the number was written where it was found, which is the local\n // zero-padding convention: an id read from the H1 of `sharding.md` still\n // renders as ADR-0007, not ADR-7, and one declared as `S3-0012` stays that.\n id = `${family}-${numbered.digits}`;\n } else if (declaredId) {\n id = declaredId.trim();\n } else if (number !== null) {\n // Numbered but with no family to prefix - a Rust RFC in `text/0001-foo.md`,\n // say. The file stem is a far better identity than a bare \"1\": it is what\n // people actually type, and it stays unique across the repository.\n //\n // A file's stem is never empty - `.md` is its own - so this fallback, and\n // with it the difference between this branch and the next, is reached only\n // by a caller identifying an empty path.\n id = stem.length > 0 ? stem : String(number);\n } else {\n id = stem.length > 0 ? stem : input.path;\n }\n\n add(id);\n if (ownsFile) {\n add(stem);\n add(input.path);\n add(stripExtension(input.path));\n }\n add(declaredId);\n for (const alias of input.declaredAliases) add(alias);\n\n if (numbered !== undefined) {\n const spellings = numberSpellings(numbered.number, numbered.digits);\n if (family !== null) {\n // Every spelling a human might type. `normaliseRef` folds separators, so\n // `adr-7`, `adr 7` and `adr7` collapse to one key; the padding variants do\n // not, and each needs registering.\n for (const digits of spellings) add(`${family}-${digits}`);\n } else {\n // With no family there is only one number space in the repository, so a\n // bare `0001` is unambiguous and worth resolving.\n for (const digits of spellings) add(digits);\n }\n }\n\n return { id, family, number, aliases: [...aliases] };\n}\n\n/**\n * Folds a reference to its lookup key.\n *\n * Case, separators and surrounding punctuation carry no meaning in a citation,\n * so `ADR-0007`, `adr 0007` and `Adr_0007` all become `adr0007`.\n */\nexport function normaliseRef(value: string): string {\n // The separators go last and take every space with them, so nothing is left\n // to trim. `+` only saves work: each separator is removed either way.\n return value\n .trim()\n .toLowerCase()\n .replace(/^[#<([]+|[)\\]>.,;:]+$/g, '')\n .replace(/[\\s._-]+/g, '');\n}\n\n/** Splits a `target#anchor` reference. */\nexport function splitAnchor(target: string): { target: string; anchor: string | null } {\n const hash = target.indexOf('#');\n if (hash === -1) return { target, anchor: null };\n // A leading `#` leaves the target empty: an anchor in the citing document.\n return { target: target.slice(0, hash), anchor: target.slice(hash + 1) };\n}\n\n/** Parses `ADR-0007` into its family and number, or returns `null`. */\nexport function parsePrefixedRef(value: string): { family: string; number: number } | null {\n const match = PREFIXED_ID.exec(value.trim().replace(/^[#([]+/, ''));\n if (!match) return null;\n return { family: (match[1] as string).toUpperCase(), number: Number.parseInt(match[2] as string, 10) };\n}\n\n/**\n * Whether a family can have this name, spaces around it aside.\n *\n * Asked of the reader of identifiers itself, with a number put after the\n * name, so the two cannot drift apart: a name is a family's when an\n * identifier written with it is read as that family. `--family` and\n * `families` take a name on trust and compare it to what that reader finds,\n * so one it can never find - an empty one, `ADR,RFC`, `ADR-0001` - matched\n * nothing, and as the only name on an allowlist it turned every citation\n * into prose and the check off with it (ADR-0010).\n */\nexport function isFamilyName(value: string): boolean {\n const name = value.trim();\n return parsePrefixedRef(`${name}-0`)?.family === name.toUpperCase();\n}\n\n/** Parses a bare `7` or `#0007`, or returns `null`. */\nexport function parseBareRef(value: string): number | null {\n const match = BARE_NUMBER.exec(value.trim());\n return match ? Number.parseInt(match[1] as string, 10) : null;\n}\n\n/** True when a reference target names a location rather than an identifier. */\nexport function looksLikePath(target: string): boolean {\n return target.includes('/') || DOCUMENT_EXTENSION.test(target);\n}\n\nconst DOCUMENT_EXTENSION = /\\.(md|markdown|mdx|txt|rst|adoc|asciidoc)$/i;\n\n/**\n * True when a path-like target could name a specification.\n *\n * A specification linking to `../../src/rules.ts` is citing source code, which\n * is a different tool's job. Treating it as a dangling specification reference\n * would report an error on one of the most ordinary things a design document\n * does, so targets carrying a non-document extension are not references at all.\n *\n * A dotfile is such a target too - `../.nvmrc` names a file whose extension is\n * its whole name - and so is a file whose extension is long: `arch.excalidraw`\n * is a drawing, not an identifier with a dot in it (ADR-0006).\n */\nexport function isDocumentTarget(target: string): boolean {\n const withoutAnchor = splitAnchor(target).target;\n const base = withoutAnchor.slice(withoutAnchor.lastIndexOf('/') + 1);\n const dot = base.lastIndexOf('.');\n // No extension: a directory, or an extensionless spec such as `rfcs/0007`.\n // Said outright rather than left to the test below, which would refuse the\n // last character `slice(-1)` handed it and answer the same.\n if (dot === -1) return true;\n const extension = base.slice(dot);\n // Only a file extension disqualifies a target, and one starts with a letter.\n // An identifier like `v1.2` or `ADR-0007.1` keeps its dot and is still\n // resolved as an id. The extension starts at the last dot and holds no\n // other, so the leading anchor decides nothing; it says the dot is where the\n // extension begins.\n if (!/^\\.[A-Za-z][A-Za-z0-9]*$/.test(extension)) return true;\n return DOCUMENT_EXTENSION.test(base);\n}\n\n/** True when a reference target points outside the repository. */\nexport function isExternal(target: string): boolean {\n return /^[a-z][a-z0-9+.-]*:/i.test(target) && !/^[a-z]:[\\\\/]/i.test(target);\n}\n\n/** The family prefix implied by a document's directory, if any. */\nexport function familyFromPath(posixPath: string): string | null {\n const segments = posixPath.toLowerCase().split('/');\n // Nearest enclosing directory wins: `docs/rfcs/adr/0007.md` is an ADR.\n for (let i = segments.length - 2; i >= 0; i -= 1) {\n const found = FAMILY_DIRECTORIES.get(segments[i] as string);\n if (found) return found;\n }\n return null;\n}\n\n/* -------------------------------------------------------------------------- */\n/* Internals */\n/* -------------------------------------------------------------------------- */\n\nfunction fileStem(posixPath: string): string {\n const base = posixPath.slice(posixPath.lastIndexOf('/') + 1);\n const dot = base.lastIndexOf('.');\n const stem = dot > 0 ? base.slice(0, dot) : base;\n // `docs/adr/0007-sharding/README.md` is identified by its directory - but a\n // README at the repository root has no directory to be named after, and must\n // keep its own name. A repository-relative path never starts with `/`, so\n // `slash > 0` and `slash >= 0` agree on every path this is given.\n const slash = posixPath.lastIndexOf('/');\n if (slash > 0 && /^(readme|index)$/i.test(stem)) {\n const parent = posixPath.slice(0, slash);\n return parent.slice(parent.lastIndexOf('/') + 1);\n }\n return stem;\n}\n\nfunction stripExtension(posixPath: string): string {\n const dot = posixPath.lastIndexOf('.');\n const slash = posixPath.lastIndexOf('/');\n return dot > slash ? posixPath.slice(0, dot) : posixPath;\n}\n\n/**\n * `kep-1234-foo` -> `kep-1234`; `0007-sharding` -> `0007`; `sharding` -> `sharding`.\n *\n * The `$` alternatives decide nothing: a stem that is the identifier alone is\n * handed back whole by the last line, and parses the same. They say that an\n * identifier may end the name as well as open it.\n */\nfunction leadingToken(stem: string): string {\n const prefixed = /^([A-Za-z]{1,15}[\\s._-]?\\d{1,6})(?:[\\s._-]|$)/.exec(stem);\n if (prefixed) return prefixed[1] as string;\n const bare = /^(\\d{1,6})(?:[\\s._-]|$)/.exec(stem);\n if (bare) return bare[1] as string;\n return stem;\n}\n\n/** `# ADR-0007: Sharding the write path` -> `ADR-0007`. */\nfunction headingId(heading: string | null): string | null {\n // Only saves the call: `exec` would read null as the word \"null\", and\n // neither that nor an empty heading holds a number.\n if (!heading) return null;\n const match = /^\\s*([A-Za-z]{1,15}[\\s._-]?\\d{1,6})\\b/.exec(heading);\n return match ? (match[1] as string) : null;\n}\n\n/**\n * Zero-padded spellings a citation might reasonably use: the number as it was\n * written, unpadded, and padded to three and to four digits.\n */\nfunction numberSpellings(number: number, written: string): string[] {\n const unpadded = String(number);\n return [...new Set([written, unpadded, unpadded.padStart(3, '0'), unpadded.padStart(4, '0')])];\n}\n\n/**\n * True when two folded spellings are one edit apart.\n *\n * One edit, not two, and a transposition counts as one: `supercedesby` for\n * `supercededby` is a slip of the finger, `categories` for `dependencies` is a\n * different word. Written out rather than as a distance matrix because the\n * answer is a yes or a no and the bound is one - the general algorithm would be\n * more code, not less.\n */\nexport function withinOneEdit(a: string, b: string): boolean {\n // The loop bounds are not boundaries: one step past the end of equal-length\n // strings compares undefined with undefined and continues, and one past the\n // end of the shorter compares nothing with the last character of the longer\n // and finds the two empty remainders equal - both the answer the loop's exit\n // gives. Nor does `<` against `<=` below matter: equal lengths never get there.\n if (a === b) return false;\n if (a.length === b.length) {\n let first = -1;\n for (let i = 0; i < a.length; i += 1) {\n if (a[i] === b[i]) continue;\n if (first === -1) {\n first = i;\n continue;\n }\n // A second difference is allowed only if the two are a swapped pair, and\n // only if there is no third.\n return first === i - 1 && a[first] === b[i] && a[i] === b[first] && a.slice(i + 1) === b.slice(i + 1);\n }\n return true;\n }\n const [short, long] = a.length < b.length ? [a, b] : [b, a];\n if (long.length - short.length !== 1) return false;\n for (let i = 0; i < short.length; i += 1) {\n if (short[i] === long[i]) continue;\n return short.slice(i) === long.slice(i + 1);\n }\n return true;\n}\n"]}
package/dist/report.d.ts CHANGED
@@ -69,9 +69,21 @@ export interface ColorEnvironment {
69
69
  */
70
70
  readonly platform?: NodeJS.Platform | undefined;
71
71
  }
72
- /** Honours `NO_COLOR`, `FORCE_COLOR` and `TERM=dumb` before falling back to TTY. */
72
+ /**
73
+ * Honours `NO_COLOR`, `FORCE_COLOR` and `TERM=dumb` before falling back to TTY.
74
+ *
75
+ * `CI` is not read. It says who started the run and nothing of what the
76
+ * stream draws: a pipeline's log that is a terminal draws colour, spec-brief
77
+ * and spec-guard colour there, and one that does not sets `NO_COLOR`.
78
+ */
73
79
  export declare function shouldUseColor(environment?: ColorEnvironment): boolean;
74
- /** True when the terminal is unlikely to render box-drawing and arrows. */
80
+ /**
81
+ * True when ASCII was asked for, or the terminal is unlikely to render
82
+ * box-drawing and arrows.
83
+ *
84
+ * `SPEC_GRAPH_ASCII` asks, and `0`, `false` and a blank do not: each is how a
85
+ * script writes "off", and every one of them used to turn ASCII on.
86
+ */
75
87
  export declare function shouldUseAscii(environment?: ColorEnvironment): boolean;
76
88
  type Paint = (text: string) => string;
77
89
  export interface Painter {
package/dist/report.js CHANGED
@@ -15,7 +15,13 @@ import { fingerprintOf } from './baseline.js';
15
15
  import { formatRef } from './source.js';
16
16
  import { DEFAULT_SEVERITIES, RULE_DESCRIPTIONS, RULE_IDS } from './rules.js';
17
17
  import { displayWidth } from './vendor/spec-core/text/index.js';
18
- /** Honours `NO_COLOR`, `FORCE_COLOR` and `TERM=dumb` before falling back to TTY. */
18
+ /**
19
+ * Honours `NO_COLOR`, `FORCE_COLOR` and `TERM=dumb` before falling back to TTY.
20
+ *
21
+ * `CI` is not read. It says who started the run and nothing of what the
22
+ * stream draws: a pipeline's log that is a terminal draws colour, spec-brief
23
+ * and spec-guard colour there, and one that does not sets `NO_COLOR`.
24
+ */
19
25
  export function shouldUseColor(environment = {}) {
20
26
  const env = environment.env ?? process.env;
21
27
  if (env['NO_COLOR'] !== undefined && env['NO_COLOR'] !== '')
@@ -28,14 +34,19 @@ export function shouldUseColor(environment = {}) {
28
34
  return true;
29
35
  if (env['TERM'] === 'dumb')
30
36
  return false;
31
- if (env['CI'] !== undefined && env['CI'] !== '')
32
- return false;
33
37
  return environment.isTTY === true;
34
38
  }
35
- /** True when the terminal is unlikely to render box-drawing and arrows. */
39
+ /**
40
+ * True when ASCII was asked for, or the terminal is unlikely to render
41
+ * box-drawing and arrows.
42
+ *
43
+ * `SPEC_GRAPH_ASCII` asks, and `0`, `false` and a blank do not: each is how a
44
+ * script writes "off", and every one of them used to turn ASCII on.
45
+ */
36
46
  export function shouldUseAscii(environment = {}) {
37
47
  const env = environment.env ?? process.env;
38
- if (env['SPEC_GRAPH_ASCII'] !== undefined && env['SPEC_GRAPH_ASCII'] !== '')
48
+ const asked = (env['SPEC_GRAPH_ASCII'] ?? '').trim().toLowerCase();
49
+ if (asked !== '' && asked !== '0' && asked !== 'false')
39
50
  return true;
40
51
  if ((environment.platform ?? process.platform) !== 'win32')
41
52
  return false;