prunelle 0.0.0-stage → 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 +152 -0
- package/package.json +59 -4
- package/src/a11y/declaration.ts +335 -0
- package/src/a11y/index.ts +446 -0
- package/src/a11y/rgaa-map.ts +184 -0
- package/src/ambient.d.ts +6 -0
- package/src/attrs.ts +43 -0
- package/src/build/bundle.ts +657 -0
- package/src/build/carry.ts +57 -0
- package/src/build/client-entries.ts +107 -0
- package/src/build/client-plugin.ts +173 -0
- package/src/build/client-prune.ts +168 -0
- package/src/build/compile.ts +129 -0
- package/src/build/ecoindex.ts +229 -0
- package/src/build/files.ts +156 -0
- package/src/build/first-load.ts +164 -0
- package/src/build/graph.ts +247 -0
- package/src/build/index.ts +641 -0
- package/src/build/is-inside.ts +12 -0
- package/src/build/islands.ts +641 -0
- package/src/build/manifest.ts +325 -0
- package/src/build/output.ts +84 -0
- package/src/build/plugin-host.ts +278 -0
- package/src/build/precompress.ts +139 -0
- package/src/build/prerender.ts +232 -0
- package/src/build/render-rules.ts +205 -0
- package/src/build/report.ts +268 -0
- package/src/build/resolve.ts +52 -0
- package/src/build/routes.ts +342 -0
- package/src/build/server-entry.ts +38 -0
- package/src/build/static.ts +207 -0
- 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 +381 -0
- package/src/cli/commands.ts +345 -0
- package/src/cli/docs.ts +402 -0
- package/src/cli/index.ts +70 -0
- package/src/cli/inspect.ts +345 -0
- package/src/cli/mcp-tools.ts +480 -0
- package/src/cli/mcp.ts +205 -0
- package/src/cli/new.ts +41 -0
- package/src/cli/render.ts +261 -0
- package/src/cli/upgrade-names.ts +209 -0
- package/src/cli/upgrade.ts +354 -0
- package/src/compiler/analyze.ts +632 -0
- package/src/compiler/ast.ts +82 -0
- package/src/compiler/browser-globals.ts +127 -0
- package/src/compiler/cacheability.ts +592 -0
- package/src/compiler/compliance-rgaa.ts +502 -0
- package/src/compiler/compliance.ts +497 -0
- package/src/compiler/data-keys.ts +295 -0
- package/src/compiler/dev-source.ts +87 -0
- package/src/compiler/dom-attrs.ts +452 -0
- package/src/compiler/dom.ts +567 -0
- package/src/compiler/emit.ts +131 -0
- package/src/compiler/expr-context.ts +518 -0
- package/src/compiler/index.ts +8 -0
- package/src/compiler/interactivity.ts +366 -0
- package/src/compiler/mistakes.ts +499 -0
- package/src/compiler/node-env.ts +50 -0
- package/src/compiler/patch.ts +97 -0
- package/src/compiler/props.ts +511 -0
- package/src/compiler/scope.ts +607 -0
- package/src/compiler/server-only.ts +326 -0
- package/src/compiler/shared.ts +369 -0
- package/src/compiler/signal-reads.ts +242 -0
- package/src/compiler/slots.ts +227 -0
- package/src/compiler/ssr-helpers.ts +555 -0
- package/src/compiler/ssr-island.ts +90 -0
- package/src/compiler/ssr-prunelle-tags.ts +69 -0
- package/src/compiler/ssr.ts +526 -0
- package/src/context.ts +165 -0
- package/src/dev/child.ts +30 -0
- package/src/dev/error-log.ts +151 -0
- package/src/dev/index.ts +258 -0
- package/src/dev/modules.ts +68 -0
- package/src/dev/open-editor.ts +204 -0
- package/src/dev/protocol.ts +22 -0
- package/src/dev/queue.ts +79 -0
- package/src/dev/reload.ts +159 -0
- package/src/dev/supervisor.ts +204 -0
- package/src/dev/watchers.ts +251 -0
- package/src/dom/action.ts +164 -0
- package/src/dom/attrs.ts +84 -0
- package/src/dom/claim.ts +120 -0
- package/src/dom/extras.ts +562 -0
- package/src/dom/index.ts +289 -0
- package/src/dom/island.ts +285 -0
- package/src/dom/loop.ts +450 -0
- package/src/dom/revive.ts +36 -0
- package/src/index.ts +22 -0
- package/src/jsx-runtime.ts +566 -0
- package/src/plugins/config.ts +86 -0
- package/src/plugins/context.ts +66 -0
- package/src/plugins/index.ts +14 -0
- package/src/plugins/load.ts +70 -0
- package/src/plugins/order.ts +111 -0
- package/src/plugins/public.ts +15 -0
- package/src/plugins/requires.ts +47 -0
- package/src/plugins/services.ts +97 -0
- package/src/plugins/types.ts +261 -0
- package/src/reactivity/graph.ts +249 -0
- package/src/reactivity/index.ts +533 -0
- package/src/reactivity/selector.ts +51 -0
- package/src/reactivity/store.ts +208 -0
- package/src/server/action-protect.ts +198 -0
- package/src/server/action-registry.ts +78 -0
- package/src/server/action.ts +530 -0
- package/src/server/app-entry.ts +23 -0
- package/src/server/assets.ts +168 -0
- package/src/server/compress.ts +642 -0
- package/src/server/consent.ts +253 -0
- package/src/server/cookies.ts +139 -0
- package/src/server/document.ts +271 -0
- package/src/server/env.ts +33 -0
- package/src/server/errors.ts +391 -0
- package/src/server/form-schema.ts +343 -0
- package/src/server/health.ts +244 -0
- package/src/server/http.ts +538 -0
- package/src/server/index.ts +586 -0
- package/src/server/lifecycle.ts +75 -0
- package/src/server/loader.ts +123 -0
- package/src/server/page.ts +107 -0
- package/src/server/param-matchers.ts +112 -0
- package/src/server/plugin-host.ts +265 -0
- package/src/server/prerendered.ts +71 -0
- package/src/server/public.ts +19 -0
- package/src/server/rate-limit.ts +156 -0
- package/src/server/region.ts +96 -0
- package/src/server/request-body.ts +27 -0
- package/src/server/request-path.ts +73 -0
- package/src/server/request-scope.ts +22 -0
- package/src/server/route-cache.ts +423 -0
- package/src/server/route-table.ts +410 -0
- package/src/server/router.ts +261 -0
- package/src/server/routing.ts +472 -0
- package/src/server/security.ts +499 -0
- package/src/server/serve-handlers.ts +83 -0
- package/src/server/served-file.ts +128 -0
- package/src/server/standard-schema.ts +87 -0
- package/src/server/start.ts +143 -0
- package/src/server/static-dir.ts +220 -0
- package/src/server/stream.ts +211 -0
- package/src/ssr/context.ts +383 -0
- package/src/ssr/index.ts +596 -0
- package/src/ssr/navigation.ts +96 -0
- package/src/ssr/region.ts +183 -0
- package/src/style.ts +33 -0
- package/src/test/browser.ts +192 -0
- package/src/test/index.ts +191 -0
- 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/src/unrenderable.ts +35 -0
- package/templates/_shared/AGENTS.md +10 -0
- package/templates/_shared/CLAUDE.md +1 -0
- package/templates/_shared/gitignore +3 -0
- package/templates/_shared/mcp.json +11 -0
- package/templates/_shared/public/robots.txt +2 -0
- package/templates/_shared/src/routes/legal.tsx +13 -0
- package/templates/_shared/tsconfig.json +25 -0
- package/templates/app/.env.example +4 -0
- package/templates/app/package.json +21 -0
- package/templates/app/prunelle.config.ts +11 -0
- package/templates/app/src/auth.ts +14 -0
- package/templates/app/src/routes/_layout.tsx +32 -0
- package/templates/app/src/routes/dashboard/_middleware.ts +3 -0
- package/templates/app/src/routes/dashboard/index.tsx +13 -0
- package/templates/app/src/routes/index.tsx +15 -0
- package/templates/app/src/routes/login.tsx +34 -0
- package/templates/app/src/styles/app.css +7 -0
- package/templates/app/tests/app.test.ts +32 -0
- package/templates/blog/content/posts/welcome.md +9 -0
- package/templates/blog/package.json +22 -0
- package/templates/blog/prunelle.config.ts +23 -0
- package/templates/blog/src/posts.ts +26 -0
- package/templates/blog/src/routes/_layout.tsx +20 -0
- package/templates/blog/src/routes/blog/[slug].tsx +31 -0
- package/templates/blog/src/routes/index.tsx +33 -0
- package/templates/blog/src/styles/app.css +10 -0
- package/templates/fullstack/package.json +19 -0
- package/templates/fullstack/prunelle.config.ts +6 -0
- package/templates/fullstack/src/actions/greet.ts +19 -0
- package/templates/fullstack/src/components/Counter.tsx +10 -0
- package/templates/fullstack/src/components/GreetForm.tsx +27 -0
- package/templates/fullstack/src/routes/_layout.tsx +14 -0
- package/templates/fullstack/src/routes/api/health.ts +5 -0
- package/templates/fullstack/src/routes/index.tsx +13 -0
- package/templates/fullstack/src/styles/app.css +29 -0
- package/templates/fullstack/tests/app.test.ts +37 -0
- package/templates/minimal/package.json +19 -0
- package/templates/minimal/prunelle.config.ts +6 -0
- package/templates/minimal/src/components/Counter.tsx +10 -0
- package/templates/minimal/src/routes/_layout.tsx +14 -0
- package/templates/minimal/src/routes/index.tsx +11 -0
- package/templates/minimal/src/styles/app.css +22 -0
- package/ts-plugin.cjs +4277 -0
- package/README.md +0 -3
|
@@ -0,0 +1,499 @@
|
|
|
1
|
+
// Refuses JSX that compiles but does the wrong thing, mostly habits from React, Solid and Astro, with an error naming the fix.
|
|
2
|
+
|
|
3
|
+
import type { JSXAttribute, JSXAttributeItem, JSXElement, Node } from 'oxc-parser'
|
|
4
|
+
import type { ComplianceRule } from './compliance'
|
|
5
|
+
import type { ServerOnlyInIsland } from './interactivity'
|
|
6
|
+
import { URL_ATTRS } from '../attrs'
|
|
7
|
+
import { walk } from './ast'
|
|
8
|
+
import { calleeName, EVENT_ATTR, filterMeaningfulChildren, isComponentTag, isUnsafeUrlAttr, jsxTagName, unwrapParens, unwrapTsExpr, VOID_ELEMENTS } from './shared'
|
|
9
|
+
|
|
10
|
+
// The prunelle prop for each DOM event, keyed by the event name prunelle binds (`onKeyDown` binds `keydown`).
|
|
11
|
+
const EVENT_PROPS = new Map(Object.entries({
|
|
12
|
+
abort: 'onAbort', animationcancel: 'onAnimationCancel', animationend: 'onAnimationEnd', animationiteration: 'onAnimationIteration', animationstart: 'onAnimationStart',
|
|
13
|
+
auxclick: 'onAuxClick', beforeinput: 'onBeforeInput', beforetoggle: 'onBeforeToggle', blur: 'onBlur', cancel: 'onCancel',
|
|
14
|
+
canplay: 'onCanPlay', canplaythrough: 'onCanPlayThrough', change: 'onChange', click: 'onClick', close: 'onClose',
|
|
15
|
+
compositionend: 'onCompositionEnd', compositionstart: 'onCompositionStart', compositionupdate: 'onCompositionUpdate',
|
|
16
|
+
contextmenu: 'onContextMenu', copy: 'onCopy', cut: 'onCut', dblclick: 'onDblClick', drag: 'onDrag', dragend: 'onDragEnd',
|
|
17
|
+
dragenter: 'onDragEnter', dragleave: 'onDragLeave', dragover: 'onDragOver', dragstart: 'onDragStart', drop: 'onDrop',
|
|
18
|
+
durationchange: 'onDurationChange', emptied: 'onEmptied', ended: 'onEnded', error: 'onError', focus: 'onFocus',
|
|
19
|
+
focusin: 'onFocusIn', focusout: 'onFocusOut', formdata: 'onFormData', gotpointercapture: 'onGotPointerCapture',
|
|
20
|
+
input: 'onInput', invalid: 'onInvalid', keydown: 'onKeyDown', keypress: 'onKeyPress', keyup: 'onKeyUp', load: 'onLoad',
|
|
21
|
+
loadeddata: 'onLoadedData', loadedmetadata: 'onLoadedMetadata', loadstart: 'onLoadStart',
|
|
22
|
+
lostpointercapture: 'onLostPointerCapture', mousedown: 'onMouseDown', mouseenter: 'onMouseEnter', mouseleave: 'onMouseLeave',
|
|
23
|
+
mousemove: 'onMouseMove', mouseout: 'onMouseOut', mouseover: 'onMouseOver', mouseup: 'onMouseUp', paste: 'onPaste',
|
|
24
|
+
pause: 'onPause', play: 'onPlay', playing: 'onPlaying', pointercancel: 'onPointerCancel', pointerdown: 'onPointerDown',
|
|
25
|
+
pointerenter: 'onPointerEnter', pointerleave: 'onPointerLeave', pointermove: 'onPointerMove', pointerout: 'onPointerOut',
|
|
26
|
+
pointerover: 'onPointerOver', pointerup: 'onPointerUp', progress: 'onProgress', ratechange: 'onRateChange', reset: 'onReset',
|
|
27
|
+
resize: 'onResize', scroll: 'onScroll', scrollend: 'onScrollEnd', securitypolicyviolation: 'onSecurityPolicyViolation',
|
|
28
|
+
seeked: 'onSeeked', seeking: 'onSeeking', select: 'onSelect', selectionchange: 'onSelectionChange',
|
|
29
|
+
selectstart: 'onSelectStart', slotchange: 'onSlotChange', stalled: 'onStalled', submit: 'onSubmit', suspend: 'onSuspend',
|
|
30
|
+
timeupdate: 'onTimeUpdate', toggle: 'onToggle', touchcancel: 'onTouchCancel', touchend: 'onTouchEnd',
|
|
31
|
+
touchmove: 'onTouchMove', touchstart: 'onTouchStart', transitioncancel: 'onTransitionCancel',
|
|
32
|
+
transitionend: 'onTransitionEnd', transitionrun: 'onTransitionRun', transitionstart: 'onTransitionStart',
|
|
33
|
+
volumechange: 'onVolumeChange', waiting: 'onWaiting', wheel: 'onWheel',
|
|
34
|
+
afterprint: 'onAfterPrint', beforeprint: 'onBeforePrint', beforeunload: 'onBeforeUnload', hashchange: 'onHashChange',
|
|
35
|
+
message: 'onMessage', offline: 'onOffline', online: 'onOnline', pagehide: 'onPageHide', pageshow: 'onPageShow',
|
|
36
|
+
popstate: 'onPopState', storage: 'onStorage', unload: 'onUnload', fullscreenchange: 'onFullscreenChange',
|
|
37
|
+
fullscreenerror: 'onFullscreenError', loadend: 'onLoadEnd', search: 'onSearch', beforematch: 'onBeforeMatch',
|
|
38
|
+
command: 'onCommand', cuechange: 'onCueChange', encrypted: 'onEncrypted', waitingforkey: 'onWaitingForKey',
|
|
39
|
+
pointerrawupdate: 'onPointerRawUpdate', contextlost: 'onContextLost', contextrestored: 'onContextRestored',
|
|
40
|
+
contentvisibilityautostatechange: 'onContentVisibilityAutoStateChange',
|
|
41
|
+
}))
|
|
42
|
+
|
|
43
|
+
// React names whose DOM event is spelled differently.
|
|
44
|
+
const RENAMED_EVENTS = new Map([['doubleclick', 'dblclick']])
|
|
45
|
+
const CAPTURE_SUFFIX = 'capture'
|
|
46
|
+
const LOWERCASE_EVENT = /^on[a-z]/
|
|
47
|
+
|
|
48
|
+
function eventProp(event: string): string {
|
|
49
|
+
return EVENT_PROPS.get(event) ?? `on${event.charAt(0).toUpperCase()}${event.slice(1)}`
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** A compiler mistake, with the source offset of the code it names once known. */
|
|
53
|
+
export class PrunelleMistake extends Error {
|
|
54
|
+
start: number | undefined = undefined
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** Code that compiles but usually means something else, at its source offset. */
|
|
58
|
+
export interface CompilerWarning {
|
|
59
|
+
message: string
|
|
60
|
+
start: number
|
|
61
|
+
rule?: ComplianceRule | undefined
|
|
62
|
+
urlOrigin?: string | undefined
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export function mistake(what: string, filename: string, fix: string): PrunelleMistake {
|
|
66
|
+
return new PrunelleMistake(`prunelle compiler: ${what} in ${filename}: ${fix}.`)
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
let collected: PrunelleMistake[] | undefined
|
|
70
|
+
|
|
71
|
+
/** Runs one check, a mistake it throws placed at `start`. The build stops at the first mistake; while `collectMistakes` runs, the mistake is recorded and the caller goes on. */
|
|
72
|
+
export function guarded(start: number, check: () => void): void {
|
|
73
|
+
try {
|
|
74
|
+
check()
|
|
75
|
+
}
|
|
76
|
+
catch (err) {
|
|
77
|
+
if (!(err instanceof PrunelleMistake))
|
|
78
|
+
throw err
|
|
79
|
+
err.start ??= start
|
|
80
|
+
if (collected === undefined)
|
|
81
|
+
throw err
|
|
82
|
+
collected.push(err)
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** Runs `fn` with every guarded check recording its mistake; `error` is what `fn` threw past them, a syntax error or a mistake that stops the analysis. */
|
|
87
|
+
export function collectMistakes<T>(fn: () => T): { value: T | undefined, mistakes: PrunelleMistake[], error: unknown } {
|
|
88
|
+
const prev = collected
|
|
89
|
+
const mistakes: PrunelleMistake[] = []
|
|
90
|
+
collected = mistakes
|
|
91
|
+
try {
|
|
92
|
+
return { value: fn(), mistakes, error: undefined }
|
|
93
|
+
}
|
|
94
|
+
catch (error) {
|
|
95
|
+
return { value: undefined, mistakes, error }
|
|
96
|
+
}
|
|
97
|
+
finally {
|
|
98
|
+
collected = prev
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
export function islandRemoved(filename: string, start?: number): PrunelleMistake {
|
|
103
|
+
const err = mistake('island()', filename, 'it is gone; write export const hydrate = \'visible\' in the component\'s file, or set $hydrate where it renders')
|
|
104
|
+
err.start = start
|
|
105
|
+
return err
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
// `<Head>` and `<Suspense>` run during server rendering only, so in an island they never update.
|
|
109
|
+
export function serverOnlyTagError(filename: string, { tag, island, reason, offset }: ServerOnlyInIsland): PrunelleMistake {
|
|
110
|
+
const err = mistake(`<${tag}> in an island`, filename, `${island} is an island because it ${reason}; move <${tag}> to the page or a layout, outside any component with state or handlers`)
|
|
111
|
+
err.start = offset
|
|
112
|
+
return err
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
const KAY_SOURCE_RE = /^@kayjs\/(kay(?=\/|$))?/
|
|
116
|
+
|
|
117
|
+
/** Refuses an import of kay, the name prunelle had before: the app would load both. */
|
|
118
|
+
export function assertNoKayImport(source: string, filename: string): void {
|
|
119
|
+
const match = KAY_SOURCE_RE.exec(source)
|
|
120
|
+
if (match !== null)
|
|
121
|
+
throw mistake(`import from '${source}'`, filename, `write '${source.replace(KAY_SOURCE_RE, match[1] === undefined ? '@prunellejs/' : 'prunelle')}' (prunelle upgrade rewrites every import)`)
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
const HYDRATE_MODES = new Set(['load', 'visible', 'idle', 'interaction', 'client'])
|
|
125
|
+
const MEDIA_MODE = /^media\(.+\)$/
|
|
126
|
+
|
|
127
|
+
/** Throws on a hydrate mode the browser runtime would silently treat as `load`; `*` stands for a mode picked at runtime. */
|
|
128
|
+
export function checkHydrateMode(mode: string, what: string, filename: string): void {
|
|
129
|
+
if (mode !== '*' && !HYDRATE_MODES.has(mode) && !MEDIA_MODE.test(mode))
|
|
130
|
+
throw mistake(what, filename, 'use load, visible, idle, interaction, client or media(<query>)')
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/** Extracts a static string literal or zero-interpolation template literal after unwrapping TS assertions. */
|
|
134
|
+
export function staticStringValue(node: Node | null | undefined): string | undefined {
|
|
135
|
+
if (node === null || node === undefined)
|
|
136
|
+
return undefined
|
|
137
|
+
const val = unwrapTsExpr(node)
|
|
138
|
+
if (val.type === 'Literal' && typeof val.value === 'string')
|
|
139
|
+
return val.value
|
|
140
|
+
return val.type === 'TemplateLiteral' && val.expressions.length === 0 ? (val.quasis[0]?.value.cooked ?? undefined) : undefined
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/** Validates an `export const hydrate = ...` initializer and returns its string mode when statically known. */
|
|
144
|
+
export function checkExportHydrate(init: Node | null | undefined, filename: string): string | undefined {
|
|
145
|
+
if (init === null || init === undefined)
|
|
146
|
+
return undefined
|
|
147
|
+
const mode = staticStringValue(init)
|
|
148
|
+
if (mode !== undefined) {
|
|
149
|
+
guarded(init.start, () => checkHydrateMode(mode, `hydrate = "${mode}"`, filename))
|
|
150
|
+
return mode
|
|
151
|
+
}
|
|
152
|
+
const val = unwrapTsExpr(init)
|
|
153
|
+
if (val.type === 'Literal' || val.type === 'ArrayExpression' || val.type === 'ObjectExpression' || (val.type === 'Identifier' && val.name === 'undefined'))
|
|
154
|
+
guarded(init.start, () => { throw mistake('hydrate', filename, 'use load, visible, idle, interaction, client or media(<query>)') })
|
|
155
|
+
return undefined
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
function checkHandler(name: string, value: JSXAttribute['value'], filename: string, code: string): void {
|
|
159
|
+
if (value === null)
|
|
160
|
+
throw mistake(name, filename, `pass a function, ${name}={() => ...}`)
|
|
161
|
+
if (value.type === 'Literal')
|
|
162
|
+
throw mistake(`${name}="..."`, filename, `pass a function, ${name}={() => ...}`)
|
|
163
|
+
if (value.type !== 'JSXExpressionContainer')
|
|
164
|
+
return
|
|
165
|
+
const expr = unwrapParens(value.expression)
|
|
166
|
+
if ((expr.type === 'Literal' && typeof expr.value === 'string') || expr.type === 'TemplateLiteral')
|
|
167
|
+
throw mistake(`${name}="..."`, filename, `pass a function, ${name}={() => ...}`)
|
|
168
|
+
if (expr.type === 'UpdateExpression' || expr.type === 'AssignmentExpression') {
|
|
169
|
+
const source = code.slice(expr.start, expr.end)
|
|
170
|
+
throw mistake(`${name} runs ${source} at render`, filename, `write ${name}={() => ${source}}`)
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
// SVG presentation attributes React spells in camelCase; SVG is case-sensitive, so the camelCase name sets nothing.
|
|
175
|
+
const KEBAB_SVG_ATTRS = new Set([
|
|
176
|
+
'alignment-baseline', 'baseline-shift', 'clip-path', 'clip-rule', 'color-interpolation', 'color-interpolation-filters',
|
|
177
|
+
'dominant-baseline', 'enable-background', 'fill-opacity', 'fill-rule', 'flood-color', 'flood-opacity', 'font-family',
|
|
178
|
+
'font-size', 'font-size-adjust', 'font-stretch', 'font-style', 'font-variant', 'font-weight', 'image-rendering',
|
|
179
|
+
'letter-spacing', 'lighting-color', 'marker-end', 'marker-mid', 'marker-start', 'paint-order', 'pointer-events',
|
|
180
|
+
'shape-rendering', 'stop-color', 'stop-opacity', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap',
|
|
181
|
+
'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', 'text-anchor', 'text-decoration',
|
|
182
|
+
'text-rendering', 'transform-origin', 'unicode-bidi', 'vector-effect', 'word-spacing', 'writing-mode',
|
|
183
|
+
])
|
|
184
|
+
const CAMEL_HUMP = /[A-Z]/g
|
|
185
|
+
// React's uncontrolled-input props and the attribute each one stands for.
|
|
186
|
+
const REACT_DEFAULTS = new Map([['defaultValue', 'value'], ['defaultChecked', 'checked']])
|
|
187
|
+
const BOOLEAN_ATTRS = new Set([
|
|
188
|
+
'allowfullscreen', 'async', 'autofocus', 'autoplay', 'checked', 'controls', 'default', 'defer', 'disabled',
|
|
189
|
+
'formnovalidate', 'hidden', 'inert', 'ismap', 'loop', 'multiple', 'muted', 'nomodule', 'novalidate', 'open',
|
|
190
|
+
'playsinline', 'readonly', 'required', 'reversed', 'selected',
|
|
191
|
+
])
|
|
192
|
+
|
|
193
|
+
function checkRef(value: JSXAttribute['value'], filename: string): void {
|
|
194
|
+
if (value === null)
|
|
195
|
+
throw mistake('ref', filename, 'pass a function, ref={el => ...}')
|
|
196
|
+
if (value.type === 'Literal')
|
|
197
|
+
throw mistake('ref="..."', filename, 'pass a function, ref={el => ...}')
|
|
198
|
+
if (value.type === 'JSXExpressionContainer' && unwrapParens(value.expression).type === 'ObjectExpression')
|
|
199
|
+
throw mistake('ref={{ ... }}', filename, 'pass a function, ref={el => ...}, prunelle has no ref objects')
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
const CAMEL_ARIA = /^aria[A-Z]/
|
|
203
|
+
|
|
204
|
+
function checkSpelling(name: string, value: JSXAttribute['value'], filename: string): void {
|
|
205
|
+
if (CAMEL_ARIA.test(name))
|
|
206
|
+
throw mistake(name, filename, `write aria-${name.slice(4).toLowerCase()}={...}, ARIA attributes use kebab-case`)
|
|
207
|
+
const kebab = name.replace(CAMEL_HUMP, hump => `-${hump.toLowerCase()}`)
|
|
208
|
+
if (kebab !== name && KEBAB_SVG_ATTRS.has(kebab))
|
|
209
|
+
throw mistake(name, filename, `write ${kebab}={...}, SVG attributes are case-sensitive`)
|
|
210
|
+
if (name === 'xlinkHref')
|
|
211
|
+
throw mistake(name, filename, 'write xlink:href={...}, or href={...}')
|
|
212
|
+
const attribute = REACT_DEFAULTS.get(name)
|
|
213
|
+
if (attribute !== undefined)
|
|
214
|
+
throw mistake(name, filename, `write ${attribute}={...}`)
|
|
215
|
+
if (value?.type === 'Literal' && value.value === 'false' && BOOLEAN_ATTRS.has(name.toLowerCase()))
|
|
216
|
+
throw mistake(`${name}="false"`, filename, `write ${name}={false}, any string turns it on`)
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
// Astro's client: directives and the $hydrate mode each one means.
|
|
220
|
+
const CLIENT_DIRECTIVES = new Map([['load', 'load'], ['visible', 'visible'], ['idle', 'idle'], ['only', 'client'], ['media', 'media(<query>)']])
|
|
221
|
+
// XML namespaces SVG and MathML really use; every other prefix is a directive from another framework.
|
|
222
|
+
const XML_NAMESPACES = new Set(['xlink', 'xml', 'xmlns'])
|
|
223
|
+
|
|
224
|
+
function checkNamespacedAttribute(namespace: string, name: string, filename: string): void {
|
|
225
|
+
if (XML_NAMESPACES.has(namespace))
|
|
226
|
+
return
|
|
227
|
+
const what = `${namespace}:${name}`
|
|
228
|
+
if (namespace === 'on')
|
|
229
|
+
throw mistake(what, filename, `write ${eventProp(name.toLowerCase())}={...}`)
|
|
230
|
+
if (namespace === 'client')
|
|
231
|
+
throw mistake(what, filename, `write $hydrate="${CLIENT_DIRECTIVES.get(name) ?? 'load'}"`)
|
|
232
|
+
if (what === 'class:list')
|
|
233
|
+
throw mistake(what, filename, 'pass one string to class, joining the names yourself')
|
|
234
|
+
if (what === 'set:html')
|
|
235
|
+
throw mistake(what, filename, 'write innerHTML={...}')
|
|
236
|
+
if (what === 'set:text')
|
|
237
|
+
throw mistake(what, filename, 'write the text as children')
|
|
238
|
+
if (namespace === 'use')
|
|
239
|
+
throw mistake(what, filename, `call ${name} in a ref`)
|
|
240
|
+
if (namespace === 'prop' || namespace === 'attr' || namespace === 'bool')
|
|
241
|
+
throw mistake(what, filename, `write ${name}={...}`)
|
|
242
|
+
throw mistake(what, filename, `prunelle has no ${namespace}: directives`)
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
// The source of `x` in React's `{{ __html: x }}`, or undefined when the attribute holds something else.
|
|
246
|
+
function reactHtmlSource(value: JSXAttribute['value'], code: string): string | undefined {
|
|
247
|
+
if (value?.type !== 'JSXExpressionContainer')
|
|
248
|
+
return undefined
|
|
249
|
+
const expr = unwrapParens(value.expression)
|
|
250
|
+
if (expr.type !== 'ObjectExpression')
|
|
251
|
+
return undefined
|
|
252
|
+
for (const p of expr.properties) {
|
|
253
|
+
if (p.type !== 'Property')
|
|
254
|
+
continue
|
|
255
|
+
const keyName = p.key.type === 'Identifier' ? p.key.name : p.key.type === 'Literal' ? String(p.key.value) : undefined
|
|
256
|
+
if (keyName === '__html')
|
|
257
|
+
return code.slice(p.value.start, p.value.end)
|
|
258
|
+
}
|
|
259
|
+
return undefined
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
function checkInnerHtml(element: JSXElement, tag: string, attr: JSXAttribute, filename: string, code: string): void {
|
|
263
|
+
const html = reactHtmlSource(attr.value, code)
|
|
264
|
+
if (html !== undefined)
|
|
265
|
+
throw mistake('innerHTML={{ __html }}', filename, `write innerHTML={${html}}, prunelle takes the HTML string itself`)
|
|
266
|
+
if (VOID_ELEMENTS.has(tag))
|
|
267
|
+
throw mistake(`innerHTML on <${tag}>`, filename, 'a void element has no content, drop innerHTML')
|
|
268
|
+
if (filterMeaningfulChildren(element.children).length > 0)
|
|
269
|
+
throw mistake('innerHTML with children', filename, 'keep one, the children or innerHTML')
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
function staticStringAttr(value: JSXAttribute['value']): string | undefined {
|
|
273
|
+
if (value === null)
|
|
274
|
+
return undefined
|
|
275
|
+
if (value.type === 'Literal' && typeof value.value === 'string')
|
|
276
|
+
return value.value
|
|
277
|
+
if (value.type === 'JSXExpressionContainer' && value.expression.type !== 'JSXEmptyExpression') {
|
|
278
|
+
const expr = unwrapParens(value.expression)
|
|
279
|
+
if (expr.type === 'Literal' && typeof expr.value === 'string')
|
|
280
|
+
return expr.value
|
|
281
|
+
if (expr.type === 'TemplateLiteral' && expr.expressions.length === 0)
|
|
282
|
+
return expr.quasis[0]?.value.cooked ?? undefined
|
|
283
|
+
}
|
|
284
|
+
return undefined
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
function checkElementAttribute(attr: JSXAttribute, tag: string, isCustomElement: boolean, filename: string, code: string, warnings: CompilerWarning[]): void {
|
|
288
|
+
if (attr.name.type !== 'JSXIdentifier')
|
|
289
|
+
return
|
|
290
|
+
const name = attr.name.name
|
|
291
|
+
if (name === '$hydrate')
|
|
292
|
+
throw mistake(`$hydrate on <${tag}>`, filename, 'only components can be islands; drop $hydrate, or move it onto a component tag')
|
|
293
|
+
if (name.toLowerCase() === 'srcdoc')
|
|
294
|
+
throw mistake(`${name} on <${tag}>`, filename, 'prunelle blocks srcdoc for XSS safety; serve the document from a route and load it with src')
|
|
295
|
+
if (name === 'dangerouslySetInnerHTML')
|
|
296
|
+
throw mistake(name, filename, `write innerHTML={${reactHtmlSource(attr.value, code) ?? '...'}}`)
|
|
297
|
+
if (name === 'classList')
|
|
298
|
+
throw mistake(name, filename, 'pass one string to class, joining the names yourself')
|
|
299
|
+
if (name === 'ref')
|
|
300
|
+
return checkRef(attr.value, filename)
|
|
301
|
+
checkSpelling(name, attr.value, filename)
|
|
302
|
+
if (URL_ATTRS.has(name.toLowerCase())) {
|
|
303
|
+
const urlText = staticStringAttr(attr.value)
|
|
304
|
+
if (urlText !== undefined && isUnsafeUrlAttr(name, urlText, tag))
|
|
305
|
+
warnings.push({ message: `prunelle compiler: unsafe URL in ${name} on <${tag}> in ${filename}; prunelle strips javascript:, vbscript:, and non-image data: URLs.`, start: attr.start })
|
|
306
|
+
}
|
|
307
|
+
if (LOWERCASE_EVENT.test(name) && EVENT_PROPS.has(name.slice(2)))
|
|
308
|
+
throw mistake(name, filename, `write ${eventProp(name.slice(2))}={...}, prunelle binds camelCase event props only`)
|
|
309
|
+
if (!EVENT_ATTR.test(name))
|
|
310
|
+
return
|
|
311
|
+
checkHandler(name, attr.value, filename, code)
|
|
312
|
+
if (!isCustomElement)
|
|
313
|
+
checkEventName(name, filename)
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
function checkEventName(name: string, filename: string): void {
|
|
317
|
+
const event = name.slice(2).toLowerCase()
|
|
318
|
+
if (EVENT_PROPS.has(event))
|
|
319
|
+
return
|
|
320
|
+
const renamed = RENAMED_EVENTS.get(event)
|
|
321
|
+
if (renamed !== undefined)
|
|
322
|
+
throw mistake(name, filename, `write ${eventProp(renamed)}={...}`)
|
|
323
|
+
if (event.endsWith(CAPTURE_SUFFIX) && EVENT_PROPS.has(event.slice(0, -CAPTURE_SUFFIX.length)))
|
|
324
|
+
throw mistake(name, filename, `prunelle has no capture props, call addEventListener('${event.slice(0, -CAPTURE_SUFFIX.length)}', fn, { capture: true }) in a ref`)
|
|
325
|
+
throw mistake(name, filename, `no DOM event is named "${event}"; for a custom event, call addEventListener in a ref`)
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
// Plain containers that never take focus unless given a tabIndex, so their onFocus/onBlur never fire.
|
|
329
|
+
const UNFOCUSABLE_TAGS = new Set([
|
|
330
|
+
'article', 'aside', 'div', 'fieldset', 'footer', 'form', 'header', 'label', 'li', 'main', 'nav', 'ol', 'p', 'section',
|
|
331
|
+
'span', 'table', 'tbody', 'td', 'th', 'thead', 'tr', 'ul',
|
|
332
|
+
])
|
|
333
|
+
const FOCUS_EVENTS = new Map([['onFocus', 'onFocusIn'], ['onBlur', 'onFocusOut']])
|
|
334
|
+
// Input types whose change event waits for the field to lose focus.
|
|
335
|
+
const TEXT_INPUT_TYPES = new Set(['text', 'search', 'email', 'url', 'tel', 'password', 'number'])
|
|
336
|
+
|
|
337
|
+
function staticAttr(attributes: readonly JSXAttributeItem[], name: string): JSXAttribute | undefined {
|
|
338
|
+
for (const a of attributes) {
|
|
339
|
+
if (a.type === 'JSXAttribute' && a.name.type === 'JSXIdentifier' && a.name.name === name)
|
|
340
|
+
return a
|
|
341
|
+
}
|
|
342
|
+
return undefined
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
function checkFocusAndChange(tag: string, attributes: readonly JSXAttributeItem[], filename: string, warnings: CompilerWarning[]): void {
|
|
346
|
+
const canFocus = !UNFOCUSABLE_TAGS.has(tag) || attributes.some(a =>
|
|
347
|
+
a.type === 'JSXSpreadAttribute'
|
|
348
|
+
|| (a.name.type === 'JSXIdentifier' && ['tabIndex', 'tabindex', 'contentEditable', 'contenteditable'].includes(a.name.name)),
|
|
349
|
+
)
|
|
350
|
+
for (const [prop, bubbling] of FOCUS_EVENTS) {
|
|
351
|
+
const attr = canFocus ? undefined : staticAttr(attributes, prop)
|
|
352
|
+
if (attr !== undefined)
|
|
353
|
+
guarded(attr.start, () => { throw mistake(`${prop} on <${tag}>`, filename, `focus does not bubble, write ${bubbling}={...}, or give the <${tag}> a tabIndex`) })
|
|
354
|
+
}
|
|
355
|
+
const onChange = staticAttr(attributes, 'onChange')
|
|
356
|
+
if (onChange === undefined)
|
|
357
|
+
return
|
|
358
|
+
const type = staticAttr(attributes, 'type')?.value
|
|
359
|
+
const isTextField = tag === 'textarea' || (tag === 'input' && (type === undefined || (type?.type === 'Literal' && typeof type.value === 'string' && TEXT_INPUT_TYPES.has(type.value))))
|
|
360
|
+
if (isTextField)
|
|
361
|
+
warnings.push({ message: `prunelle compiler: onChange on <${tag}> in ${filename} fires when the field loses focus, not per keystroke; write onInput={...} for every keystroke.`, start: onChange.start })
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
/** Throws when a JSX element would compile into something other than what its author meant, and adds to `warnings` what may be meant but usually is not. */
|
|
365
|
+
export function checkMistakes(
|
|
366
|
+
element: JSXElement,
|
|
367
|
+
filename: string,
|
|
368
|
+
code: string,
|
|
369
|
+
warnings: CompilerWarning[],
|
|
370
|
+
resolveTag: (tag: string) => string | undefined = t => (t === 'Suspense' || t === 'Region' ? t : undefined),
|
|
371
|
+
): void {
|
|
372
|
+
const tag = jsxTagName(element.openingElement.name)
|
|
373
|
+
const canonical = resolveTag(tag)
|
|
374
|
+
const isElement = tag !== '' && !isComponentTag(tag)
|
|
375
|
+
const isCustomElement = tag.includes('-')
|
|
376
|
+
if (canonical === 'Suspense') {
|
|
377
|
+
const children = filterMeaningfulChildren(element.children).length
|
|
378
|
+
if (children > 1)
|
|
379
|
+
guarded(element.start, () => { throw mistake(`<Suspense> with ${children} children`, filename, 'give it one child, and one <Suspense> per async component') })
|
|
380
|
+
}
|
|
381
|
+
const attributes = element.openingElement.attributes
|
|
382
|
+
guarded(element.start, () => checkRegionMarkup(tag, canonical, isElement, attributes, filename, element, resolveTag))
|
|
383
|
+
if (isElement)
|
|
384
|
+
guarded(element.start, () => checkKeepScroll(element, attributes, filename))
|
|
385
|
+
if (isElement && VOID_ELEMENTS.has(tag) && (filterMeaningfulChildren(element.children).length > 0 || staticAttr(attributes, 'children') !== undefined))
|
|
386
|
+
guarded(element.start, () => { throw mistake(`<${tag}> with children`, filename, `a void element has no content; write <${tag} />`) })
|
|
387
|
+
const className = isElement && staticAttr(attributes, 'class') !== undefined ? staticAttr(attributes, 'className') : undefined
|
|
388
|
+
if (className !== undefined)
|
|
389
|
+
guarded(className.start, () => { throw mistake('class and className', filename, 'keep one, they set the same attribute') })
|
|
390
|
+
const htmlFor = isElement && staticAttr(attributes, 'for') !== undefined ? staticAttr(attributes, 'htmlFor') : undefined
|
|
391
|
+
if (htmlFor !== undefined)
|
|
392
|
+
guarded(htmlFor.start, () => { throw mistake('for and htmlFor', filename, 'keep one, they set the same attribute') })
|
|
393
|
+
if (isElement)
|
|
394
|
+
checkFocusAndChange(tag, attributes, filename, warnings)
|
|
395
|
+
for (const attr of attributes) {
|
|
396
|
+
if (attr.type !== 'JSXAttribute')
|
|
397
|
+
continue
|
|
398
|
+
guarded(attr.start, () => {
|
|
399
|
+
if (attr.name.type === 'JSXNamespacedName')
|
|
400
|
+
checkNamespacedAttribute(attr.name.namespace.name, attr.name.name.name, filename)
|
|
401
|
+
else if (isElement && attr.name.name === 'innerHTML')
|
|
402
|
+
checkInnerHtml(element, tag, attr, filename, code)
|
|
403
|
+
else if (isElement)
|
|
404
|
+
checkElementAttribute(attr, tag, isCustomElement, filename, code, warnings)
|
|
405
|
+
})
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
// A literal string value of an attribute, when it has one.
|
|
410
|
+
function literalText(attr: JSXAttribute): string | undefined {
|
|
411
|
+
return attr.value?.type === 'Literal' && typeof attr.value.value === 'string' ? attr.value.value : undefined
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
// A region may hold others, each under its own name: the page tells a region from the one around it by name.
|
|
415
|
+
function checkRegionNesting(
|
|
416
|
+
element: JSXElement,
|
|
417
|
+
attributes: readonly JSXAttributeItem[],
|
|
418
|
+
filename: string,
|
|
419
|
+
resolveTag: (tag: string) => string | undefined,
|
|
420
|
+
): void {
|
|
421
|
+
const outer = staticAttr(attributes, 'name')
|
|
422
|
+
const name = outer === undefined ? undefined : literalText(outer)
|
|
423
|
+
if (name === undefined)
|
|
424
|
+
return
|
|
425
|
+
walk(element.children, (node) => {
|
|
426
|
+
if (node.type !== 'JSXElement' || resolveTag(jsxTagName(node.openingElement.name)) !== 'Region')
|
|
427
|
+
return
|
|
428
|
+
const inner = staticAttr(node.openingElement.attributes, 'name')
|
|
429
|
+
if (inner !== undefined && literalText(inner) === name)
|
|
430
|
+
throw mistake(`<Region name="${name}"> inside <Region name="${name}">`, filename, 'give the inner one its own name')
|
|
431
|
+
})
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
// The markup `regions()` from `@prunellejs/spa` reads: <Region name>, and data-pru-target, data-pru-append and data-pru-live on the elements that can use them.
|
|
435
|
+
function checkRegionMarkup(
|
|
436
|
+
tag: string,
|
|
437
|
+
canonical: string | undefined,
|
|
438
|
+
isElement: boolean,
|
|
439
|
+
attributes: readonly JSXAttributeItem[],
|
|
440
|
+
filename: string,
|
|
441
|
+
element: JSXElement,
|
|
442
|
+
resolveTag: (tag: string) => string | undefined,
|
|
443
|
+
): void {
|
|
444
|
+
if (canonical === 'Region')
|
|
445
|
+
checkRegionNesting(element, attributes, filename, resolveTag)
|
|
446
|
+
if (canonical === 'Region' && staticAttr(attributes, 'name') === undefined && !attributes.some(a => a.type === 'JSXSpreadAttribute'))
|
|
447
|
+
throw mistake('<Region> without a name', filename, 'write <Region name="pane">, the name a link names in data-pru-target')
|
|
448
|
+
if (!isElement)
|
|
449
|
+
return
|
|
450
|
+
const target = staticAttr(attributes, 'data-pru-target')
|
|
451
|
+
if (target !== undefined && tag !== 'a' && tag !== 'form')
|
|
452
|
+
throw mistake(`data-pru-target on <${tag}>`, filename, 'put it on the <a href> or the <form> that should swap the region')
|
|
453
|
+
const method = tag === 'form' && target !== undefined ? staticAttr(attributes, 'method') : undefined
|
|
454
|
+
const methodText = method === undefined ? undefined : literalText(method)
|
|
455
|
+
if (methodText !== undefined && methodText.toLowerCase() !== 'get' && staticAttr(attributes, 'data-pru-live') !== undefined)
|
|
456
|
+
throw mistake(`data-pru-live on a <form method="${methodText}">`, filename, 'a form that swaps while typing is a GET: use method="get", or drop data-pru-live')
|
|
457
|
+
if (target === undefined && staticAttr(attributes, 'data-pru-append') !== undefined)
|
|
458
|
+
throw mistake('data-pru-append without data-pru-target', filename, 'name the region the next page is appended to: data-pru-target="results"')
|
|
459
|
+
if (staticAttr(attributes, 'data-pru-live') !== undefined && (tag !== 'form' || target === undefined))
|
|
460
|
+
throw mistake('data-pru-live', filename, 'it belongs on a <form method="get" data-pru-target="..."> that swaps while typing')
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
// data-pru-keep-scroll names a panel for the script keeping its scroll offset across page loads, so its key is a literal the page can be read for, and an element inside the panel cannot take the same key.
|
|
464
|
+
function checkKeepScroll(element: JSXElement, attributes: readonly JSXAttributeItem[], filename: string): void {
|
|
465
|
+
const attr = staticAttr(attributes, 'data-pru-keep-scroll')
|
|
466
|
+
if (attr === undefined)
|
|
467
|
+
return
|
|
468
|
+
const keyOf = (a: JSXAttribute) => a.value?.type === 'JSXExpressionContainer' ? staticStringValue(a.value.expression as Node) : literalText(a)
|
|
469
|
+
const key = keyOf(attr)
|
|
470
|
+
if (key === undefined || key.trim() === '' || /["<>&]/.test(key))
|
|
471
|
+
throw mistake('data-pru-keep-scroll without a literal key', filename, 'write data-pru-keep-scroll="side": a plain string naming the panel, with no quote, < > or &')
|
|
472
|
+
walk(element.children, (node) => {
|
|
473
|
+
if (node.type !== 'JSXElement')
|
|
474
|
+
return
|
|
475
|
+
const inner = staticAttr(node.openingElement.attributes, 'data-pru-keep-scroll')
|
|
476
|
+
if (inner !== undefined && keyOf(inner) === key)
|
|
477
|
+
throw mistake(`data-pru-keep-scroll="${key}" inside data-pru-keep-scroll="${key}"`, filename, 'give each panel its own key')
|
|
478
|
+
})
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
const DIRECTIVE_FIXES: Record<string, string> = {
|
|
482
|
+
'use client': 'delete it, prunelle makes a component an island by itself when it uses state or handlers',
|
|
483
|
+
'use server': 'delete it, a server function is an action() exported from its own file',
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
/** Throws on a React or Next habit plain code carries: a 'use client' or 'use server' directive, or an effect(async ...). */
|
|
487
|
+
export function checkHabits(node: Node, isEffect: (callee: string) => boolean, filename: string): void {
|
|
488
|
+
if (node.type === 'ExpressionStatement' && 'directive' in node && typeof node.directive === 'string') {
|
|
489
|
+
const fix = DIRECTIVE_FIXES[node.directive]
|
|
490
|
+
if (fix !== undefined)
|
|
491
|
+
guarded(node.start, () => { throw mistake(`'${node.directive}'`, filename, fix) })
|
|
492
|
+
return
|
|
493
|
+
}
|
|
494
|
+
if (node.type !== 'CallExpression' || !isEffect(calleeName(node.callee)))
|
|
495
|
+
return
|
|
496
|
+
const fn = node.arguments[0]
|
|
497
|
+
if ((fn?.type === 'ArrowFunctionExpression' || fn?.type === 'FunctionExpression') && fn.async)
|
|
498
|
+
guarded(fn.start, () => { throw mistake('effect(async ...)', filename, 'effect tracks only what it reads before the first await and takes a cleanup function, not a Promise; start the async work inside a plain effect') })
|
|
499
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
// Finds the `process.env.NODE_ENV` reads of a module: `prunelle build` never sets it, so a page it prerenders reads it unset (#3681).
|
|
2
|
+
|
|
3
|
+
import type { MemberExpression, Node, Program } from 'oxc-parser'
|
|
4
|
+
import { walk } from './ast'
|
|
5
|
+
import { topLevelNames } from './browser-globals'
|
|
6
|
+
import { unwrapTsExpr } from './shared'
|
|
7
|
+
|
|
8
|
+
const MENTIONS_RE = /\bNODE_ENV\b/
|
|
9
|
+
|
|
10
|
+
function keyOf(member: MemberExpression): string | undefined {
|
|
11
|
+
if (!member.computed && member.property.type === 'Identifier')
|
|
12
|
+
return member.property.name
|
|
13
|
+
if (member.computed && member.property.type === 'Literal' && typeof member.property.value === 'string')
|
|
14
|
+
return member.property.value
|
|
15
|
+
return undefined
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
// `process.env` or `globalThis.process.env`, with `process` not bound by the module.
|
|
19
|
+
function isProcessEnv(node: Node, shadowing: ReadonlySet<string>): boolean {
|
|
20
|
+
const env = unwrapTsExpr(node)
|
|
21
|
+
if (env.type !== 'MemberExpression' || keyOf(env) !== 'env')
|
|
22
|
+
return false
|
|
23
|
+
const proc = unwrapTsExpr(env.object)
|
|
24
|
+
if (proc.type === 'Identifier')
|
|
25
|
+
return proc.name === 'process' && !shadowing.has('process')
|
|
26
|
+
if (proc.type !== 'MemberExpression' || keyOf(proc) !== 'process')
|
|
27
|
+
return false
|
|
28
|
+
const base = unwrapTsExpr(proc.object)
|
|
29
|
+
return base.type === 'Identifier' && base.name === 'globalThis' && !shadowing.has('globalThis')
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Offsets of each `process.env.NODE_ENV` read, `const { NODE_ENV } = process.env` included. */
|
|
33
|
+
export function findNodeEnvReads(program: Program, code: string): number[] {
|
|
34
|
+
if (!MENTIONS_RE.test(code))
|
|
35
|
+
return []
|
|
36
|
+
const shadowing = topLevelNames(program)
|
|
37
|
+
const reads: number[] = []
|
|
38
|
+
walk(program, (node) => {
|
|
39
|
+
if (node.type === 'MemberExpression' && keyOf(node) === 'NODE_ENV' && isProcessEnv(node.object, shadowing)) {
|
|
40
|
+
reads.push(node.start)
|
|
41
|
+
}
|
|
42
|
+
else if (node.type === 'VariableDeclarator' && node.id.type === 'ObjectPattern' && node.init !== null && isProcessEnv(node.init, shadowing)) {
|
|
43
|
+
for (const prop of node.id.properties) {
|
|
44
|
+
if (prop.type === 'Property' && !prop.computed && prop.key.type === 'Identifier' && prop.key.name === 'NODE_ENV')
|
|
45
|
+
reads.push(prop.start)
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
})
|
|
49
|
+
return reads
|
|
50
|
+
}
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
// Zero-dependency span patcher (replaces magic-string for fast TSX AST transforms).
|
|
2
|
+
|
|
3
|
+
interface Patch {
|
|
4
|
+
start: number
|
|
5
|
+
end: number
|
|
6
|
+
text: string
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
export class SourceEditor {
|
|
10
|
+
readonly #source: string
|
|
11
|
+
readonly #patches: Patch[] = []
|
|
12
|
+
readonly #prepends: string[] = []
|
|
13
|
+
readonly #appends: string[] = []
|
|
14
|
+
|
|
15
|
+
constructor(source: string) {
|
|
16
|
+
this.#source = source
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
replace(start: number, end: number, text: string): void {
|
|
20
|
+
this.#patches.push({ start, end, text })
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
remove(start: number, end: number): void {
|
|
24
|
+
this.#patches.push({ start, end, text: '' })
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
prepend(text: string): void {
|
|
28
|
+
this.#prepends.push(text)
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
append(text: string): void {
|
|
32
|
+
this.#appends.push(text)
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
toString(): string {
|
|
36
|
+
const patches = this.#patches.slice().sort((a, b) => a.start - b.start || a.end - b.end)
|
|
37
|
+
let out = this.#prepends.join('')
|
|
38
|
+
let cursor = 0
|
|
39
|
+
|
|
40
|
+
for (let i = 0; i < patches.length; i++) {
|
|
41
|
+
const p = patches[i]!
|
|
42
|
+
if (p.start < cursor)
|
|
43
|
+
throw new Error(`prunelle compiler: overlapping source patch [${p.start}, ${p.end}] overlaps previous end ${cursor}`)
|
|
44
|
+
out += this.#source.slice(cursor, p.start)
|
|
45
|
+
out += p.text
|
|
46
|
+
cursor = p.end
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
out += this.#source.slice(cursor)
|
|
50
|
+
if (this.#appends.length > 0)
|
|
51
|
+
out += this.#appends.join('')
|
|
52
|
+
return out
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
// A mark holds a source line inside generated code; `alignLines` turns it into the newlines that put the code after it back on that line.
|
|
57
|
+
const LINE_MARK_RE = /\/\*\x01(\d+)\*\//g
|
|
58
|
+
|
|
59
|
+
/** Marks the source line of an offset, for code spliced where a newline is allowed (an expression's start, never after `return`). */
|
|
60
|
+
export function lineMarker(source: string): (offset: number) => string {
|
|
61
|
+
let starts: number[] | undefined
|
|
62
|
+
return (offset) => {
|
|
63
|
+
if (starts === undefined) {
|
|
64
|
+
starts = [0]
|
|
65
|
+
for (let i = source.indexOf('\n'); i !== -1; i = source.indexOf('\n', i + 1))
|
|
66
|
+
starts.push(i + 1)
|
|
67
|
+
}
|
|
68
|
+
let lo = 0
|
|
69
|
+
let hi = starts.length - 1
|
|
70
|
+
while (lo < hi) {
|
|
71
|
+
const mid = (lo + hi + 1) >> 1
|
|
72
|
+
if (starts[mid]! <= offset)
|
|
73
|
+
lo = mid
|
|
74
|
+
else
|
|
75
|
+
hi = mid - 1
|
|
76
|
+
}
|
|
77
|
+
return `/*\x01${lo + 1}*/`
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** Replaces each line mark with the newlines that bring the code after it down to its source line, so a stack trace names the line it was written on. */
|
|
82
|
+
export function alignLines(code: string): string {
|
|
83
|
+
if (!code.includes('\x01'))
|
|
84
|
+
return code
|
|
85
|
+
let line = 1
|
|
86
|
+
let last = 0
|
|
87
|
+
return code.replace(LINE_MARK_RE, (mark: string, target: string, at: number) => {
|
|
88
|
+
for (let i = code.indexOf('\n', last); i !== -1 && i < at; i = code.indexOf('\n', i + 1))
|
|
89
|
+
line++
|
|
90
|
+
last = at + mark.length
|
|
91
|
+
const pad = Number(target) - line
|
|
92
|
+
if (pad <= 0)
|
|
93
|
+
return ''
|
|
94
|
+
line += pad
|
|
95
|
+
return '\n'.repeat(pad)
|
|
96
|
+
})
|
|
97
|
+
}
|