@tylix/compiler 0.5.2 → 0.7.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 (61) hide show
  1. package/LICENSE +21 -0
  2. package/package.json +30 -2
  3. package/src/ast/nodes.js +219 -16
  4. package/src/ast/substituteCapabilityRefs.js +185 -61
  5. package/src/codegen/emitStatementLines.js +98 -54
  6. package/src/codegen/generateExpression.js +339 -36
  7. package/src/codegen/generateMethod.js +5 -3
  8. package/src/codegen/generatePage.js +74 -44
  9. package/src/codegen/generateStatement.js +169 -20
  10. package/src/codegen/generateTemplate.js +183 -101
  11. package/src/codegen/generateTemplateExpression.js +102 -59
  12. package/src/codegen/jsGlobals.js +211 -0
  13. package/src/compileComponent.js +39 -8
  14. package/src/imports/extractImports.js +112 -26
  15. package/src/imports/resolveImports.js +186 -0
  16. package/src/index.js +3 -2
  17. package/src/lexer/Lexer.js +430 -235
  18. package/src/lexer/tokenTypes.js +32 -7
  19. package/src/parser/Parser.js +2176 -325
  20. package/src/parser/languageOptions.js +16 -0
  21. package/src/parser/parseExpressionString.js +23 -7
  22. package/src/parser/parsePageFile.js +139 -58
  23. package/src/parser/parseTemplate.js +350 -62
  24. package/src/renderPageDocument.js +338 -56
  25. package/src/runtime/capability.js +39 -17
  26. package/src/runtime/loadingIndicator.js +91 -29
  27. package/src/runtime/reactive.js +362 -64
  28. package/src/runtime/useApi.js +74 -13
  29. package/src/runtime/useChannel.js +27 -6
  30. package/src/typecheck/buildVirtualTs.js +23 -12
  31. package/src/typecheck/tylix-globals.d.ts +23 -4
  32. package/src/typecheck/typedTemplateExpr.js +195 -53
  33. package/src/typecheckPage.js +28 -4
  34. package/src/codegen/generateExpression.array.test.js +0 -13
  35. package/src/codegen/generateExpression.callexpr.test.js +0 -19
  36. package/src/codegen/generateExpression.test.js +0 -59
  37. package/src/codegen/generateMethod.asyncawait.test.js +0 -37
  38. package/src/codegen/generateMethod.ifstatement.test.js +0 -20
  39. package/src/codegen/generateMethod.test.js +0 -81
  40. package/src/codegen/generatePage.onmount.test.js +0 -46
  41. package/src/codegen/generatePage.test.js +0 -138
  42. package/src/codegen/generateStatement.test.js +0 -31
  43. package/src/codegen/generateTemplate.ifeach.test.js +0 -138
  44. package/src/codegen/generateTemplate.test.js +0 -149
  45. package/src/codegen/generateTemplateExpression.test.js +0 -34
  46. package/src/compileComponent.test.js +0 -121
  47. package/src/imports/resolvePackageComponents.js +0 -41
  48. package/src/lexer/Lexer.test.js +0 -151
  49. package/src/parser/Parser.array.test.js +0 -37
  50. package/src/parser/Parser.asyncawait.test.js +0 -33
  51. package/src/parser/Parser.ifstatement.test.js +0 -20
  52. package/src/parser/Parser.onmount.test.js +0 -18
  53. package/src/parser/Parser.test.js +0 -315
  54. package/src/parser/parseComponent.test.js +0 -53
  55. package/src/parser/parsePageFile.test.js +0 -101
  56. package/src/parser/parseTemplate.ifeach.test.js +0 -33
  57. package/src/parser/parseTemplate.pre.test.js +0 -39
  58. package/src/parser/parseTemplate.test.js +0 -112
  59. package/src/renderPageDocument.test.js +0 -125
  60. package/src/runtime/reactive.test.js +0 -106
  61. package/test/dashboard-syntax.test.js +0 -116
@@ -7,9 +7,14 @@ import { parseComponentFile } from './parser/parseComponentFile.js'
7
7
  import { parseTemplate } from './parser/parseTemplate.js'
