@rohal12/spindle 0.59.33 → 0.60.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.
@@ -0,0 +1,316 @@
1
+ import { lexJs, lexTemplate } from '../js-lexer';
2
+ import { tokenizeMarkupTolerant } from '../markup/parse';
3
+ import type { Token } from '../markup/tokens';
4
+
5
+ export interface TokenMatch {
6
+ start: number;
7
+ end: number;
8
+ token: string;
9
+ /** Set for a token in the value of an HTML attribute (else absent). */
10
+ inAttribute?: true;
11
+ }
12
+
13
+ /** A `{do}…{/do}` block: its body is JavaScript, run as written. */
14
+ export interface DoBlock {
15
+ /** Start of `{do}` and end of `{/do}`. */
16
+ start: number;
17
+ end: number;
18
+ /** The JavaScript between the two tags. */
19
+ bodyStart: number;
20
+ bodyEnd: number;
21
+ }
22
+
23
+ /** What the formatter must leave to the runtime in a piece of markup. */
24
+ export interface MarkupScan {
25
+ /** Macros, variables, expressions and links (also those in attribute values), in source order. */
26
+ tokens: TokenMatch[];
27
+ /** The HTML tags (opening, closing and self-closing). */
28
+ tags: { start: number; end: number }[];
29
+ /** The `{do}…{/do}` blocks. */
30
+ doBlocks: DoBlock[];
31
+ }
32
+
33
+ /**
34
+ * Read `text` with Spindle's own tokenizer (`tokenizeMarkupTolerant`), so the
35
+ * formatter protects exactly what the runtime executes. A token inside an
36
+ * HTML attribute value is reported too, with the attribute-safe placeholder
37
+ * it needs, because it must not be reformatted either.
38
+ */
39
+ export function scanSpindleMarkup(text: string): MarkupScan {
40
+ const tokens: TokenMatch[] = [];
41
+ const tags: { start: number; end: number }[] = [];
42
+ const doBlocks: DoBlock[] = [];
43
+ let open: Token | undefined;
44
+
45
+ const push = (t: { start: number; end: number }, inAttribute?: true) => {
46
+ const match: TokenMatch = {
47
+ start: t.start,
48
+ end: t.end,
49
+ token: text.slice(t.start, t.end),
50
+ };
51
+ if (inAttribute) match.inAttribute = true;
52
+ tokens.push(match);
53
+ };
54
+
55
+ for (const t of tokenizeMarkupTolerant(text).tokens) {
56
+ if (t.type === 'html') {
57
+ tags.push({ start: t.start, end: t.end });
58
+ for (const attribute of t.attributeSpans) {
59
+ if (
60
+ attribute.valueStart === undefined ||
61
+ attribute.valueEnd === undefined
62
+ )
63
+ continue;
64
+ const value = text.slice(attribute.valueStart, attribute.valueEnd);
65
+ if (!value.includes('{')) continue;
66
+ for (const inner of tokenizeMarkupTolerant(value, { text: true })
67
+ .tokens) {
68
+ if (
69
+ inner.type === 'macro' ||
70
+ inner.type === 'variable' ||
71
+ inner.type === 'expression'
72
+ ) {
73
+ push(
74
+ {
75
+ start: attribute.valueStart + inner.start,
76
+ end: attribute.valueStart + inner.end,
77
+ },
78
+ true,
79
+ );
80
+ }
81
+ }
82
+ }
83
+ } else if (t.type !== 'text') {
84
+ // The body of {do} is one text token, so nothing in it is a token
85
+ if (t.type === 'macro' && t.name === 'do') {
86
+ if (!t.isClose) open = t;
87
+ else if (open) {
88
+ doBlocks.push({
89
+ start: open.start,
90
+ end: t.end,
91
+ bodyStart: open.end,
92
+ bodyEnd: t.start,
93
+ });
94
+ open = undefined;
95
+ }
96
+ }
97
+ push(t);
98
+ }
99
+ }
100
+ return { tokens, tags, doBlocks };
101
+ }
102
+
103
+ /**
104
+ * The ranges of the string and template literals of the JavaScript `code`
105
+ * that span lines (outermost only): their line breaks are part of the value.
106
+ */
107
+ export function multilineJsLiterals(code: string): [number, number][] {
108
+ const spans: [number, number][] = [];
109
+ let skipUntil = 0;
110
+ lexJs(
111
+ code,
112
+ {
113
+ literal(text, index, nesting) {
114
+ if (nesting > 0 || index < skipUntil) return;
115
+ const quote = text[0];
116
+ if (quote === '`') {
117
+ // The backtick that opens a template literal: its parts follow
118
+ skipUntil = lexTemplate(code, index);
119
+ if (code.slice(index, skipUntil).includes('\n'))
120
+ spans.push([index, skipUntil]);
121
+ } else if ((quote === '"' || quote === "'") && text.includes('\n')) {
122
+ spans.push([index, index + text.length]);
123
+ }
124
+ },
125
+ },
126
+ 'statements',
127
+ );
128
+ return spans;
129
+ }
130
+
131
+ /** Whether an HTML tag (opening, closing or self-closing) overlaps the range. */
132
+ function lineHasTag(
133
+ tags: { start: number; end: number }[],
134
+ start: number,
135
+ end: number,
136
+ ): boolean {
137
+ return tags.some((tag) => tag.start < end && tag.end > start);
138
+ }
139
+
140
+ export interface PlaceholderResult {
141
+ text: string;
142
+ tokens: string[];
143
+ }
144
+
145
+ /**
146
+ * Replace `<svg>…</svg>` blocks with HTML comment placeholders so Prettier
147
+ * does not reformat them (CommonMark does not recognise multi-line SVG tags
148
+ * as HTML blocks, so reformatted attributes break rendering).
149
+ */
150
+ export function replaceSvgBlocks(html: string): PlaceholderResult {
151
+ const tokens: string[] = [];
152
+ const result = html.replace(/<svg[\s>][\s\S]*?<\/svg>/gi, (match) => {
153
+ const idx = tokens.length;
154
+ tokens.push(match);
155
+ return `<!--SVG:${idx}-->`;
156
+ });
157
+ return { text: result, tokens };
158
+ }
159
+
160
+ /** The placeholders of the token at an index. */
161
+ type PlaceholdersOf = (index: number) => string[];
162
+
163
+ export const SVG_PLACEHOLDERS: PlaceholdersOf = (i) => [`<!--SVG:${i}-->`];
164
+ export const SPINDLE_PLACEHOLDERS: PlaceholdersOf = (i) => [
165
+ `<!--SP:${i}-->`,
166
+ `__SP${i}__`,
167
+ ];
168
+
169
+ /**
170
+ * Whether `text` (what a formatter made of the placeholdered text) holds
171
+ * the placeholder of every one of `tokens` exactly once. If not, the
172
+ * formatter lost, changed or copied one, and restoring the tokens would
173
+ * lose or duplicate story text.
174
+ */
175
+ export function placeholdersIntact(
176
+ text: string,
177
+ tokens: readonly string[],
178
+ placeholdersOf: PlaceholdersOf,
179
+ ): boolean {
180
+ return tokens.every(
181
+ (_, index) =>
182
+ placeholdersOf(index).reduce(
183
+ (count, placeholder) => count + text.split(placeholder).length - 1,
184
+ 0,
185
+ ) === 1,
186
+ );
187
+ }
188
+
189
+ /** Whether `before` and `after` hold the same Spindle tokens, in the same order. */
190
+ export function sameSpindleTokens(before: string, after: string): boolean {
191
+ const tokensOf = (text: string) =>
192
+ scanSpindleMarkup(text).tokens.map((m) => m.token);
193
+ const expected = tokensOf(before);
194
+ const found = tokensOf(after);
195
+ return (
196
+ expected.length === found.length && expected.every((t, i) => t === found[i])
197
+ );
198
+ }
199
+
200
+ /**
201
+ * Put each of `tokens` back in place of its placeholders (those that
202
+ * `placeholdersOf` gives for its index): the first of each.
203
+ */
204
+ function restorePlaceholders(
205
+ text: string,
206
+ tokens: string[],
207
+ placeholdersOf: PlaceholdersOf,
208
+ ): string {
209
+ let result = text;
210
+ tokens.forEach((token, index) => {
211
+ for (const placeholder of placeholdersOf(index)) {
212
+ // Callback form: a replacement string would expand `$&`, `$'`, etc.
213
+ result = result.replace(placeholder, () => token);
214
+ }
215
+ });
216
+ return result;
217
+ }
218
+
219
+ /**
220
+ * Restore SVG blocks from placeholders.
221
+ */
222
+ export function restoreSvgBlocks(text: string, tokens: string[]): string {
223
+ return restorePlaceholders(text, tokens, SVG_PLACEHOLDERS);
224
+ }
225
+
226
+ /**
227
+ * Replace Spindle tokens with placeholders.
228
+ * Uses <!--SP:N--> in HTML content and __SPN__ in attribute values.
229
+ *
230
+ * Lines that contain Spindle tokens but no HTML tags are replaced as a
231
+ * single whole-line placeholder so Prettier cannot split them. A token that
232
+ * spans lines (a template literal with a line break) keeps its line break:
233
+ * the lines it spans are one line here. A `{do}…{/do}` block is one token:
234
+ * its body is JavaScript executed as written, which an HTML formatter must
235
+ * not re-indent or re-flow.
236
+ */
237
+ export function replaceSpindleTokens(html: string): PlaceholderResult {
238
+ const { tokens: found, tags, doBlocks } = scanSpindleMarkup(html);
239
+ // The units to protect, in source order: a do block whole, else each token
240
+ const units: TokenMatch[] = [];
241
+ const pushDoBlock = (block: DoBlock) =>
242
+ units.push({
243
+ start: block.start,
244
+ end: block.end,
245
+ token: html.slice(block.start, block.end),
246
+ });
247
+ let doIndex = 0;
248
+ for (const m of found) {
249
+ for (let block = doBlocks[doIndex]; block && block.end <= m.start;) {
250
+ pushDoBlock(block);
251
+ block = doBlocks[++doIndex];
252
+ }
253
+ const open = doBlocks[doIndex];
254
+ if (open && m.start >= open.start) continue;
255
+ units.push(m);
256
+ }
257
+ for (; doIndex < doBlocks.length; doIndex++) pushDoBlock(doBlocks[doIndex]!);
258
+ units.sort((a, b) => a.start - b.start);
259
+
260
+ const tokens: string[] = [];
261
+ const resultLines: string[] = [];
262
+ let unit = 0;
263
+ let lineStart = 0;
264
+ while (lineStart <= html.length) {
265
+ // A line ends at a line break outside every unit
266
+ let lineEnd = lineStart;
267
+ const lineUnits: TokenMatch[] = [];
268
+ for (;;) {
269
+ while (unit < units.length && units[unit]!.end <= lineEnd) unit++;
270
+ const next = units[unit];
271
+ const inside = next && next.start <= lineEnd ? next : undefined;
272
+ if (inside) {
273
+ lineUnits.push(inside);
274
+ lineEnd = inside.end;
275
+ unit++;
276
+ continue;
277
+ }
278
+ if (lineEnd >= html.length || html[lineEnd] === '\n') break;
279
+ lineEnd++;
280
+ }
281
+ const line = html.slice(lineStart, lineEnd);
282
+ const indent = line.match(/^(\s*)/)?.[1] ?? '';
283
+
284
+ if (lineUnits.length === 0) {
285
+ resultLines.push(line);
286
+ } else if (!lineHasTag(tags, lineStart, lineEnd)) {
287
+ // Spindle tokens but no HTML: one placeholder for the whole line
288
+ const idx = tokens.length;
289
+ tokens.push(line.trim());
290
+ resultLines.push(`${indent}<!--SP:${idx}-->`);
291
+ } else {
292
+ // Both HTML and Spindle: one placeholder per token, in source order
293
+ let replaced = '';
294
+ let last = lineStart;
295
+ for (const u of lineUnits) {
296
+ const idx = tokens.length;
297
+ tokens.push(u.token);
298
+ replaced +=
299
+ html.slice(last, u.start) +
300
+ (u.inAttribute ? `__SP${idx}__` : `<!--SP:${idx}-->`);
301
+ last = u.end;
302
+ }
303
+ resultLines.push(replaced + html.slice(last, lineEnd));
304
+ }
305
+ lineStart = lineEnd + 1;
306
+ }
307
+
308
+ return { text: resultLines.join('\n'), tokens };
309
+ }
310
+
311
+ /**
312
+ * Restore original Spindle tokens from placeholders.
313
+ */
314
+ export function restoreSpindleTokens(text: string, tokens: string[]): string {
315
+ return restorePlaceholders(text, tokens, SPINDLE_PLACEHOLDERS);
316
+ }
@@ -0,0 +1,62 @@
1
+ /**
2
+ * The Prettier calls of the formatter. Prettier is not imported here: the
3
+ * caller injects it, so this module (and the tooling bundle that has it) holds
4
+ * no copy of Prettier. Without it, or when it throws on a piece of code, there
5
+ * is no formatted text (`undefined`): the caller keeps the code as written.
6
+ */
7
+
8
+ /** The part of Prettier's API the formatter calls (`prettier` and `prettier/standalone` have it). */
9
+ export interface PrettierLike {
10
+ format(code: string, options: object): Promise<string>;
11
+ }
12
+
13
+ /** The options the formatter gives Prettier unless the caller passes its own. */
14
+ export const DEFAULT_PRETTIER_OPTIONS = { tabWidth: 2 };
15
+
16
+ async function run(
17
+ code: string,
18
+ prettier: PrettierLike | undefined,
19
+ options: object | undefined,
20
+ overrides: object,
21
+ ): Promise<string | undefined> {
22
+ if (!prettier) return undefined;
23
+ try {
24
+ return await prettier.format(code, {
25
+ ...(options ?? DEFAULT_PRETTIER_OPTIONS),
26
+ ...overrides,
27
+ });
28
+ } catch {
29
+ return undefined;
30
+ }
31
+ }
32
+
33
+ export function formatJS(
34
+ code: string,
35
+ prettier?: PrettierLike,
36
+ options?: object,
37
+ ): Promise<string | undefined> {
38
+ return run(code, prettier, options, { parser: 'babel' });
39
+ }
40
+
41
+ export function formatCSS(
42
+ code: string,
43
+ prettier?: PrettierLike,
44
+ options?: object,
45
+ ): Promise<string | undefined> {
46
+ return run(code, prettier, options, { parser: 'css' });
47
+ }
48
+
49
+ export function formatHTML(
50
+ code: string,
51
+ prettier?: PrettierLike,
52
+ options?: object,
53
+ ): Promise<string | undefined> {
54
+ // 'css': Prettier adds and removes whitespace only where the default CSS
55
+ // display of the elements says it does not render, so Format never
56
+ // changes the text a passage shows ('ignore' turned `<b>a</b>,` into
57
+ // `<b>a</b> ,`)
58
+ return run(code, prettier, options, {
59
+ parser: 'html',
60
+ htmlWhitespaceSensitivity: 'css',
61
+ });
62
+ }
@@ -0,0 +1,126 @@
1
+ /** A run of a passage body that is formatted as one kind of content. */
2
+ export interface Region {
3
+ type: 'spindle' | 'html' | 'script' | 'svg';
4
+ lines: string[];
5
+ }
6
+
7
+ const VOID_ELEMENTS = new Set([
8
+ 'area',
9
+ 'base',
10
+ 'br',
11
+ 'col',
12
+ 'embed',
13
+ 'hr',
14
+ 'img',
15
+ 'input',
16
+ 'link',
17
+ 'meta',
18
+ 'param',
19
+ 'source',
20
+ 'track',
21
+ 'wbr',
22
+ ]);
23
+
24
+ /**
25
+ * Segment a passage body into regions: spindle (markdown/macros), html blocks, script blocks.
26
+ */
27
+ export function segmentRegions(body: string): Region[] {
28
+ const lines = body.split('\n');
29
+ // Remove trailing empty line from split
30
+ if (lines.length > 0 && lines[lines.length - 1] === '') {
31
+ lines.pop();
32
+ }
33
+ if (lines.length === 0) return [];
34
+
35
+ const regions: Region[] = [];
36
+ let i = 0;
37
+
38
+ while (i < lines.length) {
39
+ const line = lines[i]!;
40
+ const trimmed = line.trim();
41
+
42
+ // Detect <script> blocks. A same-line element `<script>…</script>` is
43
+ // a region of this line only.
44
+ if (/^<script(\s|>)/i.test(trimmed)) {
45
+ const block = blockLines(lines, i, /<\/script\s*>/i);
46
+ regions.push({ type: 'script', lines: block });
47
+ i += block.length;
48
+ continue;
49
+ }
50
+
51
+ // Detect <svg> blocks — treat as opaque to prevent Prettier from
52
+ // breaking multi-line attributes (CommonMark does not list svg as a
53
+ // type-6 HTML block tag, so reformatted multi-line tags break rendering).
54
+ if (/^<svg(\s|>)/i.test(trimmed)) {
55
+ const block = blockLines(lines, i, /<\/svg\s*>/i);
56
+ regions.push({ type: 'svg', lines: block });
57
+ i += block.length;
58
+ continue;
59
+ }
60
+
61
+ // Detect multi-line HTML blocks
62
+ if (/^<([a-zA-Z][\w-]*)/.test(trimmed)) {
63
+ const tagMatch = trimmed.match(/^<([a-zA-Z][\w-]*)/);
64
+ const tagName = tagMatch![1]!.toLowerCase();
65
+
66
+ // Skip void elements on their own line — not a multi-line block
67
+ if (VOID_ELEMENTS.has(tagName) && !lines[i + 1]?.trim().startsWith('<')) {
68
+ pushSpindleLine(regions, line);
69
+ i++;
70
+ continue;
71
+ }
72
+
73
+ // Check if this is truly multi-line: does the tag close on the same line?
74
+ const selfClosing = new RegExp(`</${tagName}\\s*>`, 'i');
75
+ if (selfClosing.test(trimmed)) {
76
+ pushSpindleLine(regions, line);
77
+ i++;
78
+ continue;
79
+ }
80
+
81
+ // Multi-line HTML block
82
+ const htmlLines: string[] = [line];
83
+ let depth = 1;
84
+ i++;
85
+ while (i < lines.length && depth > 0) {
86
+ htmlLines.push(lines[i]!);
87
+ const opens = (
88
+ lines[i]!.match(new RegExp(`<${tagName}(?:[\\s>]|$)`, 'gi')) ?? []
89
+ ).length;
90
+ const closes = (
91
+ lines[i]!.match(new RegExp(`</${tagName}\\s*>`, 'gi')) ?? []
92
+ ).length;
93
+ depth += opens - closes;
94
+ i++;
95
+ }
96
+ regions.push({ type: 'html', lines: htmlLines });
97
+ continue;
98
+ }
99
+
100
+ // Default: spindle/markdown line
101
+ pushSpindleLine(regions, line);
102
+ i++;
103
+ }
104
+
105
+ return regions;
106
+ }
107
+
108
+ /**
109
+ * The lines of the block that opens on line `start`: up to the first line
110
+ * (the opening one included) that matches `close`, or to the end.
111
+ */
112
+ function blockLines(lines: string[], start: number, close: RegExp): string[] {
113
+ let end = start;
114
+ while (end < lines.length - 1 && !close.test(lines[end]!)) end++;
115
+ return lines.slice(start, end + 1);
116
+ }
117
+
118
+ /** Append a line to the last spindle region, or create a new one. */
119
+ function pushSpindleLine(regions: Region[], line: string): void {
120
+ const last = regions[regions.length - 1];
121
+ if (last?.type === 'spindle') {
122
+ last.lines.push(line);
123
+ } else {
124
+ regions.push({ type: 'spindle', lines: [line] });
125
+ }
126
+ }
package/src/js-lexer.ts CHANGED
@@ -793,6 +793,15 @@ export interface FindCodeEndOptions {
793
793
  goal?: JsGoal;
794
794
  /** End the code at a `{` in code, at any depth, for which this holds. */
795
795
  stop?: (index: number) => boolean;
796
+ /**
797
+ * Called when a line appended to `src` (text after a line break) could
798
+ * change the result: there is no end because the code runs to the end of
799
+ * `src` (an open bracket, comment, string or template literal), or the
800
+ * end was found by reading a template literal that runs to the end as
801
+ * closed early (see above). Not called when the code before the end
802
+ * can't be JavaScript.
803
+ */
804
+ onRunOut?: () => void;
796
805
  }
