@cslug/vue 0.0.0-stage → 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/src/render.ts ADDED
@@ -0,0 +1,262 @@
1
+ import { existsSync, readFileSync } from 'node:fs'
2
+ import { join } from 'node:path'
3
+ import { currentApp, currentContext, currentLocale, Logger, Translator } from '@cslug/core'
4
+ import { type HttpContext, type Responsable, Router } from '@cslug/http'
5
+ import { Comment, type Component, createSSRApp, defineComponent, h, useSSRContext } from 'vue'
6
+ import { renderToString } from 'vue/server-renderer'
7
+ import type { PageData } from './client/data'
8
+ import { liveReloadUrl } from './dev'
9
+ import { componentStyles } from './loader'
10
+ import { serialize } from './serialize'
11
+
12
+ /** What one render collects (Vue's SSR context). */
13
+ export type RenderState = {
14
+ http?: HttpContext
15
+ /** Components that rendered (their CSS goes into the page). */
16
+ modules: Set<string>
17
+ /** Islands on the page. */
18
+ islands: Set<string>
19
+ /** Translation namespaces the page's islands declared (`defineOptions({ lang })`). */
20
+ lang: Set<string>
21
+ /** Render islands as plain HTML (renderStandalone, mail). */
22
+ static?: boolean
23
+ dev: boolean
24
+ }
25
+
26
+ export const renderState = (): RenderState | undefined => useSSRContext<RenderState>()
27
+
28
+ /**
29
+ * The server side of `<X hydrate="…">` (the compiler rewrites the tag to this). Renders the component with the
30
+ * *serialized* props, exactly what the browser will get, so hydration matches. `hydrate="none"` and static
31
+ * renders produce the component's HTML only.
32
+ */
33
+ export const CslugIsland = defineComponent({
34
+ name: 'CslugIsland',
35
+ inheritAttrs: false,
36
+ props: {
37
+ islandComponent: { type: [Object, Function], required: true },
38
+ islandHydrate: { type: String, default: 'load' },
39
+ ssr: { type: Boolean, default: true },
40
+ },
41
+ setup(props, { attrs, slots }) {
42
+ const state = renderState()
43
+ return () => {
44
+ const component = props.islandComponent as Component & { __cslugId?: string; __file?: string; lang?: string[] }
45
+ const id = component.__cslugId
46
+ if (!id) throw new Error('hydrate="…" was used on a component that is not a .vue file compiled by cslug')
47
+ const data = serialize({ ...attrs }, state?.dev ? (p) => warn(`<${id} hydrate> prop ${p}`) : undefined)
48
+ if (props.islandHydrate === 'none' || state?.static) return h(component, data)
49
+ state?.islands.add(id)
50
+ for (const ns of component.lang ?? []) state?.lang.add(ns)
51
+ const marker = {
52
+ 'data-island': id,
53
+ 'data-hydrate': props.islandHydrate,
54
+ 'data-props': JSON.stringify(data),
55
+ ...(props.ssr ? {} : { 'data-ssr': 'false' }),
56
+ }
57
+ return h('cslug-island', marker, [props.ssr ? h(component, data) : (slots.fallback?.() ?? null)])
58
+ }
59
+ },
60
+ })
61
+
62
+ const warn = (message: string) => {
63
+ try {
64
+ currentApp().resolve(Logger).warn('vue.island_props', { message })
65
+ } catch {
66
+ console.warn(message)
67
+ }
68
+ }
69
+
70
+ /** `<Assets entry="client" />` in the layout's `<head>`: CSS, the CSRF meta tag, and JS only if the page has islands. */
71
+ export const Assets = defineComponent({
72
+ // biome-ignore lint/style/useVueMultiWordComponentNames: the name guide 08 documents
73
+ name: 'Assets',
74
+ props: { entry: { type: String, default: 'client' } },
75
+ setup(props) {
76
+ return () => h(Comment, `cslug-assets:${props.entry}`)
77
+ },
78
+ })
79
+
80
+ /** `public/build/manifest.json`, written by `cslug build` (and `cslug dev`). */
81
+ export type AssetManifest = {
82
+ entries: Record<string, { js?: string; css?: string[] }>
83
+ islands: Record<string, string>
84
+ }
85
+
86
+ let manifestCache: { path: string; mtime: number; value: AssetManifest } | undefined
87
+ /** `public/build/manifest.json` from `cslug build` (re-read when it changes); undefined before a build. */
88
+ export function readManifest(root: string): AssetManifest | undefined {
89
+ const path = join(root, 'public/build/manifest.json')
90
+ if (!existsSync(path)) return undefined
91
+ const mtime = Bun.file(path).lastModified
92
+ if (manifestCache?.path !== path || manifestCache.mtime !== mtime)
93
+ manifestCache = { path, mtime, value: JSON.parse(readFileSync(path, 'utf8')) }
94
+ return manifestCache.value
95
+ }
96
+
97
+ const escapeAttr = (s: string) => s.replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/</g, '&lt;')
98
+
99
+ /** What `<Assets>` becomes once the whole page has rendered (only then is it known which islands it has). */
100
+ function assetsHtml(entry: string, state: RenderState, root: string): string {
101
+ const manifest = readManifest(root)
102
+ const out: string[] = []
103
+ const token = state.http && !isMissing(state.http) ? state.http.session.token() : undefined
104
+ if (token) out.push(`<meta name="csrf-token" content="${escapeAttr(token)}">`)
105
+ const assets = manifest?.entries[entry]
106
+ for (const css of assets?.css ?? []) out.push(`<link rel="stylesheet" href="${escapeAttr(css)}">`)
107
+ const styles = [...state.modules].map((m) => componentStyles.get(m)).filter(Boolean)
108
+ if (styles.length) out.push(`<style data-cslug>${styles.join('\n')}</style>`)
109
+ if (state.islands.size) {
110
+ out.push('<style>cslug-island{display:contents}</style>')
111
+ if (assets?.js) {
112
+ const data = pageData(state, manifest as AssetManifest)
113
+ out.push(
114
+ `<script type="application/json" id="cslug-data">${JSON.stringify(data).replace(/</g, '\\u003c')}</script>`,
115
+ )
116
+ for (const island of state.islands) {
117
+ const chunk = manifest?.islands[island]
118
+ if (chunk) out.push(`<link rel="modulepreload" href="${escapeAttr(chunk)}">`)
119
+ }
120
+ out.push(`<script type="module" src="${escapeAttr(assets.js)}"></script>`)
121
+ } else if (state.dev) {
122
+ out.push(
123
+ `<!-- cslug: this page has islands but public/build/manifest.json has no "${entry}" entry: run cslug dev or cslug build -->`,
124
+ )
125
+ }
126
+ }
127
+ return out.join('')
128
+ }
129
+
130
+ /** What islands need in the browser: locale, their translation namespaces, named routes, chunk URLs. */
131
+ function pageData(state: RenderState, manifest: AssetManifest): PageData {
132
+ const app = currentApp()
133
+ const translator = app.resolve(Translator)
134
+ const locale = state.http?.locale ?? currentLocale()
135
+ const messages: Record<string, string> = {}
136
+ for (const ns of state.lang) Object.assign(messages, translator.messagesFor(ns, locale))
137
+ const allowed = app.config<string[] | undefined>('vue.routes')
138
+ const routes: PageData['routes'] = {}
139
+ for (const r of app.resolve(Router).routes) {
140
+ if (!r.name || (allowed && !allowed.some((p) => r.name === p || r.name?.startsWith(`${p}.`)))) continue
141
+ routes[r.name] = r.domain ? { path: r.path, domain: r.domain } : { path: r.path }
142
+ }
143
+ const islands: Record<string, string> = {}
144
+ for (const id of state.islands) if (manifest.islands[id]) islands[id] = manifest.islands[id] as string
145
+ const live = liveReloadUrl()
146
+ return {
147
+ locale,
148
+ chain: translator.chain(locale),
149
+ messages,
150
+ routes,
151
+ appUrl: app.config<string | undefined>('app.url'),
152
+ islands,
153
+ ...(live ? { live } : {}),
154
+ }
155
+ }
156
+
157
+ const isMissing = (ctx: HttpContext) => !ctx.session.available
158
+
159
+ export type RenderOptions = { http?: HttpContext; static?: boolean; root?: string }
160
+
161
+ /** Render a page component to a full HTML document. */
162
+ export async function renderPage(
163
+ page: Component,
164
+ props: Record<string, unknown> = {},
165
+ options: RenderOptions = {},
166
+ ): Promise<{ html: string; state: RenderState }> {
167
+ const app = currentApp()
168
+ const root = options.root ?? app.rootDir
169
+ const state: RenderState = {
170
+ http: options.http ?? (currentContext()?.http as HttpContext | undefined),
171
+ modules: new Set(),
172
+ islands: new Set(),
173
+ lang: new Set(),
174
+ static: options.static,
175
+ dev: app.config('app.env') !== 'production',
176
+ }
177
+ const vue = createSSRApp(page, props)
178
+ vue.component('CslugIsland', CslugIsland)
179
+ vue.component('Assets', Assets)
180
+ let html = await renderToString(vue, state)
181
+ let placed = false
182
+ html = html.replace(/<!--cslug-assets:([\w-]+)-->/g, (_m, entry: string) => {
183
+ placed = true
184
+ return assetsHtml(entry, state, root)
185
+ })
186
+ // a page without <Assets> still gets its component CSS
187
+ if (!placed && state.modules.size) {
188
+ const styles = [...state.modules].map((m) => componentStyles.get(m)).filter(Boolean)
189
+ if (styles.length)
190
+ html = html.includes('</head>')
191
+ ? html.replace('</head>', `<style data-cslug>${styles.join('\n')}</style></head>`)
192
+ : `<style data-cslug>${styles.join('\n')}</style>${html}`
193
+ }
194
+ return { html: /^\s*<html[\s>]/i.test(html) ? `<!doctype html>${html}` : html, state }
195
+ }
196
+
197
+ type ViewListener = (page: Component, props: Record<string, unknown>, ctx: HttpContext) => void
198
+ const viewListeners = new Set<ViewListener>()
199
+
200
+ /** Be told of every page rendered by `view()` (the test kit's `assertView`). Returns an unsubscribe function. */
201
+ export function onView(listener: ViewListener): () => void {
202
+ viewListeners.add(listener)
203
+ return () => {
204
+ viewListeners.delete(listener)
205
+ }
206
+ }
207
+
208
+ /** `return view(ShowCircuit, { circuit, days })` from a controller. */
209
+ export class ViewResponse implements Responsable {
210
+ constructor(
211
+ readonly page: Component,
212
+ readonly props: Record<string, unknown>,
213
+ readonly init: { status?: number; headers?: Record<string, string> } = {},
214
+ ) {}
215
+
216
+ async toResponse(ctx: HttpContext): Promise<Response> {
217
+ for (const listener of viewListeners) listener(this.page, this.props, ctx)
218
+ const { html } = await renderPage(this.page, this.props, { http: ctx })
219
+ const headers = new Headers(this.init.headers)
220
+ if (!headers.has('content-type')) headers.set('content-type', 'text/html; charset=utf-8')
221
+ return new Response(html, { status: this.init.status ?? 200, headers })
222
+ }
223
+ }
224
+
225
+ /** Props of a page component, for `view()` type checking. */
226
+ type PropsOf<C> = C extends new (
227
+ ...args: never[]
228
+ ) => { $props: infer P }
229
+ ? Omit<P, `on${string}` | 'key' | 'ref' | 'class' | 'style'>
230
+ : Record<string, unknown>
231
+
232
+ /** Return a page from a handler: `return view(BookingShow, { booking })`. Props are typed from the page. */
233
+ export function view<C extends Component>(
234
+ page: C,
235
+ props: PropsOf<C> | Record<string, unknown> = {},
236
+ init?: { status?: number; headers?: Record<string, string> },
237
+ ): ViewResponse {
238
+ return new ViewResponse(page, props as Record<string, unknown>, init)
239
+ }
240
+
241
+ /**
242
+ * One self-contained HTML file (the offline trip pack): islands rendered as plain HTML, no scripts, the page's
243
+ * CSS inlined, and `/`-rooted images from `public/` inlined as data URIs.
244
+ */
245
+ export async function renderStandalone(page: Component, props: Record<string, unknown> = {}): Promise<string> {
246
+ const app = currentApp()
247
+ const { html } = await renderPage(page, props, { static: true })
248
+ const publicDir = join(app.rootDir, 'public')
249
+ return html
250
+ .replace(/<meta name="csrf-token"[^>]*>/g, '')
251
+ .replace(/<script\b[\s\S]*?<\/script>/gi, '')
252
+ .replace(/<link rel="modulepreload"[^>]*>/g, '')
253
+ .replace(/<link rel="stylesheet" href="(\/[^"]+)">/g, (m, href: string) => {
254
+ const file = join(publicDir, href)
255
+ return existsSync(file) ? `<style>${readFileSync(file, 'utf8')}</style>` : m
256
+ })
257
+ .replace(/(<img\b[^>]*\bsrc=")(\/[^"]+)(")/g, (m, a: string, src: string, b: string) => {
258
+ const file = Bun.file(join(publicDir, src))
259
+ if (!existsSync(join(publicDir, src))) return m
260
+ return `${a}data:${file.type.split(';')[0]};base64,${Buffer.from(readFileSync(join(publicDir, src))).toString('base64')}${b}`
261
+ })
262
+ }
@@ -0,0 +1,50 @@
1
+ /** What JSON delivers to an island: `bigint` → string, `Date` → ISO string, recursively. */
2
+ export type Serialized<T> = T extends bigint
3
+ ? string
4
+ : T extends Date
5
+ ? string
6
+ : T extends { toJSON(): infer J }
7
+ ? J
8
+ : T extends (infer U)[]
9
+ ? Serialized<U>[]
10
+ : T extends object
11
+ ? { [K in keyof T]: Serialized<T[K]> }
12
+ : T
13
+
14
+ /**
15
+ * Convert a value to exactly what an island receives (and type it so): `<TodoItem :todo="serialize(todo)" hydrate />`.
16
+ * With `check`, functions, class instances (other than Date and values with `toJSON`), and cycles are reported.
17
+ */
18
+ export function serialize<T>(value: T, check?: (problem: string) => void): Serialized<T> {
19
+ if (check) inspect(value, '', new Set(), check)
20
+ return JSON.parse(
21
+ JSON.stringify(value, (_k, v) => (typeof v === 'bigint' ? v.toString() : v)) ?? 'null',
22
+ ) as Serialized<T>
23
+ }
24
+
25
+ function inspect(value: unknown, path: string, seen: Set<unknown>, report: (problem: string) => void): void {
26
+ if (typeof value === 'function') {
27
+ report(`${path || 'value'} is a function (dropped)`)
28
+ return
29
+ }
30
+ if (
31
+ !value ||
32
+ typeof value !== 'object' ||
33
+ value instanceof Date ||
34
+ typeof (value as { toJSON?: unknown }).toJSON === 'function'
35
+ )
36
+ return
37
+ if (seen.has(value)) {
38
+ report(`${path || 'value'} is circular`)
39
+ return
40
+ }
41
+ seen.add(value)
42
+ const proto = Object.getPrototypeOf(value)
43
+ if (!Array.isArray(value) && proto !== Object.prototype && proto !== null) {
44
+ report(
45
+ `${path || 'value'} is a ${proto?.constructor?.name ?? 'class'} instance (only its fields reach the browser)`,
46
+ )
47
+ }
48
+ for (const [k, v] of Object.entries(value)) inspect(v, path ? `${path}.${k}` : k, seen, report)
49
+ seen.delete(value)
50
+ }
@@ -0,0 +1,88 @@
1
+ import { reactive, type UnwrapRef } from 'vue'
2
+
3
+ /** `X-CSRF-Token` from the page's `<meta name="csrf-token">` (rendered by `<Assets>`), for hand-written `fetch`. */
4
+ export function csrfHeaders(): Record<string, string> {
5
+ if (typeof document === 'undefined') return {}
6
+ const token = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content')
7
+ return token ? { 'x-csrf-token': token } : {}
8
+ }
9
+
10
+ export type Form<F extends object, R> = {
11
+ data: UnwrapRef<F>
12
+ /** First message per field from a 422 response; cleared on the next submit. */
13
+ errors: Partial<Record<keyof F & string, string>> & Record<string, string | undefined>
14
+ /** A message for failures that are not field errors (network, 403, 419, 500). */
15
+ error: string | null
16
+ processing: boolean
17
+ /** Parsed JSON of the last successful response. */
18
+ response: R
19
+ post(url: string): Promise<boolean>
20
+ put(url: string): Promise<boolean>
21
+ patch(url: string): Promise<boolean>
22
+ delete(url: string): Promise<boolean>
23
+ reset(): void
24
+ clearErrors(): void
25
+ }
26
+
27
+ /**
28
+ * Reactive form state that submits JSON (with the CSRF token) and maps a 422 problem's `errors` to fields:
29
+ * `const form = useForm({ title: '' }); if (await form.post(route('todos.store'))) …`.
30
+ */
31
+ // biome-ignore lint/suspicious/noExplicitAny: the response type defaults to what the caller reads
32
+ export function useForm<F extends object, R = any>(initial: F): Form<F, R> {
33
+ const copy = () => structuredClone(initial)
34
+ const submit = async (method: string, url: string): Promise<boolean> => {
35
+ form.processing = true
36
+ form.clearErrors()
37
+ try {
38
+ const hasBody = method !== 'DELETE' || Object.keys(form.data as object).length > 0
39
+ const res = await fetch(url, {
40
+ method,
41
+ credentials: 'same-origin',
42
+ headers: {
43
+ accept: 'application/json',
44
+ ...(hasBody ? { 'content-type': 'application/json' } : {}),
45
+ ...csrfHeaders(),
46
+ },
47
+ body: hasBody ? JSON.stringify(form.data) : undefined,
48
+ })
49
+ const body = (res.headers.get('content-type') ?? '').includes('json') ? await res.json() : undefined
50
+ if (res.ok) {
51
+ form.response = body as UnwrapRef<R>
52
+ return true
53
+ }
54
+ if (res.status === 422 && body?.errors) {
55
+ for (const [field, messages] of Object.entries(body.errors as Record<string, string[]>))
56
+ (form.errors as Record<string, string>)[field] = messages[0] ?? ''
57
+ } else {
58
+ form.error = body?.detail ?? body?.title ?? `${res.status} ${res.statusText}`
59
+ }
60
+ return false
61
+ } catch (e) {
62
+ form.error = e instanceof Error ? e.message : String(e)
63
+ return false
64
+ } finally {
65
+ form.processing = false
66
+ }
67
+ }
68
+ const form = reactive({
69
+ data: copy(),
70
+ errors: {},
71
+ error: null as string | null,
72
+ processing: false,
73
+ response: undefined as unknown,
74
+ post: (url: string) => submit('POST', url),
75
+ put: (url: string) => submit('PUT', url),
76
+ patch: (url: string) => submit('PATCH', url),
77
+ delete: (url: string) => submit('DELETE', url),
78
+ reset() {
79
+ form.data = copy() as never
80
+ form.clearErrors()
81
+ },
82
+ clearErrors() {
83
+ form.errors = {}
84
+ form.error = null
85
+ },
86
+ })
87
+ return form as unknown as Form<F, R>
88
+ }
@@ -0,0 +1,50 @@
1
+ /** Formatters that run in the browser and on the server (no Node APIs). */
2
+
3
+ const digits = (currency: string) =>
4
+ new Intl.NumberFormat('en', { style: 'currency', currency }).resolvedOptions().maximumFractionDigits ?? 2
5
+
6
+ /** `formatMoney('220000', 'EUR', 'fr')` → `2 200,00 €` (amount in minor units; exact for any size). */
7
+ export function formatMoneyIn(
8
+ locale: string,
9
+ amount: { amount: unknown; currency: string } | bigint | number | string,
10
+ currency?: string,
11
+ ): string {
12
+ const value = typeof amount === 'object' && amount !== null ? amount : { amount, currency: currency ?? '' }
13
+ if (!value.currency) throw new Error('formatMoney(): a currency is needed')
14
+ const d = digits(value.currency)
15
+ const minor = BigInt(value.amount as string)
16
+ const negative = minor < 0n
17
+ const abs = (negative ? -minor : minor).toString().padStart(d + 1, '0')
18
+ const decimal = `${negative ? '-' : ''}${d ? `${abs.slice(0, -d)}.${abs.slice(-d)}` : abs}`
19
+ return new Intl.NumberFormat(locale, { style: 'currency', currency: value.currency }).format(decimal as `${number}`)
20
+ }
21
+
22
+ const STYLES = {
23
+ short: { dateStyle: 'short' },
24
+ medium: { dateStyle: 'medium' },
25
+ long: { dateStyle: 'long' },
26
+ full: { dateStyle: 'full' },
27
+ } as const
28
+
29
+ /** Calendar dates (`'YYYY-MM-DD'`) as is; instants in `tz` (default: the browser's). */
30
+ export function formatDateIn(
31
+ locale: string,
32
+ value: Date | string,
33
+ style: keyof typeof STYLES | Intl.DateTimeFormatOptions = 'medium',
34
+ tz?: string,
35
+ ): string {
36
+ const calendar = typeof value === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(value)
37
+ const date = calendar ? new Date(`${value}T12:00:00Z`) : new Date(value)
38
+ if (Number.isNaN(date.getTime())) throw new Error(`formatDate(): invalid date ${String(value)}`)
39
+ const base = typeof style === 'string' ? STYLES[style] : style
40
+ return new Intl.DateTimeFormat(locale, { ...base, timeZone: calendar ? 'UTC' : tz }).format(date)
41
+ }
42
+
43
+ /** Minutes as "2 h 30 min" with locale unit names. */
44
+ export function formatDurationIn(locale: string, minutes: number): string {
45
+ const h = Math.floor(minutes / 60)
46
+ const m = Math.round(minutes % 60)
47
+ const fmt = (n: number, unit: 'hour' | 'minute') =>
48
+ new Intl.NumberFormat(locale, { style: 'unit', unit, unitDisplay: 'narrow' }).format(n)
49
+ return h && m ? `${fmt(h, 'hour')} ${fmt(m, 'minute')}` : h ? fmt(h, 'hour') : fmt(m, 'minute')
50
+ }
@@ -0,0 +1,33 @@
1
+ import { reactive, watch } from 'vue'
2
+
3
+ const stores = new Map<string, object>()
4
+
5
+ /**
6
+ * State shared by every island on the page: `export const useCurrency = defineStore('currency', () => ({ code: 'EUR' }))`.
7
+ * `persist` keeps it in localStorage. On the server each call returns the initial state (never shared between
8
+ * requests).
9
+ */
10
+ export function defineStore<S extends object>(
11
+ name: string,
12
+ init: () => S,
13
+ options: { persist?: boolean } = {},
14
+ ): () => S {
15
+ return () => {
16
+ if (typeof window === 'undefined') return reactive(init()) as S
17
+ let store = stores.get(name) as S | undefined
18
+ if (!store) {
19
+ let initial = init()
20
+ const key = `cslug:store:${name}`
21
+ if (options.persist) {
22
+ try {
23
+ const saved = localStorage.getItem(key)
24
+ if (saved) initial = { ...initial, ...JSON.parse(saved) }
25
+ } catch {}
26
+ }
27
+ store = reactive(initial) as S
28
+ stores.set(name, store)
29
+ if (options.persist) watch(store, (value) => localStorage.setItem(key, JSON.stringify(value)), { deep: true })
30
+ }
31
+ return store
32
+ }
33
+ }
@@ -0,0 +1,35 @@
1
+ /** A named route as sent to the browser. */
2
+ export type ClientRoute = { path: string; domain?: string }
3
+
4
+ const fill = (pattern: string, params: Record<string, unknown>, name: string, used: Set<string>) =>
5
+ pattern.replace(/:([A-Za-z0-9_]+)/g, (_m, key: string) => {
6
+ const value = params[key]
7
+ if (value === undefined || value === null) throw new Error(`Route "${name}" needs parameter "${key}"`)
8
+ used.add(key)
9
+ return encodeURIComponent(String(value))
10
+ })
11
+
12
+ /** Same rules as @cslug/http's `urlFor` (without signing, which needs the server key). */
13
+ export function buildUrl(
14
+ routes: Record<string, ClientRoute>,
15
+ appUrl: string | undefined,
16
+ name: string,
17
+ params: Record<string, unknown> = {},
18
+ options: { absolute?: boolean; query?: Record<string, string | number | boolean | null | undefined> } = {},
19
+ ): string {
20
+ const route = routes[name]
21
+ if (!route) throw new Error(`No route named "${name}" (is it named, and allowed by config vue.routes?)`)
22
+ const used = new Set<string>()
23
+ const path = fill(route.path, params, name, used)
24
+ const host = route.domain ? fill(route.domain, params, name, used) : undefined
25
+ const query = new URLSearchParams()
26
+ for (const [k, v] of Object.entries(params))
27
+ if (!used.has(k) && v !== undefined && v !== null) query.set(k, String(v))
28
+ for (const [k, v] of Object.entries(options.query ?? {})) if (v !== undefined && v !== null) query.set(k, String(v))
29
+ const base = appUrl ? new URL(appUrl) : undefined
30
+ const origin =
31
+ options.absolute || (host && host !== base?.hostname)
32
+ ? `${base?.protocol ?? 'https:'}//${host ?? base?.host ?? ''}`
33
+ : ''
34
+ return `${origin}${path}${query.size ? `?${query}` : ''}`
35
+ }
package/src/types.ts ADDED
@@ -0,0 +1,12 @@
1
+ /** `defineOptions({ lang: ['todos'] })` in an island: the translation namespaces it needs in the browser. */
2
+ declare module 'vue' {
3
+ interface ComponentCustomOptions {
4
+ lang?: string[]
5
+ }
6
+ interface ComponentCustomProps {
7
+ /** Make this component an island: load, idle, visible, none, media:(…). */
8
+ hydrate?: 'load' | 'idle' | 'visible' | 'none' | `media:${string}`
9
+ }
10
+ }
11
+
12
+ export {}