@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
@@ -0,0 +1,319 @@
1
+ import {
2
+ ElementNode,
3
+ AttributeNode,
4
+ TextNode,
5
+ InterpolationNode,
6
+ IfNode,
7
+ EachNode,
8
+ } from '../ast/nodes.js'
9
+ import { parseExpressionString } from './parseExpressionString.js'
10
+
11
+ const TAG_NAME_RE = /^[a-zA-Z][a-zA-Z0-9-]*/
12
+ const ATTR_NAME_RE = /^[a-zA-Z][a-zA-Z0-9-]*/
13
+ const INTERP_ATTR_RE = /^\{\{\s*([\s\S]*?)\s*\}\}$/
14
+ const EACH_HEADER_RE = /^([A-Za-z_$][A-Za-z0-9_$]*)\s+in\s+([\s\S]+)$/
15
+
16
+ const NAMED_ENTITIES = {
17
+ amp: '&',
18
+ lt: '<',
19
+ gt: '>',
20
+ quot: '"',
21
+ apos: "'",
22
+ nbsp: '\u00A0',
23
+ larr: '\u2190',
24
+ rarr: '\u2192',
25
+ uarr: '\u2191',
26
+ darr: '\u2193',
27
+ mdash: '\u2014',
28
+ ndash: '\u2013',
29
+ hellip: '\u2026',
30
+ copy: '\u00A9',
31
+ reg: '\u00AE',
32
+ trade: '\u2122',
33
+ }
34
+
35
+ const ENTITY_RE = /&(#x?[0-9a-fA-F]+|[a-zA-Z]+);/g
36
+
37
+ function decodeHtmlEntities(text) {
38
+ return text.replace(ENTITY_RE, (match, body) => {
39
+ if (body[0] === '#') {
40
+ const isHex = body[1] === 'x' || body[1] === 'X'
41
+ const codePoint = isHex
42
+ ? parseInt(body.slice(2), 16)
43
+ : parseInt(body.slice(1), 10)
44
+ if (Number.isNaN(codePoint)) return match
45
+ try {
46
+ return String.fromCodePoint(codePoint)
47
+ } catch {
48
+ return match
49
+ }
50
+ }
51
+ return Object.prototype.hasOwnProperty.call(NAMED_ENTITIES, body)
52
+ ? NAMED_ENTITIES[body]
53
+ : match // unknown entity: leave as-is rather than mangling it
54
+ })
55
+ }
56
+
57
+ export function parseTemplate(source) {
58
+ const parser = new TemplateParser(source)
59
+ const nodes = parser.parseNodes(null)
60
+ if (parser.pos < parser.source.length) {
61
+ throw new Error(
62
+ `Unexpected closing tag near: ${parser.remaining().slice(0, 30)}`,
63
+ )
64
+ }
65
+ return nodes
66
+ }
67
+
68
+ class TemplateParser {
69
+ constructor(source) {
70
+ this.source = source
71
+ this.pos = 0
72
+ }
73
+
74
+ remaining() {
75
+ return this.source.slice(this.pos)
76
+ }
77
+
78
+ // Parses sibling nodes. `stopTag` (an HTML tag name) or `stopMarker`
79
+ // (a literal like "{{/if}}") tell this call when to return; nested
80
+ // control blocks / elements consume their own closing marker before
81
+ // returning, so recursion handles arbitrary nesting automatically.
82
+ parseNodes(stopTag, stopMarker = null) {
83
+ const nodes = []
84
+ while (this.pos < this.source.length) {
85
+ if (stopMarker && this.remaining().startsWith(stopMarker)) {
86
+ this.pos += stopMarker.length
87
+ return nodes
88
+ }
89
+
90
+ if (this.remaining().startsWith('</')) {
91
+ if (stopTag === null) return nodes
92
+ this.consumeClosingTag(stopTag)
93
+ return nodes
94
+ }
95
+
96
+ if (this.remaining().startsWith('{{#if')) {
97
+ nodes.push(this.parseIfBlock())
98
+ continue
99
+ }
100
+
101
+ if (this.remaining().startsWith('{{#each')) {
102
+ nodes.push(this.parseEachBlock())
103
+ continue
104
+ }
105
+
106
+ if (this.remaining().startsWith('{{')) {
107
+ nodes.push(this.parseInterpolation())
108
+ continue
109
+ }
110
+
111
+ if (this.source[this.pos] === '<') {
112
+ nodes.push(this.parseElement())
113
+ continue
114
+ }
115
+
116
+ const text = this.parseText()
117
+ const collapsed = decodeHtmlEntities(text.replace(/\s+/g, ' '))
118
+ if (collapsed.trim().length > 0) {
119
+ nodes.push(TextNode(collapsed))
120
+ }
121
+ }
122
+
123
+ if (stopMarker !== null) {
124
+ throw new Error(
125
+ `Unclosed block: reached end of template looking for "${stopMarker}"`,
126
+ )
127
+ }
128
+ if (stopTag !== null) {
129
+ throw new Error(`Unclosed tag <${stopTag}>: reached end of template`)
130
+ }
131
+ return nodes
132
+ }
133
+
134
+ parseText() {
135
+ const start = this.pos
136
+ while (
137
+ this.pos < this.source.length &&
138
+ this.source[this.pos] !== '<' &&
139
+ !this.remaining().startsWith('{{')
140
+ ) {
141
+ this.pos++
142
+ }
143
+ return this.source.slice(start, this.pos)
144
+ }
145
+
146
+ parseInterpolation() {
147
+ const start = this.pos + 2
148
+ const end = this.source.indexOf('}}', start)
149
+ if (end === -1) {
150
+ throw new Error("Unterminated interpolation: missing '}}'")
151
+ }
152
+ const exprSource = this.source.slice(start, end).trim()
153
+ this.pos = end + 2
154
+ return InterpolationNode(parseExpressionString(exprSource))
155
+ }
156
+
157
+ parseIfBlock() {
158
+ this.pos += 2 // "{{"
159
+ this.pos += 3 // "#if"
160
+ this.skipWhitespace()
161
+ const end = this.source.indexOf('}}', this.pos)
162
+ if (end === -1) {
163
+ throw new Error("Unterminated {{#if}} header: missing '}}'")
164
+ }
165
+ const conditionSource = this.source.slice(this.pos, end).trim()
166
+ this.pos = end + 2
167
+
168
+ const children = this.parseNodes(null, '{{/if}}')
169
+ return IfNode(parseExpressionString(conditionSource), children)
170
+ }
171
+
172
+ parseEachBlock() {
173
+ this.pos += 2 // "{{"
174
+ this.pos += 5 // "#each"
175
+ this.skipWhitespace()
176
+ const end = this.source.indexOf('}}', this.pos)
177
+ if (end === -1) {
178
+ throw new Error("Unterminated {{#each}} header: missing '}}'")
179
+ }
180
+ const header = this.source.slice(this.pos, end).trim()
181
+ this.pos = end + 2
182
+
183
+ const match = EACH_HEADER_RE.exec(header)
184
+ if (!match) {
185
+ throw new Error(
186
+ `Invalid {{#each}} header "${header}": expected "item in items"`,
187
+ )
188
+ }
189
+ const itemName = match[1]
190
+ const iterableSource = match[2].trim()
191
+
192
+ const children = this.parseNodes(null, '{{/each}}')
193
+ return EachNode(itemName, parseExpressionString(iterableSource), children)
194
+ }
195
+
196
+ parseElement() {
197
+ this.pos++
198
+ const tag = this.readTagName()
199
+ const attributes = this.parseAttributes()
200
+
201
+ this.skipWhitespace()
202
+ if (this.remaining().startsWith('/>')) {
203
+ this.pos += 2
204
+ return ElementNode(tag, attributes, [])
205
+ }
206
+
207
+ if (this.source[this.pos] !== '>') {
208
+ throw new Error(`Expected '>' to close <${tag}> tag`)
209
+ }
210
+ this.pos++
211
+
212
+ // <pre> is a raw-text element, same idea as <script>/<style> in
213
+ // real HTML: its content is captured verbatim -- no whitespace
214
+ // collapsing, and critically no {{ }} interpolation/control-flow
215
+ // parsing -- so code samples containing literal "{{#each}}" etc.
216
+ // display as text instead of being executed as real template
217
+ // syntax.
218
+ if (tag === 'pre') {
219
+ const closeTag = '</pre>'
220
+ const closeIndex = this.source.indexOf(closeTag, this.pos)
221
+ if (closeIndex === -1) {
222
+ throw new Error('Unclosed <pre> tag: reached end of template')
223
+ }
224
+ const rawContent = this.source.slice(this.pos, closeIndex)
225
+ this.pos = closeIndex + closeTag.length
226
+ return ElementNode(tag, attributes, [TextNode(rawContent)])
227
+ }
228
+
229
+ const children = this.parseNodes(tag)
230
+ return ElementNode(tag, attributes, children)
231
+ }
232
+
233
+ consumeClosingTag(expectedTag) {
234
+ this.pos += 2
235
+ const name = this.readTagName()
236
+ this.skipWhitespace()
237
+ if (this.source[this.pos] !== '>') {
238
+ throw new Error(`Expected '>' after closing tag name '${name}'`)
239
+ }
240
+ this.pos++
241
+ if (name !== expectedTag) {
242
+ throw new Error(
243
+ `Mismatched closing tag: expected </${expectedTag}>, got </${name}>`,
244
+ )
245
+ }
246
+ }
247
+
248
+ readTagName() {
249
+ const match = TAG_NAME_RE.exec(this.remaining())
250
+ if (!match) {
251
+ throw new Error(`Expected a tag name at position ${this.pos}`)
252
+ }
253
+ this.pos += match[0].length
254
+ return match[0]
255
+ }
256
+
257
+ parseAttributes() {
258
+ const attributes = []
259
+ this.skipWhitespace()
260
+ while (
261
+ this.pos < this.source.length &&
262
+ this.source[this.pos] !== '>' &&
263
+ !this.remaining().startsWith('/>')
264
+ ) {
265
+ attributes.push(this.parseAttribute())
266
+ this.skipWhitespace()
267
+ }
268
+ return attributes
269
+ }
270
+
271
+ parseAttribute() {
272
+ const nameMatch = ATTR_NAME_RE.exec(this.remaining())
273
+ if (!nameMatch) {
274
+ throw new Error(`Expected an attribute name at position ${this.pos}`)
275
+ }
276
+ const name = nameMatch[0]
277
+ this.pos += name.length
278
+ this.skipWhitespace()
279
+
280
+ // No '=' following the name means a bare boolean attribute
281
+ // (e.g. <input disabled>, <div data-tylix-slot>) rather than a
282
+ // parse error -- matches real HTML's own boolean-attribute
283
+ // convention, so devs coming from plain HTML don't hit a
284
+ // surprising "Expected '=' after attribute name" wall.
285
+ if (this.source[this.pos] !== '=') {
286
+ return AttributeNode(name, true, false)
287
+ }
288
+
289
+ this.pos++
290
+ this.skipWhitespace()
291
+
292
+ const quote = this.source[this.pos]
293
+ if (quote !== '"' && quote !== "'") {
294
+ throw new Error(`Expected a quoted value for attribute '${name}'`)
295
+ }
296
+ this.pos++
297
+ const valueStart = this.pos
298
+ while (this.pos < this.source.length && this.source[this.pos] !== quote) {
299
+ this.pos++
300
+ }
301
+ if (this.pos >= this.source.length) {
302
+ throw new Error(`Unterminated attribute value for '${name}'`)
303
+ }
304
+ const rawValue = this.source.slice(valueStart, this.pos)
305
+ this.pos++
306
+
307
+ const interpMatch = INTERP_ATTR_RE.exec(rawValue)
308
+ if (interpMatch) {
309
+ return AttributeNode(name, parseExpressionString(interpMatch[1]), true)
310
+ }
311
+ return AttributeNode(name, rawValue, false)
312
+ }
313
+
314
+ skipWhitespace() {
315
+ while (this.pos < this.source.length && /\s/.test(this.source[this.pos])) {
316
+ this.pos++
317
+ }
318
+ }
319
+ }
@@ -0,0 +1,39 @@
1
+ import { test } from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { parseTemplate } from "./parseTemplate.js";
4
+
5
+ test("preserves exact whitespace and newlines inside <pre>", () => {
6
+ const source = `<pre>line one
7
+ line two (indented)
8
+ line three</pre>`;
9
+ const nodes = parseTemplate(source);
10
+ const preNode = nodes[0];
11
+ assert.equal(preNode.tag, "pre");
12
+ assert.equal(preNode.children[0].value, "line one\n line two (indented)\nline three");
13
+ });
14
+
15
+ test("does not interpret {{ }} syntax inside <pre> as real interpolation/control-flow", () => {
16
+ const source = `<pre>{{#each post in posts}}
17
+ {{ post.title }}
18
+ {{/each}}</pre>`;
19
+ const nodes = parseTemplate(source);
20
+ const preNode = nodes[0];
21
+ assert.equal(preNode.children.length, 1);
22
+ assert.equal(preNode.children[0].type, "Text");
23
+ assert.match(preNode.children[0].value, /\{\{#each post in posts\}\}/);
24
+ });
25
+
26
+ test("throws a clear error on an unclosed <pre> tag", () => {
27
+ assert.throws(() => parseTemplate(`<pre>never closed`), /Unclosed <pre> tag/);
28
+ });
29
+
30
+ test("<pre> sits correctly alongside normal interpreted siblings", () => {
31
+ const source = `<div><h1>{{ title }}</h1><pre>{{ raw }}</pre></div>`;
32
+ const nodes = parseTemplate(source);
33
+ const div = nodes[0];
34
+ assert.equal(div.children[0].tag, "h1");
35
+ assert.equal(div.children[0].children[0].type, "Interpolation");
36
+ assert.equal(div.children[1].tag, "pre");
37
+ assert.equal(div.children[1].children[0].type, "Text");
38
+ assert.equal(div.children[1].children[0].value, "{{ raw }}");
39
+ });
@@ -0,0 +1,96 @@
1
+ import { test } from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { parseTemplate } from "./parseTemplate.js";
4
+
5
+ test("parses a single element with text content", () => {
6
+ const nodes = parseTemplate(`<h1>Hello</h1>`);
7
+ assert.deepEqual(nodes, [
8
+ { type: "Element", tag: "h1", attributes: [], children: [{ type: "Text", value: "Hello" }] },
9
+ ]);
10
+ });
11
+
12
+ test("parses an interpolation node", () => {
13
+ const nodes = parseTemplate(`{{ count }}`);
14
+ assert.equal(nodes.length, 1);
15
+ assert.equal(nodes[0].type, "Interpolation");
16
+ assert.deepEqual(nodes[0].expression, { type: "Identifier", name: "count" });
17
+ });
18
+
19
+ test("parses text and interpolation mixed in one element", () => {
20
+ const nodes = parseTemplate(`<p>Count: {{ count }}</p>`);
21
+ const p = nodes[0];
22
+ assert.equal(p.children.length, 2);
23
+ assert.deepEqual(p.children[0], { type: "Text", value: "Count: " });
24
+ assert.equal(p.children[1].type, "Interpolation");
25
+ });
26
+
27
+ test("parses nested elements", () => {
28
+ const nodes = parseTemplate(`<div><h1>Title</h1><p>Body</p></div>`);
29
+ const div = nodes[0];
30
+ assert.equal(div.children.length, 2);
31
+ assert.equal(div.children[0].tag, "h1");
32
+ assert.equal(div.children[1].tag, "p");
33
+ });
34
+
35
+ test("parses a static attribute", () => {
36
+ const nodes = parseTemplate(`<div class="wrapper"></div>`);
37
+ assert.deepEqual(nodes[0].attributes, [
38
+ { type: "Attribute", name: "class", value: "wrapper", dynamic: false },
39
+ ]);
40
+ });
41
+
42
+ test("parses a dynamic event-binding attribute using the expression parser", () => {
43
+ const nodes = parseTemplate(`<button onclick="{{ increment }}">+1</button>`);
44
+ const attr = nodes[0].attributes[0];
45
+ assert.equal(attr.name, "onclick");
46
+ assert.equal(attr.dynamic, true);
47
+ assert.deepEqual(attr.value, { type: "Identifier", name: "increment" });
48
+ });
49
+
50
+ test("parses a self-closing element", () => {
51
+ const nodes = parseTemplate(`<input />`);
52
+ assert.deepEqual(nodes, [{ type: "Element", tag: "input", attributes: [], children: [] }]);
53
+ });
54
+
55
+ test("parses the realistic counter template from the design doc", () => {
56
+ const nodes = parseTemplate(`
57
+ <div>
58
+ <h1>{{ title }}</h1>
59
+ <p>Count: {{ count }}, doubled: {{ doubled }}</p>
60
+ <button onclick="{{ increment }}">+1</button>
61
+ </div>
62
+ `);
63
+ const div = nodes[0];
64
+ assert.equal(div.tag, "div");
65
+ assert.equal(div.children.length, 3);
66
+ assert.equal(div.children[0].tag, "h1");
67
+ assert.equal(div.children[1].tag, "p");
68
+ assert.equal(div.children[2].tag, "button");
69
+ });
70
+
71
+ test("throws a clear error on a mismatched closing tag", () => {
72
+ assert.throws(() => parseTemplate(`<div><span></div></span>`), /Mismatched closing tag/);
73
+ });
74
+
75
+ test("throws a clear error on an unclosed tag", () => {
76
+ assert.throws(() => parseTemplate(`<div><span>text</div>`), /Unclosed tag|Mismatched closing tag/);
77
+ });
78
+
79
+ test("throws a clear error on an unterminated interpolation", () => {
80
+ assert.throws(() => parseTemplate(`<div>{{ count </div>`), /Unterminated interpolation/);
81
+ });
82
+
83
+ test("preserves meaningful whitespace between text and interpolation", () => {
84
+ const nodes = parseTemplate(`<h1>Hello {{ name }}</h1>`);
85
+ assert.equal(nodes[0].type, "Element");
86
+ const [textNode, interpNode] = nodes[0].children;
87
+ assert.equal(textNode.type, "Text");
88
+ assert.equal(textNode.value, "Hello ");
89
+ assert.equal(interpNode.type, "Interpolation");
90
+ });
91
+
92
+ test("collapses indentation-only whitespace between tags to nothing", () => {
93
+ const nodes = parseTemplate(`<div>\n <h1>Hi</h1>\n</div>`);
94
+ assert.equal(nodes[0].children.length, 1, "pure-whitespace indentation should not become a Text node");
95
+ assert.equal(nodes[0].children[0].tag, "h1");
96
+ });
@@ -0,0 +1,250 @@
1
+ import fs from 'node:fs'
2
+ import path from 'node:path'
3
+ import { fileURLToPath } from 'node:url'
4
+ import { parsePageFile } from './parser/parsePageFile.js'
5
+ import { parseComponent } from './parser/parseComponent.js'
6
+ import { parseComponentFile } from './parser/parseComponentFile.js'
7
+ import { parseTemplate } from './parser/parseTemplate.js'
8
+ import { Lexer } from './lexer/Lexer.js'
9
+ import { Parser } from './parser/Parser.js'
10
+ import { generatePage } from './codegen/generatePage.js'
11
+ import { generateTemplate } from './codegen/generateTemplate.js'
12
+
13
+ const __dirname = path.dirname(fileURLToPath(import.meta.url))
14
+ const RUNTIME_SOURCE = fs
15
+ .readFileSync(path.join(__dirname, 'runtime', 'reactive.js'), 'utf-8')
16
+ .replace(/export\s+/g, '')
17
+
18
+ const LOADING_INDICATOR_SOURCE = fs
19
+ .readFileSync(path.join(__dirname, 'runtime', 'loadingIndicator.js'), 'utf-8')
20
+ .replace(/export\s+/g, '')
21
+
22
+ const USE_API_SOURCE = fs
23
+ .readFileSync(path.join(__dirname, 'runtime', 'useApi.js'), 'utf-8')
24
+ .replace(/export\s+/g, '')
25
+
26
+ const USE_CHANNEL_SOURCE = fs
27
+ .readFileSync(path.join(__dirname, 'runtime', 'useChannel.js'), 'utf-8')
28
+ .replace(/export\s+/g, '')
29
+
30
+ function compileComponentSource(source, fallbackClassName) {
31
+ const isNativeComponent = /^\s*component\s+\w+/.test(source)
32
+
33
+ if (isNativeComponent) {
34
+ const { componentName, script, template } = parseComponentFile(source)
35
+ const pageNode =
36
+ script.trim().length > 0
37
+ ? new Parser(new Lexer(script).tokenize()).parse()
38
+ : { props: [], state: [], computed: [], actions: [] }
39
+
40
+ const classSource = generatePage(pageNode, componentName)
41
+ const templateNodes = parseTemplate(template)
42
+ const { code, rootVar } = generateTemplate(templateNodes)
43
+
44
+ return { classSource, code, rootVar, className: componentName }
45
+ }
46
+
47
+ const { script, template } = parseComponent(source)
48
+
49
+ const pageNode =
50
+ script.trim().length > 0
51
+ ? new Parser(new Lexer(script).tokenize()).parse()
52
+ : { props: [], state: [], computed: [], actions: [] }
53
+
54
+ const classSource = generatePage(pageNode, fallbackClassName)
55
+ const templateNodes = parseTemplate(template)
56
+ const { code, rootVar } = generateTemplate(templateNodes)
57
+
58
+ return { classSource, code, rootVar, className: fallbackClassName }
59
+ }
60
+
61
+ function applyLineOffset(err, offset) {
62
+ const match = /at line (\d+)/.exec(err.message)
63
+ if (match) {
64
+ const originalLine = Number(match[1])
65
+ const correctedLine = originalLine + offset - 1
66
+ err.message = err.message.replace(
67
+ `at line ${originalLine}`,
68
+ `at line ${correctedLine}`,
69
+ )
70
+ err.line = correctedLine
71
+ }
72
+ return err
73
+ }
74
+
75
+ function parseScriptWithLineOffset(script, offset) {
76
+ try {
77
+ return new Parser(new Lexer(script).tokenize()).parse()
78
+ } catch (err) {
79
+ throw applyLineOffset(err, offset)
80
+ }
81
+ }
82
+
83
+ function parseTemplateWithLineOffset(template, offset) {
84
+ try {
85
+ return parseTemplate(template)
86
+ } catch (err) {
87
+ throw applyLineOffset(err, offset)
88
+ }
89
+ }
90
+
91
+ export function renderPageDocument(
92
+ source,
93
+ childComponents = {},
94
+ { layout = null, props = {}, apiHelpers = '', channelsPort = null } = {},
95
+ ) {
96
+ const {
97
+ pageName,
98
+ script,
99
+ template,
100
+ style,
101
+ scriptStartLine,
102
+ templateStartLine,
103
+ } = parsePageFile(source)
104
+
105
+ const pageNode =
106
+ script.trim().length > 0
107
+ ? parseScriptWithLineOffset(script, scriptStartLine)
108
+ : { props: [], state: [], computed: [], actions: [] }
109
+
110
+ const classSource = generatePage(pageNode, pageName)
111
+
112
+ const templateNodes = parseTemplateWithLineOffset(template, templateStartLine)
113
+ const { code, rootVar } = generateTemplate(templateNodes)
114
+
115
+ const childNames = Object.keys(childComponents)
116
+ const childClassSources = childNames
117
+ .map(
118
+ (name) => compileComponentSource(childComponents[name], name).classSource,
119
+ )
120
+ .join('\n\n')
121
+
122
+ const childRegistrations = childNames
123
+ .map((name) => {
124
+ const compiled = compileComponentSource(childComponents[name], name)
125
+ const { code: childCode, rootVar: childRootVar, className } = compiled
126
+ return ` components[${JSON.stringify(name)}] = {
127
+ mount(document, props = {}) {
128
+ const instance = new ${className}(props);
129
+ const node = (function (document, instance) {
130
+ ${childCode}
131
+ return ${childRootVar};
132
+ })(document, instance);
133
+ return { node, instance };
134
+ },
135
+ };`
136
+ })
137
+ .join('\n\n')
138
+
139
+ let layoutClassSource = ''
140
+ let layoutMountCode = `document.getElementById("app").appendChild(${rootVar});`
141
+
142
+ if (layout !== null) {
143
+ const layoutCompiled = compileComponentSource(layout, '__Layout')
144
+ layoutClassSource = layoutCompiled.classSource
145
+ layoutMountCode = `
146
+ const layoutInstance = new ${layoutCompiled.className}();
147
+ (function (document, instance, pageRoot) {
148
+ ${layoutCompiled.code}
149
+ const slot = ${layoutCompiled.rootVar}.querySelector("[data-tylix-slot]");
150
+ if (!slot) {
151
+ throw new Error("_layout.tyx is missing a data-tylix-slot element");
152
+ }
153
+ slot.appendChild(pageRoot);
154
+ document.getElementById("app").appendChild(${layoutCompiled.rootVar});
155
+ })(document, layoutInstance, ${rootVar});`
156
+ }
157
+
158
+ const channelsPortScript =
159
+ channelsPort !== null
160
+ ? `<script>window.__TYLIX_CHANNELS_PORT__ = ${JSON.stringify(channelsPort)};</script>`
161
+ : ''
162
+
163
+ const inlineScript = `
164
+ ${RUNTIME_SOURCE}
165
+
166
+ ${LOADING_INDICATOR_SOURCE}
167
+
168
+ ${USE_API_SOURCE}
169
+
170
+ ${USE_CHANNEL_SOURCE}
171
+
172
+ ${apiHelpers}
173
+
174
+ ${classSource}
175
+
176
+ ${childClassSources}
177
+
178
+ ${layoutClassSource}
179
+
180
+ document.addEventListener("DOMContentLoaded", () => {
181
+ const instance = new ${pageName}(${JSON.stringify(props)});
182
+ const components = {};
183
+ ${childRegistrations}
184
+ (function (document, instance, components) {
185
+ ${code}
186
+ ${layoutMountCode}
187
+ })(document, instance, components);
188
+ });
189
+ `
190
+
191
+ const styleTag = style.trim().length > 0 ? `<style>\n${style}\n</style>` : ''
192
+
193
+ const scriptSegments = [
194
+ { name: 'runtime (reactive.js)', code: RUNTIME_SOURCE },
195
+ { name: 'loading indicator', code: LOADING_INDICATOR_SOURCE },
196
+ { name: 'useApi', code: USE_API_SOURCE },
197
+ { name: 'useChannel', code: USE_CHANNEL_SOURCE },
198
+ { name: 'app/useApi helpers', code: apiHelpers },
199
+ { name: 'page class', code: classSource },
200
+ { name: 'child components', code: childClassSources },
201
+ { name: 'layout', code: layoutClassSource },
202
+ ]
203
+
204
+ for (const segment of scriptSegments) {
205
+ if (!segment.code || segment.code.trim().length === 0) continue
206
+ try {
207
+ new Function(segment.code)
208
+ } catch (err) {
209
+ const genErr = new Error(
210
+ `Generated JavaScript failed to parse in "${segment.name}": ${err.message}`,
211
+ )
212
+ genErr.source = segment.code
213
+ throw genErr
214
+ }
215
+ }
216
+
217
+ try {
218
+ new Function(inlineScript)
219
+ } catch (err) {
220
+ const genErr = new Error(
221
+ `Generated JavaScript failed to parse: ${err.message}`,
222
+ )
223
+ genErr.source = inlineScript
224
+ throw genErr
225
+ }
226
+
227
+ return `<!DOCTYPE html>
228
+ <html>
229
+ <head>
230
+ <meta charset="UTF-8">
231
+ ${channelsPortScript}
232
+ <script>
233
+ (function () {
234
+ var stored = localStorage.getItem("theme");
235
+ var prefersDark = window.matchMedia("(prefers-color-scheme: dark)").matches;
236
+ if (stored === "dark" || (!stored && prefersDark)) {
237
+ document.documentElement.classList.add("dark");
238
+ }
239
+ })();
240
+ </script>
241
+ <title>${pageName}</title>
242
+ <link rel="stylesheet" href="/tailwind.css">
243
+ ${styleTag}
244
+ </head>
245
+ <body>
246
+ <div id="app"></div>
247
+ <script>${inlineScript}</script>
248
+ </body>
249
+ </html>`
250
+ }