@gjsify/rolldown-plugin-gjsify 0.3.14

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.
Files changed (89) hide show
  1. package/lib/app/browser.d.ts +17 -0
  2. package/lib/app/browser.js +77 -0
  3. package/lib/app/gjs.d.ts +27 -0
  4. package/lib/app/gjs.js +211 -0
  5. package/lib/app/index.d.ts +6 -0
  6. package/lib/app/index.js +3 -0
  7. package/lib/app/node.d.ts +17 -0
  8. package/lib/app/node.js +102 -0
  9. package/lib/globals.d.ts +4 -0
  10. package/lib/globals.js +9 -0
  11. package/lib/index.d.ts +17 -0
  12. package/lib/index.js +15 -0
  13. package/lib/library/index.d.ts +2 -0
  14. package/lib/library/index.js +1 -0
  15. package/lib/library/lib.d.ts +16 -0
  16. package/lib/library/lib.js +118 -0
  17. package/lib/plugin.d.ts +25 -0
  18. package/lib/plugin.js +67 -0
  19. package/lib/plugins/alias.d.ts +5 -0
  20. package/lib/plugins/alias.js +45 -0
  21. package/lib/plugins/css-as-string.d.ts +2 -0
  22. package/lib/plugins/css-as-string.js +34 -0
  23. package/lib/plugins/gjs-imports-empty.d.ts +2 -0
  24. package/lib/plugins/gjs-imports-empty.js +26 -0
  25. package/lib/plugins/process-stub.d.ts +28 -0
  26. package/lib/plugins/process-stub.js +60 -0
  27. package/lib/plugins/rewrite-node-modules-paths.d.ts +38 -0
  28. package/lib/plugins/rewrite-node-modules-paths.js +132 -0
  29. package/lib/plugins/shebang.d.ts +8 -0
  30. package/lib/plugins/shebang.js +26 -0
  31. package/lib/shims/console-gjs.d.ts +24 -0
  32. package/lib/shims/console-gjs.js +24 -0
  33. package/lib/types/app.d.ts +1 -0
  34. package/lib/types/app.js +1 -0
  35. package/lib/types/index.d.ts +3 -0
  36. package/lib/types/index.js +3 -0
  37. package/lib/types/plugin-options.d.ts +46 -0
  38. package/lib/types/plugin-options.js +1 -0
  39. package/lib/types/resolve-alias-options.d.ts +2 -0
  40. package/lib/types/resolve-alias-options.js +1 -0
  41. package/lib/utils/alias.d.ts +12 -0
  42. package/lib/utils/alias.js +29 -0
  43. package/lib/utils/auto-globals.d.ts +72 -0
  44. package/lib/utils/auto-globals.js +193 -0
  45. package/lib/utils/detect-free-globals.d.ts +18 -0
  46. package/lib/utils/detect-free-globals.js +268 -0
  47. package/lib/utils/entry-points.d.ts +2 -0
  48. package/lib/utils/entry-points.js +38 -0
  49. package/lib/utils/extension.d.ts +1 -0
  50. package/lib/utils/extension.js +7 -0
  51. package/lib/utils/index.d.ts +7 -0
  52. package/lib/utils/index.js +7 -0
  53. package/lib/utils/inline-static-reads.d.ts +11 -0
  54. package/lib/utils/inline-static-reads.js +549 -0
  55. package/lib/utils/merge.d.ts +2 -0
  56. package/lib/utils/merge.js +23 -0
  57. package/lib/utils/scan-globals.d.ts +32 -0
  58. package/lib/utils/scan-globals.js +85 -0
  59. package/package.json +68 -0
  60. package/src/app/browser.ts +102 -0
  61. package/src/app/gjs.ts +260 -0
  62. package/src/app/index.ts +6 -0
  63. package/src/app/node.ts +128 -0
  64. package/src/globals.ts +11 -0
  65. package/src/index.ts +32 -0
  66. package/src/library/index.ts +2 -0
  67. package/src/library/lib.ts +142 -0
  68. package/src/plugin.ts +91 -0
  69. package/src/plugins/alias.ts +53 -0
  70. package/src/plugins/css-as-string.ts +37 -0
  71. package/src/plugins/gjs-imports-empty.ts +29 -0
  72. package/src/plugins/process-stub.ts +91 -0
  73. package/src/plugins/rewrite-node-modules-paths.ts +169 -0
  74. package/src/plugins/shebang.ts +33 -0
  75. package/src/shims/console-gjs.ts +25 -0
  76. package/src/types/app.ts +1 -0
  77. package/src/types/index.ts +3 -0
  78. package/src/types/plugin-options.ts +48 -0
  79. package/src/types/resolve-alias-options.ts +1 -0
  80. package/src/utils/alias.ts +46 -0
  81. package/src/utils/auto-globals.ts +283 -0
  82. package/src/utils/detect-free-globals.ts +278 -0
  83. package/src/utils/entry-points.ts +48 -0
  84. package/src/utils/extension.ts +7 -0
  85. package/src/utils/index.ts +7 -0
  86. package/src/utils/inline-static-reads.ts +541 -0
  87. package/src/utils/merge.ts +22 -0
  88. package/src/utils/scan-globals.ts +91 -0
  89. package/tsconfig.json +16 -0
