react-native-gtkx 0.4.0-alpha.2 → 0.4.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.
Files changed (63) hide show
  1. package/README.md +35 -96
  2. package/dist/adw/index.js +3 -2
  3. package/dist/adw/index.js.map +1 -1
  4. package/dist/apis/host.gtkx.js.map +1 -1
  5. package/dist/components/modal.d.ts +1 -1
  6. package/dist/components/modal.js +16 -8
  7. package/dist/components/modal.js.map +1 -1
  8. package/dist/dnd/gtk-controllers.js +1 -1
  9. package/dist/dnd/gtk-controllers.js.map +1 -1
  10. package/dist/gtk/index.js +4 -3
  11. package/dist/gtk/index.js.map +1 -1
  12. package/dist/gtkx/bridge/adw.js +1 -1
  13. package/dist/gtkx/bridge/adw.js.map +1 -1
  14. package/dist/gtkx/bridge/core.d.ts +1 -2
  15. package/dist/gtkx/bridge/core.js +2 -5
  16. package/dist/gtkx/bridge/core.js.map +1 -1
  17. package/dist/gtkx/bridge/geometry.js +1 -1
  18. package/dist/gtkx/bridge/geometry.js.map +1 -1
  19. package/dist/gtkx/bridge/layout-manager.js +18 -5
  20. package/dist/gtkx/bridge/layout-manager.js.map +1 -1
  21. package/dist/gtkx/bridge/slot-portal.js.map +1 -1
  22. package/dist/gtkx/bridge/svg-node.js +13 -6
  23. package/dist/gtkx/bridge/svg-node.js.map +1 -1
  24. package/dist/gtkx/bridge/view-box.js +19 -10
  25. package/dist/gtkx/bridge/view-box.js.map +1 -1
  26. package/dist/gtkx/bridge/widgets.generated.adw.js +1 -1
  27. package/dist/gtkx/bridge/widgets.generated.adw.js.map +1 -1
  28. package/dist/mcp/bin.js +1 -1
  29. package/dist/mcp/bin.js.map +1 -1
  30. package/dist/mcp/data/generated.d.ts +860 -531
  31. package/dist/mcp/data/generated.js +952 -538
  32. package/dist/mcp/data/generated.js.map +1 -1
  33. package/dist/mcp/resolve.d.ts +2 -2
  34. package/dist/mcp/resolve.js +2 -2
  35. package/dist/mcp/resolve.js.map +1 -1
  36. package/dist/mcp/server.js +2 -2
  37. package/dist/mcp/server.js.map +1 -1
  38. package/dist/runner/host-dev.js +5 -0
  39. package/dist/runner/host-dev.js.map +1 -1
  40. package/dist/runner/host.js +15 -0
  41. package/dist/runner/host.js.map +1 -1
  42. package/dist/runner/index.d.ts +27 -0
  43. package/dist/runner/index.js +206 -1
  44. package/dist/runner/index.js.map +1 -1
  45. package/dist/sea/assemble.d.ts +9 -0
  46. package/dist/sea/assemble.js +16 -3
  47. package/dist/sea/assemble.js.map +1 -1
  48. package/dist/sea/bundle.d.ts +37 -2
  49. package/dist/sea/bundle.js +77 -5
  50. package/dist/sea/bundle.js.map +1 -1
  51. package/dist/sea/native-shim.js +4 -3
  52. package/dist/sea/native-shim.js.map +1 -1
  53. package/dist/testing/index.js +28 -0
  54. package/dist/testing/index.js.map +1 -1
  55. package/dist/vite/index.js +3 -3
  56. package/dist/vite/index.js.map +1 -1
  57. package/dist/vitest/index.d.ts +2 -2
  58. package/dist/vitest/index.js +1 -1
  59. package/dist/vitest/index.js.map +1 -1
  60. package/package.json +9 -9
  61. package/dist/gtkx/bridge/use-signal.d.ts +0 -2
  62. package/dist/gtkx/bridge/use-signal.js +0 -41
  63. package/dist/gtkx/bridge/use-signal.js.map +0 -1
@@ -38,7 +38,7 @@
38
38
  // resolved once here, at bundle time (see ./gtkx-config-module.ts).
39
39
  //
40
40
  // Not attempted here: the vite path. Investigated, not a drop-in of this
41
- // same technique — see docs/getting-started.md's "Shipping an app"
41
+ // same technique — see docs/guide/packaging.md's "Choosing an artifact"
42
42
  // section for the concrete blocker found empirically while building this:
43
43
  // the vite bundle loads the native addon through a DYNAMICALLY obtained
44
44
  // require (`createRequire(import.meta.url)("./gtkx.node")`), which a
@@ -48,7 +48,7 @@
48
48
  // import.meta.url no longer points at a file with real siblings on disk.
49
49
  import { mkdirSync, readdirSync, readFileSync } from "node:fs";
50
50
  import { createRequire } from "node:module";
51
- import { dirname, join } from "node:path";
51
+ import { dirname, join, relative } from "node:path";
52
52
  import { rolldown } from "rolldown";
53
53
  import { HOST_MODULE_EXTERNALS } from "../metro/index.js";
54
54
  import { buildGtkxConfigModule, virtualConfigModulePlugin, } from "./gtkx-config-module.js";
@@ -83,6 +83,73 @@ export const resolveNativeAddon = (appRoot) => {
83
83
  }
84
84
  return { path: first, key: NATIVE_ASSET_KEY };
85
85
  };
86
+ /** The exact filename `gtkx deploy`'s third-party-notices step reads —
87
+ * @gtkx/cli's own `gtkx:bundled-packages` vite plugin writes it as a build
88
+ * artifact of `gtkx build`, but is not part of @gtkx/cli's public API, so
89
+ * the name is duplicated here rather than imported (see
90
+ * @gtkx/cli/src/vite-plugins/bundled-packages.ts and
91
+ * src/deploy/notices/packages.ts for the two ends this mirrors). */
92
+ export const BUNDLED_PACKAGES_FILENAME = "gtkx-packages.json";
93
+ const stripQuery = (id) => id.split("?")[0] ?? id;
94
+ const packageIdentity = (dir) => {
95
+ try {
96
+ const parsed = JSON.parse(readFileSync(join(dir, "package.json"), "utf8"));
97
+ if (typeof parsed !== "object" ||
98
+ parsed === null ||
99
+ Array.isArray(parsed)) {
100
+ return null;
101
+ }
102
+ const { name, version } = parsed;
103
+ if (typeof name !== "string") {
104
+ return null;
105
+ }
106
+ return { name, version: typeof version === "string" ? version : null };
107
+ }
108
+ catch {
109
+ return null;
110
+ }
111
+ };
112
+ /** Walks up from `dir` until a package.json with a usable "name" turns up —
113
+ * the same walk-to-nearest-manifest approach @gtkx/cli's vite plugin uses,
114
+ * so a module two directories deep inside a package (e.g. a package's own
115
+ * dist/esm/foo.js) still resolves to that package's own root. */
116
+ const packageContaining = (dir) => {
117
+ const identity = packageIdentity(dir);
118
+ if (identity !== null) {
119
+ return { ...identity, dir };
120
+ }
121
+ const parent = dirname(dir);
122
+ return parent === dir ? null : packageContaining(parent);
123
+ };
124
+ const packageForModule = (id) => {
125
+ const path = stripQuery(id);
126
+ return path.startsWith("/") ? packageContaining(dirname(path)) : null;
127
+ };
128
+ /**
129
+ * Mirrors @gtkx/cli's own `gtkx:bundled-packages` vite plugin: for every
130
+ * real module id rolldown pulled into the bundle, records which real npm
131
+ * package it came from (name/version, deduped, plus the package's real
132
+ * directory so `gtkx deploy`'s third-party-notices step can still read its
133
+ * LICENSE/copyright text later — same as it does for a vite build). `gtkx
134
+ * deploy --skip-build` requires this file to exist under `dist/` regardless
135
+ * of toolchain (its own build-skip check runs after this one), so the
136
+ * Metro deploy path needs a real, non-empty answer here, not a stub.
137
+ */
138
+ export const collectBundledPackages = (moduleIds, distDir) => {
139
+ const found = moduleIds
140
+ .map((id) => packageForModule(id))
141
+ .filter((entry) => entry !== null);
142
+ const unique = new Map();
143
+ for (const entry of found) {
144
+ unique.set(`${entry.name}@${entry.version ?? ""}`, entry);
145
+ }
146
+ return [...unique.values()]
147
+ .map((entry) => ({ ...entry, dir: relative(distDir, entry.dir) }))
148
+ .sort((a, b) => a.name.localeCompare(b.name));
149
+ };
150
+ /** Renders {@link collectBundledPackages}' output in the exact shape
151
+ * @gtkx/cli's notice-reading side parses (`{ packages: [...] }`). */
152
+ export const renderBundledPackagesManifest = (packages) => `${JSON.stringify({ packages }, null, 4)}\n`;
86
153
  /**
87
154
  * Builds the synthetic SEA entry source: every HOST_MODULE_EXTERNALS name
88
155
  * loaded through a dynamic `import()` (mirroring runner/host.ts's own
@@ -146,7 +213,10 @@ export const buildEntrySource = (jsbundlePath) => {
146
213
  * HOST_MODULE_EXTERNALS and gtkx.config.ts's resolved values all inlined,
147
214
  * and the native addon import redirected to the SEA-asset extraction
148
215
  * shim. Returns the native addon that must be embedded as a SEA asset
149
- * under {@link NativeAddonAsset.key} for the result to run.
216
+ * under {@link NativeAddonAsset.key} for the result to run, plus the real
217
+ * module ids rolldown pulled into the bundle — {@link collectBundledPackages}
218
+ * turns those into the third-party-notices manifest a deploy needs (the
219
+ * ordinary --sea/--standalone paths ignore this half of the result).
150
220
  */
151
221
  export const bundleMetroSea = async (options) => {
152
222
  const { appRoot, jsbundlePath, outFile } = options;
@@ -183,8 +253,9 @@ export const bundleMetroSea = async (options) => {
183
253
  virtualConfigModulePlugin(configModuleSource, appRoot),
184
254
  ],
185
255
  });
