@cslug/vue 0.8.0 → 0.10.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
@@ -11,7 +11,9 @@ browser builds see the same input (see spikes/a-vue-islands). At render time:
11
11
  2. An island renders its component with the **serialized** props (what the browser will get) inside
12
12
  `<cslug-island data-island data-hydrate data-props>`, and records its `lang` namespaces.
13
13
  3. `<Assets>` was a placeholder. It becomes the CSRF meta tag, the entry CSS, the component CSS and, only if
14
- the page has islands, the page data (`#cslug-data`), the island chunk preloads and the client script.
14
+ the page has islands, the page data (`#cslug-data`), the island chunk preloads and the client script. With a
15
+ CSP nonce on the request (`ctx.nonce`, set by `csp()` from `@cslug/security`), its `<script>` and `<style>` tags
16
+ and the `cslug dev` client carry it; `useRequest().nonce` gives it to your own inline tags.
15
17
 
16
18
  **In the browser**, `@cslug/vue` resolves to `src/client` (the `browser` export condition). `mountIslands()`
17
19
  imports each island's chunk when its `hydrate` condition is met and mounts it. `useT` formats ICU messages
@@ -19,7 +21,13 @@ with `@cslug/validation`'s formatter, the same one the server uses.
19
21
 
20
22
  **The build** (`cslug build`, or `@cslug/vue/build`) runs `Bun.build` with the client entries plus one entry
21
23
  per island component, writing hashed files and `manifest.json` to `public/build/`. Under `cslug dev`, the web
22
- process builds at start, rebuilds on change and serves live reload at `/__cslug/live`.
24
+ process builds at start, rebuilds on change and serves `/__cslug/live` (SSE) to an inline dev client
25
+ (`live-client.ts`). A changed `.vue` file is recompiled in the server process (`reloadComponent()` patches the
26
+ imported component objects: `bun --watch` does not see plugin-loaded files) and, with HMR on, built alone into
27
+ `public/build/hmr/` with `vue`, `@cslug/vue` and already-loaded components taken from the page; the browser hands
28
+ it to Vue's `__VUE_HMR_RUNTIME__` (`rerender` for template-only changes, `reload` otherwise). Development browser
29
+ builds keep the render function separate from `setup` and set `__hmrId`; production builds do not, and drop
30
+ `client/hmr.ts`. `cslug dev --no-hmr` (CSLUG_HMR=0) keeps live reload only.
23
31
 
24
32
  Tests that import views statically need the loader from the first line:
25
33
  `[test] preload = ["@cslug/vue/register"]` in `bunfig.toml`. Several app roots can register the loader in one process (a test
package/docs/api.md CHANGED
@@ -9,7 +9,7 @@
9
9
  | `<Assets entry="client" />` | In the layout `<head>` |
10
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 |
11
11
  | `serialize(value)` / `Serialized<T>` | What an island receives (bigint → string, Date → ISO); type island props per prop: `defineProps<{ day: Serialized<Day> }>()` |
12
- | `useRequest()` | `locale`, `user`, `csrfToken`, `errors` (first message per field), `old`, `flash`, `url`, `alternates` |
12
+ | `useRequest()` | `locale`, `user`, `csrfToken`, `errors` (first message per field), `old`, `flash`, `url`, `alternates`, `nonce` (the CSP nonce, or `''`) |
13
13
  | `useT()` | `t`, `tr`, `locale`, `formatMoney`, `formatDate` in the current locale |
14
14
  | `route(name, params?, options?)` | |
15
15
  | `formatDuration(minutes)`, `formatMoney`, `formatDate` | |
@@ -21,7 +21,7 @@
21
21
  | `buildAssets({ root, entries?, dev?, tailwind? })` | Also at `@cslug/vue/build` with `findIslands` and `aliasPlugin` |
22
22
  | `cslug build [--dev]`, `cslug typecheck` | Commands (vue-tsc must be installed for `typecheck`) |
23
23
  | `config('vue.routes')` | Name prefixes of the routes sent to the browser (default: all named routes) |
24
- | `VueProvider` | Registers the `.vue` loader and the commands; dev mode under `cslug dev` |
24
+ | `VueProvider` | Registers the `.vue` loader and the commands; under `cslug dev` (CSLUG_DEV=1, never in production): asset watcher, `/__cslug/live`, HMR unless CSLUG_HMR=0 |
25
25
  | `registerVueLoader(root)` | What the provider and `@cslug/vue/register` call |
26
26
  | `compileSfc(file, { root, ssr })`, `rewriteIslands(source, file)` | Used by the loader and the build |
27
27
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cslug/vue",
3
- "version": "0.8.0",
3
+ "version": "0.10.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.8.0",
37
- "@cslug/http": "0.8.0",
38
- "@cslug/validation": "0.8.0",
36
+ "@cslug/core": "0.10.0",
37
+ "@cslug/http": "0.10.0",
38
+ "@cslug/validation": "0.10.0",
39
39
  "vue": "^3.5.0",
40
40
  "sass": "^1.80.0",
41
41
  "tailwindcss": "^4.0.0",
package/src/build.ts CHANGED
@@ -78,7 +78,8 @@ export const aliasPlugin = (root: string): BunPlugin => ({
78
78
  },
79
79
  })
