@slim-lang/core 1.2.11 → 1.2.13

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 (48) hide show
  1. package/README.md +522 -14
  2. package/package.json +2 -6
  3. package/packages/slim/server/main.slim +433 -422
  4. package/run-dev-slim.js +10 -5
  5. package/run-slim.js +10 -20
  6. package/src/bin/api/github_get.js +7 -12
  7. package/src/bin/api/github_req.js +54 -241
  8. package/src/bin/api/lock.js +2 -1
  9. package/src/bin/api/spm.js +20 -91
  10. package/src/bin/cli.js +73 -102
  11. package/src/bin/config.default.json +11 -11
  12. package/src/bin/helpers.js +2 -7
  13. package/src/bin/spm.js +3 -7
  14. package/src/checker.js +1705 -388
  15. package/src/compile.js +131 -100
  16. package/src/external/classErrors.js +5 -6
  17. package/src/external/client.js +0 -2
  18. package/src/external/core.js +355 -237
  19. package/src/external/defaults.js +12 -4
  20. package/src/external/dom.js +663 -0
  21. package/src/external/helpers.js +87 -58
  22. package/src/external/reactive.js +601 -0
  23. package/src/external/router.js +117 -0
  24. package/src/external/slim-globals.d.ts +43 -4
  25. package/src/external/typeSyntax.js +258 -0
  26. package/src/external/types.js +1 -1
  27. package/src/format.js +183 -12
  28. package/src/handlers/errorHandler.js +9 -36
  29. package/src/jsdoc.js +36 -16
  30. package/src/modulePaths.js +15 -5
  31. package/src/reactivity.js +774 -0
  32. package/src/repl.js +1 -1
  33. package/src/suggest.js +60 -0
  34. package/src/syntax/babel.js +46 -0
  35. package/src/syntax/index.js +39 -0
  36. package/src/syntax/lower.js +666 -0
  37. package/src/syntax/markup.js +195 -0
  38. package/src/syntax/plugin.js +903 -0
  39. package/src/syntax/types.js +106 -0
  40. package/src/test-runner.js +5 -5
  41. package/src/transform.js +209 -244
  42. package/packages/slim/helpers/string.js +0 -43
  43. package/packages/slim/types/hash.js +0 -11
  44. package/src/handlers/parser/components.js +0 -295
  45. package/src/handlers/parserHandler.js +0 -789
  46. package/src/lexer.js +0 -174
  47. package/src/parser.js +0 -803
  48. package/src/sourcemap.js +0 -0
