@driftsys/markspec 0.11.0 → 0.12.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.
Files changed (142) hide show
  1. package/README.md +9 -0
  2. package/esm/ast/normalize.d.ts +4 -5
  3. package/esm/ast/normalize.d.ts.map +1 -1
  4. package/esm/ast/normalize.js +6 -37
  5. package/esm/collect/mod.d.ts +29 -9
  6. package/esm/collect/mod.d.ts.map +1 -1
  7. package/esm/collect/mod.js +36 -10
  8. package/esm/compiler/mod.d.ts.map +1 -1
  9. package/esm/compiler/mod.js +2 -6
  10. package/esm/config/markspec.d.ts +4 -2
  11. package/esm/config/markspec.d.ts.map +1 -1
  12. package/esm/discovery/mod.d.ts +24 -8
  13. package/esm/discovery/mod.d.ts.map +1 -1
  14. package/esm/discovery/mod.js +57 -21
  15. package/esm/discovery/projects.d.ts +109 -0
  16. package/esm/discovery/projects.d.ts.map +1 -0
  17. package/esm/discovery/projects.js +232 -0
  18. package/esm/formatter/entry_body.d.ts +86 -0
  19. package/esm/formatter/entry_body.d.ts.map +1 -0
  20. package/esm/formatter/entry_body.js +287 -0
  21. package/esm/formatter/mod.d.ts +13 -9
  22. package/esm/formatter/mod.d.ts.map +1 -1
  23. package/esm/formatter/mod.js +126 -50
  24. package/esm/gates/mod.d.ts.map +1 -1
  25. package/esm/gates/mod.js +5 -4
  26. package/esm/lint/runner.d.ts.map +1 -1
  27. package/esm/lint/runner.js +4 -4
  28. package/esm/lock/check.d.ts.map +1 -1
  29. package/esm/lock/check.js +2 -1
  30. package/esm/lock/edge_drift.d.ts +2 -0
  31. package/esm/lock/edge_drift.d.ts.map +1 -1
  32. package/esm/lock/edge_drift.js +4 -0
  33. package/esm/lock/mod.d.ts +1 -1
  34. package/esm/lock/mod.d.ts.map +1 -1
  35. package/esm/lock/mod.js +1 -1
  36. package/esm/mod.d.ts +10 -6
  37. package/esm/mod.d.ts.map +1 -1
  38. package/esm/mod.js +8 -6
  39. package/esm/model/mod.d.ts +21 -0
  40. package/esm/model/mod.d.ts.map +1 -1
  41. package/esm/model/mod.js +10 -0
  42. package/esm/parser/code_regions.d.ts +29 -0
  43. package/esm/parser/code_regions.d.ts.map +1 -0
  44. package/esm/parser/code_regions.js +38 -0
  45. package/esm/parser/markdown.d.ts.map +1 -1
  46. package/esm/parser/markdown.js +103 -40
  47. package/esm/parser/mod.d.ts.map +1 -1
  48. package/esm/parser/mod.js +7 -1
  49. package/esm/parser/translate.d.ts.map +1 -1
  50. package/esm/parser/translate.js +5 -0
  51. package/esm/refs/mod.d.ts.map +1 -1
  52. package/esm/refs/mod.js +8 -19
  53. package/esm/reporter/mod.d.ts.map +1 -1
  54. package/esm/reporter/mod.js +2 -2
  55. package/esm/util/fence.d.ts +20 -29
  56. package/esm/util/fence.d.ts.map +1 -1
  57. package/esm/util/fence.js +42 -50
  58. package/esm/util/modals.d.ts +6 -0
  59. package/esm/util/modals.d.ts.map +1 -1
  60. package/esm/util/modals.js +37 -0
  61. package/esm/validator/body_blocks.d.ts +2 -1
  62. package/esm/validator/body_blocks.d.ts.map +1 -1
  63. package/esm/validator/body_blocks.js +80 -2
  64. package/esm/validator/corpus.d.ts +6 -0
  65. package/esm/validator/corpus.d.ts.map +1 -1
  66. package/esm/validator/corpus.js +16 -4
  67. package/esm/validator/mod.d.ts +1 -1
  68. package/esm/validator/mod.d.ts.map +1 -1
  69. package/esm/validator/mod.js +1 -1
  70. package/esm/validator/pipeline.d.ts.map +1 -1
  71. package/esm/validator/pipeline.js +11 -8
  72. package/package.json +1 -1
  73. package/script/ast/normalize.d.ts +4 -5
  74. package/script/ast/normalize.d.ts.map +1 -1
  75. package/script/ast/normalize.js +5 -36
  76. package/script/collect/mod.d.ts +29 -9
  77. package/script/collect/mod.d.ts.map +1 -1
  78. package/script/collect/mod.js +38 -10
  79. package/script/compiler/mod.d.ts.map +1 -1
  80. package/script/compiler/mod.js +1 -5
  81. package/script/config/markspec.d.ts +4 -2
  82. package/script/config/markspec.d.ts.map +1 -1
  83. package/script/discovery/mod.d.ts +24 -8
  84. package/script/discovery/mod.d.ts.map +1 -1
  85. package/script/discovery/mod.js +56 -20
  86. package/script/discovery/projects.d.ts +109 -0
  87. package/script/discovery/projects.d.ts.map +1 -0
  88. package/script/discovery/projects.js +240 -0
  89. package/script/formatter/entry_body.d.ts +86 -0
  90. package/script/formatter/entry_body.d.ts.map +1 -0
  91. package/script/formatter/entry_body.js +292 -0
  92. package/script/formatter/mod.d.ts +13 -9
  93. package/script/formatter/mod.d.ts.map +1 -1
  94. package/script/formatter/mod.js +124 -48
  95. package/script/gates/mod.d.ts.map +1 -1
  96. package/script/gates/mod.js +15 -14
  97. package/script/lint/runner.d.ts.map +1 -1
  98. package/script/lint/runner.js +3 -3
  99. package/script/lock/check.d.ts.map +1 -1
  100. package/script/lock/check.js +2 -1
  101. package/script/lock/edge_drift.d.ts +2 -0
  102. package/script/lock/edge_drift.d.ts.map +1 -1
  103. package/script/lock/edge_drift.js +5 -0
  104. package/script/lock/mod.d.ts +1 -1
  105. package/script/lock/mod.d.ts.map +1 -1
  106. package/script/lock/mod.js +2 -1
  107. package/script/mod.d.ts +10 -6
  108. package/script/mod.d.ts.map +1 -1
  109. package/script/mod.js +20 -5
  110. package/script/model/mod.d.ts +21 -0
  111. package/script/model/mod.d.ts.map +1 -1
  112. package/script/model/mod.js +11 -0
  113. package/script/parser/code_regions.d.ts +29 -0
  114. package/script/parser/code_regions.d.ts.map +1 -0
  115. package/script/parser/code_regions.js +41 -0
  116. package/script/parser/markdown.d.ts.map +1 -1
  117. package/script/parser/markdown.js +102 -39
  118. package/script/parser/mod.d.ts.map +1 -1
  119. package/script/parser/mod.js +7 -1
  120. package/script/parser/translate.d.ts.map +1 -1
  121. package/script/parser/translate.js +5 -0
  122. package/script/refs/mod.d.ts.map +1 -1
  123. package/script/refs/mod.js +7 -18
  124. package/script/reporter/mod.d.ts.map +1 -1
  125. package/script/reporter/mod.js +1 -1
  126. package/script/util/fence.d.ts +20 -29
  127. package/script/util/fence.d.ts.map +1 -1
  128. package/script/util/fence.js +47 -54
  129. package/script/util/modals.d.ts +6 -0
  130. package/script/util/modals.d.ts.map +1 -1
  131. package/script/util/modals.js +38 -0
  132. package/script/validator/body_blocks.d.ts +2 -1
  133. package/script/validator/body_blocks.d.ts.map +1 -1
  134. package/script/validator/body_blocks.js +80 -2
  135. package/script/validator/corpus.d.ts +6 -0
  136. package/script/validator/corpus.d.ts.map +1 -1
  137. package/script/validator/corpus.js +16 -3
  138. package/script/validator/mod.d.ts +1 -1
  139. package/script/validator/mod.d.ts.map +1 -1
  140. package/script/validator/mod.js +2 -1
  141. package/script/validator/pipeline.d.ts.map +1 -1
  142. package/script/validator/pipeline.js +11 -8
