@multiplatform.one/config 9.17.0 → 10.0.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 (52) hide show
  1. package/design-lint.mjs +29 -6
  2. package/lib/index.js +4 -4
  3. package/lib/{storybook-BpaziEtP.js → storybook-BRZwQLAM.js} +150 -9
  4. package/lib/storybook.js +1 -1
  5. package/lib/{tamaguiWorkspacePaths-DR3dud79.js → tamaguiWorkspacePaths-BFMQNk1l.js} +8 -5
  6. package/lib/{vite-CgiDLR6V.js → vite-DaBjbGS0.js} +40 -52
  7. package/lib/vite.js +4 -4
  8. package/lib/{vitest-B2vcGrZM.js → vitest-NTT7k5jB.js} +97 -10
  9. package/lib/vitest.js +2 -2
  10. package/lib/{workspacePublicPackages-DN-1LPcH.js → workspacePublicPackages-z0fVhgGN.js} +121 -8
  11. package/lint.mjs +874 -52
  12. package/oxlint.mjs +26 -1
  13. package/package.json +6 -6
  14. package/press-lint.mjs +86 -5
  15. package/spec-registry.mjs +15 -0
  16. package/src/lint.spec.ts +696 -12
  17. package/src/movedDepAliases.spec.ts +73 -0
  18. package/src/movedDepAliases.ts +91 -0
  19. package/src/nativeBlockScoping.spec.ts +12 -14
  20. package/src/nativeOnlyDepStubs.spec.ts +178 -0
  21. package/src/nativeOnlyDepStubs.ts +215 -0
  22. package/src/noVoicelessText.rule.spec.ts +1 -1
  23. package/src/noVoicelessText.spec.ts +1 -1
  24. package/src/oxlint.spec.ts +5 -5
  25. package/src/phosphorNativeInk.spec.ts +17 -18
  26. package/src/phosphorTokenColor.spec.ts +35 -0
  27. package/src/phosphorTokenColor.ts +8 -5
  28. package/src/press-lint.spec.ts +64 -3
  29. package/src/react-native.config.cjs +9 -0
  30. package/src/shims/phosphorThemeInk.js +6 -1
  31. package/src/shims/svgTouchSound.web.js +23 -0
  32. package/src/singletonDepAliases.spec.ts +99 -14
  33. package/src/singletonDepAliases.ts +102 -7
  34. package/src/storybook.spec.ts +0 -3
  35. package/src/storybook.ts +17 -6
  36. package/src/vite.nativeEntries.spec.ts +21 -20
  37. package/src/vite.spec.ts +11 -20
  38. package/src/vite.ts +44 -68
  39. package/src/vitest.spec.ts +142 -4
  40. package/src/vitest.ts +106 -8
  41. package/types/movedDepAliases.d.ts +8 -0
  42. package/types/movedDepAliases.d.ts.map +1 -0
  43. package/types/nativeOnlyDepStubs.d.ts +41 -0
  44. package/types/nativeOnlyDepStubs.d.ts.map +1 -0
  45. package/types/phosphorTokenColor.d.ts.map +1 -1
  46. package/types/singletonDepAliases.d.ts +55 -3
  47. package/types/singletonDepAliases.d.ts.map +1 -1
  48. package/types/storybook.d.ts.map +1 -1
  49. package/types/vite.d.ts +10 -1
  50. package/types/vite.d.ts.map +1 -1
  51. package/types/vitest.d.ts +46 -1
  52. package/types/vitest.d.ts.map +1 -1