256
+ let output;
186
257
  try {
187
- await bundle.write({
258
+ output = await bundle.write({
188
259
  file: outFile,
189
260
  format: "cjs",
190
261
  minify: true,
@@ -197,6 +268,7 @@ export const bundleMetroSea = async (options) => {
197
268
  finally {
198
269
  await bundle.close();
199
270
  }
200
- return nativeAddon;
271
+ const moduleIds = output.output.flatMap((chunk) => chunk.type === "chunk" ? chunk.moduleIds : []);
272
+ return { nativeAddon, moduleIds };
201
273
  };
202
274
  //# sourceMappingURL=bundle.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"bundle.js","sourceRoot":"","sources":["../../src/sea/bundle.ts"],"names":[],"mappings":"AAAA,qEAAqE;AACrE,yEAAyE;AACzE,sEAAsE;AACtE,cAAc;AACd,EAAE;AACF,mEAAmE;AACnE,yDAAyD;AACzD,6DAA6D;AAC7D,EAAE;AACF,mEAAmE;AACnE,qEAAqE;AACrE,0EAA0E;AAC1E,0EAA0E;AAC1E,0EAA0E;AAC1E,yEAAyE;AACzE,2EAA2E;AAC3E,yDAAyD;AACzD,yEAAyE;AACzE,gDAAgD;AAChD,wEAAwE;AACxE,yEAAyE;AACzE,0EAA0E;AAC1E,yEAAyE;AACzE,uEAAuE;AACvE,eAAe;AACf,0EAA0E;AAC1E,+DAA+D;AAC/D,oEAAoE;AACpE,oDAAoD;AACpD,wEAAwE;AACxE,mEAAmE;AACnE,0EAA0E;AAC1E,wEAAwE;AACxE,sEAAsE;AACtE,0EAA0E;AAC1E,qEAAqE;AACrE,uEAAuE;AACvE,sEAAsE;AACtE,EAAE;AACF,yEAAyE;AACzE,mEAAmE;AACnE,0EAA0E;AAC1E,wEAAwE;AACxE,qEAAqE;AACrE,mEAAmE;AACnE,yEAAyE;AACzE,oEAAoE;AACpE,yEAAyE;AACzE,OAAO,EAAE,SAAS,EAAE,WAAW,EAAE,YAAY,EAAE,M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CAAC,CAAC,EAAE,KAAK,OAAO,CAAC,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC,IAAI,CAAC;aACpD;YACD,iBAAiB,CAAC,OAAO,CAAC;YAC1B,qBAAqB,CAAC;gBACpB,SAAS,EAAE,cAAc;gBACzB,OAAO;gBACP,MAAM,EAAE,iBAAiB;gBACzB,QAAQ,EAAE,WAAW,CAAC,GAAG;gBACzB,UAAU,EACR,iBAAiB,KAAK,QAAQ;oBAC5B,CAAC,CAAC,YAAY,CAAC,WAAW,CAAC,IAAI,CAAC;oBAChC,CAAC,CAAC,SAAS;aAChB,CAAC;YACF,yBAAyB,CAAC,kBAAkB,EAAE,OAAO,CAAC;SACvD;KACF,CAAC,CAAA;IACF,IAAI,CAAC;QACH,MAAM,MAAM,CAAC,KAAK,CAAC;YACjB,IAAI,EAAE,OAAO;YACb,MAAM,EAAE,KAAK;YACb,MAAM,EAAE,IAAI;YACZ,gEAAgE;YAChE,8DAA8D;YAC9D,kEAAkE;YAClE,aAAa,EAAE,KAAK;SACrB,CAAC,CAAA;IACJ,CAAC;YAAS,CAAC;QACT,MAAM,MAAM,CAAC,KAAK,EAAE,CAAA;IACtB,CAAC;IAED,OAAO,WAAW,CAAA;AACpB,CAAC,CAAA","sourcesContent":["// Bundles a Metro-built react-native-gtkx app (main.jsbundle) into a\n// single CJS file suitable for Node's --experimental-sea-config, undoing\n// exactly the externalization HOST_MODULE_EXTERNALS performs at Metro\n// build time.\n//\n// Design, and where this follows/diverges from gtkx's own tutorial\n// (gtkx-org/gtkx examples/tutorial/scripts/bundle.ts and\n// bundle-postject.ts — read before any of this was written):\n//\n// - Bundling mechanics (bundle → single minified CJS file) and the\n// SEA/postject pipeline itself (./assemble.ts) follow the tutorial\n// closely. The bundler is rolldown rather than the tutorial's esbuild —\n// NOT a preference: rolldown is vite's own engine (vite 8 depends on it\n// outright, esbuild is only an optional peer there), and vite is a hard\n// dependency of @gtkx/cli, which is a hard dependency of this package.\n// So rolldown is already installed for every consumer, and esbuild would\n// have been the one genuinely new bundler in the tree.\n// - Native addon: the tutorial's shim assumes the addon file sits BESIDE\n// the built executable (require resolved from\n// dirname(process.execPath)). That is two files, not one — the actual\n// central design decision this epic exists to make — so this diverges:\n// the addon is embedded IN the artifact (as a SEA asset, or as a base64\n// literal for the --standalone .cjs) and extracted to a per-user cache\n// directory on first run. See ./native-shim.ts's header for the full\n// reasoning.\n// - Metro's externals: the tutorial has no equivalent problem, its source\n// is already a single vite/rollup bundle. Metro deliberately\n// externalizes @gtkx/*, react and yoga-layout (../metro/index.ts,\n// HOST_MODULE_EXTERNALS) so main.jsbundle expects\n// globalThis.__hostModules/__hostRequire to exist before it runs (see\n// ../runner/host.ts). This module is a third host implementation\n// (host.ts and host-dev.ts are the other two — see host-dev.ts's header\n// for why they don't share code) that builds those globals from real,\n// STATICALLY imported modules — every name in HOST_MODULE_EXTERNALS\n// becomes a literal `import * as` statement in the generated entry — so\n// the bundler can inline them instead of the app needing a runtime\n// node_modules to dynamically load them from. gtkx.config.ts is also\n// resolved once here, at bundle time (see ./gtkx-config-module.ts).\n//\n// Not attempted here: the vite path. Investigated, not a drop-in of this\n// same technique — see docs/getting-started.md's \"Shipping an app\"\n// section for the concrete blocker found empirically while building this:\n// the vite bundle loads the native addon through a DYNAMICALLY obtained\n// require (`createRequire(import.meta.url)(\"./gtkx.node\")`), which a\n// bundler does not intercept the way it intercepts a static import\n// (verified: the resolve hook never fires for it), and which is unlikely\n// to resolve at all once running from inside a real SEA blob, where\n// import.meta.url no longer points at a file with real siblings on disk.\nimport { mkdirSync, readdirSync, readFileSync } from \"node:fs\"\nimport { createRequire } from \"node:module\"\nimport { dirname, join } from \"node:path\"\nimport { rolldown } from \"rolldown\"\nimport { HOST_MODULE_EXTERNALS } from \"../metro/index.js\"\nimport {\n buildGtkxConfigModule,\n virtualConfigModulePlugin,\n} from \"./gtkx-config-module.js\"\nimport {\n NATIVE_ASSET_KEY,\n nativeAddonShimPlugin,\n type NativeAddonSource,\n} from \"./native-shim.js\"\nimport { reactAnchorPlugin } from \"./react-anchor-plugin.js\"\n\nexport type MetroSeaBundleOptions = {\n /** The app root — where gtkx.config.ts lives and package.json resolves\n * HOST_MODULE_EXTERNALS' bare specifiers (react, @gtkx/*, ...) from. */\n appRoot: string\n /** Path to the release jsbundle produced by `build-linux`. */\n jsbundlePath: string\n /** Where to write the bundled CJS entry (e.g. dist/bundle.cjs). */\n outFile: string\n /** Where the native addon's bytes come from at runtime — \"sea-asset\"\n * for a real single executable, \"inline\" for a self-contained .cjs run\n * by a system Node (default: \"sea-asset\"). */\n nativeAddonSource?: NativeAddonSource\n}\n\nexport type NativeAddonAsset = {\n /** Absolute path to the platform's @gtkx/native-<platform>-<libc>.node\n * that npm installed for this machine. */\n path: string\n /** The SEA asset key it must be embedded under. */\n key: string\n}\n\n/**\n * Locates the ONE native addon file npm installed for this machine.\n * @gtkx/native picks exactly one optionalDependency per platform/libc at\n * install time (see @gtkx/native/index.js's NAPI-RS-generated loader) —\n * failing loudly on anything other than exactly one match matters here:\n * silently picking the wrong one would embed an addon for the wrong\n * architecture with no error until the app actually launches.\n */\nexport const resolveNativeAddon = (appRoot: string): NativeAddonAsset => {\n const appRequire = createRequire(join(appRoot, \"package.json\"))\n const nativePackageJson = appRequire.resolve(\"@gtkx/native/package.json\")\n // .../node_modules/@gtkx/native/package.json -> .../node_modules/@gtkx\n const scopeDir = dirname(dirname(nativePackageJson))\n const candidates = readdirSync(scopeDir, { withFileTypes: true })\n .filter((entry) => entry.isDirectory() && entry.name.startsWith(\"native-\"))\n .flatMap((entry) => {\n const dir = join(scopeDir, entry.name)\n return readdirSync(dir)\n .filter((file) => file.endsWith(\".node\"))\n .map((file) => join(dir, file))\n })\n const [first, ...rest] = candidates\n if (!first || rest.length > 0) {\n throw new Error(\n `expected exactly one @gtkx/native-*/*.node under ${scopeDir}, found ` +\n `${candidates.length} (${candidates.join(\", \") || \"none\"}) — ` +\n \"reinstall targeting a single platform.\",\n )\n }\n return { path: first, key: NATIVE_ASSET_KEY }\n}\n\n/**\n * Builds the synthetic SEA entry source: every HOST_MODULE_EXTERNALS name\n * loaded through a dynamic `import()` (mirroring runner/host.ts's own\n * `load()`, which does the same against a real node_modules at runtime),\n * assembled into globalThis.__hostModules, then the jsbundle text executed\n * the same way host.ts does.\n *\n * Dynamic import, not static, throughout: a Node SEA's main script is\n * CommonJS only — confirmed empirically, Node 24 executes the embedded\n * main as CJS regardless of a \"type\": \"module\" field in sea-config.json\n * or an .mjs extension — and top-level await is a hard error under a \"cjs\"\n * output format REGARDLESS of whether the module is reached via a static\n * or dynamic import (the restriction is format-wide, not per-module —\n * verified: switching yoga-layout's static import to a dynamic one alone\n * did not clear the error). yoga-layout's own entry point has exactly this\n * top-level await (it loads its WASM binary asynchronously — see\n * node_modules/yoga-layout/dist/src/index.js: `const Yoga =\n * wrapAssembly(await loadYoga())` at module scope). The actual fix: import\n * \"yoga-layout/load\" instead, which exports the same `await`, just inside\n * an async FUNCTION (`export async function loadYoga()`), not at the\n * file's top level — bundleable, and awaited here like everything else.\n */\nexport const buildEntrySource = (jsbundlePath: string): string => {\n const jsbundleSource = readFileSync(jsbundlePath, \"utf8\")\n const loadLines = HOST_MODULE_EXTERNALS.map((name) => {\n if (name === \"yoga-layout\") {\n return [\n ` {`,\n ` const { loadYoga, ...rest } = await import(\"yoga-layout/load\");`,\n ` hostModules[\"yoga-layout\"] = __interopHostModule({ ...rest, default: await loadYoga() });`,\n ` }`,\n ].join(\"\\n\")\n }\n return ` hostModules[${JSON.stringify(name)}] = __interopHostModule(await import(${JSON.stringify(name)}));`\n })\n return [\n `async function __gtkxSeaMain() {`,\n // Mirrors runner/host.ts's `load()` interop: import() handles both ESM\n // and CJS, merge a `default` for Babel's default-import interop when\n // the module has none of its own.\n ` const __interopHostModule = (ns) => {`,\n ` const merged = Object.assign({ __esModule: true }, ns);`,\n ` if (!(\"default\" in ns)) merged.default = ns;`,\n ` return merged;`,\n ` };`,\n ` const hostModules = {};`,\n ...loadLines,\n ` globalThis.__hostModules = hostModules;`,\n // Node builtin proxies resolve lazily through the host's own require —\n // real here, no createRequire indirection needed (see host.ts for why\n // it needs one: this file's import.meta.url is never used for\n // anything relative, only require() of bare/builtin specifiers).\n ` globalThis.__hostRequire = require;`,\n ` require(\"node:vm\").runInThisContext(${JSON.stringify(jsbundleSource)}, { filename: ${JSON.stringify(jsbundlePath)} });`,\n `}`,\n `__gtkxSeaMain().catch((error) => { console.error(error); process.exitCode = 1; });`,\n ].join(\"\\n\")\n}\n\n/**\n * Produces `outFile`, a single CJS file with the jsbundle, its\n * HOST_MODULE_EXTERNALS and gtkx.config.ts's resolved values all inlined,\n * and the native addon import redirected to the SEA-asset extraction\n * shim. Returns the native addon that must be embedded as a SEA asset\n * under {@link NativeAddonAsset.key} for the result to run.\n */\nexport const bundleMetroSea = async (\n options: MetroSeaBundleOptions,\n): Promise<NativeAddonAsset> => {\n const { appRoot, jsbundlePath, outFile } = options\n const nativeAddonSource = options.nativeAddonSource ?? \"sea-asset\"\n const configModuleSource = await buildGtkxConfigModule(appRoot)\n const nativeAddon = resolveNativeAddon(appRoot)\n const entrySource = buildEntrySource(jsbundlePath)\n\n mkdirSync(dirname(outFile), { recursive: true })\n\n // The entry is given a path inside appRoot that does not exist on disk,\n // rather than a `\\0`-prefixed virtual id: every bare specifier it\n // imports (react, @gtkx/*, yoga-layout) must resolve from the app's own\n // node_modules, and a real directory is what makes that happen.\n const entryId = join(appRoot, \"__gtkx-sea-entry.js\")\n\n const bundle = await rolldown({\n input: entryId,\n cwd: appRoot,\n platform: \"node\",\n plugins: [\n {\n name: \"gtkx-sea-entry\",\n resolveId: (source) => (source === entryId ? entryId : null),\n load: (id) => (id === entryId ? entrySource : null),\n },\n reactAnchorPlugin(appRoot),\n nativeAddonShimPlugin({\n specifier: \"@gtkx/native\",\n appRoot,\n source: nativeAddonSource,\n assetKey: nativeAddon.key,\n addonBytes:\n nativeAddonSource === \"inline\"\n ? readFileSync(nativeAddon.path)\n : undefined,\n }),\n virtualConfigModulePlugin(configModuleSource, appRoot),\n ],\n })\n try {\n await bundle.write({\n file: outFile,\n format: \"cjs\",\n minify: true,\n // Every HOST_MODULE_EXTERNALS name is reached through a dynamic\n // import; without this each one becomes its own chunk and the\n // \"single file\" the whole build exists to produce is a directory.\n codeSplitting: false,\n })\n } finally {\n await bundle.close()\n }\n\n return nativeAddon\n}\n"]}
1
+ {"version":3,"file":"bundle.js","sourceRoot":"","sources":["../../src/sea/bundle.ts"],"names":[],"mappings":"AAAA,qEAAqE;AACrE,yEAAyE;AACzE,sEAAsE;AACtE,cAAc;AACd,EAAE;AACF,mEAAmE;AACnE,yDAAyD;AACzD,6DAA6D;AAC7D,EAAE;AACF,mEAAmE;AACnE,qEAAqE;AACrE,0EAA0E;AAC1E,0EAA0E;AAC1E,0EAA0E;AAC1E,yEAAyE;AACzE,2EAA2E;AAC3E,yDAAyD;AACzD,yEAAyE;AACzE,gDAAgD;AAChD,wEAAwE;AACxE,yEAAyE;AACzE,0EAA0E;AAC1E,yEAAyE;AACzE,uEAAuE;AACvE,eAAe;AACf,0EAA0E;AAC1E,+DAA+D;AAC/D,oEAAoE;AACpE,oDAAoD;AACpD,wEAAwE;AACxE,mEAAmE;AACnE,0EAA0E;AAC1E,wEAAwE;AACxE,sEAAsE;AACtE,0EAA0E;AAC1E,qEAAqE;AACrE,uEAAuE;AACvE,sEAAsE;AACtE,EAAE;AACF,yEAAyE;AACzE,wEAAwE;AACxE,0EAA0E;AAC1E,wEAAwE;AACxE,qEAAqE;AACrE,mEAAmE;AACnE,yEAAyE;AACzE,oEAAoE;AACpE,yEAAyE;AACzE,OAAO,EAAE,SAAS,EAAE,WAAW,EAAE,YAAY,EAAE,MAAM,SAAS,CAAA;AAC9D,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAA;AAC3C,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAA;AACnD,OAAO,EAAE,QAAQ,EAA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EAAE,CAAC,CAAC,EAAE,KAAK,OAAO,CAAC,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC,IAAI,CAAC;aACpD;YACD,iBAAiB,CAAC,OAAO,CAAC;YAC1B,qBAAqB,CAAC;gBACpB,SAAS,EAAE,cAAc;gBACzB,OAAO;gBACP,MAAM,EAAE,iBAAiB;gBACzB,QAAQ,EAAE,WAAW,CAAC,GAAG;gBACzB,UAAU,EACR,iBAAiB,KAAK,QAAQ;oBAC5B,CAAC,CAAC,YAAY,CAAC,WAAW,CAAC,IAAI,CAAC;oBAChC,CAAC,CAAC,SAAS;aAChB,CAAC;YACF,yBAAyB,CAAC,kBAAkB,EAAE,OAAO,CAAC;SACvD;KACF,CAAC,CAAA;IACF,IAAI,MAAsB,CAAA;IAC1B,IAAI,CAAC;QACH,MAAM,GAAG,MAAM,MAAM,CAAC,KAAK,CAAC;YAC1B,IAAI,EAAE,OAAO;YACb,MAAM,EAAE,KAAK;YACb,MAAM,EAAE,IAAI;YACZ,gEAAgE;YAChE,8DAA8D;YAC9D,kEAAkE;YAClE,aAAa,EAAE,KAAK;SACrB,CAAC,CAAA;IACJ,CAAC;YAAS,CAAC;QACT,MAAM,MAAM,CAAC,KAAK,EAAE,CAAA;IACtB,CAAC;IAED,MAAM,SAAS,GAAG,MAAM,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,KAAK,EAAE,EAAE,CAChD,KAAK,CAAC,IAAI,KAAK,OAAO,CAAC,CAAC,CAAC,KAAK,CAAC,SAAS,CAAC,CAAC,CAAC,EAAE,CAC9C,CAAA;IAED,OAAO,EAAE,WAAW,EAAE,SAAS,EAAE,CAAA;AACnC,CAAC,CAAA","sourcesContent":["// Bundles a Metro-built react-native-gtkx app (main.jsbundle) into a\n// single CJS file suitable for Node's --experimental-sea-config, undoing\n// exactly the externalization HOST_MODULE_EXTERNALS performs at Metro\n// build time.\n//\n// Design, and where this follows/diverges from gtkx's own tutorial\n// (gtkx-org/gtkx examples/tutorial/scripts/bundle.ts and\n// bundle-postject.ts — read before any of this was written):\n//\n// - Bundling mechanics (bundle → single minified CJS file) and the\n// SEA/postject pipeline itself (./assemble.ts) follow the tutorial\n// closely. The bundler is rolldown rather than the tutorial's esbuild —\n// NOT a preference: rolldown is vite's own engine (vite 8 depends on it\n// outright, esbuild is only an optional peer there), and vite is a hard\n// dependency of @gtkx/cli, which is a hard dependency of this package.\n// So rolldown is already installed for every consumer, and esbuild would\n// have been the one genuinely new bundler in the tree.\n// - Native addon: the tutorial's shim assumes the addon file sits BESIDE\n// the built executable (require resolved from\n// dirname(process.execPath)). That is two files, not one — the actual\n// central design decision this epic exists to make — so this diverges:\n// the addon is embedded IN the artifact (as a SEA asset, or as a base64\n// literal for the --standalone .cjs) and extracted to a per-user cache\n// directory on first run. See ./native-shim.ts's header for the full\n// reasoning.\n// - Metro's externals: the tutorial has no equivalent problem, its source\n// is already a single vite/rollup bundle. Metro deliberately\n// externalizes @gtkx/*, react and yoga-layout (../metro/index.ts,\n// HOST_MODULE_EXTERNALS) so main.jsbundle expects\n// globalThis.__hostModules/__hostRequire to exist before it runs (see\n// ../runner/host.ts). This module is a third host implementation\n// (host.ts and host-dev.ts are the other two — see host-dev.ts's header\n// for why they don't share code) that builds those globals from real,\n// STATICALLY imported modules — every name in HOST_MODULE_EXTERNALS\n// becomes a literal `import * as` statement in the generated entry — so\n// the bundler can inline them instead of the app needing a runtime\n// node_modules to dynamically load them from. gtkx.config.ts is also\n// resolved once here, at bundle time (see ./gtkx-config-module.ts).\n//\n// Not attempted here: the vite path. Investigated, not a drop-in of this\n// same technique — see docs/guide/packaging.md's \"Choosing an artifact\"\n// section for the concrete blocker found empirically while building this:\n// the vite bundle loads the native addon through a DYNAMICALLY obtained\n// require (`createRequire(import.meta.url)(\"./gtkx.node\")`), which a\n// bundler does not intercept the way it intercepts a static import\n// (verified: the resolve hook never fires for it), and which is unlikely\n// to resolve at all once running from inside a real SEA blob, where\n// import.meta.url no longer points at a file with real siblings on disk.\nimport { mkdirSync, readdirSync, readFileSync } from \"node:fs\"\nimport { createRequire } from \"node:module\"\nimport { dirname, join, relative } from \"node:path\"\nimport { rolldown, type RolldownOutput } from \"rolldown\"\nimport { HOST_MODULE_EXTERNALS } from \"../metro/index.js\"\nimport {\n buildGtkxConfigModule,\n virtualConfigModulePlugin,\n} from \"./gtkx-config-module.js\"\nimport {\n NATIVE_ASSET_KEY,\n nativeAddonShimPlugin,\n type NativeAddonSource,\n} from \"./native-shim.js\"\nimport { reactAnchorPlugin } from \"./react-anchor-plugin.js\"\n\nexport type MetroSeaBundleOptions = {\n /** The app root — where gtkx.config.ts lives and package.json resolves\n * HOST_MODULE_EXTERNALS' bare specifiers (react, @gtkx/*, ...) from. */\n appRoot: string\n /** Path to the release jsbundle produced by `build-linux`. */\n jsbundlePath: string\n /** Where to write the bundled CJS entry (e.g. dist/bundle.cjs). */\n outFile: string\n /** Where the native addon's bytes come from at runtime — \"sea-asset\"\n * for a real single executable, \"inline\" for a self-contained .cjs run\n * by a system Node (default: \"sea-asset\"). */\n nativeAddonSource?: NativeAddonSource\n}\n\nexport type NativeAddonAsset = {\n /** Absolute path to the platform's @gtkx/native-<platform>-<libc>.node\n * that npm installed for this machine. */\n path: string\n /** The SEA asset key it must be embedded under. */\n key: string\n}\n\n/**\n * Locates the ONE native addon file npm installed for this machine.\n * @gtkx/native picks exactly one optionalDependency per platform/libc at\n * install time (see @gtkx/native/index.js's NAPI-RS-generated loader) —\n * failing loudly on anything other than exactly one match matters here:\n * silently picking the wrong one would embed an addon for the wrong\n * architecture with no error until the app actually launches.\n */\nexport const resolveNativeAddon = (appRoot: string): NativeAddonAsset => {\n const appRequire = createRequire(join(appRoot, \"package.json\"))\n const nativePackageJson = appRequire.resolve(\"@gtkx/native/package.json\")\n // .../node_modules/@gtkx/native/package.json -> .../node_modules/@gtkx\n const scopeDir = dirname(dirname(nativePackageJson))\n const candidates = readdirSync(scopeDir, { withFileTypes: true })\n .filter((entry) => entry.isDirectory() && entry.name.startsWith(\"native-\"))\n .flatMap((entry) => {\n const dir = join(scopeDir, entry.name)\n return readdirSync(dir)\n .filter((file) => file.endsWith(\".node\"))\n .map((file) => join(dir, file))\n })\n const [first, ...rest] = candidates\n if (!first || rest.length > 0) {\n throw new Error(\n `expected exactly one @gtkx/native-*/*.node under ${scopeDir}, found ` +\n `${candidates.length} (${candidates.join(\", \") || \"none\"}) — ` +\n \"reinstall targeting a single platform.\",\n )\n }\n return { path: first, key: NATIVE_ASSET_KEY }\n}\n\n/** One entry of the \"which real npm package does this bundled code come\n * from\" manifest — see {@link collectBundledPackages}. */\nexport type BundledPackageRecord = {\n name: string\n version: string | null\n /** Relative to whatever directory the manifest itself is written into. */\n dir: string\n}\n\n/** The exact filename `gtkx deploy`'s third-party-notices step reads —\n * @gtkx/cli's own `gtkx:bundled-packages` vite plugin writes it as a build\n * artifact of `gtkx build`, but is not part of @gtkx/cli's public API, so\n * the name is duplicated here rather than imported (see\n * @gtkx/cli/src/vite-plugins/bundled-packages.ts and\n * src/deploy/notices/packages.ts for the two ends this mirrors). */\nexport const BUNDLED_PACKAGES_FILENAME = \"gtkx-packages.json\"\n\nconst stripQuery = (id: string): string => id.split(\"?\")[0] ?? id\n\nconst packageIdentity = (\n dir: string,\n): { name: string; version: string | null } | null => {\n try {\n const parsed: unknown = JSON.parse(\n readFileSync(join(dir, \"package.json\"), \"utf8\"),\n )\n if (\n typeof parsed !== \"object\" ||\n parsed === null ||\n Array.isArray(parsed)\n ) {\n return null\n }\n const { name, version } = parsed as { name?: unknown; version?: unknown }\n if (typeof name !== \"string\") {\n return null\n }\n return { name, version: typeof version === \"string\" ? version : null }\n } catch {\n return null\n }\n}\n\n/** Walks up from `dir` until a package.json with a usable \"name\" turns up —\n * the same walk-to-nearest-manifest approach @gtkx/cli's vite plugin uses,\n * so a module two directories deep inside a package (e.g. a package's own\n * dist/esm/foo.js) still resolves to that package's own root. */\nconst packageContaining = (dir: string): BundledPackageRecord | null => {\n const identity = packageIdentity(dir)\n if (identity !== null) {\n return { ...identity, dir }\n }\n const parent = dirname(dir)\n return parent === dir ? null : packageContaining(parent)\n}\n\nconst packageForModule = (id: string): BundledPackageRecord | null => {\n const path = stripQuery(id)\n return path.startsWith(\"/\") ? packageContaining(dirname(path)) : null\n}\n\n/**\n * Mirrors @gtkx/cli's own `gtkx:bundled-packages` vite plugin: for every\n * real module id rolldown pulled into the bundle, records which real npm\n * package it came from (name/version, deduped, plus the package's real\n * directory so `gtkx deploy`'s third-party-notices step can still read its\n * LICENSE/copyright text later — same as it does for a vite build). `gtkx\n * deploy --skip-build` requires this file to exist under `dist/` regardless\n * of toolchain (its own build-skip check runs after this one), so the\n * Metro deploy path needs a real, non-empty answer here, not a stub.\n */\nexport const collectBundledPackages = (\n moduleIds: string[],\n distDir: string,\n): BundledPackageRecord[] => {\n const found = moduleIds\n .map((id) => packageForModule(id))\n .filter((entry): entry is BundledPackageRecord => entry !== null)\n const unique = new Map<string, BundledPackageRecord>()\n for (const entry of found) {\n unique.set(`${entry.name}@${entry.version ?? \"\"}`, entry)\n }\n return [...unique.values()]\n .map((entry) => ({ ...entry, dir: relative(distDir, entry.dir) }))\n .sort((a, b) => a.name.localeCompare(b.name))\n}\n\n/** Renders {@link collectBundledPackages}' output in the exact shape\n * @gtkx/cli's notice-reading side parses (`{ packages: [...] }`). */\nexport const renderBundledPackagesManifest = (\n packages: BundledPackageRecord[],\n): string => `${JSON.stringify({ packages }, null, 4)}\\n`\n\n/**\n * Builds the synthetic SEA entry source: every HOST_MODULE_EXTERNALS name\n * loaded through a dynamic `import()` (mirroring runner/host.ts's own\n * `load()`, which does the same against a real node_modules at runtime),\n * assembled into globalThis.__hostModules, then the jsbundle text executed\n * the same way host.ts does.\n *\n * Dynamic import, not static, throughout: a Node SEA's main script is\n * CommonJS only — confirmed empirically, Node 24 executes the embedded\n * main as CJS regardless of a \"type\": \"module\" field in sea-config.json\n * or an .mjs extension — and top-level await is a hard error under a \"cjs\"\n * output format REGARDLESS of whether the module is reached via a static\n * or dynamic import (the restriction is format-wide, not per-module —\n * verified: switching yoga-layout's static import to a dynamic one alone\n * did not clear the error). yoga-layout's own entry point has exactly this\n * top-level await (it loads its WASM binary asynchronously — see\n * node_modules/yoga-layout/dist/src/index.js: `const Yoga =\n * wrapAssembly(await loadYoga())` at module scope). The actual fix: import\n * \"yoga-layout/load\" instead, which exports the same `await`, just inside\n * an async FUNCTION (`export async function loadYoga()`), not at the\n * file's top level — bundleable, and awaited here like everything else.\n */\nexport const buildEntrySource = (jsbundlePath: string): string => {\n const jsbundleSource = readFileSync(jsbundlePath, \"utf8\")\n const loadLines = HOST_MODULE_EXTERNALS.map((name) => {\n if (name === \"yoga-layout\") {\n return [\n ` {`,\n ` const { loadYoga, ...rest } = await import(\"yoga-layout/load\");`,\n ` hostModules[\"yoga-layout\"] = __interopHostModule({ ...rest, default: await loadYoga() });`,\n ` }`,\n ].join(\"\\n\")\n }\n return ` hostModules[${JSON.stringify(name)}] = __interopHostModule(await import(${JSON.stringify(name)}));`\n })\n return [\n `async function __gtkxSeaMain() {`,\n // Mirrors runner/host.ts's `load()` interop: import() handles both ESM\n // and CJS, merge a `default` for Babel's default-import interop when\n // the module has none of its own.\n ` const __interopHostModule = (ns) => {`,\n ` const merged = Object.assign({ __esModule: true }, ns);`,\n ` if (!(\"default\" in ns)) merged.default = ns;`,\n ` return merged;`,\n ` };`,\n ` const hostModules = {};`,\n ...loadLines,\n ` globalThis.__hostModules = hostModules;`,\n // Node builtin proxies resolve lazily through the host's own require —\n // real here, no createRequire indirection needed (see host.ts for why\n // it needs one: this file's import.meta.url is never used for\n // anything relative, only require() of bare/builtin specifiers).\n ` globalThis.__hostRequire = require;`,\n ` require(\"node:vm\").runInThisContext(${JSON.stringify(jsbundleSource)}, { filename: ${JSON.stringify(jsbundlePath)} });`,\n `}`,\n `__gtkxSeaMain().catch((error) => { console.error(error); process.exitCode = 1; });`,\n ].join(\"\\n\")\n}\n\n/**\n * Produces `outFile`, a single CJS file with the jsbundle, its\n * HOST_MODULE_EXTERNALS and gtkx.config.ts's resolved values all inlined,\n * and the native addon import redirected to the SEA-asset extraction\n * shim. Returns the native addon that must be embedded as a SEA asset\n * under {@link NativeAddonAsset.key} for the result to run, plus the real\n * module ids rolldown pulled into the bundle — {@link collectBundledPackages}\n * turns those into the third-party-notices manifest a deploy needs (the\n * ordinary --sea/--standalone paths ignore this half of the result).\n */\nexport const bundleMetroSea = async (\n options: MetroSeaBundleOptions,\n): Promise<{ nativeAddon: NativeAddonAsset; moduleIds: string[] }> => {\n const { appRoot, jsbundlePath, outFile } = options\n const nativeAddonSource = options.nativeAddonSource ?? \"sea-asset\"\n const configModuleSource = await buildGtkxConfigModule(appRoot)\n const nativeAddon = resolveNativeAddon(appRoot)\n const entrySource = buildEntrySource(jsbundlePath)\n\n mkdirSync(dirname(outFile), { recursive: true })\n\n // The entry is given a path inside appRoot that does not exist on disk,\n // rather than a `\\0`-prefixed virtual id: every bare specifier it\n // imports (react, @gtkx/*, yoga-layout) must resolve from the app's own\n // node_modules, and a real directory is what makes that happen.\n const entryId = join(appRoot, \"__gtkx-sea-entry.js\")\n\n const bundle = await rolldown({\n input: entryId,\n cwd: appRoot,\n platform: \"node\",\n plugins: [\n {\n name: \"gtkx-sea-entry\",\n resolveId: (source) => (source === entryId ? entryId : null),\n load: (id) => (id === entryId ? entrySource : null),\n },\n reactAnchorPlugin(appRoot),\n nativeAddonShimPlugin({\n specifier: \"@gtkx/native\",\n appRoot,\n source: nativeAddonSource,\n assetKey: nativeAddon.key,\n addonBytes:\n nativeAddonSource === \"inline\"\n ? readFileSync(nativeAddon.path)\n : undefined,\n }),\n virtualConfigModulePlugin(configModuleSource, appRoot),\n ],\n })\n let output: RolldownOutput\n try {\n output = await bundle.write({\n file: outFile,\n format: \"cjs\",\n minify: true,\n // Every HOST_MODULE_EXTERNALS name is reached through a dynamic\n // import; without this each one becomes its own chunk and the\n // \"single file\" the whole build exists to produce is a directory.\n codeSplitting: false,\n })\n } finally {\n await bundle.close()\n }\n\n const moduleIds = output.output.flatMap((chunk) =>\n chunk.type === \"chunk\" ? chunk.moduleIds : [],\n )\n\n return { nativeAddon, moduleIds }\n}\n"]}
@@ -1,6 +1,7 @@
1
1
  // The gtkx native addon (@gtkx/native-<platform>-<libc>, a Rust/NAPI addon
2
- // loaded through dlopen — see docs/getting-started.md's "Shipping an app"
3
- // section for the full design reasoning) cannot be embedded as bundled JS:
2
+ // loaded through dlopen — see docs/guide/packaging.md for the shipped
3
+ // behavior, and this file's own comments below for the full design
4
+ // reasoning) cannot be embedded as bundled JS:
4
5
  // a Node SEA is a V8 code cache blob, and dlopen needs a real file on a
5
6
  // real filesystem, not bytes inside the executable.
6
7
  //
@@ -80,7 +81,7 @@ if (!target) {
80
81
  // proven by both artifacts beats two, one of which is rarely exercised.
81
82
  const nativeModule = { exports: {} };
82
83
  process.dlopen(nativeModule, target);
83
- // The vite path's own build (dist/bundle.js, gtkx's CLI plugin) calls
84
+ // The vite path's own build (dist/bundle.mjs, gtkx's CLI plugin) calls
84
85
  // this immediately after loading the addon, before anything else touches
85
86
  // it; @gtkx/runtime's compiled JS never calls it itself (confirmed by
86
87
  // inspecting its dist — it only re-exports a handful of low-level
@@ -1 +1 @@
1
- {"version":3,"file":"native-shim.js","sourceRoot":"","sources":["../../src/sea/native-shim.ts"],"names":[],"mappings":"AAAA,2EAA2E;AAC3E,0EAA0E;AAC1E,2EAA2E;AAC3E,wEAAwE;AACxE,oDAAoD;AACpD,EAAE;AACF,wEAAwE;AACxE,oEAAoE;AACpE,sEAAsE;AACtE,sEAAsE;AACtE,wEAAwE;AACxE,wEAAwE;AACxE,yEAAyE;AACzE,0EAA0E;AAC1E,iCAAiC;AACjC,EAAE;AACF,uEAAuE;AACvE,wEAAwE;AACxE,uEAAuE;AACvE,uEAAuE;AACvE,sEAAsE;AACtE,uEAAuE;AACvE,2EAA2E;AAC3E,uEAAuE;AACvE,qBAAqB;AACrB,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW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,CAAC,MAAM,CAAC,CAAC,CAAC,IAAI,CAAC;QACrD,IAAI,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC,EAAE,KAAK,MAAM,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,IAAI,CAAC;KAChD,CAAA;AACH,CAAC,CAAA","sourcesContent":["// The gtkx native addon (@gtkx/native-<platform>-<libc>, a Rust/NAPI addon\n// loaded through dlopen — see docs/getting-started.md's \"Shipping an app\"\n// section for the full design reasoning) cannot be embedded as bundled JS:\n// a Node SEA is a V8 code cache blob, and dlopen needs a real file on a\n// real filesystem, not bytes inside the executable.\n//\n// So it has to be carried as bytes and written back to disk before use.\n// This plugin swaps every import of a given specifier (in practice,\n// \"@gtkx/native\" — see ../sea/bundle.ts) for a shim that does exactly\n// that: extract to a per-user cache directory (content-hash-keyed, so\n// repeat launches reuse the file instead of re-extracting ~1.6 MB every\n// start) and dlopen it from there. Where the bytes come from is the one\n// difference between the two single-file artifacts — Node's SEA \"assets\"\n// mechanism for the executable, a base64 literal for the standalone .cjs;\n// see {@link NativeAddonSource}.\n//\n// Cache location: XDG_CACHE_HOME (or ~/.cache) first, os.tmpdir() as a\n// fallback for a read-only $HOME. Deliberately NOT the SEA executable's\n// own directory — that may be read-only (a mounted image, a root-owned\n// install under /opt) or simply a different place than where the addon\n// was extracted the first time, if the binary moved. This is the same\n// question gtkx's own tutorial answers by placing the addon BESIDE the\n// executable (dist/gtkx.node next to dist/app) — a real divergence, not an\n// oversight: that keeps two files, which is exactly what this epic set\n// out to stop doing.\nimport { join } from \"node:path\"\nimport type { Plugin } from \"rolldown\"\n\nexport const NATIVE_ASSET_KEY = \"gtkx-native.node\"\n\n/**\n * Where the shim gets the addon's bytes from — the only difference between\n * the two single-file artifacts:\n *\n * - `\"sea-asset\"`: from the SEA blob, via node:sea. Only works inside a\n * real single executable.\n * - `\"inline\"`: from a base64 literal in the bundle itself, so the CJS\n * file is self-contained under a plain `node app.cjs` — the same\n * artifact minus the embedded Node runtime. Costs ~4/3 of the addon's\n * size in source text (the addon is ~1.6 MB) and is parsed once at\n * startup; the extraction and dlopen below are shared.\n */\nexport type NativeAddonSource = \"sea-asset\" | \"inline\"\n\nconst bytesExpression = (\n source: NativeAddonSource,\n assetKey: string,\n): string =>\n source === \"sea-asset\"\n ? `Buffer.from(require(\"node:sea\").getAsset(${JSON.stringify(assetKey)}))`\n : `Buffer.from(__gtkxNativeBase64, \"base64\")`\n\nconst shimSource = (\n source: NativeAddonSource,\n assetKey: string,\n base64: string,\n): string => `\nconst { createHash } = require(\"node:crypto\");\nconst { mkdirSync, existsSync, writeFileSync, renameSync } = require(\"node:fs\");\nconst { join } = require(\"node:path\");\nconst os = require(\"node:os\");\n${source === \"inline\" ? `const __gtkxNativeBase64 = ${JSON.stringify(base64)};` : \"\"}\n\nconst bytes = ${bytesExpression(source, assetKey)};\nconst hash = createHash(\"sha256\").update(bytes).digest(\"hex\").slice(0, 16);\nconst fileName = \"native-\" + hash + \".node\";\n\nconst candidateDirs = [\n join(process.env.XDG_CACHE_HOME || join(os.homedir(), \".cache\"), \"react-native-gtkx-sea\"),\n join(os.tmpdir(), \"react-native-gtkx-sea\"),\n];\n\nlet target;\nlet lastError;\nfor (const dir of candidateDirs) {\n try {\n mkdirSync(dir, { recursive: true });\n const candidate = join(dir, fileName);\n if (!existsSync(candidate)) {\n const tmp = candidate + \".\" + process.pid + \".tmp\";\n writeFileSync(tmp, bytes, { mode: 0o755 });\n renameSync(tmp, candidate);\n }\n target = candidate;\n break;\n } catch (error) {\n lastError = error;\n }\n}\nif (!target) {\n throw new Error(\n \"react-native-gtkx: could not extract the native addon to a writable \" +\n \"cache directory (tried \" + candidateDirs.join(\", \") + \"): \" + String(lastError),\n );\n}\n\n// Not require(target): the require() available to a SEA's main script is\n// restricted to built-ins and embedded assets (verified — requiring an\n// arbitrary absolute path from here throws ERR_UNKNOWN_BUILTIN_MODULE, the\n// same error Node throws for an unrecognized built-in specifier). That\n// restriction doesn't apply to process.dlopen(), the lower-level\n// primitive require() itself uses for \".node\" files (Module._extensions\n// [\".node\"]) — it works on any real path, which is exactly what makes\n// this shim work at all. The \"inline\" build could use a plain require()\n// here, but shares dlopen() rather than branching: one code path that is\n// proven by both artifacts beats two, one of which is rarely exercised.\nconst nativeModule = { exports: {} };\nprocess.dlopen(nativeModule, target);\n// The vite path's own build (dist/bundle.js, gtkx's CLI plugin) calls\n// this immediately after loading the addon, before anything else touches\n// it; @gtkx/runtime's compiled JS never calls it itself (confirmed by\n// inspecting its dist — it only re-exports a handful of low-level\n// functions), so ordinary require() of the addon through Node's own\n// napi module registration must be relying on something dlopen() alone\n// does not trigger. Without this call the addon has no thread registered\n// as \"the Node environment's owner\" and the first GTK-driven callback\n// into JS panics: \"the Node environment was accessed from a thread it is\n// not installed on\" (reproduced and fixed by adding this line).\nnativeModule.exports.init();\nmodule.exports = nativeModule.exports;\n`\n\nexport type NativeAddonShimOptions = {\n /** The bare specifier to replace, in practice \"@gtkx/native\". */\n specifier: string\n /** The app root — the shim's id lives here, see above. */\n appRoot: string\n /** Where the addon's bytes come from at runtime. */\n source: NativeAddonSource\n /** SEA asset key; unused when `source` is \"inline\". */\n assetKey?: string\n /** The addon's bytes; required when `source` is \"inline\". */\n addonBytes?: Buffer\n}\n\n/**\n * Intercepts every import/require of `specifier` (an exact bare module\n * specifier, e.g. \"@gtkx/native\") and replaces it with the extraction shim\n * above. The real module never reaches the bundle graph — only its\n * re-exported surface, loaded from the extracted file at runtime.\n *\n * The shim is given an id inside `appRoot` with a `.cjs` extension rather\n * than a `\\0`-prefixed virtual one: the shim IS CommonJS (it assigns\n * `module.exports` so consumers' NAMED imports of the addon still resolve\n * through the bundler's interop), and a real directory is what lets any\n * specifier inside it resolve normally.\n */\nexport const nativeAddonShimPlugin = (\n options: NativeAddonShimOptions,\n): Plugin => {\n const { specifier, appRoot, source } = options\n if (source === \"inline\" && !options.addonBytes) {\n throw new Error('the \"inline\" native addon source needs addonBytes')\n }\n const shimId = join(appRoot, \"__gtkx-sea-native-shim.cjs\")\n const contents = shimSource(\n source,\n options.assetKey ?? NATIVE_ASSET_KEY,\n options.addonBytes?.toString(\"base64\") ?? \"\",\n )\n return {\n name: \"gtkx-native-addon-shim\",\n resolveId: (id) => (id === specifier ? shimId : null),\n load: (id) => (id === shimId ? contents : null),\n }\n}\n"]}
1
+ {"version":3,"file":"native-shim.js","sourceRoot":"","sources":["../../src/sea/native-shim.ts"],"names":[],"mappings":"AAAA,2EAA2E;AAC3E,sEAAsE;AACtE,mEAAmE;AACnE,+CAA+C;AAC/C,wEAAwE;AACxE,oDAAoD;AACpD,EAAE;AACF,wEAAwE;AACxE,oEAAoE;AACpE,sEAAsE;AACtE,sEAAsE;AACtE,wEAAwE;AACxE,wEAAwE;AACxE,yEAAyE;AACzE,0EAA0E;AAC1E,iCAAiC;AACjC,EAAE;AACF,uEAAuE;AACvE,wEAAwE;AACxE,uEAAuE;AACvE,uEAAuE;AACvE,sEAAsE;AACtE,uEAAuE;AACvE,2EAA2E;AAC3E,uEAAuE;AACvE,qBAAqB;AACrB,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAA;AAGhC,MAAM,CAAC,MAAM,gBAAgB,GAAG,kBAAkB,CAAA;AAgBlD,MAAM,eAAe,GAAG,CACtB,MAAyB,EACzB,QAAgB,EACR,EAAE,CACV,MAAM,KAAK,WAAW;IACpB,CAAC,CAAC,4CAA4C,IAAI,CAAC,SAAS,CAAC,QAAQ,CAAC,IAAI;IAC1E,CAAC,CAAC,2CAA2C,CAAA;AAEjD,MAAM,UAAU,GAAG,CACjB,MAAyB,EACzB,QAAgB,EAChB,MAAc,EACN,EAAE,CAAC;;;;;EAKX,MAAM,KAAK,QAAQ,CAAC,CAAC,CAAC,8BAA8B,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE;;gBAEpE,eAAe,CAAC,MAAM,EAAE,QAAQ,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAyDhD,CAAA;AAeD;;;;;;;;;;;GAWG;AACH,MAAM,CAAC,MAAM,qBAAqB,GAAG,CACnC,OAA+B,EACvB,EAAE;IACV,MAAM,EAAE,SAAS,EAAE,OAAO,EAAE,MAAM,EAAE,GAAG,OAAO,CAAA;IAC9C,IAAI,MAAM,KAAK,QAAQ,IAAI,CAAC,OAAO,CAAC,UAAU,EAAE,CAAC;QAC/C,MAAM,IAAI,KAAK,CAAC,mDAAmD,CAAC,CAAA;IACtE,CAAC;IACD,MAAM,MAAM,GAAG,IAAI,CAAC,OAAO,EAAE,4BAA4B,CAAC,CAAA;IAC1D,MAAM,QAAQ,GAAG,UAAU,CACzB,MAAM,EACN,OAAO,CAAC,QAAQ,IAAI,gBAAgB,EACpC,OAAO,CAAC,UAAU,EAAE,QAAQ,CAAC,QAAQ,CAAC,IAAI,EAAE,CAC7C,CAAA;IACD,OAAO;QACL,IAAI,EAAE,wBAAwB;QAC9B,SAAS,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC,EAAE,KAAK,SAAS,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,IAAI,CAAC;QACrD,IAAI,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC,EAAE,KAAK,MAAM,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,IAAI,CAAC;KAChD,CAAA;AACH,CAAC,CAAA","sourcesContent":["// The gtkx native addon (@gtkx/native-<platform>-<libc>, a Rust/NAPI addon\n// loaded through dlopen — see docs/guide/packaging.md for the shipped\n// behavior, and this file's own comments below for the full design\n// reasoning) cannot be embedded as bundled JS:\n// a Node SEA is a V8 code cache blob, and dlopen needs a real file on a\n// real filesystem, not bytes inside the executable.\n//\n// So it has to be carried as bytes and written back to disk before use.\n// This plugin swaps every import of a given specifier (in practice,\n// \"@gtkx/native\" — see ../sea/bundle.ts) for a shim that does exactly\n// that: extract to a per-user cache directory (content-hash-keyed, so\n// repeat launches reuse the file instead of re-extracting ~1.6 MB every\n// start) and dlopen it from there. Where the bytes come from is the one\n// difference between the two single-file artifacts — Node's SEA \"assets\"\n// mechanism for the executable, a base64 literal for the standalone .cjs;\n// see {@link NativeAddonSource}.\n//\n// Cache location: XDG_CACHE_HOME (or ~/.cache) first, os.tmpdir() as a\n// fallback for a read-only $HOME. Deliberately NOT the SEA executable's\n// own directory — that may be read-only (a mounted image, a root-owned\n// install under /opt) or simply a different place than where the addon\n// was extracted the first time, if the binary moved. This is the same\n// question gtkx's own tutorial answers by placing the addon BESIDE the\n// executable (dist/gtkx.node next to dist/app) — a real divergence, not an\n// oversight: that keeps two files, which is exactly what this epic set\n// out to stop doing.\nimport { join } from \"node:path\"\nimport type { Plugin } from \"rolldown\"\n\nexport const NATIVE_ASSET_KEY = \"gtkx-native.node\"\n\n/**\n * Where the shim gets the addon's bytes from — the only difference between\n * the two single-file artifacts:\n *\n * - `\"sea-asset\"`: from the SEA blob, via node:sea. Only works inside a\n * real single executable.\n * - `\"inline\"`: from a base64 literal in the bundle itself, so the CJS\n * file is self-contained under a plain `node app.cjs` — the same\n * artifact minus the embedded Node runtime. Costs ~4/3 of the addon's\n * size in source text (the addon is ~1.6 MB) and is parsed once at\n * startup; the extraction and dlopen below are shared.\n */\nexport type NativeAddonSource = \"sea-asset\" | \"inline\"\n\nconst bytesExpression = (\n source: NativeAddonSource,\n assetKey: string,\n): string =>\n source === \"sea-asset\"\n ? `Buffer.from(require(\"node:sea\").getAsset(${JSON.stringify(assetKey)}))`\n : `Buffer.from(__gtkxNativeBase64, \"base64\")`\n\nconst shimSource = (\n source: NativeAddonSource,\n assetKey: string,\n base64: string,\n): string => `\nconst { createHash } = require(\"node:crypto\");\nconst { mkdirSync, existsSync, writeFileSync, renameSync } = require(\"node:fs\");\nconst { join } = require(\"node:path\");\nconst os = require(\"node:os\");\n${source === \"inline\" ? `const __gtkxNativeBase64 = ${JSON.stringify(base64)};` : \"\"}\n\nconst bytes = ${bytesExpression(source, assetKey)};\nconst hash = createHash(\"sha256\").update(bytes).digest(\"hex\").slice(0, 16);\nconst fileName = \"native-\" + hash + \".node\";\n\nconst candidateDirs = [\n join(process.env.XDG_CACHE_HOME || join(os.homedir(), \".cache\"), \"react-native-gtkx-sea\"),\n join(os.tmpdir(), \"react-native-gtkx-sea\"),\n];\n\nlet target;\nlet lastError;\nfor (const dir of candidateDirs) {\n try {\n mkdirSync(dir, { recursive: true });\n const candidate = join(dir, fileName);\n if (!existsSync(candidate)) {\n const tmp = candidate + \".\" + process.pid + \".tmp\";\n writeFileSync(tmp, bytes, { mode: 0o755 });\n renameSync(tmp, candidate);\n }\n target = candidate;\n break;\n } catch (error) {\n lastError = error;\n }\n}\nif (!target) {\n throw new Error(\n \"react-native-gtkx: could not extract the native addon to a writable \" +\n \"cache directory (tried \" + candidateDirs.join(\", \") + \"): \" + String(lastError),\n );\n}\n\n// Not require(target): the require() available to a SEA's main script is\n// restricted to built-ins and embedded assets (verified — requiring an\n// arbitrary absolute path from here throws ERR_UNKNOWN_BUILTIN_MODULE, the\n// same error Node throws for an unrecognized built-in specifier). That\n// restriction doesn't apply to process.dlopen(), the lower-level\n// primitive require() itself uses for \".node\" files (Module._extensions\n// [\".node\"]) — it works on any real path, which is exactly what makes\n// this shim work at all. The \"inline\" build could use a plain require()\n// here, but shares dlopen() rather than branching: one code path that is\n// proven by both artifacts beats two, one of which is rarely exercised.\nconst nativeModule = { exports: {} };\nprocess.dlopen(nativeModule, target);\n// The vite path's own build (dist/bundle.mjs, gtkx's CLI plugin) calls\n// this immediately after loading the addon, before anything else touches\n// it; @gtkx/runtime's compiled JS never calls it itself (confirmed by\n// inspecting its dist — it only re-exports a handful of low-level\n// functions), so ordinary require() of the addon through Node's own\n// napi module registration must be relying on something dlopen() alone\n// does not trigger. Without this call the addon has no thread registered\n// as \"the Node environment's owner\" and the first GTK-driven callback\n// into JS panics: \"the Node environment was accessed from a thread it is\n// not installed on\" (reproduced and fixed by adding this line).\nnativeModule.exports.init();\nmodule.exports = nativeModule.exports;\n`\n\nexport type NativeAddonShimOptions = {\n /** The bare specifier to replace, in practice \"@gtkx/native\". */\n specifier: string\n /** The app root — the shim's id lives here, see above. */\n appRoot: string\n /** Where the addon's bytes come from at runtime. */\n source: NativeAddonSource\n /** SEA asset key; unused when `source` is \"inline\". */\n assetKey?: string\n /** The addon's bytes; required when `source` is \"inline\". */\n addonBytes?: Buffer\n}\n\n/**\n * Intercepts every import/require of `specifier` (an exact bare module\n * specifier, e.g. \"@gtkx/native\") and replaces it with the extraction shim\n * above. The real module never reaches the bundle graph — only its\n * re-exported surface, loaded from the extracted file at runtime.\n *\n * The shim is given an id inside `appRoot` with a `.cjs` extension rather\n * than a `\\0`-prefixed virtual one: the shim IS CommonJS (it assigns\n * `module.exports` so consumers' NAMED imports of the addon still resolve\n * through the bundler's interop), and a real directory is what lets any\n * specifier inside it resolve normally.\n */\nexport const nativeAddonShimPlugin = (\n options: NativeAddonShimOptions,\n): Plugin => {\n const { specifier, appRoot, source } = options\n if (source === \"inline\" && !options.addonBytes) {\n throw new Error('the \"inline\" native addon source needs addonBytes')\n }\n const shimId = join(appRoot, \"__gtkx-sea-native-shim.cjs\")\n const contents = shimSource(\n source,\n options.assetKey ?? NATIVE_ASSET_KEY,\n options.addonBytes?.toString(\"base64\") ?? \"\",\n )\n return {\n name: \"gtkx-native-addon-shim\",\n resolveId: (id) => (id === specifier ? shimId : null),\n load: (id) => (id === shimId ? contents : null),\n }\n}\n"]}
@@ -5,6 +5,34 @@ import { render, renderHook } from "@gtkx/testing";
5
5
  // on a `Pressable` already work with no RN-flavoured wrapper: this subpath
6
6
  // re-exports that surface as-is, one import source for a consumer, plus the
7
7
  // one genuinely repeated workaround (see below).
8
+ //
9
+ // @gtkx/testing 1.0 semantics worth knowing before writing a new gtk test
10
+ // (audited against the whole suite; nothing here needed a source change,
11
+ // so it is recorded here rather than fixed):
12
+ //
13
+ // - Every query (`getByText`, `getByRole`, `screen.*`, …) only ever matches
14
+ // a MAPPED widget (`widget.getMapped()`) — a covered stack/sidebar page,
15
+ // an unpresented window, or anything with `visible={false}` is invisible
16
+ // to a query even though it is still in the tree. `{ hidden: true }`
17
+ // does NOT override this: it only widens the SEPARATE accessible-tree
18
+ // "hidden" filter `getByRole` applies on top. A widget that stays
19
+ // mounted-but-covered (createStackNavigator's inactive pages, an
20
+ // AdwNavigationSplitView pane hidden by collapse) is exactly this case —
21
+ // query only the active/visible one, the way every current test already
22
+ // does.
23
+ // - `userEvent.click`/`dblClick`/`tripleClick`/`pointer` now walk outward
24
+ // from the named widget through GTK's real claiming chain (the first
25
+ // Gtk.Button, list-box/flow-box row, or authored click gesture) instead
26
+ // of rc.4's "activate, else the nearest ancestor with any GestureClick".
27
+ // Unused anywhere in this repo's own tests today — every gesture/press
28
+ // test drives a real `zwlr_virtual_pointer_v1` or emits the GtkGesture
29
+ // signal directly (`fireEvent`) precisely because @gtkx/testing's click
30
+ // helpers still never produce a GdkEvent, targeting change or not.
31
+ // - Accessible reads (`toHaveAccessibleName`, `getByRole`'s `name`/`value`
32
+ // options, …) go through `gtk_test_accessible_check_*` with WAI-ARIA
33
+ // naming precedence and GTK mnemonic markers (`_`) stripped from any
34
+ // label with `use-underline` set. Not a concern for react-native-gtkx's
35
+ // own widgets today — nothing in the bridge sets `use-underline`.
8
36
  export * from "@gtkx/testing";
9
37
  export async function renderHookWithWindow(callback, options) {
10
38
  const { container: window } = await render(null);
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/testing/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,eAAe,CAAA;AAOlD,2EAA2E;AAC3E,0EAA0E;AAC1E,6EAA6E;AAC7E,2EAA2E;AAC3E,4EAA4E;AAC5E,iDAAiD;AACjD,cAAc,eAAe,CAAA;AA2B7B,MAAM,CAAC,KAAK,UAAU,oBAAoB,CACxC,QAAmC,EACnC,OAAkC;IAIlC,MAAM,EAAE,SAAS,EAAE,MAAM,EAAE,GAAG,MAAM,MAAM,CAAC,IAAI,CAAC,CAAA;IAChD,MAAM,IAAI,GAAG,MAAM,UAAU,CAC3B,QAAoC,EACpC,OAAmC,CACpC,CAAA;IACD,OAAO,EAAE,GAAG,IAAI,EAAE,MAAM,EAAE,CAAA;AAC5B,CAAC","sourcesContent":["import { render, renderHook } from \"@gtkx/testing\"\nimport type {\n RenderHookOptions,\n RenderHookResult,\n RenderResult,\n} from \"@gtkx/testing\"\n\n// react-native-gtkx/testing — @gtkx/testing's queries, render, renderHook,\n// fireEvent and userEvent already operate on the real GTK widget tree our\n// RN components render into, so `getByText` on a `Text` or `userEvent.click`\n// on a `Pressable` already work with no RN-flavoured wrapper: this subpath\n// re-exports that surface as-is, one import source for a consumer, plus the\n// one genuinely repeated workaround (see below).\nexport * from \"@gtkx/testing\"\n\n// RC4-WORKAROUND(renderhook-no-window): see docs/gtkx-rc4-notes.md\n// @gtkx/testing's renderHook() always mounts its test component into a bare\n// Gtk.Box, so a hook that reads the active toplevel (useWindowDimensions,\n// anything through Gtk.Window.getToplevels()) has nothing to read. render()\n// always creates and presents a harness window when no container is given,\n// regardless of what it renders — rendering null is enough to get one.\n\n/**\n * Like `renderHook`, but first creates and presents a harness window (via\n * `render(null)`), so window-dependent hooks have a toplevel to read.\n * Cleanup is automatic — @gtkx/testing tears down every active render\n * (including the harness window) after each test.\n */\nexport function renderHookWithWindow<Result>(\n callback: () => Result,\n options?: RenderHookOptions<undefined>,\n): Promise<\n RenderHookResult<Result, undefined> & { window: RenderResult[\"container\"] }\n>\nexport function renderHookWithWindow<Result, Props>(\n callback: (props: Props) => Result,\n options: RenderHookOptions<Props>,\n): Promise<\n RenderHookResult<Result, Props> & { window: RenderResult[\"container\"] }\n>\nexport async function renderHookWithWindow<Result, Props>(\n callback: (props?: Props) => Result,\n options?: RenderHookOptions<Props>,\n): Promise<\n RenderHookResult<Result, Props> & { window: RenderResult[\"container\"] }\n> {\n const { container: window } = await render(null)\n const hook = await renderHook(\n callback as (props: Props) => Result,\n options as RenderHookOptions<Props>,\n )\n return { ...hook, window }\n}\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/testing/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,eAAe,CAAA;AAOlD,2EAA2E;AAC3E,0EAA0E;AAC1E,6EAA6E;AAC7E,2EAA2E;AAC3E,4EAA4E;AAC5E,iDAAiD;AACjD,EAAE;AACF,0EAA0E;AAC1E,yEAAyE;AACzE,6CAA6C;AAC7C,EAAE;AACF,4EAA4E;AAC5E,2EAA2E;AAC3E,2EAA2E;AAC3E,uEAAuE;AACvE,wEAAwE;AACxE,oEAAoE;AACpE,mEAAmE;AACnE,2EAA2E;AAC3E,0EAA0E;AAC1E,UAAU;AACV,0EAA0E;AAC1E,uEAAuE;AACvE,0EAA0E;AAC1E,2EAA2E;AAC3E,yEAAyE;AACzE,yEAAyE;AACzE,0EAA0E;AAC1E,qEAAqE;AACrE,2EAA2E;AAC3E,uEAAuE;AACvE,uEAAuE;AACvE,0EAA0E;AAC1E,oEAAoE;AACpE,cAAc,eAAe,CAAA;AA2B7B,MAAM,CAAC,KAAK,UAAU,oBAAoB,CACxC,QAAmC,EACnC,OAAkC;IAIlC,MAAM,EAAE,SAAS,EAAE,MAAM,EAAE,GAAG,MAAM,MAAM,CAAC,IAAI,CAAC,CAAA;IAChD,MAAM,IAAI,GAAG,MAAM,UAAU,CAC3B,QAAoC,EACpC,OAAmC,CACpC,CAAA;IACD,OAAO,EAAE,GAAG,IAAI,EAAE,MAAM,EAAE,CAAA;AAC5B,CAAC","sourcesContent":["import { render, renderHook } from \"@gtkx/testing\"\nimport type {\n RenderHookOptions,\n RenderHookResult,\n RenderResult,\n} from \"@gtkx/testing\"\n\n// react-native-gtkx/testing — @gtkx/testing's queries, render, renderHook,\n// fireEvent and userEvent already operate on the real GTK widget tree our\n// RN components render into, so `getByText` on a `Text` or `userEvent.click`\n// on a `Pressable` already work with no RN-flavoured wrapper: this subpath\n// re-exports that surface as-is, one import source for a consumer, plus the\n// one genuinely repeated workaround (see below).\n//\n// @gtkx/testing 1.0 semantics worth knowing before writing a new gtk test\n// (audited against the whole suite; nothing here needed a source change,\n// so it is recorded here rather than fixed):\n//\n// - Every query (`getByText`, `getByRole`, `screen.*`, …) only ever matches\n// a MAPPED widget (`widget.getMapped()`) — a covered stack/sidebar page,\n// an unpresented window, or anything with `visible={false}` is invisible\n// to a query even though it is still in the tree. `{ hidden: true }`\n// does NOT override this: it only widens the SEPARATE accessible-tree\n// \"hidden\" filter `getByRole` applies on top. A widget that stays\n// mounted-but-covered (createStackNavigator's inactive pages, an\n// AdwNavigationSplitView pane hidden by collapse) is exactly this case —\n// query only the active/visible one, the way every current test already\n// does.\n// - `userEvent.click`/`dblClick`/`tripleClick`/`pointer` now walk outward\n// from the named widget through GTK's real claiming chain (the first\n// Gtk.Button, list-box/flow-box row, or authored click gesture) instead\n// of rc.4's \"activate, else the nearest ancestor with any GestureClick\".\n// Unused anywhere in this repo's own tests today — every gesture/press\n// test drives a real `zwlr_virtual_pointer_v1` or emits the GtkGesture\n// signal directly (`fireEvent`) precisely because @gtkx/testing's click\n// helpers still never produce a GdkEvent, targeting change or not.\n// - Accessible reads (`toHaveAccessibleName`, `getByRole`'s `name`/`value`\n// options, …) go through `gtk_test_accessible_check_*` with WAI-ARIA\n// naming precedence and GTK mnemonic markers (`_`) stripped from any\n// label with `use-underline` set. Not a concern for react-native-gtkx's\n// own widgets today — nothing in the bridge sets `use-underline`.\nexport * from \"@gtkx/testing\"\n\n// 1.2-WORKAROUND(renderhook-no-window): see docs/gtkx-1.2-notes.md\n// @gtkx/testing's renderHook() always mounts its test component into a bare\n// Gtk.Box, so a hook that reads the active toplevel (useWindowDimensions,\n// anything through Gtk.Window.getToplevels()) has nothing to read. render()\n// always creates and presents a harness window when no container is given,\n// regardless of what it renders — rendering null is enough to get one.\n\n/**\n * Like `renderHook`, but first creates and presents a harness window (via\n * `render(null)`), so window-dependent hooks have a toplevel to read.\n * Cleanup is automatic — @gtkx/testing tears down every active render\n * (including the harness window) after each test.\n */\nexport function renderHookWithWindow<Result>(\n callback: () => Result,\n options?: RenderHookOptions<undefined>,\n): Promise<\n RenderHookResult<Result, undefined> & { window: RenderResult[\"container\"] }\n>\nexport function renderHookWithWindow<Result, Props>(\n callback: (props: Props) => Result,\n options: RenderHookOptions<Props>,\n): Promise<\n RenderHookResult<Result, Props> & { window: RenderResult[\"container\"] }\n>\nexport async function renderHookWithWindow<Result, Props>(\n callback: (props?: Props) => Result,\n options?: RenderHookOptions<Props>,\n): Promise<\n RenderHookResult<Result, Props> & { window: RenderResult[\"container\"] }\n> {\n const { container: window } = await render(null)\n const hook = await renderHook(\n callback as (props: Props) => Result,\n options as RenderHookOptions<Props>,\n )\n return { ...hook, window }\n}\n"]}
@@ -105,7 +105,7 @@ export const resolvePlatformSpecifier = (source, importer, exists, options = {})
105
105
  // runtime-only check (a bare specifier assembled from string parts, so
106
106
  // Rollup's build-time graph walk never reaches it) is invisible to the
107
107
  // STATIC machinery every other gtkx import gets for free: `resolve.dedupe`
108
- // (RC4-WORKAROUND(runtime-dedupe) above) and `gtkx build`'s own asset
108
+ // (1.2-WORKAROUND(runtime-dedupe) above) and `gtkx build`'s own asset
109
109
  // pipeline for the native addon (`@gtkx/cli`'s `gtkx:native` plugin, which
110
110
  // rewrites every STATICALLY reachable `@gtkx/native` import onto the single
111
111
  // `dist/gtkx.node` it emits) both only ever see specifiers Rollup's graph
@@ -272,7 +272,7 @@ export const reactNativeGtkx = (options = {}) => {
272
272
  ],
273
273
  },
274
274
  resolve: {
275
- // RC4-WORKAROUND(runtime-dedupe): see docs/gtkx-rc4-notes.md
275
+ // 1.2-WORKAROUND(runtime-dedupe): see docs/gtkx-1.2-notes.md
276
276
  // The gtkx runtime and react are single-instance hosts: when the app
277
277
  // and react-native-gtkx resolve them from different node_modules
278
278
  // (file:-installed package, nested installs), two bundled copies
@@ -303,7 +303,7 @@ export const reactNativeGtkx = (options = {}) => {
303
303
  // `require("./gtkx.node")` — a path RELATIVE TO WHATEVER FILE
304
304
  // THE REWRITE LANDS IN, correct only when that file sits next to
305
305
  // the emitted `dist/gtkx.node` asset. The entry chunk is pinned
306
- // there already (`entryFileNames: "bundle.js"`, set by
306
+ // there already (`entryFileNames: "bundle.mjs"`, set by
307
307
  // `@gtkx/cli`'s own builder); a chunk placed one level down in
308
308
  // `assets/` breaks the SAME relative path
309
309
  // ("Cannot find module './gtkx.node'" — reproduced building
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/vite/index.ts"],"names":[],"mappings":"AAAA,yEAAyE;AACzE,4EAA4E;AAC5E,0EAA0E;AAC1E,2EAA2E;AAC3E,4BAA4B;AAC5B,EAAE;AACF,4EAA4E;AAC5E,8EAA8E;AAC9E,2EAA2E;AAC3E,2EAA2E;AAC3E,OAAO,EAAE,UAAU,EAAE,MAAM,SAAS,CAAA;AACpC,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAA;AAC3C,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,UAAU,EAAE,OAAO,EAAE,MAAM,WAAW,CAAA;AAEjE,OAAO,EACL,YAAY,EACZ,cAAc,EACd,mBAAmB,GAEpB,MAAM,qBAAqB,CAAA;AAE5B,0EAA0E;AAC1E,qCAAqC;AACrC,OAAO,EACL,oBAAoB,EACpB,eAAe,EACf,cAAc,GACf,MAAM,qBAAqB,CAAA;AAsB5B,MAAM,CAAC,MAAM,iBAAiB,GAAsB,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAA;AACvE,MAAM,CAAC,MAAM,kBAAkB,GAAsB,CAAC,KAAK,EAAE,IAAI,EAAE,KAAK,EAAE,IAAI,CAAC,CAAA;AAE/E,MAAM,iBAAiB,GAAG,mBAAmB,CAAA;AAE7C;;;;;;;;;GASG;AACH,MAAM,CAAC,MAAM,wB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AU,EAAE,OAAO,CAAC,CAAA;QACxE,CAAC;QAED,IAAI,CAAC,EAAE;YACL,IAAI,CAAC,EAAE,CAAC,UAAU,CAAC,sBAAsB,CAAC,EAAE,CAAC;gBAC3C,OAAO,IAAI,CAAA;YACb,CAAC;YACD,MAAM,SAAS,GAAG,EAAE,CAAC,KAAK,CAAC,sBAAsB,CAAC,MAAM,CAAC,CAAA;YACzD,OAAO,mBAAmB,IAAI,CAAC,SAAS,CAAC,qBAAqB,CAAC,SAAS,CAAC,CAAC,GAAG,CAAA;QAC/E,CAAC;KACF,CAAA;AACH,CAAC,CAAA;AAED,eAAe,eAAe,CAAA","sourcesContent":["// react-native-gtkx/vite — makes a gtkx project React Native compatible.\n// The gtkx CLI (dev and build) starts vite with an inline config that never\n// sets `configFile: false`, so vite picks up the project's vite.config.ts\n// from the root and merges it beneath the CLI config; this preset plugs in\n// there as a single plugin.\n//\n// vite loads the config's imported packages with BARE Node, so this subpath\n// (like ./metro and ./runner) must not contain EXTENSIONLESS relative imports\n// — the pure resolution helpers live here rather than in a sibling module,\n// and the one import that does cross a file boundary spells out its `.js`.\nimport { existsSync } from \"node:fs\"\nimport { createRequire } from \"node:module\"\nimport { dirname, extname, isAbsolute, resolve } from \"node:path\"\nimport type { Plugin } from \"vite\"\nimport {\n applyAliases,\n compileAliases,\n DEFAULT_ALIAS_TABLE,\n type AliasOverrides,\n} from \"../aliases/index.js\"\n\n// Re-exported so an app configuring `aliases` never has to reach past the\n// preset subpath it already imports.\nexport {\n CONFIGURABLE_ALIASES,\n DEFAULT_ALIASES,\n PLATFORM_ALIAS,\n} from \"../aliases/index.js\"\nexport type {\n AliasOverride,\n AliasOverrides,\n AliasPattern,\n AliasTable,\n CompiledAlias,\n} from \"../aliases/index.js\"\n\n// --- pure resolution logic (unit-tested directly) -----------------------\n\n/** Options shared by the preset factory and the pure resolver helpers. */\nexport type PlatformResolutionOptions = {\n /** Platform suffix priority, most specific first. Default: [\"linux\", \"native\"]. */\n platforms?: readonly string[]\n /** Source extensions tried for every platform suffix. Default: [\"tsx\", \"ts\", \"jsx\", \"js\"]. */\n extensions?: readonly string[]\n}\n\n/** Predicate the plugin injects as fs.existsSync; tests inject fakes. */\nexport type FileExists = (filePath: string) => boolean\n\nexport const DEFAULT_PLATFORMS: readonly string[] = [\"linux\", \"native\"]\nexport const DEFAULT_EXTENSIONS: readonly string[] = [\"tsx\", \"ts\", \"jsx\", \"js\"]\n\nconst REACT_NATIVE_GTKX = \"react-native-gtkx\"\n\n/**\n * Applies the DEFAULT alias table (../aliases/index.ts) to one specifier:\n * `react-native` and its subpaths onto `react-native-gtkx`, and the five\n * package substitutions onto their compat subpaths. Returns null for every\n * other specifier, including `react-native-gtkx` itself.\n *\n * Exported for tests and for apps driving vite by hand. The plugin does NOT\n * call it — the plugin resolves through the table its own `aliases` option\n * produced, so an app's deltas apply.\n */\nexport const rewriteReactNativeImport = (source: string): string | null =>\n applyAliases(DEFAULT_ALIAS_TABLE, source)\n\n/** Splits a vite specifier into its path part and its `?query` suffix. */\nexport const splitQuery = (\n source: string,\n): { specifier: string; query: string } => {\n const index = source.indexOf(\"?\")\n if (index === -1) {\n return { specifier: source, query: \"\" }\n }\n return { specifier: source.slice(0, index), query: source.slice(index) }\n}\n\nconst isRelative = (specifier: string): boolean =>\n specifier.startsWith(\"./\") || specifier.startsWith(\"../\")\n\n/**\n * Ordered platform suffixes, platform-major: every extension of the first\n * platform is tried before any extension of the next one\n * (`.linux.tsx`, `.linux.ts`, …, `.native.tsx`, …).\n */\nexport const platformSuffixes = (\n options: PlatformResolutionOptions = {},\n): string[] => {\n const platforms = options.platforms ?? DEFAULT_PLATFORMS\n const extensions = options.extensions ?? DEFAULT_EXTENSIONS\n return platforms.flatMap((platform) =>\n extensions.map((extension) => `.${platform}.${extension}`),\n )\n}\n\n/**\n * Candidate file paths for an extensionless base path, in priority order:\n * direct platform files first, then platform index files of a directory —\n * mirroring Metro, which exhausts file resolution before directory resolution.\n * The base file itself is not a candidate: when no platform file exists the\n * plugin bails out and the default resolver picks the base module.\n */\nexport const platformCandidates = (\n base: string,\n options: PlatformResolutionOptions = {},\n): string[] => {\n const suffixes = platformSuffixes(options)\n return [\n ...suffixes.map((suffix) => `${base}${suffix}`),\n ...suffixes.map((suffix) => `${base}/index${suffix}`),\n ]\n}\n\n// Source extensions Metro strips before trying platform variants: an\n// import of \"./useLinking.js\" (the TS-ESM style react-navigation and most\n// compiled RN libraries use) must still find useLinking.native.tsx /\n// useLinking.native.js — Metro resolves the BASE name platform-first, the\n// literal file is only the fallback.\nconst STRIPPABLE_EXTENSIONS = new Set([\".js\", \".jsx\", \".mjs\", \".ts\", \".tsx\"])\n\n/**\n * Metro platform-extension resolution for a single import: relative (or\n * absolute) specifiers that are extensionless — or carry a strippable\n * source extension — try platform candidates first; the first existing\n * candidate wins; the `?query` suffix is carried over. Returns null when\n * the import is out of scope or no platform file exists, handing the\n * import back to the default resolver.\n */\nexport const resolvePlatformSpecifier = (\n source: string,\n importer: string | undefined,\n exists: FileExists,\n options: PlatformResolutionOptions = {},\n): string | null => {\n if (importer === undefined || source.startsWith(\"\\0\")) {\n return null\n }\n const { specifier, query } = splitQuery(source)\n if (!isRelative(specifier) && !isAbsolute(specifier)) {\n return null\n }\n const extension = extname(specifier)\n if (extension !== \"\" && !STRIPPABLE_EXTENSIONS.has(extension)) {\n return null\n }\n const withExtension = isAbsolute(specifier)\n ? specifier\n : resolve(dirname(splitQuery(importer).specifier), specifier)\n const base =\n extension === \"\" ? withExtension : withExtension.slice(0, -extension.length)\n for (const candidate of platformCandidates(base, options)) {\n if (exists(candidate)) {\n return candidate + query\n }\n }\n return null\n}\n\n// The bridge's Adw probe (gtkx/bridge/adw.ts) needs to know, AT BUILD TIME,\n// whether this app's codegen store actually generated Adwaita bindings —\n// see the epic's own regression notes (.claude/epics/adw-optional/006). A\n// runtime-only check (a bare specifier assembled from string parts, so\n// Rollup's build-time graph walk never reaches it) is invisible to the\n// STATIC machinery every other gtkx import gets for free: `resolve.dedupe`\n// (RC4-WORKAROUND(runtime-dedupe) above) and `gtkx build`'s own asset\n// pipeline for the native addon (`@gtkx/cli`'s `gtkx:native` plugin, which\n// rewrites every STATICALLY reachable `@gtkx/native` import onto the single\n// `dist/gtkx.node` it emits) both only ever see specifiers Rollup's graph\n// walk actually visits. A second, independently-resolved copy of the native\n// addon double-initializes the gtkx runtime and aborts the process\n// (`g_log_set_writer_func() called multiple times`) — the exact failure\n// `runtime-dedupe` exists for, reached through a path dedupe cannot see.\n//\n// The fix: make the specifier a literal wherever Adw genuinely exists, so\n// it gets the SAME static treatment as every other gtkx import — and prune\n// it entirely wherever it does not, so `gtkx:undeclared-library` never\n// throws on the plain-GTK profile. `__GTKX_ADW_AVAILABLE__` is that lever:\n// a `define`d boolean CONSTANT (like `__DEV__` above), true only when this\n// app's OWN codegen store actually has an \"adw\" entry. The bridge guards\n// its probe on it; when the guard folds to a literal `false`, esbuild's\n// dead-code elimination removes the whole probe body — literal specifiers\n// and all — before Rollup's build ever walks the module graph, so the\n// undeclared-library plugin never sees them either.\n//\n// require.resolve, not a static/dynamic import: this file is a vite CONFIG\n// module (not part of the app's own bundle), so nothing here is subject to\n// the eslint bridge fence or Rollup's build-time graph at all — it is a\n// plain Node path lookup, run once while vite starts, mirroring exactly\n// what `gtkx:undeclared-library`'s own resolveId does with `this.resolve`.\nconst hasAdwStore = (root: string): boolean => {\n try {\n createRequire(resolve(root, \"package.json\")).resolve(\n [\"@gtkx\", \"gi\", \"adw\"].join(\"/\"),\n )\n return true\n } catch {\n return false\n }\n}\n\n// The two raw specifiers every Adw-dependent file in the bridge imports as a\n// LITERAL (gtkx/bridge/adw.ts's own probe, gtkx/bridge/adw-namespace.ts,\n// gtkx/bridge/widgets.generated.adw.ts) — needed as literals so `gtkx\n// build`'s real Rollup graph gives them the same static treatment as every\n// other gtkx import (see the doc above and .claude/epics/adw-optional/006.md).\n// That literal-ness has a cost `gtkx build` never pays but `gtkx dev` and\n// vitest do: both run every file through Vite's SSR module runner, which\n// resolves every import() call it can find in a file's text — including one\n// inside a dead `if (__GTKX_ADW_AVAILABLE__ === false)` branch — as part of\n// loading that FILE, before any of the file's own code (the runtime guard,\n// the try/catch around it) ever executes. `esbuild`'s dead-code elimination\n// is what makes the literal safe for `gtkx build`, and it is a real BUNDLE\n// optimization, not something the dev server or vitest's request-based\n// transform ever performs — so on a store with no \"Adw-1\" declared, every\n// one of those three files failed to even LOAD (a raw \"'./adw' is not\n// exported\" resolver error out of Vite's own builtin:vite-resolve, not any\n// message this package writes), which took the ENTIRE package down with it:\n// gtkx/bridge/adw.ts is an ordinary dependency of apis/host.gtkx.ts,\n// components/app-registry.tsx and common/navigation-stack.tsx, so nothing\n// that reaches any of those — which is most of the surface — could load\n// either. Found writing .claude/epics/adw-optional/005.md's own guard\n// tests: spike/plain-gtk's PRE-EXISTING alert/appearance GTK tests (003.md,\n// 004.md) failed the exact same way.\n//\n// Fixed the same way `gtkx:undeclared-library` itself is a resolveId hook,\n// not a source change: intercept these two specifiers HERE, before Vite's\n// own resolver (or gtkx's) ever sees them, whenever this app's store\n// genuinely lacks Adw — resolving them to a tiny virtual module that THROWS\n// ONLY WHEN ACTUALLY EVALUATED (i.e. lazily, exactly when something really\n// awaits the dynamic import, or — for the two eager importers above — when\n// something actually loads react-native-gtkx/adw). That is late enough for\n// gtkx/bridge/adw.ts's own `try { ... } catch { return null }` to catch it\n// as a genuine rejected promise, same as it always could for a specifier\n// Node's own loader could not find; for the two EAGER importers, it turns\n// what used to be a generic third-party resolver error into this package's\n// own named, actionable throw (the ONE message text below, since neither\n// eager importer has a call-site \"feature\" name available to it the way\n// requireAdwGi/requireAdwJsx's callers do — see gtkx/bridge/adw.ts). When\n// the store DOES have Adw, `hasAdwStore` is true and this hook falls\n// through to real resolution, unchanged: `gtkx build`'s dedupe and native-\n// asset rewrite still see a real, literal specifier.\nconst ADW_ONLY_SPECIFIERS = new Set([\"@gtkx/gi/adw\", \"@gtkx/jsx/adw\"])\nconst ADW_UNAVAILABLE_PREFIX = \"\\0gtkx-adw-unavailable:\"\nconst adwUnavailableMessage = (specifier: string): string =>\n `[react-native-gtkx] \"${specifier}\" requires \"Adw-1\" in this app's ` +\n \"gtkx.config.ts `libraries` — see docs/api.md (the plain-GTK profile) \" +\n \"for what needs Adw unconditionally and what falls back without it.\"\n\n// --- the vite plugin ----------------------------------------------------\n\nexport type ReactNativeGtkxOptions = PlatformResolutionOptions & {\n /**\n * Deltas over the preset's package aliases, keyed by package name — a\n * string target, a `{ pattern, replace }` rule, or `false` to drop one of\n * ours so the real package loads. Identical semantics to the Metro\n * preset's option of the same name: both compile the same table.\n * Invalid entries throw here, while the config is being read.\n */\n aliases?: AliasOverrides\n}\n\n/**\n * Vite plugin: aliases `react-native` (and subpaths) to `react-native-gtkx`\n * and resolves Metro-style platform extensions\n * (`.linux.tsx` → `.native.tsx` → base) for extensionless imports.\n */\nexport const reactNativeGtkx = (\n options: ReactNativeGtkxOptions = {},\n): Plugin => {\n // Throws on an unknown key, an overlapping pattern or an attempt to remove\n // the platform alias — at config load, naming what is valid.\n const aliases = compileAliases(options.aliases)\n return {\n name: \"react-native-gtkx:preset\",\n // Before vite's own resolver and the gtkx CLI plugins: the alias must win\n // over node resolution and platform files must win over the base file.\n enforce: \"pre\",\n\n config: (_config, env) => ({\n // `__DEV__` is part of the react-native runtime contract, not a Metro\n // detail: RN's own modules branch on it and so does every library\n // written against them (`@gorhom/bottom-sheet`'s logger and four of its\n // components read it at module scope). The Metro path gets it from the\n // app's stock RN preset; nothing supplied it on the vite path, so a\n // library that reads it crashed the bundle at startup with\n // \"ReferenceError: __DEV__ is not defined\" — found by building\n // spike/core-exports rather than by reading anything.\n //\n // vite's mode is the honest source: `gtkx dev` builds in development,\n // `gtkx build` in production, which is exactly the distinction RN draws.\n define: {\n __DEV__: JSON.stringify(env.mode !== \"production\"),\n // See hasAdwStore's doc above — process.cwd(), not _config.root:\n // `gtkx dev`/`gtkx build` always run from the app's own directory\n // (root defaults there too), and this must be resolvable before the\n // rest of the merged config is settled.\n __GTKX_ADW_AVAILABLE__: JSON.stringify(hasAdwStore(process.cwd())),\n },\n ssr: {\n // `gtkx dev` runs vite with ssr.external: true, which would hand\n // react-native-gtkx straight to node. Keep the package inside the\n // vite pipeline; noExternal wins over external: true.\n //\n // \"react-native\" must be listed too: with ssr.external: true vite\n // externalizes a bare import BEFORE the plugin pipeline whenever the\n // package resolves natively — and the real react-native (a Flow\n // codebase Node cannot parse) exists in RN monorepos. noExternal\n // forces the full plugin resolution, where the alias rewrites the\n // import to react-native-gtkx.\n // \"react-native-reanimated\" for the same reason as \"react-native\": an\n // app that also ships iOS/Android keeps the real package installed, it\n // resolves natively, and ssr.external: true would hand Node a codebase\n // built around a Babel plugin and a worklet runtime before the alias\n // ever gets a chance to rewrite the import.\n // \"react-native-worklets\" is the same case one package over — it is\n // where that worklet runtime actually lives since Reanimated 4.\n //\n // The rule those are instances of, stated once so the next alias does\n // not have to rediscover it: EVERY package name in the alias table must\n // be listed here. An alias is a resolveId hook, and a bare specifier\n // that vite externalizes never reaches one — so on the dev path the\n // alias silently loses to whatever is installed under the real name.\n // That is not hypothetical: an app that also ships iOS and Android has\n // all of them in node_modules, which is the case the alias exists to\n // serve. `react-native-gesture-handler` proved it — this list once held\n // three of the six names, its real package loaded, and it failed on an\n // extensionless internal import Node cannot resolve (found by running\n // the gallery's upstream-libraries section, which installs it).\n //\n // So the list is DERIVED rather than written out: it is exactly the\n // table's package names, and a name can no longer go missing from one\n // of the two places it has to appear.\n //\n // `aliases.names` includes the packages an app turned OFF with `false`,\n // deliberately. Dropping an alias means the REAL package loads, and the\n // real package imports `react-native` at module scope — an import that\n // only reaches the platform alias if Node never gets the package first.\n // Un-aliasing a package is therefore a reason to keep it inside the\n // pipeline, not a reason to let it out.\n noExternal: [\n REACT_NATIVE_GTKX,\n ...aliases.names,\n // @react-navigation is not aliased, but must go through the pipeline\n // too: it imports `react-native`, and an externalized copy resolves\n // that to the real Flow package (SyntaxError: Unexpected token\n // 'typeof') instead of our alias. Only bites on the dev path — a\n // production build inlines everything anyway.\n /^@react-navigation\\//,\n ],\n },\n resolve: {\n // RC4-WORKAROUND(runtime-dedupe): see docs/gtkx-rc4-notes.md\n // The gtkx runtime and react are single-instance hosts: when the app\n // and react-native-gtkx resolve them from different node_modules\n // (file:-installed package, nested installs), two bundled copies\n // double-init the runtime and GLib aborts. dedupe pins every copy to\n // the project's own resolution.\n dedupe: [\n \"@gtkx/css\",\n \"@gtkx/gi\",\n \"@gtkx/jsx\",\n \"@gtkx/native\",\n \"@gtkx/react\",\n \"@gtkx/runtime\",\n // react-navigation is context-based: two bundled copies of core\n // fail with \"couldn't find a navigation context\".\n \"@react-navigation/core\",\n \"@react-navigation/native\",\n \"react\",\n ],\n },\n build: {\n rolldownOptions: {\n output: {\n // A literal, code-split dynamic import (the Adw seam,\n // gtkx/bridge/adw.ts — see its own doc and 006 above) lands its\n // chunk under the Rolldown default `assets/[name]-[hash].js`\n // UNLESS told otherwise. `@gtkx/cli`'s own `gtkx:native` plugin\n // rewrites every reachable `@gtkx/native` import into\n // `require(\"./gtkx.node\")` — a path RELATIVE TO WHATEVER FILE\n // THE REWRITE LANDS IN, correct only when that file sits next to\n // the emitted `dist/gtkx.node` asset. The entry chunk is pinned\n // there already (`entryFileNames: \"bundle.js\"`, set by\n // `@gtkx/cli`'s own builder); a chunk placed one level down in\n // `assets/` breaks the SAME relative path\n // (\"Cannot find module './gtkx.node'\" — reproduced building\n // examples/gallery with the Adw seam's dynamic import made\n // literal). Keeping every chunk in `dist/` alongside the entry\n // and the addon sidesteps the mismatch instead of guessing at\n // gtkx's own relative-path assumption.\n chunkFileNames: \"[name]-[hash].js\",\n },\n },\n },\n }),\n\n async resolveId(source, importer) {\n // See ADW_ONLY_SPECIFIERS' own doc above: on a store with no \"Adw-1\",\n // resolving either of these for real fails the whole file that\n // imports them, before that file's own code (a runtime guard, a\n // try/catch) ever runs. Checked first, ahead of the alias table below\n // (neither specifier is in it).\n if (ADW_ONLY_SPECIFIERS.has(source) && !hasAdwStore(process.cwd())) {\n return ADW_UNAVAILABLE_PREFIX + source\n }\n // The app's table, not the default one: a package dropped with `false`\n // falls through to vite's own resolution and the real package loads.\n const aliased = applyAliases(aliases, source)\n if (aliased !== null) {\n const resolved = await this.resolve(aliased, importer, {\n skipSelf: true,\n })\n return resolved ?? aliased\n }\n return resolvePlatformSpecifier(source, importer, existsSync, options)\n },\n\n load(id) {\n if (!id.startsWith(ADW_UNAVAILABLE_PREFIX)) {\n return null\n }\n const specifier = id.slice(ADW_UNAVAILABLE_PREFIX.length)\n return `throw new Error(${JSON.stringify(adwUnavailableMessage(specifier))})`\n },\n }\n}\n\nexport default reactNativeGtkx\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/vite/index.ts"],"names":[],"mappings":"AAAA,yEAAyE;AACzE,4EAA4E;AAC5E,0EAA0E;AAC1E,2EAA2E;AAC3E,4BAA4B;AAC5B,EAAE;AACF,4EAA4E;AAC5E,8EAA8E;AAC9E,2EAA2E;AAC3E,2EAA2E;AAC3E,OAAO,EAAE,UAAU,EAAE,MAAM,SAAS,CAAA;AACpC,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAA;AAC3C,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,UAAU,EAAE,OAAO,EAAE,MAAM,WAAW,CAAA;AAEjE,OAAO,EACL,YAAY,EACZ,cAAc,EACd,mBAAmB,GAEpB,MAAM,qBAAqB,CAAA;AAE5B,0EAA0E;AAC1E,qCAAqC;AACrC,OAAO,EACL,oBAAoB,EACpB,eAAe,EACf,cAAc,GACf,MAAM,qBAAqB,CAAA;AAsB5B,MAAM,CAAC,MAAM,iBAAiB,GAAsB,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAA;AACvE,MAAM,CAAC,MAAM,kBAAkB,GAAsB,CAAC,KAAK,EAAE,IAAI,EAAE,KAAK,EAAE,IAAI,CAAC,CAAA;AAE/E,MAAM,iBAAiB,G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YAC5B,CAAC;YACD,OAAO,wBAAwB,CAAC,MAAM,EAAE,QAAQ,EAAE,UAAU,EAAE,OAAO,CAAC,CAAA;QACxE,CAAC;QAED,IAAI,CAAC,EAAE;YACL,IAAI,CAAC,EAAE,CAAC,UAAU,CAAC,sBAAsB,CAAC,EAAE,CAAC;gBAC3C,OAAO,IAAI,CAAA;YACb,CAAC;YACD,MAAM,SAAS,GAAG,EAAE,CAAC,KAAK,CAAC,sBAAsB,CAAC,MAAM,CAAC,CAAA;YACzD,OAAO,mBAAmB,IAAI,CAAC,SAAS,CAAC,qBAAqB,CAAC,SAAS,CAAC,CAAC,GAAG,CAAA;QAC/E,CAAC;KACF,CAAA;AACH,CAAC,CAAA;AAED,eAAe,eAAe,CAAA","sourcesContent":["// react-native-gtkx/vite — makes a gtkx project React Native compatible.\n// The gtkx CLI (dev and build) starts vite with an inline config that never\n// sets `configFile: false`, so vite picks up the project's vite.config.ts\n// from the root and merges it beneath the CLI config; this preset plugs in\n// there as a single plugin.\n//\n// vite loads the config's imported packages with BARE Node, so this subpath\n// (like ./metro and ./runner) must not contain EXTENSIONLESS relative imports\n// — the pure resolution helpers live here rather than in a sibling module,\n// and the one import that does cross a file boundary spells out its `.js`.\nimport { existsSync } from \"node:fs\"\nimport { createRequire } from \"node:module\"\nimport { dirname, extname, isAbsolute, resolve } from \"node:path\"\nimport type { Plugin } from \"vite\"\nimport {\n applyAliases,\n compileAliases,\n DEFAULT_ALIAS_TABLE,\n type AliasOverrides,\n} from \"../aliases/index.js\"\n\n// Re-exported so an app configuring `aliases` never has to reach past the\n// preset subpath it already imports.\nexport {\n CONFIGURABLE_ALIASES,\n DEFAULT_ALIASES,\n PLATFORM_ALIAS,\n} from \"../aliases/index.js\"\nexport type {\n AliasOverride,\n AliasOverrides,\n AliasPattern,\n AliasTable,\n CompiledAlias,\n} from \"../aliases/index.js\"\n\n// --- pure resolution logic (unit-tested directly) -----------------------\n\n/** Options shared by the preset factory and the pure resolver helpers. */\nexport type PlatformResolutionOptions = {\n /** Platform suffix priority, most specific first. Default: [\"linux\", \"native\"]. */\n platforms?: readonly string[]\n /** Source extensions tried for every platform suffix. Default: [\"tsx\", \"ts\", \"jsx\", \"js\"]. */\n extensions?: readonly string[]\n}\n\n/** Predicate the plugin injects as fs.existsSync; tests inject fakes. */\nexport type FileExists = (filePath: string) => boolean\n\nexport const DEFAULT_PLATFORMS: readonly string[] = [\"linux\", \"native\"]\nexport const DEFAULT_EXTENSIONS: readonly string[] = [\"tsx\", \"ts\", \"jsx\", \"js\"]\n\nconst REACT_NATIVE_GTKX = \"react-native-gtkx\"\n\n/**\n * Applies the DEFAULT alias table (../aliases/index.ts) to one specifier:\n * `react-native` and its subpaths onto `react-native-gtkx`, and the five\n * package substitutions onto their compat subpaths. Returns null for every\n * other specifier, including `react-native-gtkx` itself.\n *\n * Exported for tests and for apps driving vite by hand. The plugin does NOT\n * call it — the plugin resolves through the table its own `aliases` option\n * produced, so an app's deltas apply.\n */\nexport const rewriteReactNativeImport = (source: string): string | null =>\n applyAliases(DEFAULT_ALIAS_TABLE, source)\n\n/** Splits a vite specifier into its path part and its `?query` suffix. */\nexport const splitQuery = (\n source: string,\n): { specifier: string; query: string } => {\n const index = source.indexOf(\"?\")\n if (index === -1) {\n return { specifier: source, query: \"\" }\n }\n return { specifier: source.slice(0, index), query: source.slice(index) }\n}\n\nconst isRelative = (specifier: string): boolean =>\n specifier.startsWith(\"./\") || specifier.startsWith(\"../\")\n\n/**\n * Ordered platform suffixes, platform-major: every extension of the first\n * platform is tried before any extension of the next one\n * (`.linux.tsx`, `.linux.ts`, …, `.native.tsx`, …).\n */\nexport const platformSuffixes = (\n options: PlatformResolutionOptions = {},\n): string[] => {\n const platforms = options.platforms ?? DEFAULT_PLATFORMS\n const extensions = options.extensions ?? DEFAULT_EXTENSIONS\n return platforms.flatMap((platform) =>\n extensions.map((extension) => `.${platform}.${extension}`),\n )\n}\n\n/**\n * Candidate file paths for an extensionless base path, in priority order:\n * direct platform files first, then platform index files of a directory —\n * mirroring Metro, which exhausts file resolution before directory resolution.\n * The base file itself is not a candidate: when no platform file exists the\n * plugin bails out and the default resolver picks the base module.\n */\nexport const platformCandidates = (\n base: string,\n options: PlatformResolutionOptions = {},\n): string[] => {\n const suffixes = platformSuffixes(options)\n return [\n ...suffixes.map((suffix) => `${base}${suffix}`),\n ...suffixes.map((suffix) => `${base}/index${suffix}`),\n ]\n}\n\n// Source extensions Metro strips before trying platform variants: an\n// import of \"./useLinking.js\" (the TS-ESM style react-navigation and most\n// compiled RN libraries use) must still find useLinking.native.tsx /\n// useLinking.native.js — Metro resolves the BASE name platform-first, the\n// literal file is only the fallback.\nconst STRIPPABLE_EXTENSIONS = new Set([\".js\", \".jsx\", \".mjs\", \".ts\", \".tsx\"])\n\n/**\n * Metro platform-extension resolution for a single import: relative (or\n * absolute) specifiers that are extensionless — or carry a strippable\n * source extension — try platform candidates first; the first existing\n * candidate wins; the `?query` suffix is carried over. Returns null when\n * the import is out of scope or no platform file exists, handing the\n * import back to the default resolver.\n */\nexport const resolvePlatformSpecifier = (\n source: string,\n importer: string | undefined,\n exists: FileExists,\n options: PlatformResolutionOptions = {},\n): string | null => {\n if (importer === undefined || source.startsWith(\"\\0\")) {\n return null\n }\n const { specifier, query } = splitQuery(source)\n if (!isRelative(specifier) && !isAbsolute(specifier)) {\n return null\n }\n const extension = extname(specifier)\n if (extension !== \"\" && !STRIPPABLE_EXTENSIONS.has(extension)) {\n return null\n }\n const withExtension = isAbsolute(specifier)\n ? specifier\n : resolve(dirname(splitQuery(importer).specifier), specifier)\n const base =\n extension === \"\" ? withExtension : withExtension.slice(0, -extension.length)\n for (const candidate of platformCandidates(base, options)) {\n if (exists(candidate)) {\n return candidate + query\n }\n }\n return null\n}\n\n// The bridge's Adw probe (gtkx/bridge/adw.ts) needs to know, AT BUILD TIME,\n// whether this app's codegen store actually generated Adwaita bindings —\n// see the epic's own regression notes (.claude/epics/adw-optional/006). A\n// runtime-only check (a bare specifier assembled from string parts, so\n// Rollup's build-time graph walk never reaches it) is invisible to the\n// STATIC machinery every other gtkx import gets for free: `resolve.dedupe`\n// (1.2-WORKAROUND(runtime-dedupe) above) and `gtkx build`'s own asset\n// pipeline for the native addon (`@gtkx/cli`'s `gtkx:native` plugin, which\n// rewrites every STATICALLY reachable `@gtkx/native` import onto the single\n// `dist/gtkx.node` it emits) both only ever see specifiers Rollup's graph\n// walk actually visits. A second, independently-resolved copy of the native\n// addon double-initializes the gtkx runtime and aborts the process\n// (`g_log_set_writer_func() called multiple times`) — the exact failure\n// `runtime-dedupe` exists for, reached through a path dedupe cannot see.\n//\n// The fix: make the specifier a literal wherever Adw genuinely exists, so\n// it gets the SAME static treatment as every other gtkx import — and prune\n// it entirely wherever it does not, so `gtkx:undeclared-library` never\n// throws on the plain-GTK profile. `__GTKX_ADW_AVAILABLE__` is that lever:\n// a `define`d boolean CONSTANT (like `__DEV__` above), true only when this\n// app's OWN codegen store actually has an \"adw\" entry. The bridge guards\n// its probe on it; when the guard folds to a literal `false`, esbuild's\n// dead-code elimination removes the whole probe body — literal specifiers\n// and all — before Rollup's build ever walks the module graph, so the\n// undeclared-library plugin never sees them either.\n//\n// require.resolve, not a static/dynamic import: this file is a vite CONFIG\n// module (not part of the app's own bundle), so nothing here is subject to\n// the eslint bridge fence or Rollup's build-time graph at all — it is a\n// plain Node path lookup, run once while vite starts, mirroring exactly\n// what `gtkx:undeclared-library`'s own resolveId does with `this.resolve`.\nconst hasAdwStore = (root: string): boolean => {\n try {\n createRequire(resolve(root, \"package.json\")).resolve(\n [\"@gtkx\", \"gi\", \"adw\"].join(\"/\"),\n )\n return true\n } catch {\n return false\n }\n}\n\n// The two raw specifiers every Adw-dependent file in the bridge imports as a\n// LITERAL (gtkx/bridge/adw.ts's own probe, gtkx/bridge/adw-namespace.ts,\n// gtkx/bridge/widgets.generated.adw.ts) — needed as literals so `gtkx\n// build`'s real Rollup graph gives them the same static treatment as every\n// other gtkx import (see the doc above and .claude/epics/adw-optional/006.md).\n// That literal-ness has a cost `gtkx build` never pays but `gtkx dev` and\n// vitest do: both run every file through Vite's SSR module runner, which\n// resolves every import() call it can find in a file's text — including one\n// inside a dead `if (__GTKX_ADW_AVAILABLE__ === false)` branch — as part of\n// loading that FILE, before any of the file's own code (the runtime guard,\n// the try/catch around it) ever executes. `esbuild`'s dead-code elimination\n// is what makes the literal safe for `gtkx build`, and it is a real BUNDLE\n// optimization, not something the dev server or vitest's request-based\n// transform ever performs — so on a store with no \"Adw-1\" declared, every\n// one of those three files failed to even LOAD (a raw \"'./adw' is not\n// exported\" resolver error out of Vite's own builtin:vite-resolve, not any\n// message this package writes), which took the ENTIRE package down with it:\n// gtkx/bridge/adw.ts is an ordinary dependency of apis/host.gtkx.ts,\n// components/app-registry.tsx and common/navigation-stack.tsx, so nothing\n// that reaches any of those — which is most of the surface — could load\n// either. Found writing .claude/epics/adw-optional/005.md's own guard\n// tests: spike/plain-gtk's PRE-EXISTING alert/appearance GTK tests (003.md,\n// 004.md) failed the exact same way.\n//\n// Fixed the same way `gtkx:undeclared-library` itself is a resolveId hook,\n// not a source change: intercept these two specifiers HERE, before Vite's\n// own resolver (or gtkx's) ever sees them, whenever this app's store\n// genuinely lacks Adw — resolving them to a tiny virtual module that THROWS\n// ONLY WHEN ACTUALLY EVALUATED (i.e. lazily, exactly when something really\n// awaits the dynamic import, or — for the two eager importers above — when\n// something actually loads react-native-gtkx/adw). That is late enough for\n// gtkx/bridge/adw.ts's own `try { ... } catch { return null }` to catch it\n// as a genuine rejected promise, same as it always could for a specifier\n// Node's own loader could not find; for the two EAGER importers, it turns\n// what used to be a generic third-party resolver error into this package's\n// own named, actionable throw (the ONE message text below, since neither\n// eager importer has a call-site \"feature\" name available to it the way\n// requireAdwGi/requireAdwJsx's callers do — see gtkx/bridge/adw.ts). When\n// the store DOES have Adw, `hasAdwStore` is true and this hook falls\n// through to real resolution, unchanged: `gtkx build`'s dedupe and native-\n// asset rewrite still see a real, literal specifier.\nconst ADW_ONLY_SPECIFIERS = new Set([\"@gtkx/gi/adw\", \"@gtkx/jsx/adw\"])\nconst ADW_UNAVAILABLE_PREFIX = \"\\0gtkx-adw-unavailable:\"\nconst adwUnavailableMessage = (specifier: string): string =>\n `[react-native-gtkx] \"${specifier}\" requires \"Adw-1\" in this app's ` +\n \"gtkx.config.ts `libraries` — see docs/api.md (the plain-GTK profile) \" +\n \"for what needs Adw unconditionally and what falls back without it.\"\n\n// --- the vite plugin ----------------------------------------------------\n\nexport type ReactNativeGtkxOptions = PlatformResolutionOptions & {\n /**\n * Deltas over the preset's package aliases, keyed by package name — a\n * string target, a `{ pattern, replace }` rule, or `false` to drop one of\n * ours so the real package loads. Identical semantics to the Metro\n * preset's option of the same name: both compile the same table.\n * Invalid entries throw here, while the config is being read.\n */\n aliases?: AliasOverrides\n}\n\n/**\n * Vite plugin: aliases `react-native` (and subpaths) to `react-native-gtkx`\n * and resolves Metro-style platform extensions\n * (`.linux.tsx` → `.native.tsx` → base) for extensionless imports.\n */\nexport const reactNativeGtkx = (\n options: ReactNativeGtkxOptions = {},\n): Plugin => {\n // Throws on an unknown key, an overlapping pattern or an attempt to remove\n // the platform alias — at config load, naming what is valid.\n const aliases = compileAliases(options.aliases)\n return {\n name: \"react-native-gtkx:preset\",\n // Before vite's own resolver and the gtkx CLI plugins: the alias must win\n // over node resolution and platform files must win over the base file.\n enforce: \"pre\",\n\n config: (_config, env) => ({\n // `__DEV__` is part of the react-native runtime contract, not a Metro\n // detail: RN's own modules branch on it and so does every library\n // written against them (`@gorhom/bottom-sheet`'s logger and four of its\n // components read it at module scope). The Metro path gets it from the\n // app's stock RN preset; nothing supplied it on the vite path, so a\n // library that reads it crashed the bundle at startup with\n // \"ReferenceError: __DEV__ is not defined\" — found by building\n // spike/core-exports rather than by reading anything.\n //\n // vite's mode is the honest source: `gtkx dev` builds in development,\n // `gtkx build` in production, which is exactly the distinction RN draws.\n define: {\n __DEV__: JSON.stringify(env.mode !== \"production\"),\n // See hasAdwStore's doc above — process.cwd(), not _config.root:\n // `gtkx dev`/`gtkx build` always run from the app's own directory\n // (root defaults there too), and this must be resolvable before the\n // rest of the merged config is settled.\n __GTKX_ADW_AVAILABLE__: JSON.stringify(hasAdwStore(process.cwd())),\n },\n ssr: {\n // `gtkx dev` runs vite with ssr.external: true, which would hand\n // react-native-gtkx straight to node. Keep the package inside the\n // vite pipeline; noExternal wins over external: true.\n //\n // \"react-native\" must be listed too: with ssr.external: true vite\n // externalizes a bare import BEFORE the plugin pipeline whenever the\n // package resolves natively — and the real react-native (a Flow\n // codebase Node cannot parse) exists in RN monorepos. noExternal\n // forces the full plugin resolution, where the alias rewrites the\n // import to react-native-gtkx.\n // \"react-native-reanimated\" for the same reason as \"react-native\": an\n // app that also ships iOS/Android keeps the real package installed, it\n // resolves natively, and ssr.external: true would hand Node a codebase\n // built around a Babel plugin and a worklet runtime before the alias\n // ever gets a chance to rewrite the import.\n // \"react-native-worklets\" is the same case one package over — it is\n // where that worklet runtime actually lives since Reanimated 4.\n //\n // The rule those are instances of, stated once so the next alias does\n // not have to rediscover it: EVERY package name in the alias table must\n // be listed here. An alias is a resolveId hook, and a bare specifier\n // that vite externalizes never reaches one — so on the dev path the\n // alias silently loses to whatever is installed under the real name.\n // That is not hypothetical: an app that also ships iOS and Android has\n // all of them in node_modules, which is the case the alias exists to\n // serve. `react-native-gesture-handler` proved it — this list once held\n // three of the six names, its real package loaded, and it failed on an\n // extensionless internal import Node cannot resolve (found by running\n // the gallery's upstream-libraries section, which installs it).\n //\n // So the list is DERIVED rather than written out: it is exactly the\n // table's package names, and a name can no longer go missing from one\n // of the two places it has to appear.\n //\n // `aliases.names` includes the packages an app turned OFF with `false`,\n // deliberately. Dropping an alias means the REAL package loads, and the\n // real package imports `react-native` at module scope — an import that\n // only reaches the platform alias if Node never gets the package first.\n // Un-aliasing a package is therefore a reason to keep it inside the\n // pipeline, not a reason to let it out.\n noExternal: [\n REACT_NATIVE_GTKX,\n ...aliases.names,\n // @react-navigation is not aliased, but must go through the pipeline\n // too: it imports `react-native`, and an externalized copy resolves\n // that to the real Flow package (SyntaxError: Unexpected token\n // 'typeof') instead of our alias. Only bites on the dev path — a\n // production build inlines everything anyway.\n /^@react-navigation\\//,\n ],\n },\n resolve: {\n // 1.2-WORKAROUND(runtime-dedupe): see docs/gtkx-1.2-notes.md\n // The gtkx runtime and react are single-instance hosts: when the app\n // and react-native-gtkx resolve them from different node_modules\n // (file:-installed package, nested installs), two bundled copies\n // double-init the runtime and GLib aborts. dedupe pins every copy to\n // the project's own resolution.\n dedupe: [\n \"@gtkx/css\",\n \"@gtkx/gi\",\n \"@gtkx/jsx\",\n \"@gtkx/native\",\n \"@gtkx/react\",\n \"@gtkx/runtime\",\n // react-navigation is context-based: two bundled copies of core\n // fail with \"couldn't find a navigation context\".\n \"@react-navigation/core\",\n \"@react-navigation/native\",\n \"react\",\n ],\n },\n build: {\n rolldownOptions: {\n output: {\n // A literal, code-split dynamic import (the Adw seam,\n // gtkx/bridge/adw.ts — see its own doc and 006 above) lands its\n // chunk under the Rolldown default `assets/[name]-[hash].js`\n // UNLESS told otherwise. `@gtkx/cli`'s own `gtkx:native` plugin\n // rewrites every reachable `@gtkx/native` import into\n // `require(\"./gtkx.node\")` — a path RELATIVE TO WHATEVER FILE\n // THE REWRITE LANDS IN, correct only when that file sits next to\n // the emitted `dist/gtkx.node` asset. The entry chunk is pinned\n // there already (`entryFileNames: \"bundle.mjs\"`, set by\n // `@gtkx/cli`'s own builder); a chunk placed one level down in\n // `assets/` breaks the SAME relative path\n // (\"Cannot find module './gtkx.node'\" — reproduced building\n // examples/gallery with the Adw seam's dynamic import made\n // literal). Keeping every chunk in `dist/` alongside the entry\n // and the addon sidesteps the mismatch instead of guessing at\n // gtkx's own relative-path assumption.\n chunkFileNames: \"[name]-[hash].js\",\n },\n },\n },\n }),\n\n async resolveId(source, importer) {\n // See ADW_ONLY_SPECIFIERS' own doc above: on a store with no \"Adw-1\",\n // resolving either of these for real fails the whole file that\n // imports them, before that file's own code (a runtime guard, a\n // try/catch) ever runs. Checked first, ahead of the alias table below\n // (neither specifier is in it).\n if (ADW_ONLY_SPECIFIERS.has(source) && !hasAdwStore(process.cwd())) {\n return ADW_UNAVAILABLE_PREFIX + source\n }\n // The app's table, not the default one: a package dropped with `false`\n // falls through to vite's own resolution and the real package loads.\n const aliased = applyAliases(aliases, source)\n if (aliased !== null) {\n const resolved = await this.resolve(aliased, importer, {\n skipSelf: true,\n })\n return resolved ?? aliased\n }\n return resolvePlatformSpecifier(source, importer, existsSync, options)\n },\n\n load(id) {\n if (!id.startsWith(ADW_UNAVAILABLE_PREFIX)) {\n return null\n }\n const specifier = id.slice(ADW_UNAVAILABLE_PREFIX.length)\n return `throw new Error(${JSON.stringify(adwUnavailableMessage(specifier))})`\n },\n }\n}\n\nexport default reactNativeGtkx\n"]}
@@ -26,7 +26,7 @@ export type ReactNativeGtkxTestOptions = {
26
26
  /**
27
27
  * Run this project's test files serially. Default: false — window-resize
28
28
  * signal delivery races when several per-worker headless compositors run
29
- * at once (see docs/gtkx-rc4-notes.md); the suite this recipe is proven
29
+ * at once (see docs/gtkx-1.2-notes.md); the suite this recipe is proven
30
30
  * on takes seconds, so serial execution is the cheap fix. Override once a
31
31
  * suite is large enough for parallelism to matter more than that race.
32
32
  */
@@ -41,7 +41,7 @@ export type ReactNativeGtkxTestOptions = {
41
41
  * `test.projects` alongside a portable "unit" project.
42
42
  *
43
43
  * Requires a headless Wayland compositor on PATH (`sway` by default —
44
- * `apt install sway xwayland dbus`, see docs/getting-started.md) and
44
+ * `apt install sway xwayland dbus`, see docs/guide/toolchains.md) and
45
45
  * `gtkx codegen` to have already generated the project's `@gtkx/gi`
46
46
  * bindings — a bare `vitest run` does not trigger codegen itself, unlike
47
47
  * `gtkx dev`/`gtkx build`. A missing compositor or codegen store fails with
@@ -26,7 +26,7 @@ const SETUP_FILE = fileURLToPath(new URL("./setup.js", import.meta.url));
26
26
  * `test.projects` alongside a portable "unit" project.
27
27
  *
28
28
  * Requires a headless Wayland compositor on PATH (`sway` by default —
29
- * `apt install sway xwayland dbus`, see docs/getting-started.md) and
29
+ * `apt install sway xwayland dbus`, see docs/guide/toolchains.md) and
30
30
  * `gtkx codegen` to have already generated the project's `@gtkx/gi`
31
31
  * bindings — a bare `vitest run` does not trigger codegen itself, unlike
32
32
  * `gtkx dev`/`gtkx build`. A missing compositor or codegen store fails with
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/vitest/index.ts"],"names":[],"mappings":"AAAA,0EAA0E;AAC1E,0EAA0E;AAC1E,0EAA0E;AAC1E,wEAAwE;AACxE,uEAAuE;AACvE,mDAAmD;AACnD,EAAE;AACF,iEAAiE;AACjE,2EAA2E;AAC3E,yEAAyE;AACzE,4EAA4E;AAC5E,qEAAqE;AACrE,0EAA0E;AAC1E,sEAAsE;AACtE,OAAO,EAAE,aAAa,EAAE,GAAG,EAAE,MAAM,UAAU,CAAA;AAI7C,OAAO,EAAE,eAAe,EAA+B,MAAM,kBAAkB,CAAA;AAkC/E,MAAM,eAAe,GAAG,CAAC,wBAAwB,CAAC,CAAA;AAClD,MAAM,mBAAmB,GAAwB,CAAC,mBAAmB,CAAC,CAAA;AACtE,MAAM,UAAU,GAAG,aAAa,CAAC,IAAI,GAAG,CAAC,YAAY,EAAE,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAA;AAExE;;;;;;;;;;;;;;;GAeG;AACH,MAAM,CAAC,MAAM,mBAAmB,GAAG,KAAK,EACtC,UAAsC,EAAE,EACV,EAAE;IAChC,MAAM,IAAI,GAAG,CAAC,MAAM,MAAM,CAAC,cAAc,CAAC,CAAC,CAAC,OAAO,CAAA;IACnD,MAAM,OAAO,GAAa;QACxB,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC;QACtB,eAAe,CAAC,OAAO,CAAC,QAAQ,CAAC;KAClC,CAAA;IACD,OAAO;QACL,OAAO;QACP,IAAI,EAAE;YACJ,IAAI,EAAE,OAAO,CAAC,IAAI,IAAI,KAAK;YAC3B,OAAO,EAAE,OAAO,CAAC,OAAO,IAAI,eAAe;YAC3C,UAAU,EAAE,CAAC,UAAU,EAAE,GAAG,CAAC,OAAO,CAAC,UAAU,IAAI,EAAE,CAAC,CAAC;YACvD,MAAM,EAAE;gBACN,IAAI,EAAE;oBACJ,MAAM,EAAE,CAAC,GAAG,mBAAmB,EAAE,GAAG,CAAC,OAAO,CAAC,UAAU,IAAI,EAAE,CAAC,CAAC;iBAChE;aACF;YACD,eAAe,EAAE,OAAO,CAAC,eAAe,IAAI,KAAK;SAClD;KACF,CAAA;AACH,CAAC,CAAA;AAED,eAAe,mBAAmB,CAAA","sourcesContent":["// react-native-gtkx/vitest — the vitest recipe this repo's own test suite\n// runs on (see vitest.config.ts's \"gtk\" project), packaged for a consumer\n// app: the @gtkx/vitest headless-compositor plugin, the react-native-gtkx\n// vite preset (react-native alias + Metro-style platform extensions), a\n// default inline-deps list for RN libraries that import \"react-native\"\n// themselves, and the React act-environment setup.\n//\n// Self-contained like ./vite, ./metro and ./runner: a consumer's\n// vitest.config.ts is loaded the same way vite.config.ts is (vite's config\n// loader bundles only the user's own relative import graph; node_modules\n// imports stay bare specifiers, resolved afterwards by plain Node ESM) — so\n// this file must not contain extensionless relative imports. The one\n// relative import below carries an explicit \".js\" extension, which a real\n// sibling file on disk resolves under plain Node without any bundler.\nimport { fileURLToPath, URL } from \"node:url\"\nimport type { PluginOptions as GtkxPluginOptions } from \"@gtkx/vitest\"\nimport type { Plugin } from \"vite\"\nimport type { UserWorkspaceConfig } from \"vitest/config\"\nimport { reactNativeGtkx, type ReactNativeGtkxOptions } from \"../vite/index.js\"\n\n/**\n * Options accepted by {@link reactNativeGtkxTest}. Every field is optional\n * and falls back to the recipe this repo's own test suite runs on.\n */\nexport type ReactNativeGtkxTestOptions = {\n /** Vitest project name. Default: \"gtk\". */\n name?: string\n /** Test file glob(s), relative to the project root. Default: `[\"**\\/*.gtk.test.{ts,tsx}\"]`. */\n include?: string[]\n /** Headless compositor size/compositor, forwarded to @gtkx/vitest's plugin. */\n headless?: GtkxPluginOptions\n /** Metro-style platform resolution options, forwarded to the vite preset. */\n platform?: ReactNativeGtkxOptions\n /**\n * Extra `server.deps.inline` patterns, merged after the default\n * (`/@react-navigation/`). Needed for any node_modules library that\n * itself imports \"react-native\" — Vitest externalizes node_modules code\n * by default, a path the react-native alias cannot reach.\n */\n inlineDeps?: (string | RegExp)[]\n /** Extra setup files, run after the built-in React act-environment setup. */\n setupFiles?: string[]\n /**\n * Run this project's test files serially. Default: false — window-resize\n * signal delivery races when several per-worker headless compositors run\n * at once (see docs/gtkx-rc4-notes.md); the suite this recipe is proven\n * on takes seconds, so serial execution is the cheap fix. Override once a\n * suite is large enough for parallelism to matter more than that race.\n */\n fileParallelism?: boolean\n}\n\nconst DEFAULT_INCLUDE = [\"**/*.gtk.test.{ts,tsx}\"]\nconst DEFAULT_INLINE_DEPS: (string | RegExp)[] = [/@react-navigation/]\nconst SETUP_FILE = fileURLToPath(new URL(\"./setup.js\", import.meta.url))\n\n/**\n * A ready Vitest project config for react-native-gtkx component tests: the\n * headless Wayland compositor, the react-native alias and platform\n * extensions, and the React act-environment setup — the same recipe this\n * repo's own suite runs on. Use the result as a whole config\n * (`defineConfig(reactNativeGtkxTest())`) or as one entry of\n * `test.projects` alongside a portable \"unit\" project.\n *\n * Requires a headless Wayland compositor on PATH (`sway` by default —\n * `apt install sway xwayland dbus`, see docs/getting-started.md) and\n * `gtkx codegen` to have already generated the project's `@gtkx/gi`\n * bindings — a bare `vitest run` does not trigger codegen itself, unlike\n * `gtkx dev`/`gtkx build`. A missing compositor or codegen store fails with\n * a readable error (e.g. `Cannot find the \"sway\" executable on PATH`), not\n * a hang.\n */\nexport const reactNativeGtkxTest = async (\n options: ReactNativeGtkxTestOptions = {},\n): Promise<UserWorkspaceConfig> => {\n const gtkx = (await import(\"@gtkx/vitest\")).default\n const plugins: Plugin[] = [\n gtkx(options.headless),\n reactNativeGtkx(options.platform),\n ]\n return {\n plugins,\n test: {\n name: options.name ?? \"gtk\",\n include: options.include ?? DEFAULT_INCLUDE,\n setupFiles: [SETUP_FILE, ...(options.setupFiles ?? [])],\n server: {\n deps: {\n inline: [...DEFAULT_INLINE_DEPS, ...(options.inlineDeps ?? [])],\n },\n },\n fileParallelism: options.fileParallelism ?? false,\n },\n }\n}\n\nexport default reactNativeGtkxTest\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/vitest/index.ts"],"names":[],"mappings":"AAAA,0EAA0E;AAC1E,0EAA0E;AAC1E,0EAA0E;AAC1E,wEAAwE;AACxE,uEAAuE;AACvE,mDAAmD;AACnD,EAAE;AACF,iEAAiE;AACjE,2EAA2E;AAC3E,yEAAyE;AACzE,4EAA4E;AAC5E,qEAAqE;AACrE,0EAA0E;AAC1E,sEAAsE;AACtE,OAAO,EAAE,aAAa,EAAE,GAAG,EAAE,MAAM,UAAU,CAAA;AAI7C,OAAO,EAAE,eAAe,EAA+B,MAAM,kBAAkB,CAAA;AAkC/E,MAAM,eAAe,GAAG,CAAC,wBAAwB,CAAC,CAAA;AAClD,MAAM,mBAAmB,GAAwB,CAAC,mBAAmB,CAAC,CAAA;AACtE,MAAM,UAAU,GAAG,aAAa,CAAC,IAAI,GAAG,CAAC,YAAY,EAAE,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAA;AAExE;;;;;;;;;;;;;;;GAeG;AACH,MAAM,CAAC,MAAM,mBAAmB,GAAG,KAAK,EACtC,UAAsC,EAAE,EACV,EAAE;IAChC,MAAM,IAAI,GAAG,CAAC,MAAM,MAAM,CAAC,cAAc,CAAC,CAAC,CAAC,OAAO,CAAA;IACnD,MAAM,OAAO,GAAa;QACxB,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC;QACtB,eAAe,CAAC,OAAO,CAAC,QAAQ,CAAC;KAClC,CAAA;IACD,OAAO;QACL,OAAO;QACP,IAAI,EAAE;YACJ,IAAI,EAAE,OAAO,CAAC,IAAI,IAAI,KAAK;YAC3B,OAAO,EAAE,OAAO,CAAC,OAAO,IAAI,eAAe;YAC3C,UAAU,EAAE,CAAC,UAAU,EAAE,GAAG,CAAC,OAAO,CAAC,UAAU,IAAI,EAAE,CAAC,CAAC;YACvD,MAAM,EAAE;gBACN,IAAI,EAAE;oBACJ,MAAM,EAAE,CAAC,GAAG,mBAAmB,EAAE,GAAG,CAAC,OAAO,CAAC,UAAU,IAAI,EAAE,CAAC,CAAC;iBAChE;aACF;YACD,eAAe,EAAE,OAAO,CAAC,eAAe,IAAI,KAAK;SAClD;KACF,CAAA;AACH,CAAC,CAAA;AAED,eAAe,mBAAmB,CAAA","sourcesContent":["// react-native-gtkx/vitest — the vitest recipe this repo's own test suite\n// runs on (see vitest.config.ts's \"gtk\" project), packaged for a consumer\n// app: the @gtkx/vitest headless-compositor plugin, the react-native-gtkx\n// vite preset (react-native alias + Metro-style platform extensions), a\n// default inline-deps list for RN libraries that import \"react-native\"\n// themselves, and the React act-environment setup.\n//\n// Self-contained like ./vite, ./metro and ./runner: a consumer's\n// vitest.config.ts is loaded the same way vite.config.ts is (vite's config\n// loader bundles only the user's own relative import graph; node_modules\n// imports stay bare specifiers, resolved afterwards by plain Node ESM) — so\n// this file must not contain extensionless relative imports. The one\n// relative import below carries an explicit \".js\" extension, which a real\n// sibling file on disk resolves under plain Node without any bundler.\nimport { fileURLToPath, URL } from \"node:url\"\nimport type { PluginOptions as GtkxPluginOptions } from \"@gtkx/vitest\"\nimport type { Plugin } from \"vite\"\nimport type { UserWorkspaceConfig } from \"vitest/config\"\nimport { reactNativeGtkx, type ReactNativeGtkxOptions } from \"../vite/index.js\"\n\n/**\n * Options accepted by {@link reactNativeGtkxTest}. Every field is optional\n * and falls back to the recipe this repo's own test suite runs on.\n */\nexport type ReactNativeGtkxTestOptions = {\n /** Vitest project name. Default: \"gtk\". */\n name?: string\n /** Test file glob(s), relative to the project root. Default: `[\"**\\/*.gtk.test.{ts,tsx}\"]`. */\n include?: string[]\n /** Headless compositor size/compositor, forwarded to @gtkx/vitest's plugin. */\n headless?: GtkxPluginOptions\n /** Metro-style platform resolution options, forwarded to the vite preset. */\n platform?: ReactNativeGtkxOptions\n /**\n * Extra `server.deps.inline` patterns, merged after the default\n * (`/@react-navigation/`). Needed for any node_modules library that\n * itself imports \"react-native\" — Vitest externalizes node_modules code\n * by default, a path the react-native alias cannot reach.\n */\n inlineDeps?: (string | RegExp)[]\n /** Extra setup files, run after the built-in React act-environment setup. */\n setupFiles?: string[]\n /**\n * Run this project's test files serially. Default: false — window-resize\n * signal delivery races when several per-worker headless compositors run\n * at once (see docs/gtkx-1.2-notes.md); the suite this recipe is proven\n * on takes seconds, so serial execution is the cheap fix. Override once a\n * suite is large enough for parallelism to matter more than that race.\n */\n fileParallelism?: boolean\n}\n\nconst DEFAULT_INCLUDE = [\"**/*.gtk.test.{ts,tsx}\"]\nconst DEFAULT_INLINE_DEPS: (string | RegExp)[] = [/@react-navigation/]\nconst SETUP_FILE = fileURLToPath(new URL(\"./setup.js\", import.meta.url))\n\n/**\n * A ready Vitest project config for react-native-gtkx component tests: the\n * headless Wayland compositor, the react-native alias and platform\n * extensions, and the React act-environment setup — the same recipe this\n * repo's own suite runs on. Use the result as a whole config\n * (`defineConfig(reactNativeGtkxTest())`) or as one entry of\n * `test.projects` alongside a portable \"unit\" project.\n *\n * Requires a headless Wayland compositor on PATH (`sway` by default —\n * `apt install sway xwayland dbus`, see docs/guide/toolchains.md) and\n * `gtkx codegen` to have already generated the project's `@gtkx/gi`\n * bindings — a bare `vitest run` does not trigger codegen itself, unlike\n * `gtkx dev`/`gtkx build`. A missing compositor or codegen store fails with\n * a readable error (e.g. `Cannot find the \"sway\" executable on PATH`), not\n * a hang.\n */\nexport const reactNativeGtkxTest = async (\n options: ReactNativeGtkxTestOptions = {},\n): Promise<UserWorkspaceConfig> => {\n const gtkx = (await import(\"@gtkx/vitest\")).default\n const plugins: Plugin[] = [\n gtkx(options.headless),\n reactNativeGtkx(options.platform),\n ]\n return {\n plugins,\n test: {\n name: options.name ?? \"gtk\",\n include: options.include ?? DEFAULT_INCLUDE,\n setupFiles: [SETUP_FILE, ...(options.setupFiles ?? [])],\n server: {\n deps: {\n inline: [...DEFAULT_INLINE_DEPS, ...(options.inlineDeps ?? [])],\n },\n },\n fileParallelism: options.fileParallelism ?? false,\n },\n }\n}\n\nexport default reactNativeGtkxTest\n"]}