@@ -0,0 +1,240 @@
1
+ "use strict";
2
+ /**
3
+ * @module core/discovery/projects
4
+ *
5
+ * Project-root discovery shared by the CLI, the LSP and the MCP server.
6
+ *
7
+ * A "project root" is a directory that holds a `project.yaml` or a
8
+ * `.markspec.yaml`. {@linkcode discoverProjectRoots} finds the primary
9
+ * root by walking up from a start folder, then every nested root below
10
+ * it with the gitignore-aware file walk.
11
+ */
12
+ Object.defineProperty(exports, "__esModule", { value: true });
13
+ exports.isWithin = isWithin;
14
+ exports.nearestRoot = nearestRoot;
15
+ exports.resolveConfigRoot = resolveConfigRoot;
16
+ exports.findNestedProjectRoots = findNestedProjectRoots;
17
+ exports.discoverProjectRoots = discoverProjectRoots;
18
+ exports.createProjectRootResolver = createProjectRootResolver;
19
+ const path_1 = require("@std/path");
20
+ const mod_js_1 = require("../config/mod.js");
21
+ const markspec_js_1 = require("../config/markspec.js");
22
+ const mod_js_2 = require("./mod.js");
23
+ const gitignore_js_1 = require("./gitignore.js");
24
+ /** The file names whose directory can be a project root. */
25
+ const CONFIG_BASENAMES = new Set([
26
+ "project.yaml",
27
+ ".markspec.yaml",
28
+ ]);
29
+ /** `true` when `path` is `root` itself or lies below it. */
30
+ function isWithin(root, path) {
31
+ const rel = (0, path_1.relative)(root, path);
32
+ // A child directory may itself start with `..` (e.g. `..cache`), so
33
+ // compare whole path segments, not a string prefix.
34
+ return rel === "" ||
35
+ (rel !== ".." && !rel.startsWith(`..${path_1.SEPARATOR}`) && !(0, path_1.isAbsolute)(rel));
36
+ }
37
+ /**
38
+ * Return the deepest root in `roots` that is `dir` itself or an ancestor
39
+ * of `dir`, or `undefined` when none is.
40
+ */
41
+ function nearestRoot(dir, roots) {
42
+ let best;
43
+ for (const root of roots) {
44
+ if (!isWithin(root, dir))
45
+ continue;
46
+ if (best === undefined || root.length > best.length)
47
+ best = root;
48
+ }
49
+ return best;
50
+ }
51
+ /**
52
+ * Walk up from `startDir` to the nearest `project.yaml`, else the nearest
53
+ * `.markspec.yaml`. Returns `undefined` when neither exists.
54
+ *
55
+ * The LSP server and the MCP server use this order to find the root
56
+ * above their workspace. The CLI (`check`, `fmt`, `lint`) uses
57
+ * {@linkcode createProjectRootResolver}, which starts from this nearest
58
+ * config root but skips a config that an enclosing project hides (#845).
59
+ */
60
+ async function resolveConfigRoot(startDir, readFile) {
61
+ return await (0, mod_js_1.discoverProjectRoot)(startDir, readFile) ??
62
+ await (0, markspec_js_1.discoverMarkspecRoot)(startDir, readFile);
63
+ }
64
+ /**
65
+ * Directories strictly below `root` that a document walk-up would
66
+ * resolve to, found with the gitignore-aware project walk (honouring
67
+ * `exclude`). Each discovered `project.yaml` or `.markspec.yaml` is
68
+ * resolved with {@linkcode resolveConfigRoot} from its own directory, so a
69
+ * `.markspec.yaml` below a `project.yaml` is not a root of its own — the
70
+ * same answer the CLI gives for a file there. A found root is dropped when
71
+ * the `.markspec.yaml` `exclude:` list of another found root above it
72
+ * covers it: each project's exclude list applies to its own subtree, with
73
+ * patterns relative to that project. The result is sorted.
74
+ */
75
+ async function findNestedProjectRoots(root, io, exclude) {
76
+ const out = new Set();
77
+ for await (const path of (0, mod_js_2.discoverFiles)(root, io, {
78
+ extensions: new Set([".yaml"]),
79
+ exclude,
80
+ })) {
81
+ if (!CONFIG_BASENAMES.has((0, path_1.basename)(path)))
82
+ continue;
83
+ const dir = (0, path_1.dirname)(path);
84
+ if (dir === root)
85
+ continue;
86
+ const found = await resolveConfigRoot(dir, io.readFile);
87
+ if (found !== undefined && found !== root && isWithin(root, found)) {
88
+ out.add(found);
89
+ }
90
+ }
91
+ const nested = [...out];
92
+ const excludeRules = new Map();
93
+ const kept = [];
94
+ for (const candidate of nested) {
95
+ let covered = false;
96
+ for (const ancestor of nested) {
97
+ if (ancestor === candidate || !isWithin(ancestor, candidate))
98
+ continue;
99
+ let rules = excludeRules.get(ancestor);
100
+ if (rules === undefined) {
101
+ const { config } = await (0, markspec_js_1.loadToolConfig)(ancestor, io.readFile);
102
+ rules = (0, gitignore_js_1.parseGitignore)(config.exclude.join("\n"), "");
103
+ excludeRules.set(ancestor, rules);
104
+ }
105
+ if (isExcludedDir((0, path_1.relative)(ancestor, candidate), rules)) {
106
+ covered = true;
107
+ break;
108
+ }
109
+ }
110
+ if (!covered)
111
+ kept.push(candidate);
112
+ }
113
+ return kept.sort();
114
+ }
115
+ /** `true` when the directory at `rel` (relative, host separators), or any
116
+ * directory above it, matches `rules` — the same pruning the walk does. */
117
+ function isExcludedDir(rel, rules) {
118
+ if (rules.length === 0)
119
+ return false;
120
+ const segments = rel.split(path_1.SEPARATOR);
121
+ for (let i = 1; i <= segments.length; i++) {
122
+ if ((0, gitignore_js_1.isIgnored)(segments.slice(0, i).join("/"), true, rules))
123
+ return true;
124
+ }
125
+ return false;
126
+ }
127
+ /**
128
+ * Find every MarkSpec project reachable from `startDir`.
129
+ *
130
+ * `primaryRoot` is the nearest config root found by walking up from
131
+ * `startDir` (see {@linkcode resolveConfigRoot}), or `startDir` itself
132
+ * when there is none. `roots` holds the primary root (only when it has a
133
+ * config) plus every nested root below it, sorted. The nested scan honours
134
+ * the primary project's `.markspec.yaml` `exclude:` list, and each nested
135
+ * project's own list for the folders below it.
136
+ *
137
+ * When the primary root is a filesystem root or `options.homeDir`, no
138
+ * downward scan runs, even when that folder holds a config: `roots` then
139
+ * holds only the primary root when it has a config, and is empty
140
+ * otherwise.
141
+ */
142
+ async function discoverProjectRoots(startDir, io, options = {}) {
143
+ const configRoot = await resolveConfigRoot(startDir, io.readFile);
144
+ const primaryRoot = configRoot ?? startDir;
145
+ const isFilesystemRoot = (0, path_1.dirname)(primaryRoot) === primaryRoot;
146
+ if (isFilesystemRoot || primaryRoot === options.homeDir) {
147
+ return {
148
+ primaryRoot,
149
+ roots: configRoot !== undefined ? [primaryRoot] : [],
150
+ };
151
+ }
152
+ const { config } = configRoot !== undefined
153
+ ? await (0, markspec_js_1.loadToolConfig)(primaryRoot, io.readFile)
154
+ : { config: undefined };
155
+ const nested = await findNestedProjectRoots(primaryRoot, io, config?.exclude);
156
+ const roots = configRoot !== undefined ? [primaryRoot, ...nested] : nested;
157
+ return { primaryRoot, roots: roots.sort() };
158
+ }
159
+ /**
160
+ * Create a resolver that gives, for any folder, the project root the LSP
161
+ * would give a document in that folder when the editor workspace is the
162
+ * outermost project root above it (#845).
163
+ *
164
+ * The nearest config root {@linkcode resolveConfigRoot} finds is not
165
+ * always the owner: when an enclosing project hides that config (an
166
+ * `exclude:` entry, a `.gitignore` entry, a hidden folder), the LSP and
167
+ * the MCP server never treat it as a root, and its files belong to the
168
+ * enclosing project. So the resolver walks up from the nearest config
169
+ * root to the outermost enclosing one, finds the nested roots below that
170
+ * outermost root the way the LSP does, and returns the deepest of them
171
+ * that contains `dir`.
172
+ *
173
+ * The walk up stops before a filesystem root and before
174
+ * `options.homeDir`: {@linkcode discoverProjectRoots} never scans down
175
+ * from those folders, so a stray config there must not claim every
176
+ * project below it. Results are cached per folder.
177
+ */
178
+ function createProjectRootResolver(io, options = {}) {
179
+ const owners = new Map();
180
+ const outermosts = new Map();
181
+ const nested = new Map();
182
+ function nestedRoots(root) {
183
+ let found = nested.get(root);
184
+ if (found === undefined) {
185
+ found = (0, markspec_js_1.loadToolConfig)(root, io.readFile).then(({ config }) => findNestedProjectRoots(root, io, config.exclude));
186
+ nested.set(root, found);
187
+ }
188
+ return found;
189
+ }
190
+ function outermostOf(dir) {
191
+ let found = outermosts.get(dir);
192
+ if (found === undefined) {
193
+ found = resolveOutermost(dir);
194
+ outermosts.set(dir, found);
195
+ }
196
+ return found;
197
+ }
198
+ async function resolveOutermost(dir) {
199
+ const nearest = await resolveConfigRoot(dir, io.readFile);
200
+ return nearest === undefined ? undefined : await outermostFrom(nearest);
201
+ }
202
+ /** Walk up from the config root `nearest` to the outermost one. */
203
+ async function outermostFrom(nearest) {
204
+ let outermost = nearest;
205
+ while (true) {
206
+ const parent = (0, path_1.dirname)(outermost);
207
+ if (parent === outermost)
208
+ break;
209
+ const above = await resolveConfigRoot(parent, io.readFile);
210
+ if (above === undefined || (0, path_1.dirname)(above) === above ||
211
+ above === options.homeDir) {
212
+ break;
213
+ }
214
+ outermost = above;
215
+ }
216
+ return outermost;
217
+ }
218
+ async function resolveOwner(dir) {
219
+ const nearest = await resolveConfigRoot(dir, io.readFile);
220
+ if (nearest === undefined)
221
+ return undefined;
222
+ const outermost = await outermostFrom(nearest);
223
+ if (outermost === nearest)
224
+ return nearest;
225
+ const roots = [outermost, ...await nestedRoots(outermost)];
226
+ return nearestRoot(dir, roots) ?? outermost;
227
+ }
228
+ return {
229
+ ownerOf(dir) {
230
+ let owner = owners.get(dir);
231
+ if (owner === undefined) {
232
+ owner = resolveOwner(dir);
233
+ owners.set(dir, owner);
234
+ }
235
+ return owner;
236
+ },
237
+ nestedRoots,
238
+ outermostOf,
239
+ };
240
+ }
@@ -0,0 +1,86 @@
1
+ /**
2
+ * @module formatter/entry_body
3
+ *
4
+ * Read and replace the body of one entry in a Markdown file text.
5
+ *
6
+ * Splice-only contract: {@linkcode replaceEntryBody} changes only the
7
+ * lines of the target entry's body. Every other line of the file (other
8
+ * entries, prose, front matter, the title, the trailer block, and each
9
+ * line's own line ending) stays byte-for-byte unchanged. After the splice
10
+ * the text is parsed again; when the set of entries differs (a new entry,
11
+ * a lost entry, a changed title or trailer) or the target's body is not
12
+ * the proposal, the edit is refused.
13
+ *
14
+ * The body range starts after the title paragraph (up to the first blank
15
+ * line after the title line, so a soft-wrapped title is skipped) and the
16
+ * blank lines after it. It has as many lines as the parser's
17
+ * `entry.body`, so lazy continuation lines are included, and it must
18
+ * match that body line for line. The body indent is the content column of
19
+ * the list item: the marker column, plus the marker width, plus the spaces
20
+ * after the marker. Lines are split on `\r\n`, a
21
+ * lone `\r`, or `\n`, as in the parser.
22
+ *
23
+ * Pure: no I/O, Node-compatible.
24
+ */
25
+ /** Why {@linkcode replaceEntryBody} refused an edit. */
26
+ export type EntryBodyRefusal = "entry-not-found" | "body-empty" | "proposal-empty" | "trailer-invalid" | "entries-changed";
27
+ /** Result of {@linkcode replaceEntryBody}. */
28
+ export type EntryBodyEdit = {
29
+ readonly ok: true;
30
+ readonly text: string;
31
+ } | {
32
+ readonly ok: false;
33
+ readonly refusal: EntryBodyRefusal;
34
+ };
35
+ /**
36
+ * 0-based content column of the list item whose marker starts at `marker`
37
+ * on `line`: the marker column, plus 1 for the bullet, plus the spaces
38
+ * after it. So `- [ID]` gives the marker column plus 2 and `- [ID]` gives
39
+ * the marker column plus 4. Only a bullet followed by one to four spaces
40
+ * can start an entry: ordered lists never hold entries, and five or more
41
+ * spaces make the title an indented code block. When the line does not
42
+ * start with a bullet and a space at `marker`, the marker column plus 2 is
43
+ * used as a fallback.
44
+ */
45
+ export declare function contentColumn(line: string, marker: number): number;
46
+ /**
47
+ * Body of the entry `displayId` as written in `text`: dedented, LF line
48
+ * endings, no surrounding blank lines. Returns `""` when the entry has no
49
+ * body and `undefined` when no entry has `displayId`. `file` names a
50
+ * `.md` file. When the body lines cannot be located exactly in `text`,
51
+ * the parser's body is returned (and {@linkcode replaceEntryBody}
52
+ * refuses to edit that entry).
53
+ */
54
+ export declare function readEntryBody(text: string, file: string, displayId: string): Promise<string | undefined>;
55
+ /**
56
+ * Return `text` with the body of entry `displayId` replaced by `body`,
57
+ * re-indented to the body indent. Every other line stays byte-for-byte
58
+ * unchanged. Inserted lines take the line ending of the title line. In
59
+ * `body`, `\r\n` and a lone `\r` count as line breaks.
60
+ *
61
+ * Refusals: `entry-not-found` (no such entry), `trailer-invalid` (the
62
+ * entry's trailer block did not parse, see below), `body-empty` (the entry
63
+ * has no body), `proposal-empty` (`body` is blank), `entries-changed`
64
+ * (two entries in `text` have `displayId`; or the body lines cannot be
65
+ * located exactly in `text`; or the edited
66
+ * text no longer parses to the same entries, with the same title and
67
+ * trailer for the target, and with the proposal as the target's body;
68
+ * or the parse raises more structural diagnostics of some code, such as
69
+ * MSL-P020, than the original text).
70
+ *
71
+ * `trailer-invalid`: when a trailer line is malformed (for example an
72
+ * empty `Labels:`, a key without a colon, or a lowercase key), the parser
73
+ * reads the whole trailer block, the `Id:` line included, as body. A
74
+ * splice would then delete the `Id:` and trailer lines, and the identity
75
+ * check cannot see it, because the entry has no `id` and no attributes
76
+ * before or after the edit. So the edit is refused when an `MSL-P020`,
77
+ * `MSL-P021` or `MSL-P022` names the entry (the message starts with
78
+ * `<displayId>:`). This is broader than that case: `MSL-P020` also fires
79
+ * when a body paragraph starts with a recognized trailer key, so such an
80
+ * entry is refused too. The file already fails `markspec check` there.
81
+ * An entry whose trailer-looking lines use only unrecognized keys, and
82
+ * that the parser reads as body without a diagnostic, is edited as the
83
+ * parser sees it: those lines are body.
84
+ */
85
+ export declare function replaceEntryBody(text: string, file: string, displayId: string, body: string): Promise<EntryBodyEdit>;
86
+ //# sourceMappingURL=entry_body.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"entry_body.d.ts","sourceRoot":"","sources":["../../src/formatter/entry_body.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AAKH,wDAAwD;AACxD,MAAM,MAAM,gBAAgB,GACxB,iBAAiB,GACjB,YAAY,GACZ,gBAAgB,GAChB,iBAAiB,GACjB,iBAAiB,CAAC;AAEtB,8CAA8C;AAC9C,MAAM,MAAM,aAAa,GACrB;IAAE,QAAQ,CAAC,EAAE,EAAE,IAAI,CAAC;IAAC,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAA;CAAE,GAC5C;IAAE,QAAQ,CAAC,EAAE,EAAE,KAAK,CAAC;IAAC,QAAQ,CAAC,OAAO,EAAE,gBAAgB,CAAA;CAAE,CAAC;AA8E/D;;;;;;;;;GASG;AACH,wBAAgB,aAAa,CAAC,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,MAAM,CAGlE;AAyCD;;;;;;;GAOG;AACH,wBAAsB,aAAa,CACjC,IAAI,EAAE,MAAM,EACZ,IAAI,EAAE,MAAM,EACZ,SAAS,EAAE,MAAM,GAChB,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAS7B;AASD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AACH,wBAAsB,gBAAgB,CACpC,IAAI,EAAE,MAAM,EACZ,IAAI,EAAE,MAAM,EACZ,SAAS,EAAE,MAAM,EACjB,IAAI,EAAE,MAAM,GACX,OAAO,CAAC,aAAa,CAAC,CAoDxB"}
@@ -0,0 +1,292 @@
1
+ "use strict";
2
+ /**
3
+ * @module formatter/entry_body
4
+ *
5
+ * Read and replace the body of one entry in a Markdown file text.
6
+ *
7
+ * Splice-only contract: {@linkcode replaceEntryBody} changes only the
8
+ * lines of the target entry's body. Every other line of the file (other
9
+ * entries, prose, front matter, the title, the trailer block, and each
10
+ * line's own line ending) stays byte-for-byte unchanged. After the splice
11
+ * the text is parsed again; when the set of entries differs (a new entry,
12
+ * a lost entry, a changed title or trailer) or the target's body is not
13
+ * the proposal, the edit is refused.
14
+ *
15
+ * The body range starts after the title paragraph (up to the first blank
16
+ * line after the title line, so a soft-wrapped title is skipped) and the
17
+ * blank lines after it. It has as many lines as the parser's
18
+ * `entry.body`, so lazy continuation lines are included, and it must
19
+ * match that body line for line. The body indent is the content column of
20
+ * the list item: the marker column, plus the marker width, plus the spaces
21
+ * after the marker. Lines are split on `\r\n`, a
22
+ * lone `\r`, or `\n`, as in the parser.
23
+ *
24
+ * Pure: no I/O, Node-compatible.
25
+ */
26
+ Object.defineProperty(exports, "__esModule", { value: true });
27
+ exports.contentColumn = contentColumn;
28
+ exports.readEntryBody = readEntryBody;
29
+ exports.replaceEntryBody = replaceEntryBody;
30
+ const mod_js_1 = require("../parser/mod.js");
31
+ /**
32
+ * Split `text` into lines on `\r\n`, a lone `\r`, or `\n`, the same rule
33
+ * the parser uses to normalize line endings, so line indexes agree with
34
+ * parser line numbers. Each line keeps its own ending.
35
+ */
36
+ function splitText(text) {
37
+ const lines = [];
38
+ const endings = [];
39
+ const re = /\r\n|\r|\n/g;
40
+ let from = 0;
41
+ for (let m = re.exec(text); m !== null; m = re.exec(text)) {
42
+ lines.push(text.slice(from, m.index));
43
+ endings.push(m[0]);
44
+ from = m.index + m[0].length;
45
+ }
46
+ lines.push(text.slice(from));
47
+ endings.push("");
48
+ return { lines, endings };
49
+ }
50
+ /** Lines of `text` with trailing whitespace removed, for comparisons. */
51
+ function trimmedLines(text) {
52
+ return text.split("\n").map((l) => l.trimEnd());
53
+ }
54
+ /**
55
+ * Locate the body of `entry` in `lines`. `start === end` when the entry
56
+ * has no body.
57
+ *
58
+ * The body starts after the title paragraph and the blank lines that
59
+ * follow it. Its length is the line count of the parser's `entry.body`,
60
+ * so a lazy continuation line (a body line indented less than the body
61
+ * indent) is part of the span. `exact` is false when the dedented span,
62
+ * trimmed as a whole like the parser's body, does not match `entry.body`
63
+ * line for line (trailing whitespace ignored); the span is then not
64
+ * reliable and must not be edited.
65
+ */
66
+ function bodySpan(lines, entry) {
67
+ const titleIdx = entry.location.line - 1;
68
+ const indent = contentColumn(lines[titleIdx] ?? "", entry.location.column - 1);
69
+ const isBlank = (i) => lines[i].trim() === "";
70
+ let start = titleIdx + 1;
71
+ // Skip the rest of the title paragraph (a soft-wrapped title).
72
+ while (start < lines.length && !isBlank(start))
73
+ start++;
74
+ while (start < lines.length && isBlank(start))
75
+ start++;
76
+ if (entry.body === "")
77
+ return { start, end: start, indent, exact: true };
78
+ const expected = trimmedLines(entry.body);
79
+ const end = Math.min(start + expected.length, lines.length);
80
+ const actual = spanText(lines, { start, end, indent, exact: true });
81
+ // The parser trims its body as a whole, which drops the leading
82
+ // whitespace of the first line (an indented code block); trim the span
83
+ // the same way before comparing.
84
+ const exact = actual.join("\n").trim() === expected.join("\n");
85
+ return { start, end, indent, exact };
86
+ }
87
+ /**
88
+ * 0-based content column of the list item whose marker starts at `marker`
89
+ * on `line`: the marker column, plus 1 for the bullet, plus the spaces
90
+ * after it. So `- [ID]` gives the marker column plus 2 and `- [ID]` gives
91
+ * the marker column plus 4. Only a bullet followed by one to four spaces
92
+ * can start an entry: ordered lists never hold entries, and five or more
93
+ * spaces make the title an indented code block. When the line does not
94
+ * start with a bullet and a space at `marker`, the marker column plus 2 is
95
+ * used as a fallback.
96
+ */
97
+ function contentColumn(line, marker) {
98
+ const m = /^[-*+]( +)/.exec(line.slice(marker));
99
+ return m ? marker + 1 + m[1].length : marker + 2;
100
+ }
101
+ /** Dedented span lines, trailing whitespace removed. */
102
+ function spanText(lines, span) {
103
+ return lines.slice(span.start, span.end)
104
+ .map((l) => l.trim() === "" ? "" : dedent(l, span.indent).trimEnd());
105
+ }
106
+ /** Parse `text` and find the entry named `displayId`. */
107
+ async function locate(text, file, displayId) {
108
+ const { entries, diagnostics } = await (0, mod_js_1.parseFile)(text, { file });
109
+ const entry = entries.find((e) => e.displayId === displayId);
110
+ const trailerInvalid = diagnostics.some((d) => TRAILER_PARSE_CODES.has(d.code) && d.message.startsWith(`${displayId}:`));
111
+ return {
112
+ entries,
113
+ entry,
114
+ diagnosticCodes: diagnostics.map((d) => d.code),
115
+ trailerInvalid,
116
+ };
117
+ }
118
+ /** Parse codes that mean an entry's trailer block did not parse. */
119
+ const TRAILER_PARSE_CODES = new Set([
120
+ "MSL-P020",
121
+ "MSL-P021",
122
+ "MSL-P022",
123
+ ]);
124
+ /**
125
+ * Body of the entry `displayId` as written in `text`: dedented, LF line
126
+ * endings, no surrounding blank lines. Returns `""` when the entry has no
127
+ * body and `undefined` when no entry has `displayId`. `file` names a
128
+ * `.md` file. When the body lines cannot be located exactly in `text`,
129
+ * the parser's body is returned (and {@linkcode replaceEntryBody}
130
+ * refuses to edit that entry).
131
+ */
132
+ async function readEntryBody(text, file, displayId) {
133
+ const { entry } = await locate(text, file, displayId);
134
+ if (!entry)
135
+ return undefined;
136
+ const { lines } = splitText(text);
137
+ const span = bodySpan(lines, entry);
138
+ if (!span.exact)
139
+ return entry.body;
140
+ return lines.slice(span.start, span.end)
141
+ .map((l) => l.trim() === "" ? "" : dedent(l, span.indent))
142
+ .join("\n");
143
+ }
144
+ /** Remove up to `indent` leading spaces. */
145
+ function dedent(line, indent) {
146
+ let i = 0;
147
+ while (i < indent && line[i] === " ")
148
+ i++;
149
+ return line.slice(i);
150
+ }
151
+ /**
152
+ * Return `text` with the body of entry `displayId` replaced by `body`,
153
+ * re-indented to the body indent. Every other line stays byte-for-byte
154
+ * unchanged. Inserted lines take the line ending of the title line. In
155
+ * `body`, `\r\n` and a lone `\r` count as line breaks.
156
+ *
157
+ * Refusals: `entry-not-found` (no such entry), `trailer-invalid` (the
158
+ * entry's trailer block did not parse, see below), `body-empty` (the entry
159
+ * has no body), `proposal-empty` (`body` is blank), `entries-changed`
160
+ * (two entries in `text` have `displayId`; or the body lines cannot be
161
+ * located exactly in `text`; or the edited
162
+ * text no longer parses to the same entries, with the same title and
163
+ * trailer for the target, and with the proposal as the target's body;
164
+ * or the parse raises more structural diagnostics of some code, such as
165
+ * MSL-P020, than the original text).
166
+ *
167
+ * `trailer-invalid`: when a trailer line is malformed (for example an
168
+ * empty `Labels:`, a key without a colon, or a lowercase key), the parser
169
+ * reads the whole trailer block, the `Id:` line included, as body. A
170
+ * splice would then delete the `Id:` and trailer lines, and the identity
171
+ * check cannot see it, because the entry has no `id` and no attributes
172
+ * before or after the edit. So the edit is refused when an `MSL-P020`,
173
+ * `MSL-P021` or `MSL-P022` names the entry (the message starts with
174
+ * `<displayId>:`). This is broader than that case: `MSL-P020` also fires
175
+ * when a body paragraph starts with a recognized trailer key, so such an
176
+ * entry is refused too. The file already fails `markspec check` there.
177
+ * An entry whose trailer-looking lines use only unrecognized keys, and
178
+ * that the parser reads as body without a diagnostic, is edited as the
179
+ * parser sees it: those lines are body.
180
+ */
181
+ async function replaceEntryBody(text, file, displayId, body) {
182
+ const before = await locate(text, file, displayId);
183
+ const entry = before.entry;
184
+ if (!entry)
185
+ return { ok: false, refusal: "entry-not-found" };
186
+ if (before.trailerInvalid)
187
+ return { ok: false, refusal: "trailer-invalid" };
188
+ // Two entries with the same display ID make the target ambiguous (and
189
+ // `markspec check` already rejects the file), so do not edit either.
190
+ if (before.entries.filter((e) => e.displayId === displayId).length > 1) {
191
+ return { ok: false, refusal: "entries-changed" };
192
+ }
193
+ const { lines, endings } = splitText(text);
194
+ const span = bodySpan(lines, entry);
195
+ if (span.start === span.end)
196
+ return { ok: false, refusal: "body-empty" };
197
+ if (!span.exact)
198
+ return { ok: false, refusal: "entries-changed" };
199
+ const proposal = body.replace(/\r\n?/g, "\n").split("\n");
200
+ while (proposal.length > 0 && proposal[0].trim() === "")
201
+ proposal.shift();
202
+ while (proposal.length > 0 && proposal[proposal.length - 1].trim() === "") {
203
+ proposal.pop();
204
+ }
205
+ if (proposal.length === 0)
206
+ return { ok: false, refusal: "proposal-empty" };
207
+ const titleIdx = entry.location.line - 1;
208
+ const eol = endings[titleIdx];
209
+ const indentStr = " ".repeat(span.indent);
210
+ const inserted = proposal.map((l) => (l.trim() === "" ? "" : indentStr + l) + eol);
211
+ // The final line of the file has no ending after it; keep the old
212
+ // ending of the last body line when the body reaches the file end.
213
+ if (span.end === lines.length) {
214
+ const last = inserted.length - 1;
215
+ inserted[last] = indentStr + proposal[last] + endings[span.end - 1];
216
+ }
217
+ const keep = (from, to) => {
218
+ let out = "";
219
+ for (let i = from; i < to; i++)
220
+ out += lines[i] + endings[i];
221
+ return out;
222
+ };
223
+ const edited = keep(0, span.start) + inserted.join("") +
224
+ keep(span.end, lines.length);
225
+ const after = await locate(edited, file, displayId);
226
+ if (!sameEntries(before.entries, after.entries, entry, after.entry) ||
227
+ addsParseDiagnostic(before.diagnosticCodes, after.diagnosticCodes) ||
228
+ trimmedLines(after.entry?.body ?? "").join("\n") !==
229
+ proposal.map((l) => l.trimEnd()).join("\n").trim()) {
230
+ return { ok: false, refusal: "entries-changed" };
231
+ }
232
+ return { ok: true, text: edited };
233
+ }
234
+ /**
235
+ * Identity check: same entry count; per index, same display ID and Id;
236
+ * for the target, also the same title and the same trailer attributes.
237
+ * An unclosed fence or HTML block in the proposal (for example a final
238
+ * line of three backticks) can swallow the target's trailer without any
239
+ * parse diagnostic; this comparison and the body-equality check in
240
+ * {@linkcode replaceEntryBody} are what refuse such an edit. No input is
241
+ * known that only one of the two refuses: the splice changes only body
242
+ * lines, so another entry, or the target's title or trailer, can change
243
+ * only through a block in the proposal that also changes the target body.
244
+ * (A link reference definition named like a later display ID does not
245
+ * remove that entry: the parser reads definitions only at the top level.)
246
+ * So the tests pin the pair, not either check by itself, and each check is
247
+ * a backstop for the other.
248
+ */
249
+ function sameEntries(before, after, target, targetAfter) {
250
+ if (before.length !== after.length || !targetAfter)
251
+ return false;
252
+ for (let i = 0; i < before.length; i++) {
253
+ if (before[i].displayId !== after[i].displayId)
254
+ return false;
255
+ if (before[i].id !== after[i].id)
256
+ return false;
257
+ }
258
+ if (target.title !== targetAfter.title)
259
+ return false;
260
+ const a = target.rawAttributes;
261
+ const b = targetAfter.rawAttributes;
262
+ if (a.length !== b.length)
263
+ return false;
264
+ return a.every((attr, i) => attr.key === b[i].key && attr.value === b[i].value);
265
+ }
266
+ /**
267
+ * True when `after` holds more diagnostics of some code than `before`.
268
+ * Counts per code, not messages, so diagnostics whose location moved with
269
+ * the splice do not count as new. This catches a body with a trailer-like
270
+ * line or an entry-shaped list item after a blank line (MSL-P020), which
271
+ * the parser keeps as body text and the entry comparison alone cannot
272
+ * see. An entry-shaped item directly after a paragraph line, with no
273
+ * blank line between them, raises no diagnostic; the parser keeps it as
274
+ * body text and adds no entry, so the edit is accepted.
275
+ *
276
+ * Known limit: the parser raises at most one MSL-P020 per entry, so when
277
+ * the target body already has a trailer-like line, a proposal that adds
278
+ * more such lines raises no new MSL-P020 and is accepted. The lines stay
279
+ * body text; no trailer or entry changes.
280
+ */
281
+ function addsParseDiagnostic(before, after) {
282
+ const counts = new Map();
283
+ for (const code of before)
284
+ counts.set(code, (counts.get(code) ?? 0) + 1);
285
+ for (const code of after) {
286
+ const left = (counts.get(code) ?? 0) - 1;
287
+ if (left < 0)
288
+ return true;
289
+ counts.set(code, left);
290
+ }
291
+ return false;
292
+ }
@@ -24,7 +24,7 @@ export declare function isSentenceInitial(line: string, offset: number): boolean
24
24
  *
