@knighted/module 1.0.0-rc.6 → 1.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.
package/README.md CHANGED
@@ -11,14 +11,16 @@ Node.js utility for transforming a JavaScript or TypeScript file from an ES modu
11
11
 
12
12
  Highlights
13
13
 
14
+ - ESM ➡️ CJS and CJS ➡️ ESM with one function call.
14
15
  - Defaults to safe CommonJS output: strict live bindings, import.meta shims, and specifier preservation.
15
- - Opt into stricter/looser behaviors: live binding enforcement, import.meta.main gating, and top-level await strategies.
16
- - Can optionally rewrite relative specifiers and write transformed output to disk.
16
+ - Configurable lowering modes: full syntax transforms or globals-only.
17
+ - Specifier tools: add extensions, add directory indexes, or map with a custom callback.
18
+ - Output control: write to disk (`out`/`inPlace`) or return the transformed string.
17
19
 
18
20
  > [!IMPORTANT]
19
21
  > All parsing logic is applied under the assumption the code is in [strict mode](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode) which [modules run under by default](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules#other_differences_between_modules_and_classic_scripts).
20
22
 
21
- By default `@knighted/module` transforms the one-to-one [differences between ES modules and CommonJS](https://nodejs.org/api/esm.html#differences-between-es-modules-and-commonjs). Options let you control syntax rewriting, specifier updates, and output.
23
+ By default `@knighted/module` transforms the one-to-one [differences between ES modules and CommonJS](https://nodejs.org/api/esm.html#differences-between-es-modules-and-commonjs). Options let you control syntax rewriting (full vs globals-only), specifier updates, and output.
22
24
 
23
25
  ## Requirements
24
26
 
@@ -30,9 +32,9 @@ By default `@knighted/module` transforms the one-to-one [differences between ES
30
32
  npm install @knighted/module
31
33
  ```
32
34
 
33
- ## Example
35
+ ## Quick examples
34
36
 
35
- Given an ES module:
37
+ ESM ➡️ CJS:
36
38
 
37
39
  **file.js**
38
40
 
@@ -93,6 +95,17 @@ use@computer: $ node file.cjs
93
95
  invoked directly by node
94
96
  ```
95
97
 
98
+ CJS ➡️ ESM:
99
+
100
+ ```js
101
+ import { transform } from '@knighted/module'
102
+
103
+ await transform('./file.cjs', {
104
+ target: 'module',
105
+ out: './file.mjs',
106
+ })
107
+ ```
108
+
96
109
  ## Options
97
110
 
98
111
  ```ts
@@ -124,20 +137,21 @@ type ModuleOptions = {
124
137
  }
125
138
  ```
126
139
 
127
- Behavior notes (defaults in parentheses)
140
+ ### Behavior notes (defaults in parentheses)
128
141
 
129
142
  - `target` (`commonjs`): output module system.
130
143
  - `transformSyntax` (true): enable/disable the ESM↔CJS lowering pass; set to `'globals-only'` to rewrite module globals (`import.meta.*`, `__dirname`, `__filename`, `require.main` shims) while leaving import/export syntax untouched. In `'globals-only'`, no helpers are injected (e.g., `__requireResolve`), `require.resolve` rewrites to `import.meta.resolve`, and `idiomaticExports` is skipped. See [globals-only](#globals-only-scope).
131
144
  - `liveBindings` (`strict`): getter-based live bindings, or snapshot (`loose`/`off`).
132
145
  - `appendJsExtension` (`relative-only` when targeting ESM): append `.js` to relative specifiers; never touches bare specifiers.
133
146
  - `appendDirectoryIndex` (`index.js`): when a relative specifier ends with a slash, append this index filename (set `false` to disable).
147
+ - `appenders` precedence: `rewriteSpecifier` runs first; if it returns a string, that result is used. If it returns `undefined` or `null`, `appendJsExtension` and `appendDirectoryIndex` still run. Bare specifiers are never modified by appenders.
134
148
  - `dirFilename` (`inject`): inject `__dirname`/`__filename`, preserve existing, or throw.
135
149
  - `importMeta` (`shim`): rewrite `import.meta.*` to CommonJS equivalents.
136
150
  - `importMetaMain` (`shim`): gate `import.meta.main` with shimming/warning/error when Node support is too old.
137
151
  - `requireMainStrategy` (`import-meta-main`): use `import.meta.main` or the realpath-based `pathToFileURL(realpathSync(process.argv[1])).href` check.
138
152
  - `detectCircularRequires` (`off`): optionally detect relative static require cycles and warn/throw.
139
153
  - `topLevelAwait` (`error`): throw, wrap, or preserve when TLA appears in CommonJS output.
140
- - `rewriteSpecifier` (off): rewrite relative specifiers to a chosen extension or via a callback.
154
+ - `rewriteSpecifier` (off): rewrite relative specifiers to a chosen extension or via a callback. Precedence: the callback (if provided) runs first; if it returns a string, that wins. If it returns `undefined` or `null`, the appenders still apply.
141
155
  - `requireSource` (`builtin`): whether `require` comes from Node or `createRequire`.
142
156
  - `cjsDefault` (`auto`): bundler-style default interop vs direct `module.exports`.
143
157
  - `out`/`inPlace`: write the transformed code to a file; otherwise the function returns the transformed string only.
@@ -47,7 +47,7 @@ const rewriteSpecifierValue = (value, rewriteSpecifier) => {
47
47
  const collapsed = collapseSpecifier(value);
48
48
  const relative = /^(?:\.\.?)\//;
49
49
  if (relative.test(collapsed)) {
50
- return value.replace(/(.+)\.(?:m|c)?(?:j|t)s([)'"]*)?$/, `$1${rewriteSpecifier}$2`);
50
+ return value.replace(/(.+)\.(?:m|c)?(?:j|t)sx?([)'"]*)?$/, `$1${rewriteSpecifier}$2`);
51
51
  }
52
52
  };
53
53
  const normalizeBuiltinSpecifier = value => {
@@ -118,6 +118,9 @@ const formatSpecifiers = async (src, ast, cb) => {
118
118
  };
119
119
  await (0, _walk.walk)(ast.program, {
120
120
  enter(node) {
121
+ if (node.type === 'ImportExpression') {
122
+ formatExpression(node);
123
+ }
121
124
  if (node.type === 'ExpressionStatement') {
122
125
  const {
123
126
  expression
@@ -21,7 +21,8 @@ export type ModuleOptions = {
21
21
  appendJsExtension?: 'off' | 'relative-only' | 'all';
22
22
  /** Add directory index (e.g. /index.js) or disable. */
23
23
  appendDirectoryIndex?: string | false;
24
- /** Control __dirname and __filename handling. */
24
+ /** Precedence: rewriteSpecifier runs first; if it returns a string that wins. If it returns undefined or null, appenders apply. Bare specifiers are never modified by appenders. */
25
+ /** Control __dirname/__filename handling (inject shims, preserve existing, or throw on use). */
25
26
  dirFilename?: 'inject' | 'preserve' | 'error';
26
27
  /** How to treat import.meta. */
27
28
  importMeta?: 'preserve' | 'shim' | 'error';
package/dist/module.js CHANGED
@@ -44,7 +44,7 @@ const rewriteSpecifierValue = (value, rewriteSpecifier) => {
44
44
  const collapsed = collapseSpecifier(value);
45
45
  const relative = /^(?:\.\.?)\//;
46
46
  if (relative.test(collapsed)) {
47
- return value.replace(/(.+)\.(?:m|c)?(?:j|t)s([)'"]*)?$/, `$1${rewriteSpecifier}$2`);
47
+ return value.replace(/(.+)\.(?:m|c)?(?:j|t)sx?([)'"]*)?$/, `$1${rewriteSpecifier}$2`);
48
48
  }
49
49
  };
50
50
  const normalizeBuiltinSpecifier = value => {
package/dist/specifier.js CHANGED
@@ -111,6 +111,9 @@ const formatSpecifiers = async (src, ast, cb) => {
111
111
  };
112
112
  await walk(ast.program, {
113
113
  enter(node) {
114
+ if (node.type === 'ImportExpression') {
115
+ formatExpression(node);
116
+ }
114
117
  if (node.type === 'ExpressionStatement') {
115
118
  const {
116
119
  expression
@@ -21,7 +21,8 @@ export type ModuleOptions = {
21
21
  appendJsExtension?: 'off' | 'relative-only' | 'all';
22
22
  /** Add directory index (e.g. /index.js) or disable. */
23
23
  appendDirectoryIndex?: string | false;
24
- /** Control __dirname and __filename handling. */
24
+ /** Precedence: rewriteSpecifier runs first; if it returns a string that wins. If it returns undefined or null, appenders apply. Bare specifiers are never modified by appenders. */
25
+ /** Control __dirname/__filename handling (inject shims, preserve existing, or throw on use). */
25
26
  dirFilename?: 'inject' | 'preserve' | 'error';
26
27
  /** How to treat import.meta. */
27
28
  importMeta?: 'preserve' | 'shim' | 'error';
package/dist/types.d.ts CHANGED
@@ -21,7 +21,8 @@ export type ModuleOptions = {
21
21
  appendJsExtension?: 'off' | 'relative-only' | 'all';
22
22
  /** Add directory index (e.g. /index.js) or disable. */
23
23
  appendDirectoryIndex?: string | false;
24
- /** Control __dirname and __filename handling. */
24
+ /** Precedence: rewriteSpecifier runs first; if it returns a string that wins. If it returns undefined or null, appenders apply. Bare specifiers are never modified by appenders. */
25
+ /** Control __dirname/__filename handling (inject shims, preserve existing, or throw on use). */
25
26
  dirFilename?: 'inject' | 'preserve' | 'error';
26
27
  /** How to treat import.meta. */
27
28
  importMeta?: 'preserve' | 'shim' | 'error';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@knighted/module",
3
- "version": "1.0.0-rc.6",
3
+ "version": "1.0.0",
4
4
  "description": "Bidirectional transform for ES modules and CommonJS.",
5
5
  "type": "module",
6
6
  "main": "dist/module.js",
@@ -19,12 +19,12 @@
19
19
  "./package.json": "./package.json"
20
20
  },
21
21
  "imports": {
22
- "#parse": "./dist/parse.js",
23
- "#format": "./dist/format.js",
24
- "#utils/*.js": "./dist/utils/*.js",
25
- "#walk": "./dist/walk.js",
26
- "#helpers/*.js": "./dist/helpers/*.js",
27
- "#formatters/*.js": "./dist/formatters/*.js"
22
+ "#parse": "./src/parse.js",
23
+ "#format": "./src/format.js",
24
+ "#utils/*.js": "./src/utils/*.js",
25
+ "#walk": "./src/walk.js",
26
+ "#helpers/*.js": "./src/helpers/*.js",
27
+ "#formatters/*.js": "./src/formatters/*.js"
28
28
  },
29
29
  "engines": {
30
30
  "node": ">=22.21.1 <23 || >=24 <25"
@@ -1,12 +0,0 @@
1
- import MagicString from 'magic-string';
2
- import type { Node, AssignmentExpression } from 'oxc-parser';
3
- import type { FormatterOptions, ExportsMeta } from '../types.cjs';
4
- type AssignmentExpressionArg = {
5
- node: AssignmentExpression;
6
- parent: Node | null;
7
- code: MagicString;
8
- opts: FormatterOptions;
9
- meta: ExportsMeta;
10
- };
11
- export declare const assignmentExpression: ({ node, parent: _parent, code: _code, opts, meta: _meta, }: AssignmentExpressionArg) => Promise<void>;
12
- export {};
@@ -1,12 +0,0 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.scopes = exports.scope = void 0;
7
- const scopes = exports.scopes = ['BlockStatement', 'FunctionDeclaration', 'FunctionExpression', 'ArrowFunctionExpression', 'ClassDeclaration', 'ClassExpression', 'ClassBody', 'StaticBlock'];
8
- const scope = exports.scope = {
9
- isScope(node) {
10
- return scopes.includes(node.type);
11
- }
12
- };
@@ -1,6 +0,0 @@
1
- import type { Node } from 'oxc-parser';
2
- declare const scopes: string[];
3
- declare const scope: {
4
- isScope(node: Node): boolean;
5
- };
6
- export { scopes, scope };
@@ -1,6 +0,0 @@
1
- import type { Node } from 'oxc-parser';
2
- import type { CjsExport } from '../types.cjs';
3
- declare const exportsRename = "__exports";
4
- declare const requireMainRgx: RegExp;
5
- declare const collectCjsExports: (ast: Node) => Promise<Map<string, CjsExport>>;
6
- export { exportsRename, requireMainRgx, collectCjsExports };
@@ -1,4 +0,0 @@
1
- import MagicString from 'magic-string';
2
- import type { Node, ExpressionStatement } from 'oxc-parser';
3
- import type { FormatterOptions } from '../types.cjs';
4
- export declare const expressionStatement: (node: ExpressionStatement, parent: Node | null, src: MagicString, options: FormatterOptions) => void;
package/dist/format.d.cts DELETED
@@ -1,9 +0,0 @@
1
- import type { ParseResult } from 'oxc-parser';
2
- import type { FormatterOptions } from './types.cjs';
3
- /**
4
- * Node added support for import.meta.main.
5
- * Added in: v24.2.0, v22.18.0
6
- * @see https://nodejs.org/api/esm.html#importmetamain
7
- */
8
- declare const format: (src: string, ast: ParseResult, opts: FormatterOptions) => Promise<string>;
9
- export { format };
@@ -1,12 +0,0 @@
1
- import MagicString from 'magic-string';
2
- import type { Node, AssignmentExpression } from 'oxc-parser';
3
- import type { FormatterOptions, ExportsMeta } from '../types.js';
4
- type AssignmentExpressionArg = {
5
- node: AssignmentExpression;
6
- parent: Node | null;
7
- code: MagicString;
8
- opts: FormatterOptions;
9
- meta: ExportsMeta;
10
- };
11
- export declare const assignmentExpression: ({ node, parent: _parent, code: _code, opts, meta: _meta, }: AssignmentExpressionArg) => Promise<void>;
12
- export {};
@@ -1,4 +0,0 @@
1
- import MagicString from 'magic-string';
2
- import type { Node, ExpressionStatement } from 'oxc-parser';
3
- import type { FormatterOptions } from '../types.js';
4
- export declare const expressionStatement: (node: ExpressionStatement, parent: Node | null, src: MagicString, options: FormatterOptions) => void;
@@ -1,12 +0,0 @@
1
- import MagicString from 'magic-string';
2
- import type { Node, IdentifierName } from 'oxc-parser';
3
- import type { FormatterOptions, ExportsMeta } from '../types.js';
4
- type IdentifierArg = {
5
- node: IdentifierName;
6
- ancestors: Node[];
7
- code: MagicString;
8
- opts: FormatterOptions;
9
- meta: ExportsMeta;
10
- };
11
- export declare const identifier: ({ node, ancestors, code, opts, meta }: IdentifierArg) => void;
12
- export {};
@@ -1,4 +0,0 @@
1
- import MagicString from 'magic-string';
2
- import type { MemberExpression, Node } from 'oxc-parser';
3
- import type { FormatterOptions } from '../types.js';
4
- export declare const memberExpression: (node: MemberExpression, parent: Node | null, src: MagicString, options: FormatterOptions) => void;
@@ -1,4 +0,0 @@
1
- import MagicString from 'magic-string';
2
- import type { Node, MetaProperty } from 'oxc-parser';
3
- import type { FormatterOptions } from '../types.js';
4
- export declare const metaProperty: (node: MetaProperty, parent: Node | null, src: MagicString, options: FormatterOptions) => void;
@@ -1,31 +0,0 @@
1
- import type { Node, IdentifierName } from 'oxc-parser';
2
- /**
3
- * Focus exclusively on IdentifierName type as it has the name property,
4
- * which is what the identifer utilities are interested in.
5
- *
6
- * Explicitly ignore the TSThisParameter type as it is not a valid identifier name.
7
- */
8
- declare const isIdentifierName: (node: Node) => node is IdentifierName;
9
- /**
10
- * All methods receive the full set of ancestors, which
11
- * specifically includes the node itself as the last element.
12
- * The second to last element is the parent node, and so on.
13
- * The first element is the root node.
14
- */
15
- declare const identifier: {
16
- isNamed: (node: Node) => node is IdentifierName;
17
- isMetaProperty(ancestors: Node[]): boolean;
18
- isModuleScope(ancestors: Node[], includeImports?: boolean): boolean;
19
- isMemberExpressionRoot(ancestors: Node[]): boolean;
20
- isDeclaration(ancestors: Node[]): boolean;
21
- isClassOrFuncDeclarationId(ancestors: Node[]): boolean;
22
- isVarDeclarationInGlobalScope(ancestors: Node[]): boolean;
23
- isIife(ancestors: Node[]): boolean;
24
- isFunctionExpressionId(ancestors: Node[]): boolean;
25
- isExportSpecifierAlias(ancestors: Node[]): boolean;
26
- isClassPropertyKey(ancestors: Node[]): boolean;
27
- isMethodDefinitionKey(ancestors: Node[]): boolean;
28
- isMemberKey(ancestors: Node[]): boolean;
29
- isPropertyKey(ancestors: Node[]): boolean;
30
- };
31
- export { identifier, isIdentifierName };
@@ -1,6 +0,0 @@
1
- import type { Node } from 'oxc-parser';
2
- declare const scopes: string[];
3
- declare const scope: {
4
- isScope(node: Node): boolean;
5
- };
6
- export { scopes, scope };
@@ -1,7 +0,0 @@
1
- const scopes = ['BlockStatement', 'FunctionDeclaration', 'FunctionExpression', 'ArrowFunctionExpression', 'ClassDeclaration', 'ClassExpression', 'ClassBody', 'StaticBlock'];
2
- const scope = {
3
- isScope(node) {
4
- return scopes.includes(node.type);
5
- }
6
- };
7
- export { scopes, scope };
@@ -1,31 +0,0 @@
1
- import type { Node, IdentifierName } from 'oxc-parser';
2
- /**
3
- * Focus exclusively on IdentifierName type as it has the name property,
4
- * which is what the identifer utilities are interested in.
5
- *
6
- * Explicitly ignore the TSThisParameter type as it is not a valid identifier name.
7
- */
8
- declare const isIdentifierName: (node: Node) => node is IdentifierName;
9
- /**
10
- * All methods receive the full set of ancestors, which
11
- * specifically includes the node itself as the last element.
12
- * The second to last element is the parent node, and so on.
13
- * The first element is the root node.
14
- */
15
- declare const identifier: {
16
- isNamed: (node: Node) => node is IdentifierName;
17
- isMetaProperty(ancestors: Node[]): boolean;
18
- isModuleScope(ancestors: Node[], includeImports?: boolean): boolean;
19
- isMemberExpressionRoot(ancestors: Node[]): boolean;
20
- isDeclaration(ancestors: Node[]): boolean;
21
- isClassOrFuncDeclarationId(ancestors: Node[]): boolean;
22
- isVarDeclarationInGlobalScope(ancestors: Node[]): boolean;
23
- isIife(ancestors: Node[]): boolean;
24
- isFunctionExpressionId(ancestors: Node[]): boolean;
25
- isExportSpecifierAlias(ancestors: Node[]): boolean;
26
- isClassPropertyKey(ancestors: Node[]): boolean;
27
- isMethodDefinitionKey(ancestors: Node[]): boolean;
28
- isMemberKey(ancestors: Node[]): boolean;
29
- isPropertyKey(ancestors: Node[]): boolean;
30
- };
31
- export { identifier, isIdentifierName };
@@ -1,19 +0,0 @@
1
- import type { Node } from 'oxc-parser';
2
- import type { IdentMeta, Scope } from '../types.cjs';
3
- declare const collectScopeIdentifiers: (node: Node, scopes: Scope[]) => void;
4
- /**
5
- * Collects all module scope identifiers in the AST.
6
- *
7
- * Ignores identifiers that are in functions or classes.
8
- * Ignores new scopes for StaticBlock nodes (can only reference static class members).
9
- *
10
- * Special case handling for these which create their own scopes,
11
- * but are also valid module scope identifiers:
12
- * - ClassDeclaration
13
- * - FunctionDeclaration
14
- *
15
- * Special case handling for var inside BlockStatement
16
- * which are also valid module scope identifiers.
17
- */
18
- declare const collectModuleIdentifiers: (ast: Node, hoisting?: boolean) => Promise<Map<string, IdentMeta>>;
19
- export { collectScopeIdentifiers, collectModuleIdentifiers };
package/dist/lang.d.cts DELETED
@@ -1,3 +0,0 @@
1
- import type { ParserOptions } from 'oxc-parser';
2
- declare const getLangFromExt: (filename: string) => ParserOptions["lang"] | undefined;
3
- export { getLangFromExt };
@@ -1,13 +0,0 @@
1
- import MagicString from 'magic-string';
2
- import type { MemberExpression, Node } from 'oxc-parser';
3
- import type { FormatterOptions } from '../types.cjs';
4
- type MemberExpressionExtras = {
5
- onRequireResolve?: () => void;
6
- requireResolveName?: string;
7
- onDiagnostic?: (code: string, message: string, loc?: {
8
- start: number;
9
- end: number;
10
- }) => void;
11
- };
12
- export declare const memberExpression: (node: MemberExpression, parent: Node | null, src: MagicString, options: FormatterOptions, shadowed?: Set<string>, extras?: MemberExpressionExtras, useExportsBag?: boolean, rewriteExports?: boolean) => void;
13
- export {};
@@ -1,4 +0,0 @@
1
- import MagicString from 'magic-string';
2
- import type { Node, MetaProperty } from 'oxc-parser';
3
- import type { FormatterOptions } from '../types.cjs';
4
- export declare const metaProperty: (node: MetaProperty, parent: Node | null, src: MagicString, options: FormatterOptions) => void;
package/dist/module.d.cts DELETED
@@ -1,3 +0,0 @@
1
- import type { ModuleOptions } from './types.cjs';
2
- declare const transform: (filename: string, options?: ModuleOptions) => Promise<string>;
3
- export { transform };
package/dist/parse.d.cts DELETED
@@ -1,2 +0,0 @@
1
- declare const parse: (filename: string, code: string) => import("oxc-parser").ParseResult;
2
- export { parse };
package/dist/scope.d.cts DELETED
@@ -1,6 +0,0 @@
1
- import type { Node } from 'oxc-parser';
2
- declare const scopes: string[];
3
- declare const scope: {
4
- isScope(node: Node): boolean;
5
- };
6
- export { scopes, scope };
package/dist/scope.d.ts DELETED
@@ -1,6 +0,0 @@
1
- import type { Node } from 'oxc-parser';
2
- declare const scopes: string[];
3
- declare const scope: {
4
- isScope(node: Node): boolean;
5
- };
6
- export { scopes, scope };
@@ -1,2 +0,0 @@
1
- declare const scopeNodes: string[];
2
- export { scopeNodes };
@@ -1,16 +0,0 @@
1
- import type { ParserOptions, StringLiteral, TemplateLiteral, BinaryExpression, NewExpression, ImportDeclaration, ExportNamedDeclaration, ExportAllDeclaration, TSImportType, ImportExpression, CallExpression } from 'oxc-parser';
2
- type Spec = {
3
- type: 'StringLiteral' | 'TemplateLiteral' | 'BinaryExpression' | 'NewExpression';
4
- node: StringLiteral | TemplateLiteral | BinaryExpression | NewExpression;
5
- parent: CallExpression | ImportDeclaration | ExportNamedDeclaration | ExportAllDeclaration | ImportExpression | TSImportType;
6
- start: number;
7
- end: number;
8
- value: string;
9
- };
10
- type Callback = (spec: Spec) => string | void;
11
- declare const specifier: {
12
- update(path: string, callback: Callback): Promise<string>;
13
- updateSrc(src: string, lang: ParserOptions["lang"], callback: Callback): Promise<string>;
14
- };
15
- export { specifier };
16
- export type { Spec, Callback };
@@ -1,6 +0,0 @@
1
- import type { Node } from 'oxc-parser';
2
- declare const scopes: string[];
3
- declare const scope: {
4
- isScope(node: Node): boolean;
5
- };
6
- export { scopes, scope };
package/dist/types.d.cts DELETED
@@ -1,90 +0,0 @@
1
- import type { Node, Span, IdentifierName, IdentifierReference, BindingIdentifier, LabelIdentifier, TSIndexSignatureName } from 'oxc-parser';
2
- export type RewriteSpecifier = '.js' | '.mjs' | '.cjs' | '.ts' | '.mts' | '.cts' | ((value: string) => string | null | undefined);
3
- /** Options that control how modules are parsed, transformed, and emitted. */
4
- export type ModuleOptions = {
5
- /** Output format to emit. */
6
- target: 'module' | 'commonjs';
7
- /** Explicit source type; auto infers from file extension. */
8
- sourceType?: 'auto' | 'module' | 'commonjs';
9
- /**
10
- * Enable syntax transforms beyond parsing.
11
- * - true: full CJS↔ESM lowering/raising
12
- * - 'globals-only': rewrite module-global differences (import.meta, __dirname/filename, require.main shims) while leaving import/export shapes untouched
13
- * - false/undefined: no syntax transforms
14
- */
15
- transformSyntax?: boolean | 'globals-only';
16
- /** How to emit live bindings for ESM exports. */
17
- liveBindings?: 'strict' | 'loose' | 'off';
18
- /** Rewrite import specifiers (e.g. add extensions). */
19
- rewriteSpecifier?: RewriteSpecifier;
20
- /** Whether to append .js to relative imports. */
21
- appendJsExtension?: 'off' | 'relative-only' | 'all';
22
- /** Add directory index (e.g. /index.js) or disable. */
23
- appendDirectoryIndex?: string | false;
24
- /** Control __dirname and __filename handling. */
25
- dirFilename?: 'inject' | 'preserve' | 'error';
26
- /** How to treat import.meta. */
27
- importMeta?: 'preserve' | 'shim' | 'error';
28
- /** Strategy for import.meta.main emulation. */
29
- importMetaMain?: 'shim' | 'warn' | 'error';
30
- /** Resolution strategy for detecting the main module. */
31
- requireMainStrategy?: 'import-meta-main' | 'realpath';
32
- /** Detect circular require usage level. */
33
- detectCircularRequires?: 'off' | 'warn' | 'error';
34
- /** Source used to provide require in ESM output. */
35
- requireSource?: 'builtin' | 'create-require';
36
- /** How to rewrite nested or non-hoistable require calls. */
37
- nestedRequireStrategy?: 'create-require' | 'dynamic-import';
38
- /** Default interop style for CommonJS default imports. */
39
- cjsDefault?: 'module-exports' | 'auto' | 'none';
40
- /** Emit idiomatic exports when raising CJS to ESM. */
41
- idiomaticExports?: 'off' | 'safe' | 'aggressive';
42
- /** Handling for top-level await constructs. */
43
- topLevelAwait?: 'error' | 'wrap' | 'preserve';
44
- /** Optional diagnostics sink for warnings/errors emitted during transform. */
45
- diagnostics?: (diag: Diagnostic) => void;
46
- /** Optional source file path used for diagnostics context. */
47
- filePath?: string;
48
- /** Output directory or file path when writing. */
49
- out?: string;
50
- /** Overwrite input files instead of writing to out. */
51
- inPlace?: boolean;
52
- };
53
- export type Diagnostic = {
54
- level: 'warning' | 'error';
55
- code: string;
56
- message: string;
57
- filePath?: string;
58
- loc?: {
59
- start: number;
60
- end: number;
61
- };
62
- };
63
- export type SpannedNode = Node & Span;
64
- export type ExportsMeta = {
65
- hasExportsBeenReassigned: boolean;
66
- hasDefaultExportBeenReassigned: boolean;
67
- hasDefaultExportBeenAssigned: boolean;
68
- defaultExportValue: unknown;
69
- };
70
- export type CjsExport = {
71
- key: string;
72
- writes: SpannedNode[];
73
- fromIdentifier?: string;
74
- via: Set<'exports' | 'module.exports'>;
75
- reassignments: SpannedNode[];
76
- hasGetter?: boolean;
77
- hasNonTopLevelWrite?: boolean;
78
- };
79
- export type IdentMeta = {
80
- declare: SpannedNode[];
81
- read: SpannedNode[];
82
- };
83
- export type Scope = {
84
- type: string;
85
- name: string;
86
- node: Node;
87
- idents: Set<string>;
88
- };
89
- export type FormatterOptions = Omit<ModuleOptions, 'out' | 'inPlace'>;
90
- export type Identifier = IdentifierName | IdentifierReference | BindingIdentifier | LabelIdentifier | TSIndexSignatureName;
package/dist/url.d.cts DELETED
@@ -1,2 +0,0 @@
1
- declare const isValidUrl: (url: string) => boolean;
2
- export { isValidUrl };
package/dist/utils.d.cts DELETED
@@ -1,23 +0,0 @@
1
- import type { Node } from 'oxc-parser';
2
- import type { IdentMeta, Scope, CjsExport } from './types.cjs';
3
- declare const isValidUrl: (url: string) => boolean;
4
- declare const exportsRename = "__exports";
5
- declare const requireMainRgx: RegExp;
6
- declare const collectCjsExports: (ast: Node) => Promise<Map<string, CjsExport>>;
7
- declare const collectScopeIdentifiers: (node: Node, scopes: Scope[]) => void;
8
- /**
9
- * Collects all module scope identifiers in the AST.
10
- *
11
- * Ignores identifiers that are in functions or classes.
12
- * Ignores new scopes for StaticBlock nodes (can only reference static class members).
13
- *
14
- * Special case handling for these which create their own scopes,
15
- * but are also valid module scope identifiers:
16
- * - ClassDeclaration
17
- * - FunctionDeclaration
18
- *
19
- * Special case handling for var inside BlockStatement
20
- * which are also valid module scope identifiers.
21
- */
22
- declare const collectModuleIdentifiers: (ast: Node, hoisting?: boolean) => Promise<Map<string, IdentMeta>>;
23
- export { isValidUrl, collectScopeIdentifiers, collectModuleIdentifiers, collectCjsExports, exportsRename, requireMainRgx, };
package/dist/walk.d.cts DELETED
@@ -1,20 +0,0 @@
1
- import type { Node } from 'oxc-parser';
2
- /**
3
- * Using visitorKeys instead of oxc Visitor to keep
4
- * an ancestor-aware enter/leave API with this.skip()
5
- * without per-node method boilerplate.
6
- */
7
- type AncestorContext = {
8
- skip: () => void;
9
- };
10
- type AncestorVisitor = {
11
- enter?: (this: AncestorContext, node: Node, ancestors: Node[]) => void | Promise<void>;
12
- leave?: (this: AncestorContext, node: Node, ancestors: Node[]) => void | Promise<void>;
13
- };
14
- type WalkVisitor = {
15
- enter?: (this: AncestorContext, node: Node, parent: Node | null) => void | Promise<void>;
16
- leave?: (this: AncestorContext, node: Node, parent: Node | null) => void | Promise<void>;
17
- };
18
- declare const ancestorWalk: (node: Node, visitors: AncestorVisitor) => Promise<void>;
19
- declare const walk: (node: Node, visitors: WalkVisitor) => Promise<void>;
20
- export { ancestorWalk, walk };