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
@@ -1,28 +1,27 @@
1
- /* `<RouterLink>`, its locations, and the routes file. */
2
1
  import { escapeHtml } from "@vue/shared";
3
- import { readFileSync } from "node:fs";
4
- import { join } from "node:path";
5
- import { camelize, fail, GenError, rustStr } from "./model.js";
6
- import { allRoutes, CONFIG_FILE, ctx } from "./context.js";
7
- import { expr, lonely } from "./expr.js";
8
- import { bare, condition, strArg } from "./parens.js";
9
- import { Emitter } from "./emitter.js";
10
- import { attrOf, classItems, dollarAttrs, IGNORED_PROPS, isAttrs, mergedParts, mergeProps, renderDynamicAttr, renderStyle } from "./attrs.js";
11
- import { slotBody, statements } from "./template.js";
2
+ import { camelize, fail, rustStr } from "../model.js";
3
+ import { CONFIG_FILE } from "../context.js";
4
+ import { expr } from "../expr.js";
5
+ import { lonely } from "../strings.js";
6
+ import { bare, condition, strArg } from "../parens.js";
7
+ import { Emitter } from "../emitter.js";
8
+ import { attrOf, dollarAttrs, IGNORED_PROPS, isAttrs, mergedParts, mergeProps, renderDynamicAttr } from "../attrs.js";
9
+ import { renderStyle } from "../styles.js";
10
+ import { classItems } from "../classes.js";
11
+ import { statements } from "../template.js";
12
+ import { slotBody } from "../slots.js";
13
+ import { runOf } from "../plugin.js";
14
+ import { scopeIdOf } from "./scoped.js";
15
+ import { allRoutes, router } from "./router.js";
12
16
  export const ROUTER_LINK_PROPS = new Set(["to", "class", "activeClass", "exactActiveClass", "ariaCurrentValue"]);
13
- /** `<RouterLink>` props that change only what a click does, which the server does not render. */
14
17
  export const ROUTER_LINK_INERT = new Set(["replace", "viewTransition"]);
15
- /** The parameter names of a route path, in order. */
16
18
  export function routeParams(path) {
17
19
  return [...path.matchAll(/:(\w+)/g)].map((m) => m[1]);
18
20
  }
19
- /** A string written into a link, which vue-router percent-encodes: half of a surrogate pair makes
20
- * `encodeURI` throw, so Vue renders no page at all. */
21
21
  function noHalves(s, v, n) {
22
22
  if (v.lone)
23
- fail(s.comp, lonely("a `<RouterLink>` location"), n);
23
+ fail(s.comp, "FV0706", lonely("a `<RouterLink>` location"), n);
24
24
  }
