ferrovue 0.1.0 → 0.2.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/dist/script.js ADDED
@@ -0,0 +1,316 @@
1
+ /* `<script setup>` read: what the server evaluates, and what stays on the client. */
2
+ import { basename } from "node:path";
3
+ import { fail, GenError, snake, STR } from "./model.js";
4
+ import { CONFIG_FILE, ctx } from "./context.js";
5
+ import { definePropsType } from "./typescript.js";
6
+ import { expr, fieldVal, storeGetter, theRoute } from "./expr.js";
7
+ import { collected, heldList } from "./lists.js";
8
+ import { storeImport } from "./stores.js";
9
+ import { bare, operand, UNARY } from "./parens.js";
10
+ /** Lifecycle hooks, which never run on the server: setup may register them freely. */
11
+ export const CLIENT_HOOKS = new Set([
12
+ "onMounted", "onBeforeMount", "onUnmounted", "onBeforeUnmount", "onUpdated", "onBeforeUpdate",
13
+ "onActivated", "onDeactivated", "onErrorCaptured", "onRenderTracked", "onRenderTriggered",
14
+ ]);
15
+ /** Compiler macros and calls with no effect on the server's render. */
16
+ export const INERT_CALLS = new Set(["defineEmits", "defineSlots", "defineOptions", "defineExpose", "defineProps", "withDefaults", "provide"]);
17
+ /** A statement in setup that is a call on its own: allowed only when it cannot change the render. */
18
+ export function setupStatement(comp, st) {
19
+ const c = st.expression;
20
+ const name = c?.type === "CallExpression" && c.callee.type === "Identifier" ? c.callee.name : null;
21
+ if (name !== null && (CLIENT_HOOKS.has(name) || INERT_CALLS.has(name)))
22
+ return;
23
+ if (name === "watch") {
24
+ // A watcher's callback runs on the server only with `immediate`, and could then change state.
25
+ const options = c.arguments[2];
26
+ const immediate = options?.type === "ObjectExpression" && options.properties.some((p) => p.type === "ObjectProperty" && (p.key.name ?? p.key.value) === "immediate" && !(p.value.type === "BooleanLiteral" && !p.value.value));
27
+ if (!immediate)
28
+ return;
29
+ fail(comp, "`watch` with `immediate` runs on the server, where its effect is not translated", st);
30
+ }
31
+ if (name === "watchEffect" || name === "watchSyncEffect" || name === "watchPostEffect") {
32
+ fail(comp, `\`${name}\` runs once on the server, where its effect is not translated; use \`watch\` or \`onMounted\``, st);
33
+ }
34
+ if (name === "onServerPrefetch")
35
+ fail(comp, "`onServerPrefetch` fetches on the server; pass the data in as props instead", st);
36
+ fail(comp, `\`${st.expression?.type === "CallExpression" ? `${name ?? "a call"}()` : st.expression?.type}\` in setup could change what renders, and is not translated`, st);
37
+ }
38
+ /** What a setup binding's value is computed from: `ref(x)` and `shallowRef(x)` hold `x`,
39
+ * `computed(() => x)` is `x`, and a plain `const y = x` is `x`. */
40
+ export function setupSource(init) {
41
+ if (init.type === "CallExpression" && init.callee.type === "Identifier") {
42
+ const name = init.callee.name;
43
+ if ((name === "ref" || name === "shallowRef") && init.arguments.length === 1)
44
+ return init.arguments[0];
45
+ if (name === "computed") {
46
+ const fn = init.arguments[0];
47
+ if (fn?.type !== "ArrowFunctionExpression" && fn?.type !== "FunctionExpression")
48
+ return null;
49
+ if (fn.body.type !== "BlockStatement")
50
+ return fn.body;
51
+ const only = fn.body.body.length === 1 ? fn.body.body[0] : null;
52
+ return only?.type === "ReturnStatement" && only.argument ? only.argument : null;
53
+ }
54
+ }
55
+ if (init.type === "TSAsExpression" || init.type === "TSSatisfiesExpression" || init.type === "TSNonNullExpression")
56
+ return setupSource(init.expression);
57
+ return init;
58
+ }
59
+ /** The names a destructuring pattern binds. */
60
+ export function patternNames(p) {
61
+ switch (p?.type) {
62
+ case "Identifier":
63
+ return [p.name];
64
+ case "ObjectPattern":
65
+ return p.properties.flatMap((q) => patternNames(q.type === "RestElement" ? q.argument : q.value));
66
+ case "ArrayPattern":
67
+ return p.elements.flatMap((q) => (q ? patternNames(q) : []));
68
+ case "AssignmentPattern":
69
+ return patternNames(p.left);
70
+ case "RestElement":
71
+ return patternNames(p.argument);
72
+ default:
73
+ return [];
74
+ }
75
+ }
76
+ export function scopeFor(comp, ast, components) {
77
+ const scope = {
78
+ comp,
79
+ components,
80
+ setup: new Map(),
81
+ children: new Map(),
82
+ helpers: new Map(),
83
+ locals: new Map(),
84
+ propsIdent: null,
85
+ refs: new Set(),
86
+ clientOnly: new Map(),
87
+ narrowed: new Map(),
88
+ selfAlias: { name: null },
89
+ helperBytes: { n: 0 },
90
+ router: new Map(),
91
+ directives: new Map(),
92
+ i18nT: new Set(),
93
+ fill: false,
94
+ vnode: false,
95
+ attrs: comp.inherits ? "fv_attrs" : null,
96
+ sid: null,
97
+ };
98
+ const lets = [];
99
+ const storeHooks = new Map();
100
+ let storeToRefsName = null;
101
+ let useRouteName = null;
102
+ let useI18nName = null;
103
+ /** Setup bindings holding a store, by name. */
104
+ const storeValues = new Map();
105
+ for (const st of ast) {
106
+ if (st.type === "ImportDeclaration") {
107
+ const from = st.source.value;
108
+ if (from.endsWith(".vue")) {
109
+ const def = st.specifiers.find((x) => x.type === "ImportDefaultSpecifier");
110
+ if (def)
111
+ scope.children.set(def.local.name, basename(from, ".vue"));
112
+ }
113
+ else if (storeImport(comp, from)) {
114
+ for (const sp of st.specifiers) {
115
+ const hook = sp.type === "ImportSpecifier" ? (sp.imported.name ?? sp.imported.value) : null;
116
+ // A type from the store's file, which `readComponent` has already resolved.
117
+ if (st.importKind === "type" || sp.importKind === "type" || (hook !== null && ctx.storeStructs.has(hook)))
118
+ continue;
119
+ const store = hook ? ctx.stores.get(hook) : undefined;
120
+ if (!store || store.module !== storeImport(comp, from))
121
+ fail(comp, "import a store by its `use…` hook", sp);
122
+ storeHooks.set(sp.local.name, store);
123
+ }
124
+ }
125
+ else if (from === "vue-router") {
126
+ for (const sp of st.specifiers) {
127
+ const name = sp.type === "ImportSpecifier" ? (sp.imported.name ?? sp.imported.value) : null;
128
+ if (name === "useRoute")
129
+ useRouteName = sp.local.name;
130
+ else if (name === "RouterLink" || name === "RouterView")
131
+ scope.router.set(sp.local.name, name);
132
+ else
133
+ scope.clientOnly.set(sp.local.name, `\`${name}\` from vue-router does not run on the server`);
134
+ }
135
+ }
136
+ else if (from === "vue-i18n") {
137
+ for (const sp of st.specifiers) {
138
+ const name = sp.type === "ImportSpecifier" ? (sp.imported.name ?? sp.imported.value) : null;
139
+ if (name === "useI18n")
140
+ useI18nName = sp.local.name;
141
+ else
142
+ scope.clientOnly.set(sp.local.name, `\`${name}\` from vue-i18n does not run on the server`);
143
+ }
144
+ }
145
+ else if (from === "pinia") {
146
+ for (const sp of st.specifiers) {
147
+ const name = sp.type === "ImportSpecifier" ? (sp.imported.name ?? sp.imported.value) : null;
148
+ if (name === "storeToRefs")
149
+ storeToRefsName = sp.local.name;
150
+ else
151
+ scope.clientOnly.set(sp.local.name, `\`${name}\` from Pinia does not run on the server`);
152
+ }
153
+ }
154
+ else if (ctx.helperModule !== null && from === ctx.helperModule) {
155
+ for (const sp of st.specifiers) {
156
+ if (!ctx.helpers[sp.imported.name])
157
+ fail(comp, `\`${sp.imported.name}\` has no Rust twin: add it to \`helpers.functions\` in ${CONFIG_FILE}`, sp);
158
+ scope.helpers.set(sp.local.name, sp.imported.name);
159
+ }
160
+ }
161
+ continue;
162
+ }
163
+ if (st.type === "FunctionDeclaration") {
164
+ if (st.id)
165
+ scope.clientOnly.set(st.id.name, "it is a function, which only an event handler may call");
166
+ continue;
167
+ }
168
+ const decl = st.type === "ExportNamedDeclaration" ? st.declaration : st;
169
+ if (decl?.type === "TSInterfaceDeclaration" || decl?.type === "TSTypeAliasDeclaration")
170
+ continue;
171
+ if (st.type === "ExpressionStatement") {
172
+ setupStatement(comp, st);
173
+ continue;
174
+ }
175
+ // Setup runs on the server too, so a statement there can change what renders: `x.value = ...`
176
+ // after a `ref`, an `if`, a loop. None of it is translated, so none of it may exist.
177
+ if (st.type !== "VariableDeclaration")
178
+ fail(comp, `\`${st.type}\` in setup is not supported`, st);
179
+ for (const d of st.declarations) {
180
+ const init0 = d.init;
181
+ // `const { size = "md", label: l } = defineProps<...>()`: each name reads that prop, whose
182
+ // default `compileScript` already resolved.
183
+ if (d.id.type === "ObjectPattern" && definePropsType(init0)) {
184
+ for (const p of d.id.properties) {
185
+ if (p.type !== "ObjectProperty" || p.computed)
186
+ fail(comp, "destructured props are plain names: `...rest` has no Rust type", p);
187
+ const key = p.key.type === "Identifier" ? p.key.name : p.key.value;
188
+ const local = p.value.type === "AssignmentPattern" ? p.value.left : p.value;
189
+ if (local.type !== "Identifier")
190
+ fail(comp, "destructured props are plain names", p);
191
+ scope.setup.set(local.name, fieldVal(comp, "props", { k: "struct", name: "Props" }, key, p));
192
+ }
193
+ continue;
194
+ }
195
+ const calls = (name) => name !== null && init0?.type === "CallExpression" && init0.callee.type === "Identifier" && init0.callee.name === name;
196
+ // `const { t, locale } = useI18n()`: \`t\` translates, \`locale\` is the request's locale.
197
+ if (d.id.type === "ObjectPattern" && calls(useI18nName)) {
198
+ for (const p of d.id.properties) {
199
+ if (p.type !== "ObjectProperty" || p.computed || p.value.type !== "Identifier") {
200
+ fail(comp, "`useI18n()` is destructured into plain names", p);
201
+ }
202
+ const key = p.key.name ?? p.key.value;
203
+ if (key === "t")
204
+ scope.i18nT.add(p.value.name);
205
+ else if (key === "locale") {
206
+ scope.setup.set(p.value.name, { code: "fv_i18n.locale()", ty: STR });
207
+ scope.refs.add(p.value.name);
208
+ }
209
+ else
210
+ scope.clientOnly.set(p.value.name, `\`${key}\` from \`useI18n()\` does not run on the server`);
211
+ }
212
+ comp.readsI18n = true;
213
+ continue;
214
+ }
215
+ // `const { density, label: l } = storeToRefs(prefs)`: each name is that field of the state.
216
+ if (d.id.type === "ObjectPattern" && calls(storeToRefsName)) {
217
+ const arg = init0.arguments[0];
218
+ const store = arg?.type === "Identifier" ? storeValues.get(arg.name) : undefined;
219
+ if (!store || init0.arguments.length !== 1)
220
+ fail(comp, "`storeToRefs` takes a store bound in this setup", d);
221
+ for (const p of d.id.properties) {
222
+ if (p.type !== "ObjectProperty" || p.computed || p.value.type !== "Identifier") {
223
+ fail(comp, "`storeToRefs` is destructured into plain names", p);
224
+ }
225
+ const key = p.key.type === "Identifier" ? p.key.name : p.key.value;
226
+ const state = { code: `fv_stores.${store.field}`, ty: { k: "struct", name: store.state, store: true } };
227
+ scope.setup.set(p.value.name, storeGetter(scope, state, key, p) ?? fieldVal(comp, state.code, state.ty, key, p));
228
+ scope.refs.add(p.value.name);
229
+ }
230
+ comp.readsStores = true;
231
+ continue;
232
+ }
233
+ if (d.id.type !== "Identifier") {
234
+ // Destructuring anything else: client-side state the template may not read.
235
+ for (const name of patternNames(d.id))
236
+ scope.clientOnly.set(name, "it is destructured from a value the server does not have");
237
+ continue;
238
+ }
239
+ const local = d.id.name;
240
+ // `const prefs = usePrefs()`: the store's state, as the server was given it.
241
+ const hook = init0?.type === "CallExpression" && init0.callee.type === "Identifier" ? storeHooks.get(init0.callee.name) : undefined;
242
+ if (hook) {
243
+ if (init0.arguments.length)
244
+ fail(comp, "a store hook takes no arguments", d);
245
+ storeValues.set(local, hook);
246
+ scope.setup.set(local, { code: `fv_stores.${hook.field}`, ty: { k: "struct", name: hook.state, store: true } });
247
+ comp.readsStores = true;
248
+ continue;
249
+ }
250
+ // `const route = useRoute()`: the reader's location.
251
+ if (useRouteName !== null && init0?.type === "CallExpression" && init0.callee.type === "Identifier" && init0.callee.name === useRouteName) {
252
+ scope.setup.set(local, theRoute(scope, d));
253
+ continue;
254
+ }
255
+ // `const model = defineModel<string>()`: the model's prop.
256
+ const model = comp.models.get(local);
257
+ if (model !== undefined) {
258
+ scope.setup.set(local, fieldVal(comp, "props", { k: "struct", name: "Props" }, model, d));
259
+ scope.refs.add(local);
260
+ continue;
261
+ }
262
+ if (!init0) {
263
+ scope.clientOnly.set(local, "it has no initial value");
264
+ continue;
265
+ }
266
+ if (definePropsType(init0)) {
267
+ scope.propsIdent = local;
268
+ continue;
269
+ }
270
+ const source = setupSource(init0);
271
+ const isRef = init0.type === "CallExpression" && init0.callee.type === "Identifier" && ["ref", "shallowRef", "computed"].includes(init0.callee.name);
272
+ if (isRef)
273
+ scope.refs.add(local);
274
+ if (!source) {
275
+ scope.clientOnly.set(local, "it is not a value the server computes: only `ref(…)`, `computed(() => …)` and plain expressions are");
276
+ continue;
277
+ }
278
+ // Evaluated once, as setup is on the server. A value the server cannot evaluate is client-side
279
+ // state — a template ref, an element, a `reactive` object — which the template may still name
280
+ // from an event handler; a reference the server needs fails in `expr` with this reason.
281
+ let v;
282
+ try {
283
+ v = expr(scope, source);
284
+ }
285
+ catch (e) {
286
+ if (!(e instanceof GenError))
287
+ throw e;
288
+ scope.clientOnly.set(local, e.message.replace(/^[^:]*: /, ""));
289
+ continue;
290
+ }
291
+ if (v.ty.k === "undef") {
292
+ scope.setup.set(local, v);
293
+ continue;
294
+ }
295
+ const name = `s_${snake(local).replace(/^r#/, "")}`;
296
+ const lone = v.lone ? { lone: true } : {};
297
+ // A computed list is kept as its items, and read again by item.
298
+ if (v.ty.k === "list" && v.iter !== undefined) {
299
+ lets.push(`let ${name} = ${collected(v)};`);
300
+ scope.setup.set(local, heldList(name, v.ty.of, v.lone));
301
+ continue;
302
+ }
303
+ // An optional string a temporary owns is kept as that `Option<Cow>`.
304
+ if (v.held !== undefined) {
305
+ lets.push(`let ${name} = ${v.held};`);
306
+ scope.setup.set(local, { code: `${name}.as_deref()`, ty: v.ty, ...lone });
307
+ continue;
308
+ }
309
+ // A list, a record or an object is a place in the props: borrowed, never moved out of them.
310
+ const place = v.ty.k === "list" || v.ty.k === "record" || v.ty.k === "struct" || v.ty.k === "child";
311
+ lets.push(`let ${name} = ${place ? `&${operand(v.code, UNARY)}` : bare(v.code)};`);
312
+ scope.setup.set(local, { code: name, ty: v.ty, ...lone, ...(v.konst !== undefined ? { konst: v.konst } : {}) });
313
+ }
314
+ }
315
+ return { scope, lets };
316
+ }
@@ -0,0 +1,6 @@
1
+ import { type Component } from "./model.ts";
2
+ /** The store module an import names, resolved and without its extension, when it is one. */
3
+ export declare function storeImport(comp: Component, from: string): string | null;
4
+ /** Every store in the configured directory, and the interfaces their files declare. */
5
+ export declare function readStores(root: string, dir: string): void;
6
+ export declare function storeHome(file: string): Component;
package/dist/stores.js ADDED
@@ -0,0 +1,227 @@
1
+ /* Pinia option stores: their state, its types, and their getters. */
2
+ import { parse as parseJs } from "@babel/parser";
3
+ import { readdirSync, readFileSync } from "node:fs";
4
+ import { basename, dirname, join, relative, resolve } from "node:path";
5
+ import { BOOL, fail, FLOAT, INT, opt, sameTy, snake, STR, tagAst, UNDEF } from "./model.js";
6
+ import { ctx } from "./context.js";
7
+ import { markStore, structOf, tyOfTs, typesImports } from "./typescript.js";
8
+ import { patternNames, setupStatement } from "./script.js";
9
+ /** The store module an import names, resolved and without its extension, when it is one. */
10
+ export function storeImport(comp, from) {
11
+ if (!from.startsWith(".") || ctx.stores.size === 0)
12
+ return null;
13
+ const target = resolve(ctx.rootDir, dirname(comp.file), from).replace(/\.ts$/, "");
14
+ return [...ctx.stores.values()].some((s) => s.module === target) ? target : null;
15
+ }
16
+ /** Every store in the configured directory, and the interfaces their files declare. */
17
+ export function readStores(root, dir) {
18
+ ctx.stores = new Map();
19
+ ctx.storeStructs = new Map();
20
+ ctx.storeFiles = new Map();
21
+ const files = readdirSync(join(root, dir)).filter((f) => f.endsWith(".ts") && !f.endsWith(".test.ts")).toSorted();
22
+ for (const f of files) {
23
+ const path = join(root, dir, f);
24
+ const comp = storeHome(relative(root, path));
25
+ comp.source = readFileSync(path, "utf8");
26
+ const ast = parseJs(comp.source, { sourceType: "module", plugins: ["typescript"] }).program.body;
27
+ tagAst(ast, "source");
28
+ typesImports(comp, ast);
29
+ const decls = ast.map((st) => (st.type === "ExportNamedDeclaration" ? st.declaration : st)).filter(Boolean);
30
+ const interfaces = decls.filter((d) => d.type === "TSInterfaceDeclaration");
31
+ for (const d of interfaces) {
32
+ if (ctx.storeStructs.has(d.id.name))
33
+ fail(comp, `\`${d.id.name}\` is declared by another store too`, d);
34
+ ctx.storeStructs.set(d.id.name, { name: d.id.name, fields: [] });
35
+ ctx.storeFiles.set(d.id.name, comp.file);
36
+ }
37
+ for (const d of interfaces) {
38
+ const st = structOf(comp, d.id.name, d.body.body, ctx.storeStructs);
39
+ for (const field of st.fields)
40
+ field.ty = markStore(field.ty);
41
+ ctx.storeStructs.set(d.id.name, st);
42
+ }
43
+ for (const d of decls) {
44
+ if (d.type !== "VariableDeclaration")
45
+ continue;
46
+ for (const v of d.declarations) {
47
+ const init = v.init;
48
+ if (init?.type !== "CallExpression" || init.callee.type !== "Identifier" || init.callee.name !== "defineStore")
49
+ continue;
50
+ const [id, options] = init.arguments;
51
+ if (id?.type !== "StringLiteral")
52
+ fail(comp, "a store's id is a string literal", init);
53
+ if (options?.type === "ArrowFunctionExpression" || options?.type === "FunctionExpression") {
54
+ setupStore(comp, v.id.name, id.value, options, path);
55
+ continue;
56
+ }
57
+ if (options?.type !== "ObjectExpression")
58
+ fail(comp, "a store is `defineStore(id, { state, getters, actions })` or `defineStore(id, () => { … })`", init);
59
+ const state = options.properties.find((p) => (p.key?.name ?? p.key?.value) === "state");
60
+ const fn = state?.value ?? (state?.type === "ObjectMethod" ? state : null);
61
+ const ret = fn?.returnType?.typeAnnotation;
62
+ if (ret?.type !== "TSTypeReference" || !ctx.storeStructs.has(ret.typeName.name)) {
63
+ fail(comp, "a store's `state` declares its return type, an interface in the same file: `state: (): State => ({ … })`", state ?? init);
64
+ }
65
+ const getters = new Map();
66
+ const getterObj = options.properties.find((p) => (p.key?.name ?? p.key?.value) === "getters");
67
+ if (getterObj && getterObj.value?.type !== "ObjectExpression")
68
+ fail(comp, "a store's `getters` is an object literal", getterObj);
69
+ for (const g of getterObj?.value.properties ?? []) {
70
+ const getterFn = g.type === "ObjectMethod" ? g : g.value;
71
+ const name = g.key?.name ?? g.key?.value;
72
+ if (!getterFn || !["ArrowFunctionExpression", "FunctionExpression", "ObjectMethod"].includes(getterFn.type)) {
73
+ fail(comp, `getter \`${name}\` is a function of the state`, g);
74
+ }
75
+ let body = getterFn.body;
76
+ if (body.type === "BlockStatement") {
77
+ const only = body.body.length === 1 ? body.body[0] : null;
78
+ body = only?.type === "ReturnStatement" ? only.argument : null;
79
+ }
80
+ const param = getterFn.params[0];
81
+ // A getter the server cannot translate fails where a component reads it, not here.
82
+ getters.set(name, { param: param?.type === "Identifier" ? param.name : null, body, file: comp.file });
83
+ }
84
+ ctx.stores.set(v.id.name, {
85
+ hook: v.id.name,
86
+ id: id.value,
87
+ field: snake(id.value),
88
+ state: ret.typeName.name,
89
+ module: path.replace(/\.ts$/, ""),
90
+ getters,
91
+ });
92
+ }
93
+ }
94
+ }
95
+ }
96
+ /** A store file, as the thing its types are declared in: what errors name, and where they resolve. */
97
+ /** A setup store: \`defineStore(id, () => { …; return { … } })\`. The refs it returns are its state —
98
+ * typed by \`ref<T>(…)\`, or by the literal they start from — the computeds it returns its getters,
99
+ * and its functions actions, which only the client runs. */
100
+ function setupStore(comp, hook, id, fn, path) {
101
+ if (fn.body.type !== "BlockStatement")
102
+ fail(comp, "a setup store's function returns its state from a block: `() => { …; return { … } }`", fn);
103
+ const refs = new Map();
104
+ const computeds = new Map();
105
+ const others = new Set();
106
+ let returned = null;
107
+ for (const st of fn.body.body) {
108
+ if (st.type === "ReturnStatement") {
109
+ returned = st.argument;
110
+ continue;
111
+ }
112
+ if (st.type === "FunctionDeclaration") {
113
+ if (st.id)
114
+ others.add(st.id.name);
115
+ continue;
116
+ }
117
+ if (st.type === "ExpressionStatement") {
118
+ setupStatement(comp, st);
119
+ continue;
120
+ }
121
+ if (st.type !== "VariableDeclaration")
122
+ fail(comp, `\`${st.type}\` in a setup store is not supported`, st);
123
+ for (const d of st.declarations) {
124
+ if (d.id.type !== "Identifier") {
125
+ for (const name of patternNames(d.id))
126
+ others.add(name);
127
+ continue;
128
+ }
129
+ const init = d.init;
130
+ const callee = init?.type === "CallExpression" && init.callee.type === "Identifier" ? init.callee.name : null;
131
+ if (callee === "ref" || callee === "shallowRef") {
132
+ refs.set(d.id.name, refType(comp, init));
133
+ }
134
+ else if (callee === "computed") {
135
+ const getter = init.arguments[0];
136
+ let body = getter?.body;
137
+ if (body?.type === "BlockStatement") {
138
+ const only = body.body.length === 1 ? body.body[0] : null;
139
+ body = only?.type === "ReturnStatement" ? only.argument : null;
140
+ }
141
+ computeds.set(d.id.name, body);
142
+ }
143
+ else
144
+ others.add(d.id.name);
145
+ }
146
+ }
147
+ if (returned?.type !== "ObjectExpression")
148
+ fail(comp, "a setup store returns an object of its state, getters and actions", returned ?? fn);
149
+ const state = [];
150
+ const getters = new Map();
151
+ for (const p of returned.properties) {
152
+ if (p.type !== "ObjectProperty" || p.computed || p.value.type !== "Identifier")
153
+ fail(comp, "a setup store returns plain names: `{ count, doubled, increment }`", p);
154
+ const key = p.key.name ?? p.key.value;
155
+ const local = p.value.name;
156
+ if (refs.has(local))
157
+ state.push({ js: key, rust: snake(key), ty: markStore(refs.get(local)) });
158
+ else if (computeds.has(local))
159
+ getters.set(key, { param: null, body: computeds.get(local), file: comp.file, setup: true });
160
+ else if (!others.has(local))
161
+ fail(comp, `\`${local}\` is not declared in the store's function`, p);
162
+ }
163
+ const name = id.split(/[-_]/).map((w) => w.charAt(0).toUpperCase() + w.slice(1)).join("") + "State";
164
+ if (ctx.storeStructs.has(name))
165
+ fail(comp, `\`${name}\` names this setup store's state; rename the interface`, fn);
166
+ ctx.storeStructs.set(name, { name, fields: state });
167
+ ctx.storeFiles.set(name, comp.file);
168
+ ctx.stores.set(hook, { hook, id, field: snake(id), state: name, module: path.replace(/\.ts$/, ""), getters });
169
+ }
170
+ /** A setup store ref's type: \`ref<T>(…)\`, or what its initial literal is; optional when it has none. */
171
+ function refType(comp, init) {
172
+ const typed = init.typeParameters?.params?.[0];
173
+ const value = init.arguments[0];
174
+ if (typed) {
175
+ const ty = tyOfTs(comp, typed, ctx.storeStructs);
176
+ return value ? ty : opt(ty);
177
+ }
178
+ const literal = (n) => {
179
+ if (n?.type === "StringLiteral" || (n?.type === "TemplateLiteral" && n.expressions.length === 0))
180
+ return STR;
181
+ if (n?.type === "NumericLiteral")
182
+ return Number.isInteger(n.value) ? INT : FLOAT;
183
+ if (n?.type === "UnaryExpression" && n.operator === "-")
184
+ return literal(n.argument);
185
+ if (n?.type === "BooleanLiteral")
186
+ return BOOL;
187
+ if (n?.type === "ArrayExpression" && n.elements.length) {
188
+ const of = literal(n.elements[0]);
189
+ return of && n.elements.every((el) => sameTy(literal(el) ?? UNDEF, of)) ? { k: "list", of } : null;
190
+ }
191
+ return null;
192
+ };
193
+ return literal(value) ?? fail(comp, "a setup store's ref declares its type: `ref<string[]>([])`", init);
194
+ }
195
+ export function storeHome(file) {
196
+ return {
197
+ name: basename(file),
198
+ module: "stores",
199
+ file,
200
+ props: { name: "Props", fields: [] },
201
+ structs: ctx.storeStructs,
202
+ trustedName: null,
203
+ floatName: null,
204
+ childProps: new Map(),
205
+ imports: new Set(),
206
+ slotNames: [],
207
+ routerView: false,
208
+ routerLink: false,
209
+ readsRoute: false,
210
+ usesRoute: false,
211
+ readsStores: false,
212
+ usesStores: false,
213
+ readsI18n: false,
214
+ usesI18n: false,
215
+ readsTeleports: false,
216
+ usesTeleports: false,
217
+ models: new Map(),
218
+ aliases: new Map(),
219
+ importedTypes: new Map(),
220
+ slotShapes: new Map(),
221
+ scopeId: null,
222
+ slotted: false,
223
+ inheritAttrs: true,
224
+ inherits: false,
225
+ passesSlotIds: false,
226
+ };
227
+ }
@@ -0,0 +1,45 @@
1
+ import { type Component, type N, type Scope, type Ty, type Val } from "./model.ts";
2
+ import { Emitter } from "./emitter.ts";
3
+ /** One `${...}` inside a pushed template literal. */
4
+ export declare function slot(s: Scope, e: Emitter, n: N): void;
5
+ /** `isComment` in `@vue/server-renderer`: a chunk that is only comments and whitespace. */
6
+ export declare function isComment(text: string): boolean;
7
+ /** Whether a `_push` argument is content to `ssrRenderSlot`, rather than only comments. */
8
+ export declare function pushesContent(s: Scope, n: N): boolean;
9
+ export declare function push(s: Scope, e: Emitter, n: N): void;
10
+ export declare function renderChild(s: Scope, e: Emitter, n: N): void;
11
+ /** `name: value` in a struct literal, or the name alone when the value is a variable of that name. */
12
+ export declare function fieldInit(name: string, value: string): string;
13
+ /** Whether a component takes a `Slots` argument. */
14
+ export declare function takesSlots(c: Component): boolean;
15
+ /** The arguments after `props` that a component's `render` takes. */
16
+ export declare function extraParams(c: Component): string;
17
+ /** `render(out, props[, slots][, route])` for a child, with the slot content this template gives
18
+ * it as closures; `render_scoped`, with the scope ids its root is handed last, for a child that may
19
+ * be handed some. */
20
+ export declare function callChild(s: Scope, e: Emitter, child: Component, propsCode: string, slots: N, attrs: string | null): void;
21
+ /** The statements a parent's slot content pushes: the `if (_push)` half of its `_withCtx`. */
22
+ export declare function slotBody(s: Scope, value: N): N[];
23
+ /** A parent's slot content: what it pushes, and the parameter its scoped slot props are bound to
24
+ * (`_` when it takes none). */
25
+ export declare function slotContent(s: Scope, value: N): {
26
+ body: N[];
27
+ param: N;
28
+ };
29
+ /** Whether slot content always pushes something that is not a comment: a push of content outside
30
+ * any `if` or loop. Then nothing has to be decided at run time. */
31
+ export declare function staticallyFilled(s: Scope, body: N[]): boolean;
32
+ /** `RowSlotProps`, `RowSlot`: the names of a scoped slot's props struct and content type. */
33
+ export declare function slotTypeName(slotName: string, suffix: string): string;
34
+ /** Whether a scoped slot prop's Rust type borrows, and so needs the props' lifetime `'v`. */
35
+ export declare function slotFieldBorrows(ty: Ty): boolean;
36
+ /** A scoped slot prop's Rust type: a scalar copied, anything else borrowed from the render for `'v`. */
37
+ export declare function slotFieldTy(ty: Ty, comp: Component): string;
38
+ /** A value an outlet passes, as the scoped slot prop field holds it. */
39
+ export declare function slotFieldValue(s: Scope, v: Val, n: N): string;
40
+ /** `<slot name="x" :prop="…">fallback</slot>`: `ssrRenderSlot`, with the props a scoped slot passes. */
41
+ export declare function slotOutlet(s: Scope, e: Emitter, c: N): void;
42
+ /** A value into a child's props field, whose strings are `Cow`s. */
43
+ export declare function ownInto(comp: Component, v: Val, want: Ty, node: N): string;
44
+ export declare function statements(s: Scope, e: Emitter, body: N[]): void;
45
+ export declare function list(s: Scope, e: Emitter, c: N): void;