@knighted/module 1.0.0-rc.6 → 1.1.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 (41) hide show
  1. package/README.md +25 -7
  2. package/dist/cjs/format.cjs +27 -5
  3. package/dist/cjs/module.cjs +2 -1
  4. package/dist/cjs/specifier.cjs +3 -0
  5. package/dist/cjs/types.d.cts +4 -1
  6. package/dist/format.js +27 -5
  7. package/dist/module.js +2 -1
  8. package/dist/specifier.js +3 -0
  9. package/dist/src/types.d.ts +4 -1
  10. package/dist/types.d.ts +4 -1
  11. package/package.json +7 -7
  12. package/dist/assignmentExpression.d.cts +0 -12
  13. package/dist/cjs/helpers/scope.cjs +0 -12
  14. package/dist/cjs/scope.d.cts +0 -6
  15. package/dist/exports.d.cts +0 -6
  16. package/dist/expressionStatement.d.cts +0 -4
  17. package/dist/format.d.cts +0 -9
  18. package/dist/formatters/assignmentExpression.d.ts +0 -12
  19. package/dist/formatters/expressionStatement.d.ts +0 -4
  20. package/dist/formatters/identifier.d.ts +0 -12
  21. package/dist/formatters/memberExpression.d.ts +0 -4
  22. package/dist/formatters/metaProperty.d.ts +0 -4
  23. package/dist/helpers/identifier.d.ts +0 -31
  24. package/dist/helpers/scope.d.ts +0 -6
  25. package/dist/helpers/scope.js +0 -7
  26. package/dist/identifier.d.cts +0 -31
  27. package/dist/identifiers.d.cts +0 -19
  28. package/dist/lang.d.cts +0 -3
  29. package/dist/memberExpression.d.cts +0 -13
  30. package/dist/metaProperty.d.cts +0 -4
  31. package/dist/module.d.cts +0 -3
  32. package/dist/parse.d.cts +0 -2
  33. package/dist/scope.d.cts +0 -6
  34. package/dist/scope.d.ts +0 -6
  35. package/dist/scopeNodes.d.cts +0 -2
  36. package/dist/specifier.d.cts +0 -16
  37. package/dist/src/helpers/scope.d.ts +0 -6
  38. package/dist/types.d.cts +0 -90
  39. package/dist/url.d.cts +0 -2
  40. package/dist/utils.d.cts +0 -23
  41. package/dist/walk.d.cts +0 -20
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
@@ -117,29 +130,34 @@ type ModuleOptions = {
117
130
  requireMainStrategy?: 'import-meta-main' | 'realpath'
118
131
  detectCircularRequires?: 'off' | 'warn' | 'error'
119
132
  requireSource?: 'builtin' | 'create-require'
133
+ importMetaPrelude?: 'off' | 'auto' | 'on'
120
134
  cjsDefault?: 'module-exports' | 'auto' | 'none'
135
+ idiomaticExports?: 'off' | 'safe' | 'aggressive'
121
136
  topLevelAwait?: 'error' | 'wrap' | 'preserve'
122
137
  out?: string
123
138
  inPlace?: boolean
124
139
  }
125
140
  ```
126
141
 
127
- Behavior notes (defaults in parentheses)
142
+ ### Behavior notes (defaults in parentheses)
128
143
 
129
144
  - `target` (`commonjs`): output module system.
130
145
  - `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
146
  - `liveBindings` (`strict`): getter-based live bindings, or snapshot (`loose`/`off`).
132
147
  - `appendJsExtension` (`relative-only` when targeting ESM): append `.js` to relative specifiers; never touches bare specifiers.
133
148
  - `appendDirectoryIndex` (`index.js`): when a relative specifier ends with a slash, append this index filename (set `false` to disable).
149
+ - `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
150
  - `dirFilename` (`inject`): inject `__dirname`/`__filename`, preserve existing, or throw.
135
151
  - `importMeta` (`shim`): rewrite `import.meta.*` to CommonJS equivalents.
136
152
  - `importMetaMain` (`shim`): gate `import.meta.main` with shimming/warning/error when Node support is too old.
137
153
  - `requireMainStrategy` (`import-meta-main`): use `import.meta.main` or the realpath-based `pathToFileURL(realpathSync(process.argv[1])).href` check.
154
+ - `importMetaPrelude` (`auto`): emit a no-op `void import.meta.filename;` touch. `on` always emits; `off` never emits; `auto` emits only when helpers that reference `import.meta.*` are synthesized (e.g., `__dirname`/`__filename` in CJS→ESM, require-main shims, createRequire helpers). Useful for bundlers/transpilers that do usage-based `import.meta` polyfilling.
138
155
  - `detectCircularRequires` (`off`): optionally detect relative static require cycles and warn/throw.
139
156
  - `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.
