prunelle 0.1.1 → 0.7.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/LICENSE +21 -0
- package/llms.txt +137 -40
- package/package.json +11 -2
- package/src/a11y/declaration.ts +373 -0
- package/src/a11y/index.ts +477 -0
- package/src/a11y/rgaa-map.ts +230 -0
- package/src/attrs.ts +11 -3
- package/src/build/bundle.ts +89 -41
- package/src/build/byte-size.ts +11 -0
- package/src/build/client-entries.ts +3 -2
- package/src/build/client-plugin.ts +11 -5
- package/src/build/client-prune.ts +56 -6
- package/src/build/compile.ts +13 -10
- package/src/build/ecoindex.ts +238 -0
- package/src/build/files.ts +15 -0
- package/src/build/first-load.ts +85 -14
- package/src/build/graph.ts +29 -39
- package/src/build/index.ts +225 -122
- package/src/build/island-promote.ts +311 -0
- package/src/build/islands.ts +14 -203
- package/src/build/manifest.ts +56 -116
- package/src/build/output.ts +3 -6
- package/src/build/plugin-host.ts +115 -41
- package/src/build/precompress.ts +16 -3
- package/src/build/prerender.ts +177 -39
- package/src/build/reach.ts +200 -0
- package/src/build/render-rules.ts +2 -2
- package/src/build/report.ts +48 -5
- package/src/build/resolve.ts +8 -6
- package/src/build/routes.ts +175 -10
- package/src/build/static-headers.ts +112 -0
- package/src/build/static.ts +139 -39
- package/src/build/status-pages.ts +127 -0
- package/src/build/style-bundles.ts +526 -0
- package/src/cli/check-forms.ts +636 -0
- package/src/cli/check-imports.ts +31 -0
- package/src/cli/check-links.ts +632 -0
- package/src/cli/check-security.ts +64 -0
- package/src/cli/check.ts +101 -26
- package/src/cli/commands.ts +120 -11
- package/src/cli/docs.ts +403 -0
- package/src/cli/inspect.ts +105 -15
- package/src/cli/mcp-tools.ts +492 -0
- package/src/cli/mcp.ts +205 -0
- package/src/cli/new.ts +16 -5
- package/src/cli/render.ts +416 -0
- package/src/cli/upgrade-names.ts +73 -13
- package/src/cli/upgrade.ts +156 -22
- package/src/compiler/analyze.ts +87 -54
- package/src/compiler/browser-globals.ts +140 -17
- package/src/compiler/cacheability-private.ts +566 -0
- package/src/compiler/cacheability.ts +335 -0
- package/src/compiler/compliance-eco.ts +71 -0
- package/src/compiler/compliance-rgaa.ts +614 -0
- package/src/compiler/compliance-urls.ts +148 -0
- package/src/compiler/compliance.ts +407 -352
- package/src/compiler/data-keys.ts +199 -192
- package/src/compiler/dev-source.ts +87 -0
- package/src/compiler/dom-attrs.ts +138 -65
- package/src/compiler/dom.ts +517 -442
- package/src/compiler/expr-context.ts +260 -81
- package/src/compiler/foreign-imports.ts +88 -0
- package/src/compiler/mistakes.ts +23 -2
- package/src/compiler/props-body.ts +60 -0
- package/src/compiler/props.ts +87 -36
- package/src/compiler/scope.ts +400 -333
- package/src/compiler/server-only.ts +190 -151
- package/src/compiler/shared.ts +42 -14
- package/src/compiler/signal-reads.ts +6 -2
- package/src/compiler/spread-handlers.ts +295 -0
- package/src/compiler/ssr-prunelle-tags.ts +27 -14
- package/src/compiler/ssr.ts +220 -89
- package/src/context.ts +34 -0
- package/src/dev/error-log.ts +177 -0
- package/src/dev/host-check.ts +32 -0
- package/src/dev/index.ts +94 -34
- package/src/dev/open-editor.ts +228 -0
- package/src/dev/protocol.ts +3 -0
- package/src/dev/reload.ts +5 -3
- package/src/dev/supervisor.ts +50 -25
- package/src/dev/watchers.ts +74 -13
- package/src/dom/action.ts +47 -21
- package/src/dom/attrs.ts +15 -3
- package/src/dom/extras.ts +57 -40
- package/src/dom/index.ts +54 -14
- package/src/dom/island.ts +102 -68
- package/src/dom/loop.ts +66 -32
- package/src/eco/declaration.ts +328 -0
- package/src/eco/index.ts +69 -0
- package/src/index.ts +2 -2
- package/src/jsx-runtime.ts +2 -2
- package/src/plugins/config.ts +18 -12
- package/src/plugins/context.ts +44 -1
- package/src/plugins/index.ts +2 -2
- package/src/plugins/load.ts +30 -10
- package/src/plugins/order.ts +38 -1
- package/src/plugins/public.ts +6 -3
- package/src/plugins/services.ts +84 -0
- package/src/plugins/types.ts +51 -2
- package/src/reactivity/graph.ts +10 -0
- package/src/reactivity/index.ts +24 -16
- package/src/reactivity/selector.ts +31 -4
- package/src/reactivity/store.ts +64 -20
- package/src/server/action-flash.ts +158 -0
- package/src/server/action-protect.ts +199 -0
- package/src/server/action-registry.ts +1 -1
- package/src/server/action.ts +188 -152
- package/src/server/app-secret.ts +63 -0
- package/src/server/assets.ts +34 -2
- package/src/server/compress.ts +96 -10
- package/src/server/consent.ts +59 -22
- package/src/server/cookies.ts +16 -2
- package/src/server/document.ts +25 -10
- package/src/server/env.ts +14 -0
- package/src/server/errors.ts +308 -65
- package/src/server/form-schema.ts +337 -0
- package/src/server/health.ts +275 -0
- package/src/server/http.ts +186 -39
- package/src/server/index.ts +272 -273
- package/src/server/loader.ts +15 -2
- package/src/server/page.ts +15 -0
- package/src/server/param-matchers.ts +112 -0
- package/src/server/plugin-host.ts +125 -88
- package/src/server/public.ts +6 -5
- package/src/server/rate-limit.ts +102 -36
- package/src/server/request-body.ts +1 -1
- package/src/server/route-cache.ts +541 -0
- package/src/server/route-table.ts +356 -11
- package/src/server/router.ts +125 -40
- package/src/server/routing.ts +112 -63
- package/src/server/sanitize-html.ts +309 -0
- package/src/server/security.ts +279 -52
- package/src/server/serve-handlers.ts +31 -7
- package/src/server/standard-schema.ts +17 -0
- package/src/server/start.ts +60 -16
- package/src/server/static-dir.ts +91 -12
- package/src/server/stream.ts +68 -27
- package/src/ssr/consent-banner.ts +58 -0
- package/src/ssr/context.ts +106 -8
- package/src/ssr/index.ts +151 -4
- package/src/ssr/navigation.ts +2 -2
- package/src/ssr/region.ts +40 -19
- package/src/style.ts +64 -1
- package/src/test/browser.ts +28 -13
- package/src/test/index.ts +97 -12
- package/src/ts-plugin/diagnostics.ts +505 -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/gitignore +5 -0
- package/templates/_shared/mcp.json +11 -0
- package/templates/_shared/src/routes/legal.tsx +15 -1
- package/templates/_shared/tsconfig.json +5 -0
- package/templates/app/.env.example +4 -0
- package/templates/app/package.json +2 -1
- package/templates/app/prunelle.config.ts +2 -0
- package/templates/app/src/auth.ts +4 -6
- package/templates/app/src/mail.ts +4 -0
- package/templates/app/src/routes/_layout.tsx +9 -1
- package/templates/app/src/routes/dashboard/index.tsx +42 -8
- package/templates/app/src/routes/login.tsx +49 -30
- package/templates/app/src/routes/privacy.tsx +25 -0
- package/templates/app/src/styles/app.css +8 -1
- package/templates/app/tests/app.test.ts +44 -3
- package/templates/blog/package.json +1 -1
- package/templates/blog/prunelle.config.ts +1 -1
- package/templates/blog/src/routes/_layout.tsx +6 -1
- package/templates/blog/src/routes/index.tsx +5 -1
- package/templates/blog/src/styles/app.css +6 -1
- package/templates/fullstack/package.json +1 -1
- package/templates/fullstack/src/components/GreetForm.tsx +2 -1
- package/templates/fullstack/src/routes/_layout.tsx +4 -0
- package/templates/fullstack/src/styles/app.css +11 -1
- package/templates/minimal/package.json +1 -1
- package/templates/minimal/src/routes/_layout.tsx +4 -0
- package/templates/minimal/src/styles/app.css +11 -1
- package/ts-plugin.cjs +4277 -0
|
@@ -5,6 +5,7 @@ import type { ModuleAnalysis } from '../compiler/analyze'
|
|
|
5
5
|
import { parseTsx } from '../compiler/analyze'
|
|
6
6
|
import { clientReach } from '../compiler/interactivity'
|
|
7
7
|
import { SourceEditor } from '../compiler/patch'
|
|
8
|
+
import { referencesAny } from '../compiler/scope'
|
|
8
9
|
import { collectPatternNames } from '../compiler/shared'
|
|
9
10
|
|
|
10
11
|
/** The top-level names the browser needs to run the islands `localNames` of a module: the bindings they reach and the imports those name. */
|
|
@@ -38,17 +39,62 @@ export function clientView(analysis: ModuleAnalysis, code: string, keep: Readonl
|
|
|
38
39
|
}
|
|
39
40
|
}
|
|
40
41
|
|
|
41
|
-
|
|
42
|
-
|
|
42
|
+
function padPreservingLines(original: string, replacement: string): string {
|
|
43
|
+
if (replacement === '')
|
|
44
|
+
return original.replace(/[^\r\n]/g, ' ')
|
|
45
|
+
const origNewlines = original.split('\n').length - 1
|
|
46
|
+
const nextNewlines = replacement.split('\n').length - 1
|
|
47
|
+
return origNewlines > nextNewlines ? `${replacement}${'\n'.repeat(origNewlines - nextNewlines)}` : replacement
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** `code` with each top-level declaration, import, re-export, and pruned-binding statement outside `keep` removed. Everything else stays. */
|
|
51
|
+
export function pruneForClient(code: string, program: Program, keep: ReadonlySet<string>, options?: { preserveLines?: boolean | undefined }): string {
|
|
43
52
|
const editor = new SourceEditor(code)
|
|
53
|
+
const preserveLines = options?.preserveLines === true
|
|
54
|
+
const prunedNames = new Set<string>()
|
|
55
|
+
const planned: { stmt: Node, text: string | undefined }[] = []
|
|
44
56
|
for (const stmt of program.body) {
|
|
45
57
|
const text = keptText(stmt, code, keep)
|
|
46
|
-
|
|
47
|
-
|
|
58
|
+
planned.push({ stmt, text })
|
|
59
|
+
collectPrunedNames(stmt, text, keep, prunedNames)
|
|
60
|
+
}
|
|
61
|
+
for (const { stmt, text } of planned) {
|
|
62
|
+
let next = text
|
|
63
|
+
if (next === undefined && prunedNames.size > 0 && (stmt.type === 'ExpressionStatement' || stmt.type === 'IfStatement') && referencesAny(stmt, prunedNames))
|
|
64
|
+
next = ''
|
|
65
|
+
if (next !== undefined)
|
|
66
|
+
editor.replace(stmt.start, stmt.end, preserveLines ? padPreservingLines(code.slice(stmt.start, stmt.end), next) : next)
|
|
48
67
|
}
|
|
49
68
|
return editor.toString()
|
|
50
69
|
}
|
|
51
70
|
|
|
71
|
+
function collectPrunedNames(stmt: Node, text: string | undefined, keep: ReadonlySet<string>, out: Set<string>): void {
|
|
72
|
+
if (stmt.type === 'ImportDeclaration') {
|
|
73
|
+
if (text === undefined || stmt.importKind === 'type')
|
|
74
|
+
return
|
|
75
|
+
for (const s of stmt.specifiers) {
|
|
76
|
+
if (!keep.has(s.local.name) && !(s.type === 'ImportSpecifier' && s.importKind === 'type'))
|
|
77
|
+
out.add(s.local.name)
|
|
78
|
+
}
|
|
79
|
+
return
|
|
80
|
+
}
|
|
81
|
+
if (text !== '')
|
|
82
|
+
return
|
|
83
|
+
if (stmt.type === 'FunctionDeclaration' || stmt.type === 'ClassDeclaration' || stmt.type === 'VariableDeclaration') {
|
|
84
|
+
for (const n of declaredNames(stmt) ?? [])
|
|
85
|
+
out.add(n)
|
|
86
|
+
}
|
|
87
|
+
else if (stmt.type === 'ExportNamedDeclaration' && stmt.declaration !== null && stmt.declaration !== undefined) {
|
|
88
|
+
for (const n of declaredNames(stmt.declaration) ?? [])
|
|
89
|
+
out.add(n)
|
|
90
|
+
}
|
|
91
|
+
else if (stmt.type === 'ExportDefaultDeclaration') {
|
|
92
|
+
const decl = stmt.declaration
|
|
93
|
+
if ((decl.type === 'FunctionDeclaration' || decl.type === 'ClassDeclaration') && decl.id !== null)
|
|
94
|
+
out.add(decl.id.name)
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
52
98
|
const nameOf = (name: ModuleExportName): string => name.type === 'Identifier' ? name.name : String(name.value)
|
|
53
99
|
|
|
54
100
|
function declaredNames(decl: Declaration): string[] | undefined {
|
|
@@ -100,13 +146,17 @@ function keptText(stmt: Node, code: string, keep: ReadonlySet<string>): string |
|
|
|
100
146
|
}
|
|
101
147
|
|
|
102
148
|
function keptImport(stmt: ImportDeclaration, code: string, keep: ReadonlySet<string>): string | undefined {
|
|
103
|
-
// A type import
|
|
104
|
-
if (stmt.importKind === 'type'
|
|
149
|
+
// A type import stays as written; a side-effect import keeps all of its zero specifiers.
|
|
150
|
+
if (stmt.importKind === 'type')
|
|
105
151
|
return undefined
|
|
106
152
|
// A type specifier is erased with the types, so it stays whatever uses it.
|
|
107
153
|
const specs = stmt.specifiers.filter(s => keep.has(s.local.name) || (s.type === 'ImportSpecifier' && s.importKind === 'type'))
|
|
108
154
|
if (specs.length === stmt.specifiers.length)
|
|
109
155
|
return undefined
|
|
156
|
+
if (specs.length === 0)
|
|
157
|
+
return ''
|
|
158
|
+
if ((stmt.attributes?.length ?? 0) > 0)
|
|
159
|
+
return undefined
|
|
110
160
|
const source = code.slice(stmt.source.start, stmt.source.end)
|
|
111
161
|
return specs.map((s) => {
|
|
112
162
|
if (s.type === 'ImportDefaultSpecifier')
|
package/src/build/compile.ts
CHANGED
|
@@ -15,20 +15,18 @@ export interface CompileExecutableOptions {
|
|
|
15
15
|
manifest: BuildManifest
|
|
16
16
|
assetPrefix: string
|
|
17
17
|
site?: string | undefined
|
|
18
|
+
defaultPort?: number | undefined
|
|
18
19
|
outfile: string
|
|
19
20
|
resolvePrunelleSpecifier: (specifier: string) => string | undefined
|
|
20
21
|
bunPlugins?: BunPlugin[] | undefined
|
|
21
22
|
}
|
|
22
23
|
|
|
23
24
|
export async function compileExecutable(opts: CompileExecutableOptions): Promise<void> {
|
|
24
|
-
const { root, outDir, clientDir, manifest, assetPrefix, site, outfile, resolvePrunelleSpecifier, bunPlugins = [] } = opts
|
|
25
|
+
const { root, outDir, clientDir, manifest, assetPrefix, site, defaultPort, outfile, resolvePrunelleSpecifier, bunPlugins = [] } = opts
|
|
25
26
|
const entryPath = join(outDir, '__compile_entry.ts')
|
|
26
|
-
const prodEnvPath = join(outDir, '__compile_prod_env.ts')
|
|
27
|
-
// Evaluated first via ESM static import order so `prunelle.config.ts` and route modules see NODE_ENV=production!
|
|
28
|
-
writeFileSync(prodEnvPath, `const _envKey = 'NODE_ENV';\nprocess.env[_envKey] ??= 'production';\n`)
|
|
29
27
|
const entryJs = join(outDir, 'server', SERVER_ENTRY_FILE)
|
|
30
28
|
const lifecycle = join(import.meta.dir, '../server/lifecycle.ts')
|
|
31
|
-
const imports: string[] = [
|
|
29
|
+
const imports: string[] = []
|
|
32
30
|
|
|
33
31
|
// Embed client assets, public files and prerendered pages natively via `with { type: "file" }` (0 base64, 0 startup decode!), each with the sidecars the build compressed it into.
|
|
34
32
|
let fileIdx = 0
|
|
@@ -72,8 +70,16 @@ export async function compileExecutable(opts: CompileExecutableOptions): Promise
|
|
|
72
70
|
}
|
|
73
71
|
|
|
74
72
|
const siteProp = site !== undefined ? ` site: ${JSON.stringify(site)},` : ''
|
|
73
|
+
const healthPath = `${assetPrefix.replace(/\/$/, '')}/health`
|
|
75
74
|
const code = [
|
|
76
75
|
...imports,
|
|
76
|
+
`const hostname = process.env.HOST || undefined;`,
|
|
77
|
+
`const formatHost = (h: string) => h.includes(':') && !h.startsWith('[') ? \`[\${h}]\` : h;`,
|
|
78
|
+
`if (Bun.argv.includes('--health')) { const healthPort = Number(process.env.PORT || ${JSON.stringify(defaultPort ?? 3000)}); const rawHost = !hostname || hostname === '0.0.0.0' || hostname === '::' ? '127.0.0.1' : hostname; const r = await fetch(\`http://\${formatHost(rawHost)}:\${healthPort}\${${JSON.stringify(healthPath)}}\`).catch(() => null); process.exit(r && r.ok ? 0 : 1); }`,
|
|
79
|
+
`const _envKey = 'NODE_ENV';`,
|
|
80
|
+
`process.env[_envKey] ??= 'production';`,
|
|
81
|
+
`const { createApp, prunelleConfig } = await import(${JSON.stringify(entryJs)});`,
|
|
82
|
+
`const { handleSignals } = await import(${JSON.stringify(lifecycle)});`,
|
|
77
83
|
`const manifest = ${JSON.stringify(manifest)};`,
|
|
78
84
|
`const assets = { ${embeddedAssets.join(', ')} };`,
|
|
79
85
|
`const publicAssets = { ${embeddedPublic.join(', ')} };`,
|
|
@@ -81,9 +87,6 @@ export async function compileExecutable(opts: CompileExecutableOptions): Promise
|
|
|
81
87
|
`const prerenderedFiles = { ${embeddedPrerenderedFiles.join(', ')} };`,
|
|
82
88
|
`const prerenderedEtags = { ${embeddedPrerenderedEtags.join(', ')} };`,
|
|
83
89
|
`const port = Number(process.env.PORT || prunelleConfig.port || 3000);`,
|
|
84
|
-
`const hostname = process.env.HOST || undefined;`,
|
|
85
|
-
`const formatHost = (h: string) => h.includes(':') && !h.startsWith('[') ? \`[\${h}]\` : h;`,
|
|
86
|
-
`if (Bun.argv.includes('--health')) { const rawHost = !hostname || hostname === '0.0.0.0' || hostname === '::' ? '127.0.0.1' : hostname; const r = await fetch(\`http://\${formatHost(rawHost)}:\${port}/\`).catch(() => null); process.exit(r && r.status < 500 ? 0 : 1); }`,
|
|
87
90
|
`const app = await createApp({ assetPrefix: ${JSON.stringify(assetPrefix)},${siteProp} manifest, assets, publicAssets, publicEtags, prerenderedFiles, prerenderedEtags });`,
|
|
88
91
|
`const server = app.serve(port, hostname);`,
|
|
89
92
|
`handleSignals(app, server);`,
|
|
@@ -105,7 +108,8 @@ export async function compileExecutable(opts: CompileExecutableOptions): Promise
|
|
|
105
108
|
try {
|
|
106
109
|
res = await Bun.build({
|
|
107
110
|
entrypoints: [entryPath],
|
|
108
|
-
|
|
111
|
+
// The host passes the environment: a .env or bunfig.toml (with its preload) in whatever cwd the binary starts in is not the app's.
|
|
112
|
+
compile: { outfile, autoloadDotenv: false, autoloadBunfig: false },
|
|
109
113
|
minify: true,
|
|
110
114
|
plugins: [prunelleResolvePlugin, ...bunPlugins],
|
|
111
115
|
})
|
|
@@ -122,6 +126,5 @@ export async function compileExecutable(opts: CompileExecutableOptions): Promise
|
|
|
122
126
|
}
|
|
123
127
|
finally {
|
|
124
128
|
rmSync(entryPath, { force: true })
|
|
125
|
-
rmSync(prodEnvPath, { force: true })
|
|
126
129
|
}
|
|
127
130
|
}
|
|
@@ -0,0 +1,238 @@
|
|
|
1
|
+
// GreenIT EcoIndex score, grade (A–G), GHG emissions and water footprint for prerendered pages.
|
|
2
|
+
|
|
3
|
+
import type { Locate } from './first-load'
|
|
4
|
+
import type { RouteManifestEntry } from './manifest'
|
|
5
|
+
import { existsSync, readFileSync, statSync } from 'node:fs'
|
|
6
|
+
import { extname, join } from 'node:path'
|
|
7
|
+
import { firstLoadUrls, measureFirstLoad } from './first-load'
|
|
8
|
+
import { appBrotliCacheDir, brotliSync } from './precompress'
|
|
9
|
+
|
|
10
|
+
export type EcoIndexGrade = 'A' | 'B' | 'C' | 'D' | 'E' | 'F' | 'G'
|
|
11
|
+
|
|
12
|
+
export interface EcoIndexInputs {
|
|
13
|
+
dom: number
|
|
14
|
+
requests: number
|
|
15
|
+
weightBytes: number
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export interface RouteEcoIndex {
|
|
19
|
+
grade: EcoIndexGrade
|
|
20
|
+
score: number
|
|
21
|
+
dom: number
|
|
22
|
+
requests: number
|
|
23
|
+
weightBytes: number
|
|
24
|
+
ghgGrams: number
|
|
25
|
+
waterCl: number
|
|
26
|
+
/** Third-party requests, counted in `requests` but not in `weightBytes`. */
|
|
27
|
+
external?: number | undefined
|
|
28
|
+
url?: string | undefined
|
|
29
|
+
/** Heaviest prerendered URL when a sibling page weighs more than the lowest-EcoIndex page. */
|
|
30
|
+
heaviest?: { bytes: number, url: string } | undefined
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
// The EcoIndex as computed by its reference implementation, cnumr/ecoindex_python at 8833bb3 (components/ecoindex/compute/ecoindex.py, data/quantiles.py, data/grades.py): 20-quantile tables of DOM elements, HTTP requests and transfer size in KB of 1000.
|
|
34
|
+
const QUANTILES_DOM = [
|
|
35
|
+
0, 47, 75, 159, 233, 298, 358, 417, 476, 537, 603,
|
|
36
|
+
674, 753, 843, 949, 1076, 1237, 1459, 1801, 2479, 594601,
|
|
37
|
+
] as const
|
|
38
|
+
|
|
39
|
+
const QUANTILES_REQ = [
|
|
40
|
+
0, 2, 15, 25, 34, 42, 49, 56, 63, 70, 78,
|
|
41
|
+
86, 95, 105, 117, 130, 147, 170, 205, 281, 3920,
|
|
42
|
+
] as const
|
|
43
|
+
|
|
44
|
+
const QUANTILES_SIZE = [
|
|
45
|
+
0, 1.37, 144.7, 319.53, 479.46, 631.97, 783.38, 937.91, 1098.62, 1265.47, 1448.32,
|
|
46
|
+
1648.27, 1876.08, 2142.06, 2465.37, 2866.31, 3401.59, 4155.73, 5400.08, 8037.54, 223212.26,
|
|
47
|
+
] as const
|
|
48
|
+
|
|
49
|
+
const RAW_CLOSE_RE: Record<string, RegExp> = {
|
|
50
|
+
script: /<\/script(?:\s[^>]*)?>/gi,
|
|
51
|
+
style: /<\/style(?:\s[^>]*)?>/gi,
|
|
52
|
+
textarea: /<\/textarea(?:\s[^>]*)?>/gi,
|
|
53
|
+
title: /<\/title(?:\s[^>]*)?>/gi,
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
const isAsciiAlpha = (c: number): boolean => (c >= 65 && c <= 90) || (c >= 97 && c <= 122)
|
|
57
|
+
|
|
58
|
+
const isTagNameChar = (c: number): boolean =>
|
|
59
|
+
isAsciiAlpha(c) || (c >= 48 && c <= 57) || c === 45 || c === 95 || c === 58 || c === 46
|
|
60
|
+
|
|
61
|
+
const isTagDelimiter = (c: number): boolean =>
|
|
62
|
+
c === 62 || c === 47 || c === 32 || c === 9 || c === 10 || c === 13 || c === 12
|
|
63
|
+
|
|
64
|
+
function findTagEnd(html: string, start: number): number {
|
|
65
|
+
let quote = 0
|
|
66
|
+
for (let i = start; i < html.length; i++) {
|
|
67
|
+
const c = html.charCodeAt(i)
|
|
68
|
+
if (quote !== 0) {
|
|
69
|
+
if (c === quote)
|
|
70
|
+
quote = 0
|
|
71
|
+
}
|
|
72
|
+
else if (c === 34 || c === 39) {
|
|
73
|
+
quote = c
|
|
74
|
+
}
|
|
75
|
+
else if (c === 62) {
|
|
76
|
+
return i
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
return -1
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function skipBangConstruct(html: string, lt: number): number {
|
|
83
|
+
if (html.startsWith('<!--', lt)) {
|
|
84
|
+
const end = html.indexOf('-->', lt + 4)
|
|
85
|
+
return end === -1 ? html.length : end + 3
|
|
86
|
+
}
|
|
87
|
+
if (html.startsWith('<![CDATA[', lt)) {
|
|
88
|
+
const end = html.indexOf(']]>', lt + 9)
|
|
89
|
+
return end === -1 ? html.length : end + 3
|
|
90
|
+
}
|
|
91
|
+
const end = html.indexOf('>', lt + 2)
|
|
92
|
+
return end === -1 ? html.length : end + 1
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** Counts HTML element nodes by scanning opening tags, ignoring DOCTYPE, comments, closing tags and raw text inside script/style/textarea/title. */
|
|
96
|
+
export function countDomElements(html: string): number {
|
|
97
|
+
let count = 0
|
|
98
|
+
let i = 0
|
|
99
|
+
const len = html.length
|
|
100
|
+
while (i < len) {
|
|
101
|
+
const lt = html.indexOf('<', i)
|
|
102
|
+
if (lt === -1)
|
|
103
|
+
break
|
|
104
|
+
const next = html.charCodeAt(lt + 1)
|
|
105
|
+
if (next === 33) {
|
|
106
|
+
i = skipBangConstruct(html, lt)
|
|
107
|
+
continue
|
|
108
|
+
}
|
|
109
|
+
if (next === 47 || next === 63) {
|
|
110
|
+
const end = html.indexOf('>', lt + 2)
|
|
111
|
+
i = end === -1 ? len : end + 1
|
|
112
|
+
continue
|
|
113
|
+
}
|
|
114
|
+
if (!isAsciiAlpha(next)) {
|
|
115
|
+
i = lt + 1
|
|
116
|
+
continue
|
|
117
|
+
}
|
|
118
|
+
let nameEnd = lt + 2
|
|
119
|
+
while (nameEnd < len && isTagNameChar(html.charCodeAt(nameEnd)))
|
|
120
|
+
nameEnd++
|
|
121
|
+
if (nameEnd >= len || !isTagDelimiter(html.charCodeAt(nameEnd))) {
|
|
122
|
+
i = lt + 1
|
|
123
|
+
continue
|
|
124
|
+
}
|
|
125
|
+
const tagEnd = findTagEnd(html, nameEnd)
|
|
126
|
+
if (tagEnd === -1)
|
|
127
|
+
break
|
|
128
|
+
count++
|
|
129
|
+
i = tagEnd + 1
|
|
130
|
+
const closeRe = RAW_CLOSE_RE[html.slice(lt + 1, nameEnd).toLowerCase()]
|
|
131
|
+
if (closeRe !== undefined) {
|
|
132
|
+
closeRe.lastIndex = i
|
|
133
|
+
const match = closeRe.exec(html)
|
|
134
|
+
i = match === null ? len : closeRe.lastIndex
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
return count
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
function computeQuantile(quantiles: readonly number[], value: number): number {
|
|
141
|
+
if (value <= quantiles[0]!)
|
|
142
|
+
return 0
|
|
143
|
+
for (let i = 1; i < quantiles.length; i++) {
|
|
144
|
+
const hi = quantiles[i]!
|
|
145
|
+
if (value < hi) {
|
|
146
|
+
const lo = quantiles[i - 1]!
|
|
147
|
+
return (i - 1) + (value - lo) / (hi - lo)
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
return quantiles.length - 1
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
function gradeForScore(score: number): EcoIndexGrade {
|
|
154
|
+
if (score > 80)
|
|
155
|
+
return 'A'
|
|
156
|
+
if (score > 70)
|
|
157
|
+
return 'B'
|
|
158
|
+
if (score > 55)
|
|
159
|
+
return 'C'
|
|
160
|
+
if (score > 40)
|
|
161
|
+
return 'D'
|
|
162
|
+
if (score > 25)
|
|
163
|
+
return 'E'
|
|
164
|
+
if (score > 10)
|
|
165
|
+
return 'F'
|
|
166
|
+
return 'G'
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/** Computes the GreenIT EcoIndex score (0–100), grade (A–G), GHG emissions (gCO2e) and water consumption (cl) per view. */
|
|
170
|
+
export function computeEcoIndex(inputs: EcoIndexInputs): Omit<RouteEcoIndex, 'url'> {
|
|
171
|
+
const dom = Math.max(0, inputs.dom)
|
|
172
|
+
const requests = Math.max(0, inputs.requests)
|
|
173
|
+
const weightBytes = Math.max(0, inputs.weightBytes)
|
|
174
|
+
const qDom = computeQuantile(QUANTILES_DOM, dom)
|
|
175
|
+
const qReq = computeQuantile(QUANTILES_REQ, requests)
|
|
176
|
+
const qSize = computeQuantile(QUANTILES_SIZE, weightBytes / 1000)
|
|
177
|
+
const raw = 100 - (5 * (3 * qDom + 2 * qReq + qSize)) / 6
|
|
178
|
+
const score = Math.round(Math.min(100, Math.max(0, raw)))
|
|
179
|
+
const ghgGrams = Math.round((2 + (2 * (50 - score)) / 100) * 100) / 100
|
|
180
|
+
const waterCl = Math.round((3 + (3 * (50 - score)) / 100) * 100) / 100
|
|
181
|
+
return { grade: gradeForScore(score), score, dom, requests, weightBytes, ghgGrams, waterCl }
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
function htmlServedSize(abs: string, raw: Uint8Array): number {
|
|
185
|
+
const sidecar = `${abs}.br`
|
|
186
|
+
if (existsSync(sidecar))
|
|
187
|
+
return statSync(sidecar).size
|
|
188
|
+
const packed = brotliSync(raw, appBrotliCacheDir()).byteLength
|
|
189
|
+
return Math.min(packed, raw.byteLength)
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
function isWorse(candidate: Omit<RouteEcoIndex, 'url'>, current: Omit<RouteEcoIndex, 'url'>): boolean {
|
|
193
|
+
if (candidate.score !== current.score)
|
|
194
|
+
return candidate.score < current.score
|
|
195
|
+
if (candidate.weightBytes !== current.weightBytes)
|
|
196
|
+
return candidate.weightBytes > current.weightBytes
|
|
197
|
+
return candidate.dom > current.dom
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/** Measures EcoIndex across a route's prerendered HTML files, returning the worst (lowest) score for multi-URL routes. */
|
|
201
|
+
export function measureRouteEcoIndex(route: RouteManifestEntry, options: { prerenderBaseDir: string, locate: Locate }): RouteEcoIndex | undefined {
|
|
202
|
+
if (route.prerendered === undefined)
|
|
203
|
+
return undefined
|
|
204
|
+
const entries = Object.entries(route.prerendered).sort(([a], [b]) => a.localeCompare(b))
|
|
205
|
+
let worst: Omit<RouteEcoIndex, 'url' | 'heaviest'> | undefined
|
|
206
|
+
let worstUrl: string | undefined
|
|
207
|
+
let heaviest: { bytes: number, url: string } | undefined
|
|
208
|
+
let measured = 0
|
|
209
|
+
|
|
210
|
+
for (const [url, relFile] of entries) {
|
|
211
|
+
const abs = join(options.prerenderBaseDir, relFile)
|
|
212
|
+
const ext = extname(abs).toLowerCase()
|
|
213
|
+
if ((ext !== '.html' && ext !== '.htm') || !existsSync(abs))
|
|
214
|
+
continue
|
|
215
|
+
const raw = readFileSync(abs)
|
|
216
|
+
const html = raw.toString('utf8')
|
|
217
|
+
const htmlBytes = htmlServedSize(abs, raw)
|
|
218
|
+
const load = measureFirstLoad(firstLoadUrls(html), options.locate, htmlBytes)
|
|
219
|
+
const eco = {
|
|
220
|
+
...computeEcoIndex({ dom: countDomElements(html), requests: 1 + load.files + load.external, weightBytes: load.total }),
|
|
221
|
+
...(load.external > 0 ? { external: load.external } : {}),
|
|
222
|
+
}
|
|
223
|
+
measured++
|
|
224
|
+
if (worst === undefined || isWorse(eco, worst)) {
|
|
225
|
+
worst = eco
|
|
226
|
+
worstUrl = url
|
|
227
|
+
}
|
|
228
|
+
if (heaviest === undefined || load.total > heaviest.bytes)
|
|
229
|
+
heaviest = { bytes: load.total, url }
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
if (worst === undefined || worstUrl === undefined)
|
|
233
|
+
return undefined
|
|
234
|
+
const result: RouteEcoIndex = measured > 1 || worstUrl !== route.path ? { ...worst, url: worstUrl } : { ...worst }
|
|
235
|
+
if (heaviest !== undefined && heaviest.bytes > worst.weightBytes)
|
|
236
|
+
result.heaviest = heaviest
|
|
237
|
+
return result
|
|
238
|
+
}
|
package/src/build/files.ts
CHANGED
|
@@ -89,6 +89,12 @@ export function assertSafeOutDir(root: string, outDir: string, routesDir: string
|
|
|
89
89
|
if (dirname(realOut) === realOut || isInside(realOut, realRoot, { orSame: true })) {
|
|
90
90
|
throw new Error(`prunelle build: refusing unsafe outDir "${outDir}" — resolved target "${realOut}" is or contains project root "${realRoot}".`)
|
|
91
91
|
}
|
|
92
|
+
if (existsSync(publicDir)) {
|
|
93
|
+
const realPublic = realpathSync(publicDir)
|
|
94
|
+
if (isInside(realPublic, realOut, { orSame: true })) {
|
|
95
|
+
throw new Error(`prunelle build: refusing unsafe outDir "${outDir}" — resolved target "${realOut}" is inside publicDir ("${realPublic}"), which would publish the server bundle: set outDir outside public/ (e.g. "dist").`)
|
|
96
|
+
}
|
|
97
|
+
}
|
|
92
98
|
}
|
|
93
99
|
catch (err) {
|
|
94
100
|
if (err instanceof Error && err.message.startsWith('prunelle build: refusing unsafe outDir'))
|
|
@@ -107,6 +113,9 @@ export function assertSafeOutDir(root: string, outDir: string, routesDir: string
|
|
|
107
113
|
throw new Error(`prunelle build: refusing unsafe outDir "${outDir}" — it equals or contains protected path ${label} ("${target}").`)
|
|
108
114
|
}
|
|
109
115
|
}
|
|
116
|
+
if (isInside(publicDir, outDir)) {
|
|
117
|
+
throw new Error(`prunelle build: refusing unsafe outDir "${outDir}" — it sits inside publicDir ("${publicDir}"), which would publish the server bundle as public files: set outDir outside public/ (e.g. "dist").`)
|
|
118
|
+
}
|
|
110
119
|
// If outDir is outside root (e.g. an external temp build dir), refuse it if it looks like another project directory.
|
|
111
120
|
if (!isInside(root, outDir) && existsSync(outDir)) {
|
|
112
121
|
for (const marker of ['package.json', 'prunelle.config.ts', 'src']) {
|
|
@@ -154,3 +163,9 @@ export function formatBunBuildLogs(logs: readonly unknown[], root?: string): str
|
|
|
154
163
|
return msg
|
|
155
164
|
}).join('\n')
|
|
156
165
|
}
|
|
166
|
+
|
|
167
|
+
/** Whether a `public/` path holds a dotfile or dot folder (`.env`, `.DS_Store`, `.git/`) other than under `.well-known`: the build leaves those out. */
|
|
168
|
+
export function isHiddenPublicPath(rel: string): boolean {
|
|
169
|
+
const segments = rel.split(/[\\/]/).filter(s => s !== '')
|
|
170
|
+
return segments.some((s, i) => s.startsWith('.') && !(i === 0 && s === '.well-known'))
|
|
171
|
+
}
|
package/src/build/first-load.ts
CHANGED
|
@@ -1,23 +1,27 @@
|
|
|
1
|
-
// What a
|
|
1
|
+
// What a visit scrolled to the bottom downloads, as served (the EcoIndex measures so): the page, the files it links, and the files those pull in (a script's static imports, a stylesheet's `url()`s), each counted once. The docs footer and `prunelle build --analyze` both measure with this.
|
|
2
2
|
|
|
3
3
|
import { existsSync, readFileSync, statSync } from 'node:fs'
|
|
4
4
|
import { extname, join, posix } from 'node:path'
|
|
5
|
-
import { appBrotliCacheDir, brotliSync } from './precompress'
|
|
5
|
+
import { appBrotliCacheDir, brotliSync, COMPRESSIBLE_EXTS } from './precompress'
|
|
6
6
|
|
|
7
7
|
// A static `import ... from "./x.js"` or `import "./x.js"` of an emitted chunk; `import("./x.js")` stays lazy and is left out.
|
|
8
8
|
export const STATIC_CHUNK_IMPORT_RE = /\b(?:import|export)\s*(?:[^"'();]*?\bfrom\s*)?["'](\.\.?\/[^"']+\.js)["']/g
|
|
9
9
|
|
|
10
|
-
const TAG_RE = /<(img|script|link)\b[^>]*>/g
|
|
10
|
+
const TAG_RE = /<(\/?)(img|script|link|source|picture|video|audio|iframe)\b[^>]*>/g
|
|
11
11
|
const SRC_RE = /\bsrc="([^"]+)"/
|
|
12
|
+
const SRCSET_RE = /\bsrcset="([^"]+)"/
|
|
13
|
+
const POSTER_RE = /\bposter="([^"]+)"/
|
|
12
14
|
const HREF_RE = /\bhref="([^"]+)"/
|
|
13
15
|
const REL_RE = /\brel="([^"]+)"/
|
|
14
16
|
const TYPE_RE = /\btype="([^"]+)"/
|
|
15
|
-
const
|
|
17
|
+
const AUTOPLAY_RE = /\bautoplay\b/
|
|
18
|
+
const PRELOAD_AUTO_RE = /\bpreload(?:="auto"|="")?(?=[\s/>])/
|
|
19
|
+
const SRCSET_WIDTH_RE = /\s(\d+(?:\.\d+)?)[wx]$/
|
|
20
|
+
const THIRD_PARTY_RE = /^(?:https?:)?\/\//i
|
|
16
21
|
const FONT_FACE_RE = /@font-face\s*\{[^}]*\}/g
|
|
17
22
|
const CSS_URL_RE = /url\(\s*(["']?)([^)"']+)\1\s*\)/g
|
|
18
23
|
const CSS_IMPORT_RE = /@import\s+(?:url\(\s*)?["']([^"']+)["']/g
|
|
19
24
|
const FETCHED_RELS = new Set(['stylesheet', 'modulepreload', 'preload'])
|
|
20
|
-
const COMPRESSED_EXTS = new Set(['.html', '.js', '.mjs', '.css', '.svg', '.xml', '.json', '.txt', '.webmanifest'])
|
|
21
25
|
const FONT_EXTS = new Set(['.woff2', '.woff', '.ttf', '.otf'])
|
|
22
26
|
const IMAGE_EXTS = new Set(['.png', '.jpg', '.jpeg', '.gif', '.webp', '.avif', '.svg', '.ico'])
|
|
23
27
|
const SKIPPED_URL_RE = /^(?:[a-z][a-z0-9+.-]*:|\/\/|#)/i
|
|
@@ -35,17 +39,80 @@ export interface FirstLoad {
|
|
|
35
39
|
cached: number
|
|
36
40
|
/** Files counted besides the page. */
|
|
37
41
|
files: number
|
|
42
|
+
/** Third-party URLs the page fetches: requests whose size the build cannot know. */
|
|
43
|
+
external: number
|
|
38
44
|
}
|
|
39
45
|
|
|
40
46
|
/** Turns a URL the page links into the file that serves it, or `undefined` when no file does. */
|
|
41
47
|
export type Locate = (url: string) => string | undefined
|
|
42
48
|
|
|
43
|
-
/** The
|
|
49
|
+
/** The widest candidate of a `srcset`: the EcoIndex measures at 1920x1080, where a browser takes the large one. */
|
|
50
|
+
function widestCandidate(srcset: string): string | undefined {
|
|
51
|
+
let best: string | undefined
|
|
52
|
+
let bestSize = -1
|
|
53
|
+
for (const candidate of srcset.split(',')) {
|
|
54
|
+
const text = candidate.trim()
|
|
55
|
+
const size = Number(SRCSET_WIDTH_RE.exec(text)?.[1] ?? 1)
|
|
56
|
+
if (text !== '' && size > bestSize) {
|
|
57
|
+
best = text.split(/\s/)[0]
|
|
58
|
+
bestSize = size
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
return best
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
const imageUrl = (element: string): string | undefined => {
|
|
65
|
+
const srcset = SRCSET_RE.exec(element)?.[1]
|
|
66
|
+
return (srcset === undefined ? undefined : widestCandidate(srcset)) ?? SRC_RE.exec(element)?.[1]
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** The URLs a browser fetches from this markup once scrolled to the bottom, as the EcoIndex measures: stylesheets, preloads, scripts, one icon, every image (a `<picture>`'s first source, a `srcset`'s widest candidate), frames, posters, and the media that autoplays or preloads. */
|
|
44
70
|
export function firstLoadUrls(html: string): string[] {
|
|
45
71
|
const urls = new Set<string>()
|
|
46
72
|
const icons: string[] = []
|
|
47
73
|
let svgIcon: string | undefined
|
|
48
|
-
|
|
74
|
+
// Inside a <picture>, or a <video>/<audio> that fetches its media: whether the source a browser takes was found.
|
|
75
|
+
let picture: { taken: boolean } | undefined
|
|
76
|
+
let media: { fetches: boolean, taken: boolean } | undefined
|
|
77
|
+
const add = (url: string | undefined): void => {
|
|
78
|
+
if (url !== undefined)
|
|
79
|
+
urls.add(url)
|
|
80
|
+
}
|
|
81
|
+
for (const [element, closing, name] of html.matchAll(TAG_RE)) {
|
|
82
|
+
if (closing === '/') {
|
|
83
|
+
if (name === 'picture')
|
|
84
|
+
picture = undefined
|
|
85
|
+
else if (name === 'video' || name === 'audio')
|
|
86
|
+
media = undefined
|
|
87
|
+
continue
|
|
88
|
+
}
|
|
89
|
+
if (name === 'picture') {
|
|
90
|
+
picture = { taken: false }
|
|
91
|
+
continue
|
|
92
|
+
}
|
|
93
|
+
if (name === 'video' || name === 'audio') {
|
|
94
|
+
const fetches = AUTOPLAY_RE.test(element) || PRELOAD_AUTO_RE.test(element)
|
|
95
|
+
add(POSTER_RE.exec(element)?.[1])
|
|
96
|
+
const src = SRC_RE.exec(element)?.[1]
|
|
97
|
+
media = { fetches, taken: src !== undefined }
|
|
98
|
+
if (fetches)
|
|
99
|
+
add(src)
|
|
100
|
+
continue
|
|
101
|
+
}
|
|
102
|
+
if (name === 'source') {
|
|
103
|
+
const slot = media ?? picture
|
|
104
|
+
if (slot === undefined || slot.taken)
|
|
105
|
+
continue
|
|
106
|
+
slot.taken = true
|
|
107
|
+
if (media === undefined || media.fetches)
|
|
108
|
+
add(media === undefined ? imageUrl(element) : SRC_RE.exec(element)?.[1])
|
|
109
|
+
continue
|
|
110
|
+
}
|
|
111
|
+
if (name === 'img') {
|
|
112
|
+
if (picture?.taken !== true)
|
|
113
|
+
add(imageUrl(element))
|
|
114
|
+
continue
|
|
115
|
+
}
|
|
49
116
|
if (name === 'link') {
|
|
50
117
|
const url = HREF_RE.exec(element)?.[1]
|
|
51
118
|
const relation = REL_RE.exec(element)?.[1] ?? ''
|
|
@@ -60,9 +127,7 @@ export function firstLoadUrls(html: string): string[] {
|
|
|
60
127
|
}
|
|
61
128
|
continue
|
|
62
129
|
}
|
|
63
|
-
|
|
64
|
-
if (url !== undefined && !LAZY_RE.test(element))
|
|
65
|
-
urls.add(url)
|
|
130
|
+
add(SRC_RE.exec(element)?.[1])
|
|
66
131
|
}
|
|
67
132
|
// A browser that draws SVG icons fetches that one alone; the others are for browsers that do not.
|
|
68
133
|
for (const icon of svgIcon === undefined ? icons : [svgIcon])
|
|
@@ -93,7 +158,7 @@ function servedSize(file: string): number {
|
|
|
93
158
|
if (existsSync(sidecar))
|
|
94
159
|
return statSync(sidecar).size
|
|
95
160
|
const raw = readFileSync(file)
|
|
96
|
-
if (!
|
|
161
|
+
if (!COMPRESSIBLE_EXTS.has(extname(file).toLowerCase()))
|
|
97
162
|
return raw.byteLength
|
|
98
163
|
const key = `${file}:${raw.byteLength}`
|
|
99
164
|
let packed = brotliCache.get(key)
|
|
@@ -117,7 +182,7 @@ function cssUrls(css: string): string[] {
|
|
|
117
182
|
urls.push(match[2]!)
|
|
118
183
|
for (const match of rest.matchAll(CSS_IMPORT_RE))
|
|
119
184
|
urls.push(match[1]!)
|
|
120
|
-
return urls.filter(url => !SKIPPED_URL_RE.test(url))
|
|
185
|
+
return urls.filter(url => THIRD_PARTY_RE.test(url) || !SKIPPED_URL_RE.test(url))
|
|
121
186
|
}
|
|
122
187
|
|
|
123
188
|
/** What a file pulls in beside itself: a script's static imports and a stylesheet's `url()`s, as URLs. */
|
|
@@ -128,16 +193,22 @@ function dependenciesOf(url: string, file: string): string[] {
|
|
|
128
193
|
const text = readFileSync(file, 'utf8')
|
|
129
194
|
const base = posix.dirname(url.split(/[?#]/)[0]!)
|
|
130
195
|
const raw = ext === '.js' ? [...text.matchAll(STATIC_CHUNK_IMPORT_RE)].map(m => m[1]!) : cssUrls(text)
|
|
131
|
-
return raw.map(dep => (dep.startsWith('/') ? dep : posix.join(base, dep)))
|
|
196
|
+
return raw.map(dep => (dep.startsWith('/') || THIRD_PARTY_RE.test(dep) ? dep : posix.join(base, dep)))
|
|
132
197
|
}
|
|
133
198
|
|
|
134
199
|
/** Adds up what a first visit fetches from these root URLs and what they pull in; `htmlBytes` is the page itself, brotli; `cacheable` names the URLs served for long caching (prunelle's hashed assets). */
|
|
135
200
|
export function measureFirstLoad(roots: Iterable<string>, locate: Locate, htmlBytes = 0, cacheable: (url: string) => boolean = () => false): FirstLoad {
|
|
136
|
-
const result: FirstLoad = { html: htmlBytes, css: 0, js: 0, fonts: 0, images: 0, other: 0, total: htmlBytes, cached: 0, files: 0 }
|
|
201
|
+
const result: FirstLoad = { html: htmlBytes, css: 0, js: 0, fonts: 0, images: 0, other: 0, total: htmlBytes, cached: 0, files: 0, external: 0 }
|
|
137
202
|
const seen = new Set<string>()
|
|
138
203
|
const stack = [...roots]
|
|
139
204
|
while (stack.length > 0) {
|
|
140
205
|
const url = stack.pop()!
|
|
206
|
+
if (THIRD_PARTY_RE.test(url)) {
|
|
207
|
+
if (!seen.has(url))
|
|
208
|
+
result.external++
|
|
209
|
+
seen.add(url)
|
|
210
|
+
continue
|
|
211
|
+
}
|
|
141
212
|
const file = locate(url)
|
|
142
213
|
if (file === undefined || seen.has(file))
|
|
143
214
|
continue
|