ferrovue 0.3.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (106) hide show
  1. package/README.md +225 -42
  2. package/dist/attrs.d.ts +3 -53
  3. package/dist/attrs.js +41 -469
  4. package/dist/calls.d.ts +4 -0
  5. package/dist/calls.js +221 -0
  6. package/dist/children.d.ts +16 -0
  7. package/dist/children.js +286 -0
  8. package/dist/classes.d.ts +13 -0
  9. package/dist/classes.js +176 -0
  10. package/dist/cli.js +31 -22
  11. package/dist/client.d.ts +35 -2
  12. package/dist/client.js +77 -14
  13. package/dist/compiler.d.ts +1 -1
  14. package/dist/compiler.js +31 -92
  15. package/dist/component.d.ts +3 -1
  16. package/dist/component.js +123 -104
  17. package/dist/constants.d.ts +42 -0
  18. package/dist/constants.js +292 -0
  19. package/dist/context.d.ts +29 -67
  20. package/dist/context.js +13 -38
  21. package/dist/diagnostics.d.ts +23 -0
  22. package/dist/diagnostics.js +30 -0
  23. package/dist/diff.d.ts +0 -3
  24. package/dist/diff.js +0 -9
  25. package/dist/emitter.d.ts +0 -8
  26. package/dist/emitter.js +0 -12
  27. package/dist/errors.d.ts +867 -0
  28. package/dist/errors.js +330 -0
  29. package/dist/expr.d.ts +1 -70
  30. package/dist/expr.js +142 -934
  31. package/dist/fallthrough.d.ts +9 -0
  32. package/dist/fallthrough.js +78 -0
  33. package/dist/fixture.d.ts +4 -10
  34. package/dist/fixture.js +38 -27
  35. package/dist/hydration.d.ts +15 -0
  36. package/dist/hydration.js +80 -0
  37. package/dist/index.d.ts +3 -0
  38. package/dist/index.js +2 -0
  39. package/dist/islands.d.ts +1 -0
  40. package/dist/islands.js +1 -0
  41. package/dist/link-router.d.ts +24 -0
  42. package/dist/link-router.js +36 -0
  43. package/dist/lists.d.ts +0 -11
  44. package/dist/lists.js +34 -60
  45. package/dist/loops.d.ts +3 -0
  46. package/dist/loops.js +168 -0
  47. package/dist/model.d.ts +46 -144
  48. package/dist/model.js +150 -18
  49. package/dist/narrowing.d.ts +27 -0
  50. package/dist/narrowing.js +157 -0
  51. package/dist/numbers.d.ts +8 -0
  52. package/dist/numbers.js +73 -0
  53. package/dist/parens.d.ts +0 -27
  54. package/dist/parens.js +0 -44
  55. package/dist/plugin.d.ts +84 -0
  56. package/dist/plugin.js +26 -0
  57. package/dist/plugins/client-only.d.ts +8 -0
  58. package/dist/plugins/client-only.js +107 -0
  59. package/dist/plugins/i18n.d.ts +23 -0
  60. package/dist/{i18n.js → plugins/i18n.js} +88 -31
  61. package/dist/plugins/index.d.ts +2 -0
  62. package/dist/plugins/index.js +10 -0
  63. package/dist/plugins/router-link.d.ts +8 -0
  64. package/dist/{router.js → plugins/router-link.js} +52 -91
  65. package/dist/plugins/router.d.ts +42 -0
  66. package/dist/plugins/router.js +256 -0
  67. package/dist/plugins/scoped.d.ts +12 -0
  68. package/dist/plugins/scoped.js +125 -0
  69. package/dist/plugins/shared-types.d.ts +2 -0
  70. package/dist/plugins/shared-types.js +7 -0
  71. package/dist/plugins/stores.d.ts +37 -0
  72. package/dist/plugins/stores.js +379 -0
  73. package/dist/plugins/teleport.d.ts +5 -0
  74. package/dist/plugins/teleport.js +55 -0
  75. package/dist/plugins/twins.d.ts +10 -0
  76. package/dist/plugins/twins.js +164 -0
  77. package/dist/routes.d.ts +10 -0
  78. package/dist/routes.js +6 -0
  79. package/dist/rust.d.ts +1 -7
  80. package/dist/rust.js +56 -174
  81. package/dist/script.d.ts +3 -6
  82. package/dist/script.js +127 -140
  83. package/dist/settle.d.ts +6 -0
  84. package/dist/settle.js +34 -0
  85. package/dist/slots.d.ts +13 -0
  86. package/dist/slots.js +160 -0
  87. package/dist/strings.d.ts +13 -0
  88. package/dist/strings.js +208 -0
  89. package/dist/styles.d.ts +14 -0
  90. package/dist/styles.js +181 -0
  91. package/dist/template.d.ts +1 -42
  92. package/dist/template.js +25 -749
  93. package/dist/testing.d.ts +2 -0
  94. package/dist/testing.js +4 -10
  95. package/dist/types.d.ts +2 -0
  96. package/dist/typescript.d.ts +2 -14
  97. package/dist/typescript.js +53 -59
  98. package/dist/vite.d.ts +2 -1
  99. package/dist/vite.js +11 -32
  100. package/package.json +15 -6
  101. package/dist/i18n.d.ts +0 -27
  102. package/dist/router.d.ts +0 -17
  103. package/dist/scoped.d.ts +0 -24
  104. package/dist/scoped.js +0 -177
  105. package/dist/stores.d.ts +0 -6
  106. package/dist/stores.js +0 -229
