@knighted/module 1.1.0 → 1.2.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 (51) hide show
  1. package/README.md +2 -7
  2. package/dist/ast.d.ts +39 -0
  3. package/dist/cjs/ast.d.cts +39 -0
  4. package/dist/cjs/exports.d.cts +4 -1
  5. package/dist/cjs/format.cjs +43 -25
  6. package/dist/cjs/formatters/assignmentExpression.cjs +1 -1
  7. package/dist/cjs/formatters/identifier.cjs +2 -2
  8. package/dist/cjs/formatters/memberExpression.cjs +1 -1
  9. package/dist/cjs/helpers/ast.cjs +29 -0
  10. package/dist/cjs/helpers/identifier.cjs +5 -3
  11. package/dist/cjs/module.cjs +8 -6
  12. package/dist/cjs/specifier.cjs +1 -1
  13. package/dist/cjs/types.d.cts +2 -0
  14. package/dist/cjs/utils/exports.cjs +1 -1
  15. package/dist/cjs/utils/identifiers.cjs +2 -2
  16. package/dist/exports.d.ts +4 -1
  17. package/dist/format.js +43 -25
  18. package/dist/formatters/assignmentExpression.js +1 -1
  19. package/dist/formatters/identifier.js +2 -2
  20. package/dist/formatters/memberExpression.js +1 -1
  21. package/dist/helpers/ast.d.ts +39 -0
  22. package/dist/helpers/ast.js +18 -0
  23. package/dist/helpers/identifier.js +5 -4
  24. package/dist/module.js +9 -7
  25. package/dist/specifier.js +1 -1
  26. package/dist/types.d.ts +2 -0
  27. package/dist/{src/utils → utils}/exports.d.ts +4 -1
  28. package/dist/utils/exports.js +1 -1
  29. package/dist/utils/identifiers.js +2 -2
  30. package/package.json +10 -13
  31. package/dist/cjs/utils.cjs +0 -274
  32. package/dist/cjs/utils.d.cts +0 -23
  33. package/dist/src/format.d.ts +0 -9
  34. package/dist/src/module.d.ts +0 -3
  35. package/dist/src/parse.d.ts +0 -2
  36. package/dist/src/specifier.d.ts +0 -16
  37. package/dist/src/types.d.ts +0 -93
  38. package/dist/src/utils.d.ts +0 -23
  39. package/dist/src/walk.d.ts +0 -20
  40. package/dist/utils.d.ts +0 -23
  41. package/dist/utils.js +0 -265
  42. /package/dist/{src/formatters → formatters}/assignmentExpression.d.ts +0 -0
  43. /package/dist/{src/formatters → formatters}/expressionStatement.d.ts +0 -0
  44. /package/dist/{src/formatters → formatters}/identifier.d.ts +0 -0
  45. /package/dist/{src/formatters → formatters}/memberExpression.d.ts +0 -0
  46. /package/dist/{src/formatters → formatters}/metaProperty.d.ts +0 -0
  47. /package/dist/{src/helpers → helpers}/identifier.d.ts +0 -0
  48. /package/dist/{src/utils → utils}/identifiers.d.ts +0 -0
  49. /package/dist/{src/utils → utils}/lang.d.ts +0 -0
  50. /package/dist/{src/utils → utils}/scopeNodes.d.ts +0 -0
  51. /package/dist/{src/utils → utils}/url.d.ts +0 -0