157
+ - `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
158
  - `requireSource` (`builtin`): whether `require` comes from Node or `createRequire`.
142
159
  - `cjsDefault` (`auto`): bundler-style default interop vs direct `module.exports`.
160
+ - `idiomaticExports` (`safe`): when raising CJS to ESM, attempt to synthesize `export` statements directly when it is safe. `off` always uses the helper bag; `aggressive` currently matches `safe` heuristics.
143
161
  - `out`/`inPlace`: write the transformed code to a file; otherwise the function returns the transformed string only.
144
162
  - CommonJS → ESM lowering will throw on `with` statements and unshadowed `eval` calls to avoid unsound rewrites.
145
163
 
@@ -607,6 +607,8 @@ const format = async (src, ast, opts) => {
607
607
  let requireMainNeedsRealpath = false;
608
608
  let needsRequireResolveHelper = false;
609
609
  const nestedRequireStrategy = opts.nestedRequireStrategy ?? 'create-require';
610
+ const importMetaPreludeMode = opts.importMetaPrelude ?? 'auto';
611
+ let importMetaRef = false;
610
612
  const shouldLowerCjs = opts.target === 'commonjs' && fullTransform;
611
613
  const shouldRaiseEsm = opts.target === 'module' && fullTransform;
612
614
  let hoistedImports = [];
@@ -654,6 +656,10 @@ const format = async (src, ast, opts) => {
654
656
  const mainExpr = requireMainStrategy === 'import-meta-main' ? 'import.meta.main' : 'import.meta.url === pathToFileURL(realpathSync(process.argv[1])).href';
655
657
  if (requireMainStrategy === 'realpath') {
656
658
  requireMainNeedsRealpath = true;
659
+ importMetaRef = true;
660
+ }
661
+ if (requireMainStrategy === 'import-meta-main') {
662
+ importMetaRef = true;
657
663
  }
658
664
  code.update(node.start, node.end, negate ? `!(${mainExpr})` : mainExpr);
659
665
  return;
@@ -772,6 +778,9 @@ const format = async (src, ast, opts) => {
772
778
  }
773
779
  }
774
780
  if ((0, _identifier2.isIdentifierName)(node)) {
781
+ if (shouldRaiseEsm && node.type === 'Identifier' && (node.name === '__dirname' || node.name === '__filename')) {
782
+ importMetaRef = true;
783
+ }
775
784
  (0, _identifier.identifier)({
776
785
  node,
777
786
  ancestors,
@@ -827,8 +836,14 @@ const format = async (src, ast, opts) => {
827
836
  const asExportName = name => isValidExportName(name) ? name : JSON.stringify(name);
828
837
  const accessProp = name => isValidExportName(name) ? `${_exports.exportsRename}.${name}` : `${_exports.exportsRename}[${JSON.stringify(name)}]`;
829
838
  const exportValueFor = name => {
830
- if (name === '__dirname') return 'import.meta.dirname';
831
- if (name === '__filename') return 'import.meta.filename';
839
+ if (name === '__dirname') {
840
+ importMetaRef = true;
841
+ return 'import.meta.dirname';
842
+ }
843
+ if (name === '__filename') {
844
+ importMetaRef = true;
845
+ return 'import.meta.filename';
846
+ }
832
847
  return name;
833
848
  };
834
849
  const tempNameFor = name => {
@@ -884,6 +899,9 @@ const format = async (src, ast, opts) => {
884
899
  }
885
900
  if (shouldRaiseEsm && fullTransform) {
886
901
  const importPrelude = [];
902
+ if (needsCreateRequire || needsRequireResolveHelper) {
903
+ importMetaRef = true;
904
+ }
887
905
  if (needsCreateRequire || needsRequireResolveHelper) {
888
906
  importPrelude.push('import { createRequire } from "node:module";\n');
889
907
  }
@@ -916,9 +934,13 @@ const format = async (src, ast, opts) => {
916
934
  const exportsBagInit = useExportsBag ? `let ${_exports.exportsRename} = {};
