@tylix/compiler 0.1.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.
Files changed (49) hide show
  1. package/package.json +12 -0
  2. package/src/ast/nodes.js +143 -0
  3. package/src/codegen/generateExpression.array.test.js +13 -0
  4. package/src/codegen/generateExpression.callexpr.test.js +19 -0
  5. package/src/codegen/generateExpression.js +92 -0
  6. package/src/codegen/generateExpression.test.js +59 -0
  7. package/src/codegen/generateMethod.asyncawait.test.js +37 -0
  8. package/src/codegen/generateMethod.ifstatement.test.js +20 -0
  9. package/src/codegen/generateMethod.js +13 -0
  10. package/src/codegen/generateMethod.test.js +79 -0
  11. package/src/codegen/generatePage.js +79 -0
  12. package/src/codegen/generatePage.onmount.test.js +33 -0
  13. package/src/codegen/generatePage.test.js +138 -0
  14. package/src/codegen/generateStatement.js +64 -0
  15. package/src/codegen/generateStatement.test.js +31 -0
  16. package/src/codegen/generateTemplate.ifeach.test.js +138 -0
  17. package/src/codegen/generateTemplate.js +264 -0
  18. package/src/codegen/generateTemplate.test.js +149 -0
  19. package/src/codegen/generateTemplateExpression.js +55 -0
  20. package/src/codegen/generateTemplateExpression.test.js +34 -0
  21. package/src/compileComponent.js +54 -0
  22. package/src/compileComponent.test.js +121 -0
  23. package/src/index.js +15 -0
  24. package/src/lexer/Lexer.js +336 -0
  25. package/src/lexer/Lexer.test.js +151 -0
  26. package/src/lexer/tokenTypes.js +114 -0
  27. package/src/parser/Parser.array.test.js +37 -0
  28. package/src/parser/Parser.asyncawait.test.js +33 -0
  29. package/src/parser/Parser.ifstatement.test.js +20 -0
  30. package/src/parser/Parser.js +677 -0
  31. package/src/parser/Parser.onmount.test.js +18 -0
  32. package/src/parser/Parser.test.js +227 -0
  33. package/src/parser/parseComponent.js +29 -0
  34. package/src/parser/parseComponent.test.js +53 -0
  35. package/src/parser/parseComponentFile.js +55 -0
  36. package/src/parser/parseExpressionString.js +13 -0
  37. package/src/parser/parsePageFile.js +94 -0
  38. package/src/parser/parsePageFile.test.js +101 -0
  39. package/src/parser/parseTemplate.ifeach.test.js +33 -0
  40. package/src/parser/parseTemplate.js +319 -0
  41. package/src/parser/parseTemplate.pre.test.js +39 -0
  42. package/src/parser/parseTemplate.test.js +96 -0
  43. package/src/renderPageDocument.js +250 -0
  44. package/src/renderPageDocument.test.js +125 -0
  45. package/src/runtime/loadingIndicator.js +35 -0
  46. package/src/runtime/reactive.js +59 -0
  47. package/src/runtime/reactive.test.js +106 -0
  48. package/src/runtime/useApi.js +45 -0
  49. package/src/runtime/useChannel.js +38 -0