package/dist/script.js CHANGED
@@ -1,42 +1,37 @@
1
- /* `<script setup>` read: what the server evaluates, and what stays on the client. */
2
1
  import { basename } from "node:path";
3
- import { fail, GenError, snake, STR, takesAttrs } from "./model.js";
2
+ import { fail, nothing, GenError, snake, takesAttrs, UNDEF } from "./model.js";
4
3
  import { CONFIG_FILE, ctx } from "./context.js";
5
- import { definePropsType } from "./typescript.js";
6
- import { expr, fieldVal, storeGetter, theRoute } from "./expr.js";
4
+ import { definePropsType, resolveImport, tyOfTs } from "./typescript.js";
5
+ import { constOfDecl, declareConsts } from "./constants.js";
6
+ import { rustTy } from "./rust.js";
7
+ import { expr, fieldVal } from "./expr.js";
7
8
  import { collected, heldList } from "./lists.js";
8
- import { storeImport } from "./stores.js";
9
9
  import { bare, operand, UNARY } from "./parens.js";
10
- /** Lifecycle hooks, which never run on the server: setup may register them freely. */
10
+ import { known } from "./narrowing.js";
11
11
  export const CLIENT_HOOKS = new Set([
12
12
  "onMounted", "onBeforeMount", "onUnmounted", "onBeforeUnmount", "onUpdated", "onBeforeUpdate",
13
13
  "onActivated", "onDeactivated", "onErrorCaptured", "onRenderTracked", "onRenderTriggered",
14
14
  ]);
15
- /** Compiler macros and calls with no effect on the server's render. */
16
15
  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
16
  export function setupStatement(comp, st) {
19
17
  const c = st.expression;
20
18
  const name = c?.type === "CallExpression" && c.callee.type === "Identifier" ? c.callee.name : null;
21
19
  if (name !== null && (CLIENT_HOOKS.has(name) || INERT_CALLS.has(name)))
22
20
  return;
23
21
  if (name === "watch") {
24
- // A watcher's callback runs on the server only with `immediate`, and could then change state.
25
22
  const options = c.arguments[2];
26
23
  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
24
  if (!immediate)
28
25
  return;
29
- fail(comp, "`watch` with `immediate` runs on the server, where its effect is not translated", st);
26
+ fail(comp, "FV0102", "`watch` with `immediate` runs on the server, where its effect is not translated", st);
30
27
  }
31
28
  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);
29
+ fail(comp, "FV0103", `\`${name}\` runs once on the server, where its effect is not translated; use \`watch\` or \`onMounted\``, st);
33
30
  }
34
31
  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);
