prunelle 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/llms.txt +148 -0
- package/package.json +53 -4
- package/src/ambient.d.ts +6 -0
- package/src/attrs.ts +35 -0
- package/src/build/bundle.ts +613 -0
- package/src/build/carry.ts +57 -0
- package/src/build/client-entries.ts +107 -0
- package/src/build/client-plugin.ts +169 -0
- package/src/build/client-prune.ts +118 -0
- package/src/build/compile.ts +128 -0
- package/src/build/files.ts +156 -0
- package/src/build/first-load.ts +164 -0
- package/src/build/graph.ts +247 -0
- package/src/build/index.ts +614 -0
- package/src/build/is-inside.ts +12 -0
- package/src/build/islands.ts +641 -0
- package/src/build/manifest.ts +281 -0
- package/src/build/output.ts +84 -0
- package/src/build/plugin-host.ts +220 -0
- package/src/build/precompress.ts +139 -0
- package/src/build/prerender.ts +150 -0
- package/src/build/render-rules.ts +205 -0
- package/src/build/report.ts +247 -0
- package/src/build/resolve.ts +50 -0
- package/src/build/routes.ts +338 -0
- package/src/build/server-entry.ts +38 -0
- package/src/build/static.ts +163 -0
- package/src/build/status-pages.ts +127 -0
- package/src/cli/check-forms.ts +654 -0
- package/src/cli/check-links.ts +619 -0
- package/src/cli/check.ts +367 -0
- package/src/cli/commands.ts +265 -0
- package/src/cli/index.ts +70 -0
- package/src/cli/inspect.ts +335 -0
- package/src/cli/new.ts +41 -0
- package/src/cli/upgrade-names.ts +209 -0
- package/src/cli/upgrade.ts +354 -0
- package/src/compiler/analyze.ts +618 -0
- package/src/compiler/ast.ts +82 -0
- package/src/compiler/browser-globals.ts +127 -0
- package/src/compiler/compliance-rgaa.ts +502 -0
- package/src/compiler/compliance.ts +497 -0
- package/src/compiler/data-keys.ts +295 -0
- package/src/compiler/dom-attrs.ts +379 -0
- package/src/compiler/dom.ts +566 -0
- package/src/compiler/emit.ts +131 -0
- package/src/compiler/expr-context.ts +408 -0
- package/src/compiler/index.ts +8 -0
- package/src/compiler/interactivity.ts +366 -0
- package/src/compiler/mistakes.ts +499 -0
- package/src/compiler/node-env.ts +50 -0
- package/src/compiler/patch.ts +97 -0
- package/src/compiler/props.ts +460 -0
- package/src/compiler/scope.ts +568 -0
- package/src/compiler/server-only.ts +326 -0
- package/src/compiler/shared.ts +369 -0
- package/src/compiler/signal-reads.ts +242 -0
- package/src/compiler/slots.ts +227 -0
- package/src/compiler/ssr-helpers.ts +555 -0
- package/src/compiler/ssr-island.ts +90 -0
- package/src/compiler/ssr-prunelle-tags.ts +56 -0
- package/src/compiler/ssr.ts +491 -0
- package/src/context.ts +165 -0
- package/src/dev/child.ts +30 -0
- package/src/dev/index.ts +208 -0
- package/src/dev/modules.ts +68 -0
- package/src/dev/protocol.ts +21 -0
- package/src/dev/queue.ts +79 -0
- package/src/dev/reload.ts +157 -0
- package/src/dev/supervisor.ts +187 -0
- package/src/dev/watchers.ts +215 -0
- package/src/dom/action.ts +164 -0
- package/src/dom/attrs.ts +72 -0
- package/src/dom/claim.ts +120 -0
- package/src/dom/extras.ts +562 -0
- package/src/dom/index.ts +289 -0
- package/src/dom/island.ts +284 -0
- package/src/dom/loop.ts +450 -0
- package/src/dom/revive.ts +36 -0
- package/src/index.ts +22 -0
- package/src/jsx-runtime.ts +566 -0
- package/src/plugins/config.ts +86 -0
- package/src/plugins/context.ts +66 -0
- package/src/plugins/index.ts +14 -0
- package/src/plugins/load.ts +70 -0
- package/src/plugins/order.ts +111 -0
- package/src/plugins/public.ts +12 -0
- package/src/plugins/requires.ts +47 -0
- package/src/plugins/services.ts +35 -0
- package/src/plugins/types.ts +242 -0
- package/src/reactivity/graph.ts +249 -0
- package/src/reactivity/index.ts +533 -0
- package/src/reactivity/selector.ts +51 -0
- package/src/reactivity/store.ts +208 -0
- package/src/server/action-protect.ts +186 -0
- package/src/server/action-registry.ts +78 -0
- package/src/server/action.ts +498 -0
- package/src/server/app-entry.ts +23 -0
- package/src/server/assets.ts +136 -0
- package/src/server/compress.ts +560 -0
- package/src/server/consent.ts +253 -0
- package/src/server/cookies.ts +139 -0
- package/src/server/document.ts +271 -0
- package/src/server/env.ts +33 -0
- package/src/server/errors.ts +382 -0
- package/src/server/form-schema.ts +343 -0
- package/src/server/health.ts +244 -0
- package/src/server/http.ts +508 -0
- package/src/server/index.ts +687 -0
- package/src/server/lifecycle.ts +75 -0
- package/src/server/loader.ts +118 -0
- package/src/server/page.ts +107 -0
- package/src/server/param-matchers.ts +112 -0
- package/src/server/plugin-host.ts +256 -0
- package/src/server/prerendered.ts +71 -0
- package/src/server/public.ts +19 -0
- package/src/server/rate-limit.ts +133 -0
- package/src/server/region.ts +96 -0
- package/src/server/request-body.ts +27 -0
- package/src/server/request-path.ts +73 -0
- package/src/server/request-scope.ts +22 -0
- package/src/server/route-table.ts +82 -0
- package/src/server/router.ts +261 -0
- package/src/server/routing.ts +377 -0
- package/src/server/security.ts +472 -0
- package/src/server/serve-handlers.ts +83 -0
- package/src/server/served-file.ts +128 -0
- package/src/server/standard-schema.ts +87 -0
- package/src/server/start.ts +99 -0
- package/src/server/static-dir.ts +167 -0
- package/src/server/stream.ts +192 -0
- package/src/ssr/context.ts +350 -0
- package/src/ssr/index.ts +596 -0
- package/src/ssr/navigation.ts +96 -0
- package/src/ssr/region.ts +171 -0
- package/src/style.ts +33 -0
- package/src/test/browser.ts +192 -0
- package/src/test/index.ts +191 -0
- package/src/unrenderable.ts +35 -0
- package/templates/_shared/AGENTS.md +10 -0
- package/templates/_shared/CLAUDE.md +1 -0
- package/templates/_shared/gitignore +3 -0
- package/templates/_shared/public/robots.txt +2 -0
- package/templates/_shared/src/routes/legal.tsx +13 -0
- package/templates/_shared/tsconfig.json +20 -0
- package/templates/app/.env.example +4 -0
- package/templates/app/package.json +21 -0
- package/templates/app/prunelle.config.ts +11 -0
- package/templates/app/src/auth.ts +14 -0
- package/templates/app/src/routes/_layout.tsx +32 -0
- package/templates/app/src/routes/dashboard/_middleware.ts +3 -0
- package/templates/app/src/routes/dashboard/index.tsx +13 -0
- package/templates/app/src/routes/index.tsx +15 -0
- package/templates/app/src/routes/login.tsx +34 -0
- package/templates/app/src/styles/app.css +7 -0
- package/templates/app/tests/app.test.ts +32 -0
- package/templates/blog/content/posts/welcome.md +9 -0
- package/templates/blog/package.json +22 -0
- package/templates/blog/prunelle.config.ts +23 -0
- package/templates/blog/src/posts.ts +26 -0
- package/templates/blog/src/routes/_layout.tsx +20 -0
- package/templates/blog/src/routes/blog/[slug].tsx +31 -0
- package/templates/blog/src/routes/index.tsx +33 -0
- package/templates/blog/src/styles/app.css +10 -0
- package/templates/fullstack/package.json +19 -0
- package/templates/fullstack/prunelle.config.ts +6 -0
- package/templates/fullstack/src/actions/greet.ts +19 -0
- package/templates/fullstack/src/components/Counter.tsx +10 -0
- package/templates/fullstack/src/components/GreetForm.tsx +27 -0
- package/templates/fullstack/src/routes/_layout.tsx +14 -0
- package/templates/fullstack/src/routes/api/health.ts +5 -0
- package/templates/fullstack/src/routes/index.tsx +13 -0
- package/templates/fullstack/src/styles/app.css +29 -0
- package/templates/fullstack/tests/app.test.ts +37 -0
- package/templates/minimal/package.json +19 -0
- package/templates/minimal/prunelle.config.ts +6 -0
- package/templates/minimal/src/components/Counter.tsx +10 -0
- package/templates/minimal/src/routes/_layout.tsx +14 -0
- package/templates/minimal/src/routes/index.tsx +11 -0
- package/templates/minimal/src/styles/app.css +22 -0
- package/README.md +0 -3
|
@@ -0,0 +1,253 @@
|
|
|
1
|
+
// CNIL/RGPD one-declaration consent: cookie parsing/serialization, RequestConsent view, and zero-JS POST /_pru/consent endpoint.
|
|
2
|
+
|
|
3
|
+
import type { PluginRouteOptions } from '../plugins/types'
|
|
4
|
+
import type { RequestContext } from './http'
|
|
5
|
+
import type { TrustProxy } from './security'
|
|
6
|
+
import { wantsJson } from './http'
|
|
7
|
+
import { isTrustedOrigin, safeRedirect } from './security'
|
|
8
|
+
|
|
9
|
+
export const DEFAULT_CONSENT_COOKIE = 'pru_consent'
|
|
10
|
+
/** 180 days in seconds (CNIL 6-month guideline for consent retention). */
|
|
11
|
+
export const DEFAULT_CONSENT_MAX_AGE = 15_552_000
|
|
12
|
+
export const DEFAULT_CONSENT_ENDPOINT = '/_pru/consent'
|
|
13
|
+
const COOKIE_VERSION_PREFIX = 'v1:'
|
|
14
|
+
|
|
15
|
+
export interface ConsentConfig {
|
|
16
|
+
/** Non-essential consent categories (e.g. `['analytics', 'media']` or `{ analytics: 'Audience measurement' }`). */
|
|
17
|
+
categories: readonly string[] | Readonly<Record<string, string>>
|
|
18
|
+
/** Cookie name storing consent choices (default: `'pru_consent'`). */
|
|
19
|
+
cookieName?: string | undefined
|
|
20
|
+
/** Max-Age in seconds (default: `15552000` = 180 days, CNIL 6-month guideline). */
|
|
21
|
+
maxAge?: number | undefined
|
|
22
|
+
/** POST endpoint path handling consent form submissions (default: `'/_pru/consent'`). */
|
|
23
|
+
endpoint?: string | undefined
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export interface RequestConsent {
|
|
27
|
+
readonly decided: boolean
|
|
28
|
+
readonly categories: readonly string[]
|
|
29
|
+
has(category: string): boolean
|
|
30
|
+
all(): Record<string, boolean>
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export interface NormalizedConsentConfig {
|
|
34
|
+
readonly categories: readonly string[]
|
|
35
|
+
readonly categorySet: ReadonlySet<string>
|
|
36
|
+
readonly cookieName: string
|
|
37
|
+
readonly maxAge: number
|
|
38
|
+
readonly endpoint: string
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
const EMPTY_CONSENT: RequestConsent = {
|
|
42
|
+
decided: false,
|
|
43
|
+
categories: [],
|
|
44
|
+
has: category => category === 'essential',
|
|
45
|
+
all: () => ({}),
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export function normalizeConsentConfig(config: ConsentConfig | undefined): NormalizedConsentConfig | undefined {
|
|
49
|
+
if (config === undefined)
|
|
50
|
+
return undefined
|
|
51
|
+
const rawList = Array.isArray(config.categories) ? config.categories : Object.keys(config.categories)
|
|
52
|
+
const categories: string[] = []
|
|
53
|
+
const categorySet = new Set<string>()
|
|
54
|
+
for (const item of rawList) {
|
|
55
|
+
const name = item.trim()
|
|
56
|
+
if (name === '' || name === 'essential' || categorySet.has(name))
|
|
57
|
+
continue
|
|
58
|
+
if (name.includes(',') || name.includes(':'))
|
|
59
|
+
throw new Error(`prunelle: consent category "${name}" cannot contain "," or ":"`)
|
|
60
|
+
categorySet.add(name)
|
|
61
|
+
categories.push(name)
|
|
62
|
+
}
|
|
63
|
+
const rawEndpoint = (config.endpoint ?? DEFAULT_CONSENT_ENDPOINT).trim()
|
|
64
|
+
const endpoint = rawEndpoint.startsWith('/') ? rawEndpoint : `/${rawEndpoint}`
|
|
65
|
+
return {
|
|
66
|
+
categories,
|
|
67
|
+
categorySet,
|
|
68
|
+
cookieName: config.cookieName ?? DEFAULT_CONSENT_COOKIE,
|
|
69
|
+
maxAge: config.maxAge ?? DEFAULT_CONSENT_MAX_AGE,
|
|
70
|
+
endpoint,
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export function parseConsentCookie(raw: string | undefined, declared: ReadonlySet<string>): { decided: boolean, granted: Set<string> } {
|
|
75
|
+
const granted = new Set<string>()
|
|
76
|
+
if (raw === undefined || !raw.startsWith(COOKIE_VERSION_PREFIX))
|
|
77
|
+
return { decided: false, granted }
|
|
78
|
+
const payload = raw.slice(COOKIE_VERSION_PREFIX.length)
|
|
79
|
+
if (payload !== '') {
|
|
80
|
+
for (const part of payload.split(',')) {
|
|
81
|
+
const cat = part.trim()
|
|
82
|
+
if (declared.has(cat))
|
|
83
|
+
granted.add(cat)
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
return { decided: true, granted }
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export function serializeConsentCookie(granted: ReadonlySet<string>, declared: readonly string[]): string {
|
|
90
|
+
const ordered: string[] = []
|
|
91
|
+
for (const cat of declared) {
|
|
92
|
+
if (granted.has(cat))
|
|
93
|
+
ordered.push(cat)
|
|
94
|
+
}
|
|
95
|
+
return `${COOKIE_VERSION_PREFIX}${ordered.join(',')}`
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
export function createRequestConsent(rawCookie: string | undefined, config: NormalizedConsentConfig | undefined): RequestConsent {
|
|
99
|
+
if (config === undefined)
|
|
100
|
+
return EMPTY_CONSENT
|
|
101
|
+
const { decided, granted } = parseConsentCookie(rawCookie, config.categorySet)
|
|
102
|
+
return {
|
|
103
|
+
decided,
|
|
104
|
+
categories: config.categories,
|
|
105
|
+
has(category: string): boolean {
|
|
106
|
+
return category === 'essential' || granted.has(category)
|
|
107
|
+
},
|
|
108
|
+
all(): Record<string, boolean> {
|
|
109
|
+
const out: Record<string, boolean> = {}
|
|
110
|
+
for (const cat of config.categories)
|
|
111
|
+
out[cat] = granted.has(cat)
|
|
112
|
+
return out
|
|
113
|
+
},
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
function isTruthyFormValue(value: FormDataEntryValue | null): boolean {
|
|
118
|
+
if (typeof value !== 'string')
|
|
119
|
+
return false
|
|
120
|
+
const norm = value.trim().toLowerCase()
|
|
121
|
+
return norm !== '' && norm !== 'false' && norm !== '0' && norm !== 'off' && norm !== 'no'
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function resolveConsentRedirect(
|
|
125
|
+
request: Request,
|
|
126
|
+
url: URL,
|
|
127
|
+
formRedirect: string | undefined,
|
|
128
|
+
trustedOrigins: ReadonlySet<string> | undefined,
|
|
129
|
+
trustProxy: TrustProxy,
|
|
130
|
+
): string {
|
|
131
|
+
const fromForm = safeRedirect(formRedirect, '')
|
|
132
|
+
if (fromForm !== '')
|
|
133
|
+
return fromForm
|
|
134
|
+
const referer = request.headers.get('referer')
|
|
135
|
+
if (referer !== null) {
|
|
136
|
+
try {
|
|
137
|
+
const refUrl = new URL(referer)
|
|
138
|
+
if (isTrustedOrigin(refUrl.origin, request, trustedOrigins, trustProxy, url))
|
|
139
|
+
return safeRedirect(`${refUrl.pathname}${refUrl.search}`)
|
|
140
|
+
}
|
|
141
|
+
catch {
|
|
142
|
+
return '/'
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
return '/'
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
async function parseConsentSubmission(
|
|
149
|
+
request: Request,
|
|
150
|
+
config: NormalizedConsentConfig,
|
|
151
|
+
): Promise<{ ok: true, granted: Set<string>, redirect?: string | undefined } | { ok: false, error: string }> {
|
|
152
|
+
const ct = (request.headers.get('content-type') ?? '').toLowerCase()
|
|
153
|
+
const granted = new Set<string>()
|
|
154
|
+
|
|
155
|
+
if (ct.includes('application/json')) {
|
|
156
|
+
let body: unknown
|
|
157
|
+
try {
|
|
158
|
+
body = await request.json()
|
|
159
|
+
}
|
|
160
|
+
catch {
|
|
161
|
+
return { ok: false, error: 'Invalid JSON body' }
|
|
162
|
+
}
|
|
163
|
+
if (body === null || typeof body !== 'object' || Array.isArray(body))
|
|
164
|
+
return { ok: false, error: 'Consent payload must be a JSON object' }
|
|
165
|
+
const obj = body as Record<string, unknown>
|
|
166
|
+
if (obj.acceptAll === true || obj.action === 'accept-all') {
|
|
167
|
+
for (const cat of config.categories)
|
|
168
|
+
granted.add(cat)
|
|
169
|
+
return { ok: true, granted }
|
|
170
|
+
}
|
|
171
|
+
if (obj.rejectAll === true || obj.action === 'reject-all')
|
|
172
|
+
return { ok: true, granted }
|
|
173
|
+
if (Array.isArray(obj.categories)) {
|
|
174
|
+
for (const item of obj.categories) {
|
|
175
|
+
if (typeof item === 'string' && config.categorySet.has(item))
|
|
176
|
+
granted.add(item)
|
|
177
|
+
}
|
|
178
|
+
return { ok: true, granted }
|
|
179
|
+
}
|
|
180
|
+
if (obj.categories !== null && typeof obj.categories === 'object') {
|
|
181
|
+
for (const [cat, enabled] of Object.entries(obj.categories as Record<string, unknown>)) {
|
|
182
|
+
if (config.categorySet.has(cat) && enabled === true)
|
|
183
|
+
granted.add(cat)
|
|
184
|
+
}
|
|
185
|
+
return { ok: true, granted }
|
|
186
|
+
}
|
|
187
|
+
return { ok: true, granted }
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
let form: FormData
|
|
191
|
+
try {
|
|
192
|
+
form = await request.formData()
|
|
193
|
+
}
|
|
194
|
+
catch {
|
|
195
|
+
return { ok: false, error: 'Invalid form submission' }
|
|
196
|
+
}
|
|
197
|
+
const rawRedirect = form.get('redirect')
|
|
198
|
+
const redirect = typeof rawRedirect === 'string' ? rawRedirect : undefined
|
|
199
|
+
const action = form.get('action')
|
|
200
|
+
if (action === 'accept-all') {
|
|
201
|
+
for (const cat of config.categories)
|
|
202
|
+
granted.add(cat)
|
|
203
|
+
return { ok: true, granted, redirect }
|
|
204
|
+
}
|
|
205
|
+
if (action === 'reject-all')
|
|
206
|
+
return { ok: true, granted, redirect }
|
|
207
|
+
|
|
208
|
+
const listed = new Set(form.getAll('categories').filter((v): v is string => typeof v === 'string'))
|
|
209
|
+
for (const cat of config.categories) {
|
|
210
|
+
if (listed.has(cat) || isTruthyFormValue(form.get(cat)))
|
|
211
|
+
granted.add(cat)
|
|
212
|
+
}
|
|
213
|
+
return { ok: true, granted, redirect }
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
export type ConsentRouteRegistrar = (
|
|
217
|
+
method: string,
|
|
218
|
+
path: string,
|
|
219
|
+
handler: (ctx: RequestContext) => Response | Promise<Response>,
|
|
220
|
+
options?: PluginRouteOptions,
|
|
221
|
+
) => void
|
|
222
|
+
|
|
223
|
+
/** Registers the automatic CSRF-protected `POST /_pru/consent` endpoint when `consent` is configured. */
|
|
224
|
+
export function registerConsentRoute(
|
|
225
|
+
register: ConsentRouteRegistrar,
|
|
226
|
+
config: NormalizedConsentConfig,
|
|
227
|
+
trustedOrigins: ReadonlySet<string> | undefined,
|
|
228
|
+
trustProxy: TrustProxy,
|
|
229
|
+
): void {
|
|
230
|
+
register('POST', config.endpoint, async (ctx) => {
|
|
231
|
+
const parsed = await parseConsentSubmission(ctx.request, config)
|
|
232
|
+
if (!parsed.ok)
|
|
233
|
+
return ctx.deny(400, parsed.error)
|
|
234
|
+
|
|
235
|
+
const cookieVal = serializeConsentCookie(parsed.granted, config.categories)
|
|
236
|
+
ctx.cookies.set(config.cookieName, cookieVal, {
|
|
237
|
+
httpOnly: true,
|
|
238
|
+
sameSite: 'lax',
|
|
239
|
+
path: '/',
|
|
240
|
+
maxAge: config.maxAge,
|
|
241
|
+
category: 'essential',
|
|
242
|
+
})
|
|
243
|
+
|
|
244
|
+
if (wantsJson(ctx.request)) {
|
|
245
|
+
const consent: Record<string, boolean> = {}
|
|
246
|
+
for (const cat of config.categories)
|
|
247
|
+
consent[cat] = parsed.granted.has(cat)
|
|
248
|
+
return ctx.json({ ok: true, decided: true, consent })
|
|
249
|
+
}
|
|
250
|
+
const target = resolveConsentRedirect(ctx.request, ctx.url, parsed.redirect, trustedOrigins, trustProxy)
|
|
251
|
+
return ctx.redirect(target, 303)
|
|
252
|
+
}, { csrf: true })
|
|
253
|
+
}
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
// Typed cookie jar for RequestContext (lazy Cookie header parsing, validated & deduplicated Set-Cookie serialization).
|
|
2
|
+
|
|
3
|
+
export interface CookieOptions {
|
|
4
|
+
path?: string | undefined
|
|
5
|
+
domain?: string | undefined
|
|
6
|
+
maxAge?: number | undefined
|
|
7
|
+
expires?: Date | undefined
|
|
8
|
+
httpOnly?: boolean | undefined
|
|
9
|
+
secure?: boolean | undefined
|
|
10
|
+
sameSite?: 'strict' | 'lax' | 'none' | undefined
|
|
11
|
+
/** Consent category required before setting this cookie (omit or `'essential'` for strictly necessary cookies). */
|
|
12
|
+
category?: string | undefined
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export interface Cookies {
|
|
16
|
+
get(name: string): string | undefined
|
|
17
|
+
set(name: string, value: string, options?: CookieOptions): void
|
|
18
|
+
delete(name: string, options?: Pick<CookieOptions, 'path' | 'domain' | 'secure'>): void
|
|
19
|
+
all(): Record<string, string>
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
const VALID_COOKIE_NAME = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/
|
|
23
|
+
const UNSAFE_ATTR_VAL = /[;\r\n\u0000-\u001F\u007F]/
|
|
24
|
+
|
|
25
|
+
function parseCookieHeader(header: string | null): Map<string, string> {
|
|
26
|
+
const map = new Map<string, string>()
|
|
27
|
+
if (!header)
|
|
28
|
+
return map
|
|
29
|
+
const parts = header.split(';')
|
|
30
|
+
for (let i = 0; i < parts.length; i++) {
|
|
31
|
+
const part = parts[i]!
|
|
32
|
+
const eq = part.indexOf('=')
|
|
33
|
+
if (eq <= 0)
|
|
34
|
+
continue
|
|
35
|
+
const name = part.slice(0, eq).trim()
|
|
36
|
+
// RFC 6265 §5.4: more specific path cookies come first, so first wins.
|
|
37
|
+
if (name === '' || map.has(name))
|
|
38
|
+
continue
|
|
39
|
+
const raw = part.slice(eq + 1).trim()
|
|
40
|
+
try {
|
|
41
|
+
map.set(name, decodeURIComponent(raw))
|
|
42
|
+
}
|
|
43
|
+
catch {
|
|
44
|
+
map.set(name, raw)
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
return map
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function serializeCookie(name: string, value: string, options: CookieOptions = {}, defaultSecure = false): string {
|
|
51
|
+
if (!VALID_COOKIE_NAME.test(name))
|
|
52
|
+
throw new TypeError(`prunelle: invalid cookie name "${name}"`)
|
|
53
|
+
const path = options.path ?? '/'
|
|
54
|
+
if (UNSAFE_ATTR_VAL.test(path))
|
|
55
|
+
throw new TypeError(`prunelle: invalid cookie path "${path}"`)
|
|
56
|
+
if (options.domain !== undefined && UNSAFE_ATTR_VAL.test(options.domain))
|
|
57
|
+
throw new TypeError(`prunelle: invalid cookie domain "${options.domain}"`)
|
|
58
|
+
|
|
59
|
+
const secure = options.secure ?? defaultSecure
|
|
60
|
+
const sameSite = options.sameSite ?? 'lax'
|
|
61
|
+
if (sameSite === 'none' && !secure)
|
|
62
|
+
throw new Error(`prunelle: Cookie "${name}" with sameSite: "none" requires secure: true`)
|
|
63
|
+
|
|
64
|
+
let out = `${name}=${encodeURIComponent(value)}`
|
|
65
|
+
out += `; Path=${path}`
|
|
66
|
+
if (options.domain !== undefined)
|
|
67
|
+
out += `; Domain=${options.domain}`
|
|
68
|
+
if (options.maxAge !== undefined) {
|
|
69
|
+
if (!Number.isFinite(options.maxAge))
|
|
70
|
+
throw new TypeError(`prunelle: invalid cookie maxAge "${options.maxAge}"`)
|
|
71
|
+
out += `; Max-Age=${Math.floor(options.maxAge)}`
|
|
72
|
+
}
|
|
73
|
+
if (options.expires !== undefined)
|
|
74
|
+
out += `; Expires=${options.expires.toUTCString()}`
|
|
75
|
+
if (options.httpOnly ?? true)
|
|
76
|
+
out += '; HttpOnly'
|
|
77
|
+
if (secure)
|
|
78
|
+
out += '; Secure'
|
|
79
|
+
out += `; SameSite=${sameSite[0]!.toUpperCase()}${sameSite.slice(1)}`
|
|
80
|
+
return out
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function cookieKey(name: string, options?: Pick<CookieOptions, 'path' | 'domain'>): string {
|
|
84
|
+
return `${name}\0${options?.path ?? '/'}\0${options?.domain ?? ''}`
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
export class CookieStore implements Cookies {
|
|
88
|
+
#rawHeader: string | null
|
|
89
|
+
#values: Map<string, string> | undefined
|
|
90
|
+
readonly #headers = new Map<string, string>()
|
|
91
|
+
readonly #isHttps: boolean
|
|
92
|
+
readonly #isConsentGranted: ((category: string) => boolean) | undefined
|
|
93
|
+
|
|
94
|
+
constructor(cookieHeader: string | null, isHttps = false, isConsentGranted?: (category: string) => boolean) {
|
|
95
|
+
this.#rawHeader = cookieHeader
|
|
96
|
+
this.#isHttps = isHttps
|
|
97
|
+
this.#isConsentGranted = isConsentGranted
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
#ensureValues(): Map<string, string> {
|
|
101
|
+
if (this.#values === undefined) {
|
|
102
|
+
this.#values = parseCookieHeader(this.#rawHeader)
|
|
103
|
+
this.#rawHeader = null
|
|
104
|
+
}
|
|
105
|
+
return this.#values
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
get(name: string): string | undefined {
|
|
109
|
+
return this.#ensureValues().get(name)
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
set(name: string, value: string, options?: CookieOptions): void {
|
|
113
|
+
if (options?.category !== undefined && options.category !== 'essential') {
|
|
114
|
+
if (this.#isConsentGranted === undefined || !this.#isConsentGranted(options.category))
|
|
115
|
+
return
|
|
116
|
+
}
|
|
117
|
+
const serialized = serializeCookie(name, value, options, this.#isHttps)
|
|
118
|
+
this.#ensureValues().set(name, value)
|
|
119
|
+
this.#headers.set(cookieKey(name, options), serialized)
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
delete(name: string, options?: Pick<CookieOptions, 'path' | 'domain' | 'secure'>): void {
|
|
123
|
+
this.#ensureValues().delete(name)
|
|
124
|
+
this.#headers.set(cookieKey(name, options), serializeCookie(name, '', { ...options, maxAge: 0, expires: new Date(0) }, this.#isHttps))
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
all(): Record<string, string> {
|
|
128
|
+
return Object.fromEntries(this.#ensureValues())
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
get hasChanges(): boolean {
|
|
132
|
+
return this.#headers.size > 0
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
applyTo(headers: Headers): void {
|
|
136
|
+
for (const serialized of this.#headers.values())
|
|
137
|
+
headers.append('set-cookie', serialized)
|
|
138
|
+
}
|
|
139
|
+
}
|
|
@@ -0,0 +1,271 @@
|
|
|
1
|
+
// What every rendered document shares: its HTML headers, the plugins' `head` hooks and `transformHtml` passes, and the islands it rendered.
|
|
2
|
+
|
|
3
|
+
import type { DocumentHeadContext, PrunellePlugin, ServerErrorInfo } from '../plugins/index'
|
|
4
|
+
import type { RenderContext } from '../ssr/context'
|
|
5
|
+
import type { Navigation } from '../ssr/navigation'
|
|
6
|
+
import type { RequestContext } from './http'
|
|
7
|
+
import type { SecurityHeadersOptions, TrustProxy } from './security'
|
|
8
|
+
import { cspSha256 } from '../ssr/navigation'
|
|
9
|
+
import { readBufferedOrPassThrough } from './compress'
|
|
10
|
+
import { extractRenderedIslands, makeRequestContext } from './http'
|
|
11
|
+
import { inlineStyleHashes, PRUNELLE_ISLAND_STYLE_HASH, PRUNELLE_STREAM_SCRIPT_HASH, PRUNELLE_SUSPENSE_STYLE_HASH, resolveCspPolicy, withCspHashes } from './security'
|
|
12
|
+
|
|
13
|
+
const TITLE_INNER_RE = /^<title\b[^>]*>([\s\S]*?)<\/title>$/i
|
|
14
|
+
|
|
15
|
+
/** `styleHashes` are the page's own `<style>` blocks (`inlineStyleHashes`), added to its CSP. */
|
|
16
|
+
export type HtmlHeaders = (hasIslands: boolean, hasSuspense: boolean, isDynamic: boolean, styleHashes?: readonly string[]) => Record<string, string>
|
|
17
|
+
|
|
18
|
+
const STYLED_HEADER_CACHE_SIZE = 256
|
|
19
|
+
|
|
20
|
+
// HTML headers, one set per (dynamic, islands, suspense) combination: the CSP only gains the hashes a page needs.
|
|
21
|
+
export function createHtmlHeaders(security: SecurityHeadersOptions | false | undefined, securityRecord: Record<string, string>, navigation?: Navigation, plugins: readonly PrunellePlugin[] = []): HtmlHeaders {
|
|
22
|
+
const baseCsp = resolveCspPolicy(security)
|
|
23
|
+
const navStyles = navigation?.styleHashes ?? []
|
|
24
|
+
const navScripts = [...navigation?.scriptHashes ?? [], ...plugins.flatMap(plugin => plugin.inlineScripts ?? []).map(cspSha256)]
|
|
25
|
+
const htmlHeaderSets: Record<string, string>[] = []
|
|
26
|
+
const prunelleStyleHashes: string[][] = []
|
|
27
|
+
const prunelleScriptHashes: string[][] = []
|
|
28
|
+
for (let i = 0; i < 8; i++) {
|
|
29
|
+
const isDynamic = (i & 4) !== 0
|
|
30
|
+
const hasIslands = (i & 2) !== 0
|
|
31
|
+
const hasSuspense = (i & 1) !== 0
|
|
32
|
+
const headers: Record<string, string> = { 'content-type': 'text/html; charset=utf-8', ...securityRecord }
|
|
33
|
+
if (isDynamic)
|
|
34
|
+
headers['cache-control'] = 'private'
|
|
35
|
+
const styleHashes = [...navStyles, ...(hasIslands ? [PRUNELLE_ISLAND_STYLE_HASH] : []), ...(hasSuspense ? [PRUNELLE_SUSPENSE_STYLE_HASH] : [])]
|
|
36
|
+
const scriptHashes = [...navScripts, ...(hasSuspense ? [PRUNELLE_STREAM_SCRIPT_HASH] : [])]
|
|
37
|
+
prunelleStyleHashes.push(styleHashes)
|
|
38
|
+
prunelleScriptHashes.push(scriptHashes)
|
|
39
|
+
if (baseCsp !== undefined)
|
|
40
|
+
headers['content-security-policy'] = withCspHashes(baseCsp, { styleHashes, scriptHashes })
|
|
41
|
+
htmlHeaderSets.push(headers)
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
// Pages sharing a layout share its blocks, so their header sets are kept with LRU eviction.
|
|
45
|
+
const styledSets = new Map<string, Record<string, string>>()
|
|
46
|
+
return (hasIslands, hasSuspense, isDynamic, styleHashes) => {
|
|
47
|
+
const index = (isDynamic ? 4 : 0) | (hasIslands ? 2 : 0) | (hasSuspense ? 1 : 0)
|
|
48
|
+
const base = htmlHeaderSets[index]!
|
|
49
|
+
if (baseCsp === undefined || styleHashes === undefined || styleHashes.length === 0)
|
|
50
|
+
return base
|
|
51
|
+
const key = `${index} ${styleHashes.join(' ')}`
|
|
52
|
+
let headers = styledSets.get(key)
|
|
53
|
+
if (headers !== undefined) {
|
|
54
|
+
styledSets.delete(key)
|
|
55
|
+
styledSets.set(key, headers)
|
|
56
|
+
return headers
|
|
57
|
+
}
|
|
58
|
+
headers = {
|
|
59
|
+
...base,
|
|
60
|
+
'content-security-policy': withCspHashes(baseCsp, {
|
|
61
|
+
styleHashes: [...prunelleStyleHashes[index]!, ...styleHashes],
|
|
62
|
+
scriptHashes: prunelleScriptHashes[index]!,
|
|
63
|
+
}),
|
|
64
|
+
}
|
|
65
|
+
if (styledSets.size >= STYLED_HEADER_CACHE_SIZE)
|
|
66
|
+
styledSets.delete(styledSets.keys().next().value!)
|
|
67
|
+
styledSets.set(key, headers)
|
|
68
|
+
return headers
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** Merges multiple style-hash arrays into a deduplicated list, preserving order. */
|
|
73
|
+
export function mergeStyleHashes(...groups: readonly (readonly string[] | undefined)[]): string[] {
|
|
74
|
+
let out: string[] | undefined
|
|
75
|
+
for (const group of groups) {
|
|
76
|
+
if (group === undefined || group.length === 0)
|
|
77
|
+
continue
|
|
78
|
+
out ??= []
|
|
79
|
+
for (const h of group) {
|
|
80
|
+
if (!out.includes(h))
|
|
81
|
+
out.push(h)
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
return out ?? []
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** Extracts CSP style hashes from framework/plugin-configured `headTags` once at startup. */
|
|
88
|
+
export function headTagStyleHashes(headTags: Iterable<string> | undefined): string[] {
|
|
89
|
+
if (headTags === undefined)
|
|
90
|
+
return []
|
|
91
|
+
let combined = ''
|
|
92
|
+
for (const tag of headTags)
|
|
93
|
+
combined += tag
|
|
94
|
+
return combined === '' ? [] : inlineStyleHashes(combined)
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** Returns only `<style>` hashes newly introduced by plugin `transformHtml` hooks (never preexisting HTML). */
|
|
98
|
+
export function addedInlineStyleHashes(before: string, after: string): string[] {
|
|
99
|
+
if (before === after)
|
|
100
|
+
return []
|
|
101
|
+
const afterHashes = inlineStyleHashes(after)
|
|
102
|
+
if (afterHashes.length === 0)
|
|
103
|
+
return []
|
|
104
|
+
const beforeSet = new Set(inlineStyleHashes(before))
|
|
105
|
+
return afterHashes.filter(h => !beforeSet.has(h))
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function withBaseCsp(res: Response, htmlHeaders: HtmlHeaders): Response {
|
|
109
|
+
const csp = htmlHeaders(false, false, true)['content-security-policy']
|
|
110
|
+
if (csp === undefined)
|
|
111
|
+
return res
|
|
112
|
+
const headers = new Headers(res.headers)
|
|
113
|
+
headers.set('content-security-policy', csp)
|
|
114
|
+
return new Response(res.body, { status: res.status, statusText: res.statusText, headers })
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** A plugin's HTML page without a CSP of its own gets the app's, its `<style>` blocks hashed like a rendered page's. */
|
|
118
|
+
export async function withPluginHtmlCsp(res: Response, htmlHeaders: HtmlHeaders): Promise<Response> {
|
|
119
|
+
if (res.body === null || res.headers.has('content-security-policy') || !(res.headers.get('content-type') ?? '').trim().toLowerCase().startsWith('text/html'))
|
|
120
|
+
return res
|
|
121
|
+
// Never decode pre-compressed bytes as UTF-8; attach base CSP without touching the body.
|
|
122
|
+
if (res.headers.has('content-encoding'))
|
|
123
|
+
return withBaseCsp(res, htmlHeaders)
|
|
124
|
+
const probed = await readBufferedOrPassThrough(res)
|
|
125
|
+
if ('passthrough' in probed)
|
|
126
|
+
return withBaseCsp(probed.passthrough, htmlHeaders)
|
|
127
|
+
const html = new TextDecoder().decode(probed.buffered)
|
|
128
|
+
const headers = new Headers(res.headers)
|
|
129
|
+
const csp = htmlHeaders(false, false, true, inlineStyleHashes(html))['content-security-policy']
|
|
130
|
+
if (csp !== undefined)
|
|
131
|
+
headers.set('content-security-policy', csp)
|
|
132
|
+
return new Response(html, { status: res.status, statusText: res.statusText, headers })
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/** The revivers, for a page whose island props need them; nothing otherwise. */
|
|
136
|
+
export function revivePreload(rctx: RenderContext, reviveScript: string | undefined): string[] {
|
|
137
|
+
return rctx.revives && reviveScript !== undefined ? [reviveScript] : []
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
export function resolveRenderedIslands(rctx: RenderContext, body: string): { hasIslands: boolean, eagerChunks: string[] } {
|
|
141
|
+
if (rctx.hasIslands) {
|
|
142
|
+
const eagerChunks: string[] = []
|
|
143
|
+
for (const [chunk, eager] of rctx.renderedIslands) {
|
|
144
|
+
if (eager)
|
|
145
|
+
eagerChunks.push(chunk)
|
|
146
|
+
}
|
|
147
|
+
return { hasIslands: true, eagerChunks }
|
|
148
|
+
}
|
|
149
|
+
// Fallback only if raw HTML injected a <pru-island> without going through ssrIsland/ssrIslandStatic.
|
|
150
|
+
if (body.includes('<pru-island'))
|
|
151
|
+
return extractRenderedIslands(body)
|
|
152
|
+
return { hasIslands: false, eagerChunks: [] }
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
export interface DocumentHooksOptions {
|
|
156
|
+
plugins: readonly PrunellePlugin[]
|
|
157
|
+
lang: string
|
|
158
|
+
trustProxy: TrustProxy
|
|
159
|
+
notifyError: (error: unknown, request: Request, source: ServerErrorInfo['source']) => void
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
export function createDocumentHooks(options: DocumentHooksOptions) {
|
|
163
|
+
const { lang, trustProxy, notifyError } = options
|
|
164
|
+
const headHooks = options.plugins
|
|
165
|
+
.map(p => p.head)
|
|
166
|
+
.filter((fn): fn is NonNullable<PrunellePlugin['head']> => typeof fn === 'function')
|
|
167
|
+
const htmlTransformers = options.plugins
|
|
168
|
+
.map(p => p.transformHtml)
|
|
169
|
+
.filter((fn): fn is NonNullable<PrunellePlugin['transformHtml']> => typeof fn === 'function')
|
|
170
|
+
const hasHeadHooks = headHooks.length > 0
|
|
171
|
+
const hasHtmlTransformers = htmlTransformers.length > 0
|
|
172
|
+
|
|
173
|
+
async function resolveDocumentHead(
|
|
174
|
+
rctx: RenderContext,
|
|
175
|
+
baseHeadTags: readonly string[] | undefined,
|
|
176
|
+
url: URL,
|
|
177
|
+
req?: Request,
|
|
178
|
+
ctx?: RequestContext,
|
|
179
|
+
): Promise<{ head: string, lang: string, htmlAttrs: Record<string, string>, styleHashes: string[] }> {
|
|
180
|
+
const collectedParts = rctx.headParts.join('')
|
|
181
|
+
if (!hasHeadHooks) {
|
|
182
|
+
return {
|
|
183
|
+
head: (rctx.title ?? '') + collectedParts,
|
|
184
|
+
lang,
|
|
185
|
+
htmlAttrs: rctx.htmlAttrs,
|
|
186
|
+
styleHashes: [],
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
const headCtx = ctx ?? makeRequestContext(req ?? new Request(url.toString()), {}, { trustProxy, url }).ctx
|
|
191
|
+
const htmlAttrs: Record<string, string> = { ...rctx.htmlAttrs }
|
|
192
|
+
const initialTitleTag = rctx.title
|
|
193
|
+
const initialTitleInner = initialTitleTag !== undefined ? TITLE_INNER_RE.exec(initialTitleTag)?.[1] : undefined
|
|
194
|
+
let currentTitle = initialTitleInner
|
|
195
|
+
let titleDirty = false
|
|
196
|
+
let currentLang = htmlAttrs.lang ?? lang
|
|
197
|
+
let headBuf = (initialTitleTag ?? '') + collectedParts
|
|
198
|
+
if (baseHeadTags !== undefined) {
|
|
199
|
+
for (let i = 0; i < baseHeadTags.length; i++)
|
|
200
|
+
headBuf += baseHeadTags[i]
|
|
201
|
+
}
|
|
202
|
+
const added: string[] = []
|
|
203
|
+
|
|
204
|
+
const docHead: DocumentHeadContext = {
|
|
205
|
+
get lang() {
|
|
206
|
+
return currentLang
|
|
207
|
+
},
|
|
208
|
+
set lang(v: string) {
|
|
209
|
+
currentLang = v
|
|
210
|
+
htmlAttrs.lang = v
|
|
211
|
+
},
|
|
212
|
+
htmlAttrs,
|
|
213
|
+
get title() {
|
|
214
|
+
return currentTitle
|
|
215
|
+
},
|
|
216
|
+
set title(v: string | undefined) {
|
|
217
|
+
currentTitle = v
|
|
218
|
+
titleDirty = true
|
|
219
|
+
},
|
|
220
|
+
get headHtml() {
|
|
221
|
+
return headBuf
|
|
222
|
+
},
|
|
223
|
+
add(html: string) {
|
|
224
|
+
if (html !== '') {
|
|
225
|
+
added.push(html)
|
|
226
|
+
headBuf += html
|
|
227
|
+
}
|
|
228
|
+
},
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
for (const hook of headHooks) {
|
|
232
|
+
try {
|
|
233
|
+
await hook(docHead, headCtx)
|
|
234
|
+
}
|
|
235
|
+
catch (err) {
|
|
236
|
+
notifyError(err, req ?? headCtx.request, 'plugin')
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
const titleHtml = titleDirty
|
|
241
|
+
? (currentTitle !== undefined ? `<title>${currentTitle}</title>` : '')
|
|
242
|
+
: (initialTitleTag ?? '')
|
|
243
|
+
const addedHtml = added.length > 0 ? added.join('') : ''
|
|
244
|
+
return {
|
|
245
|
+
head: titleHtml + collectedParts + addedHtml,
|
|
246
|
+
lang: currentLang,
|
|
247
|
+
htmlAttrs,
|
|
248
|
+
styleHashes: addedHtml !== '' ? inlineStyleHashes(addedHtml) : [],
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
async function applyHtmlTransforms(html: string, url: URL, req?: Request, ctx?: RequestContext): Promise<string> {
|
|
253
|
+
if (!hasHtmlTransformers)
|
|
254
|
+
return html
|
|
255
|
+
const transformCtx = ctx ?? makeRequestContext(req ?? new Request(url.toString()), {}, { trustProxy, url }).ctx
|
|
256
|
+
let out = html
|
|
257
|
+
for (const transform of htmlTransformers) {
|
|
258
|
+
try {
|
|
259
|
+
out = await transform(out, transformCtx)
|
|
260
|
+
}
|
|
261
|
+
catch (err) {
|
|
262
|
+
notifyError(err, req ?? transformCtx.request, 'plugin')
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
return out
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
return { hasHeadHooks, hasHtmlTransformers, htmlTransformers, resolveDocumentHead, applyHtmlTransforms }
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
export type DocumentHooks = ReturnType<typeof createDocumentHooks>
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
// Typed environment variable loader using any Standard Schema validator.
|
|
2
|
+
|
|
3
|
+
import type { InferOutput, StandardSchemaV1 } from './standard-schema'
|
|
4
|
+
import { getAppContext } from '../plugins/context'
|
|
5
|
+
import { formatIssuePath, validateSchemaSync } from './standard-schema'
|
|
6
|
+
|
|
7
|
+
const NODE_ENV_KEY = 'NODE_ENV'
|
|
8
|
+
|
|
9
|
+
/** Reads NODE_ENV at runtime (preferring the active AppRuntimeContext when set): the dynamic key keeps Bun.build from constant-folding it in compiled binaries. */
|
|
10
|
+
export function nodeEnv(): string | undefined {
|
|
11
|
+
return getAppContext()?.nodeEnv ?? process.env[NODE_ENV_KEY]
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export function defineEnv<S extends StandardSchemaV1>(
|
|
15
|
+
schema: S,
|
|
16
|
+
source: Record<string, string | undefined> = process.env,
|
|
17
|
+
): Readonly<InferOutput<S>> {
|
|
18
|
+
const result = validateSchemaSync(
|
|
19
|
+
schema,
|
|
20
|
+
source,
|
|
21
|
+
'prunelle: defineEnv() requires a synchronous Standard Schema validator',
|
|
22
|
+
)
|
|
23
|
+
if (!result.ok) {
|
|
24
|
+
const details = result.issues
|
|
25
|
+
.map(issue => ` - ${formatIssuePath(issue) || '(root)'}: ${issue.message}`)
|
|
26
|
+
.join('\n')
|
|
27
|
+
throw new Error(`prunelle: invalid environment variables:\n${details}`)
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
return typeof result.value === 'object' && result.value !== null
|
|
31
|
+
? Object.freeze({ ...result.value })
|
|
32
|
+
: result.value
|
|
33
|
+
}
|