@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,125 @@
1
+ import { test } from 'node:test'
2
+ import assert from 'node:assert/strict'
3
+ import { JSDOM } from 'jsdom'
4
+ import { renderPageDocument } from './renderPageDocument.js'
5
+
6
+ function loadDocument(html) {
7
+ return new Promise((resolve) => {
8
+ const dom = new JSDOM(html, {
9
+ runScripts: 'dangerously',
10
+ resources: 'usable',
11
+ url: 'http://localhost',
12
+ })
13
+ dom.window.document.addEventListener('DOMContentLoaded', () => {
14
+ setTimeout(() => resolve(dom), 0)
15
+ })
16
+ })
17
+ }
18
+
19
+ test('renders a full HTML document from native Tylix syntax, mounted and interactive', async () => {
20
+ const source = `
21
+ page CounterPage
22
+
23
+ state
24
+ count: 0
25
+
26
+ action
27
+ increment() {
28
+ this.count = this.count + 1
29
+ }
30
+
31
+ template
32
+ <div>
33
+ <span>{{ count }}</span>
34
+ <button onclick="{{ increment }}">+1</button>
35
+ </div>
36
+ `
37
+
38
+ const html = renderPageDocument(source)
39
+ assert.match(html, /<title>CounterPage<\/title>/)
40
+
41
+ const dom = await loadDocument(html)
42
+ const { document } = dom.window
43
+
44
+ const span = document.querySelector('#app span')
45
+ const button = document.querySelector('#app button')
46
+
47
+ assert.equal(span.textContent, '0')
48
+ button.dispatchEvent(new dom.window.Event('click'))
49
+ assert.equal(span.textContent, '1')
50
+ })
51
+
52
+ test('passes route params through as props on the page instance', async () => {
53
+ const source = `
54
+ page PostDetail
55
+
56
+ props
57
+ id: string
58
+
59
+ template
60
+ <div>
61
+ <span>{{ id }}</span>
62
+ </div>
63
+ `
64
+
65
+ const html = renderPageDocument(source, {}, { props: { id: '42' } })
66
+ const dom = await loadDocument(html)
67
+ const span = dom.window.document.querySelector('#app span')
68
+
69
+ assert.equal(span.textContent, '42')
70
+ })
71
+
72
+ test('inlines the style section into the document head', async () => {
73
+ const source = `
74
+ page Home
75
+
76
+ template
77
+ <p>Hello</p>
78
+
79
+ style
80
+ p { color: red; }
81
+ `
82
+ const html = renderPageDocument(source)
83
+ assert.match(html, /<style>\s*p \{ color: red; \}\s*<\/style>/)
84
+ })
85
+
86
+ test('omits the style tag entirely when no style section is present', async () => {
87
+ const source = `page Home\n\ntemplate\n <p>Hello</p>`
88
+ const html = renderPageDocument(source)
89
+ assert.doesNotMatch(html, /<style>/)
90
+ })
91
+
92
+ test('supports a page with no script section at all', async () => {
93
+ const source = `page Static\n\ntemplate\n <p>Just static markup</p>`
94
+ const html = renderPageDocument(source)
95
+ const dom = await loadDocument(html)
96
+ assert.equal(
97
+ dom.window.document.querySelector('#app p').textContent,
98
+ 'Just static markup',
99
+ )
100
+ })
101
+
102
+ test('renders a page that nests a child component via <TagName />', async () => {
103
+ const badgeSource = `
104
+ <template>
105
+ <span class="badge">Verified</span>
106
+ </template>
107
+ `
108
+
109
+ const pageSource = `
110
+ page Profile
111
+
112
+ template
113
+ <div>
114
+ <h1>Ada Lovelace</h1>
115
+ <Badge />
116
+ </div>
117
+ `
118
+
119
+ const html = renderPageDocument(pageSource, { Badge: badgeSource })
120
+ const dom = await loadDocument(html)
121
+ const { document } = dom.window
122
+
123
+ assert.equal(document.querySelector('#app h1').textContent, 'Ada Lovelace')
124
+ assert.equal(document.querySelector('#app .badge').textContent, 'Verified')
125
+ })
@@ -0,0 +1,35 @@
1
+ let activeRequests = 0
2
+ let barEl = null
3
+
4
+ function ensureBar() {
5
+ if (barEl) return barEl
6
+ barEl = document.createElement('div')
7
+ barEl.id = 'tylix-loading-bar'
8
+ barEl.style.cssText =
9
+ 'position:fixed;top:0;left:0;height:3px;width:0%;background:#10b981;z-index:99999;transition:width 0.2s ease,opacity 0.3s ease;opacity:0;'
10
+ document.body.appendChild(barEl)
11
+ return barEl
12
+ }
13
+
14
+ export function __tylixRequestStart() {
15
+ activeRequests++
16
+ const bar = ensureBar()
17
+ bar.style.opacity = '1'
18
+ bar.style.width = '70%'
19
+ }
20
+
21
+ export function __tylixRequestEnd() {
22
+ activeRequests = Math.max(0, activeRequests - 1)
23
+ if (activeRequests === 0) {
24
+ const bar = ensureBar()
25
+ bar.style.width = '100%'
26
+ setTimeout(() => {
27
+ if (activeRequests === 0) {
28
+ bar.style.opacity = '0'
29
+ setTimeout(() => {
30
+ bar.style.width = '0%'
31
+ }, 300)
32
+ }
33
+ }, 150)
34
+ }
35
+ }
@@ -0,0 +1,59 @@
1
+ /**
2
+ * Minimal fine-grained reactivity core (Proxy get/set + dependency
3
+ * tracking), the same fundamental technique Vue 3 and Solid use to
4
+ * avoid virtual-DOM diffing entirely. An effect() records which
5
+ * reactive properties it read; reactive() re-runs exactly the effects
6
+ * that depend on a property when that property is written — nothing
7
+ * else re-renders.
8
+ */
9
+
10
+ let activeEffect = null;
11
+ const targetMap = new WeakMap();
12
+
13
+ export function reactive(target) {
14
+ return new Proxy(target, {
15
+ get(obj, key, receiver) {
16
+ track(obj, key);
17
+ return Reflect.get(obj, key, receiver);
18
+ },
19
+ set(obj, key, value, receiver) {
20
+ const changed = obj[key] !== value;
21
+ const result = Reflect.set(obj, key, value, receiver);
22
+ if (changed) trigger(obj, key);
23
+ return result;
24
+ },
25
+ });
26
+ }
27
+
28
+ function track(obj, key) {
29
+ if (!activeEffect) return;
30
+ let depsMap = targetMap.get(obj);
31
+ if (!depsMap) targetMap.set(obj, (depsMap = new Map()));
32
+ let dep = depsMap.get(key);
33
+ if (!dep) depsMap.set(key, (dep = new Set()));
34
+ dep.add(activeEffect);
35
+ }
36
+
37
+ function trigger(obj, key) {
38
+ const depsMap = targetMap.get(obj);
39
+ if (!depsMap) return;
40
+ const dep = depsMap.get(key);
41
+ if (!dep) return;
42
+ // Copy before iterating: an effect may re-track (add/remove itself)
43
+ // while running, which would corrupt the Set mid-iteration.
44
+ [...dep].forEach((fn) => fn());
45
+ }
46
+
47
+ export function effect(fn) {
48
+ const wrapped = () => {
49
+ const previousEffect = activeEffect;
50
+ activeEffect = wrapped;
51
+ try {
52
+ fn();
53
+ } finally {
54
+ activeEffect = previousEffect;
55
+ }
56
+ };
57
+ wrapped();
58
+ return wrapped;
59
+ }
@@ -0,0 +1,106 @@
1
+ import { test } from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { reactive, effect } from "./reactive.js";
4
+
5
+ test("reading a reactive property inside an effect tracks it", () => {
6
+ const state = reactive({ count: 0 });
7
+ let seen = null;
8
+
9
+ effect(() => {
10
+ seen = state.count;
11
+ });
12
+
13
+ assert.equal(seen, 0);
14
+ });
15
+
16
+ test("writing a tracked property re-runs the effect", () => {
17
+ const state = reactive({ count: 0 });
18
+ let runs = 0;
19
+
20
+ effect(() => {
21
+ state.count; // read to establish dependency
22
+ runs++;
23
+ });
24
+
25
+ assert.equal(runs, 1);
26
+ state.count = 1;
27
+ assert.equal(runs, 2);
28
+ state.count = 2;
29
+ assert.equal(runs, 3);
30
+ });
31
+
32
+ test("writing an untracked property does not re-run unrelated effects", () => {
33
+ const state = reactive({ count: 0, other: "x" });
34
+ let runs = 0;
35
+
36
+ effect(() => {
37
+ state.count;
38
+ runs++;
39
+ });
40
+
41
+ state.other = "y";
42
+ assert.equal(runs, 1, "effect should not re-run for a property it never read");
43
+ });
44
+
45
+ test("setting a property to the same value does not re-trigger", () => {
46
+ const state = reactive({ count: 5 });
47
+ let runs = 0;
48
+
49
+ effect(() => {
50
+ state.count;
51
+ runs++;
52
+ });
53
+
54
+ state.count = 5;
55
+ assert.equal(runs, 1);
56
+ });
57
+
58
+ test("multiple independent effects each track their own dependencies", () => {
59
+ const state = reactive({ a: 1, b: 2 });
60
+ let aRuns = 0;
61
+ let bRuns = 0;
62
+
63
+ effect(() => {
64
+ state.a;
65
+ aRuns++;
66
+ });
67
+ effect(() => {
68
+ state.b;
69
+ bRuns++;
70
+ });
71
+
72
+ state.a = 10;
73
+ assert.equal(aRuns, 2);
74
+ assert.equal(bRuns, 1);
75
+
76
+ state.b = 20;
77
+ assert.equal(aRuns, 2);
78
+ assert.equal(bRuns, 2);
79
+ });
80
+
81
+ test("an effect reading multiple properties re-runs when any of them change", () => {
82
+ const state = reactive({ first: "Ada", last: "Lovelace" });
83
+ const fullNames = [];
84
+
85
+ effect(() => {
86
+ fullNames.push(`${state.first} ${state.last}`);
87
+ });
88
+
89
+ state.first = "Grace";
90
+ state.last = "Hopper";
91
+
92
+ assert.deepEqual(fullNames, ["Ada Lovelace", "Grace Lovelace", "Grace Hopper"]);
93
+ });
94
+
95
+ test("computed-style derived effect updates when its source changes", () => {
96
+ const state = reactive({ count: 3 });
97
+ let doubled = null;
98
+
99
+ effect(() => {
100
+ doubled = state.count * 2;
101
+ });
102
+
103
+ assert.equal(doubled, 6);
104
+ state.count = 10;
105
+ assert.equal(doubled, 20);
106
+ });
@@ -0,0 +1,45 @@
1
+ export async function useApi(url, options = {}) {
2
+ const {
3
+ method = 'GET',
4
+ body,
5
+ headers = {},
6
+ credentials = 'include',
7
+ } = options
8
+
9
+ const finalHeaders = { ...headers }
10
+ let finalBody = body
11
+ if (body && typeof body === 'object' && !(body instanceof FormData)) {
12
+ finalHeaders['Content-Type'] =
13
+ finalHeaders['Content-Type'] || 'application/json'
14
+ finalBody = JSON.stringify(body)
15
+ }
16
+
17
+ __tylixRequestStart()
18
+ try {
19
+ const response = await fetch(url, {
20
+ method,
21
+ headers: finalHeaders,
22
+ body: finalBody,
23
+ credentials,
24
+ })
25
+ let data = null
26
+ try {
27
+ data = await response.json()
28
+ } catch {
29
+ /* empty body */
30
+ }
31
+ if (!response.ok) {
32
+ return {
33
+ ok: false,
34
+ status: response.status,
35
+ data,
36
+ error: (data && (data.error || data.message)) || 'Request failed',
37
+ }
38
+ }
39
+ return { ok: true, status: response.status, data, error: null }
40
+ } catch (err) {
41
+ return { ok: false, status: 0, data: null, error: err.message }
42
+ } finally {
43
+ __tylixRequestEnd()
44
+ }
45
+ }
@@ -0,0 +1,38 @@
1
+ export function useChannel(name) {
2
+ const port = window.__TYLIX_CHANNELS_PORT__ ?? 6001
3
+ const socket = new WebSocket(
4
+ `ws://${window.location.hostname}:${port}/${name}`,
5
+ )
6
+
7
+ const listeners = []
8
+
9
+ socket.addEventListener('message', (event) => {
10
+ let data
11
+ try {
12
+ data = JSON.parse(event.data)
13
+ } catch {
14
+ return
15
+ }
16
+ for (const fn of listeners) fn(data)
17
+ })
18
+
19
+ return {
20
+ send(data) {
21
+ if (socket.readyState === socket.OPEN) {
22
+ socket.send(JSON.stringify(data))
23
+ } else {
24
+ socket.addEventListener(
25
+ 'open',
26
+ () => socket.send(JSON.stringify(data)),
27
+ { once: true },
28
+ )
29
+ }
30
+ },
31
+ onMessage(fn) {
32
+ listeners.push(fn)
33
+ },
34
+ close() {
35
+ socket.close()
36
+ },
37
+ }
38
+ }