@rohal12/spindle 0.62.8 → 0.63.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.
@@ -15,6 +15,7 @@ export {
15
15
  pieceOffset,
16
16
  pairMarkup,
17
17
  isBlockMacro,
18
+ isSpecialPassage,
18
19
  parseStoryVariables,
19
20
  parseDeclarations,
20
21
  formatDiagnostic,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rohal12/spindle",
3
- "version": "0.62.8",
3
+ "version": "0.63.0",
4
4
  "type": "module",
5
5
  "description": "A Preact-based story format for Twine 2.",
6
6
  "license": "Unlicense",
package/src/code-check.ts CHANGED
@@ -50,6 +50,7 @@ import { NameMap } from './utils/macro-names';
50
50
  import { hasOwn } from './utils/namespace';
51
51
  import { isRawMacro } from './markup/ast';
52
52
  import { sourcePositions } from './markup/line-column';
53
+ import { MarkupExpansionBudget } from './markup/expansion-budget';
53
54
 
54
55
  /** While a pass runs: the code it parsed so far, by goal and source. */
55
56
  let parses: Map<string, ParsedCode | CodeSyntaxError> | null = null;
@@ -156,6 +157,8 @@ interface MacroPiece extends LabeledPiece {
156
157
  export interface PassagePiece extends MacroPiece {
157
158
  kind: 'passage';
158
159
  name: string;
160
+ /** A known navigation target, rather than included/dialog content. */
161
+ navigation?: true;
159
162
  }
160
163
 
161
164
  /**
@@ -387,6 +390,9 @@ export function* codeAndText(
387
390
  offset: token.targetStart,
388
391
  length: token.targetEnd - token.targetStart,
389
392
  macro: 'link',
393
+ ...(usesBuiltinSemantics('link', parametersOf) && {
394
+ navigation: true as const,
395
+ }),
390
396
  label: src.slice(token.start, token.end),
391
397
  };
392
398
  // The label is markup too (the link renders as `{link}`)
@@ -479,7 +485,16 @@ export function* codeAndText(
479
485
  continue;
480
486
  }
481
487
  const params = parametersOf(name);
482
- if (params) yield* argPieces(args, argsAt, params, token.name, label);
488
+ if (params) {
489
+ const navigation = usesBuiltinSemantics(name, parametersOf)
490
+ ? name === 'goto' || name === 'link'
491
+ ? ['passage']
492
+ : name === 'watch'
493
+ ? ['goto']
494
+ : []
495
+ : [];
496
+ yield* argPieces(args, argsAt, params, token.name, label, navigation);
497
+ }
483
498
  if (widget) yield* widgetPieces(args, argsAt, widget, token.name, label);
484
499
  }
485
500
  }
@@ -518,6 +533,7 @@ export function* passagePiecesOf(
518
533
  (i) => i,
519
534
  undefined,
520
535
  locate,
536
+ new MarkupExpansionBudget(src.length),
521
537
  );
522
538
  }
523
539
 
@@ -535,6 +551,7 @@ function* expand(
535
551
  toRoot: (offset: number) => number,
536
552
  where: string | undefined,
537
553
  locate: ReturnType<typeof sourcePositions>,
554
+ budget: MarkupExpansionBudget,
538
555
  ): Generator<Piece> {
539
556
  for (const flat of codeAndText(src, tokens, parametersOf)) {
540
557
  const piece = where ? nestedPiece(flat, toRoot, where) : flat;
@@ -543,41 +560,67 @@ function* expand(
543
560
  continue;
544
561
  }
545
562
  // The text may not be where its length says: a string with escapes
546
- const toText = (i: number) => toRoot(pieceOffset(flat, i));
547
- const inner = analyzeMarkup(flat.text, {
548
- text: true,
549
- hooks: {
550
- ...(options.isBlock && { isBlock: options.isBlock }),
551
- isRaw: (name) =>
552
- isRawMacro(name, parametersOf.widget?.(name) !== undefined),
553
- },
554
- });
555
- yield {
556
- ...(piece as TextPiece),
557
- tokens: inner.tokens.map((t) => mapOffsets(t, toText)),
558
- errors: inner.errors.map((e) => {
559
- const { line, column } = locate(toText(e.offset));
560
- return new MarkupError(
561
- e.reason,
562
- toText(e.offset),
563
- line,
564
- column,
565
- e.code,
566
- toText(e.end),
567
- e.data,
568
- );
569
- }),
570
- };
571
- yield* expand(
572
- root,
573
- flat.text,
574
- inner.tokens,
575
- parametersOf,
576
- options,
577
- toText,
578
- flat.where,
579
- locate,
580
- );
563
+ // nestedPiece flattened the offsets into the root source. Avoid composing
564
+ // a recursive mapping closure for every enclosing label.
565
+ const toText = (i: number) => pieceOffset(piece, i);
566
+ if (!budget.enter(flat.text.length)) {
567
+ const at = toText(0);
568
+ const { line, column } = locate(at);
569
+ yield {
570
+ ...(piece as TextPiece),
571
+ errors: [
572
+ new MarkupError(
573
+ 'Markup in labels and attributes exceeds the nesting or work limit',
574
+ at,
575
+ line,
576
+ column,
577
+ 'nesting-limit',
578
+ toText(flat.text.length),
579
+ { limit: String(MarkupExpansionBudget.maxDepth) },
580
+ ),
581
+ ],
582
+ };
583
+ continue;
584
+ }
585
+ try {
586
+ const inner = analyzeMarkup(flat.text, {
587
+ text: true,
588
+ hooks: {
589
+ ...(options.isBlock && { isBlock: options.isBlock }),
590
+ isRaw: (name) =>
591
+ isRawMacro(name, parametersOf.widget?.(name) !== undefined),
592
+ },
593
+ });
594
+ yield {
595
+ ...(piece as TextPiece),
596
+ tokens: inner.tokens.map((t) => mapOffsets(t, toText)),
597
+ errors: inner.errors.map((e) => {
598
+ const { line, column } = locate(toText(e.offset));
599
+ return new MarkupError(
600
+ e.reason,
601
+ toText(e.offset),
602
+ line,
603
+ column,
604
+ e.code,
605
+ toText(e.end),
606
+ e.data,
607
+ );
608
+ }),
609
+ };
610
+ yield* expand(
611
+ root,
612
+ flat.text,
613
+ inner.tokens,
614
+ parametersOf,
615
+ options,
616
+ toText,
617
+ flat.where,
618
+ locate,
619
+ budget,
620
+ );
621
+ } finally {
622
+ budget.leave();
623
+ }
581
624
  }
582
625
  }
583
626
 
@@ -676,6 +719,7 @@ export function* argPieces(
676
719
  params: readonly ParameterDef[],
677
720
  macro: string,
678
721
  label: string,
722
+ navigation: readonly string[] = [],
679
723
  ): Generator<Piece> {
680
724
  let values: Record<string, unknown>;
681
725
  const spans: ArgSpans = new Map();
@@ -702,6 +746,7 @@ export function* argPieces(
702
746
  macro,
703
747
  label,
704
748
  'quotes',
749
+ navigation,
705
750
  );
706
751
  }
707
752
 
@@ -757,6 +802,7 @@ function* valuePieces(
757
802
  macro: string,
758
803
  label: string,
759
804
  escapes: Escapes,
805
+ navigation: readonly string[] = [],
760
806
  ): Generator<Piece> {
761
807
  const name = macro.toLowerCase();
762
808
  /** The pieces of the parameters `list`, with their values in `from`. */
@@ -785,6 +831,7 @@ function* valuePieces(
785
831
  length: end - start,
786
832
  macro: name,
787
833
  label,
834
+ ...(navigation.includes(param.name) && { navigation: true as const }),
788
835
  });
789
836
  const goal = codeGoal(param);
790
837
  if (param.type === 'passage') {
@@ -1,5 +1,6 @@
1
1
  import { useStoryStore } from '../../store';
2
2
  import { evaluate } from '../../expression';
3
+ import { parseReferencePath } from '../../js-lexer';
3
4
  import { readState } from '../../execute-mutation';
4
5
  import { deepEqualStrict } from '../../structural';
5
6
  import { defineMacro } from '../../define-macro';
@@ -27,14 +28,15 @@ function assignmentArgs(
27
28
  }
28
29
 
29
30
  const { target = '', expression: expr = '' } = args;
30
- if (!target.match(/^[$_@]\w+$/)) {
31
+ const path = parseReferencePath(target);
32
+ if (!path || path.nested || path.sigil === '%') {
31
33
  throw new Error(
32
34
  `{computed}: target must be $name, _name, or @name, got "${target}"`,
33
35
  );
34
36
  }
35
37
 
36
- checkVariableName(target.slice(1), target);
37
- return { target, expr };
38
+ checkVariableName(path.name, target);
39
+ return { target: path.sigil + path.name, expr };
38
40
  }
39
41
 
40
42
  /**
@@ -5,6 +5,7 @@ import { VARIABLE_PARAMETER, useVariableAction } from './input-macro';
5
5
  defineMacro({
6
6
  name: 'cycle',
7
7
  block: true,
8
+ subMacros: ['option'],
8
9
  interpolate: true,
9
10
  storeVar: true,
10
11
  parameters: [VARIABLE_PARAMETER],
@@ -288,7 +288,8 @@ async function formatLf(
288
288
  // Prettier cannot see a `white-space` style. Leave such HTML as written.
289
289
  if (
290
290
  WHITESPACE_AS_WRITTEN.test(htmlText) ||
291
- region.lines.some((line) => literalLines.has(line.trim()))
291
+ region.lines.some((line) => literalLines.has(line.trim())) ||
292
+ hasMarkdownBoundaries(htmlText, isBlock)
292
293
  ) {
293
294
  for (let i = 0; i < region.lines.length; i++)
294
295
  preservedLines.add(lines.length + i);
@@ -378,6 +379,41 @@ async function formatLf(
378
379
  /** Literal HTML and opaque SVG, whose text can inherit significant whitespace. */
379
380
  const WHITESPACE_AS_WRITTEN = /<(?:pre|textarea|svg)[\s>]|white-space\s*:/i;
380
381
 
382
+ /** HTML whitespace formatting must not collapse the Markdown in its bodies. */
383
+ const HTML_MARKDOWN_BOUNDARIES = new Set([
384
+ 'hardBreakTrailing',
385
+ 'hardBreakEscape',
386
+ 'atxHeading',
387
+ 'setextHeading',
388
+ 'listOrdered',
389
+ 'listUnordered',
390
+ 'blockQuote',
391
+ 'thematicBreak',
392
+ 'definition',
393
+ 'table',
394
+ 'codeFenced',
395
+ ]);
396
+
397
+ function hasMarkdownBoundaries(
398
+ source: string,
399
+ isBlock: (name: string) => boolean,
400
+ ): boolean {
401
+ const { tokens } = analyzeMarkup(source, { hooks: { isBlock } });
402
+ let possibleBoundary = false;
403
+ for (const token of tokens) {
404
+ if (token.type !== 'text') continue;
405
+ if (/\n[ \t]*\n/.test(token.value)) return true;
406
+ // Non-text nodes become inline spans in Markdown. Without punctuation
407
+ // for a block construct or a hard break, their surrounding text cannot
408
+ // create a boundary. Avoid parsing thousands of placeholder-only bodies.
409
+ if (/[\\#*+\d=>[`~|-]|[ \t]\n/.test(token.value)) possibleBoundary = true;
410
+ }
411
+ return (
412
+ possibleBoundary &&
413
+ markdownLines(source, isBlock, HTML_MARKDOWN_BOUNDARIES).size > 0
414
+ );
415
+ }
416
+
381
417
  /** Preserve whole literal elements, including openers beside nested tags. */
382
418
  function whitespaceSensitiveLines(
383
419
  source: string,
package/src/js-lexer.ts CHANGED
@@ -607,6 +607,32 @@ export function parseMemberIdentifier(src: string): string | null {
607
607
  return property.name as string;
608
608
  }
609
609
 
610
+ /** Read the contiguous dot members after a variable, keeping decoded names. */
611
+ export function readMemberPath(
612
+ src: string,
613
+ end: number,
614
+ ): { path: string[]; end: number } {
615
+ const path: string[] = [];
616
+ const p = tokenizerAt(src, end, 'expression', { afterOperand: true });
617
+ try {
618
+ for (;;) {
619
+ p.nextToken();
620
+ if (p.type !== tt.dot || p.start !== end) break;
621
+ const dotEnd = p.end;
622
+ p.nextToken();
623
+ if (p.start !== dotEnd || (p.type !== tt.name && !p.type.keyword)) break;
624
+ // Field schemas cover the runtime's word-character path names.
625
+ if (!/^\w+$/.test(String(p.value))) break;
626
+ path.push(String(p.value));
627
+ end = p.end;
628
+ }
629
+ } catch (error) {
630
+ // Reference collection also reads incomplete authoring input.
631
+ if (!(error instanceof SyntaxError)) throw error;
632
+ }
633
+ return { path, end };
634
+ }
635
+
610
636
  /**
611
637
  * Parse `src` as `goal`, reading `%` as `percentAt` says where it says, and
612
638
  * noting where it read a transient in `transientsRead`.
@@ -690,152 +716,172 @@ function propertyName(node: unknown, src: string): void {
690
716
  * variable can't be. `shorthand`: the node is a shorthand property's value.
691
717
  */
692
718
  function walk(
693
- node: unknown,
719
+ root: unknown,
694
720
  src: string,
695
721
  out: ParsedCode,
696
722
  binding: boolean,
697
723
  shorthand: boolean,
698
724
  access: 'read' | 'write' | 'readwrite' = 'read',
699
725
  ): void {
700
- if (Array.isArray(node)) {
701
- for (const n of node) walk(n, src, out, binding, false, access);
702
- return;
726
+ type Visit = [unknown, boolean, boolean, typeof access];
727
+ const pending: Visit[] = [[root, binding, shorthand, access]];
728
+ while (pending.length) {
729
+ const [node, bind, short, role] = pending.pop()!;
730
+ const children: Visit[] = [];
731
+ visit(node, bind, short, role, children);
732
+ // Reverse only the work stack, retaining reference/string and error order.
733
+ for (let i = children.length - 1; i >= 0; i--) pending.push(children[i]!);
703
734
  }
704
- if (!isNode(node)) return;
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);
711
- switch (node.type) {
712
- case 'Identifier': {
713
- const sigil = sigilOf(node, src);
714
- if (!sigil) return;
715
- if (binding) {
716
- throw new CodeSyntaxError(
717
- `"${node.name as string}" is a ${NAMESPACE_NAME[sigil[0]]} variable and can't be declared`,
718
- src,
719
- node.start,
720
- );
721
- }
722
- out.refs.push({
723
- sigil: sigil[0],
724
- name: sigil[1],
725
- start: node.start,
726
- end: node.end,
727
- shorthand,
728
- read: access !== 'write',
729
- write: access !== 'read',
730
- });
735
+
736
+ function visit(
737
+ node: unknown,
738
+ binding: boolean,
739
+ shorthand: boolean,
740
+ access: Visit[3],
741
+ children: Visit[],
742
+ ): void {
743
+ if (Array.isArray(node)) {
744
+ for (const n of node) children.push([n, binding, false, access]);
731
745
  return;
732
746
  }
733
- case 'Literal':
734
- if (typeof node.value === 'string') {
735
- out.strings.push(src.slice(node.start + 1, node.end - 1));
747
+ if (!isNode(node)) return;
748
+ const sub = (
749
+ child: unknown,
750
+ bind = false,
751
+ short = false,
752
+ role: typeof access = 'read',
753
+ ) => {
754
+ children.push([child, bind, short, role]);
755
+ };
756
+ switch (node.type) {
757
+ case 'Identifier': {
758
+ const sigil = sigilOf(node, src);
759
+ if (!sigil) return;
760
+ if (binding) {
761
+ throw new CodeSyntaxError(
762
+ `"${node.name as string}" is a ${NAMESPACE_NAME[sigil[0]]} variable and can't be declared`,
763
+ src,
764
+ node.start,
765
+ );
766
+ }
767
+ out.refs.push({
768
+ sigil: sigil[0],
769
+ name: sigil[1],
770
+ start: node.start,
771
+ end: node.end,
772
+ shorthand,
773
+ read: access !== 'write',
774
+ write: access !== 'read',
775
+ });
776
+ return;
736
777
  }
737
- return;
738
- case 'TemplateElement':
739
- out.strings.push((node.value as { raw: string }).raw);
740
- return;
741
- case 'MemberExpression':
742
- sub(node.object);
743
- if (node.computed) sub(node.property);
744
- else propertyName(node.property, src);
745
- return;
746
- case 'Property':
747
- if (node.computed) sub(node.key);
748
- else if (!node.shorthand) propertyName(node.key, src);
749
- if (node.shorthand) {
750
- const value = node.value as AnyNode;
751
- if (value.type === 'AssignmentPattern') {
752
- sub(value.left, binding, true, access);
753
- sub(value.right);
778
+ case 'Literal':
779
+ if (typeof node.value === 'string') {
780
+ out.strings.push(src.slice(node.start + 1, node.end - 1));
781
+ }
782
+ return;
783
+ case 'TemplateElement':
784
+ out.strings.push((node.value as { raw: string }).raw);
785
+ return;
786
+ case 'MemberExpression':
787
+ sub(node.object);
788
+ if (node.computed) sub(node.property);
789
+ else propertyName(node.property, src);
790
+ return;
791
+ case 'Property':
792
+ if (node.computed) sub(node.key);
793
+ else if (!node.shorthand) propertyName(node.key, src);
794
+ if (node.shorthand) {
795
+ const value = node.value as AnyNode;
796
+ if (value.type === 'AssignmentPattern') {
797
+ sub(value.left, binding, true, access);
798
+ sub(value.right);
799
+ } else {
800
+ sub(value, binding, true, access);
801
+ }
754
802
  } else {
755
- sub(value, binding, true, access);
803
+ sub(node.value, binding, false, access);
756
804
  }
757
- } else {
758
- sub(node.value, binding, false, access);
759
- }
760
- return;
761
- case 'MethodDefinition':
762
- case 'PropertyDefinition':
763
- if (node.computed) sub(node.key);
764
- else propertyName(node.key, src);
765
- sub(node.value);
766
- return;
767
- case 'LabeledStatement':
768
- sub(node.body);
769
- return;
770
- case 'BreakStatement':
771
- case 'ContinueStatement':
772
- case 'MetaProperty':
773
- case 'PrivateIdentifier':
774
- return;
775
- case 'VariableDeclarator':
776
- sub(node.id, true);
777
- sub(node.init);
778
- return;
779
- case 'FunctionDeclaration':
780
- case 'FunctionExpression':
781
- case 'ArrowFunctionExpression':
782
- sub(node.id, true);
783
- for (const p of node.params as unknown[]) sub(p, true);
784
- sub(node.body);
785
- return;
786
- case 'ClassDeclaration':
787
- case 'ClassExpression':
788
- sub(node.id, true);
789
- sub(node.superClass);
790
- sub(node.body);
791
- return;
792
- case 'CatchClause':
793
- sub(node.param, true);
794
- sub(node.body);
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;
822
- case 'AssignmentPattern':
823
- sub(node.left, binding, false, access);
824
- sub(node.right);
825
- return;
826
- case 'ObjectPattern':
827
- case 'ArrayPattern':
828
- case 'RestElement':
829
- for (const key of ['properties', 'elements', 'argument']) {
830
- sub(node[key], binding, false, access);
831
- }
832
- return;
833
- default:
834
- for (const key in node) {
835
- if (key === 'type' || key === 'start' || key === 'end') continue;
836
- const v = node[key];
837
- if (typeof v === 'object' && v !== null) sub(v);
838
- }
805
+ return;
806
+ case 'MethodDefinition':
807
+ case 'PropertyDefinition':
808
+ if (node.computed) sub(node.key);
809
+ else propertyName(node.key, src);
810
+ sub(node.value);
811
+ return;
812
+ case 'LabeledStatement':
813
+ sub(node.body);
814
+ return;
815
+ case 'BreakStatement':
816
+ case 'ContinueStatement':
817
+ case 'MetaProperty':
818
+ case 'PrivateIdentifier':
819
+ return;
820
+ case 'VariableDeclarator':
821
+ sub(node.id, true);
822
+ sub(node.init);
823
+ return;
824
+ case 'FunctionDeclaration':
825
+ case 'FunctionExpression':
826
+ case 'ArrowFunctionExpression':
827
+ sub(node.id, true);
828
+ for (const p of node.params as unknown[]) sub(p, true);
829
+ sub(node.body);
830
+ return;
831
+ case 'ClassDeclaration':
832
+ case 'ClassExpression':
833
+ sub(node.id, true);
834
+ sub(node.superClass);
835
+ sub(node.body);
836
+ return;
837
+ case 'CatchClause':
838
+ sub(node.param, true);
839
+ sub(node.body);
840
+ return;
841
+ case 'AssignmentExpression':
842
+ sub(
843
+ node.left,
844
+ false,
845
+ false,
846
+ node.operator === '=' ? 'write' : 'readwrite',
847
+ );
848
+ sub(node.right);
849
+ return;
850
+ case 'UnaryExpression':
851
+ sub(
852
+ node.argument,
853
+ false,
854
+ false,
855
+ node.operator === 'delete' ? 'write' : 'read',
856
+ );
857
+ return;
858
+ case 'UpdateExpression':
859
+ sub(node.argument, false, false, 'readwrite');
860
+ return;
861
+ case 'ForInStatement':
862
+ case 'ForOfStatement':
863
+ sub(node.left, false, false, 'write');
864
+ sub(node.right);
865
+ sub(node.body);
866
+ return;
867
+ case 'AssignmentPattern':
868
+ sub(node.left, binding, false, access);
869
+ sub(node.right);
870
+ return;
871
+ case 'ObjectPattern':
872
+ case 'ArrayPattern':
873
+ case 'RestElement':
874
+ for (const key of ['properties', 'elements', 'argument']) {
875
+ sub(node[key], binding, false, access);
876
+ }
877
+ return;
878
+ default:
879
+ for (const key in node) {
880
+ if (key === 'type' || key === 'start' || key === 'end') continue;
881
+ const v = node[key];
882
+ if (typeof v === 'object' && v !== null) sub(v);
883
+ }
884
+ }
839
885
  }
840
886
  }
841
887