917
935
  ` : '';
918
936
  const modulePrelude = '';
919
- const prelude = `${importPrelude.join('')}${importPrelude.length ? '\n' : ''}${setupPrelude.join('')}${setupPrelude.length ? '\n' : ''}${requireInit}${requireResolveInit}${exportsBagInit}${modulePrelude}void import.meta.filename;
920
- `;
921
- code.prepend(prelude);
937
+ const prelude = `${importPrelude.join('')}${importPrelude.length ? '\n' : ''}${setupPrelude.join('')}${setupPrelude.length ? '\n' : ''}${requireInit}${requireResolveInit}${exportsBagInit}${modulePrelude}`;
938
+ const importMetaTouch = (() => {
939
+ if (importMetaPreludeMode === 'on') return 'void import.meta.filename;\n';
940
+ if (importMetaPreludeMode === 'off') return '';
941
+ return importMetaRef ? 'void import.meta.filename;\n' : '';
942
+ })();
943
+ code.prepend(`${prelude}${importMetaTouch}`);
922
944
  }
923
945
  if (opts.target === 'commonjs' && fullTransform && containsTopLevelAwait) {
924
946
  const body = code.toString();
@@ -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 => {
@@ -161,6 +161,7 @@ const defaultOptions = {
161
161
  nestedRequireStrategy: 'create-require',
162
162
  cjsDefault: 'auto',
163
163
  idiomaticExports: 'safe',
164
+ importMetaPrelude: 'auto',
164
165
  topLevelAwait: 'error',
165
166
  out: undefined,
166
167
  inPlace: false
@@ -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';
@@ -39,6 +40,8 @@ export type ModuleOptions = {
39
40
  cjsDefault?: 'module-exports' | 'auto' | 'none';
40
41
  /** Emit idiomatic exports when raising CJS to ESM. */
41
42
  idiomaticExports?: 'off' | 'safe' | 'aggressive';
43
+ /** Control whether a no-op import.meta prelude is emitted. */
44
+ importMetaPrelude?: 'off' | 'auto' | 'on';
42
45
  /** Handling for top-level await constructs. */
43
46
  topLevelAwait?: 'error' | 'wrap' | 'preserve';
44
47
  /** Optional diagnostics sink for warnings/errors emitted during transform. */
package/dist/format.js CHANGED
@@ -600,6 +600,8 @@ const format = async (src, ast, opts) => {
600
600
  let requireMainNeedsRealpath = false;
601
601
  let needsRequireResolveHelper = false;
602
602
  const nestedRequireStrategy = opts.nestedRequireStrategy ?? 'create-require';
603
+ const importMetaPreludeMode = opts.importMetaPrelude ?? 'auto';
604
+ let importMetaRef = false;
603
605
  const shouldLowerCjs = opts.target === 'commonjs' && fullTransform;
604
606
  const shouldRaiseEsm = opts.target === 'module' && fullTransform;
605
607
  let hoistedImports = [];
@@ -647,6 +649,10 @@ const format = async (src, ast, opts) => {
647
649
  const mainExpr = requireMainStrategy === 'import-meta-main' ? 'import.meta.main' : 'import.meta.url === pathToFileURL(realpathSync(process.argv[1])).href';
648
650
  if (requireMainStrategy === 'realpath') {
649
651
  requireMainNeedsRealpath = true;
652
+ importMetaRef = true;
653
+ }
654
+ if (requireMainStrategy === 'import-meta-main') {
655
+ importMetaRef = true;
650
656
  }
651
657
  code.update(node.start, node.end, negate ? `!(${mainExpr})` : mainExpr);
652
658
  return;
@@ -765,6 +771,9 @@ const format = async (src, ast, opts) => {
765
771
  }
766
772
  }
767
773
  if (isIdentifierName(node)) {
774
+ if (shouldRaiseEsm && node.type === 'Identifier' && (node.name === '__dirname' || node.name === '__filename')) {
775
+ importMetaRef = true;
776
+ }
768
777
  identifier({
769
778
  node,
770
779
  ancestors,
@@ -820,8 +829,14 @@ const format = async (src, ast, opts) => {
820
829
  const asExportName = name => isValidExportName(name) ? name : JSON.stringify(name);
821
830
  const accessProp = name => isValidExportName(name) ? `${exportsRename}.${name}` : `${exportsRename}[${JSON.stringify(name)}]`;
822
831
  const exportValueFor = name => {
823
- if (name === '__dirname') return 'import.meta.dirname';
824
- if (name === '__filename') return 'import.meta.filename';
832
+ if (name === '__dirname') {
833
+ importMetaRef = true;
834
+ return 'import.meta.dirname';
835
+ }
836
+ if (name === '__filename') {
837
+ importMetaRef = true;
838
+ return 'import.meta.filename';
839
+ }
825
840
  return name;
826
841
  };
827
842
  const tempNameFor = name => {
@@ -877,6 +892,9 @@ const format = async (src, ast, opts) => {
877
892
  }
878
893
  if (shouldRaiseEsm && fullTransform) {
879
894
  const importPrelude = [];
895
+ if (needsCreateRequire || needsRequireResolveHelper) {
896
+ importMetaRef = true;
897
+ }
880
898
  if (needsCreateRequire || needsRequireResolveHelper) {
881
899
  importPrelude.push('import { createRequire } from "node:module";\n');
882
900
  }
@@ -909,9 +927,13 @@ const format = async (src, ast, opts) => {
909
927
  const exportsBagInit = useExportsBag ? `let ${exportsRename} = {};
