@tylix/compiler 1.1.0 → 1.2.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.
@@ -143,15 +143,39 @@ function findInterpEnd(source, from) {
143
143
  //
144
144
  // HTML comments (<!-- ... -->) are allowed anywhere a node is allowed
145
145
  // and produce no output.
146
+ // Errors leave with `offset` (index into `source`) and, when known,
147
+ // `length`, so the dev overlay and editor can underline the spot.
146
148
  export function parseTemplate(source, options = {}) {
147
149
  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
- )
150
+ try {
151
+ const nodes = parser.parseNodes(null)
152
+ if (parser.pos < parser.source.length) {
153
+ throw new Error(
154
+ `Unexpected closing tag near: ${parser.remaining().slice(0, 30)}`,
155
+ )
156
+ }
157
+ return nodes
158
+ } catch (err) {
159
+ if (err && typeof err === 'object') {
160
+ if (err.templateOffset !== undefined) {
161
+ err.offset = err.templateOffset
162
+ delete err.templateOffset
163
+ } else {
164
+ err.offset = parser.pos
165
+ delete err.length
166
+ }
167
+ }
168
+ throw err
169
+ }
170
+ }
171
+
172
+ // Marks where in the template an error belongs (first mark wins).
173
+ function markAt(err, offset, length) {
174
+ if (err && typeof err === 'object' && err.templateOffset === undefined) {
175
+ err.templateOffset = offset
176
+ if (length !== undefined) err.length = length
153
177
  }
154
- return nodes
178
+ return err
155
179
  }
156
180
 
157
181
  class TemplateParser {
@@ -159,6 +183,9 @@ class TemplateParser {
159
183
  this.options = options
160
184
  this.source = source
161
185
  this.pos = 0
186
+ // Elements and {{#if}}/{{#each}} blocks still open, innermost
187
+ // last, so "unclosed" errors can point at the opening.
188
+ this.open = []
162
189
  // Set by parseNodes: which marker it stopped at (the stopMarker,
163
190
  // one of alsoStopAt, or null for a closing tag).
164
191
  this.stopHit = null
@@ -211,6 +238,17 @@ class TemplateParser {
211
238
  return findInterpEnd(this.source, from)
212
239
  }
213
240
 
241
+ // parseExpressionString on `raw`, which starts at `start` in the
242
+ // template; errors are rebased onto the template.
243
+ parseExpr(raw, start) {
244
+ const lead = raw.length - raw.trimStart().length
245
+ try {
246
+ return parseExpressionString(raw.trim(), this.options)
247
+ } catch (err) {
248
+ throw markAt(err, start + lead + (err?.offset ?? 0), err?.length)
249
+ }
250
+ }
251
+
214
252
  // <!-- ... --> is skipped entirely: nothing inside it is parsed,
215
253
  // so {{ }} and tags inside a comment are inert.
216
254
  skipComment() {
@@ -291,13 +329,22 @@ class TemplateParser {
291
329
  }
292
330
  }
293
331
 
332
+ const opener = this.open[this.open.length - 1]
294
333
  if (stopMarker !== null) {
295
- throw new Error(
296
- `Unclosed block: reached end of template looking for "${stopMarker}"`,
334
+ throw markAt(
335
+ new Error(
336
+ `Unclosed block: reached end of template looking for "${stopMarker}"`,
337
+ ),
338
+ opener?.pos ?? this.pos,
339
+ opener?.length,
297
340
  )
298
341
  }
299
342
  if (stopTag !== null) {
300
- throw new Error(`Unclosed tag <${stopTag}>: reached end of template`)
343
+ throw markAt(
344
+ new Error(`Unclosed tag <${stopTag}>: reached end of template`),
345
+ opener?.pos ?? this.pos,
346
+ opener?.length,
347
+ )
301
348
  }
302
349
  this.stopHit = null
303
350
  return nodes
@@ -328,19 +375,26 @@ class TemplateParser {
328
375
  }
329
376
  const exprSource = this.source.slice(start, end).trim()
330
377
  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}})`,
378
+ throw markAt(
379
+ new Error(
380
+ `Unexpected block tag "{{${exprSource}}}" at line ${line}: it has no matching opening or closing tag (check {{#if}} / {{#each}} / {{#else}} / {{/if}} / {{/each}})`,
381
+ ),
382
+ start - 2,
383
+ end + 2 - (start - 2),
333
384
  )
334
385
  }
335
386
  this.pos = end + 2
