@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/README.md +10 -2
- package/docs/README.md +26 -0
- package/docs/api.md +29 -0
- package/package.json +53 -4
- package/src/build-entry.ts +2 -0
- package/src/build.ts +201 -0
- package/src/client/data.ts +27 -0
- package/src/client/index.ts +124 -0
- package/src/commands.ts +56 -0
- package/src/compiler.ts +216 -0
- package/src/composables.ts +93 -0
- package/src/dev.ts +72 -0
- package/src/env.d.ts +3 -0
- package/src/index.ts +30 -0
- package/src/loader.ts +50 -0
- package/src/mount-stub.ts +11 -0
- package/src/provider.ts +33 -0
- package/src/register.ts +4 -0
- package/src/render.ts +262 -0
- package/src/serialize.ts +50 -0
- package/src/shared/form.ts +88 -0
- package/src/shared/format.ts +50 -0
- package/src/shared/store.ts +33 -0
- package/src/shared/url.ts +35 -0
- package/src/types.ts +12 -0
package/README.md
CHANGED
|
@@ -1,3 +1,11 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @cslug/vue
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Vue as the server template language. Pages are `.vue` files rendered to HTML on the server; a component used
|
|
4
|
+
with `hydrate="…"` becomes an island, hydrated in the browser. A page without islands ships no JavaScript.
|
|
5
|
+
|
|
6
|
+
```ts
|
|
7
|
+
return view(ShowCircuit, { circuit, days })
|
|
8
|
+
```
|
|
9
|
+
|
|
10
|
+
Part of [cslug](https://github.com/cslugts/cslug). Docs: [docs/README.md](docs/README.md), [docs/api.md](docs/api.md),
|
|
11
|
+
[guide 08](../../guides/08-views-vue-scss.md).
|
package/docs/README.md
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
# @cslug/vue
|
|
2
|
+
|
|
3
|
+
Add `VueProvider` before `HttpProvider` in `bootstrap/providers.ts`.
|
|
4
|
+
|
|
5
|
+
**On the server**, it registers a Bun loader that compiles `.vue` files (`vue/compiler-sfc`, cached by file
|
|
6
|
+
time). Before compiling, `<X hydrate="…">` is rewritten to an island wrapper in the source, so the server and
|
|
7
|
+
browser builds see the same input (see spikes/a-vue-islands). At render time:
|
|
8
|
+
|
|
9
|
+
1. The page renders with `vue/server-renderer`. Each component records itself, so the CSS of the components
|
|
10
|
+
that rendered (scoped, SCSS compiled) goes into the page.
|
|
11
|
+
2. An island renders its component with the **serialized** props (what the browser will get) inside
|
|
12
|
+
`<cslug-island data-island data-hydrate data-props>`, and records its `lang` namespaces.
|
|
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.
|
|
15
|
+
|
|
16
|
+
**In the browser**, `@cslug/vue` resolves to `src/client` (the `browser` export condition). `mountIslands()`
|
|
17
|
+
imports each island's chunk when its `hydrate` condition is met and mounts it. `useT` formats ICU messages
|
|
18
|
+
with `@cslug/validation`'s formatter, the same one the server uses.
|
|
19
|
+
|
|
20
|
+
**The build** (`cslug build`, or `@cslug/vue/build`) runs `Bun.build` with the client entries plus one entry
|
|
21
|
+
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`.
|
|
23
|
+
|
|
24
|
+
Tests that import views statically need the loader from the first line:
|
|
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
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
# @cslug/vue: API
|
|
2
|
+
|
|
3
|
+
| | |
|
|
4
|
+
|---|---|
|
|
5
|
+
| `view(Page, props, { status?, headers? })` | A `Responsable`: renders the page in the request |
|
|
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 |
|
|
8
|
+
| `renderStandalone(Page, props)` | One self-contained HTML file: no scripts, CSS and `public/` images inlined, islands as plain HTML |
|
|
9
|
+
| `<Assets entry="client" />` | In the layout `<head>` |
|
|
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
|
+
| `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` |
|
|
13
|
+
| `useT()` | `t`, `tr`, `locale`, `formatMoney`, `formatDate` in the current locale |
|
|
14
|
+
| `route(name, params?, options?)` | |
|
|
15
|
+
| `formatDuration(minutes)`, `formatMoney`, `formatDate` | |
|
|
16
|
+
| `useForm(initial)` | `data`, `errors`, `error`, `processing`, `response`, `post/put/patch/delete(url)` → boolean, `reset`, `clearErrors`; JSON with `X-CSRF-Token` |
|
|
17
|
+
| `csrfHeaders()` | For hand-written `fetch` |
|
|
18
|
+
| `defineStore(name, init, { persist? })` | State shared by the page's islands (fresh per call on the server) |
|
|
19
|
+
| `mountIslands({ setup? })` | Browser: hydrate the page's islands (`resources/client.ts`) |
|
|
20
|
+
| `buildAssets({ root, entries?, dev?, tailwind? })` | Also at `@cslug/vue/build` with `findIslands` and `aliasPlugin` |
|
|
21
|
+
| `cslug build [--dev]`, `cslug typecheck` | Commands (vue-tsc must be installed for `typecheck`) |
|
|
22
|
+
| `config('vue.routes')` | Name prefixes of the routes sent to the browser (default: all named routes) |
|
|
23
|
+
| `VueProvider` | Registers the `.vue` loader and the commands; dev mode under `cslug dev` |
|
|
24
|
+
| `registerVueLoader(root)` | What the provider and `@cslug/vue/register` call |
|
|
25
|
+
| `compileSfc(file, { root, ssr })`, `rewriteIslands(source, file)` | Used by the loader and the build |
|
|
26
|
+
|
|
27
|
+
Errors: slot content on an island (other than `#fallback`), an unknown `hydrate` value, a bound `:hydrate`,
|
|
28
|
+
`<style lang>` other than css/scss, and SCSS without the `sass` package are compile errors naming the file.
|
|
29
|
+
Props that would not survive JSON (functions, class instances, cycles) are logged in development.
|
package/package.json
CHANGED
|
@@ -1,6 +1,55 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cslug/vue",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "Vue views rendered on the server, components hydrated as islands, composables and asset build.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "git+https://github.com/cslugts/cslug.git",
|
|
10
|
+
"directory": "packages/vue"
|
|
11
|
+
},
|
|
12
|
+
"homepage": "https://github.com/cslugts/cslug/tree/main/packages/vue",
|
|
13
|
+
"keywords": [
|
|
14
|
+
"cslug",
|
|
15
|
+
"bun",
|
|
16
|
+
"framework"
|
|
17
|
+
],
|
|
18
|
+
"exports": {
|
|
19
|
+
".": {
|
|
20
|
+
"browser": "./src/client/index.ts",
|
|
21
|
+
"default": "./src/index.ts"
|
|
22
|
+
},
|
|
23
|
+
"./build": "./src/build-entry.ts",
|
|
24
|
+
"./register": "./src/register.ts"
|
|
25
|
+
},
|
|
26
|
+
"files": [
|
|
27
|
+
"src",
|
|
28
|
+
"docs",
|
|
29
|
+
"stubs",
|
|
30
|
+
"README.md"
|
|
31
|
+
],
|
|
32
|
+
"engines": {
|
|
33
|
+
"bun": ">=1.3.14"
|
|
34
|
+
},
|
|
35
|
+
"peerDependencies": {
|
|
36
|
+
"@cslug/core": "0.2.0",
|
|
37
|
+
"@cslug/http": "0.2.0",
|
|
38
|
+
"@cslug/validation": "0.2.0",
|
|
39
|
+
"vue": "^3.5.0",
|
|
40
|
+
"sass": "^1.80.0",
|
|
41
|
+
"tailwindcss": "^4.0.0",
|
|
42
|
+
"bun-plugin-tailwind": ">=0.1.0"
|
|
43
|
+
},
|
|
44
|
+
"peerDependenciesMeta": {
|
|
45
|
+
"sass": {
|
|
46
|
+
"optional": true
|
|
47
|
+
},
|
|
48
|
+
"tailwindcss": {
|
|
49
|
+
"optional": true
|
|
50
|
+
},
|
|
51
|
+
"bun-plugin-tailwind": {
|
|
52
|
+
"optional": true
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
}
|
package/src/build.ts
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The asset build (`cslug build`, `cslug dev`): `Bun.build` for the browser with cslug's plugins. Entries are
|
|
3
|
+
* the app's client entries plus **one entry per island component**, so each island is its own chunk and the
|
|
4
|
+
* manifest maps island ids to chunk URLs. Vue itself becomes a shared chunk.
|
|
5
|
+
*/
|
|
6
|
+
import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs'
|
|
7
|
+
import { dirname, join, relative } from 'node:path'
|
|
8
|
+
import type { BunPlugin } from 'bun'
|
|
9
|
+
import { parse } from 'vue/compiler-sfc'
|
|
10
|
+
import { compileScss, componentId, SfcCache } from './compiler'
|
|
11
|
+
import type { AssetManifest } from './render'
|
|
12
|
+
|
|
13
|
+
export type BuildOptions = {
|
|
14
|
+
root: string
|
|
15
|
+
/** Client entries by name (default `{ client: 'resources/client.ts' }`). */
|
|
16
|
+
entries?: Record<string, string>
|
|
17
|
+
/** Development: readable output, no hashes, source maps, Vue warnings. */
|
|
18
|
+
dev?: boolean
|
|
19
|
+
tailwind?: boolean
|
|
20
|
+
/** Default `public/build`, served at `/build`. */
|
|
21
|
+
outdir?: string
|
|
22
|
+
publicPath?: string
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export type BuildResult = { manifest: AssetManifest; ms: number; files: string[] }
|
|
26
|
+
|
|
27
|
+
const vueFiles = (dir: string): string[] =>
|
|
28
|
+
!existsSync(dir)
|
|
29
|
+
? []
|
|
30
|
+
: readdirSync(dir).flatMap((f) => {
|
|
31
|
+
const p = join(dir, f)
|
|
32
|
+
return statSync(p).isDirectory() ? vueFiles(p) : f.endsWith('.vue') ? [p] : []
|
|
33
|
+
})
|
|
34
|
+
|
|
35
|
+
type Node = {
|
|
36
|
+
type: number
|
|
37
|
+
tag?: string
|
|
38
|
+
tagType?: number
|
|
39
|
+
props?: { type: number; name: string }[]
|
|
40
|
+
children?: Node[]
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** Component files used with `hydrate` anywhere under resources/ (resolved through the importing file's imports). */
|
|
44
|
+
export function findIslands(root: string): string[] {
|
|
45
|
+
const found = new Set<string>()
|
|
46
|
+
for (const file of vueFiles(join(root, 'resources'))) {
|
|
47
|
+
const source = readFileSync(file, 'utf8')
|
|
48
|
+
if (!source.includes('hydrate')) continue
|
|
49
|
+
const { descriptor } = parse(source, { filename: file })
|
|
50
|
+
const tags = new Set<string>()
|
|
51
|
+
const visit = (nodes: Node[] = []) => {
|
|
52
|
+
for (const n of nodes) {
|
|
53
|
+
if (n.type === 1 && n.tagType === 1 && n.tag && n.props?.some((p) => p.type === 6 && p.name === 'hydrate'))
|
|
54
|
+
tags.add(n.tag)
|
|
55
|
+
visit(n.children)
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
visit((descriptor.template?.ast as Node | undefined)?.children)
|
|
59
|
+
const script = `${descriptor.script?.content ?? ''}\n${descriptor.scriptSetup?.content ?? ''}`
|
|
60
|
+
for (const tag of tags) {
|
|
61
|
+
const pascal = tag.replace(/(^|-)(\w)/g, (_m, _d, c: string) => c.toUpperCase())
|
|
62
|
+
const spec = new RegExp(`import\\s+${pascal}\\s+from\\s+['"]([^'"]+\\.vue)['"]`).exec(script)?.[1]
|
|
63
|
+
if (!spec)
|
|
64
|
+
throw new Error(`${relative(root, file)}: <${tag} hydrate> must be imported from a .vue file in this component`)
|
|
65
|
+
found.add(Bun.resolveSync(spec, dirname(file)))
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
return [...found].sort()
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** `@/…` → `resources/…` in imports. */
|
|
72
|
+
export const aliasPlugin = (root: string): BunPlugin => ({
|
|
73
|
+
name: 'cslug-alias',
|
|
74
|
+
setup(build) {
|
|
75
|
+
build.onResolve({ filter: /^@\// }, (args) => ({
|
|
76
|
+
path: Bun.resolveSync(join(root, 'resources', args.path.slice(2)), root),
|
|
77
|
+
}))
|
|
78
|
+
},
|
|
79
|
+
})
|
|
80
|
+
|
|
81
|
+
function vuePlugins(root: string, dev: boolean): BunPlugin[] {
|
|
82
|
+
const cache = new SfcCache()
|
|
83
|
+
return [
|
|
84
|
+
aliasPlugin(root),
|
|
85
|
+
{
|
|
86
|
+
name: 'cslug-vue-client',
|
|
87
|
+
setup(build) {
|
|
88
|
+
// the component CSS is rendered into the page by the server, so the client build only needs the code
|
|
89
|
+
build.onLoad({ filter: /\.vue$/ }, ({ path }) => ({
|
|
90
|
+
contents: cache.get(path, { root, ssr: false, production: !dev }).code,
|
|
91
|
+
loader: 'ts',
|
|
92
|
+
}))
|
|
93
|
+
},
|
|
94
|
+
},
|
|
95
|
+
{
|
|
96
|
+
name: 'cslug-scss',
|
|
97
|
+
setup(build) {
|
|
98
|
+
build.onLoad({ filter: /\.scss$/ }, ({ path }) => ({
|
|
99
|
+
contents: compileScss(readFileSync(path, 'utf8'), path, root),
|
|
100
|
+
loader: 'css',
|
|
101
|
+
}))
|
|
102
|
+
},
|
|
103
|
+
},
|
|
104
|
+
]
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** Build the client entries and the islands; write `manifest.json`. */
|
|
108
|
+
export async function buildAssets(options: BuildOptions): Promise<BuildResult> {
|
|
109
|
+
const started = performance.now()
|
|
110
|
+
const { root } = options
|
|
111
|
+
const dev = options.dev ?? false
|
|
112
|
+
const outdir = join(root, options.outdir ?? 'public/build')
|
|
113
|
+
const publicPath = options.publicPath ?? '/build/'
|
|
114
|
+
const entries = options.entries ?? { client: 'resources/client.ts' }
|
|
115
|
+
const islands = findIslands(root)
|
|
116
|
+
const plugins = vuePlugins(root, dev)
|
|
117
|
+
if (options.tailwind) {
|
|
118
|
+
const tailwind = (await import(Bun.resolveSync('bun-plugin-tailwind', root))).default as BunPlugin
|
|
119
|
+
plugins.push(tailwind)
|
|
120
|
+
}
|
|
121
|
+
const entryFiles = Object.values(entries).map((e) => join(root, e))
|
|
122
|
+
for (const e of entryFiles) if (!existsSync(e)) throw new Error(`Asset entry ${relative(root, e)} does not exist`)
|
|
123
|
+
|
|
124
|
+
rmSync(outdir, { recursive: true, force: true })
|
|
125
|
+
const result = await Bun.build({
|
|
126
|
+
entrypoints: [...entryFiles, ...islands],
|
|
127
|
+
root,
|
|
128
|
+
outdir,
|
|
129
|
+
target: 'browser',
|
|
130
|
+
format: 'esm',
|
|
131
|
+
splitting: true,
|
|
132
|
+
minify: !dev,
|
|
133
|
+
sourcemap: dev ? 'linked' : 'none',
|
|
134
|
+
conditions: ['browser'],
|
|
135
|
+
// no publicPath: Bun would prefix it to relative chunk paths (/build/../chunks/…); relative imports resolve
|
|
136
|
+
// correctly from wherever the entry is served
|
|
137
|
+
naming: dev
|
|
138
|
+
? { entry: '[dir]/[name].[ext]', chunk: 'chunks/[name]-[hash].[ext]', asset: 'assets/[name]-[hash].[ext]' }
|
|
139
|
+
: {
|
|
140
|
+
entry: '[dir]/[name]-[hash].[ext]',
|
|
141
|
+
chunk: 'chunks/[name]-[hash].[ext]',
|
|
142
|
+
asset: 'assets/[name]-[hash].[ext]',
|
|
143
|
+
},
|
|
144
|
+
define: {
|
|
145
|
+
'process.env.NODE_ENV': JSON.stringify(dev ? 'development' : 'production'),
|
|
146
|
+
__VUE_OPTIONS_API__: 'true',
|
|
147
|
+
__VUE_PROD_DEVTOOLS__: 'false',
|
|
148
|
+
__VUE_PROD_HYDRATION_MISMATCH_DETAILS__: dev ? 'true' : 'false',
|
|
149
|
+
},
|
|
150
|
+
plugins,
|
|
151
|
+
// report the errors ourselves: with `throw`, Bun only says "Bundle failed"
|
|
152
|
+
throw: false,
|
|
153
|
+
})
|
|
154
|
+
if (!result.success)
|
|
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
|
+
)
|
|
165
|
+
|
|
166
|
+
// map outputs back to their entry: "resources/components/day-card-1a2b3c4d.js" → "resources/components/day-card"
|
|
167
|
+
const stem = (file: string) =>
|
|
168
|
+
relative(outdir, file)
|
|
169
|
+
.replace(/\\/g, '/')
|
|
170
|
+
.replace(dev ? /\.(js|css)$/ : /-[a-z0-9]{8}\.(js|css)$/, '')
|
|
171
|
+
const url = (file: string) => publicPath + relative(outdir, file).replace(/\\/g, '/')
|
|
172
|
+
const byStem = new Map<string, { js?: string; css: string[] }>()
|
|
173
|
+
for (const out of result.outputs) {
|
|
174
|
+
if (out.kind !== 'entry-point' && !(out.kind === 'asset' && out.path.endsWith('.css'))) continue
|
|
175
|
+
const s = stem(out.path)
|
|
176
|
+
const item = byStem.get(s) ?? { css: [] }
|
|
177
|
+
if (out.path.endsWith('.css')) item.css.push(url(out.path))
|
|
178
|
+
else if (out.path.endsWith('.js')) item.js = url(out.path)
|
|
179
|
+
byStem.set(s, item)
|
|
180
|
+
}
|
|
181
|
+
const manifest: AssetManifest = { entries: {}, islands: {} }
|
|
182
|
+
for (const [name, entry] of Object.entries(entries)) {
|
|
183
|
+
const item = byStem.get(entry.replace(/\.[jt]sx?$/, ''))
|
|
184
|
+
manifest.entries[name] = { js: item?.js, css: item?.css ?? [] }
|
|
185
|
+
}
|
|
186
|
+
for (const island of islands) {
|
|
187
|
+
const js = byStem.get(
|
|
188
|
+
relative(root, island)
|
|
189
|
+
.replace(/\\/g, '/')
|
|
190
|
+
.replace(/\.vue$/, ''),
|
|
191
|
+
)?.js
|
|
192
|
+
if (js) manifest.islands[componentId(island, root)] = js
|
|
193
|
+
}
|
|
194
|
+
mkdirSync(outdir, { recursive: true })
|
|
195
|
+
writeFileSync(join(outdir, 'manifest.json'), JSON.stringify(manifest, null, 2))
|
|
196
|
+
return {
|
|
197
|
+
manifest,
|
|
198
|
+
ms: Math.round(performance.now() - started),
|
|
199
|
+
files: result.outputs.map((o) => relative(root, o.path)),
|
|
200
|
+
}
|
|
201
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import type { ClientRoute } from '../shared/url'
|
|
2
|
+
|
|
3
|
+
/** What `<Assets>` puts in the page for its islands (`<script type="application/json" id="cslug-data">`). */
|
|
4
|
+
export type PageData = {
|
|
5
|
+
locale: string
|
|
6
|
+
/** Locales tried for a message: the locale, its fallbacks, the default. */
|
|
7
|
+
chain: string[]
|
|
8
|
+
/** Messages of the namespaces the page's islands declared (`defineOptions({ lang: [...] })`), by key. */
|
|
9
|
+
messages: Record<string, string>
|
|
10
|
+
routes: Record<string, ClientRoute>
|
|
11
|
+
appUrl?: string
|
|
12
|
+
/** Island id → chunk URL. */
|
|
13
|
+
islands: Record<string, string>
|
|
14
|
+
/** Development: the live-reload endpoint. */
|
|
15
|
+
live?: string
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
let cached: PageData | undefined
|
|
19
|
+
/** The data the server embedded in the page (`#cslug-data`): locale, messages, routes, islands. Read once. */
|
|
20
|
+
export function pageData(): PageData {
|
|
21
|
+
if (cached) return cached
|
|
22
|
+
const el = typeof document === 'undefined' ? null : document.getElementById('cslug-data')
|
|
23
|
+
cached = el?.textContent
|
|
24
|
+
? (JSON.parse(el.textContent) as PageData)
|
|
25
|
+
: { locale: 'en', chain: ['en'], messages: {}, routes: {}, islands: {} }
|
|
26
|
+
return cached
|
|
27
|
+
}
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @cslug/vue in the browser (the `browser` export condition; `cslug build` uses it). Same names as the server
|
|
3
|
+
* entry, so components render on both sides; server-only APIs (`view`, `useRequest`, …) are absent or throw.
|
|
4
|
+
*/
|
|
5
|
+
import { formatIcu } from '@cslug/validation'
|
|
6
|
+
import { type App, createApp, createSSRApp } from 'vue'
|
|
7
|
+
import { formatDateIn, formatDurationIn, formatMoneyIn } from '../shared/format'
|
|
8
|
+
import { buildUrl } from '../shared/url'
|
|
9
|
+
import { pageData } from './data'
|
|
10
|
+
|
|
11
|
+
export { type Serialized, serialize } from '../serialize'
|
|
12
|
+
export { csrfHeaders, type Form, useForm } from '../shared/form'
|
|
13
|
+
export { defineStore } from '../shared/store'
|
|
14
|
+
export { type PageData, pageData } from './data'
|
|
15
|
+
|
|
16
|
+
/** Translations for islands: the namespaces they declared with `defineOptions({ lang: [...] })`. */
|
|
17
|
+
export function useT() {
|
|
18
|
+
const data = pageData()
|
|
19
|
+
const locale = data.locale
|
|
20
|
+
return {
|
|
21
|
+
locale,
|
|
22
|
+
t: (key: string, params?: Record<string, unknown>) => {
|
|
23
|
+
const message = data.messages[key]
|
|
24
|
+
if (message === undefined) {
|
|
25
|
+
console.warn(
|
|
26
|
+
`[cslug] missing translation "${key}" in the browser: add its namespace to defineOptions({ lang: [...] })`,
|
|
27
|
+
)
|
|
28
|
+
return key
|
|
29
|
+
}
|
|
30
|
+
return formatIcu(message, params, locale)
|
|
31
|
+
},
|
|
32
|
+
tr: (value: Partial<Record<string, string>> | string | null | undefined) => {
|
|
33
|
+
if (value === null || value === undefined) return ''
|
|
34
|
+
if (typeof value === 'string') return value
|
|
35
|
+
for (const l of data.chain) if (value[l]) return value[l] as string
|
|
36
|
+
return Object.values(value).find(Boolean) ?? ''
|
|
37
|
+
},
|
|
38
|
+
formatMoney: (amount: Parameters<typeof formatMoneyIn>[1], currency?: string) =>
|
|
39
|
+
formatMoneyIn(locale, amount, currency),
|
|
40
|
+
formatDate: (value: Date | string, style?: Parameters<typeof formatDateIn>[2]) =>
|
|
41
|
+
formatDateIn(locale, value, style),
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export const route = (name: string, params?: Record<string, unknown>, options?: Parameters<typeof buildUrl>[4]) =>
|
|
46
|
+
buildUrl(pageData().routes, pageData().appUrl, name, params, options)
|
|
47
|
+
export const formatMoney = (amount: Parameters<typeof formatMoneyIn>[1], currency?: string) =>
|
|
48
|
+
formatMoneyIn(pageData().locale, amount, currency)
|
|
49
|
+
export const formatDate = (value: Date | string, style?: Parameters<typeof formatDateIn>[2]) =>
|
|
50
|
+
formatDateIn(pageData().locale, value, style)
|
|
51
|
+
export const formatDuration = (minutes: number) => formatDurationIn(pageData().locale, minutes)
|
|
52
|
+
|
|
53
|
+
/** Server only. */
|
|
54
|
+
export function useRequest(): never {
|
|
55
|
+
throw new Error('useRequest() runs on the server only: pass what the island needs as props')
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Longest wait for an idle period before a `hydrate="idle"` island hydrates anyway. */
|
|
59
|
+
const IDLE_TIMEOUT_MS = 2000
|
|
60
|
+
|
|
61
|
+
type MountOptions = { setup?: (app: App, island: { id: string; element: HTMLElement }) => void }
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Hydrate every `<cslug-island>` when its condition is met (load, idle, visible, media:…). Each island is its own
|
|
65
|
+
* Vue app; `setup` installs app-wide plugins. In development, also connects to live reload.
|
|
66
|
+
*/
|
|
67
|
+
export function mountIslands(options: MountOptions = {}): void {
|
|
68
|
+
const data = pageData()
|
|
69
|
+
for (const el of document.querySelectorAll<HTMLElement>('cslug-island:not([data-mounted])')) {
|
|
70
|
+
const id = el.dataset.island as string
|
|
71
|
+
const mode = el.dataset.hydrate ?? 'load'
|
|
72
|
+
const mount = async () => {
|
|
73
|
+
if (el.dataset.mounted) return
|
|
74
|
+
el.dataset.mounted = 'pending'
|
|
75
|
+
const url = data.islands[id]
|
|
76
|
+
if (!url) throw new Error(`[cslug] no chunk for island ${id}: run cslug build`)
|
|
77
|
+
const component = (await import(/* @vite-ignore */ url)).default
|
|
78
|
+
const props = JSON.parse(el.dataset.props ?? '{}')
|
|
79
|
+
const app = el.dataset.ssr === 'false' ? createApp(component, props) : createSSRApp(component, props)
|
|
80
|
+
options.setup?.(app, { id, element: el })
|
|
81
|
+
app.mount(el)
|
|
82
|
+
el.dataset.mounted = 'true'
|
|
83
|
+
}
|
|
84
|
+
const run = () => {
|
|
85
|
+
mount().catch((e) => console.error(e))
|
|
86
|
+
}
|
|
87
|
+
if (mode === 'load') run()
|
|
88
|
+
else if (mode === 'idle') {
|
|
89
|
+
// the timeout bounds the wait: a page that is never idle (busy main thread) still hydrates
|
|
90
|
+
if ('requestIdleCallback' in window) requestIdleCallback(run, { timeout: IDLE_TIMEOUT_MS })
|
|
91
|
+
else setTimeout(run)
|
|
92
|
+
} else if (mode === 'visible') {
|
|
93
|
+
const observer = new IntersectionObserver((entries) => {
|
|
94
|
+
if (entries.some((e) => e.isIntersecting)) {
|
|
95
|
+
observer.disconnect()
|
|
96
|
+
run()
|
|
97
|
+
}
|
|
98
|
+
})
|
|
99
|
+
observer.observe(el.firstElementChild ?? el)
|
|
100
|
+
} else if (mode.startsWith('media:')) {
|
|
101
|
+
const mq = matchMedia(mode.slice(6))
|
|
102
|
+
if (mq.matches) run()
|
|
103
|
+
else mq.addEventListener('change', run, { once: true })
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
if (data.live) liveReload(data.live)
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** Reload when the dev server says so, or when it comes back after a restart. */
|
|
110
|
+
function liveReload(url: string): void {
|
|
111
|
+
let wasDown = false
|
|
112
|
+
const source = new EventSource(url)
|
|
113
|
+
source.addEventListener('reload', () => location.reload())
|
|
114
|
+
source.addEventListener('css', () => {
|
|
115
|
+
for (const link of document.querySelectorAll<HTMLLinkElement>('link[rel="stylesheet"]'))
|
|
116
|
+
link.href = link.href.replace(/(\?.*)?$/, `?t=${Date.now()}`)
|
|
117
|
+
})
|
|
118
|
+
source.onerror = () => {
|
|
119
|
+
wasDown = true
|
|
120
|
+
}
|
|
121
|
+
source.onopen = () => {
|
|
122
|
+
if (wasDown) location.reload()
|
|
123
|
+
}
|
|
124
|
+
}
|
package/src/commands.ts
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { existsSync } from 'node:fs'
|
|
2
|
+
import { join } from 'node:path'
|
|
3
|
+
import { Command, flag } from '@cslug/core'
|
|
4
|
+
import { buildAssets } from './build'
|
|
5
|
+
|
|
6
|
+
/** Asset settings from cslug.config.ts (`assets`). */
|
|
7
|
+
export async function assetConfig(root: string): Promise<{ entries?: Record<string, string>; tailwind?: boolean }> {
|
|
8
|
+
const path = join(root, 'cslug.config.ts')
|
|
9
|
+
if (!existsSync(path)) return {}
|
|
10
|
+
const config = (await import(path)).default as
|
|
11
|
+
| { assets?: { entries?: Record<string, string>; tailwind?: boolean } }
|
|
12
|
+
| undefined
|
|
13
|
+
return config?.assets ?? {}
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** `cslug build`: minified, hashed assets in public/build with manifest.json. */
|
|
17
|
+
export class BuildCommand extends Command {
|
|
18
|
+
static signature = 'build'
|
|
19
|
+
static description = 'Build the browser assets (islands, client entries, styles) into public/build'
|
|
20
|
+
static boot = false
|
|
21
|
+
static args = { dev: flag.boolean().describe('Unminified, with source maps') }
|
|
22
|
+
|
|
23
|
+
async handle({ dev }: Command.Args<typeof BuildCommand>) {
|
|
24
|
+
const { manifest, ms, files } = await buildAssets({
|
|
25
|
+
root: this.app.rootDir,
|
|
26
|
+
dev,
|
|
27
|
+
...(await assetConfig(this.app.rootDir)),
|
|
28
|
+
})
|
|
29
|
+
this.success(`built ${files.length} files in ${ms} ms (${Object.keys(manifest.islands).length} islands)`)
|
|
30
|
+
for (const [name, e] of Object.entries(manifest.entries))
|
|
31
|
+
this.line(` ${name}: ${[e.js, ...(e.css ?? [])].filter(Boolean).join(', ')}`)
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** `cslug typecheck`: vue-tsc over .ts and .vue (templates and view() props included). */
|
|
36
|
+
export class TypecheckCommand extends Command {
|
|
37
|
+
static signature = 'typecheck'
|
|
38
|
+
static description = 'Type-check .ts and .vue files with vue-tsc'
|
|
39
|
+
static boot = false
|
|
40
|
+
|
|
41
|
+
async handle() {
|
|
42
|
+
const bin = join(this.app.rootDir, 'node_modules/.bin/vue-tsc')
|
|
43
|
+
if (!existsSync(bin)) {
|
|
44
|
+
this.error('vue-tsc is not installed: bun add -d vue-tsc')
|
|
45
|
+
return 1
|
|
46
|
+
}
|
|
47
|
+
const proc = Bun.spawn([bin, '--noEmit', '-p', 'tsconfig.json'], {
|
|
48
|
+
cwd: this.app.rootDir,
|
|
49
|
+
stdout: 'inherit',
|
|
50
|
+
stderr: 'inherit',
|
|
51
|
+
})
|
|
52
|
+
const code = await proc.exited
|
|
53
|
+
if (code === 0) this.success('no type errors')
|
|
54
|
+
return code
|
|
55
|
+
}
|
|
56
|
+
}
|