@driftsys/markspec 0.9.0 → 0.10.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (87) hide show
  1. package/esm/compiler/mod.d.ts +7 -0
  2. package/esm/compiler/mod.d.ts.map +1 -1
  3. package/esm/compiler/mod.js +17 -3
  4. package/esm/compiler/schema.d.ts +8 -1
  5. package/esm/compiler/schema.d.ts.map +1 -1
  6. package/esm/compiler/schema.js +8 -1
  7. package/esm/formatter/dprint.d.ts +62 -0
  8. package/esm/formatter/dprint.d.ts.map +1 -0
  9. package/esm/formatter/dprint.js +83 -0
  10. package/esm/formatter/md_equiv.d.ts +24 -0
  11. package/esm/formatter/md_equiv.d.ts.map +1 -0
  12. package/esm/formatter/md_equiv.js +81 -0
  13. package/esm/formatter/mod.d.ts +25 -0
  14. package/esm/formatter/mod.d.ts.map +1 -1
  15. package/esm/formatter/mod.js +106 -6
  16. package/esm/formatter/prose.d.ts +48 -0
  17. package/esm/formatter/prose.d.ts.map +1 -0
  18. package/esm/formatter/prose.js +85 -0
  19. package/esm/mod.d.ts +8 -4
  20. package/esm/mod.d.ts.map +1 -1
  21. package/esm/mod.js +5 -2
  22. package/esm/model/mod.d.ts +19 -1
  23. package/esm/model/mod.d.ts.map +1 -1
  24. package/esm/model/profile.d.ts +34 -0
  25. package/esm/model/profile.d.ts.map +1 -1
  26. package/esm/profile/chain.js +1 -0
  27. package/esm/profile/delivered.d.ts +27 -0
  28. package/esm/profile/delivered.d.ts.map +1 -0
  29. package/esm/profile/delivered.js +60 -0
  30. package/esm/profile/manifest.d.ts +1 -0
  31. package/esm/profile/manifest.d.ts.map +1 -1
  32. package/esm/profile/manifest.js +107 -0
  33. package/esm/profile/merge.d.ts.map +1 -1
  34. package/esm/profile/merge.js +21 -0
  35. package/esm/refs/mod.d.ts.map +1 -1
  36. package/esm/refs/mod.js +22 -0
  37. package/esm/reporter/mod.js +17 -4
  38. package/esm/validator/corpus.d.ts +25 -0
  39. package/esm/validator/corpus.d.ts.map +1 -0
  40. package/esm/validator/corpus.js +138 -0
  41. package/esm/validator/mod.d.ts +2 -0
  42. package/esm/validator/mod.d.ts.map +1 -1
  43. package/esm/validator/mod.js +1 -0
  44. package/package.json +3 -1
  45. package/script/compiler/mod.d.ts +7 -0
  46. package/script/compiler/mod.d.ts.map +1 -1
  47. package/script/compiler/mod.js +16 -2
  48. package/script/compiler/schema.d.ts +8 -1
  49. package/script/compiler/schema.d.ts.map +1 -1
  50. package/script/compiler/schema.js +8 -1
  51. package/script/formatter/dprint.d.ts +62 -0
  52. package/script/formatter/dprint.d.ts.map +1 -0
  53. package/script/formatter/dprint.js +120 -0
  54. package/script/formatter/md_equiv.d.ts +24 -0
  55. package/script/formatter/md_equiv.d.ts.map +1 -0
  56. package/script/formatter/md_equiv.js +87 -0
  57. package/script/formatter/mod.d.ts +25 -0
  58. package/script/formatter/mod.d.ts.map +1 -1
  59. package/script/formatter/mod.js +106 -5
  60. package/script/formatter/prose.d.ts +48 -0
  61. package/script/formatter/prose.d.ts.map +1 -0
  62. package/script/formatter/prose.js +88 -0
  63. package/script/mod.d.ts +8 -4
  64. package/script/mod.d.ts.map +1 -1
  65. package/script/mod.js +14 -3
  66. package/script/model/mod.d.ts +19 -1
  67. package/script/model/mod.d.ts.map +1 -1
  68. package/script/model/profile.d.ts +34 -0
  69. package/script/model/profile.d.ts.map +1 -1
  70. package/script/profile/chain.js +1 -0
  71. package/script/profile/delivered.d.ts +27 -0
  72. package/script/profile/delivered.d.ts.map +1 -0
  73. package/script/profile/delivered.js +65 -0
  74. package/script/profile/manifest.d.ts +1 -0
  75. package/script/profile/manifest.d.ts.map +1 -1
  76. package/script/profile/manifest.js +108 -1
  77. package/script/profile/merge.d.ts.map +1 -1
  78. package/script/profile/merge.js +21 -0
  79. package/script/refs/mod.d.ts.map +1 -1
  80. package/script/refs/mod.js +22 -0
  81. package/script/reporter/mod.js +17 -4
  82. package/script/validator/corpus.d.ts +25 -0
  83. package/script/validator/corpus.d.ts.map +1 -0
  84. package/script/validator/corpus.js +142 -0
  85. package/script/validator/mod.d.ts +2 -0
  86. package/script/validator/mod.d.ts.map +1 -1
  87. package/script/validator/mod.js +4 -1
