prunelle 0.7.3 → 0.7.4
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 +3 -3
- package/package.json +1 -1
- package/src/a11y/index.ts +9 -2
- package/src/build/index.ts +29 -30
- package/src/build/prerender.ts +29 -13
- package/src/build/static.ts +24 -2
- package/src/cli/check-forms.ts +16 -6
- package/src/cli/check-links.ts +12 -9
- package/src/cli/check-security.ts +75 -8
- package/src/cli/commands.ts +3 -3
- package/src/cli/upgrade.ts +36 -3
- package/src/compiler/dom.ts +41 -15
- package/src/compiler/ssr-helpers.ts +45 -21
- package/src/compiler/ssr.ts +32 -16
- package/src/context.ts +2 -0
- package/src/dev/error-log.ts +1 -1
- package/src/dom/attrs.ts +1 -1
- package/src/jsx-runtime.ts +1 -1
- package/src/reactivity/index.ts +14 -2
- package/src/server/assets.ts +22 -4
- package/src/server/consent.ts +7 -2
- package/src/server/cookies.ts +8 -1
- package/src/server/errors.ts +57 -26
- package/src/server/rate-limit.ts +36 -12
- package/src/server/route-cache.ts +9 -10
- package/src/server/route-table.ts +14 -2
- package/src/server/router.ts +4 -4
- package/src/server/sanitize-html.ts +21 -7
- package/src/server/security.ts +13 -3
- package/src/server/static-dir.ts +3 -10
- package/src/ssr/consent-banner.ts +3 -1
- package/src/ssr/context.ts +85 -2
- package/src/ssr/index.ts +16 -4
- package/src/style.ts +9 -7
- package/src/unrenderable.ts +15 -5
package/llms.txt
CHANGED
|
@@ -61,7 +61,7 @@
|
|
|
61
61
|
- **Config (`prunelle.config.ts`)**: `defineConfig({ site, lang, port, routesDir, outDir, publicDir, assetPrefix, security, trustedOrigins, trustProxy, maxRequestBodySize, navigation, routeCache, autoPrerender, streamTimeout, consent, compliance, budget, compress, healthCheck, onError, plugins })`. `trustProxy: true | number` trusts that many right-most proxy hops for `X-Forwarded-*` (an https `site` makes cookies `Secure` and sends HSTS without it; production warns once on `X-Forwarded-Proto` while it is off, and once on the first POST refused as `untrusted origin`, naming the Origin, the origin the server computed, `trustProxy` and `trustedOrigins`); `prunelle start` in production notices when it binds loopback (the default; `HOST` or `--host 0.0.0.0` opens it for a container); `maxRequestBodySize` defaults to `1 MiB`. `lang` sets `<html lang>` and the language of `@prunellejs/ui`'s built-in labels (`'fr'` or `'fr-*'` gives French ones); with no `lang` and no `@prunellejs/i18n`, `prunelle check` warns `rgaa/document-lang`.
|
|
62
62
|
- **Security headers & CSP**: on by default (`security: false` disables them, or override `csp`, `hsts`, `frameOptions`, `referrerPolicy`, `contentTypeOptions`, `permissionsPolicy`, `crossOriginOpenerPolicy`, `crossOriginResourcePolicy`; the last two default to `same-origin`, and every header also goes on the build-swap `503`). `prunelle check` warns on `security: false`, `csp: false`, `'unsafe-inline'` in a script or style directive and `export const csrf = false` (`security/headers-off`, `csp-off`, `unsafe-inline`, `csrf-off`). The strict `DEFAULT_CSP` (style attributes allowed) gets automatic SHA-256 hashes for island/Suspense styles, the app's own `<style>` blocks and stream scripts; `HSTS` is sent on HTTPS requests.
|
|
63
63
|
- `security: { csp: { 'style-src': [...], 'font-src': [...] } }` (or `extendCsp()` / `DEFAULT_CSP` from `prunelle/server`) adds sources to single directives without copying the whole policy; a new `*-src` directive inherits `default-src`, and automatic hashes still land in the extended directives.
|
|
64
|
-
- A `--static` export embeds each page's and `404.html`'s hashed CSP in `<meta http-equiv="Content-Security-Policy">` with `frame-ancestors`, `report-uri` and `sandbox` stripped (browsers ignore them in `<meta>`): the build writes the headers that cannot live there from `security` into `dist/_headers` (Netlify, Cloudflare Pages), `dist/prunelle.caddy` (`import` it in a site block) and `dist/prunelle.nginx.conf` (`include` it in a server block), with the exact-path rules of `dist/_redirects` (written by `@prunellejs/seo` `redirects`, or shipped in `public/`) as `redir` and `location =` lines; a file the app ships under those names is kept, and `security: false`
|
|
64
|
+
- A `--static` export embeds each page's and `404.html`'s hashed CSP in `<meta http-equiv="Content-Security-Policy">` with `frame-ancestors`, `report-uri` and `sandbox` stripped (browsers ignore them in `<meta>`): the build writes the headers that cannot live there from `security` into `dist/_headers` (Netlify, Cloudflare Pages), `dist/prunelle.caddy` (`import` it in a site block) and `dist/prunelle.nginx.conf` (`include` it in a server block), with the exact-path rules of `dist/_redirects` (written by `@prunellejs/seo` `redirects`, or shipped in `public/`) as `redir` and `location =` lines; a file the app ships under those names is kept, and `security: false` skips `_headers` while keeping comment-only `prunelle.caddy` / `prunelle.nginx.conf` (plus any `_redirects` rules) so existing includes do not fail.
|
|
65
65
|
- **Observability**: the Bun server (not a `--static` export served by `prunelle start`) answers `/_pru/health` (at `${assetPrefix}/health`): `200 { ok: true }`, or `503` when the app's `healthCheck` or a plugin's `api.healthCheck(name, fn)` fails or takes over 5 s (cached for 5 s; a failure reads `check failed`, the error goes to stderr, `prunelle dev` shows it); `./app --health` probes it for a container `HEALTHCHECK`. Every request gets `ctx.requestId` (honoring a safe incoming `x-request-id` when `trustProxy` is truthy), returned in `x-request-id` and passed to `onError` as `info.requestId`. `prunelle dev` sends `Server-Timing` (`middleware`, `load`, `render`, `stream`; zero overhead in production).
|
|
66
66
|
- **Server helpers (`prunelle/server`)**:
|
|
67
67
|
- `defineEnv(standardSchema)` validates env vars at startup. `nodeEnv()` is safe in `--compile`: server code reads it, never `process.env.NODE_ENV`, which `prunelle build` leaves unset for a prerendered page (build and `prunelle check` warn on such a read outside island code).
|
|
@@ -79,7 +79,7 @@
|
|
|
79
79
|
- `rgpd/privacy-notice`: a `.tsx` file in `src/` with an `<input>` collecting an email or a phone number (`type="email|tel"` or `name="email|phone|tel"`) while the app has no `/privacy`, `/confidentialite`, `/politique-de-confidentialite` or localized variant, or a privacy notice still holding a `[to fill in` placeholder. The `app` template ships `/privacy` and links it under its sign-up form.
|
|
80
80
|
- Silence per rule with `compliance: { ignore: [...], legalNotice?: string | false, privacyNotice?: string | false, publicBody?: boolean }`, or `// prunelle-ignore <rule>` / `/* prunelle-ignore <rule> */` / `// prunelle-ignore-file <rule>`. The form check's warnings (`action/unguarded-public-form`, `form/invalid-option`, `form/schema-unsupported`, `form/unchecked` for an action module that fails to import) are silenced the same way, the comment going on the line above the `<form>` or `<option>`; its errors cannot be.
|
|
81
81
|
- One-declaration consent: `consent: { categories: ['analytics', 'media'] | { analytics: 'Audience measurement' }, cookieName?: 'pru_consent', maxAge?: 15552000, endpoint?: '/_pru/consent', version?: '2026-11' }` wires a CSRF-protected `POST /_pru/consent` endpoint (a zero-JS `<form method="post" action="/_pru/consent">` with `action="accept-all"|"reject-all"` or category checkboxes, `name="categories" value="analytics"` or `name="analytics"`, gets a `303`, JSON a `200`), exposes `ctx.consent` (`decided`, `decidedAt`, `categories`, `labels`, `endpoint`, `has(cat)`, `all()`), refuses `ctx.cookies.set(name, val, { category })` before consent is granted, and exports server-only `<ConsentGate category="media" fallback={...}>` (0 KB browser JS, refused inside islands). The cookie stores the time of the choice and `version`: changing `version` asks every visitor again. `prunelle check` warns (`rgpd/consent-retention`) when `maxAge` is past 180 days, and `prunelle dev` warns once per cookie set with no `category`, which counts as essential.
|
|
82
|
-
- `<ConsentBanner policyHref?="/cookies" title? accept? refuse? choose? save? legend?>{text?}</ConsentBanner>` renders, until the visitor decides, a form with Refuse all and Accept all side by side and the categories (by label) behind a `<details>`; `<ConsentPreferences />` renders the choice in force, to change or withdraw it (put it on the cookie policy page). Both are server-only, private on a cached route, and throw `prunelle: <ConsentBanner> has no consent category to ask about` without `consent.categories`. Markup: `data-ui="consent"` with `data-part` `title`, `body`, `form`, `actions`, `details`, `choices`, `choice`, `preferences`; buttons carry `data-ui="button"`.
|
|
82
|
+
- `<ConsentBanner policyHref?="/cookies" policyLabel? title? accept? refuse? choose? save? legend?>{text?}</ConsentBanner>` renders, until the visitor decides, a form with Refuse all and Accept all side by side and the categories (by label) behind a `<details>`; `<ConsentPreferences />` renders the choice in force, to change or withdraw it (put it on the cookie policy page). Both are server-only, private on a cached route, and throw `prunelle: <ConsentBanner> has no consent category to ask about` without `consent.categories`. Markup: `data-ui="consent"` with `data-part` `title`, `body`, `form`, `actions`, `details`, `choices`, `choice`, `preferences`; buttons carry `data-ui="button"`.
|
|
83
83
|
- **Page changes (plain multi-page navigation, 0 B of JS)**: every page carries inline, CSP-hashed `@view-transition { navigation: auto }` (inside `@media (prefers-reduced-motion: no-preference)`) and a `<script type="speculationrules">` prefetching same-origin links on press (`eagerness: conservative`); it never links to another origin, `/_pru/*` (actions included), `[download]`, `[rel~=nofollow]`, nor a link or ancestor with `data-pru-no-prefetch`. Name an element that stays still with CSS `view-transition-name`.
|
|
84
84
|
- `defineConfig({ navigation: { viewTransitions?: boolean (true), prefetch?: 'conservative' | 'moderate' | 'eager' | false ('conservative'), prerender?: 'conservative' | 'moderate' | 'eager' | boolean (false; true is 'moderate'; it runs `load()` of pages nobody opens) } })`; a bad value throws `prunelle: navigation.<key> is ...`.
|
|
85
85
|
- `data-pru-keep-scroll="<key>"` on a scrolling element keeps its `scrollTop` across page loads (restored before first paint when the next page has the same key; per history entry on back/forward/reload; a no-op when `sessionStorage` is blocked), through one inline hashed script at the end of `<body>` on pages using the attribute. The key is a literal string without `"<>&` (compile error otherwise, also for a nested panel of the same key); the same key on two elements of one rendered page throws `prunelle: data-pru-keep-scroll="..." is on two elements of one page`. `@prunellejs/spa` keeps the same attribute across its swaps.
|
|
@@ -114,7 +114,7 @@
|
|
|
114
114
|
- `api.rateLimiter({ max, windowMs })` returns a limiter in the server's store (bounded to 10 000 keys and 1 000 000 hits, swept every minute, dropped with the server) for a limit a route option cannot key, such as per email: `hit(key)` returns 0, or the whole seconds to wait; `peek(key)` answers the same without counting, to check a limit that only some outcomes count.
|
|
115
115
|
- Build hooks: `build(ctx)` (`emitAsset`, `emitPublic`, `addStyle`, `addRouteStyle`, `addHead`, `addRouteHead`, `provide`, `inject`, `setData`, `routes`), `afterPrerender(ctx)` (`routes`, `publicFiles`, `assets`, `emitAsset`, `emitPublic`, `setData`), `transform`, `bunPlugins` (array or `({ root, assetPrefix, minify, target, lang }) => [...]`), `css`, `prerenderPaths`, `clientEntry`, `regionClientEntry`, `watchPaths`, `commands`.
|
|
116
116
|
- Page hooks: `head(head, ctx)`, `transformHtml`, `inlineScripts` (the inline scripts the plugin writes into pages, each as it stands between its tags: every page's CSP allows them by hash, since prunelle never hashes a script it finds in a page), `onError(info)` (`{ error, request, source, requestId }`), `check(ctx)`.
|
|
117
|
-
- `requires({ root, site, consentCategories })` returns one message per setting the plugin needs in production, naming it and its fix: a production start (`NODE_ENV=production`, not `prunelle dev`) refuses while any is unmet, listing them all; `prunelle dev`, tests and `prunelle check` warn once each; a throwing `requires` counts as unmet. First-party: auth refuses an in-memory store, jobs an in-memory DB, files `memoryFiles()` or a missing signing secret, mail a missing transport or `from`, mcp a missing `token`, seo and a content feed a missing `site`, analytics a consent category `consent.categories` does not declare.
|
|
117
|
+
- `requires({ root, site, consentCategories })` returns one message per setting the plugin needs in production, naming it and its fix: a production start (`NODE_ENV=production`, not `prunelle dev`) refuses while any is unmet, listing them all; `prunelle dev`, tests and `prunelle check` warn once each; a throwing `requires` counts as unmet. First-party: auth refuses an in-memory store, a missing or short `secret`, or a missing `mailer` when `requireEmailVerification` is on, jobs an in-memory DB, files `memoryFiles()` or a missing signing secret, mail a missing transport or `from`, mcp a missing `token`, seo and a content feed a missing `site`, analytics a consent category `consent.categories` does not declare.
|
|
118
118
|
- Runtime state (timers, connections, caches) is created in `server(api)` and released in `api.onShutdown()`, never in the plugin factory: `prunelle dev` starts the next server on the same instance before shutting the last one down, and a new process on a `prunelle.config.ts` edit. A throwing `onShutdown` or `onError` hook is logged with its plugin's name; the others still run.
|
|
119
119
|
- First-party packages (19 total with `prunelle`), each with its full reference:
|
|
120
120
|
- `@prunellejs/ui` (`node_modules/@prunellejs/ui/llms.txt`): zero-JS layout, form and overlay primitives, island widgets (`Tabs`, `Menu`, `Select`, `CommandPalette`, `DataTable`, `toast()`), `@layer kui` Style Grammars, `prunelle ui-eject`.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "prunelle",
|
|
3
|
-
"version": "0.7.
|
|
3
|
+
"version": "0.7.4",
|
|
4
4
|
"description": "Bun-native TSX web framework with zero-directive automatic islands, fine-grained signals, and single-binary deploys",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"homepage": "https://prunelle.kaynooo.fr",
|
package/src/a11y/index.ts
CHANGED
|
@@ -410,9 +410,16 @@ async function runA11yCommand(args: string[], root: string, pluginOptions: A11yP
|
|
|
410
410
|
return badUsage('--status is gone: the compliance level follows the manual audit, so pass --audit-date YYYY-MM-DD and --rate <percent> (100 is totally, 50 or more partially compliant)')
|
|
411
411
|
if ((values['audit-date'] === undefined) !== (values.rate === undefined))
|
|
412
412
|
return badUsage('--audit-date and --rate go together: pass the day the manual RGAA audit ended and the percentage of criteria it found met')
|
|
413
|
-
const
|
|
414
|
-
|
|
413
|
+
const rawRate = values.rate?.trim()
|
|
414
|
+
const manualAudit = values['audit-date'] !== undefined && rawRate !== undefined
|
|
415
|
+
? { date: new Date(`${values['audit-date']}T00:00:00Z`), rate: rawRate === '' ? Number.NaN : Number(rawRate) }
|
|
415
416
|
: undefined
|
|
417
|
+
if (manualAudit !== undefined) {
|
|
418
|
+
if (Number.isNaN(manualAudit.date.getTime()))
|
|
419
|
+
return badUsage('--audit-date must be a valid YYYY-MM-DD date, e.g. --audit-date 2026-03-31')
|
|
420
|
+
if (!(manualAudit.rate >= 0 && manualAudit.rate <= 100))
|
|
421
|
+
return badUsage(`--rate must be a percentage from 0 to 100, got "${values.rate}"`)
|
|
422
|
+
}
|
|
416
423
|
|
|
417
424
|
const wantDraft = values.draft !== undefined
|
|
418
425
|
const force = values.force === true
|
package/src/build/index.ts
CHANGED
|
@@ -38,7 +38,7 @@ import { parseByteSize } from './byte-size'
|
|
|
38
38
|
import { SERVER_ENTRY_FILE, serverEntrySource } from './server-entry'
|
|
39
39
|
import { PRUNELLE_SRC_ROOT, resolvePrunelleSpecifier } from './resolve'
|
|
40
40
|
import { ancestorFiles, assertNoRouteConflicts, discoverRouteMatchers, fileToRoutePath, hasRouteHandlerExport, missingPathsProblem, normalizeRoutePattern, routeExportProblem, routeFileProblem, SPECIAL_ROUTE_FILES } from './routes'
|
|
41
|
-
import { emitStaticNotFoundPages, exportStatic } from './static'
|
|
41
|
+
import { emitStaticNotFoundPages, exportStatic, normalizeAssetPrefix } from './static'
|
|
42
42
|
import { findUnknownStatusPages } from './status-pages'
|
|
43
43
|
import { consolidateStylesheets } from './style-bundles'
|
|
44
44
|
|
|
@@ -175,7 +175,7 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
|
|
|
175
175
|
const stageSuffix = processSuffix()
|
|
176
176
|
const stageDir = stageDirFor(finalOutDir, stageSuffix)
|
|
177
177
|
const outDir = options.static ? join(cacheBaseDir, `${STATIC_STAGE_PREFIX}${stageSuffix}`) : stageDir
|
|
178
|
-
const assetPrefix = (options.assetPrefix ?? fileConfig.assetPrefix ?? '/_pru')
|
|
178
|
+
const assetPrefix = normalizeAssetPrefix(options.assetPrefix ?? fileConfig.assetPrefix ?? '/_pru')
|
|
179
179
|
assertOwnOutDir(root, finalOutDir, assetPrefix)
|
|
180
180
|
removeStaleStages(finalOutDir)
|
|
181
181
|
removeDeadProcessDirs(cacheBaseDir, STATIC_STAGE_PREFIX)
|
|
@@ -194,28 +194,9 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
|
|
|
194
194
|
|
|
195
195
|
try {
|
|
196
196
|
return await runWithAppContext(appCtx, () => runBuild({
|
|
197
|
-
options,
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
routesDir,
|
|
201
|
-
publicDir,
|
|
202
|
-
finalOutDir,
|
|
203
|
-
stageDir,
|
|
204
|
-
outDir,
|
|
205
|
-
stageSuffix,
|
|
206
|
-
assetPrefix,
|
|
207
|
-
site,
|
|
208
|
-
lang: options.lang ?? fileConfig.lang,
|
|
209
|
-
budget: resolveBudget(options.maxJs, fileConfig.budget),
|
|
210
|
-
defaultPort: fileConfig.port,
|
|
211
|
-
compliance: fileConfig.compliance,
|
|
212
|
-
consentMaxAge: fileConfig.consent?.maxAge,
|
|
213
|
-
autoPrerender: options.autoPrerender ?? fileConfig.autoPrerender ?? false,
|
|
214
|
-
minify: options.minify ?? true,
|
|
215
|
-
isDev,
|
|
216
|
-
nodeEnv: effectiveNodeEnv,
|
|
217
|
-
appCtx,
|
|
218
|
-
publicFiles,
|
|
197
|
+
options, root, plugins: resolvePlugins(options.plugins ?? fileConfig.plugins), routesDir, publicDir, finalOutDir, stageDir, outDir, stageSuffix, assetPrefix, site,
|
|
198
|
+
lang: options.lang ?? fileConfig.lang, budget: resolveBudget(options.maxJs, fileConfig.budget), defaultPort: fileConfig.port, compliance: fileConfig.compliance,
|
|
199
|
+
consentMaxAge: fileConfig.consent?.maxAge, autoPrerender: options.autoPrerender ?? fileConfig.autoPrerender ?? false, minify: options.minify ?? true, isDev, nodeEnv: effectiveNodeEnv, appCtx, publicFiles,
|
|
219
200
|
}))
|
|
220
201
|
}
|
|
221
202
|
finally {
|
|
@@ -369,15 +350,33 @@ function copyPublicFiles(publicDir: string, outPublicDir: string, publicFiles: P
|
|
|
369
350
|
}
|
|
370
351
|
}
|
|
371
352
|
|
|
372
|
-
function collectNonEmptyClientAssets(
|
|
353
|
+
function collectNonEmptyClientAssets(
|
|
354
|
+
clientDir: string,
|
|
355
|
+
assetPrefix: string,
|
|
356
|
+
client: { assetFiles: readonly string[], srcCssToUrl: Map<string, string>, islandCssUrl: Map<string, string>, styleUrls: string[] },
|
|
357
|
+
): { assets: string[], builtClientAssets: Set<string> } {
|
|
373
358
|
const assets: string[] = []
|
|
374
|
-
|
|
359
|
+
const dropped = new Set<string>()
|
|
360
|
+
for (const rel of client.assetFiles) {
|
|
375
361
|
const abs = join(clientDir, rel)
|
|
376
362
|
const size = fileSize(abs)
|
|
377
|
-
if (size === 0)
|
|
378
|
-
|
|
379
|
-
|
|
363
|
+
if (size === 0 || size === undefined) {
|
|
364
|
+
if (size === 0)
|
|
365
|
+
rmSync(abs, { force: true })
|
|
366
|
+
dropped.add(`${assetPrefix}/${rel}`)
|
|
367
|
+
}
|
|
368
|
+
else {
|
|
380
369
|
assets.push(rel)
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
if (dropped.size > 0) {
|
|
373
|
+
for (const map of [client.srcCssToUrl, client.islandCssUrl]) {
|
|
374
|
+
for (const [k, url] of map) {
|
|
375
|
+
if (dropped.has(url))
|
|
376
|
+
map.delete(k)
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
client.styleUrls = client.styleUrls.filter(url => !dropped.has(url))
|
|
381
380
|
}
|
|
382
381
|
return { assets, builtClientAssets: new Set(assets) }
|
|
383
382
|
}
|
|
@@ -475,7 +474,7 @@ async function runBuild(run: BuildRun): Promise<BuildManifest> {
|
|
|
475
474
|
if (options.cache !== undefined)
|
|
476
475
|
refreshCacheWatches(options.cache, graph, [...pluginCssFiles, ...(hasConfigFile ? [configSrc] : [])])
|
|
477
476
|
|
|
478
|
-
const { assets, builtClientAssets } = collectNonEmptyClientAssets(clientDir, client
|
|
477
|
+
const { assets, builtClientAssets } = collectNonEmptyClientAssets(clientDir, assetPrefix, client)
|
|
479
478
|
|
|
480
479
|
const { routes, statusPages, globalStyles, routeSourceFiles, globalSourceFiles } = buildRouteEntries({
|
|
481
480
|
graph, islands, islandChunks: client.islandChunks, srcCssToUrl: client.srcCssToUrl, islandCssUrl: client.islandCssUrl,
|
package/src/build/prerender.ts
CHANGED
|
@@ -36,25 +36,27 @@ function extForContentType(contentType: string | null): string {
|
|
|
36
36
|
return CONTENT_TYPE_EXT[mime] ?? ''
|
|
37
37
|
}
|
|
38
38
|
|
|
39
|
-
function assertSafePrerenderPath(raw: string, original: string): string {
|
|
39
|
+
function assertSafePrerenderPath(raw: string, original: string, routeLabel: string): string {
|
|
40
40
|
const decoded = decodeRequestPath(raw)
|
|
41
41
|
if (decoded?.staticPath === undefined)
|
|
42
|
-
throw new Error(`prunelle build: unsafe or malformed prerender path "${original}".`)
|
|
42
|
+
throw new Error(`prunelle build: unsafe or malformed prerender path "${original}" from ${routeLabel}.`)
|
|
43
43
|
if (decoded.staticPath.split('/').some(seg => seg === '..' || seg.includes('\\') || seg.includes('\0')))
|
|
44
|
-
throw new Error(`prunelle build: prerender path "${original}" escapes output directory.`)
|
|
44
|
+
throw new Error(`prunelle build: prerender path "${original}" from ${routeLabel} escapes output directory.`)
|
|
45
45
|
return decoded.staticPath
|
|
46
46
|
}
|
|
47
47
|
|
|
48
|
-
function normalizePrerenderUrl(urlStr: string): string {
|
|
49
|
-
|
|
48
|
+
function normalizePrerenderUrl(urlStr: string, routeLabel: string): string {
|
|
49
|
+
if (urlStr.includes('?') || urlStr.includes('#'))
|
|
50
|
+
throw new Error(`prunelle build: prerender path "${urlStr}" from ${routeLabel} cannot contain "?" or "#": percent-encode it (e.g. %3F or %23) or remove the query/hash.`)
|
|
51
|
+
assertSafePrerenderPath(urlStr, urlStr, routeLabel)
|
|
50
52
|
let pathname: string
|
|
51
53
|
try {
|
|
52
54
|
pathname = new URL(urlStr, 'http://localhost').pathname
|
|
53
55
|
}
|
|
54
56
|
catch {
|
|
55
|
-
throw new Error(`prunelle build: invalid prerender path "${urlStr}".`)
|
|
57
|
+
throw new Error(`prunelle build: invalid prerender path "${urlStr}" from ${routeLabel}.`)
|
|
56
58
|
}
|
|
57
|
-
const staticPath = assertSafePrerenderPath(pathname, urlStr)
|
|
59
|
+
const staticPath = assertSafePrerenderPath(pathname, urlStr, routeLabel)
|
|
58
60
|
return staticPath.length > 1 && staticPath.endsWith('/') ? (staticPath.replace(TRAILING_SLASHES_RE, '') || '/') : staticPath
|
|
59
61
|
}
|
|
60
62
|
|
|
@@ -107,11 +109,15 @@ export interface PrerenderOptions {
|
|
|
107
109
|
|
|
108
110
|
const ROUTE_SOURCE_EXTENSIONS = ['.tsx', '.ts', '.jsx', '.js', '.mdx', '.md']
|
|
109
111
|
|
|
110
|
-
// The source file of a built route module (`server/posts/[slug].js` is `src/routes/posts/[slug].tsx`)
|
|
112
|
+
// The source file of a built route module (`server/posts/[slug].js` or `server/src/routes/posts/[slug].js` is `src/routes/posts/[slug].tsx`).
|
|
111
113
|
function routeSource(options: PrerenderOptions, route: RouteManifestEntry): string {
|
|
112
|
-
const
|
|
113
|
-
const
|
|
114
|
-
|
|
114
|
+
const stripped = route.file.replace(/^server\//, '').replace(/\.js$/, '')
|
|
115
|
+
for (const base of [options.routesDir, options.root]) {
|
|
116
|
+
const source = ROUTE_SOURCE_EXTENSIONS.map(ext => `${join(base, stripped)}${ext}`).find(file => existsSync(file))
|
|
117
|
+
if (source !== undefined)
|
|
118
|
+
return relPosix(options.root, source)
|
|
119
|
+
}
|
|
120
|
+
return route.file
|
|
115
121
|
}
|
|
116
122
|
|
|
117
123
|
// The build fails through the CLI, which prints only the message: the page's own error and its stack go in it.
|
|
@@ -175,7 +181,8 @@ async function planRoutes(options: PrerenderOptions, modules: Record<string, unk
|
|
|
175
181
|
urls = await runPluginHook(plugin, 'prerenderPaths', () => plugin.prerenderPaths!(urls, route))
|
|
176
182
|
}
|
|
177
183
|
|
|
178
|
-
|
|
184
|
+
const routeLabel = `"${route.path}" (${routeSource(options, route)})`
|
|
185
|
+
urls = [...new Set(urls.map(u => normalizePrerenderUrl(u, routeLabel)))]
|
|
179
186
|
|
|
180
187
|
if (urls.length === 0) {
|
|
181
188
|
if (hasPathsFn)
|
|
@@ -205,6 +212,7 @@ export async function prerender(options: PrerenderOptions) {
|
|
|
205
212
|
try {
|
|
206
213
|
const routePlans = await planRoutes(options, entry?.modules)
|
|
207
214
|
const allTasks = routePlans.flatMap(plan => plan.tasks)
|
|
215
|
+
const claimedFiles = new Map<string, { url: string, source: string }>()
|
|
208
216
|
let nextIdx = 0
|
|
209
217
|
let failed = false
|
|
210
218
|
const runWorker = async (): Promise<void> => {
|
|
@@ -231,6 +239,14 @@ export async function prerender(options: PrerenderOptions) {
|
|
|
231
239
|
}
|
|
232
240
|
const ct = res.headers.get('content-type')
|
|
233
241
|
const absOut = resolvePrerenderPath(prerenderDir, u, isStatic, ct)
|
|
242
|
+
const relOut = relPosix(isStatic ? prerenderDir : outDir, absOut)
|
|
243
|
+
const source = routeSource(options, task.route)
|
|
244
|
+
const prev = claimedFiles.get(absOut)
|
|
245
|
+
if (prev !== undefined) {
|
|
246
|
+
failed = true
|
|
247
|
+
throw new Error(`prunelle build: prerendered file "${relOut}" is written by both "${prev.url}" (${prev.source}) and "${u}" (${source}).`)
|
|
248
|
+
}
|
|
249
|
+
claimedFiles.set(absOut, { url: u, source })
|
|
234
250
|
mkdirSync(dirname(absOut), { recursive: true })
|
|
235
251
|
if ((ct ?? '').toLowerCase().includes('text/html')) {
|
|
236
252
|
const html = await res.text()
|
|
@@ -250,7 +266,7 @@ export async function prerender(options: PrerenderOptions) {
|
|
|
250
266
|
else {
|
|
251
267
|
writeFileSync(absOut, new Uint8Array(await res.arrayBuffer()))
|
|
252
268
|
}
|
|
253
|
-
task.relOut =
|
|
269
|
+
task.relOut = relOut
|
|
254
270
|
}
|
|
255
271
|
}
|
|
256
272
|
|
package/src/build/static.ts
CHANGED
|
@@ -22,6 +22,28 @@ import { pageFailure } from './prerender'
|
|
|
22
22
|
import { writeStaticHostFiles } from './static-headers'
|
|
23
23
|
|
|
24
24
|
const LEADING_SLASH_RE = /^\//
|
|
25
|
+
const REMOTE_ASSET_PREFIX_RE = /^(?:https?:)?\/\//i
|
|
26
|
+
|
|
27
|
+
/** Validates `assetPrefix`: must be a root-relative path (`/assets`) or an absolute URL (`https://cdn.example.com/_pru`). */
|
|
28
|
+
export function normalizeAssetPrefix(raw: string): string {
|
|
29
|
+
const hint = `prunelle: invalid assetPrefix ${JSON.stringify(raw)}: use a path starting with "/" (e.g. "/_pru") or an absolute URL (e.g. "https://cdn.example.com/_pru").`
|
|
30
|
+
if (raw === '' || /[\s?#]/.test(raw))
|
|
31
|
+
throw new Error(hint)
|
|
32
|
+
if (REMOTE_ASSET_PREFIX_RE.test(raw)) {
|
|
33
|
+
try {
|
|
34
|
+
const url = new URL(raw.startsWith('//') ? `https:${raw}` : raw)
|
|
35
|
+
if (url.hostname === '' || url.search !== '' || url.hash !== '')
|
|
36
|
+
throw new Error(hint)
|
|
37
|
+
}
|
|
38
|
+
catch {
|
|
39
|
+
throw new Error(hint)
|
|
40
|
+
}
|
|
41
|
+
return raw.replace(/\/+$/, '')
|
|
42
|
+
}
|
|
43
|
+
if (!raw.startsWith('/') || raw.split('/').some(seg => seg === '..' || seg.includes('\\')))
|
|
44
|
+
throw new Error(hint)
|
|
45
|
+
return raw.replace(/\/+$/, '')
|
|
46
|
+
}
|
|
25
47
|
|
|
26
48
|
export interface StaticExportOptions {
|
|
27
49
|
/** The app's folder, whose `.prunelle-cache/` keeps the brotli of what was compressed before. */
|
|
@@ -189,8 +211,8 @@ export async function exportStatic(options: StaticExportOptions): Promise<void>
|
|
|
189
211
|
if (options.notFoundEmitted !== true)
|
|
190
212
|
await emitStaticNotFoundPages(options)
|
|
191
213
|
|
|
192
|
-
//
|
|
193
|
-
const assetDir = join(stageDir, options.assetPrefix.replace(LEADING_SLASH_RE, ''))
|
|
214
|
+
// Root-relative prefixes mirror the URL path under <stage>/; absolute CDN prefixes land in <stage>/client/ like the server build.
|
|
215
|
+
const assetDir = join(stageDir, REMOTE_ASSET_PREFIX_RE.test(options.assetPrefix) ? 'client' : options.assetPrefix.replace(LEADING_SLASH_RE, ''))
|
|
194
216
|
for (const rel of options.assets)
|
|
195
217
|
copyInto(assetDir, rel, join(clientDir, rel))
|
|
196
218
|
// Also pick up files written directly into the public folder without registering them.
|
package/src/cli/check-forms.ts
CHANGED
|
@@ -499,17 +499,27 @@ function buildMiddlewareLookup(routesDir: string, routeFiles: readonly string[],
|
|
|
499
499
|
return { hasAncestorMiddleware, pagesRendering }
|
|
500
500
|
}
|
|
501
501
|
|
|
502
|
+
function compilePattern(source: string): RegExp | undefined {
|
|
503
|
+
try {
|
|
504
|
+
return new RegExp(source, 'u')
|
|
505
|
+
}
|
|
506
|
+
catch {
|
|
507
|
+
try {
|
|
508
|
+
return new RegExp(source)
|
|
509
|
+
}
|
|
510
|
+
catch {
|
|
511
|
+
return undefined
|
|
512
|
+
}
|
|
513
|
+
}
|
|
514
|
+
}
|
|
515
|
+
|
|
502
516
|
/** The `patternProperties` keys of a schema as regexes: a field name one matches is a key the schema accepts. */
|
|
503
517
|
function fieldPatterns(patternProperties: unknown): RegExp[] {
|
|
504
518
|
if (!isRecord(patternProperties))
|
|
505
519
|
return []
|
|
506
520
|
return Object.keys(patternProperties).flatMap((source) => {
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
}
|
|
510
|
-
catch {
|
|
511
|
-
return []
|
|
512
|
-
}
|
|
521
|
+
const pattern = compilePattern(source)
|
|
522
|
+
return pattern === undefined ? [] : [pattern]
|
|
513
523
|
})
|
|
514
524
|
}
|
|
515
525
|
|
package/src/cli/check-links.ts
CHANGED
|
@@ -8,7 +8,7 @@ import type { ParamMatcher, ParamMatcherMap, ParsedPatternSegment } from '../ser
|
|
|
8
8
|
import { existsSync, readFileSync, statSync } from 'node:fs'
|
|
9
9
|
import { basename, resolve } from 'node:path'
|
|
10
10
|
import { pathToFileURL } from 'node:url'
|
|
11
|
-
import { isInNodeModules, relPosix, walkAllFiles, walkFiles } from '../build/files'
|
|
11
|
+
import { isHiddenPublicPath, isInNodeModules, relPosix, walkAllFiles, walkFiles } from '../build/files'
|
|
12
12
|
import { isInside } from '../build/is-inside'
|
|
13
13
|
import { discoverRouteMatchers, fileToRoutePath, hasRouteHandlerExport, SPECIAL_ROUTE_FILES } from '../build/routes'
|
|
14
14
|
import { walk } from '../compiler/ast'
|
|
@@ -46,6 +46,12 @@ function normalizePathname(raw: string): string {
|
|
|
46
46
|
return p.length > 1 && p.endsWith('/') ? (p.replace(/\/+$/, '') || '/') : p
|
|
47
47
|
}
|
|
48
48
|
|
|
49
|
+
function decodePathname(raw: string): string {
|
|
50
|
+
const norm = normalizePathname(raw)
|
|
51
|
+
const decoded = decodeRequestPath(norm)?.staticPath
|
|
52
|
+
return decoded !== undefined ? normalizePathname(decoded) : norm
|
|
53
|
+
}
|
|
54
|
+
|
|
49
55
|
const isInternalLink = (raw: string): boolean => raw.startsWith('/') && !raw.startsWith('//')
|
|
50
56
|
const matchesLinkIgnore = (raw?: string): boolean => { const t = (raw ?? '').trim(); return t === '' || t.split(/[\s,]+/).some(tok => LINK_IGNORE_TOKENS.has(tok)) }
|
|
51
57
|
const spaces = (n: number): string => ' '.repeat(Math.max(0, n))
|
|
@@ -236,7 +242,7 @@ function collectPublicPaths(publicDir: string, emittedPublic: readonly string[])
|
|
|
236
242
|
out.add(clean === 'index.html' ? '/' : `/${clean.slice(0, -5)}`)
|
|
237
243
|
if (clean.endsWith('/index.html')) out.add(`/${clean.slice(0, -'/index.html'.length)}`)
|
|
238
244
|
}
|
|
239
|
-
if (existsSync(publicDir)) walkAllFiles(publicDir).forEach(abs =>
|
|
245
|
+
if (existsSync(publicDir)) walkAllFiles(publicDir).forEach((abs) => { const rel = relPosix(publicDir, abs); if (!isHiddenPublicPath(rel)) add(rel) })
|
|
240
246
|
emittedPublic.forEach(add)
|
|
241
247
|
return out
|
|
242
248
|
}
|
|
@@ -343,16 +349,13 @@ function createLinkResolver(opts: {
|
|
|
343
349
|
const { router, publicPaths, dynamicPatterns, staticPaths, suggestionPool, prefixSuggestionPool, locales } = opts
|
|
344
350
|
const assetPrefix = opts.assetPrefix.replace(/\/+$/, '')
|
|
345
351
|
const isAsset = (p: string): boolean => assetPrefix !== '' && (p === assetPrefix || p.startsWith(`${assetPrefix}/`))
|
|
346
|
-
const hasPublic = (p: string): boolean =>
|
|
347
|
-
if (publicPaths.has(p)) return true
|
|
348
|
-
const decoded = decodeRequestPath(p)?.staticPath
|
|
349
|
-
return decoded !== undefined && publicPaths.has(normalizePathname(decoded))
|
|
350
|
-
}
|
|
352
|
+
const hasPublic = (p: string): boolean => publicPaths.has(p) || publicPaths.has(decodePathname(p))
|
|
351
353
|
const matchExact = (p: string): { ok: true } | { ok: false, miss?: RouteEntry } => {
|
|
352
354
|
if (hasPublic(p)) return { ok: true }
|
|
353
355
|
const hit = router.match(p)
|
|
354
356
|
if (hit === undefined) return { ok: false }
|
|
355
|
-
|
|
357
|
+
if (hit.data.knownPaths === undefined) return { ok: true }
|
|
358
|
+
return hit.data.knownPaths.has(p) || hit.data.knownPaths.has(decodePathname(p)) ? { ok: true } : { ok: false, miss: hit.data }
|
|
356
359
|
}
|
|
357
360
|
const checkExact = (raw: string): string | undefined => {
|
|
358
361
|
const trimmed = raw.trim()
|
|
@@ -599,7 +602,7 @@ export async function checkAppLinks(input: LinkCheckInput): Promise<string[]> {
|
|
|
599
602
|
const pattern = fileToRoutePath(routesDir, file)
|
|
600
603
|
const isDynamic = pattern.includes(':') || pattern.includes('*')
|
|
601
604
|
const knownPathList = isDynamic && analysis.hasPaths ? await evaluateRoutePaths(file, analysis, appCtx) : undefined
|
|
602
|
-
register(pattern, { pattern, fileRel: relPosix(root, file), isDynamic, knownPaths: knownPathList !== undefined ? new Set(knownPathList) : undefined, knownPathList })
|
|
605
|
+
register(pattern, { pattern, fileRel: relPosix(root, file), isDynamic, knownPaths: knownPathList !== undefined ? new Set(knownPathList.map(decodePathname)) : undefined, knownPathList })
|
|
603
606
|
}
|
|
604
607
|
probe.pluginRoutes.forEach(p => register(p, { pattern: p, isDynamic: p.includes(':') || p.includes('*') }))
|
|
605
608
|
if (config.consent !== undefined) {
|
|
@@ -1,9 +1,12 @@
|
|
|
1
1
|
// `prunelle check` warnings about what weakens an app's defences: dotfiles under public/, and the security opt-outs in its config.
|
|
2
2
|
|
|
3
|
+
import type { Node } from 'oxc-parser'
|
|
3
4
|
import type { SecurityHeadersOptions } from '../server/security'
|
|
4
5
|
import { relative } from 'node:path'
|
|
6
|
+
import { parseSync } from 'oxc-parser'
|
|
5
7
|
import { isHiddenPublicPath, walkAllFiles } from '../build/files'
|
|
6
|
-
import {
|
|
8
|
+
import { walk } from '../compiler/ast'
|
|
9
|
+
import { formatDiagnostic, unwrapTsExpr } from '../compiler/shared'
|
|
7
10
|
import { resolveCspPolicy } from '../server/security'
|
|
8
11
|
|
|
9
12
|
/** One warning per dotfile in `public/` (other than `.well-known`): the build leaves it out, so it is either dead weight or a secret about to be committed. */
|
|
@@ -15,18 +18,82 @@ export function publicDotfileWarnings(publicDir: string, root: string): string[]
|
|
|
15
18
|
.map(file => formatDiagnostic(`${relative(root, file.abs)}:1:1`, `[security/public-dotfile] "${file.rel}" is in public/ but the build does not copy dotfiles, so it is never served: delete it, or move it out of public/ (only .well-known/ is kept).`, 'warning'))
|
|
16
19
|
}
|
|
17
20
|
|
|
18
|
-
|
|
19
|
-
|
|
21
|
+
const EXTERNAL_URL_PREFIX_RE = /^(?:https?:)?\/\//i
|
|
22
|
+
|
|
23
|
+
function isResponseObject(node: Node): boolean {
|
|
24
|
+
const expr = unwrapTsExpr(node)
|
|
25
|
+
if (expr.type === 'Identifier')
|
|
26
|
+
return expr.name === 'Response'
|
|
27
|
+
return expr.type === 'MemberExpression'
|
|
28
|
+
&& !expr.computed
|
|
29
|
+
&& expr.object.type === 'Identifier'
|
|
30
|
+
&& expr.object.name === 'globalThis'
|
|
31
|
+
&& expr.property.type === 'Identifier'
|
|
32
|
+
&& expr.property.name === 'Response'
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function leadingStringLiteral(node: Node): string | undefined {
|
|
36
|
+
const expr = unwrapTsExpr(node)
|
|
37
|
+
if (expr.type === 'Literal' && typeof expr.value === 'string')
|
|
38
|
+
return expr.value
|
|
39
|
+
if (expr.type === 'TemplateLiteral')
|
|
40
|
+
return expr.quasis[0]?.value.cooked ?? expr.quasis[0]?.value.raw ?? ''
|
|
41
|
+
return undefined
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function allowsExternalRedirect(arg: Node | undefined): boolean {
|
|
45
|
+
if (arg === undefined || arg.type === 'SpreadElement')
|
|
46
|
+
return false
|
|
47
|
+
const expr = unwrapTsExpr(arg)
|
|
48
|
+
if (expr.type !== 'ObjectExpression')
|
|
49
|
+
return true
|
|
50
|
+
let external: boolean | undefined
|
|
51
|
+
for (const prop of expr.properties) {
|
|
52
|
+
if (prop.type === 'SpreadElement') {
|
|
53
|
+
external = true
|
|
54
|
+
continue
|
|
55
|
+
}
|
|
56
|
+
const key = !prop.computed && prop.key.type === 'Identifier'
|
|
57
|
+
? prop.key.name
|
|
58
|
+
: prop.key.type === 'Literal' && typeof prop.key.value === 'string'
|
|
59
|
+
? prop.key.value
|
|
60
|
+
: undefined
|
|
61
|
+
if (key !== 'external')
|
|
62
|
+
continue
|
|
63
|
+
const val = unwrapTsExpr(prop.value)
|
|
64
|
+
const definitelyNotTrue = (val.type === 'Literal' && val.value !== true)
|
|
65
|
+
|| (val.type === 'Identifier' && val.name === 'undefined')
|
|
66
|
+
external = !definitelyNotTrue
|
|
67
|
+
}
|
|
68
|
+
return external === true
|
|
69
|
+
}
|
|
20
70
|
|
|
21
71
|
/** One warning per `ctx.redirect("https://other.site/…")` that lacks `{ external: true }`: since 0.x it throws at runtime. */
|
|
22
72
|
export function externalRedirectWarnings(files: readonly string[], read: (file: string) => string, locate: (file: string, offset: number) => string): string[] {
|
|
23
73
|
const warnings: string[] = []
|
|
24
74
|
for (const file of files) {
|
|
25
75
|
const code = read(file)
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
}
|
|
76
|
+
if (!code.includes('.redirect('))
|
|
77
|
+
continue
|
|
78
|
+
const lang = file.endsWith('.tsx') || file.endsWith('.jsx') ? 'tsx' : 'ts'
|
|
79
|
+
const parsed = parseSync(file, code, { lang, sourceType: 'module' })
|
|
80
|
+
walk(parsed.program, (node) => {
|
|
81
|
+
if (node.type !== 'CallExpression')
|
|
82
|
+
return
|
|
83
|
+
const callee = unwrapTsExpr(node.callee)
|
|
84
|
+
if (callee.type !== 'MemberExpression' || callee.computed || callee.property.type !== 'Identifier' || callee.property.name !== 'redirect')
|
|
85
|
+
return
|
|
86
|
+
if (isResponseObject(callee.object))
|
|
87
|
+
return
|
|
88
|
+
const first = node.arguments[0]
|
|
89
|
+
if (first === undefined || first.type === 'SpreadElement')
|
|
90
|
+
return
|
|
91
|
+
const prefix = leadingStringLiteral(first)
|
|
92
|
+
if (prefix === undefined || !EXTERNAL_URL_PREFIX_RE.test(prefix))
|
|
93
|
+
return
|
|
94
|
+
if (!allowsExternalRedirect(node.arguments[2]))
|
|
95
|
+
warnings.push(formatDiagnostic(locate(file, callee.object.end), '[security/external-redirect] ctx.redirect() to another site throws unless the app passes { external: true } as its third argument: add `{ external: true }` if the address is the app\'s own, and never pass one read from the request.', 'warning'))
|
|
96
|
+
})
|
|
30
97
|
}
|
|
31
98
|
return warnings
|
|
32
99
|
}
|
|
@@ -44,7 +111,7 @@ export function securityConfigWarnings(security: SecurityHeadersOptions | false
|
|
|
44
111
|
const csp = resolveCspPolicy(security)
|
|
45
112
|
const loose = (csp ?? '').split(';')
|
|
46
113
|
.map(part => part.trim().split(/\s+/))
|
|
47
|
-
.filter(([name, ...tokens]) => INLINE_CODE_DIRECTIVES.has(name!.toLowerCase()) && tokens.
|
|
114
|
+
.filter(([name, ...tokens]) => INLINE_CODE_DIRECTIVES.has(name!.toLowerCase()) && tokens.some(token => token.toLowerCase() === '\'unsafe-inline\''))
|
|
48
115
|
.map(([name]) => name!.toLowerCase())
|
|
49
116
|
return loose.length === 0
|
|
50
117
|
? []
|
package/src/cli/commands.ts
CHANGED
|
@@ -130,16 +130,16 @@ function upgradeCommand(cwd: string): Commands[string] {
|
|
|
130
130
|
console.log(`prunelle upgrade rewrote ${res.changed.length} file${res.changed.length === 1 ? '' : 's'}`)
|
|
131
131
|
// The dependencies moved: the first run for this app, which renames its cookies; a later run only fixes what an older prunelle left.
|
|
132
132
|
const moved = res.changed.some(file => file === 'package.json' || file.endsWith('/package.json'))
|
|
133
|
+
let installFailed = false
|
|
133
134
|
if (moved && values['no-install'] !== true) {
|
|
134
135
|
const install = Bun.spawnSync(['bun', 'install'], { cwd: root, stdout: 'inherit', stderr: 'inherit' })
|
|
135
|
-
|
|
136
|
-
return 1
|
|
136
|
+
installFailed = install.exitCode !== 0
|
|
137
137
|
}
|
|
138
138
|
if (moved)
|
|
139
139
|
console.log('Signed-in users sign in again and visitors answer the cookie banner again: prunelle names its cookies pru_session and pru_consent.')
|
|
140
140
|
for (const line of res.manual)
|
|
141
141
|
console.error(line)
|
|
142
|
-
if (res.manual.length > 0)
|
|
142
|
+
if (installFailed || res.manual.length > 0)
|
|
143
143
|
return 1
|
|
144
144
|
console.log('Next: prunelle check')
|
|
145
145
|
return 0
|
package/src/cli/upgrade.ts
CHANGED
|
@@ -56,9 +56,18 @@ const PRUNELLE_SOURCE_RE = /^prunelle(\/.*)?$/
|
|
|
56
56
|
const NPM_KAY_ALIAS_RE = /^npm:(@kayjs\/[\w-]+)(?:@.*)?$/
|
|
57
57
|
const ESCAPE_RE = /[.*+?^${}()|[\]\\]/g
|
|
58
58
|
const GITIGNORE_CACHE_RE = /(?:^|\/)\.prunelle-cache(?:\/|$|\s)/m
|
|
59
|
+
const PARSE_LOC_RE = /:(\d+):\d+:\s*error:\s*(?:prunelle compiler:\s*)?([^\n]+)/
|
|
59
60
|
|
|
60
61
|
const apply = (text: string, rules: readonly [RegExp, string][]): string => rules.reduce((out, [re, to]) => out.replace(re, to), text)
|
|
61
62
|
|
|
63
|
+
function formatParseManual(file: string, err: unknown, action: string): string {
|
|
64
|
+
const msg = err instanceof Error ? err.message : String(err)
|
|
65
|
+
const match = PARSE_LOC_RE.exec(msg)
|
|
66
|
+
const line = match?.[1] ?? '1'
|
|
67
|
+
const reason = match?.[2]?.trim() ?? msg.split('\n', 1)[0]!.trim()
|
|
68
|
+
return `${file}:${line}: ${reason} — ${action}.`
|
|
69
|
+
}
|
|
70
|
+
|
|
62
71
|
/** Why `root` is no app to upgrade: neither on kay nor prunelle, nor a workspace holding one; undefined when it is one. */
|
|
63
72
|
export function notAnApp(root: string): string | undefined {
|
|
64
73
|
if (hasKayOrPrunelle(root) || existsSync(join(root, 'kay.config.ts')) || existsSync(join(root, 'prunelle.config.ts')) || workspaceMembers(root).some(m => hasKayOrPrunelle(join(root, m))))
|
|
@@ -112,7 +121,16 @@ function upgradeDir(root: string, inheritedAliases?: ReadonlyMap<string, string>
|
|
|
112
121
|
const publicDir = configuredPublicDir(root)
|
|
113
122
|
for (const file of sourceFiles(root, publicDir)) {
|
|
114
123
|
const text = readFileSync(join(root, file), 'utf8')
|
|
115
|
-
|
|
124
|
+
let renamed = text
|
|
125
|
+
if (SOURCE_FILE_RE.test(file)) {
|
|
126
|
+
try {
|
|
127
|
+
renamed = renameKayNames(file, text, aliases)
|
|
128
|
+
}
|
|
129
|
+
catch (err) {
|
|
130
|
+
manual.push(formatParseManual(file, err, 'fix the syntax error and re-run prunelle upgrade'))
|
|
131
|
+
continue
|
|
132
|
+
}
|
|
133
|
+
}
|
|
116
134
|
const next = apply(apply(renamed, PATH_RULES), WIRE_RULES)
|
|
117
135
|
write(file, text, next)
|
|
118
136
|
if (SOURCE_FILE_RE.test(file) && next !== text)
|
|
@@ -197,7 +215,14 @@ function configuredPublicDir(root: string): string {
|
|
|
197
215
|
: existsSync(join(root, 'kay.config.ts')) ? 'kay.config.ts' : undefined
|
|
198
216
|
if (file === undefined)
|
|
199
217
|
return resolve(root, 'public')
|
|
200
|
-
|
|
218
|
+
let program: ReturnType<typeof parseTsx>
|
|
219
|
+
try {
|
|
220
|
+
program = parseTsx(file, readFileSync(join(root, file), 'utf8'))
|
|
221
|
+
}
|
|
222
|
+
catch (err) {
|
|
223
|
+
void err
|
|
224
|
+
return resolve(root, 'public')
|
|
225
|
+
}
|
|
201
226
|
let value: string | undefined
|
|
202
227
|
walk(program.body, (node) => {
|
|
203
228
|
if (value !== undefined)
|
|
@@ -349,7 +374,15 @@ function exportsOf(file: string): Set<string> {
|
|
|
349
374
|
|
|
350
375
|
// A name kay exported that prunelle no longer does is reported on the line importing it.
|
|
351
376
|
function checkImports(file: string, code: string, manual: string[]): void {
|
|
352
|
-
|
|
377
|
+
let body: ReturnType<typeof parseTsx>['body']
|
|
378
|
+
try {
|
|
379
|
+
body = parseTsx(file, code).body
|
|
380
|
+
}
|
|
381
|
+
catch (err) {
|
|
382
|
+
manual.push(formatParseManual(file, err, 'fix the syntax error and check its prunelle imports'))
|
|
383
|
+
return
|
|
384
|
+
}
|
|
385
|
+
for (const stmt of body) {
|
|
353
386
|
if (stmt.type !== 'ImportDeclaration' || !PRUNELLE_SOURCE_RE.test(stmt.source.value))
|
|
354
387
|
continue
|
|
355
388
|
const line = code.slice(0, stmt.start).split('\n').length
|