prunelle 0.1.1 → 0.5.2
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 +23 -19
- package/package.json +8 -2
- package/src/a11y/declaration.ts +335 -0
- package/src/a11y/index.ts +446 -0
- package/src/a11y/rgaa-map.ts +184 -0
- package/src/attrs.ts +11 -3
- package/src/build/bundle.ts +80 -36
- package/src/build/client-entries.ts +3 -2
- package/src/build/client-plugin.ts +8 -4
- package/src/build/client-prune.ts +56 -6
- package/src/build/compile.ts +11 -9
- package/src/build/ecoindex.ts +229 -0
- package/src/build/index.ts +174 -108
- package/src/build/islands.ts +2 -2
- package/src/build/manifest.ts +66 -5
- package/src/build/output.ts +2 -2
- package/src/build/plugin-host.ts +91 -33
- package/src/build/precompress.ts +15 -2
- package/src/build/prerender.ts +128 -46
- package/src/build/report.ts +23 -2
- package/src/build/resolve.ts +8 -6
- package/src/build/routes.ts +175 -10
- package/src/build/static.ts +137 -39
- package/src/build/status-pages.ts +127 -0
- package/src/build/style-bundles.ts +526 -0
- package/src/cli/check-forms.ts +654 -0
- package/src/cli/check-links.ts +619 -0
- package/src/cli/check.ts +52 -5
- package/src/cli/commands.ts +86 -4
- package/src/cli/docs.ts +402 -0
- package/src/cli/inspect.ts +31 -2
- package/src/cli/mcp-tools.ts +480 -0
- package/src/cli/mcp.ts +205 -0
- package/src/cli/new.ts +2 -2
- package/src/cli/render.ts +261 -0
- package/src/cli/upgrade-names.ts +73 -13
- package/src/cli/upgrade.ts +137 -16
- package/src/compiler/analyze.ts +20 -6
- package/src/compiler/cacheability.ts +592 -0
- package/src/compiler/compliance-rgaa.ts +502 -0
- package/src/compiler/compliance.ts +120 -221
- package/src/compiler/dev-source.ts +87 -0
- package/src/compiler/dom-attrs.ts +138 -65
- package/src/compiler/dom.ts +12 -11
- package/src/compiler/expr-context.ts +167 -57
- package/src/compiler/props.ts +87 -36
- package/src/compiler/scope.ts +56 -17
- package/src/compiler/ssr-prunelle-tags.ts +27 -14
- package/src/compiler/ssr.ts +216 -84
- package/src/dev/error-log.ts +151 -0
- package/src/dev/index.ts +84 -34
- package/src/dev/open-editor.ts +204 -0
- package/src/dev/protocol.ts +1 -0
- package/src/dev/reload.ts +5 -3
- package/src/dev/supervisor.ts +42 -25
- package/src/dev/watchers.ts +47 -11
- package/src/dom/action.ts +4 -1
- package/src/dom/attrs.ts +15 -3
- package/src/dom/extras.ts +2 -2
- package/src/dom/island.ts +11 -10
- package/src/plugins/config.ts +4 -4
- package/src/plugins/index.ts +2 -2
- package/src/plugins/public.ts +5 -2
- package/src/plugins/services.ts +62 -0
- package/src/plugins/types.ts +32 -0
- package/src/server/action-protect.ts +198 -0
- package/src/server/action-registry.ts +1 -1
- package/src/server/action.ts +82 -27
- package/src/server/assets.ts +34 -2
- package/src/server/compress.ts +91 -9
- package/src/server/errors.ts +303 -65
- package/src/server/form-schema.ts +343 -0
- package/src/server/health.ts +244 -0
- package/src/server/http.ts +128 -31
- package/src/server/index.ts +230 -260
- package/src/server/loader.ts +5 -0
- package/src/server/param-matchers.ts +112 -0
- package/src/server/plugin-host.ts +123 -88
- package/src/server/public.ts +3 -3
- package/src/server/rate-limit.ts +58 -35
- package/src/server/request-body.ts +1 -1
- package/src/server/route-cache.ts +423 -0
- package/src/server/route-table.ts +339 -8
- package/src/server/router.ts +125 -40
- package/src/server/routing.ts +196 -63
- package/src/server/security.ts +208 -32
- package/src/server/serve-handlers.ts +21 -7
- package/src/server/start.ts +60 -16
- package/src/server/static-dir.ts +61 -8
- package/src/server/stream.ts +41 -22
- package/src/ssr/context.ts +85 -3
- package/src/ssr/index.ts +120 -1
- package/src/ssr/region.ts +31 -19
- package/src/test/browser.ts +6 -0
- package/src/test/index.ts +17 -3
- package/src/ts-plugin/diagnostics.ts +378 -0
- package/src/ts-plugin/fixes.ts +364 -0
- package/src/ts-plugin/index.ts +194 -0
- package/templates/_shared/AGENTS.md +2 -2
- package/templates/_shared/mcp.json +11 -0
- package/templates/_shared/src/routes/legal.tsx +5 -0
- package/templates/_shared/tsconfig.json +5 -0
- package/templates/blog/prunelle.config.ts +1 -1
- package/templates/blog/src/routes/index.tsx +4 -0
- package/ts-plugin.cjs +4277 -0
package/src/cli/mcp.ts
ADDED
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
// Built-in `prunelle mcp` stdio JSON-RPC 2.0 server (MCP 2025-03-26, zero external dependencies).
|
|
2
|
+
|
|
3
|
+
import { readFileSync } from 'node:fs'
|
|
4
|
+
import { join, resolve } from 'node:path'
|
|
5
|
+
import {
|
|
6
|
+
callPrunelleTool,
|
|
7
|
+
hasPrunelleTool,
|
|
8
|
+
listPrunelleResources,
|
|
9
|
+
listPrunelleTools,
|
|
10
|
+
readPrunelleResource,
|
|
11
|
+
} from './mcp-tools'
|
|
12
|
+
|
|
13
|
+
export const PRUNELLE_MCP_PROTOCOL_VERSION = '2025-03-26'
|
|
14
|
+
|
|
15
|
+
export interface PrunelleMcpOptions {
|
|
16
|
+
root: string
|
|
17
|
+
allowWrite?: boolean | undefined
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
interface JsonRpcRequest {
|
|
21
|
+
jsonrpc: '2.0'
|
|
22
|
+
id?: string | number | null | undefined
|
|
23
|
+
method: string
|
|
24
|
+
params?: Record<string, unknown> | undefined
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
interface JsonRpcResponse {
|
|
28
|
+
jsonrpc: '2.0'
|
|
29
|
+
id: string | number | null
|
|
30
|
+
result?: unknown
|
|
31
|
+
error?: { code: number, message: string, data?: unknown }
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function readPrunelleVersion(): string {
|
|
35
|
+
try {
|
|
36
|
+
const pkg = JSON.parse(readFileSync(join(import.meta.dir, '../../package.json'), 'utf8')) as { version?: unknown }
|
|
37
|
+
return typeof pkg.version === 'string' && pkg.version.length > 0 ? pkg.version : '0.0.0'
|
|
38
|
+
}
|
|
39
|
+
catch {
|
|
40
|
+
return '0.0.0'
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
const PRUNELLE_VERSION = readPrunelleVersion()
|
|
45
|
+
|
|
46
|
+
const SERVER_INSTRUCTIONS = [
|
|
47
|
+
'Prunelle development MCP server.',
|
|
48
|
+
'Read `prunelle://llms/*` resources or call `docs` for framework and plugin APIs.',
|
|
49
|
+
'Use `check`, `inspect`, `build_analyze`, `render`, and `dev_errors` to verify and debug the app.',
|
|
50
|
+
'Tools that write build output (`build`, or `build_analyze` with `write: true` / `outDir`) require `--allow-write`.',
|
|
51
|
+
].join(' ')
|
|
52
|
+
|
|
53
|
+
function rpcError(id: string | number | null, code: number, message: string): JsonRpcResponse {
|
|
54
|
+
return { jsonrpc: '2.0', id, error: { code, message } }
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function rpcResult(id: string | number | null, result: unknown): JsonRpcResponse {
|
|
58
|
+
return { jsonrpc: '2.0', id, result }
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function asParamsRecord(params: unknown): Record<string, unknown> | undefined {
|
|
62
|
+
if (params === undefined || params === null)
|
|
63
|
+
return undefined
|
|
64
|
+
if (typeof params === 'object' && !Array.isArray(params))
|
|
65
|
+
return params as Record<string, unknown>
|
|
66
|
+
return undefined
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** Creates an in-process JSON-RPC 2.0 dispatcher for `prunelle mcp` (used by both stdio transport and unit tests). */
|
|
70
|
+
export function createPrunelleMcpDispatcher(options: PrunelleMcpOptions): {
|
|
71
|
+
handleMessage: (msg: unknown) => Promise<unknown | undefined>
|
|
72
|
+
handleLine: (line: string) => Promise<string | undefined>
|
|
73
|
+
} {
|
|
74
|
+
const ctx = {
|
|
75
|
+
root: resolve(options.root),
|
|
76
|
+
allowWrite: options.allowWrite === true,
|
|
77
|
+
}
|
|
78
|
+
const tools = listPrunelleTools()
|
|
79
|
+
const toolNamesHint = tools.map(t => t.name).join(', ')
|
|
80
|
+
|
|
81
|
+
async function handleMessage(msg: unknown): Promise<JsonRpcResponse | undefined> {
|
|
82
|
+
if (typeof msg !== 'object' || msg === null || Array.isArray(msg))
|
|
83
|
+
return rpcError(null, -32600, 'Invalid Request')
|
|
84
|
+
|
|
85
|
+
const req = msg as Partial<JsonRpcRequest>
|
|
86
|
+
const hasId = 'id' in req && req.id !== undefined
|
|
87
|
+
const id = hasId ? (req.id ?? null) : null
|
|
88
|
+
|
|
89
|
+
if (req.jsonrpc !== '2.0' || typeof req.method !== 'string')
|
|
90
|
+
return rpcError(id, -32600, 'Invalid Request')
|
|
91
|
+
|
|
92
|
+
// JSON-RPC notifications (no `id`) produce no response.
|
|
93
|
+
if (!hasId)
|
|
94
|
+
return undefined
|
|
95
|
+
|
|
96
|
+
switch (req.method) {
|
|
97
|
+
case 'initialize':
|
|
98
|
+
return rpcResult(id, {
|
|
99
|
+
protocolVersion: PRUNELLE_MCP_PROTOCOL_VERSION,
|
|
100
|
+
capabilities: {
|
|
101
|
+
tools: { listChanged: false },
|
|
102
|
+
resources: { subscribe: false, listChanged: false },
|
|
103
|
+
},
|
|
104
|
+
serverInfo: { name: 'prunelle', version: PRUNELLE_VERSION },
|
|
105
|
+
instructions: SERVER_INSTRUCTIONS,
|
|
106
|
+
})
|
|
107
|
+
|
|
108
|
+
case 'ping':
|
|
109
|
+
return rpcResult(id, {})
|
|
110
|
+
|
|
111
|
+
case 'tools/list':
|
|
112
|
+
return rpcResult(id, { tools })
|
|
113
|
+
|
|
114
|
+
case 'tools/call': {
|
|
115
|
+
const params = asParamsRecord(req.params)
|
|
116
|
+
const toolName = typeof params?.name === 'string' ? params.name : undefined
|
|
117
|
+
if (toolName === undefined)
|
|
118
|
+
return rpcError(id, -32602, 'Missing tool name')
|
|
119
|
+
if (!hasPrunelleTool(toolName))
|
|
120
|
+
return rpcError(id, -32602, `Unknown tool: ${toolName} (available: ${toolNamesHint})`)
|
|
121
|
+
const toolResult = await callPrunelleTool(ctx, toolName, params?.arguments)
|
|
122
|
+
return rpcResult(id, toolResult)
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
case 'resources/list':
|
|
126
|
+
return rpcResult(id, { resources: listPrunelleResources(ctx.root) })
|
|
127
|
+
|
|
128
|
+
case 'resources/read': {
|
|
129
|
+
const params = asParamsRecord(req.params)
|
|
130
|
+
const uri = typeof params?.uri === 'string' ? params.uri : undefined
|
|
131
|
+
if (uri === undefined)
|
|
132
|
+
return rpcError(id, -32602, 'Missing resource uri')
|
|
133
|
+
const content = readPrunelleResource(ctx.root, uri)
|
|
134
|
+
if (content === undefined)
|
|
135
|
+
return rpcError(id, -32002, `Unknown resource: ${uri}`)
|
|
136
|
+
return rpcResult(id, { contents: [content] })
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
default:
|
|
140
|
+
return rpcError(id, -32601, `Method not found: ${req.method}`)
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
async function handleLine(line: string): Promise<string | undefined> {
|
|
145
|
+
const trimmed = line.trim()
|
|
146
|
+
if (trimmed.length === 0)
|
|
147
|
+
return undefined
|
|
148
|
+
let parsed: unknown
|
|
149
|
+
try {
|
|
150
|
+
parsed = JSON.parse(trimmed)
|
|
151
|
+
}
|
|
152
|
+
catch {
|
|
153
|
+
return JSON.stringify(rpcError(null, -32700, 'Parse error'))
|
|
154
|
+
}
|
|
155
|
+
const response = await handleMessage(parsed)
|
|
156
|
+
return response !== undefined ? JSON.stringify(response) : undefined
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
return { handleMessage, handleLine }
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/** Runs the `prunelle mcp` stdio JSON-RPC 2.0 loop, redirecting console/stdout logs to stderr so framing stays clean. */
|
|
163
|
+
export async function runPrunelleMcpStdio(options: PrunelleMcpOptions): Promise<number> {
|
|
164
|
+
const dispatcher = createPrunelleMcpDispatcher(options)
|
|
165
|
+
const writeFrame = process.stdout.write.bind(process.stdout)
|
|
166
|
+
const origStdoutWrite = process.stdout.write
|
|
167
|
+
const origConsoleLog = console.log
|
|
168
|
+
const origConsoleInfo = console.info
|
|
169
|
+
const origConsoleDebug = console.debug
|
|
170
|
+
|
|
171
|
+
process.stdout.write = process.stderr.write.bind(process.stderr)
|
|
172
|
+
console.log = console.error
|
|
173
|
+
console.info = console.error
|
|
174
|
+
console.debug = console.error
|
|
175
|
+
|
|
176
|
+
const emit = (line: string | undefined): void => {
|
|
177
|
+
if (line !== undefined)
|
|
178
|
+
writeFrame(`${line}\n`)
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
try {
|
|
182
|
+
const decoder = new TextDecoder()
|
|
183
|
+
let buffer = ''
|
|
184
|
+
for await (const chunk of process.stdin) {
|
|
185
|
+
buffer += typeof chunk === 'string' ? chunk : decoder.decode(chunk, { stream: true })
|
|
186
|
+
let newlineIdx = buffer.indexOf('\n')
|
|
187
|
+
while (newlineIdx !== -1) {
|
|
188
|
+
const line = buffer.slice(0, newlineIdx)
|
|
189
|
+
buffer = buffer.slice(newlineIdx + 1)
|
|
190
|
+
emit(await dispatcher.handleLine(line))
|
|
191
|
+
newlineIdx = buffer.indexOf('\n')
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
const trailing = buffer + decoder.decode()
|
|
195
|
+
if (trailing.trim().length > 0)
|
|
196
|
+
emit(await dispatcher.handleLine(trailing))
|
|
197
|
+
return 0
|
|
198
|
+
}
|
|
199
|
+
finally {
|
|
200
|
+
process.stdout.write = origStdoutWrite
|
|
201
|
+
console.log = origConsoleLog
|
|
202
|
+
console.info = origConsoleInfo
|
|
203
|
+
console.debug = origConsoleDebug
|
|
204
|
+
}
|
|
205
|
+
}
|
package/src/cli/new.ts
CHANGED
|
@@ -15,8 +15,8 @@ export interface ScaffoldOptions {
|
|
|
15
15
|
|
|
16
16
|
const TEMPLATES_DIR = join(import.meta.dir, '../../templates')
|
|
17
17
|
|
|
18
|
-
// npm leaves
|
|
19
|
-
const RENAMED: Record<string, string> = { gitignore: '.gitignore' }
|
|
18
|
+
// npm leaves dotfiles like `.gitignore` out of a package, so the template stores them without the leading dot.
|
|
19
|
+
const RENAMED: Record<string, string> = { 'gitignore': '.gitignore', 'mcp.json': '.mcp.json' }
|
|
20
20
|
|
|
21
21
|
export function scaffoldProject(targetDir: string, options: ScaffoldOptions = {}): { root: string, files: string[] } {
|
|
22
22
|
const root = resolve(targetDir)
|
|
@@ -0,0 +1,261 @@
|
|
|
1
|
+
// `prunelle render <url>`: render a route or API endpoint in-process via `testApp()` without binding a port or touching `dist/`.
|
|
2
|
+
|
|
3
|
+
import { existsSync, readFileSync, statSync, writeFileSync } from 'node:fs'
|
|
4
|
+
import { join, resolve } from 'node:path'
|
|
5
|
+
import { isNotSourceDir, relPosix, walkFiles } from '../build/files'
|
|
6
|
+
import { ensureCacheGitignore } from '../build/precompress'
|
|
7
|
+
import { SERVER_ENTRY_FILE } from '../build/server-entry'
|
|
8
|
+
import { testApp } from '../test/index'
|
|
9
|
+
|
|
10
|
+
const ABSOLUTE_URL_RE = /^https?:\/\//i
|
|
11
|
+
const CONFIG_FILES = ['prunelle.config.ts', 'prunelle.config.js', 'prunelle.config.mjs'] as const
|
|
12
|
+
const CUSTOM_ROUTES_DIR_RE = /\broutesDir\s*:\s*['"]([^'"]+)['"]/
|
|
13
|
+
const CUSTOM_PUBLIC_DIR_RE = /\bpublicDir\s*:\s*['"]([^'"]+)['"]/
|
|
14
|
+
const SAFE_ORIGIN_METHODS = new Set(['GET', 'HEAD', 'OPTIONS'])
|
|
15
|
+
|
|
16
|
+
const STATUS_TEXT: Record<number, string> = {
|
|
17
|
+
200: 'OK',
|
|
18
|
+
201: 'Created',
|
|
19
|
+
202: 'Accepted',
|
|
20
|
+
204: 'No Content',
|
|
21
|
+
301: 'Moved Permanently',
|
|
22
|
+
302: 'Found',
|
|
23
|
+
303: 'See Other',
|
|
24
|
+
304: 'Not Modified',
|
|
25
|
+
307: 'Temporary Redirect',
|
|
26
|
+
308: 'Permanent Redirect',
|
|
27
|
+
400: 'Bad Request',
|
|
28
|
+
401: 'Unauthorized',
|
|
29
|
+
403: 'Forbidden',
|
|
30
|
+
404: 'Not Found',
|
|
31
|
+
405: 'Method Not Allowed',
|
|
32
|
+
409: 'Conflict',
|
|
33
|
+
413: 'Payload Too Large',
|
|
34
|
+
422: 'Unprocessable Content',
|
|
35
|
+
429: 'Too Many Requests',
|
|
36
|
+
500: 'Internal Server Error',
|
|
37
|
+
502: 'Bad Gateway',
|
|
38
|
+
503: 'Service Unavailable',
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export interface RenderUrlOptions {
|
|
42
|
+
root: string
|
|
43
|
+
url: string
|
|
44
|
+
method?: string | undefined
|
|
45
|
+
body?: string | undefined
|
|
46
|
+
headers?: readonly string[] | undefined
|
|
47
|
+
cookies?: readonly string[] | undefined
|
|
48
|
+
includeHeaders?: boolean | undefined
|
|
49
|
+
fresh?: boolean | undefined
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export interface RenderUrlResult {
|
|
53
|
+
status: number
|
|
54
|
+
statusText: string
|
|
55
|
+
headers: Record<string, string>
|
|
56
|
+
setCookies: string[]
|
|
57
|
+
body: string
|
|
58
|
+
ok: boolean
|
|
59
|
+
reusedBuild: boolean
|
|
60
|
+
errors: string[]
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function normalizeTargetUrl(rawUrl: string): string {
|
|
64
|
+
const trimmed = rawUrl.trim()
|
|
65
|
+
if (trimmed.length === 0)
|
|
66
|
+
throw new Error('prunelle render: URL cannot be empty')
|
|
67
|
+
|
|
68
|
+
if (ABSOLUTE_URL_RE.test(trimmed)) {
|
|
69
|
+
try {
|
|
70
|
+
return new URL(trimmed).href
|
|
71
|
+
}
|
|
72
|
+
catch {
|
|
73
|
+
throw new Error(`prunelle render: invalid URL "${rawUrl}"`)
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
const normalized = trimmed.startsWith('/') ? trimmed : `/${trimmed}`
|
|
78
|
+
try {
|
|
79
|
+
void new URL(normalized, 'http://localhost')
|
|
80
|
+
}
|
|
81
|
+
catch {
|
|
82
|
+
throw new Error(`prunelle render: invalid URL "${rawUrl}"`)
|
|
83
|
+
}
|
|
84
|
+
return normalized
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function buildRequestHeaders(
|
|
88
|
+
rawHeaders: readonly string[] | undefined,
|
|
89
|
+
rawCookies: readonly string[] | undefined,
|
|
90
|
+
method: string,
|
|
91
|
+
targetUrl: string,
|
|
92
|
+
): Headers {
|
|
93
|
+
const headers = new Headers()
|
|
94
|
+
|
|
95
|
+
for (const raw of rawHeaders ?? []) {
|
|
96
|
+
const colon = raw.indexOf(':')
|
|
97
|
+
if (colon <= 0)
|
|
98
|
+
throw new Error(`prunelle render: invalid header "${raw}" (expected "Name: Value")`)
|
|
99
|
+
const name = raw.slice(0, colon).trim()
|
|
100
|
+
if (name.length === 0)
|
|
101
|
+
throw new Error(`prunelle render: invalid header "${raw}" (expected "Name: Value")`)
|
|
102
|
+
const value = raw.slice(colon + 1).trim()
|
|
103
|
+
headers.append(name, value)
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
if (rawCookies !== undefined && rawCookies.length > 0) {
|
|
107
|
+
const joined = rawCookies.join('; ')
|
|
108
|
+
const existing = headers.get('cookie')
|
|
109
|
+
headers.set('cookie', existing !== null && existing.length > 0 ? `${existing}; ${joined}` : joined)
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
if (!SAFE_ORIGIN_METHODS.has(method) && !headers.has('origin')) {
|
|
113
|
+
const origin = ABSOLUTE_URL_RE.test(targetUrl) ? new URL(targetUrl).origin : 'http://localhost'
|
|
114
|
+
headers.set('origin', origin)
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
return headers
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
function collectConfiguredDirs(root: string): string[] {
|
|
121
|
+
const dirs = new Set<string>([resolve(root, 'src'), resolve(root, 'public')])
|
|
122
|
+
for (const file of CONFIG_FILES) {
|
|
123
|
+
const full = join(root, file)
|
|
124
|
+
if (!existsSync(full))
|
|
125
|
+
continue
|
|
126
|
+
const text = readFileSync(full, 'utf8')
|
|
127
|
+
const routesMatch = CUSTOM_ROUTES_DIR_RE.exec(text)
|
|
128
|
+
if (routesMatch?.[1] !== undefined)
|
|
129
|
+
dirs.add(resolve(root, routesMatch[1]))
|
|
130
|
+
const publicMatch = CUSTOM_PUBLIC_DIR_RE.exec(text)
|
|
131
|
+
if (publicMatch?.[1] !== undefined)
|
|
132
|
+
dirs.add(resolve(root, publicMatch[1]))
|
|
133
|
+
}
|
|
134
|
+
return [...dirs]
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
function computeSourceStamp(root: string): string {
|
|
138
|
+
const files = new Set<string>()
|
|
139
|
+
|
|
140
|
+
for (const name of [...CONFIG_FILES, 'package.json']) {
|
|
141
|
+
const full = join(root, name)
|
|
142
|
+
const st = statSync(full, { throwIfNoEntry: false })
|
|
143
|
+
if (st !== undefined && st.isFile())
|
|
144
|
+
files.add(full)
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
for (const dir of collectConfiguredDirs(root)) {
|
|
148
|
+
for (const file of walkFiles(dir, { skipDir: isNotSourceDir, keep: entry => entry.isFile() }))
|
|
149
|
+
files.add(file)
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
const entries: string[] = []
|
|
153
|
+
for (const file of files) {
|
|
154
|
+
const st = statSync(file, { throwIfNoEntry: false })
|
|
155
|
+
if (st !== undefined)
|
|
156
|
+
entries.push(`${relPosix(root, file)}:${st.mtimeMs}:${st.size}`)
|
|
157
|
+
}
|
|
158
|
+
entries.sort()
|
|
159
|
+
return entries.join('\n')
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
function readStamp(stampFile: string): string | undefined {
|
|
163
|
+
if (!existsSync(stampFile))
|
|
164
|
+
return undefined
|
|
165
|
+
try {
|
|
166
|
+
return readFileSync(stampFile, 'utf8')
|
|
167
|
+
}
|
|
168
|
+
catch {
|
|
169
|
+
return undefined
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
function extractResponseHeaders(res: Response): { headers: Record<string, string>, setCookies: string[] } {
|
|
174
|
+
const setCookies = res.headers.getSetCookie?.() ?? []
|
|
175
|
+
const headers: Record<string, string> = {}
|
|
176
|
+
for (const [key, value] of res.headers.entries()) {
|
|
177
|
+
if (key.toLowerCase() === 'set-cookie')
|
|
178
|
+
continue
|
|
179
|
+
headers[key] = value
|
|
180
|
+
}
|
|
181
|
+
return { headers, setCookies }
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/** Renders a URL against the Prunelle app under `options.root` in-process, reusing a cached build under `.prunelle-cache/render-build` when sources are unchanged. */
|
|
185
|
+
export async function renderUrl(options: RenderUrlOptions): Promise<RenderUrlResult> {
|
|
186
|
+
const root = resolve(options.root)
|
|
187
|
+
const targetUrl = normalizeTargetUrl(options.url)
|
|
188
|
+
const method = options.method !== undefined && options.method.trim().length > 0
|
|
189
|
+
? options.method.trim().toUpperCase()
|
|
190
|
+
: (options.body !== undefined ? 'POST' : 'GET')
|
|
191
|
+
const headers = buildRequestHeaders(options.headers, options.cookies, method, targetUrl)
|
|
192
|
+
|
|
193
|
+
const cacheRoot = join(root, '.prunelle-cache')
|
|
194
|
+
const renderOutDir = join(cacheRoot, 'render-build')
|
|
195
|
+
const stampFile = join(renderOutDir, '.render-stamp')
|
|
196
|
+
const manifestFile = join(renderOutDir, 'manifest.json')
|
|
197
|
+
const entryFile = join(renderOutDir, 'server', SERVER_ENTRY_FILE)
|
|
198
|
+
|
|
199
|
+
const sourceStamp = computeSourceStamp(root)
|
|
200
|
+
const canReuse = options.fresh !== true
|
|
201
|
+
&& existsSync(manifestFile)
|
|
202
|
+
&& existsSync(entryFile)
|
|
203
|
+
&& readStamp(stampFile) === sourceStamp
|
|
204
|
+
|
|
205
|
+
if (!canReuse)
|
|
206
|
+
ensureCacheGitignore(cacheRoot)
|
|
207
|
+
|
|
208
|
+
const app = await testApp({
|
|
209
|
+
root,
|
|
210
|
+
outDir: renderOutDir,
|
|
211
|
+
prebuilt: canReuse,
|
|
212
|
+
})
|
|
213
|
+
|
|
214
|
+
try {
|
|
215
|
+
if (!canReuse)
|
|
216
|
+
writeFileSync(stampFile, sourceStamp, 'utf8')
|
|
217
|
+
|
|
218
|
+
const reqInit: RequestInit = method !== 'GET' && method !== 'HEAD' && options.body !== undefined
|
|
219
|
+
? { method, headers, body: options.body }
|
|
220
|
+
: { method, headers }
|
|
221
|
+
const res = await app.fetch(targetUrl, reqInit)
|
|
222
|
+
const body = await res.text()
|
|
223
|
+
const { headers: resHeaders, setCookies } = extractResponseHeaders(res)
|
|
224
|
+
const statusText = res.statusText.length > 0 ? res.statusText : (STATUS_TEXT[res.status] ?? '')
|
|
225
|
+
|
|
226
|
+
return {
|
|
227
|
+
status: res.status,
|
|
228
|
+
statusText,
|
|
229
|
+
headers: resHeaders,
|
|
230
|
+
setCookies,
|
|
231
|
+
body,
|
|
232
|
+
ok: res.status >= 200 && res.status < 400,
|
|
233
|
+
reusedBuild: canReuse,
|
|
234
|
+
errors: [...app.errors],
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
finally {
|
|
238
|
+
await app.app.dispose?.()
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
/** Formats a `RenderUrlResult`, prepending the HTTP status line and headers when `includeHeaders` is true (`-i`). */
|
|
243
|
+
export function formatRenderResult(result: RenderUrlResult, includeHeaders: boolean): string {
|
|
244
|
+
if (!includeHeaders)
|
|
245
|
+
return result.body
|
|
246
|
+
|
|
247
|
+
const statusLine = result.statusText.length > 0
|
|
248
|
+
? `HTTP/1.1 ${result.status} ${result.statusText}`
|
|
249
|
+
: `HTTP/1.1 ${result.status}`
|
|
250
|
+
const lines = [statusLine]
|
|
251
|
+
|
|
252
|
+
for (const [name, value] of Object.entries(result.headers)) {
|
|
253
|
+
if (name.toLowerCase() === 'set-cookie')
|
|
254
|
+
continue
|
|
255
|
+
lines.push(`${name}: ${value}`)
|
|
256
|
+
}
|
|
257
|
+
for (const cookie of result.setCookies)
|
|
258
|
+
lines.push(`set-cookie: ${cookie}`)
|
|
259
|
+
|
|
260
|
+
return `${lines.join('\n')}\n\n${result.body}`
|
|
261
|
+
}
|
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 {
|