336
387
  return {
337
- ...InterpolationNode(parseExpressionString(exprSource, this.options)),
388
+ ...InterpolationNode(
389
+ this.parseExpr(this.source.slice(start, end), start),
390
+ ),
338
391
  line,
339
392
  }
340
393
  }
341
394
 
342
395
  parseIfBlock() {
343
396
  const line = this.lineAt(this.pos)
397
+ const blockStart = this.pos
344
398
  this.pos += 2 // "{{"
345
399
  this.pos += 3 // "#if"
346
400
  this.skipWhitespace()
@@ -348,15 +402,19 @@ class TemplateParser {
348
402
  if (end === -1) {
349
403
  throw new Error("Unterminated {{#if}} header: missing '}}'")
350
404
  }
351
- const conditionSource = this.source.slice(this.pos, end).trim()
405
+ const conditionStart = this.pos
406
+ const conditionSource = this.source.slice(this.pos, end)
352
407
  this.pos = end + 2
353
- return this.parseIfRest(conditionSource, line)
408
+ this.open.push({ pos: blockStart, length: this.pos - blockStart })
409
+ const node = this.parseIfRest(conditionSource, line, conditionStart)
410
+ this.open.pop()
411
+ return node
354
412
  }
355
413
 
356
414
  // Parses the body of an {{#if}} (header already consumed), plus an
357
415
  // optional {{#else}} or {{#else if cond}} chain. An else-if is a
358
416
  // nested IfNode in elseChildren that shares the single {{/if}}.
359
- parseIfRest(conditionSource, line) {
417
+ parseIfRest(conditionSource, line, conditionStart) {
360
418
  const children = this.parseNodes(null, '{{/if}}', ['{{#else'])
361
419
 
362
420
  let elseChildren = null
@@ -368,6 +426,7 @@ class TemplateParser {
368
426
  if (end === -1) {
369
427
  throw new Error("Unterminated {{#else}} header: missing '}}'")
370
428
  }
429
+ const headerStart = this.pos
371
430
  const header = this.source.slice(this.pos, end).trim()
372
431
  this.pos = end + 2
373
432
 
@@ -375,7 +434,8 @@ class TemplateParser {
375
434
  if (header === '') {
376
435
  elseChildren = this.parseNodes(null, '{{/if}}')
377
436
  } else if (elseIf) {
378
- elseChildren = [this.parseIfRest(elseIf[1].trim(), elseLine)]
437
+ const condStart = headerStart + elseIf[0].length - elseIf[1].length
438
+ elseChildren = [this.parseIfRest(elseIf[1], elseLine, condStart)]
379
439
  } else {
380
440
  throw new Error(
381
441
  `Invalid {{#else}} header "${header}" at line ${elseLine}: expected {{#else}} or {{#else if condition}}`,
@@ -385,7 +445,7 @@ class TemplateParser {
385
445
 
386
446
  return {
387
447
  ...IfNode(
388
- parseExpressionString(conditionSource, this.options),
448
+ this.parseExpr(conditionSource, conditionStart),
389
449
  children,
390
450
  elseChildren,
391
451
  ),
@@ -395,6 +455,7 @@ class TemplateParser {
395
455
 
396
456
  parseEachBlock() {
397
457
  const line = this.lineAt(this.pos)
458
+ const blockStart = this.pos
398
459
  this.pos += 2 // "{{"
399
460
  this.pos += 5 // "#each"
400
461
  this.skipWhitespace()
@@ -402,19 +463,26 @@ class TemplateParser {
402
463
  if (end === -1) {
403
464
  throw new Error("Unterminated {{#each}} header: missing '}}'")
404
465
  }
466
+ const headerStart = this.pos
405
467
  const header = this.source.slice(this.pos, end).trim()
406
468
  this.pos = end + 2
407
469
 
408
470
  const match = EACH_HEADER_RE.exec(header)
409
471
  if (!match) {
410
- throw new Error(
411
- `Invalid {{#each}} header "${header}": expected "item in items", "item, index in items" or "[a, b] in pairs"`,
472
+ throw markAt(
473
+ new Error(
474
+ `Invalid {{#each}} header "${header}": expected "item in items", "item, index in items" or "[a, b] in pairs"`,
475
+ ),
476
+ blockStart,
477
+ this.pos - blockStart,
412
478
  )
413
479
  }
414
480
  const itemName = match[1]
415
481
  const indexName = match[2] ?? null
416
- const iterableSource = match[3].trim()
482
+ const iterableSource = match[3]
483
+ const iterableStart = headerStart + header.length - match[3].length
417
484
 
485
+ this.open.push({ pos: blockStart, length: this.pos - blockStart })
418
486
  const children = this.parseNodes(null, '{{/each}}', ['{{#else'])
419
487
 
420
488
  let elseChildren = null
@@ -434,11 +502,12 @@ class TemplateParser {
434
502
  this.pos = elseEnd + 2
435
503
  elseChildren = this.parseNodes(null, '{{/each}}')
436
504
  }
505
+ this.open.pop()
437
506
 
438
507
  return {
439
508
  ...EachNode(
440
509
  itemName,
441
- parseExpressionString(iterableSource, this.options),
510
+ this.parseExpr(iterableSource, iterableStart),
442
511
  children,
443
512
  indexName,
444
513
  elseChildren,
@@ -449,6 +518,7 @@ class TemplateParser {
449
518
 
450
519
  parseElement() {
451
520
  const line = this.lineAt(this.pos)
521
+ const elementStart = this.pos
452
522
  this.pos++
453
523
  const tag = this.readTagName()
454
524
  const attributes = this.parseAttributes()
@@ -489,11 +559,14 @@ class TemplateParser {
489
559
  }
490
560
  }
491
561
 
562
+ this.open.push({ pos: elementStart, length: tag.length + 1 })
492
563
  const children = this.parseNodes(tag)
564
+ this.open.pop()
493
565
  return { ...ElementNode(tag, attributes, children), line }
494
566
  }
495
567
 
496
568
  consumeClosingTag(expectedTag) {
569
+ const closeStart = this.pos
497
570
  this.pos += 2
498
571
  const name = this.readTagName()
499
572
  this.skipWhitespace()
@@ -502,8 +575,12 @@ class TemplateParser {
502
575
  }
503
576
  this.pos++
504
577
  if (name !== expectedTag) {
505
- throw new Error(
506
- `Mismatched closing tag: expected </${expectedTag}>, got </${name}>`,
578
+ throw markAt(
579
+ new Error(
580
+ `Mismatched closing tag: expected </${expectedTag}>, got </${name}>`,
581
+ ),
582
+ closeStart,
583
+ this.pos - closeStart,
507
584
  )
508
585
  }
509
586
  }
@@ -552,10 +629,11 @@ class TemplateParser {
552
629
 
553
630
  const quote = this.source[this.pos]
554
631
  let rawValue
632
+ let valueStart
555
633
 
556
634
  if (quote === '"' || quote === "'") {
557
635
  this.pos++
558
- const valueStart = this.pos
636
+ valueStart = this.pos
559
637
  while (this.pos < this.source.length && this.source[this.pos] !== quote) {
560
638
  this.pos++
561
639
  }
@@ -568,7 +646,7 @@ class TemplateParser {
568
646
  // Unquoted value (<input type=text>): runs to whitespace or
569
647
  // '>'. A {{ ... }} inside it is scanned as a unit, so
570
648
  // `value={{ a + b }}` keeps its spaces.
571
- const valueStart = this.pos
649
+ valueStart = this.pos
572
650
  while (
573
651
  this.pos < this.source.length &&
574
652
  !/[\s>]/.test(this.source[this.pos])
@@ -591,7 +669,7 @@ class TemplateParser {
591
669
  }
592
670
  }
593
671
 
594
- return { ...this.buildAttribute(name, rawValue, line), line }
672
+ return { ...this.buildAttribute(name, rawValue, line, valueStart), line }
595
673
  }
596
674
 
597
675
  // Splits an attribute value into literal text and {{ }} parts.
@@ -600,7 +678,7 @@ class TemplateParser {
600
678
  // numbers stay numbers, etc.)
601
679
  // "btn {{ a }} x-{{ b }}" -> a template literal
602
680
  // Literal text has HTML entities decoded (title="a &amp; b").
603
- buildAttribute(name, rawValue, line) {
681
+ buildAttribute(name, rawValue, line, valueStart = 0) {
604
682
  if (!rawValue.includes('{{')) {
605
683
  return AttributeNode(name, decodeHtmlEntities(rawValue), false)
606
684
  }
@@ -622,9 +700,9 @@ class TemplateParser {
622
700
  }
623
701
  parts.push({
624
702
  type: 'expr',
625
- expression: parseExpressionString(
626
- rawValue.slice(i + 2, end).trim(),
627
- this.options,
703
+ expression: this.parseExpr(
704
+ rawValue.slice(i + 2, end),
705
+ valueStart + i + 2,
628
706
  ),
629
707
  })
630
708
  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.