@kerf-js/start 0.1.2-nightly.20261118.86 → 0.1.3
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/package.json +2 -2
- package/src/app.mjs +25 -22
- package/src/contract.mjs +3 -11
- package/src/dev-runtime.mjs +103 -34
- package/src/inspect/server.mjs +16 -0
- package/src/inspect.mjs +4 -11
- package/src/server/form.ts +4 -3
- package/src/server/functions.ts +6 -3
- package/src/server/origin.ts +33 -0
- package/src/sidecar/dev-watch.mjs +32 -12
- package/src/vite/config-hooks.mjs +1 -1
- package/src/vite/dev-hooks.mjs +16 -8
- package/src/vite/shared.mjs +18 -1
- package/src/vite/trace-deps.mjs +77 -0
- package/src/vite.mjs +7 -35
- package/src/watch-tree.mjs +26 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kerf-js/start",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.3",
|
|
4
4
|
"description": "kerf Start: file routes, server functions, streaming SSR, a database and auth",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"kerf"
|
|
@@ -86,7 +86,7 @@
|
|
|
86
86
|
"vite": "8.3.5"
|
|
87
87
|
},
|
|
88
88
|
"peerDependencies": {
|
|
89
|
-
"@kerf-js/core": "^0.1.
|
|
89
|
+
"@kerf-js/core": "^0.1.3",
|
|
90
90
|
"better-auth": "^1.7.0",
|
|
91
91
|
"drizzle-orm": "^0.45.0",
|
|
92
92
|
"drizzle-zod": "^0.8.0",
|
package/src/app.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
// `kerf dev` and `kerf build` for an app with src/routes
|
|
1
|
+
// `kerf dev` and `kerf build` for an app with src/routes: Vite 8 with kerf() (hydratable output),
|
|
2
2
|
// kerfStart() and Nitro's Vite plugin. A vite.config in the app is merged in. The CLI passes the config's `site`.
|
|
3
3
|
|
|
4
4
|
import { existsSync, readFileSync, readdirSync, realpathSync } from 'node:fs'
|
|
@@ -7,13 +7,15 @@ import { fileURLToPath } from 'node:url'
|
|
|
7
7
|
import { createBuilder, createServer } from 'vite'
|
|
8
8
|
import { nitro } from 'nitro/vite'
|
|
9
9
|
import kerf from '@kerf-js/core/vite'
|
|
10
|
-
import { devRunner,
|
|
10
|
+
import { devRunner, devRuntime } from './dev-runtime.mjs'
|
|
11
11
|
import { pageSockets } from './live-target.mjs'
|
|
12
12
|
import kerfStart, { startDir } from './vite.mjs'
|
|
13
13
|
import { ownNodePreset } from './server/node-preset.mjs'
|
|
14
14
|
import { buildDate, finalizeBuild, nitroOutput } from './vite/nitro-output.mjs'
|
|
15
|
+
import { labelChunkGroups } from './vite/shared.mjs'
|
|
16
|
+
import { externalAddons, traceDeps } from './vite/trace-deps.mjs'
|
|
15
17
|
|
|
16
|
-
/**
|
|
18
|
+
/** Enable crossws only for apps that declare a channel or shared state. */
|
|
17
19
|
function usesSockets(root) {
|
|
18
20
|
const src = join(root, 'src')
|
|
19
21
|
if (!existsSync(src)) return false
|
|
@@ -35,6 +37,7 @@ function config({
|
|
|
35
37
|
command,
|
|
36
38
|
nitro: nitroOptions = {},
|
|
37
39
|
production,
|
|
40
|
+
refreshPlugins,
|
|
38
41
|
}) {
|
|
39
42
|
root = command === 'build' ? realpathSync(root) : resolve(root)
|
|
40
43
|
const sockets = usesSockets(root)
|
|
@@ -56,7 +59,7 @@ function config({
|
|
|
56
59
|
plugins: [
|
|
57
60
|
kerf({ hydratable: site?.render !== 'shell', csp: site?.csp }),
|
|
58
61
|
kerfStart({ root, site, hydration }),
|
|
59
|
-
|
|
62
|
+
refreshPlugins && devRuntime(refreshPlugins),
|
|
60
63
|
nitro({
|
|
61
64
|
preset,
|
|
62
65
|
// Every app gets this: built assets ship as .br and .gz next to the file, and Nitro picks by Accept-Encoding.
|
|
@@ -68,14 +71,14 @@ function config({
|
|
|
68
71
|
}),
|
|
69
72
|
...(sockets && { features: { websocket: true } }),
|
|
70
73
|
...(runner && { devServer: { runner } }),
|
|
71
|
-
//
|
|
74
|
+
// The server lists share cards so Nitro can prerender the PNGs.
|
|
72
75
|
...(site?.render !== 'shell' && {
|
|
73
76
|
prerender: { routes: ['/_kerf/og-routes'], failOnError: true },
|
|
74
77
|
}),
|
|
75
78
|
// Prerendered cards are static files at content-addressed URLs: immutable. The rule names each file (a
|
|
76
79
|
// `/_kerf/og/**` rule would also override the handler's no-cache for a stale `?v=` on demand). Prerender runs
|
|
77
80
|
// before Nitro bundles the server, so rules added when it is done are in the build. (Dev sends no-store.)
|
|
78
|
-
...
|
|
81
|
+
...traceDeps(root),
|
|
79
82
|
...nitroOptions,
|
|
80
83
|
...(command === 'build' && {
|
|
81
84
|
hooks: {
|
|
@@ -91,7 +94,7 @@ function config({
|
|
|
91
94
|
},
|
|
92
95
|
async 'rollup:before'(instance, bundle) {
|
|
93
96
|
await nitroOptions.hooks?.['rollup:before']?.(instance, bundle)
|
|
94
|
-
|
|
97
|
+
shapeBundle(instance, bundle, production.date)
|
|
95
98
|
},
|
|
96
99
|
},
|
|
97
100
|
plugins: [
|
|
@@ -104,18 +107,12 @@ function config({
|
|
|
104
107
|
}
|
|
105
108
|
}
|
|
106
109
|
|
|
107
|
-
/**
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
...(existsSync(join(root, '.kerf/slots/media.server.ts'))
|
|
114
|
-
? ['css-tree*', 'csso*', 'sharp*']
|
|
115
|
-
: []),
|
|
116
|
-
...(existsSync(join(root, 'node_modules/nodemailer')) ? ['nodemailer*'] : []),
|
|
117
|
-
]
|
|
118
|
-
return deps.length ? { traceDeps: deps } : {}
|
|
110
|
+
/** What Start adds to each bundle Nitro builds: the prerender's and the server's. */
|
|
111
|
+
function shapeBundle(instance, bundle, date) {
|
|
112
|
+
bundle.plugins.push(nitroOutput(instance, date))
|
|
113
|
+
// the prerender bundle resolves without tracing; the server's bundle traces the addon into `.output`
|
|
114
|
+
if (instance.options.preset === 'nitro-prerender') bundle.plugins.push(externalAddons())
|
|
115
|
+
labelChunkGroups(bundle, 'nitro')
|
|
119
116
|
}
|
|
120
117
|
|
|
121
118
|
function immutableCards() {
|
|
@@ -139,9 +136,15 @@ function immutableCards() {
|
|
|
139
136
|
|
|
140
137
|
/** Start the dev server; resolves with it once it listens. */
|
|
141
138
|
export async function dev(options) {
|
|
142
|
-
const
|
|
143
|
-
await
|
|
144
|
-
|
|
139
|
+
const refreshPlugins = () => config({ ...options, refreshPlugins }).plugins
|
|
140
|
+
const server = await createServer(config({ ...options, refreshPlugins }))
|
|
141
|
+
try {
|
|
142
|
+
await server.listen()
|
|
143
|
+
return server
|
|
144
|
+
} catch (error) {
|
|
145
|
+
await server.close()
|
|
146
|
+
throw error
|
|
147
|
+
}
|
|
145
148
|
}
|
|
146
149
|
|
|
147
150
|
/** Build client and server for `preset` (node by default; bun, deno_server…), into `.output/` unless the preset moves it. */
|
package/src/contract.mjs
CHANGED
|
@@ -6,8 +6,6 @@ import { scanRoutes } from './routes.mjs'
|
|
|
6
6
|
import { createHash } from 'node:crypto'
|
|
7
7
|
import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs'
|
|
8
8
|
import { join, resolve } from 'node:path'
|
|
9
|
-
import { createServer } from 'vite'
|
|
10
|
-
import kerf from '@kerf-js/core/vite'
|
|
11
9
|
import {
|
|
12
10
|
holdsSockets,
|
|
13
11
|
literalSecrets,
|
|
@@ -20,7 +18,8 @@ import {
|
|
|
20
18
|
import { readMigrations } from './migrations.mjs'
|
|
21
19
|
import { shapeTree } from './shape.mjs'
|
|
22
20
|
import { describe } from './contract/describe.mjs'
|
|
23
|
-
import
|
|
21
|
+
import { startDir } from './vite.mjs'
|
|
22
|
+
import { inspectionServer } from './inspect/server.mjs'
|
|
24
23
|
|
|
25
24
|
export { describe }
|
|
26
25
|
|
|
@@ -228,14 +227,7 @@ async function withFns({ root, site = {} }, fn) {
|
|
|
228
227
|
const env = process.env.NODE_ENV
|
|
229
228
|
let server
|
|
230
229
|
try {
|
|
231
|
-
server = await
|
|
232
|
-
root,
|
|
233
|
-
configFile: false,
|
|
234
|
-
logLevel: 'silent',
|
|
235
|
-
appType: 'custom',
|
|
236
|
-
server: { middlewareMode: true, hmr: false, ws: false },
|
|
237
|
-
plugins: [kerf({ hydratable: true, csp: site?.csp }), kerfStart({ root, site })],
|
|
238
|
-
})
|
|
230
|
+
server = await inspectionServer(root, site)
|
|
239
231
|
await server.ssrLoadModule('virtual:kerf/fns')
|
|
240
232
|
const { fns } = await server.ssrLoadModule(join(startDir, 'data.ts'))
|
|
241
233
|
return await fn(fns, server)
|
package/src/dev-runtime.mjs
CHANGED
|
@@ -1,46 +1,115 @@
|
|
|
1
|
-
//
|
|
2
|
-
//
|
|
3
|
-
//
|
|
4
|
-
//
|
|
1
|
+
// Nitro starts evaluating each entry as soon as it receives the environment registration.
|
|
2
|
+
// Vite creates environments before running configureServer, buildStart and the optimizer's init.
|
|
3
|
+
// If the SSR stylesheet crawl reaches the client graph then, Vite can replace the dependency
|
|
4
|
+
// metadata for an optimized import while the crawl is still waiting for that import to load.
|
|
5
5
|
|
|
6
6
|
const alternate = Boolean(process.versions.bun || process.versions.deno)
|
|
7
7
|
|
|
8
|
+
/** Use Vite's own HTTP server for WebSocket upgrades on Bun and Deno. */
|
|
8
9
|
export const devRunner = (sockets) => (alternate && sockets ? 'self' : undefined)
|
|
9
10
|
|
|
10
11
|
const GUARD = /if \("Deno" in globalThis \|\| "Bun" in globalThis\) throw new Error\([^)]*\);?/
|
|
12
|
+
const WORKER_TIMEOUT = 30_000
|
|
11
13
|
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
14
|
+
/** Register Nitro entries after the environments they import through are ready. */
|
|
15
|
+
export function devRuntime(refreshPlugins) {
|
|
16
|
+
let nitro
|
|
17
|
+
let register
|
|
18
|
+
let useSelf
|
|
19
|
+
return {
|
|
20
|
+
name: 'kerf:dev-runtime',
|
|
21
|
+
apply: 'serve',
|
|
22
|
+
enforce: 'post',
|
|
23
|
+
nitro: {
|
|
24
|
+
setup(instance) {
|
|
25
|
+
nitro = instance
|
|
26
|
+
},
|
|
27
|
+
},
|
|
28
|
+
configResolved(config) {
|
|
29
|
+
useSelf = (nitro.options.devServer.runner || process.env.NITRO_DEV_RUNNER) === 'self'
|
|
30
|
+
const dev = config.environments.nitro.dev
|
|
31
|
+
const createNitro = dev.createEnvironment
|
|
32
|
+
const held = Promise.withResolvers()
|
|
33
|
+
dev.createEnvironment = async (...args) => {
|
|
34
|
+
try {
|
|
35
|
+
const env = await createNitro(...args)
|
|
36
|
+
register = holdRegistrations(env.devServer, useSelf)
|
|
37
|
+
return env
|
|
38
|
+
} finally {
|
|
39
|
+
held.resolve()
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
// Nitro can resend registrations as soon as the worker reports ready, including services
|
|
43
|
+
// still under construction. Install the gate before Nitro starts creating those services.
|
|
44
|
+
for (const [name, environment] of Object.entries(config.environments)) {
|
|
45
|
+
if (name === 'nitro' || environment.consumer !== 'server') continue
|
|
46
|
+
const create = environment.dev.createEnvironment
|
|
47
|
+
environment.dev.createEnvironment = async (...args) => {
|
|
48
|
+
await held.promise
|
|
49
|
+
return create(...args)
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
},
|
|
53
|
+
configureServer(server) {
|
|
54
|
+
// Vite creates the replacement server before closing the current one. Nitro's plugin
|
|
55
|
+
// retains its RunnerManager across configs; each server needs to own the runner it closes.
|
|
56
|
+
server.config.inlineConfig.plugins = refreshPlugins()
|
|
57
|
+
const environments = Object.values(server.environments)
|
|
58
|
+
let remaining = environments.length
|
|
59
|
+
for (const environment of environments) {
|
|
60
|
+
const listen = environment.listen.bind(environment)
|
|
61
|
+
environment.listen = async (...args) => {
|
|
62
|
+
await listen(...args)
|
|
63
|
+
if (--remaining === 0) await register()
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
},
|
|
67
|
+
closeServer: () => nitro.close(),
|
|
68
|
+
transform: {
|
|
69
|
+
filter: { id: /crossws/, code: 'incompatible environment' },
|
|
70
|
+
handler: (code) => (alternate && useSelf ? code.replace(GUARD, '') : undefined),
|
|
71
|
+
},
|
|
72
|
+
}
|
|
73
|
+
}
|
|
29
74
|
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
75
|
+
function holdRegistrations(worker, useSelf) {
|
|
76
|
+
const send = worker.sendMessage
|
|
77
|
+
const entries = new Map()
|
|
78
|
+
worker.sendMessage = (message) => {
|
|
79
|
+
if (message?.type === 'custom' && message.event === 'nitro:vite-env')
|
|
80
|
+
entries.set(message.data.name, message)
|
|
81
|
+
else send.call(worker, message)
|
|
82
|
+
}
|
|
83
|
+
return async () => {
|
|
84
|
+
await worker.waitForReady(WORKER_TIMEOUT)
|
|
85
|
+
worker.sendMessage = send
|
|
86
|
+
for (const [name, message] of entries) {
|
|
87
|
+
// A self runner reuses Nitro's module and its global table across Vite restarts.
|
|
88
|
+
if (useSelf && globalThis.__nitro_vite_envs__)
|
|
89
|
+
globalThis.__nitro_vite_envs__[name] = undefined
|
|
90
|
+
worker.sendMessage(message)
|
|
91
|
+
}
|
|
92
|
+
await registrationsReceived(worker)
|
|
93
|
+
}
|
|
37
94
|
}
|
|
38
95
|
|
|
39
|
-
function
|
|
40
|
-
const
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
96
|
+
async function registrationsReceived(worker) {
|
|
97
|
+
const token = 'kerf:dev-registered'
|
|
98
|
+
const settled = Promise.withResolvers()
|
|
99
|
+
const timer = setTimeout(
|
|
100
|
+
() =>
|
|
101
|
+
settled.reject(new Error('Nitro did not register the Vite environments within 30 seconds')),
|
|
102
|
+
WORKER_TIMEOUT,
|
|
103
|
+
)
|
|
104
|
+
const onMessage = (message) => {
|
|
105
|
+
if (message?.type === 'pong' && message.data === token) settled.resolve()
|
|
106
|
+
}
|
|
107
|
+
worker.onMessage(onMessage)
|
|
108
|
+
try {
|
|
109
|
+
worker.sendMessage({ type: 'ping', data: token })
|
|
110
|
+
await settled.promise
|
|
111
|
+
} finally {
|
|
112
|
+
clearTimeout(timer)
|
|
113
|
+
worker.offMessage(onMessage)
|
|
45
114
|
}
|
|
46
115
|
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { createServer } from 'vite'
|
|
2
|
+
import kerf from '@kerf-js/core/vite'
|
|
3
|
+
import kerfStart from '../vite.mjs'
|
|
4
|
+
|
|
5
|
+
/** Load SSR modules for a one-shot check without touching the live dev server's dependency cache. */
|
|
6
|
+
export function inspectionServer(root, site) {
|
|
7
|
+
return createServer({
|
|
8
|
+
root,
|
|
9
|
+
configFile: false,
|
|
10
|
+
logLevel: 'silent',
|
|
11
|
+
appType: 'custom',
|
|
12
|
+
optimizeDeps: { noDiscovery: true },
|
|
13
|
+
server: { middlewareMode: true, hmr: false, ws: false, watch: null },
|
|
14
|
+
plugins: [kerf({ hydratable: true, csp: site?.csp }), kerfStart({ root, site })],
|
|
15
|
+
})
|
|
16
|
+
}
|
package/src/inspect.mjs
CHANGED
|
@@ -6,13 +6,13 @@
|
|
|
6
6
|
|
|
7
7
|
import { readFileSync } from 'node:fs'
|
|
8
8
|
import { join, resolve } from 'node:path'
|
|
9
|
-
import {
|
|
10
|
-
import
|
|
11
|
-
import kerfStart, { startDir } from './vite.mjs'
|
|
9
|
+
import { parseSync } from 'vite'
|
|
10
|
+
import { startDir } from './vite.mjs'
|
|
12
11
|
import { deployUrl } from './derive.mjs'
|
|
13
12
|
import { compare } from './inspect/compare.mjs'
|
|
14
13
|
import { inspectRoutes } from './inspect/routes.mjs'
|
|
15
14
|
import { inspectSamples, inspectCards } from './inspect/samples.mjs'
|
|
15
|
+
import { inspectionServer } from './inspect/server.mjs'
|
|
16
16
|
import { filePath, scanRoutes } from './routes.mjs'
|
|
17
17
|
|
|
18
18
|
const quote = (s) => JSON.stringify(s)
|
|
@@ -133,14 +133,7 @@ function makeTaker(found, run, seen, manifest, pages) {
|
|
|
133
133
|
*/
|
|
134
134
|
export async function routesMeta({ root, site = {}, preset }) {
|
|
135
135
|
root = resolve(root)
|
|
136
|
-
const server = await
|
|
137
|
-
root,
|
|
138
|
-
configFile: false,
|
|
139
|
-
logLevel: 'silent',
|
|
140
|
-
appType: 'custom',
|
|
141
|
-
server: { middlewareMode: true, hmr: false, ws: false },
|
|
142
|
-
plugins: [kerf({ hydratable: true, csp: site?.csp }), kerfStart({ root, site })],
|
|
143
|
-
})
|
|
136
|
+
const server = await inspectionServer(root, site)
|
|
144
137
|
try {
|
|
145
138
|
const { manifest, modules } = await server.ssrLoadModule('virtual:kerf/routes')
|
|
146
139
|
const { createHandler, cardPath } = await server.ssrLoadModule(join(startDir, 'server.tsx'))
|
package/src/server/form.ts
CHANGED
|
@@ -4,6 +4,7 @@ import type { Scope } from '../exec'
|
|
|
4
4
|
import { bodyLimit, echoed, limited, withHeaders } from './request'
|
|
5
5
|
import type { HandlerOptions } from './types'
|
|
6
6
|
import { functionFault } from './function-fault'
|
|
7
|
+
import { externalOrigin } from './origin'
|
|
7
8
|
export function makeForm(
|
|
8
9
|
options: HandlerOptions,
|
|
9
10
|
page: (url: URL, request: Request, scope: Scope) => Promise<Response>,
|
|
@@ -13,12 +14,12 @@ export function makeForm(
|
|
|
13
14
|
* errors and what was typed. A form can't send `x-kerf`, so the CSRF proof is the browser's own origin headers.
|
|
14
15
|
*/
|
|
15
16
|
return async function form(url: URL, request: Request, scope: Scope): Promise<Response> {
|
|
17
|
+
const expected = externalOrigin(request, options.site?.trustProxy)
|
|
16
18
|
const origin = request.headers.get('origin')
|
|
17
19
|
const from = request.headers.get('sec-fetch-site')
|
|
18
20
|
if (
|
|
19
|
-
!
|
|
20
|
-
|
|
21
|
-
: from === 'same-origin')
|
|
21
|
+
!expected ||
|
|
22
|
+
!(origin ? origin === expected && (!from || from === 'same-origin') : from === 'same-origin')
|
|
22
23
|
) {
|
|
23
24
|
options.onDiagnostic?.({
|
|
24
25
|
code: 'F002',
|
package/src/server/functions.ts
CHANGED
|
@@ -10,6 +10,7 @@ import { ERROR_HEADER } from '../failure'
|
|
|
10
10
|
import { admitValue, errorFrameStatus, peerStatus, shellResponse, tags } from '../shell/operation'
|
|
11
11
|
import { isSchema, validOperationId } from '../shell/wire'
|
|
12
12
|
import type { Answer, Fn } from '../data/types'
|
|
13
|
+
import { externalOrigin } from './origin'
|
|
13
14
|
|
|
14
15
|
/** `/_kerf/fn/<id>`: GET runs a query, POST a mutation (CSRF-checked), both answering JSON (research 27 §3). */
|
|
15
16
|
export async function serverFunction(
|
|
@@ -61,7 +62,7 @@ export async function serverFunction(
|
|
|
61
62
|
const type = request.headers.get('content-type') ?? ''
|
|
62
63
|
const multipart = type.startsWith('multipart/form-data') // `<Form>` with a file; `x-kerf` still forces a preflight
|
|
63
64
|
if (
|
|
64
|
-
crossOrigin(options, request
|
|
65
|
+
crossOrigin(options, request) ||
|
|
65
66
|
request.headers.get('x-kerf') !== '1' ||
|
|
66
67
|
!(multipart || type.startsWith('application/json'))
|
|
67
68
|
)
|
|
@@ -156,7 +157,9 @@ function functionResponses(scope: Scope, options: HandlerOptions, id: string) {
|
|
|
156
157
|
return { out, fail }
|
|
157
158
|
}
|
|
158
159
|
|
|
159
|
-
function crossOrigin(options: HandlerOptions, request: Request
|
|
160
|
+
function crossOrigin(options: HandlerOptions, request: Request) {
|
|
161
|
+
const expected = externalOrigin(request, options.site?.trustProxy)
|
|
162
|
+
if (!expected) return true
|
|
160
163
|
const origin = request.headers.get('origin')
|
|
161
164
|
const from = request.headers.get('sec-fetch-site')
|
|
162
165
|
// Naming an origin permits its mutation; CORS separately decides whether the browser can read it.
|
|
@@ -164,6 +167,6 @@ function crossOrigin(options: HandlerOptions, request: Request, url: URL) {
|
|
|
164
167
|
const trusted = !!origin && !!named && (named === '*' || named.includes(origin))
|
|
165
168
|
return (
|
|
166
169
|
!trusted &&
|
|
167
|
-
((origin && origin !==
|
|
170
|
+
((origin && origin !== expected) || (from && from !== 'same-origin' && from !== 'none'))
|
|
168
171
|
)
|
|
169
172
|
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
// CSRF uses the public origin behind an explicitly trusted proxy, without changing routing or cache URLs.
|
|
2
|
+
|
|
3
|
+
/** The browser's origin from an explicitly trusted hop, or null for malformed/short forwarding or TLS downgrades. */
|
|
4
|
+
export function externalOrigin(request: Request, trustProxy?: boolean | number): string | null {
|
|
5
|
+
const url = new URL(request.url)
|
|
6
|
+
if (trustProxy === undefined || trustProxy === false || trustProxy === 0) return url.origin
|
|
7
|
+
const hops = trustProxy === true ? 1 : trustProxy
|
|
8
|
+
if (!Number.isSafeInteger(hops) || hops < 1) return null
|
|
9
|
+
const proto = request.headers.get('x-forwarded-proto')
|
|
10
|
+
const host = request.headers.get('x-forwarded-host')
|
|
11
|
+
if (proto === null && host === null) return url.origin
|
|
12
|
+
if (proto === null) return null
|
|
13
|
+
const protocols = proto.split(',').map((part) => part.trim())
|
|
14
|
+
const hosts = host === null ? null : host.split(',').map((part) => part.trim())
|
|
15
|
+
if (
|
|
16
|
+
protocols.length < hops ||
|
|
17
|
+
protocols.some((part) => !part) ||
|
|
18
|
+
(hosts && (hosts.length !== protocols.length || hosts.some((part) => !part)))
|
|
19
|
+
)
|
|
20
|
+
return null
|
|
21
|
+
const protocol = protocols[protocols.length - hops]
|
|
22
|
+
if (protocol !== 'http' && protocol !== 'https') return null
|
|
23
|
+
if (url.protocol === 'https:' && protocol !== 'https') return null
|
|
24
|
+
// Proxies that preserve Host may set only X-Forwarded-Proto; do not use an unrelated entry from another hop.
|
|
25
|
+
const authority = hosts ? hosts[hosts.length - hops]! : url.host
|
|
26
|
+
if (!/^(?:[a-z\d_-]+(?:\.[a-z\d_-]+)*\.?|\[[\da-f:.]+\])(?::\d{1,5})?$/i.test(authority))
|
|
27
|
+
return null
|
|
28
|
+
try {
|
|
29
|
+
return new URL(`${protocol}://${authority}`).origin
|
|
30
|
+
} catch {
|
|
31
|
+
return null
|
|
32
|
+
}
|
|
33
|
+
}
|
|
@@ -1,7 +1,8 @@
|
|
|
1
|
-
import { existsSync
|
|
1
|
+
import { existsSync } from 'node:fs'
|
|
2
2
|
import { join } from 'node:path'
|
|
3
3
|
import { isServerModule } from '../vite.mjs'
|
|
4
4
|
import { buildable, crateDir, isNative, urlVariable } from './common.mjs'
|
|
5
|
+
import { watchFailure, watchTree } from '../watch-tree.mjs'
|
|
5
6
|
|
|
6
7
|
export async function watchServices(deps) {
|
|
7
8
|
const {
|
|
@@ -42,11 +43,8 @@ export async function watchServices(deps) {
|
|
|
42
43
|
}
|
|
43
44
|
if (!first.blocked) await rebuild(service)
|
|
44
45
|
const changed = debounce(() => rebuild(service))
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
if (file && !/^target([\\/]|$)/.test(file) && !file.endsWith('.lock')) changed()
|
|
48
|
-
}),
|
|
49
|
-
)
|
|
46
|
+
const crate = watchCrate(dir, service, changed, log)
|
|
47
|
+
if (crate) watchers.push(crate)
|
|
50
48
|
}
|
|
51
49
|
|
|
52
50
|
// A server module's edit may change a schema: the contract is regenerated, and only a change to a service's hash
|
|
@@ -69,12 +67,8 @@ export async function watchServices(deps) {
|
|
|
69
67
|
log(`[kerf] the contract couldn't be regenerated: ${e.message.split('\n')[0]}`)
|
|
70
68
|
}
|
|
71
69
|
})
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
watch(src, { recursive: true }, (_, file) => {
|
|
75
|
-
if (file && isServerModule(`src/${file.replaceAll('\\', '/')}`)) contractChanged()
|
|
76
|
-
}),
|
|
77
|
-
)
|
|
70
|
+
const server = existsSync(src) ? watchServerModules(src, contractChanged, log) : null
|
|
71
|
+
if (server) watchers.push(server)
|
|
78
72
|
|
|
79
73
|
return watchers
|
|
80
74
|
}
|
|
@@ -86,3 +80,29 @@ const debounce = (fn, ms = 200) => {
|
|
|
86
80
|
t = setTimeout(() => fn(), ms)
|
|
87
81
|
}
|
|
88
82
|
}
|
|
83
|
+
|
|
84
|
+
/** A crate's sources, for a rebuild on an edit; its `target` and lockfile are cargo's own writes. */
|
|
85
|
+
const watchCrate = (dir, service, changed, log) =>
|
|
86
|
+
watchTree(
|
|
87
|
+
dir,
|
|
88
|
+
(_, file) => {
|
|
89
|
+
if (file && !/^target([\\/]|$)/.test(file) && !file.endsWith('.lock')) changed()
|
|
90
|
+
},
|
|
91
|
+
(error) =>
|
|
92
|
+
log(
|
|
93
|
+
`[kerf] can't watch crates/${service} (${watchFailure(error)}): restart dev after an edit`,
|
|
94
|
+
),
|
|
95
|
+
)
|
|
96
|
+
|
|
97
|
+
/** The app's server modules, whose edits may change the contract a service is built from. */
|
|
98
|
+
const watchServerModules = (src, changed, log) =>
|
|
99
|
+
watchTree(
|
|
100
|
+
src,
|
|
101
|
+
(_, file) => {
|
|
102
|
+
if (file && isServerModule(`src/${file.replaceAll('\\', '/')}`)) changed()
|
|
103
|
+
},
|
|
104
|
+
(error) =>
|
|
105
|
+
log(
|
|
106
|
+
`[kerf] can't watch src/ (${watchFailure(error)}): restart dev after a server module's schema changes`,
|
|
107
|
+
),
|
|
108
|
+
)
|
package/src/vite/dev-hooks.mjs
CHANGED
|
@@ -1,9 +1,10 @@
|
|
|
1
|
-
import { existsSync, readFileSync
|
|
1
|
+
import { existsSync, readFileSync } from 'node:fs'
|
|
2
2
|
import { join, relative } from 'node:path'
|
|
3
3
|
import { waitingForAFix, reaches, refresh } from './dev.mjs'
|
|
4
4
|
import { serverExports } from './syntax.mjs'
|
|
5
5
|
import { isServerModule } from './server-functions.mjs'
|
|
6
6
|
import { SHEET, ASSETS, V } from './shared.mjs'
|
|
7
|
+
import { watchFailure, watchTree } from '../watch-tree.mjs'
|
|
7
8
|
|
|
8
9
|
export const configureServer = (s) =>
|
|
9
10
|
function (server) {
|
|
@@ -21,7 +22,8 @@ export const configureServer = (s) =>
|
|
|
21
22
|
server.middlewares.use(waitingForAFix)
|
|
22
23
|
// A route file added or removed changes the virtual modules; edits to existing ones are ordinary HMR/reloads.
|
|
23
24
|
const dir = join(s.root, 'src')
|
|
24
|
-
|
|
25
|
+
// A one-shot server (`kerf check`, `kerf routes --meta`, a build's contract) asks Vite to watch nothing: so does this.
|
|
26
|
+
if (!existsSync(dir) || server.config.server.watch === null) return
|
|
25
27
|
const routesDir = relative(dir, join(s.root, s.manifest.dir)).split('\\').join('/')
|
|
26
28
|
const shape = () =>
|
|
27
29
|
JSON.stringify([
|
|
@@ -49,17 +51,23 @@ export const configureServer = (s) =>
|
|
|
49
51
|
)
|
|
50
52
|
server.ws.send({ type: 'full-reload' })
|
|
51
53
|
}
|
|
52
|
-
const w =
|
|
53
|
-
|
|
54
|
-
|
|
54
|
+
const w = watchTree(
|
|
55
|
+
dir,
|
|
56
|
+
(event, file) => {
|
|
57
|
+
if (event === 'rename' && file) changed(file)
|
|
58
|
+
},
|
|
59
|
+
(error) =>
|
|
60
|
+
server.config.logger.warn(
|
|
61
|
+
`kerf: can't watch src/ (${watchFailure(error)}): Vite's own watcher still sees routes added or removed`,
|
|
62
|
+
{ timestamp: true },
|
|
63
|
+
),
|
|
64
|
+
)
|
|
55
65
|
// Not every runtime's recursive watch reports a new file, and Vite's watcher does.
|
|
56
66
|
for (const event of ['add', 'unlink'])
|
|
57
67
|
server.watcher.on(event, (file) => {
|
|
58
68
|
if (file.startsWith(dir)) changed(relative(dir, file))
|
|
59
69
|
})
|
|
60
|
-
|
|
61
|
-
const close = server.close.bind(server)
|
|
62
|
-
server.close = () => (w.close(), close())
|
|
70
|
+
s.closeRoutes = () => w?.close()
|
|
63
71
|
}
|
|
64
72
|
|
|
65
73
|
export const hotUpdate = (s) =>
|
package/src/vite/shared.mjs
CHANGED
|
@@ -72,8 +72,25 @@ const kitGroup = (name) => (id, ctx) => (packageLazy(id, (m) => ctx.getModuleInf
|
|
|
72
72
|
export const KIT_CHUNKS = [
|
|
73
73
|
{
|
|
74
74
|
name: kitGroup('icons'),
|
|
75
|
+
debugName: 'icons',
|
|
75
76
|
test: /[\\/]node_modules[\\/]@kerf-js[\\/]veneer-icons[\\/]/,
|
|
76
77
|
priority: 2,
|
|
77
78
|
},
|
|
78
|
-
{ name: kitGroup('kit'), test: OWN, minShareCount: 2, priority: 1 },
|
|
79
|
+
{ name: kitGroup('kit'), debugName: 'kit', test: OWN, minShareCount: 2, priority: 1 },
|
|
79
80
|
]
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* A `debugName` for each code-splitting group named by a function, which Rolldown wants for its timing report and
|
|
84
|
+
* warns about without. Nitro's server build has one (a chunk per package) and names it no other way.
|
|
85
|
+
*/
|
|
86
|
+
export function labelChunkGroups(config, prefix) {
|
|
87
|
+
const outputs = [config?.output ?? []].flat()
|
|
88
|
+
for (const output of outputs) {
|
|
89
|
+
const groups = output?.codeSplitting?.groups
|
|
90
|
+
if (!Array.isArray(groups)) continue
|
|
91
|
+
for (const [i, group] of groups.entries())
|
|
92
|
+
if (typeof group?.name === 'function' && group.debugName === undefined)
|
|
93
|
+
group.debugName = `${prefix} ${i}`
|
|
94
|
+
}
|
|
95
|
+
return config
|
|
96
|
+
}
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
// The packages a built server loads by name at runtime, which Nitro can't see to copy into `.output`. Nitro's `traceDeps`
|
|
2
|
+
// keeps each external and traces it into the build; nf3 warns for an entry no installed package resolves ("could not
|
|
3
|
+
// resolve `traceInclude` entry … from any root"), so each one here is listed only when the app has it.
|
|
4
|
+
|
|
5
|
+
import { existsSync, readFileSync, realpathSync } from 'node:fs'
|
|
6
|
+
import { dirname, join } from 'node:path'
|
|
7
|
+
|
|
8
|
+
const readJson = (file) => {
|
|
9
|
+
try {
|
|
10
|
+
return JSON.parse(readFileSync(file, 'utf8'))
|
|
11
|
+
} catch {
|
|
12
|
+
return null
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** Where `name` is installed for code in any of `from`, Node's way: `node_modules/<name>` in each directory up. */
|
|
17
|
+
export function packageDir(name, from) {
|
|
18
|
+
for (let dir of from) {
|
|
19
|
+
for (;;) {
|
|
20
|
+
const at = join(dir, 'node_modules', name)
|
|
21
|
+
if (existsSync(join(at, 'package.json'))) return realpathSync(at)
|
|
22
|
+
const up = dirname(dir)
|
|
23
|
+
if (up === dir) break
|
|
24
|
+
dir = up
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
return null
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** The plugin a generated slot file names, or null: `kerf plugins sync` writes `provider = null` for an unfilled slot. */
|
|
31
|
+
function slotProvider(root, slot) {
|
|
32
|
+
const file = join(root, '.kerf', 'slots', slot)
|
|
33
|
+
if (!existsSync(file)) return null
|
|
34
|
+
const text = readFileSync(file, 'utf8')
|
|
35
|
+
if (/^export const provider = null$/m.test(text)) return null
|
|
36
|
+
return /["']?plugin["']?\s*:\s*["']([^"']+)["']/.exec(text)?.[1] ?? ''
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Nitro's `traceDeps` for the app: the media route's sharp, and css-tree and csso under svgo, which read JSON from their
|
|
41
|
+
* packages, when a plugin provides the media slot; and nodemailer for SMTP.
|
|
42
|
+
*/
|
|
43
|
+
export function traceDeps(root) {
|
|
44
|
+
const pkg = readJson(join(root, 'package.json')) ?? {}
|
|
45
|
+
const direct = Object.keys({ ...pkg.dependencies, ...pkg.devDependencies })
|
|
46
|
+
.map((name) => packageDir(name, [root]))
|
|
47
|
+
.filter(Boolean)
|
|
48
|
+
// what nf3 resolves an entry from: the app, and the packages that declare it (one of the app's own, or theirs)
|
|
49
|
+
const bases = [root, ...direct]
|
|
50
|
+
const deps = []
|
|
51
|
+
const media = slotProvider(root, 'media.server.ts')
|
|
52
|
+
if (media !== null) {
|
|
53
|
+
const provider = media && packageDir(media, bases)
|
|
54
|
+
const from = provider ? [provider, ...bases] : bases
|
|
55
|
+
const svgo = packageDir('svgo', from)
|
|
56
|
+
for (const name of ['css-tree', 'csso'])
|
|
57
|
+
if (packageDir(name, svgo ? [svgo, ...from] : from)) deps.push(`${name}*`)
|
|
58
|
+
if (packageDir('sharp', from)) deps.push('sharp*')
|
|
59
|
+
}
|
|
60
|
+
if (existsSync(join(root, 'node_modules/nodemailer'))) deps.push('nodemailer*')
|
|
61
|
+
return deps.length ? { traceDeps: deps } : {}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Takumi's addon, which every server's share cards import by name (`og/native.mjs`), and Bun's built-in modules
|
|
66
|
+
* (`bun:sqlite`, imported only under Bun), as externals of Nitro's prerender bundle. That bundle resolves without
|
|
67
|
+
* tracing and on Node, so it called each import UNRESOLVED_IMPORT: Takumi sits beside @kerf-js/start under pnpm (the
|
|
68
|
+
* prerender's `native()` loads that copy), and Node has no `bun:` modules. The server's bundle is left to Nitro, which
|
|
69
|
+
* traces the addon into `.output`.
|
|
70
|
+
*/
|
|
71
|
+
export const externalAddons = () => ({
|
|
72
|
+
name: 'kerf:start:external-addons',
|
|
73
|
+
resolveId: {
|
|
74
|
+
filter: { id: /^(?:@takumi-rs\/core|bun:[\w/-]+)$/ },
|
|
75
|
+
handler: (id) => ({ id, external: true }),
|
|
76
|
+
},
|
|
77
|
+
})
|
package/src/vite.mjs
CHANGED
|
@@ -1,38 +1,7 @@
|
|
|
1
|
-
//
|
|
2
|
-
//
|
|
3
|
-
//
|
|
4
|
-
//
|
|
5
|
-
// virtual:kerf/routes server: the manifest, every route, layout and card module, and each one's stylesheets
|
|
6
|
-
// client: the route table and a chunk loader per route id (load/meta/prerender stripped)
|
|
7
|
-
// virtual:kerf/app server: site config, build id, card fonts (bytes, so every preset can read them)
|
|
8
|
-
// virtual:kerf/entry-server the Nitro SSR entry: `export default { fetch }`
|
|
9
|
-
// virtual:kerf/entry-client the client entry: `start()`, unless the app has src/entry.client.ts
|
|
10
|
-
// virtual:kerf/fns server: imports every server module, so `/_kerf/fn/<id>` knows every function
|
|
11
|
-
// virtual:kerf/context server: `src/context.server.ts`'s default export (the app's part of `ctx`)
|
|
12
|
-
// virtual:kerf/auth server: `src/auth.server.ts`'s default export, mounted at its base path
|
|
13
|
-
// virtual:kerf/migrations server: `drizzle/`'s migrations, embedded (a bundle can't read a folder on every preset)
|
|
14
|
-
// virtual:kerf/media server: the `media.server` provider when one is bound (research 29 §6)
|
|
15
|
-
// virtual:kerf/realtime server: `src/realtime.server.ts`'s default export (the bus, origins and limits)
|
|
16
|
-
// virtual:kerf/cache server: `src/cache.server.ts`'s default export (the shared cache's store)
|
|
17
|
-
// virtual:kerf/cron server: `src/cron.server.ts`'s default export (jobs on a schedule)
|
|
18
|
-
// virtual:kerf/email server: `src/email.server.ts`'s default export (the mailer)
|
|
19
|
-
// virtual:kerf/jobs server: `src/jobs.server.ts`'s default export (the job queue)
|
|
20
|
-
// virtual:kerf/extensions server: each `server.extension` provider with its `src/<key>.server.ts` (extension.ts)
|
|
21
|
-
//
|
|
22
|
-
// Server modules (`src/server/**`, `*.server.ts`, research 27 §2): each `query`/`mutation`/`stream`/`channel` export
|
|
23
|
-
// gets an `$id` on both sides; the client build replaces the module with stubs that keep only `optimistic`, the
|
|
24
|
-
// query's shape and a shared state's `initial`.
|
|
25
|
-
//
|
|
26
|
-
// Stylesheets: routes are chunks the entry only reaches through `import()`, so `?assets=client` names just the entry's
|
|
27
|
-
// CSS. Each route and layout's own CSS comes from Nitro's assets manifest (build) or the client module graph (dev);
|
|
28
|
-
// the server links the entry's and those of the levels it matched, so nothing paints before its styles and other
|
|
29
|
-
// routes' CSS stays out of the page. In dev the links stand in for Vite's injected `<style>`s and HMR updates them.
|
|
30
|
-
// A build keeps each chunk's sheet for client navigation and writes a shared sheet (what every route has) and one sheet
|
|
31
|
-
// per route for the rest, hashed and cached for good. Each page carries the part of those its first paint needs
|
|
32
|
-
// (`firstPaint`) and links them at the end of its shell, where they block nothing above and hold whatever streams after.
|
|
33
|
-
// `site: { criticalCss: false }` splits by chunk and puts them in the HTML (`inlineSheets`, inline.mjs): whole while the
|
|
34
|
-
// document fits the first flight, else the rules the page's HTML reaches, with the sheets behind them as links that
|
|
35
|
-
// don't hold the paint. `site: { inlineCss: false }` keeps plain links.
|
|
1
|
+
// Start supplies Nitro's virtual entries and the file-routes manifest. Client modules reach
|
|
2
|
+
// routes through dynamic imports and drop server-only exports and function bodies.
|
|
3
|
+
// Route CSS follows the matched layouts and routes from the client graph in dev, or Nitro's
|
|
4
|
+
// asset manifest in a build. Dev links let Vite swap the existing sheets during HMR.
|
|
36
5
|
|
|
37
6
|
import { existsSync } from 'node:fs'
|
|
38
7
|
import { relative } from 'node:path'
|
|
@@ -197,6 +166,9 @@ export default function kerfStart(options = {}) {
|
|
|
197
166
|
entryWatchLifecycle(state, server, modes)
|
|
198
167
|
return configured
|
|
199
168
|
},
|
|
169
|
+
closeServer() {
|
|
170
|
+
state.closeRoutes?.()
|
|
171
|
+
},
|
|
200
172
|
hotUpdate: shapeHotUpdate(state, modes, hotUpdate(state)),
|
|
201
173
|
},
|
|
202
174
|
{
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
// A recursive `fs.watch` that can fail without taking the process with it. A sandbox or a busy machine limits
|
|
2
|
+
// watchers (EMFILE, ENOSPC), and an FSWatcher's 'error' with no listener is an uncaught exception.
|
|
3
|
+
|
|
4
|
+
import { watch } from 'node:fs'
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* `fs.watch(dir, { recursive: true }, listener)`, or null when it can't watch. Whether it can't start or fails later,
|
|
8
|
+
* `warn` hears why once and the watcher is closed: the caller goes on without it.
|
|
9
|
+
*/
|
|
10
|
+
export function watchTree(dir, listener, warn) {
|
|
11
|
+
let watcher
|
|
12
|
+
try {
|
|
13
|
+
watcher = watch(dir, { recursive: true }, listener)
|
|
14
|
+
} catch (error) {
|
|
15
|
+
warn(error)
|
|
16
|
+
return null
|
|
17
|
+
}
|
|
18
|
+
watcher.on('error', (error) => {
|
|
19
|
+
warn(error)
|
|
20
|
+
watcher.close()
|
|
21
|
+
})
|
|
22
|
+
return watcher
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** What a watcher's failure was, for a warning: its code (EMFILE) when it has one. */
|
|
26
|
+
export const watchFailure = (error) => error?.code ?? error?.message ?? String(error)
|