@@ -0,0 +1,62 @@
1
+ /**
2
+ * @module formatter/dprint
3
+ *
4
+ * Loader for the embedded dprint-markdown WASM plugin (ADR-029).
5
+ * `markspec fmt` formats whole Markdown documents with one canonical,
6
+ * zero-config style; this module owns that style and the (cached)
7
+ * WASM instantiation. Dynamic imports keep the plugin off every code
8
+ * path except formatting (`fmt`, the `check` MSL-F010 drift gate, LSP
9
+ * documentFormatting).
10
+ *
11
+ * Node-compatible: `node:fs/promises` + WebAssembly only, no `Deno.*`.
12
+ *
13
+ * Packaging note: `@dprint/formatter` and `@dprint/markdown` are dynamically
14
+ * imported bare npm specifiers, and their `plugin.wasm` ships inside the npm
15
+ * package — no vendored copy in this repo. `deno compile` only embeds the
16
+ * resolved npm tree (and thus the wasm) when the compile entry point itself
17
+ * lives inside this workspace member (`packages/markspec/`); an entry point
18
+ * outside that tree can't resolve the import map at runtime. The project's
19
+ * one real compile target (`packages/markspec/main.ts`) already satisfies
20
+ * this, so it's a non-issue in production — it only bites a from-scratch
21
+ * smoke test placed elsewhere.
22
+ */
23
+ /** Per-call options for a {@linkcode ProseFormatter}. */
24
+ export interface ProseFormatOptions {
25
+ /** Override the effective line width for this fragment. Used by the
26
+ * entry-body polish: bodies are formatted dedented and re-indented
27
+ * afterwards, so the budget must shrink by the indent width to stay
28
+ * in agreement with a whole-file dprint view of the same content. */
29
+ readonly lineWidth?: number;
30
+ }
31
+ /** Formats a Markdown fragment to the canonical MarkSpec style. */
32
+ export type ProseFormatter = (markdown: string, options?: ProseFormatOptions) => string;
33
+ /**
34
+ * The fixed MarkSpec Markdown style (ADR-029). Zero configuration by
35
+ * design — one canonical form across every project. `newLineKind` is
36
+ * "lf" because `format()` operates on a pure-LF buffer and re-applies
37
+ * the file's detected line ending on output.
38
+ */
39
+ export declare const MARKSPEC_MARKDOWN_GLOBAL_CONFIG: Readonly<{
40
+ lineWidth: number;
41
+ newLineKind: "lf";
42
+ }>;
43
+ /** Plugin-level style knobs. See ADR-029 for the rationale per value.
44
+ *
45
+ * Frozen: this is the single canonical MarkSpec style, exported through the
46
+ * public barrel. Freezing stops a consumer from mutating the shared object
47
+ * after the formatter has already baked these values in at `instantiate()`
48
+ * (which would drift the entry-body width budget from the whole-document
49
+ * formatter — see `emitBodyViaAst`). */
50
+ export declare const MARKSPEC_MARKDOWN_PLUGIN_CONFIG: Readonly<Record<string, unknown>>;
51
+ /**
52
+ * Load the dprint-markdown WASM plugin (once — subsequent calls return
53
+ * the cached instance) and return a synchronous prose formatter.
54
+ *
55
+ * A failed instantiation is NOT cached: the rejected promise is cleared
56
+ * before it propagates, so the next call retries from scratch instead of
57
+ * replaying the same failure forever. This matters for the long-lived LSP
58
+ * session, where a transient WASM-load failure must not permanently
59
+ * disable formatting for the rest of the process.
60
+ */
61
+ export declare function loadMarkdownFormatter(): Promise<ProseFormatter>;
62
+ //# sourceMappingURL=dprint.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"dprint.d.ts","sourceRoot":"","sources":["../../src/formatter/dprint.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;GAqBG;AAEH,yDAAyD;AACzD,MAAM,WAAW,kBAAkB;IACjC;;;yEAGqE;IACrE,QAAQ,CAAC,SAAS,CAAC,EAAE,MAAM,CAAC;CAC7B;AAED,mEAAmE;AACnE,MAAM,MAAM,cAAc,GAAG,CAC3B,QAAQ,EAAE,MAAM,EAChB,OAAO,CAAC,EAAE,kBAAkB,KACzB,MAAM,CAAC;AAEZ;;;;;GAKG;AACH,eAAO,MAAM,+BAA+B,EAAE,QAAQ,CAAC;IACrD,SAAS,EAAE,MAAM,CAAC;IAClB,WAAW,EAAE,IAAI,CAAC;CACnB,CAGC,CAAC;AAEH;;;;;;wCAMwC;AACxC,eAAO,MAAM,+BAA+B,EAAE,QAAQ,CACpD,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAMvB,CAAC;AAIH;;;;;;;;;GASG;AACH,wBAAgB,qBAAqB,IAAI,OAAO,CAAC,cAAc,CAAC,CAM/D"}
@@ -0,0 +1,120 @@
1
+ "use strict";
2
+ /**
3
+ * @module formatter/dprint
4
+ *
5
+ * Loader for the embedded dprint-markdown WASM plugin (ADR-029).
6
+ * `markspec fmt` formats whole Markdown documents with one canonical,
7
+ * zero-config style; this module owns that style and the (cached)
8
+ * WASM instantiation. Dynamic imports keep the plugin off every code
9
+ * path except formatting (`fmt`, the `check` MSL-F010 drift gate, LSP
10
+ * documentFormatting).
11
+ *
12
+ * Node-compatible: `node:fs/promises` + WebAssembly only, no `Deno.*`.
13
+ *
14
+ * Packaging note: `@dprint/formatter` and `@dprint/markdown` are dynamically
15
+ * imported bare npm specifiers, and their `plugin.wasm` ships inside the npm
16
+ * package — no vendored copy in this repo. `deno compile` only embeds the
17
+ * resolved npm tree (and thus the wasm) when the compile entry point itself
18
+ * lives inside this workspace member (`packages/markspec/`); an entry point
19
+ * outside that tree can't resolve the import map at runtime. The project's
20
+ * one real compile target (`packages/markspec/main.ts`) already satisfies
21
+ * this, so it's a non-issue in production — it only bites a from-scratch
22
+ * smoke test placed elsewhere.
23
+ */
24
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
25
+ if (k2 === undefined) k2 = k;
26
+ var desc = Object.getOwnPropertyDescriptor(m, k);
27
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
28
+ desc = { enumerable: true, get: function() { return m[k]; } };
29
+ }
30
+ Object.defineProperty(o, k2, desc);
31
+ }) : (function(o, m, k, k2) {
32
+ if (k2 === undefined) k2 = k;
33
+ o[k2] = m[k];
34
+ }));
35
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
36
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
37
+ }) : function(o, v) {
38
+ o["default"] = v;
39
+ });
40
+ var __importStar = (this && this.__importStar) || (function () {
41
+ var ownKeys = function(o) {
42
+ ownKeys = Object.getOwnPropertyNames || function (o) {
43
+ var ar = [];
44
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
45
+ return ar;
46
+ };
47
+ return ownKeys(o);
48
+ };
49
+ return function (mod) {
50
+ if (mod && mod.__esModule) return mod;
51
+ var result = {};
52
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
53
+ __setModuleDefault(result, mod);
54
+ return result;
55
+ };
56
+ })();
57
+ Object.defineProperty(exports, "__esModule", { value: true });
58
+ exports.MARKSPEC_MARKDOWN_PLUGIN_CONFIG = exports.MARKSPEC_MARKDOWN_GLOBAL_CONFIG = void 0;
59
+ exports.loadMarkdownFormatter = loadMarkdownFormatter;
60
+ /**
61
+ * The fixed MarkSpec Markdown style (ADR-029). Zero configuration by
62
+ * design — one canonical form across every project. `newLineKind` is
63
+ * "lf" because `format()` operates on a pure-LF buffer and re-applies
64
+ * the file's detected line ending on output.
65
+ */
66
+ exports.MARKSPEC_MARKDOWN_GLOBAL_CONFIG = Object.freeze({
67
+ lineWidth: 80,
68
+ newLineKind: "lf",
69
+ });
70
+ /** Plugin-level style knobs. See ADR-029 for the rationale per value.
71
+ *
72
+ * Frozen: this is the single canonical MarkSpec style, exported through the
73
+ * public barrel. Freezing stops a consumer from mutating the shared object
74
+ * after the formatter has already baked these values in at `instantiate()`
75
+ * (which would drift the entry-body width budget from the whole-document
76
+ * formatter — see `emitBodyViaAst`). */
77
+ exports.MARKSPEC_MARKDOWN_PLUGIN_CONFIG = Object.freeze({
78
+ textWrap: "always",
79
+ emphasisKind: "underscores",
80
+ strongKind: "asterisks",
81
+ unorderedListKind: "dashes",
82
+ });
83
+ let cached;
84
+ /**
85
+ * Load the dprint-markdown WASM plugin (once — subsequent calls return
86
+ * the cached instance) and return a synchronous prose formatter.
87
+ *
88
+ * A failed instantiation is NOT cached: the rejected promise is cleared
89
+ * before it propagates, so the next call retries from scratch instead of
90
+ * replaying the same failure forever. This matters for the long-lived LSP
91
+ * session, where a transient WASM-load failure must not permanently
92
+ * disable formatting for the rest of the process.
93
+ */
94
+ function loadMarkdownFormatter() {
95
+ cached ??= instantiate().catch((err) => {
96
+ cached = undefined;
97
+ throw err;
98
+ });
99
+ return cached;
100
+ }
101
+ async function instantiate() {
102
+ const { createFromBuffer } = await Promise.resolve().then(() => __importStar(require("@dprint/formatter")));
103
+ const { getPath } = await Promise.resolve().then(() => __importStar(require("@dprint/markdown")));
104
+ const { readFile } = await Promise.resolve().then(() => __importStar(require("node:fs/promises")));
105
+ const wasm = await readFile(getPath());
106
+ // `readFile` returns a Node `Buffer`, whose `buffer` property is typed
107
+ // `ArrayBufferLike` (may be a `SharedArrayBuffer`) — not assignable to
108
+ // `BufferSource`'s `ArrayBuffer`-backed view. Copy into a plain
109
+ // `Uint8Array` so the type is unambiguous; this runs once per process
110
+ // (the result is cached by `loadMarkdownFormatter`).
111
+ const formatter = createFromBuffer(Uint8Array.from(wasm));
112
+ formatter.setConfig(exports.MARKSPEC_MARKDOWN_GLOBAL_CONFIG, exports.MARKSPEC_MARKDOWN_PLUGIN_CONFIG);
113
+ return (markdown, options) => formatter.formatText({
114
+ filePath: "fragment.md",
115
+ fileText: markdown,
116
+ overrideConfig: options?.lineWidth !== undefined
117
+ ? { lineWidth: options.lineWidth }
118
+ : undefined,
119
+ });
120
+ }
@@ -0,0 +1,24 @@
1
+ /**
2
+ * @module formatter/md_equiv
3
+ *
4
+ * CommonMark-semantic Markdown equivalence — the gate for the ADR-029
5
+ * dprint pass. Two fragments are equivalent when they parse to the
6
+ * same mdast structure after eliding source `position`s and collapsing
7
+ * ASCII whitespace runs inside `text` node values. Only ASCII
8
+ * whitespace is collapsed — NBSP (U+00A0) and Unicode spaces are
9
+ * content, not wrap artifacts, and must not compare equal to a plain
10
+ * space. Soft-wrap positions,
11
+ * emphasis delimiter style (`*x*` vs `_x_`), table cell padding, and
12
+ * list marker style are presentation, not content — they compare
13
+ * equal. Hard breaks are `break` nodes in mdast, so wrap-collapsing
14
+ * cannot erase or fabricate one. Code (`code`, `inlineCode`), `html`,
15
+ * and definition `url`s stay byte-exact.
16
+ *
17
+ * DELIBERATELY weaker than ADR-015's `astEquivalent` (byte-verbatim on
18
+ * inline markup). Used ONLY to accept/reject dprint output; the
19
+ * ADR-015 relation still guards §5.2 body emission (MSL-F900) and must
20
+ * not be modified.
21
+ */
22
+ /** True when `a` and `b` are the same Markdown, modulo presentation. */
23
+ export declare function markdownSemanticallyEquivalent(a: string, b: string): boolean;
24
+ //# sourceMappingURL=md_equiv.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"md_equiv.d.ts","sourceRoot":"","sources":["../../src/formatter/md_equiv.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AAQH,wEAAwE;AACxE,wBAAgB,8BAA8B,CAC5C,CAAC,EAAE,MAAM,EACT,CAAC,EAAE,MAAM,GACR,OAAO,CAMT"}
@@ -0,0 +1,87 @@
1
+ "use strict";
2
+ /**
3
+ * @module formatter/md_equiv
4
+ *
5
+ * CommonMark-semantic Markdown equivalence — the gate for the ADR-029
6
+ * dprint pass. Two fragments are equivalent when they parse to the
7
+ * same mdast structure after eliding source `position`s and collapsing
8
+ * ASCII whitespace runs inside `text` node values. Only ASCII
9
+ * whitespace is collapsed — NBSP (U+00A0) and Unicode spaces are
10
+ * content, not wrap artifacts, and must not compare equal to a plain
11
+ * space. Soft-wrap positions,
12
+ * emphasis delimiter style (`*x*` vs `_x_`), table cell padding, and
13
+ * list marker style are presentation, not content — they compare
14
+ * equal. Hard breaks are `break` nodes in mdast, so wrap-collapsing
15
+ * cannot erase or fabricate one. Code (`code`, `inlineCode`), `html`,
16
+ * and definition `url`s stay byte-exact.
17
+ *
18
+ * DELIBERATELY weaker than ADR-015's `astEquivalent` (byte-verbatim on
19
+ * inline markup). Used ONLY to accept/reject dprint output; the
20
+ * ADR-015 relation still guards §5.2 body emission (MSL-F900) and must
21
+ * not be modified.
22
+ */
23
+ var __importDefault = (this && this.__importDefault) || function (mod) {
24
+ return (mod && mod.__esModule) ? mod : { "default": mod };
25
+ };
26
+ Object.defineProperty(exports, "__esModule", { value: true });
27
+ exports.markdownSemanticallyEquivalent = markdownSemanticallyEquivalent;
28
+ const unified_1 = require("unified");
29
+ const remark_parse_1 = __importDefault(require("remark-parse"));
30
+ const remark_gfm_1 = __importDefault(require("remark-gfm"));
31
+ const parser = (0, unified_1.unified)().use(remark_parse_1.default).use(remark_gfm_1.default);
32
+ /** True when `a` and `b` are the same Markdown, modulo presentation. */
33
+ function markdownSemanticallyEquivalent(a, b) {
34
+ if (a === b)
35
+ return true;
36
+ return deepEqual(normalize(parser.parse(a)), normalize(parser.parse(b)));
37
+ }
38
+ /**
39
+ * Recursively strip `position` keys and collapse ASCII whitespace runs
40
+ * in `text` node values (reflow can only introduce ASCII spaces and
41
+ * newlines; `\s` would also match NBSP and Unicode Zs spaces, letting
42
+ * a content change pass as a wrap change). Returns a plain JSON-ish
43
+ * structure for comparison; never mutates the input tree.
44
+ */
45
+ function normalize(node) {
46
+ if (Array.isArray(node))
47
+ return node.map(normalize);
48
+ if (node === null || typeof node !== "object")
49
+ return node;
50
+ const src = node;
51
+ const out = {};
52
+ for (const key of Object.keys(src).sort()) {
53
+ if (key === "position")
54
+ continue;
55
+ if (key === "value" && src.type === "text" &&
56
+ typeof src.value === "string") {
57
+ out.value = src.value.replace(/[ \t\r\n\f\v]+/g, " ");
58
+ continue;
59
+ }
60
+ out[key] = normalize(src[key]);
61
+ }
62
+ return out;
63
+ }
64
+ /** Structural deep-equality over the normalized trees. */
65
+ function deepEqual(a, b) {
66
+ if (a === b)
67
+ return true;
68
+ if (typeof a !== typeof b)
69
+ return false;
70
+ if (a === null || b === null)
71
+ return a === b;
72
+ if (Array.isArray(a) || Array.isArray(b)) {
73
+ if (!Array.isArray(a) || !Array.isArray(b))
74
+ return false;
75
+ if (a.length !== b.length)
76
+ return false;
77
+ return a.every((v, i) => deepEqual(v, b[i]));
78
+ }
79
+ if (typeof a === "object" && typeof b === "object") {
80
+ const ak = Object.keys(a);
81
+ const bk = Object.keys(b);
82
+ if (ak.length !== bk.length)
83
+ return false;
84
+ return ak.every((k) => deepEqual(a[k], b[k]));
85
+ }
86
+ return false;
87
+ }
@@ -6,6 +6,7 @@
6
6
  * and requirement block insertion.
