@tylix/compiler 0.6.0 → 1.0.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.
- package/LICENSE +21 -0
- package/package.json +30 -2
- package/src/ast/nodes.js +145 -23
- package/src/ast/substituteCapabilityRefs.js +52 -5
- package/src/codegen/emitStatementLines.js +60 -10
- package/src/codegen/generateExpression.js +294 -35
- package/src/codegen/generateStatement.js +125 -20
- package/src/codegen/generateTemplate.js +107 -96
- package/src/codegen/generateTemplateExpression.js +63 -10
- package/src/codegen/jsGlobals.js +62 -2
- package/src/compileComponent.js +37 -6
- package/src/lexer/Lexer.js +128 -28
- package/src/parser/Parser.js +1840 -500
- package/src/parser/parseExpressionString.js +5 -0
- package/src/parser/parseTemplate.js +153 -41
- package/src/renderPageDocument.js +71 -8
- package/src/runtime/capability.js +8 -1
- package/src/runtime/reactive.js +289 -61
- package/src/runtime/useApi.js +74 -13
- package/src/runtime/useChannel.js +27 -6
- package/src/typecheck/buildVirtualTs.js +11 -1
- package/src/typecheck/tylix-globals.d.ts +23 -4
- package/src/typecheck/typedTemplateExpr.js +90 -27
- package/src/codegen/generateExpression.array.test.js +0 -13
- package/src/codegen/generateExpression.callexpr.test.js +0 -19
- package/src/codegen/generateExpression.test.js +0 -59
- package/src/codegen/generateMethod.asyncawait.test.js +0 -37
- package/src/codegen/generateMethod.ifstatement.test.js +0 -20
- package/src/codegen/generateMethod.test.js +0 -81
- package/src/codegen/generatePage.onmount.test.js +0 -46
- package/src/codegen/generatePage.test.js +0 -138
- package/src/codegen/generateStatement.test.js +0 -31
- package/src/codegen/generateTemplate.ifeach.test.js +0 -138
- package/src/codegen/generateTemplate.test.js +0 -149
- package/src/codegen/generateTemplateExpression.test.js +0 -34
- package/src/compileComponent.test.js +0 -121
- package/src/lexer/Lexer.test.js +0 -151
- package/src/parser/Parser.array.test.js +0 -37
- package/src/parser/Parser.asyncawait.test.js +0 -33
- package/src/parser/Parser.ifstatement.test.js +0 -20
- package/src/parser/Parser.onmount.test.js +0 -18
- package/src/parser/Parser.test.js +0 -315
- package/src/parser/parseComponent.test.js +0 -53
- package/src/parser/parsePageFile.test.js +0 -101
- package/src/parser/parseTemplate.ifeach.test.js +0 -33
- package/src/parser/parseTemplate.pre.test.js +0 -39
- package/src/parser/parseTemplate.test.js +0 -112
- package/src/renderPageDocument.test.js +0 -125
- package/src/runtime/reactive.test.js +0 -106
- package/test/dashboard-syntax.test.js +0 -116
package/src/runtime/reactive.js
CHANGED
|
@@ -6,16 +6,26 @@
|
|
|
6
6
|
* that depend on a property when that property is written -- nothing
|
|
7
7
|
* else re-renders.
|
|
8
8
|
*
|
|
9
|
-
* What is wrapped: plain objects
|
|
10
|
-
* memoized (so repeated reads return the same Proxy
|
|
11
|
-
*
|
|
12
|
-
* alone: their methods need the real object as `this` and break
|
|
13
|
-
* called through a Proxy.
|
|
9
|
+
* What is wrapped: plain objects, arrays, Map, Set and Date, lazily
|
|
10
|
+
* on read and memoized (so repeated reads return the same Proxy
|
|
11
|
+
* identity). Promise, RegExp, DOM nodes and other class instances are
|
|
12
|
+
* left alone: their methods need the real object as `this` and break
|
|
13
|
+
* when called through a Proxy.
|
|
14
14
|
*
|
|
15
|
-
*
|
|
16
|
-
*
|
|
17
|
-
*
|
|
18
|
-
*
|
|
15
|
+
* Map and Set: get/has/set/add/delete/clear, size, forEach and
|
|
16
|
+
* iteration are instrumented. Reads of a key re-run when that key is
|
|
17
|
+
* added, changed or removed; size and iteration re-run when entries
|
|
18
|
+
* are added, removed (or, for a Map, changed).
|
|
19
|
+
*
|
|
20
|
+
* Date: every read method (getDate, toLocaleDateString, ...) is
|
|
21
|
+
* tracked, and every setter (setDate, setHours, ...) re-runs readers
|
|
22
|
+
* when it actually changes the time value.
|
|
23
|
+
*
|
|
24
|
+
* What is tracked on plain objects: property reads, `key in obj`, and
|
|
25
|
+
* key enumeration (Object.keys, for...in). Writes that ADD a key also
|
|
26
|
+
* notify readers of the array's length / the object's key list, which
|
|
27
|
+
* is what makes `items.push(x)` re-render a list that iterates
|
|
28
|
+
* `items`.
|
|
19
29
|
*
|
|
20
30
|
* Every effect tracks (a) which dep Sets it's currently a member of,
|
|
21
31
|
* and (b) which child effects were created while it was running
|
|
@@ -36,8 +46,20 @@ const targetMap = new WeakMap()
|
|
|
36
46
|
const reactiveMap = new WeakMap()
|
|
37
47
|
// Every proxy we have handed out, to avoid double-wrapping.
|
|
38
48
|
const proxies = new WeakSet()
|
|
49
|
+
// proxy -> original object, so a Map/Set key or value that is already
|
|
50
|
+
// a proxy can still be looked up by its original.
|
|
51
|
+
const proxyToRaw = new WeakMap()
|
|
39
52
|
|
|
40
53
|
const ITERATE_KEY = Symbol('iterate')
|
|
54
|
+
const DATE_KEY = Symbol('date')
|
|
55
|
+
|
|
56
|
+
function collectionKind(val) {
|
|
57
|
+
const proto = Object.getPrototypeOf(val)
|
|
58
|
+
if (proto === Map.prototype) return 'map'
|
|
59
|
+
if (proto === Set.prototype) return 'set'
|
|
60
|
+
if (proto === Date.prototype) return 'date'
|
|
61
|
+
return null
|
|
62
|
+
}
|
|
41
63
|
|
|
42
64
|
function isReactiveTarget(val) {
|
|
43
65
|
if (val === null || typeof val !== 'object') return false
|
|
@@ -45,60 +67,244 @@ function isReactiveTarget(val) {
|
|
|
45
67
|
if (Object.isFrozen(val)) return false
|
|
46
68
|
if (Array.isArray(val)) return true
|
|
47
69
|
const proto = Object.getPrototypeOf(val)
|
|
48
|
-
return
|
|
70
|
+
return (
|
|
71
|
+
proto === Object.prototype || proto === null || collectionKind(val) !== null
|
|
72
|
+
)
|
|
49
73
|
}
|
|
50
74
|
|
|
51
75
|
function isIndexKey(key) {
|
|
52
76
|
return typeof key === 'string' && /^(0|[1-9]\d*)$/.test(key)
|
|
53
77
|
}
|
|
54
78
|
|
|
79
|
+
// Returns the original object behind a reactive proxy (or the value
|
|
80
|
+
// itself when it is not a proxy).
|
|
81
|
+
export function toRaw(value) {
|
|
82
|
+
return proxyToRaw.get(value) ?? value
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function wrapValue(value) {
|
|
86
|
+
return isReactiveTarget(value) ? reactive(value) : value
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
// ---- plain objects and arrays ----
|
|
90
|
+
|
|
91
|
+
const objectHandler = {
|
|
92
|
+
get(obj, key, receiver) {
|
|
93
|
+
const result = Reflect.get(obj, key, receiver)
|
|
94
|
+
if (typeof key !== 'symbol') track(obj, key)
|
|
95
|
+
// Lazily wrap nested reactive targets so writes to THEIR
|
|
96
|
+
// properties are tracked too.
|
|
97
|
+
return isReactiveTarget(result) ? reactive(result) : result
|
|
98
|
+
},
|
|
99
|
+
has(obj, key) {
|
|
100
|
+
if (typeof key !== 'symbol') track(obj, key)
|
|
101
|
+
return Reflect.has(obj, key)
|
|
102
|
+
},
|
|
103
|
+
ownKeys(obj) {
|
|
104
|
+
track(obj, Array.isArray(obj) ? 'length' : ITERATE_KEY)
|
|
105
|
+
return Reflect.ownKeys(obj)
|
|
106
|
+
},
|
|
107
|
+
set(obj, key, value, receiver) {
|
|
108
|
+
const isArray = Array.isArray(obj)
|
|
109
|
+
const hadKey =
|
|
110
|
+
isArray && isIndexKey(key)
|
|
111
|
+
? Number(key) < obj.length
|
|
112
|
+
: Object.prototype.hasOwnProperty.call(obj, key)
|
|
113
|
+
const oldValue = obj[key]
|
|
114
|
+
const result = Reflect.set(obj, key, value, receiver)
|
|
115
|
+
if (!hadKey) {
|
|
116
|
+
trigger(obj, key, 'add')
|
|
117
|
+
} else if (!Object.is(oldValue, value)) {
|
|
118
|
+
trigger(obj, key, 'set', isArray && key === 'length' ? value : undefined)
|
|
119
|
+
}
|
|
120
|
+
return result
|
|
121
|
+
},
|
|
122
|
+
deleteProperty(obj, key) {
|
|
123
|
+
const hadKey = Object.prototype.hasOwnProperty.call(obj, key)
|
|
124
|
+
const result = Reflect.deleteProperty(obj, key)
|
|
125
|
+
if (hadKey && result) trigger(obj, key, 'delete')
|
|
126
|
+
return result
|
|
127
|
+
},
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
// ---- Map and Set ----
|
|
131
|
+
|
|
132
|
+
function makeIterator(inner, wrap) {
|
|
133
|
+
return {
|
|
134
|
+
next() {
|
|
135
|
+
const step = inner.next()
|
|
136
|
+
return step.done ? step : { value: wrap(step.value), done: false }
|
|
137
|
+
},
|
|
138
|
+
[Symbol.iterator]() {
|
|
139
|
+
return this
|
|
140
|
+
},
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
const wrapEntry = (entry) => [wrapValue(entry[0]), wrapValue(entry[1])]
|
|
145
|
+
|
|
146
|
+
// Each method receives (rawTarget, proxy, ...args).
|
|
147
|
+
const mapMethods = {
|
|
148
|
+
get(obj, self, key) {
|
|
149
|
+
key = toRaw(key)
|
|
150
|
+
track(obj, key)
|
|
151
|
+
return wrapValue(obj.get(key))
|
|
152
|
+
},
|
|
153
|
+
has(obj, self, key) {
|
|
154
|
+
key = toRaw(key)
|
|
155
|
+
track(obj, key)
|
|
156
|
+
return obj.has(key)
|
|
157
|
+
},
|
|
158
|
+
set(obj, self, key, value) {
|
|
159
|
+
key = toRaw(key)
|
|
160
|
+
value = toRaw(value)
|
|
161
|
+
const had = obj.has(key)
|
|
162
|
+
const old = obj.get(key)
|
|
163
|
+
obj.set(key, value)
|
|
164
|
+
if (!had) trigger(obj, key, 'add')
|
|
165
|
+
else if (!Object.is(old, value)) trigger(obj, key, 'set')
|
|
166
|
+
return self
|
|
167
|
+
},
|
|
168
|
+
delete(obj, self, key) {
|
|
169
|
+
key = toRaw(key)
|
|
170
|
+
const had = obj.has(key)
|
|
171
|
+
const result = obj.delete(key)
|
|
172
|
+
if (had) trigger(obj, key, 'delete')
|
|
173
|
+
return result
|
|
174
|
+
},
|
|
175
|
+
clear(obj) {
|
|
176
|
+
const had = obj.size > 0
|
|
177
|
+
obj.clear()
|
|
178
|
+
if (had) trigger(obj, undefined, 'clear')
|
|
179
|
+
},
|
|
180
|
+
forEach(obj, self, callback, thisArg) {
|
|
181
|
+
track(obj, ITERATE_KEY)
|
|
182
|
+
obj.forEach((v, k) =>
|
|
183
|
+
callback.call(thisArg, wrapValue(v), wrapValue(k), self),
|
|
184
|
+
)
|
|
185
|
+
},
|
|
186
|
+
keys(obj) {
|
|
187
|
+
track(obj, ITERATE_KEY)
|
|
188
|
+
return makeIterator(obj.keys(), wrapValue)
|
|
189
|
+
},
|
|
190
|
+
values(obj) {
|
|
191
|
+
track(obj, ITERATE_KEY)
|
|
192
|
+
return makeIterator(obj.values(), wrapValue)
|
|
193
|
+
},
|
|
194
|
+
entries(obj) {
|
|
195
|
+
track(obj, ITERATE_KEY)
|
|
196
|
+
return makeIterator(obj.entries(), wrapEntry)
|
|
197
|
+
},
|
|
198
|
+
}
|
|
199
|
+
mapMethods[Symbol.iterator] = mapMethods.entries
|
|
200
|
+
|
|
201
|
+
const setMethods = {
|
|
202
|
+
has(obj, self, value) {
|
|
203
|
+
value = toRaw(value)
|
|
204
|
+
track(obj, value)
|
|
205
|
+
return obj.has(value)
|
|
206
|
+
},
|
|
207
|
+
add(obj, self, value) {
|
|
208
|
+
value = toRaw(value)
|
|
209
|
+
if (!obj.has(value)) {
|
|
210
|
+
obj.add(value)
|
|
211
|
+
trigger(obj, value, 'add')
|
|
212
|
+
}
|
|
213
|
+
return self
|
|
214
|
+
},
|
|
215
|
+
delete(obj, self, value) {
|
|
216
|
+
value = toRaw(value)
|
|
217
|
+
const had = obj.has(value)
|
|
218
|
+
const result = obj.delete(value)
|
|
219
|
+
if (had) trigger(obj, value, 'delete')
|
|
220
|
+
return result
|
|
221
|
+
},
|
|
222
|
+
clear(obj) {
|
|
223
|
+
const had = obj.size > 0
|
|
224
|
+
obj.clear()
|
|
225
|
+
if (had) trigger(obj, undefined, 'clear')
|
|
226
|
+
},
|
|
227
|
+
forEach(obj, self, callback, thisArg) {
|
|
228
|
+
track(obj, ITERATE_KEY)
|
|
229
|
+
obj.forEach((v) => {
|
|
230
|
+
const wrapped = wrapValue(v)
|
|
231
|
+
callback.call(thisArg, wrapped, wrapped, self)
|
|
232
|
+
})
|
|
233
|
+
},
|
|
234
|
+
values(obj) {
|
|
235
|
+
track(obj, ITERATE_KEY)
|
|
236
|
+
return makeIterator(obj.values(), wrapValue)
|
|
237
|
+
},
|
|
238
|
+
entries(obj) {
|
|
239
|
+
track(obj, ITERATE_KEY)
|
|
240
|
+
return makeIterator(obj.entries(), wrapEntry)
|
|
241
|
+
},
|
|
242
|
+
}
|
|
243
|
+
setMethods.keys = setMethods.values
|
|
244
|
+
setMethods[Symbol.iterator] = setMethods.values
|
|
245
|
+
|
|
246
|
+
function collectionHandler(methods) {
|
|
247
|
+
return {
|
|
248
|
+
get(obj, key, receiver) {
|
|
249
|
+
if (key === 'size') {
|
|
250
|
+
track(obj, ITERATE_KEY)
|
|
251
|
+
return obj.size
|
|
252
|
+
}
|
|
253
|
+
if (Object.prototype.hasOwnProperty.call(methods, key)) {
|
|
254
|
+
const method = methods[key]
|
|
255
|
+
return (...args) => method(obj, receiver, ...args)
|
|
256
|
+
}
|
|
257
|
+
const result = Reflect.get(obj, key, obj)
|
|
258
|
+
return typeof result === 'function' && key !== 'constructor'
|
|
259
|
+
? result.bind(obj)
|
|
260
|
+
: result
|
|
261
|
+
},
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
const mapHandler = collectionHandler(mapMethods)
|
|
266
|
+
const setHandler = collectionHandler(setMethods)
|
|
267
|
+
|
|
268
|
+
// ---- Date ----
|
|
269
|
+
|
|
270
|
+
const dateHandler = {
|
|
271
|
+
get(obj, key, receiver) {
|
|
272
|
+
const result = Reflect.get(obj, key, obj)
|
|
273
|
+
if (typeof result !== 'function' || key === 'constructor') return result
|
|
274
|
+
const isSetter = typeof key === 'string' && key.startsWith('set')
|
|
275
|
+
return (...args) => {
|
|
276
|
+
if (isSetter) {
|
|
277
|
+
const before = obj.getTime()
|
|
278
|
+
const out = result.apply(obj, args)
|
|
279
|
+
if (!Object.is(before, obj.getTime())) trigger(obj, DATE_KEY, 'set')
|
|
280
|
+
return out
|
|
281
|
+
}
|
|
282
|
+
track(obj, DATE_KEY)
|
|
283
|
+
return result.apply(obj, args)
|
|
284
|
+
}
|
|
285
|
+
},
|
|
286
|
+
}
|
|
287
|
+
|
|
55
288
|
export function reactive(target) {
|
|
56
289
|
if (!isReactiveTarget(target)) return target
|
|
57
290
|
if (proxies.has(target)) return target
|
|
58
291
|
const existing = reactiveMap.get(target)
|
|
59
292
|
if (existing) return existing
|
|
60
293
|
|
|
61
|
-
const
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
if (typeof key !== 'symbol') track(obj, key)
|
|
71
|
-
return Reflect.has(obj, key)
|
|
72
|
-
},
|
|
73
|
-
ownKeys(obj) {
|
|
74
|
-
track(obj, Array.isArray(obj) ? 'length' : ITERATE_KEY)
|
|
75
|
-
return Reflect.ownKeys(obj)
|
|
76
|
-
},
|
|
77
|
-
set(obj, key, value, receiver) {
|
|
78
|
-
const isArray = Array.isArray(obj)
|
|
79
|
-
const hadKey =
|
|
80
|
-
isArray && isIndexKey(key)
|
|
81
|
-
? Number(key) < obj.length
|
|
82
|
-
: Object.prototype.hasOwnProperty.call(obj, key)
|
|
83
|
-
const oldValue = obj[key]
|
|
84
|
-
const result = Reflect.set(obj, key, value, receiver)
|
|
85
|
-
if (!hadKey) {
|
|
86
|
-
trigger(obj, key, 'add')
|
|
87
|
-
} else if (!Object.is(oldValue, value)) {
|
|
88
|
-
trigger(obj, key, 'set', isArray && key === 'length' ? value : undefined)
|
|
89
|
-
}
|
|
90
|
-
return result
|
|
91
|
-
},
|
|
92
|
-
deleteProperty(obj, key) {
|
|
93
|
-
const hadKey = Object.prototype.hasOwnProperty.call(obj, key)
|
|
94
|
-
const result = Reflect.deleteProperty(obj, key)
|
|
95
|
-
if (hadKey && result) trigger(obj, key, 'delete')
|
|
96
|
-
return result
|
|
97
|
-
},
|
|
98
|
-
})
|
|
294
|
+
const kind = collectionKind(target)
|
|
295
|
+
const handler =
|
|
296
|
+
kind === 'map'
|
|
297
|
+
? mapHandler
|
|
298
|
+
: kind === 'set'
|
|
299
|
+
? setHandler
|
|
300
|
+
: kind === 'date'
|
|
301
|
+
? dateHandler
|
|
302
|
+
: objectHandler
|
|
99
303
|
|
|
304
|
+
const proxy = new Proxy(target, handler)
|
|
100
305
|
reactiveMap.set(target, proxy)
|
|
101
306
|
proxies.add(proxy)
|
|
307
|
+
proxyToRaw.set(proxy, target)
|
|
102
308
|
return proxy
|
|
103
309
|
}
|
|
104
310
|
|
|
@@ -123,23 +329,31 @@ function trigger(obj, key, type, newLength) {
|
|
|
123
329
|
if (dep) for (const fn of dep) queued.add(fn)
|
|
124
330
|
}
|
|
125
331
|
|
|
126
|
-
|
|
332
|
+
if (type === 'clear') {
|
|
333
|
+
// Map/Set cleared: every reader of any key or of the contents.
|
|
334
|
+
for (const dep of depsMap.values()) collect(dep)
|
|
335
|
+
} else {
|
|
336
|
+
collect(depsMap.get(key))
|
|
127
337
|
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
338
|
+
if (type === 'add') {
|
|
339
|
+
if (Array.isArray(obj)) {
|
|
340
|
+
if (isIndexKey(key)) collect(depsMap.get('length'))
|
|
341
|
+
} else {
|
|
342
|
+
collect(depsMap.get(ITERATE_KEY))
|
|
343
|
+
}
|
|
344
|
+
} else if (type === 'delete' && !Array.isArray(obj)) {
|
|
345
|
+
collect(depsMap.get(ITERATE_KEY))
|
|
346
|
+
} else if (type === 'set' && obj instanceof Map) {
|
|
347
|
+
// values() / entries() / forEach() readers see the new value.
|
|
132
348
|
collect(depsMap.get(ITERATE_KEY))
|
|
133
349
|
}
|
|
134
|
-
} else if (type === 'delete' && !Array.isArray(obj)) {
|
|
135
|
-
collect(depsMap.get(ITERATE_KEY))
|
|
136
|
-
}
|
|
137
350
|
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
351
|
+
// `arr.length = 0` / splice shrinking: readers of the removed
|
|
352
|
+
// indices must hear about it too.
|
|
353
|
+
if (Array.isArray(obj) && key === 'length' && newLength !== undefined) {
|
|
354
|
+
for (const [k, dep] of depsMap) {
|
|
355
|
+
if (isIndexKey(k) && Number(k) >= newLength) collect(dep)
|
|
356
|
+
}
|
|
143
357
|
}
|
|
144
358
|
}
|
|
145
359
|
|
|
@@ -196,4 +410,18 @@ export function effect(fn) {
|
|
|
196
410
|
wrapped.children = []
|
|
197
411
|
wrapped()
|
|
198
412
|
return wrapped
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
// Runs fn with dependency tracking switched off, then restores it.
|
|
416
|
+
// Reads inside fn do NOT subscribe whichever effect happens to be
|
|
417
|
+
// running, which is what you want for one-off setup code that gets
|
|
418
|
+
// triggered from inside a render effect (capability init()).
|
|
419
|
+
export function untracked(fn) {
|
|
420
|
+
const previousEffect = activeEffect
|
|
421
|
+
activeEffect = null
|
|
422
|
+
try {
|
|
423
|
+
return fn()
|
|
424
|
+
} finally {
|
|
425
|
+
activeEffect = previousEffect
|
|
426
|
+
}
|
|
199
427
|
}
|
package/src/runtime/useApi.js
CHANGED
|
@@ -4,16 +4,56 @@ export async function useApi(url, options = {}) {
|
|
|
4
4
|
body,
|
|
5
5
|
headers = {},
|
|
6
6
|
credentials = 'include',
|
|
7
|
+
// Abort after this many milliseconds. 0 means no timeout.
|
|
8
|
+
timeout = 0,
|
|
9
|
+
signal,
|
|
7
10
|
} = options
|
|
8
11
|
|
|
9
12
|
const finalHeaders = { ...headers }
|
|
13
|
+
const hasHeader = (name) =>
|
|
14
|
+
Object.keys(finalHeaders).some((k) => k.toLowerCase() === name)
|
|
15
|
+
|
|
16
|
+
// Bodies fetch understands natively are sent untouched. Any other
|
|
17
|
+
// object (plain objects, arrays, reactive proxies) is sent as JSON.
|
|
18
|
+
const isNativeBody =
|
|
19
|
+
body instanceof FormData ||
|
|
20
|
+
body instanceof Blob ||
|
|
21
|
+
body instanceof URLSearchParams ||
|
|
22
|
+
body instanceof ArrayBuffer ||
|
|
23
|
+
ArrayBuffer.isView(body) ||
|
|
24
|
+
(typeof ReadableStream !== 'undefined' && body instanceof ReadableStream)
|
|
25
|
+
|
|
10
26
|
let finalBody = body
|
|
11
|
-
if (body && typeof body === 'object' && !
|
|
12
|
-
|
|
13
|
-
finalHeaders['Content-Type']
|
|
27
|
+
if (body && typeof body === 'object' && !isNativeBody) {
|
|
28
|
+
if (!hasHeader('content-type')) {
|
|
29
|
+
finalHeaders['Content-Type'] = 'application/json'
|
|
30
|
+
}
|
|
14
31
|
finalBody = JSON.stringify(body)
|
|
15
32
|
}
|
|
16
33
|
|
|
34
|
+
// fetch() throws a TypeError for a GET/HEAD with a body, which used
|
|
35
|
+
// to surface as a confusing "could not reach the server".
|
|
36
|
+
const upper = String(method).toUpperCase()
|
|
37
|
+
if ((upper === 'GET' || upper === 'HEAD') && finalBody !== undefined) {
|
|
38
|
+
console.warn(
|
|
39
|
+
`[tylix] ${upper} ${url}: a ${upper} request cannot have a body, so it was ignored.`,
|
|
40
|
+
)
|
|
41
|
+
finalBody = undefined
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
let controller = null
|
|
45
|
+
let timer = null
|
|
46
|
+
let fetchSignal = signal
|
|
47
|
+
if (timeout > 0) {
|
|
48
|
+
controller = new AbortController()
|
|
49
|
+
timer = setTimeout(() => controller.abort(), timeout)
|
|
50
|
+
if (signal) {
|
|
51
|
+
if (signal.aborted) controller.abort()
|
|
52
|
+
else signal.addEventListener('abort', () => controller.abort(), { once: true })
|
|
53
|
+
}
|
|
54
|
+
fetchSignal = controller.signal
|
|
55
|
+
}
|
|
56
|
+
|
|
17
57
|
// __tylixRequestStart/End are injected by the runtime. Guarding them
|
|
18
58
|
// lets this exact file work whether or not they exist.
|
|
19
59
|
const track = typeof __tylixRequestStart === 'function'
|
|
@@ -25,13 +65,17 @@ export async function useApi(url, options = {}) {
|
|
|
25
65
|
headers: finalHeaders,
|
|
26
66
|
body: finalBody,
|
|
27
67
|
credentials,
|
|
68
|
+
signal: fetchSignal,
|
|
28
69
|
})
|
|
70
|
+
|
|
29
71
|
let data = null
|
|
30
72
|
try {
|
|
31
|
-
|
|
73
|
+
const text = await response.text()
|
|
74
|
+
if (text) data = JSON.parse(text)
|
|
32
75
|
} catch {
|
|
33
|
-
/* empty body */
|
|
76
|
+
/* empty or non-JSON body */
|
|
34
77
|
}
|
|
78
|
+
|
|
35
79
|
if (!response.ok) {
|
|
36
80
|
// Only present when the server runs with APP_DEBUG=true.
|
|
37
81
|
const debug =
|
|
@@ -41,18 +85,26 @@ export async function useApi(url, options = {}) {
|
|
|
41
85
|
ok: false,
|
|
42
86
|
status: response.status,
|
|
43
87
|
data,
|
|
44
|
-
error:
|
|
88
|
+
error:
|
|
89
|
+
(data && (data.error || data.message)) ||
|
|
90
|
+
`Request failed (HTTP ${response.status})`,
|
|
45
91
|
debug,
|
|
46
92
|
}
|
|
47
93
|
}
|
|
48
94
|
return { ok: true, status: response.status, data, error: null, debug: null }
|
|
49
95
|
} catch (err) {
|
|
96
|
+
const timedOut =
|
|
97
|
+
controller && controller.signal.aborted && !(signal && signal.aborted)
|
|
98
|
+
const message = timedOut
|
|
99
|
+
? `Request timed out after ${timeout}ms`
|
|
100
|
+
: err.message
|
|
50
101
|
console.warn(
|
|
51
|
-
`[tylix] ${method} ${url} could not reach the server: ${
|
|
102
|
+
`[tylix] ${method} ${url} could not reach the server: ${message}. ` +
|
|
52
103
|
'Is "tylix dev" running, and is the URL correct?',
|
|
53
104
|
)
|
|
54
|
-
return { ok: false, status: 0, data: null, error:
|
|
105
|
+
return { ok: false, status: 0, data: null, error: message, debug: null }
|
|
55
106
|
} finally {
|
|
107
|
+
if (timer) clearTimeout(timer)
|
|
56
108
|
if (track) __tylixRequestEnd()
|
|
57
109
|
}
|
|
58
110
|
|
|
@@ -61,7 +113,13 @@ export async function useApi(url, options = {}) {
|
|
|
61
113
|
// file still works if the compiler injects only this one function.
|
|
62
114
|
// ---------------------------------------------------------------
|
|
63
115
|
function showDebug(debug, method, url) {
|
|
64
|
-
|
|
116
|
+
// Neither step may throw: this runs inside the request's try block,
|
|
117
|
+
// so an error here would be reported as a network failure.
|
|
118
|
+
try {
|
|
119
|
+
logToConsole(debug, method, url)
|
|
120
|
+
} catch (err) {
|
|
121
|
+
console.warn('[tylix] debug logging failed:', err)
|
|
122
|
+
}
|
|
65
123
|
try {
|
|
66
124
|
showOverlay(debug, method, url)
|
|
67
125
|
} catch (err) {
|
|
@@ -99,10 +157,6 @@ export async function useApi(url, options = {}) {
|
|
|
99
157
|
index: 0,
|
|
100
158
|
open: false,
|
|
101
159
|
})
|
|
102
|
-
store.errors.unshift({ debug, method, url })
|
|
103
|
-
store.errors = store.errors.slice(0, 20)
|
|
104
|
-
store.index = 0
|
|
105
|
-
render()
|
|
106
160
|
|
|
107
161
|
function h(tag, props, ...children) {
|
|
108
162
|
const node = document.createElement(tag)
|
|
@@ -401,5 +455,12 @@ export async function useApi(url, options = {}) {
|
|
|
401
455
|
.frame span { color: var(--ac); font-size: 12px; word-break: break-all; }
|
|
402
456
|
.actions { display: flex; gap: 8px; margin-top: 22px; }
|
|
403
457
|
`
|
|
458
|
+
|
|
459
|
+
// Last on purpose: render() reads CSS and KEYWORDS, which are
|
|
460
|
+
// consts and cannot be touched before their declarations above.
|
|
461
|
+
store.errors.unshift({ debug, method, url })
|
|
462
|
+
store.errors = store.errors.slice(0, 20)
|
|
463
|
+
store.index = 0
|
|
464
|
+
render()
|
|
404
465
|
}
|
|
405
466
|
}
|
|
@@ -1,11 +1,27 @@
|
|
|
1
1
|
export function useChannel(name) {
|
|
2
2
|
const port = window.__TYLIX_CHANNELS_PORT__ ?? 6001
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
)
|
|
6
|
-
|
|
3
|
+
// An https page may not open a plain ws:// socket (SecurityError).
|
|
4
|
+
const scheme = window.location.protocol === 'https:' ? 'wss' : 'ws'
|
|
7
5
|
const listeners = []
|
|
8
6
|
|
|
7
|
+
let socket
|
|
8
|
+
try {
|
|
9
|
+
socket = new WebSocket(
|
|
10
|
+
`${scheme}://${window.location.hostname}:${port}/${name}`,
|
|
11
|
+
)
|
|
12
|
+
} catch (err) {
|
|
13
|
+
// Return an inert channel so one failed socket does not take the
|
|
14
|
+
// whole page down; the page can still render.
|
|
15
|
+
console.error(`useChannel("${name}") could not connect:`, err)
|
|
16
|
+
return {
|
|
17
|
+
send() {},
|
|
18
|
+
onMessage() {
|
|
19
|
+
return () => {}
|
|
20
|
+
},
|
|
21
|
+
close() {},
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
|
|
9
25
|
socket.addEventListener('message', (event) => {
|
|
10
26
|
let data
|
|
11
27
|
try {
|
|
@@ -13,7 +29,7 @@ export function useChannel(name) {
|
|
|
13
29
|
} catch {
|
|
14
30
|
return
|
|
15
31
|
}
|
|
16
|
-
for (const fn of listeners) fn(data)
|
|
32
|
+
for (const fn of [...listeners]) fn(data)
|
|
17
33
|
})
|
|
18
34
|
|
|
19
35
|
return {
|
|
@@ -28,11 +44,16 @@ export function useChannel(name) {
|
|
|
28
44
|
)
|
|
29
45
|
}
|
|
30
46
|
},
|
|
47
|
+
// Returns an unsubscribe function.
|
|
31
48
|
onMessage(fn) {
|
|
32
49
|
listeners.push(fn)
|
|
50
|
+
return () => {
|
|
51
|
+
const i = listeners.indexOf(fn)
|
|
52
|
+
if (i !== -1) listeners.splice(i, 1)
|
|
53
|
+
}
|
|
33
54
|
},
|
|
34
55
|
close() {
|
|
35
56
|
socket.close()
|
|
36
57
|
},
|
|
37
58
|
}
|
|
38
|
-
}
|
|
59
|
+
}
|
|
@@ -51,6 +51,10 @@ export function buildVirtualPageTs(pageNode, className, templateNodes = null) {
|
|
|
51
51
|
},
|
|
52
52
|
}
|
|
53
53
|
|
|
54
|
+
// Module-level helpers and type declarations go before the class.
|
|
55
|
+
const helpers = pageNode.helpers ?? []
|
|
56
|
+
for (const h of helpers) emitStatementLines(h, sink, '')
|
|
57
|
+
|
|
54
58
|
if (pageNode.props.length > 0) {
|
|
55
59
|
sink.pushLine(`interface ${className}Props {`, null)
|
|
56
60
|
for (const p of pageNode.props) {
|
|
@@ -91,7 +95,7 @@ export function buildVirtualPageTs(pageNode, className, templateNodes = null) {
|
|
|
91
95
|
: ''
|
|
92
96
|
sink.pushLine(``, null)
|
|
93
97
|
sink.pushLine(
|
|
94
|
-
` ${a.isAsync ? 'async ' : ''}${a.name}(${generateParams(a.params, true)})${returnType ? `: ${returnType}` : ''} {`,
|
|
98
|
+
` ${a.isAsync ? 'async ' : ''}${a.name}${a.typeParams ?? ''}(${generateParams(a.params, true)})${returnType ? `: ${returnType}` : ''} {`,
|
|
95
99
|
a.line,
|
|
96
100
|
)
|
|
97
101
|
for (const stmt of a.body) emitStatementLines(stmt, sink, ' ')
|
|
@@ -121,6 +125,12 @@ export function buildVirtualPageTs(pageNode, className, templateNodes = null) {
|
|
|
121
125
|
|
|
122
126
|
sink.pushLine(`}`, null)
|
|
123
127
|
|
|
128
|
+
// Module-level helpers (e.g. `const name = ...`) would clash with DOM
|
|
129
|
+
// globals in a script file; `export {}` makes it a module.
|
|
130
|
+
if (helpers.some((h) => h.type !== 'TypeDeclaration')) {
|
|
131
|
+
sink.pushLine('export {};', null)
|
|
132
|
+
}
|
|
133
|
+
|
|
124
134
|
return { source: lines.join('\n') + '\n', lineMap }
|
|
125
135
|
}
|
|
126
136
|
|
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
|
|
2
1
|
// Present on failed requests only when the server runs with APP_DEBUG=true.
|
|
3
2
|
interface TylixDebugInfo {
|
|
4
3
|
status: number
|
|
@@ -40,15 +39,25 @@ interface TylixApiResult {
|
|
|
40
39
|
debug?: TylixDebugInfo | null
|
|
41
40
|
}
|
|
42
41
|
|
|
42
|
+
interface TylixChannel {
|
|
43
|
+
send(data: unknown): void
|
|
44
|
+
// Returns an unsubscribe function.
|
|
45
|
+
onMessage(fn: (data: any) => void): () => void
|
|
46
|
+
close(): void
|
|
47
|
+
}
|
|
48
|
+
|
|
43
49
|
declare function useApi(
|
|
44
50
|
path: string,
|
|
45
51
|
options?: {
|
|
46
52
|
method?: string
|
|
47
53
|
body?: unknown
|
|
48
54
|
headers?: Record<string, string>
|
|
55
|
+
credentials?: RequestCredentials
|
|
56
|
+
// Abort after this many milliseconds. 0 or omitted means no timeout.
|
|
57
|
+
timeout?: number
|
|
58
|
+
signal?: AbortSignal
|
|
49
59
|
},
|
|
50
60
|
): Promise<TylixApiResult>
|
|
51
|
-
|
|
52
61
|
// getApi/postApi/putApi/deleteApi share useApi's response shape --
|
|
53
62
|
// convenience wrappers over the same underlying call.
|
|
54
63
|
declare function getApi(
|
|
@@ -73,6 +82,16 @@ declare function deleteApi(
|
|
|
73
82
|
options?: { headers?: Record<string, string> },
|
|
74
83
|
): Promise<TylixApiResult>
|
|
75
84
|
|
|
76
|
-
|
|
85
|
+
interface ApiOptions {
|
|
86
|
+
headers?: Record<string, string>
|
|
87
|
+
credentials?: RequestCredentials
|
|
88
|
+
timeout?: number
|
|
89
|
+
signal?: AbortSignal
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
declare function useChannel(name: string): TylixChannel
|
|
93
|
+
|
|
94
|
+
declare function notFound(): void
|
|
77
95
|
|
|
78
|
-
|
|
96
|
+
// Capability names used in page scripts compile to this call.
|
|
97
|
+
declare function resolveCapability(name: string): any
|