@gjsify/rolldown-plugin-gjsify 0.4.44 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/app/gjs.d.ts +25 -0
- package/lib/app/gjs.js +66 -31
- package/lib/app/index.d.ts +1 -1
- package/lib/app/index.js +1 -1
- package/lib/app/node.js +18 -1
- package/lib/globals.d.ts +1 -1
- package/lib/globals.js +1 -1
- package/lib/index.d.ts +2 -0
- package/lib/index.js +1 -0
- package/lib/library/index.d.ts +1 -1
- package/lib/library/index.js +1 -1
- package/lib/library/lib.d.ts +13 -0
- package/lib/library/lib.js +46 -6
- package/lib/plugins/css-as-string.js +8 -1
- package/lib/plugins/externals.d.ts +23 -0
- package/lib/plugins/externals.js +44 -0
- package/lib/utils/auto-globals.d.ts +24 -0
- package/lib/utils/auto-globals.js +92 -17
- package/lib/utils/detect-free-globals.d.ts +15 -3
- package/lib/utils/detect-free-globals.js +38 -3
- package/lib/utils/scan-globals.d.ts +28 -0
- package/lib/utils/scan-globals.js +106 -0
- package/package.json +10 -10
package/lib/app/gjs.d.ts
CHANGED
|
@@ -30,6 +30,31 @@ export interface GjsFactoryInput {
|
|
|
30
30
|
pluginOptions: PluginOptions;
|
|
31
31
|
}
|
|
32
32
|
export declare const setupForGjs: (input: GjsFactoryInput) => Promise<GjsBuildConfig>;
|
|
33
|
+
/**
|
|
34
|
+
* Build the canonical `--app gjs` externals predicate:
|
|
35
|
+
*
|
|
36
|
+
* - `@gjsify/<pkg>/register[/<feature>]` (and the bare `<pkg>/register`
|
|
37
|
+
* form) MUST NEVER be externalized — these are the side-effect entry
|
|
38
|
+
* points `--globals auto` injects to wire up
|
|
39
|
+
* `globalThis.{Buffer,fetch,…}`. GJS's native ESM loader has no
|
|
40
|
+
* node_modules walker AND does not follow `package.json#exports` maps
|
|
41
|
+
* for bare specifiers, so an externalized
|
|
42
|
+
* `import '@gjsify/buffer/register/buffer'` throws `Module not found`
|
|
43
|
+
* at runtime even when the file is on disk via the exports map.
|
|
44
|
+
* Inlining is the only safe option — the exclusion is by SHAPE
|
|
45
|
+
* (`isRegisterSubpath`), not an explicit package list, so it scales
|
|
46
|
+
* to every package added by the tree-shakeable-globals convention.
|
|
47
|
+
* It short-circuits BEFORE the user-external check so `bundler.external`
|
|
48
|
+
* can never override it. See AGENTS.md §Tree-shakeable globals.
|
|
49
|
+
* - `gi://*` URIs are external by prefix (GJS-native imports).
|
|
50
|
+
* - `cairo`/`gettext`/`system` + user externals match by exact name.
|
|
51
|
+
*
|
|
52
|
+
* Used by `setupForGjs` for the in-process alias layer AND as the
|
|
53
|
+
* predicate behind `externalsPlugin` (resolveId `{ external: true }`,
|
|
54
|
+
* honoured by both bundler engines). Exported for the regression tests
|
|
55
|
+
* in `auto-globals.spec.ts` — canonical contract, change-detector status.
|
|
56
|
+
*/
|
|
57
|
+
export declare function createGjsExternalsPredicate(userExternal?: string[]): (id: string) => boolean;
|
|
33
58
|
/**
|
|
34
59
|
* Recognize the `/register` and `/register/<feature>` subpath shapes that
|
|
35
60
|
* `--globals auto` injects into the bundle as side-effect imports.
|
package/lib/app/gjs.js
CHANGED
|
@@ -11,6 +11,7 @@
|
|
|
11
11
|
import { fileURLToPath } from 'node:url';
|
|
12
12
|
import { dirname, resolve } from 'node:path';
|
|
13
13
|
import { aliasPlugin } from '../plugins/alias.js';
|
|
14
|
+
import { externalsPlugin } from '../plugins/externals.js';
|
|
14
15
|
import { deepkitPlugin } from '@gjsify/rolldown-plugin-deepkit';
|
|
15
16
|
import blueprintPlugin from '@gjsify/vite-plugin-blueprint';
|
|
16
17
|
import { getAliasesForGjs } from '../utils/alias.js';
|
|
@@ -53,36 +54,24 @@ function resolveShim(shimName) {
|
|
|
53
54
|
}
|
|
54
55
|
export const setupForGjs = async (input) => {
|
|
55
56
|
const userExternal = input.userExternal ?? [];
|
|
56
|
-
//
|
|
57
|
-
//
|
|
58
|
-
//
|
|
59
|
-
//
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
// package list, so the invariant scales to every package added
|
|
75
|
-
// by the tree-shakeable-globals convention. See AGENTS.md
|
|
76
|
-
// §Tree-shakeable globals — /register subpath convention, and
|
|
77
|
-
// §Build — Rolldown, platform plugins for the externals policy.
|
|
78
|
-
if (isRegisterSubpath(id))
|
|
79
|
-
return false;
|
|
80
|
-
if (id.startsWith('gi://'))
|
|
81
|
-
return true;
|
|
82
|
-
if (exactExternal.includes(id))
|
|
83
|
-
return true;
|
|
84
|
-
return false;
|
|
85
|
-
};
|
|
57
|
+
// Externals policy — enforced in TWO serializable forms so it is
|
|
58
|
+
// identical under npm rolldown (Node) AND `@gjsify/rolldown-native`
|
|
59
|
+
// (the GJS-default engine, which JSON.stringify's its options to the
|
|
60
|
+
// Rust core and silently DROPS function values — the bug class that
|
|
61
|
+
// already shipped via app/node.ts and library/lib.ts predicates):
|
|
62
|
+
//
|
|
63
|
+
// 1. `options.external` = a plain string array of EXACT names
|
|
64
|
+
// (`cairo`/`gettext`/`system` + user `bundler.external` entries).
|
|
65
|
+
// Arrays serialize fine on both engines.
|
|
66
|
+
// 2. `externalsPlugin(external)` in the plugin chain for the SHAPE
|
|
67
|
+
// rules an exact array can't express (`gi://` prefix match) —
|
|
68
|
+
// a resolveId hook returning `{ external: true }` is honoured by
|
|
69
|
+
// both engines via `normalizeResolveIdResult`.
|
|
70
|
+
//
|
|
71
|
+
// `exactExternal` filters out register subpaths so a user external
|
|
72
|
+
// entry can never override the force-inline carve-out below.
|
|
73
|
+
const exactExternal = ['cairo', 'gettext', 'system', ...userExternal.filter((id) => !isRegisterSubpath(id))];
|
|
74
|
+
const external = createGjsExternalsPredicate(userExternal);
|
|
86
75
|
const format = input.pluginOptions.format ?? 'esm';
|
|
87
76
|
const exclude = input.pluginOptions.exclude ?? [];
|
|
88
77
|
const entryPoints = await globToEntryPoints(input.input, exclude);
|
|
@@ -125,7 +114,11 @@ export const setupForGjs = async (input) => {
|
|
|
125
114
|
const options = {
|
|
126
115
|
input: finalInput,
|
|
127
116
|
platform: 'neutral',
|
|
128
|
-
|
|
117
|
+
// EXACT names only — the `gi://` prefix + register-subpath shape
|
|
118
|
+
// rules live in `externalsPlugin` below (see the policy note at
|
|
119
|
+
// the top of this function). A function predicate here would be
|
|
120
|
+
// silently dropped by the native engine's JSON options boundary.
|
|
121
|
+
external: exactExternal,
|
|
129
122
|
// 'browser' field is needed so packages like create-hash, create-hmac,
|
|
130
123
|
// randombytes use their pure-JS browser entry instead of index.js
|
|
131
124
|
// (which does require('crypto') and causes circular dependencies via
|
|
@@ -200,6 +193,12 @@ export const setupForGjs = async (input) => {
|
|
|
200
193
|
...flattenAliases(aliasMap),
|
|
201
194
|
},
|
|
202
195
|
}),
|
|
196
|
+
// Enforce the full `--app gjs` externals policy (gi:// prefix,
|
|
197
|
+
// exact names, register-subpath force-inline) via resolveId —
|
|
198
|
+
// the only form BOTH engines honour (the native engine drops
|
|
199
|
+
// function `external` options at its JSON boundary). Runs after
|
|
200
|
+
// the alias plugin's `pre`-order resolveId so aliases apply first.
|
|
201
|
+
externalsPlugin(external, { name: 'gjsify-gjs-externalize' }),
|
|
203
202
|
blueprintPlugin(),
|
|
204
203
|
deepkitPlugin({ reflection: input.pluginOptions.reflection }),
|
|
205
204
|
// GTK4's CSS engine is much older than browser engines — its
|
|
@@ -313,6 +312,42 @@ function flattenAliases(map) {
|
|
|
313
312
|
}
|
|
314
313
|
return out;
|
|
315
314
|
}
|
|
315
|
+
/**
|
|
316
|
+
* Build the canonical `--app gjs` externals predicate:
|
|
317
|
+
*
|
|
318
|
+
* - `@gjsify/<pkg>/register[/<feature>]` (and the bare `<pkg>/register`
|
|
319
|
+
* form) MUST NEVER be externalized — these are the side-effect entry
|
|
320
|
+
* points `--globals auto` injects to wire up
|
|
321
|
+
* `globalThis.{Buffer,fetch,…}`. GJS's native ESM loader has no
|
|
322
|
+
* node_modules walker AND does not follow `package.json#exports` maps
|
|
323
|
+
* for bare specifiers, so an externalized
|
|
324
|
+
* `import '@gjsify/buffer/register/buffer'` throws `Module not found`
|
|
325
|
+
* at runtime even when the file is on disk via the exports map.
|
|
326
|
+
* Inlining is the only safe option — the exclusion is by SHAPE
|
|
327
|
+
* (`isRegisterSubpath`), not an explicit package list, so it scales
|
|
328
|
+
* to every package added by the tree-shakeable-globals convention.
|
|
329
|
+
* It short-circuits BEFORE the user-external check so `bundler.external`
|
|
330
|
+
* can never override it. See AGENTS.md §Tree-shakeable globals.
|
|
331
|
+
* - `gi://*` URIs are external by prefix (GJS-native imports).
|
|
332
|
+
* - `cairo`/`gettext`/`system` + user externals match by exact name.
|
|
333
|
+
*
|
|
334
|
+
* Used by `setupForGjs` for the in-process alias layer AND as the
|
|
335
|
+
* predicate behind `externalsPlugin` (resolveId `{ external: true }`,
|
|
336
|
+
* honoured by both bundler engines). Exported for the regression tests
|
|
337
|
+
* in `auto-globals.spec.ts` — canonical contract, change-detector status.
|
|
338
|
+
*/
|
|
339
|
+
export function createGjsExternalsPredicate(userExternal = []) {
|
|
340
|
+
const exact = ['cairo', 'gettext', 'system', ...userExternal];
|
|
341
|
+
return (id) => {
|
|
342
|
+
if (isRegisterSubpath(id))
|
|
343
|
+
return false;
|
|
344
|
+
if (id.startsWith('gi://'))
|
|
345
|
+
return true;
|
|
346
|
+
if (exact.includes(id))
|
|
347
|
+
return true;
|
|
348
|
+
return false;
|
|
349
|
+
};
|
|
350
|
+
}
|
|
316
351
|
/**
|
|
317
352
|
* Recognize the `/register` and `/register/<feature>` subpath shapes that
|
|
318
353
|
* `--globals auto` injects into the bundle as side-effect imports.
|
package/lib/app/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { setupForGjs, isRegisterSubpath } from './gjs.js';
|
|
1
|
+
export { setupForGjs, isRegisterSubpath, createGjsExternalsPredicate } from './gjs.js';
|
|
2
2
|
export type { GjsBuildConfig, GjsFactoryInput } from './gjs.js';
|
|
3
3
|
export { setupForNode } from './node.js';
|
|
4
4
|
export type { NodeBuildConfig, NodeFactoryInput } from './node.js';
|
package/lib/app/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { setupForGjs, isRegisterSubpath } from './gjs.js';
|
|
1
|
+
export { setupForGjs, isRegisterSubpath, createGjsExternalsPredicate } from './gjs.js';
|
|
2
2
|
export { setupForNode } from './node.js';
|
|
3
3
|
export { setupForBrowser } from './browser.js';
|
|
4
4
|
export { setupForNativescript } from './nativescript.js';
|
package/lib/app/node.js
CHANGED
|
@@ -55,7 +55,24 @@ export const setupForNode = async (input) => {
|
|
|
55
55
|
const options = {
|
|
56
56
|
input: entryPoints,
|
|
57
57
|
platform: 'node',
|
|
58
|
-
external,
|
|
58
|
+
// Pass the EXACT-MATCH external set as a plain string array, NOT the
|
|
59
|
+
// `external` predicate function. `@gjsify/rolldown-native` ships the
|
|
60
|
+
// whole options object to its Rust core via `JSON.stringify` — a
|
|
61
|
+
// function value does not survive serialization (it is silently
|
|
62
|
+
// dropped), so a function `external` is honoured under npm rolldown
|
|
63
|
+
// (Node) but IGNORED under native rolldown (GJS), leaving
|
|
64
|
+
// `node-datachannel` (and the rest of EXTERNALS_NODE) bundled. That
|
|
65
|
+
// descends into node-datachannel's `require('…/node_datachannel.node')`
|
|
66
|
+
// and fails the `--app node` build with `Module not found`. The
|
|
67
|
+
// predicate here is pure exact membership, so the array is
|
|
68
|
+
// behaviourally identical under both engines AND JSON-serializable.
|
|
69
|
+
// (The gjs target follows the same rule: exact names as an array,
|
|
70
|
+
// plus an `externalsPlugin` resolveId hook for its gi://-prefix and
|
|
71
|
+
// register-subpath shape rules — see app/gjs.ts. The browser target
|
|
72
|
+
// already uses a plain array.)
|
|
73
|
+
// The function form is still used for `getAliasesForNode({ external })`
|
|
74
|
+
// above — that runs in-process and is never serialized.
|
|
75
|
+
external: exactExternal,
|
|
59
76
|
resolve: {
|
|
60
77
|
mainFields: format === 'esm' ? ['module', 'main', 'browser'] : ['main', 'module', 'browser'],
|
|
61
78
|
// CJS-priority conditions for Node bundles. Rolldown uses the first
|
package/lib/globals.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { resolveGlobalsList, writeRegisterInjectFile } from './utils/scan-globals.js';
|
|
1
|
+
export { resolveGlobalsList, writeRegisterInjectFile, isRegisterPathResolvable, filterResolvableRegisterPaths } from './utils/scan-globals.js';
|
|
2
2
|
export { detectFreeGlobals } from './utils/detect-free-globals.js';
|
|
3
3
|
export { detectAutoGlobals } from './utils/auto-globals.js';
|
|
4
4
|
export type { AutoGlobalsResult, DetectAutoGlobalsOptions, AnalysisOptions } from './utils/auto-globals.js';
|
package/lib/globals.js
CHANGED
|
@@ -4,6 +4,6 @@
|
|
|
4
4
|
// (or auto-detect via the iterative multi-pass build) and write the inject
|
|
5
5
|
// stub that the plugin picks up via its `autoGlobalsInject` option. See the
|
|
6
6
|
// "Tree-shakeable Globals" section in AGENTS.md for the architecture.
|
|
7
|
-
export { resolveGlobalsList, writeRegisterInjectFile } from './utils/scan-globals.js';
|
|
7
|
+
export { resolveGlobalsList, writeRegisterInjectFile, isRegisterPathResolvable, filterResolvableRegisterPaths } from './utils/scan-globals.js';
|
|
8
8
|
export { detectFreeGlobals } from './utils/detect-free-globals.js';
|
|
9
9
|
export { detectAutoGlobals } from './utils/auto-globals.js';
|
package/lib/index.d.ts
CHANGED
|
@@ -12,6 +12,8 @@ export type { TextLoaderPluginOptions, LoaderKind } from './plugins/text-loader.
|
|
|
12
12
|
export { shebangPlugin, GJS_SHEBANG, NODE_SHEBANG, expandEnvTemplate, resolveShebangLine } from './plugins/shebang.js';
|
|
13
13
|
export type { ShebangPluginOptions } from './plugins/shebang.js';
|
|
14
14
|
export { gjsImportsEmptyPlugin } from './plugins/gjs-imports-empty.js';
|
|
15
|
+
export { externalsPlugin } from './plugins/externals.js';
|
|
16
|
+
export type { ExternalsPredicate, ExternalsPluginOptions } from './plugins/externals.js';
|
|
15
17
|
export { platformResolvePlugin, detectNativescriptPlatform, nativescriptPlatformDefines, } from './plugins/platform-resolve.js';
|
|
16
18
|
export type { PlatformResolvePluginOptions, NativescriptPlatform } from './plugins/platform-resolve.js';
|
|
17
19
|
export * from './plugin.js';
|
package/lib/index.js
CHANGED
|
@@ -9,6 +9,7 @@ export { cssAsStringPlugin } from './plugins/css-as-string.js';
|
|
|
9
9
|
export { textLoaderPlugin } from './plugins/text-loader.js';
|
|
10
10
|
export { shebangPlugin, GJS_SHEBANG, NODE_SHEBANG, expandEnvTemplate, resolveShebangLine } from './plugins/shebang.js';
|
|
11
11
|
export { gjsImportsEmptyPlugin } from './plugins/gjs-imports-empty.js';
|
|
12
|
+
export { externalsPlugin } from './plugins/externals.js';
|
|
12
13
|
export { platformResolvePlugin, detectNativescriptPlatform, nativescriptPlatformDefines, } from './plugins/platform-resolve.js';
|
|
13
14
|
export * from './plugin.js';
|
|
14
15
|
import { gjsifyPlugin } from './plugin.js';
|
package/lib/library/index.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export { setupLib } from './lib.js';
|
|
1
|
+
export { setupLib, isExternalSpecifier } from './lib.js';
|
|
2
2
|
export type { LibBuildConfig, LibFactoryInput } from './lib.js';
|
package/lib/library/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export { setupLib } from './lib.js';
|
|
1
|
+
export { setupLib, isExternalSpecifier } from './lib.js';
|
package/lib/library/lib.d.ts
CHANGED
|
@@ -14,3 +14,16 @@ export interface LibFactoryInput {
|
|
|
14
14
|
pluginOptions: PluginOptions;
|
|
15
15
|
}
|
|
16
16
|
export declare const setupLib: (input: LibFactoryInput) => Promise<LibBuildConfig>;
|
|
17
|
+
/**
|
|
18
|
+
* Whether a specifier should stay external in library mode: a bare /
|
|
19
|
+
* scoped / protocol specifier (`@gjsify/web-streams`, `node:fs`, `gi://Gtk`)
|
|
20
|
+
* is external; the package's own relative/absolute source modules —
|
|
21
|
+
* rolldown's `\0`-prefixed virtual modules (its runtime helper, plugin
|
|
22
|
+
* stubs) — and `data:` URI modules (inlined by definition, must never be
|
|
23
|
+
* re-emitted as a by-reference import) are bundled.
|
|
24
|
+
*
|
|
25
|
+
* Exported for the unit tests in `@gjsify/cli`'s `test:node` harness
|
|
26
|
+
* (the plugin package has no test runner of its own) — this is the
|
|
27
|
+
* canonical library-mode externals contract.
|
|
28
|
+
*/
|
|
29
|
+
export declare function isExternalSpecifier(id: string): boolean;
|
package/lib/library/lib.js
CHANGED
|
@@ -11,6 +11,7 @@
|
|
|
11
11
|
// lowering. Library output stays maximally portable.
|
|
12
12
|
import { aliasPlugin } from '../plugins/alias.js';
|
|
13
13
|
import { cssAsStringPlugin } from '../plugins/css-as-string.js';
|
|
14
|
+
import { externalsPlugin } from '../plugins/externals.js';
|
|
14
15
|
import { globToEntryPoints } from '../utils/entry-points.js';
|
|
15
16
|
export const setupLib = async (input) => {
|
|
16
17
|
// Derive output format from `library: 'esm' | 'cjs'` when the caller
|
|
@@ -34,15 +35,28 @@ export const setupLib = async (input) => {
|
|
|
34
35
|
// emitted package re-exports its dep tree by reference. Rolldown's
|
|
35
36
|
// default behaviour would inline workspace packages into the output
|
|
36
37
|
// directory; we mark anything not starting with `./` or `/` as external.
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
38
|
+
//
|
|
39
|
+
// The policy is enforced ONLY via `externalsPlugin` below — NOT via a
|
|
40
|
+
// top-level `external` function option. A function `external` is
|
|
41
|
+
// honoured by npm rolldown (Node), but `@gjsify/rolldown-native`
|
|
42
|
+
// JSON.stringify's its options to the Rust core which silently DROPS
|
|
43
|
+
// function values (same hazard commit 78a6042ac fixed for app/node.ts).
|
|
44
|
+
// Under native rolldown — the Node-free GJS build — a function predicate
|
|
45
|
+
// is ignored and every *resolvable* dep (`@gjsify/web-streams`,
|
|
46
|
+
// `@girs/*`, `@gjsify/utils`) gets INLINED into the package's own
|
|
47
|
+
// `lib/esm/` subtree. That bakes a private copy of e.g.
|
|
48
|
+
// `@gjsify/web-streams` into each consumer; a later app bundle then carries
|
|
49
|
+
// TWO web-streams copies whose module-level brand Symbols (`kState`/`kType`)
|
|
50
|
+
// differ, so a `ReadableStream` made by one copy fails the other's
|
|
51
|
+
// `isReadableStream` brand check (`transform.readable must be a
|
|
52
|
+
// ReadableStream` from `Blob.stream().pipeThrough(new DecompressionStream)`).
|
|
53
|
+
// The resolveId hook returning `{ external: true }` is honoured by BOTH
|
|
54
|
+
// engines (`normalizeResolveIdResult` forwards `external` on the native
|
|
55
|
+
// facade) — so the engine can never inline a workspace dep regardless of
|
|
56
|
+
// how it serializes options.
|
|
42
57
|
const options = {
|
|
43
58
|
input: entryPoints,
|
|
44
59
|
platform: 'neutral',
|
|
45
|
-
external,
|
|
46
60
|
resolve: {
|
|
47
61
|
mainFields: format === 'esm' ? ['module', 'main'] : ['main'],
|
|
48
62
|
conditionNames: format === 'esm' ? ['module', 'import'] : ['require'],
|
|
@@ -64,6 +78,11 @@ export const setupLib = async (input) => {
|
|
|
64
78
|
};
|
|
65
79
|
const plugins = [
|
|
66
80
|
aliasPlugin({ entries: flattenAliases(aliasMap) }),
|
|
81
|
+
// Enforce the library-mode externals policy in a form native rolldown
|
|
82
|
+
// honours (a top-level `external` function would be dropped under the
|
|
83
|
+
// Node-free GJS build — see the note above). Runs after the alias
|
|
84
|
+
// plugin's `pre`-order resolveId so user aliases still apply.
|
|
85
|
+
externalsPlugin(isExternalSpecifier, { name: 'gjsify-lib-externalize' }),
|
|
67
86
|
// Rolldown removed experimental CSS bundling — `.css` files would
|
|
68
87
|
// error at the bundler level. Library-mode packages that bundle
|
|
69
88
|
// CSS as a string (e.g. `@gjsify/adwaita-fonts/index.css`) need
|
|
@@ -74,6 +93,27 @@ export const setupLib = async (input) => {
|
|
|
74
93
|
];
|
|
75
94
|
return { options, plugins };
|
|
76
95
|
};
|
|
96
|
+
/**
|
|
97
|
+
* Whether a specifier should stay external in library mode: a bare /
|
|
98
|
+
* scoped / protocol specifier (`@gjsify/web-streams`, `node:fs`, `gi://Gtk`)
|
|
99
|
+
* is external; the package's own relative/absolute source modules —
|
|
100
|
+
* rolldown's `\0`-prefixed virtual modules (its runtime helper, plugin
|
|
101
|
+
* stubs) — and `data:` URI modules (inlined by definition, must never be
|
|
102
|
+
* re-emitted as a by-reference import) are bundled.
|
|
103
|
+
*
|
|
104
|
+
* Exported for the unit tests in `@gjsify/cli`'s `test:node` harness
|
|
105
|
+
* (the plugin package has no test runner of its own) — this is the
|
|
106
|
+
* canonical library-mode externals contract.
|
|
107
|
+
*/
|
|
108
|
+
export function isExternalSpecifier(id) {
|
|
109
|
+
if (id.startsWith('./') || id.startsWith('../') || id.startsWith('/'))
|
|
110
|
+
return false;
|
|
111
|
+
if (id.startsWith('\0'))
|
|
112
|
+
return false;
|
|
113
|
+
if (id.startsWith('data:'))
|
|
114
|
+
return false;
|
|
115
|
+
return true;
|
|
116
|
+
}
|
|
77
117
|
/**
|
|
78
118
|
* Compute the common-ancestor directory of a set of entry paths so
|
|
79
119
|
* Rolldown's `preserveModulesRoot` strips the right prefix from emitted
|
|
@@ -66,7 +66,14 @@ async function tryLoadNativeBundler() {
|
|
|
66
66
|
// optional peer dep at build time. Resolution happens only at
|
|
67
67
|
// runtime under GJS (where the prebuild is installed).
|
|
68
68
|
const specifier = '@gjsify/lightningcss-native';
|
|
69
|
-
|
|
69
|
+
// GJS's native ESM loader has NO node_modules resolver, so a BARE
|
|
70
|
+
// `import('@gjsify/lightningcss-native')` throws "Module not found"
|
|
71
|
+
// under GJS — which is exactly the runtime this native path is for.
|
|
72
|
+
// Resolve the bare specifier to a concrete file path first (anchored
|
|
73
|
+
// at the bundle's own location), then import the resulting file:// URL
|
|
74
|
+
// — mirroring how `bundler-pick.ts` loads `@gjsify/rolldown-native`.
|
|
75
|
+
const resolved = createRequire(import.meta.url).resolve(specifier);
|
|
76
|
+
const mod = (await import(/* @vite-ignore */ pathToFileURL(resolved).href));
|
|
70
77
|
if (!mod.hasNativeLightningcss())
|
|
71
78
|
return null;
|
|
72
79
|
return async (filename, targets) => {
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import type { RolldownPluginOption } from 'rolldown';
|
|
2
|
+
/** Decides whether a specifier must stay external (`true`) or flow through normal resolution (`false`). */
|
|
3
|
+
export type ExternalsPredicate = (id: string) => boolean;
|
|
4
|
+
export interface ExternalsPluginOptions {
|
|
5
|
+
/** Plugin name shown in errors/debug output. Default: `'gjsify-externalize'`. */
|
|
6
|
+
name?: string;
|
|
7
|
+
}
|
|
8
|
+
/**
|
|
9
|
+
* Externalize specifiers matching `predicate` via a `resolveId` hook —
|
|
10
|
+
* the engine-agnostic equivalent of a (native-dropped) `external`
|
|
11
|
+
* function option. Returning `{ id, external: true }` keeps the ORIGINAL
|
|
12
|
+
* specifier in the emitted module so the output re-imports the dep by
|
|
13
|
+
* reference (library mode: `preserveModules` writes
|
|
14
|
+
* `import … from '@gjsify/web-streams'` unchanged; app mode: the bundle
|
|
15
|
+
* keeps `import 'gi://Gtk?version=4.0'` for the GJS loader).
|
|
16
|
+
*
|
|
17
|
+
* Entry guard: entry modules MUST be resolved + emitted, never
|
|
18
|
+
* externalized. Rolldown's `external` OPTION skips entries implicitly,
|
|
19
|
+
* but a resolveId HOOK fires for them too — guard on the absent importer
|
|
20
|
+
* (and `isEntry`) so `src/index.ts` etc. aren't marked external (a
|
|
21
|
+
* regression there externalizes ENTRY modules and emits empty packages).
|
|
22
|
+
*/
|
|
23
|
+
export declare function externalsPlugin(predicate: ExternalsPredicate, options?: ExternalsPluginOptions): RolldownPluginOption;
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
// Engine-agnostic externals enforcement via a `resolveId` hook.
|
|
2
|
+
//
|
|
3
|
+
// Rolldown's top-level `external` option accepts a function predicate on
|
|
4
|
+
// the npm engine (Node), but `@gjsify/rolldown-native` ships its options
|
|
5
|
+
// to the Rust core via `JSON.stringify` — function values are silently
|
|
6
|
+
// DROPPED at that boundary (the Rust deserializer only accepts a
|
|
7
|
+
// `Vec<String>` of exact names). Two bugs already shipped from this class
|
|
8
|
+
// (app/node.ts predicate → node-datachannel inlined; library/lib.ts
|
|
9
|
+
// predicate → `@gjsify/web-streams` inlined per-package, breaking the
|
|
10
|
+
// ReadableStream brand check), and `--app gjs` was the third live
|
|
11
|
+
// instance.
|
|
12
|
+
//
|
|
13
|
+
// A `resolveId` hook returning `{ id, external: true }` is honoured by
|
|
14
|
+
// BOTH engines: npm rolldown natively, and the native facade via
|
|
15
|
+
// `normalizeResolveIdResult` (which forwards `external` through the B.3
|
|
16
|
+
// nested-plugin protocol). Enforcing externals policy here — instead of
|
|
17
|
+
// (or in addition to) the `external` option — makes the policy identical
|
|
18
|
+
// under npm rolldown, native rolldown, AND the `--globals auto` analysis
|
|
19
|
+
// passes (`bundleToChunks`), which compose the same plugin chain.
|
|
20
|
+
/**
|
|
21
|
+
* Externalize specifiers matching `predicate` via a `resolveId` hook —
|
|
22
|
+
* the engine-agnostic equivalent of a (native-dropped) `external`
|
|
23
|
+
* function option. Returning `{ id, external: true }` keeps the ORIGINAL
|
|
24
|
+
* specifier in the emitted module so the output re-imports the dep by
|
|
25
|
+
* reference (library mode: `preserveModules` writes
|
|
26
|
+
* `import … from '@gjsify/web-streams'` unchanged; app mode: the bundle
|
|
27
|
+
* keeps `import 'gi://Gtk?version=4.0'` for the GJS loader).
|
|
28
|
+
*
|
|
29
|
+
* Entry guard: entry modules MUST be resolved + emitted, never
|
|
30
|
+
* externalized. Rolldown's `external` OPTION skips entries implicitly,
|
|
31
|
+
* but a resolveId HOOK fires for them too — guard on the absent importer
|
|
32
|
+
* (and `isEntry`) so `src/index.ts` etc. aren't marked external (a
|
|
33
|
+
* regression there externalizes ENTRY modules and emits empty packages).
|
|
34
|
+
*/
|
|
35
|
+
export function externalsPlugin(predicate, options) {
|
|
36
|
+
return {
|
|
37
|
+
name: options?.name ?? 'gjsify-externalize',
|
|
38
|
+
resolveId(source, importer, opts) {
|
|
39
|
+
if (importer === undefined || opts?.isEntry)
|
|
40
|
+
return null;
|
|
41
|
+
return predicate(source) ? { id: source, external: true } : null;
|
|
42
|
+
},
|
|
43
|
+
};
|
|
44
|
+
}
|
|
@@ -37,6 +37,30 @@ export interface DetectAutoGlobalsOptions {
|
|
|
37
37
|
* unavailable native libraries.
|
|
38
38
|
*/
|
|
39
39
|
excludeGlobals?: string[];
|
|
40
|
+
/**
|
|
41
|
+
* Skip the committed register-globals closure-map expansion and run the
|
|
42
|
+
* pure iterative loop. Used by the closure-map GENERATOR
|
|
43
|
+
* (`packages/infra/cli/scripts/generate-register-closure.mjs`): computing
|
|
44
|
+
* a register module's closure THROUGH the committed map would re-add
|
|
45
|
+
* every identifier the OLD entry contained — removed globals could never
|
|
46
|
+
* leave the map (a ratchet, with transitive pollution into sibling
|
|
47
|
+
* entries) and `--check` would stay green on semantically stale data.
|
|
48
|
+
* Builds never set this; the expansion is exactly what makes them
|
|
49
|
+
* converge after one detection pass.
|
|
50
|
+
*/
|
|
51
|
+
disableClosureExpansion?: boolean;
|
|
52
|
+
/**
|
|
53
|
+
* Working directory of the project being built. Used to locate the
|
|
54
|
+
* project's `node_modules` when checking whether a detected global's
|
|
55
|
+
* polyfill package is actually installed.
|
|
56
|
+
*
|
|
57
|
+
* When omitted the resolvability gate is BYPASSED (every detected
|
|
58
|
+
* register path is written as-is) to preserve the original behaviour
|
|
59
|
+
* for callers that don't know the project root. The real CLI build
|
|
60
|
+
* (`actions/build.ts`) passes `process.cwd()` so the gate is active in
|
|
61
|
+
* a normal `gjsify build`.
|
|
62
|
+
*/
|
|
63
|
+
cwd?: string;
|
|
40
64
|
}
|
|
41
65
|
/**
|
|
42
66
|
* Build options accepted by the analyser. A subset of Rolldown's
|
|
@@ -37,28 +37,69 @@ const defaultBundler = async ({ rolldownInput, format }) => {
|
|
|
37
37
|
}
|
|
38
38
|
};
|
|
39
39
|
import { detectFreeGlobals } from './detect-free-globals.js';
|
|
40
|
-
import { resolveGlobalsList, writeRegisterInjectFile } from './scan-globals.js';
|
|
40
|
+
import { resolveGlobalsList, writeRegisterInjectFile, filterResolvableRegisterPaths } from './scan-globals.js';
|
|
41
41
|
import { GJS_GLOBALS_MAP } from '@gjsify/resolve-npm/globals-map';
|
|
42
|
+
import { REGISTER_GLOBALS_CLOSURE } from '@gjsify/resolve-npm/register-globals-closure';
|
|
42
43
|
const GLOBALS_MAP = GJS_GLOBALS_MAP;
|
|
44
|
+
const CLOSURE_MAP = REGISTER_GLOBALS_CLOSURE;
|
|
43
45
|
/** Maximum iterations to prevent runaway loops on pathological inputs. */
|
|
44
46
|
const MAX_ITERATIONS = 5;
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
47
|
+
/**
|
|
48
|
+
* Expand a detected-identifier set with the PRECOMPUTED transitive closure of
|
|
49
|
+
* the register modules those identifiers inject (the committed
|
|
50
|
+
* `register-globals-closure` map, generated by
|
|
51
|
+
* `packages/infra/cli/scripts/generate-register-closure.mjs`).
|
|
52
|
+
*
|
|
53
|
+
* The iterative loop's passes 2..N exist only to discover which ADDITIONAL
|
|
54
|
+
* globals the injected register modules' own code references — static,
|
|
55
|
+
* per-register information. Seeding pass 2 with the full closure makes the
|
|
56
|
+
* loop converge at the very next pass (a verification bundle), collapsing
|
|
57
|
+
* ~3-5 analysis bundles to 2 for every `--globals auto` build. A stale or
|
|
58
|
+
* missing closure entry is SAFE: the verification pass detects unexpected
|
|
59
|
+
* growth and the loop simply continues iterating (slower + a hint to
|
|
60
|
+
* regenerate).
|
|
61
|
+
*/
|
|
62
|
+
function expandWithClosure(detected, excludeSet) {
|
|
63
|
+
const out = new Set(detected);
|
|
64
|
+
const queue = [...detected];
|
|
65
|
+
while (queue.length > 0) {
|
|
66
|
+
const id = queue.pop();
|
|
67
|
+
const registerPath = GLOBALS_MAP[id];
|
|
68
|
+
if (!registerPath)
|
|
69
|
+
continue;
|
|
70
|
+
const entry = CLOSURE_MAP[registerPath];
|
|
71
|
+
if (!entry)
|
|
72
|
+
continue; // unknown register — the iterative loop covers it
|
|
73
|
+
for (const cid of entry) {
|
|
74
|
+
if (excludeSet.has(cid))
|
|
75
|
+
continue;
|
|
76
|
+
if (!GLOBALS_MAP[cid])
|
|
77
|
+
continue;
|
|
78
|
+
if (!out.has(cid)) {
|
|
79
|
+
out.add(cid);
|
|
80
|
+
queue.push(cid);
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
return out;
|
|
85
|
+
}
|
|
86
|
+
function isSubset(a, b) {
|
|
48
87
|
for (const x of a)
|
|
49
88
|
if (!b.has(x))
|
|
50
89
|
return false;
|
|
51
90
|
return true;
|
|
52
91
|
}
|
|
53
|
-
async function applyExcludeGlobals(detected, currentInject, extraRegisterPaths, excludeGlobals) {
|
|
92
|
+
async function applyExcludeGlobals(detected, currentInject, extraRegisterPaths, excludeGlobals, cwd) {
|
|
54
93
|
if (!excludeGlobals?.length)
|
|
55
94
|
return { detected, injectPath: currentInject };
|
|
56
95
|
for (const id of excludeGlobals)
|
|
57
96
|
detected.delete(id);
|
|
58
|
-
|
|
97
|
+
let filtered = detectedToRegisterPaths(detected);
|
|
59
98
|
for (const p of extraRegisterPaths)
|
|
60
99
|
filtered.add(p);
|
|
61
|
-
|
|
100
|
+
if (cwd)
|
|
101
|
+
filtered = filterResolvableRegisterPaths(filtered, cwd);
|
|
102
|
+
const injectPath = filtered.size > 0 ? ((await writeRegisterInjectFile(filtered, cwd)) ?? undefined) : undefined;
|
|
62
103
|
return { detected, injectPath };
|
|
63
104
|
}
|
|
64
105
|
function detectedToRegisterPaths(detected) {
|
|
@@ -95,10 +136,14 @@ export async function detectAutoGlobals(analysisOptions, pluginOptions, gjsifyPl
|
|
|
95
136
|
? resolveGlobalsList(options.extraGlobalsList)
|
|
96
137
|
: new Set();
|
|
97
138
|
const excludeSet = new Set(options.excludeGlobals ?? []);
|
|
139
|
+
const cwd = options.cwd;
|
|
98
140
|
let detected = new Set();
|
|
99
141
|
let currentInject = undefined;
|
|
100
142
|
if (extraRegisterPaths.size > 0) {
|
|
101
|
-
|
|
143
|
+
const resolvableExtra = cwd
|
|
144
|
+
? filterResolvableRegisterPaths(extraRegisterPaths, cwd)
|
|
145
|
+
: extraRegisterPaths;
|
|
146
|
+
currentInject = (await writeRegisterInjectFile(resolvableExtra, cwd)) ?? undefined;
|
|
102
147
|
}
|
|
103
148
|
// Caller-provided plugins (e.g. PnP relay) survive every pass; the
|
|
104
149
|
// gjsify plugin appended last so its hooks run after any custom
|
|
@@ -204,25 +249,55 @@ export async function detectAutoGlobals(analysisOptions, pluginOptions, gjsifyPl
|
|
|
204
249
|
for (const id of excludeSet)
|
|
205
250
|
newDetected.delete(id);
|
|
206
251
|
}
|
|
207
|
-
// Fixpoint check: detection is monotonic —
|
|
208
|
-
//
|
|
209
|
-
//
|
|
210
|
-
|
|
252
|
+
// Fixpoint check: detection is monotonic — injecting registers can
|
|
253
|
+
// only ADD references. The injected set (`detected`) may be a
|
|
254
|
+
// SUPERSET of what the bundle actually references (the closure-map
|
|
255
|
+
// expansion below deliberately over-approximates), so convergence is
|
|
256
|
+
// "this pass found nothing OUTSIDE the injected set", not equality.
|
|
257
|
+
if (isSubset(newDetected, detected)) {
|
|
211
258
|
if (verbose) {
|
|
212
259
|
const sorted = [...detected].sort();
|
|
213
260
|
const extras = extraRegisterPaths.size > 0 ? ` (+ ${extraRegisterPaths.size} extra register module(s))` : '';
|
|
214
261
|
console.debug(`[gjsify] --globals auto: converged after ${iteration - 1} iteration(s), ${detected.size} global(s)${sorted.length ? ': ' + sorted.join(', ') : ''}${extras}`);
|
|
215
262
|
}
|
|
216
|
-
return applyExcludeGlobals(detected, currentInject, extraRegisterPaths, options.excludeGlobals);
|
|
263
|
+
return applyExcludeGlobals(detected, currentInject, extraRegisterPaths, options.excludeGlobals, cwd);
|
|
264
|
+
}
|
|
265
|
+
// Seed the next pass with the PRECOMPUTED closure of every detected
|
|
266
|
+
// identifier's register module — the static answer to what passes
|
|
267
|
+
// 2..N of the plain loop would re-discover one bundle at a time.
|
|
268
|
+
// Union with the previously-injected set keeps growth monotonic
|
|
269
|
+
// (an over-approximated superset must never shrink, or the subset
|
|
270
|
+
// convergence check could oscillate).
|
|
271
|
+
const expanded = options.disableClosureExpansion
|
|
272
|
+
? newDetected
|
|
273
|
+
: expandWithClosure(newDetected, excludeSet);
|
|
274
|
+
if (verbose && expanded.size > newDetected.size) {
|
|
275
|
+
console.debug(`[gjsify] --globals auto: closure map expanded ${newDetected.size} → ${expanded.size} global(s)`);
|
|
276
|
+
}
|
|
277
|
+
if (iteration > 1 && verbose) {
|
|
278
|
+
// Reaching a growth pass after the closure-seeded pass means the
|
|
279
|
+
// committed closure map no longer covers a register module's
|
|
280
|
+
// references — correctness is preserved by iterating, but builds
|
|
281
|
+
// pay extra passes until the map is regenerated.
|
|
282
|
+
console.debug('[gjsify] --globals auto: detection grew past the closure-map expansion — the committed ' +
|
|
283
|
+
'register-globals-closure map looks stale. Regenerate via ' +
|
|
284
|
+
'`node packages/infra/cli/scripts/generate-register-closure.mjs`.');
|
|
217
285
|
}
|
|
218
|
-
detected =
|
|
219
|
-
|
|
286
|
+
detected = new Set([...detected, ...expanded]);
|
|
287
|
+
let registerPaths = detectedToRegisterPaths(detected);
|
|
220
288
|
for (const p of extraRegisterPaths)
|
|
221
289
|
registerPaths.add(p);
|
|
290
|
+
// Filter out register paths whose polyfill package is not installed
|
|
291
|
+
// in the project. An unresolvable import in the analysis bundle causes
|
|
292
|
+
// a hard Rolldown error — emitting it is strictly worse than skipping
|
|
293
|
+
// with a warning. The caller can add the dep or use --exclude-globals
|
|
294
|
+
// to acknowledge the gap. See AGENTS.md fix (a) rationale.
|
|
295
|
+
if (cwd)
|
|
296
|
+
registerPaths = filterResolvableRegisterPaths(registerPaths, cwd);
|
|
222
297
|
if (registerPaths.size === 0) {
|
|
223
298
|
return { detected, injectPath: undefined };
|
|
224
299
|
}
|
|
225
|
-
currentInject = (await writeRegisterInjectFile(registerPaths)) ?? undefined;
|
|
300
|
+
currentInject = (await writeRegisterInjectFile(registerPaths, cwd)) ?? undefined;
|
|
226
301
|
if (verbose) {
|
|
227
302
|
const sorted = [...detected].sort();
|
|
228
303
|
console.debug(`[gjsify] --globals auto: iteration ${iteration}, ${detected.size} global(s)${sorted.length ? ': ' + sorted.join(', ') : ''}`);
|
|
@@ -231,7 +306,7 @@ export async function detectAutoGlobals(analysisOptions, pluginOptions, gjsifyPl
|
|
|
231
306
|
if (verbose) {
|
|
232
307
|
console.debug(`[gjsify] --globals auto: hit max iterations (${MAX_ITERATIONS}), using last detected set`);
|
|
233
308
|
}
|
|
234
|
-
return applyExcludeGlobals(detected, currentInject, extraRegisterPaths, options.excludeGlobals);
|
|
309
|
+
return applyExcludeGlobals(detected, currentInject, extraRegisterPaths, options.excludeGlobals, cwd);
|
|
235
310
|
}
|
|
236
311
|
/**
|
|
237
312
|
* Append an additional entry path to a Rolldown `input` value while
|
|
@@ -11,8 +11,20 @@
|
|
|
11
11
|
* declared-names check is a safety net for edge cases where esbuild
|
|
12
12
|
* keeps the original name.
|
|
13
13
|
*
|
|
14
|
-
* `typeof X` references
|
|
15
|
-
* `typeof
|
|
16
|
-
*
|
|
14
|
+
* `typeof X` references that appear in presence-check guards
|
|
15
|
+
* (`typeof document !== 'undefined'`) and NOWHERE ELSE in the bundle are
|
|
16
|
+
* NOT counted as free-global uses. Such guards are pervasive in
|
|
17
|
+
* isomorphic npm packages that support both browser and non-browser
|
|
18
|
+
* runtimes; on GJS the guarded branch is dead but the bundler cannot DCE
|
|
19
|
+
* a `typeof` expression (its value depends on the runtime). If the same
|
|
20
|
+
* identifier also appears in a genuine reference position the injection
|
|
21
|
+
* still fires — the typeof-guard suppression only applies when the guard
|
|
22
|
+
* is the SOLE occurrence.
|
|
23
|
+
*
|
|
24
|
+
* If `typeof X` was the ONLY reference to a global AND its polyfill
|
|
25
|
+
* package is unresolvable, silently skipping avoids an unresolved-import
|
|
26
|
+
* hard error at bundle time. The resolvability gate in `auto-globals.ts`
|
|
27
|
+
* provides the second layer of protection for cases where `X` does appear
|
|
28
|
+
* in a real reference position but the package is still absent.
|
|
17
29
|
*/
|
|
18
30
|
export declare function detectFreeGlobals(code: string): Set<string>;
|
|
@@ -135,9 +135,21 @@ function extractBindingNames(node) {
|
|
|
135
135
|
* declared-names check is a safety net for edge cases where esbuild
|
|
136
136
|
* keeps the original name.
|
|
137
137
|
*
|
|
138
|
-
* `typeof X` references
|
|
139
|
-
* `typeof
|
|
140
|
-
*
|
|
138
|
+
* `typeof X` references that appear in presence-check guards
|
|
139
|
+
* (`typeof document !== 'undefined'`) and NOWHERE ELSE in the bundle are
|
|
140
|
+
* NOT counted as free-global uses. Such guards are pervasive in
|
|
141
|
+
* isomorphic npm packages that support both browser and non-browser
|
|
142
|
+
* runtimes; on GJS the guarded branch is dead but the bundler cannot DCE
|
|
143
|
+
* a `typeof` expression (its value depends on the runtime). If the same
|
|
144
|
+
* identifier also appears in a genuine reference position the injection
|
|
145
|
+
* still fires — the typeof-guard suppression only applies when the guard
|
|
146
|
+
* is the SOLE occurrence.
|
|
147
|
+
*
|
|
148
|
+
* If `typeof X` was the ONLY reference to a global AND its polyfill
|
|
149
|
+
* package is unresolvable, silently skipping avoids an unresolved-import
|
|
150
|
+
* hard error at bundle time. The resolvability gate in `auto-globals.ts`
|
|
151
|
+
* provides the second layer of protection for cases where `X` does appear
|
|
152
|
+
* in a real reference position but the package is still absent.
|
|
141
153
|
*/
|
|
142
154
|
export function detectFreeGlobals(code) {
|
|
143
155
|
const ast = acorn.parse(code, {
|
|
@@ -211,6 +223,12 @@ export function detectFreeGlobals(code) {
|
|
|
211
223
|
// all four host-object names for safety (esbuild also never renames
|
|
212
224
|
// these because they are language keywords / pre-defined globals).
|
|
213
225
|
const freeGlobals = new Set();
|
|
226
|
+
// Globals seen only inside `typeof X` expressions so far. Moved into
|
|
227
|
+
// freeGlobals the moment the same name is detected in a real-use
|
|
228
|
+
// position. Names that remain here at the end were only ever
|
|
229
|
+
// presence-checked — not genuinely used — and are excluded from the
|
|
230
|
+
// injection set (see JSDoc above).
|
|
231
|
+
const typeofGuardGlobals = new Set();
|
|
214
232
|
const HOST_OBJECTS = new Set(['globalThis', 'global', 'window', 'self', 'globalObject']);
|
|
215
233
|
walk.ancestor(ast, {
|
|
216
234
|
MemberExpression(node) {
|
|
@@ -334,7 +352,24 @@ export function detectFreeGlobals(code) {
|
|
|
334
352
|
case 'ImportDefaultSpecifier':
|
|
335
353
|
case 'ImportNamespaceSpecifier':
|
|
336
354
|
return;
|
|
355
|
+
// `typeof X` — presence-check guard. Defer: record in the
|
|
356
|
+
// typeof-guard set and only promote to freeGlobals if the
|
|
357
|
+
// same name also appears in a real-use position elsewhere
|
|
358
|
+
// in the bundle. See JSDoc on detectFreeGlobals.
|
|
359
|
+
case 'UnaryExpression': {
|
|
360
|
+
const unary = parent;
|
|
361
|
+
if (unary.operator === 'typeof') {
|
|
362
|
+
if (!freeGlobals.has(name)) {
|
|
363
|
+
typeofGuardGlobals.add(name);
|
|
364
|
+
}
|
|
365
|
+
return;
|
|
366
|
+
}
|
|
367
|
+
break;
|
|
368
|
+
}
|
|
337
369
|
}
|
|
370
|
+
// Real-use position. Promote from typeofGuardGlobals if
|
|
371
|
+
// this name was previously seen only as a typeof argument.
|
|
372
|
+
typeofGuardGlobals.delete(name);
|
|
338
373
|
freeGlobals.add(name);
|
|
339
374
|
},
|
|
340
375
|
});
|
|
@@ -18,6 +18,34 @@
|
|
|
18
18
|
* → Set { }
|
|
19
19
|
*/
|
|
20
20
|
export declare function resolveGlobalsList(globalsArg: string): Set<string>;
|
|
21
|
+
/**
|
|
22
|
+
* Return true if `registerPath`'s base package is present in the
|
|
23
|
+
* project's node_modules tree (checked by walking up from `fromDir`).
|
|
24
|
+
*
|
|
25
|
+
* Bare-specifier register paths (e.g. `fetch/register/fetch`) are first
|
|
26
|
+
* resolved to their canonical `@gjsify/` form via the alias map so the
|
|
27
|
+
* presence check searches the right `node_modules` directory.
|
|
28
|
+
*
|
|
29
|
+
* The check is a simple `package.json` existence test — the same fast
|
|
30
|
+
* approach Node's own resolver uses as the first step. We walk up the
|
|
31
|
+
* directory tree (like Node's require algorithm) so nested
|
|
32
|
+
* `node_modules` trees (e.g. workspace setups) are handled correctly.
|
|
33
|
+
*
|
|
34
|
+
* Returns false — never throws — so a missing package causes a graceful
|
|
35
|
+
* skip rather than a build crash.
|
|
36
|
+
*/
|
|
37
|
+
export declare function isRegisterPathResolvable(registerPath: string, fromDir: string): boolean;
|
|
38
|
+
/**
|
|
39
|
+
* Filter `registerPaths` to only those whose base package is resolvable
|
|
40
|
+
* from `fromDir`. Emits a `console.warn` for each skipped path —
|
|
41
|
+
* skipping silently would mask genuine missing-polyfill cases.
|
|
42
|
+
*
|
|
43
|
+
* Trade-off: if a project intentionally relies on a bundled polyfill
|
|
44
|
+
* for a global that is also referenced in a typeof-guard inside an npm
|
|
45
|
+
* dep, and that polyfill is not a direct/transitive dep, the warn makes
|
|
46
|
+
* the gap visible so the developer can add the dep explicitly.
|
|
47
|
+
*/
|
|
48
|
+
export declare function filterResolvableRegisterPaths(registerPaths: Set<string>, fromDir: string): Set<string>;
|
|
21
49
|
/**
|
|
22
50
|
* Write a stub ESM file with `import` statements for the given register
|
|
23
51
|
* paths and return its absolute path, suitable for passing to esbuild's
|
|
@@ -11,9 +11,11 @@
|
|
|
11
11
|
// (or via the default script scaffolded by `@gjsify/create-app`). See
|
|
12
12
|
// the "Tree-shakeable Globals" section in AGENTS.md for the rationale.
|
|
13
13
|
import { writeFile, mkdir } from 'node:fs/promises';
|
|
14
|
+
import { existsSync } from 'node:fs';
|
|
14
15
|
import { createHash } from 'node:crypto';
|
|
15
16
|
import { join } from 'node:path';
|
|
16
17
|
import { GJS_GLOBALS_MAP, GJS_GLOBALS_GROUPS } from '@gjsify/resolve-npm/globals-map';
|
|
18
|
+
import { ALIASES_WEB_FOR_GJS } from '@gjsify/resolve-npm';
|
|
17
19
|
const GLOBALS_MAP = GJS_GLOBALS_MAP;
|
|
18
20
|
const GLOBALS_GROUPS = GJS_GLOBALS_GROUPS;
|
|
19
21
|
/**
|
|
@@ -60,6 +62,110 @@ export function resolveGlobalsList(globalsArg) {
|
|
|
60
62
|
}
|
|
61
63
|
return result;
|
|
62
64
|
}
|
|
65
|
+
/**
|
|
66
|
+
* Extract the npm package name from a register specifier.
|
|
67
|
+
*
|
|
68
|
+
* Examples:
|
|
69
|
+
* `@gjsify/dom-elements/register/document` → `@gjsify/dom-elements`
|
|
70
|
+
* `@gjsify/fetch/register` → `@gjsify/fetch`
|
|
71
|
+
* `fetch/register` → `fetch`
|
|
72
|
+
*/
|
|
73
|
+
function packageNameFromRegisterPath(registerPath) {
|
|
74
|
+
if (registerPath.startsWith('@')) {
|
|
75
|
+
// scoped: @scope/pkg/...
|
|
76
|
+
const parts = registerPath.split('/');
|
|
77
|
+
return parts.slice(0, 2).join('/');
|
|
78
|
+
}
|
|
79
|
+
// unscoped: pkg/...
|
|
80
|
+
return registerPath.split('/')[0] ?? registerPath;
|
|
81
|
+
}
|
|
82
|
+
const ALIAS_MAP_FOR_GJS = ALIASES_WEB_FOR_GJS;
|
|
83
|
+
/**
|
|
84
|
+
* Resolve a bare-specifier register path to its canonical `@gjsify/`
|
|
85
|
+
* form using the ALIASES_WEB_FOR_GJS alias table (e.g.
|
|
86
|
+
* `fetch/register/fetch` → `@gjsify/fetch/register/fetch`).
|
|
87
|
+
*
|
|
88
|
+
* The globals-map uses bare specifiers for packages that the gjsify alias
|
|
89
|
+
* plugin rewrites at build time. For the resolvability check we need the
|
|
90
|
+
* CANONICAL package name so we look in the right `node_modules` directory.
|
|
91
|
+
* If no alias is found the original path is returned unchanged.
|
|
92
|
+
*/
|
|
93
|
+
function resolveRegisterAlias(registerPath) {
|
|
94
|
+
// Direct alias lookup first (handles full `fetch/register/fetch` etc).
|
|
95
|
+
if (ALIAS_MAP_FOR_GJS[registerPath])
|
|
96
|
+
return ALIAS_MAP_FOR_GJS[registerPath];
|
|
97
|
+
// Prefix lookup: `web-streams/register/readable` → check `web-streams` alias.
|
|
98
|
+
const pkgName = packageNameFromRegisterPath(registerPath);
|
|
99
|
+
const aliasedPkg = ALIAS_MAP_FOR_GJS[pkgName];
|
|
100
|
+
if (aliasedPkg && !registerPath.startsWith('@')) {
|
|
101
|
+
// Replace the bare-package prefix with the aliased @gjsify/ package name.
|
|
102
|
+
const tail = registerPath.slice(pkgName.length); // e.g. '/register/readable'
|
|
103
|
+
return aliasedPkg + tail;
|
|
104
|
+
}
|
|
105
|
+
return registerPath;
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* Return true if `registerPath`'s base package is present in the
|
|
109
|
+
* project's node_modules tree (checked by walking up from `fromDir`).
|
|
110
|
+
*
|
|
111
|
+
* Bare-specifier register paths (e.g. `fetch/register/fetch`) are first
|
|
112
|
+
* resolved to their canonical `@gjsify/` form via the alias map so the
|
|
113
|
+
* presence check searches the right `node_modules` directory.
|
|
114
|
+
*
|
|
115
|
+
* The check is a simple `package.json` existence test — the same fast
|
|
116
|
+
* approach Node's own resolver uses as the first step. We walk up the
|
|
117
|
+
* directory tree (like Node's require algorithm) so nested
|
|
118
|
+
* `node_modules` trees (e.g. workspace setups) are handled correctly.
|
|
119
|
+
*
|
|
120
|
+
* Returns false — never throws — so a missing package causes a graceful
|
|
121
|
+
* skip rather than a build crash.
|
|
122
|
+
*/
|
|
123
|
+
export function isRegisterPathResolvable(registerPath, fromDir) {
|
|
124
|
+
// Resolve bare-specifier aliases to @gjsify/ canonical form first.
|
|
125
|
+
const canonical = resolveRegisterAlias(registerPath);
|
|
126
|
+
const pkgName = packageNameFromRegisterPath(canonical);
|
|
127
|
+
const parts = pkgName.split('/');
|
|
128
|
+
// Walk up the directory tree mirroring Node's module-resolution
|
|
129
|
+
// algorithm: check <dir>/node_modules/<pkg>/package.json at each level.
|
|
130
|
+
let dir = fromDir;
|
|
131
|
+
const root = dir.slice(0, dir.indexOf('/') + 1) || '/';
|
|
132
|
+
while (true) {
|
|
133
|
+
const candidate = join(dir, 'node_modules', ...parts, 'package.json');
|
|
134
|
+
if (existsSync(candidate))
|
|
135
|
+
return true;
|
|
136
|
+
if (dir === root)
|
|
137
|
+
break;
|
|
138
|
+
const parent = join(dir, '..');
|
|
139
|
+
if (parent === dir)
|
|
140
|
+
break;
|
|
141
|
+
dir = parent;
|
|
142
|
+
}
|
|
143
|
+
return false;
|
|
144
|
+
}
|
|
145
|
+
/**
|
|
146
|
+
* Filter `registerPaths` to only those whose base package is resolvable
|
|
147
|
+
* from `fromDir`. Emits a `console.warn` for each skipped path —
|
|
148
|
+
* skipping silently would mask genuine missing-polyfill cases.
|
|
149
|
+
*
|
|
150
|
+
* Trade-off: if a project intentionally relies on a bundled polyfill
|
|
151
|
+
* for a global that is also referenced in a typeof-guard inside an npm
|
|
152
|
+
* dep, and that polyfill is not a direct/transitive dep, the warn makes
|
|
153
|
+
* the gap visible so the developer can add the dep explicitly.
|
|
154
|
+
*/
|
|
155
|
+
export function filterResolvableRegisterPaths(registerPaths, fromDir) {
|
|
156
|
+
const out = new Set();
|
|
157
|
+
for (const p of registerPaths) {
|
|
158
|
+
if (isRegisterPathResolvable(p, fromDir)) {
|
|
159
|
+
out.add(p);
|
|
160
|
+
}
|
|
161
|
+
else {
|
|
162
|
+
console.warn(`[gjsify] --globals auto: skipping register import '${p}' — ` +
|
|
163
|
+
`package '${packageNameFromRegisterPath(p)}' is not installed in this project. ` +
|
|
164
|
+
`If you need this global, add the package as a dependency or use --exclude-globals to suppress this warning.`);
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
return out;
|
|
168
|
+
}
|
|
63
169
|
/**
|
|
64
170
|
* Write a stub ESM file with `import` statements for the given register
|
|
65
171
|
* paths and return its absolute path, suitable for passing to esbuild's
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@gjsify/rolldown-plugin-gjsify",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.5.0",
|
|
4
4
|
"description": "Rolldown / Rollup / Vite plugin orchestrator for GJS, Node, and Browser targets",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "lib/index.js",
|
|
@@ -51,11 +51,11 @@
|
|
|
51
51
|
],
|
|
52
52
|
"license": "MIT",
|
|
53
53
|
"dependencies": {
|
|
54
|
-
"@gjsify/console": "^0.
|
|
55
|
-
"@gjsify/resolve-npm": "^0.
|
|
56
|
-
"@gjsify/rolldown-plugin-deepkit": "^0.
|
|
57
|
-
"@gjsify/rolldown-plugin-pnp": "^0.
|
|
58
|
-
"@gjsify/vite-plugin-blueprint": "^0.
|
|
54
|
+
"@gjsify/console": "^0.5.0",
|
|
55
|
+
"@gjsify/resolve-npm": "^0.5.0",
|
|
56
|
+
"@gjsify/rolldown-plugin-deepkit": "^0.5.0",
|
|
57
|
+
"@gjsify/rolldown-plugin-pnp": "^0.5.0",
|
|
58
|
+
"@gjsify/vite-plugin-blueprint": "^0.5.0",
|
|
59
59
|
"@rollup/pluginutils": "^5.4.0",
|
|
60
60
|
"acorn": "^8.16.0",
|
|
61
61
|
"acorn-walk": "^8.3.5",
|
|
@@ -63,8 +63,8 @@
|
|
|
63
63
|
"lightningcss": "^1.32.0"
|
|
64
64
|
},
|
|
65
65
|
"peerDependencies": {
|
|
66
|
-
"@gjsify/lightningcss-native": "^0.
|
|
67
|
-
"rolldown": "^1.0
|
|
66
|
+
"@gjsify/lightningcss-native": "^0.5.0",
|
|
67
|
+
"rolldown": "^1.1.0"
|
|
68
68
|
},
|
|
69
69
|
"peerDependenciesMeta": {
|
|
70
70
|
"@gjsify/lightningcss-native": {
|
|
@@ -75,8 +75,8 @@
|
|
|
75
75
|
}
|
|
76
76
|
},
|
|
77
77
|
"devDependencies": {
|
|
78
|
-
"@types/node": "^25.9.
|
|
79
|
-
"rolldown": "^1.0
|
|
78
|
+
"@types/node": "^25.9.2",
|
|
79
|
+
"rolldown": "^1.1.0",
|
|
80
80
|
"typescript": "^6.0.3"
|
|
81
81
|
}
|
|
82
82
|
}
|