7
7
  */
8
8
  import type { Attribute, Diagnostic } from "../model/mod.js";
9
+ import { type ProseFormatter } from "./dprint.js";
9
10
  /**
10
11
  * Decide whether the EARS keyword at `offset` in `line` is at sentence
11
12
  * start (return value true). Delegates to the shared implementation in
@@ -49,6 +50,23 @@ export interface FormatOptions {
49
50
  * Injectable for deterministic tests.
50
51
  */
51
52
  readonly today?: () => string;
53
+ /**
54
+ * Whole-document Markdown formatter (ADR-029). When supplied, prose
55
+ * segments outside entry blocks and each entry body are routed
56
+ * through it (dprint-markdown), gated by CommonMark-semantic
57
+ * equivalence. When absent, format() is entry-only — the exact
58
+ * pre-ADR-029 behaviour. The entry-body polish passes a per-call
59
+ * `lineWidth` reduced by the body indent (see `emitBodyViaAst`);
60
+ * one-arg formatter callbacks simply ignore it.
61
+ *
62
+ * The pass is Markdown-only: it runs only when {@linkcode file} has a
63
+ * Markdown extension (`.md`). A source-file (or absent) `file` disables
64
+ * it even when this callback is set — a source file's doc comment must
65
+ * never be reflowed as Markdown, and the semantic gate cannot catch
66
+ * that class of corruption. Callers that format Markdown held in memory
67
+ * must therefore pass a `.md`-suffixed `file`.
68
+ */
69
+ readonly formatMarkdownProse?: ProseFormatter;
52
70
  }
