prunelle 0.1.1 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/llms.txt +12 -12
- package/package.json +1 -1
- package/src/build/client-entries.ts +3 -2
- package/src/build/compile.ts +2 -1
- package/src/build/index.ts +68 -29
- package/src/build/manifest.ts +18 -1
- package/src/build/output.ts +2 -2
- package/src/build/precompress.ts +15 -2
- package/src/build/prerender.ts +2 -2
- package/src/build/routes.ts +171 -10
- package/src/build/static.ts +71 -17
- package/src/build/status-pages.ts +127 -0
- package/src/cli/check-forms.ts +654 -0
- package/src/cli/check-links.ts +619 -0
- package/src/cli/check.ts +37 -4
- package/src/cli/commands.ts +5 -3
- package/src/cli/inspect.ts +21 -2
- package/src/cli/upgrade-names.ts +73 -13
- package/src/cli/upgrade.ts +137 -16
- package/src/compiler/compliance-rgaa.ts +502 -0
- package/src/compiler/compliance.ts +119 -220
- package/src/compiler/ssr.ts +121 -24
- package/src/dom/action.ts +4 -1
- package/src/dom/island.ts +5 -5
- package/src/plugins/config.ts +1 -1
- package/src/plugins/types.ts +13 -0
- package/src/server/action-protect.ts +186 -0
- package/src/server/action.ts +33 -10
- package/src/server/errors.ts +291 -62
- package/src/server/form-schema.ts +343 -0
- package/src/server/health.ts +244 -0
- package/src/server/http.ts +84 -17
- package/src/server/index.ts +162 -91
- package/src/server/param-matchers.ts +112 -0
- package/src/server/plugin-host.ts +40 -14
- package/src/server/public.ts +3 -3
- package/src/server/route-table.ts +5 -2
- package/src/server/router.ts +125 -40
- package/src/server/routing.ts +95 -57
- package/src/server/security.ts +171 -22
- package/src/server/serve-handlers.ts +21 -7
- package/src/ssr/context.ts +49 -0
- package/src/ssr/index.ts +120 -1
- package/src/test/browser.ts +6 -0
- package/src/test/index.ts +17 -3
- package/templates/_shared/src/routes/legal.tsx +5 -0
- package/templates/blog/prunelle.config.ts +1 -1
- package/templates/blog/src/routes/index.tsx +4 -0
package/src/cli/check.ts
CHANGED
|
@@ -3,20 +3,23 @@
|
|
|
3
3
|
import type { IslandIssue } from '../build/islands'
|
|
4
4
|
import type { ModuleAnalysis } from '../compiler/analyze'
|
|
5
5
|
import type { ComplianceConfig } from '../compiler/compliance'
|
|
6
|
-
import type { CheckPluginContext, PrunellePlugin } from '../plugins/index'
|
|
6
|
+
import type { CheckPluginContext, PrunelleConfig, PrunellePlugin } from '../plugins/index'
|
|
7
7
|
import { existsSync, readFileSync } from 'node:fs'
|
|
8
8
|
import { basename, join, relative, resolve } from 'node:path'
|
|
9
9
|
import { isInNodeModules, isNotSourceDir, isTsFile, relPosix, walkFiles, walkRoutes } from '../build/files'
|
|
10
10
|
import { ModuleGraph } from '../build/graph'
|
|
11
11
|
import { nodeEnvWarning, renderProblems, serverNodeEnvReads } from '../build/render-rules'
|
|
12
12
|
import { analyzeIslands } from '../build/islands'
|
|
13
|
-
import { fileToRoutePath, hasRouteHandlerExport, missingPathsProblem, normalizeRoutePattern, routeExportProblemLocation, routeFileProblem, SPECIAL_ROUTE_FILES } from '../build/routes'
|
|
13
|
+
import { discoverRouteMatchers, fileToRoutePath, hasRouteHandlerExport, missingPathsProblem, normalizeRoutePattern, routeExportProblemLocation, routeFileProblem, SPECIAL_ROUTE_FILES } from '../build/routes'
|
|
14
|
+
import { findUnknownStatusPages } from '../build/status-pages'
|
|
14
15
|
import { analyzeModule } from '../compiler/analyze'
|
|
15
16
|
import { collectProjectComplianceWarnings, shouldEmitWarning } from '../compiler/compliance'
|
|
16
17
|
import { collectMistakes, PrunelleMistake, serverOnlyTagError } from '../compiler/mistakes'
|
|
17
18
|
import { DIAGNOSTIC_PREFIX_RE, formatDiagnostic, formatLoc } from '../compiler/shared'
|
|
18
19
|
import { createAppContext, loadConfig, resolvePlugins, runWithAppContext } from '../plugins/index'
|
|
19
20
|
import { collectRequirements } from '../plugins/requires'
|
|
21
|
+
import { checkAppForms } from './check-forms'
|
|
22
|
+
import { checkAppLinks } from './check-links'
|
|
20
23
|
|
|
21
24
|
/** Whether `prunelle check` typechecked the app, with which tool, or why it did not. */
|
|
22
25
|
export type TypecheckRun = { ran: true, tool: string } | { ran: false, reason: string }
|
|
@@ -176,7 +179,7 @@ function formatIslandIssue(issue: IslandIssue, root: string, sources: Map<string
|
|
|
176
179
|
// Each plugin's check(ctx) runs inside a real AppRuntimeContext; what it reports without a place lands on prunelle.config.ts.
|
|
177
180
|
async function runPluginChecks(plugins: readonly PrunellePlugin[], paths: { root: string, routesDir: string, outDir: string, assetPrefix: string, site: string | undefined }, errors: string[], warnings: string[]): Promise<void> {
|
|
178
181
|
const { root, routesDir, outDir, assetPrefix, site } = paths
|
|
179
|
-
const appCtx = createAppContext({ root, outDir, publicDir: join(outDir, 'public'), assetPrefix, dev: false })
|
|
182
|
+
const appCtx = createAppContext({ root, outDir, publicDir: join(outDir, 'public'), assetPrefix, site, dev: false })
|
|
180
183
|
const placed = (message: string, severity: 'error' | 'warning'): string =>
|
|
181
184
|
DIAGNOSTIC_PREFIX_RE.test(message) ? message : formatDiagnostic('prunelle.config.ts:1:1', message, severity)
|
|
182
185
|
const pluginCtx: CheckPluginContext = {
|
|
@@ -210,12 +213,15 @@ export async function checkProject(rootDir: string, options: { skipTypecheck?: b
|
|
|
210
213
|
// 1. Validate prunelle.config.ts
|
|
211
214
|
let routesDir = resolve(root, 'src/routes')
|
|
212
215
|
let outDir = resolve(root, 'dist')
|
|
216
|
+
let publicDir = resolve(root, 'public')
|
|
213
217
|
let assetPrefix = '/_pru'
|
|
214
218
|
let site: string | undefined
|
|
215
219
|
let compliance: ComplianceConfig | undefined
|
|
220
|
+
let loadedConfig: PrunelleConfig = {}
|
|
216
221
|
let plugins: Awaited<ReturnType<typeof loadConfig>>['plugins'] = []
|
|
217
222
|
try {
|
|
218
223
|
const cfg = await loadConfig(root)
|
|
224
|
+
loadedConfig = cfg
|
|
219
225
|
plugins = resolvePlugins(cfg.plugins)
|
|
220
226
|
site = cfg.site
|
|
221
227
|
compliance = cfg.compliance
|
|
@@ -223,6 +229,8 @@ export async function checkProject(rootDir: string, options: { skipTypecheck?: b
|
|
|
223
229
|
routesDir = resolve(root, cfg.routesDir)
|
|
224
230
|
if (cfg.outDir !== undefined)
|
|
225
231
|
outDir = resolve(root, cfg.outDir)
|
|
232
|
+
if (cfg.publicDir !== undefined)
|
|
233
|
+
publicDir = resolve(root, cfg.publicDir)
|
|
226
234
|
if (cfg.assetPrefix !== undefined)
|
|
227
235
|
assetPrefix = cfg.assetPrefix.replace(/\/$/, '')
|
|
228
236
|
}
|
|
@@ -265,9 +273,19 @@ export async function checkProject(rootDir: string, options: { skipTypecheck?: b
|
|
|
265
273
|
|
|
266
274
|
// Exact route discovery matching `prunelle build` (`walkRoutes` skips `_components/` dirs, `.d.ts`, `.test.ts`)
|
|
267
275
|
const routeFiles = existsSync(routesDir) ? walkRoutes(routesDir).sort() : []
|
|
276
|
+
for (const unknown of findUnknownStatusPages(root, routeFiles))
|
|
277
|
+
errors.push(formatDiagnostic(`${relPosix(root, unknown.file)}:1:1`, `prunelle check: ${unknown.message}`))
|
|
268
278
|
const routeFileSet = new Set(routeFiles)
|
|
269
279
|
const specialFiles = routeFiles.filter(f => SPECIAL_ROUTE_FILES.has(basename(f)))
|
|
270
280
|
const pageFiles = routeFiles.filter(f => !basename(f).startsWith('_') && analyses.has(f) && hasRouteHandlerExport(analyses.get(f)!))
|
|
281
|
+
const matcherDiscovery = discoverRouteMatchers({
|
|
282
|
+
root,
|
|
283
|
+
routesDir,
|
|
284
|
+
routeFiles: [...specialFiles, ...pageFiles],
|
|
285
|
+
loadAnalysis: load,
|
|
286
|
+
})
|
|
287
|
+
for (const problem of matcherDiscovery.problems)
|
|
288
|
+
errors.push(formatDiagnostic(`${relPosix(root, problem.file)}:1:1`, `prunelle check: ${problem.message}`))
|
|
271
289
|
|
|
272
290
|
// 3a. Unified island planning, state-read promotion, special-file checks & reachability checks (shared with `prunelle build`)
|
|
273
291
|
const islands = analyzeIslands({
|
|
@@ -288,6 +306,13 @@ export async function checkProject(rootDir: string, options: { skipTypecheck?: b
|
|
|
288
306
|
if (isInNodeModules(file))
|
|
289
307
|
continue
|
|
290
308
|
const rel = relPosix(root, file)
|
|
309
|
+
for (const imp of analysis.imports) {
|
|
310
|
+
if (imp.source === '@prunellejs/auth') {
|
|
311
|
+
const removed = imp.specifiers.find(s => s.imported === 'createRateLimiter' || s.imported === 'RateLimiter')
|
|
312
|
+
if (removed !== undefined)
|
|
313
|
+
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'))
|
|
314
|
+
}
|
|
315
|
+
}
|
|
291
316
|
for (const offset of serverNodeEnvReads(analysis, islands, file))
|
|
292
317
|
warnings.push(formatDiagnostic(locOf(root, file, sources, offset), nodeEnvWarning(rel), 'warning'))
|
|
293
318
|
|
|
@@ -325,7 +350,15 @@ export async function checkProject(rootDir: string, options: { skipTypecheck?: b
|
|
|
325
350
|
// 3c. French web law compliance checks (CSS third-party URLs, LCEN legal notice, RGAA accessibility statement)
|
|
326
351
|
warnings.push(...collectProjectComplianceWarnings({ root, srcDir, routesDir, routeFiles, analyses, compliance, site }))
|
|
327
352
|
|
|
328
|
-
// 3d.
|
|
353
|
+
// 3d. Form field / schema checks & public action protection warnings (#4, #5)
|
|
354
|
+
const formCheck = await checkAppForms({ root, routesDir, routeFiles, graph, sources })
|
|
355
|
+
errors.push(...formCheck.errors)
|
|
356
|
+
warnings.push(...formCheck.warnings)
|
|
357
|
+
|
|
358
|
+
// 3e. Broken internal link checks (#3)
|
|
359
|
+
warnings.push(...await checkAppLinks({ root, routesDir, publicDir, assetPrefix, site, config: loadedConfig, plugins, routeFiles, analyses, sources }))
|
|
360
|
+
|
|
361
|
+
// 3f. Plugin check(ctx) hooks
|
|
329
362
|
await runPluginChecks(plugins, { root, routesDir, outDir, assetPrefix, site }, errors, warnings)
|
|
330
363
|
|
|
331
364
|
const typecheck = options.skipTypecheck === true ? { ran: false as const, reason: "skipped by --no-typecheck" } : runTypecheck(root, errors)
|
package/src/cli/commands.ts
CHANGED
|
@@ -123,13 +123,15 @@ function upgradeCommand(cwd: string): Commands[string] {
|
|
|
123
123
|
const res = upgradeProject(root)
|
|
124
124
|
for (const file of res.changed)
|
|
125
125
|
console.log(` ${file}`)
|
|
126
|
-
console.log(`prunelle upgrade rewrote ${res.changed.length}
|
|
127
|
-
|
|
126
|
+
console.log(`prunelle upgrade rewrote ${res.changed.length} file${res.changed.length === 1 ? '' : 's'}`)
|
|
127
|
+
// The dependencies moved: the first run for this app, which renames its cookies; a later run only fixes what an older prunelle left.
|
|
128
|
+
const moved = res.changed.some(file => file === 'package.json' || file.endsWith('/package.json'))
|
|
129
|
+
if (moved && values['no-install'] !== true) {
|
|
128
130
|
const install = Bun.spawnSync(['bun', 'install'], { cwd: root, stdout: 'inherit', stderr: 'inherit' })
|
|
129
131
|
if (install.exitCode !== 0)
|
|
130
132
|
return 1
|
|
131
133
|
}
|
|
132
|
-
if (
|
|
134
|
+
if (moved)
|
|
133
135
|
console.log('Signed-in users sign in again and visitors answer the cookie banner again: prunelle names its cookies pru_session and pru_consent.')
|
|
134
136
|
for (const line of res.manual)
|
|
135
137
|
console.error(line)
|
package/src/cli/inspect.ts
CHANGED
|
@@ -8,9 +8,10 @@ import { relPosix, walkRoutes } from '../build/files'
|
|
|
8
8
|
import { ModuleGraph } from '../build/graph'
|
|
9
9
|
import { analyzeIslands } from '../build/islands'
|
|
10
10
|
import { buildActionEntries, buildRouteEntries } from '../build/manifest'
|
|
11
|
-
import { hasRouteHandlerExport, SPECIAL_ROUTE_FILES } from '../build/routes'
|
|
11
|
+
import { hasRouteHandlerExport, routeGroupsOf, SPECIAL_ROUTE_FILES } from '../build/routes'
|
|
12
12
|
import { createAppContext, loadConfig, pickRuntimeConfig, resolvePlugins, runWithAppContext } from '../plugins/index'
|
|
13
13
|
import { actionHash } from '../server/action'
|
|
14
|
+
import { extractOptionalParams, extractPatternMatchers } from '../server/param-matchers'
|
|
14
15
|
|
|
15
16
|
const HTTP_METHODS = new Set(['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'])
|
|
16
17
|
|
|
@@ -19,6 +20,9 @@ export interface InspectRoute {
|
|
|
19
20
|
file?: string | undefined
|
|
20
21
|
plugin?: string | undefined
|
|
21
22
|
methods?: string[] | undefined
|
|
23
|
+
groups?: string[] | undefined
|
|
24
|
+
matchers?: Record<string, string> | undefined
|
|
25
|
+
optionalParams?: string[] | undefined
|
|
22
26
|
layouts: string[]
|
|
23
27
|
middlewares: string[]
|
|
24
28
|
load: boolean
|
|
@@ -106,6 +110,7 @@ async function discoverPluginRoutes(
|
|
|
106
110
|
},
|
|
107
111
|
inject: key => services.get(key.name) as never,
|
|
108
112
|
getBuildData: () => undefined,
|
|
113
|
+
healthCheck: () => {},
|
|
109
114
|
onShutdown: (fn) => {
|
|
110
115
|
shutdowns.push(fn)
|
|
111
116
|
},
|
|
@@ -198,13 +203,21 @@ export async function inspectProject(rootDir: string): Promise<InspectReport> {
|
|
|
198
203
|
})
|
|
199
204
|
|
|
200
205
|
const fileRoutes: InspectRoute[] = routeEntries.map((entry, idx) => {
|
|
201
|
-
const
|
|
206
|
+
const pageFile = pageFiles[idx]!
|
|
207
|
+
const analysis = graph.analyses.get(pageFile)
|
|
202
208
|
const hasDefault = analysis?.exportedNames.includes('default') === true
|
|
203
209
|
const methods = analysis?.exportedNames.filter(name => HTTP_METHODS.has(name)) ?? []
|
|
210
|
+
const groups = routeGroupsOf(routesDir, pageFile)
|
|
211
|
+
const matcherRefs = extractPatternMatchers(entry.path)
|
|
212
|
+
const matchers = matcherRefs.length > 0 ? Object.fromEntries(matcherRefs.map(m => [m.param, m.matcher])) : undefined
|
|
213
|
+
const optionalParams = extractOptionalParams(entry.path)
|
|
204
214
|
return {
|
|
205
215
|
path: entry.path,
|
|
206
216
|
file: entry.file,
|
|
207
217
|
...(methods.length > 0 ? { methods } : {}),
|
|
218
|
+
...(groups.length > 0 ? { groups } : {}),
|
|
219
|
+
...(matchers !== undefined ? { matchers } : {}),
|
|
220
|
+
...(optionalParams.length > 0 ? { optionalParams } : {}),
|
|
208
221
|
layouts: hasDefault ? entry.layouts : [],
|
|
209
222
|
middlewares: entry.middlewares,
|
|
210
223
|
load: entry.hasLoad === true,
|
|
@@ -261,6 +274,12 @@ export function formatInspectReport(report: InspectReport): string {
|
|
|
261
274
|
if (r.methods !== undefined && r.methods.length > 0)
|
|
262
275
|
parts.push(r.methods.join(','))
|
|
263
276
|
parts.push(r.file ?? `(plugin: ${r.plugin})`)
|
|
277
|
+
if (r.groups !== undefined && r.groups.length > 0)
|
|
278
|
+
parts.push(`groups=[${r.groups.join(', ')}]`)
|
|
279
|
+
if (r.matchers !== undefined)
|
|
280
|
+
parts.push(`matchers=[${Object.entries(r.matchers).map(([k, v]) => `${k}=${v}`).join(', ')}]`)
|
|
281
|
+
if (r.optionalParams !== undefined && r.optionalParams.length > 0)
|
|
282
|
+
parts.push(`optional=[${r.optionalParams.join(', ')}]`)
|
|
264
283
|
if (r.load)
|
|
265
284
|
parts.push('load')
|
|
266
285
|
if (r.prerender)
|
package/src/cli/upgrade-names.ts
CHANGED
|
@@ -6,6 +6,7 @@ import { walk } from '../compiler/ast'
|
|
|
6
6
|
import { SourceEditor } from '../compiler/patch'
|
|
7
7
|
|
|
8
8
|
const KAY_SOURCE_RE = /^@kayjs\//
|
|
9
|
+
const REF_TYPES_RE = /^(\s*\/\/\/\s*<reference\s+types=)(["'])([^"']+)\2(\s*\/>)/gm
|
|
9
10
|
|
|
10
11
|
type Import = Extract<AstNode, { type: 'ImportDeclaration' }>
|
|
11
12
|
type Specifier = Extract<AstNode, { type: 'ImportSpecifier' }>
|
|
@@ -25,17 +26,61 @@ export function prunelleName(name: string): string | undefined {
|
|
|
25
26
|
}
|
|
26
27
|
|
|
27
28
|
const nameOf = (node: { type: string, name?: string, value?: unknown }): string => node.type === 'Identifier' ? node.name! : String(node.value)
|
|
28
|
-
const fromKay = (source: { value: unknown } | null | undefined): boolean => typeof source?.value === 'string' && KAY_SOURCE_RE.test(source.value)
|
|
29
29
|
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
30
|
+
function resolveAlias(spec: string, aliases?: ReadonlyMap<string, string>): string | undefined {
|
|
31
|
+
if (aliases === undefined || aliases.size === 0)
|
|
32
|
+
return undefined
|
|
33
|
+
for (const [alias, target] of aliases) {
|
|
34
|
+
if (spec === alias)
|
|
35
|
+
return target
|
|
36
|
+
if (spec.startsWith(`${alias}/`))
|
|
37
|
+
return `${target}${spec.slice(alias.length)}`
|
|
38
|
+
}
|
|
39
|
+
return undefined
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function hasKaySourceHint(code: string, aliases?: ReadonlyMap<string, string>): boolean {
|
|
43
|
+
if (code.includes('@kayjs/'))
|
|
44
|
+
return true
|
|
45
|
+
if (aliases === undefined || aliases.size === 0)
|
|
46
|
+
return false
|
|
47
|
+
for (const alias of aliases.keys()) {
|
|
48
|
+
if (code.includes(alias))
|
|
49
|
+
return true
|
|
50
|
+
}
|
|
51
|
+
return false
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function rewriteTripleSlash(code: string, aliases?: ReadonlyMap<string, string>): string {
|
|
55
|
+
if (aliases === undefined || aliases.size === 0 || !code.includes('<reference'))
|
|
56
|
+
return code
|
|
57
|
+
return code.replace(REF_TYPES_RE, (full, pre: string, quote: string, spec: string, post: string) => {
|
|
58
|
+
const target = resolveAlias(spec, aliases)
|
|
59
|
+
return target === undefined ? full : `${pre}${quote}${target}${quote}${post}`
|
|
60
|
+
})
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** Rewrites the names `code` imports from `@kayjs/*` (and any npm aliases in `aliases`), plus alias module specifiers, run before `@kayjs/*` specifiers are renamed. */
|
|
64
|
+
export function renameKayNames(file: string, code: string, aliases?: ReadonlyMap<string, string>): string {
|
|
65
|
+
if (!hasKaySourceHint(code, aliases))
|
|
33
66
|
return code
|
|
34
67
|
const program = parseTsx(file, code)
|
|
35
68
|
const editor = new SourceEditor(code)
|
|
36
69
|
const bindings = new Map<string, Binding>()
|
|
37
70
|
const namespaces = new Set<string>()
|
|
38
71
|
const skipped = new Set<number>()
|
|
72
|
+
const patchedSources = new Set<number>()
|
|
73
|
+
const fromKay = (source: { value?: unknown } | null | undefined): boolean =>
|
|
74
|
+
typeof source?.value === 'string' && (KAY_SOURCE_RE.test(source.value) || resolveAlias(source.value, aliases) !== undefined)
|
|
75
|
+
const rewriteSource = (source: { start: number, end: number, value?: unknown } | null | undefined): void => {
|
|
76
|
+
if (source === null || source === undefined || typeof source.value !== 'string' || patchedSources.has(source.start))
|
|
77
|
+
return
|
|
78
|
+
const target = resolveAlias(source.value, aliases)
|
|
79
|
+
if (target === undefined)
|
|
80
|
+
return
|
|
81
|
+
patchedSources.add(source.start)
|
|
82
|
+
editor.replace(source.start + 1, source.end - 1, target)
|
|
83
|
+
}
|
|
39
84
|
const rename = (node: AstNode): void => {
|
|
40
85
|
const renamed = node.type === 'Identifier' || node.type === 'JSXIdentifier' ? prunelleName(node.name) : undefined
|
|
41
86
|
if (renamed !== undefined)
|
|
@@ -45,8 +90,11 @@ export function renameKayNames(file: string, code: string): string {
|
|
|
45
90
|
for (const stmt of program.body) {
|
|
46
91
|
if (stmt.type === 'ImportDeclaration' && fromKay(stmt.source))
|
|
47
92
|
collectImport(stmt, bindings, namespaces)
|
|
48
|
-
if (stmt.type === 'TSModuleDeclaration' && stmt.id.type === 'Literal'
|
|
49
|
-
|
|
93
|
+
if (stmt.type === 'TSModuleDeclaration' && stmt.id.type === 'Literal') {
|
|
94
|
+
rewriteSource(stmt.id)
|
|
95
|
+
if (fromKay(stmt.id))
|
|
96
|
+
renameAugmented(stmt.body, rename)
|
|
97
|
+
}
|
|
50
98
|
}
|
|
51
99
|
|
|
52
100
|
const names = new Set<string>()
|
|
@@ -56,13 +104,22 @@ export function renameKayNames(file: string, code: string): string {
|
|
|
56
104
|
binding.pinned = true
|
|
57
105
|
}
|
|
58
106
|
walk(program.body, (node) => {
|
|
59
|
-
if (node.type === 'ImportDeclaration')
|
|
107
|
+
if (node.type === 'ImportDeclaration') {
|
|
108
|
+
rewriteSource(node.source)
|
|
60
109
|
return false
|
|
110
|
+
}
|
|
61
111
|
if (node.type === 'ExportNamedDeclaration' && node.source !== null) {
|
|
112
|
+
rewriteSource(node.source)
|
|
62
113
|
if (fromKay(node.source))
|
|
63
114
|
reexport(node.specifiers, editor)
|
|
64
115
|
return false
|
|
65
116
|
}
|
|
117
|
+
if (node.type === 'ExportAllDeclaration') {
|
|
118
|
+
rewriteSource(node.source)
|
|
119
|
+
return false
|
|
120
|
+
}
|
|
121
|
+
if (node.type === 'ImportExpression' && node.source.type === 'Literal')
|
|
122
|
+
rewriteSource(node.source)
|
|
66
123
|
// Every keyed node (property, method, class field, type member) names its key, which is no reference.
|
|
67
124
|
const keyed = node as AstNode & { key?: AstNode & { type: string, name?: string }, computed?: boolean, shorthand?: boolean }
|
|
68
125
|
if (keyed.key !== undefined && keyed.computed === false) {
|
|
@@ -79,11 +136,14 @@ export function renameKayNames(file: string, code: string): string {
|
|
|
79
136
|
rename(right)
|
|
80
137
|
skipped.add(right.start)
|
|
81
138
|
}
|
|
82
|
-
if (node.type === 'TSImportType'
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
head =
|
|
86
|
-
|
|
139
|
+
if (node.type === 'TSImportType') {
|
|
140
|
+
rewriteSource(node.source)
|
|
141
|
+
if (fromKay(node.source) && node.qualifier !== null) {
|
|
142
|
+
let head: AstNode = node.qualifier
|
|
143
|
+
while (head.type === 'TSQualifiedName')
|
|
144
|
+
head = head.left
|
|
145
|
+
rename(head)
|
|
146
|
+
}
|
|
87
147
|
}
|
|
88
148
|
if (node.type === 'ExportSpecifier')
|
|
89
149
|
pin(nameOf(node.local))
|
|
@@ -109,7 +169,7 @@ export function renameKayNames(file: string, code: string): string {
|
|
|
109
169
|
for (const ref of binding.refs)
|
|
110
170
|
editor.replace(ref.start, ref.end, binding.renamed)
|
|
111
171
|
}
|
|
112
|
-
return editor.toString()
|
|
172
|
+
return rewriteTripleSlash(editor.toString(), aliases)
|
|
113
173
|
}
|
|
114
174
|
|
|
115
175
|
function collectImport(stmt: Import, bindings: Map<string, Binding>, namespaces: Set<string>): void {
|
package/src/cli/upgrade.ts
CHANGED
|
@@ -1,11 +1,13 @@
|
|
|
1
1
|
// `prunelle upgrade`: moves an app written for kay v2 (`@kayjs/kay`) onto prunelle: its dependencies, config file, imports, the names it imports and the names the browser receives.
|
|
2
2
|
|
|
3
|
+
import type { Dirent } from 'node:fs'
|
|
3
4
|
import { existsSync, readdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs'
|
|
4
|
-
import { dirname, join } from 'node:path'
|
|
5
|
+
import { dirname, join, resolve } from 'node:path'
|
|
5
6
|
import pkg from '../../package.json' with { type: 'json' }
|
|
6
7
|
import { isNotSourceDir, relPosix } from '../build/files'
|
|
7
8
|
import { resolvePrunelleSpecifier } from '../build/resolve'
|
|
8
9
|
import { parseTsx } from '../compiler/analyze'
|
|
10
|
+
import { walk } from '../compiler/ast'
|
|
9
11
|
import { renameKayNames } from './upgrade-names'
|
|
10
12
|
|
|
11
13
|
export interface UpgradeResult {
|
|
@@ -17,11 +19,13 @@ export interface UpgradeResult {
|
|
|
17
19
|
|
|
18
20
|
// The specifiers and file names every kind of file may name.
|
|
19
21
|
const PATH_RULES: [RegExp, string][] = [
|
|
22
|
+
// A kay v2 version written beside a package, as notes do, names no prunelle release: the current one replaces it.
|
|
23
|
+
[/(@kayjs\/[\w-]+)@[\^~]?2\.\d+\.\d+[\w.-]*/g, `$1@^${pkg.version}`],
|
|
20
24
|
[/@kayjs\/kay(?![\w-])/g, 'prunelle'],
|
|
21
25
|
[/@kayjs\//g, '@prunellejs/'],
|
|
22
26
|
[/\.kay-(cache|dev)\b/g, '.prunelle-$1'],
|
|
23
27
|
[/\bkay\.config\b/g, 'prunelle.config'],
|
|
24
|
-
[/\bkay v2\b/
|
|
28
|
+
[/\bkay v2\b/gi, 'prunelle'],
|
|
25
29
|
]
|
|
26
30
|
// The names kay sent the browser, as app code and styles may spell them.
|
|
27
31
|
const WIRE_RULES: [RegExp, string][] = [
|
|
@@ -37,19 +41,31 @@ const CLI_RULE: [RegExp, string] = [/(?<![\w.@/-])kay(?![\w.:/-])/g, 'prunelle']
|
|
|
37
41
|
|
|
38
42
|
const SOURCE_FILE_RE = /\.(?:tsx?|mts)$/
|
|
39
43
|
const STYLE_OR_SCRIPT_RE = /\.(?:css|js|mjs)$/
|
|
44
|
+
const TSCONFIG_FILE_RE = /^tsconfig(?:\.[\w-]+)?\.json$/
|
|
40
45
|
const CONFIG_FILE_RE = /^(?:tsconfig(?:\.[\w-]+)?\.json|bunfig\.toml|\.gitignore|\.dockerignore)$/
|
|
41
46
|
const BUILD_FILE_RE = /^(?:Dockerfile(?:\.[\w-]+)?|[\w-]+\.Dockerfile|[Jj]ustfile|Makefile|(?:docker-)?compose(?:\.[\w-]+)?\.ya?ml)$/
|
|
47
|
+
// The agent instructions `prunelle new` writes, which name the llms.txt to read and the CLI to run (#42).
|
|
48
|
+
const AGENT_FILE_RE = /^(?:AGENTS|CLAUDE)\.md$/
|
|
42
49
|
const CI_DIRS = ['.forgejo/workflows', '.github/workflows', '.gitea/workflows']
|
|
43
50
|
const CACHE_DIRS = ['.kay-cache', '.kay-dev']
|
|
44
51
|
const PRUNELLE_SOURCE_RE = /^prunelle(\/.*)?$/
|
|
52
|
+
const NPM_KAY_ALIAS_RE = /^npm:(@kayjs\/[\w-]+)(?:@.*)?$/
|
|
53
|
+
const ESCAPE_RE = /[.*+?^${}()|[\]\\]/g
|
|
54
|
+
const GITIGNORE_CACHE_RE = /(?:^|\/)\.prunelle-cache(?:\/|$|\s)/m
|
|
45
55
|
|
|
46
56
|
const apply = (text: string, rules: readonly [RegExp, string][]): string => rules.reduce((out, [re, to]) => out.replace(re, to), text)
|
|
47
57
|
|
|
48
58
|
/** Rewrites the app at `root` in place, and each package its bun workspace lists; installing the renamed dependencies is the caller's job. */
|
|
49
59
|
export function upgradeProject(root: string): UpgradeResult {
|
|
60
|
+
return upgradeDir(root)
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function upgradeDir(root: string, inheritedAliases?: ReadonlyMap<string, string>): UpgradeResult {
|
|
50
64
|
const v1 = kayV1Dependency(root)
|
|
51
65
|
if (v1 !== undefined)
|
|
52
66
|
return { changed: [], manual: [`package.json:1: ${v1} is kay v1: prunelle upgrade moves kay v2 apps, so this one is left as it is.`] }
|
|
67
|
+
const aliases = kayAliases(root, inheritedAliases)
|
|
68
|
+
const isApp = hasKayOrPrunelle(root)
|
|
53
69
|
const changed: string[] = []
|
|
54
70
|
const manual: string[] = []
|
|
55
71
|
const write = (file: string, before: string, after: string): void => {
|
|
@@ -63,9 +79,13 @@ export function upgradeProject(root: string): UpgradeResult {
|
|
|
63
79
|
const text = readFileSync(join(root, file), 'utf8')
|
|
64
80
|
if (file === 'package.json')
|
|
65
81
|
write(file, text, upgradePackageJson(text))
|
|
82
|
+
else if (TSCONFIG_FILE_RE.test(file))
|
|
83
|
+
write(file, text, upgradeTsconfig(text, aliases))
|
|
84
|
+
else if (file === '.gitignore')
|
|
85
|
+
write(file, text, upgradeGitignore(text, isApp))
|
|
66
86
|
else if (CONFIG_FILE_RE.test(file))
|
|
67
87
|
write(file, text, apply(text, PATH_RULES))
|
|
68
|
-
else if (BUILD_FILE_RE.test(file))
|
|
88
|
+
else if (BUILD_FILE_RE.test(file) || AGENT_FILE_RE.test(file))
|
|
69
89
|
write(file, text, apply(apply(text, PATH_RULES), [CLI_RULE]))
|
|
70
90
|
}
|
|
71
91
|
for (const dir of CI_DIRS) {
|
|
@@ -77,9 +97,10 @@ export function upgradeProject(root: string): UpgradeResult {
|
|
|
77
97
|
write(file, text, apply(apply(text, PATH_RULES), [CLI_RULE]))
|
|
78
98
|
}
|
|
79
99
|
}
|
|
80
|
-
|
|
100
|
+
const publicDir = configuredPublicDir(root)
|
|
101
|
+
for (const file of sourceFiles(root, publicDir)) {
|
|
81
102
|
const text = readFileSync(join(root, file), 'utf8')
|
|
82
|
-
const renamed = SOURCE_FILE_RE.test(file) ? renameKayNames(file, text) : text
|
|
103
|
+
const renamed = SOURCE_FILE_RE.test(file) ? renameKayNames(file, text, aliases) : text
|
|
83
104
|
const next = apply(apply(renamed, PATH_RULES), WIRE_RULES)
|
|
84
105
|
write(file, text, next)
|
|
85
106
|
if (SOURCE_FILE_RE.test(file) && next !== text)
|
|
@@ -91,8 +112,9 @@ export function upgradeProject(root: string): UpgradeResult {
|
|
|
91
112
|
changed.push(`${dir}/`)
|
|
92
113
|
}
|
|
93
114
|
}
|
|
94
|
-
|
|
95
|
-
|
|
115
|
+
// A member on neither kay nor prunelle, a plain Bun app or a tool, has nothing to move; one already on prunelle may keep names an earlier upgrade missed.
|
|
116
|
+
for (const member of workspaceMembers(root).filter(m => hasKayOrPrunelle(join(root, m)))) {
|
|
117
|
+
const res = upgradeDir(join(root, member), aliases)
|
|
96
118
|
changed.push(...res.changed.map(file => `${member}/${file}`))
|
|
97
119
|
manual.push(...res.manual.map(line => `${member}/${line}`))
|
|
98
120
|
}
|
|
@@ -102,6 +124,83 @@ export function upgradeProject(root: string): UpgradeResult {
|
|
|
102
124
|
const DEP_FIELDS = ['dependencies', 'devDependencies', 'peerDependencies', 'optionalDependencies']
|
|
103
125
|
const V1_RANGE_RE = /^[~^>=\s]*1\./
|
|
104
126
|
|
|
127
|
+
const KAY_OR_PRUNELLE_RE = /^(?:npm:)?(?:@kayjs\/|prunelle(?:@|$)|@prunellejs\/)/
|
|
128
|
+
|
|
129
|
+
function hasKayOrPrunelle(root: string): boolean {
|
|
130
|
+
if (!existsSync(join(root, 'package.json')))
|
|
131
|
+
return false
|
|
132
|
+
const json = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8')) as Record<string, Record<string, string> | undefined>
|
|
133
|
+
return DEP_FIELDS.some(field => Object.entries(json[field] ?? {}).some(([name, range]) => KAY_OR_PRUNELLE_RE.test(name) || KAY_OR_PRUNELLE_RE.test(range)))
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
function kayTargetPackage(name: string, version: string): string | undefined {
|
|
137
|
+
if (name.startsWith('@kayjs/'))
|
|
138
|
+
return apply(name, PATH_RULES)
|
|
139
|
+
const match = NPM_KAY_ALIAS_RE.exec(version)
|
|
140
|
+
return match === null ? undefined : apply(match[1]!, PATH_RULES)
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
function kayAliases(root: string, inherited?: ReadonlyMap<string, string>): Map<string, string> {
|
|
144
|
+
const aliases = new Map<string, string>(inherited)
|
|
145
|
+
if (!existsSync(join(root, 'package.json')))
|
|
146
|
+
return aliases
|
|
147
|
+
const json = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8')) as Record<string, Record<string, string> | undefined>
|
|
148
|
+
for (const field of DEP_FIELDS) {
|
|
149
|
+
for (const [name, version] of Object.entries(json[field] ?? {})) {
|
|
150
|
+
if (name.startsWith('@kayjs/'))
|
|
151
|
+
continue
|
|
152
|
+
const match = NPM_KAY_ALIAS_RE.exec(version)
|
|
153
|
+
if (match !== null)
|
|
154
|
+
aliases.set(name, apply(match[1]!, PATH_RULES))
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
return aliases
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
function upgradeTsconfig(text: string, aliases: ReadonlyMap<string, string>): string {
|
|
161
|
+
let out = apply(text, PATH_RULES)
|
|
162
|
+
for (const [alias, target] of aliases) {
|
|
163
|
+
const escaped = alias.replace(ESCAPE_RE, '\\$&')
|
|
164
|
+
if (target === 'prunelle')
|
|
165
|
+
out = out.replace(new RegExp(`("jsxImportSource"\\s*:\\s*")${escaped}(")`, 'g'), `$1${target}$2`)
|
|
166
|
+
out = out.replace(/"types"\s*:\s*\[[^\]]*\]/g, block =>
|
|
167
|
+
block.replace(new RegExp(`"${escaped}((?:/[^"]*)?)"`, 'g'), `"${target}$1"`))
|
|
168
|
+
}
|
|
169
|
+
return out
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
function upgradeGitignore(text: string, addCache: boolean): string {
|
|
173
|
+
const next = apply(text, PATH_RULES)
|
|
174
|
+
if (!addCache || GITIGNORE_CACHE_RE.test(next))
|
|
175
|
+
return next
|
|
176
|
+
const eol = next.includes('\r\n') ? '\r\n' : '\n'
|
|
177
|
+
const sep = next === '' || next.endsWith('\n') ? '' : eol
|
|
178
|
+
return `${next}${sep}.prunelle-cache/${eol}`
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
// Reads `publicDir` statically from prunelle.config.ts (or kay.config.ts) so built scripts in `public/` are left alone (#43).
|
|
182
|
+
function configuredPublicDir(root: string): string {
|
|
183
|
+
const file = existsSync(join(root, 'prunelle.config.ts'))
|
|
184
|
+
? 'prunelle.config.ts'
|
|
185
|
+
: existsSync(join(root, 'kay.config.ts')) ? 'kay.config.ts' : undefined
|
|
186
|
+
if (file === undefined)
|
|
187
|
+
return resolve(root, 'public')
|
|
188
|
+
const program = parseTsx(file, readFileSync(join(root, file), 'utf8'))
|
|
189
|
+
let value: string | undefined
|
|
190
|
+
walk(program.body, (node) => {
|
|
191
|
+
if (value !== undefined)
|
|
192
|
+
return false
|
|
193
|
+
if (node.type === 'Property' && !node.computed && node.key.type === 'Identifier' && node.key.name === 'publicDir') {
|
|
194
|
+
if (node.value.type === 'Literal' && typeof node.value.value === 'string')
|
|
195
|
+
value = node.value.value
|
|
196
|
+
else if (node.value.type === 'TemplateLiteral' && node.value.expressions.length === 0)
|
|
197
|
+
value = node.value.quasis[0]?.value.cooked ?? node.value.quasis[0]?.value.raw
|
|
198
|
+
}
|
|
199
|
+
return true
|
|
200
|
+
})
|
|
201
|
+
return resolve(root, value ?? 'public')
|
|
202
|
+
}
|
|
203
|
+
|
|
105
204
|
// kay's core at a 1.x range, as `@kayjs/kay` or an `npm:@kayjs/kay@` alias: an app of `.kay` files prunelle cannot take.
|
|
106
205
|
function kayV1Dependency(root: string): string | undefined {
|
|
107
206
|
if (!existsSync(join(root, 'package.json')))
|
|
@@ -149,18 +248,33 @@ function rootFiles(root: string): string[] {
|
|
|
149
248
|
return readdirSync(root, { withFileTypes: true }).filter(e => e.isFile()).map(e => e.name).sort()
|
|
150
249
|
}
|
|
151
250
|
|
|
152
|
-
//
|
|
153
|
-
function
|
|
251
|
+
// The entries of `dir`, none for a folder the user cannot read: a container's data, never source they edit.
|
|
252
|
+
function readableEntries(dir: string): Dirent[] {
|
|
253
|
+
try {
|
|
254
|
+
return readdirSync(dir, { withFileTypes: true })
|
|
255
|
+
}
|
|
256
|
+
catch (err) {
|
|
257
|
+
if ((err as NodeJS.ErrnoException).code === 'EACCES' || (err as NodeJS.ErrnoException).code === 'EPERM')
|
|
258
|
+
return []
|
|
259
|
+
throw err
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
// A folder holding its own package.json is another package, upgraded on its own; `publicDir` holds built static files left untouched (#43).
|
|
264
|
+
function sourceFiles(root: string, publicDir: string, dir = root, out: string[] = []): string[] {
|
|
154
265
|
if (dir !== root && existsSync(join(dir, 'package.json')))
|
|
155
266
|
return out
|
|
156
|
-
for (const entry of
|
|
267
|
+
for (const entry of readableEntries(dir)) {
|
|
157
268
|
if (isNotSourceDir(entry.name))
|
|
158
269
|
continue
|
|
159
270
|
const path = join(dir, entry.name)
|
|
160
|
-
if (entry.isDirectory())
|
|
161
|
-
|
|
162
|
-
|
|
271
|
+
if (entry.isDirectory()) {
|
|
272
|
+
if (resolve(path) !== publicDir)
|
|
273
|
+
sourceFiles(root, publicDir, path, out)
|
|
274
|
+
}
|
|
275
|
+
else if (SOURCE_FILE_RE.test(entry.name) || STYLE_OR_SCRIPT_RE.test(entry.name)) {
|
|
163
276
|
out.push(relPosix(root, path))
|
|
277
|
+
}
|
|
164
278
|
}
|
|
165
279
|
return out.sort()
|
|
166
280
|
}
|
|
@@ -173,10 +287,17 @@ function upgradePackageJson(text: string): string {
|
|
|
173
287
|
const range = `^${pkg.version}`
|
|
174
288
|
for (const field of DEP_FIELDS) {
|
|
175
289
|
const deps = json[field] as Record<string, string> | undefined
|
|
176
|
-
if (deps === undefined || !Object.
|
|
290
|
+
if (deps === undefined || !Object.entries(deps).some(([name, version]) => kayTargetPackage(name, version) !== undefined))
|
|
177
291
|
continue
|
|
178
|
-
const
|
|
179
|
-
|
|
292
|
+
const next = new Map<string, string>()
|
|
293
|
+
for (const [name, version] of Object.entries(deps)) {
|
|
294
|
+
const target = kayTargetPackage(name, version)
|
|
295
|
+
if (target !== undefined)
|
|
296
|
+
next.set(target, range)
|
|
297
|
+
else if (!next.has(name))
|
|
298
|
+
next.set(name, version)
|
|
299
|
+
}
|
|
300
|
+
json[field] = Object.fromEntries([...next.entries()].sort(([a], [b]) => a.localeCompare(b)))
|
|
180
301
|
}
|
|
181
302
|
const scripts = json.scripts as Record<string, string> | undefined
|
|
182
303
|
if (scripts !== undefined)
|