@tylix/compiler 1.1.0 → 1.3.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.
@@ -6,6 +6,8 @@ import {
6
6
  IfNode,
7
7
  EachNode,
8
8
  TemplateLiteralExpr,
9
+ AwaitNode,
10
+ RawHtmlNode,
9
11
  } from '../ast/nodes.js'
10
12
  import { parseExpressionString } from './parseExpressionString.js'
11
13
 
@@ -143,15 +145,39 @@ function findInterpEnd(source, from) {
143
145
  //
144
146
  // HTML comments (<!-- ... -->) are allowed anywhere a node is allowed
145
147
  // and produce no output.
148
+ // Errors leave with `offset` (index into `source`) and, when known,
149
+ // `length`, so the dev overlay and editor can underline the spot.
146
150
  export function parseTemplate(source, options = {}) {
147
151
  const parser = new TemplateParser(source, options)
148
- const nodes = parser.parseNodes(null)
149
- if (parser.pos < parser.source.length) {
150
- throw new Error(
151
- `Unexpected closing tag near: ${parser.remaining().slice(0, 30)}`,
152
- )
152
+ try {
153
+ const nodes = parser.parseNodes(null)
154
+ if (parser.pos < parser.source.length) {
155
+ throw new Error(
156
+ `Unexpected closing tag near: ${parser.remaining().slice(0, 30)}`,
157
+ )
158
+ }
159
+ return nodes
160
+ } catch (err) {
161
+ if (err && typeof err === 'object') {
162
+ if (err.templateOffset !== undefined) {
163
+ err.offset = err.templateOffset
164
+ delete err.templateOffset
165
+ } else {
166
+ err.offset = parser.pos
167
+ delete err.length
168
+ }
169
+ }
170
+ throw err
153
171
  }
154
- return nodes
172
+ }
173
+
174
+ // Marks where in the template an error belongs (first mark wins).
175
+ function markAt(err, offset, length) {
176
+ if (err && typeof err === 'object' && err.templateOffset === undefined) {
177
+ err.templateOffset = offset
178
+ if (length !== undefined) err.length = length
179
+ }
180
+ return err
155
181
  }
156
182
 
157
183
  class TemplateParser {
@@ -159,6 +185,9 @@ class TemplateParser {
159
185
  this.options = options
160
186
  this.source = source
161
187
  this.pos = 0
188
+ // Elements and {{#if}}/{{#each}} blocks still open, innermost
189
+ // last, so "unclosed" errors can point at the opening.
190
+ this.open = []
162
191
  // Set by parseNodes: which marker it stopped at (the stopMarker,
163
192
  // one of alsoStopAt, or null for a closing tag).
164
193
  this.stopHit = null
@@ -211,6 +240,17 @@ class TemplateParser {
211
240
  return findInterpEnd(this.source, from)
212
241
  }
213
242
 
243
+ // parseExpressionString on `raw`, which starts at `start` in the
244
+ // template; errors are rebased onto the template.
245
+ parseExpr(raw, start) {
246
+ const lead = raw.length - raw.trimStart().length
247
+ try {
248
+ return parseExpressionString(raw.trim(), this.options)
249
+ } catch (err) {
250
+ throw markAt(err, start + lead + (err?.offset ?? 0), err?.length)
251
+ }
252
+ }
253
+
214
254
  // <!-- ... --> is skipped entirely: nothing inside it is parsed,
215
255
  // so {{ }} and tags inside a comment are inert.
216
256
  skipComment() {
@@ -268,6 +308,16 @@ class TemplateParser {
268
308
  continue
269
309
  }
270
310
 
311
+ if (this.at('{{#await')) {
312
+ nodes.push(this.parseAwaitBlock())
313
+ continue
314
+ }
315
+
316
+ if (this.at('{{@html')) {
317
+ nodes.push(this.parseRawHtml())
318
+ continue
319
+ }
320
+
271
321
  if (this.at('{{')) {
272
322
  nodes.push(this.parseInterpolation())
273
323
  continue
@@ -291,13 +341,22 @@ class TemplateParser {
291
341
  }
292
342
  }
293
343
 
344
+ const opener = this.open[this.open.length - 1]
294
345
  if (stopMarker !== null) {
295
- throw new Error(
296
- `Unclosed block: reached end of template looking for "${stopMarker}"`,
346
+ throw markAt(
347
+ new Error(
348
+ `Unclosed block: reached end of template looking for "${stopMarker}"`,
349
+ ),
350
+ opener?.pos ?? this.pos,
351
+ opener?.length,
297
352
  )
298
353
  }
299
354
  if (stopTag !== null) {
300
- throw new Error(`Unclosed tag <${stopTag}>: reached end of template`)
355
+ throw markAt(
356
+ new Error(`Unclosed tag <${stopTag}>: reached end of template`),
357
+ opener?.pos ?? this.pos,
358
+ opener?.length,
359
+ )
301
360
  }
302
361
  this.stopHit = null
303
362
  return nodes
@@ -328,19 +387,26 @@ class TemplateParser {
328
387
  }
329
388
  const exprSource = this.source.slice(start, end).trim()
330
389
  if (exprSource.startsWith('#') || exprSource.startsWith('/')) {
331
- throw new Error(
332
- `Unexpected block tag "{{${exprSource}}}" at line ${line}: it has no matching opening or closing tag (check {{#if}} / {{#each}} / {{#else}} / {{/if}} / {{/each}})`,
390
+ throw markAt(
391
+ new Error(
392
+ `Unexpected block tag "{{${exprSource}}}" at line ${line}: it has no matching opening or closing tag (check {{#if}} / {{#each}} / {{#else}} / {{/if}} / {{/each}})`,
393
+ ),
394
+ start - 2,
395
+ end + 2 - (start - 2),
333
396
  )
334
397
  }
335
398
  this.pos = end + 2
336
399
  return {
337
- ...InterpolationNode(parseExpressionString(exprSource, this.options)),
400
+ ...InterpolationNode(
401
+ this.parseExpr(this.source.slice(start, end), start),
402
+ ),
338
403
  line,
339
404
  }
340
405
  }
341
406
 
342
407
  parseIfBlock() {
343
408
  const line = this.lineAt(this.pos)
409
+ const blockStart = this.pos
344
410
  this.pos += 2 // "{{"
345
411
  this.pos += 3 // "#if"
346
412
  this.skipWhitespace()
@@ -348,15 +414,19 @@ class TemplateParser {
348
414
  if (end === -1) {
349
415
  throw new Error("Unterminated {{#if}} header: missing '}}'")
350
416
  }
351
- const conditionSource = this.source.slice(this.pos, end).trim()
417
+ const conditionStart = this.pos
418
+ const conditionSource = this.source.slice(this.pos, end)
352
419
  this.pos = end + 2
353
- return this.parseIfRest(conditionSource, line)
420
+ this.open.push({ pos: blockStart, length: this.pos - blockStart })
421
+ const node = this.parseIfRest(conditionSource, line, conditionStart)
422
+ this.open.pop()
423
+ return node
354
424
  }
355
425
 
356
426
  // Parses the body of an {{#if}} (header already consumed), plus an
357
427
  // optional {{#else}} or {{#else if cond}} chain. An else-if is a
358
428
  // nested IfNode in elseChildren that shares the single {{/if}}.
359
- parseIfRest(conditionSource, line) {
429
+ parseIfRest(conditionSource, line, conditionStart) {
360
430
  const children = this.parseNodes(null, '{{/if}}', ['{{#else'])
361
431
 
362
432
  let elseChildren = null
@@ -368,6 +438,7 @@ class TemplateParser {
368
438
  if (end === -1) {
369
439
  throw new Error("Unterminated {{#else}} header: missing '}}'")
370
440
  }
441
+ const headerStart = this.pos
371
442
  const header = this.source.slice(this.pos, end).trim()
372
443
  this.pos = end + 2
373
444
 
@@ -375,7 +446,8 @@ class TemplateParser {
375
446
  if (header === '') {
376
447
  elseChildren = this.parseNodes(null, '{{/if}}')
377
448
  } else if (elseIf) {
378
- elseChildren = [this.parseIfRest(elseIf[1].trim(), elseLine)]
449
+ const condStart = headerStart + elseIf[0].length - elseIf[1].length
450
+ elseChildren = [this.parseIfRest(elseIf[1], elseLine, condStart)]
379
451
  } else {
380
452
  throw new Error(
381
453
  `Invalid {{#else}} header "${header}" at line ${elseLine}: expected {{#else}} or {{#else if condition}}`,
@@ -385,7 +457,7 @@ class TemplateParser {
385
457
 
386
458
  return {
387
459
  ...IfNode(
388
- parseExpressionString(conditionSource, this.options),
460
+ this.parseExpr(conditionSource, conditionStart),
389
461
  children,
390
462
  elseChildren,
391
463
  ),
@@ -393,8 +465,94 @@ class TemplateParser {
393
465
  }
394
466
  }
395
467
 
468
+ // {{@html expr}}
469
+ parseRawHtml() {
470
+ const line = this.lineAt(this.pos)
471
+ const start = this.pos
472
+ const exprStart = this.pos + '{{@html'.length
473
+ const end = this.findInterpEnd(exprStart)
474
+ if (end === -1) {
475
+ throw markAt(new Error("Unterminated {{@html}}: missing '}}'"), start, 7)
476
+ }
477
+ const raw = this.source.slice(exprStart, end)
478
+ if (!raw.trim()) {
479
+ throw markAt(new Error('{{@html}} needs an expression: {{@html content}}'), start, end + 2 - start)
480
+ }
481
+ this.pos = end + 2
482
+ return { ...RawHtmlNode(this.parseExpr(raw, exprStart)), line }
483
+ }
484
+
485
+ // {{#await p}}…{{#then v}}…{{#catch e}}…{{/await}}
486
+ // {{#await p then v}}…{{#catch e}}…{{/await}}
487
+ parseAwaitBlock() {
488
+ const line = this.lineAt(this.pos)
489
+ const blockStart = this.pos
490
+ this.pos += '{{#await'.length
491
+ const headerStart = this.pos
492
+ const end = this.findInterpEnd(this.pos)
493
+ if (end === -1) {
494
+ throw markAt(new Error("Unterminated {{#await}} header: missing '}}'"), blockStart, 8)
495
+ }
496
+ const header = this.source.slice(headerStart, end)
497
+ this.pos = end + 2
498
+
499
+ // "p then v": the last top-level " then " splits promise and name.
500
+ const short = /^([\s\S]*?\S)\s+then(?:\s+(\[[^\]]*\]|\{[^}]*\}|[A-Za-z_$][\w$]*))?\s*$/.exec(header)
501
+ const promiseSource = short ? short[1] : header
502
+ if (!promiseSource.trim()) {
503
+ throw markAt(new Error('{{#await}} needs a promise: {{#await loadPosts()}}'), blockStart, this.pos - blockStart)
504
+ }
505
+ const promise = this.parseExpr(promiseSource, headerStart)
506
+
507
+ let pending = null
508
+ let thenName = short ? short[2] ?? null : null
509
+ let thenChildren = null
510
+ let catchName = null
511
+ let catchChildren = null
512
+
513
+ this.open.push({ pos: blockStart, length: this.pos - blockStart })
514
+ const markers = ['{{#then', '{{#catch']
515
+ let section = short ? 'then' : 'pending'
516
+ for (;;) {
517
+ const children = this.parseNodes(null, '{{/await}}', markers)
518
+ if (section === 'pending') pending = children
519
+ else if (section === 'then') thenChildren = children
520
+ else catchChildren = children
521
+ if (this.stopHit === '{{/await}}') break
522
+ if (this.stopHit === null) {
523
+ // A closing tag (or the end) came first.
524
+ throw markAt(new Error('Unclosed {{#await}}: expected {{/await}} before this point'), blockStart, headerStart - blockStart)
525
+ }
526
+
527
+ const marker = this.stopHit
528
+ const markerStart = this.pos
529
+ const next = marker === '{{#then' ? 'then' : 'catch'
530
+ if ((next === 'then' && (section !== 'pending')) || (next === 'catch' && section === 'catch')) {
531
+ throw markAt(new Error(`Unexpected {{#${next}}}: an {{#await}} has at most one {{#then}} and one {{#catch}}, in that order`), markerStart, marker.length)
532
+ }
533
+ this.pos += marker.length
534
+ const nameEnd = this.findInterpEnd(this.pos)
535
+ if (nameEnd === -1) throw markAt(new Error(`Unterminated {{#${next}}}: missing '}}'`), markerStart, marker.length)
536
+ const name = this.source.slice(this.pos, nameEnd).trim()
537
+ if (name && !/^(\[[^\]]*\]|\{[^}]*\}|[A-Za-z_$][\w$]*)$/.test(name)) {
538
+ throw markAt(new Error(`Invalid {{#${next}}} name "${name}": expected a name like {{#${next} ${next === 'then' ? 'posts' : 'error'}}}`), markerStart, nameEnd + 2 - markerStart)
539
+ }
540
+ this.pos = nameEnd + 2
541
+ if (next === 'then') thenName = name || null
542
+ else catchName = name || null
543
+ section = next
544
+ }
545
+ this.open.pop()
546
+
547
+ return {
548
+ ...AwaitNode(promise, pending, thenName, thenChildren, catchName, catchChildren),
549
+ line,
550
+ }
551
+ }
552
+
396
553
  parseEachBlock() {
397
554
  const line = this.lineAt(this.pos)
555
+ const blockStart = this.pos
398
556
  this.pos += 2 // "{{"
399
557
  this.pos += 5 // "#each"
400
558
  this.skipWhitespace()
@@ -402,19 +560,26 @@ class TemplateParser {
402
560
  if (end === -1) {
403
561
  throw new Error("Unterminated {{#each}} header: missing '}}'")
404
562
  }
563
+ const headerStart = this.pos
405
564
  const header = this.source.slice(this.pos, end).trim()
406
565
  this.pos = end + 2
407
566
 
408
567
  const match = EACH_HEADER_RE.exec(header)
409
568
  if (!match) {
410
- throw new Error(
411
- `Invalid {{#each}} header "${header}": expected "item in items", "item, index in items" or "[a, b] in pairs"`,
569
+ throw markAt(
570
+ new Error(
571
+ `Invalid {{#each}} header "${header}": expected "item in items", "item, index in items" or "[a, b] in pairs"`,
572
+ ),
573
+ blockStart,
574
+ this.pos - blockStart,
412
575
  )
413
576
  }
414
577
  const itemName = match[1]
415
578
  const indexName = match[2] ?? null
416
- const iterableSource = match[3].trim()
579
+ const iterableSource = match[3]
580
+ const iterableStart = headerStart + header.length - match[3].length
417
581
 
582
+ this.open.push({ pos: blockStart, length: this.pos - blockStart })
418
583
  const children = this.parseNodes(null, '{{/each}}', ['{{#else'])
419
584
 
420
585
  let elseChildren = null
@@ -434,11 +599,12 @@ class TemplateParser {
434
599
  this.pos = elseEnd + 2
435
600
  elseChildren = this.parseNodes(null, '{{/each}}')
436
601
  }
602
+ this.open.pop()
437
603
 
438
604
  return {
439
605
  ...EachNode(
440
606
  itemName,
441
- parseExpressionString(iterableSource, this.options),
607
+ this.parseExpr(iterableSource, iterableStart),
442
608
  children,
443
609
  indexName,
444
610
  elseChildren,
@@ -449,6 +615,7 @@ class TemplateParser {
449
615
 
450
616
  parseElement() {
451
617
  const line = this.lineAt(this.pos)
618
+ const elementStart = this.pos
452
619
  this.pos++
453
620
  const tag = this.readTagName()
454
621
  const attributes = this.parseAttributes()
@@ -489,11 +656,14 @@ class TemplateParser {
489
656
  }
490
657
  }
491
658
 
659
+ this.open.push({ pos: elementStart, length: tag.length + 1 })
492
660
  const children = this.parseNodes(tag)
661
+ this.open.pop()
493
662
  return { ...ElementNode(tag, attributes, children), line }
494
663
  }
495
664
 
496
665
  consumeClosingTag(expectedTag) {
666
+ const closeStart = this.pos
497
667
  this.pos += 2
498
668
  const name = this.readTagName()
499
669
  this.skipWhitespace()
@@ -502,8 +672,12 @@ class TemplateParser {
502
672
  }
503
673
  this.pos++
504
674
  if (name !== expectedTag) {
505
- throw new Error(
506
- `Mismatched closing tag: expected </${expectedTag}>, got </${name}>`,
675
+ throw markAt(
676
+ new Error(
677
+ `Mismatched closing tag: expected </${expectedTag}>, got </${name}>`,
678
+ ),
679
+ closeStart,
680
+ this.pos - closeStart,
507
681
  )
508
682
  }
509
683
  }
@@ -552,10 +726,11 @@ class TemplateParser {
552
726
 
553
727
  const quote = this.source[this.pos]
554
728
  let rawValue
729
+ let valueStart
555
730
 
556
731
  if (quote === '"' || quote === "'") {
557
732
  this.pos++
558
- const valueStart = this.pos
733
+ valueStart = this.pos
559
734
  while (this.pos < this.source.length && this.source[this.pos] !== quote) {
560
735
  this.pos++
561
736
  }
@@ -568,7 +743,7 @@ class TemplateParser {
568
743
  // Unquoted value (<input type=text>): runs to whitespace or
569
744
  // '>'. A {{ ... }} inside it is scanned as a unit, so
570
745
  // `value={{ a + b }}` keeps its spaces.
571
- const valueStart = this.pos
746
+ valueStart = this.pos
572
747
  while (
573
748
  this.pos < this.source.length &&
574
749
  !/[\s>]/.test(this.source[this.pos])
@@ -591,7 +766,7 @@ class TemplateParser {
591
766
  }
592
767
  }
593
768
 
594
- return { ...this.buildAttribute(name, rawValue, line), line }
769
+ return { ...this.buildAttribute(name, rawValue, line, valueStart), line }
595
770
  }
596
771
 
597
772
  // Splits an attribute value into literal text and {{ }} parts.
@@ -600,7 +775,7 @@ class TemplateParser {
600
775
  // numbers stay numbers, etc.)
601
776
  // "btn {{ a }} x-{{ b }}" -> a template literal
602
777
  // Literal text has HTML entities decoded (title="a &amp; b").
603
- buildAttribute(name, rawValue, line) {
778
+ buildAttribute(name, rawValue, line, valueStart = 0) {
604
779
  if (!rawValue.includes('{{')) {
605
780
  return AttributeNode(name, decodeHtmlEntities(rawValue), false)
606
781
  }
@@ -622,9 +797,9 @@ class TemplateParser {
622
797
  }
623
798
  parts.push({
624
799
  type: 'expr',
625
- expression: parseExpressionString(
626
- rawValue.slice(i + 2, end).trim(),
627
- this.options,
800
+ expression: this.parseExpr(
801
+ rawValue.slice(i + 2, end),
802
+ valueStart + i + 2,
628
803
  ),
629
804
  })
630
805
  i = end + 2
@@ -45,13 +45,31 @@ const NOT_FOUND_SOURCE = fs
45
45
  // Attaches a class's module-level helpers (see withHelpers) to a fresh
46
46
  // instance, so templates can call them: a bare `formatPrice(x)` in a
47
47
  // template compiles to `instance.formatPrice(x)`.
48
+ //
49
+ // It also reports the instance to the devtools hook when one is
50
+ // installed (see runtime/devtoolsHook.js); __tylixAttach tells it which
51
+ // DOM node the instance rendered.
48
52
  const EXPOSE_HELPERS_SOURCE = `
49
- function __tylixExpose(instance, cls) {
53
+ var __tylixRuntime = { effect: effect, untracked: untracked, toRaw: toRaw };
54
+ function __tylixHook() {
55
+ return typeof window !== "undefined" ? window.__TYLIX_DEVTOOLS_HOOK__ : undefined;
56
+ }
57
+ function __tylixExpose(instance, cls, meta) {
50
58
  var helpers = cls && cls.__helpers;
51
59
  if (helpers) {
52
60
  for (var key of Object.keys(helpers)) instance[key] = helpers[key];
53
61
  }
62
+ var hook = __tylixHook();
63
+ if (hook && hook.register) {
64
+ try { hook.register(instance, meta || { kind: "component", name: cls && cls.name }, __tylixRuntime); } catch (e) {}
65
+ }
54
66
  return instance;
67
+ }
68
+ function __tylixAttach(instance, node) {
69
+ var hook = __tylixHook();
70
+ if (hook && hook.attach) {
71
+ try { hook.attach(instance, node); } catch (e) {}
72
+ }
55
73
  }`
56
74
 
57
75
  function escapeHtml(text) {
@@ -427,7 +445,7 @@ export async function renderPageDocument(
427
445
  loadingClassSource = loadingCompiled.classSource
428
446
  loadingMountCode = `
429
447
  try {
430
- const loadingInstance = __tylixExpose(new ${loadingCompiled.className}({ loading: __tylixLoading }), ${loadingCompiled.className});
448
+ const loadingInstance = __tylixExpose(new ${loadingCompiled.className}({ loading: __tylixLoading }), ${loadingCompiled.className}, { kind: "loading", name: "Loading" });
431
449
  (function (document, instance) {
432
450
  ${loadingCompiled.code}
433
451
  document.body.appendChild(${loadingCompiled.rootVar});
@@ -469,11 +487,12 @@ ${loadingCompiled.code}
469
487
  const { code: childCode, rootVar: childRootVar, className } = compiled
470
488
  return ` components[${label}] = {
471
489
  mount(document, props = {}) {
472
- const instance = __tylixExpose(new ${className}(props), ${className});
490
+ const instance = __tylixExpose(new ${className}(props), ${className}, { kind: "component", name: ${label} });
473
491
  const node = (function (document, instance) {
474
492
  ${childCode}
475
493
  return ${childRootVar};
476
494
  })(document, instance);
495
+ __tylixAttach(instance, node);
477
496
  // needs/prefetch first, then onMount, same order as pages.
478
497
  // Runs a microtask later, after the caller has attached the node.
479
498
  Promise.resolve()
@@ -500,7 +519,7 @@ ${childCode}
500
519
  }
501
520
  layoutClassSource = layoutCompiled.classSource
502
521
  layoutMountCode = `
503
- const layoutInstance = __tylixExpose(new ${layoutCompiled.className}(), ${layoutCompiled.className});
522
+ const layoutInstance = __tylixExpose(new ${layoutCompiled.className}(), ${layoutCompiled.className}, { kind: "layout", name: "Layout" });
504
523
  if (typeof layoutInstance.__ready === "function") {
505
524
  try {
506
525
  await layoutInstance.__ready();
@@ -516,6 +535,7 @@ ${layoutCompiled.code}
516
535
  }
517
536
  slot.appendChild(pageRoot);
518
537
  document.getElementById("app").appendChild(${layoutCompiled.rootVar});
538
+ __tylixAttach(instance, ${layoutCompiled.rootVar});
519
539
  })(document, layoutInstance, ${rootVar});
520
540
  if (typeof layoutInstance.__onMount === "function") {
521
541
  try {
@@ -563,7 +583,7 @@ ${layoutClassSource}
563
583
  ${loadingClassSource}
564
584
 
565
585
  document.addEventListener("DOMContentLoaded", () => {
566
- const instance = __tylixExpose(new ${pageName}(${JSON.stringify(props)}), ${pageName});
586
+ const instance = __tylixExpose(new ${pageName}(${JSON.stringify(props)}), ${pageName}, { kind: "page", name: ${JSON.stringify(pageName)} });
567
587
  const components = {};
568
588
  ${childRegistrations}
569
589
  (async function (document, instance, components) {
@@ -576,6 +596,7 @@ ${loadingMountCode}
576
596
  }
577
597
  }
578
598
  ${code}
599
+ __tylixAttach(instance, ${rootVar});
579
600
  ${layoutMountCode}
580
601
  if (typeof instance.__onMount === "function") {
581
602
  try {
@@ -54,6 +54,13 @@ export function resolveCapability(name) {
54
54
  // keep writing to reactive state.
55
55
  instance.ready = () => entry.initPromise ?? Promise.resolve()
56
56
  entry.instance = instance
57
+ const hook =
58
+ typeof window !== 'undefined' ? window.__TYLIX_DEVTOOLS_HOOK__ : undefined
59
+ if (hook && hook.capability) {
60
+ try {
61
+ hook.capability(name, instance)
62
+ } catch {}
63
+ }
57
64
  }
58
65
 
59
66
  // init() runs exactly once, whether it is async or not.