53
71
  /** Result of a format operation. */
54
72
  export interface FormatResult {
@@ -107,6 +125,13 @@ export declare function sortAttributes(attributes: Attribute[]): Attribute[];
107
125
  * 0 for entries inside source-file doc comments).
108
126
  */
109
127
  export declare function renderAttributeBlock(attributes: Attribute[], indent: number): string;
128
+ /**
129
+ * Find the 0-based line index where a list item's content ends.
130
+ * Exported for the ADR-029 prose pass (entry-extent computation).
131
+ * Scans forward from the entry start, stopping at: a sibling list item
132
+ * (`- ` at the entry's marker column), a line with less indent, or EOF.
133
+ */
134
+ export declare function findItemEnd(lines: readonly string[], startIdx: number, indent: number): number;
110
135
  /**
111
136
  * Find the 0-based line range [start, end) of the attribute block
112
137
  * for an entry starting at the given line.
@@ -1 +1 @@
1
- {"version":3,"file":"mod.d.ts","sourceRoot":"","sources":["../../src/formatter/mod.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAIH,OAAO,KAAK,EACV,SAAS,EACT,UAAU,EAGX,MAAM,iBAAiB,CAAC;AA0BzB;;;;;GAKG;AACH,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,OAAO,CAEvE;AAED;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,wBAAgB,sBAAsB,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM,CAc/D;AA0OD,sCAAsC;AACtC,MAAM,WAAW,aAAa;IAC5B,yCAAyC;IACzC,QAAQ,CAAC,IAAI,CAAC,EAAE,MAAM,CAAC;IACvB,6CAA6C;IAC7C,QAAQ,CAAC,YAAY,CAAC,EAAE,MAAM,MAAM,CAAC;IACrC;;;;OAIG;IACH,QAAQ,CAAC,KAAK,CAAC,EAAE,MAAM,MAAM,CAAC;CAC/B;AAED,oCAAoC;AACpC,MAAM,WAAW,YAAY;IAC3B,mCAAmC;IACnC,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,sEAAsE;IACtE,QAAQ,CAAC,WAAW,EAAE,SAAS,UAAU,EAAE,CAAC;IAC5C,qCAAqC;IACrC,QAAQ,CAAC,OAAO,EAAE,OAAO,CAAC;CAC3B;AA2BD;;;;;;;GAOG;AACH,wBAAgB,MAAM,CACpB,QAAQ,EAAE,MAAM,EAChB,OAAO,CAAC,EA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CA2B5C"}
@@ -14,10 +14,13 @@ exports.expandCsvValues = expandCsvValues;
14
14
  exports.canonicalizeKey = canonicalizeKey;
15
15
  exports.sortAttributes = sortAttributes;
16
16
  exports.renderAttributeBlock = renderAttributeBlock;
17
+ exports.findItemEnd = findItemEnd;
17
18
  exports.findAttributeBlockRange = findAttributeBlockRange;
19
+ const path_1 = require("@std/path");
18
20
  const ulid_1 = require("@std/ulid");
19
21
  const yaml_1 = require("@std/yaml");
20
22
  const mod_js_1 = require("../model/mod.js");
23
+ const mod_js_2 = require("../discovery/mod.js");
21
24
  const attributes_js_1 = require("../parser/attributes.js");
22
25
  const frontmatter_js_1 = require("../parser/frontmatter.js");
23
26
  const markdown_js_1 = require("../parser/markdown.js");
@@ -29,6 +32,9 @@ const build_js_1 = require("../ast/build.js");
29
32
  const render_js_1 = require("../ast/render.js");
30
33
  const normalize_js_1 = require("../ast/normalize.js");
31
34
  const equivalence_js_1 = require("../ast/equivalence.js");
35
+ const prose_js_1 = require("./prose.js");
36
+ const dprint_js_1 = require("./dprint.js");
37
+ const md_equiv_js_1 = require("./md_equiv.js");
32
38
  /**
33
39
  * Decide whether the EARS keyword at `offset` in `line` is at sentence
34
40
  * start (return value true). Delegates to the shared implementation in
@@ -185,6 +191,14 @@ const CANONICAL_ORDER = [
185
191
  * string, preserving the leading/trailing blank-line delimiters
186
192
  * that separate the body from the title and attr block.
187
193
  *
194
+ * When `proseFormat` (ADR-029) is supplied, the AST-canonical body is
195
+ * further polished by the whole-document Markdown formatter (dprint),
196
+ * gated by CommonMark-semantic equivalence — NOT the strict ADR-015
197
+ * relation above, which is byte-verbatim on inline markup and would
198
+ * reject every legitimate re-wrap. A rejected polish keeps the
199
+ * AST-canonical body and raises an info diagnostic (MSL-F012) naming
200
+ * the entry.
201
+ *
188
202
  * Returns `true` when any entry body was rewritten (so `format()` can
189
203
  * keep `changed` accurate for `--check` mode); `false` when every body
190
204
  * was already §5.2-canonical.
@@ -193,7 +207,7 @@ const CANONICAL_ORDER = [
193
207
  * `normalizeBodyAst` is FORMATTER-ONLY — the validate/parse path must
194
208
  * never call it.
195
209
  */
