@traqula/core 0.0.21 → 0.0.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.
Files changed (111) hide show
  1. package/dist/cjs/lib/AstCoreFactory.js +152 -0
  2. package/dist/cjs/lib/generator-builder/builderTypes.js +16 -0
  3. package/dist/cjs/lib/generator-builder/dynamicGenerator.js +207 -0
  4. package/dist/cjs/lib/generator-builder/generatorBuilder.js +126 -0
  5. package/dist/cjs/lib/generator-builder/generatorTypes.js +16 -0
  6. package/dist/cjs/lib/index.js +59 -0
  7. package/dist/cjs/lib/indirection-builder/IndirBuilder.js +90 -0
  8. package/dist/cjs/lib/indirection-builder/dynamicIndirected.js +55 -0
  9. package/dist/cjs/lib/indirection-builder/helpers.js +34 -0
  10. package/dist/cjs/lib/lexer-builder/LexerBuilder.js +123 -0
  11. package/dist/cjs/lib/parser-builder/builderTypes.js +16 -0
  12. package/dist/cjs/lib/parser-builder/dynamicParser.js +139 -0
  13. package/dist/cjs/lib/parser-builder/parserBuilder.js +182 -0
  14. package/dist/cjs/lib/parser-builder/ruleDefTypes.js +16 -0
  15. package/dist/cjs/lib/transformers/TransformerObject.js +213 -0
  16. package/dist/cjs/lib/transformers/TransformerSubTyped.js +144 -0
  17. package/dist/cjs/lib/transformers/TransformerTyped.js +123 -0
  18. package/dist/cjs/lib/types.js +16 -0
  19. package/dist/cjs/lib/utils.js +39 -0
  20. package/dist/cjs/package.json +1 -0
  21. package/dist/cjs/test/generatorBuilder/generatorBuilder.types.test.js +30 -0
  22. package/dist/cjs/test/grammar-builder/parserBuilder.types.test.js +27 -0
  23. package/dist/cjs/test/transformer.test.js +82 -0
  24. package/{lib → dist/esm/lib}/AstCoreFactory.d.ts +2 -9
  25. package/dist/esm/lib/AstCoreFactory.js.map +1 -0
  26. package/dist/esm/lib/generator-builder/builderTypes.js.map +1 -0
  27. package/dist/esm/lib/generator-builder/dynamicGenerator.js.map +1 -0
  28. package/dist/esm/lib/generator-builder/generatorBuilder.js.map +1 -0
  29. package/{lib → dist/esm/lib}/generator-builder/generatorTypes.d.ts +1 -1
  30. package/dist/esm/lib/generator-builder/generatorTypes.js.map +1 -0
  31. package/{lib → dist/esm/lib}/index.d.ts +4 -4
  32. package/{lib → dist/esm/lib}/index.js +4 -4
  33. package/dist/esm/lib/index.js.map +1 -0
  34. package/dist/esm/lib/indirection-builder/IndirBuilder.js.map +1 -0
  35. package/dist/esm/lib/indirection-builder/dynamicIndirected.js.map +1 -0
  36. package/dist/esm/lib/indirection-builder/helpers.js.map +1 -0
  37. package/{lib → dist/esm/lib}/lexer-builder/LexerBuilder.d.ts +2 -3
  38. package/{lib → dist/esm/lib}/lexer-builder/LexerBuilder.js +1 -1
  39. package/dist/esm/lib/lexer-builder/LexerBuilder.js.map +1 -0
  40. package/{lib → dist/esm/lib}/parser-builder/builderTypes.d.ts +1 -1
  41. package/dist/esm/lib/parser-builder/builderTypes.js.map +1 -0
  42. package/{lib → dist/esm/lib}/parser-builder/dynamicParser.d.ts +2 -2
  43. package/{lib → dist/esm/lib}/parser-builder/dynamicParser.js +1 -1
  44. package/dist/esm/lib/parser-builder/dynamicParser.js.map +1 -0
  45. package/{lib → dist/esm/lib}/parser-builder/parserBuilder.d.ts +1 -2
  46. package/dist/esm/lib/parser-builder/parserBuilder.js.map +1 -0
  47. package/{lib → dist/esm/lib}/parser-builder/ruleDefTypes.d.ts +1 -2
  48. package/dist/esm/lib/parser-builder/ruleDefTypes.js.map +1 -0
  49. package/dist/esm/lib/transformers/TransformerObject.js.map +1 -0
  50. package/{lib → dist/esm/lib/transformers}/TransformerSubTyped.d.ts +14 -50
  51. package/dist/esm/lib/transformers/TransformerSubTyped.js.map +1 -0
  52. package/{lib → dist/esm/lib/transformers}/TransformerTyped.d.ts +8 -20
  53. package/dist/esm/lib/transformers/TransformerTyped.js.map +1 -0
  54. package/{lib/nodeTypings.d.ts → dist/esm/lib/types.d.ts} +8 -3
  55. package/dist/esm/lib/types.js +2 -0
  56. package/dist/esm/lib/types.js.map +1 -0
  57. package/{lib → dist/esm/lib}/utils.d.ts +1 -1
  58. package/{lib → dist/esm/lib}/utils.js +1 -1
  59. package/dist/esm/lib/utils.js.map +1 -0
  60. package/dist/esm/test/generatorBuilder/generatorBuilder.types.test.d.ts +1 -0
  61. package/dist/esm/test/generatorBuilder/generatorBuilder.types.test.js +38 -0
  62. package/dist/esm/test/generatorBuilder/generatorBuilder.types.test.js.map +1 -0
  63. package/dist/esm/test/grammar-builder/parserBuilder.types.test.d.ts +1 -0
  64. package/dist/esm/test/grammar-builder/parserBuilder.types.test.js +38 -0
  65. package/dist/esm/test/grammar-builder/parserBuilder.types.test.js.map +1 -0
  66. package/dist/esm/test/transformer.test.d.ts +1 -0
  67. package/dist/esm/test/transformer.test.js +82 -0
  68. package/dist/esm/test/transformer.test.js.map +1 -0
  69. package/package.json +13 -17
  70. package/lib/AstCoreFactory.js.map +0 -1
  71. package/lib/TransformerObject.js.map +0 -1
  72. package/lib/TransformerSubTyped.js.map +0 -1
  73. package/lib/TransformerTyped.js.map +0 -1
  74. package/lib/generator-builder/builderTypes.js.map +0 -1
  75. package/lib/generator-builder/dynamicGenerator.js.map +0 -1
  76. package/lib/generator-builder/generatorBuilder.js.map +0 -1
  77. package/lib/generator-builder/generatorTypes.js.map +0 -1
  78. package/lib/index.cjs +0 -10553
  79. package/lib/index.js.map +0 -1
  80. package/lib/indirection-builder/IndirBuilder.js.map +0 -1
  81. package/lib/indirection-builder/dynamicIndirected.js.map +0 -1
  82. package/lib/indirection-builder/helpers.js.map +0 -1
  83. package/lib/lexer-builder/LexerBuilder.js.map +0 -1
  84. package/lib/nodeTypings.js +0 -2
  85. package/lib/nodeTypings.js.map +0 -1
  86. package/lib/parser-builder/builderTypes.js.map +0 -1
  87. package/lib/parser-builder/dynamicParser.js.map +0 -1
  88. package/lib/parser-builder/parserBuilder.js.map +0 -1
  89. package/lib/parser-builder/ruleDefTypes.js.map +0 -1
  90. package/lib/utils.js.map +0 -1
  91. /package/{lib → dist/esm/lib}/AstCoreFactory.js +0 -0
  92. /package/{lib → dist/esm/lib}/generator-builder/builderTypes.d.ts +0 -0
  93. /package/{lib → dist/esm/lib}/generator-builder/builderTypes.js +0 -0
  94. /package/{lib → dist/esm/lib}/generator-builder/dynamicGenerator.d.ts +0 -0
  95. /package/{lib → dist/esm/lib}/generator-builder/dynamicGenerator.js +0 -0
  96. /package/{lib → dist/esm/lib}/generator-builder/generatorBuilder.d.ts +0 -0
  97. /package/{lib → dist/esm/lib}/generator-builder/generatorBuilder.js +0 -0
  98. /package/{lib → dist/esm/lib}/generator-builder/generatorTypes.js +0 -0
  99. /package/{lib → dist/esm/lib}/indirection-builder/IndirBuilder.d.ts +0 -0
  100. /package/{lib → dist/esm/lib}/indirection-builder/IndirBuilder.js +0 -0
  101. /package/{lib → dist/esm/lib}/indirection-builder/dynamicIndirected.d.ts +0 -0
  102. /package/{lib → dist/esm/lib}/indirection-builder/dynamicIndirected.js +0 -0
  103. /package/{lib → dist/esm/lib}/indirection-builder/helpers.d.ts +0 -0
  104. /package/{lib → dist/esm/lib}/indirection-builder/helpers.js +0 -0
  105. /package/{lib → dist/esm/lib}/parser-builder/builderTypes.js +0 -0
  106. /package/{lib → dist/esm/lib}/parser-builder/parserBuilder.js +0 -0
  107. /package/{lib → dist/esm/lib}/parser-builder/ruleDefTypes.js +0 -0
  108. /package/{lib → dist/esm/lib/transformers}/TransformerObject.d.ts +0 -0
  109. /package/{lib → dist/esm/lib/transformers}/TransformerObject.js +0 -0
  110. /package/{lib → dist/esm/lib/transformers}/TransformerSubTyped.js +0 -0
  111. /package/{lib → dist/esm/lib/transformers}/TransformerTyped.js +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"file":"TransformerSubTyped.js","sourceRoot":"","sources":["../../../../lib/transformers/TransformerSubTyped.ts"],"names":[],"mappings":"AAOA,OAAO,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAC;AAEzD,MAAM,OAAO,mBAAyC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,CAAM,OAAO,CAAC,CAAC;gBACnD,WAAW,GAAG,QAAQ,IAAI,KAAK,CAAC;gBAChC,IAAI,CAAC,WAAW,EAAE,CAAC;oBACjB,KAAK,MAAM,IAAI,IAAI,IAAI,IAAI,EAAE,EAAE,CAAC;wBAC9B,IAAI,WAAW,EAAE,CAAC;4BAChB,OAAO;wBACT,CAAC;wBACD,OAAO,CAAC,IAAI,CAAC,CAAC;oBAChB,CAAC;gBACH,CAAC;YACH,CAAC;QACH,CAAC,CAAC;QAEF,OAAO,CAAC,WAAW,CAAC,CAAC;IACvB,CAAC;CACF","sourcesContent":["import type { SubTyped, Typed } from '../types.js';\nimport type {\n SelectiveTraversalContext,\n TransformContext,\n VisitContext,\n} from './TransformerObject.js';\nimport type { DefaultNodePreVisitor, Safeness, SafeWrap } from './TransformerTyped.js';\nimport { TransformerTyped } from './TransformerTyped.js';\n\nexport class TransformerSubTyped<Nodes extends Typed> extends TransformerTyped<Nodes> {\n public constructor(\n defaultContext: TransformContext = {},\n defaultNodePreVisitor: DefaultNodePreVisitor<Nodes> = {},\n ) {\n super(defaultContext, defaultNodePreVisitor);\n };\n\n public override clone(\n newDefaultContext: TransformContext = {},\n newDefaultNodePreVisitor: DefaultNodePreVisitor<Nodes> = {},\n ): TransformerSubTyped<Nodes> {\n return new TransformerSubTyped(\n { ...this.defaultContext, ...newDefaultContext },\n { ...this.defaultNodePreVisitor, ...newDefaultNodePreVisitor },\n );\n }\n\n /**\n * Shares the functionality and first two arguments with {@link this.transformNode}.\n * The third argument allows you to also transform based on the subType of objects.\n * Note that when a callback for the subtype is provided, the callback for the general type is **NOT** executed.\n * @param startObject\n * @param nodeCallBacks\n * @param nodeSpecificCallBacks\n */\n public transformNodeSpecific<Safe extends Safeness = 'safe', OutType = unknown>(\n startObject: object,\n nodeCallBacks: {[T in Nodes['type']]?: {\n transform?: (copy: SafeWrap<Safe, Extract<Nodes, Typed<T>>>, orig: Extract<Nodes, Typed<T>>) => unknown;\n preVisitor?: (orig: Extract<Nodes, Typed<T>>) => TransformContext;\n }},\n nodeSpecificCallBacks: {[Type in Nodes['type']]?: {\n [SubType in Extract<Nodes, SubTyped<Type>>['subType']]?: {\n transform?: (op: SafeWrap<Safe, Extract<Nodes, SubTyped<Type, SubType>>>) => unknown;\n preVisitor?: (op: Extract<Nodes, SubTyped<Type, SubType>>) => TransformContext;\n }}},\n ): Safe extends 'unsafe' ? OutType : unknown {\n const transformWrapper = (copy: object, orig: object): unknown => {\n let ogTransform: ((copy: any, orig: any) => unknown) | undefined;\n const casted = <SubTyped<Nodes['type']>>copy;\n if (casted.type && casted.subType) {\n const specific = nodeSpecificCallBacks[casted.type];\n if (specific) {\n ogTransform = specific[<keyof typeof specific> casted.subType]?.transform;\n }\n if (!ogTransform) {\n ogTransform = nodeCallBacks[casted.type]?.transform;\n }\n }\n return ogTransform ? ogTransform(casted, orig) : copy;\n };\n const preVisitWrapper = (curObject: object): VisitContext => {\n let ogPreVisit: ((node: any) => VisitContext) | undefined;\n const casted = <SubTyped<Nodes['type']>>curObject;\n if (casted.type && casted.subType) {\n const specific = nodeSpecificCallBacks[casted.type];\n if (specific) {\n ogPreVisit = specific[<keyof typeof specific> casted.subType]?.preVisitor;\n }\n if (!ogPreVisit) {\n ogPreVisit = nodeCallBacks[casted.type]?.preVisitor;\n }\n }\n return ogPreVisit ? ogPreVisit(casted) : {};\n };\n return <any> this.transformObject(startObject, transformWrapper, preVisitWrapper);\n }\n\n /**\n * Similar to {@link this.visitNode} but also allows you to match based on the subtype of objects.\n * When both nodeCallBack and NodeSpecific callBack are matched, will only visit nodeSpecifCallback\n */\n public visitNodeSpecific(\n startObject: object,\n nodeCallBacks: {[T in Nodes['type']]?: {\n visitor?: (op: Extract<Nodes, Typed<T>>) => void;\n preVisitor?: (op: Extract<Nodes, Typed<T>>) => VisitContext;\n }},\n nodeSpecificCallBacks: {[Type in Nodes['type']]?:\n {[Subtype in Extract<Nodes, SubTyped<Type>>['subType']]?: {\n visitor?: (op: Extract<Nodes, SubTyped<Type, Subtype>>) => void;\n preVisitor?: (op: Extract<Nodes, SubTyped<Type, Subtype>>) => VisitContext;\n }}},\n ): void {\n const visitWrapper = (curObject: object): void => {\n let ogTransform: ((node: any) => void) | undefined;\n const casted = <SubTyped<Nodes['type']>>curObject;\n if (casted.type && casted.subType) {\n const specific = nodeSpecificCallBacks[casted.type];\n if (specific) {\n ogTransform = specific[<keyof typeof specific> casted.subType]?.visitor;\n }\n if (!ogTransform) {\n ogTransform = nodeCallBacks[casted.type]?.visitor;\n }\n }\n if (ogTransform) {\n ogTransform(casted);\n }\n };\n const preVisitWrapper = (curObject: object): VisitContext => {\n let ogPreVisit: ((node: any) => VisitContext) | undefined;\n const casted = <SubTyped<Nodes['type']>>curObject;\n if (casted.type && casted.subType) {\n const specific = nodeSpecificCallBacks[casted.type];\n if (specific) {\n ogPreVisit = specific[<keyof typeof specific> casted.subType]?.preVisitor;\n }\n if (!ogPreVisit) {\n ogPreVisit = nodeCallBacks[casted.type]?.preVisitor;\n }\n }\n return ogPreVisit ? ogPreVisit(casted) : {};\n };\n this.visitObject(startObject, visitWrapper, preVisitWrapper);\n }\n\n /**\n * Similar to {@link this.traverseNodes} but also allows you to match based on the subtype of objects.\n * @param currentNode\n * @param traverseNode\n * @param traverseSubNode\n */\n public traverseSubNodes(\n currentNode: Nodes,\n traverseNode: {[Type in Nodes['type']]?:\n (op: Extract<Nodes, Typed<Type>>) => SelectiveTraversalContext<Nodes> },\n traverseSubNode: {[Type in Nodes['type']]?:\n {[Subtype in Extract<Nodes, SubTyped<Type>>['subType']]?:\n (op: Extract<Nodes, SubTyped<Type, Subtype>>) => SelectiveTraversalContext<Nodes> }},\n ): void {\n let didShortCut = false;\n\n const recurse = (curNode: Nodes): void => {\n let traverser: ((call: any) => SelectiveTraversalContext<Nodes>) | undefined;\n const subObj = traverseSubNode[<Nodes['type']>curNode.type];\n if (subObj) {\n traverser = subObj[<keyof typeof subObj>curNode.subType];\n }\n if (!traverser) {\n traverser = traverseNode[<Nodes['type']>curNode.type];\n }\n if (traverser) {\n const { next, shortcut } = traverser(<any>curNode);\n didShortCut = shortcut ?? false;\n if (!didShortCut) {\n for (const node of next ?? []) {\n if (didShortCut) {\n return;\n }\n recurse(node);\n }\n }\n }\n };\n\n recurse(currentNode);\n }\n}\n"]}