80
80
 
81
- function vuePlugins(root: string, dev: boolean): BunPlugin[] {
81
+ /** The `.vue` (client output) and `.scss` plugins, after the `@/` alias. */
82
+ export function vuePlugins(root: string, dev: boolean): BunPlugin[] {
82
83
  const cache = new SfcCache()
83
84
  return [
84
85
  aliasPlugin(root),
@@ -11,8 +11,6 @@ export type PageData = {
11
11
  appUrl?: string
12
12
  /** Island id → chunk URL. */
13
13
  islands: Record<string, string>
14
- /** Development: the live-reload endpoint. */
15
- live?: string
16
14
  }
17
15
 
18
16
  let cached: PageData | undefined
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Development only (`cslug dev` builds; dropped from production bundles): expose the page's Vue and @cslug/vue to
3
+ * the hot modules the dev server builds, so an updated component shares the running instances instead of loading
4
+ * a second copy.
5
+ */
6
+ import * as vue from 'vue'
7
+ import * as cslug from './index'
8
+
9
+ ;(globalThis as unknown as { __cslug_hmr?: Record<string, unknown> }).__cslug_hmr = { vue, '@cslug/vue': cslug }
@@ -70,7 +70,7 @@ type MountOptions = { setup?: (app: App, island: { id: string; element: HTMLElem
70
70
 
71
71
  /**
72
72
  * Hydrate every `<cslug-island>` when its condition is met (load, idle, visible, media:…). Each island is its own
73
- * Vue app; `setup` installs app-wide plugins. In development, also connects to live reload.
73
+ * Vue app; `setup` installs app-wide plugins.
74
74
  */
75
75
  export function mountIslands(options: MountOptions = {}): void {
76
76
  const data = pageData()
@@ -111,22 +111,6 @@ export function mountIslands(options: MountOptions = {}): void {
111
111
  else mq.addEventListener('change', run, { once: true })
112
112
  }
113
113
  }
114
- if (data.live) liveReload(data.live)
115
- }
116
-
117
- /** Reload when the dev server says so, or when it comes back after a restart. */
118
- function liveReload(url: string): void {
119
- let wasDown = false
120
- const source = new EventSource(url)
121
- source.addEventListener('reload', () => location.reload())
122
- source.addEventListener('css', () => {
123
- for (const link of document.querySelectorAll<HTMLLinkElement>('link[rel="stylesheet"]'))
124
- link.href = link.href.replace(/(\?.*)?$/, `?t=${Date.now()}`)
125
- })
126
- source.onerror = () => {
127
- wasDown = true
128
- }
129
- source.onopen = () => {
130
- if (wasDown) location.reload()
131
- }
114
+ // development: let hot modules reuse this page's Vue (the condition is constant, so production drops the chunk)
115
+ if (process.env.NODE_ENV !== 'production') import('./hmr').catch(() => {})
132
116
  }
package/src/compiler.ts CHANGED
@@ -146,8 +146,37 @@ export function compileSfc(filename: string, options: CompileOptions): CompiledS
146
146
 
147
147
  const scoped = descriptor.styles.some((s) => s.scoped)
148
148
  const scopeId = `data-v-${hash}`
149
+ // development in the browser: the render function stays separate from setup, so a template-only change can be
150
+ // swapped in without losing the component's state (HMR)
151
+ const hot = !options.ssr && !options.production
149
152
  let code: string
150
- if (descriptor.script || descriptor.scriptSetup) {
153
+ if ((descriptor.script || descriptor.scriptSetup) && hot) {
154
+ const script = compileScript(descriptor, {
155
+ id: hash,
156
+ inlineTemplate: false,
157
+ genDefaultAs: '_sfc_main',
158
+ isProd: false,
159
+ fs: { fileExists: existsSync, readFile: (f) => readFileSync(f, 'utf8') },
160
+ })
161
+ code = script.content
162
+ if (descriptor.template) {
163
+ const lang = descriptor.scriptSetup?.lang ?? descriptor.script?.lang
164
+ const t = compileTemplate({
165
+ source: descriptor.template.content,
166
+ filename,
167
+ id: hash,
168
+ scoped,
169
+ compilerOptions: {
170
+ scopeId: scoped ? scopeId : undefined,
171
+ bindingMetadata: script.bindings,
172
+ isTS: lang === 'ts',
173
+ expressionPlugins: lang === 'ts' ? ['typescript'] : [],
174
+ },
175
+ })
176
+ if (t.errors.length) throw new Error(`${filename}: ${t.errors.join('; ')}`)
177
+ code += `\n${t.code.replace(/^export function render/m, 'function render')}\n_sfc_main.render = render`
178
+ }
179
+ } else if (descriptor.script || descriptor.scriptSetup) {
151
180
  code = compileScript(descriptor, {
152
181
  id: hash,
153
182
  inlineTemplate: true,
@@ -188,6 +217,10 @@ export function compileSfc(filename: string, options: CompileOptions): CompiledS
188
217
  `_sfc_main.__cslugId = ${JSON.stringify(id)}`,
189
218
  scoped ? `_sfc_main.__scopeId = ${JSON.stringify(scopeId)}` : '',
190
219
  options.production ? '' : `_sfc_main.__file = ${JSON.stringify(filename)}`,
220
+ // HMR: Vue tracks instances by __hmrId; the registry holds the first definition loaded on the page, the one
221
+ // every instance (and every later hot module importing this component) shares
222
+ hot ? `_sfc_main.__hmrId = ${JSON.stringify(id)}` : '',
223
+ hot ? `;(globalThis.__cslug_components ??= {})[${JSON.stringify(id)}] ??= _sfc_main` : '',
191
224
  ]
192
225
  // server: record that this component rendered (its CSS goes into the page) and which namespaces islands need
193
226
  if (options.ssr) {
@@ -203,14 +236,19 @@ export function compileSfc(filename: string, options: CompileOptions): CompiledS
203
236
 
204
237
  /** Compiled results by file, reused while the file is unchanged. */
205
238
  export class SfcCache {
206
- private readonly entries = new Map<string, { mtime: number; result: CompiledSfc }>()
239
+ private readonly entries = new Map<string, { mtime: number; size: number; result: CompiledSfc }>()
240
+ /** Forget every result (development: a stylesheet a component `@use`s changed). */
241
+ clear(): void {
242
+ this.entries.clear()
243
+ }
207
244
  get(filename: string, options: CompileOptions): CompiledSfc {
208
245
  const key = `${options.ssr ? 's' : 'c'}:${filename}`
209
- const mtime = statSync(filename).mtimeMs
246
+ // the size too: a file written twice within the same millisecond (truncate, then write) keeps its mtime
247
+ const { mtimeMs: mtime, size } = statSync(filename)
210
248
  const hit = this.entries.get(key)
211
- if (hit && hit.mtime === mtime) return hit.result
249
+ if (hit && hit.mtime === mtime && hit.size === size) return hit.result
212
250
  const result = compileSfc(filename, options)
213
- this.entries.set(key, { mtime, result })
251
+ this.entries.set(key, { mtime, size, result })
214
252
  return result
215
253
  }
216
254
  }
@@ -21,6 +21,8 @@ export type RequestInfo = {
21
21
  url: string
22
22
  /** This page in each supported locale (for `<link rel="alternate" hreflang>`), when its route has `:locale`. */
23
23
  alternates: { locale: string; url: string }[]
24
+ /** The CSP nonce for your own inline `<script>` / `<style>` (`csp()` from @cslug/security), or ''. */
25
+ nonce: string
24
26
  }
25
27
 
26
28
  /** The current request, read-only, on the server. Inside a hydrated island it throws: pass props instead. */
@@ -36,6 +38,7 @@ export function useRequest(): RequestInfo {
36
38
  flash: {},
37
39
  url: '',
38
40
  alternates: [],
41
+ nonce: '',
39
42
  }
40
43
  }
41
44
  const hasSession = ctx.session.available
@@ -52,6 +55,7 @@ export function useRequest(): RequestInfo {
52
55
  flash: hasSession ? ctx.session.flashed() : {},
53
56
  url: url.toString(),
54
57
  alternates: alternates(ctx, url),
58
+ nonce: ctx.nonce ?? '',
55
59
  }
56
60
  }
57
61
 
package/src/dev.ts CHANGED
@@ -1,18 +1,22 @@
1
- import { watch } from 'node:fs'
2
- import { join } from 'node:path'
1
+ import { existsSync, readdirSync, readFileSync, statSync, watch } from 'node:fs'
2
+ import { basename, dirname, extname, join, relative } from 'node:path'
3
3
  import { type Application, Logger } from '@cslug/core'
4
4
  import type { RouteRegistrar } from '@cslug/http'
5
- import { buildAssets } from './build'
5
+ import type { BunPlugin } from 'bun'
6
+ import { parse } from 'vue/compiler-sfc'
7
+ import { type BuildOptions, buildAssets, vuePlugins } from './build'
8
+ import { componentId } from './compiler'
9
+ import { refreshComponentStyles, reloadComponent } from './loader'
6
10
 
7
11
  const LIVE = '/__cslug/live'
8
- let enabled = false
12
+ let state: { hmr: boolean } | undefined
9
13
  const clients = new Set<ReadableStreamDefaultController<Uint8Array>>()
10
14
 
11
- /** The live-reload endpoint when `cslug dev` runs (CSLUG_DEV=1), else undefined. */
12
- export const liveReloadUrl = () => (enabled ? LIVE : undefined)
15
+ /** The live endpoint and whether HMR is on, when `cslug dev` runs (CSLUG_DEV=1); else undefined. */
16
+ export const liveConfig = () => (state ? { url: LIVE, hmr: state.hmr } : undefined)
13
17
 
14
- function broadcast(event: 'reload' | 'css'): void {
15
- const chunk = new TextEncoder().encode(`event: ${event}\ndata: {}\n\n`)
18
+ function broadcast(event: 'reload' | 'css' | 'vue', data: object = {}): void {
19
+ const chunk = new TextEncoder().encode(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`)
16
20
  for (const c of clients) {
17
21
  try {
18
22
  c.enqueue(chunk)
@@ -22,34 +26,195 @@ function broadcast(event: 'reload' | 'css'): void {
22
26
  }
23
27
  }
24
28
 
29
+ /** What a `.vue` change touched: the script (remount), the template only (re-render, state kept) or the styles. */
30
+ type Kind = 'reload' | 'rerender' | 'style' | 'none'
31
+ type Parts = { script: string; template: string; style: string }
32
+
33
+ function sfcParts(file: string): Parts | undefined {
34
+ try {
35
+ const { descriptor } = parse(readFileSync(file, 'utf8'), { filename: file })
36
+ const scoped = descriptor.styles.some((s) => s.scoped)
37
+ return {
38
+ // `scoped` changes the scope id the template is compiled with
39
+ script: [descriptor.script?.content, descriptor.scriptSetup?.content, descriptor.scriptSetup?.lang, scoped].join(
40
+ '\0',
41
+ ),
42
+ template: descriptor.template?.content ?? '',
43
+ style: descriptor.styles.map((s) => `${s.lang}\0${s.scoped}\0${s.content}`).join('\0'),
44
+ }
45
+ } catch {
46
+ return undefined
47
+ }
48
+ }
49
+
50
+ const vueFiles = (dir: string): string[] =>
51
+ !existsSync(dir)
52
+ ? []
53
+ : readdirSync(dir).flatMap((f) => {
54
+ const p = join(dir, f)
55
+ return statSync(p).isDirectory() ? vueFiles(p) : f.endsWith('.vue') ? [p] : []
56
+ })
57
+
25
58
  /**
26
- * Development: build the assets now, rebuild when resources/ changes, and tell open pages to reload (CSS-only
27
- * changes swap the stylesheets). Server-side `.vue` changes restart the process (`bun --watch`); pages reconnect
28
- * and reload.
59
+ * Hot module for one changed `.vue` file: the component alone, with `vue` and `@cslug/vue` taken from the page
60
+ * (`client/hmr.ts`) and the components it imports taken from the page's registry when they are loaded there.
29
61
  */
30
- export async function startDev(app: Application, options: Parameters<typeof buildAssets>[0]): Promise<() => void> {
31
- enabled = true
62
+ async function buildHot(file: string, options: BuildOptions, n: number): Promise<string> {
63
+ const { root } = options
64
+ const outdir = join(root, options.outdir ?? 'public/build', 'hmr')
65
+ const publicPath = `${options.publicPath ?? '/build/'}hmr/`
66
+ const globals: Record<string, string[]> = {
67
+ vue: Object.keys(await import('vue')),
68
+ // by URL: a static path would pull the browser entry into apps' server type-check
69
+ '@cslug/vue': Object.keys(await import(new URL('./client/index.ts', import.meta.url).href)),
70
+ }
71
+ const shared: BunPlugin = {
72
+ name: 'cslug-hot',
73
+ setup(build) {
74
+ build.onResolve({ filter: /^(vue|@cslug\/vue)$/ }, (args) => ({ path: args.path, namespace: 'cslug-global' }))
75
+ build.onLoad({ filter: /.*/, namespace: 'cslug-global' }, ({ path }) => ({
76
+ contents: [
77
+ `const m = globalThis.__cslug_hmr[${JSON.stringify(path)}]`,
78
+ `export const { ${(globals[path] ?? []).filter((k) => k !== 'default' && /^[A-Za-z_$][\w$]*$/.test(k)).join(', ')} } = m`,
79
+ ].join('\n'),
80
+ loader: 'js',
81
+ }))
82
+ // components imported by the changed one: the page's definition when it has one (so their instances are kept)
83
+ build.onResolve({ filter: /\.vue$/ }, (args) => {
84
+ if (args.kind.startsWith('entry-point') || args.namespace === 'cslug-live') return undefined
85
+ const path = args.path.startsWith('@/')
86
+ ? Bun.resolveSync(join(root, 'resources', args.path.slice(2)), root)
87
+ : Bun.resolveSync(args.path, dirname(args.importer))
88
+ return { path, namespace: 'cslug-live' }
89
+ })
90
+ build.onLoad({ filter: /.*/, namespace: 'cslug-live' }, ({ path }) => ({
91
+ contents: `import fresh from ${JSON.stringify(path)}\nexport default globalThis.__cslug_components?.[${JSON.stringify(componentId(path, root))}] ?? fresh`,
92
+ loader: 'js',
93
+ }))
94
+ build.onResolve({ filter: /\.vue$/, namespace: 'cslug-live' }, (args) => ({ path: args.path }))
95
+ },
96
+ }
97
+ const result = await Bun.build({
98
+ entrypoints: [file],
99
+ root,
100
+ outdir,
101
+ target: 'browser',
102
+ format: 'esm',
103
+ conditions: ['browser'],
104
+ naming: `[name]-${n}.[ext]`,
105
+ define: { 'process.env.NODE_ENV': '"development"', __VUE_OPTIONS_API__: 'true', __VUE_PROD_DEVTOOLS__: 'false' },
106
+ plugins: [shared, ...vuePlugins(root, true)],
107
+ throw: false,
108
+ })
109
+ const out = result.outputs.find((o) => o.kind === 'entry-point')
110
+ if (!result.success || !out) throw new AggregateError(result.logs, `Hot update of ${relative(root, file)} failed`)
111
+ return publicPath + relative(outdir, out.path).replace(/\\/g, '/')
112
+ }
113
+
114
+ /**
115
+ * Development: build the assets now, rebuild when resources/ changes, and tell open pages (SSE):
116
+ * - a `.vue` file: patch the server's copy (pages render the new template), then hot-update the islands that use it
117
+ * (`hmr`), else reload the pages that rendered it;
118
+ * - a stylesheet: swap the stylesheets and the component styles that `@use` it;
119
+ * - anything else in resources/ (client `.ts`, images…): reload.
120
+ * Server code outside resources/ restarts the process (`bun --watch`); pages reconnect and reload.
121
+ */
122
+ export async function startDev(app: Application, options: BuildOptions & { hmr?: boolean }): Promise<() => void> {
123
+ const hmr = options.hmr ?? true
124
+ state = { hmr }
32
125
  const log = app.resolve(Logger)
33
- const rebuild = async (css: boolean) => {
126
+ const resources = join(app.rootDir, 'resources')
127
+ const known = new Map<string, Parts | undefined>()
128
+ for (const f of vueFiles(resources)) known.set(f, sfcParts(f))
129
+ let hot = 0
130
+
131
+ const build = async () => {
132
+ const { ms } = await buildAssets(options)
133
+ log.info('vue.assets_built', { ms })
134
+ }
135
+
136
+ const updateVue = async (file: string): Promise<boolean> => {
137
+ if (!existsSync(file)) return false
138
+ const before = known.get(file)
139
+ const after = sfcParts(file)
140
+ const kind: Kind =
141
+ !before || !after || before.script !== after.script
142
+ ? 'reload'
143
+ : before.template !== after.template
144
+ ? 'rerender'
145
+ : before.style !== after.style
146
+ ? 'style'
147
+ : 'none'
148
+ if (kind === 'none') return true
149
+ const server = await reloadComponent(file)
150
+ const id = server?.id ?? componentId(file, app.rootDir)
151
+ const url = hmr && kind !== 'style' ? await buildHot(file, options, ++hot) : undefined
152
+ // only once it worked: a save caught half-written fails, and the next event must not look like "no change"
153
+ known.set(file, after)
154
+ broadcast('vue', { id, kind, ...(url ? { url } : {}), ...(server ? { css: server.css } : {}) })
155
+ log.info('vue.hot_update', {
156
+ component: id,
157
+ kind: url ? kind : 'reload',
158
+ server: server ? 'recompiled' : 'not loaded',
159
+ })
160
+ return true
161
+ }
162
+
163
+ const flush = async (changed: Set<string>) => {
164
+ const files = [...changed]
165
+ const vue = files.filter((f) => f.endsWith('.vue'))
166
+ const styles = files.filter((f) => /\.s?css$/.test(f))
167
+ const other = files.filter((f) => !vue.includes(f) && !styles.includes(f))
34
168
  try {
35
- const { ms } = await buildAssets(options)
36
- log.info('vue.assets_built', { ms })
37
- broadcast(css ? 'css' : 'reload')
169
+ await build()
170
+ // every changed component is recompiled on the server, even when the pages reload anyway
171
+ let reload = other.length > 0
172
+ for (const f of vue) if (!(await updateVue(f))) reload = true
173
+ if (reload) return broadcast('reload')
174
+ if (styles.length) broadcast('css', { styles: refreshComponentStyles(known.keys()) })
38
175
  } catch (error) {
39
176
  log.error('vue.assets_failed', { error })
40
177
  }
41
178
  }
42
- await rebuild(false)
179
+
180
+ try {
181
+ await build()
182
+ } catch (error) {
183
+ log.error('vue.assets_failed', { error })
184
+ }
185
+ // a comment every few seconds keeps idle connections under Bun.serve's idle timeout (a drop would reload pages)
186
+ const heartbeat = setInterval(() => {
187
+ const ping = new TextEncoder().encode(': ping\n\n')
188
+ for (const c of clients) {
189
+ try {
190
+ c.enqueue(ping)
191
+ } catch {
192
+ clients.delete(c)
193
+ }
194
+ }
195
+ }, 5000)
43
196
  let timer: ReturnType<typeof setTimeout> | undefined
44
- const watcher = watch(join(app.rootDir, 'resources'), { recursive: true }, (_event, file) => {
197
+ let pending = new Set<string>()
198
+ let running = Promise.resolve()
199
+ const watcher = watch(resources, { recursive: true }, (_event, file) => {
200
+ const name = basename(String(file ?? ''))
201
+ // directories, editor swap and backup files
202
+ if (!extname(name) || name.startsWith('.') || name.endsWith('~')) return
203
+ pending.add(join(resources, String(file)))
45
204
  clearTimeout(timer)
46
- timer = setTimeout(() => rebuild(/\.(s?css)$/.test(String(file))), 50)
205
+ timer = setTimeout(() => {
206
+ const batch = pending
207
+ pending = new Set()
208
+ running = running.then(() => flush(batch))
209
+ }, 50)
47
210
  })
48
211
  return () => {
212
+ clearInterval(heartbeat)
213
+ clearTimeout(timer)
49
214
  watcher.close()
50
215
  for (const c of clients) c.close()
51
216
  clients.clear()
52
- enabled = false
217
+ state = undefined
53
218
  }
54
219
  }
55
220
 
@@ -0,0 +1,88 @@
1
+ /**
2
+ * The development client, inlined into every page `cslug dev` renders (`liveScript()`): it runs as
3
+ * `(liveClient)(config)`, so it must stay self-contained (no imports, nothing from the enclosing module).
4
+ *
5
+ * Events from `/__cslug/live` (SSE):
6
+ * - `reload`: reload the page;
7
+ * - `css`: swap the stylesheets, and the component styles this page rendered;
8
+ * - `vue` `{ id, kind, url?, css? }`: a component changed. If the page's islands loaded it and HMR is on, import
9
+ * the hot module and hand it to Vue (`rerender` keeps the state, `reload` remounts the component); else reload the
10
+ * page if it rendered the component; else nothing (another page's component).
11
+ * When the server comes back after a restart, the page reloads.
12
+ */
13
+ export type LiveConfig = { url: string; hmr: boolean; modules: string[]; nonce?: string }
14
+
15
+ type Def = Record<string, unknown>
16
+ type HmrRuntime = { rerender(id: string, render: unknown): void; reload(id: string, def: Def): void }
17
+
18
+ export function liveClient(config: LiveConfig): void {
19
+ const g = globalThis as unknown as { __cslug_components?: Record<string, Def>; __VUE_HMR_RUNTIME__?: HmrRuntime }
20
+ const rendered = (id: string) => config.modules.includes(id)
21
+ const setStyle = (id: string, css: string) => {
22
+ // Array.from and forEach: apps may type-check without the DOM.Iterable lib
23
+ let el = Array.from(document.querySelectorAll<HTMLStyleElement>('style[data-cslug]')).find(
24
+ (s) => s.dataset.cslug === id,
25
+ )
26
+ if (!el) {
27
+ el = document.createElement('style')
28
+ el.dataset.cslug = id
29
+ if (config.nonce) el.nonce = config.nonce
30
+ document.head.append(el)
31
+ }
32
+ el.textContent = css
33
+ }
34
+ const source = new EventSource(config.url)
35
+ let wasDown = false
36
+ source.addEventListener('reload', () => location.reload())
37
+ source.addEventListener('css', (e) => {
38
+ const data = JSON.parse((e as MessageEvent<string>).data) as { styles?: Record<string, string> }
39
+ document.querySelectorAll<HTMLLinkElement>('link[rel="stylesheet"]').forEach((link) => {
40
+ link.href = link.href.replace(/(\?.*)?$/, `?t=${Date.now()}`)
41
+ })
42
+ for (const [id, css] of Object.entries(data.styles ?? {})) if (rendered(id)) setStyle(id, css)
43
+ })
44
+ source.addEventListener('vue', async (e) => {
45
+ const data = JSON.parse((e as MessageEvent<string>).data) as {
46
+ id: string
47
+ kind: 'rerender' | 'reload' | 'style'
48
+ url?: string
49
+ css?: string
50
+ }
51
+ if (data.css !== undefined && rendered(data.id)) setStyle(data.id, data.css)
52
+ if (data.kind === 'style') return
53
+ const def = g.__cslug_components?.[data.id]
54
+ const runtime = g.__VUE_HMR_RUNTIME__
55
+ if (config.hmr && def && data.url && runtime) {
56
+ try {
57
+ const next = (await import(/* @vite-ignore */ data.url)).default as Def
58
+ if (data.kind === 'rerender') {
59
+ runtime.rerender(data.id, next.render)
60
+ def.render = next.render
61
+ } else {
62
+ runtime.reload(data.id, next)
63
+ for (const key of Object.keys(def)) if (key !== '__file' && !(key in next)) delete def[key]
64
+ Object.assign(def, next)
65
+ }
66
+ console.info(`[cslug] hot updated ${data.id}`)
67
+ return
68
+ } catch (error) {
69
+ console.error('[cslug] hot update failed, reloading', error)
70
+ }
71
+ location.reload()
72
+ return
73
+ }
74
+ if (def || rendered(data.id)) location.reload()
75
+ })
76
+ source.onerror = () => {
77
+ wasDown = true
78
+ }
79
+ source.onopen = () => {
80
+ if (wasDown) location.reload()
81
+ // connected: updates from now on reach this page (tests wait for it)
82
+ document.documentElement.dataset.cslugLive = 'open'
83
+ }
84
+ }
85
+
86
+ /** The inline `<script type="module">` that runs the client with `config`. */
87
+ export const liveScript = (config: LiveConfig): string =>
88
+ `<script type="module"${config.nonce ? ` nonce="${config.nonce.replace(/[^\w+/=-]/g, '')}"` : ''}>(${liveClient.toString()})(${JSON.stringify(config).replace(/</g, '\\u003c')})</script>`
package/src/loader.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { readFileSync } from 'node:fs'
1
2
  import { CslugError } from '@cslug/core'
2
3
  import { type CompiledSfc, SfcCache } from './compiler'
3
4
 
@@ -48,3 +49,53 @@ export function registerVueLoader(root: string = process.cwd(), options: { produ
48
49
 
49
50
  /** The first registered root. */
50
51
  export const vueLoaderRoot = () => roots.keys().next().value as string | undefined
52
+
53
+ /** Every definition each `.vue` file has had in this process (development: they are all patched on a change). */
54
+ const definitions = new Map<string, Record<string, unknown>[]>()
55
+
56
+ /**
57
+ * Development: compile a changed `.vue` file again and patch the component objects already imported, so pages
58
+ * render the new template without restarting the process (`bun --watch` does not see files loaded by plugins).
59
+ * Returns the component id and CSS, or undefined when this process never loaded the file. Throws on compile errors.
60
+ */
61
+ export async function reloadComponent(path: string): Promise<{ id: string; css: string } | undefined> {
62
+ const loaded = path in require.cache
63
+ if (!loaded && !definitions.has(path)) return undefined
64
+ const defs = definitions.get(path) ?? []
65
+ if (loaded) {
66
+ const current = (await import(path)).default as Record<string, unknown>
67
+ if (!defs.includes(current)) defs.push(current)
68
+ delete require.cache[path]
69
+ }
70
+ definitions.set(path, defs)
71
+ const fresh = (await import(path)).default as Record<string, unknown>
72
+ for (const def of defs) {
73
+ for (const key of Object.keys(def)) if (!(key in fresh)) delete def[key]
74
+ Object.assign(def, fresh)
75
+ }
76
+ defs.push(fresh)
77
+ const id = fresh.__cslugId as string
78
+ return { id, css: componentStyles.get(id) ?? '' }
79
+ }
80
+
81
+ /**
82
+ * Development: a stylesheet changed, so recompile the CSS of the loaded components whose styles are SCSS (they may
83
+ * `@use` it). Returns the styles that changed, by component id.
84
+ */
85
+ export function refreshComponentStyles(paths: Iterable<string>): Record<string, string> {
86
+ cache.clear()
87
+ const changed: Record<string, string> = {}
88
+ for (const path of paths) {
89
+ if (!(path in require.cache) && !definitions.has(path)) continue
90
+ if (!/lang=["']scss["']/.test(readFileSync(path, 'utf8'))) continue
91
+ const base = rootOf(path)
92
+ try {
93
+ const { id, css } = cache.get(path, { root: base, ssr: true, production: roots.get(base)?.production })
94
+ if (componentStyles.get(id) !== css) changed[id] = css
95
+ componentStyles.set(id, css)
96
+ } catch {
97
+ // a broken component is reported when it is saved or rendered
98
+ }
99
+ }
100
+ return changed
101
+ }
package/src/provider.ts CHANGED
@@ -7,7 +7,7 @@ import { registerVueLoader } from './loader'
7
7
  /**
8
8
  * Registers the `.vue` loader (before the HTTP provider imports routes, controllers and views) and the `build`
9
9
  * and `typecheck` commands. Under `cslug dev` (CSLUG_DEV=1) it also builds the assets, rebuilds them on change,
10
- * and serves live reload.
10
+ * and serves live reload and HMR (off with `cslug dev --no-hmr`, CSLUG_HMR=0). Never in production.
11
11
  */
12
12
  export class VueProvider extends ServiceProvider {
13
13
  private stopDev?: () => void
@@ -23,6 +23,7 @@ export class VueProvider extends ServiceProvider {
23
23
  this.stopDev = await startDev(this.app, {
24
24
  root: this.app.rootDir,
25
25
  dev: true,
26
+ hmr: process.env.CSLUG_HMR !== '0',
26
27
  ...(await assetConfig(this.app.rootDir)),
27
28
  })
28
29
  }
package/src/render.ts CHANGED
@@ -5,7 +5,8 @@ import { type HttpContext, type Responsable, Router } from '@cslug/http'
5
5
  import { Comment, type Component, createSSRApp, defineComponent, h, useSSRContext } from 'vue'
6
6
  import { renderToString } from 'vue/server-renderer'
7
7
  import type { PageData } from './client/data'
8
- import { liveReloadUrl } from './dev'
8
+ import { liveConfig } from './dev'
9
+ import { liveScript } from './live-client'
9
10
  import { componentStyles } from './loader'
10
11
  import { serialize } from './serialize'
11
12
 
@@ -103,11 +104,11 @@ function assetsHtml(entry: string, state: RenderState, root: string): string {
103
104
  const token = state.http && !isMissing(state.http) ? state.http.session.token() : undefined
104
105
  if (token) out.push(`<meta name="csrf-token" content="${escapeAttr(token)}">`)
105
106
  const assets = manifest?.entries[entry]
107
+ const nonce = nonceAttr(state)
106
108
  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
+ out.push(componentCss(state))
109
110
  if (state.islands.size) {
110
- out.push('<style>cslug-island{display:contents}</style>')
111
+ out.push(`<style${nonce}>cslug-island{display:contents}</style>`)
111
112
  if (assets?.js) {
112
113
  const data = pageData(state, manifest as AssetManifest)
113
114
  out.push(
@@ -117,16 +118,38 @@ function assetsHtml(entry: string, state: RenderState, root: string): string {
117
118
  const chunk = manifest?.islands[island]
118
119
  if (chunk) out.push(`<link rel="modulepreload" href="${escapeAttr(chunk)}">`)
119
120
  }
120
- out.push(`<script type="module" src="${escapeAttr(assets.js)}"></script>`)
121
+ out.push(`<script type="module" src="${escapeAttr(assets.js)}"${nonce}></script>`)
121
122
  } else if (state.dev) {
122
123
  out.push(
123
124
  `<!-- cslug: this page has islands but public/build/manifest.json has no "${entry}" entry: run cslug dev or cslug build -->`,
124
125
  )
125
126
  }
126
127
  }
128
+ out.push(devClient(state))
127
129
  return out.join('')
128
130
  }
129
131
 
132
+ /**
133
+ * The CSS of the components the page rendered: one `<style data-cslug>`, or under `cslug dev` one per component
134
+ * (`data-cslug="<id>"`) so a change replaces just that one.
135
+ */
136
+ function componentCss(state: RenderState): string {
137
+ const ids = [...state.modules].filter((m) => componentStyles.get(m))
138
+ if (!ids.length) return ''
139
+ const nonce = nonceAttr(state)
140
+ if (!liveConfig()) return `<style data-cslug${nonce}>${ids.map((m) => componentStyles.get(m)).join('\n')}</style>`
141
+ return ids.map((m) => `<style data-cslug="${escapeAttr(m)}"${nonce}>${componentStyles.get(m)}</style>`).join('')
142
+ }
143
+
144
+ /** ` nonce="…"` when a CSP middleware gave this request a nonce (`csp()` from @cslug/security). */
145
+ const nonceAttr = (state: RenderState) => (state.http?.nonce ? ` nonce="${escapeAttr(state.http.nonce)}"` : '')
146
+
147
+ /** Under `cslug dev`: the live-reload and HMR client (live-client.ts), told which components the page rendered. */
148
+ function devClient(state: RenderState): string {
149
+ const live = liveConfig()
150
+ return live ? liveScript({ ...live, modules: [...state.modules], nonce: state.http?.nonce }) : ''
151
+ }
152
+
130
153
  /** What islands need in the browser: locale, their translation namespaces, named routes, chunk URLs. */
131
154
  function pageData(state: RenderState, manifest: AssetManifest): PageData {
132
155
  const app = currentApp()
@@ -142,7 +165,6 @@ function pageData(state: RenderState, manifest: AssetManifest): PageData {
142
165
  }
143
166
  const islands: Record<string, string> = {}
144
167
  for (const id of state.islands) if (manifest.islands[id]) islands[id] = manifest.islands[id] as string
145
- const live = liveReloadUrl()
146
168
  return {
147
169
  locale,
148
170
  chain: translator.chain(locale),
@@ -150,7 +172,6 @@ function pageData(state: RenderState, manifest: AssetManifest): PageData {
150
172
  routes,
151
173
  appUrl: app.config<string | undefined>('app.url'),
152
174
  islands,
153
- ...(live ? { live } : {}),
154
175
  }
155
176
  }
156
177
 
@@ -183,13 +204,12 @@ export async function renderPage(
183
204
  placed = true
184
205
  return assetsHtml(entry, state, root)
185
206
  })
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}`
207
+ // a page without <Assets> still gets its component CSS (and the dev client)
208
+ if (!placed) {
209
+ const head = componentCss(state)
210
+ if (head) html = html.includes('</head>') ? html.replace('</head>', `${head}</head>`) : `${head}${html}`
211
+ const client = devClient(state)
212
+ if (client) html = html.includes('</body>') ? html.replace('</body>', `${client}</body>`) : `${html}${client}`
193
213
  }
194
214
  return { html: /^\s*<html[\s>]/i.test(html) ? `<!doctype html>${html}` : html, state }
195
215
  }