package/package.json ADDED
@@ -0,0 +1,12 @@
1
+ {
2
+ "name": "@tylix/compiler",
3
+ "version": "0.1.0",
4
+ "type": "module",
5
+ "main": "./src/index.js",
6
+ "scripts": {
7
+ "test": "node --test src/*.test.js src/**/*.test.js"
8
+ },
9
+ "devDependencies": {
10
+ "jsdom": "^24.0.0"
11
+ }
12
+ }
@@ -0,0 +1,143 @@
1
+ /**
2
+ * Plain-object AST node factories for the Tylix script grammar.
3
+ * Every node has a `type` discriminator so the codegen stage (and
4
+ * later, the Analyzer) can switch on it without instanceof checks.
5
+ */
6
+ export function PageNode({
7
+ props = [],
8
+ state = [],
9
+ computed = [],
10
+ actions = [],
11
+ onMount = null,
12
+ }) {
13
+ return { type: 'Page', props, state, computed, actions, onMount }
14
+ }
15
+
16
+ export function PropNode(name, propType) {
17
+ return { type: 'Prop', name, propType }
18
+ }
19
+
20
+ export function StateNode(name, value) {
21
+ return { type: 'State', name, value }
22
+ }
23
+
24
+ export function MethodNode(name, params, body) {
25
+ return { type: 'Method', name, params, body }
26
+ }
27
+
28
+ export function AssignmentExpr(target, value) {
29
+ return { type: 'AssignmentExpression', target, value }
30
+ }
31
+
32
+ export function BinaryExpr(operator, left, right) {
33
+ return { type: 'BinaryExpression', operator, left, right }
34
+ }
35
+
36
+ export function Identifier(name) {
37
+ return { type: 'Identifier', name }
38
+ }
39
+
40
+ export function MemberExpr(object, property, computed = false) {
41
+ return { type: 'MemberExpression', object, property, computed }
42
+ }
43
+
44
+ export function NewExpr(callee, args) {
45
+ return { type: 'NewExpression', callee, args }
46
+ }
47
+
48
+ export function Literal(value) {
49
+ return { type: 'Literal', value }
50
+ }
51
+
52
+ export function ReturnStatement(argument) {
53
+ return { type: 'ReturnStatement', argument }
54
+ }
55
+
56
+ export function ExpressionStatement(expression) {
57
+ return { type: 'ExpressionStatement', expression }
58
+ }
59
+
60
+ export function ElementNode(tag, attributes, children) {
61
+ return { type: 'Element', tag, attributes, children }
62
+ }
63
+
64
+ export function AttributeNode(name, value, dynamic) {
65
+ return { type: 'Attribute', name, value, dynamic }
66
+ }
67
+
68
+ export function TextNode(value) {
69
+ return { type: 'Text', value }
70
+ }
71
+
72
+ export function InterpolationNode(expression) {
73
+ return { type: 'Interpolation', expression }
74
+ }
75
+
76
+ export function IfNode(condition, children) {
77
+ return { type: 'If', condition, children }
78
+ }
79
+
80
+ export function EachNode(itemName, iterable, children) {
81
+ return { type: 'Each', itemName, iterable, children }
82
+ }
83
+
84
+ export function CallExpr(callee, args) {
85
+ return { type: 'CallExpression', callee, args }
86
+ }
87
+
88
+ export function AwaitExpr(argument) {
89
+ return { type: 'AwaitExpression', argument }
90
+ }
91
+
92
+ export function VariableDeclaration(kind, name, init) {
93
+ return { type: 'VariableDeclaration', kind, name, init }
94
+ }
95
+
96
+ export function ObjectExpr(properties) {
97
+ // properties: [{ key, value }]
98
+ return { type: 'ObjectExpression', properties }
99
+ }
100
+
101
+ export function ArrayExpr(elements) {
102
+ return { type: 'ArrayExpression', elements }
103
+ }
104
+
105
+ export function IfStatement(condition, consequent, alternate) {
106
+ return { type: 'IfStatement', condition, consequent, alternate }
107
+ }
108
+
109
+ export function UnaryExpr(operator, argument) {
110
+ return { type: 'UnaryExpression', operator, argument }
111
+ }
112
+
113
+ export function TernaryExpr(condition, consequent, alternate) {
114
+ return { type: 'TernaryExpression', condition, consequent, alternate }
115
+ }
116
+
117
+ export function ForInStatement(varName, iterable, body) {
118
+ return { type: 'ForInStatement', varName, iterable, body }
119
+ }
120
+
121
+ export function ForRangeStatement(varName, start, end, body) {
122
+ return { type: 'ForRangeStatement', varName, start, end, body }
123
+ }
124
+
125
+ export function RepeatStatement(count, body) {
126
+ return { type: 'RepeatStatement', count, body }
127
+ }
128
+
129
+ export function BreakStatement() {
130
+ return { type: 'BreakStatement' }
131
+ }
132
+
133
+ export function ContinueStatement() {
134
+ return { type: 'ContinueStatement' }
135
+ }
136
+
137
+ export function ArrowFunctionExpr(params, body) {
138
+ return { type: 'ArrowFunctionExpression', params, body }
139
+ }
140
+
141
+ export function TemplateLiteralExpr(parts) {
142
+ return { type: 'TemplateLiteralExpression', parts }
143
+ }
@@ -0,0 +1,13 @@
1
+ import { test } from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { generateExpression } from "./generateExpression.js";
4
+ import { ArrayExpr, Literal } from "../ast/nodes.js";
5
+
6
+ test("generates an empty array literal", () => {
7
+ assert.equal(generateExpression(ArrayExpr([])), "[]");
8
+ });
9
+
10
+ test("generates an array literal with literal elements", () => {
11
+ const node = ArrayExpr([Literal(1), Literal(2), Literal("x")]);
12
+ assert.equal(generateExpression(node), '[1, 2, "x"]');
13
+ });
@@ -0,0 +1,19 @@
1
+ import { test } from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { generateExpression } from "./generateExpression.js";
4
+ import { CallExpr, MemberExpr, Identifier, Literal } from "../ast/nodes.js";
5
+
6
+ test("generates a call with no arguments", () => {
7
+ const node = CallExpr(MemberExpr(Identifier("this"), "load"), []);
8
+ assert.equal(generateExpression(node), "this.load()");
9
+ });
10
+
11
+ test("generates a call with multiple arguments", () => {
12
+ const node = CallExpr(Identifier("remove"), [Literal(1), Literal("x")]);
13
+ assert.equal(generateExpression(node), 'remove(1, "x")');
14
+ });
15
+
16
+ test("generates a call with a member-expression argument", () => {
17
+ const node = CallExpr(Identifier("remove"), [MemberExpr(Identifier("post"), "id")]);
18
+ assert.equal(generateExpression(node), "remove(post.id)");
19
+ });
@@ -0,0 +1,92 @@
1
+ /**
2
+ * Compiles a single expression AST node into a JS source string.
3
+ * Used both for method-body statements and template interpolations,
4
+ * so every consumer (class codegen, template codegen) shares one
5
+ * source of truth for expression -> JS translation.
6
+ */
7
+ export function generateExpression(node) {
8
+ switch (node.type) {
9
+ case 'Literal':
10
+ return typeof node.value === 'string'
11
+ ? JSON.stringify(node.value)
12
+ : String(node.value)
13
+
14
+ case 'Identifier':
15
+ return node.name
16
+
17
+ case 'MemberExpression':
18
+ return node.computed
19
+ ? `${generateExpression(node.object)}[${generateExpression(node.property)}]`
20
+ : `${generateExpression(node.object)}.${node.property}`
21
+
22
+ case 'NewExpression': {
23
+ const args = node.args.map((a) => generateExpression(a)).join(', ')
24
+ return `new ${generateExpression(node.callee)}(${args})`
25
+ }
26
+
27
+ case 'BinaryExpression':
28
+ return `(${generateExpression(node.left)} ${node.operator} ${generateExpression(node.right)})`
29
+
30
+ case 'UnaryExpression':
31
+ return `(${node.operator}${generateExpression(node.argument)})`
32
+
33
+ case 'TernaryExpression':
34
+ return `(${generateExpression(node.condition)} ? ${generateExpression(node.consequent)} : ${generateExpression(node.alternate)})`
35
+
36
+ case 'ArrowFunctionExpression': {
37
+ const params = node.params.join(', ')
38
+ return `(${params}) => (${generateExpression(node.body)})`
39
+ }
40
+
41
+ case 'TemplateLiteralExpression': {
42
+ const inner = node.parts
43
+ .map((p) =>
44
+ p.type === 'text'
45
+ ? escapeTemplateText(p.value)
46
+ : `\${${generateExpression(p.expression)}}`,
47
+ )
48
+ .join('')
49
+ return `\`${inner}\``
50
+ }
51
+
52
+ case 'AssignmentExpression':
53
+ return `${generateExpression(node.target)} = ${generateExpression(node.value)}`
54
+
55
+ case 'CallExpression': {
56
+ const args = node.args.map((a) => generateExpression(a)).join(', ')
57
+ return `${generateExpression(node.callee)}(${args})`
58
+ }
59
+
60
+ case 'AwaitExpression':
61
+ return `await ${generateExpression(node.argument)}`
62
+
63
+ case 'ObjectExpression': {
64
+ const props = node.properties
65
+ .map((p) => `${JSON.stringify(p.key)}: ${generateExpression(p.value)}`)
66
+ .join(', ')
67
+ return `{ ${props} }`
68
+ }
69
+
70
+ case 'ArrayExpression': {
71
+ const elements = node.elements
72
+ .map((e) => generateExpression(e))
73
+ .join(', ')
74
+ return `[${elements}]`
75
+ }
76
+
77
+ default:
78
+ throw new Error(`generateExpression: unknown node type "${node.type}"`)
79
+ }
80
+ }
81
+
82
+ // Escapes characters that would otherwise break out of the generated
83
+ // JS template literal's own backtick delimiters -- backslashes,
84
+ // literal backticks, and literal "${" sequences appearing in static
85
+ // text parts (as opposed to real interpolations, which are already
86
+ // handled separately above).
87
+ function escapeTemplateText(text) {
88
+ return text
89
+ .replace(/\\/g, '\\\\')
90
+ .replace(/`/g, '\\`')
91
+ .replace(/\$\{/g, '\\${')
92
+ }
@@ -0,0 +1,59 @@
1
+ import { test } from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { generateExpression } from "./generateExpression.js";
4
+ import {
5
+ Literal,
6
+ Identifier,
7
+ MemberExpr,
8
+ BinaryExpr,
9
+ AssignmentExpr,
10
+ } from "../ast/nodes.js";
11
+
12
+ test("generates a number literal", () => {
13
+ assert.equal(generateExpression(Literal(42)), "42");
14
+ });
15
+
16
+ test("generates a string literal as a properly quoted JS string", () => {
17
+ assert.equal(generateExpression(Literal("hello")), '"hello"');
18
+ });
19
+
20
+ test("generates an identifier", () => {
21
+ assert.equal(generateExpression(Identifier("count")), "count");
22
+ });
23
+
24
+ test("generates a member expression", () => {
25
+ const node = MemberExpr(Identifier("this"), "count");
26
+ assert.equal(generateExpression(node), "this.count");
27
+ });
28
+
29
+ test("generates a chained member expression", () => {
30
+ const node = MemberExpr(MemberExpr(Identifier("this"), "state"), "count");
31
+ assert.equal(generateExpression(node), "this.state.count");
32
+ });
33
+
34
+ test("generates a binary expression wrapped in parens", () => {
35
+ const node = BinaryExpr("+", Identifier("count"), Literal(1));
36
+ assert.equal(generateExpression(node), "(count + 1)");
37
+ });
38
+
39
+ test("generates a nested binary expression", () => {
40
+ const node = BinaryExpr("*", BinaryExpr("+", Identifier("a"), Identifier("b")), Literal(2));
41
+ assert.equal(generateExpression(node), "((a + b) * 2)");
42
+ });
43
+
44
+ test("generates an assignment expression", () => {
45
+ const node = AssignmentExpr(MemberExpr(Identifier("this"), "count"), Literal(0));
46
+ assert.equal(generateExpression(node), "this.count = 0");
47
+ });
48
+
49
+ test("generates an assignment with a binary expression value", () => {
50
+ const node = AssignmentExpr(
51
+ MemberExpr(Identifier("this"), "count"),
52
+ BinaryExpr("+", MemberExpr(Identifier("this"), "count"), Literal(1))
53
+ );
54
+ assert.equal(generateExpression(node), "this.count = (this.count + 1)");
55
+ });
56
+
57
+ test("throws on an unknown node type", () => {
58
+ assert.throws(() => generateExpression({ type: "Bogus" }), /unknown node type "Bogus"/);
59
+ });
@@ -0,0 +1,37 @@
1
+ import { test } from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { generateMethod } from "./generateMethod.js";
4
+ import { Parser } from "../parser/Parser.js";
5
+ import { Lexer } from "../lexer/Lexer.js";
6
+
7
+ test("generates a real async method that awaits a resolved promise", async () => {
8
+ const source = `
9
+ action
10
+ async load() {
11
+ const value = await this.fetchValue()
12
+ this.result = value
13
+ }`;
14
+ const page = new Parser(new Lexer(source).tokenize()).parse();
15
+ const methodSource = generateMethod(page.actions[0]);
16
+
17
+ const classSource = `class Test {
18
+ constructor() { this.result = null; }
19
+ async fetchValue() { return 42; }
20
+ ${methodSource}
21
+ }`;
22
+ const TestClass = new Function(`return ${classSource}`)();
23
+ const instance = new TestClass();
24
+ await instance.load();
25
+ assert.equal(instance.result, 42);
26
+ });
27
+
28
+ test("generates an object literal argument correctly", () => {
29
+ const source = `
30
+ action
31
+ async save() {
32
+ await this.post({ method: "POST", id: 5 })
33
+ }`;
34
+ const page = new Parser(new Lexer(source).tokenize()).parse();
35
+ const methodSource = generateMethod(page.actions[0]);
36
+ assert.match(methodSource, /this\.post\(\{ "method": "POST", "id": 5 \}\)/);
37
+ });
@@ -0,0 +1,20 @@
1
+ import { test } from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { generateMethod } from "./generateMethod.js";
4
+ import { Parser } from "../parser/Parser.js";
5
+ import { Lexer } from "../lexer/Lexer.js";
6
+
7
+ test("generates a real if/else branch that executes correctly", () => {
8
+ const source = `action\ncheck(ok) {\n if (ok) {\n this.result = "yes"\n } else {\n this.result = "no"\n }\n}`;
9
+ const page = new Parser(new Lexer(source).tokenize()).parse();
10
+ const methodSource = generateMethod(page.actions[0]);
11
+
12
+ const classSource = `class Test { constructor() { this.result = null; } ${methodSource} }`;
13
+ const TestClass = new Function(`return ${classSource}`)();
14
+ const instance = new TestClass();
15
+
16
+ instance.check(true);
17
+ assert.equal(instance.result, "yes");
18
+ instance.check(false);
19
+ assert.equal(instance.result, "no");
20
+ });
@@ -0,0 +1,13 @@
1
+ import { generateStatement } from "./generateStatement.js";
2
+
3
+ /**
4
+ * Compiles a MethodNode (used for both `computed` and `action` entries)
5
+ * into a JS class method source string, indented for readability in
6
+ * generated output.
7
+ */
8
+ export function generateMethod(node) {
9
+ const params = node.params.join(", ");
10
+ const body = node.body.map((stmt) => ` ${generateStatement(stmt)}`).join("\n");
11
+ const asyncPrefix = node.isAsync ? "async " : "";
12
+ return ` ${asyncPrefix}${node.name}(${params}) {\n${body}\n }`;
13
+ }
@@ -0,0 +1,79 @@
1
+ import { test } from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { generateMethod } from "./generateMethod.js";
4
+ import {
5
+ MethodNode,
6
+ ReturnStatement,
7
+ ExpressionStatement,
8
+ AssignmentExpr,
9
+ BinaryExpr,
10
+ MemberExpr,
11
+ Identifier,
12
+ Literal,
13
+ } from "../ast/nodes.js";
14
+
15
+ test("generates a zero-parameter method with a single return statement", () => {
16
+ const node = MethodNode(
17
+ "doubled",
18
+ [],
19
+ [ReturnStatement(BinaryExpr("*", MemberExpr(Identifier("this"), "count"), Literal(2)))]
20
+ );
21
+
22
+ const code = generateMethod(node);
23
+ assert.equal(code, " doubled() {\n return (this.count * 2);\n }");
24
+ });
25
+
26
+ test("generates a method with parameters", () => {
27
+ const node = MethodNode("setCount", ["value"], [
28
+ ExpressionStatement(AssignmentExpr(MemberExpr(Identifier("this"), "count"), Identifier("value"))),
29
+ ]);
30
+
31
+ const code = generateMethod(node);
32
+ assert.equal(code, " setCount(value) {\n this.count = value;\n }");
33
+ });
34
+
35
+ test("generates a method with multiple statements", () => {
36
+ const node = MethodNode(
37
+ "increment",
38
+ [],
39
+ [
40
+ ExpressionStatement(
41
+ AssignmentExpr(
42
+ MemberExpr(Identifier("this"), "count"),
43
+ BinaryExpr("+", MemberExpr(Identifier("this"), "count"), Literal(1))
44
+ )
45
+ ),
46
+ ReturnStatement(MemberExpr(Identifier("this"), "count")),
47
+ ]
48
+ );
49
+
50
+ const code = generateMethod(node);
51
+ assert.equal(
52
+ code,
53
+ " increment() {\n this.count = (this.count + 1);\n return this.count;\n }"
54
+ );
55
+ });
56
+
57
+ test("the generated method source is valid, executable JavaScript", () => {
58
+ const node = MethodNode(
59
+ "increment",
60
+ [],
61
+ [
62
+ ExpressionStatement(
63
+ AssignmentExpr(
64
+ MemberExpr(Identifier("this"), "count"),
65
+ BinaryExpr("+", MemberExpr(Identifier("this"), "count"), Literal(1))
66
+ )
67
+ ),
68
+ ]
69
+ );
70
+
71
+ const methodSource = generateMethod(node);
72
+ const classSource = `class Test { ${methodSource} }`;
73
+ const TestClass = new Function(`return ${classSource}`)();
74
+
75
+ const instance = new TestClass();
76
+ instance.count = 5;
77
+ instance.increment();
78
+ assert.equal(instance.count, 6);
79
+ });
@@ -0,0 +1,79 @@
1
+ import { generateMethod } from './generateMethod.js'
2
+ import { generateExpression } from './generateExpression.js'
3
+
4
+ /**
5
+ * Compiles a full PageNode into JS source defining a component class.
6
+ * - state entries become reactive-backed getter/setter pairs, so
7
+ * `this.count` reads/writes go through the reactive() proxy and
8
+ * correctly trigger dependent effects (template re-renders, computed
9
+ * re-evaluation) without any special-casing in the method codegen.
10
+ * - computed entries become plain getters (their body already contains
11
+ * a `return` statement from the parser).
12
+ * - action entries become plain instance methods.
13
+ *
14
+ * The generated class expects `reactive` to be in scope where the
15
+ * module is evaluated (imported from @tylix/compiler's runtime).
16
+ */
17
+ export function generatePage(pageNode, className = 'Page') {
18
+ const propAssignments = pageNode.props
19
+ .map((p) => ` this.${p.name} = props.${p.name};`)
20
+ .join('\n')
21
+
22
+ const stateInit = pageNode.state
23
+ .map((s) => ` ${s.name}: ${generateExpression(s.value)},`)
24
+ .join('\n')
25
+
26
+ const stateAccessors = pageNode.state
27
+ .map(
28
+ (s) => ` get ${s.name}() {
29
+ return this.__state.${s.name};
30
+ }
31
+ set ${s.name}(value) {
32
+ this.__state.${s.name} = value;
33
+ }`,
34
+ )
35
+ .join('\n\n')
36
+
37
+ const computedGetters = pageNode.computed
38
+ .map((c) => {
39
+ const body = c.body
40
+ .map((stmt) => ` ${statementSource(stmt)}`)
41
+ .join('\n')
42
+ return ` get ${c.name}() {\n${body}\n }`
43
+ })
44
+ .join('\n\n')
45
+
46
+ const actionMethods = pageNode.actions
47
+ .map((a) => generateMethod(a))
48
+ .join('\n\n')
49
+
50
+ const onMountCall = pageNode.onMount ? ` this.__onMount();\n` : ''
51
+
52
+ const onMountMethod = pageNode.onMount
53
+ ? (() => {
54
+ const body = pageNode.onMount.body
55
+ .map((stmt) => ` ${statementSource(stmt)}`)
56
+ .join('\n')
57
+ const asyncPrefix = pageNode.onMount.isAsync ? 'async ' : ''
58
+ return ` ${asyncPrefix}__onMount() {\n${body}\n }`
59
+ })()
60
+ : ''
61
+
62
+ return `class ${className} {
63
+ constructor(props = {}) {
64
+ ${propAssignments ? propAssignments + '\n' : ''} this.__state = reactive({
65
+ ${stateInit}
66
+ });
67
+ ${onMountCall} }
68
+
69
+ ${[stateAccessors, computedGetters, actionMethods, onMountMethod].filter(Boolean).join('\n\n')}
70
+ }`
71
+ }
72
+
73
+ // Local import kept separate from generateMethod's own statement
74
+ // formatting so computed getters and state accessors can share the
75
+ // same statement codegen without generateMethod's parameter handling.
76
+ import { generateStatement } from './generateStatement.js'
77
+ function statementSource(stmt) {
78
+ return generateStatement(stmt)
79
+ }
@@ -0,0 +1,33 @@
1
+ import { test } from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { generatePage } from "./generatePage.js";
4
+ import { reactive } from "../runtime/reactive.js";
5
+ import { Parser } from "../parser/Parser.js";
6
+ import { Lexer } from "../lexer/Lexer.js";
7
+
8
+ test("onMount runs automatically on construction", () => {
9
+ const source = `state\ncount: 0\nonMount\nthis.count = 99`;
10
+ const page = new Parser(new Lexer(source).tokenize()).parse();
11
+ const classSource = generatePage(page, "Page");
12
+ const Page = new Function("reactive", `return ${classSource}`)(reactive);
13
+
14
+ const instance = new Page();
15
+ assert.equal(instance.count, 99);
16
+ });
17
+
18
+ test("async onMount can await before setting state", async () => {
19
+ const source = `state\ndata: 0\nonMount\nasync {\n const value = await this.fetchIt()\n this.data = value\n}`;
20
+ const page = new Parser(new Lexer(source).tokenize()).parse();
21
+ const classSource = generatePage(page, "Page");
22
+
23
+ const PageClass = new Function(
24
+ "reactive",
25
+ `const Page = ${classSource};
26
+ Page.prototype.fetchIt = async function () { return 123; };
27
+ return Page;`
28
+ )(reactive);
29
+
30
+ const instance = new PageClass();
31
+ await instance.__onMount();
32
+ assert.equal(instance.data, 123);
33
+ });