prunelle 0.0.0-stage → 0.7.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.
Files changed (222) hide show
  1. package/LICENSE +21 -0
  2. package/llms.txt +245 -0
  3. package/package.json +62 -4
  4. package/src/a11y/declaration.ts +373 -0
  5. package/src/a11y/index.ts +477 -0
  6. package/src/a11y/rgaa-map.ts +230 -0
  7. package/src/ambient.d.ts +6 -0
  8. package/src/attrs.ts +43 -0
  9. package/src/build/bundle.ts +661 -0
  10. package/src/build/byte-size.ts +11 -0
  11. package/src/build/carry.ts +57 -0
  12. package/src/build/client-entries.ts +107 -0
  13. package/src/build/client-plugin.ts +175 -0
  14. package/src/build/client-prune.ts +168 -0
  15. package/src/build/compile.ts +130 -0
  16. package/src/build/ecoindex.ts +238 -0
  17. package/src/build/files.ts +171 -0
  18. package/src/build/first-load.ts +235 -0
  19. package/src/build/graph.ts +237 -0
  20. package/src/build/index.ts +678 -0
  21. package/src/build/is-inside.ts +12 -0
  22. package/src/build/island-promote.ts +311 -0
  23. package/src/build/islands.ts +452 -0
  24. package/src/build/manifest.ts +204 -0
  25. package/src/build/output.ts +81 -0
  26. package/src/build/plugin-host.ts +294 -0
  27. package/src/build/precompress.ts +139 -0
  28. package/src/build/prerender.ts +288 -0
  29. package/src/build/reach.ts +200 -0
  30. package/src/build/render-rules.ts +205 -0
  31. package/src/build/report.ts +290 -0
  32. package/src/build/resolve.ts +52 -0
  33. package/src/build/routes.ts +342 -0
  34. package/src/build/server-entry.ts +38 -0
  35. package/src/build/static-headers.ts +112 -0
  36. package/src/build/static.ts +209 -0
  37. package/src/build/status-pages.ts +127 -0
  38. package/src/build/style-bundles.ts +526 -0
  39. package/src/cli/check-forms.ts +636 -0
  40. package/src/cli/check-imports.ts +31 -0
  41. package/src/cli/check-links.ts +632 -0
  42. package/src/cli/check-security.ts +64 -0
  43. package/src/cli/check.ts +409 -0
  44. package/src/cli/commands.ts +372 -0
  45. package/src/cli/docs.ts +403 -0
  46. package/src/cli/index.ts +70 -0
  47. package/src/cli/inspect.ts +406 -0
  48. package/src/cli/mcp-tools.ts +492 -0
  49. package/src/cli/mcp.ts +205 -0
  50. package/src/cli/new.ts +52 -0
  51. package/src/cli/render.ts +416 -0
  52. package/src/cli/upgrade-names.ts +209 -0
  53. package/src/cli/upgrade.ts +367 -0
  54. package/src/compiler/analyze.ts +651 -0
  55. package/src/compiler/ast.ts +82 -0
  56. package/src/compiler/browser-globals.ts +250 -0
  57. package/src/compiler/cacheability-private.ts +566 -0
  58. package/src/compiler/cacheability.ts +335 -0
  59. package/src/compiler/compliance-eco.ts +71 -0
  60. package/src/compiler/compliance-rgaa.ts +614 -0
  61. package/src/compiler/compliance-urls.ts +148 -0
  62. package/src/compiler/compliance.ts +653 -0
  63. package/src/compiler/data-keys.ts +302 -0
  64. package/src/compiler/dev-source.ts +87 -0
  65. package/src/compiler/dom-attrs.ts +452 -0
  66. package/src/compiler/dom.ts +641 -0
  67. package/src/compiler/emit.ts +131 -0
  68. package/src/compiler/expr-context.ts +587 -0
  69. package/src/compiler/foreign-imports.ts +88 -0
  70. package/src/compiler/index.ts +8 -0
  71. package/src/compiler/interactivity.ts +366 -0
  72. package/src/compiler/mistakes.ts +520 -0
  73. package/src/compiler/node-env.ts +50 -0
  74. package/src/compiler/patch.ts +97 -0
  75. package/src/compiler/props-body.ts +60 -0
  76. package/src/compiler/props.ts +511 -0
  77. package/src/compiler/scope.ts +635 -0
  78. package/src/compiler/server-only.ts +365 -0
  79. package/src/compiler/shared.ts +397 -0
  80. package/src/compiler/signal-reads.ts +246 -0
  81. package/src/compiler/slots.ts +227 -0
  82. package/src/compiler/spread-handlers.ts +295 -0
  83. package/src/compiler/ssr-helpers.ts +555 -0
  84. package/src/compiler/ssr-island.ts +90 -0
  85. package/src/compiler/ssr-prunelle-tags.ts +69 -0
  86. package/src/compiler/ssr.ts +525 -0
  87. package/src/context.ts +199 -0
  88. package/src/dev/child.ts +30 -0
  89. package/src/dev/error-log.ts +177 -0
  90. package/src/dev/host-check.ts +32 -0
  91. package/src/dev/index.ts +268 -0
  92. package/src/dev/modules.ts +68 -0
  93. package/src/dev/open-editor.ts +228 -0
  94. package/src/dev/protocol.ts +24 -0
  95. package/src/dev/queue.ts +79 -0
  96. package/src/dev/reload.ts +159 -0
  97. package/src/dev/supervisor.ts +212 -0
  98. package/src/dev/watchers.ts +276 -0
  99. package/src/dom/action.ts +187 -0
  100. package/src/dom/attrs.ts +84 -0
  101. package/src/dom/claim.ts +120 -0
  102. package/src/dom/extras.ts +579 -0
  103. package/src/dom/index.ts +329 -0
  104. package/src/dom/island.ts +318 -0
  105. package/src/dom/loop.ts +484 -0
  106. package/src/dom/revive.ts +36 -0
  107. package/src/eco/declaration.ts +328 -0
  108. package/src/eco/index.ts +69 -0
  109. package/src/index.ts +22 -0
  110. package/src/jsx-runtime.ts +566 -0
  111. package/src/plugins/config.ts +92 -0
  112. package/src/plugins/context.ts +109 -0
  113. package/src/plugins/index.ts +14 -0
  114. package/src/plugins/load.ts +90 -0
  115. package/src/plugins/order.ts +148 -0
  116. package/src/plugins/public.ts +15 -0
  117. package/src/plugins/requires.ts +47 -0
  118. package/src/plugins/services.ts +119 -0
  119. package/src/plugins/types.ts +278 -0
  120. package/src/reactivity/graph.ts +259 -0
  121. package/src/reactivity/index.ts +541 -0
  122. package/src/reactivity/selector.ts +78 -0
  123. package/src/reactivity/store.ts +252 -0
  124. package/src/server/action-flash.ts +158 -0
  125. package/src/server/action-protect.ts +199 -0
  126. package/src/server/action-registry.ts +78 -0
  127. package/src/server/action.ts +511 -0
  128. package/src/server/app-entry.ts +23 -0
  129. package/src/server/app-secret.ts +63 -0
  130. package/src/server/assets.ts +168 -0
  131. package/src/server/compress.ts +646 -0
  132. package/src/server/consent.ts +290 -0
  133. package/src/server/cookies.ts +153 -0
  134. package/src/server/document.ts +286 -0
  135. package/src/server/env.ts +47 -0
  136. package/src/server/errors.ts +396 -0
  137. package/src/server/form-schema.ts +337 -0
  138. package/src/server/health.ts +275 -0
  139. package/src/server/http.ts +588 -0
  140. package/src/server/index.ts +615 -0
  141. package/src/server/lifecycle.ts +75 -0
  142. package/src/server/loader.ts +131 -0
  143. package/src/server/page.ts +122 -0
  144. package/src/server/param-matchers.ts +112 -0
  145. package/src/server/plugin-host.ts +267 -0
  146. package/src/server/prerendered.ts +71 -0
  147. package/src/server/public.ts +20 -0
  148. package/src/server/rate-limit.ts +199 -0
  149. package/src/server/region.ts +96 -0
  150. package/src/server/request-body.ts +27 -0
  151. package/src/server/request-path.ts +73 -0
  152. package/src/server/request-scope.ts +22 -0
  153. package/src/server/route-cache.ts +541 -0
  154. package/src/server/route-table.ts +424 -0
  155. package/src/server/router.ts +261 -0
  156. package/src/server/routing.ts +388 -0
  157. package/src/server/sanitize-html.ts +309 -0
  158. package/src/server/security.ts +550 -0
  159. package/src/server/serve-handlers.ts +93 -0
  160. package/src/server/served-file.ts +128 -0
  161. package/src/server/standard-schema.ts +104 -0
  162. package/src/server/start.ts +143 -0
  163. package/src/server/static-dir.ts +246 -0
  164. package/src/server/stream.ts +233 -0
  165. package/src/ssr/consent-banner.ts +58 -0
  166. package/src/ssr/context.ts +399 -0
  167. package/src/ssr/index.ts +624 -0
  168. package/src/ssr/navigation.ts +96 -0
  169. package/src/ssr/region.ts +192 -0
  170. package/src/style.ts +96 -0
  171. package/src/test/browser.ts +201 -0
  172. package/src/test/index.ts +262 -0
  173. package/src/ts-plugin/diagnostics.ts +505 -0
  174. package/src/ts-plugin/fixes.ts +364 -0
  175. package/src/ts-plugin/index.ts +194 -0
  176. package/src/unrenderable.ts +35 -0
  177. package/templates/_shared/AGENTS.md +10 -0
  178. package/templates/_shared/CLAUDE.md +1 -0
  179. package/templates/_shared/gitignore +8 -0
  180. package/templates/_shared/mcp.json +11 -0
  181. package/templates/_shared/public/robots.txt +2 -0
  182. package/templates/_shared/src/routes/legal.tsx +22 -0
  183. package/templates/_shared/tsconfig.json +25 -0
  184. package/templates/app/.env.example +8 -0
  185. package/templates/app/package.json +22 -0
  186. package/templates/app/prunelle.config.ts +13 -0
  187. package/templates/app/src/auth.ts +12 -0
  188. package/templates/app/src/mail.ts +4 -0
  189. package/templates/app/src/routes/_layout.tsx +40 -0
  190. package/templates/app/src/routes/dashboard/_middleware.ts +3 -0
  191. package/templates/app/src/routes/dashboard/index.tsx +47 -0
  192. package/templates/app/src/routes/index.tsx +15 -0
  193. package/templates/app/src/routes/login.tsx +53 -0
  194. package/templates/app/src/routes/privacy.tsx +25 -0
  195. package/templates/app/src/styles/app.css +14 -0
  196. package/templates/app/tests/app.test.ts +73 -0
  197. package/templates/blog/content/posts/welcome.md +9 -0
  198. package/templates/blog/package.json +22 -0
  199. package/templates/blog/prunelle.config.ts +23 -0
  200. package/templates/blog/src/posts.ts +26 -0
  201. package/templates/blog/src/routes/_layout.tsx +25 -0
  202. package/templates/blog/src/routes/blog/[slug].tsx +31 -0
  203. package/templates/blog/src/routes/index.tsx +33 -0
  204. package/templates/blog/src/styles/app.css +15 -0
  205. package/templates/fullstack/package.json +19 -0
  206. package/templates/fullstack/prunelle.config.ts +6 -0
  207. package/templates/fullstack/src/actions/greet.ts +19 -0
  208. package/templates/fullstack/src/components/Counter.tsx +10 -0
  209. package/templates/fullstack/src/components/GreetForm.tsx +28 -0
  210. package/templates/fullstack/src/routes/_layout.tsx +18 -0
  211. package/templates/fullstack/src/routes/api/health.ts +5 -0
  212. package/templates/fullstack/src/routes/index.tsx +13 -0
  213. package/templates/fullstack/src/styles/app.css +39 -0
  214. package/templates/fullstack/tests/app.test.ts +37 -0
  215. package/templates/minimal/package.json +19 -0
  216. package/templates/minimal/prunelle.config.ts +6 -0
  217. package/templates/minimal/src/components/Counter.tsx +10 -0
  218. package/templates/minimal/src/routes/_layout.tsx +18 -0
  219. package/templates/minimal/src/routes/index.tsx +11 -0
  220. package/templates/minimal/src/styles/app.css +32 -0
  221. package/ts-plugin.cjs +4277 -0
  222. package/README.md +0 -3