@@ -0,0 +1,29 @@
1
+ import { EXTERNALS_NODE, EXTERNALS_NPM, ALIASES_GENERAL_FOR_GJS, ALIASES_NODE_FOR_GJS, ALIASES_WEB_FOR_GJS, ALIASES_GENERAL_FOR_NODE, ALIASES_GJS_FOR_NODE, ALIASES_WEB_FOR_NODE } from "@gjsify/resolve-npm";
2
+ export const setNodeAliasPrefix = (ALIASES) => {
3
+ // Also resolve alias names with `node:${ALIAS}`
4
+ for (const ALIAS in ALIASES) {
5
+ if (ALIAS.startsWith('node:')) {
6
+ continue;
7
+ }
8
+ const key = `node:${ALIAS}`;
9
+ if (!ALIASES[key])
10
+ ALIASES[key] = ALIASES[ALIAS];
11
+ }
12
+ return ALIASES;
13
+ };
14
+ const getAliasesGeneralForGjs = (options) => ALIASES_GENERAL_FOR_GJS;
15
+ const getAliasesNodeForGjs = (options) => setNodeAliasPrefix(ALIASES_NODE_FOR_GJS);
16
+ const getAliasesWebForGjs = (options) => ALIASES_WEB_FOR_GJS;
17
+ const getAliasesGeneralForNode = (options) => ALIASES_GENERAL_FOR_NODE;
18
+ const getAliasesGjsForNode = (options) => ALIASES_GJS_FOR_NODE;
19
+ const getAliasesWebForNode = (options) => ALIASES_WEB_FOR_NODE;
20
+ export const getAliasesForGjs = (options) => {
21
+ return { ...getAliasesGeneralForGjs(options), ...getAliasesNodeForGjs(options), ...getAliasesWebForGjs(options) };
22
+ };
23
+ export const getAliasesForNode = (options) => {
24
+ return { ...getAliasesGeneralForNode(options), ...getAliasesGjsForNode(options), ...getAliasesWebForNode(options) };
25
+ };
26
+ /** Array of Node.js build in module names (also with node: prefix) */
27
+ export const externalNode = [...EXTERNALS_NODE, ...EXTERNALS_NODE.map(E => `node:${E}`)];
28
+ /** Array of NPM module names for which we have our own implementation */
29
+ export const externalNPM = [...EXTERNALS_NPM];
@@ -0,0 +1,72 @@
1
+ import { type InputOptions, type RolldownPluginOption, type TransformOptions } from 'rolldown';
2
+ import type { PluginOptions } from '../types/plugin-options.js';
3
+ export interface AutoGlobalsResult {
4
+ /** Global identifiers detected in the bundle */
5
+ detected: Set<string>;
6
+ /** Path to the generated inject stub, or undefined if no globals needed */
7
+ injectPath: string | undefined;
8
+ }
9
+ export interface DetectAutoGlobalsOptions {
10
+ /**
11
+ * Extra explicit identifiers (or group aliases like `dom`/`web`/`node`)
12
+ * that should always be injected, in addition to whatever the iterative
13
+ * detection finds. Used by `--globals auto,<extras>` for cases where
14
+ * the detector cannot statically see a global because it's accessed via
15
+ * indirection (e.g. Excalibur's `BrowserComponent.nativeComponent.matchMedia`).
16
+ */
17
+ extraGlobalsList?: string;
18
+ /**
19
+ * Identifiers to remove from the auto-detected set before writing the
20
+ * inject stub. Useful for globals that appear as false positives from
21
+ * dead browser-compat code in npm dependencies whose polyfills require
22
+ * unavailable native libraries.
23
+ */
24
+ excludeGlobals?: string[];
25
+ }
26
+ /**
27
+ * Build options accepted by the analyser. A subset of Rolldown's
28
+ * `InputOptions` plus the `output` shape used by `RolldownBuild.generate`.
29
+ *
30
+ * The caller passes the same input + output options it would use for the
31
+ * final build (input, plugins, external, define, …). We strip output-side
32
+ * fields that would force a write-to-disk and replace them with in-memory
33
+ * settings.
34
+ */
35
+ export interface AnalysisOptions {
36
+ input: InputOptions['input'];
37
+ plugins?: RolldownPluginOption[];
38
+ external?: InputOptions['external'];
39
+ resolve?: InputOptions['resolve'];
40
+ /**
41
+ * Pass-through to Rolldown's `transform` (Oxc-driven) — `define`,
42
+ * `dropLabels`, `treeShake`, etc. live here in Rolldown's shape.
43
+ */
44
+ transform?: TransformOptions;
45
+ /** Format for the analysis bundle output. Use 'esm' to match the final build. */
46
+ format?: 'esm' | 'cjs' | 'iife';
47
+ }
48
+ /**
49
+ * Build a `gjsifyPlugin` for the analyser to insert into the plugin array.
50
+ * Late-imported via dynamic `await import()` to break the cyclic dep
51
+ * between this file and `../plugin.ts`.
52
+ */
53
+ type GjsifyPluginFactory = (options: PluginOptions) => RolldownPluginOption | Promise<RolldownPluginOption>;
54
+ /**
55
+ * Run an iterative Rolldown build (in-memory) with acorn-based global
56
+ * detection. Each pass uses the globals discovered by the previous pass,
57
+ * stopping once the detected set is stable (fixpoint reached).
58
+ *
59
+ * Returns the inject stub path that the caller should pass to the
60
+ * final (real) build via `pluginOptions.autoGlobalsInject`.
61
+ *
62
+ * @param analysisOptions Rolldown input options for the in-memory build.
63
+ * @param pluginOptions Gjsify plugin options (without `autoGlobalsInject`,
64
+ * which this function computes).
65
+ * @param gjsifyPluginFactory Factory returning the gjsify plugin instance
66
+ * for a given set of plugin options. Provided by the caller to avoid a
67
+ * cyclic import between this module and `../plugin.ts`.
68
+ * @param verbose Emit per-iteration debug output to console.
69
+ * @param options Optional `extraGlobalsList` / `excludeGlobals`.
70
+ */
71
+ export declare function detectAutoGlobals(analysisOptions: AnalysisOptions, pluginOptions: Omit<PluginOptions, 'autoGlobalsInject'>, gjsifyPluginFactory: GjsifyPluginFactory, verbose?: boolean, options?: DetectAutoGlobalsOptions): Promise<AutoGlobalsResult>;
72
+ export {};
@@ -0,0 +1,193 @@
1
+ // Iterative multi-pass build orchestrator for `--globals auto`.
2
+ //
3
+ // Architecturally identical to the esbuild predecessor — only the inner
4
+ // build call swaps `esbuild.build()` for `rolldown()`. The "after
5
+ // tree-shaking" analysis property is bundler-agnostic and load-bearing
6
+ // per AGENTS.md "Tree-shakeability invariants — permanent". See the
7
+ // rationale block at the top of `detect-free-globals.ts`.
8
+ //
9
+ // Pass 1: rolldown() with no globals injection
10
+ // → in-memory bundle parsed by acorn for free globals
11
+ // Pass 2: rolldown() with detected globals injected
12
+ // → some injected register modules pull in MORE code that
13
+ // references additional globals (tree-shaking dependency cycle)
14
+ // Pass N: repeat until the detected set converges (typically 2–3 iterations,
15
+ // capped at MAX_ITERATIONS=5)
16
+ //
17
+ // We deliberately do NOT minify the analysis builds: minification can
18
+ // alias `globalThis` to a short variable and defeat MemberExpression
19
+ // detection in detect-free-globals.ts.
20
+ import { rolldown } from 'rolldown';
21
+ import { detectFreeGlobals } from './detect-free-globals.js';
22
+ import { resolveGlobalsList, writeRegisterInjectFile } from './scan-globals.js';
23
+ import { GJS_GLOBALS_MAP } from '@gjsify/resolve-npm/globals-map';
24
+ const GLOBALS_MAP = GJS_GLOBALS_MAP;
25
+ /** Maximum iterations to prevent runaway loops on pathological inputs. */
26
+ const MAX_ITERATIONS = 5;
27
+ function setsEqual(a, b) {
28
+ if (a.size !== b.size)
29
+ return false;
30
+ for (const x of a)
31
+ if (!b.has(x))
32
+ return false;
33
+ return true;
34
+ }
35
+ async function applyExcludeGlobals(detected, currentInject, extraRegisterPaths, excludeGlobals) {
36
+ if (!excludeGlobals?.length)
37
+ return { detected, injectPath: currentInject };
38
+ for (const id of excludeGlobals)
39
+ detected.delete(id);
40
+ const filtered = detectedToRegisterPaths(detected);
41
+ for (const p of extraRegisterPaths)
42
+ filtered.add(p);
43
+ const injectPath = filtered.size > 0 ? (await writeRegisterInjectFile(filtered)) ?? undefined : undefined;
44
+ return { detected, injectPath };
45
+ }
46
+ function detectedToRegisterPaths(detected) {
47
+ const paths = new Set();
48
+ for (const name of detected) {
49
+ const path = GLOBALS_MAP[name];
50
+ if (path)
51
+ paths.add(path);
52
+ }
53
+ return paths;
54
+ }
55
+ /**
56
+ * Run an iterative Rolldown build (in-memory) with acorn-based global
57
+ * detection. Each pass uses the globals discovered by the previous pass,
58
+ * stopping once the detected set is stable (fixpoint reached).
59
+ *
60
+ * Returns the inject stub path that the caller should pass to the
61
+ * final (real) build via `pluginOptions.autoGlobalsInject`.
62
+ *
63
+ * @param analysisOptions Rolldown input options for the in-memory build.
64
+ * @param pluginOptions Gjsify plugin options (without `autoGlobalsInject`,
65
+ * which this function computes).
66
+ * @param gjsifyPluginFactory Factory returning the gjsify plugin instance
67
+ * for a given set of plugin options. Provided by the caller to avoid a
68
+ * cyclic import between this module and `../plugin.ts`.
69
+ * @param verbose Emit per-iteration debug output to console.
70
+ * @param options Optional `extraGlobalsList` / `excludeGlobals`.
71
+ */
72
+ export async function detectAutoGlobals(analysisOptions, pluginOptions, gjsifyPluginFactory, verbose, options = {}) {
73
+ const extraRegisterPaths = options.extraGlobalsList
74
+ ? resolveGlobalsList(options.extraGlobalsList)
75
+ : new Set();
76
+ const excludeSet = new Set(options.excludeGlobals ?? []);
77
+ let detected = new Set();
78
+ let currentInject = undefined;
79
+ if (extraRegisterPaths.size > 0) {
80
+ currentInject = (await writeRegisterInjectFile(extraRegisterPaths)) ?? undefined;
81
+ }
82
+ // Caller-provided plugins (e.g. PnP relay) survive every pass; the
83
+ // gjsify plugin appended last so its hooks run after any custom
84
+ // resolvers / loaders.
85
+ const callerPlugins = (analysisOptions.plugins ?? []).filter((p) => {
86
+ const name = p && typeof p === 'object' && 'name' in p ? p.name : undefined;
87
+ return name !== 'gjsify' && name !== 'gjsify-orchestrator';
88
+ });
89
+ for (let iteration = 1; iteration <= MAX_ITERATIONS; iteration++) {
90
+ const gjsifyInstance = await gjsifyPluginFactory({
91
+ ...pluginOptions,
92
+ autoGlobalsInject: currentInject,
93
+ });
94
+ // The auto-globals inject stub is a side-effect-only ESM file that
95
+ // imports `<pkg>/register/<feature>` paths. Rolldown's `transform.inject`
96
+ // is the source-AST per-identifier rewrite we MUST NOT use (see
97
+ // AGENTS.md "Tree-shakeability invariants"). Instead, when the
98
+ // analyser has produced an inject path, append it as an additional
99
+ // entry — Rolldown bundles its side effects into the output and the
100
+ // detector sees the resulting identifier references.
101
+ const inputWithInject = currentInject
102
+ ? appendInjectAsEntry(analysisOptions.input, currentInject)
103
+ : analysisOptions.input;
104
+ const build = await rolldown({
105
+ input: inputWithInject,
106
+ external: analysisOptions.external,
107
+ resolve: analysisOptions.resolve,
108
+ transform: analysisOptions.transform,
109
+ plugins: [...callerPlugins, gjsifyInstance],
110
+ logLevel: 'silent',
111
+ });
112
+ const chunkCodes = [];
113
+ try {
114
+ const result = await build.generate({
115
+ format: analysisOptions.format ?? 'esm',
116
+ minify: false,
117
+ sourcemap: false,
118
+ });
119
+ for (const entry of result.output) {
120
+ if (entry.type === 'chunk')
121
+ chunkCodes.push(entry.code);
122
+ }
123
+ }
124
+ finally {
125
+ await build.close();
126
+ }
127
+ if (chunkCodes.length === 0) {
128
+ return { detected: new Set(), injectPath: currentInject };
129
+ }
130
+ // Parse each chunk independently and union the detected sets.
131
+ // Rolldown emits one chunk per entry — concatenating them would
132
+ // produce a syntactically invalid combined program (duplicate
133
+ // top-level declarations: `File`, `Buffer`, …) that acorn can't
134
+ // parse. Per-chunk parsing keeps each chunk's lexical scope intact.
135
+ const newDetected = new Set();
136
+ for (const code of chunkCodes) {
137
+ for (const id of detectFreeGlobals(code))
138
+ newDetected.add(id);
139
+ }
140
+ // Apply excludeGlobals BEFORE writing the next iteration's inject file.
141
+ // Otherwise an excluded identifier would still appear in the inject
142
+ // import list and the analysis build itself would fail when the
143
+ // corresponding `@gjsify/<pkg>/register/<feature>` is not in the
144
+ // project's resolvable dep tree.
145
+ if (excludeSet.size > 0) {
146
+ for (const id of excludeSet)
147
+ newDetected.delete(id);
148
+ }
149
+ // Fixpoint check: detection is monotonic — once a global is needed,
150
+ // more code gets pulled in by the next pass, which can only ADD
151
+ // requirements. So a set that didn't grow is a converged set.
152
+ if (setsEqual(detected, newDetected)) {
153
+ if (verbose) {
154
+ const sorted = [...detected].sort();
155
+ const extras = extraRegisterPaths.size > 0 ? ` (+ ${extraRegisterPaths.size} extra register module(s))` : '';
156
+ console.debug(`[gjsify] --globals auto: converged after ${iteration - 1} iteration(s), ${detected.size} global(s)${sorted.length ? ': ' + sorted.join(', ') : ''}${extras}`);
157
+ }
158
+ return applyExcludeGlobals(detected, currentInject, extraRegisterPaths, options.excludeGlobals);
159
+ }
160
+ detected = newDetected;
161
+ const registerPaths = detectedToRegisterPaths(detected);
162
+ for (const p of extraRegisterPaths)
163
+ registerPaths.add(p);
164
+ if (registerPaths.size === 0) {
165
+ return { detected, injectPath: undefined };
166
+ }
167
+ currentInject = (await writeRegisterInjectFile(registerPaths)) ?? undefined;
168
+ if (verbose) {
169
+ const sorted = [...detected].sort();
170
+ console.debug(`[gjsify] --globals auto: iteration ${iteration}, ${detected.size} global(s)${sorted.length ? ': ' + sorted.join(', ') : ''}`);
171
+ }
172
+ }
173
+ if (verbose) {
174
+ console.debug(`[gjsify] --globals auto: hit max iterations (${MAX_ITERATIONS}), using last detected set`);
175
+ }
176
+ return applyExcludeGlobals(detected, currentInject, extraRegisterPaths, options.excludeGlobals);
177
+ }
178
+ /**
179
+ * Append an additional entry path to a Rolldown `input` value while
180
+ * preserving its shape (string → array, array → array, record → record).
181
+ * The new entry is given the synthetic name `__gjsify_inject` when the
182
+ * record form is used so it doesn't collide with user-named outputs.
183
+ */
184
+ function appendInjectAsEntry(input, injectPath) {
185
+ if (input === undefined)
186
+ return [injectPath];
187
+ if (typeof input === 'string')
188
+ return [input, injectPath];
189
+ if (Array.isArray(input)) {
190
+ return [...input, injectPath];
191
+ }
192
+ return { ...input, __gjsify_inject: injectPath };
193
+ }
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Parse bundled JS code and return the set of free (unbound) identifiers
3
+ * that match known GJS globals from `GJS_GLOBALS_MAP`.
4
+ *
5
+ * "Free" means the identifier is referenced but never declared in the
6
+ * module (var/let/const/function/class/import/param/catch).
7
+ *
8
+ * After esbuild bundling + minification, local variables that shadow
9
+ * globals are renamed to short names, so any surviving known-global name
10
+ * in the output is almost certainly a true global reference. The
11
+ * declared-names check is a safety net for edge cases where esbuild
12
+ * keeps the original name.
13
+ *
14
+ * `typeof X` references ARE included — if code guards with
15
+ * `typeof fetch !== 'undefined'`, it intends to use fetch when available
16
+ * and we can provide it.
17
+ */
18
+ export declare function detectFreeGlobals(code: string): Set<string>;
@@ -0,0 +1,268 @@
1
+ // Detect free (unbound) global identifiers in bundled JS output.
2
+ //
3
+ // Used by the `--globals auto` two-pass build: the first esbuild pass
4
+ // produces a minified bundle without globals injection, this module
5
+ // parses it with acorn and finds references to known GJS globals that
6
+ // are not locally declared. The result feeds the second pass's inject
7
+ // stub so only actually-needed globals are registered.
8
+ import * as acorn from 'acorn';
9
+ import * as walk from 'acorn-walk';
10
+ import { GJS_GLOBALS_MAP } from '@gjsify/resolve-npm/globals-map';
11
+ const KNOWN_GLOBALS = new Set(Object.keys(GJS_GLOBALS_MAP));
12
+ /**
13
+ * Method markers — `<host>.<method>(…)` patterns that imply a global
14
+ * identifier should be injected even though the identifier itself never
15
+ * appears in the bundle.
16
+ *
17
+ * Example: a project that calls `navigator.getGamepads()` doesn't reference
18
+ * any of the gamepad-related identifiers in the globals map, but it still
19
+ * needs `@gjsify/gamepad/register` to patch `navigator` with the method.
20
+ * This marker maps `navigator.getGamepads` → inject the `GamepadEvent`
21
+ * register path (which is the gamepad package's register entry).
22
+ *
23
+ * Keyed by `host.method` (lowercase host, exact method name). Values are
24
+ * KNOWN_GLOBALS identifiers — the detector adds them as free globals if
25
+ * the corresponding member expression is found in the bundle.
26
+ */
27
+ const METHOD_MARKERS = {
28
+ // Gamepad API — navigator.getGamepads is patched on by @gjsify/gamepad/register
29
+ 'navigator.getGamepads': 'GamepadEvent',
30
+ // WebRTC — navigator.mediaDevices is patched on by @gjsify/webrtc/register/media-devices
31
+ 'navigator.mediaDevices': 'MediaDevices',
32
+ // WebAssembly Promise APIs — the runtime stubs throw at first call, so
33
+ // any reference to these methods needs the `@gjsify/webassembly` polyfill.
34
+ // The register entry replaces the stubs with wrappers around the working
35
+ // synchronous `new WebAssembly.{Module,Instance}` constructors.
36
+ 'WebAssembly.compile': 'WebAssembly',
37
+ 'WebAssembly.compileStreaming': 'WebAssembly',
38
+ 'WebAssembly.instantiate': 'WebAssembly',
39
+ 'WebAssembly.instantiateStreaming': 'WebAssembly',
40
+ 'WebAssembly.validate': 'WebAssembly',
41
+ // Note: URL.createObjectURL / URL.revokeObjectURL don't need markers —
42
+ // they are first-class static methods on @gjsify/url's URL class, so the
43
+ // free `URL` identifier (detected directly, maps to
44
+ // @gjsify/node-globals/register/url in GJS_GLOBALS_MAP) already pulls in
45
+ // the correct register module.
46
+ };
47
+ /**
48
+ * Extract all bound names from a binding pattern
49
+ * (Identifier, ObjectPattern, ArrayPattern, AssignmentPattern, RestElement).
50
+ */
51
+ function extractBindingNames(node) {
52
+ if (!node)
53
+ return [];
54
+ switch (node.type) {
55
+ case 'Identifier':
56
+ return [node.name];
57
+ case 'ObjectPattern':
58
+ return node.properties.flatMap((p) => p.type === 'RestElement'
59
+ ? extractBindingNames(p.argument)
60
+ : extractBindingNames(p.value));
61
+ case 'ArrayPattern':
62
+ return node.elements.flatMap((e) => e
63
+ ? e.type === 'RestElement'
64
+ ? extractBindingNames(e.argument)
65
+ : extractBindingNames(e)
66
+ : []);
67
+ case 'AssignmentPattern':
68
+ return extractBindingNames(node.left);
69
+ case 'RestElement':
70
+ return extractBindingNames(node.argument);
71
+ default:
72
+ return [];
73
+ }
74
+ }
75
+ /**
76
+ * Parse bundled JS code and return the set of free (unbound) identifiers
77
+ * that match known GJS globals from `GJS_GLOBALS_MAP`.
78
+ *
79
+ * "Free" means the identifier is referenced but never declared in the
80
+ * module (var/let/const/function/class/import/param/catch).
81
+ *
82
+ * After esbuild bundling + minification, local variables that shadow
83
+ * globals are renamed to short names, so any surviving known-global name
84
+ * in the output is almost certainly a true global reference. The
85
+ * declared-names check is a safety net for edge cases where esbuild
86
+ * keeps the original name.
87
+ *
88
+ * `typeof X` references ARE included — if code guards with
89
+ * `typeof fetch !== 'undefined'`, it intends to use fetch when available
90
+ * and we can provide it.
91
+ */
92
+ export function detectFreeGlobals(code) {
93
+ const ast = acorn.parse(code, {
94
+ ecmaVersion: 'latest',
95
+ sourceType: 'module',
96
+ });
97
+ // --- Pass 1: collect all declared names across the entire module ---
98
+ const declaredNames = new Set();
99
+ walk.simple(ast, {
100
+ VariableDeclarator(node) {
101
+ for (const name of extractBindingNames(node.id)) {
102
+ declaredNames.add(name);
103
+ }
104
+ },
105
+ FunctionDeclaration(node) {
106
+ if (node.id)
107
+ declaredNames.add(node.id.name);
108
+ for (const param of node.params) {
109
+ for (const name of extractBindingNames(param)) {
110
+ declaredNames.add(name);
111
+ }
112
+ }
113
+ },
114
+ FunctionExpression(node) {
115
+ if (node.id)
116
+ declaredNames.add(node.id.name);
117
+ for (const param of node.params) {
118
+ for (const name of extractBindingNames(param)) {
119
+ declaredNames.add(name);
120
+ }
121
+ }
122
+ },
123
+ ArrowFunctionExpression(node) {
124
+ for (const param of node.params) {
125
+ for (const name of extractBindingNames(param)) {
126
+ declaredNames.add(name);
127
+ }
128
+ }
129
+ },
130
+ ClassDeclaration(node) {
131
+ if (node.id)
132
+ declaredNames.add(node.id.name);
133
+ },
134
+ ImportSpecifier(node) {
135
+ declaredNames.add(node.local.name);
136
+ },
137
+ ImportDefaultSpecifier(node) {
138
+ declaredNames.add(node.local.name);
139
+ },
140
+ ImportNamespaceSpecifier(node) {
141
+ declaredNames.add(node.local.name);
142
+ },
143
+ CatchClause(node) {
144
+ if (node.param) {
145
+ for (const name of extractBindingNames(node.param)) {
146
+ declaredNames.add(name);
147
+ }
148
+ }
149
+ },
150
+ });
151
+ // --- Pass 2: find Identifier nodes in reference position ---
152
+ // Also detects MemberExpressions like `globalThis.X` / `global.X` /
153
+ // `window.X` / `self.X` where X is a known global. esbuild's `define`
154
+ // config replaces `global`/`window` with `globalThis`, but we accept
155
+ // all four host-object names for safety (esbuild also never renames
156
+ // these because they are language keywords / pre-defined globals).
157
+ const freeGlobals = new Set();
158
+ const HOST_OBJECTS = new Set(['globalThis', 'global', 'window', 'self', 'globalObject']);
159
+ walk.ancestor(ast, {
160
+ MemberExpression(node) {
161
+ // Only dot-access — skip computed (bracket) access since the
162
+ // property is then a dynamic Expression, not a known name.
163
+ if (node.computed)
164
+ return;
165
+ if (node.object.type !== 'Identifier')
166
+ return;
167
+ if (node.property.type !== 'Identifier')
168
+ return;
169
+ const objName = node.object.name;
170
+ const propName = node.property.name;
171
+ // Pattern A: globalThis.X / global.X / window.X / self.X
172
+ // The property is a known global identifier itself.
173
+ if (HOST_OBJECTS.has(objName)) {
174
+ if (KNOWN_GLOBALS.has(propName)) {
175
+ freeGlobals.add(propName);
176
+ }
177
+ return;
178
+ }
179
+ // Pattern B: known-instance method markers like
180
+ // `navigator.getGamepads` → marker map forwards to a global
181
+ // identifier that triggers the right register path even though
182
+ // the identifier itself never appears in the bundle.
183
+ const markerKey = `${objName}.${propName}`;
184
+ const markerTarget = METHOD_MARKERS[markerKey];
185
+ if (markerTarget && KNOWN_GLOBALS.has(markerTarget)) {
186
+ freeGlobals.add(markerTarget);
187
+ }
188
+ },
189
+ Identifier(node, ancestors) {
190
+ const name = node.name;
191
+ // Quick filter: only check known globals
192
+ if (!KNOWN_GLOBALS.has(name))
193
+ return;
194
+ // Skip if locally declared
195
+ if (declaredNames.has(name))
196
+ return;
197
+ // Determine if this Identifier is in a reference position
198
+ // by checking the parent node.
199
+ const parent = ancestors[ancestors.length - 2];
200
+ if (!parent) {
201
+ freeGlobals.add(name);
202
+ return;
203
+ }
204
+ switch (parent.type) {
205
+ // obj.prop — skip if this is the non-computed property
206
+ case 'MemberExpression': {
207
+ const mem = parent;
208
+ if (mem.property === node && !mem.computed)
209
+ return;
210
+ break;
211
+ }
212
+ // { key: value } — skip if this is the non-computed key
213
+ case 'Property': {
214
+ const prop = parent;
215
+ if (prop.key === node && !prop.computed)
216
+ return;
217
+ break;
218
+ }
219
+ // Method/property definitions in classes
220
+ case 'MethodDefinition':
221
+ case 'PropertyDefinition': {
222
+ const def = parent;
223
+ if (def.key === node && !def.computed)
224
+ return;
225
+ break;
226
+ }
227
+ // label: — skip
228
+ case 'LabeledStatement': {
229
+ const labeled = parent;
230
+ if (labeled.label === node)
231
+ return;
232
+ break;
233
+ }
234
+ // export { X as Y } — skip the exported name
235
+ case 'ExportSpecifier': {
236
+ const spec = parent;
237
+ if (spec.exported === node)
238
+ return;
239
+ break;
240
+ }
241
+ // Declaration ids (function name, class name, variable id)
242
+ // are already in declaredNames, but guard anyway
243
+ case 'FunctionDeclaration':
244
+ case 'FunctionExpression':
245
+ case 'ClassDeclaration':
246
+ case 'ClassExpression': {
247
+ const decl = parent;
248
+ if (decl.id === node)
249
+ return;
250
+ break;
251
+ }
252
+ case 'VariableDeclarator': {
253
+ const vd = parent;
254
+ if (vd.id === node)
255
+ return;
256
+ break;
257
+ }
258
+ // import { X } / import X — already in declaredNames
259
+ case 'ImportSpecifier':
260
+ case 'ImportDefaultSpecifier':
261
+ case 'ImportNamespaceSpecifier':
262
+ return;
263
+ }
264
+ freeGlobals.add(name);
265
+ },
266
+ });
267
+ return freeGlobals;
268
+ }
@@ -0,0 +1,2 @@
1
+ export type EntryPoints = string | string[] | Record<string, string>;
2
+ export declare const globToEntryPoints: (_entryPoints: EntryPoints | undefined, ignore?: string[]) => Promise<EntryPoints | undefined>;
@@ -0,0 +1,38 @@
1
+ // Glob expansion for Rolldown entry-point input.
2
+ //
3
+ // Rolldown's `input` accepts:
4
+ // - a single path string
5
+ // - an array of strings
6
+ // - a record mapping output names to input paths
7
+ //
8
+ // `globToEntryPoints` accepts the same shapes and expands any glob patterns
9
+ // against the filesystem via `fast-glob`. Pure-string entries return as-is
10
+ // when they don't contain wildcards (fast-glob handles that gracefully).
11
+ //
12
+ // `.d.ts` files are always excluded — they are type-only declarations,
13
+ // not parseable as runtime modules. esbuild handled this implicitly via
14
+ // its loader table; Rolldown's Oxc parser errors on declaration-only
15
+ // shapes (`get foo(): T;`).
16
+ import fastGlob from 'fast-glob';
17
+ const DEFAULT_IGNORE = ['**/*.d.ts'];
18
+ export const globToEntryPoints = async (_entryPoints, ignore = []) => {
19
+ if (_entryPoints === undefined)
20
+ return undefined;
21
+ const fullIgnore = [...DEFAULT_IGNORE, ...ignore];
22
+ if (typeof _entryPoints === 'string') {
23
+ const expanded = await fastGlob([_entryPoints], { ignore: fullIgnore });
24
+ return expanded;
25
+ }
26
+ if (Array.isArray(_entryPoints)) {
27
+ return await fastGlob(_entryPoints, { ignore: fullIgnore });
28
+ }
29
+ const entryPoints = {};
30
+ for (const input in _entryPoints) {
31
+ const output = _entryPoints[input];
32
+ const inputs = await fastGlob(input, { ignore: fullIgnore });
33
+ for (const matched of inputs) {
34
+ entryPoints[matched] = output;
35
+ }
36
+ }
37
+ return entryPoints;
38
+ };
@@ -0,0 +1 @@
1
+ export declare const getJsExtensions: (allowExt?: string) => Record<string, string>;
@@ -0,0 +1,7 @@
1
+ export const getJsExtensions = (allowExt) => {
2
+ const extensions = { '.js': '.js', '.ts': '.js', '.mts': '.js', '.cts': '.js', '.cjs': '.js', '.mjs': '.js' };
3
+ if (allowExt && extensions[allowExt]) {
4
+ delete extensions[allowExt];
5
+ }
6
+ return extensions;
7
+ };
@@ -0,0 +1,7 @@
1
+ export * from './alias.js';
2
+ export * from './entry-points.js';
3
+ export * from './extension.js';
4
+ export * from './merge.js';
5
+ export { detectFreeGlobals } from './detect-free-globals.js';
6
+ export { resolveGlobalsList, writeRegisterInjectFile } from './scan-globals.js';
7
+ export { inlineStaticReads } from './inline-static-reads.js';
@@ -0,0 +1,7 @@
1
+ export * from './alias.js';
2
+ export * from './entry-points.js';
3
+ export * from './extension.js';
4
+ export * from './merge.js';
5
+ export { detectFreeGlobals } from './detect-free-globals.js';
6
+ export { resolveGlobalsList, writeRegisterInjectFile } from './scan-globals.js';
7
+ export { inlineStaticReads } from './inline-static-reads.js';
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Run the inliner on a source string. Returns the rewritten source (or the
3
+ * original string when no inlining applied) and the count of edits applied.
4
+ *
5
+ * Safe to call on any JS source. Files that don't reference `readFileSync` /
6
+ * `readdirSync` / `existsSync` skip the AST parse entirely (cheap fast path).
7
+ */
8
+ export declare function inlineStaticReads(src: string, sourceFilePath: string): {
9
+ contents: string;
10
+ inlined: number;
11
+ };