196
- function emitBodyViaAst(lines, file, diagnostics, cachedEntries) {
210
+ function emitBodyViaAst(lines, file, diagnostics, cachedEntries, proseFormat) {
197
211
  // When the caller supplies pre-parsed entries whose line numbers are still
198
212
  // valid in `lines` (i.e., no line-count-changing operations occurred before
199
213
  // this call), skip the re-parse entirely — the common hot path for files
@@ -256,6 +270,52 @@ function emitBodyViaAst(lines, file, diagnostics, cachedEntries) {
256
270
  });
257
271
  continue;
258
272
  }
273
+ // ADR-029: polish the canonical body with the whole-document
274
+ // Markdown formatter. Gated by CommonMark-semantic equivalence —
275
+ // NOT the strict ADR-015 relation, which is byte-verbatim on
276
+ // inline markup and would reject every legitimate re-wrap. On
277
+ // rejection keep the AST-canonical body and say so (info).
278
+ let finalBody = emittedBody;
279
+ if (proseFormat !== undefined) {
280
+ // The body is formatted DEDENTED and re-indented afterwards, so the
281
+ // width budget must shrink by the indent — otherwise a wrap point
282
+ // landing near 80 columns dedented exceeds 80 re-indented, and an
283
+ // external whole-file dprint view (which sees the indent) re-wraps
284
+ // it: a formatter ping-pong. Floor of 20 keeps a pathological indent
285
+ // from degenerating into one-word-per-line output.
286
+ let polished;
287
+ try {
288
+ polished = proseFormat(emittedBody, {
289
+ lineWidth: Math.max(20, dprint_js_1.MARKSPEC_MARKDOWN_GLOBAL_CONFIG.lineWidth - indent),
290
+ }).replace(/\n$/, "");
291
+ }
292
+ catch {
293
+ // The dprint WASM formatter can throw on a pathological body.
294
+ // Treat a throw exactly like a rejected rewrite: keep the
295
+ // canonical body and report the fallback (never crash the run).
296
+ diagnostics.push({
297
+ code: "MSL-F012",
298
+ severity: "info",
299
+ message: `${entry.displayId}: Markdown pass errored — kept ` +
300
+ `the canonical body`,
301
+ location: entry.location,
302
+ });
303
+ }
304
+ if (polished !== undefined && polished !== emittedBody) {
305
+ if ((0, md_equiv_js_1.markdownSemanticallyEquivalent)(emittedBody, polished)) {
306
+ finalBody = polished;
307
+ }
308
+ else {
309
+ diagnostics.push({
310
+ code: "MSL-F012",
311
+ severity: "info",
312
+ message: `${entry.displayId}: Markdown pass produced a ` +
313
+ `non-equivalent body — kept the canonical body`,
314
+ location: entry.location,
315
+ });
316
+ }
317
+ }
318
+ }
259
319
  // The emitted body is the §5.2-canonical body and re-builds