@@ -0,0 +1,73 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { describe, expect, it } from "vitest";
4
+ import { movedDepAliases } from "./movedDepAliases";
5
+ import { createStorybookViteConfig } from "./storybook";
6
+ import { createViteConfig } from "./vite";
7
+
8
+ const workspaceRoot = path.resolve(__dirname, "../../..");
9
+
10
+ describe("movedDepAliases", () => {
11
+ it("points react-native-svg's dead registry import at react-native-web's (FZ-10849)", () => {
12
+ // react-native-svg 15.16.0 and 15.16.1 both ship
13
+ // lib/module/lib/resolveAssetUri.web.js importing getAssetByID from
14
+ // @react-native/assets-registry/registry. React Native 0.88 renamed that
15
+ // package, so the specifier resolves nowhere and `storybook build` dies
16
+ // with "Rolldown failed to resolve import". Upstream fixed only the native
17
+ // twin, whose own comment says react-native no longer ships it.
18
+ const alias = movedDepAliases(workspaceRoot)["@react-native/assets-registry/registry"];
19
+ expect(alias, "the moved registry must be aliased").toBeTruthy();
20
+ expect(path.isAbsolute(alias)).toBe(true);
21
+ expect(fs.existsSync(alias)).toBe(true);
22
+ });
23
+
24
+ it("aims at the web registry, which is the one web assets are registered in", () => {
25
+ // Both react-native-web's and React Native's registries expose
26
+ // registerAsset and getAssetByID, but on web it is react-native-web's
27
+ // Image that registers, and it keeps the store on a
28
+ // Symbol.for("react-native-web.AssetRegistry") global so its CJS and ESM
29
+ // copies share one array. RN's registry would be a second, empty one and
30
+ // every numeric source would throw "asset with ID could not be found".
31
+ const alias = movedDepAliases(workspaceRoot)["@react-native/assets-registry/registry"];
32
+ expect(alias).toContain(path.join("react-native-web", "dist", "modules", "AssetRegistry"));
33
+ const source = fs.readFileSync(alias, "utf8");
34
+ expect(source).toContain("export function getAssetByID");
35
+ expect(source).toContain("react-native-web.AssetRegistry");
36
+ });
37
+
38
+ it("drops the entry while the package it names is still resolvable", () => {
39
+ // The alias is measured, not asserted: a tree that carries
40
+ // @react-native/assets-registry needs no alias, and shadowing a real
41
+ // package would be worse than the resolve error.
42
+ expect(() =>
43
+ require.resolve("@react-native/assets-registry/package.json", { paths: [workspaceRoot] }),
44
+ ).toThrow();
45
+ });
46
+
47
+ it("omits everything when nothing is installed", () => {
48
+ expect(movedDepAliases(path.join(workspaceRoot, "public", "config"))).toEqual(
49
+ expect.objectContaining({}),
50
+ );
51
+ for (const target of Object.values(movedDepAliases(path.join(workspaceRoot, "public")))) {
52
+ expect(fs.existsSync(target)).toBe(true);
53
+ }
54
+ });
55
+ });
56
+
57
+ describe("the factories that build a web bundle carry it", () => {
58
+ it("createStorybookViteConfig aliases it, which is where the build failed", () => {
59
+ const alias = (createStorybookViteConfig({ workspaceRoot }).resolve?.alias ?? {}) as Record<
60
+ string,
61
+ string
62
+ >;
63
+ expect(alias["@react-native/assets-registry/registry"]).toBeTruthy();
64
+ });
65
+
66
+ it("createViteConfig aliases it too, so a generated project is not left with it", () => {
67
+ const alias = (createViteConfig({ projectRoot: workspaceRoot }).resolve?.alias ?? {}) as Record<
68
+ string,
69
+ string
70
+ >;
71
+ expect(alias["@react-native/assets-registry/registry"]).toBeTruthy();
72
+ });
73
+ });
@@ -0,0 +1,91 @@
1
+ import fs from "node:fs";
2
+ import { createRequire } from "node:module";
3
+ import path from "node:path";
4
+
5
+ /**
6
+ * Modules a publisher still imports from a package that no longer exists.
7
+ *
8
+ * Different from `unexportedDepAliases`, which maps a subpath of a package
9
+ * that IS installed and simply never declared it. Here the whole package is
10
+ * gone from the tree, so there is nothing to deep-import: the build fails on
11
+ * resolution and no exports map or `--frozen-lockfile` install can help.
12
+ *
13
+ * FZ-10849. `react-native-svg` 15.16.0 and 15.16.1 both ship
14
+ * `lib/module/lib/resolveAssetUri.web.js` importing `getAssetByID` from
15
+ * `@react-native/assets-registry/registry`. React Native 0.88 renamed that
16
+ * package: the tree carries `@react-native/asset-utils` and RN re-exports the
17
+ * registry's two functions from its own `react-native/asset-registry`
18
+ * subpath. The old name resolves nowhere, and `storybook build` dies with
19
+ * `[vite]: Rolldown failed to resolve import "@react-native/assets-registry/
20
+ * registry"`. Upstream fixed only the native twin, whose own comment says
21
+ * "react-native no longer ships (0.87+)" while the web file next to it still
22
+ * imports it.
23
+ *
24
+ * The target is react-native-web's registry, not React Native's. Both expose
25
+ * `registerAsset` and `getAssetByID`, but on web it is react-native-web's
26
+ * `Image` that registers assets, and it keeps the store on a
27
+ * `Symbol.for("react-native-web.AssetRegistry")` global so its CJS and ESM
28
+ * copies share one array. Pointing at RN's registry instead would hand
29
+ * react-native-svg a second, permanently empty one, and every numeric
30
+ * `source` would throw "asset with ID could not be found".
31
+ *
32
+ * Each entry is measured rather than asserted: the alias applies only while
33
+ * the package it names is genuinely unresolvable and the replacement file is
34
+ * on disk. A react-native-svg release that fixes its own import, or a tree
35
+ * that still carries the old package, drops the entry instead of shadowing
36
+ * something real.
37
+ */
38
+ interface MovedModule {
39
+ /** The specifier the publisher still imports. */
40
+ specifier: string;
41
+ /** Package whose absence is what makes the move real. */
42
+ goneWith: string;
43
+ /** Package that holds the replacement, and the file inside it. */
44
+ nowIn: string;
45
+ file: string;
46
+ }
47
+
48
+ const MOVED_MODULES: readonly MovedModule[] = [
49
+ {
50
+ specifier: "@react-native/assets-registry/registry",
51
+ goneWith: "@react-native/assets-registry",
52
+ nowIn: "react-native-web",
53
+ file: "dist/modules/AssetRegistry/index.js",
54
+ },
55
+ ];
56
+
57
+ /**
58
+ * Vite `resolve.alias` entries for modules that moved out from under a
59
+ * publisher's import.
60
+ *
61
+ * @param root Directory whose `node_modules` the packages resolve from.
62
+ */
63
+ export function movedDepAliases(root: string = process.cwd()): Record<string, string> {
64
+ const requireFrom = createRequire(path.join(root, "package.json"));
65
+ const aliases: Record<string, string> = {};
66
+ for (const moved of MOVED_MODULES) {
67
+ if (resolvesPackage(moved.goneWith, root, requireFrom)) continue;
68
+ const host = resolvePackageDir(moved.nowIn, root, requireFrom);
69
+ if (!host) continue;
70
+ const target = path.join(host, moved.file);
71
+ if (fs.existsSync(target)) aliases[moved.specifier] = target;
72
+ }
73
+ return aliases;
74
+ }
75
+
76
+ function resolvesPackage(pkgName: string, root: string, requireFrom: NodeRequire): boolean {
77
+ return resolvePackageDir(pkgName, root, requireFrom) !== undefined;
78
+ }
79
+
80
+ function resolvePackageDir(
81
+ pkgName: string,
82
+ root: string,
83
+ requireFrom: NodeRequire,
84
+ ): string | undefined {
85
+ try {
86
+ return path.dirname(requireFrom.resolve(`${pkgName}/package.json`));
87
+ } catch {
88
+ const hoisted = path.join(root, "node_modules", ...pkgName.split("/"));
89
+ return fs.existsSync(path.join(hoisted, "package.json")) ? hoisted : undefined;
90
+ }
91
+ }
@@ -1,4 +1,4 @@
1
- import { beforeEach, describe, expect, it } from "vitest";
1
+ import { describe, expect, it } from "vitest";
2
2
  import { createViteConfig } from "./vite";