@@ -0,0 +1,774 @@
1
+ import * as t from "@babel/types"
2
+ import _traverse from "@babel/traverse"
3
+ import { parseMarkup } from "./syntax/markup.js"
4
+ import fs from "node:fs"
5
+ import { parseSlim, slimSyntaxError } from "./syntax/plugin.js"
6
+
7
+ const traverse = _traverse.default ?? _traverse
8
+
9
+ const SKIP_KEYS = new Set(["loc", "start", "end", "extra", "leadingComments", "trailingComments", "innerComments"])
10
+
11
+ const isNode = value => !!value && typeof value === "object" && typeof value.type === "string"
12
+ const isMarkup = node => node?.type === "TaggedTemplateExpression" && node._slimMarkup === true
13
+ const id = name => t.identifier(name)
14
+ const call = (name, args) => t.callExpression(id(name), args)
15
+ const call_ = call
16
+ const thunk = body => t.arrowFunctionExpression([], body)
17
+
18
+ function done(name) {
19
+ const node = id(name)
20
+ node._slimDone = true
21
+ return node
22
+ }
23
+
24
+ const SVG_ONLY = new Set([
25
+ "g", "path", "circle", "rect", "line", "polyline", "polygon", "ellipse", "tspan", "defs", "use",
26
+ "symbol", "clipPath", "mask", "pattern", "linearGradient", "radialGradient", "stop", "filter", "marker", "text"
27
+ ])
28
+
29
+ const NOT_COMPONENTS = new Set([
30
+ "Object", "Array", "String", "Number", "Boolean", "Symbol", "BigInt", "Date", "Error", "TypeError",
31
+ "RangeError", "SyntaxError", "Promise", "Map", "Set", "WeakMap", "WeakSet", "WeakRef", "Proxy", "Reflect",
32
+ "JSON", "Math", "Intl", "URL", "URLSearchParams", "Response", "Request", "Headers", "Blob", "File",
33
+ "FormData", "Event", "CustomEvent", "AbortController", "RegExp"
34
+ ])
35
+
36
+ const READ_METHODS = new Set([
37
+ "at", "concat", "entries", "every", "filter", "find", "findIndex", "findLast", "findLastIndex", "flat",
38
+ "flatMap", "forEach", "includes", "indexOf", "join", "keys", "lastIndexOf", "map", "reduce", "reduceRight",
39
+ "slice", "some", "values", "with", "get", "charAt", "charCodeAt", "codePointAt", "endsWith", "startsWith",
40
+ "padStart", "padEnd", "repeat", "replace", "replaceAll", "search", "split", "substring", "substr",
41
+ "trim", "trimStart", "trimEnd", "match", "matchAll", "localeCompare", "normalize", "valueOf"
42
+ ])
43
+
44
+ function readsOnly(member) {
45
+ const name = !member.computed && t.isIdentifier(member.property) ? member.property.name
46
+ : t.isStringLiteral(member.property) ? member.property.value : null
47
+ if (name === null) return false
48
+ return READ_METHODS.has(name) || /^(get|has|is|to)[A-Z]/.test(name)
49
+ }
50
+
51
+
52
+ const ESCAPES = { n: "\n", t: "\t", r: "\r", b: "\b", f: "\f", v: "\v", 0: "\0" }
53
+
54
+ function cook(raw) {
55
+ return raw.replace(/\\(u\{[0-9a-fA-F]+\}|u[0-9a-fA-F]{4}|x[0-9a-fA-F]{2}|\r\n|[\s\S])/g, (_, escape) => {
56
+ if (escape[0] === "u" && escape.length > 1) {
57
+ return String.fromCodePoint(parseInt(escape[1] === "{" ? escape.slice(2, -1) : escape.slice(1), 16))
58
+ }
59
+ if (escape[0] === "x" && escape.length === 3) return String.fromCharCode(parseInt(escape.slice(1), 16))
60
+ if (escape === "\n" || escape === "\r\n" || escape === "\r") return ""
61
+ return ESCAPES[escape] ?? escape
62
+ })
63
+ }
64
+
65
+ function staticText(node) {
66
+ if (t.isStringLiteral(node)) return node.value
67
+ if (t.isNumericLiteral(node)) return String(node.value)
68
+ if (t.isNullLiteral(node) || t.isBooleanLiteral(node) || t.isIdentifier(node, { name: "undefined" })) return ""
69
+ if (t.isTemplateLiteral(node) && node.expressions.length === 0) return node.quasis[0].value.cooked
70
+ return null
71
+ }
72
+
73
+ function containsMarkup(node) {
74
+ if (isMarkup(node)) return true
75
+ if (t.isConditionalExpression(node)) return containsMarkup(node.consequent) || containsMarkup(node.alternate)
76
+ if (t.isLogicalExpression(node)) return containsMarkup(node.right)
77
+ return false
78
+ }
79
+
80
+ function returnedMarkup(fn) {
81
+ if (isMarkup(fn.body)) return { get: () => fn.body, set: value => { fn.body = value } }
82
+ if (!t.isBlockStatement(fn.body)) return null
83
+ const returns = []
84
+ const find = node => {
85
+ if (!isNode(node) || (node !== fn.body && t.isFunction(node))) return
86
+ if (t.isReturnStatement(node)) returns.push(node)
87
+ for (const [key, value] of Object.entries(node)) {
88
+ if (SKIP_KEYS.has(key)) continue
89
+ if (Array.isArray(value)) value.forEach(find)
90
+ else find(value)
91
+ }
92
+ }
93
+ find(fn.body)
94
+ const last = fn.body.body.at(-1)
95
+ if (returns.length !== 1 || returns[0] !== last || !isMarkup(last.argument)) return null
96
+ return { get: () => last.argument, set: value => { last.argument = value } }
97
+ }
98
+
99
+ function returnedComponent(fn) {
100
+ const isComponent = node => t.isCallExpression(node) && t.isIdentifier(node.callee) && /^[A-Z]/.test(node.callee.name) &&
101
+ !NOT_COMPONENTS.has(node.callee.name)
102
+ if (isComponent(fn.body)) return { get: () => fn.body, set: value => { fn.body = value }, component: true }
103
+ return null
104
+ }
105
+
106
+ function listOf(node) {
107
+ if (!t.isCallExpression(node) || node.arguments.length !== 1) return null
108
+ const callee = node.callee
109
+ if (!t.isMemberExpression(callee) || callee.computed || !t.isIdentifier(callee.property, { name: "map" })) return null
110
+ const fn = node.arguments[0]
111
+ if (!t.isArrowFunctionExpression(fn) && !t.isFunctionExpression(fn)) return null
112
+ if (fn.params.length === 0 || fn.params.length > 2 || !fn.params.every(param => t.isIdentifier(param))) return null
113
+ const row = returnedMarkup(fn) ?? returnedComponent(fn)
114
+ return row ? { source: callee.object, fn, row } : null
115
+ }
116
+
117
+ const isComponentTag = node => node.type === "element" && /^[A-Z]/.test(node.tag.split(".").at(-1)) && !node.tag.includes("-")
118
+
119
+ const KEEPS_WHITESPACE = new Set(["pre", "textarea", "script", "style"])
120
+
121
+ function collapseText(text) {
122
+ if (!/[\r\n]/.test(text)) return text
123
+ const lines = text.split(/\r\n|\n|\r/)
124
+ let out = ""
125
+ lines.forEach((line, index) => {
126
+ let part = line
127
+ if (index > 0) part = part.replace(/^[ \t]+/, "")
128
+ if (index < lines.length - 1) part = part.replace(/[ \t]+$/, "")
129
+ if (part) out += (out ? " " : "") + part
130
+ })
131
+ return out
132
+ }
133
+
134
+ function collapseWhitespace(nodes) {
135
+ const out = []
136
+ for (const node of nodes) {
137
+ if (node.type === "text") {
138
+ const value = collapseText(node.value)
139
+ if (value) out.push({ ...node, value })
140
+ } else if (node.type === "element") {
141
+ out.push(KEEPS_WHITESPACE.has(node.tag.toLowerCase()) ? node : { ...node, children: collapseWhitespace(node.children) })
142
+ } else {
143
+ out.push(node)
144
+ }
145
+ }
146
+ return out
147
+ }
148
+
149
+
150
+ class MarkupCompiler {
151
+ constructor(program) {
152
+ this.program = program
153
+ }
154
+
155
+ fail(node, message) {
156
+ return this.program.fail(node, message)
157
+ }
158
+
159
+ nested(node, ctx) {
160
+ if (!isNode(node)) return node
161
+ if (node._slimComponent) return node
162
+ if (isMarkup(node)) return this.markup(node, ctx)
163
+ if (node._slimRoot) return this.markup(node._slimRoot, ctx, { root: true })
164
+ for (const [key, value] of Object.entries(node)) {
165
+ if (SKIP_KEYS.has(key)) continue
166
+ if (Array.isArray(value)) node[key] = value.map(child => this.nested(child, ctx))
167
+ else if (isNode(value)) node[key] = this.nested(value, ctx)
168
+ }
169
+ return node
170
+ }
171
+
172
+ markup(node, ctx, options = {}) {
173
+ const tree = collapseWhitespace(parseMarkup(node._slimQuasis.map(cook), message => this.fail(node, message)))
174
+ return this.fromTree(tree, node, node.quasi.expressions, ctx, options)
175
+ }
176
+
177
+ fromTree(tree, node, expressions, ctx, { root = false, onKey = null } = {}) {
178
+ const roots = tree.filter(child => !(child.type === "text" && child.value.trim() === ""))
179
+
180
+ if (roots.length === 1 && roots[0].type === "hole") {
181
+ const expression = expressions[roots[0].index]
182
+ const text = staticText(expression)
183
+ if (text === null || root) {
184
+ return call("__root__", [this.valueOf(expression, ctx)])
185
+ }
186
+ }
187
+
188
+ const state = { markup: node, expressions, bindings: [], refs: new Map(), declarations: [], count: 0 }
189
+ const svg = ctx.svg || (roots[0]?.type === "element" && SVG_ONLY.has(roots[0].tag))
190
+ const rootCtx = { ...ctx, svg }
191
+
192
+ if (onKey && roots.length === 1 && roots[0].type === "element") {
193
+ const index = roots[0].attrs.findIndex(attr => attr.name === "key")
194
+ if (index !== -1) {
195
+ const [key] = roots[0].attrs.splice(index, 1)
196
+ if (key.parts) {
197
+ const value = this.attributeValue(key, state, rootCtx)
198
+ rootCtx.rowKey = t.cloneNode(value, true)
199
+ onKey(value)
200
+ }
201
+ }
202
+ }
203
+
204
+ if (roots.length === 1 && isComponentTag(roots[0])) {
205
+ return call("__root__", [thunk(this.component(roots[0], state, rootCtx))])
206
+ }
207
+
208
+ const template = roots.length === 1 && roots[0].type === "element"
209
+ ? [this.element(roots[0], [], rootCtx, state)]
210
+ : this.children(roots, [], rootCtx, state)
211
+ const name = this.program.template(template, svg)
212
+ if (state.bindings.length === 0) return call(name, [])
213
+
214
+ const statements = [
215
+ t.variableDeclaration("const", [t.variableDeclarator(id("__r__"), call(name, []))]),
216
+ ...state.declarations,
217
+ ...state.bindings.map(binding => t.expressionStatement(binding)),
218
+ t.returnStatement(id("__r__"))
219
+ ]
220
+ return t.callExpression(thunk(t.blockStatement(statements)), [])
221
+ }
222
+
223
+ ref(path, state) {
224
+ if (path.length === 0) return id("__r__")
225
+ const key = path.join(".")
226
+ const known = state.refs.get(key)
227
+ if (known) return id(known)
228
+
229
+ const parent = path.slice(0, -1)
230
+ const index = path[path.length - 1]
231
+ let expression = null
232
+ for (let j = index - 1; j >= 0; j--) {
233
+ const sibling = state.refs.get([...parent, j].join("."))
234
+ if (!sibling) continue
235
+ expression = call("__next__", [id(sibling), t.numericLiteral(index - j)])
236
+ break
237
+ }
238
+ if (!expression) expression = call("__child__", [this.ref(parent, state), t.numericLiteral(index)])
239
+ const name = `__n${++state.count}__`
240
+ state.declarations.push(t.variableDeclaration("const", [t.variableDeclarator(id(name), expression)]))
241
+ state.refs.set(key, name)
242
+ return id(name)
243
+ }
244
+
245
+ children(nodes, path, ctx, state) {
246
+ const out = []
247
+ for (const node of nodes) {
248
+ const here = [...path, out.length]
249
+ if (node.type === "text") {
250
+ out.push(node.value)
251
+ } else if (node.type === "comment") {
252
+ out.push(["#comment", node.value])
253
+ } else if (node.type === "hole") {
254
+ const expression = state.expressions[node.index]
255
+ const text = staticText(expression)
256
+ if (text !== null) {
257
+ if (text !== "") out.push(text)
258
+ continue
259
+ }
260
+ out.push("")
261
+ state.bindings.push(this.childBinding(() => this.ref(here, state), expression, ctx))
262
+ } else if (isComponentTag(node)) {
263
+ out.push("")
264
+ state.bindings.push(call("__insert__", [this.ref(here, state), thunk(this.component(node, state, ctx))]))
265
+ } else {
266
+ out.push(this.element(node, here, ctx, state))
267
+ }
268
+ }
269
+ return out
270
+ }
271
+
272
+ element(node, path, ctx, state) {
273
+ const attrs = {}
274
+ let childScope = ctx.scope
275
+ const svg = ctx.svg || node.tag === "svg"
276
+ const el = () => this.ref(path, state)
277
+
278
+ for (const attr of node.attrs) {
279
+ if (attr.spread !== undefined) {
280
+ state.bindings.push(call("__spread__", [el(), thunk(this.hole(state.expressions[attr.spread], ctx))]))
281
+ } else if (attr.event !== undefined) {
282
+ state.bindings.push(call("__on__", [el(), t.stringLiteral(attr.event), this.hole(state.expressions[attr.hole], ctx)]))
283
+ } else if (attr.parts && attr.name.startsWith("bind:")) {
284
+ state.bindings.push(...this.twoWay(node, attr, el, state, ctx))
285
+ } else if (attr.parts) {
286
+ if (attr.name === "key") continue
287
+ if (attr.name === "class" && ctx.scope !== null) {
288
+ attr.parts = attr.parts.map(part => typeof part === "string" ? part.replaceAll("&", ctx.scope) : part)
289
+ if (typeof attr.parts[0] === "string" && attr.parts[0].trim()) childScope = attr.parts[0].trim().split(/\s+/)[0]
290
+ }
291
+ const value = this.attributeValue(attr, state, ctx)
292
+ if (ctx.rowKey && t.isNodesEquivalent(value, ctx.rowKey)) {
293
+ state.bindings.push(call("__set__", [el(), t.stringLiteral(attr.name), value]))
294
+ } else {
295
+ state.bindings.push(call("__attr__", [el(), t.stringLiteral(attr.name), thunk(value)]))
296
+ }
297
+ } else if (attr.name === "move" && (attr.value === true || typeof attr.value === "string")) {
298
+ state.bindings.push(call_("__move__", [el(), attr.value === true ? t.numericLiteral(200) : t.stringLiteral(attr.value)]))
299
+ } else if ((attr.name === "enter" || attr.name === "leave") && typeof attr.value === "string") {
300
+ state.bindings.push(call_(`__${attr.name}__`, [el(), t.stringLiteral(attr.value)]))
301
+ } else {
302
+ if (attr.name === "key") continue
303
+ let value = attr.value
304
+ if (attr.name === "class" && ctx.scope !== null && typeof value === "string") {
305
+ value = value.replaceAll("&", ctx.scope)
306
+ childScope = value.trim().split(/\s+/)[0] || ctx.scope
307
+ }
308
+ attrs[attr.name] = value
309
+ }
310
+ }
311
+
312
+ const childCtx = { ...ctx, scope: childScope, svg: svg && node.tag !== "foreignObject" }
313
+ const children = this.children(node.children, path, childCtx, state)
314
+ return [node.tag, Object.keys(attrs).length ? attrs : 0, ...children]
315
+ }
316
+
317
+ twoWay(node, attr, el, state, ctx) {
318
+ const property = attr.name.slice("bind:".length)
319
+ const [part] = attr.parts
320
+ const markup = state.markup
321
+ if (attr.parts.length !== 1 || typeof part === "string") {
322
+ this.fail(markup, `${attr.name} takes a value to keep in sync: ${attr.name}=\${name}`)
323
+ }
324
+ if (property !== "value" && property !== "checked") {
325
+ this.fail(markup, `"${attr.name}" is not supported: use bind:value or bind:checked`)
326
+ }
327
+ const target = this.nested(state.expressions[part.hole], ctx)
328
+ if (!t.isIdentifier(target) && !t.isMemberExpression(target)) {
329
+ this.fail(target, `${attr.name} needs something it can assign to, like a state or a field: ${attr.name}=\${name}`)
330
+ }
331
+
332
+ const type = node.attrs.find(other => other.name === "type" && typeof other.value === "string")?.value.toLowerCase()
333
+ const tag = node.tag.toLowerCase()
334
+ const event = property === "checked" || tag === "select" || type === "checkbox" || type === "radio" ? "change" : "input"
335
+ const read = t.memberExpression(t.memberExpression(id("__e__"), id("target")),
336
+ id(property === "checked" ? "checked" : type === "number" || type === "range" ? "valueAsNumber" : "value"))
337
+ const write = t.arrowFunctionExpression([id("__e__")], t.assignmentExpression("=", t.cloneNode(target, true), read))
338
+ return [
339
+ call("__attr__", [el(), t.stringLiteral(property), thunk(target)]),
340
+ call("__on__", [el(), t.stringLiteral(event), write])
341
+ ]
342
+ }
343
+
344
+ attributeValue(attr, state, ctx) {
345
+ const parts = attr.parts.map(part => typeof part === "string" ? part : this.hole(state.expressions[part.hole], ctx))
346
+ if (!attr.quoted && parts.length === 1) return parts[0]
347
+ let value = null
348
+ for (const part of parts) {
349
+ const piece = typeof part === "string" ? t.stringLiteral(part) : call("__s__", [part])
350
+ value = value ? t.binaryExpression("+", value, piece) : piece
351
+ }
352
+ return typeof parts[0] === "string" ? value : t.binaryExpression("+", t.stringLiteral(""), value)
353
+ }
354
+
355
+ hole(expression, ctx) {
356
+ return this.nested(expression, ctx)
357
+ }
358
+
359
+ childBinding(anchor, expression, ctx) {
360
+ const list = listOf(expression)
361
+ if (list) {
362
+ list.fn._slimListRow = true
363
+ let key = null
364
+ if (!list.row.component) list.row.set(this.markup(list.row.get(), ctx, { onKey: value => { key = value } }))
365
+ list.fn.body = this.nested(list.fn.body, ctx)
366
+ for (const param of list.fn.params) param._slimReactive = "signal"
367
+ const args = [anchor(), thunk(this.nested(list.source, ctx)), list.fn]
368
+ const withIndex = list.fn.params.length > 1
369
+ if (key || withIndex) args.push(key ? t.arrowFunctionExpression(list.fn.params.map(param => id(param.name)), key) : t.nullLiteral())
370
+ if (withIndex) args.push(t.booleanLiteral(true))
371
+ return call("__list__", args)
372
+ }
373
+
374
+ if (ctx.rowKey && t.isNodesEquivalent(expression, ctx.rowKey)) return call("__once__", [anchor(), this.nested(expression, ctx)])
375
+ return call("__insert__", [anchor(), this.valueOf(expression, ctx)])
376
+ }
377
+
378
+ component(node, state, ctx) {
379
+ const properties = []
380
+ const prop = (name, value) => t.objectProperty(t.isValidIdentifier(name) ? id(name) : t.stringLiteral(name), value)
381
+ for (const attr of node.attrs) {
382
+ if (attr.spread !== undefined) {
383
+ properties.push(t.spreadElement(this.hole(state.expressions[attr.spread], ctx)))
384
+ } else if (attr.event !== undefined) {
385
+ properties.push(prop(attr.name, this.hole(state.expressions[attr.hole], ctx)))
386
+ } else if (attr.name === "key") {
387
+ continue
388
+ } else if (attr.name.startsWith("bind:")) {
389
+ this.fail(state.markup, `${attr.name} works on inputs, not on the component <${node.tag}>: pass the value and a callback as props`)
390
+ } else if (attr.parts) {
391
+ properties.push(prop(attr.name, this.attributeValue(attr, state, ctx)))
392
+ } else {
393
+ properties.push(prop(attr.name, attr.value === true ? t.booleanLiteral(true) : t.stringLiteral(attr.value)))
394
+ }
395
+ }
396
+ if (node.children.some(child => !(child.type === "text" && child.value.trim() === ""))) {
397
+ properties.push(prop("children", this.fromTree(node.children, state.markup, state.expressions, ctx)))
398
+ }
399
+ const callee = node.tag.split(".").map(id).reduce((object, property) => t.memberExpression(object, property))
400
+ return t.callExpression(callee, [t.objectExpression(properties)])
401
+ }
402
+
403
+ valueOf(expression, ctx) {
404
+ if (t.isConditionalExpression(expression) && containsMarkup(expression)) {
405
+ return call("__branch__", [
406
+ thunk(this.nested(expression.test, ctx)),
407
+ thunk(this.nested(expression.consequent, ctx)),
408
+ thunk(this.nested(expression.alternate, ctx))
409
+ ])
410
+ }
411
+ if (t.isLogicalExpression(expression, { operator: "&&" }) && containsMarkup(expression)) {
412
+ return call("__branch__", [thunk(this.nested(expression.left, ctx)), thunk(this.nested(expression.right, ctx)), t.nullLiteral()])
413
+ }
414
+ return thunk(this.nested(expression, ctx))
415
+ }
416
+ }
417
+
418
+
419
+ let importedReactive = new Map()
420
+
421
+ function reactiveKind(path) {
422
+ const binding = path.scope.getBinding(path.node.name)
423
+ if (!binding) return importedReactive.get(path.node.name) ?? null
424
+ const node = binding.identifier
425
+ if (node._slimReactive) return node._slimReactive
426
+ if (node._slimProps) return "props"
427
+ if (node._slimPropAlias !== undefined) return "alias"
428
+ return null
429
+ }
430
+
431
+ function readsReactive(path) {
432
+ if (path.isIdentifier()) return reactiveKind(path) !== null
433
+ if (path.isFunction()) return false
434
+ let found = false
435
+ path.traverse({
436
+ Function(inner) { inner.skip() },
437
+ Identifier(inner) {
438
+ if (!inner.isReferencedIdentifier()) return
439
+ if (reactiveKind(inner) !== null) {
440
+ found = true
441
+ inner.stop()
442
+ }
443
+ }
444
+ })
445
+ return found
446
+ }
447
+
448
+ function keyName(key) {
449
+ if (t.isIdentifier(key)) return key.name
450
+ if (t.isStringLiteral(key)) return key.value
451
+ return null
452
+ }
453
+
454
+ function innerPath(path) {
455
+ const body = path.get("body")
456
+ if (!body.isBlockStatement()) return body.get("arguments.0")
457
+ const statement = body.get("body").find(item => item.isReturnStatement() && t.isCallExpression(item.node.argument))
458
+ return statement.get("argument.arguments.0")
459
+ }
460
+
461
+ function prepareDeclarations(statements) {
462
+ const declarationOf = statement => statement.isExportNamedDeclaration() ? statement.get("declaration") : statement
463
+
464
+ for (const statement of statements) {
465
+ const declaration = declarationOf(statement)
466
+ if (!declaration.node?.slimState) continue
467
+ const [declarator] = declaration.node.declarations
468
+ declarator.id._slimReactive = "signal"
469
+ declarator.init = call("__signal__", [declarator.init])
470
+ }
471
+
472
+ for (const statement of statements) {
473
+ const declaration = declarationOf(statement)
474
+ if (!declaration.isVariableDeclaration({ kind: "const" }) || declaration.node.slimState) continue
475
+ for (const declarator of declaration.get("declarations")) {
476
+ const { id: name, init } = declarator.node
477
+ if (!t.isIdentifier(name) || name.name.startsWith("__") || !init) continue
478
+ const injected = t.isCallExpression(init) && t.isIdentifier(init.callee, { name: "inject" })
479
+ if (!injected && !readsReactive(declarator.get("init"))) continue
480
+ name._slimReactive = "computed"
481
+ declarator.node.init = call("__computed__", [thunk(init)])
482
+ }
483
+ }
484
+ }
485
+
486
+ function prepare(path, compiler) {
487
+ const outer = path.node
488
+ const inner = innerPath(path)
489
+
490
+ const param = outer.params[0]
491
+ const target = t.isAssignmentPattern(param) ? param.left : param
492
+ if (t.isIdentifier(target)) target._slimProps = true
493
+ if (t.isObjectPattern(target)) {
494
+ for (const property of target.properties) {
495
+ const value = t.isAssignmentPattern(property.value) ? property.value.left : property.value
496
+ value._slimPropAlias = keyName(property.key)
497
+ }
498
+ }
499
+
500
+ prepareDeclarations(inner.get("body.body"))
501
+
502
+ const ctx = { scope: outer._slimComponent.bem, svg: false }
503
+ inner.node.body = compiler.nested(inner.node.body, ctx)
504
+ }
505
+
506
+ function passGetters(path) {
507
+ path.traverse({
508
+ CallExpression(call) {
509
+ const callee = call.node.callee
510
+ if (t.isIdentifier(callee, { name: "provide" }) && call.node.arguments.length === 2) {
511
+ const value = call.get("arguments.1")
512
+ if (!value.isFunction() && readsReactive(value)) value.replaceWith(call_("__live__", [thunk(value.node)]))
513
+ return
514
+ }
515
+ if (!t.isIdentifier(callee) || !/^[A-Z]/.test(callee.name) || NOT_COMPONENTS.has(callee.name)) return
516
+ const argument = call.get("arguments.0")
517
+ if (!argument?.node || !argument.isObjectExpression()) return
518
+ for (const property of argument.get("properties")) {
519
+ if (!property.isObjectProperty()) continue
520
+ const value = property.get("value")
521
+ if (value.isFunction() || !readsReactive(value)) continue
522
+ const { key, computed } = property.node
523
+ property.replaceWith(t.objectMethod("get", key, [], t.blockStatement([t.returnStatement(value.node)]), computed))
524
+ }
525
+ }
526
+ })
527
+ }
528
+
529
+ const COMPARISONS = new Set(["==", "===", "!=", "!=="])
530
+
531
+ function changesThrough(ref) {
532
+ let top = ref
533
+ while ((top.parentPath.isMemberExpression() || top.parentPath.isOptionalMemberExpression()) &&
534
+ top.parentPath.node.object === top.node) top = top.parentPath
535
+ if (top === ref) return false
536
+ const outer = top.parentPath
537
+ return (outer.isAssignmentExpression() && outer.node.left === top.node) || outer.isUpdateExpression() ||
538
+ outer.isUnaryExpression({ operator: "delete" }) ||
539
+ ((outer.isCallExpression() || outer.isOptionalCallExpression()) && outer.node.callee === top.node && !readsOnly(top.node))
540
+ }
541
+
542
+ function checkAliases(path, fail) {
543
+ path.traverse({
544
+ VariableDeclarator(declarator) {
545
+ const { id: name, init } = declarator.node
546
+ if (!t.isIdentifier(name) || !t.isIdentifier(init) || name._slimReactive) return
547
+ const kind = reactiveKind(declarator.get("init"))
548
+ if (kind !== "signal" && kind !== "computed") return
549
+ const binding = declarator.scope.getBinding(name.name)
550
+ const changed = binding?.referencePaths.find(changesThrough)
551
+ if (changed) {
552
+ fail(changed.node, `"${name.name}" holds the state "${init.name}": a change through "${name.name}" doesn't update the page — change "${init.name}" itself`)
553
+ }
554
+ }
555
+ })
556
+ }
557
+
558
+ function rewrite(path, fail) {
559
+ const leaves = []
560
+ const mutations = []
561
+ const selections = []
562
+
563
+ checkAliases(path, fail)
564
+
565
+ path.traverse({
566
+ Identifier(ref) {
567
+ const node = ref.node
568
+ if (node._slimDone) return
569
+ const binding = ref.scope.getBinding(node.name)
570
+ if (binding?.identifier === node) return
571
+ const kind = reactiveKind(ref)
572
+ if (kind === null || kind === "props") return
573
+
574
+ const parent = ref.parentPath
575
+ if (parent.isExportSpecifier()) return
576
+ const write = (parent.isAssignmentExpression() && parent.node.left === node) || parent.isUpdateExpression()
577
+ if (!write && !ref.isReferencedIdentifier()) return
578
+
579
+ if (kind === "alias") {
580
+ if (write) fail(node, `"${node.name}" is a prop and can't be assigned: copy it into a state or a let first`)
581
+ leaves.push([ref, t.memberExpression(done("__props__"), id(binding.identifier._slimPropAlias))])
582
+ return
583
+ }
584
+
585
+ if (kind === "signal" && parent.isBinaryExpression() && COMPARISONS.has(parent.node.operator) &&
586
+ !referencesAny(parent.node[ref.key === "left" ? "right" : "left"], new Set([node.name])) &&
587
+ ref.findParent(ancestor => ancestor.node._slimListRow)) {
588
+ selections.push([parent, ref.key === "left" ? "right" : "left", node.name])
589
+ return
590
+ }
591
+
592
+ leaves.push([ref, t.memberExpression(done(node.name), id("v"))])
593
+ if (write) return
594
+
595
+ let top = ref
596
+ let depth = 0
597
+ while ((top.parentPath.isMemberExpression() || top.parentPath.isOptionalMemberExpression()) &&
598
+ top.parentPath.node.object === top.node) {
599
+ top = top.parentPath
600
+ depth++
601
+ }
602
+ if (top === ref) return
603
+ const outer = top.parentPath
604
+ const changes = (outer.isAssignmentExpression() && outer.node.left === top.node) ||
605
+ (outer.isUpdateExpression()) ||
606
+ (outer.isUnaryExpression({ operator: "delete" })) ||
607
+ ((outer.isCallExpression() || outer.isOptionalCallExpression()) && outer.node.callee === top.node && !readsOnly(top.node))
608
+ if (changes && kind === "computed") {
609
+ fail(node, `"${node.name}" is recomputed from a state or props, a change to it is lost on the next update — change what it comes from, or declare it with state`)
610
+ }
611
+ if (changes) mutations.push([outer, node.name, depth >= 2 ? ref.parentPath : null])
612
+ }
613
+ })
614
+
615
+ for (const [ref, value] of leaves) {
616
+ const parent = ref.parent
617
+ if (t.isObjectProperty(parent) && parent.shorthand && parent.value === ref.node) parent.shorthand = false
618
+ ref.replaceWith(value)
619
+ }
620
+ for (const [comparison, other, name] of selections) {
621
+ const { operator } = comparison.node
622
+ const test = call("__is__", [done(name), comparison.node[other], t.booleanLiteral(operator.length === 3)])
623
+ comparison.replaceWith(operator[0] === "!" ? t.unaryExpression("!", test) : test)
624
+ }
625
+ mutations.sort((a, b) => b[0].getAncestry().length - a[0].getAncestry().length)
626
+ for (const [target, name, item] of mutations) {
627
+ if (!item) {
628
+ target.replaceWith(call("__mut__", [done(name), target.node]))
629
+ continue
630
+ }
631
+ const object = item.node
632
+ item.replaceWith(id("__o__"))
633
+ target.replaceWith(call("__mut_deep__", [done(name), t.arrowFunctionExpression([id("__o__")], target.node), object]))
634
+ }
635
+ }
636
+
637
+ function propsParameter(path) {
638
+ const outer = path.node
639
+ const param = outer.params[0]
640
+ const target = t.isAssignmentPattern(param) ? param.left : param
641
+ if (!t.isObjectPattern(target)) return
642
+
643
+ const defaults = target.properties
644
+ .filter(property => t.isAssignmentPattern(property.value))
645
+ .map(property => t.objectProperty(t.stringLiteral(keyName(property.key)), thunk(property.value.right)))
646
+ outer.params[0] = t.assignmentPattern(id("__props__"), t.objectExpression([]))
647
+ if (defaults.length === 0) return
648
+
649
+ const inner = innerPath(path).node
650
+ inner.body.body.unshift(t.expressionStatement(t.assignmentExpression("=", id("__props__"),
651
+ call("__defaults__", [id("__props__"), t.objectExpression(defaults)]))))
652
+ }
653
+
654
+
655
+ const exportsCache = new Map()
656
+
657
+ function referencesAny(node, names) {
658
+ if (!isNode(node) || t.isFunction(node)) return false
659
+ if (t.isIdentifier(node) && names.has(node.name)) return true
660
+ for (const [key, value] of Object.entries(node)) {
661
+ if (SKIP_KEYS.has(key)) continue
662
+ if (Array.isArray(value) ? value.some(child => referencesAny(child, names)) : referencesAny(value, names)) return true
663
+ }
664
+ return false
665
+ }
666
+
667
+ export function reactiveExports(file) {
668
+ let stat
669
+ try {
670
+ stat = fs.statSync(file)
671
+ } catch {
672
+ return new Map()
673
+ }
674
+ const cached = exportsCache.get(file)
675
+ if (cached && cached.mtime === stat.mtimeMs) return cached.exports
676
+
677
+ const exports = new Map()
678
+ let program
679
+ try {
680
+ program = parseSlim(fs.readFileSync(file, "utf8"), file).program
681
+ } catch {
682
+ exportsCache.set(file, { mtime: stat.mtimeMs, exports })
683
+ return exports
684
+ }
685
+
686
+ const local = new Map()
687
+ for (const statement of program.body) {
688
+ const declaration = statement.type === "ExportNamedDeclaration" ? statement.declaration : statement
689
+ if (declaration?.type !== "VariableDeclaration") continue
690
+ for (const declarator of declaration.declarations) {
691
+ if (declarator.id.type !== "Identifier") continue
692
+ const name = declarator.id.name
693
+ if (declaration.slimState) local.set(name, "signal")
694
+ else if (declaration.kind === "const" && referencesAny(declarator.init, local)) local.set(name, "computed")
695
+ else continue
696
+ if (statement.type === "ExportNamedDeclaration") exports.set(name, local.get(name))
697
+ }
698
+ }
699
+ for (const statement of program.body) {
700
+ if (statement.type !== "ExportNamedDeclaration" || statement.declaration || statement.source) continue
701
+ for (const specifier of statement.specifiers) {
702
+ const exported = specifier.exported.name ?? specifier.exported.value
703
+ if (local.has(specifier.local.name)) exports.set(exported, local.get(specifier.local.name))
704
+ }
705
+ }
706
+
707
+ exportsCache.set(file, { mtime: stat.mtimeMs, exports })
708
+ return exports
709
+ }
710
+
711
+ export function compileReactivity(ast, code, { importedReactive: imported = new Map() } = {}) {
712
+ const fail = (node, message) => { throw slimSyntaxError(code, node.start ?? 0, message) }
713
+ const templates = []
714
+ const program = {
715
+ fail,
716
+ template(roots, svg) {
717
+ const name = `__tpl${templates.length + 1}__`
718
+ const args = [t.valueToNode(roots)]
719
+ if (svg) args.push(t.booleanLiteral(true))
720
+ const declaration = t.variableDeclaration("const", [t.variableDeclarator(id(name), call("__template__", args))])
721
+ declaration._slimTypeSlots = true
722
+ templates.push(declaration)
723
+ return name
724
+ }
725
+ }
726
+ const compiler = new MarkupCompiler(program)
727
+ importedReactive = imported
728
+
729
+ const pass = visit => {
730
+ traverse.cache.clear()
731
+ traverse(ast, { Program: visit })
732
+ }
733
+ const components = programPath => {
734
+ const found = []
735
+ programPath.traverse({
736
+ Function(path) {
737
+ if (!path.node._slimComponent) return
738
+ found.push(path)
739
+ path.skip()
740
+ }
741
+ })
742
+ return found
743
+ }
744
+
745
+ const moduleStates = ast.program.body.some(statement => (statement.declaration ?? statement).slimState)
746
+ let found = moduleStates || importedReactive.size > 0
747
+ pass(programPath => {
748
+ if (moduleStates) prepareDeclarations(programPath.get("body"))
749
+ for (const path of components(programPath)) {
750
+ found = true
751
+ prepare(path, compiler)
752
+ }
753
+ })
754
+ if (!found) return
755
+
756
+ pass(passGetters)
757
+ pass(programPath => {
758
+ rewrite(programPath, fail)
759
+ for (const path of components(programPath)) {
760
+ propsParameter(path)
761
+ for (const statement of innerPath(path).node.body.body) {
762
+ if (statement.slimState) statement.kind = "const"
763
+ }
764
+ }
765
+ for (const statement of ast.program.body) {
766
+ const declaration = statement.declaration ?? statement
767
+ if (declaration.slimState) declaration.kind = "const"
768
+ }
769
+ })
770
+ traverse.cache.clear()
771
+ importedReactive = new Map()
772
+
773
+ ast.program.body.unshift(...templates)
774
+ }