@cslug/vue 0.1.0 → 0.3.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/docs/README.md CHANGED
@@ -22,4 +22,5 @@ per island component, writing hashed files and `manifest.json` to `public/build/
22
22
  process builds at start, rebuilds on change and serves live reload at `/__cslug/live`.
23
23
 
24
24
  Tests that import views statically need the loader from the first line:
25
- `[test] preload = ["@cslug/vue/register"]` in `bunfig.toml`.
25
+ `[test] preload = ["@cslug/vue/register"]` in `bunfig.toml`. Several app roots can register the loader in one process (a test
26
+ suite with several fixture apps): each `.vue` file compiles against the registered root that contains it.
package/docs/api.md CHANGED
@@ -4,6 +4,7 @@
4
4
  |---|---|
5
5
  | `view(Page, props, { status?, headers? })` | A `Responsable`: renders the page in the request |
6
6
  | `renderPage(Page, props, { http?, static? })` | `{ html, state }` (`state.islands`, `state.modules`) |
7
+ | `onView((page, props, ctx) => …)` | Be told of every page `view()` renders (the test kit's `assertView`); returns an unsubscribe function |
7
8
  | `renderStandalone(Page, props)` | One self-contained HTML file: no scripts, CSS and `public/` images inlined, islands as plain HTML |
8
9
  | `<Assets entry="client" />` | In the layout `<head>` |
9
10
  | `hydrate="load \| idle \| visible \| media:(…) \| none"` | On any component use; `idle` waits at most 2 s; `:ssr="false"` + `<template #fallback>` to skip server rendering |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cslug/vue",
3
- "version": "0.1.0",
3
+ "version": "0.3.0",
4
4
  "description": "Vue views rendered on the server, components hydrated as islands, composables and asset build.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -33,9 +33,9 @@
33
33
  "bun": ">=1.3.14"
34
34
  },
35
35
  "peerDependencies": {
36
- "@cslug/core": "0.1.0",
37
- "@cslug/http": "0.1.0",
38
- "@cslug/validation": "0.1.0",
36
+ "@cslug/core": "0.3.0",
37
+ "@cslug/http": "0.3.0",
38
+ "@cslug/validation": "0.3.0",
39
39
  "vue": "^3.5.0",
40
40
  "sass": "^1.80.0",
41
41
  "tailwindcss": "^4.0.0",
package/src/build.ts CHANGED
@@ -148,9 +148,20 @@ export async function buildAssets(options: BuildOptions): Promise<BuildResult> {
148
148
  __VUE_PROD_HYDRATION_MISMATCH_DETAILS__: dev ? 'true' : 'false',
149
149
  },
150
150
  plugins,
151
+ // report the errors ourselves: with `throw`, Bun only says "Bundle failed"
152
+ throw: false,
151
153
  })
152
154
  if (!result.success)
153
- throw new AggregateError(result.logs, `Asset build failed:\n${result.logs.map((l) => String(l)).join('\n')}`)
155
+ throw new AggregateError(
156
+ result.logs,
157
+ `Asset build failed:\n${result.logs
158
+ .map((l) => {
159
+ // ResolveMessage.referrer: the file that made the import (a server module reaching a browser bundle)
160
+ const where = (l as { referrer?: string }).referrer || l.position?.file
161
+ return `${l.message}${where ? ` (in ${relative(root, where)}${l.position?.line ? `:${l.position.line}` : ''})` : ''}`
162
+ })
163
+ .join('\n')}`,
164
+ )
154
165
 
155
166
  // map outputs back to their entry: "resources/components/day-card-1a2b3c4d.js" → "resources/components/day-card"
156
167
  const stem = (file: string) =>
@@ -16,6 +16,7 @@ export type PageData = {
16
16
  }
17
17
 
18
18
  let cached: PageData | undefined
19
+ /** The data the server embedded in the page (`#cslug-data`): locale, messages, routes, islands. Read once. */
19
20
  export function pageData(): PageData {
20
21
  if (cached) return cached
21
22
  const el = typeof document === 'undefined' ? null : document.getElementById('cslug-data')
package/src/compiler.ts CHANGED
@@ -133,6 +133,7 @@ export function compileScss(source: string, filename: string, root: string): str
133
133
  }).css
