prunelle 0.7.7 → 0.9.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 +63 -46
- package/package.json +7 -2
- package/src/a11y/declaration.ts +6 -10
- package/src/a11y/index.ts +69 -125
- package/src/animate.ts +127 -0
- package/src/build/asides.ts +51 -0
- package/src/build/bundle.ts +88 -134
- package/src/build/client-entries.ts +6 -6
- package/src/build/client-outputs.ts +75 -0
- package/src/build/client-plugin.ts +9 -4
- package/src/build/ecoindex.ts +4 -2
- package/src/build/files.ts +18 -0
- package/src/build/graph.ts +15 -7
- package/src/build/index.ts +20 -10
- package/src/build/island-promote.ts +1 -1
- package/src/build/islands.ts +4 -1
- package/src/build/key-types.ts +31 -0
- package/src/build/manifest.ts +19 -1
- package/src/build/plugin-host.ts +2 -0
- package/src/build/prerender.ts +2 -2
- package/src/build/reach.ts +14 -1
- package/src/build/report.ts +1 -1
- package/src/build/route-types.ts +16 -0
- package/src/build/routes.ts +24 -15
- package/src/build/seed-ids.ts +65 -0
- package/src/build/seed-writes.ts +111 -0
- package/src/build/static-headers.ts +2 -2
- package/src/build/static.ts +1 -1
- package/src/cli/check-cache.ts +51 -0
- package/src/cli/check-consent.ts +95 -0
- package/src/cli/check-forms.ts +2 -2
- package/src/cli/check-links-patterns.ts +101 -0
- package/src/cli/check-links.ts +16 -100
- package/src/cli/check-regions.ts +185 -0
- package/src/cli/check-security.ts +57 -6
- package/src/cli/check.ts +40 -17
- package/src/cli/commands.ts +134 -14
- package/src/cli/docs.ts +21 -2
- package/src/cli/index.ts +1 -1
- package/src/cli/inspect.ts +2 -0
- package/src/cli/mcp-tools.ts +2 -2
- package/src/cli/new.ts +9 -5
- package/src/cli/upgrade-names.ts +14 -2
- package/src/cli/upgrade.ts +3 -0
- package/src/compiler/analyze.ts +18 -4
- package/src/compiler/cacheability.ts +24 -2
- package/src/compiler/compliance-contrast.ts +284 -0
- package/src/compiler/compliance-empty.ts +24 -0
- package/src/compiler/compliance-rgaa-content.ts +95 -0
- package/src/compiler/compliance-rgaa-criteria.ts +45 -0
- package/src/compiler/compliance-rgaa-pages.ts +140 -0
- package/src/compiler/compliance-rgaa.ts +19 -0
- package/src/compiler/compliance-third-party.ts +59 -0
- package/src/compiler/compliance-urls.ts +52 -0
- package/src/compiler/compliance.ts +72 -42
- package/src/compiler/cookie-inventory.ts +119 -0
- package/src/compiler/dom-attrs.ts +4 -1
- package/src/compiler/emit.ts +1 -1
- package/src/compiler/foreign-imports.ts +5 -3
- package/src/compiler/mistakes.ts +18 -9
- package/src/compiler/props-pattern.ts +211 -0
- package/src/compiler/props.ts +177 -346
- package/src/compiler/shared.ts +9 -16
- package/src/compiler/ssr-emit.ts +510 -0
- package/src/compiler/ssr-helpers.ts +170 -121
- package/src/compiler/ssr.ts +25 -440
- package/src/context.ts +14 -1
- package/src/dev/child.ts +1 -1
- package/src/dev/hot-islands.ts +71 -0
- package/src/dev/index.ts +31 -18
- package/src/dev/protocol.ts +1 -1
- package/src/dev/queue.ts +3 -2
- package/src/dev/reload.ts +1 -1
- package/src/dev/supervisor.ts +3 -1
- package/src/dev/watchers.ts +6 -2
- package/src/dom/action.ts +97 -14
- package/src/dom/attrs.ts +8 -0
- package/src/dom/extras.ts +2 -1
- package/src/dom/field-marks.ts +24 -0
- package/src/dom/hot.ts +9 -0
- package/src/dom/index.ts +25 -5
- package/src/dom/island-hot.ts +29 -0
- package/src/dom/island.ts +13 -2
- package/src/dom/prefetch.ts +132 -0
- package/src/dom/regions.ts +498 -0
- package/src/dom/swap.ts +245 -0
- package/src/dom/trusted.ts +22 -0
- package/src/dom/upload.ts +44 -0
- package/src/eco/declaration.ts +39 -40
- package/src/eco/index.ts +5 -5
- package/src/href.ts +31 -0
- package/src/index.ts +9 -3
- package/src/plugins/config.ts +1 -1
- package/src/plugins/context.ts +7 -1
- package/src/plugins/daily.ts +27 -0
- package/src/plugins/index.ts +3 -3
- package/src/plugins/order.ts +1 -1
- package/src/plugins/public.ts +8 -5
- package/src/plugins/services.ts +88 -14
- package/src/plugins/types.ts +121 -10
- package/src/reactivity/hmr.ts +90 -0
- package/src/reactivity/index.ts +38 -18
- package/src/reactivity/resource.ts +115 -0
- package/src/reactivity/seed.ts +39 -0
- package/src/reactivity/server-seed.ts +194 -0
- package/src/reactivity/store.ts +55 -1
- package/src/rgpd/draft.ts +171 -0
- package/src/rgpd/forms.ts +85 -0
- package/src/rgpd/index.ts +57 -0
- package/src/server/action-flash.ts +1 -0
- package/src/server/action-registry.ts +6 -8
- package/src/server/action.ts +51 -19
- package/src/server/app-secret.ts +22 -17
- package/src/server/cache-invalidation.ts +96 -0
- package/src/server/compress.ts +3 -1
- package/src/server/consent.ts +16 -2
- package/src/server/cookie-inventory.ts +78 -0
- package/src/server/cookies.ts +50 -0
- package/src/server/csp-report.ts +86 -0
- package/src/server/discard.ts +13 -0
- package/src/server/document.ts +7 -4
- package/src/server/env.ts +1 -1
- package/src/server/errors.ts +9 -2
- package/src/server/field-errors.ts +91 -0
- package/src/server/form-schema.ts +16 -11
- package/src/server/health.ts +35 -14
- package/src/server/http.ts +25 -10
- package/src/server/index.ts +102 -299
- package/src/server/loader.ts +1 -0
- package/src/server/page.ts +11 -24
- package/src/server/plugin-host.ts +26 -8
- package/src/server/public.ts +14 -3
- package/src/server/rate-limit.ts +39 -10
- package/src/server/region.ts +3 -0
- package/src/server/request-handler.ts +370 -0
- package/src/server/request-log.ts +94 -0
- package/src/server/route-cache.ts +41 -6
- package/src/server/route-input.ts +54 -0
- package/src/server/route-table.ts +35 -19
- package/src/server/routing.ts +12 -11
- package/src/server/sanitize-html.ts +1 -1
- package/src/server/security.ts +81 -20
- package/src/server/serve-handlers.ts +9 -5
- package/src/server/shared-store.ts +314 -0
- package/src/server/start.ts +12 -5
- package/src/server/static-dir.ts +14 -10
- package/src/server/stream.ts +2 -1
- package/src/server/surface.ts +39 -0
- package/src/server/webhook.ts +48 -0
- package/src/server/workers.ts +168 -0
- package/src/ssr/consent-banner.ts +20 -16
- package/src/ssr/consent-texts.ts +40 -0
- package/src/ssr/context.ts +26 -3
- package/src/ssr/cookie-table.ts +75 -0
- package/src/ssr/index.ts +23 -13
- package/src/ssr/navigation.ts +161 -14
- package/src/test/browser.ts +50 -22
- package/src/test/build-reuse.ts +70 -0
- package/src/test/index.ts +45 -6
- package/src/test/mount.ts +53 -0
- package/src/test/outside.ts +94 -0
- package/templates/_shared/AGENTS.md +1 -1
- package/templates/_shared/Dockerfile +22 -0
- package/templates/_shared/dockerignore +9 -0
- package/templates/_shared/gitignore +2 -0
- package/templates/app/.env.example +3 -1
- package/templates/app/compose.yaml +32 -0
- package/templates/app/db/migrations/001_notes.sql +7 -0
- package/templates/app/db/schema.ts +11 -0
- package/templates/app/package.json +1 -0
- package/templates/app/prunelle.config.ts +6 -0
- package/templates/app/src/actions/notes.ts +26 -0
- package/templates/app/src/auth.ts +4 -2
- package/templates/app/src/db.ts +5 -0
- package/templates/app/src/routes/dashboard/index.tsx +26 -1
- package/templates/app/src/routes/privacy.tsx +6 -2
- package/templates/app/tests/app.test.ts +14 -3
- package/templates/plugin/AGENTS.md +11 -0
- package/templates/plugin/CLAUDE.md +1 -0
- package/templates/plugin/README.md +27 -0
- package/templates/plugin/gitignore +2 -0
- package/templates/plugin/llms.txt +19 -0
- package/templates/plugin/package.json +33 -0
- package/templates/plugin/src/index.ts +40 -0
- package/templates/plugin/tests/fixture/prunelle.config.ts +4 -0
- package/templates/plugin/tests/fixture/src/routes/index.tsx +11 -0
- package/templates/plugin/tests/plugin.test.ts +42 -0
- package/templates/plugin/tsconfig.json +19 -0
- package/ts-plugin.cjs +3674 -2196
|
@@ -103,7 +103,7 @@ export function externalRedirectWarnings(files: readonly string[], read: (file:
|
|
|
103
103
|
// Fetch directives whose `'unsafe-inline'` lets an injected script or stylesheet run; `style-src-attr` is left out, as the default policy allows `style=""` attributes.
|
|
104
104
|
const INLINE_CODE_DIRECTIVES = new Set(['default-src', 'script-src', 'script-src-elem', 'style-src', 'style-src-elem'])
|
|
105
105
|
|
|
106
|
-
/** One warning for each way `security` in `prunelle.config.ts` turns a default defence off: all headers, the CSP,
|
|
106
|
+
/** One warning for each way `security` in `prunelle.config.ts` turns a default defence off: all headers, the CSP, `'unsafe-inline'` in it, or its Trusted Types. */
|
|
107
107
|
export function securityConfigWarnings(security: SecurityHeadersOptions | false | undefined): string[] {
|
|
108
108
|
const at = 'prunelle.config.ts:1:1'
|
|
109
109
|
if (security === false)
|
|
@@ -115,25 +115,76 @@ export function securityConfigWarnings(security: SecurityHeadersOptions | false
|
|
|
115
115
|
.map(part => part.trim().split(/\s+/))
|
|
116
116
|
.filter(([name, ...tokens]) => INLINE_CODE_DIRECTIVES.has(name!.toLowerCase()) && tokens.some(token => token.toLowerCase() === '\'unsafe-inline\''))
|
|
117
117
|
.map(([name]) => name!.toLowerCase())
|
|
118
|
-
return
|
|
119
|
-
? []
|
|
120
|
-
|
|
118
|
+
return [
|
|
119
|
+
...loose.length === 0 ? [] : [formatDiagnostic(at, `[security/unsafe-inline] the CSP allows 'unsafe-inline' in ${loose.join(', ')}, which lets an injected script or style run: remove it, since prunelle hashes its own inline scripts and styles, or add a hash of the inline one you need.`, 'warning')],
|
|
120
|
+
...security?.trustedTypes === false ? [formatDiagnostic(at, '[security/trusted-types-off] security.trustedTypes is false, so the browser lets any script write an HTML string into the page, an injected one included: drop it, and write HTML with innerHTML={html} on an element, or through a Trusted Types policy of the app listed with `csp: { \'trusted-types\': [\'my-policy\'] }`.', 'warning')] : [],
|
|
121
|
+
]
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
// Members that write an HTML string into the page: the browser refuses each one a plain string under `require-trusted-types-for 'script'`.
|
|
125
|
+
const HTML_SINK_PROPERTIES = new Set(['innerHTML', 'outerHTML', 'srcdoc'])
|
|
126
|
+
const HTML_SINK_METHODS = new Set(['insertAdjacentHTML', 'parseFromString', 'createContextualFragment', 'setHTMLUnsafe'])
|
|
127
|
+
const HTML_SINK_HINT = /HTML|srcdoc|parseFromString|createContextualFragment|document\.write/
|
|
128
|
+
|
|
129
|
+
function htmlSinkAt(node: Node): number | undefined {
|
|
130
|
+
if (node.type === 'AssignmentExpression') {
|
|
131
|
+
const target = unwrapTsExpr(node.left as Node)
|
|
132
|
+
return target.type === 'MemberExpression' && !target.computed && target.property.type === 'Identifier' && HTML_SINK_PROPERTIES.has(target.property.name) ? target.start : undefined
|
|
133
|
+
}
|
|
134
|
+
if (node.type !== 'CallExpression')
|
|
135
|
+
return undefined
|
|
136
|
+
const callee = unwrapTsExpr(node.callee)
|
|
137
|
+
if (callee.type !== 'MemberExpression' || callee.computed || callee.property.type !== 'Identifier')
|
|
138
|
+
return undefined
|
|
139
|
+
const name = callee.property.name
|
|
140
|
+
const onDocument = callee.object.type === 'Identifier' && callee.object.name === 'document' && (name === 'write' || name === 'writeln')
|
|
141
|
+
return HTML_SINK_METHODS.has(name) || onDocument ? callee.start : undefined
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** One warning per line of app code writing an HTML string into the page while the CSP requires Trusted Types, which make the browser refuse it. */
|
|
145
|
+
export function htmlSinkWarnings(files: readonly string[], read: (file: string) => string, locate: (file: string, offset: number) => string, security: SecurityHeadersOptions | false | undefined, compliance?: ComplianceConfig | undefined): string[] {
|
|
146
|
+
if (isRuleIgnored('security/html-sink', compliance) || !/require-trusted-types-for/i.test(resolveCspPolicy(security) ?? ''))
|
|
147
|
+
return []
|
|
148
|
+
const warnings: string[] = []
|
|
149
|
+
for (const file of files) {
|
|
150
|
+
const code = read(file)
|
|
151
|
+
if (!HTML_SINK_HINT.test(code))
|
|
152
|
+
continue
|
|
153
|
+
const ignores = parsePrunelleIgnores(code)
|
|
154
|
+
const parsed = parseSync(file, code, { lang: file.endsWith('.tsx') || file.endsWith('.jsx') ? 'tsx' : 'ts', sourceType: 'module' })
|
|
155
|
+
walk(parsed.program, (node) => {
|
|
156
|
+
const at = htmlSinkAt(node)
|
|
157
|
+
if (at !== undefined && !isIgnoredAt(ignores, 'security/html-sink', at))
|
|
158
|
+
warnings.push(formatDiagnostic(locate(file, at), '[security/html-sink] this writes an HTML string into the page, which the browser refuses under the CSP\'s Trusted Types (`require-trusted-types-for \'script\'`): render it with innerHTML={html} on an element, set plain text with textContent, or pass it through a Trusted Types policy of the app listed with `security: { csp: { \'trusted-types\': [\'my-policy\'] } }`.', 'warning'))
|
|
159
|
+
})
|
|
160
|
+
}
|
|
161
|
+
return warnings
|
|
121
162
|
}
|
|
122
163
|
|
|
123
164
|
const CSRF_OFF_RE = /export\s+const\s+csrf\s*=\s*false\b/g
|
|
165
|
+
const VERIFY_WEBHOOK_RE = /\bverifyWebhook\s*\(/
|
|
124
166
|
|
|
125
|
-
/** One warning per route file that exports `csrf = false`: it accepts a cross-site POST, so it must check a signature or a token itself. A route
|
|
167
|
+
/** One warning per route file that exports `csrf = false`: it accepts a cross-site POST, so it must check a signature or a token itself. A route calling `verifyWebhook()` does; another says so with `// prunelle-ignore security/csrf-off` above the export. */
|
|
126
168
|
export function csrfOffWarnings(files: readonly string[], read: (file: string) => string, locate: (file: string, offset: number) => string, compliance?: ComplianceConfig | undefined): string[] {
|
|
127
169
|
if (isRuleIgnored('security/csrf-off', compliance))
|
|
128
170
|
return []
|
|
129
171
|
const warnings: string[] = []
|
|
130
172
|
for (const file of files) {
|
|
131
173
|
const code = read(file)
|
|
174
|
+
if (VERIFY_WEBHOOK_RE.test(code))
|
|
175
|
+
continue
|
|
132
176
|
const ignores = parsePrunelleIgnores(code)
|
|
133
177
|
for (const match of code.matchAll(CSRF_OFF_RE)) {
|
|
134
178
|
if (!isIgnoredAt(ignores, 'security/csrf-off', match.index))
|
|
135
|
-
warnings.push(formatDiagnostic(locate(file, match.index), '[security/csrf-off] this route skips the cross-site request check, so any site can post to it: keep it only for a webhook or bearer-token API that verifies
|
|
179
|
+
warnings.push(formatDiagnostic(locate(file, match.index), '[security/csrf-off] this route skips the cross-site request check, so any site can post to it: keep it only for a webhook, checked with `verifyWebhook()` from `prunelle/server`, or a bearer-token API that verifies its token itself, and say so with `// prunelle-ignore security/csrf-off` above the export; drop `export const csrf = false` for anything a browser form posts to.', 'warning'))
|
|
136
180
|
}
|
|
137
181
|
}
|
|
138
182
|
return warnings
|
|
139
183
|
}
|
|
184
|
+
|
|
185
|
+
/** A warning when `trustProxy` is on and `site` is not: any `X-Forwarded-Host` then counts as the app's host, though a proxy that sets `Host` alone passes the client's one through. */
|
|
186
|
+
export function proxyWithoutSiteWarnings(trustProxy: boolean | number | undefined, site: string | undefined, compliance?: ComplianceConfig | undefined): string[] {
|
|
187
|
+
if (trustProxy === undefined || trustProxy === false || trustProxy === 0 || site !== undefined || isRuleIgnored('security/proxy-no-site', compliance))
|
|
188
|
+
return []
|
|
189
|
+
return [formatDiagnostic('prunelle.config.ts:1:1', '[security/proxy-no-site] trustProxy is on but site is not set, so the origin check and ctx.redirect take any X-Forwarded-Host as this app\'s host, even one a client sent past a proxy that does not overwrite it: set site: \'https://your.domain\' in prunelle.config.ts, and list any other domain the app answers on in trustedOrigins.', 'warning')]
|
|
190
|
+
}
|
package/src/cli/check.ts
CHANGED
|
@@ -12,19 +12,23 @@ import { formatIslandValueWarnings } from '../build/island-promote'
|
|
|
12
12
|
import { nodeEnvWarning, renderProblems, serverNodeEnvReads } from '../build/render-rules'
|
|
13
13
|
import { analyzeIslands } from '../build/islands'
|
|
14
14
|
import { ancestorFiles, discoverRouteMatchers, fileToRoutePath, hasRouteHandlerExport, missingPathsProblem, normalizeRoutePattern, routeExportProblemLocation, routeFileProblem, SPECIAL_ROUTE_FILES } from '../build/routes'
|
|
15
|
+
import { writeRouteTypes } from '../build/route-types'
|
|
15
16
|
import { findUnknownStatusPages } from '../build/status-pages'
|
|
16
17
|
import { analyzeModule } from '../compiler/analyze'
|
|
17
18
|
import { findCachedRoutePrivateReads } from '../compiler/cacheability'
|
|
18
|
-
import { collectProjectComplianceWarnings, pluginSetsLang, shouldEmitWarning } from '../compiler/compliance'
|
|
19
|
+
import { collectProjectComplianceWarnings, pluginChecksTitle, pluginSetsLang, shouldEmitWarning } from '../compiler/compliance'
|
|
19
20
|
import { collectMistakes, PrunelleMistake, serverOnlyTagError } from '../compiler/mistakes'
|
|
20
21
|
import { DIAGNOSTIC_PREFIX_RE, formatDiagnostic, formatLoc } from '../compiler/shared'
|
|
21
22
|
import { createAppContext, loadConfig, resolvePlugins, runWithAppContext } from '../plugins/index'
|
|
22
23
|
import { collectRequirements } from '../plugins/requires'
|
|
23
24
|
import { normalizeConsentConfig } from '../server/consent'
|
|
25
|
+
import { cookieWarnings } from './check-consent'
|
|
24
26
|
import { checkAppForms } from './check-forms'
|
|
25
27
|
import { unresolvedImport } from './check-imports'
|
|
26
28
|
import { checkAppLinks } from './check-links'
|
|
27
|
-
import {
|
|
29
|
+
import { checkRegionTargets } from './check-regions'
|
|
30
|
+
import { unknownCacheTagWarnings } from './check-cache'
|
|
31
|
+
import { csrfOffWarnings, externalRedirectWarnings, htmlSinkWarnings, proxyWithoutSiteWarnings, publicDotfileWarnings, securityConfigWarnings } from './check-security'
|
|
28
32
|
|
|
29
33
|
/** Whether `prunelle check` typechecked the app, with which tool, or why it did not. */
|
|
30
34
|
export type TypecheckRun = { ran: true, tool: string } | { ran: false, reason: string }
|
|
@@ -185,8 +189,8 @@ function formatIslandIssue(issue: IslandIssue, root: string, sources: Map<string
|
|
|
185
189
|
}
|
|
186
190
|
|
|
187
191
|
// Each plugin's check(ctx) runs inside a real AppRuntimeContext; what it reports without a place lands on prunelle.config.ts.
|
|
188
|
-
async function runPluginChecks(plugins: readonly PrunellePlugin[], paths: { root: string, routesDir: string, publicDir: string, outDir: string, assetPrefix: string, site: string | undefined, consentCategories: readonly string[] }, errors: string[], warnings: string[]): Promise<void> {
|
|
189
|
-
const { root, routesDir, publicDir, outDir, assetPrefix, site, consentCategories } = paths
|
|
192
|
+
async function runPluginChecks(plugins: readonly PrunellePlugin[], paths: { root: string, routesDir: string, publicDir: string, outDir: string, assetPrefix: string, site: string | undefined, consentCategories: readonly string[], store: string | undefined }, errors: string[], warnings: string[]): Promise<void> {
|
|
193
|
+
const { root, routesDir, publicDir, outDir, assetPrefix, site, consentCategories, store } = paths
|
|
190
194
|
const appCtx = createAppContext({ root, outDir, publicDir: join(outDir, 'public'), assetPrefix, site, dev: false })
|
|
191
195
|
const placed = (message: string, severity: 'error' | 'warning'): string =>
|
|
192
196
|
DIAGNOSTIC_PREFIX_RE.test(message) ? message : formatDiagnostic('prunelle.config.ts:1:1', message, severity)
|
|
@@ -194,6 +198,7 @@ async function runPluginChecks(plugins: readonly PrunellePlugin[], paths: { root
|
|
|
194
198
|
root,
|
|
195
199
|
routesDir,
|
|
196
200
|
publicDir,
|
|
201
|
+
site,
|
|
197
202
|
error: message => errors.push(placed(message, 'error')),
|
|
198
203
|
warn: message => warnings.push(placed(message, 'warning')),
|
|
199
204
|
provide: appCtx.provide,
|
|
@@ -209,7 +214,7 @@ async function runPluginChecks(plugins: readonly PrunellePlugin[], paths: { root
|
|
|
209
214
|
errors.push(placed(`${plugin.name}: ${err instanceof Error ? err.message : String(err)}`, 'error'))
|
|
210
215
|
}
|
|
211
216
|
}
|
|
212
|
-
const { unmet, failed } = await runWithAppContext(appCtx, () => collectRequirements(plugins, { root, site, consentCategories }))
|
|
217
|
+
const { unmet, failed } = await runWithAppContext(appCtx, () => collectRequirements(plugins, { root, site, consentCategories, store }))
|
|
213
218
|
for (const line of unmet)
|
|
214
219
|
warnings.push(placed(`${line} (a production start refuses until it is set)`, 'warning'))
|
|
215
220
|
for (const line of failed)
|
|
@@ -228,6 +233,23 @@ function discoverProjectFiles(srcDir: string, routesDir: string, configFile: str
|
|
|
228
233
|
return [...fileSet].sort()
|
|
229
234
|
}
|
|
230
235
|
|
|
236
|
+
function removedImportWarning(imp: { source: string, specifiers: readonly { imported: string }[] }): string | undefined {
|
|
237
|
+
if (imp.source === '@prunellejs/auth') {
|
|
238
|
+
const removed = imp.specifiers.find(s => s.imported === 'createRateLimiter' || s.imported === 'RateLimiter')
|
|
239
|
+
if (removed !== undefined)
|
|
240
|
+
return `prunelle check: ${removed.imported} was removed from @prunellejs/auth in 0.2.0: use \`rateLimit\` on \`api.route()\`/\`action()\`, \`api.rateLimiter()\` in a plugin, or \`createRateLimitStore()\` from \`prunelle/server\`.`
|
|
241
|
+
}
|
|
242
|
+
if (imp.source === '@prunellejs/cms' || imp.source.startsWith('@prunellejs/cms/'))
|
|
243
|
+
return 'prunelle check: @prunellejs/cms was removed: remove it from prunelle.config.ts and package.json, and edit Markdown files directly or load from a headless CMS via @prunellejs/content `load()`.'
|
|
244
|
+
if (imp.source === 'prunelle/config' && imp.specifiers.some(s => s.imported === 'a11y'))
|
|
245
|
+
return 'prunelle check: `a11y()` was removed from prunelle/config: `prunelle a11y` is now a built-in CLI command, so remove `a11y()` from prunelle.config.ts.'
|
|
246
|
+
if (imp.source === '@prunellejs/spa' && imp.specifiers.some(s => s.imported === 'regions'))
|
|
247
|
+
return 'prunelle check: `regions()` was removed from @prunellejs/spa: `<Region>` swapping is built into `prunelle` automatically on routes rendering `<Region>`, so remove `regions()` from prunelle.config.ts and import `refreshRegion` from `prunelle`.'
|
|
248
|
+
if (imp.source === '@prunellejs/spa/regions')
|
|
249
|
+
return 'prunelle check: `@prunellejs/spa/regions` was removed: import `refreshRegion` from `prunelle` instead.'
|
|
250
|
+
return undefined
|
|
251
|
+
}
|
|
252
|
+
|
|
231
253
|
export async function checkProject(rootDir: string, options: { skipTypecheck?: boolean } = {}): Promise<CheckResult> {
|
|
232
254
|
const root = resolve(rootDir)
|
|
233
255
|
const errors: string[] = []
|
|
@@ -289,11 +311,11 @@ export async function checkProject(rootDir: string, options: { skipTypecheck?: b
|
|
|
289
311
|
|
|
290
312
|
// Exact route discovery matching `prunelle build` (`walkRoutes` skips `_components/` dirs, `.d.ts`, `.test.ts`)
|
|
291
313
|
const routeFiles = existsSync(routesDir) ? walkRoutes(routesDir).sort() : []
|
|
292
|
-
|
|
293
|
-
errors.push(formatDiagnostic(`${relPosix(root, unknown.file)}:1:1`, `prunelle check: ${unknown.message}`))
|
|
314
|
+
errors.push(...findUnknownStatusPages(root, routeFiles).map(unknown => formatDiagnostic(`${relPosix(root, unknown.file)}:1:1`, `prunelle check: ${unknown.message}`)))
|
|
294
315
|
const routeFileSet = new Set(routeFiles)
|
|
295
316
|
const specialFiles = routeFiles.filter(f => SPECIAL_ROUTE_FILES.has(basename(f)))
|
|
296
317
|
const pageFiles = routeFiles.filter(f => !basename(f).startsWith('_') && analyses.has(f) && hasRouteHandlerExport(analyses.get(f)!))
|
|
318
|
+
writeRouteTypes(root, routesDir, pageFiles)
|
|
297
319
|
const matcherDiscovery = discoverRouteMatchers({
|
|
298
320
|
root,
|
|
299
321
|
routesDir,
|
|
@@ -331,11 +353,9 @@ export async function checkProject(rootDir: string, options: { skipTypecheck?: b
|
|
|
331
353
|
const unresolved = unresolvedImport(file, rel, imp.source, imp.specifiers)
|
|
332
354
|
if (unresolved !== undefined)
|
|
333
355
|
errors.push(formatDiagnostic(locOf(root, file, sources, imp.start), unresolved))
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
warnings.push(formatDiagnostic(locOf(root, file, sources, imp.start), `prunelle check: ${removed.imported} was removed from @prunellejs/auth in 0.2.0: use \`rateLimit\` on \`api.route()\`/\`action()\`, \`api.rateLimiter()\` in a plugin, or \`createRateLimitStore()\` from \`prunelle/server\`.`, 'warning'))
|
|
338
|
-
}
|
|
356
|
+
const removedWarning = removedImportWarning(imp)
|
|
357
|
+
if (removedWarning !== undefined)
|
|
358
|
+
warnings.push(formatDiagnostic(locOf(root, file, sources, imp.start), removedWarning, 'warning'))
|
|
339
359
|
}
|
|
340
360
|
if (file !== configFile) {
|
|
341
361
|
for (const offset of serverNodeEnvReads(analysis, islands, file))
|
|
@@ -385,23 +405,26 @@ export async function checkProject(rootDir: string, options: { skipTypecheck?: b
|
|
|
385
405
|
}
|
|
386
406
|
|
|
387
407
|
// 3d. French web law compliance checks (CSS third-party URLs, LCEN legal notice, RGAA accessibility statement)
|
|
388
|
-
warnings.push(...collectProjectComplianceWarnings({ root, srcDir, routesDir, publicDir, routeFiles, analyses, compliance, consentMaxAge: loadedConfig.consent?.maxAge, site, lang: loadedConfig.lang, langFromPlugin: pluginSetsLang(plugins) }))
|
|
408
|
+
warnings.push(...collectProjectComplianceWarnings({ root, srcDir, routesDir, publicDir, routeFiles, analyses, compliance, consentMaxAge: loadedConfig.consent?.maxAge, site, lang: loadedConfig.lang, langFromPlugin: pluginSetsLang(plugins), titleChecked: pluginChecksTitle(plugins) }))
|
|
389
409
|
|
|
390
410
|
// 3d. Form field / schema checks & public action protection warnings (#4, #5)
|
|
391
411
|
const formCheck = await checkAppForms({ root, routesDir, routeFiles, graph, sources, compliance })
|
|
392
412
|
errors.push(...formCheck.errors)
|
|
393
413
|
warnings.push(...formCheck.warnings)
|
|
394
414
|
|
|
395
|
-
warnings.push(...publicDotfileWarnings(publicDir, root))
|
|
396
|
-
warnings.push(...securityConfigWarnings(loadedConfig.security))
|
|
415
|
+
warnings.push(...publicDotfileWarnings(publicDir, root), ...securityConfigWarnings(loadedConfig.security), ...proxyWithoutSiteWarnings(loadedConfig.trustProxy, site, compliance))
|
|
397
416
|
warnings.push(...csrfOffWarnings(routeFiles, file => sourceOf(file, sources), (file, offset) => locOf(root, file, sources, offset), compliance))
|
|
398
417
|
warnings.push(...externalRedirectWarnings(files, file => sourceOf(file, sources), (file, offset) => locOf(root, file, sources, offset)))
|
|
418
|
+
warnings.push(...htmlSinkWarnings(files, file => sourceOf(file, sources), (file, offset) => locOf(root, file, sources, offset), loadedConfig.security, compliance))
|
|
419
|
+
warnings.push(...unknownCacheTagWarnings(files, file => sourceOf(file, sources), (file, offset) => locOf(root, file, sources, offset), new Set(routeFiles.flatMap(file => analyses.get(file)?.cache?.tags ?? []))))
|
|
420
|
+
warnings.push(...cookieWarnings(loadedConfig.consent !== undefined, files, file => sourceOf(file, sources), (file, offset) => locOf(root, file, sources, offset), compliance))
|
|
399
421
|
|
|
400
|
-
// 3e. Broken internal link checks (#3)
|
|
422
|
+
// 3e. Broken internal link & region target checks (#3, #379)
|
|
401
423
|
warnings.push(...await checkAppLinks({ root, routesDir, publicDir, assetPrefix, site, config: loadedConfig, plugins, routeFiles, analyses, sources }))
|
|
424
|
+
errors.push(...checkRegionTargets({ graph, routesDir, pageFiles, locate: (file, offset) => locOf(root, file, sources, offset) }))
|
|
402
425
|
|
|
403
426
|
// 3f. Plugin check(ctx) hooks
|
|
404
|
-
await runPluginChecks(plugins, { root, routesDir, publicDir, outDir, assetPrefix, site, consentCategories }, errors, warnings)
|
|
427
|
+
await runPluginChecks(plugins, { root, routesDir, publicDir, outDir, assetPrefix, site, consentCategories, store: loadedConfig.store }, errors, warnings)
|
|
405
428
|
|
|
406
429
|
const typecheck = options.skipTypecheck === true ? { ran: false as const, reason: "skipped by --no-typecheck" } : runTypecheck(root, errors)
|
|
407
430
|
|
package/src/cli/commands.ts
CHANGED
|
@@ -6,7 +6,7 @@ import { resolve } from 'node:path'
|
|
|
6
6
|
import { badUsage, Exit, fail, parse } from '@kaynooo/cli-kit'
|
|
7
7
|
import { parseByteSize } from '../build/byte-size'
|
|
8
8
|
|
|
9
|
-
const TEMPLATES = ['minimal', 'fullstack', 'blog', 'app'] as const
|
|
9
|
+
const TEMPLATES = ['minimal', 'fullstack', 'blog', 'app', 'plugin'] as const
|
|
10
10
|
|
|
11
11
|
|
|
12
12
|
const ROOT = { type: 'string', description: 'the app folder, when it is not the current one or the [dir] argument' } as const
|
|
@@ -52,9 +52,9 @@ function rootOf(cwd: string, root: string | undefined, dir: string | undefined):
|
|
|
52
52
|
|
|
53
53
|
function newCommand(cwd: string): Commands[string] {
|
|
54
54
|
return {
|
|
55
|
-
summary: 'create an app from a template',
|
|
55
|
+
summary: 'create an app or a plugin from a template',
|
|
56
56
|
run: async (args) => {
|
|
57
|
-
const { values, positionals: [dir] } = parse(args, 'prunelle new [options] <dir>: creates an app from a template', {
|
|
57
|
+
const { values, positionals: [dir] } = parse(args, 'prunelle new [options] <dir>: creates an app from a template, or a plugin package with --template plugin', {
|
|
58
58
|
template: { type: 'string', choices: TEMPLATES, description: 'the template (minimal)' },
|
|
59
59
|
force: { type: 'boolean', description: 'write into a folder that is not empty' },
|
|
60
60
|
root: ROOT,
|
|
@@ -66,7 +66,7 @@ function newCommand(cwd: string): Commands[string] {
|
|
|
66
66
|
for (const file of res.overwritten)
|
|
67
67
|
console.log(`prunelle new: overwrote ${file}`)
|
|
68
68
|
console.log(`Created Prunelle (${template}) project in ${res.root} (${res.files.length} files)`)
|
|
69
|
-
console.log(`\nNext steps:\n cd ${dir}\n bun install\n bun run dev`)
|
|
69
|
+
console.log(`\nNext steps:\n cd ${dir}\n bun install\n ${template === 'plugin' ? 'bun test' : 'bun run dev'}`)
|
|
70
70
|
return 0
|
|
71
71
|
},
|
|
72
72
|
}
|
|
@@ -97,6 +97,8 @@ function checkCommand(cwd: string): Commands[string] {
|
|
|
97
97
|
console.warn(warning)
|
|
98
98
|
for (const e of res.errors)
|
|
99
99
|
console.error(e)
|
|
100
|
+
const { rgaaCriteriaCovered, RGAA_CRITERIA_TOTAL } = await import('../compiler/compliance-rgaa-criteria')
|
|
101
|
+
console.log(`prunelle check: its RGAA rules partly cover ${rgaaCriteriaCovered()} of the ${RGAA_CRITERIA_TOTAL} RGAA 4.1 criteria, so a clean run does not make the site accessible: \`prunelle a11y\` audits the rendered pages, and a manual audit covers the rest.`)
|
|
100
102
|
const typecheck = res.typecheck.ran ? `typechecked with ${res.typecheck.tool}` : `no typecheck: ${res.typecheck.reason}`
|
|
101
103
|
if (failed) {
|
|
102
104
|
if (res.ok)
|
|
@@ -193,11 +195,83 @@ function buildCommand(cwd: string): Commands[string] {
|
|
|
193
195
|
}
|
|
194
196
|
}
|
|
195
197
|
|
|
198
|
+
function a11yCommand(cwd: string): Commands[string] {
|
|
199
|
+
return {
|
|
200
|
+
summary: 'audit rendered routes with axe-core + RGAA 4.1 and draft the accessibility declaration',
|
|
201
|
+
run: async (args) => {
|
|
202
|
+
const { values, positionals } = parse(args, 'prunelle a11y [options] [dest]: audits rendered routes with axe-core + RGAA 4.1 and drafts an accessibility declaration', {
|
|
203
|
+
'routes': { type: 'string', description: 'comma-separated routes to audit (e.g. /,/about)' },
|
|
204
|
+
'all-static': { type: 'boolean', description: 'include static non-dynamic HTML routes alongside prerendered routes' },
|
|
205
|
+
'json': { type: 'boolean', description: 'print the audit report as JSON on stdout' },
|
|
206
|
+
'draft': { type: 'string', optional: { bare: '' }, description: 'write an editable RGAA 4.1.2 accessibility declaration page (default: src/routes/accessibilite.tsx)' },
|
|
207
|
+
'force': { type: 'boolean', description: 'overwrite an existing declaration file when used with --draft' },
|
|
208
|
+
'out': { type: 'string', description: 'destination path for --draft (default: src/routes/accessibilite.tsx)' },
|
|
209
|
+
'audit-date': { type: 'string', description: 'day the manual RGAA audit ended (YYYY-MM-DD), written into --draft with --rate' },
|
|
210
|
+
'rate': { type: 'string', description: 'applicable RGAA criteria the manual audit found met, in percent: 100 is totally, 50 or more partially compliant' },
|
|
211
|
+
'status': { type: 'string', description: 'removed: the level now follows --audit-date and --rate' },
|
|
212
|
+
'org': { type: 'string', description: 'organization name written into --draft' },
|
|
213
|
+
'contact': { type: 'string', description: 'contact email written into --draft' },
|
|
214
|
+
'no-fail': { type: 'boolean', description: 'exit 0 even when accessibility violations are found' },
|
|
215
|
+
'root': ROOT,
|
|
216
|
+
}, {
|
|
217
|
+
positionals: ['[dest]'],
|
|
218
|
+
exits: [
|
|
219
|
+
[0, 'no accessibility violations found (or --draft / --no-fail)'],
|
|
220
|
+
[1, 'one or more accessibility violations found, or audit failed'],
|
|
221
|
+
USAGE_EXIT,
|
|
222
|
+
],
|
|
223
|
+
})
|
|
224
|
+
const rawRoutes = values.routes !== undefined ? values.routes.split(',').map(s => s.trim()).filter(Boolean) : undefined
|
|
225
|
+
if (values.routes !== undefined && (rawRoutes === undefined || rawRoutes.length === 0))
|
|
226
|
+
return badUsage('--routes requires at least one route path, e.g. --routes /,/about')
|
|
227
|
+
if (values.status !== undefined)
|
|
228
|
+
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)')
|
|
229
|
+
if ((values['audit-date'] === undefined) !== (values.rate === undefined))
|
|
230
|
+
return badUsage('--audit-date and --rate go together: pass the day the manual RGAA audit ended and the percentage of criteria it found met')
|
|
231
|
+
const rawRate = values.rate?.trim()
|
|
232
|
+
const manualAudit = values['audit-date'] !== undefined && rawRate !== undefined
|
|
233
|
+
? { date: new Date(`${values['audit-date']}T00:00:00Z`), rate: rawRate === '' ? Number.NaN : Number(rawRate) }
|
|
234
|
+
: undefined
|
|
235
|
+
if (manualAudit !== undefined) {
|
|
236
|
+
if (Number.isNaN(manualAudit.date.getTime()))
|
|
237
|
+
return badUsage('--audit-date must be a valid YYYY-MM-DD date, e.g. --audit-date 2026-03-31')
|
|
238
|
+
if (!(manualAudit.rate >= 0 && manualAudit.rate <= 100))
|
|
239
|
+
return badUsage(`--rate must be a percentage from 0 to 100, got "${values.rate}"`)
|
|
240
|
+
}
|
|
241
|
+
const wantDraft = values.draft !== undefined
|
|
242
|
+
const draft = wantDraft
|
|
243
|
+
? (values.out ?? (values.draft !== '' ? values.draft : undefined) ?? positionals[0] ?? '')
|
|
244
|
+
: undefined
|
|
245
|
+
const { formatA11yReport, runA11y } = await import('../a11y/index')
|
|
246
|
+
const { report, drafted } = await failing('a11y', () => runA11y({
|
|
247
|
+
root: rootOf(cwd, values.root, undefined),
|
|
248
|
+
routes: rawRoutes,
|
|
249
|
+
includeAllStatic: values['all-static'] === true,
|
|
250
|
+
draft,
|
|
251
|
+
force: values.force === true,
|
|
252
|
+
audit: manualAudit,
|
|
253
|
+
organization: values.org,
|
|
254
|
+
contactEmail: values.contact,
|
|
255
|
+
}))
|
|
256
|
+
if (values.json === true) {
|
|
257
|
+
console.log(JSON.stringify(drafted !== undefined ? { ...report, declaration: { path: drafted.relativePath, status: drafted.status } } : report, null, 2))
|
|
258
|
+
return !report.ok && !wantDraft && values['no-fail'] !== true ? 1 : 0
|
|
259
|
+
}
|
|
260
|
+
console.log(formatA11yReport(report))
|
|
261
|
+
if (drafted !== undefined)
|
|
262
|
+
console.log(`prunelle a11y: drafted RGAA 4.1.2 accessibility declaration at ${drafted.relativePath} (${drafted.status})`)
|
|
263
|
+
if (!report.ok && !wantDraft && values['no-fail'] !== true)
|
|
264
|
+
return fail(`found ${report.totalViolations} accessibility violation${report.totalViolations === 1 ? '' : 's'}`, 1)
|
|
265
|
+
return 0
|
|
266
|
+
},
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
|
|
196
270
|
function ecoCommand(cwd: string): Commands[string] {
|
|
197
271
|
return {
|
|
198
|
-
summary: '
|
|
272
|
+
summary: 'report what prunelle saw of the RGESN eco-design criteria, and draft the declaration',
|
|
199
273
|
run: async (args) => {
|
|
200
|
-
const { values, positionals: [dir] } = parse(args, 'prunelle eco [options] [dir]: builds the app and
|
|
274
|
+
const { values, positionals: [dir] } = parse(args, 'prunelle eco [options] [dir]: builds the app and reports what it saw of the RGESN 2024 criteria, leaving every verdict to a person', {
|
|
201
275
|
declaration: { type: 'string', optional: { bare: '' }, description: 'write an editable RGESN 2024 eco-design declaration page (default: src/routes/ecoconception.tsx)' },
|
|
202
276
|
service: { type: 'string', description: 'the service\'s name, written into --declaration' },
|
|
203
277
|
org: { type: 'string', description: 'the entity running the evaluation, written into --declaration' },
|
|
@@ -212,28 +286,72 @@ function ecoCommand(cwd: string): Commands[string] {
|
|
|
212
286
|
}
|
|
213
287
|
}
|
|
214
288
|
|
|
289
|
+
function rgpdCommand(cwd: string): Commands[string] {
|
|
290
|
+
return {
|
|
291
|
+
summary: 'list the personal data the app processes, and draft the privacy notice and the record of processing',
|
|
292
|
+
run: async (args) => {
|
|
293
|
+
const { values, positionals: [dir] } = parse(args, 'prunelle rgpd [options] [dir]: lists the personal data the plugins declare and the app\'s forms collect, and drafts the RGPD privacy notice and record of processing from it', {
|
|
294
|
+
draft: { type: 'string', optional: { bare: '' }, description: 'write the privacy notice page (default: src/routes/confidentialite.tsx) and registre-des-traitements.md' },
|
|
295
|
+
force: { type: 'boolean', description: 'overwrite files --draft finds already there' },
|
|
296
|
+
org: { type: 'string', description: 'the controller\'s name, written into --draft' },
|
|
297
|
+
contact: { type: 'string', description: 'the contact email for personal data, written into --draft' },
|
|
298
|
+
root: ROOT,
|
|
299
|
+
}, { positionals: ['[dir]'], exits: [OK, [1, 'the config failed to load, or a file --draft would write exists without --force'], USAGE_EXIT] })
|
|
300
|
+
const { formatRgpdResult, runRgpd } = await import('../rgpd/index')
|
|
301
|
+
const result = await failing('rgpd', () => runRgpd({ root: rootOf(cwd, values.root, dir), draft: values.draft, force: values.force === true, organization: values.org, contactEmail: values.contact }))
|
|
302
|
+
console.log(formatRgpdResult(result))
|
|
303
|
+
return 0
|
|
304
|
+
},
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
|
|
215
308
|
const SERVE_EXITS: ExitRow[] = [[0, 'the server started'], [1, 'the config or the server failed to load'], USAGE_EXIT]
|
|
216
309
|
|
|
217
310
|
function startCommand(cwd: string): Commands[string] {
|
|
218
311
|
return {
|
|
219
312
|
summary: 'serve the built app',
|
|
220
313
|
run: async (args) => {
|
|
221
|
-
const { values, positionals: [dir] } = parse(args, 'prunelle start [options] [dir]: serves the built app', {
|
|
314
|
+
const { values, positionals: [dir] } = parse(args, 'prunelle start [options] [dir]: serves the built app', {
|
|
315
|
+
port: PORT,
|
|
316
|
+
host: HOST,
|
|
317
|
+
workers: { type: 'string', description: 'how many processes serve the app on its port, a whole number or auto for one per CPU core (1, Linux only)' },
|
|
318
|
+
root: ROOT,
|
|
319
|
+
}, { positionals: ['[dir]'], exits: SERVE_EXITS })
|
|
222
320
|
const root = rootOf(cwd, values.root, dir)
|
|
223
321
|
process.env.NODE_ENV ??= 'production'
|
|
322
|
+
const { followPrimary, parseWorkers, reportListening, superviseWorkers, workerOf } = await import('../server/workers')
|
|
323
|
+
const worker = workerOf()
|
|
324
|
+
if (worker !== undefined)
|
|
325
|
+
followPrimary()
|
|
326
|
+
const count = worker === undefined && values.workers !== undefined ? parseWorkers(values.workers) ?? badUsage(`invalid --workers "${values.workers}": give how many processes serve the app, a whole number from 1 or auto`) : 1
|
|
327
|
+
if (count > 1 && process.platform !== 'linux')
|
|
328
|
+
return fail(`--workers shares one port between processes, and only Linux spreads connections across them`, 1, `on ${process.platform}, run one process per port behind a proxy`)
|
|
329
|
+
// The primary serves nothing, so it loads neither the config nor the app: each worker does.
|
|
330
|
+
if (count > 1)
|
|
331
|
+
return await superviseWorkers({ count, command: [process.execPath, ...process.execArgv, ...process.argv.slice(1)] }).exited
|
|
224
332
|
const { loadConfig } = await import('../plugins/index')
|
|
225
333
|
const config = await failing('start', async () => loadConfig(root))
|
|
226
334
|
const port = parsePort(values.port ?? (process.env.PORT || config.port), 3000)
|
|
227
335
|
const hostname = values.host ?? (process.env.HOST || '127.0.0.1')
|
|
336
|
+
if (worker !== undefined && port === 0)
|
|
337
|
+
return fail('--workers needs a fixed port, and port 0 gives each process its own', 1, 'set --port or PORT')
|
|
338
|
+
const { loopbackBindNotice } = await import('../server/security')
|
|
339
|
+
const notice = process.env.NODE_ENV === 'production' ? loopbackBindNotice(hostname, values.host !== undefined || Boolean(process.env.HOST)) : undefined
|
|
228
340
|
const { startServer } = await import('../server/start')
|
|
229
341
|
const { handleSignals } = await import('../server/lifecycle')
|
|
230
|
-
const { app, server } = await failing('start', async () => startServer({ root, port, hostname }))
|
|
342
|
+
const { app, server } = await failing('start', async () => startServer({ root, port, hostname, reusePort: worker !== undefined, quietReload: worker !== undefined && worker.index > 1 }))
|
|
231
343
|
handleSignals(app, server)
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
344
|
+
if (worker !== undefined)
|
|
345
|
+
reportListening()
|
|
346
|
+
// The first worker speaks for the others.
|
|
347
|
+
if (worker !== undefined && worker.index > 1)
|
|
348
|
+
return 0
|
|
349
|
+
console.log(`prunelle server listening on http://${hostname}:${server.port}${worker === undefined ? '' : ` with ${worker.count} workers`}`)
|
|
235
350
|
if (notice !== undefined)
|
|
236
351
|
console.warn(notice)
|
|
352
|
+
const perProcess = worker === undefined ? [] : app.perProcessState?.() ?? []
|
|
353
|
+
if (worker !== undefined && perProcess.length > 0)
|
|
354
|
+
console.warn(`prunelle start: ${worker.count} processes serve this app with no \`store\`, so ${perProcess.join('; ')}: set \`store: 'data/app.db'\` in prunelle.config.ts to share them.`)
|
|
237
355
|
return 0
|
|
238
356
|
},
|
|
239
357
|
}
|
|
@@ -245,12 +363,12 @@ function devCommand(cwd: string): Commands[string] {
|
|
|
245
363
|
run: async (args) => {
|
|
246
364
|
const { values, positionals: [dir] } = parse(args, 'prunelle dev [options] [dir]: serves the app and rebuilds it when a file changes', { port: PORT, host: HOST, root: ROOT }, { positionals: ['[dir]'], exits: SERVE_EXITS })
|
|
247
365
|
const root = rootOf(cwd, values.root, dir)
|
|
248
|
-
const { loadConfig
|
|
366
|
+
const { loadConfig } = await import('../plugins/index')
|
|
249
367
|
const config = await failing('dev', async () => loadConfig(root, { dev: true }))
|
|
250
368
|
const port = parsePort(values.port ?? (process.env.PORT || config.port), 3000)
|
|
251
369
|
const hostname = values.host ?? (process.env.HOST || '127.0.0.1')
|
|
252
370
|
const { devSupervisor } = await import('../dev/supervisor')
|
|
253
|
-
const dev = await failing('dev', async () => devSupervisor({ root, port, hostname
|
|
371
|
+
const dev = await failing('dev', async () => devSupervisor({ root, port, hostname }))
|
|
254
372
|
for (const signal of ['SIGINT', 'SIGTERM'] as const)
|
|
255
373
|
process.once(signal, () => void dev.stop().finally(() => process.exit(0)))
|
|
256
374
|
return 0
|
|
@@ -262,7 +380,7 @@ function docsCommand(cwd: string): Commands[string] {
|
|
|
262
380
|
return {
|
|
263
381
|
summary: 'search llms.txt across prunelle and installed plugins',
|
|
264
382
|
run: async (args) => {
|
|
265
|
-
const { values, positionals } = parse(args, 'prunelle docs [options] <words...>: searches llms.txt of prunelle
|
|
383
|
+
const { values, positionals } = parse(args, 'prunelle docs [options] <words...>: searches llms.txt of prunelle, every installed @prunellejs/* package and every dependency of the app that ships one', {
|
|
266
384
|
json: { type: 'boolean', description: 'print { query, words, packages, matches } as JSON' },
|
|
267
385
|
limit: { type: 'string', description: 'maximum matching sections to print (default: 20)' },
|
|
268
386
|
root: ROOT,
|
|
@@ -342,7 +460,9 @@ export function builtinCommands(cwd: string): Commands {
|
|
|
342
460
|
mcp: mcpCommand(cwd),
|
|
343
461
|
dev: devCommand(cwd),
|
|
344
462
|
build: buildCommand(cwd),
|
|
463
|
+
a11y: a11yCommand(cwd),
|
|
345
464
|
eco: ecoCommand(cwd),
|
|
465
|
+
rgpd: rgpdCommand(cwd),
|
|
346
466
|
start: startCommand(cwd),
|
|
347
467
|
upgrade: upgradeCommand(cwd),
|
|
348
468
|
}
|
package/src/cli/docs.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
// `prunelle docs <words>`: discover and search installed `llms.txt` files for `prunelle
|
|
1
|
+
// `prunelle docs <words>`: discover and search installed `llms.txt` files for `prunelle`, `@prunellejs/*` packages and the app's other dependencies.
|
|
2
2
|
|
|
3
3
|
import { readdirSync, readFileSync, statSync } from 'node:fs'
|
|
4
4
|
import { dirname, join, resolve } from 'node:path'
|
|
@@ -119,11 +119,26 @@ function scanScopedPackages(
|
|
|
119
119
|
}
|
|
120
120
|
}
|
|
121
121
|
|
|
122
|
-
|
|
122
|
+
// A third-party plugin has no scope of its own, so it is found as a dependency the app declares; one it does not declare is a dependency's, whose docs it never asked for.
|
|
123
|
+
function declaredDependencies(root: string): string[] {
|
|
124
|
+
const pkgJsonPath = join(root, 'package.json')
|
|
125
|
+
if (!isFile(pkgJsonPath))
|
|
126
|
+
return []
|
|
127
|
+
try {
|
|
128
|
+
const parsed = JSON.parse(readFileSync(pkgJsonPath, 'utf8')) as { dependencies?: Record<string, string>, devDependencies?: Record<string, string> }
|
|
129
|
+
return [...Object.keys(parsed.dependencies ?? {}), ...Object.keys(parsed.devDependencies ?? {})]
|
|
130
|
+
}
|
|
131
|
+
catch {
|
|
132
|
+
return []
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/** Discovers `llms.txt` files for `prunelle`, installed `@prunellejs/*` (and `@prunelle/*`) packages, and every dependency `rootDir`'s `package.json` declares, from `rootDir` up through ancestor `node_modules`. */
|
|
123
137
|
export function discoverLlmsDocs(rootDir: string): LlmsPackageDoc[] {
|
|
124
138
|
const root = resolve(rootDir)
|
|
125
139
|
const docs: LlmsPackageDoc[] = []
|
|
126
140
|
const seen = new Set<string>()
|
|
141
|
+
const dependencies = declaredDependencies(root)
|
|
127
142
|
|
|
128
143
|
let dir = root
|
|
129
144
|
while (true) {
|
|
@@ -132,6 +147,10 @@ export function discoverLlmsDocs(rootDir: string): LlmsPackageDoc[] {
|
|
|
132
147
|
if (!seen.has('prunelle'))
|
|
133
148
|
addPackageDoc(docs, seen, root, join(nodeModulesDir, 'prunelle'), 'prunelle')
|
|
134
149
|
scanScopedPackages(docs, seen, root, nodeModulesDir)
|
|
150
|
+
for (const name of dependencies) {
|
|
151
|
+
if (!seen.has(name))
|
|
152
|
+
addPackageDoc(docs, seen, root, join(nodeModulesDir, name), name)
|
|
153
|
+
}
|
|
135
154
|
}
|
|
136
155
|
const parent = dirname(dir)
|
|
137
156
|
if (parent === dir)
|
package/src/cli/index.ts
CHANGED
|
@@ -38,7 +38,7 @@ function pluginCommands(cwd: string): (words: string[]) => Promise<Commands> {
|
|
|
38
38
|
root: { type: 'string', description: 'the app directory (default: the current one)' },
|
|
39
39
|
})
|
|
40
40
|
const taken = takeRoot(args, cwd)
|
|
41
|
-
await run(taken.rest, taken.root)
|
|
41
|
+
await run(taken.rest, taken.root, { store: config.store })
|
|
42
42
|
return 0
|
|
43
43
|
},
|
|
44
44
|
}
|
package/src/cli/inspect.ts
CHANGED
package/src/cli/mcp-tools.ts
CHANGED
|
@@ -240,7 +240,7 @@ export function listPrunelleTools(): McpToolDefinition[] {
|
|
|
240
240
|
},
|
|
241
241
|
{
|
|
242
242
|
name: 'docs',
|
|
243
|
-
description: 'Search `llms.txt` documentation across `prunelle
|
|
243
|
+
description: 'Search `llms.txt` documentation across `prunelle`, every installed `@prunellejs/*` package, and every dependency of the app that ships one.',
|
|
244
244
|
inputSchema: {
|
|
245
245
|
type: 'object',
|
|
246
246
|
properties: {
|
|
@@ -466,7 +466,7 @@ export async function callPrunelleTool(ctx: PrunelleMcpContext, name: string, ra
|
|
|
466
466
|
}
|
|
467
467
|
}
|
|
468
468
|
|
|
469
|
-
/** Lists every discovered `llms.txt` (`prunelle
|
|
469
|
+
/** Lists every discovered `llms.txt` (`prunelle`, installed `@prunellejs/*` packages and the app's dependencies) as an MCP resource. */
|
|
470
470
|
export function listPrunelleResources(root: string): McpResource[] {
|
|
471
471
|
return discoverLlmsDocs(root).map(doc => ({
|
|
472
472
|
uri: `${LLMS_URI_PREFIX}${doc.packageName}`,
|
package/src/cli/new.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
// `prunelle new <name> [--template minimal|fullstack|blog|app] [--force]` project scaffolder: copies `templates/_shared` and `templates/<template
|
|
1
|
+
// `prunelle new <name> [--template minimal|fullstack|blog|app|plugin] [--force]` project scaffolder: copies `templates/_shared` and `templates/<template>`, or `templates/plugin` alone.
|
|
2
2
|
|
|
3
3
|
import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs'
|
|
4
4
|
import { basename, dirname, join, resolve } from 'node:path'
|
|
@@ -6,7 +6,7 @@ import pkg from '../../package.json' with { type: 'json' }
|
|
|
6
6
|
import { DEFAULT_DECLARATION_PATH, draftAccessibilityStatement } from '../a11y/declaration'
|
|
7
7
|
import { isNotSourceDir, relPosix, walkFiles } from '../build/files'
|
|
8
8
|
|
|
9
|
-
export type ScaffoldTemplate = 'minimal' | 'fullstack' | 'blog' | 'app'
|
|
9
|
+
export type ScaffoldTemplate = 'minimal' | 'fullstack' | 'blog' | 'app' | 'plugin'
|
|
10
10
|
|
|
11
11
|
export interface ScaffoldOptions {
|
|
12
12
|
template?: ScaffoldTemplate | undefined
|
|
@@ -17,7 +17,7 @@ export interface ScaffoldOptions {
|
|
|
17
17
|
const TEMPLATES_DIR = join(import.meta.dir, '../../templates')
|
|
18
18
|
|
|
19
19
|
// npm leaves dotfiles like `.gitignore` out of a package, so the template stores them without the leading dot.
|
|
20
|
-
const RENAMED: Record<string, string> = { 'gitignore': '.gitignore', 'mcp.json': '.mcp.json' }
|
|
20
|
+
const RENAMED: Record<string, string> = { 'gitignore': '.gitignore', 'dockerignore': '.dockerignore', 'mcp.json': '.mcp.json' }
|
|
21
21
|
|
|
22
22
|
// What a fresh `git init` leaves in a folder: it does not make the folder one with work in it.
|
|
23
23
|
const FRESH_REPO_ENTRIES = new Set(['.git'])
|
|
@@ -33,10 +33,12 @@ export function scaffoldProject(targetDir: string, options: ScaffoldOptions = {}
|
|
|
33
33
|
|
|
34
34
|
const written: string[] = []
|
|
35
35
|
const overwritten: string[] = []
|
|
36
|
-
|
|
36
|
+
// A plugin is a package, not an app: it gets none of an app's pages, Docker files or accessibility statement.
|
|
37
|
+
const isPlugin = template === 'plugin'
|
|
38
|
+
for (const dir of isPlugin ? [join(TEMPLATES_DIR, template)] : [join(TEMPLATES_DIR, '_shared'), join(TEMPLATES_DIR, template)]) {
|
|
37
39
|
for (const abs of walkFiles(dir, { skipDir: isNotSourceDir, keep: entry => entry.isFile() })) {
|
|
38
40
|
const rel = RENAMED[relPosix(dir, abs)] ?? relPosix(dir, abs)
|
|
39
|
-
const text = readFileSync(abs, 'utf8').replaceAll('__APP_NAME__', name).replaceAll('__PRUNELLE_VERSION__', prunelleVersion)
|
|
41
|
+
const text = readFileSync(abs, 'utf8').replaceAll('__APP_NAME__', name).replaceAll('__PRUNELLE_VERSION__', prunelleVersion).replaceAll('__BUN_VERSION__', Bun.version)
|
|
40
42
|
if (existsSync(join(root, rel)))
|
|
41
43
|
overwritten.push(rel)
|
|
42
44
|
mkdirSync(dirname(join(root, rel)), { recursive: true })
|
|
@@ -44,6 +46,8 @@ export function scaffoldProject(targetDir: string, options: ScaffoldOptions = {}
|
|
|
44
46
|
written.push(rel)
|
|
45
47
|
}
|
|
46
48
|
}
|
|
49
|
+
if (isPlugin)
|
|
50
|
+
return { root, files: written, overwritten }
|
|
47
51
|
// Drafted rather than copied, so it is dated on the day the app is made and never drifts from what `prunelle a11y --draft` writes.
|
|
48
52
|
if (existsSync(join(root, DEFAULT_DECLARATION_PATH)))
|
|
49
53
|
overwritten.push(DEFAULT_DECLARATION_PATH)
|