@@ -1,93 +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
- /** 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). */
26
- dirFilename?: 'inject' | 'preserve' | 'error';
27
- /** How to treat import.meta. */
28
- importMeta?: 'preserve' | 'shim' | 'error';
29
- /** Strategy for import.meta.main emulation. */
30
- importMetaMain?: 'shim' | 'warn' | 'error';
31
- /** Resolution strategy for detecting the main module. */
32
- requireMainStrategy?: 'import-meta-main' | 'realpath';
33
- /** Detect circular require usage level. */
34
- detectCircularRequires?: 'off' | 'warn' | 'error';
35
- /** Source used to provide require in ESM output. */
36
- requireSource?: 'builtin' | 'create-require';
37
- /** How to rewrite nested or non-hoistable require calls. */
38
- nestedRequireStrategy?: 'create-require' | 'dynamic-import';
39
- /** Default interop style for CommonJS default imports. */
40
- cjsDefault?: 'module-exports' | 'auto' | 'none';
41
- /** Emit idiomatic exports when raising CJS to ESM. */
42
- idiomaticExports?: 'off' | 'safe' | 'aggressive';
43
- /** Control whether a no-op import.meta prelude is emitted. */
44
- importMetaPrelude?: 'off' | 'auto' | 'on';
45
- /** Handling for top-level await constructs. */
46
- topLevelAwait?: 'error' | 'wrap' | 'preserve';
47
- /** Optional diagnostics sink for warnings/errors emitted during transform. */
48
- diagnostics?: (diag: Diagnostic) => void;
49
- /** Optional source file path used for diagnostics context. */
50
- filePath?: string;
51
- /** Output directory or file path when writing. */
52
- out?: string;
53
- /** Overwrite input files instead of writing to out. */
54
- inPlace?: boolean;
55
- };
56
- export type Diagnostic = {
57
- level: 'warning' | 'error';
58
- code: string;
59
- message: string;
60
- filePath?: string;
61
- loc?: {
62
- start: number;
63
- end: number;
64
- };
65
- };
66
- export type SpannedNode = Node & Span;
67
- export type ExportsMeta = {
68
- hasExportsBeenReassigned: boolean;
69
- hasDefaultExportBeenReassigned: boolean;
70
- hasDefaultExportBeenAssigned: boolean;
71
- defaultExportValue: unknown;
72
- };
73
- export type CjsExport = {
74
- key: string;
75
- writes: SpannedNode[];
76
- fromIdentifier?: string;
77
- via: Set<'exports' | 'module.exports'>;
78
- reassignments: SpannedNode[];
79
- hasGetter?: boolean;
80
- hasNonTopLevelWrite?: boolean;
81
- };
82
- export type IdentMeta = {
83
- declare: SpannedNode[];
84
- read: SpannedNode[];
85
- };
86
- export type Scope = {
87
- type: string;
88
- name: string;
89
- node: Node;
90
- idents: Set<string>;
91
- };
92
- export type FormatterOptions = Omit<ModuleOptions, 'out' | 'inPlace'>;
93
- export type Identifier = IdentifierName | IdentifierReference | BindingIdentifier | LabelIdentifier | TSIndexSignatureName;
@@ -1,23 +0,0 @@
1
- import type { Node } from 'oxc-parser';
2
- import type { IdentMeta, Scope, CjsExport } from './types.js';
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, };
@@ -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 };
package/dist/utils.d.ts DELETED
@@ -1,23 +0,0 @@
1
- import type { Node } from 'oxc-parser';
2
- import type { IdentMeta, Scope, CjsExport } from './types.js';
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/utils.js DELETED
@@ -1,265 +0,0 @@
1
- import { ancestorWalk } from './walk.js';
2
- import { identifier } from './helpers/identifier.js';
3
- import { scopeNodes } from './utils/scopeNodes.js';
4
- const isValidUrl = url => {
5
- try {
6
- new URL(url);
7
- return true;
8
- } catch {
9
- return false;
10
- }
11
- };
12
- const exportsRename = '__exports';
13
- const requireMainRgx = /(require\.main\s*===\s*module|module\s*===\s*require\.main)/g;
14
- const resolveExportTarget = node => {
15
- if (node.type !== 'MemberExpression') return null;
16
- const base = node.object;
17
- const prop = node.property;
18
- if (prop.type !== 'Identifier') return null;
19
- if (base.type === 'Identifier' && base.name === 'exports') {
20
- return {
21
- key: prop.name,
22
- via: 'exports'
23
- };
24
- }
25
- if (base.type === 'MemberExpression' && base.object.type === 'Identifier' && base.object.name === 'module' && base.property.type === 'Identifier' && base.property.name === 'exports') {
26
- return {
27
- key: prop.name,
28
- via: 'module.exports'
29
- };
30
- }
31
- if (base.type === 'Identifier' && base.name === 'module' && prop.type === 'Identifier' && prop.name === 'exports') {
32
- return {
33
- key: 'default',
34
- via: 'module.exports'
35
- };
36
- }
37
- return null;
38
- };
39
- const collectCjsExports = async ast => {
40
- const exportsMap = new Map();
41
- const localToExport = new Map();
42
- await ancestorWalk(ast, {
43
- enter(node) {
44
- if (node.type === 'AssignmentExpression') {
45
- const target = resolveExportTarget(node.left);
46
- if (target) {
47
- const entry = exportsMap.get(target.key) ?? {
48
- key: target.key,
49
- writes: [],
50
- via: new Set(),
51
- reassignments: []
52
- };
53
- entry.via.add(target.via);
54
- entry.writes.push(node);
55
- if (node.right.type === 'Identifier') {
56
- entry.fromIdentifier ??= node.right.name;
57
- if (entry.fromIdentifier) {
58
- const set = localToExport.get(entry.fromIdentifier) ?? new Set();
59
- set.add(target.key);
60
- localToExport.set(entry.fromIdentifier, set);
61
- }
62
- }
63
- exportsMap.set(target.key, entry);
64
- return;
65
- }
66
- if (node.left.type === 'Identifier') {
67
- const keys = localToExport.get(node.left.name);
68
- if (keys) {
69
- keys.forEach(key => {
70
- const entry = exportsMap.get(key);
71
- if (entry) {
72
- entry.reassignments.push(node);
73
- exportsMap.set(key, entry);
74
- }
75
- });
76
- }
77
- }
78
- }
79
- }
80
- });
81
- return exportsMap;
82
- };
83
- const collectScopeIdentifiers = (node, scopes) => {
84
- const {
85
- type
86
- } = node;
87
- switch (type) {
88
- case 'BlockStatement':
89
- case 'ClassBody':
90
- scopes.push({
91
- node,
92
- type: 'Block',
93
- name: type,
94
- idents: new Set()
95
- });
96
- break;
97
- case 'FunctionDeclaration':
98
- case 'FunctionExpression':
99
- case 'ArrowFunctionExpression':
100
- {
101
- const name = node.id ? node.id.name : 'anonymous';
102
- const scope = {
103
- node,
104
- name,
105
- type: 'Function',
106
- idents: new Set()
107
- };
108
- node.params.map(param => {
109
- if (param.type === 'TSParameterProperty') {
110
- return param.parameter;
111
- }
112
- if (param.type === 'RestElement') {
113
- return param.argument;
114
- }
115
- if (param.type === 'AssignmentPattern') {
116
- return param.left;
117
- }
118
- return param;
119
- }).filter(identifier.isNamed).forEach(param => {
120
- scope.idents.add(param.name);
121
- });
122
-
123
- /**
124
- * If a FunctionExpression has an id, it is a named function expression.
125
- * The function expression name shadows the module scope identifier, so
126
- * we don't want to count reads of module identifers that have the same name.
127
- * They also do not cause a SyntaxError if the function expression name is
128
- * the same as a module scope identifier.
129
- *
130
- * TODO: Is this necessary for FunctionDeclaration?
131
- */
132
- if (node.type === 'FunctionExpression' && node.id) {
133
- scope.idents.add(node.id.name);
134
- }
135
-
136
- // First add the function to any previous scopes
137
- if (scopes.length > 0) {
138
- scopes[scopes.length - 1].idents.add(name);
139
- }
140
-
141
- // Then add the function scope to the scopes stack
142
- scopes.push(scope);
143
- }
144
- break;
145
- case 'ClassDeclaration':
146
- {
147
- const className = node.id ? node.id.name : 'anonymous';
148
-
149
- // First add the class to any previous scopes
150
- if (scopes.length > 0) {
151
- scopes[scopes.length - 1].idents.add(className);
152
- }
153
-
154
- // Then add the class to the scopes stack
155
- scopes.push({
156
- node,
157
- name: className,
158
- type: 'Class',
159
- idents: new Set()
160
- });
161
- }
162
- break;
163
- case 'ClassExpression':
164
- {}
165
- break;
166
- case 'VariableDeclaration':
167
- if (scopes.length > 0) {
168
- const scope = scopes[scopes.length - 1];
169
- node.declarations.forEach(decl => {
170
- if (decl.type === 'VariableDeclarator' && decl.id.type === 'Identifier') {
171
- scope.idents.add(decl.id.name);
172
- }
173
- });
174
- }
175
- break;
176
- }
177
- };
178
-
179
- /**
180
- * Collects all module scope identifiers in the AST.
181
- *
182
- * Ignores identifiers that are in functions or classes.
183
- * Ignores new scopes for StaticBlock nodes (can only reference static class members).
184
- *
185
- * Special case handling for these which create their own scopes,
186
- * but are also valid module scope identifiers:
187
- * - ClassDeclaration
188
- * - FunctionDeclaration
189
- *
190
- * Special case handling for var inside BlockStatement
191
- * which are also valid module scope identifiers.
192
- */
193
- const collectModuleIdentifiers = async (ast, hoisting = true) => {
194
- const identifiers = new Map();
195
- const globalReads = new Map();
196
- const scopes = [];
197
- await ancestorWalk(ast, {
198
- enter(node, ancestors) {
199
- const {
200
- type
201
- } = node;
202
- collectScopeIdentifiers(node, scopes);
203
-
204
- // Add module scope identifiers to the registry map
205
-
206
- if (type === 'Identifier') {
207
- const {
208
- name
209
- } = node;
210
- const meta = identifiers.get(name) ?? {
211
- declare: [],
212
- read: []
213
- };
214
- const isDeclaration = identifier.isDeclaration(ancestors);
215
- const inScope = scopes.some(scope => scope.idents.has(name) || scope.name === name);
216
- if (hoisting && !identifier.isDeclaration(ancestors) && !identifier.isFunctionExpressionId(ancestors) && !identifier.isExportSpecifierAlias(ancestors) && !identifier.isClassPropertyKey(ancestors) && !identifier.isMethodDefinitionKey(ancestors) && !identifier.isMemberKey(ancestors) && !identifier.isPropertyKey(ancestors) && !identifier.isIife(ancestors) && !inScope) {
217
- if (globalReads.has(name)) {
218
- globalReads.get(name)?.push(node);
219
- } else {
220
- globalReads.set(name, [node]);
221
- }
222
- }
223
- if (isDeclaration) {
224
- const isModuleScope = identifier.isModuleScope(ancestors);
225
- const isClassOrFuncDeclaration = identifier.isClassOrFuncDeclarationId(ancestors);
226
- const isVarDeclarationInGlobalScope = identifier.isVarDeclarationInGlobalScope(ancestors);
227
- const parent = ancestors[ancestors.length - 2];
228
- const grandParent = ancestors[ancestors.length - 3];
229
- const hoistSafe = parent.type === 'FunctionDeclaration' || parent.type === 'VariableDeclarator' && grandParent?.type === 'VariableDeclaration' && grandParent.kind === 'var';
230
- if (isModuleScope || isClassOrFuncDeclaration || isVarDeclarationInGlobalScope) {
231
- meta.declare.push(node);
232
-
233
- // Check for hoisted reads
234
- if (hoisting && hoistSafe && globalReads.has(name)) {
235
- const reads = globalReads.get(name);
236
- if (reads) {
237
- reads.forEach(read => {
238
- if (!meta.read.includes(read)) {
239
- meta.read.push(read);
240
- }
241
- });
242
- }
243
- }
244
- identifiers.set(name, meta);
245
- }
246
- } else {
247
- if (identifiers.has(name) && !inScope && !identifier.isIife(ancestors) && !identifier.isFunctionExpressionId(ancestors) && !identifier.isExportSpecifierAlias(ancestors) && !identifier.isClassPropertyKey(ancestors) && !identifier.isMethodDefinitionKey(ancestors) && !identifier.isMemberKey(ancestors) && !identifier.isPropertyKey(ancestors)) {
248
- // Closure is referencing module scope identifier
249
- meta.read.push(node);
250
- }
251
- }
252
- }
253
- },
254
- leave(node) {
255
- const {
256
- type
257
- } = node;
258
- if (scopeNodes.includes(type)) {
259
- scopes.pop();
260
- }
261
- }
262
- });
263
- return identifiers;
264
- };
265
- export { isValidUrl, collectScopeIdentifiers, collectModuleIdentifiers, collectCjsExports, exportsRename, requireMainRgx };
File without changes
File without changes
File without changes
File without changes
File without changes