32
+ fail(comp, "FV0104", "`onServerPrefetch` fetches on the server; pass the data in as props instead", st);
33
+ fail(comp, "FV0105", `\`${st.expression?.type === "CallExpression" ? `${name ?? "a call"}()` : st.expression?.type}\` in setup could change what renders, and is not translated`, st);
37
34
  }
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
35
  export function setupSource(init) {
41
36
  if (init.type === "CallExpression" && init.callee.type === "Identifier") {
42
37
  const name = init.callee.name;
@@ -56,7 +51,23 @@ export function setupSource(init) {
56
51
  return setupSource(init.expression);
57
52
  return init;
58
53
  }
59
- /** The names a destructuring pattern binds. */
54
+ function localTy(ty, comp) {
55
+ return rustTy(ty, comp).replace(/\bCow<'a, /g, "std::borrow::Cow<").replace(/'a\b/g, "'_");
56
+ }
57
+ function emptyRef(comp, init) {
58
+ if (init?.type !== "CallExpression" || init.callee.type !== "Identifier" || !["ref", "shallowRef"].includes(init.callee.name))
59
+ return null;
60
+ const typed = init.typeParameters?.params?.[0];
61
+ const [value, ...rest] = init.arguments;
62
+ if (rest.length)
63
+ return null;
64
+ if (!value || (value.type === "Identifier" && value.name === "undefined"))
65
+ return { code: "None", ty: UNDEF };
66
+ if (!typed || value.type !== "ArrayExpression" || value.elements.length > 0)
67
+ return null;
68
+ const ty = tyOfTs(comp, typed, comp.structs);
69
+ return ty.k === "list" ? { code: `Vec::<${localTy(ty.of, comp)}>::new()`, ty } : null;
70
+ }
60
71
  export function patternNames(p) {
61
72
  switch (p?.type) {
62
73
  case "Identifier":
@@ -73,6 +84,46 @@ export function patternNames(p) {
73
84
  return [];
74
85
  }
75
86
  }
87
+ function asyncLoader(arg) {
88
+ if (arg?.type === "ObjectExpression") {
89
+ const loader = arg.properties.find((p) => p.type === "ObjectProperty" && !p.computed && (p.key.name ?? p.key.value) === "loader");
90
+ return loader?.value;
91
+ }
92
+ return arg;
93
+ }
94
+ /** The components `<script setup>` declares with `defineAsyncComponent(() => import("./X.vue"))`,
95
+ * by local name, each the name of the `.vue` file it loads. */
96
+ export function asyncChildren(comp, ast) {
97
+ const callees = new Set();
98
+ for (const st of ast) {
99
+ if (st.type !== "ImportDeclaration" || st.source.value !== "vue")
100
+ continue;
101
+ for (const sp of st.specifiers) {
102
+ if (sp.type === "ImportSpecifier" && (sp.imported.name ?? sp.imported.value) === "defineAsyncComponent")
103
+ callees.add(sp.local.name);
104
+ }
105
+ }
106
+ const found = new Map();
107
+ if (!callees.size)
108
+ return found;
109
+ for (const st of ast) {
110
+ if (st.type !== "VariableDeclaration")
111
+ continue;
112
+ for (const d of st.declarations) {
113
+ const init = d.init;
114
+ if (init?.type !== "CallExpression" || init.callee.type !== "Identifier" || !callees.has(init.callee.name))
115
+ continue;
116
+ const loader = asyncLoader(init.arguments[0]);
117
+ const imported = loader?.type === "ArrowFunctionExpression" && loader.params.length === 0 ? loader.body : null;
118
+ const spec = imported?.type === "ImportExpression" ? imported.source : imported?.type === "CallExpression" && imported.callee.type === "Import" ? imported.arguments[0] : null;
119
+ if (d.id.type !== "Identifier" || spec?.type !== "StringLiteral" || !spec.value.endsWith(".vue")) {
120
+ fail(comp, "FV0106", '`defineAsyncComponent` loads a component of this project, as `defineAsyncComponent(() => import("./Child.vue"))`', init);
121
+ }
122
+ found.set(d.id.name, basename(spec.value, ".vue"));
123
+ }
124
+ }
125
+ return found;
126
+ }
76
127
  export function scopeFor(comp, ast, components) {
77
128
  const scope = {
78
129
  comp,
@@ -87,25 +138,35 @@ export function scopeFor(comp, ast, components) {
87
138
  narrowed: new Map(),
88
139
  selfAlias: { name: null },
89
140
  helperBytes: { n: 0 },
90
- router: new Map(),
91
141
  directives: new Map(),
92
- i18nT: new Set(),
93
142
  fill: false,
94
143
  vnode: false,
95
- // A component a parent may pass attributes takes them with the scope ids, as one `fv::Attrs`.
96
144
  attrs: comp.inherits ? (takesAttrs(comp) ? "fv_attrs.ids()" : "fv_attrs") : null,
97
145
  fallthrough: takesAttrs(comp) ? "fv_attrs" : null,
98
146
  attrsBindings: new Set(),
147
+ slotsBindings: new Set(),
148
+ consts: new Map(),
99
149
  sid: null,
150
+ plugins: new Map(),
100
151
  };
152
+ for (const p of ctx.plugins)
153
+ if (p.scope)
154
+ scope.plugins.set(p, p.scope(scope));
155
+ const evaluable = (local, d, why) => {
156
+ try {
157
+ scope.consts.set(local, constOfDecl(d));
158
+ }
159
+ catch (e) {
160
+ if (!(e instanceof GenError))
161
+ throw e;
162
+ scope.clientOnly.set(local, `${why}: ${e.message.split("\n")[0]}`);
163
+ }
164
+ };
165
+ const locals = declareConsts(comp, ast);
101
166
  const lets = [];
102
- const storeHooks = new Map();
103
- let storeToRefsName = null;
104
- let useRouteName = null;
105
- let useI18nName = null;
167
+ const asyncs = asyncChildren(comp, ast);
106
168
  let useAttrsName = null;
107
- /** Setup bindings holding a store, by name. */
108
- const storeValues = new Map();
169
+ let useSlotsName = null;
109
170
  for (const st of ast) {
110
171
  if (st.type === "ImportDeclaration") {
111
172
  const from = st.source.value;
@@ -113,61 +174,37 @@ export function scopeFor(comp, ast, components) {
113
174
  const def = st.specifiers.find((x) => x.type === "ImportDefaultSpecifier");
114
175
  if (def)
115
176
  scope.children.set(def.local.name, basename(from, ".vue"));
177
+ continue;
116
178
  }
117
- else if (storeImport(comp, from)) {
179
+ if (ctx.plugins.some((p) => p.scriptImport?.(scope, st, from)))
180
+ continue;
181
+ if (from === "vue") {
118
182
  for (const sp of st.specifiers) {
119
- const hook = sp.type === "ImportSpecifier" ? (sp.imported.name ?? sp.imported.value) : null;
120
- // A type from the store's file, which `readComponent` has already resolved.
121
- if (st.importKind === "type" || sp.importKind === "type" || (hook !== null && ctx.storeStructs.has(hook)))
183
+ if (sp.type !== "ImportSpecifier")
122
184
  continue;
123
- const store = hook ? ctx.stores.get(hook) : undefined;
124
- if (!store || store.module !== storeImport(comp, from))
125
- fail(comp, "import a store by its `use…` hook", sp);
126
- storeHooks.set(sp.local.name, store);
127
- }
128
- }
129
- else if (from === "vue-router") {
130
- for (const sp of st.specifiers) {
131
- const name = sp.type === "ImportSpecifier" ? (sp.imported.name ?? sp.imported.value) : null;
132
- if (name === "useRoute")
133
- useRouteName = sp.local.name;
134
- else if (name === "RouterLink" || name === "RouterView")
135
- scope.router.set(sp.local.name, name);
136
- else
137
- scope.clientOnly.set(sp.local.name, `\`${name}\` from vue-router does not run on the server`);
138
- }
139
- }
140
- else if (from === "vue-i18n") {
141
- for (const sp of st.specifiers) {
142
- const name = sp.type === "ImportSpecifier" ? (sp.imported.name ?? sp.imported.value) : null;
143
- if (name === "useI18n")
144
- useI18nName = sp.local.name;
145
- else
146
- scope.clientOnly.set(sp.local.name, `\`${name}\` from vue-i18n does not run on the server`);
147
- }
148
- }
149
- else if (from === "vue") {
150
- for (const sp of st.specifiers) {
151
- if (sp.type === "ImportSpecifier" && (sp.imported.name ?? sp.imported.value) === "useAttrs")
185
+ const imported = sp.imported.name ?? sp.imported.value;
186
+ if (imported === "useAttrs")
152
187
  useAttrsName = sp.local.name;
153
- }
154
- }
155
- else if (from === "pinia") {
156
- for (const sp of st.specifiers) {
157
- const name = sp.type === "ImportSpecifier" ? (sp.imported.name ?? sp.imported.value) : null;
158
- if (name === "storeToRefs")
159
- storeToRefsName = sp.local.name;
160
- else
161
- scope.clientOnly.set(sp.local.name, `\`${name}\` from Pinia does not run on the server`);
188
+ if (imported === "useSlots")
189
+ useSlotsName = sp.local.name;
162
190
  }
163
191
  }
164
192
  else if (ctx.helperModule !== null && from === ctx.helperModule) {
165
193
  for (const sp of st.specifiers) {
166
194
  if (!ctx.helpers[sp.imported.name])
167
- fail(comp, `\`${sp.imported.name}\` has no Rust twin: add it to \`helpers.functions\` in ${CONFIG_FILE}`, sp);
195
+ fail(comp, "FV1108", `\`${sp.imported.name}\` has no Rust twin: add it to \`helpers.functions\` in ${CONFIG_FILE}`, sp);
168
196
  scope.helpers.set(sp.local.name, sp.imported.name);
169
197
  }
170
198
  }
199
+ else {
200
+ const file = resolveImport(comp.file, from);
201
+ const decls = file !== null ? ctx.constDecls.get(file) : undefined;
202
+ for (const sp of decls && st.importKind !== "type" ? st.specifiers : []) {
203
+ const d = sp.type === "ImportSpecifier" && sp.importKind !== "type" ? decls.get(sp.imported.name ?? sp.imported.value) : undefined;
204
+ if (d?.exported)
205
+ evaluable(sp.local.name, d, `it is imported from ${d.home.file}, where it is not a constant the compiler evaluates`);
206
+ }
207
+ }
171
208
  continue;
172
209
  }
173
210
  if (st.type === "FunctionDeclaration") {
@@ -178,97 +215,52 @@ export function scopeFor(comp, ast, components) {
178
215
  const decl = st.type === "ExportNamedDeclaration" ? st.declaration : st;
179
216
  if (decl?.type === "TSInterfaceDeclaration" || decl?.type === "TSTypeAliasDeclaration")
180
217
  continue;
218
+ if (decl?.type === "TSEnumDeclaration") {
219
+ evaluable(decl.id.name, locals.get(decl.id.name), "it is not an enum the compiler evaluates");
220
+ continue;
221
+ }
181
222
  if (st.type === "ExpressionStatement") {
182
223
  setupStatement(comp, st);
183
224
  continue;
184
225
  }
185
- // Setup runs on the server too, so a statement there can change what renders: `x.value = ...`
186
- // after a `ref`, an `if`, a loop. None of it is translated, so none of it may exist.
187
226
  if (st.type !== "VariableDeclaration")
188
- fail(comp, `\`${st.type}\` in setup is not supported`, st);
227
+ fail(comp, "FV0107", `\`${st.type}\` in setup is not supported`, st);
189
228
  for (const d of st.declarations) {
190
229
  const init0 = d.init;
191
- // `const { size = "md", label: l } = defineProps<...>()`: each name reads that prop, whose
192
- // default `compileScript` already resolved.
193
230
  if (d.id.type === "ObjectPattern" && definePropsType(init0)) {
194
231
  for (const p of d.id.properties) {
195
232
  if (p.type !== "ObjectProperty" || p.computed)
196
- fail(comp, "destructured props are plain names: `...rest` has no Rust type", p);
233
+ fail(comp, "FV0108", "destructured props are plain names: `...rest` has no Rust type", p);
197
234
  const key = p.key.type === "Identifier" ? p.key.name : p.key.value;
198
235
  const local = p.value.type === "AssignmentPattern" ? p.value.left : p.value;
199
236
  if (local.type !== "Identifier")
200
- fail(comp, "destructured props are plain names", p);
237
+ fail(comp, "FV0109", "destructured props are plain names", p);
201
238
  scope.setup.set(local.name, fieldVal(comp, "props", { k: "struct", name: "Props" }, key, p));
202
239
  }
203
240
  continue;
204
241
  }
205
- const calls = (name) => name !== null && init0?.type === "CallExpression" && init0.callee.type === "Identifier" && init0.callee.name === name;
206
- // `const { t, locale } = useI18n()`: \`t\` translates, \`locale\` is the request's locale.
207
- if (d.id.type === "ObjectPattern" && calls(useI18nName)) {
208
- for (const p of d.id.properties) {
209
- if (p.type !== "ObjectProperty" || p.computed || p.value.type !== "Identifier") {
210
- fail(comp, "`useI18n()` is destructured into plain names", p);
211
- }
212
- const key = p.key.name ?? p.key.value;
213
- if (key === "t")
214
- scope.i18nT.add(p.value.name);
215
- else if (key === "locale") {
216
- scope.setup.set(p.value.name, { code: "fv_i18n.locale()", ty: STR });
217
- scope.refs.add(p.value.name);
218
- }
219
- else
220
- scope.clientOnly.set(p.value.name, `\`${key}\` from \`useI18n()\` does not run on the server`);
221
- }
222
- comp.readsI18n = true;
242
+ const loaded = d.id.type === "Identifier" ? asyncs.get(d.id.name) : undefined;
243
+ if (loaded !== undefined) {
244
+ scope.children.set(d.id.name, loaded);
223
245
  continue;
224
246
  }
225
- // `const { density, label: l } = storeToRefs(prefs)`: each name is that field of the state.
226
- if (d.id.type === "ObjectPattern" && calls(storeToRefsName)) {
227
- const arg = init0.arguments[0];
228
- const store = arg?.type === "Identifier" ? storeValues.get(arg.name) : undefined;
229
- if (!store || init0.arguments.length !== 1)
230
- fail(comp, "`storeToRefs` takes a store bound in this setup", d);
231
- for (const p of d.id.properties) {
232
- if (p.type !== "ObjectProperty" || p.computed || p.value.type !== "Identifier") {
233
- fail(comp, "`storeToRefs` is destructured into plain names", p);
234
- }
235
- const key = p.key.type === "Identifier" ? p.key.name : p.key.value;
236
- const state = { code: `fv_stores.${store.field}`, ty: { k: "struct", name: store.state, store: true } };
237
- scope.setup.set(p.value.name, storeGetter(scope, state, key, p) ?? fieldVal(comp, state.code, state.ty, key, p));
238
- scope.refs.add(p.value.name);
239
- }
240
- comp.readsStores = true;
247
+ if (ctx.plugins.some((p) => p.scriptBinding?.(scope, d)))
241
248
  continue;
242
- }
243
249
  if (d.id.type !== "Identifier") {
244
- // Destructuring anything else: client-side state the template may not read.
245
250
  for (const name of patternNames(d.id))
246
251
  scope.clientOnly.set(name, "it is destructured from a value the server does not have");
247
252
  continue;
248
253
  }
249
254
  const local = d.id.name;
250
- // `const prefs = usePrefs()`: the store's state, as the server was given it.
251
- const hook = init0?.type === "CallExpression" && init0.callee.type === "Identifier" ? storeHooks.get(init0.callee.name) : undefined;
252
- if (hook) {
253
- if (init0.arguments.length)
254
- fail(comp, "a store hook takes no arguments", d);
255
- storeValues.set(local, hook);
256
- scope.setup.set(local, { code: `fv_stores.${hook.field}`, ty: { k: "struct", name: hook.state, store: true } });
257
- comp.readsStores = true;
258
- continue;
259
- }
260
- // `const route = useRoute()`: the reader's location.
261
- if (useRouteName !== null && init0?.type === "CallExpression" && init0.callee.type === "Identifier" && init0.callee.name === useRouteName) {
262
- scope.setup.set(local, theRoute(scope, d));
263
- continue;
264
- }
265
- // `const attrs = useAttrs()`: `$attrs`, which the template may bind whole.
266
255
  if (useAttrsName !== null && init0?.type === "CallExpression" && init0.callee.type === "Identifier" && init0.callee.name === useAttrsName) {
267
256
  scope.attrsBindings.add(local);
268
257
  scope.clientOnly.set(local, "`useAttrs()` is bound whole, with `v-bind`; a value read from it has no type");
269
258
  continue;
270
259
  }
271
- // `const model = defineModel<string>()`: the model's prop.
260
+ if (useSlotsName !== null && init0?.type === "CallExpression" && init0.callee.type === "Identifier" && init0.callee.name === useSlotsName) {
261
+ scope.slotsBindings.add(local);
262
+ continue;
263
+ }
272
264
  const model = comp.models.get(local);
273
265
  if (model !== undefined) {
274
266
  scope.setup.set(local, fieldVal(comp, "props", { k: "struct", name: "Props" }, model, d));
@@ -287,16 +279,14 @@ export function scopeFor(comp, ast, components) {
287
279
  const isRef = init0.type === "CallExpression" && init0.callee.type === "Identifier" && ["ref", "shallowRef", "computed"].includes(init0.callee.name);
288
280
  if (isRef)
289
281
  scope.refs.add(local);
290
- if (!source) {
291
- scope.clientOnly.set(local, "it is not a value the server computes: only `ref(…)`, `computed(() => …)` and plain expressions are");
292
- continue;
293
- }
294
- // Evaluated once, as setup is on the server. A value the server cannot evaluate is client-side
295
- // state — a template ref, an element, a `reactive` object — which the template may still name
296
- // from an event handler; a reference the server needs fails in `expr` with this reason.
297
282
  let v;
298
283
  try {
299
- v = expr(scope, source);
284
+ const empty = emptyRef(comp, init0);
285
+ if (!empty && !source) {
286
+ scope.clientOnly.set(local, "it is not a value the server computes: only `ref(…)`, `computed(() => …)` and plain expressions are");
287
+ continue;
288
+ }
289
+ v = empty ?? expr(scope, source);
300
290
  }
301
291
  catch (e) {
302
292
  if (!(e instanceof GenError))
@@ -304,25 +294,22 @@ export function scopeFor(comp, ast, components) {
304
294
  scope.clientOnly.set(local, e.message.replace(/^[^:]*: /, ""));
305
295
  continue;
306
296
  }
307
- if (v.ty.k === "undef") {
297
+ if (nothing(v.ty) || (v.ty.k === "str" && known(v) !== undefined)) {
308
298
  scope.setup.set(local, v);
309
299
  continue;
310
300
  }
311
301
  const name = `s_${snake(local).replace(/^r#/, "")}`;
312
302
  const lone = v.lone ? { lone: true } : {};
313
- // A computed list is kept as its items, and read again by item.
314
303
  if (v.ty.k === "list" && v.iter !== undefined) {
315
304
  lets.push(`let ${name} = ${collected(v)};`);
316
305
  scope.setup.set(local, heldList(name, v.ty.of, v.lone));
317
306
  continue;
318
307
  }
319
- // An optional string a temporary owns is kept as that `Option<Cow>`.
320
308
  if (v.held !== undefined) {
321
309
  lets.push(`let ${name} = ${v.held};`);
322
310
  scope.setup.set(local, { code: `${name}.as_deref()`, ty: v.ty, ...lone });
323
311
  continue;
324
312
  }
325
- // A list, a record or an object is a place in the props: borrowed, never moved out of them.
326
313
  const place = v.ty.k === "list" || v.ty.k === "record" || v.ty.k === "struct" || v.ty.k === "child";
327
314
  lets.push(`let ${name} = ${place ? `&${operand(v.code, UNARY)}` : bare(v.code)};`);
328
315
  scope.setup.set(local, { code: name, ty: v.ty, ...lone, ...(v.konst !== undefined ? { konst: v.konst } : {}) });
@@ -0,0 +1,6 @@
1
+ import { type App } from "vue";
2
+ /** Whether the app shows an async component that has not loaded yet. */
3
+ export declare function stillLoading(app: App): boolean;
4
+ /** Wait until every async component the app shows has loaded, been hydrated or rendered, and every
5
+ * update this caused has been flushed. */
6
+ export declare function settled(app: App): Promise<void>;
package/dist/settle.js ADDED
@@ -0,0 +1,34 @@
1
+ import { nextTick } from "vue";
2
+ function loading(vnode, found) {
3
+ if (!vnode || typeof vnode !== "object")
4
+ return;
5
+ const type = vnode.type;
6
+ if (type.__asyncLoader && !type.__asyncResolved)
7
+ found.push(type.__asyncLoader());
8
+ if (vnode.component)
9
+ loading(vnode.component.subTree, found);
10
+ if (Array.isArray(vnode.children))
11
+ for (const child of vnode.children)
12
+ loading(child, found);
13
+ }
14
+ function loaders(app) {
15
+ const found = [];
16
+ loading(app._instance?.subTree, found);
17
+ return found;
18
+ }
19
+ /** Whether the app shows an async component that has not loaded yet. */
20
+ export function stillLoading(app) {
21
+ return loaders(app).length > 0;
22
+ }
23
+ /** Wait until every async component the app shows has loaded, been hydrated or rendered, and every
24
+ * update this caused has been flushed. */
25
+ export async function settled(app) {
26
+ for (let round = 0; round < 20; round++) {
27
+ const found = loaders(app);
28
+ await Promise.all(found);
29
+ await nextTick();
30
+ if (!found.length)
31
+ return;
32
+ }
33
+ throw new Error("async components were still loading after 20 rounds");
34
+ }
@@ -0,0 +1,13 @@
1
+ import { type Component, type N, type Scope, type Ty, type Val } from "./model.ts";
2
+ import { Emitter } from "./emitter.ts";
3
+ export declare function slotBody(s: Scope, value: N): N[];
4
+ export declare function slotContent(s: Scope, value: N): {
5
+ body: N[];
6
+ param: N;
7
+ };
8
+ export declare function staticallyFilled(body: N[]): boolean;
9
+ export declare function slotTypeName(slotName: string, suffix: string): string;
10
+ export declare function slotFieldBorrows(ty: Ty): boolean;
11
+ export declare function slotFieldTy(ty: Ty, comp: Component): string;
12
+ export declare function slotFieldValue(s: Scope, v: Val, n: N): string;
13
+ export declare function slotOutlet(s: Scope, e: Emitter, c: N): void;
package/dist/slots.js ADDED
@@ -0,0 +1,160 @@
1
+ import { fail, nothing, GenError, rustStr, snake } from "./model.js";
2
+ import { expr } from "./expr.js";
3
+ import { atom, bare, operand, strArg, UNARY } from "./parens.js";
4
+ import { Emitter } from "./emitter.js";
5
+ import { rustTy } from "./rust.js";
6
+ import { fieldInit } from "./children.js";
7
+ import { pushesContent, statements } from "./template.js";
8
+ function borrowed(code) {
9
+ return code.startsWith("&") || /^\w+$/.test(code) || /^fv_sp\d+\.\w+$/.test(code) ? code : `&${operand(code, UNARY)}`;
10
+ }
11
+ export function slotBody(s, value) {
12
+ return slotContent(s, value).body;
13
+ }
14
+ export function slotContent(s, value) {
15
+ const fn = value.type === "CallExpression" && value.callee.type === "Identifier" && value.callee.name === "_withCtx"
16
+ ? value.arguments[0]
17
+ : null;
18
+ if (fn?.type !== "ArrowFunctionExpression" || fn.body.type !== "BlockStatement") {
19
+ fail(s.comp, "FV0006", "unexpected slot content", value);
20
+ }
21
+ const branch = fn.body.body.length === 1 ? fn.body.body[0] : null;
22
+ if (branch?.type !== "IfStatement" || branch.test.type !== "Identifier" || branch.test.name !== "_push") {
23
+ fail(s.comp, "FV0006", "unexpected slot content", fn);
24
+ }
25
+ const body = branch.consequent.type === "BlockStatement" ? branch.consequent.body : [branch.consequent];
26
+ return { body, param: fn.params[0] };
27
+ }
28
+ export function staticallyFilled(body) {
29
+ return body.some((st) => st.type === "ExpressionStatement" && st.expression.type === "CallExpression" &&
30
+ st.expression.callee.type === "Identifier" && st.expression.callee.name === "_push" &&
31
+ pushesContent(st.expression.arguments[0]) === true);
32
+ }
33
+ export function slotTypeName(slotName, suffix) {
34
+ return slotName.split(/[-_]/).map((w) => w.charAt(0).toUpperCase() + w.slice(1)).join("") + suffix;
35
+ }
36
+ export function slotFieldBorrows(ty) {
37
+ const copied = (t) => t.k === "int" || t.k === "float" || t.k === "bool";
38
+ return !(copied(ty) || (ty.k === "opt" && copied(ty.of)));
39
+ }
40
+ export function slotFieldTy(ty, comp) {
41
+ const owned = (t) => rustTy(t, comp).replace(/'a\b/g, "'v");
42
+ switch (ty.k) {
43
+ case "int":
44
+ return "i64";
45
+ case "float":
46
+ return "f64";
47
+ case "bool":
48
+ return "bool";
49
+ case "str":
50
+ return "&'v str";
51
+ case "list":
52
+ return `&'v [${owned(ty.of)}]`;
53
+ case "struct":
54
+ case "child":
55
+ case "html":
56
+ return `&'v ${owned(ty)}`;
57
+ case "opt":
58
+ return `Option<${slotFieldTy(ty.of, comp)}>`;
59
+ default:
60
+ throw new GenError("FV0908", `no Rust type for a slot prop of type ${JSON.stringify(ty)}`);
61
+ }
62
+ }
63
+ export function slotFieldValue(s, v, n) {
64
+ switch (v.ty.k) {
65
+ case "str":
66
+ return strArg(v.code);
67
+ case "int":
68
+ case "float":
69
+ case "bool":
70
+ return bare(v.code);
71
+ case "list":
72
+ if (v.code.startsWith("["))
73
+ fail(s.comp, "FV0909", "a slot prop is not an array literal: pass a list the component holds", n);
74
+ if (v.iter !== undefined)
75
+ fail(s.comp, "FV0910", "a slot prop is not a computed list: pass a list the component holds", n);
76
+ return borrowed(v.code);
77
+ case "struct":
78
+ case "child":
79
+ case "html":
80
+ return borrowed(v.code);
81
+ case "opt":
82
+ if (v.ty.of.k === "list")
83
+ return `${atom(v.code)}.map(|v| &v[..])`;
84
+ if (v.ty.of.k === "opt" || nothing(v.ty.of))
85
+ break;
86
+ return v.code;
87
+ }
88
+ return fail(s.comp, "FV0911", "a slot prop is a string, a number, a boolean, an object or a list", n);
89
+ }
90
+ export function slotOutlet(s, e, c) {
91
+ const [, nameNode, slotProps, fallback] = c.arguments;
92
+ if (nameNode?.type !== "StringLiteral")
93
+ fail(s.comp, "FV0912", "a slot's name is literal", c);
94
+ if (slotProps?.type !== "ObjectExpression")
95
+ fail(s.comp, "FV0913", "a slot's props are attributes or a `v-bind` object literal", c);
96
+ const slotName = nameNode.value;
97
+ const field = `fv_slots.${snake(slotName)}`;
98
+ const outlet = `\`<slot${slotName === "default" ? "" : ` name="${slotName}"`}>\``;
99
+ let fn = "fv::slot_into";
100
+ let args = field;
101
+ if (slotProps.properties.length) {
102
+ const fields = [];
103
+ const values = [];
104
+ for (const p of slotProps.properties) {
105
+ if (p.type !== "ObjectProperty" || p.computed)
106
+ fail(s.comp, "FV0914", "slot props hold plain names", p);
107
+ const key = p.key.name ?? p.key.value;
108
+ if (!/^[A-Za-z_$][\w$]*$/.test(key))
109
+ fail(s.comp, "FV0915", `slot prop \`${key}\` is not a plain name; write it in camelCase`, p);
110
+ const v = expr(s, p.value);
111
+ fields.push({ js: key, rust: snake(key), ty: v.ty });
112
+ values.push(fieldInit(snake(key), slotFieldValue(s, v, p.value)));
113
+ }
114
+ const name = slotTypeName(slotName, "SlotProps");
115
+ const shape = { name, fields, slot: true };
116
+ const had = s.comp.slotShapes.get(slotName);
117
+ if (had && JSON.stringify(had.fields) !== JSON.stringify(fields)) {
118
+ fail(s.comp, "FV0916", `every ${outlet} passes the same props, of the same types`, c);
119
+ }
120
+ if (!had) {
121
+ if (s.comp.structs.has(name) && !s.comp.structs.get(name).slot)
122
+ fail(s.comp, "FV0917", `\`${name}\` names this slot's props; rename the interface`, c);
123
+ s.comp.slotShapes.set(slotName, shape);
124
+ s.comp.structs.set(name, shape);
125
+ }
126
+ fn = "fv::scoped_slot_into";
127
+ args = `${field}, &${name} { ${values.join(", ")} }`;
128
+ }
129
+ else if (s.comp.slotShapes.has(slotName)) {
130
+ fail(s.comp, "FV0916", `every ${outlet} passes the same props, of the same types`, c);
131
+ }
132
+ const id = c.arguments[6];
133
+ let slotted = null;
134
+ if (id?.type === "StringLiteral")
135
+ slotted = rustStr(id.value);
136
+ else if (id?.type === "BinaryExpression" && id.operator === "+" && id.left.type === "StringLiteral" && id.right.type === "Identifier" && id.right.name === "_scopeId") {
137
+ slotted = s.sid === null ? rustStr(id.left.value) : `&[${rustStr(id.left.value)}, ${s.sid}].concat()`;
138
+ }
139
+ else if (id?.type === "Identifier" && id.name === "_scopeId")
140
+ slotted = s.sid;
141
+ else if (id && id.type !== "NullLiteral")
142
+ fail(s.comp, "FV0006", "unexpected slot scope id", id);
143
+ if (s.comp.passesSlotIds) {
144
+ fn = fn === "fv::slot_into" ? "fv::slot_into_slotted" : "fv::scoped_slot_into_slotted";
145
+ args += `, ${slotted ?? '""'}`;
146
+ }
147
+ else if (slotted !== null)
148
+ fail(s.comp, "FV0918", "a slot scope id passed to content that does not take one", c);
149
+ const call = (rest) => (s.fill ? `if ${fn}(out, ${args}, ${rest}) { filled = true; }` : `${fn}(out, ${args}, ${rest});`);
150
+ if (fallback?.type === "NullLiteral" || !fallback) {
151
+ e.stmt(call("None"));
152
+ return;
153
+ }
154
+ if (fallback.type !== "ArrowFunctionExpression" || fallback.body.type !== "BlockStatement") {
155
+ fail(s.comp, "FV0006", "unexpected slot fallback", fallback);
156
+ }
157
+ e.open(`${s.fill ? "if " : ""}${fn}(out, ${args}, Some(&mut |out: &mut String|`);
158
+ statements(s, e, fallback.body.body);
159
+ e.close(s.fill ? ")) { filled = true; }" : "));");
160
+ }
@@ -0,0 +1,13 @@
1
+ import { type Component, type N, type Scope, type Val } from "./model.ts";
2
+ export declare function lonely(what: string): string;
3
+ export declare function meet(comp: Component, a: Val, b: Val, what: string, n: N, how: "equal" | "order" | "search" | "join"): void;
4
+ export declare function loneOf(...vs: (Val | undefined)[]): {
5
+ lone?: true;
6
+ };
7
+ export declare function isTemporary(v: Val): boolean;
8
+ export declare function asCow(v: Val): string;
9
+ export declare function yieldsCow(code: string): boolean;
10
+ export declare function unquote(literal: string): string;
11
+ export declare function stringsEqual(a: Val, b: Val): string;
12
+ export declare function formatted(comp: Component, parts: (string | Val)[], n: N, what: string): Val;
13
+ export declare function stringMethod(s: Scope, target: Val, method: string, args: N[], n: N): Val | null;