797
806
 
798
807
  /** The rest of a word, after a number (`2s`). */
@@ -828,9 +837,9 @@ const WORDS_BEFORE_STRING = new Set(['of', 'get', 'set', 'static', 'async']);
828
837
  export function findCodeEnd(
829
838
  src: string,
830
839
  start: number,
831
- { goal = 'expression', stop }: FindCodeEndOptions = {},
840
+ { goal = 'expression', stop, onRunOut }: FindCodeEndOptions = {},
832
841
  ): number {
833
- const end = scanCodeEnd(src, start, goal, stop);
842
+ const end = scanCodeEnd(src, start, goal, stop, onRunOut);
834
843
  return end < 0 && !stop ? parsedCodeEnd(src, start, goal) : end;
835
844
  }
836
845
 
@@ -866,7 +875,13 @@ function scanCodeEnd(
866
875
  start: number,
867
876
  goal: JsGoal,
868
877
  stop: ((index: number) => boolean) | undefined,
878
+ onRunOut: (() => void) | undefined,
869
879
  ): number {
880
+ /** No end: the code runs to the end of `src`. */
881
+ const ranOut = () => {
882
+ onRunOut?.();
883
+ return -1;
884
+ };
870
885
  const stack: string[] = [];
871
886
  let prevEnd = -1;
872
887
  let prevWord = false;
@@ -885,15 +900,30 @@ function scanCodeEnd(
885
900
  // on after its first character, as after an operator
886
901
  resumeAt = Math.max(tok.pos, from) + 1;
887
902
  afterOperand = false;
888
- if (resumeAt >= src.length) return -1;
903
+ if (resumeAt >= src.length) return ranOut();
889
904
  break;
890
905
  }
891
906
  const k = stack.lastIndexOf('${');
892
907
  const unclosed = /^Unterminated template/.test(message);
893
908
  // One such slip per block: more is no code an author meant. (A raw
894
909
  // body that is no code ends at its first closer.)
895
- if (!unclosed || k < 0 || templateSlip || stop) return -1;
896
- // The template's text starts just past the backtick that opened it
910
+ if (!unclosed || k < 0 || templateSlip || stop) {
911
+ // An unterminated literal runs to the end, and a line after it
912
+ // could close it; not so a regex literal, which ends at the line
913
+ // break, or a quote after a word (`don't`), which is no string
914
+ const toEnd =
915
+ /^Unterminated/.test(message) &&
916
+ !/^Unterminated regular/.test(message) &&
917
+ !(
918
+ /^Unterminated string/.test(message) &&
919
+ prevWord &&
920
+ tok.pos === prevEnd
921
+ );
922
+ return toEnd ? ranOut() : -1;
923
+ }
924
+ // The template's text starts just past the backtick that opened it.
925
+ // It ran to the end: a backtick appended would close it instead.
926
+ onRunOut?.();
897
927
  templateSlip = true;
898
928
  stack.length = k;
899
929
  resumeAt = tok.pos;
@@ -902,7 +932,7 @@ function scanCodeEnd(
902
932
  }
903
933
  if (tok.restarted && stack.includes('${')) return -1;
904
934
  const t = tok.type;
905
- if (t === tt.eof) return -1;
935
+ if (t === tt.eof) return ranOut();
906
936
  if (t === tt.string && prevWord && tok.start === prevEnd) return -1;
907
937
  prevWord =
908
938
  (t === tt.name && !WORDS_BEFORE_STRING.has(tok.value as string)) ||