8
8
  import { Lexer } from './lexer/Lexer.js'
9
9
  import { Parser } from './parser/Parser.js'
10
+ import { normalizeLanguageOptions } from './parser/languageOptions.js'
10
11
  import { generatePage } from './codegen/generatePage.js'
11
12
  import { generateTemplate } from './codegen/generateTemplate.js'
12
13
  import { generateCapability } from './codegen/generateCapability.js'
14
+ import {
15
+ generateStatement,
16
+ declaredNames,
17
+ } from './codegen/generateStatement.js'
13
18
  import { substituteCapabilityRefs } from './ast/substituteCapabilityRefs.js'
14
19
 
15
20
  const __dirname = path.dirname(fileURLToPath(import.meta.url))
@@ -37,9 +42,29 @@ const NOT_FOUND_SOURCE = fs
37
42
  .readFileSync(path.join(__dirname, 'runtime', 'notFound.js'), 'utf-8')
38
43
  .replace(/export\s+/g, '')
39
44
 
40
- const capabilityCache = new Map() // capabilitiesDir -> { signature, code }
45
+ // Attaches a class's module-level helpers (see withHelpers) to a fresh
46
+ // instance, so templates can call them: a bare `formatPrice(x)` in a
47
+ // template compiles to `instance.formatPrice(x)`.
48
+ const EXPOSE_HELPERS_SOURCE = `
49
+ function __tylixExpose(instance, cls) {
50
+ var helpers = cls && cls.__helpers;
51
+ if (helpers) {
52
+ for (var key of Object.keys(helpers)) instance[key] = helpers[key];
53
+ }
54
+ return instance;
55
+ }`
56
+
57
+ function escapeHtml(text) {
58
+ return String(text)
59
+ .replace(/&/g, '&')
60
+ .replace(/</g, '&lt;')
61
+ .replace(/>/g, '&gt;')
62
+ .replace(/"/g, '&quot;')
63
+ }
64
+
65
+ const capabilityCache = new Map() // `${dir}|not=${mode}` -> { signature, code }
41
66
 
42
- async function loadCapabilityDefinitions(capabilitiesDir) {
67
+ async function loadCapabilityDefinitions(capabilitiesDir, language) {
43
68
  const exists = await fs.promises
44
69
  .access(capabilitiesDir)
45
70
  .then(() => true)
@@ -59,7 +84,10 @@ async function loadCapabilityDefinitions(capabilitiesDir) {
59
84
  .sort()
60
85
  .join('|')
61
86
 
62
- const cached = capabilityCache.get(capabilitiesDir)
87
+ // The same directory compiles differently under different language
88
+ // options, so the options are part of the cache key.
89
+ const cacheKey = `${capabilitiesDir}|not=${language.not}`
90
+ const cached = capabilityCache.get(cacheKey)
63
91
  if (cached && cached.signature === signature) {
64
92
  return cached.code
65
93
  }
@@ -74,6 +102,7 @@ async function loadCapabilityDefinitions(capabilitiesDir) {
74
102
  try {
75
103
  const capabilityNode = new Parser(
76
104
  new Lexer(source).tokenize(),
105
+ language,
77
106
  ).parseCapability()
78
107
  return generateCapability(capabilityNode)
79
108
  } catch (err) {
@@ -84,7 +113,7 @@ async function loadCapabilityDefinitions(capabilitiesDir) {
84
113
  )
85
114
  ).join('\n\n')
86
115
 
87
- capabilityCache.set(capabilitiesDir, { signature, code: definitions })
116
+ capabilityCache.set(cacheKey, { signature, code: definitions })
88
117
  return definitions
89
118
  }
90
119
 
@@ -111,34 +140,162 @@ async function loadHeadTags(headFile) {
111
140
  return html
112
141
  }
113
142
 
114
- function compileComponentSource(source, fallbackClassName) {
143
+ // The HTML document around every page. This is what renders when the
144
+ // project has no app/index.html. A project file replaces it entirely and
145
+ // uses the same three placeholders.
146
+ const DEFAULT_SHELL = `<!DOCTYPE html>
147
+ <html>
148
+ <head>
149
+ <meta charset="UTF-8">
150
+ <meta name="viewport" content="width=device-width, initial-scale=1">
151
+ <title>%tylix.title%</title>
152
+ <link rel="icon" type="image/png" href="/favicon.png">
153
+ %tylix.head%
154
+ </head>
155
+ <body>
156
+ %tylix.body%
157
+ </body>
158
+ </html>`
159
+
160
+ const REQUIRED_PLACEHOLDERS = ['%tylix.head%', '%tylix.body%']
161
+
162
+ const shellCache = new Map() // shellFile -> { mtimeMs, html }
163
+
164
+ // Optional project file (app/index.html): the full HTML document, with
165
+ // its own DOCTYPE, <head> and <body>. It must contain %tylix.head% and
166
+ // %tylix.body%; %tylix.title% is optional. Cached by modified time like
167
+ // head.html. A missing file means the built-in shell above.
168
+ async function loadShell(shellFile) {
169
+ let stat
170
+ try {
171
+ stat = await fs.promises.stat(shellFile)
172
+ } catch {
173
+ return DEFAULT_SHELL
174
+ }
175
+ if (!stat.isFile()) return DEFAULT_SHELL
176
+
177
+ const cached = shellCache.get(shellFile)
178
+ if (cached && cached.mtimeMs === stat.mtimeMs) return cached.html
179
+
180
+ const html = await fs.promises.readFile(shellFile, 'utf-8')
181
+ const missing = REQUIRED_PLACEHOLDERS.filter((p) => !html.includes(p))
182
+ if (missing.length > 0) {
183
+ throw new Error(
184
+ `app/index.html is missing ${missing.join(' and ')}. ` +
185
+ 'Put %tylix.head% inside <head> and %tylix.body% inside <body>.',
186
+ )
187
+ }
188
+
189
+ shellCache.set(shellFile, { mtimeMs: stat.mtimeMs, html })
190
+ return html
191
+ }
192
+
193
+ const loadingCache = new Map() // loadingFile -> { mtimeMs, source }
194
+
195
+ // Optional project file (app/loading.tyx): the loading indicator, written
196
+ // like a layout (<script> and <template>). A missing file returns null and
197
+ // the built-in top bar is used instead. Cached by modified time like
198
+ // head.html and index.html.
199
+ async function loadLoadingPage(loadingFile) {
200
+ let stat
201
+ try {
202
+ stat = await fs.promises.stat(loadingFile)
203
+ } catch {
204
+ return null
205
+ }
206
+ if (!stat.isFile()) return null
207
+
208
+ const cached = loadingCache.get(loadingFile)
209
+ if (cached && cached.mtimeMs === stat.mtimeMs) return cached.source
210
+
211
+ const source = await fs.promises.readFile(loadingFile, 'utf-8')
212
+ loadingCache.set(loadingFile, { mtimeMs: stat.mtimeMs, source })
213
+ return source
214
+ }
215
+
216
+ const EMPTY_PAGE = {
217
+ props: [],
218
+ state: [],
219
+ computed: [],
220
+ actions: [],
221
+ uses: [],
222
+ helpers: [],
223
+ }
224
+
225
+ // Turns a registry key (a tag name such as "AdminCard" or "my-card")
226
+ // into a class name that is always a valid, unique identifier. The
227
+ // index guarantees uniqueness even if two sanitized names coincide,
228
+ // and the prefix keeps a component called Map or Error from shadowing
229
+ // the global of the same name inside the shared inline script.
230
+ function childClassName(name, index) {
231
+ return `__C${index}_${String(name).replace(/[^A-Za-z0-9_$]/g, '_')}`
232
+ }
233
+
234
+ // Module-level declarations of a page or component (`function`,
235
+ // `const`, `let`, `class`, `enum`; `type`/`interface` are erased) are
236
+ // emitted in a function scope of their own around that class, so two
237
+ // components can both define a helper with the same name. The names are
238
+ // stored on the class (`__helpers`) and attached to every instance by
239
+ // __tylixExpose, which is how templates reach them. With no runtime
240
+ // helpers the class source is returned untouched.
241
+ function withHelpers(classSource, className, helpers) {
242
+ const source = (helpers ?? [])
243
+ .map((h) => generateStatement(h, false))
244
+ .filter((s) => s.trim().length > 0)
245
+ .join('\n')
246
+ if (source.length === 0) return classSource
247
+
248
+ const exposed = helpers
249
+ .flatMap(declaredNames)
250
+ .map((n) => `${JSON.stringify(n)}: ${n}`)
251
+ .join(', ')
252
+ return `const ${className} = (() => {
253
+ ${source}
254
+ const __Class = ${classSource};
255
+ __Class.__helpers = { ${exposed} };
256
+ return __Class;
257
+ })();`
258
+ }
259
+
260
+ // `fallbackClassName` ALWAYS decides the class name -- for native
261
+ // `component Card` files too -- so two files that both declare Card
262
+ // can live in one page.
263
+ function compileComponentSource(source, fallbackClassName, language) {
115
264
  const isNativeComponent = /^\s*component\s+\w+/.test(source)
116
265
 
117
266
  if (isNativeComponent) {
118
- const { componentName, script, template } = parseComponentFile(source)
267
+ const { script, template } = parseComponentFile(source)
119
268
  const pageNode = substituteCapabilityRefs(
120
269
  script.trim().length > 0
121
- ? new Parser(new Lexer(script).tokenize()).parse()
122
- : { props: [], state: [], computed: [], actions: [], uses: [] },
270
+ ? new Parser(new Lexer(script).tokenize(), language).parse()
271
+ : EMPTY_PAGE,
123
272
  )
124
273
 
125
- const classSource = generatePage(pageNode, componentName)
126
- const templateNodes = parseTemplate(template)
274
+ const classSource = withHelpers(
275
+ generatePage(pageNode, fallbackClassName),
276
+ fallbackClassName,
277
+ pageNode.helpers,
278
+ )
279
+ const templateNodes = parseTemplate(template, language)
127
280
  const { code, rootVar } = generateTemplate(templateNodes)
128
281
 
129
- return { classSource, code, rootVar, className: componentName }
282
+ return { classSource, code, rootVar, className: fallbackClassName }
130
283
  }
131
284
 
132
285
  const { script, template } = parseComponent(source)
133
286
 
134
287
  const pageNode = substituteCapabilityRefs(
135
288
  script.trim().length > 0
136
- ? new Parser(new Lexer(script).tokenize()).parse()
137
- : { props: [], state: [], computed: [], actions: [], uses: [] },
289
+ ? new Parser(new Lexer(script).tokenize(), language).parse()
290
+ : EMPTY_PAGE,
138
291
  )
139
292
 
140
- const classSource = generatePage(pageNode, fallbackClassName)
141
- const templateNodes = parseTemplate(template)
293
+ const classSource = withHelpers(
294
+ generatePage(pageNode, fallbackClassName),
295
+ fallbackClassName,
296
+ pageNode.helpers,
297
+ )
298
+ const templateNodes = parseTemplate(template, language)
142
299
  const { code, rootVar } = generateTemplate(templateNodes)
143
300
 
144
301
  return { classSource, code, rootVar, className: fallbackClassName }
@@ -158,17 +315,17 @@ function applyLineOffset(err, offset) {
158
315
  return err
159
316
  }
160
317
 
161
- function parseScriptWithLineOffset(script, offset) {
318
+ function parseScriptWithLineOffset(script, offset, language) {
162
319
  try {
163
- return new Parser(new Lexer(script).tokenize()).parse()
320
+ return new Parser(new Lexer(script).tokenize(), language).parse()
164
321
  } catch (err) {
165
322
  throw applyLineOffset(err, offset)
166
323
  }
167
324
  }
168
325
 
169
- function parseTemplateWithLineOffset(template, offset) {
326
+ function parseTemplateWithLineOffset(template, offset, language) {
170
327
  try {
171
- return parseTemplate(template)
328
+ return parseTemplate(template, language)
172
329
  } catch (err) {
173
330
  throw applyLineOffset(err, offset)
174
331
  }
@@ -189,8 +346,29 @@ export async function renderPageDocument(
189
346
  capabilitiesDir = path.join(process.cwd(), 'app', 'capabilities'),
190
347
  // Optional file of extra <head> tags (scripts, meta, links).
191
348
  headFile = path.join(process.cwd(), 'app', 'head.html'),
349
+ // Optional full HTML document that wraps every page.
350
+ shellFile = path.join(process.cwd(), 'app', 'index.html'),
351
+ // Optional loading indicator page, mounted before the page renders.
352
+ loadingFile = path.join(process.cwd(), 'app', 'loading.tyx'),
353
+ // Compiler language switches, e.g. { not: 'loose' }. Omitted means
354
+ // legacy behaviour, so existing callers compile unchanged.
355
+ language: languageOption = {},
356
+ // false turns off the built-in top loading bar. A project loading page
357
+ // (app/loading.tyx) also replaces it.
358
+ loadingBar = true,
192
359
  } = {},
193
360
  ) {
361
+ // createApp already has a variable called `language` that holds
362
+ // 'typescript' | 'javascript'. Passing that here would silently fall
363
+ // back to the defaults, so refuse it loudly instead.
364
+ if (languageOption !== null && typeof languageOption !== 'object') {
365
+ throw new Error(
366
+ `renderPageDocument: the "language" option must be an object like { not: 'loose' }, got ${typeof languageOption} "${languageOption}". ` +
367
+ 'The project language ("typescript"/"javascript") is a different setting.',
368
+ )
369
+ }
370
+ const language = normalizeLanguageOptions(languageOption ?? {})
371
+
194
372
  const {
195
373
  pageName,
196
374
  script,
@@ -202,36 +380,107 @@ export async function renderPageDocument(
202
380
 
203
381
  const pageNode = substituteCapabilityRefs(
204
382
  script.trim().length > 0
205
- ? parseScriptWithLineOffset(script, scriptStartLine)
206
- : { props: [], state: [], computed: [], actions: [], uses: [] },
383
+ ? parseScriptWithLineOffset(script, scriptStartLine, language)
384
+ : EMPTY_PAGE,
207
385
  )
208
386
 
209
- const classSource = generatePage(pageNode, pageName)
387
+ const classSource = withHelpers(
388
+ generatePage(pageNode, pageName),
389
+ pageName,
390
+ pageNode.helpers,
391
+ )
210
392
 
211
- const templateNodes = parseTemplateWithLineOffset(template, templateStartLine)
393
+ const templateNodes = parseTemplateWithLineOffset(
394
+ template,
395
+ templateStartLine,
396
+ language,
397
+ )
212
398
  const { code, rootVar } = generateTemplate(templateNodes)
213
399
 
214
- const capabilityDefinitions = await loadCapabilityDefinitions(capabilitiesDir)
400
+ const capabilityDefinitions = await loadCapabilityDefinitions(
401
+ capabilitiesDir,
402
+ language,
403
+ )
215
404
  const headTags = await loadHeadTags(headFile)
405
+ const shell = await loadShell(shellFile)
406
+
407
+ // The loading page is compiled like a layout and mounted before the
408
+ // page's own data requests start, so the very first request shows it.
409
+ // It receives the shared loading state (see runtime/loadingIndicator.js)
410
+ // as its "loading" prop. A failure while mounting it is logged and never
411
+ // blocks the page.
412
+ const loadingSource = await loadLoadingPage(loadingFile)
413
+ let loadingClassSource = ''
414
+ let loadingMountCode = ''
415
+ if (loadingSource !== null) {
416
+ let loadingCompiled
417
+ try {
418
+ loadingCompiled = compileComponentSource(
419
+ loadingSource,
420
+ '__Loading',
421
+ language,
422
+ )
423
+ } catch (err) {
424
+ err.message = `In app/loading.tyx: ${err.message}`
425
+ throw err
426
+ }
427
+ loadingClassSource = loadingCompiled.classSource
428
+ loadingMountCode = `
429
+ try {
430
+ const loadingInstance = __tylixExpose(new ${loadingCompiled.className}({ loading: __tylixLoading }), ${loadingCompiled.className});
431
+ (function (document, instance) {
432
+ ${loadingCompiled.code}
433
+ document.body.appendChild(${loadingCompiled.rootVar});
434
+ })(document, loadingInstance);
435
+ if (typeof loadingInstance.__onMount === "function") {
436
+ Promise.resolve(loadingInstance.__onMount()).catch((err) => {
437
+ console.error("loading page onMount failed:", err);
438
+ });
439
+ }
440
+ } catch (err) {
441
+ console.error("loading page failed:", err);
442
+ }`
443
+ }
216
444
 
445
+ // Each child is compiled exactly once, under a unique class name
446
+ // derived from its registry key (the tag name the page uses), not
447
+ // from whatever `component X` line the file declares.
217
448
  const childNames = Object.keys(childComponents)
218
- const childClassSources = childNames
219
- .map(
220
- (name) => compileComponentSource(childComponents[name], name).classSource,
221
- )
449
+ const compiledChildren = childNames.map((name, i) => {
450
+ try {
451
+ return compileComponentSource(
452
+ childComponents[name],
453
+ childClassName(name, i),
454
+ language,
455
+ )
456
+ } catch (err) {
457
+ err.message = `In component <${name}>: ${err.message}`
458
+ throw err
459
+ }
460
+ })
461
+ const childClassSources = compiledChildren
462
+ .map((c) => c.classSource)
222
463
  .join('\n\n')
223
464
 
224
- const childRegistrations = childNames
225
- .map((name) => {
226
- const compiled = compileComponentSource(childComponents[name], name)
465
+ const childRegistrations = compiledChildren
466
+ .map((compiled, i) => {
467
+ const name = childNames[i]
468
+ const label = JSON.stringify(name)
227
469
  const { code: childCode, rootVar: childRootVar, className } = compiled
228
- return ` components[${JSON.stringify(name)}] = {
470
+ return ` components[${label}] = {
229
471
  mount(document, props = {}) {
230
- const instance = new ${className}(props);
472
+ const instance = __tylixExpose(new ${className}(props), ${className});
231
473
  const node = (function (document, instance) {
232
474
  ${childCode}
233
475
  return ${childRootVar};
234
476
  })(document, instance);
477
+ // needs/prefetch first, then onMount, same order as pages.
478
+ // Runs a microtask later, after the caller has attached the node.
479
+ Promise.resolve()
480
+ .then(() => (typeof instance.__ready === "function" ? instance.__ready() : null))
481
+ .catch((err) => console.error("component ready failed (" + ${label} + "):", err))
482
+ .then(() => (typeof instance.__onMount === "function" ? instance.__onMount() : null))
483
+ .catch((err) => console.error("component onMount failed (" + ${label} + "):", err));
235
484
  return { node, instance };
236
485
  },
237
486
  };`
@@ -242,10 +491,23 @@ ${childCode}
242
491
  let layoutMountCode = `document.getElementById("app").appendChild(${rootVar});`
243
492
 
244
493
  if (layout !== null) {
245
- const layoutCompiled = compileComponentSource(layout, '__Layout')
494
+ let layoutCompiled
495
+ try {
496
+ layoutCompiled = compileComponentSource(layout, '__Layout', language)
497
+ } catch (err) {
498
+ err.message = `In _layout.tyx: ${err.message}`
499
+ throw err
500
+ }
246
501
  layoutClassSource = layoutCompiled.classSource
247
502
  layoutMountCode = `
248
- const layoutInstance = new ${layoutCompiled.className}();
503
+ const layoutInstance = __tylixExpose(new ${layoutCompiled.className}(), ${layoutCompiled.className});
504
+ if (typeof layoutInstance.__ready === "function") {
505
+ try {
506
+ await layoutInstance.__ready();
507
+ } catch (err) {
508
+ console.error("layout ready failed:", err);
509
+ }
510
+ }
249
511
  (function (document, instance, pageRoot) {
250
512
  ${layoutCompiled.code}
251
513
  const slot = ${layoutCompiled.rootVar}.querySelector("[data-tylix-slot]");
@@ -254,7 +516,14 @@ ${layoutCompiled.code}
254
516
  }
255
517
  slot.appendChild(pageRoot);
256
518
  document.getElementById("app").appendChild(${layoutCompiled.rootVar});
257
- })(document, layoutInstance, ${rootVar});`
519
+ })(document, layoutInstance, ${rootVar});
520
+ if (typeof layoutInstance.__onMount === "function") {
521
+ try {
522
+ await layoutInstance.__onMount();
523
+ } catch (err) {
524
+ console.error("layout onMount failed:", err);
525
+ }
526
+ }`
258
527
  }
259
528
 
260
529
  const channelsPortScript =
@@ -265,8 +534,12 @@ ${layoutCompiled.code}
265
534
  // If __ready() rejects (a failed needs/prefetch call), log it and keep
266
535
  // going so the page still renders, instead of showing a blank screen.
267
536
  const inlineScript = `
537
+ ${loadingClassSource || !loadingBar ? 'window.__TYLIX_CUSTOM_LOADING__ = true;' : ''}
538
+
268
539
  ${RUNTIME_SOURCE}
269
540
 
541
+ ${EXPOSE_HELPERS_SOURCE}
542
+
270
543
  ${CAPABILITY_SOURCE}
271
544
 
272
545
  ${capabilityDefinitions}
@@ -287,11 +560,14 @@ ${childClassSources}
287
560
 
288
561
  ${layoutClassSource}
289
562
 
563
+ ${loadingClassSource}
564
+
290
565
  document.addEventListener("DOMContentLoaded", () => {
291
- const instance = new ${pageName}(${JSON.stringify(props)});
566
+ const instance = __tylixExpose(new ${pageName}(${JSON.stringify(props)}), ${pageName});
292
567
  const components = {};
293
568
  ${childRegistrations}
294
569
  (async function (document, instance, components) {
570
+ ${loadingMountCode}
295
571
  if (typeof instance.__ready === "function") {
296
572
  try {
297
573
  await instance.__ready();
@@ -330,6 +606,7 @@ ${layoutMountCode}
330
606
  { name: 'page class', code: classSource },
331
607
  { name: 'child components', code: childClassSources },
332
608
  { name: 'layout', code: layoutClassSource },
609
+ { name: 'loading page', code: loadingClassSource },
333
610
  ]
334
611
 
335
612
  for (const segment of scriptSegments) {
@@ -355,13 +632,16 @@ ${layoutMountCode}
355
632
  throw genErr
356
633
  }
357
634
 
358
- return `<!DOCTYPE html>
359
- <html>
360
- <head>
361
- <meta charset="UTF-8">
362
- <meta name="viewport" content="width=device-width, initial-scale=1">
363
- ${channelsPortScript}
364
- <script>
635
+ // A "</script" anywhere in the generated code (a <pre> sample, a
636
+ // route prop, a string) would end the script element early, and
637
+ // "<!--" can start an HTML comment inside it. Both replacements mean
638
+ // the same thing to the JS engine. Done AFTER the validation above,
639
+ // which must see the unescaped source.
640
+ const safeScript = inlineScript
641
+ .replace(/<\/(script)/gi, '<\\/$1')
642
+ .replace(/<!--/g, '<\\!--')
643
+
644
+ const themeScript = `<script>
365
645
  (function () {
366
646
  var stored = localStorage.getItem("theme");
367
647
  var prefersDark = window.matchMedia("(prefers-color-scheme: dark)").matches;
@@ -369,16 +649,18 @@ ${layoutMountCode}
369
649
  document.documentElement.classList.add("dark");
370
650
  }
371
651
  })();
372
- </script>
373
- <title>${pageNode.title ?? pageName}</title>
374
- <link rel="icon" type="image/png" href="/favicon.png">
375
- ${styleLinks}
376
- ${headTags}
377
- ${styleTag}
378
- </head>
379
- <body>
380
- <div id="app"></div>
381
- <script>${inlineScript}</script>
382
- </body>
383
- </html>`
652
+ </script>`
653
+
654
+ const values = {
655
+ title: escapeHtml(pageNode.title ?? pageName),
656
+ head: [channelsPortScript, themeScript, styleLinks, headTags, styleTag]
657
+ .filter((part) => part && part.length > 0)
658
+ .join('\n '),
659
+ body: `<div id="app"></div>\n <script>${safeScript}</script>`,
660
+ }
661
+
662
+ // One pass with a function replacer, so a "$&" or a placeholder-looking
663
+ // string inside the generated script is never treated as a pattern or
664
+ // substituted a second time.
665
+ return shell.replace(/%tylix\.(title|head|body)%/g, (_, key) => values[key])
384
666
  }
@@ -3,9 +3,7 @@
3
3
  // usesAccessors, which call resolveCapability(name) as a getter).
4
4
  // One instance per capability name, shared across every page in the
5
5
  // app -- resolveCapability memoizes on first resolution rather than
6
- // re-running the def, the same "resolve once, reuse forever" shape
7
- // createResource's .load() gives resources, just app-scoped instead
8
- // of per-page.
6
+ // re-running the def.
9
7
  //
10
8
  // A capability def has the shape:
11
9
  // {
@@ -17,11 +15,19 @@
17
15
  // async init() { ... }, // optional, runs once; `this`
18
16
  // // bound the same way
19
17
  // }
18
+ //
19
+ // `reactive` and `untracked` come from runtime/reactive.js, which is
20
+ // concatenated ahead of this file in the inline script.
20
21
 
21
22
  const registry = new Map()
22
23
 
23
24
  export function defineCapability(name, def) {
24
- registry.set(name, { def, instance: null, initPromise: null })
25
+ registry.set(name, {
26
+ def,
27
+ instance: null,
28
+ initStarted: false,
29
+ initPromise: null,
30
+ })
25
31
  }
26
32
 
27
33
  export function bindActions(actions, instance) {
@@ -41,21 +47,37 @@ export function resolveCapability(name) {
41
47
  }
42
48
 
43
49
  if (!entry.instance) {
44
- entry.instance = reactive({ ...entry.def.state })
45
- Object.assign(
46
- entry.instance,
47
- bindActions(entry.def.actions, entry.instance),
48
- )
50
+ const instance = reactive({ ...entry.def.state })
51
+ Object.assign(instance, bindActions(entry.def.actions, instance))
52
+ // Exposed so pages can `await Auth.ready()` before making a
53
+ // redirect decision. Defined once, here, so resolving does not
54
+ // keep writing to reactive state.
55
+ instance.ready = () => entry.initPromise ?? Promise.resolve()
56
+ entry.instance = instance
49
57
  }
50
58
 
51
- if (!entry.initPromise && entry.def.init) {
52
- entry.initPromise = entry.def.init.call(entry.instance)
59
+ // init() runs exactly once, whether it is async or not.
60
+ if (!entry.initStarted) {
61
+ entry.initStarted = true
62
+ if (entry.def.init) {
63
+ try {
64
+ // Resolution usually happens inside a template effect (a
65
+ // `uses` getter read during render). Run init untracked, so
66
+ // the state it reads before its first `await` does not
67
+ // subscribe that unrelated effect.
68
+ entry.initPromise = Promise.resolve(
69
+ untracked(() => entry.def.init.call(entry.instance)),
70
+ )
71
+ } catch (err) {
72
+ entry.initPromise = Promise.reject(err)
73
+ }
74
+ // Log here so a failed init is never an unhandled rejection;
75
+ // ready() still rejects for anyone awaiting it.
76
+ entry.initPromise.catch((err) => {
77
+ console.error(`Capability "${name}" init failed:`, err)
78
+ })
79
+ }
53
80
  }
54
81
 
55
- // Exposed so pages can `await Auth.ready()` before making a
56
- // redirect decision, instead of racing the reactive `loading` flag
57
- // with their own onMount timing.
58
- entry.instance.ready = () => entry.initPromise ?? Promise.resolve()
59
-
60
82
  return entry.instance
61
- }
83
+ }