@tylix/compiler 0.3.5 → 0.3.7

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.
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "@tylix/compiler",
3
- "version": "0.3.5",
3
+ "version": "0.3.7",
4
4
  "type": "module",
5
- "keywords": [
5
+ "keywords": [
6
6
  "tylix",
7
7
  "compiler",
8
8
  "ui"
@@ -17,4 +17,4 @@
17
17
  "devDependencies": {
18
18
  "jsdom": "^24.0.0"
19
19
  }
20
- }
20
+ }
package/src/ast/nodes.js CHANGED
@@ -4,13 +4,46 @@
4
4
  * later, the Analyzer) can switch on it without instanceof checks.
5
5
  */
6
6
  export function PageNode({
7
+ title = null,
8
+ layout = null,
9
+ needs = [],
7
10
  props = [],
8
11
  state = [],
12
+ uses = [],
13
+ prefetch = [],
14
+ background = [],
15
+ permissions = [],
16
+ meta = [],
9
17
  computed = [],
10
18
  actions = [],
11
19
  onMount = null,
12
20
  }) {
13
- return { type: 'Page', props, state, computed, actions, onMount }
21
+ return {
22
+ type: 'Page',
23
+ title,
24
+ layout,
25
+ needs,
26
+ props,
27
+ state,
28
+ uses,
29
+ prefetch,
30
+ background,
31
+ permissions,
32
+ meta,
33
+ computed,
34
+ actions,
35
+ onMount,
36
+ }
37
+ }
38
+
39
+ export function CapabilityRefNode(capability, member, args = null) {
40
+ // args === null means it's a bare reference (needs/uses entries: `Auth`)
41
+ // args !== null (possibly []) means it's a call (prefetch/background: `Posts.latest`, `Posts.search("x")`)
42
+ return { type: 'CapabilityRef', capability, member, args }
43
+ }
44
+
45
+ export function MetaEntryNode(key, value) {
46
+ return { type: 'MetaEntry', key, value }
14
47
  }
15
48
 