134
134
  }
135
135
 
136
+ /** Compile one `.vue` file to a module (server or client build), with its scoped CSS. */
136
137
  export function compileSfc(filename: string, options: CompileOptions): CompiledSfc {
137
138
  const source = rewriteIslands(readFileSync(filename, 'utf8'), filename)
138
139
  const id = componentId(filename, options.root)
@@ -2,7 +2,7 @@
2
2
  * Composables for views and components. These are the server versions; the browser build (M4b) resolves
3
3
  * `@cslug/vue` to versions with the same names and signatures.
4
4
  */
5
- import { currentApp, currentLocale, formatDate, formatMoney, Translator, t, tr } from '@cslug/core'
5
+ import { type AuthUser, currentApp, currentLocale, formatDate, formatMoney, Translator, t, tr } from '@cslug/core'
6
6
  import { route as httpRoute, Router, type UrlOptions } from '@cslug/http'
7
7
  import { renderState } from './render'
8
8
  import { formatDurationIn } from './shared/format'
@@ -10,7 +10,7 @@ import { formatDurationIn } from './shared/format'
10
10
  export type RequestInfo = {
11
11
  locale: string
12
12
  /** The signed-in user (set by @cslug/auth), or null. */
13
- user: unknown
13
+ user: AuthUser | null
14
14
  csrfToken: string
15
15
  /** First error message per field, after a failed form post. */
16
16
  errors: Record<string, string>
@@ -38,14 +38,14 @@ export function useRequest(): RequestInfo {
38
38
  alternates: [],
39
39
  }
40
40
  }
41
- const hasSession = ctx.session.constructor.name !== 'MissingSession'
41
+ const hasSession = ctx.session.available
42
42
  const errors = hasSession
43
43
  ? Object.fromEntries(Object.entries(ctx.session.errors()).map(([k, v]) => [k, v[0] ?? '']))
44
44
  : {}
45
45
  const url = new URL(ctx.request.url)
46
46
  return {
47
47
  locale: ctx.locale,
48
- user: (ctx as unknown as { user?: unknown }).user ?? null,
48
+ user: (ctx as unknown as { user?: AuthUser | null }).user ?? null,
49
49
  csrfToken: hasSession ? ctx.session.token() : '',
50
50
  errors,
51
51
  old: hasSession ? (ctx.session.old() as Record<string, unknown>) : {},
package/src/index.ts CHANGED
@@ -16,6 +16,7 @@ export {
16
16
  type AssetManifest,
17
17
  Assets,
18
18
  CslugIsland,
19
+ onView,
19
20
  type RenderOptions,
20
21
  type RenderState,
21
22
  readManifest,
package/src/loader.ts CHANGED
@@ -4,30 +4,38 @@ import { type CompiledSfc, SfcCache } from './compiler'
4
4
  /** CSS of every compiled component, by component id (collected into the page when it renders). */
5
5
  export const componentStyles = new Map<string, string>()
6
6
  const cache = new SfcCache()
7
- let registered: string | undefined
7
+ const roots = new Map<string, { production?: boolean }>()
8
+
9
+ /** The registered app root containing `file` (the longest one), else the first registered. */
10
+ function rootOf(file: string): string {
11
+ let best: string | undefined
12
+ for (const root of roots.keys()) if (file.startsWith(`${root}/`) && (!best || root.length > best.length)) best = root
13
+ return best ?? (roots.keys().next().value as string)
14
+ }
8
15
 
9
16
  /**
10
17
  * Teach Bun to import `.vue` files (compiled for the server). `VueProvider` calls this; tests that import views
11
18
  * statically need it earlier, through bunfig.toml: `[test] preload = ["@cslug/vue/register"]`.
19
+ * Several roots may be registered in one process (test suites with several fixture apps): each `.vue` file is
20
+ * compiled, and its `@/…` imports resolved, against the root that contains it.
12
21
  */
13
22
  export function registerVueLoader(root: string = process.cwd(), options: { production?: boolean } = {}): void {
14
- if (registered) {
15
- if (registered !== root)
16
- throw new CslugError('vue.loader_root', `The .vue loader is already registered for ${registered}`)
17
- return
18
- }
19
- registered = root
23
+ if (roots.has(root)) return
24
+ roots.set(root, options)
25
+ if (roots.size > 1) return // the plugin is already installed
20
26
  Bun.plugin({
21
27
  name: 'cslug-vue-server',
22
28
  setup(build) {
23
29
  // `@/…` → resources/… (as in the browser build)
24
- build.onResolve({ filter: /^@\// }, (args) => ({
25
- path: Bun.resolveSync(`${root}/resources/${args.path.slice(2)}`, root),
26
- }))
30
+ build.onResolve({ filter: /^@\// }, (args) => {
31
+ const base = rootOf(args.importer)
32
+ return { path: Bun.resolveSync(`${base}/resources/${args.path.slice(2)}`, base) }
33
+ })
27
34
  build.onLoad({ filter: /\.vue$/ }, ({ path }) => {
35
+ const base = rootOf(path)
28
36
  let compiled: CompiledSfc
29
37
  try {
30
- compiled = cache.get(path, { root, ssr: true, production: options.production })
38
+ compiled = cache.get(path, { root: base, ssr: true, production: roots.get(base)?.production })
31
39
  } catch (error) {
32
40
  throw new CslugError('vue.compile', error instanceof Error ? error.message : String(error), { cause: error })
33
41
  }
@@ -38,4 +46,5 @@ export function registerVueLoader(root: string = process.cwd(), options: { produ
38
46
  })
39
47
  }
40
48
 
41
- export const vueLoaderRoot = () => registered
49
+ /** The first registered root. */
50
+ export const vueLoaderRoot = () => roots.keys().next().value as string | undefined
package/src/render.ts CHANGED
@@ -84,6 +84,7 @@ export type AssetManifest = {
84
84
  }
85
85
 
86
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. */
87
88
  export function readManifest(root: string): AssetManifest | undefined {
88
89
  const path = join(root, 'public/build/manifest.json')
89
90
  if (!existsSync(path)) return undefined
@@ -153,7 +154,7 @@ function pageData(state: RenderState, manifest: AssetManifest): PageData {
153
154
  }
154
155
  }
155
156
 
156
- const isMissing = (ctx: HttpContext) => ctx.session.constructor.name === 'MissingSession'
157
+ const isMissing = (ctx: HttpContext) => !ctx.session.available
157
158
 
158
159
  export type RenderOptions = { http?: HttpContext; static?: boolean; root?: string }
159
160
 
@@ -193,6 +194,17 @@ export async function renderPage(
193
194
  return { html: /^\s*<html[\s>]/i.test(html) ? `<!doctype html>${html}` : html, state }
194
195
  }
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
+
196
208
  /** `return view(ShowCircuit, { circuit, days })` from a controller. */
197
209
  export class ViewResponse implements Responsable {
198
210
  constructor(
@@ -202,6 +214,7 @@ export class ViewResponse implements Responsable {
202
214
  ) {}
203
215
 
204
216
  async toResponse(ctx: HttpContext): Promise<Response> {
217
+ for (const listener of viewListeners) listener(this.page, this.props, ctx)
205
218
  const { html } = await renderPage(this.page, this.props, { http: ctx })
206
219
  const headers = new Headers(this.init.headers)
207
220
  if (!headers.has('content-type')) headers.set('content-type', 'text/html; charset=utf-8')
@@ -216,6 +229,7 @@ type PropsOf<C> = C extends new (
216
229
  ? Omit<P, `on${string}` | 'key' | 'ref' | 'class' | 'style'>
217
230
  : Record<string, unknown>
218
231
 
232
+ /** Return a page from a handler: `return view(BookingShow, { booking })`. Props are typed from the page. */
219
233
  export function view<C extends Component>(
220
234
  page: C,
221
235
  props: PropsOf<C> | Record<string, unknown> = {},
@@ -16,9 +16,7 @@ export function formatMoneyIn(
16
16
  const negative = minor < 0n
17
17
  const abs = (negative ? -minor : minor).toString().padStart(d + 1, '0')
18
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(
20
- decimal as unknown as number,
21
- )
19
+ return new Intl.NumberFormat(locale, { style: 'currency', currency: value.currency }).format(decimal as `${number}`)
22
20
  }
23
21
 
24
22
  const STYLES = {