910
928
  ` : '';
911
929
  const modulePrelude = '';
912
- const prelude = `${importPrelude.join('')}${importPrelude.length ? '\n' : ''}${setupPrelude.join('')}${setupPrelude.length ? '\n' : ''}${requireInit}${requireResolveInit}${exportsBagInit}${modulePrelude}void import.meta.filename;
913
- `;
914
- code.prepend(prelude);
930
+ const prelude = `${importPrelude.join('')}${importPrelude.length ? '\n' : ''}${setupPrelude.join('')}${setupPrelude.length ? '\n' : ''}${requireInit}${requireResolveInit}${exportsBagInit}${modulePrelude}`;
931
+ const importMetaTouch = (() => {
932
+ if (importMetaPreludeMode === 'on') return 'void import.meta.filename;\n';
933
+ if (importMetaPreludeMode === 'off') return '';
934
+ return importMetaRef ? 'void import.meta.filename;\n' : '';
935
+ })();
936
+ code.prepend(`${prelude}${importMetaTouch}`);
915
937
  }
916
938
  if (opts.target === 'commonjs' && fullTransform && containsTopLevelAwait) {
917
939
  const body = code.toString();
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 => {
@@ -158,6 +158,7 @@ const defaultOptions = {
158
158
  nestedRequireStrategy: 'create-require',
159
159
  cjsDefault: 'auto',
160
160
  idiomaticExports: 'safe',
161
+ importMetaPrelude: 'auto',
161
162
  topLevelAwait: 'error',
162
163
  out: undefined,
163
164
  inPlace: false
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';
@@ -39,6 +40,8 @@ export type ModuleOptions = {
39
40
  cjsDefault?: 'module-exports' | 'auto' | 'none';
40
41
  /** Emit idiomatic exports when raising CJS to ESM. */
41
42
  idiomaticExports?: 'off' | 'safe' | 'aggressive';
43
+ /** Control whether a no-op import.meta prelude is emitted. */
44
+ importMetaPrelude?: 'off' | 'auto' | 'on';
42
45
  /** Handling for top-level await constructs. */
43
46
  topLevelAwait?: 'error' | 'wrap' | 'preserve';
44
47
  /** Optional diagnostics sink for warnings/errors emitted during transform. */
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';
@@ -39,6 +40,8 @@ export type ModuleOptions = {
39
40
  cjsDefault?: 'module-exports' | 'auto' | 'none';
40
41
  /** Emit idiomatic exports when raising CJS to ESM. */
41
42
  idiomaticExports?: 'off' | 'safe' | 'aggressive';
43
+ /** Control whether a no-op import.meta prelude is emitted. */
44
+ importMetaPrelude?: 'off' | 'auto' | 'on';
42
45
  /** Handling for top-level await constructs. */
43
46
  topLevelAwait?: 'error' | 'wrap' | 'preserve';
44
47
  /** Optional diagnostics sink for warnings/errors emitted during transform. */
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.1.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 };