prunelle 0.1.1 → 0.5.2
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/llms.txt +23 -19
- package/package.json +8 -2
- package/src/a11y/declaration.ts +335 -0
- package/src/a11y/index.ts +446 -0
- package/src/a11y/rgaa-map.ts +184 -0
- package/src/attrs.ts +11 -3
- package/src/build/bundle.ts +80 -36
- package/src/build/client-entries.ts +3 -2
- package/src/build/client-plugin.ts +8 -4
- package/src/build/client-prune.ts +56 -6
- package/src/build/compile.ts +11 -9
- package/src/build/ecoindex.ts +229 -0
- package/src/build/index.ts +174 -108
- package/src/build/islands.ts +2 -2
- package/src/build/manifest.ts +66 -5
- package/src/build/output.ts +2 -2
- package/src/build/plugin-host.ts +91 -33
- package/src/build/precompress.ts +15 -2
- package/src/build/prerender.ts +128 -46
- package/src/build/report.ts +23 -2
- package/src/build/resolve.ts +8 -6
- package/src/build/routes.ts +175 -10
- package/src/build/static.ts +137 -39
- package/src/build/status-pages.ts +127 -0
- package/src/build/style-bundles.ts +526 -0
- package/src/cli/check-forms.ts +654 -0
- package/src/cli/check-links.ts +619 -0
- package/src/cli/check.ts +52 -5
- package/src/cli/commands.ts +86 -4
- package/src/cli/docs.ts +402 -0
- package/src/cli/inspect.ts +31 -2
- package/src/cli/mcp-tools.ts +480 -0
- package/src/cli/mcp.ts +205 -0
- package/src/cli/new.ts +2 -2
- package/src/cli/render.ts +261 -0
- package/src/cli/upgrade-names.ts +73 -13
- package/src/cli/upgrade.ts +137 -16
- package/src/compiler/analyze.ts +20 -6
- package/src/compiler/cacheability.ts +592 -0
- package/src/compiler/compliance-rgaa.ts +502 -0
- package/src/compiler/compliance.ts +120 -221
- package/src/compiler/dev-source.ts +87 -0
- package/src/compiler/dom-attrs.ts +138 -65
- package/src/compiler/dom.ts +12 -11
- package/src/compiler/expr-context.ts +167 -57
- package/src/compiler/props.ts +87 -36
- package/src/compiler/scope.ts +56 -17
- package/src/compiler/ssr-prunelle-tags.ts +27 -14
- package/src/compiler/ssr.ts +216 -84
- package/src/dev/error-log.ts +151 -0
- package/src/dev/index.ts +84 -34
- package/src/dev/open-editor.ts +204 -0
- package/src/dev/protocol.ts +1 -0
- package/src/dev/reload.ts +5 -3
- package/src/dev/supervisor.ts +42 -25
- package/src/dev/watchers.ts +47 -11
- package/src/dom/action.ts +4 -1
- package/src/dom/attrs.ts +15 -3
- package/src/dom/extras.ts +2 -2
- package/src/dom/island.ts +11 -10
- package/src/plugins/config.ts +4 -4
- package/src/plugins/index.ts +2 -2
- package/src/plugins/public.ts +5 -2
- package/src/plugins/services.ts +62 -0
- package/src/plugins/types.ts +32 -0
- package/src/server/action-protect.ts +198 -0
- package/src/server/action-registry.ts +1 -1
- package/src/server/action.ts +82 -27
- package/src/server/assets.ts +34 -2
- package/src/server/compress.ts +91 -9
- package/src/server/errors.ts +303 -65
- package/src/server/form-schema.ts +343 -0
- package/src/server/health.ts +244 -0
- package/src/server/http.ts +128 -31
- package/src/server/index.ts +230 -260
- package/src/server/loader.ts +5 -0
- package/src/server/param-matchers.ts +112 -0
- package/src/server/plugin-host.ts +123 -88
- package/src/server/public.ts +3 -3
- package/src/server/rate-limit.ts +58 -35
- package/src/server/request-body.ts +1 -1
- package/src/server/route-cache.ts +423 -0
- package/src/server/route-table.ts +339 -8
- package/src/server/router.ts +125 -40
- package/src/server/routing.ts +196 -63
- package/src/server/security.ts +208 -32
- package/src/server/serve-handlers.ts +21 -7
- package/src/server/start.ts +60 -16
- package/src/server/static-dir.ts +61 -8
- package/src/server/stream.ts +41 -22
- package/src/ssr/context.ts +85 -3
- package/src/ssr/index.ts +120 -1
- package/src/ssr/region.ts +31 -19
- package/src/test/browser.ts +6 -0
- package/src/test/index.ts +17 -3
- package/src/ts-plugin/diagnostics.ts +378 -0
- package/src/ts-plugin/fixes.ts +364 -0
- package/src/ts-plugin/index.ts +194 -0
- package/templates/_shared/AGENTS.md +2 -2
- package/templates/_shared/mcp.json +11 -0
- package/templates/_shared/src/routes/legal.tsx +5 -0
- package/templates/_shared/tsconfig.json +5 -0
- package/templates/blog/prunelle.config.ts +1 -1
- package/templates/blog/src/routes/index.tsx +4 -0
- package/ts-plugin.cjs +4277 -0
package/src/server/static-dir.ts
CHANGED
|
@@ -1,12 +1,16 @@
|
|
|
1
1
|
// Standalone `--static` directory server (used when `outDir` holds exported HTML without `manifest.json`): every file is listed once at startup, so a request is a map lookup.
|
|
2
2
|
|
|
3
3
|
import type { FSWatcher } from 'node:fs'
|
|
4
|
+
import type { PrunellePlugin } from '../plugins/index'
|
|
5
|
+
import type { NavigationConfig } from '../ssr/navigation'
|
|
4
6
|
import type { PrunelleApp, PrunelleServer } from './http'
|
|
5
7
|
import type { SecurityHeadersOptions, TrustProxy } from './security'
|
|
6
8
|
import type { FileSource, ServedFile } from './served-file'
|
|
7
9
|
import { readdirSync, readFileSync, realpathSync, statSync, watch } from 'node:fs'
|
|
8
10
|
import { extname, join, resolve } from 'node:path'
|
|
9
11
|
import { isInside } from '../build/is-inside'
|
|
12
|
+
import { resolvePlugins } from '../plugins/index'
|
|
13
|
+
import { createNavigation, cspSha256 } from '../ssr/navigation'
|
|
10
14
|
import { CompressionCache, isCompressibleType } from './compress'
|
|
11
15
|
import { applyHstsHeader, MIME } from './http'
|
|
12
16
|
import { decodeRequestPath } from './request-path'
|
|
@@ -15,6 +19,37 @@ import { createFileServer, servedFile } from './served-file'
|
|
|
15
19
|
|
|
16
20
|
const isRead = (request: Request): boolean => request.method === 'GET' || request.method === 'HEAD'
|
|
17
21
|
|
|
22
|
+
const EXTRA_STATIC_MIME: Record<string, string> = {
|
|
23
|
+
'.htm': 'text/html; charset=utf-8',
|
|
24
|
+
'.rss': 'application/rss+xml; charset=utf-8',
|
|
25
|
+
'.atom': 'application/atom+xml; charset=utf-8',
|
|
26
|
+
'.ics': 'text/calendar; charset=utf-8',
|
|
27
|
+
'.csv': 'text/csv; charset=utf-8',
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export interface StaticDirExtraOptions {
|
|
31
|
+
navigation?: NavigationConfig | undefined
|
|
32
|
+
plugins?: readonly PrunellePlugin[] | undefined
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function findNotFound(rel: string | undefined, byDir: ReadonlyMap<string, ServedFile>): ServedFile | undefined {
|
|
36
|
+
if (byDir.size === 0)
|
|
37
|
+
return undefined
|
|
38
|
+
if (rel !== undefined && rel !== '') {
|
|
39
|
+
let dir = rel
|
|
40
|
+
while (true) {
|
|
41
|
+
const hit = byDir.get(dir)
|
|
42
|
+
if (hit !== undefined)
|
|
43
|
+
return hit
|
|
44
|
+
const slash = dir.lastIndexOf('/')
|
|
45
|
+
if (slash === -1)
|
|
46
|
+
break
|
|
47
|
+
dir = dir.slice(0, slash)
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
return byDir.get('')
|
|
51
|
+
}
|
|
52
|
+
|
|
18
53
|
|
|
19
54
|
/** The files under `absRoot` by their path from it, `/`-separated; a symlink counts only when it lands on a file inside `realRoot`. */
|
|
20
55
|
function listFiles(absRoot: string, realRoot: string): Map<string, string> {
|
|
@@ -53,6 +88,7 @@ export function createStaticDirServer(
|
|
|
53
88
|
compressEnabled: boolean,
|
|
54
89
|
trustProxy: TrustProxy,
|
|
55
90
|
isDev = false,
|
|
91
|
+
extra?: StaticDirExtraOptions,
|
|
56
92
|
): PrunelleApp {
|
|
57
93
|
const prefix = assetPrefix.replace(/^\/+/, '').replace(/\/$/, '')
|
|
58
94
|
const absRoot = resolve(outDir)
|
|
@@ -67,7 +103,16 @@ export function createStaticDirServer(
|
|
|
67
103
|
const securityEntries = buildSecurityHeaderEntries(security)
|
|
68
104
|
const securityRecord = Object.fromEntries(securityEntries)
|
|
69
105
|
const baseCsp = resolveCspPolicy(security)
|
|
70
|
-
const
|
|
106
|
+
const nav = extra !== undefined ? createNavigation(extra.navigation) : undefined
|
|
107
|
+
const plugins = extra?.plugins !== undefined ? resolvePlugins(extra.plugins) : []
|
|
108
|
+
const extraStyleHashes = [PRUNELLE_ISLAND_STYLE_HASH, ...(nav?.styleHashes ?? [])]
|
|
109
|
+
const extraScriptHashes = [
|
|
110
|
+
...(nav?.scriptHashes ?? []),
|
|
111
|
+
...plugins.flatMap(p => p.inlineScripts ?? []).map(cspSha256),
|
|
112
|
+
]
|
|
113
|
+
const htmlCsp = baseCsp !== undefined
|
|
114
|
+
? withCspHashes(baseCsp, { styleHashes: extraStyleHashes, scriptHashes: extraScriptHashes })
|
|
115
|
+
: undefined
|
|
71
116
|
const hstsValue = resolveHstsValue(security)
|
|
72
117
|
const withHsts = hstsValue === undefined || isDev
|
|
73
118
|
? (res: Response) => res
|
|
@@ -76,7 +121,7 @@ export function createStaticDirServer(
|
|
|
76
121
|
|
|
77
122
|
function entryFor(rel: string, path: string, all: ReadonlyMap<string, string>): ServedFile {
|
|
78
123
|
const ext = extname(rel).toLowerCase()
|
|
79
|
-
const type = MIME[ext] ?? 'application/octet-stream'
|
|
124
|
+
const type = MIME[ext] ?? EXTRA_STATIC_MIME[ext] ?? 'application/octet-stream'
|
|
80
125
|
const isHtml = ext === '.html' || ext === '.htm'
|
|
81
126
|
// An exported page's CSP gains the hashes of its own `<style>` blocks.
|
|
82
127
|
const csp = isHtml && htmlCsp !== undefined ? withCspHashes(htmlCsp, { styleHashes: inlineStyleHashes(readFileSync(path, 'utf8')) }) : undefined
|
|
@@ -100,11 +145,18 @@ export function createStaticDirServer(
|
|
|
100
145
|
}
|
|
101
146
|
|
|
102
147
|
// Each file at its own path, then `x.html` at `x` and `x/index.html` at `x`, a real file always winning.
|
|
103
|
-
function buildTable(): { table: Map<string, ServedFile>,
|
|
148
|
+
function buildTable(): { table: Map<string, ServedFile>, notFoundByDir: Map<string, ServedFile> } {
|
|
104
149
|
const files = listFiles(absRoot, realRoot)
|
|
105
150
|
const table = new Map<string, ServedFile>()
|
|
106
|
-
|
|
107
|
-
|
|
151
|
+
const notFoundByDir = new Map<string, ServedFile>()
|
|
152
|
+
for (const [rel, path] of files) {
|
|
153
|
+
const entry = entryFor(rel, path, files)
|
|
154
|
+
table.set(rel, entry)
|
|
155
|
+
if (rel === '404.html')
|
|
156
|
+
notFoundByDir.set('', entry)
|
|
157
|
+
else if (rel.endsWith('/404.html'))
|
|
158
|
+
notFoundByDir.set(rel.slice(0, -'/404.html'.length), entry)
|
|
159
|
+
}
|
|
108
160
|
for (const [rel, entry] of [...table]) {
|
|
109
161
|
if (rel.endsWith('.html') && !table.has(rel.slice(0, -5)))
|
|
110
162
|
table.set(rel.slice(0, -5), entry)
|
|
@@ -116,7 +168,7 @@ export function createStaticDirServer(
|
|
|
116
168
|
table.set(dir, entry)
|
|
117
169
|
}
|
|
118
170
|
}
|
|
119
|
-
return { table,
|
|
171
|
+
return { table, notFoundByDir }
|
|
120
172
|
}
|
|
121
173
|
|
|
122
174
|
let current = buildTable()
|
|
@@ -141,8 +193,9 @@ export function createStaticDirServer(
|
|
|
141
193
|
const found = rel === undefined ? undefined : current.table.get(rel)
|
|
142
194
|
if (found !== undefined)
|
|
143
195
|
return serveFile(req, found)
|
|
144
|
-
|
|
145
|
-
|
|
196
|
+
const notFound = findNotFound(rel, current.notFoundByDir)
|
|
197
|
+
if (notFound !== undefined)
|
|
198
|
+
return serveFile(req, notFound, 404)
|
|
146
199
|
return withHsts(new Response('Not Found', { status: 404, headers: securityRecord }), req)
|
|
147
200
|
}
|
|
148
201
|
|
package/src/server/stream.ts
CHANGED
|
@@ -37,6 +37,7 @@ async function settleWithin(
|
|
|
37
37
|
timer = setTimeout(() => {
|
|
38
38
|
if (onAbort !== undefined)
|
|
39
39
|
signal.removeEventListener('abort', onAbort)
|
|
40
|
+
chunk.discard?.()
|
|
40
41
|
const error = new Error(`<Suspense> boundary ${chunk.id} did not resolve within ${streamTimeout} ms`)
|
|
41
42
|
resolve({ html: runInScope(() => chunk.renderError(error)), error })
|
|
42
43
|
}, remaining)
|
|
@@ -52,7 +53,13 @@ async function settleWithin(
|
|
|
52
53
|
}
|
|
53
54
|
|
|
54
55
|
/** Streams `shell` (a document holding `STREAM_TAIL_MARK`), with every boundary of `rctx` flushed before its tail. */
|
|
55
|
-
export function streamDocument(
|
|
56
|
+
export function streamDocument(
|
|
57
|
+
shell: string,
|
|
58
|
+
rctx: RenderContext,
|
|
59
|
+
streamTimeout: number,
|
|
60
|
+
onBoundaryError: (error: unknown) => void,
|
|
61
|
+
transformChunk?: (html: string) => string | Promise<string>,
|
|
62
|
+
): ReadableStream<Uint8Array> {
|
|
56
63
|
let splitAt = shell.lastIndexOf(STREAM_TAIL_MARK)
|
|
57
64
|
let tailOffset = STREAM_TAIL_MARK.length
|
|
58
65
|
if (splitAt === -1) {
|
|
@@ -75,39 +82,51 @@ export function streamDocument(shell: string, rctx: RenderContext, streamTimeout
|
|
|
75
82
|
}
|
|
76
83
|
catch {
|
|
77
84
|
closed = true
|
|
85
|
+
rctx.aborted = true
|
|
78
86
|
abortCtrl.abort()
|
|
79
87
|
}
|
|
80
88
|
}
|
|
81
89
|
|
|
82
90
|
return new ReadableStream<Uint8Array>({
|
|
83
91
|
async start(controller) {
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
const chunks = rctx.pending.slice(flushed)
|
|
91
|
-
flushed = rctx.pending.length
|
|
92
|
-
await Promise.all(chunks.map(async (chunk) => {
|
|
93
|
-
const settled = await settleWithin(chunk, deadline, streamTimeout, abortCtrl.signal, runInScope)
|
|
94
|
-
if (settled === undefined || closed || abortCtrl.signal.aborted)
|
|
92
|
+
try {
|
|
93
|
+
safeEnqueue(controller, textEncoder.encode(openingHtml))
|
|
94
|
+
// A resolved boundary can render boundaries of its own, so each flush also drains the ones it added.
|
|
95
|
+
let flushed = 0
|
|
96
|
+
const flushPending = async (): Promise<void> => {
|
|
97
|
+
if (closed || abortCtrl.signal.aborted)
|
|
95
98
|
return
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
99
|
+
const chunks = rctx.pending.slice(flushed)
|
|
100
|
+
flushed = rctx.pending.length
|
|
101
|
+
await Promise.all(chunks.map(async (chunk) => {
|
|
102
|
+
const settled = await settleWithin(chunk, deadline, streamTimeout, abortCtrl.signal, runInScope)
|
|
103
|
+
if (settled === undefined || closed || abortCtrl.signal.aborted)
|
|
104
|
+
return
|
|
105
|
+
if ('error' in settled)
|
|
106
|
+
runInScope(() => onBoundaryError(settled.error))
|
|
107
|
+
let chunkHtml = settled.html
|
|
108
|
+
if (transformChunk !== undefined && chunkHtml !== '')
|
|
109
|
+
chunkHtml = await runInScope(() => transformChunk(chunkHtml))
|
|
110
|
+
if (closed || abortCtrl.signal.aborted)
|
|
111
|
+
return
|
|
112
|
+
safeEnqueue(controller, textEncoder.encode(streamChunkScript(chunk.id, chunkHtml)))
|
|
113
|
+
await flushPending()
|
|
114
|
+
}))
|
|
115
|
+
}
|
|
116
|
+
await flushPending()
|
|
117
|
+
if (!closed && !abortCtrl.signal.aborted) {
|
|
118
|
+
safeEnqueue(controller, textEncoder.encode(tailHtml))
|
|
119
|
+
closed = true
|
|
120
|
+
safeClose(controller)
|
|
121
|
+
}
|
|
101
122
|
}
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
safeEnqueue(controller, textEncoder.encode(tailHtml))
|
|
105
|
-
closed = true
|
|
106
|
-
safeClose(controller)
|
|
123
|
+
finally {
|
|
124
|
+
rctx.aborted = true
|
|
107
125
|
}
|
|
108
126
|
},
|
|
109
127
|
cancel() {
|
|
110
128
|
closed = true
|
|
129
|
+
rctx.aborted = true
|
|
111
130
|
abortCtrl.abort()
|
|
112
131
|
},
|
|
113
132
|
})
|
package/src/ssr/context.ts
CHANGED
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
|
|
4
4
|
import type { CatchProps, ConsentGateProps } from '../context'
|
|
5
5
|
import type { Html, PrunelleChild } from '../jsx-runtime'
|
|
6
|
+
import type { FieldConstraint } from '../server/form-schema'
|
|
6
7
|
import { AsyncLocalStorage } from 'node:async_hooks'
|
|
7
8
|
import { registerServerContextBridge } from '../context'
|
|
8
9
|
import { raw, ssrChild } from './index'
|
|
@@ -18,6 +19,8 @@ export interface PendingChunk {
|
|
|
18
19
|
// Settles to the boundary's HTML, or to its error template and the error: it never rejects.
|
|
19
20
|
settled: Promise<SettledChunk>
|
|
20
21
|
renderError: (error: unknown) => string
|
|
22
|
+
/** Marks this chunk as timed out / aborted so late resolution skips rendering into the RenderContext. */
|
|
23
|
+
discard?: () => void
|
|
21
24
|
}
|
|
22
25
|
|
|
23
26
|
export interface RenderContext {
|
|
@@ -51,10 +54,18 @@ export interface RenderContext {
|
|
|
51
54
|
inTarget: boolean
|
|
52
55
|
/** Compiler-emitted inline `<style>` contents rendered during this request, for CSP hashing. */
|
|
53
56
|
inlineStyles: string[] | undefined
|
|
57
|
+
/** True once HTTP headers (and CSP) have been flushed for a streamed response. */
|
|
58
|
+
headersFlushed: boolean
|
|
59
|
+
/** True once the post-flush inline `<style>` warning has been emitted for this request. */
|
|
60
|
+
warnedStreamStyle: boolean
|
|
61
|
+
/** True once the stream/region finished, timed out, was aborted, or was discarded (e.g. HEAD). */
|
|
62
|
+
aborted: boolean
|
|
54
63
|
/** Request consent state used by `<ConsentGate>`. */
|
|
55
64
|
consent: { has(category: string): boolean } | undefined
|
|
56
65
|
/** Reports an error a `<Catch>` rendered its fallback for, to the app's error hook. */
|
|
57
66
|
onCaught: ((error: unknown) => void) | undefined
|
|
67
|
+
/** Actions referenced via `useAction(fn).action` during this request, keyed by action URL. */
|
|
68
|
+
formActions: Map<string, unknown> | undefined
|
|
58
69
|
}
|
|
59
70
|
|
|
60
71
|
interface RenderScope {
|
|
@@ -63,12 +74,25 @@ interface RenderScope {
|
|
|
63
74
|
outerContexts: ReadonlyMap<symbol, unknown> | undefined
|
|
64
75
|
island: string | undefined
|
|
65
76
|
inTarget: boolean
|
|
77
|
+
formFields: ReadonlyMap<string, FieldConstraint> | undefined
|
|
66
78
|
}
|
|
67
79
|
|
|
68
80
|
const STORAGE_KEY = Symbol.for('pru.render.storage')
|
|
69
81
|
const SCOPE_STORAGE_KEY = Symbol.for('pru.render.scope.storage')
|
|
70
82
|
const renderStorage: AsyncLocalStorage<RenderContext> = ((globalThis as Record<symbol, AsyncLocalStorage<RenderContext> | undefined>)[STORAGE_KEY] ??= new AsyncLocalStorage<RenderContext>())
|
|
71
83
|
const scopeStorage: AsyncLocalStorage<RenderScope> = ((globalThis as Record<symbol, AsyncLocalStorage<RenderScope> | undefined>)[SCOPE_STORAGE_KEY] ??= new AsyncLocalStorage<RenderScope>())
|
|
84
|
+
let fallbackFormAction: { url: string, action: unknown } | undefined
|
|
85
|
+
let fallbackFormFields: ReadonlyMap<string, FieldConstraint> | undefined
|
|
86
|
+
|
|
87
|
+
;(globalThis as { __pruAct?: (url: string, action: unknown) => void }).__pruAct = (url, action) => {
|
|
88
|
+
if (url === '')
|
|
89
|
+
return
|
|
90
|
+
const ctx = renderStorage.getStore()
|
|
91
|
+
if (ctx !== undefined)
|
|
92
|
+
(ctx.formActions ??= new Map()).set(url, action)
|
|
93
|
+
else
|
|
94
|
+
fallbackFormAction = { url, action }
|
|
95
|
+
}
|
|
72
96
|
|
|
73
97
|
function activeScope(ctx: RenderContext): RenderScope {
|
|
74
98
|
const scope = scopeStorage.getStore()
|
|
@@ -80,6 +104,38 @@ function activeScope(ctx: RenderContext): RenderScope {
|
|
|
80
104
|
outerContexts: ctx.outerContexts,
|
|
81
105
|
island: ctx.island,
|
|
82
106
|
inTarget: ctx.inTarget,
|
|
107
|
+
formFields: undefined,
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
export function lookupFormAction(url: string): unknown {
|
|
112
|
+
const ctx = renderStorage.getStore()
|
|
113
|
+
if (ctx !== undefined)
|
|
114
|
+
return ctx.formActions?.get(url)
|
|
115
|
+
return fallbackFormAction?.url === url ? fallbackFormAction.action : undefined
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
export function currentFormFields(): ReadonlyMap<string, FieldConstraint> | undefined {
|
|
119
|
+
const ctx = renderStorage.getStore()
|
|
120
|
+
return ctx !== undefined ? activeScope(ctx).formFields : fallbackFormFields
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
export function runWithFormFields<T>(fields: ReadonlyMap<string, FieldConstraint>, fn: () => T): T {
|
|
124
|
+
const ctx = renderStorage.getStore()
|
|
125
|
+
if (ctx !== undefined)
|
|
126
|
+
return scopeStorage.run({ ...activeScope(ctx), formFields: fields }, fn)
|
|
127
|
+
const prev = fallbackFormFields
|
|
128
|
+
fallbackFormFields = fields
|
|
129
|
+
try {
|
|
130
|
+
const out = fn()
|
|
131
|
+
if (out instanceof Promise)
|
|
132
|
+
return out.finally(() => { fallbackFormFields = prev }) as T
|
|
133
|
+
fallbackFormFields = prev
|
|
134
|
+
return out
|
|
135
|
+
}
|
|
136
|
+
catch (err) {
|
|
137
|
+
fallbackFormFields = prev
|
|
138
|
+
throw err
|
|
83
139
|
}
|
|
84
140
|
}
|
|
85
141
|
|
|
@@ -163,8 +219,12 @@ export function createRenderContext(
|
|
|
163
219
|
regionAncestors: ancestors,
|
|
164
220
|
inTarget: false,
|
|
165
221
|
inlineStyles: undefined,
|
|
222
|
+
headersFlushed: false,
|
|
223
|
+
warnedStreamStyle: false,
|
|
224
|
+
aborted: false,
|
|
166
225
|
consent,
|
|
167
226
|
onCaught,
|
|
227
|
+
formActions: undefined,
|
|
168
228
|
}
|
|
169
229
|
}
|
|
170
230
|
|
|
@@ -173,9 +233,14 @@ export function recordInlineStyle(css: string): void {
|
|
|
173
233
|
const ctx = renderStorage.getStore()
|
|
174
234
|
if (ctx === undefined || css === '')
|
|
175
235
|
return
|
|
236
|
+
const isNew = ctx.inlineStyles === undefined || !ctx.inlineStyles.includes(css)
|
|
237
|
+
if (ctx.headersFlushed && isNew && !ctx.warnedStreamStyle) {
|
|
238
|
+
ctx.warnedStreamStyle = true
|
|
239
|
+
console.warn('prunelle: an inline <style> was rendered inside a streamed <Suspense> boundary after CSP headers were sent; move the style into a CSS file or outside <Suspense> so strict CSP does not block it.')
|
|
240
|
+
}
|
|
176
241
|
if (ctx.inlineStyles === undefined)
|
|
177
242
|
ctx.inlineStyles = [css]
|
|
178
|
-
else if (
|
|
243
|
+
else if (isNew)
|
|
179
244
|
ctx.inlineStyles.push(css)
|
|
180
245
|
}
|
|
181
246
|
|
|
@@ -277,18 +342,35 @@ export function Suspense(props: { fallback?: PrunelleChild, error?: PrunelleChil
|
|
|
277
342
|
return ''
|
|
278
343
|
}
|
|
279
344
|
}
|
|
280
|
-
|
|
345
|
+
let discarded = false
|
|
346
|
+
const isAborted = (): boolean => ctx.aborted || discarded
|
|
347
|
+
ctx.pending.push({
|
|
348
|
+
id,
|
|
349
|
+
settled: settle(ctx, scope, child, renderError, isAborted),
|
|
350
|
+
renderError,
|
|
351
|
+
discard: () => { discarded = true },
|
|
352
|
+
})
|
|
281
353
|
|
|
282
354
|
const fallbackHtml = ssrChild(props.fallback)
|
|
283
355
|
return raw(`<pru-s id="k-s-${id}">${fallbackHtml}</pru-s>`)
|
|
284
356
|
}
|
|
285
357
|
|
|
286
|
-
async function settle(
|
|
358
|
+
async function settle(
|
|
359
|
+
ctx: RenderContext,
|
|
360
|
+
scope: RenderScope,
|
|
361
|
+
child: Promise<PrunelleChild>,
|
|
362
|
+
renderError: (error: unknown) => string,
|
|
363
|
+
isAborted: () => boolean,
|
|
364
|
+
): Promise<SettledChunk> {
|
|
287
365
|
try {
|
|
288
366
|
const resolved = await child
|
|
367
|
+
if (isAborted())
|
|
368
|
+
return { html: '' }
|
|
289
369
|
return { html: runWithRenderContext(ctx, () => scopeStorage.run(scope, () => ssrChild(resolved))) }
|
|
290
370
|
}
|
|
291
371
|
catch (error) {
|
|
372
|
+
if (isAborted())
|
|
373
|
+
return { html: '' }
|
|
292
374
|
return { html: renderError(error), error }
|
|
293
375
|
}
|
|
294
376
|
}
|
package/src/ssr/index.ts
CHANGED
|
@@ -1,11 +1,15 @@
|
|
|
1
1
|
// Prunelle SSR runtime: flat string concatenation with fast-path escaping and zero-overhead islands.
|
|
2
2
|
|
|
3
3
|
import type { Html, HydrateStrategy, PrunelleChild } from '../jsx-runtime'
|
|
4
|
+
import type { ServerAction } from '../server/action'
|
|
5
|
+
import type { FieldConstraint } from '../server/form-schema'
|
|
4
6
|
import { isBlockedAttr, isStringBoolAttr, isUnsafeUrlAttr } from '../attrs'
|
|
5
7
|
import { renderOnServer } from '../reactivity/index'
|
|
8
|
+
import { renderProtectFields } from '../server/action-protect'
|
|
9
|
+
import { extractFormSchema, lookupFieldConstraint } from '../server/form-schema'
|
|
6
10
|
import { styleText } from '../style'
|
|
7
11
|
import { assertRenderable } from '../unrenderable'
|
|
8
|
-
import { currentRenderContext, PRUNELLE_STREAM_SCRIPT, renderIsland } from './context'
|
|
12
|
+
import { currentFormFields, currentRenderContext, lookupFormAction, PRUNELLE_STREAM_SCRIPT, renderIsland, runWithFormFields } from './context'
|
|
9
13
|
import { keepScrollTag } from './navigation'
|
|
10
14
|
export { ssrStyleBlock } from './context'
|
|
11
15
|
|
|
@@ -143,6 +147,8 @@ export function ssrSpread(props: Record<string, unknown> | null | undefined, tag
|
|
|
143
147
|
if (props == null || typeof props !== 'object')
|
|
144
148
|
return ''
|
|
145
149
|
let out = ''
|
|
150
|
+
let formPresent = 0
|
|
151
|
+
const trackForm = (tag === 'input' || tag === 'select' || tag === 'textarea') && currentFormFields() !== undefined
|
|
146
152
|
for (const [rawKey, value] of Object.entries(props)) {
|
|
147
153
|
if (rawKey === 'key' || rawKey === 'ref' || rawKey === '$hydrate' || rawKey === 'children')
|
|
148
154
|
continue
|
|
@@ -151,8 +157,121 @@ export function ssrSpread(props: Record<string, unknown> | null | undefined, tag
|
|
|
151
157
|
const name = rawKey === 'className' ? 'class' : rawKey === 'htmlFor' ? 'for' : rawKey
|
|
152
158
|
if (isBlockedAttr(name))
|
|
153
159
|
continue
|
|
160
|
+
if (trackForm && value !== undefined) {
|
|
161
|
+
const bit = FORM_ATTR_BITS[name.toLowerCase()]
|
|
162
|
+
if (bit !== undefined)
|
|
163
|
+
formPresent |= bit
|
|
164
|
+
}
|
|
154
165
|
out += name === 'style' ? ssrStyle(value) : ssrAttr(name, value, tag)
|
|
155
166
|
}
|
|
167
|
+
if (trackForm && typeof props.name === 'string')
|
|
168
|
+
out += ssrFormAttrs(tag, props.name, formPresent, props.type)
|
|
169
|
+
return out
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
const FORM_ATTR_BITS: Record<string, number> = {
|
|
173
|
+
type: 1,
|
|
174
|
+
required: 2,
|
|
175
|
+
minlength: 4,
|
|
176
|
+
maxlength: 8,
|
|
177
|
+
min: 16,
|
|
178
|
+
max: 32,
|
|
179
|
+
step: 64,
|
|
180
|
+
pattern: 128,
|
|
181
|
+
}
|
|
182
|
+
const TEXT_INPUT_TYPES = new Set(['text', 'search', 'url', 'tel', 'email', 'password'])
|
|
183
|
+
const NON_REQUIRED_INPUT_TYPES = new Set(['hidden', 'submit', 'button', 'reset', 'image'])
|
|
184
|
+
|
|
185
|
+
function resolveActionForForm(action: unknown): ServerAction<unknown, unknown> | undefined {
|
|
186
|
+
if (typeof action === 'function' && (action as { __pruAction?: boolean }).__pruAction === true)
|
|
187
|
+
return action as ServerAction<unknown, unknown>
|
|
188
|
+
if (typeof action === 'string') {
|
|
189
|
+
const found = lookupFormAction(action)
|
|
190
|
+
if (typeof found === 'function' && (found as { __pruAction?: boolean }).__pruAction === true)
|
|
191
|
+
return found as ServerAction<unknown, unknown>
|
|
192
|
+
}
|
|
193
|
+
return undefined
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
function formFieldsOf(act: ServerAction<unknown, unknown>): ReadonlyMap<string, FieldConstraint> | undefined {
|
|
197
|
+
if (act.schema === undefined)
|
|
198
|
+
return undefined
|
|
199
|
+
const extracted = extractFormSchema(act.schema)
|
|
200
|
+
return extracted.ok && extracted.fields.size > 0 ? extracted.fields : undefined
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
/** Wraps an action-bound `<form>` render during SSR: injects schema constraints for child fields and appends honeypot / signed timestamp inputs. */
|
|
204
|
+
export function ssrForm(action: unknown, render: (action: unknown) => string): string {
|
|
205
|
+
const act = resolveActionForForm(action)
|
|
206
|
+
if (act === undefined)
|
|
207
|
+
return `${render(action)}</form>`
|
|
208
|
+
const hidden = renderProtectFields(act.protect, act.url)
|
|
209
|
+
const fields = formFieldsOf(act)
|
|
210
|
+
const body = fields !== undefined ? runWithFormFields(fields, () => render(action)) : render(action)
|
|
211
|
+
return `${body}${hidden}</form>`
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/** Async variant of `ssrForm` for action-bound `<form>` elements containing `await`. */
|
|
215
|
+
export async function ssrFormAsync(action: unknown, render: (action: unknown) => Promise<string>): Promise<string> {
|
|
216
|
+
const act = resolveActionForForm(action)
|
|
217
|
+
if (act === undefined)
|
|
218
|
+
return `${await render(action)}</form>`
|
|
219
|
+
const hidden = renderProtectFields(act.protect, act.url)
|
|
220
|
+
const fields = formFieldsOf(act)
|
|
221
|
+
const body = fields !== undefined ? await runWithFormFields(fields, () => render(action)) : await render(action)
|
|
222
|
+
return `${body}${hidden}</form>`
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
/** Emits schema-derived HTML5 constraint attributes on `<input>`, `<select>`, and `<textarea>` inside an action-bound `<form>`. */
|
|
226
|
+
export function ssrFormAttrs(tag: 'input' | 'select' | 'textarea', name: unknown, present: number, inputType?: unknown): string {
|
|
227
|
+
const fields = currentFormFields()
|
|
228
|
+
if (fields === undefined || typeof name !== 'string' || name === '')
|
|
229
|
+
return ''
|
|
230
|
+
const c = lookupFieldConstraint(fields, name)
|
|
231
|
+
if (c === undefined)
|
|
232
|
+
return ''
|
|
233
|
+
|
|
234
|
+
let out = ''
|
|
235
|
+
const explicitType = typeof inputType === 'string' ? inputType.toLowerCase() : undefined
|
|
236
|
+
let effectiveType: string | undefined
|
|
237
|
+
if (tag === 'input') {
|
|
238
|
+
if (explicitType === undefined && (present & 1) === 0 && c.type !== undefined) {
|
|
239
|
+
out += ` type="${c.type}"`
|
|
240
|
+
effectiveType = c.type
|
|
241
|
+
}
|
|
242
|
+
else {
|
|
243
|
+
effectiveType = explicitType ?? 'text'
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
const skipRequired = tag === 'input' && (
|
|
248
|
+
NON_REQUIRED_INPUT_TYPES.has(effectiveType!)
|
|
249
|
+
|| (effectiveType === 'checkbox' && c.isArray === true)
|
|
250
|
+
)
|
|
251
|
+
if (c.required === true && (present & 2) === 0 && !skipRequired)
|
|
252
|
+
out += ' required'
|
|
253
|
+
|
|
254
|
+
const supportsLength = tag === 'textarea' || (tag === 'input' && TEXT_INPUT_TYPES.has(effectiveType!))
|
|
255
|
+
if (supportsLength) {
|
|
256
|
+
if (c.minLength !== undefined && (present & 4) === 0)
|
|
257
|
+
out += ` minlength="${c.minLength}"`
|
|
258
|
+
if (c.maxLength !== undefined && (present & 8) === 0)
|
|
259
|
+
out += ` maxlength="${c.maxLength}"`
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
if (tag === 'input') {
|
|
263
|
+
if (effectiveType === 'number' || effectiveType === 'range') {
|
|
264
|
+
if (c.min !== undefined && (present & 16) === 0)
|
|
265
|
+
out += ` min="${c.min}"`
|
|
266
|
+
if (c.max !== undefined && (present & 32) === 0)
|
|
267
|
+
out += ` max="${c.max}"`
|
|
268
|
+
if (c.step !== undefined && (present & 64) === 0)
|
|
269
|
+
out += ` step="${c.step}"`
|
|
270
|
+
}
|
|
271
|
+
if (TEXT_INPUT_TYPES.has(effectiveType!) && c.pattern !== undefined && (present & 128) === 0)
|
|
272
|
+
out += ` pattern="${escAttr(c.pattern)}"`
|
|
273
|
+
}
|
|
274
|
+
|
|
156
275
|
return out
|
|
157
276
|
}
|
|
158
277
|
|
package/src/ssr/region.ts
CHANGED
|
@@ -83,6 +83,7 @@ async function settleChunkWithin(
|
|
|
83
83
|
let timer: ReturnType<typeof setTimeout> | undefined
|
|
84
84
|
const timedOut = new Promise<SettledChunk>((resolve) => {
|
|
85
85
|
timer = setTimeout(() => {
|
|
86
|
+
chunk.discard?.()
|
|
86
87
|
const error = new Error(`<Suspense> boundary ${chunk.id} did not resolve within ${streamTimeout} ms`)
|
|
87
88
|
resolve({ html: runInScope(() => chunk.renderError(error)), error })
|
|
88
89
|
}, remaining)
|
|
@@ -98,8 +99,7 @@ async function settleChunkWithin(
|
|
|
98
99
|
async function awaitRegionDiscovery(
|
|
99
100
|
ctx: RenderContext,
|
|
100
101
|
deadline: number,
|
|
101
|
-
|
|
102
|
-
runInScope: <T>(fn: () => T) => T,
|
|
102
|
+
reportError: (id: number, error: unknown) => void,
|
|
103
103
|
): Promise<void> {
|
|
104
104
|
const watched = new Set<number>()
|
|
105
105
|
let pendingCount = 0
|
|
@@ -125,8 +125,8 @@ async function awaitRegionDiscovery(
|
|
|
125
125
|
pendingCount--
|
|
126
126
|
if (done)
|
|
127
127
|
return
|
|
128
|
-
if ('error' in settled
|
|
129
|
-
|
|
128
|
+
if ('error' in settled)
|
|
129
|
+
reportError(chunk.id, settled.error)
|
|
130
130
|
if (ctx.regionHtml !== undefined) {
|
|
131
131
|
finish()
|
|
132
132
|
return
|
|
@@ -150,22 +150,34 @@ export async function finishRegion(ctx: RenderContext, options?: FinishRegionOpt
|
|
|
150
150
|
const onError = options?.onError
|
|
151
151
|
const runInScope = options?.runInScope ?? (<T>(fn: () => T) => fn())
|
|
152
152
|
const deadline = Date.now() + streamTimeout
|
|
153
|
+
const reported = new Set<number>()
|
|
154
|
+
const reportError = (id: number, error: unknown): void => {
|
|
155
|
+
if (onError === undefined || reported.has(id))
|
|
156
|
+
return
|
|
157
|
+
reported.add(id)
|
|
158
|
+
runInScope(() => onError(error))
|
|
159
|
+
}
|
|
153
160
|
|
|
154
|
-
|
|
155
|
-
|
|
161
|
+
try {
|
|
162
|
+
if (ctx.regionHtml === undefined && ctx.pending.length > 0)
|
|
163
|
+
await awaitRegionDiscovery(ctx, deadline, reportError)
|
|
156
164
|
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
165
|
+
let html = ctx.regionHtml
|
|
166
|
+
if (html === undefined)
|
|
167
|
+
return undefined
|
|
168
|
+
for (let i = 0; i < ctx.pending.length; i++) {
|
|
169
|
+
const chunk = ctx.pending[i]!
|
|
170
|
+
const range = findPlaceholderRange(html, chunk.id)
|
|
171
|
+
if (range === undefined)
|
|
172
|
+
continue
|
|
173
|
+
const settled = await settleChunkWithin(chunk, deadline, streamTimeout, runInScope)
|
|
174
|
+
if ('error' in settled)
|
|
175
|
+
reportError(chunk.id, settled.error)
|
|
176
|
+
html = html.slice(0, range[0]) + settled.html + html.slice(range[1])
|
|
177
|
+
}
|
|
178
|
+
return html
|
|
179
|
+
}
|
|
180
|
+
finally {
|
|
181
|
+
ctx.aborted = true
|
|
169
182
|
}
|
|
170
|
-
return html
|
|
171
183
|
}
|
package/src/test/browser.ts
CHANGED
|
@@ -23,6 +23,8 @@ export interface BrowserPage {
|
|
|
23
23
|
/** Moves the pointer over the first element matching `selector`, as a visitor hovering a link does. */
|
|
24
24
|
hover(selector: string): Promise<void>
|
|
25
25
|
fill(selector: string, value: string): Promise<void>
|
|
26
|
+
/** Presses a key (`'Escape'`, `'ArrowRight'`, `'Tab'`) through the browser's keyboard input pipeline. */
|
|
27
|
+
press(key: string): Promise<void>
|
|
26
28
|
/** The text content of the first element matching `selector`. */
|
|
27
29
|
text(selector: string): Promise<string>
|
|
28
30
|
close(): Promise<void>
|
|
@@ -53,6 +55,7 @@ interface Page {
|
|
|
53
55
|
click(selector: string, options: { timeout: number }): Promise<void>
|
|
54
56
|
hover(selector: string, options: { timeout: number }): Promise<void>
|
|
55
57
|
fill(selector: string, value: string, options: { timeout: number }): Promise<void>
|
|
58
|
+
keyboard: { press(key: string): Promise<void> }
|
|
56
59
|
locator(selector: string): { first: () => { innerText: (options: { timeout: number }) => Promise<string> } }
|
|
57
60
|
}
|
|
58
61
|
interface BrowserContext {
|
|
@@ -126,6 +129,9 @@ function wrapPage(page: Page, context: BrowserContext, timeout: number, url: str
|
|
|
126
129
|
async fill(selector, value) {
|
|
127
130
|
await page.fill(selector, value, { timeout })
|
|
128
131
|
},
|
|
132
|
+
async press(key) {
|
|
133
|
+
await page.keyboard.press(key)
|
|
134
|
+
},
|
|
129
135
|
async text(selector) {
|
|
130
136
|
return await page.locator(selector).first().innerText({ timeout })
|
|
131
137
|
},
|