prunelle 0.7.1 → 0.7.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/llms.txt +5 -5
- package/package.json +1 -1
- package/src/a11y/declaration.ts +4 -0
- package/src/a11y/index.ts +11 -0
- package/src/build/bundle.ts +2 -2
- package/src/build/files.ts +9 -0
- package/src/build/first-load.ts +2 -3
- package/src/build/index.ts +6 -12
- package/src/build/island-promote.ts +69 -8
- package/src/build/output.ts +3 -6
- package/src/build/plugin-host.ts +4 -2
- package/src/build/precompress.ts +1 -1
- package/src/build/prerender.ts +7 -4
- package/src/build/reach.ts +92 -28
- package/src/build/static-headers.ts +27 -8
- package/src/cli/check-forms.ts +60 -34
- package/src/cli/check-imports.ts +9 -3
- package/src/cli/check.ts +5 -15
- package/src/cli/new.ts +1 -1
- package/src/cli/upgrade.ts +4 -8
- package/src/compiler/analyze.ts +19 -41
- package/src/compiler/cacheability-private.ts +566 -0
- package/src/compiler/cacheability.ts +21 -322
- package/src/compiler/compliance-eco.ts +4 -4
- package/src/compiler/compliance-urls.ts +5 -3
- package/src/compiler/compliance.ts +68 -17
- package/src/compiler/expr-context.ts +113 -44
- package/src/compiler/spread-handlers.ts +295 -0
- package/src/dom/extras.ts +28 -26
- package/src/dom/island.ts +49 -34
- package/src/eco/declaration.ts +87 -16
- package/src/eco/index.ts +7 -3
- package/src/plugins/config.ts +13 -8
- package/src/reactivity/store.ts +19 -7
- package/src/server/action.ts +137 -40
- package/src/server/errors.ts +3 -0
- package/src/server/form-schema.ts +6 -12
- package/src/server/index.ts +6 -6
- package/src/server/page.ts +15 -0
- package/src/server/route-cache.ts +99 -3
- package/src/server/route-table.ts +23 -13
- package/src/server/standard-schema.ts +17 -0
- package/src/ssr/context.ts +1 -1
- package/src/ssr/index.ts +4 -2
- package/src/ssr/region.ts +18 -9
package/src/dom/island.ts
CHANGED
|
@@ -136,6 +136,35 @@ function isAllowedChunkUrl(chunk: string): boolean {
|
|
|
136
136
|
return !/^(?:javascript|data|vbscript):/i.test(chunk)
|
|
137
137
|
}
|
|
138
138
|
|
|
139
|
+
function watchVisible(root: HTMLElement, onVisible: () => void): (() => void) | undefined {
|
|
140
|
+
if (typeof IntersectionObserver === 'undefined') {
|
|
141
|
+
onVisible()
|
|
142
|
+
return undefined
|
|
143
|
+
}
|
|
144
|
+
const targets: Element[] = []
|
|
145
|
+
collectVisibleTargets(root, targets)
|
|
146
|
+
let restoreDisplay: (() => void) | undefined
|
|
147
|
+
if (targets.length === 0) {
|
|
148
|
+
const display = typeof getComputedStyle === 'function' ? getComputedStyle(root).display : 'contents'
|
|
149
|
+
if (display === 'contents' || display === '') {
|
|
150
|
+
const prev = root.style.display
|
|
151
|
+
root.style.display = 'inline'
|
|
152
|
+
restoreDisplay = () => { root.style.display = prev }
|
|
153
|
+
}
|
|
154
|
+
targets.push(root)
|
|
155
|
+
}
|
|
156
|
+
const io = new IntersectionObserver((entries) => {
|
|
157
|
+
if (entries.some(e => e.isIntersecting))
|
|
158
|
+
onVisible()
|
|
159
|
+
}, { rootMargin: '200px' })
|
|
160
|
+
for (const target of targets)
|
|
161
|
+
io.observe(target)
|
|
162
|
+
return () => {
|
|
163
|
+
io.disconnect()
|
|
164
|
+
restoreDisplay?.()
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
|
|
139
168
|
let clientIslandIdSeq = 0
|
|
140
169
|
|
|
141
170
|
export function defineIslandElement(): void {
|
|
@@ -150,7 +179,9 @@ export function defineIslandElement(): void {
|
|
|
150
179
|
_s = false
|
|
151
180
|
_t = 0
|
|
152
181
|
|
|
153
|
-
_clearStrategy(): void {
|
|
182
|
+
_clearStrategy(token?: number): void {
|
|
183
|
+
if (token !== undefined && token !== this._t)
|
|
184
|
+
return
|
|
154
185
|
this._c?.()
|
|
155
186
|
this._c = undefined
|
|
156
187
|
}
|
|
@@ -163,32 +194,7 @@ export function defineIslandElement(): void {
|
|
|
163
194
|
|
|
164
195
|
const h = this.getAttribute('h')
|
|
165
196
|
if ((typeof PRUNELLE_VISIBLE === 'undefined' || PRUNELLE_VISIBLE) && h === 'visible') {
|
|
166
|
-
|
|
167
|
-
void this._l(false, token)
|
|
168
|
-
return
|
|
169
|
-
}
|
|
170
|
-
const targets: Element[] = []
|
|
171
|
-
collectVisibleTargets(this, targets)
|
|
172
|
-
let restoreDisplay: (() => void) | undefined
|
|
173
|
-
if (targets.length === 0) {
|
|
174
|
-
const display = typeof getComputedStyle === 'function' ? getComputedStyle(this).display : 'contents'
|
|
175
|
-
if (display === 'contents' || display === '') {
|
|
176
|
-
const prev = this.style.display
|
|
177
|
-
this.style.display = 'inline'
|
|
178
|
-
restoreDisplay = () => { this.style.display = prev }
|
|
179
|
-
}
|
|
180
|
-
targets.push(this)
|
|
181
|
-
}
|
|
182
|
-
const io = new IntersectionObserver((entries) => {
|
|
183
|
-
if (entries.some(e => e.isIntersecting))
|
|
184
|
-
void this._l(false, token)
|
|
185
|
-
}, { rootMargin: '200px' })
|
|
186
|
-
this._c = () => {
|
|
187
|
-
io.disconnect()
|
|
188
|
-
restoreDisplay?.()
|
|
189
|
-
}
|
|
190
|
-
for (const target of targets)
|
|
191
|
-
io.observe(target)
|
|
197
|
+
this._c = watchVisible(this, () => void this._l(false, token))
|
|
192
198
|
return
|
|
193
199
|
}
|
|
194
200
|
if ((typeof PRUNELLE_IDLE === 'undefined' || PRUNELLE_IDLE) && h === 'idle') {
|
|
@@ -242,13 +248,17 @@ export function defineIslandElement(): void {
|
|
|
242
248
|
|
|
243
249
|
// Resolves false when the chunk failed to load or hydrate.
|
|
244
250
|
async _l(clientOnly: boolean, token: number, keepStrategy = false, after?: () => void): Promise<boolean> {
|
|
251
|
+
if (token !== this._t)
|
|
252
|
+
return true
|
|
245
253
|
if (!keepStrategy)
|
|
246
|
-
this._clearStrategy()
|
|
254
|
+
this._clearStrategy(token)
|
|
247
255
|
const chunk = this.getAttribute('c')
|
|
248
|
-
if (!chunk || !isAllowedChunkUrl(chunk) ||
|
|
256
|
+
if (!chunk || !isAllowedChunkUrl(chunk) || !this.isConnected || this._d !== undefined) {
|
|
249
257
|
if (chunk && !isAllowedChunkUrl(chunk))
|
|
250
258
|
console.error(`[pru-island] refused chunk URL ${chunk}: it must be on this origin.`)
|
|
251
|
-
this._clearStrategy()
|
|
259
|
+
this._clearStrategy(token)
|
|
260
|
+
if (!this.isConnected)
|
|
261
|
+
this._s = false
|
|
252
262
|
return true
|
|
253
263
|
}
|
|
254
264
|
|
|
@@ -263,11 +273,14 @@ export function defineIslandElement(): void {
|
|
|
263
273
|
const raw = this._p ?? this.getAttribute('p')
|
|
264
274
|
const [loaded, revive] = await Promise.all([import(chunk) as Promise<IslandModule>, raw?.includes('"__k":') ? reviver() : undefined])
|
|
265
275
|
mod = loaded
|
|
266
|
-
if (
|
|
267
|
-
|
|
276
|
+
if (token !== this._t)
|
|
277
|
+
return true
|
|
278
|
+
this._clearStrategy(token)
|
|
279
|
+
if (!this.isConnected || this._d !== undefined) {
|
|
280
|
+
if (!this.isConnected)
|
|
281
|
+
this._s = false
|
|
268
282
|
return true
|
|
269
283
|
}
|
|
270
|
-
this._clearStrategy()
|
|
271
284
|
|
|
272
285
|
const props = (raw ? revive?.parseIslandProps(raw) ?? JSON.parse(raw) : {}) as Record<string, unknown>
|
|
273
286
|
const slot = extractOwnSlot(this) ?? this._slot ?? null
|
|
@@ -282,6 +295,8 @@ export function defineIslandElement(): void {
|
|
|
282
295
|
: loaded.hydrate(this, render, idPrefix)
|
|
283
296
|
if (!this.isConnected || token !== this._t) {
|
|
284
297
|
dispose()
|
|
298
|
+
if (token === this._t)
|
|
299
|
+
this._s = false
|
|
285
300
|
return true
|
|
286
301
|
}
|
|
287
302
|
this._d = dispose
|
|
@@ -290,7 +305,7 @@ export function defineIslandElement(): void {
|
|
|
290
305
|
}
|
|
291
306
|
catch (err) {
|
|
292
307
|
if (!keepStrategy)
|
|
293
|
-
this._clearStrategy()
|
|
308
|
+
this._clearStrategy(token)
|
|
294
309
|
dispose?.()
|
|
295
310
|
// The chunk URL is a hash; in dev the component's own name says which island failed.
|
|
296
311
|
console.error(`[pru-island] failed to hydrate ${process.env.NODE_ENV !== 'production' && mod?.default?.name ? `<${mod.default.name}> (${chunk})` : chunk}:`, err)
|
package/src/eco/declaration.ts
CHANGED
|
@@ -5,7 +5,9 @@ import { mkdirSync, writeFileSync } from 'node:fs'
|
|
|
5
5
|
import { dirname, join, resolve } from 'node:path'
|
|
6
6
|
import { escapeAttr, escapeJsxText, formatFrenchDate, layoutRendersMain, STATEMENT_PLACEHOLDER } from '../a11y/declaration'
|
|
7
7
|
import { relPosix } from '../build/files'
|
|
8
|
+
import { isInside } from '../build/is-inside'
|
|
8
9
|
import { fileToRoutePath } from '../build/routes'
|
|
10
|
+
import { parseOrigin } from '../compiler/compliance-urls'
|
|
9
11
|
|
|
10
12
|
export const DEFAULT_ECO_DECLARATION_PATH = 'src/routes/ecoconception.tsx'
|
|
11
13
|
const RGESN_URL = 'https://ecoresponsable.numerique.gouv.fr/publications/referentiel-general-ecoconception/'
|
|
@@ -19,6 +21,12 @@ export interface EcoFacts {
|
|
|
19
21
|
compress: boolean
|
|
20
22
|
/** `budget.firstLoad` in bytes, when the config sets one. */
|
|
21
23
|
firstLoadBudget: number | undefined
|
|
24
|
+
/** Public site URL (`config.site`), used to tell a same-origin `assetPrefix` from another domain. */
|
|
25
|
+
site?: string | undefined
|
|
26
|
+
/** Compliance rules listed in `config.compliance.ignore`. */
|
|
27
|
+
ignoredRules?: readonly string[] | undefined
|
|
28
|
+
/** Configured `routesDir` relative to `root` (or absolute), when different from `'src/routes'`. */
|
|
29
|
+
routesDir?: string | undefined
|
|
22
30
|
}
|
|
23
31
|
|
|
24
32
|
export type EcoVerdict = 'Validé' | 'Non validé'
|
|
@@ -35,8 +43,10 @@ export interface EcoCriterion {
|
|
|
35
43
|
|
|
36
44
|
export interface EcoDeclarationOptions {
|
|
37
45
|
root: string
|
|
38
|
-
/** Destination relative to `root` (or absolute). Default: `'src/routes/ecoconception.tsx'
|
|
46
|
+
/** Destination relative to `root` (or absolute). Default: `'<routesDir>/ecoconception.tsx'` (`'src/routes/ecoconception.tsx'`). */
|
|
39
47
|
outPath?: string | undefined
|
|
48
|
+
/** Routes directory relative to `root` (or absolute). Default: `'src/routes'`. */
|
|
49
|
+
routesDir?: string | undefined
|
|
40
50
|
facts: EcoFacts
|
|
41
51
|
service?: string | undefined
|
|
42
52
|
organization?: string | undefined
|
|
@@ -75,34 +85,97 @@ function fill(what: string): string {
|
|
|
75
85
|
return `${STATEMENT_PLACEHOLDER} : ${what}]`
|
|
76
86
|
}
|
|
77
87
|
|
|
88
|
+
function foreignAssetPrefix(assetPrefix: string, site: string | undefined): string | undefined {
|
|
89
|
+
if (!ABSOLUTE_URL_RE.test(assetPrefix))
|
|
90
|
+
return undefined
|
|
91
|
+
const siteOrigin = parseOrigin(site)
|
|
92
|
+
if (siteOrigin !== undefined) {
|
|
93
|
+
const prefixUrl = assetPrefix.startsWith('//') ? `${new URL(siteOrigin).protocol}${assetPrefix}` : assetPrefix
|
|
94
|
+
if (parseOrigin(prefixUrl) === siteOrigin)
|
|
95
|
+
return undefined
|
|
96
|
+
}
|
|
97
|
+
return assetPrefix
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
function checkRuleVerdict(
|
|
101
|
+
files: readonly string[],
|
|
102
|
+
ignored: boolean,
|
|
103
|
+
rule: string,
|
|
104
|
+
validText: string,
|
|
105
|
+
invalidPrefix: string,
|
|
106
|
+
manualPrompt: string,
|
|
107
|
+
): Pick<EcoCriterion, 'verdict' | 'evidence'> {
|
|
108
|
+
if (files.length > 0)
|
|
109
|
+
return { verdict: 'Non validé', evidence: `${invalidPrefix}${files.join(', ')}.` }
|
|
110
|
+
if (ignored)
|
|
111
|
+
return { verdict: undefined, evidence: `La règle ${rule} est ignorée dans prunelle.config.ts (compliance.ignore) ; ${fill(manualPrompt)}.` }
|
|
112
|
+
return { verdict: 'Validé', evidence: validText }
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
function sameDomainVerdict(assetOrigin: string | undefined, externalPages: readonly string[]): Pick<EcoCriterion, 'verdict' | 'evidence'> {
|
|
116
|
+
if (assetOrigin === undefined && externalPages.length === 0) {
|
|
117
|
+
return {
|
|
118
|
+
verdict: 'Validé',
|
|
119
|
+
evidence: 'Les scripts, feuilles de style, polices et images sont servis par le domaine des pages.',
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
if (assetOrigin !== undefined && externalPages.length === 0) {
|
|
123
|
+
return {
|
|
124
|
+
verdict: 'Non validé',
|
|
125
|
+
evidence: `Les scripts et feuilles de style sont servis depuis ${assetOrigin}, un autre domaine que celui des pages.`,
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
const externalNote = `des ressources statiques sont chargées depuis un autre domaine sur : ${externalPages.join(', ')}`
|
|
129
|
+
return {
|
|
130
|
+
verdict: 'Non validé',
|
|
131
|
+
evidence: assetOrigin === undefined
|
|
132
|
+
? `${externalNote[0]!.toUpperCase()}${externalNote.slice(1)}.`
|
|
133
|
+
: `Les scripts et feuilles de style sont servis depuis ${assetOrigin}, un autre domaine que celui des pages ; ${externalNote}.`,
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
78
137
|
/** The RGESN 2024 criteria prunelle can judge, or measure in part, from the build, `prunelle check` and the config. */
|
|
79
138
|
export function evaluateEcoCriteria(facts: EcoFacts): EcoCriterion[] {
|
|
80
139
|
const autoplay = filesWarnedFor(facts.warnings, 'rgesn/autoplay')
|
|
81
140
|
const thirdParty = filesWarnedFor(facts.warnings, 'rgpd/third-party-url')
|
|
141
|
+
const ignored = new Set(facts.ignoredRules ?? [])
|
|
82
142
|
const measured = facts.report.routes.flatMap(r => r.ecoIndex === undefined ? [] : [r.ecoIndex])
|
|
83
143
|
const requests = Math.max(0, ...measured.map(e => e.requests))
|
|
84
144
|
const mostRequests = measured.length === 0 ? '' : ` La page la plus sollicitée fait ${requests} requête${requests > 1 ? 's' : ''} ;`
|
|
85
145
|
const total = facts.report.routes.length
|
|
86
146
|
const noJs = facts.report.routes.filter(r => r.jsGzip === 0).length
|
|
87
|
-
const assetOrigin =
|
|
147
|
+
const assetOrigin = foreignAssetPrefix(facts.assetPrefix, facts.site)
|
|
148
|
+
const externalPages = [...new Set(
|
|
149
|
+
facts.report.routes
|
|
150
|
+
.filter(r => (r.ecoIndex?.external ?? 0) > 0)
|
|
151
|
+
.map(r => r.ecoIndex?.url ?? r.path),
|
|
152
|
+
)].sort()
|
|
88
153
|
return [
|
|
89
154
|
{
|
|
90
155
|
id: '4.1',
|
|
91
156
|
label: 'Le service numérique comporte-t-il uniquement des animations, vidéos et sons dont la lecture automatique est désactivée ?',
|
|
92
157
|
priority: 'Prioritaire',
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
158
|
+
...checkRuleVerdict(
|
|
159
|
+
autoplay,
|
|
160
|
+
ignored.has('rgesn/autoplay'),
|
|
161
|
+
'rgesn/autoplay',
|
|
162
|
+
'Aucune vidéo ni aucun son du code source ne se lance seul (prunelle check, règle rgesn/autoplay).',
|
|
163
|
+
'Une lecture automatique reste dans : ',
|
|
164
|
+
'vérification manuelle de la lecture automatique',
|
|
165
|
+
),
|
|
97
166
|
},
|
|
98
167
|
{
|
|
99
168
|
id: '4.4',
|
|
100
169
|
label: 'Le service numérique permet-il à l\'utilisateur de décider de l\'activation d\'un service tiers ?',
|
|
101
170
|
priority: 'Recommandé',
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
171
|
+
...checkRuleVerdict(
|
|
172
|
+
thirdParty,
|
|
173
|
+
ignored.has('rgpd/third-party-url'),
|
|
174
|
+
'rgpd/third-party-url',
|
|
175
|
+
'Aucune ressource tierce n\'est chargée avant le consentement du visiteur : chacune attend son accord (prunelle check, règle rgpd/third-party-url).',
|
|
176
|
+
'Des ressources tierces se chargent sans consentement dans : ',
|
|
177
|
+
'vérification manuelle des services tiers',
|
|
178
|
+
),
|
|
106
179
|
},
|
|
107
180
|
{
|
|
108
181
|
id: '6.1',
|
|
@@ -132,10 +205,7 @@ export function evaluateEcoCriteria(facts: EcoFacts): EcoCriterion[] {
|
|
|
132
205
|
id: '6.7',
|
|
133
206
|
label: 'Le service numérique héberge-t-il toutes les ressources statiques transférées dont il est l\'émetteur sur un même domaine ?',
|
|
134
207
|
priority: 'Modéré',
|
|
135
|
-
|
|
136
|
-
evidence: assetOrigin === undefined
|
|
137
|
-
? 'Les scripts, feuilles de style, polices et images sont servis par le domaine des pages.'
|
|
138
|
-
: `Les scripts et feuilles de style sont servis depuis ${assetOrigin}, un autre domaine que celui des pages.`,
|
|
208
|
+
...sameDomainVerdict(assetOrigin, externalPages),
|
|
139
209
|
},
|
|
140
210
|
]
|
|
141
211
|
}
|
|
@@ -177,10 +247,11 @@ function criteriaSections(criteria: readonly EcoCriterion[]): string {
|
|
|
177
247
|
/** Generates (and by default writes) a draft RGESN 2024 eco-design declaration page in TSX. */
|
|
178
248
|
export function draftEcoDeclaration(options: EcoDeclarationOptions): EcoDeclarationResult {
|
|
179
249
|
const root = resolve(options.root)
|
|
180
|
-
const
|
|
250
|
+
const routesDir = resolve(root, options.routesDir ?? options.facts.routesDir ?? 'src/routes')
|
|
251
|
+
const dest = options.outPath !== undefined ? resolve(root, options.outPath) : join(routesDir, 'ecoconception.tsx')
|
|
181
252
|
const relativePath = relPosix(root, dest)
|
|
182
253
|
// A second run finds the declaration among the built pages: it is not part of the service it describes.
|
|
183
|
-
const ownPath =
|
|
254
|
+
const ownPath = isInside(routesDir, dest) ? fileToRoutePath(routesDir, dest) : undefined
|
|
184
255
|
const report = { ...options.facts.report, routes: options.facts.report.routes.filter(r => r.path !== ownPath) }
|
|
185
256
|
const criteria = evaluateEcoCriteria({ ...options.facts, report })
|
|
186
257
|
const { iso, human } = formatFrenchDate(options.date ?? new Date())
|
package/src/eco/index.ts
CHANGED
|
@@ -4,14 +4,14 @@ import type { BundleReport } from '../build/report'
|
|
|
4
4
|
import type { EcoCriterion, EcoDeclarationResult, EcoFacts } from './declaration'
|
|
5
5
|
import { parseByteSize } from '../build/byte-size'
|
|
6
6
|
import { loadConfig } from '../plugins/load'
|
|
7
|
-
import {
|
|
7
|
+
import { draftEcoDeclaration, evaluateEcoCriteria } from './declaration'
|
|
8
8
|
|
|
9
9
|
export { DEFAULT_ECO_DECLARATION_PATH, draftEcoDeclaration, evaluateEcoCriteria } from './declaration'
|
|
10
10
|
export type { EcoCriterion, EcoDeclarationOptions, EcoDeclarationResult, EcoFacts, EcoVerdict } from './declaration'
|
|
11
11
|
|
|
12
12
|
export interface EcoRunOptions {
|
|
13
13
|
root: string
|
|
14
|
-
/** Write the declaration page, at this path (`''` for
|
|
14
|
+
/** Write the declaration page, at this path (`''` for `<routesDir>/ecoconception.tsx`). */
|
|
15
15
|
declaration?: string | undefined
|
|
16
16
|
service?: string | undefined
|
|
17
17
|
organization?: string | undefined
|
|
@@ -36,6 +36,9 @@ export async function collectEcoFacts(root: string): Promise<EcoFacts> {
|
|
|
36
36
|
assetPrefix: config.assetPrefix ?? '/_pru',
|
|
37
37
|
compress: config.compress !== false,
|
|
38
38
|
firstLoadBudget: config.budget?.firstLoad === undefined ? undefined : parseByteSize(config.budget.firstLoad),
|
|
39
|
+
site: config.site,
|
|
40
|
+
ignoredRules: config.compliance?.ignore,
|
|
41
|
+
routesDir: config.routesDir,
|
|
39
42
|
}
|
|
40
43
|
}
|
|
41
44
|
|
|
@@ -45,7 +48,8 @@ export async function runEco(options: EcoRunOptions): Promise<EcoRunResult> {
|
|
|
45
48
|
return { criteria: evaluateEcoCriteria(facts) }
|
|
46
49
|
const declaration = draftEcoDeclaration({
|
|
47
50
|
root: options.root,
|
|
48
|
-
outPath: options.declaration === '' ?
|
|
51
|
+
outPath: options.declaration === '' ? undefined : options.declaration,
|
|
52
|
+
routesDir: facts.routesDir,
|
|
49
53
|
facts,
|
|
50
54
|
service: options.service,
|
|
51
55
|
organization: options.organization,
|
package/src/plugins/config.ts
CHANGED
|
@@ -6,20 +6,25 @@ export function defineConfig(config: PrunelleConfig): PrunelleConfig {
|
|
|
6
6
|
return config
|
|
7
7
|
}
|
|
8
8
|
|
|
9
|
-
/** Forwards every runtime key from `prunelle.config.ts`, stripping build/CLI-only keys (`routesDir`, `outDir`, `publicDir`, `port`, `compliance`, `autoPrerender`). */
|
|
10
|
-
export function pickRuntimeConfig(config: PrunelleConfig | undefined): ServerRuntimeConfig {
|
|
11
|
-
if (config === undefined)
|
|
12
|
-
return {}
|
|
13
|
-
const { routesDir: _r, outDir: _o, publicDir: _p, port: _pt, compliance: _c, autoPrerender: _ap, ...runtime } = config
|
|
14
|
-
return runtime
|
|
15
|
-
}
|
|
16
|
-
|
|
17
9
|
// Typed as records so that a key added to the config types without being listed here fails the typecheck.
|
|
18
10
|
const RUNTIME_KEYS: Record<keyof ServerRuntimeConfig, true> = { site: true, lang: true, assetPrefix: true, security: true, trustedOrigins: true, trustProxy: true, maxRequestBodySize: true, navigation: true, streamTimeout: true, consent: true, compress: true, routeCache: true, healthCheck: true, onError: true, plugins: true }
|
|
19
11
|
const BUILD_KEYS: Record<Exclude<keyof PrunelleConfig, keyof ServerRuntimeConfig>, true> = { port: true, routesDir: true, outDir: true, publicDir: true, compliance: true, autoPrerender: true, budget: true }
|
|
12
|
+
const BUILD_KEY_SET = new Set<string>(Object.keys(BUILD_KEYS))
|
|
20
13
|
const RUNTIME_CONFIG_KEYS = Object.keys(RUNTIME_KEYS) as (keyof ServerRuntimeConfig)[]
|
|
21
14
|
const CONFIG_KEYS = [...RUNTIME_CONFIG_KEYS, ...Object.keys(BUILD_KEYS)]
|
|
22
15
|
|
|
16
|
+
/** Forwards every runtime key from `prunelle.config.ts`, stripping build/CLI-only keys (`BUILD_KEYS`). */
|
|
17
|
+
export function pickRuntimeConfig(config: PrunelleConfig | undefined): ServerRuntimeConfig {
|
|
18
|
+
if (config === undefined)
|
|
19
|
+
return {}
|
|
20
|
+
const runtime: Record<string, unknown> = {}
|
|
21
|
+
for (const [key, value] of Object.entries(config)) {
|
|
22
|
+
if (!BUILD_KEY_SET.has(key))
|
|
23
|
+
runtime[key] = value
|
|
24
|
+
}
|
|
25
|
+
return runtime as ServerRuntimeConfig
|
|
26
|
+
}
|
|
27
|
+
|
|
23
28
|
// Edit distance, two neighbours swapped counting as one edit.
|
|
24
29
|
function editDistance(a: string, b: string): number {
|
|
25
30
|
let before: number[] = []
|
package/src/reactivity/store.ts
CHANGED
|
@@ -7,14 +7,26 @@ const RAW = Symbol('prunelle.store.raw')
|
|
|
7
7
|
const OWN_KEYS = Symbol('prunelle.store.keys')
|
|
8
8
|
|
|
9
9
|
// An array method that moves several entries writes each one in turn; batched, its readers see only the finished array, and untracked, an effect calling it does not subscribe to what it writes.
|
|
10
|
-
|
|
11
|
-
|
|
10
|
+
// Search methods read proxied entries, so fall back to the raw array when given an unwrapped object.
|
|
11
|
+
const arrayMethods = new Map<PropertyKey, (this: unknown[], ...args: unknown[]) => unknown>([
|
|
12
|
+
...(['copyWithin', 'fill', 'pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'] as const).map((name) => {
|
|
12
13
|
const method = Array.prototype[name] as (...args: unknown[]) => unknown
|
|
13
14
|
return [name, function (this: unknown[], ...args: unknown[]) {
|
|
14
15
|
return batch(() => untrack(() => method.apply(this, args)))
|
|
15
|
-
}]
|
|
16
|
+
}] as const
|
|
16
17
|
}),
|
|
17
|
-
)
|
|
18
|
+
...(['includes', 'indexOf', 'lastIndexOf'] as const).map((name) => {
|
|
19
|
+
const method = Array.prototype[name] as (...args: unknown[]) => unknown
|
|
20
|
+
return [name, function (this: unknown[], ...args: unknown[]) {
|
|
21
|
+
const res = method.apply(this, args)
|
|
22
|
+
if ((res === -1 || res === false) && typeof args[0] === 'object' && args[0] !== null) {
|
|
23
|
+
args[0] = unwrap(args[0])
|
|
24
|
+
return method.apply(unwrap(this), args)
|
|
25
|
+
}
|
|
26
|
+
return res
|
|
27
|
+
}] as const
|
|
28
|
+
}),
|
|
29
|
+
])
|
|
18
30
|
|
|
19
31
|
const proxyCache = new WeakMap<object, object>()
|
|
20
32
|
const depsCache = new WeakMap<object, Map<PropertyKey, Signal<number>>>()
|
|
@@ -117,9 +129,9 @@ function wrap<T extends object>(target: T): T {
|
|
|
117
129
|
get(obj, key, receiver) {
|
|
118
130
|
if (key === RAW)
|
|
119
131
|
return obj
|
|
120
|
-
const
|
|
121
|
-
if (
|
|
122
|
-
return
|
|
132
|
+
const method = Array.isArray(obj) ? arrayMethods.get(key) : undefined
|
|
133
|
+
if (method !== undefined)
|
|
134
|
+
return method
|
|
123
135
|
if (isTracking()) {
|
|
124
136
|
getDep(obj, key).value
|
|
125
137
|
// A reader of an array's length is walking it (a list loop reads entries untracked), so any entry write reaches it.
|
package/src/server/action.ts
CHANGED
|
@@ -150,28 +150,72 @@ export function isServerAction(value: unknown): value is ServerAction<unknown, u
|
|
|
150
150
|
return typeof value === 'function' && (value as { __pruAction?: boolean }).__pruAction === true
|
|
151
151
|
}
|
|
152
152
|
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
153
|
+
const UNSAFE_NESTED_KEYS = new Set(['__proto__', 'constructor', 'prototype'])
|
|
154
|
+
const MAX_NESTED_DEPTH = 10
|
|
155
|
+
|
|
156
|
+
function isPlainRecord(value: unknown): value is Record<string, unknown> {
|
|
157
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value) && !(value instanceof Blob)
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
function appendFormValue(target: Record<string, unknown>, key: string, value: FormDataEntryValue, forceArray: boolean): void {
|
|
161
|
+
if (!Object.hasOwn(target, key)) {
|
|
162
|
+
setField(target, key, forceArray ? [value] : value)
|
|
163
|
+
return
|
|
164
|
+
}
|
|
165
|
+
const prev = target[key]
|
|
166
|
+
if (Array.isArray(prev))
|
|
167
|
+
prev.push(value)
|
|
168
|
+
else
|
|
169
|
+
setField(target, key, [prev, value])
|
|
170
|
+
}
|
|
157
171
|
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
172
|
+
/** Parses `FormData` into a plain record, mapping trailing `[]` names to arrays and dotted names (`a.b`, `a.b.c`) to nested objects safely. */
|
|
173
|
+
export function parseFormData(formData: FormData): Record<string, unknown> {
|
|
174
|
+
const out: Record<string, unknown> = {}
|
|
175
|
+
for (const [rawKey, val] of formData.entries()) {
|
|
176
|
+
const forceArray = rawKey.length > 2 && rawKey.endsWith('[]')
|
|
177
|
+
const key = forceArray ? rawKey.slice(0, -2) : rawKey
|
|
178
|
+
if (!key.includes('.')) {
|
|
179
|
+
appendFormValue(out, key, val, forceArray)
|
|
180
|
+
continue
|
|
181
|
+
}
|
|
182
|
+
const parts = key.split('.')
|
|
183
|
+
if (parts.some(p => UNSAFE_NESTED_KEYS.has(p)))
|
|
184
|
+
continue
|
|
185
|
+
if (parts.length > MAX_NESTED_DEPTH || parts.some(p => p.length === 0)) {
|
|
186
|
+
appendFormValue(out, key, val, forceArray)
|
|
187
|
+
continue
|
|
188
|
+
}
|
|
189
|
+
let cur = out
|
|
190
|
+
let blocked = false
|
|
191
|
+
for (let i = 0; i < parts.length - 1; i++) {
|
|
192
|
+
const seg = parts[i]!
|
|
193
|
+
if (!Object.hasOwn(cur, seg)) {
|
|
194
|
+
const next: Record<string, unknown> = {}
|
|
195
|
+
setField(cur, seg, next)
|
|
196
|
+
cur = next
|
|
165
197
|
}
|
|
166
|
-
else if (
|
|
167
|
-
|
|
198
|
+
else if (isPlainRecord(cur[seg])) {
|
|
199
|
+
cur = cur[seg]
|
|
168
200
|
}
|
|
169
201
|
else {
|
|
170
|
-
|
|
202
|
+
blocked = true
|
|
203
|
+
break
|
|
171
204
|
}
|
|
172
205
|
}
|
|
173
|
-
|
|
206
|
+
if (!blocked)
|
|
207
|
+
appendFormValue(cur, parts[parts.length - 1]!, val, forceArray)
|
|
174
208
|
}
|
|
209
|
+
return out
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
async function parseActionBody(boundedReq: Request): Promise<unknown> {
|
|
213
|
+
const contentType = (boundedReq.headers.get('content-type') ?? '').toLowerCase()
|
|
214
|
+
if (contentType.includes('application/json'))
|
|
215
|
+
return boundedReq.json()
|
|
216
|
+
|
|
217
|
+
if (contentType.includes('multipart/form-data') || contentType.includes('application/x-www-form-urlencoded'))
|
|
218
|
+
return parseFormData(await boundedReq.formData())
|
|
175
219
|
|
|
176
220
|
return undefined
|
|
177
221
|
}
|
|
@@ -197,10 +241,48 @@ function trustedReferer(request: Request, trustedOrigins: ReadonlySet<string> |
|
|
|
197
241
|
return isTrustedOrigin(refUrl.origin, request, trustedOrigins, trustProxy, requestUrl) ? refUrl : undefined
|
|
198
242
|
}
|
|
199
243
|
|
|
200
|
-
function
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
244
|
+
function issuePathSegments(issue: StandardSchemaIssue): string[] | undefined {
|
|
245
|
+
if (!issue.path || issue.path.length === 0 || issue.path.length > MAX_NESTED_DEPTH)
|
|
246
|
+
return undefined
|
|
247
|
+
const out: string[] = []
|
|
248
|
+
for (const seg of issue.path) {
|
|
249
|
+
const key = typeof seg === 'object' && seg !== null ? seg.key : seg
|
|
250
|
+
if (typeof key !== 'string' || key.length === 0 || (issue.path.length > 1 && UNSAFE_NESTED_KEYS.has(key)))
|
|
251
|
+
return undefined
|
|
252
|
+
out.push(key)
|
|
253
|
+
}
|
|
254
|
+
return out
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
function getAtPath(obj: Record<string, unknown>, path: readonly string[]): { has: boolean, value: unknown } {
|
|
258
|
+
let cur: unknown = obj
|
|
259
|
+
for (let i = 0; i < path.length - 1; i++) {
|
|
260
|
+
if (!isPlainRecord(cur) || !Object.hasOwn(cur, path[i]!))
|
|
261
|
+
return { has: false, value: undefined }
|
|
262
|
+
cur = cur[path[i]!]
|
|
263
|
+
}
|
|
264
|
+
const leaf = path[path.length - 1]!
|
|
265
|
+
if (!isPlainRecord(cur) || !Object.hasOwn(cur, leaf))
|
|
266
|
+
return { has: false, value: undefined }
|
|
267
|
+
return { has: true, value: cur[leaf] }
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
function setAtPath(obj: Record<string, unknown>, path: readonly string[], value: unknown, remove = false): boolean {
|
|
271
|
+
let cur = obj
|
|
272
|
+
for (let i = 0; i < path.length - 1; i++) {
|
|
273
|
+
const seg = path[i]!
|
|
274
|
+
if (!Object.hasOwn(cur, seg) || !isPlainRecord(cur[seg]))
|
|
275
|
+
return false
|
|
276
|
+
const cloned = { ...cur[seg] }
|
|
277
|
+
setField(cur, seg, cloned)
|
|
278
|
+
cur = cloned
|
|
279
|
+
}
|
|
280
|
+
const leaf = path[path.length - 1]!
|
|
281
|
+
if (remove)
|
|
282
|
+
delete cur[leaf]
|
|
283
|
+
else
|
|
284
|
+
setField(cur, leaf, value)
|
|
285
|
+
return true
|
|
204
286
|
}
|
|
205
287
|
|
|
206
288
|
function setField(target: Record<string, unknown>, key: string, value: unknown): void {
|
|
@@ -211,7 +293,7 @@ const ARRAY_WORD_RE = /\barray\b/i
|
|
|
211
293
|
const MISSING_WORD_RE = /\b(?:required|missing|undefined)\b/i
|
|
212
294
|
const NON_ARRAY_TYPE_RE = /\b(?:string|number|boolean|object|file|date|bigint|symbol)\b/i
|
|
213
295
|
|
|
214
|
-
function looksLikeFormArrayMismatch(issue: StandardSchemaIssue,
|
|
296
|
+
function looksLikeFormArrayMismatch(issue: StandardSchemaIssue, hasValue: boolean): boolean {
|
|
215
297
|
const meta = issue as { code?: unknown, expected?: unknown, type?: unknown }
|
|
216
298
|
if (typeof meta.expected === 'string')
|
|
217
299
|
return ARRAY_WORD_RE.test(meta.expected)
|
|
@@ -226,40 +308,55 @@ function looksLikeFormArrayMismatch(issue: StandardSchemaIssue, body: Record<str
|
|
|
226
308
|
if (ARRAY_WORD_RE.test(issue.message))
|
|
227
309
|
return true
|
|
228
310
|
// An unchecked checkbox group is omitted from FormData; generic "Required"/"missing" messages without a non-array type may be expecting [].
|
|
229
|
-
return !
|
|
311
|
+
return !hasValue && MISSING_WORD_RE.test(issue.message) && !NON_ARRAY_TYPE_RE.test(issue.message)
|
|
230
312
|
}
|
|
231
313
|
|
|
232
|
-
// A form sends one checked box as a single value and none as nothing, so a field the schema wants as an array fails. Each failing
|
|
314
|
+
// A form sends one checked box as a single value and none as nothing, so a field the schema wants as an array fails. Each failing field whose issue looks like a missing/non-array type mismatch is retried as an array, and the array is kept only where it clears that field's issue.
|
|
233
315
|
async function retryWithFormArrays(schema: StandardSchemaV1, body: Record<string, unknown>, failed: ValidationFailure): Promise<ValidationResult<unknown>> {
|
|
234
|
-
const retried = { ...body }
|
|
235
|
-
const wrapped
|
|
316
|
+
const retried: Record<string, unknown> = { ...body }
|
|
317
|
+
const wrapped = new Map<string, string[]>()
|
|
236
318
|
for (const issue of failed.issues) {
|
|
237
|
-
const
|
|
238
|
-
if (
|
|
319
|
+
const path = issuePathSegments(issue)
|
|
320
|
+
if (path === undefined)
|
|
239
321
|
continue
|
|
240
|
-
|
|
322
|
+
const pathKey = path.join('.')
|
|
323
|
+
if (wrapped.has(pathKey))
|
|
241
324
|
continue
|
|
242
|
-
|
|
243
|
-
|
|
325
|
+
const current = getAtPath(retried, path)
|
|
326
|
+
if (Array.isArray(current.value) || !looksLikeFormArrayMismatch(issue, current.has))
|
|
327
|
+
continue
|
|
328
|
+
if (setAtPath(retried, path, current.has ? [current.value] : []))
|
|
329
|
+
wrapped.set(pathKey, path)
|
|
244
330
|
}
|
|
245
|
-
if (wrapped.
|
|
331
|
+
if (wrapped.size === 0)
|
|
246
332
|
return failed
|
|
247
333
|
const second = await validateSchema(schema, retried)
|
|
248
334
|
if (second.ok)
|
|
249
335
|
return second
|
|
250
|
-
const stillFailing = new Set(second.issues.map(
|
|
251
|
-
const kept = wrapped.filter(
|
|
336
|
+
const stillFailing = new Set(second.issues.map(i => issuePathSegments(i)?.join('.')))
|
|
337
|
+
const kept = [...wrapped.keys()].filter(k => !stillFailing.has(k))
|
|
252
338
|
if (kept.length === 0)
|
|
253
339
|
return failed
|
|
254
|
-
for (const
|
|
255
|
-
if (kept.includes(
|
|
340
|
+
for (const [pathKey, path] of wrapped) {
|
|
341
|
+
if (kept.includes(pathKey))
|
|
256
342
|
continue
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
343
|
+
const orig = getAtPath(body, path)
|
|
344
|
+
setAtPath(retried, path, orig.value, !orig.has)
|
|
345
|
+
}
|
|
346
|
+
return kept.length === wrapped.size ? second : validateSchema(schema, retried)
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
function flattenFlashBody(rawBody: unknown, prefix = '', out: Record<string, unknown> = Object.create(null), depth = 0): unknown {
|
|
350
|
+
if (!isPlainRecord(rawBody) || depth > MAX_NESTED_DEPTH)
|
|
351
|
+
return depth === 0 ? rawBody : out
|
|
352
|
+
for (const [k, v] of Object.entries(rawBody)) {
|
|
353
|
+
const full = prefix === '' ? k : `${prefix}.${k}`
|
|
354
|
+
if (typeof v === 'string')
|
|
355
|
+
setField(out, full, v)
|
|
356
|
+
else if (isPlainRecord(v))
|
|
357
|
+
flattenFlashBody(v, full, out, depth + 1)
|
|
261
358
|
}
|
|
262
|
-
return
|
|
359
|
+
return out
|
|
263
360
|
}
|
|
264
361
|
|
|
265
362
|
/** Programmatic action invocation with Standard Schema validation (used by `ServerPluginAPI.invokeAction` inside middleware chains). */
|
|
@@ -325,7 +422,7 @@ export async function executeAction(
|
|
|
325
422
|
const back = json ? undefined : trustedReferer(request, trustedOrigins, trustProxy, ctx.url)
|
|
326
423
|
if (back === undefined)
|
|
327
424
|
return undefined
|
|
328
|
-
ctx.cookies.set(ACTION_ERROR_COOKIE, buildActionErrorFlash(act.url, error, fieldErrors, rawBody, flashAllowlist(act)), {
|
|
425
|
+
ctx.cookies.set(ACTION_ERROR_COOKIE, buildActionErrorFlash(act.url, error, fieldErrors, flattenFlashBody(rawBody), flashAllowlist(act)), {
|
|
329
426
|
httpOnly: true,
|
|
330
427
|
sameSite: 'lax',
|
|
331
428
|
maxAge: 60,
|