@@ -0,0 +1,75 @@
1
+ // Graceful stop for `prunelle start` and compiled binaries; `prunelle dev` keeps its own.
2
+
3
+ import type { PrunelleApp } from './http'
4
+
5
+ const SIGNALS = ['SIGTERM', 'SIGINT', 'SIGHUP'] as const
6
+
7
+ export interface HandleSignalsOptions {
8
+ timeoutMs?: number | undefined
9
+ /** @internal Exit callback (defaults to `process.exit`). */
10
+ exit?: ((code: number) => void) | undefined
11
+ }
12
+
13
+ // On the first signal the server stops taking connections, ends long-lived streams, waits for open requests to drain, then runs onShutdown hooks; exits 0 when done, or 1 after `timeoutMs`.
14
+ export function handleSignals(
15
+ app: PrunelleApp,
16
+ server: ReturnType<PrunelleApp['serve']>,
17
+ { timeoutMs = 10_000, exit = (code: number) => process.exit(code) }: HandleSignalsOptions = {},
18
+ ): () => void {
19
+ let stopping = false
20
+ const listeners: [typeof SIGNALS[number], () => void][] = []
21
+
22
+ const stop = async (): Promise<void> => {
23
+ if (stopping)
24
+ return
25
+ stopping = true
26
+ let timedOut = false
27
+ const forced = setTimeout(() => {
28
+ timedOut = true
29
+ console.error(`prunelle: requests still open after ${timeoutMs} ms; closing them`)
30
+ exit(1)
31
+ }, timeoutMs)
32
+ let exitCode = 0
33
+ try {
34
+ const drained = server.stop()
35
+ try {
36
+ await app.closeStreams?.()
37
+ }
38
+ catch (error) {
39
+ exitCode = 1
40
+ console.error('prunelle: error closing streams during shutdown:', error)
41
+ }
42
+ await drained
43
+ }
44
+ catch (error) {
45
+ exitCode = 1
46
+ console.error('prunelle: error draining server during shutdown:', error)
47
+ }
48
+ finally {
49
+ try {
50
+ await app.dispose?.()
51
+ }
52
+ catch (error) {
53
+ exitCode = 1
54
+ console.error('prunelle: error disposing app during shutdown:', error)
55
+ }
56
+ clearTimeout(forced)
57
+ }
58
+ if (!timedOut)
59
+ exit(exitCode)
60
+ }
61
+
62
+ for (const signal of SIGNALS) {
63
+ const listener = () => {
64
+ void stop()
65
+ }
66
+ listeners.push([signal, listener])
67
+ process.on(signal, listener)
68
+ }
69
+
70
+ return () => {
71
+ for (const [signal, listener] of listeners)
72
+ process.off(signal, listener)
73
+ listeners.length = 0
74
+ }
75
+ }
@@ -0,0 +1,131 @@
1
+ // Filesystem server loader: reads `dist/manifest.json`, maps the built assets on disk, and starts the app from `dist/server/_entry.js` (or serves a `--static` dir).
2
+
3
+ import type { BuildManifest } from '../build/index'
4
+ import type { ServerEntry } from './app-entry'
5
+ import type { EmbeddedBody, PrunelleApp, ServerOptions } from './http'
6
+ import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'
7
+ import { join, resolve } from 'node:path'
8
+ import { SERVER_ENTRY_FILE } from '../build/server-entry'
9
+ import { loadConfig, resolveServerConfig } from '../plugins/index'
10
+ import { devFromEnv } from './env'
11
+ import { createStaticDirServer } from './static-dir'
12
+
13
+ let serverLoadSeq = 0
14
+
15
+ export async function createServer(options: ServerOptions): Promise<PrunelleApp> {
16
+ return (await startBuiltApp(options)).app
17
+ }
18
+
19
+ /** The app, the folder it was built into, and the entry it was assembled from, whose bundled modules `testApp().import()` and the prerender step read. */
20
+ export async function startBuiltApp(options: ServerOptions): Promise<{ app: PrunelleApp, outDir: string, entry?: ServerEntry | undefined }> {
21
+ const built = await loadServerEntry(options)
22
+ if (built.entry === undefined)
23
+ return { app: await serveStaticDir(options, built.root, built.outDir), outDir: built.outDir }
24
+ const { root, outDir, manifest, entry } = built
25
+ const clientDir = join(outDir, 'client')
26
+ const assets: Record<string, EmbeddedBody> = {}
27
+ const publicAssets: Record<string, EmbeddedBody> = {}
28
+ const publicEtags: Record<string, string> = {}
29
+ const prerenderedFiles: Record<string, string> = {}
30
+ const srcPublicDir = resolve(root, entry.prunelleConfig.publicDir ?? 'public')
31
+
32
+ // File paths only: Bun.file() serves them zero-copy, and nothing is read at startup.
33
+ const withSidecars = (files: Record<string, EmbeddedBody>, rel: string, abs: string): void => {
34
+ files[rel] = abs
35
+ for (const ext of ['.br', '.gz']) {
36
+ if (existsSync(`${abs}${ext}`))
37
+ files[`${rel}${ext}`] = `${abs}${ext}`
38
+ }
39
+ }
40
+ for (const rel of [...manifest.assets, ...(manifest.carriedAssets ?? [])]) {
41
+ const abs = join(clientDir, rel)
42
+ if (existsSync(abs))
43
+ withSidecars(assets, rel, abs)
44
+ }
45
+
46
+ for (const rel of manifest.publicFiles ?? []) {
47
+ const outAbs = join(outDir, 'public', rel)
48
+ const abs = existsSync(outAbs) ? outAbs : join(srcPublicDir, rel)
49
+ if (existsSync(abs)) {
50
+ withSidecars(publicAssets, rel, abs)
51
+ const st = statSync(abs)
52
+ publicEtags[rel] = `W/"${st.size.toString(36)}-${Math.floor(st.mtimeMs).toString(36)}"`
53
+ }
54
+ }
55
+
56
+ for (const r of manifest.routes) {
57
+ for (const relHtml of Object.values(r.prerendered ?? {})) {
58
+ const abs = join(outDir, relHtml)
59
+ if (existsSync(abs))
60
+ withSidecars(prerenderedFiles, relHtml, abs)
61
+ }
62
+ }
63
+
64
+ const app = await entry.createApp({
65
+ ...resolveServerConfig(undefined, options),
66
+ manifest,
67
+ assets,
68
+ publicAssets,
69
+ publicEtags,
70
+ prerenderedFiles,
71
+ root,
72
+ outDir,
73
+ publicDir: join(outDir, 'public'),
74
+ dev: options.dev ?? devFromEnv(),
75
+ devHost: options.devHost,
76
+ nodeEnv: options.nodeEnv,
77
+ errorSink: options.errorSink,
78
+ prerender: options.prerender,
79
+ static: options.static,
80
+ })
81
+ return { app, outDir, entry }
82
+ }
83
+
84
+ type BuiltOutput =
85
+ | { root: string, outDir: string, manifest: BuildManifest, entry: ServerEntry }
86
+ | { root: string, outDir: string, entry?: undefined }
87
+
88
+ /** Finds the build output and imports its server entry; a `--static` export has none. */
89
+ async function loadServerEntry(options: ServerOptions): Promise<BuiltOutput> {
90
+ const root = resolve(options.root)
91
+ let outDir = resolve(root, options.outDir ?? 'dist')
92
+ // prunelle.config.ts is read natively only to find an `outDir` it moved; the app itself runs from its bundled copy.
93
+ if (options.outDir === undefined && !existsSync(join(outDir, 'manifest.json')))
94
+ outDir = resolve(root, (await loadConfig(root, { dev: options.dev, nodeEnv: options.nodeEnv })).outDir ?? 'dist')
95
+ const manifestPath = join(outDir, 'manifest.json')
96
+ if (!existsSync(manifestPath)) {
97
+ if (existsSync(outDir) && readdirSync(outDir).length > 0)
98
+ return { root, outDir }
99
+ throw new Error(`prunelle server: missing ${manifestPath}. Run build() first.`)
100
+ }
101
+ const manifest = JSON.parse(readFileSync(manifestPath, 'utf8')) as BuildManifest
102
+ const entryPath = join(outDir, 'server', SERVER_ENTRY_FILE)
103
+ if (!existsSync(entryPath))
104
+ throw new Error(`prunelle server: missing ${entryPath}, the server entry prunelle build writes. Run prunelle build again.`)
105
+ const stamp = `${Date.now()}-${++serverLoadSeq}`
106
+ const importModule = options.importModule ?? ((path: string) => import(`${path}?v=${stamp}`))
107
+ const entry = await importModule(entryPath) as unknown as ServerEntry
108
+ return { root, outDir, manifest, entry }
109
+ }
110
+
111
+ async function serveStaticDir(options: ServerOptions, root: string, outDir: string): Promise<PrunelleApp> {
112
+ const config = await loadConfig(root, { dev: options.dev, nodeEnv: options.nodeEnv })
113
+ const site = (options.site ?? config.site)?.replace(/\/$/, '') || undefined
114
+ const isDev = options.dev ?? devFromEnv()
115
+ return createStaticDirServer(
116
+ outDir,
117
+ options.assetPrefix ?? config.assetPrefix ?? '/_pru',
118
+ options.security ?? config.security,
119
+ (options.compress ?? config.compress) !== false,
120
+ options.trustProxy ?? config.trustProxy ?? false,
121
+ isDev,
122
+ {
123
+ navigation: options.navigation ?? config.navigation,
124
+ plugins: options.plugins ?? config.plugins,
125
+ onError: options.onError ?? config.onError,
126
+ errorSink: options.errorSink,
127
+ httpsSite: !isDev && site?.startsWith('https://') === true,
128
+ nodeEnv: options.nodeEnv,
129
+ },
130
+ )
131
+ }
@@ -0,0 +1,122 @@
1
+ // What a route file is to the server: the page, layout and middleware modules it loads, and the answers derived from their exports.
2
+
3
+ import type { BuildManifest, RouteManifestEntry } from '../build/index'
4
+ import type { Html } from '../jsx-runtime'
5
+ import type { Middleware, RequestContext } from './http'
6
+ import type { PrunelleLocals } from './index'
7
+ import { existsSync } from 'node:fs'
8
+ import { join } from 'node:path'
9
+
10
+ export interface LoadedPageModule {
11
+ default?: (props: Record<string, unknown>) => Html | string | Promise<Html | string>
12
+ load?: (ctx: RequestContext) => unknown | Promise<unknown>
13
+ clientData?: readonly string[] | ((data: unknown) => unknown) | undefined
14
+ csrf?: boolean | undefined
15
+ GET?: (ctx: RequestContext) => Response | Promise<Response>
16
+ POST?: (ctx: RequestContext) => Response | Promise<Response>
17
+ PUT?: (ctx: RequestContext) => Response | Promise<Response>
18
+ PATCH?: (ctx: RequestContext) => Response | Promise<Response>
19
+ DELETE?: (ctx: RequestContext) => Response | Promise<Response>
20
+ HEAD?: (ctx: RequestContext) => Response | Promise<Response>
21
+ OPTIONS?: (ctx: RequestContext) => Response | Promise<Response>
22
+ [key: string]: unknown
23
+ }
24
+
25
+ export interface LoadedLayoutModule {
26
+ default: (props: { children: Html, url?: URL, params?: Record<string, string>, locals?: PrunelleLocals }) => Html | string | Promise<Html | string>
27
+ }
28
+
29
+ export interface LoadedMiddlewareModule {
30
+ default: Middleware
31
+ }
32
+
33
+ const HTTP_METHOD_EXPORTS = ['GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'] as const
34
+
35
+ export function mergedHeadTags(manifest: BuildManifest, entry: RouteManifestEntry): string[] | undefined {
36
+ return entry.headTags !== undefined && entry.headTags.length > 0
37
+ ? [...(manifest.headTags ?? []), ...entry.headTags]
38
+ : manifest.headTags
39
+ }
40
+
41
+ /** Whether the app ships a `/favicon.ico` in `public/` (or via `emitPublic`), so SSR should not inject an empty `data:,` icon. */
42
+ export function hasPublicFavicon(
43
+ manifest: BuildManifest,
44
+ publicMap?: ReadonlyMap<string, unknown>,
45
+ publicDir?: string,
46
+ ): boolean {
47
+ if (publicMap?.has('/favicon.ico'))
48
+ return true
49
+ if (manifest.publicFiles?.some(f => f === 'favicon.ico' || f === '/favicon.ico'))
50
+ return true
51
+ return publicDir !== undefined && existsSync(join(publicDir, 'favicon.ico'))
52
+ }
53
+
54
+ export function allowedMethodsHeader(mod: LoadedPageModule): string {
55
+ const allowed = new Set<string>()
56
+ if (typeof mod.default === 'function') {
57
+ allowed.add('GET')
58
+ allowed.add('HEAD')
59
+ }
60
+ for (const m of HTTP_METHOD_EXPORTS) {
61
+ if (typeof mod[m] === 'function')
62
+ allowed.add(m)
63
+ }
64
+ if (allowed.has('GET'))
65
+ allowed.add('HEAD')
66
+ return [...allowed].join(', ')
67
+ }
68
+
69
+ async function cancelBodyQuietly(body: ReadableStream<Uint8Array>): Promise<void> {
70
+ try {
71
+ await body.cancel()
72
+ }
73
+ catch {}
74
+ }
75
+
76
+ export function stripHeadBody(res: Response): Response {
77
+ if (res.body !== null)
78
+ void cancelBodyQuietly(res.body)
79
+ return new Response(null, { status: res.status, statusText: res.statusText, headers: res.headers })
80
+ }
81
+
82
+ export function isPlainObject(v: unknown): v is Record<string, unknown> {
83
+ return typeof v === 'object' && v !== null && !Array.isArray(v)
84
+ }
85
+
86
+ function pickObjectKeys(obj: Record<string, unknown>, keys: readonly string[]): Record<string, unknown> | undefined {
87
+ if (keys.length === 0)
88
+ return undefined
89
+ const picked: Record<string, unknown> = {}
90
+ let count = 0
91
+ for (const k of keys) {
92
+ if (Object.hasOwn(obj, k)) {
93
+ Object.defineProperty(picked, k, { value: obj[k], enumerable: true, writable: true, configurable: true })
94
+ count++
95
+ }
96
+ }
97
+ return count > 0 ? picked : undefined
98
+ }
99
+
100
+ export function pickPageIslandProps(data: unknown, entry: RouteManifestEntry, mod: LoadedPageModule): Record<string, unknown> {
101
+ if (data === undefined)
102
+ return {}
103
+ if (typeof mod.clientData === 'function') {
104
+ const subset = mod.clientData(data)
105
+ return subset === undefined ? {} : { data: subset }
106
+ }
107
+ if (Array.isArray(mod.clientData)) {
108
+ if (!isPlainObject(data))
109
+ return {}
110
+ const subset = pickObjectKeys(data, mod.clientData)
111
+ return subset === undefined ? {} : { data: subset }
112
+ }
113
+ if (entry.islandDataKeys !== undefined) {
114
+ if (entry.islandDataKeys.length === 0)
115
+ return {}
116
+ if (isPlainObject(data)) {
117
+ const subset = pickObjectKeys(data, entry.islandDataKeys)
118
+ return subset === undefined ? {} : { data: subset }
119
+ }
120
+ }
121
+ return { data }
122
+ }
@@ -0,0 +1,112 @@
1
+ // Route parameter matchers (built-in `integer`, `uuid`, `slug` and app-defined `src/params/<name>.ts`) and shared route-pattern segment parsing.
2
+
3
+ export type ParamMatcher = (value: string) => boolean
4
+ export type ParamMatcherMap = Readonly<Record<string, ParamMatcher>>
5
+
6
+ const INTEGER_RE = /^\d+$/
7
+ const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
8
+ const SLUG_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/
9
+
10
+ export const BUILTIN_PARAM_MATCHERS: ParamMatcherMap = {
11
+ integer: value => INTEGER_RE.test(value),
12
+ uuid: value => UUID_RE.test(value),
13
+ slug: value => SLUG_RE.test(value),
14
+ }
15
+
16
+ export const BUILTIN_PARAM_MATCHER_NAMES = ['integer', 'uuid', 'slug'] as const
17
+
18
+ export function isBuiltinMatcher(name: string): boolean {
19
+ return Object.hasOwn(BUILTIN_PARAM_MATCHERS, name)
20
+ }
21
+
22
+ /** Extracts a matcher function from an app param matcher module (`export function match` or `export default`). */
23
+ export function extractMatcherFn(mod: unknown): ParamMatcher | undefined {
24
+ if (typeof mod === 'function')
25
+ return mod as ParamMatcher
26
+ if (mod !== null && typeof mod === 'object') {
27
+ const rec = mod as Record<string, unknown>
28
+ if (typeof rec.match === 'function')
29
+ return rec.match as ParamMatcher
30
+ if (typeof rec.default === 'function')
31
+ return rec.default as ParamMatcher
32
+ }
33
+ return undefined
34
+ }
35
+
36
+ /** Merges built-in matchers with app matchers listed in the build manifest. */
37
+ export function resolveParamMatchers(
38
+ manifestMatchers: Readonly<Record<string, string>> | undefined,
39
+ modules: Readonly<Record<string, unknown>>,
40
+ ): ParamMatcherMap {
41
+ if (manifestMatchers === undefined)
42
+ return BUILTIN_PARAM_MATCHERS
43
+ const merged: Record<string, ParamMatcher> = { ...BUILTIN_PARAM_MATCHERS }
44
+ for (const [name, modKey] of Object.entries(manifestMatchers)) {
45
+ const fn = extractMatcherFn(modules[modKey])
46
+ if (fn !== undefined)
47
+ merged[name] = fn
48
+ }
49
+ return merged
50
+ }
51
+
52
+ export interface ParsedPatternSegment {
53
+ kind: 'static' | 'param' | 'optional' | 'catchall'
54
+ /** Exact literal for static, parameter name for param/optional/catchall. */
55
+ value: string
56
+ matcherName?: string | undefined
57
+ }
58
+
59
+ function splitNameAndMatcher(spec: string, fallbackName?: string): { name: string, matcherName?: string | undefined } {
60
+ const eq = spec.indexOf('=')
61
+ if (eq === -1)
62
+ return { name: spec || fallbackName || '' }
63
+ const name = spec.slice(0, eq) || fallbackName || ''
64
+ const matcherName = spec.slice(eq + 1)
65
+ return matcherName.length > 0 ? { name, matcherName } : { name }
66
+ }
67
+
68
+ /** Parses one segment of a compiled route pattern (`about`, `:id`, `:id=integer`, `:lang?`, `:page=integer?`, `*rest`, `*path=slug`). */
69
+ export function parsePatternSegment(seg: string): ParsedPatternSegment {
70
+ if (seg.startsWith('*')) {
71
+ const { name, matcherName } = splitNameAndMatcher(seg.slice(1), 'rest')
72
+ return { kind: 'catchall', value: name, matcherName }
73
+ }
74
+ if (seg.startsWith(':')) {
75
+ const body = seg.slice(1)
76
+ const optional = body.endsWith('?')
77
+ const spec = optional ? body.slice(0, -1) : body
78
+ const { name, matcherName } = splitNameAndMatcher(spec)
79
+ return { kind: optional ? 'optional' : 'param', value: name, matcherName }
80
+ }
81
+ return { kind: 'static', value: seg }
82
+ }
83
+
84
+ /** Lists every param matcher reference in a compiled route pattern (e.g. `'/users/:id=integer'` -> `[{ param: 'id', matcher: 'integer' }]`). */
85
+ export function extractPatternMatchers(routePath: string): { param: string, matcher: string }[] {
86
+ const result: { param: string, matcher: string }[] = []
87
+ if (!routePath.includes('='))
88
+ return result
89
+ for (const seg of routePath.split('/')) {
90
+ if (seg === '')
91
+ continue
92
+ const parsed = parsePatternSegment(seg)
93
+ if (parsed.matcherName !== undefined)
94
+ result.push({ param: parsed.value, matcher: parsed.matcherName })
95
+ }
96
+ return result
97
+ }
98
+
99
+ /** Lists optional parameter names in a compiled route pattern (e.g. `'/:lang?/about'` -> `['lang']`). */
100
+ export function extractOptionalParams(routePath: string): string[] {
101
+ const result: string[] = []
102
+ if (!routePath.includes('?'))
103
+ return result
104
+ for (const seg of routePath.split('/')) {
105
+ if (seg === '')
106
+ continue
107
+ const parsed = parsePatternSegment(seg)
108
+ if (parsed.kind === 'optional')
109
+ result.push(parsed.value)
110
+ }
111
+ return result
112
+ }