@rohal12/spindle 0.59.22 → 0.59.23

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
1
  import type { Passage } from './parser';
2
- import type { Token } from './markup/tokens';
2
+ import type { Spans, Token } from './markup/tokens';
3
3
  import { MarkupError, tokenizeMarkup } from './markup/parse';
4
4
  import { isCodeAttribute, splitSigilTemplate } from './markup/code-attributes';
5
5
  import { errorMessage } from './utils/error-message';
@@ -18,6 +18,7 @@ import {
18
18
  import { getMacroParameters, type ParameterDef } from './registry';
19
19
  import { NOT_MARKUP } from './markup/validate';
20
20
  import { createNamespace, variableNameError } from './utils/namespace';
21
+ import { staticLiteral, type LiteralShape } from './static-literal';
21
22
 
22
23
  /**
23
24
  * The tokens of markup, or none if it is malformed: validateMarkup reports
@@ -102,32 +103,169 @@ function inferSchema(
102
103
  return { type: jsType as VarType };
103
104
  }
104
105
 
106
+ /** What is wrong with a declaration (see DeclarationError). */
107
+ export type DeclarationErrorCode =
108
+ | 'invalid-declaration'
109
+ | 'invalid-name'
110
+ | 'duplicate-declaration'
111
+ | 'unsupported-value';
112
+
105
113
  /**
106
- * Parse a StoryVariables or StoryTransients passage content into a schema map.
107
- * Each line: `$varName = expression` (or `%varName = expression` for transients)
114
+ * A declaration of a StoryVariables or StoryTransients passage: the name
115
+ * (without the sigil) and the initializer expression (without surrounding
116
+ * space) are written from `nameStart` to `nameEnd` and from `valueStart` to
117
+ * `valueEnd` (UTF-16 offsets).
108
118
  */
109
- export function parseStoryVariables(
119
+ export interface Declaration extends Spans<'name'>, Spans<'value'> {
120
+ name: string;
121
+ /**
122
+ * The shape of the initializer when it is static: a literal, or an array or
123
+ * object literal of them (an object has the members that are static).
124
+ * Absent when it is not.
125
+ */
126
+ schema?: FieldSchema;
127
+ }
128
+
129
+ /**
130
+ * An invalid line of a StoryVariables or StoryTransients passage, from
131
+ * `offset` up to `end` (UTF-16 offsets into the content).
132
+ */
133
+ export interface DeclarationError extends Record<'offset' | 'end', number> {
134
+ code: DeclarationErrorCode;
135
+ /** What is wrong, as parseStoryVariables throws it after the passage name. */
136
+ message: string;
137
+ }
138
+
139
+ const UNSUPPORTED_TYPE = 'Expected number, string, boolean, array, or object.';
140
+
141
+ /** The schema of a literal shape (see staticLiteral). */
142
+ function shapeSchema(shape: LiteralShape): FieldSchema {
143
+ if (!shape.fields) return { type: shape.type };
144
+ const fields = new Map<string, FieldSchema>();
145
+ for (const [key, member] of shape.fields)
146
+ fields.set(key, shapeSchema(member));
147
+ return { type: shape.type, fields };
148
+ }
149
+
150
+ /**
151
+ * Read the declarations of a StoryVariables (`$name = value`) or
152
+ * StoryTransients (`%name = value`) passage, without evaluating them and
153
+ * without throwing: every valid declaration, and every invalid line as an
154
+ * error. It is the grammar parseStoryVariables reads with.
155
+ *
156
+ * A declaration is a line of the form `$name = expression`; blank lines are
157
+ * skipped. A line that is not, and a name that cannot be a variable, are
158
+ * errors. So is an initializer that no variable can hold (a function,
159
+ * `undefined`), when it is a literal; whether any other initializer can only
160
+ * be known by running it. A name declared again is an error too, but both
161
+ * declarations are returned (the later wins when evaluated).
162
+ */
163
+ export function parseDeclarations(
110
164
  content: string,
111
165
  sigil: '$' | '%' = '$',
112
- ): Map<string, VariableSchema> {
113
- const schema = new Map<string, VariableSchema>();
166
+ ): { declarations: Declaration[]; errors: DeclarationError[] } {
167
+ const declarations: Declaration[] = [];
168
+ const errors: DeclarationError[] = [];
114
169
  const DECLARATION_RE = declarationRegex(sigil);
115
- const passageName = sigil === '%' ? 'StoryTransients' : 'StoryVariables';
170
+ const seen = new Set<string>();
116
171
 
172
+ let lineStart = 0;
117
173
  for (const rawLine of content.split('\n')) {
174
+ const at = lineStart + rawLine.length - rawLine.trimStart().length;
175
+ lineStart += rawLine.length + 1;
118
176
  const line = rawLine.trim();
119
177
  if (!line) continue;
120
178
 
121
179
  const match = line.match(DECLARATION_RE);
180
+ const error = (
181
+ code: DeclarationErrorCode,
182
+ start: number,
183
+ end: number,
184
+ message: string,
185
+ ) => errors.push({ code, offset: start, end, message });
122
186
  if (!match) {
123
- throw new Error(
124
- `${passageName}: Invalid declaration: "${line}". Expected: ${sigil}name = value`,
187
+ error(
188
+ 'invalid-declaration',
189
+ at,
190
+ at + line.length,
191
+ `Invalid declaration: "${line}". Expected: ${sigil}name = value`,
125
192
  );
193
+ continue;
126
194
  }
127
195
 
128
196
  const [, name, expr] = match as [string, string, string];
197
+ const nameStart = at + sigil.length;
198
+ const nameEnd = nameStart + name.length;
129
199
  const nameError = variableNameError(name, sigil + name);
130
- if (nameError) throw new Error(`${passageName}: ${nameError}`);
200
+ if (nameError) {
201
+ error('invalid-name', nameStart, nameEnd, nameError);
202
+ continue;
203
+ }
204
+ const valueEnd = at + line.length;
205
+ const declaration: Declaration = {
206
+ name,
207
+ nameStart,
208
+ nameEnd,
209
+ valueStart: valueEnd - expr.length,
210
+ valueEnd,
211
+ };
212
+ if (seen.has(name)) {
213
+ error(
214
+ 'duplicate-declaration',
215
+ nameStart,
216
+ nameEnd,
217
+ `Duplicate declaration of ${sigil}${name}`,
218
+ );
219
+ }
220
+ seen.add(name);
221
+ const literal = staticLiteral(expr);
222
+ if (literal && 'shape' in literal) {
223
+ declaration.schema = shapeSchema(literal.shape);
224
+ } else if (literal) {
225
+ error(
226
+ 'unsupported-value',
227
+ declaration.valueStart,
228
+ valueEnd,
229
+ `Unsupported type "${literal.unsupported}" for value ${expr}. ${UNSUPPORTED_TYPE}`,
230
+ );
231
+ }
232
+ declarations.push(declaration);
233
+ }
234
+ return { declarations, errors };
235
+ }
236
+
237
+ /**
238
+ * Parse a StoryVariables or StoryTransients passage content into a schema map.
239
+ * Each line: `$varName = expression` (or `%varName = expression` for transients)
240
+ * The expressions are evaluated; parseDeclarations reads the same lines
241
+ * without.
242
+ */
243
+ export function parseStoryVariables(
244
+ content: string,
245
+ sigil: '$' | '%' = '$',
246
+ ): Map<string, VariableSchema> {
247
+ const schema = new Map<string, VariableSchema>();
248
+ const passageName = sigil === '%' ? 'StoryTransients' : 'StoryVariables';
249
+ const { declarations, errors } = parseDeclarations(content, sigil);
250
+
251
+ // Lines in order: the first that is invalid, or that cannot be evaluated,
252
+ // is the error. What parseDeclarations reports about a value that is
253
+ // evaluated here is left to the evaluation (its wording is the runtime's).
254
+ const lines = [
255
+ ...errors
256
+ .filter(
257
+ (e) => e.code === 'invalid-declaration' || e.code === 'invalid-name',
258
+ )
259
+ .map((e) => ({ at: e.offset, error: e })),
260
+ ...declarations.map((d) => ({ at: d.nameStart, declaration: d })),
261
+ ].sort((a, b) => a.at - b.at);
262
+
263
+ for (const line of lines) {
264
+ if ('error' in line) {
265
+ throw new Error(`${passageName}: ${line.error.message}`);
266
+ }
267
+ const { name, valueStart, valueEnd } = line.declaration;
268
+ const expr = content.slice(valueStart, valueEnd);
131
269
  let value: unknown;
132
270
  try {
133
271
  value = new Function('return (' + expr + ')')();
package/src/tooling.ts CHANGED
@@ -12,14 +12,25 @@ 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
22
  import { blockWidgetNames } from './widgets/widget-def';
20
23
  import type { ParameterDef } from './registry';
21
24
 
22
- export { parseStoryVariables } from './story-variables';
25
+ export { parseDeclarations, parseStoryVariables } from './story-variables';
26
+ export type {
27
+ Declaration,
28
+ DeclarationError,
29
+ DeclarationErrorCode,
30
+ FieldSchema,
31
+ VarType,
32
+ VariableSchema,
33
+ } from './story-variables';
23
34
  export { checkParameterTypes } from './registry';
24
35
  export { formatDiagnostic } from './markup/validate';
25
36
 
@@ -40,7 +51,32 @@ export {
40
51
  } from './markup/parse';
41
52
  export type { ParseMarkupOptions, TolerantTokens } from './markup/parse';
42
53
  export { SIGIL_SCOPES, isSigil } from './markup/tokens';
43
- export type { Selectors, Token, VariableScope } from './markup/tokens';
54
+ export type {
55
+ AttributeSpan,
56
+ ExpressionToken,
57
+ HtmlToken,
58
+ LinkToken,
59
+ MacroToken,
60
+ SelectorSpan,
61
+ Selectors,
62
+ TextToken,
63
+ Token,
64
+ VariableScope,
65
+ VariableToken,
66
+ } from './markup/tokens';
67
+ export { pairMarkup } from './markup/pair';
68
+ export { pieceOffset };
69
+ export type {
70
+ PairedBody,
71
+ PairedBranch,
72
+ PairedMarkup,
73
+ PairedNode,
74
+ PairingError,
75
+ PairingErrorCode,
76
+ PairMarkupOptions,
77
+ } from './markup/pair';
78
+ export { isBlockMacro } from './markup/ast';
79
+ export type { MarkupErrorCode } from './markup/parse';
44
80
  export {
45
81
  endsWithOperator,
46
82
  readQuoted,
@@ -56,8 +92,21 @@ export {
56
92
  } from './components/macros/macro-args';
57
93
  export type { PassageTarget } from './components/macros/macro-args';
58
94
  export { transform } from './transform';
59
- export type { PassageReference } from './code-check';
60
- export type { MarkupDiagnostic, MarkupPassage } from './markup/validate';
95
+ export type {
96
+ ArgumentErrorPiece,
97
+ CodePiece,
98
+ PassagePiece,
99
+ PassageReference,
100
+ Piece,
101
+ PieceBase,
102
+ TextPiece,
103
+ } from './code-check';
104
+ export type {
105
+ MarkupDiagnostic,
106
+ MarkupDiagnosticCode,
107
+ MarkupDiagnosticData,
108
+ MarkupPassage,
109
+ } from './markup/validate';
61
110
 
62
111
  /** What tooling knows about a macro (see MacroMetadata). */
63
112
  /** Options for validating markup from tooling. */
@@ -117,15 +166,47 @@ export function validateStoryMarkup(
117
166
  });
118
167
  }
119
168
 
169
+ /** Whether a macro takes a body, among `macros` and the built-in ones. */
170
+ function blockLookup(macros: readonly ToolingMacro[]) {
171
+ const blocks = new Set(
172
+ macros.filter((m) => m.block).map((m) => m.name.toLowerCase()),
173
+ );
174
+ return (name: string) => blocks.has(name.toLowerCase()) || isBlockMacro(name);
175
+ }
176
+
177
+ /**
178
+ * What a passage's markup runs and names, and where: the pieces of code
179
+ * (`{$expr}` displays, `{do}` bodies, conditions, macro arguments by their
180
+ * declared parameter types, strings that hold code), the passage names written
181
+ * out (links, `passage` arguments), the texts that hold markup of their own
182
+ * (labels, attribute values) and the arguments that don't have their
183
+ * parameters' forms, in source order with offsets (UTF-16) into `source`. The
184
+ * markup in a text follows it, as pieces marked `nested` with offsets into
185
+ * `source` too. Malformed tags are skipped, so it reads half-typed markup.
186
+ * The macros are those the markup may use, built-in and user-defined.
187
+ */
188
+ export function passagePieces(
189
+ source: string,
190
+ macros: Iterable<ToolingMacro> = [],
191
+ ): Piece[] {
192
+ const all = [...macros];
193
+ const { tokens } = tokenizeMarkupTolerant(source);
194
+ return [
195
+ ...passagePiecesOf(source, tokens, parameterLookup(all), {
196
+ isBlock: blockLookup(all),
197
+ }),
198
+ ];
199
+ }
200
+
120
201
  /**
121
202
  * The passages the markup of `source` names (see PassageReference), against
122
203
  * the given macros: what the story-start check looks up. Malformed tags are
123
- * skipped, so it reads half-typed markup.
204
+ * skipped, so it reads half-typed markup. It is `passagePieces`, less what
205
+ * names no passage.
124
206
  */
125
207
  export function collectStoryPassageReferences(
126
208
  source: string,
127
209
  macros: Iterable<ToolingMacro>,
128
210
  ): PassageReference[] {
129
- const { tokens } = tokenizeMarkupTolerant(source);
130
- return collectPassageReferences(source, tokens, parameterLookup(macros));
211
+ return referencesOf(passagePieces(source, macros));
131
212
  }
@@ -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)