@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.
@@ -0,0 +1,389 @@
1
+ // Tylix devtools hook: a plain browser script (no imports or exports).
2
+ //
3
+ // Installs window.__TYLIX_DEVTOOLS_HOOK__, which the native runtime
4
+ // reports to as it creates page, layout and component instances and
5
+ // resolves capabilities. `tylix dev` injects it into every page, and
6
+ // the Tylix DevTools browser extension installs it before any page
7
+ // script runs, so it also works on apps not served by `tylix dev`.
8
+ // Without it, the runtime's only cost is one property check per
9
+ // instance.
10
+ //
11
+ // Everything the hook hands out is plain JSON, so the extension can
12
+ // fetch it with devtools.inspectedWindow.eval:
13
+ // hook.snapshot() tree of live instances + capabilities
14
+ // hook.inspect(id) state / props / computed / actions of one
15
+ // hook.set(id, key, json) assign a state field or prop (re-renders)
16
+ // hook.call(id, action, argsJson)
17
+ // hook.highlight(id) / hook.highlight(null)
18
+ // hook.version bumps whenever anything watched changes
19
+ // From the console: __TYLIX_DEVTOOLS_HOOK__.find("Counter")
20
+ ;(function () {
21
+ if (typeof window === 'undefined' || window.__TYLIX_DEVTOOLS_HOOK__) return
22
+
23
+ var nextId = 1
24
+ var records = new Map() // id -> { id, kind, name, instance, node, watcher }
25
+ var byInstance = new WeakMap() // instance -> record
26
+ var capabilities = new Map() // name -> { id, name, instance, watcher }
27
+ var runtime = null // { effect, untracked, toRaw } from the page
28
+ var watching = false
29
+ var overlay = null
30
+
31
+ var hook = {
32
+ version: 0,
33
+ apiVersion: 1,
34
+
35
+ // Called by the runtime (see __tylixExpose).
36
+ register: function (instance, meta, rt) {
37
+ if (!instance || byInstance.has(instance)) return
38
+ if (rt) runtime = rt
39
+ var rec = {
40
+ id: nextId++,
41
+ kind: (meta && meta.kind) || 'component',
42
+ name: (meta && meta.name) || 'Anonymous',
43
+ instance: instance,
44
+ node: null,
45
+ watcher: null,
46
+ }
47
+ records.set(rec.id, rec)
48
+ byInstance.set(instance, rec)
49
+ if (watching) watch(rec)
50
+ bump()
51
+ },
52
+
53
+ attach: function (instance, node) {
54
+ var rec = byInstance.get(instance)
55
+ if (rec) {
56
+ rec.node = node
57
+ bump()
58
+ }
59
+ },
60
+
61
+ capability: function (name, instance) {
62
+ if (capabilities.has(name)) return
63
+ var rec = { id: 'cap:' + name, name: name, instance: instance, watcher: null }
64
+ capabilities.set(name, rec)
65
+ if (watching) watch(rec)
66
+ bump()
67
+ },
68
+
69
+ snapshot: function () {
70
+ startWatching()
71
+ prune()
72
+ var live = []
73
+ records.forEach(function (rec) {
74
+ live.push(rec)
75
+ })
76
+ var items = live.map(function (rec) {
77
+ return {
78
+ id: rec.id,
79
+ kind: rec.kind,
80
+ name: rec.name,
81
+ parentId: parentOf(rec, live),
82
+ tag: rec.node && rec.node.tagName ? rec.node.tagName.toLowerCase() : null,
83
+ }
84
+ })
85
+ var caps = []
86
+ capabilities.forEach(function (rec) {
87
+ caps.push({ id: rec.id, name: rec.name })
88
+ })
89
+ return { version: hook.version, instances: items, capabilities: caps, url: location.href }
90
+ },
91
+
92
+ inspect: function (id) {
93
+ var rec = lookup(id)
94
+ if (!rec) return null
95
+ var inst = rec.instance
96
+ var out = { id: id, name: rec.name, kind: rec.kind || 'capability', state: [], props: [], computed: [], actions: [] }
97
+ var seen = {}
98
+
99
+ if (rec.kind) {
100
+ // page / layout / component: generated class instance
101
+ var state = inst.__state ? keysOf(inst.__state) : []
102
+ state.forEach(function (k) {
103
+ seen[k] = true
104
+ out.state.push(field(inst, k, true))
105
+ })
106
+ var props = inst.__props ? keysOf(inst.__props) : []
107
+ props.forEach(function (k) {
108
+ if (seen[k]) return
109
+ seen[k] = true
110
+ out.props.push(field(inst, k, true))
111
+ })
112
+ var proto = Object.getPrototypeOf(inst)
113
+ Object.getOwnPropertyNames(proto).forEach(function (k) {
114
+ if (k === 'constructor' || k.indexOf('__') === 0 || seen[k]) return
115
+ var d = Object.getOwnPropertyDescriptor(proto, k)
116
+ if (d.get) out.computed.push(field(inst, k, false))
117
+ else if (typeof d.value === 'function') out.actions.push(k)
118
+ })
119
+ } else {
120
+ // capability: a reactive object of state plus bound actions
121
+ keysOf(inst).forEach(function (k) {
122
+ if (k === 'ready') return
123
+ var v = safeGet(inst, k)
124
+ if (typeof v.value === 'function') out.actions.push(k)
125
+ else out.state.push(field(inst, k, true))
126
+ })
127
+ }
128
+ return out
129
+ },
130
+
131
+ set: function (id, key, json) {
132
+ var rec = lookup(id)
133
+ if (!rec) return { ok: false, error: 'Not found (the component may have unmounted).' }
134
+ var value
135
+ try {
136
+ value = JSON.parse(json)
137
+ } catch (e) {
138
+ return { ok: false, error: 'Not valid JSON: ' + e.message }
139
+ }
140
+ try {
141
+ rec.instance[key] = value
142
+ bump()
143
+ return { ok: true }
144
+ } catch (e) {
145
+ return { ok: false, error: String((e && e.message) || e) }
146
+ }
147
+ },
148
+
149
+ call: function (id, action, argsJson) {
150
+ var rec = lookup(id)
151
+ if (!rec) return { ok: false, error: 'Not found.' }
152
+ var args = []
153
+ try {
154
+ if (argsJson && argsJson.trim()) args = JSON.parse('[' + argsJson + ']')
155
+ } catch (e) {
156
+ return { ok: false, error: 'Arguments must be comma-separated JSON: ' + e.message }
157
+ }
158
+ try {
159
+ var result = rec.instance[action].apply(rec.instance, args)
160
+ if (result && typeof result.then === 'function') {
161
+ result.then(
162
+ function (v) { console.log('[tylix devtools] ' + rec.name + '.' + action + '() resolved:', v) },
163
+ function (err) { console.error('[tylix devtools] ' + rec.name + '.' + action + '() rejected:', err) },
164
+ )
165
+ return { ok: true, result: '(promise, see the console)' }
166
+ }
167
+ return { ok: true, result: preview(result, 2) }
168
+ } catch (e) {
169
+ return { ok: false, error: String((e && e.message) || e) }
170
+ }
171
+ },
172
+
173
+ highlight: function (id) {
174
+ var rec = id == null ? null : records.get(id)
175
+ var node = rec && rec.node
176
+ if (!node || !node.getBoundingClientRect || !node.isConnected) {
177
+ if (overlay) overlay.style.display = 'none'
178
+ return false
179
+ }
180
+ if (!overlay) {
181
+ overlay = document.createElement('div')
182
+ overlay.setAttribute('data-tylix-devtools', '')
183
+ overlay.style.cssText =
184
+ 'position:fixed;pointer-events:none;z-index:2147483646;background:rgba(16,185,129,.15);' +
185
+ 'border:2px solid #10b981;border-radius:4px;transition:all .08s ease;font:11px/1.6 ui-monospace,monospace'
186
+ var label = document.createElement('span')
187
+ label.style.cssText = 'position:absolute;top:-20px;left:-2px;background:#10b981;color:#022c22;padding:0 6px;border-radius:3px;white-space:nowrap'
188
+ overlay.appendChild(label)
189
+ document.documentElement.appendChild(overlay)
190
+ }
191
+ var r = node.getBoundingClientRect()
192
+ overlay.style.display = ''
193
+ overlay.style.left = r.left + 'px'
194
+ overlay.style.top = r.top + 'px'
195
+ overlay.style.width = r.width + 'px'
196
+ overlay.style.height = r.height + 'px'
197
+ overlay.firstChild.textContent = '<' + rec.name + '> ' + Math.round(r.width) + '×' + Math.round(r.height)
198
+ node.scrollIntoView({ block: 'nearest' })
199
+ return true
200
+ },
201
+
202
+ // Console helper: the live instances named `name`.
203
+ find: function (name) {
204
+ var out = []
205
+ records.forEach(function (rec) {
206
+ if (rec.name === name) out.push(rec.instance)
207
+ })
208
+ capabilities.forEach(function (rec) {
209
+ if (rec.name === name) out.push(rec.instance)
210
+ })
211
+ return out
212
+ },
213
+ }
214
+
215
+ function bump() {
216
+ hook.version++
217
+ }
218
+
219
+ function lookup(id) {
220
+ if (typeof id === 'string' && id.indexOf('cap:') === 0) return capabilities.get(id.slice(4)) || null
221
+ return records.get(id) || null
222
+ }
223
+
224
+ // Watching starts the first time a snapshot is asked for, so a page
225
+ // that nobody inspects never pays for it.
226
+ function startWatching() {
227
+ if (watching || !runtime) return
228
+ watching = true
229
+ records.forEach(watch)
230
+ capabilities.forEach(watch)
231
+ }
232
+
233
+ // Re-reads everything the instance holds (deeply, so nested edits
234
+ // count) inside an effect; any change bumps the version.
235
+ function watch(rec) {
236
+ if (!runtime || rec.watcher) return
237
+ var first = true
238
+ rec.watcher = runtime.untracked(function () {
239
+ return runtime.effect(function () {
240
+ try {
241
+ touch(rec.instance.__state || rec.instance, 0)
242
+ if (rec.instance.__propOverrides) touch(rec.instance.__propOverrides, 0)
243
+ } catch (e) {}
244
+ if (!first) bump()
245
+ first = false
246
+ })
247
+ })
248
+ }
249
+
250
+ function touch(value, depth) {
251
+ if (value === null || typeof value !== 'object' || depth > 6) return
252
+ if (typeof Node !== 'undefined' && value instanceof Node) return
253
+ if (value instanceof Map || value instanceof Set) {
254
+ value.forEach(function (v) {
255
+ touch(v, depth + 1)
256
+ })
257
+ return
258
+ }
259
+ for (var k in value) touch(value[k], depth + 1)
260
+ }
261
+
262
+ // Unmounted components (their node left the document) and the
263
+ // loading page, once the real page is up, are dropped.
264
+ function prune() {
265
+ records.forEach(function (rec, id) {
266
+ var gone =
267
+ (rec.kind === 'component' && rec.node && !rec.node.isConnected) ||
268
+ (rec.kind === 'loading' && (!rec.node || !rec.node.isConnected))
269
+ if (gone) {
270
+ if (rec.watcher) rec.watcher.active = false
271
+ records.delete(id)
272
+ }
273
+ })
274
+ }
275
+
276
+ // The closest live instance whose node contains this one's.
277
+ function parentOf(rec, live) {
278
+ if (rec.kind === 'page' || rec.kind === 'layout') return null
279
+ var best = null
280
+ if (rec.node) {
281
+ for (var i = 0; i < live.length; i++) {
282
+ var other = live[i]
283
+ if (other === rec || !other.node || other.node === rec.node) continue
284
+ if (other.node.contains && other.node.contains(rec.node)) {
285
+ if (!best || best.node.contains(other.node)) best = other
286
+ }
287
+ }
288
+ }
289
+ if (best) return best.id
290
+ // Not inside another component: under the page.
291
+ for (var j = 0; j < live.length; j++) if (live[j].kind === 'page') return live[j].id
292
+ return null
293
+ }
294
+
295
+ function keysOf(obj) {
296
+ try {
297
+ return Object.keys(runtime && runtime.toRaw ? runtime.toRaw(obj) : obj)
298
+ } catch (e) {
299
+ return []
300
+ }
301
+ }
302
+
303
+ function safeGet(obj, key) {
304
+ try {
305
+ return { value: obj[key] }
306
+ } catch (e) {
307
+ return { error: String((e && e.message) || e) }
308
+ }
309
+ }
310
+
311
+ function field(inst, key, editable) {
312
+ var got = safeGet(inst, key)
313
+ var f = { key: key, editable: editable }
314
+ if ('error' in got) {
315
+ f.preview = '⚠ ' + got.error
316
+ f.editable = false
317
+ } else {
318
+ f.preview = preview(got.value, 4)
319
+ f.json = toJson(got.value)
320
+ if (f.json === undefined) f.editable = false
321
+ }
322
+ return f
323
+ }
324
+
325
+ function toJson(value) {
326
+ try {
327
+ var seen = new WeakSet()
328
+ return JSON.stringify(value, function (k, v) {
329
+ if (typeof v === 'function') return undefined
330
+ if (v && typeof v === 'object') {
331
+ if (seen.has(v)) return '[Circular]'
332
+ seen.add(v)
333
+ }
334
+ return v
335
+ }, 2)
336
+ } catch (e) {
337
+ return undefined
338
+ }
339
+ }
340
+
341
+ // A JSON-safe, size-limited picture of a value for display.
342
+ function preview(value, depth) {
343
+ if (value === undefined) return { t: 'undefined' }
344
+ if (value === null) return { t: 'null' }
345
+ var type = typeof value
346
+ if (type === 'string') return { t: 'string', v: value.length > 500 ? value.slice(0, 500) + '…' : value }
347
+ if (type === 'number' || type === 'boolean') return { t: type, v: value }
348
+ if (type === 'bigint') return { t: 'bigint', v: String(value) }
349
+ if (type === 'function') return { t: 'function', v: value.name || 'anonymous' }
350
+ if (type === 'symbol') return { t: 'symbol', v: String(value) }
351
+ if (value instanceof Date) return { t: 'date', v: isNaN(value) ? 'Invalid Date' : value.toISOString() }
352
+ if (typeof Node !== 'undefined' && value instanceof Node) return { t: 'node', v: value.nodeName.toLowerCase() }
353
+ if (value instanceof Promise) return { t: 'promise' }
354
+ if (depth <= 0) return { t: Array.isArray(value) ? 'array' : 'object', n: sizeOf(value), more: true }
355
+ if (Array.isArray(value)) {
356
+ return { t: 'array', n: value.length, items: value.slice(0, 100).map(function (v) { return preview(v, depth - 1) }) }
357
+ }
358
+ if (value instanceof Map) {
359
+ var entries = []
360
+ value.forEach(function (v, k) {
361
+ if (entries.length < 100) entries.push([String(k), preview(v, depth - 1)])
362
+ })
363
+ return { t: 'map', n: value.size, entries: entries }
364
+ }
365
+ if (value instanceof Set) {
366
+ var items = []
367
+ value.forEach(function (v) {
368
+ if (items.length < 100) items.push(preview(v, depth - 1))
369
+ })
370
+ return { t: 'set', n: value.size, items: items }
371
+ }
372
+ var keys = Object.keys(value)
373
+ return {
374
+ t: 'object',
375
+ n: keys.length,
376
+ entries: keys.slice(0, 100).map(function (k) { return [k, preview(safeGet(value, k).value, depth - 1)] }),
377
+ }
378
+ }
379
+
380
+ function sizeOf(v) {
381
+ try {
382
+ return Array.isArray(v) ? v.length : Object.keys(v).length
383
+ } catch (e) {
384
+ return 0
385
+ }
386
+ }
387
+
388
+ Object.defineProperty(window, '__TYLIX_DEVTOOLS_HOOK__', { value: hook, configurable: true })
389
+ })()
@@ -43,9 +43,9 @@ export function buildVirtualPageTs(pageNode, className, templateNodes = null) {
43
43
  const lines = []
44
44
  const lineMap = []
45
45
  const sink = {
46
- pushLine(text, originalLine) {
46
+ pushLine(text, originalLine, section = 'script') {
47
47
  if (originalLine != null) {
48
- lineMap.push({ virtualLine: lines.length + 1, originalLine })
48
+ lineMap.push({ virtualLine: lines.length + 1, originalLine, section })
49
49
  }
50
50
  lines.push(text)
51
51
  },
@@ -118,7 +118,11 @@ export function buildVirtualPageTs(pageNode, className, templateNodes = null) {
118
118
  sink.pushLine(``, null)
119
119
  // async so `await` inside event handlers typechecks
120
120
  sink.pushLine(` async __render() {`, null)
121
- emitChecks(checks, sink, ' ')
121
+ // Template check lines count from the template section's start.
122
+ const templateSink = {
123
+ pushLine: (text, line) => sink.pushLine(text, line, 'template'),
124
+ }
125
+ emitChecks(checks, templateSink, ' ')
122
126
  sink.pushLine(` }`, null)
123
127
  }
124
128
  }
@@ -134,6 +138,17 @@ export function buildVirtualPageTs(pageNode, className, templateNodes = null) {
134
138
  return { source: lines.join('\n') + '\n', lineMap }
135
139
  }
136
140
 
141
+ // Like mapVirtualLineToSource, but also says which section the line
142
+ // counts from: { line, section: 'script' | 'template' }.
143
+ export function mapVirtualLine(lineMap, virtualLine) {
144
+ let best = lineMap[0] ?? { originalLine: 1, section: 'script' }
145
+ for (const entry of lineMap) {
146
+ if (entry.virtualLine <= virtualLine) best = entry
147
+ else break
148
+ }
149
+ return { line: best.originalLine, section: best.section ?? 'script' }
150
+ }
151
+
137
152
  export function mapVirtualLineToSource(lineMap, virtualLine) {
138
153
  let best = lineMap[0]?.originalLine ?? 1
139
154
  for (const entry of lineMap) {
@@ -7,6 +7,25 @@ const GLOBALS_FILE = fileURLToPath(
7
7
  new URL('./tylix-globals.d.ts', import.meta.url),
8
8
  )
9
9
 
10
+ // lib.*.d.ts and the Tylix globals almost never change while a process runs,
11
+ // and parsing them is most of a check's cost, so each one is parsed
12
+ // once. Keyed by file, target and modification time (the globals file
13
+ // can change under `tylix dev` with a hot-reloaded compiler).
14
+ const libCache = new Map()
15
+
16
+ function cachedLibFile(fileName, languageVersion, load) {
17
+ let mtime = 0
18
+ try {
19
+ mtime = ts.sys.getModifiedTime?.(fileName)?.getTime() ?? 0
20
+ } catch {}
21
+ const key = `${fileName}\0${JSON.stringify(languageVersion)}`
22
+ const hit = libCache.get(key)
23
+ if (hit && hit.mtime === mtime) return hit.file
24
+ const file = load()
25
+ if (file) libCache.set(key, { file, mtime })
26
+ return file
27
+ }
28
+
10
29
  export function typecheckSource(
11
30
  virtualSource,
12
31
  apiHelpersSource = '',
@@ -24,6 +43,11 @@ export function typecheckSource(
24
43
  const host = ts.createCompilerHost(options)
25
44
  const originalGetSourceFile = host.getSourceFile
26
45
  host.getSourceFile = (fileName, languageVersion, ...rest) => {
46
+ if (fileName !== VIRTUAL_FILE_NAME && fileName !== API_HELPERS_VIRTUAL_FILE_NAME) {
47
+ return cachedLibFile(fileName, languageVersion, () =>
48
+ originalGetSourceFile(fileName, languageVersion, ...rest),
49
+ )
50
+ }
27
51
  if (fileName === VIRTUAL_FILE_NAME) {
28
52
  return ts.createSourceFile(fileName, virtualSource, languageVersion, true)
29
53
  }
@@ -194,7 +194,7 @@ export function typedTemplateExpr(node, scope) {
194
194
  }
195
195
 
196
196
  // Any on<event> attribute is an event listener (see generateTemplate).
197
- const EVENT_ATTR_RE = /^on([a-z]+)$/i
197
+ const EVENT_ATTR_RE = /^on([a-z]+)(?:\.[a-z0-9]+)*$/i
198
198
 
199
199
  // [event interface, element type of `event.target`] per DOM event
200
200
  // name. Anything not listed falls back to a plain Event on a generic
@@ -312,6 +312,23 @@ export function collectTemplateChecks(nodes, scope, out) {
312
312
  if (node.elseChildren) {
313
313
  collectTemplateChecks(node.elseChildren, scope, out)
314
314
  }
315
+ } else if (node.type === 'RawHtml') {
316
+ out.push({ kind: 'check', expr: typedTemplateExpr(node.expression, scope), line: node.line, eventType: null, eventBase: null })
317
+ } else if (node.type === 'Await') {
318
+ out.push({ kind: 'check', expr: typedTemplateExpr(node.promise, scope), line: node.line, eventType: null, eventBase: null })
319
+ if (node.pending) collectTemplateChecks(node.pending, scope, out)
320
+ // then/catch values are bound like an each item (typed any), so
321
+ // the checker has a real declaration for the name.
322
+ for (const [name, children] of [[node.thenName, node.thenChildren], [node.catchName, node.catchChildren]]) {
323
+ if (!children) continue
324
+ if (!name) {
325
+ collectTemplateChecks(children, scope, out)
326
+ continue
327
+ }
328
+ const inner = []
329
+ collectTemplateChecks(children, new Set([...scope, ...paramNames([name])]), inner)
330
+ out.push({ kind: 'each', itemName: name, indexName: null, iterableExpr: '[]', line: node.line, children: inner })
331
+ }
315
332
  } else if (node.type === 'Element') {
316
333
  for (const attr of node.attributes) {
317
334
  if (!attr.dynamic) continue
@@ -5,7 +5,7 @@ import { Parser } from './parser/Parser.js'
5
5
  import { normalizeLanguageOptions } from './parser/languageOptions.js'
6
6
  import {
7
7
  buildVirtualPageTs,
8
- mapVirtualLineToSource,
8
+ mapVirtualLine,
9
9
  } from './typecheck/buildVirtualTs.js'
10
10
  import { typecheckSource } from './typecheck/typecheckVirtualFile.js'
11
11
  import { substituteCapabilityRefs } from './ast/substituteCapabilityRefs.js'
@@ -45,7 +45,8 @@ export function typecheckPage(
45
45
  }
46
46
  const language = normalizeLanguageOptions(languageOption ?? {})
47
47
 
48
- const { pageName, script, template, scriptStartLine } = parsePageFile(source)
48
+ const { pageName, script, template, scriptStartLine, templateStartLine } =
49
+ parsePageFile(source)
49
50
 
50
51
  const pageNode = substituteCapabilityRefs(
51
52
  script.trim().length > 0
@@ -64,7 +65,8 @@ export function typecheckPage(
64
65
  const diagnostics = typecheckSource(virtualSource, apiHelpersSource)
65
66
 
66
67
  return diagnostics.map((d) => {
67
- const scriptLine = mapVirtualLineToSource(lineMap, d.virtualLine)
68
- return { message: d.message, line: scriptLine + scriptStartLine - 1 }
68
+ const { line, section } = mapVirtualLine(lineMap, d.virtualLine)
69
+ const startLine = section === 'template' ? templateStartLine : scriptStartLine
70
+ return { message: d.message, line: line + startLine - 1, section }
69
71
  })
70
72
  }