16
49
  export function PropNode(name, propType, optional = false) {
@@ -0,0 +1,162 @@
1
+ import { Identifier, MemberExpr } from './nodes.js'
2
+
3
+ function rewriteExpr(node, capabilityNames) {
4
+ if (node == null) return node
5
+ switch (node.type) {
6
+ case 'Identifier':
7
+ return capabilityNames.has(node.name)
8
+ ? MemberExpr(Identifier('this'), node.name)
9
+ : node
10
+ case 'MemberExpression':
11
+ return {
12
+ ...node,
13
+ object: rewriteExpr(node.object, capabilityNames),
14
+ property: node.computed
15
+ ? rewriteExpr(node.property, capabilityNames)
16
+ : node.property,
17
+ }
18
+ case 'CallExpression':
19
+ return {
20
+ ...node,
21
+ callee: rewriteExpr(node.callee, capabilityNames),
22
+ args: node.args.map((a) => rewriteExpr(a, capabilityNames)),
23
+ }
24
+ case 'AssignmentExpression':
25
+ return {
26
+ ...node,
27
+ target: rewriteExpr(node.target, capabilityNames),
28
+ value: rewriteExpr(node.value, capabilityNames),
29
+ }
30
+ case 'BinaryExpression':
31
+ return {
32
+ ...node,
33
+ left: rewriteExpr(node.left, capabilityNames),
34
+ right: rewriteExpr(node.right, capabilityNames),
35
+ }
36
+ case 'UnaryExpression':
37
+ return { ...node, argument: rewriteExpr(node.argument, capabilityNames) }
38
+ case 'AwaitExpression':
39
+ return { ...node, argument: rewriteExpr(node.argument, capabilityNames) }
40
+ case 'TernaryExpression':
41
+ return {
42
+ ...node,
43
+ condition: rewriteExpr(node.condition, capabilityNames),
44
+ consequent: rewriteExpr(node.consequent, capabilityNames),
45
+ alternate: rewriteExpr(node.alternate, capabilityNames),
46
+ }
47
+ case 'NullishCoalescingExpression':
48
+ return {
49
+ ...node,
50
+ left: rewriteExpr(node.left, capabilityNames),
51
+ right: rewriteExpr(node.right, capabilityNames),
52
+ }
53
+ case 'ArrowFunctionExpression':
54
+ return { ...node, body: rewriteExpr(node.body, capabilityNames) }
55
+ case 'ArrayExpression':
56
+ return {
57
+ ...node,
58
+ elements: node.elements.map((e) => rewriteExpr(e, capabilityNames)),
59
+ }
60
+ case 'ObjectExpression':
61
+ return {
62
+ ...node,
63
+ properties: node.properties.map((p) => ({
64
+ ...p,
65
+ value: rewriteExpr(p.value, capabilityNames),
66
+ })),
67
+ }
68
+ default:
69
+ return node
70
+ }
71
+ }
72
+
73
+ function rewriteStatement(stmt, capabilityNames) {
74
+ switch (stmt.type) {
75
+ case 'ExpressionStatement':
76
+ return {
77
+ ...stmt,
78
+ expression: rewriteExpr(stmt.expression, capabilityNames),
79
+ }
80
+ case 'ReturnStatement':
81
+ return { ...stmt, argument: rewriteExpr(stmt.argument, capabilityNames) }
82
+ case 'VariableDeclaration':
83
+ return { ...stmt, init: rewriteExpr(stmt.init, capabilityNames) }
84
+ case 'IfStatement':
85
+ return {
86
+ ...stmt,
87
+ condition: rewriteExpr(stmt.condition, capabilityNames),
88
+ consequent: stmt.consequent.map((s) =>
89
+ rewriteStatement(s, capabilityNames),
90
+ ),
91
+ alternate: stmt.alternate
92
+ ? stmt.alternate.map((s) => rewriteStatement(s, capabilityNames))
93
+ : null,
94
+ }
95
+ case 'ForInStatement':
96
+ return {
97
+ ...stmt,
98
+ iterable: rewriteExpr(stmt.iterable, capabilityNames),
99
+ body: stmt.body.map((s) => rewriteStatement(s, capabilityNames)),
100
+ }
101
+ case 'ForRangeStatement':
102
+ return {
103
+ ...stmt,
104
+ start: rewriteExpr(stmt.start, capabilityNames),
105
+ end: rewriteExpr(stmt.end, capabilityNames),
106
+ body: stmt.body.map((s) => rewriteStatement(s, capabilityNames)),
107
+ }
108
+ case 'RepeatStatement':
109
+ return {
110
+ ...stmt,
111
+ count: rewriteExpr(stmt.count, capabilityNames),
112
+ body: stmt.body.map((s) => rewriteStatement(s, capabilityNames)),
113
+ }
114
+ case 'TryStatement':
115
+ return {
116
+ ...stmt,
117
+ tryBlock: stmt.tryBlock.map((s) =>
118
+ rewriteStatement(s, capabilityNames),
119
+ ),
120
+ catchBlock: stmt.catchBlock
121
+ ? stmt.catchBlock.map((s) => rewriteStatement(s, capabilityNames))
122
+ : null,
123
+ finallyBlock: stmt.finallyBlock
124
+ ? stmt.finallyBlock.map((s) => rewriteStatement(s, capabilityNames))
125
+ : null,
126
+ }
127
+ case 'BreakStatement':
128
+ case 'ContinueStatement':
129
+ return stmt
130
+ default:
131
+ return stmt
132
+ }
133
+ }
134
+
135
+ export function substituteCapabilityRefs(pageNode) {
136
+ const capabilityNames = new Set([
137
+ ...(pageNode.uses ?? []).map((u) => u.name),
138
+ ...(pageNode.needs ?? []).map((n) => n.name),
139
+ ...(pageNode.background ?? []).map((b) => b.name),
140
+ ])
141
+ if (capabilityNames.size === 0) return pageNode
142
+
143
+ return {
144
+ ...pageNode,
145
+ computed: (pageNode.computed ?? []).map((c) => ({
146
+ ...c,
147
+ body: c.body.map((s) => rewriteStatement(s, capabilityNames)),
148
+ })),
149
+ actions: (pageNode.actions ?? []).map((a) => ({
150
+ ...a,
151
+ body: a.body.map((s) => rewriteStatement(s, capabilityNames)),
152
+ })),
153
+ onMount: pageNode.onMount
154
+ ? {
155
+ ...pageNode.onMount,
156
+ body: pageNode.onMount.body.map((s) =>
157
+ rewriteStatement(s, capabilityNames),
158
+ ),
159
+ }
160
+ : null,
161
+ }
162
+ }
@@ -0,0 +1,49 @@
1
+ import { generateExpression } from './generateExpression.js'
2
+ import { generateStatement } from './generateStatement.js'
3
+ import { generateMethod } from './generateMethod.js'
4
+
5
+ /**
6
+ * Compiles a capability AST (see Parser.parseCapability) into a
7
+ * defineCapability(name, def) call.
8
+ *
9
+ * Unlike generatePage's class output, there's no reactive() wrapping
10
+ * here and no accessor pairs -- resolveCapability (runtime/capability.js)
11
+ * handles wrapping entry.def.state in reactive() itself on first
12
+ * resolution, so state is emitted as a plain object literal, and
13
+ * actions/init are emitted as plain (unbound) methods that
14
+ * resolveCapability binds to the reactive instance at resolve time.
15
+ *
16
+ * action entries reuse generateMethod as-is -- its `name(params) {
17
+ * body }` output is valid both as a class method (generatePage's use)
18
+ * and as ES6 object-method shorthand (this file's use), so there's no
19
+ * need for a second, parallel method-body codegen path here.
20
+ */
21
+ export function generateCapability(capabilityNode) {
22
+ const stateProps = capabilityNode.state
23
+ .map((s) => ` ${s.name}: ${generateExpression(s.value)},`)
24
+ .join('\n')
25
+
26
+ const actionMethods = capabilityNode.actions
27
+ .map((a) => ` ${generateMethod(a)},`)
28
+ .join('\n')
29
+
30
+ const initMethod = capabilityNode.init
31
+ ? (() => {
32
+ const body = capabilityNode.init.body
33
+ .map((stmt) => ` ${generateStatement(stmt)}`)
34
+ .join('\n')
35
+ const asyncPrefix = capabilityNode.init.isAsync ? 'async ' : ''
36
+ return ` ${asyncPrefix}init() {\n${body}\n },`
37
+ })()
38
+ : ''
39
+
40
+ return `defineCapability(${JSON.stringify(capabilityNode.name)}, {
41
+ state: {
42
+ ${stateProps}
43
+ },
44
+ actions: {
45
+ ${actionMethods}
46
+ },
47
+ ${initMethod}
48
+ });`
49
+ }
@@ -24,7 +24,9 @@ test("generates a zero-parameter method with a single return statement", () => {
24
24
  });
25
25
 
26
26
  test("generates a method with parameters", () => {
27
- const node = MethodNode("setCount", ["value"], [
27
+ // Params are { name, typeAnnotation } objects, the same shape the
28
+ // parser produces.
29
+ const node = MethodNode("setCount", [{ name: "value", typeAnnotation: null }], [
28
30
  ExpressionStatement(AssignmentExpr(MemberExpr(Identifier("this"), "count"), Identifier("value"))),
29
31
  ]);
30
32
 
@@ -76,4 +78,4 @@ test("the generated method source is valid, executable JavaScript", () => {
76
78
  instance.count = 5;
77
79
  instance.increment();
78
80
  assert.equal(instance.count, 6);
79
- });
81
+ });
@@ -7,12 +7,17 @@ import { generateExpression } from './generateExpression.js'
7
7
  * `this.count` reads/writes go through the reactive() proxy and
8
8
  * correctly trigger dependent effects (template re-renders, computed
9
9
  * re-evaluation) without any special-casing in the method codegen.
10
+ * - uses entries become read-only getters that resolve a named
11
+ * capability from the shared runtime registry -- unlike state,
12
+ * there's no matching setter, since capabilities are singletons
13
+ * owned by the registry, not per-page instance data.
10
14
  * - computed entries become plain getters (their body already contains
11
15
  * a `return` statement from the parser).
12
16
  * - action entries become plain instance methods.
13
17
  *
14
- * The generated class expects `reactive` to be in scope where the
15
- * module is evaluated (imported from @tylix/compiler's runtime).
18
+ * The generated class expects `reactive` and `resolveCapability` to be
19
+ * in scope where the module is evaluated (imported from
20
+ * @tylix/compiler's runtime).
16
21
  */
17
22
  export function generatePage(pageNode, className = 'Page', target = 'client') {
18
23
  const propAssignments = pageNode.props
@@ -34,6 +39,36 @@ export function generatePage(pageNode, className = 'Page', target = 'client') {
34
39
  )
35
40
  .join('\n\n')
36
41
 
42
+ // pageNode.uses may be absent on older/pre-capability ASTs (e.g.
43
+ // anything compiled before this field existed), so default to []
44
+ // rather than assuming every caller has been updated.
45
+ // pageNode.uses/needs/background may each name capabilities the page
46
+ // reads from directly (Auth.user, Theme.mode, etc.) -- substituteCapabilityRefs
47
+ // already treats all three as the same "capability name" pool when
48
+ // rewriting bare references to `this.<Name>`, so the getters generated
49
+ // here must cover the same pool, not just `uses` alone, or a
50
+ // needs-only or background-only capability resolves to undefined at
51
+ // runtime with no compile-time signal that anything's wrong.
52
+ const capabilityRefs = [
53
+ ...(pageNode.uses ?? []),
54
+ ...(pageNode.needs ?? []),
55
+ ...(pageNode.background ?? []),
56
+ ]
57
+ const seenCapabilities = new Set()
58
+ const uniqueCapabilityRefs = capabilityRefs.filter((c) => {
59
+ if (seenCapabilities.has(c.name)) return false
60
+ seenCapabilities.add(c.name)
61
+ return true
62
+ })
63
+
64
+ const usesAccessors = uniqueCapabilityRefs
65
+ .map(
66
+ (u) => ` get ${u.name}() {
67
+ return resolveCapability(${JSON.stringify(u.name)});
68
+ }`,
69
+ )
70
+ .join('\n\n')
71
+
37
72
  const computedGetters = pageNode.computed
38
73
  .map((c) => {
39
74
  const body = c.body
@@ -47,13 +82,44 @@ export function generatePage(pageNode, className = 'Page', target = 'client') {
47
82
  .map((a) => generateMethod(a))
48
83
  .join('\n\n')
49
84
 
85
+ const needsResolution = (pageNode.needs ?? [])
86
+ .map(
87
+ (n) => ` await resolveCapability(${JSON.stringify(n.name)}).ready();`,
88
+ )
89
+ .join('\n')
90
+
91
+ const prefetchResolution = (pageNode.prefetch ?? [])
92
+ .map((p) => {
93
+ const argsSrc = p.args
94
+ ? p.args.map((a) => generateExpression(a)).join(', ')
95
+ : ''
96
+ return ` await resolveCapability(${JSON.stringify(p.capability)}).${p.member}(${argsSrc});`
97
+ })
98
+ .join('\n')
99
+
100
+ const backgroundResolution = (pageNode.background ?? [])
101
+ .map((b) => ` resolveCapability(${JSON.stringify(b.name)});`) // fire-and-forget, no await
102
+ .join('\n')
103
+
104
+ const readyBody = [needsResolution, prefetchResolution]
105
+ .filter(Boolean)
106
+ .join('\n')
107
+
108
+ const readyMethod = readyBody ? ` async __ready() {\n${readyBody}\n }` : ''
109
+
50
110
  // onMount is only ever emitted into the class at all when
51
111
  // generating for the client bundle. Server-side (SSR) output never
52
112
  // contains the onMount call OR its method body -- there's no
53
113
  // runtime guard to rely on, because the code simply isn't there.
54
- const onMountCall =
55
- pageNode.onMount && target === 'client' ? ` this.__onMount();\n` : ''
56
-
114
+ //
115
+ // IMPORTANT: onMount is no longer invoked from inside the
116
+ // constructor. Pages that declare `needs` capabilities must have
117
+ // those capabilities' async init() fully resolved (via __ready())
118
+ // before onMount runs, or onMount's own logic (e.g. redirecting
119
+ // based on Auth.user) races against that resolution and reads
120
+ // stale/uninitialized capability state. The caller (renderPageDocument.js)
121
+ // is responsible for awaiting __ready() and then calling __onMount()
122
+ // explicitly, in that order.
57
123
  const onMountMethod =
58
124
  pageNode.onMount && target === 'client'
59
125
  ? (() => {
@@ -70,9 +136,9 @@ export function generatePage(pageNode, className = 'Page', target = 'client') {
70
136
  ${propAssignments ? propAssignments + '\n' : ''} this.__state = reactive({
71
137
  ${stateInit}
72
138
  });
73
- ${onMountCall} }
139
+ ${backgroundResolution ? backgroundResolution + '\n' : ''} }
74
140
 
75
- ${[stateAccessors, computedGetters, actionMethods, onMountMethod].filter(Boolean).join('\n\n')}
141
+ ${[stateAccessors, usesAccessors, computedGetters, actionMethods, readyMethod, onMountMethod].filter(Boolean).join('\n\n')}
76
142
  }`
77
143
  }
78
144
 
@@ -5,13 +5,26 @@ import { reactive } from "../runtime/reactive.js";
5
5
  import { Parser } from "../parser/Parser.js";
6
6
  import { Lexer } from "../lexer/Lexer.js";
7
7
 
8
- test("onMount runs automatically on construction", () => {
9
- const source = `state\ncount: 0\nonMount\nthis.count = 99`;
8
+ function buildPageClass(source) {
10
9
  const page = new Parser(new Lexer(source).tokenize()).parse();
11
10
  const classSource = generatePage(page, "Page");
12
- const Page = new Function("reactive", `return ${classSource}`)(reactive);
11
+ return new Function("reactive", `return ${classSource}`)(reactive);
12
+ }
13
+
14
+ // onMount is not invoked from the constructor: the host awaits
15
+ // __ready() (so capabilities are loaded) and then calls __onMount().
16
+ test("onMount does not run on construction", () => {
17
+ const Page = buildPageClass(`state\ncount: 0\nonMount\nthis.count = 99`);
18
+
19
+ const instance = new Page();
20
+ assert.equal(instance.count, 0);
21
+ });
22
+
23
+ test("onMount runs when the host calls __onMount()", () => {
24
+ const Page = buildPageClass(`state\ncount: 0\nonMount\nthis.count = 99`);
13
25
 
14
26
  const instance = new Page();
27
+ instance.__onMount();
15
28
  assert.equal(instance.count, 99);
16
29
  });
17
30
 
@@ -30,4 +43,4 @@ test("async onMount can await before setting state", async () => {
30
43
  const instance = new PageClass();
31
44
  await instance.__onMount();
32
45
  assert.equal(instance.data, 123);
33
- });
46
+ });
package/src/index.js CHANGED
@@ -19,3 +19,5 @@ export * from './typecheckPage.js'
19
19
  export * from './typecheck/transpileHelperSource.js'
20
20
  export * from './imports/extractImports.js'
21
21
  export * from './imports/resolvePackageComponents.js'
22
+ export * from './runtime/capability.js'
23
+ export * from './codegen/generateCapability.js'
@@ -356,6 +356,18 @@ export class Lexer {
356
356
  this.pos++
357
357
  }
358
358
  const text = this.source.slice(start, this.pos)
359
+
360
+ const unitMatch = /^(ms|s|m|h|d)/.exec(this.source.slice(this.pos))
361
+ if (
362
+ unitMatch &&
363
+ !/[A-Za-z0-9_$]/.test(this.source[this.pos + unitMatch[0].length] ?? '')
364
+ ) {
365
+ const unit = unitMatch[0]
366
+ this.pos += unit.length
367
+ this.pushToken(TokenType.DURATION, `${text}${unit}`)
368
+ return
369
+ }
370
+
359
371
  this.pushToken(TokenType.NUMBER, Number(text))
360
372
  }
361
373
 
@@ -8,7 +8,17 @@ export const TokenType = {
8
8
  ACTION: 'ACTION',
9
9
  TEMPLATE: 'TEMPLATE',
10
10
  PROPS: 'PROPS',
11
+ USES: 'USES',
12
+ CAPABILITY: 'CAPABILITY',
13
+ INIT: 'INIT',
11
14
  ONMOUNT: 'ONMOUNT',
15
+ NEEDS: 'NEEDS',
16
+ PREFETCH: 'PREFETCH',
17
+ BACKGROUND: 'BACKGROUND',
18
+ PERMISSIONS: 'PERMISSIONS',
19
+ META: 'META',
20
+ TITLE: 'TITLE',
21
+ DURATION: 'DURATION',
12
22
  NEW: 'NEW',
13
23
  TRY: 'TRY',
14
24
  CATCH: 'CATCH',
@@ -96,6 +106,17 @@ export const KEYWORDS = {
96
106
  action: TokenType.ACTION,
97
107
  template: TokenType.TEMPLATE,
98
108
  props: TokenType.PROPS,
109
+ uses: TokenType.USES,
110
+ capability: TokenType.CAPABILITY,
111
+ init: TokenType.INIT,
112
+ title: TokenType.TITLE,
113
+ layout: TokenType.LAYOUT,
114
+ needs: TokenType.NEEDS,
115
+ prefetch: TokenType.PREFETCH,
116
+ background: TokenType.BACKGROUND,
117
+ permissions: TokenType.PERMISSIONS,
118
+ meta: TokenType.META,
119
+ actions: TokenType.ACTION,
99
120
  onMount: TokenType.ONMOUNT,
100
121
  new: TokenType.NEW,
101
122
  return: TokenType.RETURN,