@@ -1,14 +1,14 @@
1
- import type { Node } from './nodeTypings.js';
1
+ import type { Typed } from '../types.js';
2
2
  import type { SelectiveTraversalContext, TransformContext, VisitContext } from './TransformerObject.js';
3
3
  import { TransformerObject } from './TransformerObject.js';
4
4
  export type Safeness = 'safe' | 'unsafe';
5
5
  export type SafeWrap<Safe extends Safeness, obj extends object> = Safe extends 'safe' ? {
6
6
  [key in keyof obj]: unknown;
7
7
  } : obj;
8
- export type DefaultNodePreVisitor<Nodes extends Pick<Node, 'type'>> = {
8
+ export type DefaultNodePreVisitor<Nodes extends Typed> = {
9
9
  [T in Nodes['type']]?: TransformContext;
10
10
  };
11
- export declare class TransformerTyped<Nodes extends Pick<Node, 'type'>> extends TransformerObject {
11
+ export declare class TransformerTyped<Nodes extends Typed> extends TransformerObject {
12
12
  protected defaultNodePreVisitor: DefaultNodePreVisitor<Nodes>;
13
13
  constructor(defaultContext?: TransformContext, defaultNodePreVisitor?: DefaultNodePreVisitor<Nodes>);
14
14
  clone(newDefaultContext?: TransformContext, newDefaultNodePreVisitor?: DefaultNodePreVisitor<Nodes>): TransformerTyped<Nodes>;
@@ -24,14 +24,8 @@ export declare class TransformerTyped<Nodes extends Pick<Node, 'type'>> extends
24
24
  */
25
25
  transformNode<Safe extends Safeness = 'safe', OutType = unknown>(startObject: object, nodeCallBacks: {
26
26
  [T in Nodes['type']]?: {
27
- transform?: (copy: SafeWrap<Safe, Extract<Nodes, {
28
- type: T;
29
- }>>, orig: Extract<Nodes, {
30
- type: T;
31
- }>) => unknown;
32
- preVisitor?: (orig: Extract<Nodes, {
33
- type: T;
34
- }>) => TransformContext;
27
+ transform?: (copy: SafeWrap<Safe, Extract<Nodes, Typed<T>>>, orig: Extract<Nodes, Typed<T>>) => unknown;
28
+ preVisitor?: (orig: Extract<Nodes, Typed<T>>) => TransformContext;
35
29
  };
36
30
  }): Safe extends 'unsafe' ? OutType : unknown;
37
31
  /**
@@ -42,12 +36,8 @@ export declare class TransformerTyped<Nodes extends Pick<Node, 'type'>> extends
42
36
  */
43
37
  visitNode(startObject: object, nodeCallBacks: {
44
38
  [T in Nodes['type']]?: {
45
- visitor?: (op: Extract<Nodes, {
46
- type: T;
47
- }>) => void;
48
- preVisitor?: (op: Extract<Nodes, {
49
- type: T;
50
- }>) => VisitContext;
39
+ visitor?: (op: Extract<Nodes, Typed<T>>) => void;
40
+ preVisitor?: (op: Extract<Nodes, Typed<T>>) => VisitContext;
51
41
  };
52
42
  }): void;
53
43
  /**
@@ -56,8 +46,6 @@ export declare class TransformerTyped<Nodes extends Pick<Node, 'type'>> extends
56
46
  * @param traverse
57
47
  */
58
48
  traverseNodes(currentNode: Nodes, traverse: {
59
- [T in Nodes['type']]?: (op: Extract<Nodes, {
60
- type: T;
61
- }>) => SelectiveTraversalContext<Nodes>;
49
+ [T in Nodes['type']]?: (op: Extract<Nodes, Typed<T>>) => SelectiveTraversalContext<Nodes>;
62
50
  }): void;
63
51
  }
@@ -0,0 +1 @@
1
+ {"version":3,"file":"TransformerTyped.js","sourceRoot":"","sources":["../../../../lib/transformers/TransformerTyped.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,iBAAiB,EAAE,MAAM,wBAAwB,CAAC;AAQ3D,MAAM,OAAO,gBAAsC,SAAQ,iBAAiB;IAG9D;IAFZ,YACE,iBAAmC,EAAE,EAC3B,wBAAsD,EAAE;QAElE,KAAK,CAAC,cAAc,CAAC,CAAC;QAFZ,0BAAqB,GAArB,qBAAqB,CAAmC;IAGpE,CAAC;IAAA,CAAC;IAEc,KAAK,CACnB,oBAAsC,EAAE,EACxC,2BAAyD,EAAE;QAE3D,OAAO,IAAI,gBAAgB,CACzB,EAAE,GAAG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EAAE,IAAI,EAAE,QAAQ,EAAE,GAAG,SAAS,CAAM,OAAO,CAAC,CAAC;gBACnD,WAAW,GAAG,QAAQ,IAAI,KAAK,CAAC;gBAChC,IAAI,CAAC,WAAW,EAAE,CAAC;oBACjB,KAAK,MAAM,IAAI,IAAI,IAAI,IAAI,EAAE,EAAE,CAAC;wBAC9B,IAAI,WAAW,EAAE,CAAC;4BAChB,OAAO;wBACT,CAAC;wBACD,OAAO,CAAC,IAAI,CAAC,CAAC;oBAChB,CAAC;gBACH,CAAC;YACH,CAAC;QACH,CAAC,CAAC;QAEF,OAAO,CAAC,WAAW,CAAC,CAAC;IACvB,CAAC;CACF","sourcesContent":["import type { Typed } from '../types.js';\nimport type { SelectiveTraversalContext, TransformContext, VisitContext } from './TransformerObject.js';\nimport { TransformerObject } from './TransformerObject.js';\n\nexport type Safeness = 'safe' | 'unsafe';\nexport type SafeWrap<Safe extends Safeness, obj extends object> =\n Safe extends 'safe' ? {[key in keyof obj]: unknown } : obj;\n\nexport type DefaultNodePreVisitor<Nodes extends Typed> = {[T in Nodes['type']]?: TransformContext };\n\nexport class TransformerTyped<Nodes extends Typed> extends TransformerObject {\n public constructor(\n defaultContext: TransformContext = {},\n protected defaultNodePreVisitor: DefaultNodePreVisitor<Nodes> = {},\n ) {\n super(defaultContext);\n };\n\n public override clone(\n newDefaultContext: TransformContext = {},\n newDefaultNodePreVisitor: DefaultNodePreVisitor<Nodes> = {},\n ): TransformerTyped<Nodes> {\n return new TransformerTyped(\n { ...this.defaultContext, ...newDefaultContext },\n { ...this.defaultNodePreVisitor, ...newDefaultNodePreVisitor },\n );\n }\n\n /**\n * Transform a single node.\n * The transformation calls the preVisitor from starting from the startObject.\n * The preVisitor can dictate whether transformation should be stopped.\n * Note that stopping the transformation also prevets further copying.\n * The transformer itself transforms object starting with the deepest one that can be visited.\n * The transformer callback is performed on a copy of the original.\n * @param startObject\n * @param nodeCallBacks\n */\n public transformNode<Safe extends Safeness = 'safe', OutType = unknown>(\n startObject: object,\n nodeCallBacks: {[T in Nodes['type']]?: {\n transform?: (copy: SafeWrap<Safe, Extract<Nodes, Typed<T>>>, orig: Extract<Nodes, Typed<T>>) => unknown;\n preVisitor?: (orig: Extract<Nodes, Typed<T>>) => TransformContext;\n }},\n ): Safe extends 'unsafe' ? OutType : unknown {\n const transformWrapper = (copy: object, orig: object): unknown => {\n let ogTransform: ((copy: any, orig: any) => unknown) | undefined;\n const casted = <Typed<Nodes['type']>>copy;\n if (casted.type) {\n ogTransform = nodeCallBacks[casted.type]?.transform;\n }\n return ogTransform ? ogTransform(casted, orig) : copy;\n };\n const nodeDefaults = this.defaultNodePreVisitor;\n const preVisitWrapper = (curObject: object): VisitContext => {\n let ogPreVisit: ((node: any) => VisitContext) | undefined;\n let nodeContext: VisitContext = {};\n const casted = <Typed<Nodes['type']>>curObject;\n if (casted.type) {\n ogPreVisit = nodeCallBacks[casted.type]?.preVisitor;\n nodeContext = nodeDefaults[casted.type] ?? nodeContext;\n }\n return ogPreVisit ? { ...nodeContext, ...ogPreVisit(casted) } : nodeContext;\n };\n return <any> this.transformObject(startObject, transformWrapper, preVisitWrapper);\n }\n\n /**\n * Similar to {@link this.transformNode}, but without copying the startObject.\n * The pre-visitor visits starting from the root, going deeper, while the actual visitor goes in reverse.\n * @param startObject\n * @param nodeCallBacks\n */\n public visitNode(\n startObject: object,\n nodeCallBacks: {[T in Nodes['type']]?: {\n visitor?: (op: Extract<Nodes, Typed<T>>) => void;\n preVisitor?: (op: Extract<Nodes, Typed<T>>) => VisitContext;\n }},\n ): void {\n const visitorWrapper = (curObject: object): void => {\n const casted = <Typed<Nodes['type']>>curObject;\n if (casted.type) {\n const ogTransform = nodeCallBacks[casted.type]?.visitor;\n if (ogTransform) {\n ogTransform(<any> casted);\n }\n }\n };\n const nodeDefaults = this.defaultNodePreVisitor;\n const preVisitWrapper = (curObject: object): VisitContext => {\n let ogPreVisit: ((node: any) => VisitContext) | undefined;\n let nodeContext: VisitContext = {};\n const casted = <Typed<Nodes['type']>>curObject;\n if (casted.type) {\n ogPreVisit = nodeCallBacks[casted.type]?.preVisitor;\n nodeContext = nodeDefaults[casted.type] ?? nodeContext;\n }\n return ogPreVisit ? { ...nodeContext, ...ogPreVisit(casted) } : nodeContext;\n };\n return this.visitObject(startObject, visitorWrapper, preVisitWrapper);\n }\n\n /**\n * Traverses only selected nodes as returned by the function.\n * @param currentNode\n * @param traverse\n */\n public traverseNodes(\n currentNode: Nodes,\n traverse: {[T in Nodes['type']]?: (op: Extract<Nodes, Typed<T>>) => SelectiveTraversalContext<Nodes> },\n ): void {\n let didShortCut = false;\n\n const recurse = (curNode: Nodes): void => {\n const traverser = traverse[<Nodes['type']>curNode.type];\n if (traverser) {\n const { next, shortcut } = traverser(<any>curNode);\n didShortCut = shortcut ?? false;\n if (!didShortCut) {\n for (const node of next ?? []) {\n if (didShortCut) {\n return;\n }\n recurse(node);\n }\n }\n }\n };\n\n recurse(currentNode);\n }\n}\n"]}
@@ -1,3 +1,10 @@
1
+ export interface Typed<Type extends string = string> {
2
+ type: Type;
3
+ subType?: string;
4
+ }
5
+ export interface SubTyped<Type extends string = string, SubType extends string = string> extends Typed<Type> {
6
+ subType: SubType;
7
+ }
1
8
  export interface Localized {
2
9
  /**
3
10
  * Location undefined means the node does have a string representation, but it was not clarified.
@@ -12,9 +19,7 @@ export interface Wrap<T> extends Localized {
12
19
  * A AST node. Nodes are indexable by their types.
13
20
  * When generating, the SUBRULES called should be located within the current location range.
14
21
  */
15
- export interface Node extends Localized {
16
- type: string;
17
- subType?: string;
22
+ export interface Node extends Localized, Typed {
18
23
  }
19
24
  export interface SourceLocationBase {
20
25
  sourceLocationType: string;
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../../lib/types.ts"],"names":[],"mappings":"","sourcesContent":["export interface Typed<Type extends string = string> {\n type: Type;\n subType?: string;\n}\n\nexport interface SubTyped<Type extends string = string, SubType extends string = string> extends Typed<Type> {\n subType: SubType;\n}\n\nexport interface Localized {\n /**\n * Location undefined means the node does have a string representation, but it was not clarified.\n * This happens when an AST node is patched by a client of the lib.\n */\n loc: SourceLocation;\n}\n\nexport interface Wrap<T> extends Localized {\n val: T;\n}\n\n/**\n * A AST node. Nodes are indexable by their types.\n * When generating, the SUBRULES called should be located within the current location range.\n */\nexport interface Node extends Localized, Typed {}\n\nexport interface SourceLocationBase {\n sourceLocationType: string;\n}\n\nexport interface SourceLocationSource extends SourceLocationBase {\n sourceLocationType: 'source';\n start: number;\n end: number;\n}\n\n/**\n * NoStringManifestation means the node does not have a string representation.\n * For example the literal '5' has an integer type (which is an AST node),\n * but the type does not have an associated string representation.\n * When set to true, the node will not be printed, start and end are meaningless in this case.\n */\nexport interface SourceLocationNoMaterialize extends SourceLocationBase {\n sourceLocationType: 'noMaterialize';\n}\n\nexport interface SourceLocationStringReplace extends SourceLocationBase {\n sourceLocationType: 'stringReplace';\n newSource: string;\n start: number;\n end: number;\n}\n\nexport interface SourceLocationNodeReplace extends SourceLocationBase {\n sourceLocationType: 'nodeReplace';\n start: number;\n end: number;\n}\n/**\n * Must have an ancestor of type {@link SourceLocationNodeReplace}\n */\nexport interface SourceLocationNodeAutoGenerate extends SourceLocationBase {\n sourceLocationType: 'autoGenerate';\n}\n\nexport type SourceLocation =\n | SourceLocationSource\n | SourceLocationNoMaterialize\n | SourceLocationStringReplace\n | SourceLocationNodeReplace\n | SourceLocationNodeAutoGenerate;\n"]}
@@ -1,4 +1,4 @@
1
- import type { ITokenConfig, TokenType } from '@chevrotain/types';
1
+ import type { ITokenConfig, TokenType } from '@traqula/chevrotain';
2
2
  /**
3
3
  * Check whether the first two types overlap, if no, return the 3th argument, else the 4th.
4
4
  */
@@ -1,4 +1,4 @@
1
- import { createToken as chevcT } from 'chevrotain';
1
+ import { createToken as chevcT } from '@traqula/chevrotain';
2
2
  export function unCapitalize(str) {
3
3
  return (str.charAt(0).toLowerCase() + str.slice(1));
4
4
  }
@@ -0,0 +1 @@
1
+ {"version":3,"file":"utils.js","sourceRoot":"","sources":["../../../lib/utils.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,WAAW,IAAI,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAO5D,MAAM,UAAU,YAAY,CAAmB,GAAM;IACnD,OAAyB,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,WAAW,EAAE,GAAG,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC;AACxE,CAAC;AAID,MAAM,UAAU,WAAW,CAAsB,MAAqC;IACpF,OAAoC,MAAM,CAAC,MAAM,CAAC,CAAC;AACrD,CAAC;AAKD;;;GAGG;AACH,MAAM,CAAC,MAAM,kBAAkB,GAC7B,wFAAwF,CAAC","sourcesContent":["import type { ITokenConfig, TokenType } from '@traqula/chevrotain';\nimport { createToken as chevcT } from '@traqula/chevrotain';\n\n/**\n * Check whether the first two types overlap, if no, return the 3th argument, else the 4th.\n */\nexport type CheckOverlap<T, U, V, W = never> = T & U extends never ? V : W;\n\nexport function unCapitalize<T extends string>(str: T): Uncapitalize<T> {\n return <Uncapitalize<T>> (str.charAt(0).toLowerCase() + str.slice(1));\n}\n\nexport type NamedToken<Name extends string = string> = TokenType & { name: Name };\n\nexport function createToken<Name extends string>(config: ITokenConfig & { name: Name }): NamedToken<Name> {\n return <TokenType & { name: Name }> chevcT(config);\n}\n\nexport type Patch<T extends object, Patch extends {[Key in keyof T ]?: unknown }> =\n {[Key in keyof T]: Key extends keyof Patch ? Patch[Key] : T[Key] };\n\n/**\n * Key that allows you to set the space based indentation of your query when generating newlines using the NEW_LINE.\n * A value of -1 disables the generation of newlines from the NEW_LINE function\n */\nexport const traqulaIndentation =\n 'When you use this string, you expect traqula to handle indentation after every newline';\n"]}
@@ -0,0 +1,38 @@
1
+ import { describe, it, expectTypeOf } from 'vitest';
2
+ import { GeneratorBuilder } from '../../lib/index.js';
3
+ const RuleA = {
4
+ name: 'apple',
5
+ gImpl: () => () => { },
6
+ };
7
+ const RuleB = {
8
+ name: 'banana',
9
+ gImpl: () => () => { },
10
+ };
11
+ const RuleC = {
12
+ name: 'coconut',
13
+ gImpl: () => () => { },
14
+ };
15
+ describe('parserBuilder', () => {
16
+ describe('types', () => {
17
+ it('builder constructor', () => {
18
+ expectTypeOf(GeneratorBuilder.create([RuleA]))
19
+ .branded.toEqualTypeOf();
20
+ expectTypeOf(GeneratorBuilder.create([RuleB]))
21
+ .branded.toEqualTypeOf();
22
+ expectTypeOf(GeneratorBuilder.create([RuleA, RuleB]))
23
+ .branded
24
+ .toEqualTypeOf();
25
+ // AddRule
26
+ expectTypeOf(GeneratorBuilder.create([RuleA, RuleB]).addRule(RuleC))
27
+ .branded.toEqualTypeOf();
28
+ // Merge
29
+ expectTypeOf(GeneratorBuilder.create([RuleA])
30
+ .merge(GeneratorBuilder.create([RuleB]), [])).branded
31
+ .toEqualTypeOf();
32
+ expectTypeOf(GeneratorBuilder.create([RuleA, RuleB])
33
+ .merge(GeneratorBuilder.create([RuleB, RuleC]), [])).branded
34
+ .toEqualTypeOf();
35
+ });
36
+ });
37
+ });
38
+ //# sourceMappingURL=generatorBuilder.types.test.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"generatorBuilder.types.test.js","sourceRoot":"","sources":["../../../../test/generatorBuilder/generatorBuilder.types.test.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,EAAE,EAAE,YAAY,EAAE,MAAM,QAAQ,CAAC;AAEpD,OAAO,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAMtD,MAAM,KAAK,GAA+D;IACxE,IAAI,EAAE,OAAO;IACb,KAAK,EAAE,GAAG,EAAE,CAAC,GAAG,EAAE,GAAE,CAAC;CACtB,CAAC;AACF,MAAM,KAAK,GAAkE;IAC3E,IAAI,EAAE,QAAQ;IACd,KAAK,EAAE,GAAG,EAAE,CAAC,GAAG,EAAE,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C;QACT,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC","sourcesContent":["import { describe, it, expectTypeOf } from 'vitest';\nimport type { GeneratorRule, Node } from '../../lib/index.js';\nimport { GeneratorBuilder } from '../../lib/index.js';\n\ninterface Context {\n world: 'hello';\n}\n\nconst RuleA: GeneratorRule<Context, 'apple', { apple: 'apple' } & Node> = {\n name: 'apple',\n gImpl: () => () => {},\n};\nconst RuleB: GeneratorRule<Context, 'banana', { banana: 'banana' } & Node> = {\n name: 'banana',\n gImpl: () => () => {},\n};\nconst RuleC: GeneratorRule<Context, 'coconut', { coconut: 'coconut' } & Node> = {\n name: 'coconut',\n gImpl: () => () => {},\n};\n\ndescribe('parserBuilder', () => {\n describe('types', () => {\n it('builder constructor', () => {\n expectTypeOf(GeneratorBuilder.create(<const> [ RuleA ]))\n .branded.toEqualTypeOf<GeneratorBuilder<Context, 'apple', { apple: typeof RuleA }>>();\n expectTypeOf(GeneratorBuilder.create(<const> [ RuleB ]))\n .branded.toEqualTypeOf<GeneratorBuilder<Context, 'banana', { banana: typeof RuleB }>>();\n expectTypeOf(GeneratorBuilder.create(<const> [ RuleA, RuleB ]))\n .branded\n .toEqualTypeOf<GeneratorBuilder<Context, 'apple' | 'banana', { apple: typeof RuleA; banana: typeof RuleB }>>();\n\n // AddRule\n expectTypeOf(GeneratorBuilder.create(<const> [ RuleA, RuleB ]).addRule(RuleC))\n .branded.toEqualTypeOf<GeneratorBuilder<\n Context,\n 'apple' | 'banana' | 'coconut',\n { apple: typeof RuleA; banana: typeof RuleB; coconut: typeof RuleC }\n >>();\n\n // Merge\n expectTypeOf(\n GeneratorBuilder.create(<const> [ RuleA ])\n .merge(GeneratorBuilder.create(<const> [ RuleB ]), <const> []),\n ).branded\n .toEqualTypeOf<GeneratorBuilder<Context, 'apple' | 'banana', { apple: typeof RuleA; banana: typeof RuleB }>>();\n\n expectTypeOf(\n GeneratorBuilder.create(<const> [ RuleA, RuleB ])\n .merge(GeneratorBuilder.create(<const> [ RuleB, RuleC ]), <const> []),\n ).branded\n .toEqualTypeOf<GeneratorBuilder<\n Context,\n 'apple' | 'banana' | 'coconut',\n { apple: typeof RuleA; banana: typeof RuleB; coconut: typeof RuleC }\n >>();\n });\n });\n});\n"]}
@@ -0,0 +1,38 @@
1
+ import { describe, it, expectTypeOf } from 'vitest';
2
+ import { ParserBuilder } from '../../lib/index.js';
3
+ const RuleA = {
4
+ name: 'apple',
5
+ impl: () => () => 'apple',
6
+ };
7
+ const RuleB = {
8
+ name: 'banana',
9
+ impl: () => () => 'banana',
10
+ };
11
+ const RuleC = {
12
+ name: 'coconut',
13
+ impl: () => () => 'coconut',
14
+ };
15
+ describe('parserBuilder', () => {
16
+ describe('types', () => {
17
+ it('builder constructor', () => {
18
+ expectTypeOf(ParserBuilder.create([RuleA]))
19
+ .branded.toEqualTypeOf();
20
+ expectTypeOf(ParserBuilder.create([RuleB]))
21
+ .branded.toEqualTypeOf();
22
+ expectTypeOf(ParserBuilder.create([RuleA, RuleB]))
23
+ .branded
24
+ .toEqualTypeOf();
25
+ // AddRule
26
+ expectTypeOf(ParserBuilder.create([RuleA, RuleB]).addRule(RuleC))
27
+ .branded.toEqualTypeOf();
28
+ // Merge
29
+ expectTypeOf(ParserBuilder.create([RuleA])
30
+ .merge(ParserBuilder.create([RuleB]), [])).branded
31
+ .toEqualTypeOf();
32
+ expectTypeOf(ParserBuilder.create([RuleA, RuleB])
33
+ .merge(ParserBuilder.create([RuleB, RuleC]), [])).branded
34
+ .toEqualTypeOf();
35
+ });
36
+ });
37
+ });
38
+ //# sourceMappingURL=parserBuilder.types.test.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"parserBuilder.types.test.js","sourceRoot":"","sources":["../../../../test/grammar-builder/parserBuilder.types.test.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,EAAE,EAAE,YAAY,EAAE,MAAM,QAAQ,CAAC;AAEpD,OAAO,EAAE,aAA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AA6F,CAAC;YAE9G,YAAY,CACV,aAAa,CAAC,MAAM,CAAS,CAAE,KAAK,EAAE,KAAK,CAAE,CAAC;iBAC3C,KAAK,CAAC,aAAa,CAAC,MAAM,CAAS,CAAE,KAAK,EAAE,KAAK,CAAE,CAAC,EAAU,EAAE,CAAC,CACrE,CAAC,OAAO;iBACN,aAAa,EAIZ,CAAC;QACP,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC","sourcesContent":["import { describe, it, expectTypeOf } from 'vitest';\nimport type { ParserRule } from '../../lib/index.js';\nimport { ParserBuilder } from '../../lib/index.js';\n\ninterface Context {\n world: 'hello';\n}\n\nconst RuleA: ParserRule<Context, 'apple', 'apple'> = {\n name: 'apple',\n impl: () => () => 'apple',\n};\nconst RuleB: ParserRule<Context, 'banana', 'banana'> = {\n name: 'banana',\n impl: () => () => 'banana',\n};\nconst RuleC: ParserRule<Context, 'coconut', 'coconut'> = {\n name: 'coconut',\n impl: () => () => 'coconut',\n};\n\ndescribe('parserBuilder', () => {\n describe('types', () => {\n it('builder constructor', () => {\n expectTypeOf(ParserBuilder.create(<const> [ RuleA ]))\n .branded.toEqualTypeOf<ParserBuilder<Context, 'apple', { apple: typeof RuleA }>>();\n expectTypeOf(ParserBuilder.create(<const> [ RuleB ]))\n .branded.toEqualTypeOf<ParserBuilder<Context, 'banana', { banana: typeof RuleB }>>();\n expectTypeOf(ParserBuilder.create(<const> [ RuleA, RuleB ]))\n .branded\n .toEqualTypeOf<ParserBuilder<Context, 'apple' | 'banana', { apple: typeof RuleA; banana: typeof RuleB }>>();\n\n // AddRule\n expectTypeOf(ParserBuilder.create(<const> [ RuleA, RuleB ]).addRule(RuleC))\n .branded.toEqualTypeOf<ParserBuilder<\n Context,\n'apple' | 'banana' | 'coconut',\n{ apple: typeof RuleA; banana: typeof RuleB; coconut: typeof RuleC }\n >>();\n\n // Merge\n expectTypeOf(\n ParserBuilder.create(<const> [ RuleA ])\n .merge(ParserBuilder.create(<const> [ RuleB ]), <const> []),\n ).branded\n .toEqualTypeOf<ParserBuilder<Context, 'apple' | 'banana', { apple: typeof RuleA; banana: typeof RuleB }>>();\n\n expectTypeOf(\n ParserBuilder.create(<const> [ RuleA, RuleB ])\n .merge(ParserBuilder.create(<const> [ RuleB, RuleC ]), <const> []),\n ).branded\n .toEqualTypeOf<ParserBuilder<\n Context,\n'apple' | 'banana' | 'coconut',\n{ apple: typeof RuleA; banana: typeof RuleB; coconut: typeof RuleC }\n >>();\n });\n });\n});\n"]}
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,82 @@
1
+ import { describe, it } from 'vitest';
2
+ import { TransformerTyped } from '../lib/index.js';
3
+ describe('transformer', () => {
4
+ const transformer = new TransformerTyped();
5
+ it('makes copies when needed', ({ expect }) => {
6
+ const fruit = {
7
+ type: 'fruit',
8
+ clone1: { type: 'vegetable', random: { type: 'fruit', val: 'blep' } },
9
+ };
10
+ const fullCopy = transformer.transformNode(fruit, {});
11
+ expect(fullCopy).not.toBe(fruit);
12
+ expect(fullCopy.clone1).not.toBe(fruit.clone1);
13
+ expect(fullCopy.clone1.random).not.toBe(fruit.clone1.random);
14
+ const sameVegetable = transformer.transformNode(fruit, {
15
+ vegetable: { preVisitor: () => ({ copy: false }) },
16
+ fruit: { transform: (fruit) => {
17
+ fruit.test = 'yes';
18
+ return fruit;
19
+ } },
20
+ });
21
+ expect(sameVegetable).not.toBe(fruit);
22
+ expect(sameVegetable.clone1).toBe(fruit.clone1);
23
+ expect(sameVegetable.clone1.random).toMatchObject({ test: 'yes' });
24
+ });
25
+ it('knows shortcut and continue', ({ expect }) => {
26
+ const in2 = { type: 'fruit', val: 'depth3' };
27
+ const in1 = { type: 'vegetable', in: in2, val: 'depth2' };
28
+ const side1 = { type: 'fruit', val: 'side1' };
29
+ const side2 = { type: 'vegetable' };
30
+ const fruit = { type: 'fruit', in: in1, val: 'depth1', side: side1, side2 };
31
+ const onlyCopyDepth1 = transformer.transformNode(fruit, {
32
+ fruit: { preVisitor: () => ({ continue: false }) },
33
+ });
34
+ expect(onlyCopyDepth1).not.toBe(fruit);
35
+ expect(onlyCopyDepth1.in).toBe(in1);
36
+ expect(onlyCopyDepth1.in.in).toBe(in2);
37
+ expect(onlyCopyDepth1.side).toBe(side1);
38
+ const doNotCopy = transformer.transformNode(fruit, {
39
+ fruit: { preVisitor: () => ({ continue: false, copy: false }) },
40
+ });
41
+ expect(doNotCopy).toBe(fruit);
42
+ expect(doNotCopy.in).toBe(in1);
43
+ expect(doNotCopy.in.in).toBe(in2);
44
+ expect(doNotCopy.side).toBe(side1);
45
+ const doNotCopyByShortcut = transformer.transformNode(fruit, {
46
+ fruit: { preVisitor: () => ({ shortcut: true }) },
47
+ });
48
+ expect(doNotCopyByShortcut).not.toBe(fruit);
49
+ expect(doNotCopyByShortcut.in).toBe(in1);
50
+ expect(doNotCopyByShortcut.in.in).toBe(in2);
51
+ expect(doNotCopyByShortcut.side).toBe(side1);
52
+ const doNotCopySideWhenShortcut = transformer.transformNode(fruit, {
53
+ vegetable: { preVisitor: () => ({ shortcut: true }) },
54
+ });
55
+ expect(doNotCopySideWhenShortcut).not.toBe(fruit);
56
+ expect(doNotCopySideWhenShortcut.in).toBe(in1);
57
+ expect(doNotCopySideWhenShortcut.in.in).toBe(in2);
58
+ expect(doNotCopySideWhenShortcut.side).toBe(side1);
59
+ expect(doNotCopySideWhenShortcut.side2).not.toBe(side2);
60
+ });
61
+ it('knows shallowKeys and ignoreKeys', ({ expect }) => {
62
+ const in2 = { type: 'fruit', val: 'depth3' };
63
+ const in1 = { type: 'vegetable', in: in2, val: 'depth2' };
64
+ const side1 = { type: 'fruit', val: 'side1' };
65
+ const fruit = { type: 'fruit', in: in1, val: 'depth1', side: side1 };
66
+ const noDeepOnShallowKeys = transformer.transformNode(fruit, {
67
+ fruit: { preVisitor: () => ({ shallowKeys: new Set(['in']) }) },
68
+ });
69
+ expect(noDeepOnShallowKeys).not.toBe(fruit);
70
+ expect(noDeepOnShallowKeys.in).not.toBe(in1);
71
+ expect(noDeepOnShallowKeys.in.in).toBe(in2);
72
+ expect(noDeepOnShallowKeys.side).not.toBe(side1);
73
+ const ignoreKeysAreIgnored = transformer.transformNode(fruit, {
74
+ fruit: { preVisitor: () => ({ ignoreKeys: new Set(['in']) }) },
75
+ });
76
+ expect(ignoreKeysAreIgnored).not.toBe(fruit);
77
+ expect(ignoreKeysAreIgnored.in).toBe(in1);
78
+ expect(ignoreKeysAreIgnored.in.in).toBe(in2);
79
+ expect(ignoreKeysAreIgnored.side).not.toBe(side1);
80
+ });
81
+ });
82
+ //# sourceMappingURL=transformer.test.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"transformer.test.js","sourceRoot":"","sources":["../../../test/transformer.test.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,EAAE,EAAE,MAAM,QAAQ,CAAC;AACtC,OAAO,EAAE,gBAAgB,EAAE,MAAM,iBAAiB,CAAC;AAYnD,QAAQ,CAAC,aAAa,EAAE,GAAG,EAAE;IAC3B,MAAM,WAAW,GAAG,IAAI,gBAAgB,EAAqB,CAAC;IAC9D,EAAE,CAAC,0BAA0B,EAAE,CAAC,EAAE,MAAM,EAAE,EAAE,EAAE;QAC5C,MAAM,KAAK,GAAU;YACnB,IAAI,EAAE,OAAO;YACb,MAAM,EAAE,EAAE,IAAI,EAAE,WAAW,EAAE,MAAM,EAAE,EAAE,IAAI,EAAE,OAAO,EAAE,GAAG,EAAE,MAAM,EAAE,EAAC;SACrE,CAAC;QACF,MAAM,QAAQ,GAAS,WAAW,CAAC,aAAa,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;QAC5D,MAAM,CAAC,QAAQ,CAAC,CAAC,GAAG,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;QACjC,MAAM,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC,GAAG,CAAC,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;QAC/C,MAAM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AG,CAAC,CAAC;QAC1C,MAAM,CAAC,oBAAoB,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;QAC7C,MAAM,CAAC,oBAAoB,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IACpD,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC","sourcesContent":["import { describe, it } from 'vitest';\nimport { TransformerTyped } from '../lib/index.js';\n\ninterface Fruit {\n type: 'fruit';\n [key: string]: any;\n}\n\ninterface Vegetable {\n type: 'vegetable';\n [key: string]: any;\n}\n\ndescribe('transformer', () => {\n const transformer = new TransformerTyped<Fruit | Vegetable>();\n it('makes copies when needed', ({ expect }) => {\n const fruit: Fruit = {\n type: 'fruit',\n clone1: { type: 'vegetable', random: { type: 'fruit', val: 'blep' }},\n };\n const fullCopy = <any> transformer.transformNode(fruit, {});\n expect(fullCopy).not.toBe(fruit);\n expect(fullCopy.clone1).not.toBe(fruit.clone1);\n expect(fullCopy.clone1.random).not.toBe(fruit.clone1.random);\n\n const sameVegetable = <any> transformer.transformNode(fruit, {\n vegetable: { preVisitor: () => ({ copy: false }) },\n fruit: { transform: (fruit: any) => {\n fruit.test = 'yes';\n return fruit;\n } },\n });\n expect(sameVegetable).not.toBe(fruit);\n expect(sameVegetable.clone1).toBe(fruit.clone1);\n expect(sameVegetable.clone1.random).toMatchObject({ test: 'yes' });\n });\n\n it('knows shortcut and continue', ({ expect }) => {\n const in2 = { type: 'fruit', val: 'depth3' };\n const in1 = { type: 'vegetable', in: in2, val: 'depth2' };\n const side1 = { type: 'fruit', val: 'side1' };\n const side2 = { type: 'vegetable' };\n const fruit: Fruit = { type: 'fruit', in: in1, val: 'depth1', side: side1, side2 };\n\n const onlyCopyDepth1 = <any> transformer.transformNode(fruit, {\n fruit: { preVisitor: () => ({ continue: false }) },\n });\n expect(onlyCopyDepth1).not.toBe(fruit);\n expect(onlyCopyDepth1.in).toBe(in1);\n expect(onlyCopyDepth1.in.in).toBe(in2);\n expect(onlyCopyDepth1.side).toBe(side1);\n\n const doNotCopy = <any> transformer.transformNode(fruit, {\n fruit: { preVisitor: () => ({ continue: false, copy: false }) },\n });\n expect(doNotCopy).toBe(fruit);\n expect(doNotCopy.in).toBe(in1);\n expect(doNotCopy.in.in).toBe(in2);\n expect(doNotCopy.side).toBe(side1);\n\n const doNotCopyByShortcut = <any> transformer.transformNode(fruit, {\n fruit: { preVisitor: () => ({ shortcut: true }) },\n });\n expect(doNotCopyByShortcut).not.toBe(fruit);\n expect(doNotCopyByShortcut.in).toBe(in1);\n expect(doNotCopyByShortcut.in.in).toBe(in2);\n expect(doNotCopyByShortcut.side).toBe(side1);\n\n const doNotCopySideWhenShortcut = <any> transformer.transformNode(fruit, {\n vegetable: { preVisitor: () => ({ shortcut: true }) },\n });\n expect(doNotCopySideWhenShortcut).not.toBe(fruit);\n expect(doNotCopySideWhenShortcut.in).toBe(in1);\n expect(doNotCopySideWhenShortcut.in.in).toBe(in2);\n expect(doNotCopySideWhenShortcut.side).toBe(side1);\n expect(doNotCopySideWhenShortcut.side2).not.toBe(side2);\n });\n\n it('knows shallowKeys and ignoreKeys', ({ expect }) => {\n const in2 = { type: 'fruit', val: 'depth3' };\n const in1 = { type: 'vegetable', in: in2, val: 'depth2' };\n const side1 = { type: 'fruit', val: 'side1' };\n const fruit: Fruit = { type: 'fruit', in: in1, val: 'depth1', side: side1 };\n\n const noDeepOnShallowKeys = <any> transformer.transformNode(fruit, {\n fruit: { preVisitor: () => ({ shallowKeys: new Set([ 'in' ]) }) },\n });\n expect(noDeepOnShallowKeys).not.toBe(fruit);\n expect(noDeepOnShallowKeys.in).not.toBe(in1);\n expect(noDeepOnShallowKeys.in.in).toBe(in2);\n expect(noDeepOnShallowKeys.side).not.toBe(side1);\n\n const ignoreKeysAreIgnored = <any> transformer.transformNode(fruit, {\n fruit: { preVisitor: () => ({ ignoreKeys: new Set([ 'in' ]) }) },\n });\n expect(ignoreKeysAreIgnored).not.toBe(fruit);\n expect(ignoreKeysAreIgnored.in).toBe(in1);\n expect(ignoreKeysAreIgnored.in.in).toBe(in2);\n expect(ignoreKeysAreIgnored.side).not.toBe(side1);\n });\n});\n"]}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@traqula/core",
3
3
  "type": "module",
4
- "version": "0.0.21",
4
+ "version": "0.0.23",
5
5
  "description": "Core components of Traqula",
6
6
  "lsd:module": true,
7
7
  "license": "MIT",
@@ -17,35 +17,31 @@
17
17
  "exports": {
18
18
  "./package.json": "./package.json",
19
19
  ".": {
20
- "types": "./lib/index.d.ts",
21
- "import": "./lib/index.js",
22
- "require": "./lib/index.cjs"
20
+ "types": "./dist/esm/lib/index.d.ts",
21
+ "import": "./dist/esm/lib/index.js",
22
+ "require": "./dist/cjs/lib/index.js"
23
23
  }
24
24
  },
25
- "main": "lib/index.js",
25
+ "main": "dist/esm/lib/index.js",
26
26
  "publishConfig": {
27
27
  "access": "public"
28
28
  },
29
29
  "files": [
30
- "lib/**/*.cjs",
31
- "lib/**/*.d.ts",
32
- "lib/**/*.js",
33
- "lib/**/*.js.map"
30
+ "dist/**/*.d.ts",
31
+ "dist/**/*.js",
32
+ "dist/**/*.js.map",
33
+ "dist/**/package.json"
34
34
  ],
35
35
  "engines": {
36
36
  "node": "^20.19.0 || >=22.12.0"
37
37
  },
38
- "typings": "lib/index",
39
38
  "scripts": {
40
39
  "build": "yarn build:ts && yarn build:transpile",
41
- "build:ts": "node \"../../node_modules/typescript/bin/tsc\"",
42
- "build:transpile": "node \"../../node_modules/esbuild/bin/esbuild\" --format=cjs --bundle --log-level=error --outfile=lib/index.cjs lib/index.ts"
40
+ "build:ts": "node \"../../node_modules/typescript/bin/tsc\" -b",
41
+ "build:transpile": "esbuild \"dist/esm/**/*.js\" --outdir=dist/cjs --platform=node --format=cjs"
43
42
  },
44
43
  "dependencies": {
45
- "chevrotain": "^11.0.3"
44
+ "@traqula/chevrotain": "^0.0.23"
46
45
  },
47
- "devDependencies": {
48
- "@chevrotain/types": "^11.0.3"
49
- },
50
- "gitHead": "6e27b4bab942e473c11576196320bd52894ea5a4"
46
+ "gitHead": "36ec1aae80524a84f044182811a55ebeef6d9cda"
51
47
  }
@@ -1 +0,0 @@
1
- {"version":3,"file":"AstCoreFactory.js","sourceRoot":"","sources":["AstCoreFactory.ts"],"names":[],"mappings":"AAiBA,MAAM,OAAO,cAAc;IAClB,IAAI,CAAI,GAAM,EAAE,GAAmB;QACxC,OAAO,EAAE,GAAG,EAAE,GAAG,EAAE,CAAC;IACtB,CAAC;IAEM,WAAW,CAAC,GAAY;QAC7B,OAAO,OAAO,GAAG,KAAK,QAAQ,IAAI,GAAG,KAAK,IAAI,IAAI,KAAK,IAAI,GAAG;YAC5D,OAAO,GAAG,CAAC,GAAG,KAAK,QAAQ,IAAI,GAAG,CAAC,GAAG,KAAK,IAAI,IAAI,oBAAoB,IAAI,GAAG,CAAC,GAAG,CAAC;IACvF,CAAC;IAEM,cAAc,CAAC,GAAG,QAA4C;QACnE,MAAM,YAAY,GAAG,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,KAAK,SAAS,CAAC,CAAC;QAC3D,IAAI,YAAY,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;YAC9B,OAAO,IAAI,CAAC,2BAA2B,EAAE,CAAC;QAC5C,CAAC;QACD,MAAM,QAAQ,GAAG,YAAY,CAAC,MAAM,CAAC,OAAO,CAAC,EAAE,CAC7C,CAAC,IAAI,CAAC,WAAW,CAAC,OAAO,CAAC,IAAI,IAAI,CAAC,sBAAsB,CAAC,OAAO,CAAC,GAAG,CAAC;YACtE,IAAI,CAAC,6BAA6B,CAAC,OAAO,CAAC,GAAG,CAAC,IAAI,IAAI,CAAC,2BAA2B,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC;QACpG,IAAI,QAAQ,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;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AEM,6BAA6B,CAAC,GAAW;QAC9C,OAAO,IAAI,CAAC,gBAAgB,CAAC,GAAG,CAAC,IAAI,GAAG,CAAC,kBAAkB,KAAK,eAAe,CAAC;IAClF,CAAC;IAEM,QAAQ,CAAsB,GAAW,EAAE,IAAU;QAC1D,MAAM,MAAM,GAAmB,GAAG,CAAC;QACnC,OAAO,MAAM,CAAC,IAAI,KAAK,IAAI,CAAC;IAC9B,CAAC;IAEM,WAAW,CAA8C,GAAW,EAAE,IAAU,EAAE,OAAgB;QAEvG,MAAM,IAAI,GAA0C,GAAG,CAAC;QACxD,OAAO,IAAI,CAAC,IAAI,KAAK,IAAI,IAAI,IAAI,CAAC,OAAO,KAAK,OAAO,CAAC;IACxD,CAAC;CACF","sourcesContent":["import type { IToken } from 'chevrotain';\n\nimport type {\n SourceLocation,\n SourceLocationNodeAutoGenerate,\n SourceLocationNodeReplace,\n SourceLocationNoMaterialize,\n SourceLocationSource,\n SourceLocationStringReplace,\n Node,\n Localized,\n Wrap,\n} from './nodeTypings.js';\n\nexport type Typed<Type extends PropertyKey> = { type: Type };\nexport type SubTyped<Type extends PropertyKey, Subtype extends PropertyKey> = { type: Type; subType: Subtype };\n\nexport class AstCoreFactory {\n public wrap<T>(val: T, loc: SourceLocation): Wrap<T> {\n return { val, loc };\n }\n\n public isLocalized(obj: unknown): obj is Localized {\n return typeof obj === 'object' && obj !== null && 'loc' in obj &&\n typeof obj.loc === 'object' && obj.loc !== null && 'sourceLocationType' in obj.loc;\n }\n\n public sourceLocation(...elements: (undefined | IToken | Localized)[]): SourceLocation {\n const pureElements = elements.filter(x => x !== undefined);\n if (pureElements.length === 0) {\n return this.sourceLocationNoMaterialize();\n }\n const filtered = pureElements.filter(element =>\n !this.isLocalized(element) || this.isSourceLocationSource(element.loc) ||\n this.isSourceLocationStringReplace(element.loc) || this.isSourceLocationNodeReplace(element.loc));\n if (filtered.length === 0) {\n return this.gen();\n }\n const first = filtered.at(0)!;\n const last = filtered.at(-1)!;\n return {\n sourceLocationType: 'source',\n start: this.isLocalized(first) ?\n (<SourceLocationSource | SourceLocationStringReplace> first.loc).start :\n first.startOffset,\n end: this.isLocalized(last) ?\n (<SourceLocationSource | SourceLocationStringReplace> last.loc).end :\n (last.endOffset! + 1),\n };\n }\n\n public sourceLocationNoMaterialize(): SourceLocationNoMaterialize {\n return { sourceLocationType: 'noMaterialize' };\n }\n\n /**\n * Returns a copy of the argument that is not materialized\n */\n public dematerialized<T extends Node>(arg: T): T & { loc: SourceLocationNoMaterialize } {\n return { ...arg, loc: this.sourceLocationNoMaterialize() };\n }\n\n public safeObjectTransform(value: unknown, mapper: (some: object) => any): any {\n if (value && typeof value === 'object') {\n // If you wonder why this is all so hard, this is the reason. We cannot lose the methods of our Array objects\n if (Array.isArray(value)) {\n return value.map(x => this.safeObjectTransform(x, mapper));\n }\n return mapper(value);\n }\n return value;\n }\n\n public forcedAutoGenTree<T extends object>(obj: T): T {\n const copy = { ...obj };\n for (const [ key, value ] of Object.entries(copy)) {\n (<Record<string, object>> copy)[key] = this.safeObjectTransform(value, obj => this.forcedAutoGenTree(obj));\n }\n if (this.isLocalized(copy)) {\n copy.loc = this.gen();\n }\n return copy;\n }\n\n public forceMaterialized<T extends Node>(arg: T): T {\n if (this.isSourceLocationNoMaterialize(arg.loc)) {\n return this.forcedAutoGenTree(arg);\n }\n return { ...arg };\n }\n\n public isSourceLocation(loc: object): loc is SourceLocation {\n return 'sourceLocationType' in loc;\n }\n\n public sourceLocationSource(start: number, end: number): SourceLocationSource {\n return {\n sourceLocationType: 'source',\n start,\n end,\n };\n }\n\n public gen(): SourceLocationNodeAutoGenerate {\n return { sourceLocationType: 'autoGenerate' };\n }\n\n public isSourceLocationSource(loc: object): loc is SourceLocationSource {\n return this.isSourceLocation(loc) && loc.sourceLocationType === 'source';\n }\n\n public isSourceLocationStringReplace(loc: object): loc is SourceLocationStringReplace {\n return this.isSourceLocation(loc) && loc.sourceLocationType === 'stringReplace';\n }\n\n public sourceLocationNodeReplaceUnsafe(loc: SourceLocation): SourceLocationNodeReplace {\n if (this.isSourceLocationSource(loc)) {\n return this.sourceLocationNodeReplace(loc);\n }\n throw new Error('not possible');\n }\n\n public sourceLocationNodeReplace(location: SourceLocationSource): SourceLocationNodeReplace;\n public sourceLocationNodeReplace(start: number, end: number): SourceLocationNodeReplace;\n public sourceLocationNodeReplace(startOrLoc: number | SourceLocationSource, end?: number): SourceLocationNodeReplace {\n let starting;\n let ending;\n if (typeof startOrLoc === 'number') {\n starting = startOrLoc;\n ending = end!;\n } else {\n starting = startOrLoc.start;\n ending = startOrLoc.end;\n }\n return {\n sourceLocationType: 'nodeReplace',\n start: starting,\n end: ending,\n };\n }\n\n public isSourceLocationNodeReplace(loc: object): loc is SourceLocationNodeReplace {\n return this.isSourceLocation(loc) && loc.sourceLocationType === 'nodeReplace';\n }\n\n public isSourceLocationNodeAutoGenerate(loc: object): loc is SourceLocationNodeAutoGenerate {\n return this.isSourceLocation(loc) && loc.sourceLocationType === 'autoGenerate';\n }\n\n public nodeShouldPrint(node: Localized): boolean {\n return this.isSourceLocationNodeReplace(node.loc) ||\n this.isSourceLocationNodeAutoGenerate(node.loc);\n }\n\n public printFilter(node: Localized, callback: () => void): void {\n if (this.nodeShouldPrint(node)) {\n callback();\n }\n }\n\n public isSourceLocationNoMaterialize(loc: object): loc is SourceLocationNoMaterialize {\n return this.isSourceLocation(loc) && loc.sourceLocationType === 'noMaterialize';\n }\n\n public isOfType<Type extends string>(obj: object, type: Type): obj is Typed<Type> {\n const casted: { type?: any } = obj;\n return casted.type === type;\n }\n\n public isOfSubType<Type extends string, SubType extends string>(obj: object, type: Type, subType: SubType):\n obj is SubTyped<Type, SubType> {\n const temp: { type?: unknown; subType?: unknown } = obj;\n return temp.type === type && temp.subType === subType;\n }\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"TransformerObject.js","sourceRoot":"","sources":["TransformerObject.ts"],"names":[],"mappings":"AAsCA,MAAM,OAAO,iBAAiB;IAMU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,GAAG,IAAI,OAAO,GAAG,KAAK,QAAQ,EAAE,CAAC;4BACnC,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;wBAClB,CAAC;oBACH,CAAC;gBACH,CAAC;YACH,CAAC;YACD,aAAa,EAAE,CAAC;QAClB,CAAC;QACD,IAAI,KAAK,CAAC,MAAM,IAAI,IAAI,CAAC,YAAY,EAAE,CAAC;YACtC,MAAM,IAAI,KAAK,CAAC,mCAAmC,CAAC,CAAC;QACvD,CAAC;QACD,aAAa,EAAE,CAAC;IAClB,CAAC;CACF","sourcesContent":["export interface VisitContext {\n /**\n * Whether you should stop iterating after this object. Default false.\n */\n shortcut?: boolean;\n /**\n * Whether you should continue iterating deeper with this object. Default true.\n */\n continue?: boolean;\n /**\n * Object keys that can be ignored, meaning they do not get visited.\n */\n ignoreKeys?: Set<string>;\n}\n\nexport interface TransformContext extends VisitContext {\n /**\n * Object keys that will be shallowly copied but not traversed.\n * When the same key is included here and in ignoreKeys, the copy will still be made.\n */\n shallowKeys?: Set<string>;\n /**\n * Whether the visited object should be shallowly copied or not. Defaults to true.\n */\n copy?: boolean;\n}\n\nexport interface SelectiveTraversalContext<Nodes> {\n /**\n * Nodes you should visit next. Defaults to empty list\n */\n next?: Nodes[];\n /**\n * Whether you should stop visiting after visiting this object. Default false.\n */\n shortcut?: boolean;\n}\n\nexport class TransformerObject {\n protected maxStackSize = 1_000_000;\n /**\n * Creates stateless transformer.\n * @param defaultContext\n */\n public constructor(protected readonly defaultContext: TransformContext = {}) {}\n\n public clone(newDefaultContext: TransformContext = {}): TransformerObject {\n return new TransformerObject({ ...this.defaultContext, ...newDefaultContext });\n }\n\n /**\n * Function to shallow clone any type.\n * @param obj\n * @protected\n */\n protected cloneObj<T>(obj: T): T {\n if (obj === null || typeof obj !== 'object') {\n return obj;\n }\n\n const proto = Object.getPrototypeOf(obj);\n\n // Fast path: plain object\n if (proto === Object.prototype || proto === null) {\n // Spread or assign preserves fast properties\n return { ...obj };\n }\n\n // Otherwise, preserve prototype for custom objects\n return Object.assign(Object.create(proto), obj);\n }\n\n /**\n * Recursively transforms all objects that are not arrays. Mapper is called on deeper objects first.\n * @param startObject object to start iterating from\n * @param mapper mapper to transform the various objects - argument is a copy of the original\n * @param preVisitor callback that is evaluated before iterating deeper.\n * If continues is false, we do not iterate deeper, current object is still mapped. - default: true\n * If shortcut is true, we do not iterate deeper, nor do we branch out, this mapper will be the last one called.\n * - Default false\n */\n public transformObject(\n startObject: object,\n mapper: (copy: object, orig: object) => unknown,\n preVisitor: (orig: object) => TransformContext = () => ({}),\n ): unknown {\n const defaults = this.defaultContext;\n const defaultCopyFlag = defaults.copy ?? true;\n const defaultContinues = defaults.continue ?? true;\n const defaultIgnoreKeys = defaults.ignoreKeys;\n const defaultShallowKeys = defaults.shallowKeys;\n const defaultDidShortCut = defaults.shortcut ?? false;\n\n // Code handles own stack instead of using recursion - this optimizes it for deep operations.\n let didShortCut = false;\n const resultWrap = { res: startObject };\n\n // Grows with stack\n const stack = [ startObject ];\n const stackParent: object[] = [ resultWrap ];\n const stackParentKey: string[] = [ 'res' ];\n\n // Grows with reverse stack - when popping down the stack, you realise you still want to map something.\n // Counter of stack size when we started adding the children of this object, going beyond this means a new parent\n const handleMapperOnLen: number[] = [];\n const mapperCopyStack: object[] = [];\n const mapperOrigStack: object[] = [];\n const mapperParent: object[] = [];\n const mapperParentKey: string[] = [];\n\n function handleMapper(): void {\n while (stack.length === handleMapperOnLen.at(-1)) {\n handleMapperOnLen.pop();\n const copyToMap = mapperCopyStack.pop()!;\n const origToMap = mapperOrigStack.pop()!;\n const parent = <Record<string, unknown>> mapperParent.pop()!;\n const parentKey = mapperParentKey.pop()!;\n parent[parentKey] = mapper(copyToMap, origToMap);\n }\n }\n\n while (stack.length > 0 && stack.length < this.maxStackSize) {\n const curObject = stack.pop()!;\n const curParent = stackParent.pop()!;\n const curKey = stackParentKey.pop()!;\n\n // Only add to the stack when you did not shortcut\n if (!didShortCut) {\n if (Array.isArray(curObject)) {\n const newArr = [ ...curObject ];\n handleMapperOnLen.push(stack.length);\n mapperCopyStack.push(newArr);\n mapperOrigStack.push(curObject);\n mapperParent.push(curParent);\n mapperParentKey.push(curKey);\n\n for (let index = curObject.length - 1; index >= 0; index--) {\n const val = curObject[index];\n if (val !== null && typeof val === 'object') {\n stack.push(val);\n stackParent.push(newArr);\n stackParentKey.push(index.toString());\n }\n }\n handleMapper();\n continue;\n }\n\n // Perform pre visit before expanding the stack\n const context = preVisitor(<any>curObject);\n const copyFlag = context.copy ?? defaultCopyFlag;\n const continues = context.continue ?? defaultContinues;\n const ignoreKeys = context.ignoreKeys ?? defaultIgnoreKeys;\n const shallowKeys = context.shallowKeys ?? defaultShallowKeys;\n didShortCut = context.shortcut ?? defaultDidShortCut;\n\n const copy = copyFlag ? this.cloneObj(curObject) : curObject;\n\n // Register that you want to be visited\n handleMapperOnLen.push(stack.length);\n mapperCopyStack.push(copy);\n mapperOrigStack.push(curObject);\n mapperParent.push(curParent);\n mapperParentKey.push(curKey);\n\n // Extend stack if needed. When shortcutted, should still unwind the stack, but no longer add to it.\n if (continues && !didShortCut) {\n for (const key in copy) {\n if (!Object.hasOwn(copy, key)) {\n continue;\n }\n const val = (<Record<string, unknown>> copy)[key];\n\n // If shallow copy required, do\n const onlyShallow = shallowKeys && shallowKeys?.has(key);\n if (onlyShallow) {\n // Do not add stack entry - assign straight away\n (<Record<string, unknown>> copy)[key] = this.cloneObj(val);\n }\n if (ignoreKeys && ignoreKeys.has(key)) {\n // Do not add stack entry\n continue;\n }\n if (!onlyShallow && val !== null && typeof val === 'object') {\n // Do add stack entry.\n stack.push(val);\n stackParentKey.push(key);\n stackParent.push(copy);\n }\n }\n }\n }\n handleMapper();\n }\n if (stack.length >= this.maxStackSize) {\n throw new Error('Transform object stack overflowed');\n }\n handleMapper();\n\n return <any> resultWrap.res;\n }\n\n /**\n * Visitor that visits all objects. Visits deeper objects first.\n */\n public visitObject(\n startObject: object,\n visitor: (orig: object) => void,\n preVisitor: (orig: object) => VisitContext = () => ({}),\n ): void {\n const defaults = this.defaultContext;\n const defaultContinues = defaults.continue ?? true;\n const defaultIgnoreKeys = defaults.ignoreKeys;\n const defaultShortcut = defaults.shortcut ?? false;\n\n let didShortCut = false;\n\n // Stack of things to preVisit\n const stack = [ startObject ];\n // When the stack is done preVisiting things above this lengths, visit the bellow\n const handleVisitorOnLen: number[] = [];\n const visitorStack: object[] = [];\n\n function handleVisitor(): void {\n while (stack.length === handleVisitorOnLen.at(-1)) {\n handleVisitorOnLen.pop();\n const toVisit = visitorStack.pop()!;\n visitor(toVisit);\n }\n }\n\n while (stack.length > 0 && stack.length < this.maxStackSize) {\n const curObject = stack.pop()!;\n\n if (!didShortCut) {\n if (Array.isArray(curObject)) {\n for (let i = curObject.length - 1; i >= 0; i--) {\n stack.push(curObject[i]);\n }\n handleVisitor();\n continue;\n }\n\n // Perform pre visit before expanding the stack\n const context = preVisitor(curObject);\n didShortCut = context.shortcut ?? defaultShortcut;\n const continues = context.continue ?? defaultContinues;\n const ignoreKeys = context.ignoreKeys ?? defaultIgnoreKeys;\n\n // Register that you want to be visited\n handleVisitorOnLen.push(stack.length);\n visitorStack.push(curObject);\n\n // Extend stack if needed. When shortcutted, should still unwind the stack, but no longer add to it.\n if (continues && !didShortCut) {\n for (const key in curObject) {\n if (!Object.hasOwn(curObject, key)) {\n continue;\n }\n if (ignoreKeys && ignoreKeys.has(key)) {\n continue;\n }\n const val = (<Record<string, unknown>> curObject)[key];\n if (val && typeof val === 'object') {\n stack.push(val);\n }\n }\n }\n }\n handleVisitor();\n }\n if (stack.length >= this.maxStackSize) {\n throw new Error('Transform object stack overflowed');\n }\n handleVisitor();\n }\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"TransformerSubTyped.js","sourceRoot":"","sources":["TransformerSubTyped.ts"],"names":[],"mappings":"AAOA,OAAO,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAC;AAEzD,MAAM,OAAO,mBAAkE,SA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,CAAM,OAAO,CAAC,CAAC;gBACnD,WAAW,GAAG,QAAQ,IAAI,KAAK,CAAC;gBAChC,IAAI,CAAC,WAAW,EAAE,CAAC;oBACjB,KAAK,MAAM,IAAI,IAAI,IAAI,IAAI,EAAE,EAAE,CAAC;wBAC9B,IAAI,WAAW,EAAE,CAAC;4BAChB,OAAO;wBACT,CAAC;wBACD,OAAO,CAAC,IAAI,CAAC,CAAC;oBAChB,CAAC;gBACH,CAAC;YACH,CAAC;QACH,CAAC,CAAC;QAEF,OAAO,CAAC,WAAW,CAAC,CAAC;IACvB,CAAC;CACF","sourcesContent":["import type { Node } from './nodeTypings.js';\nimport type {\n SelectiveTraversalContext,\n TransformContext,\n VisitContext,\n} from './TransformerObject.js';\nimport type { DefaultNodePreVisitor, Safeness, SafeWrap } from './TransformerTyped.js';\nimport { TransformerTyped } from './TransformerTyped.js';\n\nexport class TransformerSubTyped<Nodes extends Pick<Node, 'type' | 'subType'>> extends TransformerTyped<Nodes> {\n public constructor(\n defaultContext: TransformContext = {},\n defaultNodePreVisitor: DefaultNodePreVisitor<Nodes> = {},\n ) {\n super(defaultContext, defaultNodePreVisitor);\n };\n\n public override clone(\n newDefaultContext: TransformContext = {},\n newDefaultNodePreVisitor: DefaultNodePreVisitor<Nodes> = {},\n ): TransformerSubTyped<Nodes> {\n return new TransformerSubTyped(\n { ...this.defaultContext, ...newDefaultContext },\n { ...this.defaultNodePreVisitor, ...newDefaultNodePreVisitor },\n );\n }\n\n /**\n * Shares the functionality and first two arguments with {@link this.transformNode}.\n * The third argument allows you to also transform based on the subType of objects.\n * Note that when a callback for the subtype is provided, the callback for the general type is **NOT** executed.\n * @param startObject\n * @param nodeCallBacks\n * @param nodeSpecificCallBacks\n */\n public transformNodeSpecific<Safe extends Safeness = 'safe', OutType = unknown>(\n startObject: object,\n nodeCallBacks: {[T in Nodes['type']]?: {\n transform?: (copy: SafeWrap<Safe, Extract<Nodes, { type: T }>>, orig: Extract<Nodes, { type: T }>) => unknown;\n preVisitor?: (orig: Extract<Nodes, { type: T }>) => TransformContext;\n }},\n nodeSpecificCallBacks: {[Type in Nodes['type']]?: {\n [SubType in Extract<Nodes, { type: Type; subType: string }>['subType']]?: {\n transform?: (op: SafeWrap<Safe, Extract<Nodes, { type: Type; subType: SubType }>>) => unknown;\n preVisitor?: (op: Extract<Nodes, { type: Type; subType: SubType }>) => TransformContext;\n }}},\n ): Safe extends 'unsafe' ? OutType : unknown {\n const transformWrapper = (copy: object, orig: object): unknown => {\n let ogTransform: ((copy: any, orig: any) => unknown) | undefined;\n const casted = <{ type?: Nodes['type']; subType?: string }>copy;\n if (casted.type && casted.subType) {\n const specific = nodeSpecificCallBacks[casted.type];\n if (specific) {\n ogTransform = specific[<keyof typeof specific> casted.subType]?.transform;\n }\n if (!ogTransform) {\n ogTransform = nodeCallBacks[casted.type]?.transform;\n }\n }\n return ogTransform ? ogTransform(casted, orig) : copy;\n };\n const preVisitWrapper = (curObject: object): VisitContext => {\n let ogPreVisit: ((node: any) => VisitContext) | undefined;\n const casted = <{ type?: Nodes['type']; subType?: string }>curObject;\n if (casted.type && casted.subType) {\n const specific = nodeSpecificCallBacks[casted.type];\n if (specific) {\n ogPreVisit = specific[<keyof typeof specific> casted.subType]?.preVisitor;\n }\n if (!ogPreVisit) {\n ogPreVisit = nodeCallBacks[casted.type]?.preVisitor;\n }\n }\n return ogPreVisit ? ogPreVisit(casted) : {};\n };\n return <any> this.transformObject(startObject, transformWrapper, preVisitWrapper);\n }\n\n /**\n * Similar to {@link this.visitNode} but also allows you to match based on the subtype of objects.\n * When both nodeCallBack and NodeSpecific callBack are matched, will only visit nodeSpecifCallback\n */\n public visitNodeSpecific(\n startObject: object,\n nodeCallBacks: {[T in Nodes['type']]?: {\n visitor?: (op: Extract<Nodes, { type: T }>) => void;\n preVisitor?: (op: Extract<Nodes, { type: T }>) => VisitContext;\n }},\n nodeSpecificCallBacks: {[Type in Nodes['type']]?:\n {[Subtype in Extract<Nodes, { type: Type; subType: string }>['subType']]?: {\n visitor?: (op: Extract<Nodes, { type: Type; subType: Subtype }>) => void;\n preVisitor?: (op: Extract<Nodes, { type: Type; subType: Subtype }>) => VisitContext;\n }}},\n ): void {\n const visitWrapper = (curObject: object): void => {\n let ogTransform: ((node: any) => void) | undefined;\n const casted = <{ type?: Nodes['type']; subType?: string }>curObject;\n if (casted.type && casted.subType) {\n const specific = nodeSpecificCallBacks[casted.type];\n if (specific) {\n ogTransform = specific[<keyof typeof specific> casted.subType]?.visitor;\n }\n if (!ogTransform) {\n ogTransform = nodeCallBacks[casted.type]?.visitor;\n }\n }\n if (ogTransform) {\n ogTransform(casted);\n }\n };\n const preVisitWrapper = (curObject: object): VisitContext => {\n let ogPreVisit: ((node: any) => VisitContext) | undefined;\n const casted = <{ type?: Nodes['type']; subType?: string }>curObject;\n if (casted.type && casted.subType) {\n const specific = nodeSpecificCallBacks[casted.type];\n if (specific) {\n ogPreVisit = specific[<keyof typeof specific> casted.subType]?.preVisitor;\n }\n if (!ogPreVisit) {\n ogPreVisit = nodeCallBacks[casted.type]?.preVisitor;\n }\n }\n return ogPreVisit ? ogPreVisit(casted) : {};\n };\n this.visitObject(startObject, visitWrapper, preVisitWrapper);\n }\n\n /**\n * Similar to {@link this.traverseNodes} but also allows you to match based on the subtype of objects.\n * @param currentNode\n * @param traverseNode\n * @param traverseSubNode\n */\n public traverseSubNodes(\n currentNode: Nodes,\n traverseNode: {[Type in Nodes['type']]?:\n (op: Extract<Nodes, { type: Type }>) => SelectiveTraversalContext<Nodes> },\n traverseSubNode: {[Type in Nodes['type']]?:\n {[Subtype in Extract<Nodes, { type: Type; subType: string }>['subType']]?:\n (op: Extract<Nodes, { type: Type; subType: Subtype }>) => SelectiveTraversalContext<Nodes> }},\n ): void {\n let didShortCut = false;\n\n const recurse = (curNode: Nodes): void => {\n let traverser: ((call: any) => SelectiveTraversalContext<Nodes>) | undefined;\n const subObj = traverseSubNode[<Nodes['type']>curNode.type];\n if (subObj) {\n traverser = subObj[<keyof typeof subObj>curNode.subType];\n }\n if (!traverser) {\n traverser = traverseNode[<Nodes['type']>curNode.type];\n }\n if (traverser) {\n const { next, shortcut } = traverser(<any>curNode);\n didShortCut = shortcut ?? false;\n if (!didShortCut) {\n for (const node of next ?? []) {\n if (didShortCut) {\n return;\n }\n recurse(node);\n }\n }\n }\n };\n\n recurse(currentNode);\n }\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"TransformerTyped.js","sourceRoot":"","sources":["TransformerTyped.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,iBAAiB,EAAE,MAAM,wBAAwB,CAAC;AAQ3D,MAAM,OAAO,gBAAmD,SAAQ,iBAAiB;IAG3E;IAFZ,YACE,iBAAmC,EAAE,EAC3B,wBAAsD,EAAE;QAElE,KAAK,CAAC,cAAc,CAAC,CAAC;QAFZ,0BAAqB,GAArB,qBAAqB,CAAmC;IAGpE,CAAC;IAAA,CAAC;IAEc,KAAK,CACnB,oBAAsC,EAAE,EACxC,2BAAyD,EAAE;QAE3D,OAAO,IAAI,gBAAgB,CACzB,EAAE,GAAG,IAAI,CAAC,cAAc,EAAE,GAAG,iBAAiB,EAAE,EAChD,EAAE,GAAG,IAAI,CAAC,qBAAqB,EAAE,GAAG,wBAAwB,EAAE,CAC/D,CAAC;IACJ,CAAC;IAED;;;;;;;;;OASG;IACI,aAAa,CAClB,WAAmB,EACnB,aAGE;QAEF,MAAM,gBAAgB,GAAG,CAAC,IAAY,EAAE,IAAY,EAAW,EAAE;YAC/D,IAAI,WAA4D,CAAC;YACjE,MAAM,MAAM,GAA6B,IAAI,CAAC;YAC9C,IAAI,MAAM,CAAC,IAAI,EAAE,CAAC;gBAChB,WAAW,GAAG,aAAa,CAAC,MAAM,CAAC,IAAI,CAAC,EAAE,SAAS,CAAC;YACtD,CAAC;YACD,OAAO,WAAW,CAAC,CAAC,CAAC,WAAW,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC;QACxD,CAAC,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AM,CAAC,IAAI,EAAE,CAAC;gBAChB,UAAU,GAAG,aAAa,CAAC,MAAM,CAAC,IAAI,CAAC,EAAE,UAAU,CAAC;gBACpD,WAAW,GAAG,YAAY,CAAC,MAAM,CAAC,IAAI,CAAC,IAAI,WAAW,CAAC;YACzD,CAAC;YACD,OAAO,UAAU,CAAC,CAAC,CAAC,EAAE,GAAG,WAAW,EAAE,GAAG,UAAU,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC,CAAC,WAAW,CAAC;QAC9E,CAAC,CAAC;QACF,OAAO,IAAI,CAAC,WAAW,CAAC,WAAW,EAAE,cAAc,EAAE,eAAe,CAAC,CAAC;IACxE,CAAC;IAED;;;;OAIG;IACI,aAAa,CAClB,WAAkB,EAClB,QAAyG;QAEzG,IAAI,WAAW,GAAG,KAAK,CAAC;QAExB,MAAM,OAAO,GAAG,CAAC,OAAc,EAAQ,EAAE;YACvC,MAAM,SAAS,GAAG,QAAQ,CAAgB,OAAO,CAAC,IAAI,CAAC,CAAC;YACxD,IAAI,SAAS,EAAE,CAAC;gBACd,MAAM,EAAE,IAAI,EAAE,QAAQ,EAAE,GAAG,SAAS,CAAM,OAAO,CAAC,CAAC;gBACnD,WAAW,GAAG,QAAQ,IAAI,KAAK,CAAC;gBAChC,IAAI,CAAC,WAAW,EAAE,CAAC;oBACjB,KAAK,MAAM,IAAI,IAAI,IAAI,IAAI,EAAE,EAAE,CAAC;wBAC9B,IAAI,WAAW,EAAE,CAAC;4BAChB,OAAO;wBACT,CAAC;wBACD,OAAO,CAAC,IAAI,CAAC,CAAC;oBAChB,CAAC;gBACH,CAAC;YACH,CAAC;QACH,CAAC,CAAC;QAEF,OAAO,CAAC,WAAW,CAAC,CAAC;IACvB,CAAC;CACF","sourcesContent":["import type { Node } from './nodeTypings.js';\nimport type { SelectiveTraversalContext, TransformContext, VisitContext } from './TransformerObject.js';\nimport { TransformerObject } from './TransformerObject.js';\n\nexport type Safeness = 'safe' | 'unsafe';\nexport type SafeWrap<Safe extends Safeness, obj extends object> =\n Safe extends 'safe' ? {[key in keyof obj]: unknown } : obj;\n\nexport type DefaultNodePreVisitor<Nodes extends Pick<Node, 'type'>> = {[T in Nodes['type']]?: TransformContext };\n\nexport class TransformerTyped<Nodes extends Pick<Node, 'type'>> extends TransformerObject {\n public constructor(\n defaultContext: TransformContext = {},\n protected defaultNodePreVisitor: DefaultNodePreVisitor<Nodes> = {},\n ) {\n super(defaultContext);\n };\n\n public override clone(\n newDefaultContext: TransformContext = {},\n newDefaultNodePreVisitor: DefaultNodePreVisitor<Nodes> = {},\n ): TransformerTyped<Nodes> {\n return new TransformerTyped(\n { ...this.defaultContext, ...newDefaultContext },\n { ...this.defaultNodePreVisitor, ...newDefaultNodePreVisitor },\n );\n }\n\n /**\n * Transform a single node.\n * The transformation calls the preVisitor from starting from the startObject.\n * The preVisitor can dictate whether transformation should be stopped.\n * Note that stopping the transformation also prevets further copying.\n * The transformer itself transforms object starting with the deepest one that can be visited.\n * The transformer callback is performed on a copy of the original.\n * @param startObject\n * @param nodeCallBacks\n */\n public transformNode<Safe extends Safeness = 'safe', OutType = unknown>(\n startObject: object,\n nodeCallBacks: {[T in Nodes['type']]?: {\n transform?: (copy: SafeWrap<Safe, Extract<Nodes, { type: T }>>, orig: Extract<Nodes, { type: T }>) => unknown;\n preVisitor?: (orig: Extract<Nodes, { type: T }>) => TransformContext;\n }},\n ): Safe extends 'unsafe' ? OutType : unknown {\n const transformWrapper = (copy: object, orig: object): unknown => {\n let ogTransform: ((copy: any, orig: any) => unknown) | undefined;\n const casted = <{ type?: Nodes['type'] }>copy;\n if (casted.type) {\n ogTransform = nodeCallBacks[casted.type]?.transform;\n }\n return ogTransform ? ogTransform(casted, orig) : copy;\n };\n const nodeDefaults = this.defaultNodePreVisitor;\n const preVisitWrapper = (curObject: object): VisitContext => {\n let ogPreVisit: ((node: any) => VisitContext) | undefined;\n let nodeContext: VisitContext = {};\n const casted = <{ type?: Nodes['type'] }>curObject;\n if (casted.type) {\n ogPreVisit = nodeCallBacks[casted.type]?.preVisitor;\n nodeContext = nodeDefaults[casted.type] ?? nodeContext;\n }\n return ogPreVisit ? { ...nodeContext, ...ogPreVisit(casted) } : nodeContext;\n };\n return <any> this.transformObject(startObject, transformWrapper, preVisitWrapper);\n }\n\n /**\n * Similar to {@link this.transformNode}, but without copying the startObject.\n * The pre-visitor visits starting from the root, going deeper, while the actual visitor goes in reverse.\n * @param startObject\n * @param nodeCallBacks\n */\n public visitNode(\n startObject: object,\n nodeCallBacks: {[T in Nodes['type']]?: {\n visitor?: (op: Extract<Nodes, { type: T }>) => void;\n preVisitor?: (op: Extract<Nodes, { type: T }>) => VisitContext;\n }},\n ): void {\n const visitorWrapper = (curObject: object): void => {\n const casted = <{ type?: Nodes['type'] }>curObject;\n if (casted.type) {\n const ogTransform = nodeCallBacks[casted.type]?.visitor;\n if (ogTransform) {\n ogTransform(<any> casted);\n }\n }\n };\n const nodeDefaults = this.defaultNodePreVisitor;\n const preVisitWrapper = (curObject: object): VisitContext => {\n let ogPreVisit: ((node: any) => VisitContext) | undefined;\n let nodeContext: VisitContext = {};\n const casted = <{ type?: Nodes['type'] }>curObject;\n if (casted.type) {\n ogPreVisit = nodeCallBacks[casted.type]?.preVisitor;\n nodeContext = nodeDefaults[casted.type] ?? nodeContext;\n }\n return ogPreVisit ? { ...nodeContext, ...ogPreVisit(casted) } : nodeContext;\n };\n return this.visitObject(startObject, visitorWrapper, preVisitWrapper);\n }\n\n /**\n * Traverses only selected nodes as returned by the function.\n * @param currentNode\n * @param traverse\n */\n public traverseNodes(\n currentNode: Nodes,\n traverse: {[T in Nodes['type']]?: (op: Extract<Nodes, { type: T }>) => SelectiveTraversalContext<Nodes> },\n ): void {\n let didShortCut = false;\n\n const recurse = (curNode: Nodes): void => {\n const traverser = traverse[<Nodes['type']>curNode.type];\n if (traverser) {\n const { next, shortcut } = traverser(<any>curNode);\n didShortCut = shortcut ?? false;\n if (!didShortCut) {\n for (const node of next ?? []) {\n if (didShortCut) {\n return;\n }\n recurse(node);\n }\n }\n }\n };\n\n recurse(currentNode);\n }\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"builderTypes.js","sourceRoot":"","sources":["builderTypes.ts"],"names":[],"mappings":"","sourcesContent":["import type { ParseNamesFromList } from '../parser-builder/builderTypes.js';\nimport type { GeneratorRule } from './generatorTypes.js';\n\n/**\n * Convert a list of ruledefs to a record that maps each rule name to its definition.\n */\nexport type GenRuleMap<RuleNames extends string> = {[Key in RuleNames]: GeneratorRule<any, Key> };\n\n/**\n * Convert a list of RuleDefs to a Record with the name of the RuleDef as the key, matching the RuleDefMap type.\n */\nexport type GenRulesToObject<\n T extends readonly GeneratorRule[],\n Names extends string = ParseNamesFromList<T>,\n Agg extends Record<string, GeneratorRule> = Record<never, never>,\n> = T extends readonly [infer First, ...infer Rest] ? (\n First extends GeneratorRule ? (\n Rest extends readonly GeneratorRule[] ? (\n GenRulesToObject<Rest, Names, {[K in keyof Agg | First['name']]: K extends First['name'] ? First : Agg[K] }>\n ) : never\n ) : never\n) : GenRuleMap<Names> & Agg;\n\nexport type GeneratorFromRules<Context, Names extends string, RuleDefs extends GenRuleMap<Names>> = {\n [K in Names]: RuleDefs[K] extends GeneratorRule<Context, K, infer RET, infer ARGS> ?\n (input: RET, context: Context & { origSource: string; offset?: number }, ...args: ARGS) => string : never\n};\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"dynamicGenerator.js","sourceRoot":"","sources":["dynamicGenerator.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AACtD,OAAO,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AAIjD,MAAM,OAAO,gBAAgB;IAYE;IAXV,OAAO,GAAG,IAAI,cAAc,EAAE,CAAC;IACxC,SAAS,GAAwB,SAAS,CAAC;IAC3C,UAAU,GAAG,EAAE,CAAC;IAChB,cAAc,GAAG,CAAC,CAAC;IACnB,QAAQ,GAAoC,EAA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G,IAAI,EAAE,EAAE;QAClE,KAAK,MAAM,GAAG,IAAI,IAAI,EAAE,CAAC;YACvB,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC;QACtB,CAAC;IACH,CAAC,CAAC;IAEe,YAAY,GAAiC,CAAC,GAAG,IAAI,EAAE,EAAE;QACxE,IAAI,CAAC,OAAO,EAAE,CAAC;QACf,IAAI,CAAC,KAAK,CAAC,GAAG,IAAI,CAAC,CAAC;IACtB,CAAC,CAAC;IAEe,cAAc,GAAoC,CAAC,GAAG,IAAI,EAAE,EAAE;QAC7E,IAAI,CAAC,OAAO,EAAE,CAAC;QACf,IAAI,CAAC,KAAK,CAAC,GAAG,IAAI,CAAC,CAAC;QACpB,IAAI,CAAC,OAAO,EAAE,CAAC;IACjB,CAAC,CAAC;CACH","sourcesContent":["import { AstCoreFactory } from '../AstCoreFactory.js';\nimport { traqulaIndentation } from '../utils.js';\nimport type { GenRuleMap } from './builderTypes.js';\nimport type { GeneratorRule, RuleDefArg } from './generatorTypes.js';\n\nexport class DynamicGenerator<Context, Names extends string, RuleDefs extends GenRuleMap<Names>> {\n protected readonly factory = new AstCoreFactory();\n protected __context: Context | undefined = undefined;\n protected origSource = '';\n protected generatedUntil = 0;\n protected toEnsure: ((willPrint: string) => void)[] = [];\n /**\n * Should not contain empty strings\n * @protected\n */\n protected readonly stringBuilder: string[] = [];\n\n public constructor(protected rules: RuleDefs) {\n // eslint-disable-next-line ts/no-unnecessary-type-assertion\n for (const rule of <GeneratorRule[]> Object.values(rules)) {\n // Define function implementation\n this[<keyof (typeof this)> rule.name] =\n <any> ((input: any, context: Context & { origSource: string; offset?: number }, args: any) => {\n this.stringBuilder.length = 0;\n this.origSource = context.origSource;\n this.generatedUntil = context?.offset ?? 0;\n this.setContext(context);\n\n this.subrule(rule, input, args);\n\n this.catchup(this.origSource.length);\n\n return this.stringBuilder.join('');\n });\n }\n }\n\n public setContext(context: Context): void {\n this.__context = context;\n }\n\n protected getSafeContext(): Context & { [traqulaIndentation]?: number } {\n return <Context & { [traqulaIndentation]?: number }> this.__context;\n }\n\n protected readonly subrule: RuleDefArg['SUBRULE'] = (cstDef, ast, ...arg) => {\n const def = this.rules[<Names> cstDef.name];\n if (!def) {\n throw new Error(`Rule ${cstDef.name} not found`);\n }\n\n const generate = (): void => def.gImpl({\n SUBRULE: this.subrule,\n PRINT: this.print,\n ENSURE: this.ensure,\n ENSURE_EITHER: this.ensureEither,\n NEW_LINE: this.newLine,\n HANDLE_LOC: this.handleLoc,\n CATCHUP: this.catchup,\n\n PRINT_WORD: this.printWord,\n PRINT_WORDS: this.printWords,\n PRINT_ON_EMPTY: this.printOnEmpty,\n PRINT_ON_OWN_LINE: this.printOnOwnLine,\n })(ast, this.getSafeContext(), ...arg);\n\n if (this.factory.isLocalized(ast)) {\n this.handleLoc(ast, generate);\n } else {\n generate();\n }\n };\n\n protected readonly handleLoc: RuleDefArg['HANDLE_LOC'] = (localized, handle) => {\n if (this.factory.isSourceLocationNoMaterialize(localized.loc)) {\n return;\n }\n if (this.factory.isSourceLocationStringReplace(localized.loc)) {\n this.catchup(localized.loc.start);\n this.print(localized.loc.newSource);\n this.generatedUntil = localized.loc.end;\n return;\n }\n if (this.factory.isSourceLocationNodeReplace(localized.loc)) {\n this.catchup(localized.loc.start);\n this.generatedUntil = localized.loc.end;\n }\n if (this.factory.isSourceLocationSource(localized.loc)) {\n this.catchup(localized.loc.start);\n }\n // If autoGenerate - do nothing\n\n const ret = handle();\n\n if (this.factory.isSourceLocationSource(localized.loc)) {\n this.catchup(localized.loc.end);\n }\n return ret;\n };\n\n protected readonly catchup: RuleDefArg['CATCHUP'] = (until) => {\n const start = this.generatedUntil;\n if (start < until) {\n this.print(this.origSource.slice(start, until));\n }\n this.generatedUntil = Math.max(this.generatedUntil, until);\n };\n\n private handeEnsured(toPrint: string): void {\n for (const callBack of this.toEnsure) {\n callBack(toPrint);\n }\n this.toEnsure.length = 0;\n }\n\n protected readonly print: RuleDefArg['PRINT'] = (...args) => {\n const joined = args.join('');\n this.handeEnsured(joined);\n this.stringBuilder.push(joined);\n };\n\n private doesEndWith(subsStr: string): boolean {\n const len = subsStr.length;\n let temp = '';\n while (temp.length < len && this.stringBuilder.length > 0) {\n temp = this.stringBuilder.pop() + temp;\n }\n this.stringBuilder.push(temp);\n return temp.endsWith(subsStr);\n }\n\n protected readonly ensure: RuleDefArg['ENSURE'] = (...args) => {\n // Check whether already present\n const toEnsure = args.join('');\n if (!this.doesEndWith(toEnsure)) {\n this.toEnsure.push((willPrint) => {\n if (!willPrint.startsWith(toEnsure) && !this.doesEndWith(toEnsure)) {\n this.stringBuilder.push(toEnsure);\n }\n });\n }\n };\n\n protected readonly ensureEither: RuleDefArg['ENSURE_EITHER'] = (...args) => {\n if (args.length === 1) {\n this.ensure(...args);\n } else if (args.length > 1 &&\n // Not already matched?\n !args.some(subStr => this.doesEndWith(subStr))) {\n this.toEnsure.push((willPrint) => {\n if (!args.some(subStr => willPrint.startsWith(subStr)) && !args.some(subStr => this.doesEndWith(subStr))) {\n this.stringBuilder.push(args[0]);\n }\n });\n }\n };\n\n private pruneEndingBlanks(): void {\n let temp = '';\n while (/^[ \\t]*$/u.test(temp) && this.stringBuilder.length > 0) {\n temp = this.stringBuilder.pop() + temp;\n }\n this.print(temp.trimEnd());\n }\n\n protected readonly newLine: RuleDefArg['NEW_LINE'] = (arg) => {\n const indentation = this.getSafeContext()[traqulaIndentation] ?? 0;\n if (indentation === -1) {\n return;\n }\n const force = arg?.force ?? false;\n this.pruneEndingBlanks();\n if (force) {\n this.print('\\n', ' '.repeat(indentation));\n } else {\n let temp = '';\n while (!temp.includes('\\n') && this.stringBuilder.length > 0) {\n temp = this.stringBuilder.pop() + temp;\n }\n if (/\\n[ \\t]*$/u.test(temp)) {\n // Pointer is on empty newline -> set correct indentation\n temp = temp.replace(/\\n[ \\t]*$/u, `\\n${' '.repeat(indentation)}`);\n this.print(temp);\n } else {\n // Pointer not on empty newline, print newline.\n this.print(temp, '\\n', ' '.repeat(indentation));\n }\n }\n };\n\n private readonly printWord: RuleDefArg['PRINT_WORD'] = (...args) => {\n this.ensureEither(' ', '\\n');\n this.print(...args);\n this.ensureEither(' ', '\\n');\n };\n\n private readonly printWords: RuleDefArg['PRINT_WORD'] = (...args) => {\n for (const arg of args) {\n this.printWord(arg);\n }\n };\n\n private readonly printOnEmpty: RuleDefArg['PRINT_ON_EMPTY'] = (...args) => {\n this.newLine();\n this.print(...args);\n };\n\n private readonly printOnOwnLine: RuleDefArg['PRINT_ON_OWN_LINE'] = (...args) => {\n this.newLine();\n this.print(...args);\n this.newLine();\n };\n}\n"]}