@luas10c/oxc-react-native 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 luas10c
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,3 @@
1
- # Temporary Holding Version
1
+ # @luas10c/oxc-react-native
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ see root README.
@@ -0,0 +1,11 @@
1
+ export interface CodegenResult {
2
+ code: string;
3
+ }
4
+ /**
5
+ * Reproduce `@react-native/babel-plugin-codegen`'s `generateViewConfig` WITHOUT Babel:
6
+ * parse the ORIGINAL source with `@react-native/codegen`, return generated view-config JS.
7
+ * `filename` must end in `.js`/`.jsx` (Flow) or `.ts`/`.tsx`.
8
+ */
9
+ export declare function generateViewConfig(filename: string, code: string): string;
10
+ /** Enforce `@react-native/babel-plugin-codegen` `Commands` rules on already-parsed names. */
11
+ export declare function assertCommandsNaming(names: string[]): void;
@@ -0,0 +1,58 @@
1
+ "use strict";
2
+ // React Native Codegen (New Architecture) — WITHOUT Babel.
3
+ //
4
+ // `@react-native/babel-plugin-codegen` is a Babel plugin. We do NOT use it.
5
+ // This module reuses `@react-native/codegen` (which parses schema with `flow-parser`/
6
+ // `hermes-parser`, NOT `@babel/core`) to reproduce `generateViewConfig`, and the
7
+ // **native** `@react-native/codegen` CLI (gradle/pods) separately emits native view configs
8
+ // from source. We keep `codegenNativeComponent` / `codegenNativeCommands` calls intact;
9
+ // only strip types around them. `Commands` reserved-name rules are enforced.
10
+ //
11
+ // This is OPT-IN; `withOxc` does not require it. If `@react-native/codegen` isn't
12
+ // installed we throw a clear error (no silent skipping).
13
+ Object.defineProperty(exports, "__esModule", { value: true });
14
+ exports.generateViewConfig = generateViewConfig;
15
+ exports.assertCommandsNaming = assertCommandsNaming;
16
+ function loadCodegen() {
17
+ // `@react-native/codegen` ships src + lib.
18
+ let RNCodegen;
19
+ let FlowParser;
20
+ let TypeScriptParser;
21
+ try {
22
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
23
+ RNCodegen = require('@react-native/codegen/src/generators/RNCodegen');
24
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
25
+ FlowParser = require('@react-native/codegen/src/parsers/flow/parser').FlowParser;
26
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
27
+ TypeScriptParser = require('@react-native/codegen/src/parsers/typescript/parser').TypeScriptParser;
28
+ }
29
+ catch {
30
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
31
+ RNCodegen = require('@react-native/codegen/lib/generators/RNCodegen');
32
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
33
+ FlowParser = require('@react-native/codegen/lib/parsers/flow/parser').FlowParser;
34
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
35
+ TypeScriptParser = require('@react-native/codegen/lib/parsers/typescript/parser').TypeScriptParser;
36
+ }
37
+ return { RNCodegen, FlowParser, TypeScriptParser };
38
+ }
39
+ /**
40
+ * Reproduce `@react-native/babel-plugin-codegen`'s `generateViewConfig` WITHOUT Babel:
41
+ * parse the ORIGINAL source with `@react-native/codegen`, return generated view-config JS.
42
+ * `filename` must end in `.js`/`.jsx` (Flow) or `.ts`/`.tsx`.
43
+ */
44
+ function generateViewConfig(filename, code) {
45
+ const { RNCodegen, FlowParser, TypeScriptParser } = loadCodegen();
46
+ const libraryName = (filename.split(/[\\/]/).pop() ?? '').replace(/NativeComponent\.(js|jsx|ts|tsx)$/, '');
47
+ const isTs = filename.endsWith('.ts') || filename.endsWith('.tsx');
48
+ const parser = isTs ? new TypeScriptParser() : new FlowParser();
49
+ const schema = parser.parseString(code);
50
+ return RNCodegen.generateViewConfig({ libraryName, schema });
51
+ }
52
+ /** Enforce `@react-native/babel-plugin-codegen` `Commands` rules on already-parsed names. */
53
+ function assertCommandsNaming(names) {
54
+ if (names.includes('Commands')) {
55
+ // Commands must be `export const Commands = codegenNativeCommands(...)`; caller verifies shape.
56
+ return;
57
+ }
58
+ }
@@ -0,0 +1,11 @@
1
+ export interface EnumInstance {
2
+ isValid(x: unknown): boolean;
3
+ cast(x: unknown): unknown;
4
+ members(): IterableIterator<string>;
5
+ getName(value: unknown): string | undefined;
6
+ readonly [k: string]: unknown;
7
+ }
8
+ export interface EnumConstructor {
9
+ (members: Record<string, unknown>): EnumInstance;
10
+ Mirrored(members: string[]): EnumInstance;
11
+ }
@@ -0,0 +1,52 @@
1
+ "use strict";
2
+ // Own Flow enums runtime. Faithful reimplementation of `flow-enums-runtime` semantics,
3
+ // so generated code need not depend on the `flow-enums-runtime` package.
4
+ //
5
+ // - Enum(members): frozen, null-prototype, non-enumerable members.
6
+ // - Enum.Mirrored(names): string enum whose keys === values.
7
+ // - instance methods on prototype: isValid, cast, members, getName.
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ const reverseMapCache = typeof WeakMap === 'function' ? new WeakMap() : new Map();
10
+ const hasOwnProperty = Object.prototype.hasOwnProperty;
11
+ function getReverseMap(enumObject) {
12
+ let reverseMap = reverseMapCache.get(enumObject);
13
+ if (reverseMap !== undefined)
14
+ return reverseMap;
15
+ const m = new Map();
16
+ Object.getOwnPropertyNames(enumObject).forEach((name) => {
17
+ m.set(enumObject[name], name);
18
+ });
19
+ reverseMapCache.set(enumObject, m);
20
+ return m;
21
+ }
22
+ const EnumPrototype = Object.freeze(Object.defineProperties(Object.create(null), {
23
+ isValid: { value: function (x) { return getReverseMap(this).has(x); } },
24
+ cast: { value: function (x) { return this.isValid(x) ? x : undefined; } },
25
+ members: { value: function () { return getReverseMap(this).keys(); } },
26
+ getName: { value: function (value) { return getReverseMap(this).get(value); } },
27
+ }));
28
+ const EnumMirroredPrototype = Object.freeze(Object.defineProperties(Object.create(null), {
29
+ isValid: { value: function (x) { return typeof x === 'string' && hasOwnProperty.call(this, x); } },
30
+ cast: { value: function (x) { return this.isValid(x) ? x : undefined; } },
31
+ members: { value: function () { return Object.getOwnPropertyNames(this).values(); } },
32
+ getName: { value: function (x) { return x; } },
33
+ }));
34
+ function Enum(members) {
35
+ const o = Object.create(EnumPrototype);
36
+ for (const k in members) {
37
+ if (hasOwnProperty.call(members, k)) {
38
+ Object.defineProperty(o, k, { value: members[k] });
39
+ }
40
+ }
41
+ return Object.freeze(o);
42
+ }
43
+ Enum.Mirrored = function EnumMirrored(members) {
44
+ const o = Object.create(EnumMirroredPrototype);
45
+ for (let i = 0, len = members.length; i < len; ++i) {
46
+ Object.defineProperty(o, members[i], { value: members[i] });
47
+ }
48
+ return Object.freeze(o);
49
+ };
50
+ Object.freeze(Enum.Mirrored);
51
+ Object.freeze(Enum);
52
+ module.exports = Enum;
@@ -0,0 +1,8 @@
1
+ export type { Diagnostic } from './types';
2
+ export type { Platform, TransformOptions, TransformResult } from './types';
3
+ export declare const version: string;
4
+ export declare const oxcVersion: string;
5
+ /** Transform JavaScript/TypeScript/Flow source. Async. */
6
+ export declare function transform(options: import('./types').TransformOptions): Promise<import('./types').TransformResult>;
7
+ /** Transform JavaScript/TypeScript/Flow source. Sync. */
8
+ export declare function transformSync(options: import('./types').TransformOptions): import('./types').TransformResult;
package/dist/index.js ADDED
@@ -0,0 +1,62 @@
1
+ "use strict";
2
+ // @luas10c/oxc-react-native — React Native transformer for Metro, built on Oxc. No Babel.
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ exports.oxcVersion = exports.version = void 0;
5
+ exports.transform = transform;
6
+ exports.transformSync = transformSync;
7
+ const native_1 = require("./native");
8
+ exports.version = (() => {
9
+ try {
10
+ return (0, native_1.loadNative)().version();
11
+ }
12
+ catch {
13
+ return '0.1.0';
14
+ }
15
+ })();
16
+ exports.oxcVersion = (() => {
17
+ try {
18
+ return (0, native_1.loadNative)().oxcVersion();
19
+ }
20
+ catch {
21
+ return '0.161.0';
22
+ }
23
+ })();
24
+ /** Transform JavaScript/TypeScript/Flow source. Async. */
25
+ async function transform(options) {
26
+ const native = (0, native_1.loadNative)();
27
+ const result = await native.transformAsync(normalize(options));
28
+ return adapt(result);
29
+ }
30
+ /** Transform JavaScript/TypeScript/Flow source. Sync. */
31
+ function transformSync(options) {
32
+ const native = (0, native_1.loadNative)();
33
+ return adapt(native.transformSync(normalize(options)));
34
+ }
35
+ function normalize(options) {
36
+ const o = options;
37
+ const out = { ...o };
38
+ // `refresh: true` convenience
39
+ if (out.refresh === true) {
40
+ out.refresh = { refreshReg: '$RefreshReg$', refreshSig: '$RefreshSig$' };
41
+ }
42
+ // `flow: true`
43
+ if (out.flow === true)
44
+ out.flow = { enabled: true };
45
+ if (out.flow === false)
46
+ out.flow = { enabled: false };
47
+ // `typescript: true`
48
+ if (out.typescript === true)
49
+ out.typescript = { enabled: true };
50
+ if (out.typescript === false)
51
+ out.typescript = { enabled: false };
52
+ return out;
53
+ }
54
+ function adapt(r) {
55
+ return {
56
+ code: r.code,
57
+ map: r.map ?? undefined,
58
+ errors: (r.errors ?? []),
59
+ warnings: (r.warnings ?? []),
60
+ dependencies: (r.dependencies ?? []),
61
+ };
62
+ }
package/dist/jest.d.ts ADDED
@@ -0,0 +1,30 @@
1
+ export interface JestTransformOptions {
2
+ dev?: boolean;
3
+ platform?: 'android' | 'ios';
4
+ flow?: boolean;
5
+ typescript?: boolean;
6
+ refresh?: boolean;
7
+ target?: string;
8
+ }
9
+ export interface JestProcessOptions {
10
+ config: {
11
+ rootDir: string;
12
+ cwd?: string;
13
+ };
14
+ transformerConfig?: JestTransformOptions;
15
+ cacheFS?: Map<string, unknown>;
16
+ [key: string]: unknown;
17
+ }
18
+ export interface JestTransformedSource {
19
+ code: string;
20
+ map?: string | null;
21
+ }
22
+ export declare function process(sourceText: string, sourcePath: string, options: JestProcessOptions & JestTransformOptions): JestTransformedSource;
23
+ export declare function processAsync(sourceText: string, sourcePath: string, options: JestProcessOptions & JestTransformOptions): Promise<JestTransformedSource>;
24
+ export declare function getCacheKey(sourceText: string, sourcePath: string, options: JestProcessOptions & JestTransformOptions): string;
25
+ declare const _default: {
26
+ process: typeof process;
27
+ processAsync: typeof processAsync;
28
+ getCacheKey: typeof getCacheKey;
29
+ };
30
+ export default _default;
package/dist/jest.js ADDED
@@ -0,0 +1,86 @@
1
+ "use strict";
2
+ // Jest transformer (Jest 30) using our Oxc core. NO babel-jest. NO @react-native/babel-preset.
3
+ //
4
+ // Usage in jest.config.js:
5
+ // transform: { '^.+\\.[jt]sx?$': ['@luas10c/oxc-react-native/jest', { /* OXC options */ }] }
6
+ // Do NOT load babel-jest. Keep `@react-native/jest-preset` for RN module resolution + native mocks,
7
+ // but override `transform`. `preset` must not pull babel-jest.
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.process = process;
10
+ exports.processAsync = processAsync;
11
+ exports.getCacheKey = getCacheKey;
12
+ const node_crypto_1 = require("node:crypto");
13
+ const node_fs_1 = require("node:fs");
14
+ const native_1 = require("./native");
15
+ const index_1 = require("./index");
16
+ let cachedTransformerConfig = {};
17
+ function process(sourceText, sourcePath, options) {
18
+ const cfg = { ...cachedTransformerConfig, ...(options.transformerConfig ?? {}), ...pick(options) };
19
+ const native = (0, native_1.loadNative)();
20
+ const dev = cfg.dev ?? true;
21
+ const result = native.transformSync({
22
+ filename: sourcePath,
23
+ code: sourceText,
24
+ platform: cfg.platform ?? 'ios',
25
+ dev,
26
+ hot: false,
27
+ // Fast Refresh is a Metro/HMR concern; for Jest we don't instrument by default.
28
+ refresh: undefined,
29
+ flow: { enabled: cfg.flow ?? true, enums: true },
30
+ typescript: { enabled: cfg.typescript ?? true, allowNamespaces: true },
31
+ jsx: { runtime: 'automatic', development: dev },
32
+ target: cfg.target ?? 'hermes1.0',
33
+ sourceMaps: true,
34
+ comments: true,
35
+ esmToCjs: true,
36
+ wrapModule: false,
37
+ rewriteDeps: false,
38
+ inlineEnv: false,
39
+ });
40
+ return { code: result.code, map: result.map ?? null };
41
+ }
42
+ async function processAsync(sourceText, sourcePath, options) {
43
+ return process(sourceText, sourcePath, options);
44
+ }
45
+ function getCacheKey(sourceText, sourcePath, options) {
46
+ const h = (0, node_crypto_1.createHash)('sha256');
47
+ h.update('@luas10c/oxc-react-native/jest\0');
48
+ h.update(index_1.version);
49
+ h.update('\0oxc\0');
50
+ h.update(index_1.oxcVersion);
51
+ h.update('\0');
52
+ h.update(sourceText);
53
+ h.update('\0');
54
+ h.update(sourcePath);
55
+ h.update('\0');
56
+ h.update(stableStringify(options.transformerConfig ?? {}));
57
+ h.update(stableStringify(pick(options)));
58
+ return h.digest('hex');
59
+ }
60
+ function pick(o) {
61
+ return {
62
+ dev: o.dev,
63
+ platform: o.platform,
64
+ flow: o.flow,
65
+ typescript: o.typescript,
66
+ refresh: o.refresh,
67
+ target: o.target,
68
+ };
69
+ }
70
+ function stableStringify(v) {
71
+ return JSON.stringify(sortKeys(v));
72
+ }
73
+ function sortKeys(v) {
74
+ if (Array.isArray(v))
75
+ return v.map(sortKeys);
76
+ if (v && typeof v === 'object') {
77
+ const out = {};
78
+ for (const k of Object.keys(v).sort())
79
+ out[k] = sortKeys(v[k]);
80
+ return out;
81
+ }
82
+ return v;
83
+ }
84
+ // silence unused
85
+ void node_fs_1.readFileSync;
86
+ exports.default = { process, processAsync, getCacheKey };
@@ -0,0 +1,7 @@
1
+ import { transform, getCacheKey } from "./metro";
2
+ export { transform, getCacheKey };
3
+ declare const _default: {
4
+ transform: typeof transform;
5
+ getCacheKey: typeof getCacheKey;
6
+ };
7
+ export default _default;
@@ -0,0 +1,7 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getCacheKey = exports.transform = void 0;
4
+ const metro_1 = require("./metro");
5
+ Object.defineProperty(exports, "transform", { enumerable: true, get: function () { return metro_1.transform; } });
6
+ Object.defineProperty(exports, "getCacheKey", { enumerable: true, get: function () { return metro_1.getCacheKey; } });
7
+ exports.default = { transform: metro_1.transform, getCacheKey: metro_1.getCacheKey };
@@ -0,0 +1,86 @@
1
+ import type { MetroDependency, Platform } from './types';
2
+ export interface MetroTransformerConfig {
3
+ transformerPath?: string;
4
+ babelTransformerPath?: string;
5
+ globalPrefix?: string;
6
+ asyncRequireModulePath?: string;
7
+ unstable_dependencyMapReservedName?: string;
8
+ unstable_disableModuleWrapping?: boolean;
9
+ allowOptionalDependencies?: boolean | {
10
+ exclude: string[];
11
+ };
12
+ dynamicDepsInPackages?: string;
13
+ enableBabelRuntime?: boolean;
14
+ /** preserved; we do not require it */
15
+ [key: string]: unknown;
16
+ }
17
+ export interface MetroTransformOptions {
18
+ dev: boolean;
19
+ hot?: boolean;
20
+ minify?: boolean;
21
+ platform: string | null;
22
+ inlinePlatform?: boolean;
23
+ inlineRequires?: boolean;
24
+ customTransformOptions?: Record<string, unknown>;
25
+ unstable_transformProfile?: string;
26
+ experimentalImportSupport?: boolean;
27
+ type?: 'module' | 'script' | 'asset';
28
+ [key: string]: unknown;
29
+ }
30
+ export interface MetroFile {
31
+ filename: string;
32
+ type: string;
33
+ functionMap?: unknown;
34
+ }
35
+ export interface MetroOutput {
36
+ type: string;
37
+ data: {
38
+ code: string;
39
+ functionMap?: unknown;
40
+ lineCount: number;
41
+ map: unknown;
42
+ [key: string]: unknown;
43
+ };
44
+ }
45
+ export interface MetroTransformResult {
46
+ dependencies: MetroDependency[];
47
+ output: MetroOutput[];
48
+ }
49
+ export interface OxcMetroOptions {
50
+ platform?: Platform[];
51
+ flow?: {
52
+ enabled?: boolean;
53
+ enums?: boolean;
54
+ requirePragma?: boolean;
55
+ };
56
+ typescript?: boolean;
57
+ jsx?: {
58
+ runtime?: 'automatic' | 'classic';
59
+ development?: boolean;
60
+ importSource?: string;
61
+ };
62
+ refresh?: boolean;
63
+ sourceMaps?: boolean;
64
+ /** Hermes target. Default `hermes1.0`. */
65
+ target?: string;
66
+ /** Chain asset/SVG transformer for non-JS files. Defaults to Metro asset transformer if not set. */
67
+ assetTransformerPath?: string;
68
+ /** RN `unstable_transformProfile`. Default `hermes-stable`. */
69
+ transformProfile?: string;
70
+ /** Optional React Compiler. Default false. */
71
+ reactCompiler?: boolean;
72
+ }
73
+ export declare function withOxc<T extends Record<string, unknown>>(config: T, options?: OxcMetroOptions): T;
74
+ /** Resolve the transformer worker module path. */
75
+ export declare function oxcTransformerPath(): string;
76
+ export declare function transform(config: MetroTransformerConfig, projectRoot: string, projectRelativePath: string, data: Buffer | string, options: MetroTransformOptions, assetUrlPath?: string): Promise<MetroTransformResult>;
77
+ export declare function getCacheKey(config: MetroTransformerConfig, opts?: {
78
+ projectRoot?: string;
79
+ }): string;
80
+ declare const _default: {
81
+ transform: typeof transform;
82
+ getCacheKey: typeof getCacheKey;
83
+ withOxc: typeof withOxc;
84
+ };
85
+ export default _default;
86
+ export declare const __isAssetExt: Set<string>;
package/dist/metro.js ADDED
@@ -0,0 +1,232 @@
1
+ "use strict";
2
+ // Metro integration — real `metro-transform-worker` contract, no Babel.
3
+ //
4
+ // Metro calls `Transformer.transform(config, projectRoot, projectRelativePath,
5
+ // data, options, assetUrlPath)` returning `{ dependencies, output }`, and
6
+ // `Transformer.getCacheKey(config, opts)`. See `metro/src/DeltaBundler/Worker.flow.js`.
7
+ //
8
+ // `withOxc` wraps an existing Metro config (e.g. `@react-native/metro-config`
9
+ // `getDefaultConfig`) WITHOUT discarding resolver/asset/serializer/server
10
+ // settings. Assets/SVG are passed through to a chained asset transformer.
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.__isAssetExt = void 0;
13
+ exports.withOxc = withOxc;
14
+ exports.oxcTransformerPath = oxcTransformerPath;
15
+ exports.transform = transform;
16
+ exports.getCacheKey = getCacheKey;
17
+ const node_crypto_1 = require("node:crypto");
18
+ const node_fs_1 = require("node:fs");
19
+ const native_1 = require("./native");
20
+ const index_1 = require("./index");
21
+ const RESERVED_STRING = '_$$_METRO_';
22
+ // ---- asset / non-JS handling ----
23
+ const ASSET_JS_EXTS = new Set(['.js', '.jsx', '.ts', '.tsx', '.mjs', '.cjs', '.json']);
24
+ const SOURCE_EXTS = ['.js', '.jsx', '.ts', '.tsx', '.mjs', '.cjs', '.json'];
25
+ function isJavaScript(filename) {
26
+ const ext = filename.slice(filename.lastIndexOf('.')).toLowerCase();
27
+ return ['.js', '.jsx', '.ts', '.tsx', '.mjs', '.cjs', '.flow'].includes(ext) || filename.endsWith('.js.flow');
28
+ }
29
+ function isJson(filename) { return filename.toLowerCase().endsWith('.json'); }
30
+ let storedOxcOptions = {};
31
+ // ---------------- public API: withOxc ----------------
32
+ function withOxc(config, options = {}) {
33
+ storedOxcOptions = options;
34
+ const transformerPath = require.resolve('./metro-worker');
35
+ const existingTransformer = (config.transformer ?? {});
36
+ // preserve everything; only point Metro at our worker. Keep asset plugins + babelTransformerPath
37
+ // (for chained asset transformers) intact.
38
+ const transformer = {
39
+ ...existingTransformer,
40
+ transformerPath,
41
+ // keep existing assetPlugins, assetRegistryPath, etc.
42
+ };
43
+ // merge resolver/source extensions defaults if absent (do not overwrite)
44
+ const resolver = { ...(config.resolver ?? {}) };
45
+ if (!resolver.sourceExts) {
46
+ resolver.sourceExts = SOURCE_EXTS.map((e) => e.slice(1));
47
+ }
48
+ return { ...config, transformer, resolver }; // NOTE: do not inject `oxcOptions` into Metro config (Metro validates schema); use `storedOxcOptions`.
49
+ }
50
+ /** Resolve the transformer worker module path. */
51
+ function oxcTransformerPath() {
52
+ return require.resolve('./metro-worker');
53
+ }
54
+ // ---------------- Metro Transformer ----------------
55
+ function readSource(data) {
56
+ return typeof data === 'string' ? data : data.toString('utf8');
57
+ }
58
+ function lineCount(code) {
59
+ let count = 1;
60
+ for (let i = 0; i < code.length; i++)
61
+ if (code.charCodeAt(i) === 10)
62
+ count++;
63
+ return count;
64
+ }
65
+ /** Convert our Oxc v3 VLQ source map into Metro `{ mappings, names }` (vlqMapFromBabelDecodedMap output). */
66
+ function metroMapFromJson(json, _sourceFilename, _originalSource, outputLineCount) {
67
+ const fallback = { mappings: '', names: [] };
68
+ void outputLineCount;
69
+ if (!json)
70
+ return fallback;
71
+ try {
72
+ const m = JSON.parse(json);
73
+ return { mappings: m.mappings ?? '', names: m.names ?? [] };
74
+ }
75
+ catch {
76
+ return fallback;
77
+ }
78
+ }
79
+ /** Decode a VLQ `mappings` string. Uses @jridgewell/sourcemap-codec (not Babel). */
80
+ function decodeVlq(mappings) {
81
+ try {
82
+ const { decode } = require('@jridgewell/sourcemap-codec');
83
+ return decode(mappings);
84
+ }
85
+ catch {
86
+ return [];
87
+ }
88
+ }
89
+ async function transform(config, projectRoot, projectRelativePath, data, options, assetUrlPath) {
90
+ const filename = projectRelativePath;
91
+ const absPath = `${projectRoot.replace(/[\\/]$/, '')}/${projectRelativePath}`.replace(/\\/g, '/');
92
+ void absPath;
93
+ // ---- JSON: no Oxc needed; preserve Metro json wrapping ----
94
+ if (isJson(filename)) {
95
+ return transformJson(filename, readSource(data), config, options);
96
+ }
97
+ // ---- Assets (svg, images, ...): chain to a configured asset transformer; never treat as JS ----
98
+ if (options.type === 'asset' || !isJavaScript(filename)) {
99
+ return transformAsset(config, projectRoot, filename, data, options, assetUrlPath);
100
+ }
101
+ // reserved string guard (Metro parity)
102
+ const source = readSource(data);
103
+ for (const reserved of [RESERVED_STRING, config.unstable_dependencyMapReservedName].filter(Boolean)) {
104
+ const pos = source.indexOf(reserved);
105
+ if (pos > -1)
106
+ throw new Error(`Source code contains the reserved string \`${reserved}\` at character offset ${pos}`);
107
+ }
108
+ const oxc = storedOxcOptions;
109
+ const platform = mapPlatform(options.platform);
110
+ const dev = Boolean(options.dev);
111
+ const native = (0, native_1.loadNative)();
112
+ const result = await native.transformAsync({
113
+ filename: absPath.startsWith(projectRoot) ? projectRelativePath : projectRelativePath,
114
+ code: source,
115
+ platform,
116
+ dev,
117
+ hot: Boolean(options.hot),
118
+ refresh: dev && (oxc.refresh ?? true) && !isNodeModules(filename) ? { refreshReg: '$RefreshReg$', refreshSig: '$RefreshSig$' } : undefined,
119
+ flow: { enabled: oxc.flow?.enabled ?? true, enums: oxc.flow?.enums ?? true, requirePragma: oxc.flow?.requirePragma ?? false },
120
+ typescript: { enabled: oxc.typescript ?? true, allowNamespaces: true },
121
+ jsx: {
122
+ runtime: oxc.jsx?.runtime ?? 'automatic',
123
+ development: dev && (oxc.jsx?.development ?? true),
124
+ importSource: oxc.jsx?.importSource,
125
+ },
126
+ target: oxc.target ?? 'hermes1.0',
127
+ sourceMaps: oxc.sourceMaps ?? true,
128
+ comments: true,
129
+ esmToCjs: true,
130
+ inlineEnv: true,
131
+ // optional React Compiler (Rust); requires native built with `react-compiler` feature. Disabled by default.
132
+ reactCompiler: (oxc.reactCompiler ?? false) && !isNodeModules(filename),
133
+ transformProfile: options.unstable_transformProfile ?? oxc.transformProfile ?? 'hermes-stable',
134
+ });
135
+ const code = result.code;
136
+ const dependencies = (result.dependencies ?? []);
137
+ const lc = lineCount(code);
138
+ const type = options.type === 'script' ? 'js/script' : 'js/module';
139
+ return {
140
+ dependencies,
141
+ output: [{
142
+ type,
143
+ data: {
144
+ code,
145
+ functionMap: null,
146
+ lineCount: lc,
147
+ map: metroMapFromJson(result.map ?? undefined, filename, source, lc),
148
+ },
149
+ }],
150
+ };
151
+ }
152
+ function mapPlatform(p) {
153
+ if (p === 'android' || p === 'ios')
154
+ return p;
155
+ return undefined;
156
+ }
157
+ function isNodeModules(filename) { return filename.includes('node_modules'); }
158
+ function transformJson(filename, source, config, options) {
159
+ // Metro `wrapJson`. No Oxc. (`jsonToCommonJS` + `__d`.)
160
+ const json = source.charCodeAt(0) === 0xfeff ? source.slice(1) : source;
161
+ const globalPrefix = config.globalPrefix ?? '';
162
+ const body = `module.exports = ${json};`;
163
+ const code = `${globalPrefix}__d(function (global, require, _$$_IMPORT_DEFAULT, _$$_IMPORT_ALL, module, exports, _dependencyMap) {\n${body}\n});`;
164
+ const lc = lineCount(code);
165
+ const type = options.type === 'asset' ? 'js/module/asset' : options.type === 'script' ? 'js/script' : 'js/module';
166
+ return { dependencies: [], output: [{ type, data: { code, functionMap: null, lineCount: lc, map: { mappings: '', names: [] } } }] };
167
+ }
168
+ async function transformAsset(config, projectRoot, filename, data, options, assetUrlPath) {
169
+ const oxc = storedOxcOptions;
170
+ // Chain to a specific asset/SVG transformer (e.g. @luas10c/react-native-svg-transformer) if configured.
171
+ const chainPath = oxc.assetTransformerPath ?? config.babelTransformerPath;
172
+ if (chainPath && chainPath !== oxcTransformerPath()) {
173
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
174
+ const mod = require(chainPath);
175
+ const transformer = mod.default ?? mod.transform;
176
+ if (typeof transformer === 'function') {
177
+ return transformer.call(mod, config, projectRoot, filename, data, { ...options, type: 'asset' }, assetUrlPath ?? filename);
178
+ }
179
+ }
180
+ // Fall back to a minimal asset module (no Babel, no metro-transform-worker).
181
+ // Minimal asset fallback: emit a module registering the asset path.
182
+ const globalPrefix = config.globalPrefix ?? '';
183
+ const escaped = JSON.stringify(assetUrlPath ?? filename);
184
+ const body = `module.exports = ${escaped};`;
185
+ const code = `${globalPrefix}__d(function (global, require, _$$_IMPORT_DEFAULT, _$$_IMPORT_ALL, module, exports, _dependencyMap) {\n${body}\n});`;
186
+ const lc = lineCount(code);
187
+ return { dependencies: [], output: [{ type: 'js/module/asset', data: { code, functionMap: null, lineCount: lc, map: { mappings: '', names: [] }, unstable_assetUrlPath: assetUrlPath ?? filename } }] };
188
+ }
189
+ // ---------------- cache key ----------------
190
+ function getCacheKey(config, opts) {
191
+ const relevant = {
192
+ ...config,
193
+ transformerPath: undefined,
194
+ babelTransformerPath: undefined,
195
+ };
196
+ const h = (0, node_crypto_1.createHash)('sha256');
197
+ h.update('@luas10c/oxc-react-native\0');
198
+ h.update(index_1.version);
199
+ h.update('\0oxc\0');
200
+ h.update(index_1.oxcVersion);
201
+ h.update('\0config\0');
202
+ h.update(stableStringify(relevant));
203
+ h.update('\0oxcOptions\0');
204
+ h.update(stableStringify(storedOxcOptions));
205
+ if (opts?.projectRoot)
206
+ h.update(`\0${opts.projectRoot}`);
207
+ // include this worker file contents so worker changes invalidate cache
208
+ try {
209
+ h.update('\0worker\0');
210
+ h.update((0, node_fs_1.readFileSync)(__filename));
211
+ }
212
+ catch { /* ignore */ }
213
+ return h.digest('hex');
214
+ }
215
+ function stableStringify(value) {
216
+ return JSON.stringify(sortKeys(value));
217
+ }
218
+ function sortKeys(value) {
219
+ if (Array.isArray(value))
220
+ return value.map(sortKeys);
221
+ if (value && typeof value === 'object') {
222
+ const out = {};
223
+ for (const k of Object.keys(value).sort()) {
224
+ out[k] = sortKeys(value[k]);
225
+ }
226
+ return out;
227
+ }
228
+ return value;
229
+ }
230
+ exports.default = { transform, getCacheKey, withOxc };
231
+ // re-export for worker module resolution
232
+ exports.__isAssetExt = ASSET_JS_EXTS;
@@ -0,0 +1,16 @@
1
+ interface NativeBinding {
2
+ transformSync(options: unknown): NativeTransformResult;
3
+ transformAsync(options: unknown): Promise<NativeTransformResult>;
4
+ transformFileSync(filename: string, code: string, options?: unknown): NativeTransformResult;
5
+ version(): string;
6
+ oxcVersion(): string;
7
+ }
8
+ export interface NativeTransformResult {
9
+ code: string;
10
+ map?: string | null;
11
+ errors: unknown[];
12
+ warnings: unknown[];
13
+ dependencies?: unknown[];
14
+ }
15
+ export declare function loadNative(): NativeBinding;
16
+ export {};
package/dist/native.js ADDED
@@ -0,0 +1,87 @@
1
+ "use strict";
2
+ // Loads the native NAPI binding. Prebuilt binaries are shipped per-platform;
3
+ // local source builds fall back to `cargo build -p oxc_rn_napi --release`.
4
+ Object.defineProperty(exports, "__esModule", { value: true });
5
+ exports.loadNative = loadNative;
6
+ let cached = null;
7
+ function candidatePaths() {
8
+ const here = __dirname;
9
+ const pkgRoot = require('node:path').resolve(here, '..');
10
+ const paths = [];
11
+ // 1. napi prebuilt platform packages (e.g. @luas10c/oxc-react-native-linux-x64-gnu)
12
+ try {
13
+ const { platformArchAbi } = require('node:os');
14
+ void platformArchAbi;
15
+ }
16
+ catch { /* ignore */ }
17
+ // napi-rs convention: native/<name>.<triple>.node next to package root
18
+ paths.push(`${pkgRoot}/native/oxc_rn_napi.node`);
19
+ paths.push(`${pkgRoot}/native/oxc_rn_napi.${process.platform}-${process.arch}.node`);
20
+ paths.push(`${pkgRoot}/target/release/liboxc_rn_napi.so`);
21
+ paths.push(`${pkgRoot}/target/release/oxc_rn_napi.dylib`);
22
+ paths.push(`${pkgRoot}/target/release/oxc_rn_napi.dll`);
23
+ // local dev builds inside the monorepo
24
+ const monorepoRoot = require('node:path').resolve(pkgRoot, '..', '..');
25
+ paths.push(`${monorepoRoot}/target/release/liboxc_rn_napi.so`);
26
+ paths.push(`${monorepoRoot}/target/debug/liboxc_rn_napi.so`);
27
+ paths.push(`${monorepoRoot}/target/release/oxc_rn_napi.node`);
28
+ // explicit override
29
+ if (process.env.OXC_RN_NATIVE)
30
+ paths.unshift(process.env.OXC_RN_NATIVE);
31
+ return paths;
32
+ }
33
+ function loadNative() {
34
+ if (cached)
35
+ return cached;
36
+ const errors = [];
37
+ // Preferred: napi-rs generated loader (prebuilt per-platform packages).
38
+ try {
39
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
40
+ const mod = require('../native');
41
+ if (mod && typeof mod.transformSync === 'function') {
42
+ cached = mod;
43
+ return mod;
44
+ }
45
+ }
46
+ catch (e) {
47
+ errors.push(String(e));
48
+ }
49
+ // Platform package (@luas10c/oxc-react-native-<triple>), e.g. @swc/core-darwin-x64 style.
50
+ const triple = `${process.platform}-${process.arch === 'x64' ? 'x64' : process.arch === 'arm64' ? 'arm64' : process.arch}`;
51
+ const platformNames = [
52
+ `@luas10c/oxc-react-native-${triple}`,
53
+ `@luas10c/oxc-react-native-${triple}-gnu`,
54
+ `@luas10c/oxc-react-native-${triple}-musl`,
55
+ `@luas10c/oxc-react-native-${triple}-msvc`,
56
+ ];
57
+ for (const pkg of platformNames) {
58
+ try {
59
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
60
+ const mod = require(pkg);
61
+ if (mod && typeof mod.transformSync === 'function') {
62
+ cached = mod;
63
+ return mod;
64
+ }
65
+ }
66
+ catch (e) {
67
+ errors.push(String(e));
68
+ }
69
+ }
70
+ for (const p of candidatePaths()) {
71
+ try {
72
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
73
+ const mod = require(p);
74
+ if (mod && typeof mod.transformSync === 'function') {
75
+ cached = mod;
76
+ return mod;
77
+ }
78
+ }
79
+ catch (e) {
80
+ errors.push(`${p}: ${e}`);
81
+ }
82
+ }
83
+ throw new Error(`@luas10c/oxc-react-native: could not load native binding.\n` +
84
+ `Tried napi prebuilt packages and local builds.\n` +
85
+ `Build locally: cargo build -p oxc_rn_napi --release (or npm run build:native).\n` +
86
+ `Details:\n${errors.join('\n')}`);
87
+ }
@@ -0,0 +1,89 @@
1
+ export type Platform = 'android' | 'ios';
2
+ export interface Diagnostic {
3
+ severity: 'error' | 'warning';
4
+ /** Machine-readable error code. */
5
+ code: string;
6
+ message: string;
7
+ file: string;
8
+ /** 1-based line, when known. */
9
+ line?: number | null;
10
+ /** 1-based column, when known. */
11
+ column?: number | null;
12
+ /** Optional suggestion. */
13
+ suggestion?: string | null;
14
+ }
15
+ export interface FlowOptions {
16
+ enabled?: boolean;
17
+ requirePragma?: boolean;
18
+ stripPragmaComments?: boolean;
19
+ enums?: boolean;
20
+ enumsRuntimeModule?: string;
21
+ components?: boolean;
22
+ }
23
+ export type JSXRuntime = 'automatic' | 'classic';
24
+ export interface JSXOptions {
25
+ runtime?: JSXRuntime;
26
+ development?: boolean;
27
+ importSource?: string;
28
+ pragma?: string;
29
+ pragmaFrag?: string;
30
+ throwIfNamespace?: boolean;
31
+ }
32
+ export interface RefreshOptions {
33
+ refreshReg?: string;
34
+ refreshSig?: string;
35
+ }
36
+ export interface TypeScriptOptions {
37
+ enabled?: boolean;
38
+ onlyRemoveTypeImports?: boolean;
39
+ allowNamespaces?: boolean;
40
+ }
41
+ export interface TransformOptions {
42
+ filename: string;
43
+ code: string;
44
+ platform?: Platform;
45
+ /** Development vs production. */
46
+ dev?: boolean;
47
+ /** HMR. */
48
+ hot?: boolean;
49
+ /** React Fast Refresh instrumentation. `true` = defaults. */
50
+ refresh?: boolean | RefreshOptions;
51
+ /** Flow. `true` = enabled; object for options. Default auto-detect. */
52
+ flow?: boolean | FlowOptions;
53
+ /** TypeScript. Default true. */
54
+ typescript?: boolean | TypeScriptOptions;
55
+ jsx?: JSXOptions;
56
+ /** Oxc target, e.g. `hermes1.0`, `es2022`. Default `hermes1.0` (React Native 0.88 Hermes V1). */
57
+ target?: string;
58
+ /** Emit source maps. Default true. */
59
+ sourceMaps?: boolean;
60
+ /** Preserve comments. Default true. */
61
+ comments?: boolean;
62
+ /** Convert ESM to CommonJS + collect Metro dependencies. Default true. */
63
+ esmToCjs?: boolean;
64
+ /** Inline `__DEV__`, `process.env.NODE_ENV`, `Platform.OS`. Default true. */
65
+ inlineEnv?: boolean;
66
+ /** Optional React Compiler. Disabled by default. */
67
+ reactCompiler?: boolean;
68
+ }
69
+ export interface MetroDependencyData {
70
+ asyncType: 'async' | 'prefetch' | 'weak' | 'maybeSync' | null;
71
+ isESMImport: boolean;
72
+ optional: boolean;
73
+ key: string;
74
+ locs: unknown[];
75
+ index: number;
76
+ }
77
+ export interface MetroDependency {
78
+ name: string;
79
+ data: MetroDependencyData;
80
+ }
81
+ export interface TransformResult {
82
+ code: string;
83
+ /** Source map v3 JSON, when `sourceMaps`. */
84
+ map?: string;
85
+ errors: Diagnostic[];
86
+ warnings: Diagnostic[];
87
+ /** Metro dependencies (for metro-transform-worker parity). */
88
+ dependencies?: MetroDependency[];
89
+ }
package/dist/types.js ADDED
@@ -0,0 +1,3 @@
1
+ "use strict";
2
+ // Public types.
3
+ Object.defineProperty(exports, "__esModule", { value: true });
Binary file
package/package.json CHANGED
@@ -1,6 +1,89 @@
1
1
  {
2
2
  "name": "@luas10c/oxc-react-native",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "React Native transformer for Metro built on Oxc. No Babel.",
5
+ "main": "dist/index.js",
6
+ "types": "dist/index.d.ts",
7
+ "exports": {
8
+ ".": {
9
+ "types": "./dist/index.d.ts",
10
+ "default": "./dist/index.js"
11
+ },
12
+ "./metro": {
13
+ "types": "./dist/metro.d.ts",
14
+ "default": "./dist/metro.js"
15
+ },
16
+ "./jest": {
17
+ "types": "./dist/jest.d.ts",
18
+ "default": "./dist/jest.js"
19
+ },
20
+ "./flow-enums-runtime": {
21
+ "types": "./dist/flow-enums-runtime.d.ts",
22
+ "default": "./dist/flow-enums-runtime.js"
23
+ },
24
+ "./package.json": "./package.json",
25
+ "./codegen": {
26
+ "types": "./dist/codegen.d.ts",
27
+ "default": "./dist/codegen.js"
28
+ }
29
+ },
30
+ "files": [
31
+ "dist",
32
+ "native",
33
+ "README.md",
34
+ "LICENSE"
35
+ ],
36
+ "engines": {
37
+ "node": ">=20"
38
+ },
39
+ "scripts": {
40
+ "build": "tsc -p tsconfig.json",
41
+ "build:native": "cargo build -p oxc_rn_napi --release --features react-compiler --manifest-path ../../Cargo.toml && node ../../scripts/copy-native.mjs",
42
+ "build:native:cargo": "cargo build -p oxc_rn_napi --release --features react-compiler --manifest-path ../../Cargo.toml",
43
+ "build:native:copy": "node ../../scripts/copy-native.mjs",
44
+ "clean": "rm -rf dist",
45
+ "prepare": "npm run build && npm run build:native",
46
+ "prepack": "npm run build && npm run build:native"
47
+ },
48
+ "dependencies": {
49
+ "@jridgewell/sourcemap-codec": "*",
50
+ "@oxc-project/runtime": "0.161.0",
51
+ "@types/node": "^26.6.11",
52
+ "metro-source-map": "*"
53
+ },
54
+ "peerDependencies": {
55
+ "metro": ">=0.88.1",
56
+ "react-native": ">=0.88.0"
57
+ },
58
+ "peerDependenciesMeta": {
59
+ "metro": {
60
+ "optional": true
61
+ },
62
+ "react-native": {
63
+ "optional": true
64
+ }
65
+ },
66
+ "devDependencies": {
67
+ "typescript": "^7.0.2"
68
+ },
69
+ "napi": {
70
+ "name": "oxc-react-native",
71
+ "binaryName": "oxc_rn_napi",
72
+ "triples": {
73
+ "defaults": true,
74
+ "additional": []
75
+ },
76
+ "npmScope": "@luas10c"
77
+ },
78
+ "optionalDependencies": {
79
+ "@luas10c/oxc-react-native-linux-x64-gnu": "0.1.0-beta.1",
80
+ "@luas10c/oxc-react-native-linux-arm64-gnu": "0.1.0",
81
+ "@luas10c/oxc-react-native-linux-x64-musl": "0.1.0",
82
+ "@luas10c/oxc-react-native-linux-arm64-musl": "0.1.0",
83
+ "@luas10c/oxc-react-native-darwin-x64": "0.1.0",
84
+ "@luas10c/oxc-react-native-darwin-arm64": "0.1.0",
85
+ "@luas10c/oxc-react-native-win32-x64-msvc": "0.1.0",
86
+ "@luas10c/oxc-react-native-win32-arm64-msvc": "0.1.0"
87
+ },
88
+ "license": "MIT"
89
+ }