25
25
  * The pass skips:
26
26
  *
27
- * - Fenced code blocks (between paired ``` or ~~~ markers) — code is
27
+ * - CommonMark fenced code blocks and inline-code spans — code is
28
28
  * verbatim per round-trip invariants (spec §5.1).
29
29
  * - Lines indented by four or more spaces (or a tab) — conservatively
30
30
  * captures indented code blocks and attribute trailers, both of which
@@ -33,8 +33,8 @@ export declare function isSentenceInitial(line: string, offset: number): boolean
33
33
  * @remarks Not called by `format()` as of SP3 Task 5 — body modal
34
34
  * normalization moved to `normalizeBodyAst` in the AST pass (spec-correct
35
35
  * verbatim-boundary handling). Retained as an exported symbol because
36
- * `mod_test.ts` tests it directly and `core/ast/normalize.ts` documents
37
- * the intentional duplication until a follow-up collapses the two. Do NOT
36
+ * `mod_test.ts` tests it directly. Both entry points delegate to the same
37
+ * AST-backed prose normalizer. Do NOT
38
38
  * delete — external callers may depend on this export.
39
39
  */
40
40
  export declare function normalizeModalKeywords(markdown: string): string;
@@ -121,17 +121,21 @@ export declare function sortAttributes(attributes: Attribute[]): Attribute[];
121
121
  * no trailing line-continuation characters.
122
122
  *
123
123
  * @param attributes - The attributes to render, in canonical order.
124
- * @param indent - Body indent for the entry (2 for list-wrapped entries,
125
- * 0 for entries inside source-file doc comments).
124
+ * @param indent - The 0-based list item content column, or 0 inside
125
+ * source-file doc comments.
126
126
  */
127
127
  export declare function renderAttributeBlock(attributes: Attribute[], indent: number): string;
128
128
  /**
129
129
  * Find the 0-based line index where a list item's content ends.
130
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.
131
+ * Scans forward from the later of the line after the entry start and
132
+ * `itemEndFloor` until a line has less indent than the content column, a
133
+ * conventional sibling marker is found, or EOF. Pass the parser's
134
+ * `Entry.endLine` as `itemEndFloor` so that a lazy continuation line
135
+ * inside the item does not end the scan early; the default `0` keeps
136
+ * the indentation-only scan.
133
137
  */
134
- export declare function findItemEnd(lines: readonly string[], startIdx: number, indent: number): number;
138
+ export declare function findItemEnd(lines: readonly string[], startIdx: number, indent: number, itemEndFloor?: number): number;
135
139
  /**
136
140
  * Find the 0-based line range [start, end) of the attribute block
137
141
  * for an entry starting at the given line.
@@ -139,7 +143,7 @@ export declare function findItemEnd(lines: readonly string[], startIdx: number,
139
143
  * Scans forward from the entry start to find the list item boundary,
140
144
  * then walks backwards to find the contiguous trailing attribute block.
141
145
  */
142
- export declare function findAttributeBlockRange(lines: readonly string[], entryStartLine: number, indent: number): {
146
+ export declare function findAttributeBlockRange(lines: readonly string[], entryStartLine: number, indent: number, itemEndFloor?: number): {
143
147
  start: number;
144
148
  end: number;
145
149
  } | undefined;