25
- /** A value written into a URL — a parameter or a query value — as the `&str` vue-router stringifies. */
26
25
  export function urlText(s, v, n) {
27
26
  noHalves(s, v, n);
28
27
  if (v.ty.k === "str")
@@ -31,14 +30,13 @@ export function urlText(s, v, n) {
31
30
  return `&*fv::Js(${bare(v.code)}).to_string()`;
32
31
  if (v.ty.k === "bool")
33
32
  return `if ${condition(v.code)} { "true" } else { "false" }`;
34
- return fail(s.comp, "a route parameter is a string or a number that is present", n);
33
+ return fail(s.comp, "FV1201", "a route parameter is a string or a number that is present", n);
35
34
  }
36
- /** \`let fv_link = …;\`: a \`<RouterLink>\`'s \`to\` resolved from the reader's route. */
37
35
  export function resolveLink(s, e, to) {
38
36
  if (to.type !== "ObjectExpression") {
39
37
  const target = expr(s, to);
40
38
  if (target.ty.k !== "str")
41
- fail(s.comp, "`<RouterLink>`'s `to` is a string or an object literal", to);
39
+ fail(s.comp, "FV1202", "`<RouterLink>`'s `to` is a string or an object literal", to);
42
40
  noHalves(s, target, to);
43
41
  e.stmt(`let fv_link = fv_route.link(${strArg(target.code)});`);
44
42
  return;
@@ -46,28 +44,29 @@ export function resolveLink(s, e, to) {
46
44
  const parts = new Map();
47
45
  for (const p of to.properties) {
48
46
  if (p.type !== "ObjectProperty" || p.computed)
49
- fail(s.comp, "a `to` object holds plain keys", p);
47
+ fail(s.comp, "FV1203", "a `to` object holds plain keys", p);
50
48
  const key = p.key.name ?? p.key.value;
51
49
  if (["replace", "force", "state"].includes(key))
52
50
  continue;
53
51
  if (!["name", "path", "params", "query", "hash"].includes(key))
54
- fail(s.comp, `\`${key}\` in a \`to\` object`, p);
52
+ fail(s.comp, "FV1204", `\`${key}\` in a \`to\` object`, p);
55
53
  parts.set(key, p.value);
56
54
  }
57
55
  e.open("let fv_link =");
58
56
  const query = parts.get("query");
59
- // The query, built only when the location has one.
60
57
  const search = query ? "&fv_search" : '""';
61
58
  if (query) {
62
59
  e.stmt("let mut fv_search = String::new();");
63
60
  if (query.type !== "ObjectExpression")
64
- fail(s.comp, "a `to`'s `query` is an object literal", query);
61
+ fail(s.comp, "FV1205", "a `to`'s `query` is an object literal", query);
65
62
  for (const p of query.properties) {
66
63
  if (p.type !== "ObjectProperty" || p.computed)
67
- fail(s.comp, "a query holds plain keys", p);
64
+ fail(s.comp, "FV1206", "a query holds plain keys", p);
68
65
  const key = String(p.key.name ?? p.key.value);
69
66
  const v = expr(s, p.value);
70
- // An absent value leaves its key out, as `undefined` does.
67
+ if (v.ty.k === "null" || (v.ty.k === "opt" && v.ty.none !== undefined)) {
68
+ fail(s.comp, "FV1207", "a query value that may be `null`, which vue-router writes as the key alone: give `undefined` to leave it out", p.value);
69
+ }
71
70
  if (v.ty.k === "undef")
72
71
  continue;
73
72
  if (v.ty.k === "opt") {
@@ -84,7 +83,7 @@ export function resolveLink(s, e, to) {
84
83
  if (h) {
85
84
  const v = expr(s, h);
86
85
  if (v.ty.k !== "str")
87
- fail(s.comp, "a `to`'s `hash` is a string", h);
86
+ fail(s.comp, "FV1208", "a `to`'s `hash` is a string", h);
88
87
  noHalves(s, v, h);
89
88
  hash = strArg(v.code);
90
89
  }
@@ -92,46 +91,44 @@ export function resolveLink(s, e, to) {
92
91
  const path = parts.get("path");
93
92
  if (name) {
94
93
  if (name.type !== "StringLiteral")
95
- fail(s.comp, "a `to`'s `name` is a string literal, checked against the routes", name);
96
- const route = allRoutes(ctx.routes).find((r) => r.name === name.value);
94
+ fail(s.comp, "FV1209", "a `to`'s `name` is a string literal, checked against the routes", name);
95
+ const route = allRoutes(runOf(router).routes).find((r) => r.name === name.value);
97
96
  if (!route)
98
- fail(s.comp, `no route is called \`${name.value}\``, name);
97
+ fail(s.comp, "FV1210", `no route is called \`${name.value}\``, name);
99
98
  const wanted = routeParams(route.fullPath);
100
99
  const given = new Map();
101
100
  const params = parts.get("params");
102
101
  if (params) {
103
102
  if (params.type !== "ObjectExpression")
104
- fail(s.comp, "a `to`'s `params` is an object literal", params);
103
+ fail(s.comp, "FV1211", "a `to`'s `params` is an object literal", params);
105
104
  for (const p of params.properties) {
106
105
  if (p.type !== "ObjectProperty" || p.computed)
107
- fail(s.comp, "params hold plain keys", p);
106
+ fail(s.comp, "FV1212", "params hold plain keys", p);
108
107
  const key = String(p.key.name ?? p.key.value);
109
108
  if (!wanted.includes(key))
110
- fail(s.comp, `route \`${name.value}\` has no parameter \`${key}\``, p);
109
+ fail(s.comp, "FV1213", `route \`${name.value}\` has no parameter \`${key}\``, p);
111
110
  given.set(key, p.value);
112
111
  }
113
112
  }
114
113
  const missing = wanted.filter((w) => !given.has(w));
115
114
  if (missing.length)
116
- fail(s.comp, `route \`${name.value}\` needs \`${missing.join("`, `")}\`: give every parameter`, to);
115
+ fail(s.comp, "FV1214", `route \`${name.value}\` needs \`${missing.join("`, `")}\`: give every parameter`, to);
117
116
  const list = wanted.map((w) => `(${rustStr(w)}, ${urlText(s, expr(s, given.get(w)), given.get(w))})`);
118
117
  e.stmt(`fv_route.link_named(${rustStr(name.value)}, &[${list.join(", ")}], ${search}, ${hash})`);
119
118
  }
120
119
  else if (path) {
121
120
  if (parts.has("params"))
122
- fail(s.comp, "a `to` with a `path` takes no `params`, which vue-router ignores", path);
121
+ fail(s.comp, "FV1215", "a `to` with a `path` takes no `params`, which vue-router ignores", path);
123
122
  const v = expr(s, path);
124
123
  if (v.ty.k !== "str")
125
- fail(s.comp, "a `to`'s `path` is a string", path);
124
+ fail(s.comp, "FV1216", "a `to`'s `path` is a string", path);
126
125
  noHalves(s, v, path);
127
126
  e.stmt(`fv_route.link_path(${strArg(v.code)}, ${search}, ${hash})`);
128
127
  }
129
128
  else
130
- fail(s.comp, "a `to` object has a `name` or a `path`", to);
129
+ fail(s.comp, "FV1217", "a `to` object has a `name` or a `path`", to);
131
130
  e.close(";");
132
131
  }
133
- /** \`<RouterLink to="...">\` as vue-router renders it: \`aria-current\` and the active classes when it
134
- * points where the reader is, then \`href\`, then the link's own class and attributes. */
135
132
  export function routerLink(s, e, n) {
136
133
  const [, rawProps, slots, , slotScopeId] = n.arguments;
137
134
  let props = rawProps;
@@ -139,12 +136,12 @@ export function routerLink(s, e, n) {
139
136
  props = mergeProps(s, props);
140
137
  }
141
138
  if (props?.type !== "ObjectExpression")
142
- fail(s.comp, "`<RouterLink>` takes literal attributes", n);
139
+ fail(s.comp, "FV1218", "`<RouterLink>` takes literal attributes", n);
143
140
  const fields = new Map();
144
141
  const attrs = [];
145
142
  for (const p of props.properties) {
146
143
  if (p.type !== "ObjectProperty" || p.computed)
147
- fail(s.comp, "`<RouterLink>` attributes hold plain keys", p);
144
+ fail(s.comp, "FV1219", "`<RouterLink>` attributes hold plain keys", p);
148
145
  const raw = p.key.type === "Identifier" ? p.key.name : p.key.value;
149
146
  const key = raw.replace(/-(\w)/g, (_, c) => c.toUpperCase());
150
147
  if (ROUTER_LINK_PROPS.has(key))
@@ -152,58 +149,47 @@ export function routerLink(s, e, n) {
152
149
  else if (/^on[^a-z]/.test(raw) || IGNORED_PROPS.has(raw) || ROUTER_LINK_INERT.has(key))
153
150
  continue;
154
151
  else if (key === "custom")
155
- fail(s.comp, "`custom` on `<RouterLink>` renders a scoped slot, which is not supported", p);
152
+ fail(s.comp, "FV1220", "`custom` on `<RouterLink>` renders a scoped slot, which is not supported", p);
156
153
  else if (key === "href" || key === "ariaCurrent")
157
- fail(s.comp, `\`${raw}\` on \`<RouterLink>\` is its own`, p);
154
+ fail(s.comp, "FV1221", `\`${raw}\` on \`<RouterLink>\` is its own`, p);
158
155
  else
159
156
  attrs.push({ ...p, key: { type: "StringLiteral", value: raw } });
160
157
  }
161
158
  const to = fields.get("to");
162
159
  if (!to)
163
- fail(s.comp, "`<RouterLink>` needs `to`", n);
164
- /* vue-router renders the link from virtual nodes (`renderElementVNode`). The `<a>` takes the ids
165
- * of a component's root after its attributes: what the parent passes on when the link is its
166
- * root, the id of the component that wrote it, and the slot scope ids around it — as
167
- * `scope_attrs` gathers them. Its content takes that component's id, which the compiled template
168
- * spells out, and the slot scope ids again, each once: unlike the raw `_scopeId` the compiled
169
- * elements would write, so an element there is refused when there are some. */
160
+ fail(s.comp, "FV1222", "`<RouterLink>` needs `to`", n);
170
161
  const passed = (rawProps?.type === "Identifier" && rawProps.name === "_attrs") || rawProps?.arguments?.some((a) => a.type === "Identifier" && a.name === "_attrs");
171
162
  const base = passed ? s.attrs : null;
172
163
  const slotted = slotScopeId ? s.sid : null;
173
- const scopeId = s.comp.scopeId;
164
+ const scopeId = scopeIdOf(s.comp);
174
165
  const content = slots?.type === "ObjectExpression" ? slots.properties.filter((p) => (p.key?.name ?? p.key?.value) !== "_").map((p) => p.value) : [];
175
- /** Whether the link's content holds a node that `is` picks out. */
176
166
  const holds = (is) => {
177
167
  const within = (x) => !!x && typeof x === "object" && (is(x) || Object.values(x).some(within));
178
168
  return content.some((c) => slotBody(s, c).some(within));
179
169
  };
180
170
  const writesScopeId = (x) => x.type === "TemplateLiteral" && x.expressions.some((y) => y.type === "Identifier" && y.name === "_scopeId");
181
171
  if (slotted !== null && holds(writesScopeId)) {
182
- fail(s.comp, "an element inside a `<RouterLink>` in slot content given a slot scope id: vue-router writes those ids by rules of its own", to);
172
+ fail(s.comp, "FV1223", "an element inside a `<RouterLink>` in slot content given a slot scope id: vue-router writes those ids by rules of its own", to);
183
173
  }
184
- // A `<slot>` there is rendered as a virtual node too, which passes its own slot scope ids.
185
174
  if ((scopeId !== null || slotted !== null || base !== null) && holds((x) => x.type === "CallExpression" && x.callee.name === "_ssrRenderSlot")) {
186
- fail(s.comp, "a `<slot>` inside a `<RouterLink>` that takes scope ids: vue-router renders it by rules of its own", to);
175
+ fail(s.comp, "FV1224", "a `<slot>` inside a `<RouterLink>` that takes scope ids: vue-router renders it by rules of its own", to);
187
176
  }
188
- if (!ctx.routes)
189
- fail(s.comp, `\`<RouterLink>\` needs \`routes\` in ${CONFIG_FILE}: the paths it resolves against`, n);
190
- /** A literal-string prop, which the class names and `aria-current` must be. */
177
+ if (!runOf(router).routes)
178
+ fail(s.comp, "FV1225", `\`<RouterLink>\` needs \`routes\` in ${CONFIG_FILE}: the paths it resolves against`, n);
191
179
  const literal = (key, fallback) => {
192
180
  const v = fields.get(key);
193
181
  if (!v)
194
182
  return fallback;
195
183
  if (v.type !== "StringLiteral")
196
- fail(s.comp, `\`${key}\` on \`<RouterLink>\` is a string literal`, v);
184
+ fail(s.comp, "FV1226", `\`${key}\` on \`<RouterLink>\` is a string literal`, v);
197
185
  return v.value;
198
186
  };
199
- const activeClass = literal("activeClass", ctx.linkActive);
200
- const exactClass = literal("exactActiveClass", ctx.linkExactActive);
187
+ const activeClass = literal("activeClass", runOf(router).linkActive);
188
+ const exactClass = literal("exactActiveClass", runOf(router).linkExactActive);
201
189
  const ariaCurrent = literal("ariaCurrentValue", "page");
202
190
  e.open("");
203
191
  resolveLink(s, e, to);
204
192
  e.lit("<a");
205
- /* Attributes this component is passed fall through to the link: merged into its virtual node's
206
- * props with the template's, then onto the `<a>` vue-router renders. */
207
193
  const parts = mergedParts(rawProps);
208
194
  const passedOn = (p) => s.fallthrough !== null && ((isAttrs(p) && s.comp.inheritAttrs) || dollarAttrs(s, p));
209
195
  const fallsThrough = parts.some(passedOn);
@@ -211,10 +197,10 @@ export function routerLink(s, e, n) {
211
197
  for (const name of s.comp.attrNames) {
212
198
  const key = camelize(name);
213
199
  if ((ROUTER_LINK_PROPS.has(key) && key !== "class") || ROUTER_LINK_INERT.has(key) || key === "custom" || key === "viewTransition") {
214
- fail(s.comp, `\`${name}\`, an attribute ${s.comp.name} may be passed, would reach its \`<RouterLink>\` as a prop`, n);
200
+ fail(s.comp, "FV1227", `\`${name}\`, an attribute ${s.comp.name} may be passed, would reach its \`<RouterLink>\` as a prop`, n);
215
201
  }
216
202
  if (key === "href" || key === "ariaCurrent")
217
- fail(s.comp, `\`${name}\`, an attribute ${s.comp.name} may be passed, would replace its \`<RouterLink>\`'s own`, n);
203
+ fail(s.comp, "FV1228", `\`${name}\`, an attribute ${s.comp.name} may be passed, would replace its \`<RouterLink>\`'s own`, n);
218
204
  }
219
205
  e.open(`if ${s.fallthrough}.is_empty()`);
220
206
  }
@@ -224,8 +210,6 @@ export function routerLink(s, e, n) {
224
210
  e.lit(' href="');
225
211
  e.stmt("fv::escape_into(out, &fv_link.href);");
226
212
  e.lit('" class="');
227
- // `{ [activeClass]: isActive, [exactActiveClass]: isExactActive }`. When the two are one class,
228
- // the later key wins: the class goes with `isExactActive`.
229
213
  const linkItems = activeClass === exactClass
230
214
  ? [`if fv_link.exact { ${rustStr(exactClass)} } else { "" }`]
231
215
  : [`if fv_link.active { ${rustStr(activeClass)} } else { "" }`, `if fv_link.exact { ${rustStr(exactClass)} } else { "" }`];
@@ -251,7 +235,6 @@ export function routerLink(s, e, n) {
251
235
  e.stmt(`out.push_str(&fv::scope_attrs(${base ?? '""'}, ${scopeId === null ? '""' : rustStr(scopeId)}, ${slotted ?? '""'}));`);
252
236
  if (fallsThrough) {
253
237
  e.close(" else {");
254
- // The template's attributes for the link, merged in their order with those passed on.
255
238
  const sources = [];
256
239
  for (const p of parts) {
257
240
  if (passedOn(p))
@@ -274,7 +257,6 @@ export function routerLink(s, e, n) {
274
257
  const ids = base === null && slotted === null
275
258
  ? rustStr(scopeId === null ? "" : ` ${scopeId}`)
276
259
  : `&fv::scope_attrs(${base ?? '""'}, ${scopeId === null ? '""' : rustStr(scopeId)}, ${slotted ?? '""'})`;
277
- // vue-router's own: `aria-current` (`null` when the link is not exact), `href`, its classes.
278
260
  const linkOwn = [
279
261
  `("aria-current", if fv_link.exact { fv::Attr::str(${rustStr(ariaCurrent)}) } else { fv::Attr::Undefined })`,
280
262
  '("href", fv::Attr::str(&fv_link.href))',
@@ -286,37 +268,16 @@ export function routerLink(s, e, n) {
286
268
  e.lit(">");
287
269
  if (slots && slots.type !== "NullLiteral") {
288
270
  if (slots.type !== "ObjectExpression")
289
- fail(s.comp, "slots must be an object literal", slots);
271
+ fail(s.comp, "FV0901", "slots must be an object literal", slots);
290
272
  for (const p of slots.properties) {
291
273
  const key = p.key?.type === "Identifier" ? p.key.name : p.key?.value;
292
274
  if (key === "_")
293
275
  continue;
294
276
  if (key !== "default")
295
- fail(s.comp, "`<RouterLink>` has only its default slot", p);
277
+ fail(s.comp, "FV1229", "`<RouterLink>` has only its default slot", p);
296
278
  statements({ ...s, fill: false, vnode: true }, e, slotBody(s, p.value));
297
279
  }
298
280
  }
299
281
  e.lit("</a>");
300
282
  e.close();
301
283
  }
302
- /** The routes file: vue-router paths, each a string or `{ "path", "name" }`. */
303
- export function readRoutes(root, file) {
304
- const raw = JSON.parse(readFileSync(join(root, file), "utf8"));
305
- if (!Array.isArray(raw))
306
- throw new GenError(`${file} lists the routes in an array`);
307
- const read = (list, parent) => list.map((r) => {
308
- const o = (typeof r === "string" ? { path: r } : r);
309
- if (typeof o?.path !== "string" || (o.name !== undefined && typeof o.name !== "string") || (o.children !== undefined && !Array.isArray(o.children))) {
310
- throw new GenError(`${file}: a route is a path, or \`{ "path": "…", "name": "…", "children": [ … ] }\``);
311
- }
312
- // A child's path joins its parent's unless it starts with `/`; an empty one is the parent's.
313
- const fullPath = parent === null || o.path.startsWith("/") ? o.path : `${parent}${parent.endsWith("/") || o.path === "" ? "" : "/"}${o.path}`;
314
- const def = { path: o.path, fullPath };
315
- if (o.name !== undefined)
316
- def.name = o.name;
317
- if (o.children)
318
- def.children = read(o.children, fullPath);
319
- return def;
320
- });
321
- return read(raw, null);
322
- }
@@ -0,0 +1,42 @@
1
+ import { type Component } from "../model.ts";
2
+ import { type Plugin } from "../plugin.ts";
3
+ declare module "../model.ts" {
4
+ interface PluginTys {
5
+ route: {
6
+ k: "route";
7
+ };
8
+ params: {
9
+ k: "params";
10
+ };
11
+ queryobj: {
12
+ k: "queryobj";
13
+ };
14
+ query: {
15
+ k: "query";
16
+ };
17
+ }
18
+ }
19
+ export interface RouteDef {
20
+ path: string;
21
+ name?: string;
22
+ children?: RouteDef[];
23
+ fullPath: string;
24
+ }
25
+ export declare function allRoutes(routes: RouteDef[]): RouteDef[];
26
+ interface RouterRun {
27
+ routes: RouteDef[] | null;
28
+ file: string | null;
29
+ base: string;
30
+ linkActive: string;
31
+ linkExactActive: string;
32
+ readers: Set<Component>;
33
+ views: Set<Component>;
34
+ }
35
+ interface RouterScope {
36
+ useRoute: string | null;
37
+ components: Map<string, "RouterLink" | "RouterView">;
38
+ }
39
+ export declare function readRoutes(root: string, file: string): RouteDef[];
40
+ export declare function routesSource(routes: RouteDef[], file: string): string;
41
+ export declare const router: Plugin<RouterRun, RouterScope>;
42
+ export {};
@@ -0,0 +1,256 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { BOOL, fail, failIn, GenError, opt, rustStr, STR } from "../model.js";
4
+ import { CONFIG_FILE } from "../context.js";
5
+ import { expr } from "../expr.js";
6
+ import { boolOf, pathOf } from "../narrowing.js";
7
+ import { atom, bare, not, strArg } from "../parens.js";
8
+ import { runOf, scopeOf } from "../plugin.js";
9
+ import { header } from "../rust.js";
10
+ import { scopeIdOf } from "./scoped.js";
11
+ import { routerLink } from "./router-link.js";
12
+ export function allRoutes(routes) {
13
+ return routes.flatMap((r) => [r, ...allRoutes(r.children ?? [])]);
14
+ }
15
+ function typeofString(n) {
16
+ if (n.type !== "BinaryExpression" || (n.operator !== "===" && n.operator !== "!=="))
17
+ return null;
18
+ const isTypeof = (m) => m.type === "UnaryExpression" && m.operator === "typeof";
19
+ const isString = (m) => m.type === "StringLiteral" && m.value === "string";
20
+ const target = isTypeof(n.left) && isString(n.right) ? n.left.argument : isTypeof(n.right) && isString(n.left) ? n.right.argument : null;
21
+ return target ? { target, negated: n.operator === "!==" } : null;
22
+ }
23
+ function theRoute(s, n) {
24
+ if (!runOf(router).routes)
25
+ fail(s.comp, "FV1230", `reading the route needs \`routes\` in ${CONFIG_FILE}`, n);
26
+ runOf(router).readers.add(s.comp);
27
+ return { code: "fv_route", ty: { k: "route" } };
28
+ }
29
+ function routeField(s, base, prop, n) {
30
+ if (base.ty.k === "params") {
31
+ return { code: `fv_route.param(${rustStr(prop)})`, ty: opt(STR) };
32
+ }
33
+ if (base.ty.k === "queryobj")
34
+ return { code: `fv_route.query(${rustStr(prop)})`, ty: { k: "query" } };
35
+ switch (prop) {
36
+ case "path":
37
+ return { code: "fv_route.path()", ty: STR };
38
+ case "hash":
39
+ return { code: "fv_route.hash()", ty: STR };
40
+ case "name":
41
+ return { code: "fv_route.name()", ty: opt(STR) };
42
+ case "params":
43
+ return { code: "fv_route", ty: { k: "params" } };
44
+ case "query":
45
+ return { code: "fv_route", ty: { k: "queryobj" } };
46
+ case "fullPath":
47
+ return { code: "fv_route.full_path()", ty: STR };
48
+ }
49
+ return fail(s.comp, "FV1231", `\`route.${prop}\` is not available on the server: \`path\`, \`fullPath\`, \`hash\`, \`name\`, \`params\` and \`query\` are`, n);
50
+ }
51
+ export function readRoutes(root, file) {
52
+ const raw = JSON.parse(readFileSync(join(root, file), "utf8"));
53
+ if (!Array.isArray(raw))
54
+ throw new GenError("FV1232", `${file} lists the routes in an array`, { file });
55
+ const read = (list, parent) => list.map((r) => {
56
+ const o = (typeof r === "string" ? { path: r } : r);
57
+ if (typeof o?.path !== "string" || (o.name !== undefined && typeof o.name !== "string") || (o.children !== undefined && !Array.isArray(o.children))) {
58
+ failIn(file, "FV1233", `a route is a path, or \`{ "path": "…", "name": "…", "children": [ … ] }\``);
59
+ }
60
+ const fullPath = parent === null || o.path.startsWith("/") ? o.path : `${parent}${parent.endsWith("/") || o.path === "" ? "" : "/"}${o.path}`;
61
+ const def = { path: o.path, fullPath };
62
+ if (o.name !== undefined)
63
+ def.name = o.name;
64
+ if (o.children)
65
+ def.children = read(o.children, fullPath);
66
+ return def;
67
+ });
68
+ return read(raw, null);
69
+ }
70
+ function routeDefs(routes, depth) {
71
+ const pad = " ".repeat(depth);
72
+ return routes
73
+ .map((r) => {
74
+ const name = r.name === undefined ? "None" : `Some(${rustStr(r.name)})`;
75
+ const children = r.children?.length ? `&[\n${routeDefs(r.children, depth + 1)}\n${pad}]` : "&[]";
76
+ return `${pad}ferrovue::RouteDef { path: ${rustStr(r.path)}, name: ${name}, children: ${children} },`;
77
+ })
78
+ .join("\n");
79
+ }
80
+ export function routesSource(routes, file) {
81
+ return `${header(file, "the routes file")}
82
+ //! The app's routes: what \`<RouterLink>\` resolves against and \`useRoute()\` reads.
83
+
84
+ /// Each route: its vue-router path, its name if it has one, and the routes nested in it.
85
+ pub const ROUTES: &[ferrovue::RouteDef<'static>] = &[
86
+ ${routeDefs(routes, 1)}
87
+ ];
88
+
89
+ /// Every route's full path, nested ones included.
90
+ pub const PATHS: &[&str] = &[
91
+ ${allRoutes(routes).map((r) => ` ${rustStr(r.fullPath)},`).join("\n")}
92
+ ];
93
+
94
+ /// The history's base, which every link's \`href\` starts with.
95
+ pub const BASE: &str = ${rustStr(runOf(router).base)};
96
+
97
+ /// The router these routes make: build it once, and resolve each request's location with
98
+ /// [\`ferrovue::Router::at\`].
99
+ pub fn router() -> ferrovue::Router {
100
+ ferrovue::Router::tree(ROUTES).with_base(BASE)
101
+ }
102
+ `;
103
+ }
104
+ export const router = {
105
+ name: "router",
106
+ configure(config, root) {
107
+ const r = config.router ?? (config.routes ? { routes: config.routes } : null);
108
+ return {
109
+ routes: r ? readRoutes(root, r.routes) : null,
110
+ file: r?.routes ?? null,
111
+ base: r?.base ?? "",
112
+ linkActive: r?.linkActiveClass ?? "router-link-active",
113
+ linkExactActive: r?.linkExactActiveClass ?? "router-link-exact-active",
114
+ readers: new Set(),
115
+ views: new Set(),
116
+ };
117
+ },
118
+ compiled(comp, code, script) {
119
+ const imported = (exported) => script.some((st) => st.type === "ImportDeclaration" && st.source.value === "vue-router" &&
120
+ st.specifiers.some((sp) => sp.type === "ImportSpecifier" && (sp.imported.name ?? sp.imported.value) === exported));
121
+ const run = runOf(router);
122
+ if (code.includes('_resolveComponent("RouterLink")') || imported("RouterLink") || code.includes("_ctx.$route"))
123
+ run.readers.add(comp);
124
+ if (code.includes('_resolveComponent("RouterView")') || imported("RouterView"))
125
+ run.views.add(comp);
126
+ },
127
+ scope: () => ({ useRoute: null, components: new Map() }),
128
+ scriptImport(s, st, from) {
129
+ if (from !== "vue-router")
130
+ return false;
131
+ const own = scopeOf(router, s);
132
+ for (const sp of st.specifiers) {
133
+ const name = sp.type === "ImportSpecifier" ? (sp.imported.name ?? sp.imported.value) : null;
134
+ if (name === "useRoute")
135
+ own.useRoute = sp.local.name;
136
+ else if (name === "RouterLink" || name === "RouterView")
137
+ own.components.set(sp.local.name, name);
138
+ else
139
+ s.clientOnly.set(sp.local.name, `\`${name}\` from vue-router does not run on the server`);
140
+ }
141
+ return true;
142
+ },
143
+ scriptBinding(s, d) {
144
+ const { useRoute } = scopeOf(router, s);
145
+ const init = d.init;
146
+ if (useRoute === null || d.id.type !== "Identifier" || init?.type !== "CallExpression" || init.callee.type !== "Identifier" || init.callee.name !== useRoute)
147
+ return false;
148
+ s.setup.set(d.id.name, theRoute(s, d));
149
+ return true;
150
+ },
151
+ global: (s, name, n) => (name === "$route" ? theRoute(s, n) : null),
152
+ member(s, base, prop, n, computed) {
153
+ if (base.ty.k === "params" || base.ty.k === "queryobj" || (base.ty.k === "route" && !computed))
154
+ return routeField(s, base, prop, n);
155
+ return null;
156
+ },
157
+ equality(s, n) {
158
+ const tested = typeofString(n);
159
+ if (!tested)
160
+ return null;
161
+ const v = expr(s, tested.target);
162
+ if (v.ty.k !== "query")
163
+ fail(s.comp, "FV1234", '`typeof` tests a query value only, as `typeof route.query.q === "string"`', n);
164
+ const one = `${atom(v.code)}.attr_value().is_some()`;
165
+ return boolOf(tested.negated ? not(one) : one);
166
+ },
167
+ presence(s, n) {
168
+ const t = typeofString(n);
169
+ if (!t)
170
+ return undefined;
171
+ const path = pathOf(t.target);
172
+ const v = expr(s, t.target);
173
+ if (path === null || v.ty.k !== "query")
174
+ return null;
175
+ const option = `${atom(v.code)}.attr_value()`;
176
+ return { path, of: STR, negated: t.negated, truthy: false, option, present: `${option}.is_some()`, pattern: (name) => `let Some(${name}) = ${option}` };
177
+ },
178
+ values: {
179
+ describe: (ty) => (ty.k === "query" ? "a query value" : undefined),
180
+ truthy: (v) => (v.ty.k === "query" ? `${atom(v.code)}.truthy()` : undefined),
181
+ interpolate(e, v) {
182
+ if (v.ty.k !== "query")
183
+ return false;
184
+ e.stmt(`${atom(v.code)}.write_display(out);`);
185
+ return true;
186
+ },
187
+ unbindable: (ty) => ty.k === "query"
188
+ ? { what: "a query value, which is an array when its key is repeated", fix: 'narrow it to one string, as `typeof route.query.q === "string" ? route.query.q : ""`' }
189
+ : undefined,
190
+ nullish(s, a, b, n) {
191
+ if (a.ty.k !== "query")
192
+ return undefined;
193
+ if (b.ty.k !== "str")
194
+ fail(s.comp, "FV1235", "`??` after a query value takes a string", n);
195
+ return { code: `${atom(a.code)}.or(${bare(b.code)})`, ty: a.ty };
196
+ },
197
+ equals(a, b) {
198
+ if (a.ty.k === "query" && b.ty.k === "str")
199
+ return `${atom(a.code)}.is(${strArg(b.code)})`;
200
+ if (b.ty.k === "query" && a.ty.k === "str")
201
+ return `${atom(b.code)}.is(${strArg(a.code)})`;
202
+ if (a.ty.k === "query" && b.ty.k === "undef")
203
+ return `${atom(a.code)}.is_undefined()`;
204
+ if (b.ty.k === "query" && a.ty.k === "undef")
205
+ return `${atom(b.code)}.is_undefined()`;
206
+ return undefined;
207
+ },
208
+ isArray: (v) => (v.ty.k === "query" ? { code: `${atom(v.code)}.is_array()`, ty: BOOL } : undefined),
209
+ },
210
+ resolveComponent(s, local, name) {
211
+ if (name !== "RouterLink" && name !== "RouterView")
212
+ return false;
213
+ scopeOf(router, s).components.set(local, name);
214
+ return true;
215
+ },
216
+ component(s, e, n) {
217
+ const target = n.arguments[0];
218
+ const { components } = scopeOf(router, s);
219
+ const routed = target.type === "Identifier"
220
+ ? components.get(target.name)
221
+ : target.type === "MemberExpression" && target.object.name === "$setup"
222
+ ? components.get(target.computed ? target.property.value : target.property.name)
223
+ : undefined;
224
+ if (routed === "RouterLink")
225
+ routerLink(s, e, n);
226
+ else if (routed === "RouterView") {
227
+ if (scopeIdOf(s.comp) !== null)
228
+ fail(s.comp, "FV1236", "`<RouterView>` in a component with `<style scoped>` gives the page this component's id, which the server's page does not carry", n);
229
+ e.stmt("fv_slots.router_view.render_to(out);");
230
+ }
231
+ else
232
+ return false;
233
+ return true;
234
+ },
235
+ child(s, child, n) {
236
+ if (runOf(router).views.has(child)) {
237
+ fail(s.comp, "FV1237", `${child.name} holds \`<RouterView>\`: the server renders it at the top, never as a child`, n);
238
+ }
239
+ },
240
+ slotFields: (comp) => (runOf(router).views.has(comp) ? [{ js: "routerView", rust: "router_view", doc: "The page `<RouterView>` shows." }] : []),
241
+ params: [
242
+ {
243
+ name: "fv_route",
244
+ ty: "&fv::Route<'_>",
245
+ pageTy: "&'p fv::Route<'p>",
246
+ reads: (c) => runOf(router).readers.has(c),
247
+ test: { lines: ["let router = route_table::router();", "let route = router.at(&fixture.route);"], arg: "&route", fixture: true },
248
+ fixtureField: ' #[serde(rename = "$route", default = "Fixture::root")]\n route: String,',
249
+ fixtureDefault: ' fn root() -> String {\n "/".to_owned()\n }',
250
+ },
251
+ ],
252
+ modules() {
253
+ const { routes, file } = runOf(router);
254
+ return routes ? [["route_table.rs", routesSource(routes, file)]] : [];
255
+ },
256
+ };
@@ -0,0 +1,12 @@
1
+ import { type Component } from "../model.ts";
2
+ import { type ScopeIdMode } from "../context.ts";
3
+ import { type Plugin } from "../plugin.ts";
4
+ interface ScopedRun {
5
+ mode: ScopeIdMode;
6
+ viteRoot: string;
7
+ ids: Map<Component, string>;
8
+ slotted: Set<Component>;
9
+ }
10
+ export declare function scopeIdOf(comp: Component): string | null;
11
+ export declare const scoped: Plugin<ScopedRun>;
12
+ export {};