@rohal12/spindle 0.59.22 → 0.59.25

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/tooling.ts CHANGED
@@ -12,16 +12,46 @@ import {
12
12
  import { isBlockMacro } from './markup/ast';
13
13
  import { tokenizeMarkupTolerant } from './markup/parse';
14
14
  import {
15
- collectPassageReferences,
16
15
  parameterLookup,
16
+ passagePiecesOf,
17
+ pieceOffset,
18
+ referencesOf,
17
19
  type PassageReference,
20
+ type Piece,
18
21
  } from './code-check';
19
- import { blockWidgetNames } from './widgets/widget-def';
22
+ import {
23
+ blockWidgetNames,
24
+ widgetDefinitions as readWidgetDefinitions,
25
+ type WidgetDefinition,
26
+ } from './widgets/widget-def';
27
+ import {
28
+ checkVariableReferences,
29
+ collectVariableReferences,
30
+ type VariableDeclarations,
31
+ type VariableDiagnostic,
32
+ type VariableReference,
33
+ } from './story-variables';
20
34
  import type { ParameterDef } from './registry';
21
35
 
22
- export { parseStoryVariables } from './story-variables';
36
+ export { parseDeclarations, parseStoryVariables } from './story-variables';
37
+ export type {
38
+ VariableDeclarations,
39
+ VariableDiagnostic,
40
+ VariableDiagnosticCode,
41
+ VariableReference,
42
+ } from './story-variables';
43
+ export type {
44
+ Declaration,
45
+ DeclarationError,
46
+ DeclarationErrorCode,
47
+ FieldSchema,
48
+ VarType,
49
+ VariableSchema,
50
+ } from './story-variables';
23
51
  export { checkParameterTypes } from './registry';
24
52
  export { formatDiagnostic } from './markup/validate';
53
+ export { parseWidgetDef } from './widgets/widget-def';
54
+ export type { WidgetDef, WidgetDefinition } from './widgets/widget-def';
25
55
 
26
56
  // The parsing rules (see "Tooling API" in docs/tooling.md): the leaf rules
27
57
  // the runtime parses with, so editor tooling needn't mirror them.
@@ -40,7 +70,32 @@ export {
40
70
  } from './markup/parse';
41
71
  export type { ParseMarkupOptions, TolerantTokens } from './markup/parse';
42
72
  export { SIGIL_SCOPES, isSigil } from './markup/tokens';
43
- export type { Selectors, Token, VariableScope } from './markup/tokens';
73
+ export type {
74
+ AttributeSpan,
75
+ ExpressionToken,
76
+ HtmlToken,
77
+ LinkToken,
78
+ MacroToken,
79
+ SelectorSpan,
80
+ Selectors,
81
+ TextToken,
82
+ Token,
83
+ VariableScope,
84
+ VariableToken,
85
+ } from './markup/tokens';
86
+ export { pairMarkup } from './markup/pair';
87
+ export { pieceOffset };
88
+ export type {
89
+ PairedBody,
90
+ PairedBranch,
91
+ PairedMarkup,
92
+ PairedNode,
93
+ PairingError,
94
+ PairingErrorCode,
95
+ PairMarkupOptions,
96
+ } from './markup/pair';
97
+ export { isBlockMacro } from './markup/ast';
98
+ export type { MarkupErrorCode } from './markup/parse';
44
99
  export {
45
100
  endsWithOperator,
46
101
  readQuoted,
@@ -56,8 +111,21 @@ export {
56
111
  } from './components/macros/macro-args';
57
112
  export type { PassageTarget } from './components/macros/macro-args';
58
113
  export { transform } from './transform';
59
- export type { PassageReference } from './code-check';
60
- export type { MarkupDiagnostic, MarkupPassage } from './markup/validate';
114
+ export type {
115
+ ArgumentErrorPiece,
116
+ CodePiece,
117
+ PassagePiece,
118
+ PassageReference,
119
+ Piece,
120
+ PieceBase,
121
+ TextPiece,
122
+ } from './code-check';
123
+ export type {
124
+ MarkupDiagnostic,
125
+ MarkupDiagnosticCode,
126
+ MarkupDiagnosticData,
127
+ MarkupPassage,
128
+ } from './markup/validate';
61
129
 
62
130
  /** What tooling knows about a macro (see MacroMetadata). */
63
131
  /** Options for validating markup from tooling. */
@@ -81,6 +149,8 @@ export interface ToolingMacro {
81
149
  parameters?: readonly ParameterDef[];
82
150
  /** Whether it resolves markup: its strings hold markup by default. */
83
151
  interpolate?: boolean;
152
+ /** Whether its first argument names the story variable it binds. */
153
+ storeVar?: boolean;
84
154
  }
85
155
 
86
156
  /**
@@ -117,15 +187,114 @@ export function validateStoryMarkup(
117
187
  });
118
188
  }
119
189
 
190
+ /** Whether a macro takes a body, among `macros` and the built-in ones. */
191
+ function blockLookup(macros: readonly ToolingMacro[]) {
192
+ const blocks = new Set(
193
+ macros.filter((m) => m.block).map((m) => m.name.toLowerCase()),
194
+ );
195
+ return (name: string) => blocks.has(name.toLowerCase()) || isBlockMacro(name);
196
+ }
197
+
198
+ /**
199
+ * What a passage's markup runs and names, and where: the pieces of code
200
+ * (`{$expr}` displays, `{do}` bodies, conditions, macro arguments by their
201
+ * declared parameter types, strings that hold code), the passage names written
202
+ * out (links, `passage` arguments), the texts that hold markup of their own
203
+ * (labels, attribute values) and the arguments that don't have their
204
+ * parameters' forms, in source order with offsets (UTF-16) into `source`. The
205
+ * markup in a text follows it, as pieces marked `nested` with offsets into
206
+ * `source` too. Malformed tags are skipped, so it reads half-typed markup.
207
+ * The macros are those the markup may use, built-in and user-defined.
208
+ */
209
+ export function passagePieces(
210
+ source: string,
211
+ macros: Iterable<ToolingMacro> = [],
212
+ ): Piece[] {
213
+ const all = [...macros];
214
+ const { tokens } = tokenizeMarkupTolerant(source);
215
+ return [
216
+ ...passagePiecesOf(source, tokens, parameterLookup(all), {
217
+ isBlock: blockLookup(all),
218
+ }),
219
+ ];
220
+ }
221
+
120
222
  /**
121
223
  * The passages the markup of `source` names (see PassageReference), against
122
224
  * the given macros: what the story-start check looks up. Malformed tags are
123
- * skipped, so it reads half-typed markup.
225
+ * skipped, so it reads half-typed markup. It is `passagePieces`, less what
226
+ * names no passage.
124
227
  */
125
228
  export function collectStoryPassageReferences(
126
229
  source: string,
127
230
  macros: Iterable<ToolingMacro>,
128
231
  ): PassageReference[] {
129
- const { tokens } = tokenizeMarkupTolerant(source);
130
- return collectPassageReferences(source, tokens, parameterLookup(macros));
232
+ return referencesOf(passagePieces(source, macros));
233
+ }
234
+
235
+ /**
236
+ * The widgets the story defines, as the runtime reads them: those of
237
+ * StoryInit and of the passages tagged `widget`, with their parameters,
238
+ * whether their body renders `{@children}` (a block widget) and where they
239
+ * are written, in source order. Half-typed definitions are reported without a
240
+ * `closeStart`. The macros are those the markup may use, built-in and
241
+ * user-defined (a `{@children}` in an attribute or label counts).
242
+ */
243
+ export function widgetDefinitions(
244
+ passages: Iterable<MarkupPassage>,
245
+ macros: Iterable<ToolingMacro> = [],
246
+ ): WidgetDefinition[] {
247
+ return readWidgetDefinitions(passages, parameterLookup([...macros]));
248
+ }
249
+
250
+ /** Passages tagged so hold code or styles, not markup. */
251
+ const NOT_MARKUP_TAGS = ['script', 'stylesheet'];
252
+
253
+ /** What reading the variable references of markup depends on. */
254
+ function referenceOptions(macros: Iterable<ToolingMacro>) {
255
+ const all = [...macros];
256
+ return {
257
+ storeVarMacros: new Set(
258
+ all.filter((m) => m.storeVar).map((m) => m.name.toLowerCase()),
259
+ ),
260
+ parametersOf: parameterLookup(all),
261
+ tolerant: true,
262
+ };
263
+ }
264
+
265
+ /**
266
+ * The `$` and `%` variable references that the markup of a passage evaluates,
267
+ * in source order, with the dotted path of fields accessed and where each is
268
+ * written (offsets into `source`, UTF-16): `{$var}` displays, code in
269
+ * expressions, conditions, `{do}` bodies and macro arguments, quoted names
270
+ * bound by input macros, and the markup in labels and HTML attributes. Prose
271
+ * is literal text. Malformed tags are skipped, so it reads half-typed markup.
272
+ * The macros are those the markup may use, built-in and user-defined.
273
+ */
274
+ export function variableReferences(
275
+ source: string,
276
+ macros: Iterable<ToolingMacro> = [],
277
+ ): VariableReference[] {
278
+ return collectVariableReferences(source, referenceOptions(macros));
279
+ }
280
+
281
+ /**
282
+ * The variable references of the passages' markup that are not valid against
283
+ * the declarations, as the story start checks them: a variable (or, when
284
+ * `transients` is given, a transient) that is not declared, and a field of a
285
+ * primitive that it has no member of. Built on `variableReferences`:
286
+ * tolerant of half-typed markup, and it evaluates no project code.
287
+ */
288
+ export function validateVariableReferences(
289
+ passages: Iterable<MarkupPassage>,
290
+ declarations: VariableDeclarations,
291
+ macros: Iterable<ToolingMacro> = [],
292
+ ): VariableDiagnostic[] {
293
+ return checkVariableReferences(
294
+ [...passages].filter(
295
+ (p) => !p.tags?.some((t) => NOT_MARKUP_TAGS.includes(t)),
296
+ ),
297
+ declarations,
298
+ referenceOptions(macros),
299
+ );
131
300
  }
@@ -35,6 +35,8 @@ import type {
35
35
  validateStoryMarkup as SourceValidateStoryMarkup,
36
36
  } from './tooling';
37
37
  import type { bootStory as PublishedBootStory } from '../types/headless';
38
+ import type * as SourceTooling from './tooling';
39
+ import type * as PublishedTooling from '../types/tooling';
38
40
 
39
41
  /** What the source declares, by published name. */
40
42
  interface Source {
@@ -77,6 +79,56 @@ const _sourceToPublished: Published = {} as Source;
77
79
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
78
80
  const _publishedToSource: Source = {} as Published;
79
81
 
82
+ /** `true` if `A` and `B` are assignable to each other, else `false`. */
83
+ type Same<A, B> = [A] extends [B] ? ([B] extends [A] ? true : false) : false;
84
+
85
+ // The rest of the tooling entry point: what it parses and returns (tokens,
86
+ // pieces, pairing, declarations) and the stateless checks. Each must be the
87
+ // same type in the source and in types/tooling.d.ts, or `false` here is no
88
+ // `true`.
89
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
90
+ const _toolingTypes: [
91
+ Same<SourceTooling.MarkupError, PublishedTooling.MarkupError>,
92
+ Same<SourceTooling.Token, PublishedTooling.Token>,
93
+ Same<SourceTooling.Piece, PublishedTooling.Piece>,
94
+ Same<SourceTooling.PairedNode, PublishedTooling.PairedNode>,
95
+ Same<SourceTooling.PairingError, PublishedTooling.PairingError>,
96
+ Same<SourceTooling.Declaration, PublishedTooling.Declaration>,
97
+ Same<SourceTooling.DeclarationError, PublishedTooling.DeclarationError>,
98
+ Same<SourceTooling.ToolingMacro, PublishedTooling.ToolingMacro>,
99
+ Same<typeof SourceTooling.pairMarkup, typeof PublishedTooling.pairMarkup>,
100
+ Same<
101
+ typeof SourceTooling.passagePieces,
102
+ typeof PublishedTooling.passagePieces
103
+ >,
104
+ Same<
105
+ typeof SourceTooling.parseDeclarations,
106
+ typeof PublishedTooling.parseDeclarations
107
+ >,
108
+ Same<
109
+ typeof SourceTooling.validateStoryMarkup,
110
+ typeof PublishedTooling.validateStoryMarkup
111
+ >,
112
+ Same<
113
+ typeof SourceTooling.collectStoryPassageReferences,
114
+ typeof PublishedTooling.collectStoryPassageReferences
115
+ >,
116
+ ] = [
117
+ true,
118
+ true,
119
+ true,
120
+ true,
121
+ true,
122
+ true,
123
+ true,
124
+ true,
125
+ true,
126
+ true,
127
+ true,
128
+ true,
129
+ true,
130
+ ];
131
+
80
132
  // A typical custom macro written against the published types must type-check,
81
133
  // and misuse of the hooks must not (no `any` leaking through).
82
134
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
@@ -65,12 +65,16 @@ export function astContainsChildren(
65
65
  return true;
66
66
  }
67
67
  if (node.type === 'html') {
68
- const span = { start: 0, end: 0 };
68
+ // A token in name only: the scan reads its attribute values
69
69
  const tag: Token = {
70
70
  isClose: false,
71
71
  isSelfClose: false,
72
+ tagNameStart: 0,
73
+ tagNameEnd: 0,
74
+ attributeSpans: [],
72
75
  ...node,
73
- ...span,
76
+ start: 0,
77
+ end: 0,
74
78
  };
75
79
  if (
76
80
  tokenTextContainsChildren(tag, parametersOf) ||
@@ -80,8 +84,16 @@ export function astContainsChildren(
80
84
  }
81
85
  }
82
86
  if (node.type === 'macro') {
83
- const span = { start: 0, end: 0 };
84
- const tag: Token = { isClose: false, ...node, ...span };
87
+ const tag: Token = {
88
+ isClose: false,
89
+ nameStart: 0,
90
+ nameEnd: 0,
91
+ argsStart: 0,
92
+ argsEnd: 0,
93
+ ...node,
94
+ start: 0,
95
+ end: 0,
96
+ };
85
97
  if (
86
98
  tokenTextContainsChildren(tag, parametersOf) ||
87
99
  astContainsChildren(node.children, parametersOf)
@@ -2,9 +2,10 @@
2
2
  * Reading widget definitions without rendering anything: the `{widget}`
3
3
  * macro, startup and markup validation (also in tooling) share these.
4
4
  */
5
- import { parseMacroArgs } from '../components/macros/macro-args';
5
+ import { parseMacroArgs, type ArgSpans } from '../components/macros/macro-args';
6
6
  import type { MacroArgs } from '../registry';
7
7
  import { tokenizeMarkupTolerant } from '../markup/parse';
8
+ import type { MacroToken } from '../markup/tokens';
8
9
  import type { ParametersOf } from '../code-check';
9
10
  import { registeredParameters, tokenTextContainsChildren } from './ast-scanner';
10
11
 
@@ -39,39 +40,74 @@ export function parseWidgetDef(rawArgs: string): WidgetDef {
39
40
  return widgetDef(parseMacroArgs(rawArgs, WIDGET_PARAMETERS));
40
41
  }
41
42
 
43
+ /** A passage that may define widgets, as the tooling reads it. */
44
+ export interface WidgetPassage {
45
+ name: string;
46
+ tags?: string[];
47
+ content: string;
48
+ }
49
+
42
50
  /**
43
- * The names of the block widgets (those whose body renders `{@children}`)
44
- * that StoryInit and the passages tagged `widget` define. They must be
45
- * known as block macros before any passage is parsed, so that passages
46
- * invoking them nest their content whatever the passage order.
51
+ * A widget defined by a `{widget}` macro, with where it is written (UTF-16
52
+ * offsets into the passage content).
53
+ */
54
+ export interface WidgetDefinition extends WidgetDef {
55
+ /** Whether its body renders `{@children}`. */
56
+ block: boolean;
57
+ /** The passage defining it. */
58
+ passage: string;
59
+ /** The opening `{widget …}` tag. */
60
+ start: number;
61
+ end: number;
62
+ /** The name as written, without quotes. */
63
+ nameStart: number;
64
+ nameEnd: number;
65
+ /** The `{/widget}` closer, absent while the definition is not closed. */
66
+ closeStart?: number;
67
+ }
68
+
69
+ /** Where the name is written in the arguments, without its quotes. */
70
+ function nameSpan(rawArgs: string): [number, number] {
71
+ const spans: ArgSpans = new Map();
72
+ parseMacroArgs(rawArgs, WIDGET_PARAMETERS, spans);
73
+ const [start, end] = spans.get(WIDGET_PARAMETERS[0]) ?? [0, 0];
74
+ const quote = rawArgs[start];
75
+ return (quote === '"' || quote === "'") && end - start >= 2
76
+ ? [start + 1, rawArgs[end - 1] === quote ? end - 1 : end]
77
+ : [start, end];
78
+ }
79
+
80
+ /**
81
+ * The widgets that StoryInit and the passages tagged `widget` define, in
82
+ * source order: the ones the runtime registers, read tolerantly (a half-typed
83
+ * definition is still reported, without a `closeStart`). Definitions whose
84
+ * arguments cannot be read are left out.
47
85
  *
48
86
  * The passages are read as flat tokens, which need no block macros to be
49
87
  * known, so a `{@children}` in an HTML comment or in a `{do}` body is text
50
- * here as it is to the parser, and does not make a block widget (#387).
88
+ * here as it is to the parser, and does not make a block widget (#387). In
89
+ * nested definitions, it belongs to the innermost.
51
90
  */
52
- export function blockWidgetNames(
53
- passages: Iterable<{ name: string; tags?: string[]; content: string }>,
91
+ export function widgetDefinitions(
92
+ passages: Iterable<WidgetPassage>,
54
93
  parametersOf: ParametersOf = registeredParameters,
55
- ): string[] {
56
- const names: string[] = [];
94
+ ): WidgetDefinition[] {
95
+ const found: WidgetDefinition[] = [];
57
96
  for (const passage of passages) {
58
97
  if (passage.name !== 'StoryInit' && !passage.tags?.includes('widget')) {
59
98
  continue;
60
99
  }
61
- // The open definitions: their arguments, and whether a slot was seen
62
- const open: { rawArgs: string; isBlock: boolean }[] = [];
100
+ // The open definitions: their tags, and whether a slot was seen
101
+ const open: { token: MacroToken; isBlock: boolean; closeStart?: number }[] =
102
+ [];
103
+ const done: typeof open = [];
63
104
  for (const token of tokenizeMarkupTolerant(passage.content).tokens) {
64
105
  if (token.type === 'macro' && token.name.toLowerCase() === 'widget') {
65
106
  if (!token.isClose) {
66
- open.push({ rawArgs: token.rawArgs, isBlock: false });
67
- continue;
68
- }
69
- const def = open.pop();
70
- if (!def?.isBlock) continue;
71
- try {
72
- names.push(parseWidgetDef(def.rawArgs).name);
73
- } catch {
74
- // The {widget} macro reports a definition it cannot read
107
+ open.push({ token, isBlock: false });
108
+ } else {
109
+ const def = open.pop();
110
+ if (def) done.push({ ...def, closeStart: token.start });
75
111
  }
76
112
  } else if (
77
113
  open.length > 0 &&
@@ -83,6 +119,41 @@ export function blockWidgetNames(
83
119
  open[open.length - 1]!.isBlock = true;
84
120
  }
85
121
  }
122
+ done.push(...open);
123
+ const defs: WidgetDefinition[] = [];
124
+ for (const { token, isBlock, closeStart } of done) {
125
+ try {
126
+ const [from, to] = nameSpan(token.rawArgs);
127
+ defs.push({
128
+ ...parseWidgetDef(token.rawArgs),
129
+ block: isBlock,
130
+ passage: passage.name,
131
+ start: token.start,
132
+ end: token.end,
133
+ nameStart: token.argsStart + from,
134
+ nameEnd: token.argsStart + to,
135
+ ...(closeStart === undefined ? {} : { closeStart }),
136
+ });
137
+ } catch {
138
+ // The {widget} macro reports a definition it cannot read
139
+ }
140
+ }
141
+ found.push(...defs.sort((a, b) => a.start - b.start));
86
142
  }
87
- return names;
143
+ return found;
144
+ }
145
+
146
+ /**
147
+ * The names of the block widgets (those whose body renders `{@children}`)
148
+ * that StoryInit and the passages tagged `widget` define, closed. They must
149
+ * be known as block macros before any passage is parsed, so that passages
150
+ * invoking them nest their content whatever the passage order.
151
+ */
152
+ export function blockWidgetNames(
153
+ passages: Iterable<WidgetPassage>,
154
+ parametersOf: ParametersOf = registeredParameters,
155
+ ): string[] {
156
+ return widgetDefinitions(passages, parametersOf)
157
+ .filter((def) => def.block && def.closeStart !== undefined)
158
+ .map((def) => def.name);
88
159
  }