3
3
 
4
4
  interface NativePlugin {
@@ -10,7 +10,11 @@ interface NativePlugin {
10
10
  ) => Promise<{ code: string } | null> | { code: string } | null;
11
11
  }
12
12
 
13
- const nativeHook = globalThis as unknown as { __vxrnAddNativePlugins?: NativePlugin[] };
13
+ function nativePlugins<T>(config: ReturnType<typeof createViteConfig>): T[] {
14
+ return (config.plugins as Array<{ api?: { vxrnNative?: () => T } } | undefined>)
15
+ .flat()
16
+ .flatMap((plugin) => (plugin?.api?.vxrnNative ? [plugin.api.vxrnNative()] : []));
17
+ }
14
18
 
15
19
  const fixture = `
16
20
  function run() {
@@ -33,22 +37,17 @@ function runFunctionScoped(code: string): unknown[] {
33
37
  return new Function(`${functionScoped}\nreturn run();`)() as unknown[];
34
38
  }
35
39
 
36
- function blockScopingPlugin(): NativePlugin | undefined {
37
- return nativeHook.__vxrnAddNativePlugins?.find((p) => p.name === "vxrn-native-block-scoping");
40
+ function blockScopingPlugin(config: ReturnType<typeof createViteConfig>): NativePlugin | undefined {
41
+ return nativePlugins<NativePlugin>(config).find((p) => p.name === "vxrn-native-block-scoping");
38
42
  }
39
43
 
40
- beforeEach(() => {
41
- delete nativeHook.__vxrnAddNativePlugins;
42
- });
43
-
44
44
  describe("native block scoping (FZ-8895)", () => {
45
45
  it("models the Hermes bug: a function-scoped run of the raw fixture sees only last values", () => {
46
46
  expect(runFunctionScoped(fixture)).toEqual([3, 3, 3, 3, 3, 3, "b", "b"]);
47
47
  });
48
48
 
49
49
  it("lowers let/const in a production native chunk so loop closures keep per-iteration values", async () => {
50
- createViteConfig({ one: true });
51
- const plugin = blockScopingPlugin();
50
+ const plugin = blockScopingPlugin(createViteConfig({ one: true }));
52
51
  expect(plugin).toBeDefined();
53
52
  plugin!.options?.({});
54
53
  const result = await plugin!.renderChunk!(fixture, { fileName: "main.jsbundle" });
@@ -57,8 +56,7 @@ describe("native block scoping (FZ-8895)", () => {
57
56
  });
58
57
 
59
58
  it("leaves dev-engine chunks alone so Fast Refresh stays fast", async () => {
60
- createViteConfig({ one: true });
61
- const plugin = blockScopingPlugin()!;
59
+ const plugin = blockScopingPlugin(createViteConfig({ one: true }))!;
62
60
  plugin.options?.({ experimental: { devMode: { host: "localhost", port: 8081 } } });
63
61
  expect(await plugin.renderChunk!(fixture, { fileName: "main.jsbundle" })).toBeNull();
64
62
  });
@@ -72,7 +70,7 @@ describe("native block scoping (FZ-8895)", () => {
72
70
  });
73
71
 
74
72
  it("can be turned off with nativeFixes.blockScoping: false", () => {
75
- createViteConfig({ one: true, nativeFixes: { blockScoping: false } });
76
- expect(blockScopingPlugin()).toBeUndefined();
73
+ const config = createViteConfig({ one: true, nativeFixes: { blockScoping: false } });
74
+ expect(blockScopingPlugin(config)).toBeUndefined();
77
75
  });
78
76
  });
@@ -0,0 +1,178 @@
1
+ import fs from "node:fs";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+ import { afterAll, beforeAll, describe, expect, it } from "vitest";
5
+ import {
6
+ nativeOnlyDepResolver,
7
+ nativeOnlyDepStubOptimizerPlugin,
8
+ nativeOnlyDepStubs,
9
+ } from "./nativeOnlyDepStubs";
10
+
11
+ const soundModule =
12
+ "import { TurboModuleRegistry } from 'react-native';\n" +
13
+ "export default TurboModuleRegistry.getEnforcing('RNSVGSoundModule');\n";
14
+
15
+ /**
16
+ * Builds a throwaway tree carrying react-native-svg 15.16.0's fabric sound
17
+ * module and a react-native-web entry in its published shape. Asserting
18
+ * against the real tree would pass for the wrong reason the moment either
19
+ * package changes under us.
20
+ */
21
+ function writeFixture(
22
+ root: string,
23
+ { svg = true, webTurboModules = false }: { svg?: boolean; webTurboModules?: boolean } = {},
24
+ ) {
25
+ fs.mkdirSync(root, { recursive: true });
26
+ fs.writeFileSync(path.join(root, "package.json"), JSON.stringify({ name: "fixture-root" }));
27
+
28
+ const webDir = path.join(root, "node_modules", "react-native-web");
29
+ fs.mkdirSync(path.join(webDir, "dist"), { recursive: true });
30
+ fs.writeFileSync(
31
+ path.join(webDir, "package.json"),
32
+ JSON.stringify({ name: "react-native-web", version: "0.21.2", main: "dist/index.js" }),
33
+ );
34
+ fs.writeFileSync(
35
+ path.join(webDir, "dist", "index.js"),
36
+ "export { default as View } from './exports/View';\n" +
37
+ "export { default as NativeModules } from './exports/NativeModules';\n" +
38
+ (webTurboModules
39
+ ? "export { default as TurboModuleRegistry } from './exports/TurboModuleRegistry';\n"
40
+ : ""),
41
+ );
42
+ if (!svg) return;
43
+
44
+ const svgDir = path.join(root, "node_modules", "react-native-svg");
45
+ fs.mkdirSync(path.join(svgDir, "lib", "module", "fabric"), { recursive: true });
46
+ fs.mkdirSync(path.join(svgDir, "lib", "module", "lib"), { recursive: true });
47
+ fs.writeFileSync(
48
+ path.join(svgDir, "package.json"),
49
+ JSON.stringify({
50
+ name: "react-native-svg",
51
+ version: "15.16.0",
52
+ main: "lib/commonjs/index.js",
53
+ module: "lib/module/index.js",
54
+ }),
55
+ );
56
+ fs.writeFileSync(
57
+ path.join(svgDir, "lib", "module", "fabric", "NativeSvgSoundModule.js"),
58
+ soundModule,
59
+ );
60
+ fs.writeFileSync(
61
+ path.join(svgDir, "lib", "module", "lib", "SvgTouchableMixin.js"),
62
+ "export const SvgTouchableMixin = {};\n",
63
+ );
64
+ }
65
+
66
+ function importerIn(root: string) {
67
+ return path.join(
68
+ root,
69
+ "node_modules",
70
+ "react-native-svg",
71
+ "lib",
72
+ "module",
73
+ "lib",
74
+ "SvgTouchableMixin.js",
75
+ );
76
+ }
77
+
78
+ describe("nativeOnlyDepStubs", () => {
79
+ // realpath: macOS /var is a symlink to /private/var and require.resolve
80
+ // reports the resolved path.
81
+ const root = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "native-only-dep-stubs-")));
82
+
83
+ beforeAll(() => writeFixture(root));
84
+ afterAll(() => fs.rmSync(root, { recursive: true, force: true }));
85
+
86
+ it("positive control: the module needs a binding the web runtime has not got", () => {
87
+ // Without this the whole suite could be green around a stub that guards
88
+ // nothing — the shape it exists for is this import against those exports.
89
+ const shipped = fs.readFileSync(
90
+ path.join(
91
+ root,
92
+ "node_modules",
93
+ "react-native-svg",
94
+ "lib",
95
+ "module",
96
+ "fabric",
97
+ "NativeSvgSoundModule.js",
98
+ ),
99
+ "utf8",
100
+ );
101
+ const web = fs.readFileSync(
102
+ path.join(root, "node_modules", "react-native-web", "dist", "index.js"),
103
+ "utf8",
104
+ );
105
+ expect(shipped).toMatch(/import \{ TurboModuleRegistry \} from 'react-native'/);
106
+ expect(web).not.toMatch(/TurboModuleRegistry/);
107
+ });
108
+
109
+ it("resolves the publisher's relative specifier to a stub that exists", () => {
110
+ const resolve = nativeOnlyDepResolver(root);
111
+ const stub = resolve?.("../fabric/NativeSvgSoundModule", importerIn(root));
112
+
113
+ expect(stub).toMatch(/shims[\\/]svgTouchSound\.web\.js$/);
114
+ expect(fs.existsSync(stub!)).toBe(true);
115
+ // SvgTouchableMixin calls `.playTouchSound()` off the default export, so a
116
+ // stub without it would crash instead of staying silent.
117
+ expect(fs.readFileSync(stub!, "utf8")).toMatch(/playTouchSound\(\)\s*\{\}/);
118
+ });
119
+
120
+ it("matches the extension spellings a bundler can hand the resolver", () => {
121
+ const resolve = nativeOnlyDepResolver(root);
122
+ const importer = importerIn(root);
123
+
124
+ expect(resolve?.("../fabric/NativeSvgSoundModule.js", importer)).toBeTruthy();
125
+ expect(resolve?.("../fabric/NativeSvgSoundModule.ts", importer)).toBeTruthy();
126
+ });
127
+
128
+ it("declines the same specifier from outside the owning package", () => {
129
+ const resolve = nativeOnlyDepResolver(root);
130
+
131
+ // The specifier is relative, so only the importer says whose it is.
132
+ expect(resolve?.("../fabric/NativeSvgSoundModule", path.join(root, "app", "Screen.tsx"))).toBe(
133
+ null,
134
+ );
135
+ expect(resolve?.("../fabric/NativeSvgSoundModule", undefined)).toBe(null);
136
+ });
137
+
138
+ it("declines the package's other modules", () => {
139
+ const resolve = nativeOnlyDepResolver(root);
140
+
141
+ expect(resolve?.("../fabric/SvgViewNativeComponent", importerIn(root))).toBe(null);
142
+ expect(resolve?.("react-native", importerIn(root))).toBe(null);
143
+ });
144
+
145
+ it("emits nothing once the web runtime exports the binding", () => {
146
+ const healed = fs.realpathSync(
147
+ fs.mkdtempSync(path.join(os.tmpdir(), "native-only-dep-stubs-healed-")),
148
+ );
149
+ writeFixture(healed, { webTurboModules: true });
150
+ try {
151
+ expect(nativeOnlyDepStubs(healed)).toEqual([]);
152
+ expect(nativeOnlyDepResolver(healed)).toBeUndefined();
153
+ } finally {
154
+ fs.rmSync(healed, { recursive: true, force: true });
155
+ }
156
+ });
157
+
158
+ it("emits nothing when the package is not installed", () => {
159
+ const bare = fs.realpathSync(
160
+ fs.mkdtempSync(path.join(os.tmpdir(), "native-only-dep-stubs-bare-")),
161
+ );
162
+ writeFixture(bare, { svg: false });
163
+ try {
164
+ expect(nativeOnlyDepStubs(bare)).toEqual([]);
165
+ } finally {
166
+ fs.rmSync(bare, { recursive: true, force: true });
167
+ }
168
+ });
169
+
170
+ it("hands the dep optimizer a plugin with no vite-only fields", () => {
171
+ // rolldown receives this object directly, not through vite's plugin
172
+ // normalization, so `enforce` and friends have no meaning there.
173
+ const plugin = nativeOnlyDepStubOptimizerPlugin(root);
174
+
175
+ expect(Object.keys(plugin!).sort()).toEqual(["name", "resolveId"]);
176
+ expect(plugin!.resolveId("../fabric/NativeSvgSoundModule", importerIn(root))).toBeTruthy();
177
+ });
178
+ });
@@ -0,0 +1,215 @@
1
+ import fs from "node:fs";
2
+ import { createRequire } from "node:module";
3
+ import path from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ import type { Plugin } from "vite";
6
+
7
+ /**
8
+ * Modules a package ships for a native runtime only, which its own web graph
9
+ * still imports.
10
+ *
11
+ * Different from `movedDepAliases` (the package the publisher imports is gone
12
+ * from the tree) and from `unexportedDepAliases` (the subpath is there but
13
+ * undeclared). Here the file resolves perfectly well; what it imports cannot
14
+ * exist on web, because `react-native` aliases to `react-native-web` and
15
+ * react-native-web implements no TurboModules. Repointing that import would be
16
+ * a lie. The module itself is dead code behind a `Platform.OS` branch, so the
17
+ * honest move is to drop it and say why.
18
+ *
19
+ * FZ-10849. `react-native-svg` 15.16.0 added
20
+ * `fabric/NativeSvgSoundModule` for the Android touch sound and reaches
21
+ * it from `SvgTouchableMixin` through a `require()` nested in
22
+ * `if (Platform.OS === "android")`. Rolldown hoists that require into a static
23
+ * import, so `TurboModuleRegistry` becomes a hard requirement of the web
24
+ * graph. `storybook build` survives it (Rollup shims the missing export and
25
+ * prints `[SHIMMED_EXPORT]`); the dev dep-optimizer does not, and fails the
26
+ * whole optimization, so no dev server starts at all.
27
+ *
28
+ * Each entry is measured, not asserted. A stub is wired up only while the
29
+ * package really ships the module, the module really takes the binding off
30
+ * `react-native`, and the web runtime really does not export it. A
31
+ * react-native-svg release that adds a web twin, or a react-native-web that
32
+ * grows the binding, drops the entry instead of shadowing something live.
33
+ */
34
+ interface NativeOnlyModule {
35
+ /** Package whose web graph reaches the module. */
36
+ pkg: string;
37
+ /** Paths inside that package where the module ships. */
38
+ flavours: readonly string[];
39
+ /** The specifier its sibling imports it by, extension optional. */
40
+ specifier: string;
41
+ /** The `react-native` binding it needs and web cannot supply. */
42
+ binding: string;
43
+ /** Replacement, in `src/shims`. */
44
+ stub: string;
45
+ }
46
+
47
+ const NATIVE_ONLY_MODULES: readonly NativeOnlyModule[] = [
48
+ {
49
+ pkg: "react-native-svg",
50
+ flavours: [
51
+ "lib/module/fabric/NativeSvgSoundModule.js",
52
+ "lib/commonjs/fabric/NativeSvgSoundModule.js",
53
+ "src/fabric/NativeSvgSoundModule.ts",
54
+ ],
55
+ specifier: "../fabric/NativeSvgSoundModule",
56
+ binding: "TurboModuleRegistry",
57
+ stub: "svgTouchSound.web.js",
58
+ },
59
+ ];
60
+
61
+ /** The web stand-in for `react-native`, whose exports decide every entry. */
62
+ const webRuntime = { pkg: "react-native-web", entry: "dist/index.js" };
63
+
64
+ export interface NativeOnlyDepStub {
65
+ /** Path fragment that proves an importer belongs to the owning package. */
66
+ marker: string;
67
+ /** Every spelling of the specifier a bundler can hand the resolver. */
68
+ specifiers: readonly string[];
69
+ /** Absolute path of the replacement module. */
70
+ stub: string;
71
+ }
72
+
73
+ /** Resolves a package's native-only module to its web stub, or null. */
74
+ export type NativeOnlyDepResolver = (id: string, importer?: string) => string | null;
75
+
76
+ /**
77
+ * Entries whose breakage is real in this tree, with their stub resolved.
78
+ *
79
+ * @param root Directory whose `node_modules` the packages resolve from.
80
+ */
81
+ export function nativeOnlyDepStubs(root: string = process.cwd()): NativeOnlyDepStub[] {
82
+ const requireFrom = createRequire(path.join(root, "package.json"));
83
+ const webExports = runtimeExports(root, requireFrom);
84
+ const stubs: NativeOnlyDepStub[] = [];
85
+ for (const entry of NATIVE_ONLY_MODULES) {
86
+ if (!webExports || webExports.has(entry.binding)) continue;
87
+ const pkgDir = resolvePackageDir(entry.pkg, root, requireFrom);
88
+ if (!pkgDir) continue;
89
+ const shipped = entry.flavours
90
+ .map((flavour) => path.join(pkgDir, flavour))
91
+ .filter((file) => fs.existsSync(file));
92
+ if (!shipped.some((file) => importsBinding(file, entry.binding))) continue;
93
+ const stub = stubFile(entry.stub);
94
+ if (!stub) continue;
95
+ stubs.push({
96
+ marker: `${path.sep}${entry.pkg}${path.sep}`,
97
+ specifiers: [entry.specifier, `${entry.specifier}.js`, `${entry.specifier}.ts`],
98
+ stub,
99
+ });
100
+ }
101
+ return stubs;
102
+ }
103
+
104
+ /**
105
+ * The resolver behind both plugins below, or undefined when nothing in this
106
+ * tree measures as broken.
107
+ */
108
+ export function nativeOnlyDepResolver(
109
+ root: string = process.cwd(),
110
+ ): NativeOnlyDepResolver | undefined {
111
+ const stubs = nativeOnlyDepStubs(root);
112
+ if (!stubs.length) return undefined;
113
+ return (id, importer) => {
114
+ if (!importer) return null;
115
+ for (const stub of stubs) {
116
+ if (!importer.includes(stub.marker)) continue;
117
+ if (stub.specifiers.includes(id)) return stub.stub;
118
+ }
119
+ return null;
120
+ };
121
+ }
122
+
123
+ /**
124
+ * Vite plugin for the transform pipeline (`vite build`, `storybook build`).
125
+ *
126
+ * `enforce: "pre"` is load-bearing: a normal-order plugin resolves after
127
+ * `vite:resolve`, which has already turned the relative specifier into a real
128
+ * file by then.
129
+ */
130
+ export function nativeOnlyDepStubPlugin(root: string = process.cwd()): Plugin | undefined {
131
+ const resolver = nativeOnlyDepResolver(root);
132
+ if (!resolver) return undefined;
133
+ return {
134
+ name: "multiplatform-native-only-dep-stubs",
135
+ enforce: "pre",
136
+ resolveId(id, importer) {
137
+ return resolver(id, importer);
138
+ },
139
+ };
140
+ }
141
+
142
+ /**
143
+ * The same resolver for the dev dep-optimizer, which runs its own rolldown
144
+ * build that sees neither user plugins nor `resolve.alias` for a relative
145
+ * specifier — only `optimizeDeps.rolldownOptions.plugins`. Carries no vite-only
146
+ * fields, since rolldown receives this object directly.
147
+ */
148
+ export function nativeOnlyDepStubOptimizerPlugin(
149
+ root: string = process.cwd(),
150
+ ): { name: string; resolveId: NativeOnlyDepResolver } | undefined {
151
+ const resolver = nativeOnlyDepResolver(root);
152
+ if (!resolver) return undefined;
153
+ return { name: "multiplatform-native-only-dep-stubs", resolveId: resolver };
154
+ }
155
+
156
+ /** Names the web runtime re-exports, or undefined when it cannot be read. */
157
+ function runtimeExports(root: string, requireFrom: NodeRequire): Set<string> | undefined {
158
+ const pkgDir = resolvePackageDir(webRuntime.pkg, root, requireFrom);
159
+ if (!pkgDir) return undefined;
160
+ let source: string;
161
+ try {
162
+ source = fs.readFileSync(path.join(pkgDir, webRuntime.entry), "utf8");
163
+ } catch {
164
+ return undefined;
165
+ }
166
+ const names = new Set<string>();
167
+ for (const match of source.matchAll(/^export\s*\{([^}]*)\}/gm)) {
168
+ for (const clause of match[1]!.split(",")) {
169
+ const name = clause
170
+ .trim()
171
+ .split(/\s+as\s+/)
172
+ .pop()
173
+ ?.trim();
174
+ if (name) names.add(name);
175
+ }
176
+ }
177
+ for (const match of source.matchAll(/^export\s+(?:const|let|var|function|class)\s+(\w+)/gm)) {
178
+ names.add(match[1]!);
179
+ }
180
+ return names.size ? names : undefined;
181
+ }
182
+
183
+ /** Whether the module takes the binding off `react-native` by name. */
184
+ function importsBinding(file: string, binding: string): boolean {
185
+ let source: string;
186
+ try {
187
+ source = fs.readFileSync(file, "utf8");
188
+ } catch {
189
+ return false;
190
+ }
191
+ return new RegExp(`(?:import|require)[^;]*\\b${binding}\\b[^;]*['"]react-native['"]`, "s").test(
192
+ source,
193
+ );
194
+ }
195
+
196
+ /** `src/shims/<name>` from source, `../src/shims/<name>` from the built `lib`. */
197
+ function stubFile(name: string): string | undefined {
198
+ const here = path.dirname(fileURLToPath(import.meta.url));
199
+ return [path.resolve(here, "shims", name), path.resolve(here, "../src/shims", name)].find(
200
+ (candidate) => fs.existsSync(candidate),
201
+ );
202
+ }
203
+
204
+ function resolvePackageDir(
205
+ pkgName: string,
206
+ root: string,
207
+ requireFrom: NodeRequire,
208
+ ): string | undefined {
209
+ try {
210
+ return path.dirname(requireFrom.resolve(`${pkgName}/package.json`));
211
+ } catch {
212
+ const hoisted = path.join(root, "node_modules", ...pkgName.split("/"));
213
+ return fs.existsSync(path.join(hoisted, "package.json")) ? hoisted : undefined;
214
+ }
215
+ }
@@ -184,7 +184,7 @@ describe("no-voiceless-text in process (LC-137)", () => {
184
184
  const lines = lint(
185
185
  [
186
186
  styled("Shout", "Caption"),
187
- styled("Caption", "Text", { color: "$color11" }),
187
+ styled("Caption", "Text", { color: "$color-11" }),
188
188
  styled("Mono", "Text", { fontFamily: "$mono" }),
189
189
  styled("Plain", "Unknown"),
190
190
  named("tamagui", [["Text"]]),
@@ -108,7 +108,7 @@ describe("mpo-conventions/no-voiceless-text (FZ-7739, LC-137)", () => {
108
108
  " </>",
109
109
  " );",
110
110
  "}",
111
- 'const Caption = styled(Text, { color: "$color11" });',
111
+ 'const Caption = styled(Text, { color: "$color-11" });',
112
112
  'const Mono = styled(Text, { fontFamily: "$mono" });',
113
113
  "",
114
114
  ].join("\n"),
@@ -37,7 +37,7 @@ describe("matchColorLiteral", () => {
37
37
  expect(matchColorLiteral("#fff")).toBe("#fff");
38
38
  expect(matchColorLiteral("rgba(0,0,0,0.35)")).toBe("rgba(0,0,0,0.35)");
39
39
  expect(matchColorLiteral("hsl(0, 0%, 50%)")).toBe("hsl(0, 0%, 50%)");
40
- expect(matchColorLiteral("$color10")).toBeUndefined();
40
+ expect(matchColorLiteral("$color-10")).toBeUndefined();
41
41
  expect(matchColorLiteral("#025")).toBe("#025");
42
42
  });
43
43
  });
@@ -216,10 +216,10 @@ describe("mpo-conventions/no-chrome-props (MPO-17)", () => {
216
216
  const filename = "features/lookout/src/WallScreen.tsx";
217
217
  const importCard = houseImport("@multiplatform.one/components", ["Card"]);
218
218
 
219
- it("errors on Card backgroundColor=$color5 and stays silent on Card flex={1}", () => {
219
+ it("errors on Card backgroundColor=$color-5 and stays silent on Card flex={1}", () => {
220
220
  const chrome = driveHouseRule("no-chrome-props", filename, [
221
221
  importCard,
222
- jsxOpen("Card", [{ prop: "backgroundColor", value: token("$color5") }]),
222
+ jsxOpen("Card", [{ prop: "backgroundColor", value: token("$color-5") }]),
223
223
  ]);
224
224
  expect(chrome.map((r) => r.data?.prop)).toEqual(["backgroundColor"]);
225
225
 
@@ -235,14 +235,14 @@ describe("mpo-conventions/no-chrome-props (MPO-17)", () => {
235
235
  driveHouseRule(
236
236
  "no-chrome-props",
237
237
  filename,
238
- [importCard, jsxOpen("Card", [{ prop: "bg", value: token("$color2") }])],
238
+ [importCard, jsxOpen("Card", [{ prop: "bg", value: token("$color-2") }])],
239
239
  { chromeAllow: ["Card"] },
240
240
  ),
241
241
  ).toEqual([]);
242
242
  expect(
243
243
  driveHouseRule("no-chrome-props", filename, [
244
244
  houseImport("somewhere-else", ["Card"]),
245
- jsxOpen("Card", [{ prop: "backgroundColor", value: token("$color5") }]),
245
+ jsxOpen("Card", [{ prop: "backgroundColor", value: token("$color-5") }]),
246
246
  ]),
247
247
  ).toEqual([]);
248
248
  });