260
320
  // AST-equivalent to the canonical AST. Splice it back into the
261
321
  // document — the AST is the load-bearing emission path.
@@ -274,7 +334,7 @@ function emitBodyViaAst(lines, file, diagnostics, cachedEntries) {
274
334
  while (ei >= si && rawSegment[ei].trim() === "") {
275
335
  trailBlanks.unshift(rawSegment[ei--]);
276
336
  }
277
- const emittedLines = emittedBody.split("\n").map((l) => l ? `${indentStr}${l}` : l);
337
+ const emittedLines = finalBody.split("\n").map((l) => l ? `${indentStr}${l}` : l);
278
338
  const newSegment = [...leadBlanks, ...emittedLines, ...trailBlanks];
279
339
  // `changed` accuracy: only flag a body rewrite when the spliced
280
340
  // segment actually differs from the original lines (a §5.2-canonical
@@ -340,7 +400,16 @@ function format(markdown, options) {
340
400
  const body = rawBody;
341
401
  const { entries } = (0, markdown_js_1.parseMarkdown)(body, { file });
342
402
  const diagnostics = [...fm.diagnostics];
343
- if (entries.length === 0 && !fm.hadFrontMatter) {
403
+ // ADR-029: the whole-document Markdown pass is Markdown-only. Gate on the
404
+ // file extension HERE so the invariant has one home — a caller that wires
405
+ // formatMarkdownProse without its own guard (e.g. a future write tool, or
406
+ // formatSource forwarding options with a source-file label) cannot silently
407
+ // reflow a source file's doc comment as Markdown. The CommonMark-semantic
408
+ // gate cannot catch that class, so it must be prevented, not detected. The
409
+ // CLI/LSP call-site guards remain as defense-in-depth.
410
+ const isMarkdownFile = mod_js_2.MARKDOWN_EXTENSIONS.has((0, path_1.extname)(file).toLowerCase());
411
+ const proseFormat = isMarkdownFile ? options?.formatMarkdownProse : undefined;
412
+ if (entries.length === 0 && !fm.hadFrontMatter && proseFormat === undefined) {
344
413
  // No entries and no front matter — nothing to format. Returning the
345
414
  // original `markdown` preserves the source's exact byte sequence,
346
415
  // including its line-ending convention.
@@ -461,9 +530,40 @@ function format(markdown, options) {
461
530
  // emitBodyViaAst skips its re-parse (the hot path for already-formatted
462
531
  // files). When `changed` is true, any splicing or collapse may have
463
532
  // shifted positions, so pass undefined to trigger the normal re-parse.
464
- if (emitBodyViaAst(collapsedLines, file, diagnostics, changed ? undefined : entries))
533
+ if (emitBodyViaAst(collapsedLines, file, diagnostics, changed ? undefined : entries, proseFormat))
465
534
  changed = true;
466
- const formattedBody = collapsedLines.join("\n");
535
+ // ADR-029 whole-document Markdown pass: prose segments outside entry
536
+ // blocks through dprint, gated per segment. Entry bodies were already
537
+ // polished inside emitBodyViaAst. Re-parse for fresh extents when any
538
+ // earlier pass changed line positions.
539
+ let proseLines = collapsedLines;
540
+ if (proseFormat !== undefined) {
541
+ const proseEntries = changed
542
+ ? (0, markdown_js_1.parseMarkdown)(collapsedLines.join("\n"), { file }).entries
543
+ : entries;
544
+ const extents = proseEntries.map((e) => {
545
+ const start = e.location.line - 1;
546
+ const entryIndent = (e.location.column - 1) + 2;
547
+ return { start, end: findItemEnd(collapsedLines, start, entryIndent) };
548
+ });
549
+ const prose = (0, prose_js_1.formatProseSegments)(collapsedLines, extents, proseFormat);
550
+ if (prose.changed)
551
+ changed = true;
552
+ for (const fallback of prose.fallbacks) {
553
+ const cause = fallback.reason === "error"
554
+ ? "errored"
555
+ : "produced non-equivalent output";
556
+ diagnostics.push({
557
+ code: "MSL-F012",
558
+ severity: "info",
559
+ message: `Markdown pass ${cause} for this prose segment — kept ` +
560
+ `the original text`,
561
+ location: { file, line: fallback.line + 1, column: 1 },
562
+ });
563
+ }
564
+ proseLines = prose.lines;
565
+ }
566
+ const formattedBody = proseLines.join("\n");
467
567
  if (fm.hadFrontMatter) {
468
568
  const canonicalFm = renderFrontMatter(fm.attributes);
469
569
  const outputLf = canonicalFm + formattedBody;
@@ -626,6 +726,7 @@ function renderAttributeBlock(attributes, indent) {
626
726
  }
627
727
  /**
628
728
  * Find the 0-based line index where a list item's content ends.
729
+ * Exported for the ADR-029 prose pass (entry-extent computation).
629
730
  * Scans forward from the entry start, stopping at: a sibling list item
630
731
  * (`- ` at the entry's marker column), a line with less indent, or EOF.
631
732
  */
@@ -0,0 +1,48 @@
1
+ /**
2
+ * @module formatter/prose
3
+ *
4
+ * ADR-029 whole-document Markdown pass: splits a document's lines into
5
+ * prose / entry-block segments and routes each prose segment through
6
+ * the injected {@linkcode ProseFormatter} (dprint-markdown). Every
7
+ * rewritten segment must pass {@linkcode markdownSemanticallyEquivalent}
8
+ * against its original — a rejected segment is kept byte-identical and
9
+ * reported via `fallbacks` (with its reason) so `format()` can emit an
10
+ * advisory diagnostic ("never make a file worse").
11
+ *
12
+ * Entry blocks (title line → item end, trailers included) are never
13
+ * given to dprint here; entry BODIES are polished separately inside
14
+ * `emitBodyViaAst` (core/formatter/mod.ts) where the parser's
15
+ * dedent/re-indent machinery and the body-AST gate already live.
16
+ */
17
+ import type { ProseFormatter } from "./dprint.js";
18
+ /** 0-based `[start, end)` line span of one entry block. */
19
+ export interface EntryExtent {
20
+ readonly start: number;
21
+ readonly end: number;
22
+ }
23
+ /**
24
+ * Why a prose segment kept its original text instead of the formatted
25
+ * output: the dprint formatter threw (`"error"`), or its output failed the
26
+ * CommonMark-semantic gate (`"non-equivalent"`). Threaded so `format()`
27
+ * can emit an accurate MSL-F012 cause per segment rather than collapsing
28
+ * both into one message.
29
+ */
30
+ export interface ProseFallback {
31
+ readonly line: number;
32
+ readonly reason: "error" | "non-equivalent";
33
+ }
34
+ /** Result of {@linkcode formatProseSegments}. */
35
+ export interface ProsePassResult {
36
+ readonly lines: string[];
37
+ readonly changed: boolean;
38
+ /** One entry per prose segment that fell back to its original text,
39
+ * with the 0-based first line and the reason. */
40
+ readonly fallbacks: readonly ProseFallback[];
41
+ }
42
+ /**
43
+ * Format every prose gap between entry extents. Boundary blank lines
44
+ * stay outside the formatted chunk so entry-block separation is never
45
+ * disturbed.
46
+ */
47
+ export declare function formatProseSegments(lines: readonly string[], entryExtents: readonly EntryExtent[], proseFormat: ProseFormatter): ProsePassResult;
48
+ //# sourceMappingURL=prose.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"prose.d.ts","sourceRoot":"","sources":["../../src/formatter/prose.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AAEH,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAGlD,2DAA2D;AAC3D,MAAM,WAAW,WAAW;IAC1B,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC;CACtB;AAED;;;;;;GAMG;AACH,MAAM,WAAW,aAAa;IAC5B,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,MAAM,EAAE,OAAO,GAAG,gBAAgB,CAAC;CAC7C;AAED,iDAAiD;AACjD,MAAM,WAAW,eAAe;IAC9B,QAAQ,CAAC,KAAK,EAAE,MAAM,EAAE,CAAC;IACzB,QAAQ,CAAC,OAAO,EAAE,OAAO,CAAC;IAC1B;qDACiD;IACjD,QAAQ,CAAC,SAAS,EAAE,SAAS,aAAa,EAAE,CAAC;CAC9C;AAED;;;;GAIG;AACH,wBAAgB,mBAAmB,CACjC,KAAK,EAAE,SAAS,MAAM,EAAE,EACxB,YAAY,EAAE,SAAS,WAAW,EAAE,EACpC,WAAW,EAAE,cAAc,GAC1B,eAAe,CA4DjB"}