@rohal12/spindle 0.61.7 → 0.62.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.
package/src/js-lexer.ts CHANGED
@@ -26,6 +26,7 @@
26
26
  * be declared (`let _x`, `(_a) => …`) or be property names (`a.@x`), and
27
27
  * code must be valid modern JavaScript (a non-strict script).
28
28
  */
29
+ import type { Span } from './markup/tokens';
29
30
  import {
30
31
  Parser,
31
32
  tokTypes as tt,
@@ -496,15 +497,16 @@ function bracketsBefore(
496
497
  // Parsing: references, string text, errors
497
498
  // ---------------------------------------------------------------------------
498
499
 
499
- export interface VariableRef {
500
+ export interface VariableRef extends Span {
500
501
  sigil: Sigil;
501
502
  /** The name after the sigil. */
502
503
  name: string;
503
- /** Range of the sigil and name in the source. */
504
- start: number;
505
- end: number;
506
504
  /** A shorthand property (`{ $gold }`): its key is to be written out. */
507
505
  shorthand: boolean;
506
+ /** Whether evaluating this occurrence reads the binding. */
507
+ read: boolean;
508
+ /** Whether this occurrence assigns or deletes the binding itself (not a member). */
509
+ write: boolean;
508
510
  }
509
511
 
510
512
  export interface ParsedCode {
@@ -693,14 +695,19 @@ function walk(
693
695
  out: ParsedCode,
694
696
  binding: boolean,
695
697
  shorthand: boolean,
698
+ access: 'read' | 'write' | 'readwrite' = 'read',
696
699
  ): void {
697
700
  if (Array.isArray(node)) {
698
- for (const n of node) walk(n, src, out, binding, false);
701
+ for (const n of node) walk(n, src, out, binding, false, access);
699
702
  return;
700
703
  }
701
704
  if (!isNode(node)) return;
702
- const sub = (child: unknown, bind = false, short = false) =>
703
- walk(child, src, out, bind, short);
705
+ const sub = (
706
+ child: unknown,
707
+ bind = false,
708
+ short = false,
709
+ role: typeof access = 'read',
710
+ ) => walk(child, src, out, bind, short, role);
704
711
  switch (node.type) {
705
712
  case 'Identifier': {
706
713
  const sigil = sigilOf(node, src);
@@ -718,6 +725,8 @@ function walk(
718
725
  start: node.start,
719
726
  end: node.end,
720
727
  shorthand,
728
+ read: access !== 'write',
729
+ write: access !== 'read',
721
730
  });
722
731
  return;
723
732
  }
@@ -740,13 +749,13 @@ function walk(
740
749
  if (node.shorthand) {
741
750
  const value = node.value as AnyNode;
742
751
  if (value.type === 'AssignmentPattern') {
743
- sub(value.left, binding, true);
752
+ sub(value.left, binding, true, access);
744
753
  sub(value.right);
745
754
  } else {
746
- sub(value, binding, true);
755
+ sub(value, binding, true, access);
747
756
  }
748
757
  } else {
749
- sub(node.value, binding);
758
+ sub(node.value, binding, false, access);
750
759
  }
751
760
  return;
752
761
  case 'MethodDefinition':
@@ -784,15 +793,41 @@ function walk(
784
793
  sub(node.param, true);
785
794
  sub(node.body);
786
795
  return;
796
+ case 'AssignmentExpression':
797
+ sub(
798
+ node.left,
799
+ false,
800
+ false,
801
+ node.operator === '=' ? 'write' : 'readwrite',
802
+ );
803
+ sub(node.right);
804
+ return;
805
+ case 'UnaryExpression':
806
+ sub(
807
+ node.argument,
808
+ false,
809
+ false,
810
+ node.operator === 'delete' ? 'write' : 'read',
811
+ );
812
+ return;
813
+ case 'UpdateExpression':
814
+ sub(node.argument, false, false, 'readwrite');
815
+ return;
816
+ case 'ForInStatement':
817
+ case 'ForOfStatement':
818
+ sub(node.left, false, false, 'write');
819
+ sub(node.right);
820
+ sub(node.body);
821
+ return;
787
822
  case 'AssignmentPattern':
788
- sub(node.left, binding);
823
+ sub(node.left, binding, false, access);
789
824
  sub(node.right);
790
825
  return;
791
826
  case 'ObjectPattern':
792
827
  case 'ArrayPattern':
793
828
  case 'RestElement':
794
829
  for (const key of ['properties', 'elements', 'argument']) {
795
- sub(node[key], binding);
830
+ sub(node[key], binding, false, access);
796
831
  }
797
832
  return;
798
833
  default:
@@ -1,5 +1,5 @@
1
1
  import { glob, readFile, stat } from 'node:fs/promises';
2
- import { isAbsolute, relative, resolve, sep } from 'node:path';
2
+ import { resolve } from 'node:path';
3
3
  import { fileURLToPath } from 'node:url';
4
4
  import type * as TweeTs from '@rohal12/twee-ts';
5
5
  import { errorMessage } from '../utils/error-message';
@@ -61,57 +61,6 @@ async function expandGlob(pattern: string): Promise<string[]> {
61
61
  return matches.sort();
62
62
  }
63
63
 
64
- /** A path segment with glob syntax in it (as `path.matchesGlob` reads it). */
65
- const GLOB_SEGMENT = /[*?[\]{}()!+@]/;
66
-
67
- /**
68
- * An `exclude` glob of the project config as twee-ts matches it: against
69
- * paths relative to the working directory. A relative glob is relative to the
70
- * project directory; an absolute one has its literal leading folders made
71
- * relative. Either way the folder part added or rewritten is escaped.
72
- */
73
- function rebaseExclude(dir: string, pattern: string): string {
74
- let base = dir;
75
- let rest = pattern.replace(/^\.\//, '');
76
- if (isAbsolute(pattern)) {
77
- const parts = pattern.split('/');
78
- let literal = parts.findIndex((part) => GLOB_SEGMENT.test(part));
79
- if (literal === -1) literal = parts.length;
80
- base = parts.slice(0, literal).join('/') || '/';
81
- rest = parts.slice(literal).join('/');
82
- }
83
- const fromCwd = globLiteral(
84
- relative(process.cwd(), base).split(sep).join('/'),
85
- );
86
- if (fromCwd === '') return rest;
87
- return rest === '' ? fromCwd : `${fromCwd}/${rest}`;
88
- }
89
-
90
- /**
91
- * The project config with its paths made independent of the working
92
- * directory. twee-ts reads `sources`, `modules` and `headFile` relative to
93
- * the working directory, and matches `exclude` globs against paths relative
94
- * to it, so each is rebased from the project directory.
95
- */
96
- function rebaseConfig(
97
- dir: string,
98
- config: TweeTs.TweeTsConfig,
99
- ): TweeTs.TweeTsConfig {
100
- const rebased: TweeTs.TweeTsConfig = {
101
- ...config,
102
- sources: (config.sources ?? ['.']).map((s) => resolve(dir, s)),
103
- };
104
- if (config.modules)
105
- rebased.modules = config.modules.map((m) => resolve(dir, m));
106
- if (config.headFile !== undefined) {
107
- rebased.headFile = resolve(dir, config.headFile);
108
- }
109
- if (config.exclude) {
110
- rebased.exclude = config.exclude.map((e) => rebaseExclude(dir, e));
111
- }
112
- return rebased;
113
- }
114
-
115
64
  /**
116
65
  * The project config less its output and format options. Those are ours: the
117
66
  * project's own would write a file, compile for another format, or fetch one.
@@ -130,15 +79,6 @@ function withoutFormatOptions(
130
79
  );
131
80
  }
132
81
 
133
- /**
134
- * `text` as a glob matching only itself, for Node's `path.matchesGlob` (which
135
- * twee-ts uses): a metacharacter goes in brackets. Braces and `!` cannot be
136
- * bracketed there, so each becomes `?` (any one character).
137
- */
138
- function globLiteral(text: string): string {
139
- return text.replace(/[*?[\]()+@]/g, (c) => `[${c}]`).replace(/[{}!]/g, '?');
140
- }
141
-
142
82
  /** The compile sources and project config for a path (or glob). */
143
83
  async function sourcesFor(
144
84
  tweeTs: TweeTsModule,
@@ -163,11 +103,13 @@ async function sourcesFor(
163
103
  if (!isDirectory) return { sources: [path], config: {} };
164
104
  const found = tweeTs.loadConfig(path);
165
105
  if (!found) return { sources: [path], config: {} };
166
- const config = rebaseConfig(resolve(path), found);
106
+ // twee-ts resolves config paths and structured excludes against the project
107
+ // directory itself. Rebasing them again would duplicate relative prefixes.
108
+ const config = found;
167
109
  if (config.sources?.length === 0) {
168
110
  throw new Error(`spindle: ${path} has a twee-ts config with no sources`);
169
111
  }
170
- return { sources: config.sources ?? [], config };
112
+ return { sources: [...(config.sources ?? [resolve(path)])], config };
171
113
  }
172
114
 
173
115
  /** The diagnostics a thrown twee-ts error carries, when it has any. */
package/src/tooling.ts CHANGED
@@ -55,13 +55,24 @@ export type {
55
55
  } from './story-variables';
56
56
  export { checkParameterTypes } from './registry';
57
57
  export { formatDiagnostic } from './markup/validate';
58
- export { parseWidgetDef } from './widgets/widget-def';
58
+ export {
59
+ effectiveWidgetDefinitions,
60
+ parseWidgetDef,
61
+ } from './widgets/widget-def';
59
62
  export type { WidgetDef, WidgetDefinition } from './widgets/widget-def';
60
63
 
61
64
  // The parsing rules (see "Tooling API" in docs/tooling.md): the leaf rules
62
65
  // the runtime parses with, so editor tooling needn't mirror them.
63
- export { findCodeEnd, lexJs, lexTemplate, scanStringLiteral } from './js-lexer';
66
+ export {
67
+ findCodeEnd,
68
+ lexJs,
69
+ lexTemplate,
70
+ parseCode,
71
+ scanStringLiteral,
72
+ } from './js-lexer';
64
73
  export type {
74
+ ParsedCode,
75
+ VariableRef,
65
76
  FindCodeEndOptions,
66
77
  JsGoal,
67
78
  JsLexHandlers,
@@ -116,10 +127,14 @@ export {
116
127
  } from './components/macros/arg-utils';
117
128
  export { splitIncludeFlag } from './components/macros/include-args';
118
129
  export {
130
+ macroArgumentSpans,
119
131
  evaluatePassageName,
120
132
  passageTarget,
121
133
  } from './components/macros/macro-args';
122
- export type { PassageTarget } from './components/macros/macro-args';
134
+ export type {
135
+ MacroArgumentSpan,
136
+ PassageTarget,
137
+ } from './components/macros/macro-args';
123
138
  export { transform } from './transform';
124
139
  export type {
125
140
  ArgumentErrorPiece,
@@ -164,13 +179,13 @@ export interface ToolingMacro {
164
179
  * Its declared parameters: their types tell which arguments are code, and
165
180
  * what a `string` or `text` argument holds (see ParameterDef.holds).
166
181
  */
182
+ parameters?: readonly ParameterDef[];
167
183
  /**
168
184
  * For a widget: its `@` parameters and what the ones that declare it hold
169
185
  * (`@target:passage`, see WidgetDef), so that a call is checked like the
170
186
  * call of a macro whose `string` parameter has that `holds`.
171
187
  */
172
188
  widget?: Pick<WidgetDef, 'params' | 'holds'>;
173
- parameters?: readonly ParameterDef[];
174
189
  /** Whether it resolves markup: its strings hold markup by default. */
175
190
  interpolate?: boolean;
176
191
  /** Whether its first argument names the story variable it binds. */
@@ -86,12 +86,26 @@ const _publishedToSource: Source = {} as Published;
86
86
  /** `true` if `A` and `B` are assignable to each other, else `false`. */
87
87
  type Same<A, B> = [A] extends [B] ? ([B] extends [A] ? true : false) : false;
88
88
 
89
+ /** Also catch missing optional fields, which mutual assignability allows. */
90
+ type SameShape<A, B> = Same<A, B> extends true ? Same<keyof A, keyof B> : false;
91
+
89
92
  // The rest of the tooling entry point: what it parses and returns (tokens,
90
93
  // pieces, pairing, declarations) and the stateless checks. Each must be the
91
94
  // same type in the source and in types/tooling.d.ts, or `false` here is no
92
95
  // `true`.
93
96
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
94
- const _toolingTypes: [
97
+ type AssertTrue<T extends readonly true[]> = T;
98
+ type ToolingChecks = [
99
+ Same<typeof SourceTooling.parseCode, typeof PublishedTooling.parseCode>,
100
+ Same<
101
+ typeof SourceTooling.macroArgumentSpans,
102
+ typeof PublishedTooling.macroArgumentSpans
103
+ >,
104
+ Same<
105
+ typeof SourceTooling.effectiveWidgetDefinitions,
106
+ typeof PublishedTooling.effectiveWidgetDefinitions
107
+ >,
108
+ SameShape<SourceTooling.WidgetDefinition, PublishedTooling.WidgetDefinition>,
95
109
  Same<SourceTooling.MarkupError, PublishedTooling.MarkupError>,
96
110
  Same<SourceTooling.Token, PublishedTooling.Token>,
97
111
  Same<SourceTooling.Piece, PublishedTooling.Piece>,
@@ -99,7 +113,7 @@ const _toolingTypes: [
99
113
  Same<SourceTooling.PairingError, PublishedTooling.PairingError>,
100
114
  Same<SourceTooling.Declaration, PublishedTooling.Declaration>,
101
115
  Same<SourceTooling.DeclarationError, PublishedTooling.DeclarationError>,
102
- Same<SourceTooling.ToolingMacro, PublishedTooling.ToolingMacro>,
116
+ SameShape<SourceTooling.ToolingMacro, PublishedTooling.ToolingMacro>,
103
117
  Same<typeof SourceTooling.pairMarkup, typeof PublishedTooling.pairMarkup>,
104
118
  Same<
105
119
  typeof SourceTooling.passagePieces,
@@ -139,28 +153,8 @@ const _toolingTypes: [
139
153
  typeof SourceTooling.formatPassage,
140
154
  typeof PublishedTooling.formatPassage
141
155
  >,
142
- ] = [
143
- true,
144
- true,
145
- true,
146
- true,
147
- true,
148
- true,
149
- true,
150
- true,
151
- true,
152
- true,
153
- true,
154
- true,
155
- true,
156
- true,
157
- true,
158
- true,
159
- true,
160
- true,
161
- true,
162
- true,
163
156
  ];
157
+ type _toolingTypes = AssertTrue<ToolingChecks>;
164
158
 
165
159
  // A typical custom macro written against the published types must type-check,
166
160
  // and misuse of the hooks must not (no `any` leaking through).
@@ -120,7 +120,7 @@ export interface VariableSchema extends FieldSchema {
120
120
  * Parse the content of a `StoryVariables` (`$name = value`) or
121
121
  * `StoryTransients` (`%name = value`, pass `sigil: '%'`) passage into a
122
122
  * schema map, exactly as Spindle does at boot.
123
- * Throws on invalid declarations or unsupported value types (e.g. `null`).
123
+ * Throws on invalid declarations or unsupported value types (e.g. `undefined`).
124
124
  */
125
125
  export declare function parseStoryVariables(
126
126
  content: string,
@@ -534,10 +534,12 @@ export declare function splitTopLevel(
534
534
  * Read the `"…"` or `'…'` string whose opening quote is at `start`: its
535
535
  * unescaped value (`\"`, `\'` and `\\` only) and the index just past it, or
536
536
  * `null` if there is none or it is unterminated.
537
+ * With `tolerant`, an unterminated string instead extends to its scanned end.
537
538
  */
538
539
  export declare function readQuoted(
539
540
  src: string,
540
541
  start: number,
542
+ tolerant?: boolean,
541
543
  ): { value: string; end: number } | null;
542
544
 
543
545
  /** Undo `\"`, `\'` and `\\` in the body of a quoted macro argument. */
@@ -653,6 +655,8 @@ export interface ToolingMacro {
653
655
  name: string;
654
656
  block: boolean;
655
657
  subMacros: string[];
658
+ /** A widget's parameters and their argument contracts. */
659
+ widget?: Pick<WidgetDef, 'params' | 'holds'>;
656
660
  /**
657
661
  * Its declared parameters: their types tell which arguments are code, and
658
662
  * what a `string` or `text` argument holds (see `ParameterDef.holds`).
@@ -777,6 +781,8 @@ export interface WidgetDef {
777
781
  name: string;
778
782
  /** The `@` parameters. */
779
783
  params: string[];
784
+ holds?: Record<string, StringHolds>;
785
+ badHolds?: { param: string; written: string }[];
780
786
  }
781
787
 
782
788
  /**
@@ -1186,3 +1192,52 @@ export declare function formatPassage(
1186
1192
  body: string,
1187
1193
  options?: PassageFormatOptions,
1188
1194
  ): Promise<string>;
1195
+
1196
+ /** The runtime's selected closed widgets, preserving input object identities.
1197
+ * Tagged passages register before StoryInit; later names replace earlier ones
1198
+ * case-insensitively. Map definitions to documents before calling this function.
1199
+ */
1200
+ export declare function effectiveWidgetDefinitions(
1201
+ definitions: readonly WidgetDefinition[],
1202
+ ): WidgetDefinition[];
1203
+
1204
+ /** One executable sigil reference, with UTF-16 offsets into the code. */
1205
+ export interface VariableRef {
1206
+ sigil: Sigil;
1207
+ name: string;
1208
+ start: number;
1209
+ end: number;
1210
+ shorthand: boolean;
1211
+ read: boolean;
1212
+ write: boolean;
1213
+ }
1214
+
1215
+ export interface ParsedCode {
1216
+ refs: VariableRef[];
1217
+ strings: string[];
1218
+ }
1219
+
1220
+ /** Parse executable code using the runtime grammar. Throws for malformed code
1221
+ * (including sigil declarations); lexJs remains available for tolerant scanning.
1222
+ * Member assignments read their root binding; only direct targets write it.
1223
+ */
1224
+ export declare function parseCode(src: string, goal?: JsGoal): ParsedCode;
1225
+
1226
+ /** A consumed argument and its original parameter (including option keywords). */
1227
+ export interface MacroArgumentSpan {
1228
+ parameter: ParameterDef;
1229
+ parameterIndex: number;
1230
+ parameterPath: number[];
1231
+ start: number;
1232
+ end: number;
1233
+ }
1234
+
1235
+ /** Runtime argument grouping, tolerant of missing/unclosed strings. UTF-16
1236
+ * offsets include quotes, flags, separators and option keywords. Absent
1237
+ * arguments have no span. Options also have an enclosing parameter span.
1238
+ * No expressions are evaluated; parameter object identities are preserved.
1239
+ */
1240
+ export declare function macroArgumentSpans(
1241
+ rawArgs: string,
1242
+ parameters: readonly ParameterDef[],
1243
+ ): MacroArgumentSpan[];