@bleedingdev/modern-js-server-utils 3.9.0-ultramodern.17 → 3.9.0-ultramodern.19

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.
@@ -1,314 +0,0 @@
1
- "use strict";
2
- var __webpack_require__ = {};
3
- (()=>{
4
- __webpack_require__.n = (module)=>{
5
- var getter = module && module.__esModule ? ()=>module['default'] : ()=>module;
6
- __webpack_require__.d(getter, {
7
- a: getter
8
- });
9
- return getter;
10
- };
11
- })();
12
- (()=>{
13
- __webpack_require__.d = (exports1, getters, values)=>{
14
- var define = (defs, kind)=>{
15
- for(var key in defs)if (__webpack_require__.o(defs, key) && !__webpack_require__.o(exports1, key)) Object.defineProperty(exports1, key, {
16
- enumerable: true,
17
- [kind]: defs[key]
18
- });
19
- };
20
- define(getters, "get");
21
- define(values, "value");
22
- };
23
- })();
24
- (()=>{
25
- __webpack_require__.o = (obj, prop)=>Object.prototype.hasOwnProperty.call(obj, prop);
26
- })();
27
- (()=>{
28
- __webpack_require__.r = (exports1)=>{
29
- if ("u" > typeof Symbol && Symbol.toStringTag) Object.defineProperty(exports1, Symbol.toStringTag, {
30
- value: 'Module'
31
- });
32
- Object.defineProperty(exports1, '__esModule', {
33
- value: true
34
- });
35
- };
36
- })();
37
- var __webpack_exports__ = {};
38
- __webpack_require__.r(__webpack_exports__);
39
- __webpack_require__.d(__webpack_exports__, {
40
- compileByTs: ()=>compileByTs,
41
- createResolvedTsgoConfig: ()=>createResolvedTsgoConfig,
42
- getTsgoBinPath: ()=>getTsgoBinPath,
43
- rewriteOutputSpecifiers: ()=>rewriteOutputSpecifiers
44
- });
45
- const utils_namespaceObject = require("@modern-js/utils");
46
- const external_child_process_namespaceObject = require("child_process");
47
- const external_path_namespaceObject = require("path");
48
- var external_path_default = /*#__PURE__*/ __webpack_require__.n(external_path_namespaceObject);
49
- const external_importRewriter_js_namespaceObject = require("./importRewriter.js");
50
- const external_tsconfigPathsPlugin_js_namespaceObject = require("./tsconfigPathsPlugin.js");
51
- const copyFiles = async (from, to, appDirectory)=>{
52
- if (await utils_namespaceObject.fs.pathExists(from)) {
53
- const relativePath = external_path_default().relative(appDirectory, from);
54
- const targetDir = external_path_default().join(to, relativePath);
55
- await utils_namespaceObject.fs.copy(from, targetDir, {
56
- filter: (src)=>!/\.(?:[cm]?ts|tsx|jsx?)$/u.test(src) && !src.endsWith('tsconfig.json')
57
- });
58
- }
59
- };
60
- let resolvedConfigCount = 0;
61
- const createResolvedTsgoConfig = async (appDirectory, tsconfigPath, distDir, sourceDirs, moduleType, tsgoBinPath, excludeFiles = [])=>{
62
- const tsconfigDir = external_path_default().dirname(tsconfigPath);
63
- const output = await runTsgo(tsgoBinPath, [
64
- '--showConfig',
65
- '-p',
66
- tsconfigPath
67
- ], {
68
- cwd: tsconfigDir
69
- });
70
- const config = JSON.parse(output.stdout);
71
- config.compilerOptions ??= {};
72
- config.compilerOptions.rootDir = appDirectory;
73
- config.compilerOptions.outDir = distDir;
74
- config.compilerOptions.composite = false;
75
- config.compilerOptions.declarationMap = false;
76
- config.compilerOptions.emitDeclarationOnly = false;
77
- config.compilerOptions.incremental = false;
78
- config.compilerOptions.noEmit = false;
79
- if (void 0 === config.compilerOptions.jsx || 'preserve' === config.compilerOptions.jsx) config.compilerOptions.jsx = 'react-jsx';
80
- delete config.compilerOptions.tsBuildInfoFile;
81
- if (true === config.compilerOptions.allowImportingTsExtensions) config.compilerOptions.rewriteRelativeImportExtensions = true;
82
- config.files = filterSourceFiles(tsconfigDir, sourceDirs, config.files, excludeFiles);
83
- delete config.include;
84
- delete config.references;
85
- delete config.compilerOptions.baseUrl;
86
- if ([
87
- 'node',
88
- 'node10'
89
- ].includes(String(config.compilerOptions.moduleResolution).toLowerCase())) delete config.compilerOptions.moduleResolution;
90
- if ('module' !== moduleType) {
91
- if ([
92
- 'preserve',
93
- 'esnext',
94
- 'es2015',
95
- 'es2020',
96
- 'es2022',
97
- 'es6'
98
- ].includes(String(config.compilerOptions.module).toLowerCase())) {
99
- config.compilerOptions.module = 'commonjs';
100
- delete config.compilerOptions.moduleResolution;
101
- }
102
- config.compilerOptions.verbatimModuleSyntax = false;
103
- }
104
- const resolvedConfigPath = external_path_default().join(tsconfigDir, `.tsgo.${process.pid}.${resolvedConfigCount++}.resolved.json`);
105
- await utils_namespaceObject.fs.writeFile(resolvedConfigPath, JSON.stringify(config, null, 2));
106
- return {
107
- config,
108
- resolvedConfigPath
109
- };
110
- };
111
- const filterSourceFiles = (tsconfigDir, sourceDirs, files = [], excludeFiles = [])=>{
112
- const sourcePosixPaths = sourceDirs.map((sourceDir)=>sourceDir.split(external_path_default().sep).join(external_path_default().posix.sep));
113
- const excludedPaths = new Set(excludeFiles.map((file)=>external_path_default().normalize(file).split(external_path_default().sep).join(external_path_default().posix.sep)));
114
- return files.filter((fileName)=>{
115
- const absoluteFileName = external_path_default().resolve(tsconfigDir, fileName).split(external_path_default().sep).join(external_path_default().posix.sep);
116
- if (excludedPaths.has(absoluteFileName)) return false;
117
- return fileName.endsWith('.d.ts') || sourcePosixPaths.some((sourceDir)=>absoluteFileName.includes(sourceDir));
118
- });
119
- };
120
- const runTsgo = (tsgoBinPath, args, options)=>new Promise((resolve, reject)=>{
121
- const child = (0, external_child_process_namespaceObject.spawn)(process.execPath, [
122
- tsgoBinPath,
123
- ...args
124
- ], {
125
- cwd: options.cwd,
126
- stdio: [
127
- 'ignore',
128
- 'pipe',
129
- 'pipe'
130
- ]
131
- });
132
- let stdout = '';
133
- let stderr = '';
134
- child.stdout.on('data', (data)=>{
135
- stdout += data;
136
- });
137
- child.stderr.on('data', (data)=>{
138
- stderr += data;
139
- });
140
- child.on('error', reject);
141
- child.on('close', (code)=>{
142
- const result = {
143
- stdout,
144
- stderr,
145
- code: code ?? 1
146
- };
147
- if (false !== options.reject && 0 !== result.code) return void reject(new Error(stderr || stdout || `tsgo exited with ${result.code}`));
148
- resolve(result);
149
- });
150
- });
151
- const getTsgoBinEntry = (pkg)=>{
152
- if ('string' == typeof pkg.bin) return pkg.bin;
153
- return pkg.bin?.tsc ?? pkg.bin?.tsgo;
154
- };
155
- const resolveTsgoBinPath = (pkgPath)=>{
156
- const pkgDir = external_path_default().dirname(pkgPath);
157
- const pkg = require(pkgPath);
158
- const declaredBinEntry = getTsgoBinEntry(pkg);
159
- const candidates = [
160
- declaredBinEntry ? external_path_default().resolve(pkgDir, declaredBinEntry) : void 0,
161
- external_path_default().join(pkgDir, 'bin/tsgo.js')
162
- ].filter((candidate)=>Boolean(candidate));
163
- return candidates.find((candidate)=>utils_namespaceObject.fs.existsSync(candidate)) ?? candidates[0];
164
- };
165
- const getTsgoBinPath = (appDirectory, resolvePaths = [
166
- appDirectory,
167
- __dirname
168
- ])=>{
169
- try {
170
- let pkgPath;
171
- try {
172
- pkgPath = require.resolve("@typescript/native/package.json", {
173
- paths: resolvePaths
174
- });
175
- } catch {
176
- pkgPath = require.resolve("@typescript/native-preview/package.json", {
177
- paths: resolvePaths
178
- });
179
- }
180
- return resolveTsgoBinPath(pkgPath);
181
- } catch {
182
- throw new Error('tsgo could not be found! Please install "@typescript/native" (or legacy "@typescript/native-preview") in your project to compile BFF/server code.');
183
- }
184
- };
185
- const OUTPUT_SOURCE_EXTENSIONS = {
186
- '.js': [
187
- '.ts',
188
- '.tsx',
189
- '.js',
190
- '.jsx'
191
- ],
192
- '.mjs': [
193
- '.mts',
194
- '.mjs'
195
- ],
196
- '.cjs': [
197
- '.cts',
198
- '.cjs'
199
- ],
200
- '.d.ts': [
201
- '.ts',
202
- '.tsx',
203
- '.js',
204
- '.jsx'
205
- ],
206
- '.d.mts': [
207
- '.mts',
208
- '.mjs'
209
- ],
210
- '.d.cts': [
211
- '.cts',
212
- '.cjs'
213
- ]
214
- };
215
- const getSourceFileForOutput = (appDirectory, distDir, outputFile)=>{
216
- const relativeOutput = external_path_default().relative(distDir, outputFile);
217
- const parsed = external_path_default().parse(relativeOutput);
218
- const isDeclaration = parsed.name.endsWith('.d');
219
- const outputExtension = isDeclaration ? `.d${parsed.ext}` : parsed.ext;
220
- const sourceName = isDeclaration ? parsed.name.slice(0, -2) : parsed.name;
221
- const sourceBase = external_path_default().join(appDirectory, parsed.dir, sourceName);
222
- const extensions = OUTPUT_SOURCE_EXTENSIONS[outputExtension] ?? OUTPUT_SOURCE_EXTENSIONS['.js'];
223
- for (const extension of extensions){
224
- const candidate = `${sourceBase}${extension}`;
225
- if (utils_namespaceObject.fs.existsSync(candidate)) return candidate;
226
- }
227
- };
228
- const sourceMappingUrlRE = /^\/\/[#@] sourceMappingURL=.*$/gm;
229
- const dropStaleSourceMap = async (outputFile, content)=>{
230
- const mapFile = `${outputFile}.map`;
231
- if (await utils_namespaceObject.fs.pathExists(mapFile)) await utils_namespaceObject.fs.remove(mapFile);
232
- return content.replace(sourceMappingUrlRE, '');
233
- };
234
- const rewriteOutputSpecifiers = async (appDirectory, distDir, baseUrl, paths, moduleType)=>{
235
- if (!await utils_namespaceObject.fs.pathExists(distDir)) return;
236
- const matcher = (0, external_tsconfigPathsPlugin_js_namespaceObject.createTsconfigPathsMatcher)(baseUrl, paths);
237
- if (!matcher) return;
238
- const files = await collectOutputFiles(distDir);
239
- await Promise.all(files.map(async (file)=>{
240
- const sourceFile = getSourceFileForOutput(appDirectory, distDir, file);
241
- if (!sourceFile) return;
242
- (0, external_importRewriter_js_namespaceObject.assertNoNativeModuleOutputCollision)(sourceFile, utils_namespaceObject.fs.existsSync);
243
- const content = await utils_namespaceObject.fs.readFile(file, 'utf8');
244
- const { content: rewritten, changed } = (0, external_importRewriter_js_namespaceObject.rewriteImportSpecifiers)(content, (specifier)=>(0, external_tsconfigPathsPlugin_js_namespaceObject.getNotAliasedPath)(sourceFile, matcher, specifier, moduleType));
245
- if (changed) await utils_namespaceObject.fs.writeFile(file, await dropStaleSourceMap(file, rewritten));
246
- }));
247
- };
248
- const collectOutputFiles = async (dir)=>{
249
- const entries = await utils_namespaceObject.fs.readdir(dir, {
250
- withFileTypes: true
251
- });
252
- const files = await Promise.all(entries.map(async (entry)=>{
253
- const fullPath = external_path_default().join(dir, entry.name);
254
- if (entry.isDirectory()) return collectOutputFiles(fullPath);
255
- return /\.(?:c|m)?js$|\.d\.(?:c|m)?ts$/.test(entry.name) ? [
256
- fullPath
257
- ] : [];
258
- }));
259
- return files.flat();
260
- };
261
- const compileByTs = async (appDirectory, config, compileOptions)=>{
262
- utils_namespaceObject.logger.info("Running tsgo compile...");
263
- const { sourceDirs, distDir, tsconfigPath } = compileOptions;
264
- if (!tsconfigPath) return;
265
- const { alias } = config;
266
- const aliasOption = (0, utils_namespaceObject.getAliasConfig)(alias, {
267
- appDirectory,
268
- tsconfigPath
269
- });
270
- const { paths = {}, absoluteBaseUrl = './' } = aliasOption;
271
- const tsgoBinPath = getTsgoBinPath(appDirectory);
272
- const { config: tsgoConfig, resolvedConfigPath } = await createResolvedTsgoConfig(appDirectory, tsconfigPath, distDir, sourceDirs, compileOptions.moduleType, tsgoBinPath, compileOptions.excludeFiles);
273
- let result;
274
- try {
275
- result = await runTsgo(tsgoBinPath, [
276
- '-p',
277
- resolvedConfigPath
278
- ], {
279
- cwd: appDirectory,
280
- reject: false
281
- });
282
- } finally{
283
- await utils_namespaceObject.fs.remove(resolvedConfigPath);
284
- }
285
- if (result.stderr) utils_namespaceObject.logger.error(result.stderr);
286
- if (result.stdout) utils_namespaceObject.logger.info(result.stdout);
287
- await rewriteOutputSpecifiers(appDirectory, distDir, absoluteBaseUrl, paths, compileOptions.moduleType);
288
- if (0 !== result.code) {
289
- const noEmitOnError = tsgoConfig.compilerOptions?.noEmitOnError;
290
- if (void 0 === noEmitOnError || true === noEmitOnError) if (compileOptions.throwErrorInsteadOfExit) {
291
- utils_namespaceObject.logger.error('TS-Go compilation failed');
292
- throw new Error([
293
- `TS-Go compilation failed with exit code ${result.code}.`,
294
- result.stderr.trim() || result.stdout.trim()
295
- ].filter(Boolean).join('\n'));
296
- } else process.exit(1);
297
- }
298
- for (const source of sourceDirs)await copyFiles(source, distDir, appDirectory);
299
- await rewriteOutputSpecifiers(appDirectory, distDir, absoluteBaseUrl, paths, compileOptions.moduleType);
300
- utils_namespaceObject.logger.info("TS-Go compile succeed");
301
- };
302
- exports.compileByTs = __webpack_exports__.compileByTs;
303
- exports.createResolvedTsgoConfig = __webpack_exports__.createResolvedTsgoConfig;
304
- exports.getTsgoBinPath = __webpack_exports__.getTsgoBinPath;
305
- exports.rewriteOutputSpecifiers = __webpack_exports__.rewriteOutputSpecifiers;
306
- for(var __rspack_i in __webpack_exports__)if (-1 === [
307
- "compileByTs",
308
- "createResolvedTsgoConfig",
309
- "getTsgoBinPath",
310
- "rewriteOutputSpecifiers"
311
- ].indexOf(__rspack_i)) exports[__rspack_i] = __webpack_exports__[__rspack_i];
312
- Object.defineProperty(exports, '__esModule', {
313
- value: true
314
- });
@@ -1,194 +0,0 @@
1
- "use strict";
2
- var __webpack_require__ = {};
3
- (()=>{
4
- __webpack_require__.n = (module1)=>{
5
- var getter = module1 && module1.__esModule ? ()=>module1['default'] : ()=>module1;
6
- __webpack_require__.d(getter, {
7
- a: getter
8
- });
9
- return getter;
10
- };
11
- })();
12
- (()=>{
13
- __webpack_require__.d = (exports1, getters, values)=>{
14
- var define = (defs, kind)=>{
15
- for(var key in defs)if (__webpack_require__.o(defs, key) && !__webpack_require__.o(exports1, key)) Object.defineProperty(exports1, key, {
16
- enumerable: true,
17
- [kind]: defs[key]
18
- });
19
- };
20
- define(getters, "get");
21
- define(values, "value");
22
- };
23
- })();
24
- (()=>{
25
- __webpack_require__.o = (obj, prop)=>Object.prototype.hasOwnProperty.call(obj, prop);
26
- })();
27
- (()=>{
28
- __webpack_require__.r = (exports1)=>{
29
- if ("u" > typeof Symbol && Symbol.toStringTag) Object.defineProperty(exports1, Symbol.toStringTag, {
30
- value: 'Module'
31
- });
32
- Object.defineProperty(exports1, '__esModule', {
33
- value: true
34
- });
35
- };
36
- })();
37
- var __webpack_exports__ = {};
38
- __webpack_require__.r(__webpack_exports__);
39
- __webpack_require__.d(__webpack_exports__, {
40
- createTsconfigPathsMatcher: ()=>createTsconfigPathsMatcher,
41
- getNotAliasedPath: ()=>getNotAliasedPath
42
- });
43
- const utils_namespaceObject = require("@modern-js/utils");
44
- const tsconfig_paths_namespaceObject = require("@modern-js/utils/tsconfig-paths");
45
- const external_path_namespaceObject = require("path");
46
- var external_path_default = /*#__PURE__*/ __webpack_require__.n(external_path_namespaceObject);
47
- const windowsAbsolutePathRE = /^[A-Za-z]:[\\/]/u;
48
- const isAbsolutePath = (input)=>external_path_default().isAbsolute(input) || external_path_default().win32.isAbsolute(input);
49
- const pathApiFor = (...inputs)=>inputs.some((input)=>windowsAbsolutePathRE.test(input)) ? external_path_default().win32 : external_path_default();
50
- const toImportSpecifier = (sourceFile, resolvedPath)=>{
51
- const pathApi = pathApiFor(sourceFile, resolvedPath);
52
- const relativePath = pathApi.relative(pathApi.dirname(sourceFile), resolvedPath).split(pathApi.sep).join(external_path_default().posix.sep);
53
- return '.' === relativePath[0] ? relativePath : `./${relativePath}`;
54
- };
55
- const SOURCE_TO_OUTPUT_EXTENSION = new Map([
56
- [
57
- '.ts',
58
- '.js'
59
- ],
60
- [
61
- '.tsx',
62
- '.js'
63
- ],
64
- [
65
- '.js',
66
- '.js'
67
- ],
68
- [
69
- '.jsx',
70
- '.js'
71
- ],
72
- [
73
- '.mts',
74
- '.mjs'
75
- ],
76
- [
77
- '.mjs',
78
- '.mjs'
79
- ],
80
- [
81
- '.cts',
82
- '.cjs'
83
- ],
84
- [
85
- '.cjs',
86
- '.cjs'
87
- ]
88
- ]);
89
- const toEsmOutputPath = (resolvedPath)=>{
90
- const sourcePath = ((0, utils_namespaceObject.findSourceEntry)(resolvedPath) || resolvedPath).replace(/\\/g, '/');
91
- const ext = external_path_default().extname(sourcePath);
92
- if (!ext) return `${sourcePath}.js`;
93
- const outputExtension = SOURCE_TO_OUTPUT_EXTENSION.get(ext);
94
- if (!outputExtension) return sourcePath;
95
- return `${sourcePath.slice(0, -ext.length)}${outputExtension}`;
96
- };
97
- const resolveRelativeEsmSpecifier = (sourceFile, text)=>{
98
- if (!text.startsWith('./') && !text.startsWith('../')) return;
99
- const pathApi = pathApiFor(sourceFile);
100
- return pathApi.resolve(pathApi.dirname(sourceFile), text);
101
- };
102
- const isRegExpKey = (str)=>str.startsWith('^') || str.endsWith('$');
103
- const resolveAliasPath = (baseUrl, filePath)=>{
104
- if (filePath.startsWith('.') || filePath.startsWith('..')) return external_path_default().resolve(baseUrl, filePath);
105
- return filePath;
106
- };
107
- const createAliasMatcher = (baseUrl, alias)=>{
108
- const aliasPairs = Object.keys(alias).reduce((o, key)=>{
109
- if (isRegExpKey(key)) {
110
- const regexp = new RegExp(key);
111
- const aliasPath = resolveAliasPath(baseUrl, alias[key]);
112
- o.push([
113
- regexp,
114
- aliasPath
115
- ]);
116
- } else {
117
- const aliasPath = resolveAliasPath(baseUrl, alias[key]);
118
- o.push([
119
- key,
120
- aliasPath
121
- ]);
122
- }
123
- return o;
124
- }, []);
125
- const cacheMap = new Map();
126
- return (requestedModule)=>{
127
- if (cacheMap.has(requestedModule)) return cacheMap.get(requestedModule);
128
- for (const [key, value] of aliasPairs){
129
- if (key instanceof RegExp) {
130
- if (key.test(requestedModule)) {
131
- cacheMap.set(requestedModule, value);
132
- return value;
133
- }
134
- }
135
- if (requestedModule === key) {
136
- cacheMap.set(requestedModule, value);
137
- return value;
138
- }
139
- }
140
- };
141
- };
142
- const createTsconfigPathsMatcher = (baseUrl, paths)=>{
143
- const tsPaths = {};
144
- const alias = {};
145
- Object.keys(paths).forEach((key)=>{
146
- if (Array.isArray(paths[key])) tsPaths[key] = paths[key];
147
- else alias[key] = paths[key];
148
- });
149
- const matchAliasPath = createAliasMatcher(baseUrl, alias);
150
- const matchTsPath = (0, tsconfig_paths_namespaceObject.createMatchPath)(baseUrl, tsPaths, [
151
- 'main'
152
- ]);
153
- return (requestedModule, readJSONSync, fileExists, extensions)=>{
154
- const result = matchTsPath(requestedModule, readJSONSync, fileExists, extensions);
155
- if (result) return result;
156
- return matchAliasPath(requestedModule);
157
- };
158
- };
159
- function getNotAliasedPath(sourceFile, matcher, text, moduleType) {
160
- let result = (0, utils_namespaceObject.findMatchedSourcePath)(matcher, text);
161
- if (!result && 'module' === moduleType) result = resolveRelativeEsmSpecifier(sourceFile, text);
162
- if (!result) return;
163
- if (!isAbsolutePath(result)) {
164
- if (!result.startsWith('.') && !result.startsWith('..')) try {
165
- const packagePath = require.resolve(result, {
166
- paths: [
167
- process.cwd(),
168
- ...module.paths
169
- ]
170
- });
171
- if (packagePath) return result;
172
- } catch {}
173
- try {
174
- const packagePath = require.resolve(text, {
175
- paths: [
176
- process.cwd(),
177
- ...module.paths
178
- ]
179
- });
180
- if (packagePath) return text;
181
- } catch {}
182
- }
183
- if ('module' === moduleType || /\.[cm]ts$/iu.test(result)) result = toEsmOutputPath(result);
184
- return toImportSpecifier(sourceFile, result) || './';
185
- }
186
- exports.createTsconfigPathsMatcher = __webpack_exports__.createTsconfigPathsMatcher;
187
- exports.getNotAliasedPath = __webpack_exports__.getNotAliasedPath;
188
- for(var __rspack_i in __webpack_exports__)if (-1 === [
189
- "createTsconfigPathsMatcher",
190
- "getNotAliasedPath"
191
- ].indexOf(__rspack_i)) exports[__rspack_i] = __webpack_exports__[__rspack_i];
192
- Object.defineProperty(exports, '__esModule', {
193
- value: true
194
- });
@@ -1,134 +0,0 @@
1
- import { parseSync } from "@swc/core";
2
- const assertNoNativeModuleOutputCollision = (sourceFile, fileExists)=>{
3
- const rawModuleFile = sourceFile.endsWith('.mts') ? `${sourceFile.slice(0, -4)}.mjs` : sourceFile.endsWith('.cts') ? `${sourceFile.slice(0, -4)}.cjs` : void 0;
4
- if (rawModuleFile && fileExists(rawModuleFile)) throw new Error(`Native module sources collide: "${sourceFile}" and "${rawModuleFile}" publish the same output.`);
5
- };
6
- const isObjectRecord = (value)=>'object' == typeof value && null !== value;
7
- const isAstNode = (value)=>isObjectRecord(value) && 'string' == typeof value.type;
8
- const isStringLiteral = (value)=>isAstNode(value) && 'StringLiteral' === value.type && 'string' == typeof value.value && 'object' == typeof value.span && null !== value.span && 'number' == typeof value.span.start && 'number' == typeof value.span.end;
9
- const getCallSpecifier = (node)=>{
10
- if ('CallExpression' !== node.type || !Array.isArray(node.arguments)) return;
11
- const callee = node.callee;
12
- const isDynamicImport = isAstNode(callee) && 'Import' === callee.type;
13
- const isCommonJsRequire = isAstNode(callee) && 'Identifier' === callee.type && 'require' === callee.value;
14
- if (!isDynamicImport && !isCommonJsRequire) return;
15
- const firstArgument = node.arguments[0];
16
- if (!isObjectRecord(firstArgument)) return;
17
- return isStringLiteral(firstArgument.expression) ? firstArgument.expression : void 0;
18
- };
19
- const collectSpecifierLiterals = (content)=>{
20
- const parserOptions = {
21
- decorators: true,
22
- syntax: "typescript",
23
- target: 'esnext'
24
- };
25
- let program;
26
- try {
27
- program = parseSync(content, parserOptions);
28
- } catch (typescriptError) {
29
- try {
30
- program = parseSync(content, {
31
- ...parserOptions,
32
- tsx: true
33
- });
34
- } catch {
35
- throw typescriptError;
36
- }
37
- }
38
- const literals = [];
39
- const seenSpans = new Set();
40
- const add = (value)=>{
41
- if (!isStringLiteral(value)) return;
42
- const spanKey = `${value.span.start}:${value.span.end}`;
43
- if (!seenSpans.has(spanKey)) {
44
- seenSpans.add(spanKey);
45
- literals.push(value);
46
- }
47
- };
48
- const visit = (value)=>{
49
- if (Array.isArray(value)) return void value.forEach(visit);
50
- if (!isObjectRecord(value)) return;
51
- if (isAstNode(value)) switch(value.type){
52
- case 'ImportDeclaration':
53
- case 'ExportAllDeclaration':
54
- case 'ExportNamedDeclaration':
55
- add(value.source);
56
- break;
57
- case 'TsImportType':
58
- add(value.argument);
59
- break;
60
- case 'TsExternalModuleReference':
61
- add(value.expression);
62
- break;
63
- case 'CallExpression':
64
- add(getCallSpecifier(value));
65
- break;
66
- }
67
- for (const [key, child] of Object.entries(value))if ('span' !== key) visit(child);
68
- };
69
- visit(program);
70
- return literals.sort((left, right)=>left.span.start - right.span.start);
71
- };
72
- const mapUtf8ByteOffsets = (content, byteOffsets)=>{
73
- const pending = new Set(byteOffsets);
74
- const result = new Map();
75
- let byteOffset = 0;
76
- let stringOffset = 0;
77
- while(stringOffset <= content.length && pending.size > 0){
78
- if (pending.delete(byteOffset)) result.set(byteOffset, stringOffset);
79
- if (stringOffset === content.length) break;
80
- const codePoint = content.codePointAt(stringOffset);
81
- if (void 0 === codePoint) break;
82
- const character = String.fromCodePoint(codePoint);
83
- byteOffset += Buffer.byteLength(character);
84
- stringOffset += character.length;
85
- }
86
- if (pending.size > 0) throw new Error('SWC returned an import specifier span outside its source');
87
- return result;
88
- };
89
- const scanSpecifiers = (content)=>{
90
- const literals = collectSpecifierLiterals(content);
91
- const byteOffsets = literals.flatMap((literal)=>[
92
- literal.span.start,
93
- literal.span.end - 2
94
- ]);
95
- const stringOffsets = mapUtf8ByteOffsets(content, byteOffsets);
96
- return literals.map((literal)=>{
97
- const start = stringOffsets.get(literal.span.start);
98
- const end = stringOffsets.get(literal.span.end - 2);
99
- if (void 0 === start || void 0 === end) throw new Error('Could not locate an SWC import specifier in its source');
100
- return {
101
- start,
102
- end,
103
- value: content.slice(start, end)
104
- };
105
- });
106
- };
107
- const rewriteImportSpecifiers = (content, rewrite)=>{
108
- const specifiers = scanSpecifiers(content);
109
- if (0 === specifiers.length) return {
110
- content,
111
- changed: false
112
- };
113
- let result = '';
114
- let cursor = 0;
115
- let changed = false;
116
- for (const specifier of specifiers){
117
- if (specifier.value.includes('\\')) continue;
118
- const next = rewrite(specifier.value);
119
- if (void 0 !== next && next !== specifier.value) {
120
- changed = true;
121
- result += content.slice(cursor, specifier.start) + next;
122
- cursor = specifier.end;
123
- }
124
- }
125
- if (!changed) return {
126
- content,
127
- changed: false
128
- };
129
- return {
130
- content: result + content.slice(cursor),
131
- changed: true
132
- };
133
- };
134
- export { assertNoNativeModuleOutputCollision, rewriteImportSpecifiers };