rsbuild-plugin-dts 0.20.0 → 0.20.2

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,21 +0,0 @@
1
- MIT License
2
-
3
- Copyright (c) 2024 Madeline Gurriarán
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
@@ -1 +0,0 @@
1
- {"name":"tinyglobby","author":"Superchupu","version":"0.2.14","funding":{"url":"https://github.com/sponsors/SuperchupuDev"},"license":"MIT","types":"index.d.ts","type":"commonjs"}
package/dist/utils.js DELETED
@@ -1,367 +0,0 @@
1
- import { createRequire as __rspack_createRequire } from "node:module";
2
- const __rspack_createRequire_require = __rspack_createRequire(import.meta.url);
3
- import node_fs from "node:fs";
4
- import promises from "node:fs/promises";
5
- import { createRequire } from "node:module";
6
- import { platform } from "node:os";
7
- import node_path, { basename, dirname, extname, isAbsolute, join, normalize, relative, resolve } from "node:path";
8
- import { fileURLToPath } from "node:url";
9
- import { parseAsync } from "@ast-grep/napi";
10
- import { logger } from "@rsbuild/core";
11
- import magic_string from "../compiled/magic-string/index.js";
12
- import picocolors from "../compiled/picocolors/index.js";
13
- import { convertPathToPattern, glob } from "../compiled/tinyglobby/index.js";
14
- const tsconfig_paths_index_js_namespaceObject = __rspack_createRequire_require("../compiled/tsconfig-paths/index.js");
15
- const { createMatchPath: createMatchPath, loadConfig: loadConfig } = tsconfig_paths_index_js_namespaceObject;
16
- const utils_filename = fileURLToPath(import.meta.url);
17
- const utils_require = createRequire(utils_filename);
18
- const ts = utils_require("typescript");
19
- const JS_EXTENSIONS = [
20
- 'js',
21
- 'mjs',
22
- 'jsx',
23
- '(?<!\\.d\\.)ts',
24
- '(?<!\\.d\\.)mts',
25
- '(?<!\\.d\\.)cts',
26
- 'tsx',
27
- 'cjs',
28
- 'cjsx',
29
- 'mjsx',
30
- 'mtsx',
31
- 'ctsx'
32
- ];
33
- const JS_EXTENSIONS_PATTERN = new RegExp(`\\.(${JS_EXTENSIONS.join('|')})$`);
34
- function loadTsconfig(tsconfigPath) {
35
- const configFile = ts.readConfigFile(tsconfigPath, ts.sys.readFile.bind(ts.sys));
36
- const configFileContent = ts.parseJsonConfigFileContent(configFile.config, ts.sys, node_path.dirname(tsconfigPath));
37
- return configFileContent;
38
- }
39
- function mergeAliasWithTsConfigPaths(paths, alias = {}) {
40
- const mergedPaths = {};
41
- if (alias && 'object' == typeof alias && Object.keys(alias).length > 0) {
42
- for (const [key, value] of Object.entries(alias))if ('string' == typeof value && value.trim()) mergedPaths[key] = [
43
- value
44
- ];
45
- }
46
- if (paths) {
47
- for (const [key, value] of Object.entries(paths))if (Array.isArray(value) && value.length > 0) {
48
- if (!mergedPaths[key]) mergedPaths[key] = [
49
- ...value
50
- ];
51
- }
52
- }
53
- return Object.keys(mergedPaths).length > 0 ? mergedPaths : {};
54
- }
55
- const TEMP_FOLDER = '.rslib';
56
- const TEMP_DTS_DIR = `${TEMP_FOLDER}/declarations`;
57
- function ensureTempDeclarationDir(cwd, name) {
58
- const dirPath = node_path.join(cwd, TEMP_DTS_DIR, name);
59
- if (node_fs.existsSync(dirPath)) return dirPath;
60
- node_fs.mkdirSync(dirPath, {
61
- recursive: true
62
- });
63
- const gitIgnorePath = node_path.join(cwd, TEMP_FOLDER, '.gitignore');
64
- node_fs.writeFileSync(gitIgnorePath, '**/*\n');
65
- return dirPath;
66
- }
67
- async function pathExists(path) {
68
- return node_fs.promises.access(path).then(()=>true).catch(()=>false);
69
- }
70
- async function isDirectory(filePath) {
71
- try {
72
- const stat = await promises.stat(filePath);
73
- return stat.isDirectory();
74
- } catch {
75
- return false;
76
- }
77
- }
78
- async function emptyDir(dir) {
79
- if (!await pathExists(dir)) return;
80
- try {
81
- for (const file of (await node_fs.promises.readdir(dir)))await node_fs.promises.rm(node_path.resolve(dir, file), {
82
- recursive: true,
83
- force: true
84
- });
85
- } catch (err) {
86
- logger.warn(`Failed to empty dir: ${dir}`);
87
- logger.warn(err);
88
- }
89
- }
90
- async function clearTempDeclarationDir(cwd) {
91
- const dirPath = node_path.join(cwd, TEMP_DTS_DIR);
92
- await emptyDir(dirPath);
93
- }
94
- function getFileLoc(diagnostic, configPath) {
95
- if (diagnostic.file) {
96
- const { line, character } = ts.getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start);
97
- return `${picocolors.cyan(diagnostic.file.fileName)}:${picocolors.yellow(line + 1)}:${picocolors.yellow(character + 1)}`;
98
- }
99
- return picocolors.cyan(configPath);
100
- }
101
- const prettyTime = (seconds)=>{
102
- const format = (time)=>picocolors.bold(time);
103
- if (seconds < 10) {
104
- const digits = seconds >= 0.01 ? 2 : 3;
105
- return `${format(seconds.toFixed(digits))} s`;
106
- }
107
- if (seconds < 60) return `${format(seconds.toFixed(1))} s`;
108
- const minutes = Math.floor(seconds / 60);
109
- const minutesLabel = `${format(minutes.toFixed(0))} m`;
110
- const remainingSeconds = seconds % 60;
111
- if (0 === remainingSeconds) return minutesLabel;
112
- const secondsLabel = `${format(remainingSeconds.toFixed(remainingSeconds % 1 === 0 ? 0 : 1))} s`;
113
- return `${minutesLabel} ${secondsLabel}`;
114
- };
115
- const convertPath = (path)=>{
116
- if ('win32' === platform()) return convertPathToPattern(path);
117
- return path;
118
- };
119
- function getTimeCost(start) {
120
- const second = (Date.now() - start) / 1000;
121
- return prettyTime(second);
122
- }
123
- async function addBannerAndFooter(dtsFile, banner, footer) {
124
- const content = await promises.readFile(dtsFile, 'utf-8');
125
- const code = new magic_string(content);
126
- if (banner && !content.trimStart().startsWith(banner.trim())) code.prepend(`${banner}\n`);
127
- if (footer && !content.trimEnd().endsWith(footer.trim())) code.append(`\n${footer}\n`);
128
- if (code.hasChanged()) await promises.writeFile(dtsFile, code.toString());
129
- }
130
- async function addExtension(redirect, dtsFile, path, jsExtension, dtsExtension) {
131
- if (!redirect.extension) return path;
132
- if (!isAbsolute(path) && !path.startsWith('.')) return path;
133
- const candidatePaths = [];
134
- if (await isDirectory(join(dirname(dtsFile), path))) candidatePaths.push(`${path.replace(/\/+$/, '')}/index`);
135
- candidatePaths.push(path);
136
- for (const candidatePath of candidatePaths)if (await pathExists(join(dirname(dtsFile), `${candidatePath}${dtsExtension}`))) return `${candidatePath}${jsExtension}`;
137
- return path;
138
- }
139
- async function redirectDtsImports(dtsFile, dtsExtension, redirect, matchPath, outDir, rootDir) {
140
- const content = await promises.readFile(dtsFile, 'utf-8');
141
- const code = new magic_string(content);
142
- const sgNode = (await parseAsync("typescript", content)).root();
143
- const matcher = {
144
- rule: {
145
- any: [
146
- {
147
- kind: 'import_statement',
148
- has: {
149
- field: 'source',
150
- has: {
151
- pattern: '$IMP',
152
- kind: 'string_fragment'
153
- }
154
- }
155
- },
156
- {
157
- kind: 'import_statement',
158
- has: {
159
- kind: 'import_require_clause',
160
- has: {
161
- field: 'source',
162
- has: {
163
- pattern: '$IMP',
164
- kind: 'string_fragment'
165
- }
166
- }
167
- }
168
- },
169
- {
170
- kind: 'export_statement',
171
- has: {
172
- field: 'source',
173
- has: {
174
- pattern: '$IMP',
175
- kind: 'string_fragment'
176
- }
177
- }
178
- },
179
- {
180
- any: [
181
- {
182
- pattern: 'require($A)'
183
- },
184
- {
185
- pattern: 'import($A)'
186
- }
187
- ],
188
- has: {
189
- field: 'arguments',
190
- has: {
191
- has: {
192
- pattern: '$IMP',
193
- kind: 'string_fragment'
194
- }
195
- }
196
- }
197
- }
198
- ]
199
- }
200
- };
201
- const matchModule = sgNode.findAll(matcher).map((match)=>{
202
- const matchNode = match.getMatch('IMP');
203
- return {
204
- n: matchNode.text(),
205
- s: matchNode.range().start.index,
206
- e: matchNode.range().end.index
207
- };
208
- });
209
- const jsExtension = dtsExtension.replace(/\.d\.ts$/, '.js').replace(/\.d\.cts$/, '.cjs').replace(/\.d\.mts$/, '.mjs');
210
- for (const imp of matchModule){
211
- const { n: importPath, s: start, e: end } = imp;
212
- if (importPath) try {
213
- const absoluteImportPath = matchPath(importPath, void 0, void 0, [
214
- '.jsx',
215
- '.tsx',
216
- '.js',
217
- '.ts',
218
- '.mjs',
219
- '.mts',
220
- '.cjs',
221
- '.cts',
222
- '.d.ts'
223
- ]);
224
- let redirectImportPath = importPath;
225
- if (absoluteImportPath && !absoluteImportPath.includes('node_modules') && redirect.path) {
226
- const relativeRootDir = node_path.relative(normalize(rootDir), normalize(absoluteImportPath));
227
- const isOutsideRootdir = relativeRootDir.startsWith('..') || node_path.isAbsolute(relativeRootDir);
228
- if (isOutsideRootdir) {
229
- const relativePath = relative(dirname(dtsFile), absoluteImportPath);
230
- redirectImportPath = relativePath.startsWith('..') ? relativePath : `./${relativePath}`;
231
- } else {
232
- const originalFilePath = resolve(rootDir, relative(outDir, dtsFile));
233
- const originalSourceDir = dirname(originalFilePath);
234
- const relativePath = relative(originalSourceDir, absoluteImportPath);
235
- redirectImportPath = relativePath.startsWith('..') ? relativePath : `./${relativePath}`;
236
- }
237
- }
238
- const ext = extname(redirectImportPath);
239
- if (ext) if (JS_EXTENSIONS_PATTERN.test(redirectImportPath)) {
240
- if (redirect.extension) redirectImportPath = redirectImportPath.replace(/\.[^.]+$/, jsExtension);
241
- } else redirectImportPath = await addExtension(redirect, dtsFile, redirectImportPath, jsExtension, dtsExtension);
242
- else {
243
- if (absoluteImportPath && normalize(absoluteImportPath).startsWith(normalize(rootDir))) redirectImportPath = await addExtension(redirect, dtsFile, redirectImportPath, jsExtension, dtsExtension);
244
- if (!absoluteImportPath && importPath.startsWith('.')) redirectImportPath = await addExtension(redirect, dtsFile, redirectImportPath, jsExtension, dtsExtension);
245
- }
246
- const normalizedRedirectImportPath = redirectImportPath.split(node_path.sep).join('/');
247
- code.overwrite(start, end, normalizedRedirectImportPath);
248
- } catch (err) {
249
- logger.warn(err);
250
- }
251
- }
252
- if (code.hasChanged()) await promises.writeFile(dtsFile, code.toString());
253
- }
254
- async function processDtsFiles(bundle, dir, dtsExtension, redirect, tsconfigPath, rootDir, paths, banner, footer) {
255
- if (bundle) return;
256
- let matchPath;
257
- if (redirect.path || redirect.extension) {
258
- const result = loadConfig(tsconfigPath);
259
- if ('failed' === result.resultType) return void logger.error(result.message);
260
- const { absoluteBaseUrl, addMatchAll } = result;
261
- const mainFields = [];
262
- matchPath = createMatchPath(absoluteBaseUrl, paths, mainFields, addMatchAll);
263
- }
264
- const dtsFiles = await globDtsFiles(dir, [
265
- `/**/*${dtsExtension}`
266
- ]);
267
- await Promise.all(dtsFiles.map(async (file)=>{
268
- try {
269
- if (banner || footer) await addBannerAndFooter(file, banner, footer);
270
- if ((redirect.path || redirect.extension) && matchPath) await redirectDtsImports(file, dtsExtension, redirect, matchPath, dir, rootDir);
271
- } catch (error) {
272
- logger.error(`Failed to rename declaration file ${file}: ${error}`);
273
- }
274
- }));
275
- }
276
- function processSourceEntry(bundle, entryConfig) {
277
- if (!bundle) return [];
278
- if (entryConfig && Object.values(entryConfig).every((val)=>'string' == typeof val)) {
279
- const entries = Object.entries(entryConfig).map(([name, path])=>({
280
- name,
281
- path
282
- }));
283
- if (0 === entries.length) {
284
- const noValidEntryError = new Error(`Can not find a valid entry for ${picocolors.cyan('dts.bundle')} option, please check your entry config.`);
285
- noValidEntryError.stack = '';
286
- throw noValidEntryError;
287
- }
288
- return entries;
289
- }
290
- const error = new Error('@microsoft/api-extractor only support entry of Record<string, string> type to bundle declaration files, please check your entry config.');
291
- error.stack = '';
292
- throw error;
293
- }
294
- async function calcLongestCommonPath(absPaths) {
295
- if (0 === absPaths.length) return null;
296
- const sep = node_path.posix.sep;
297
- const splitPaths = absPaths.map((p)=>p.split(sep));
298
- let lcaFragments = splitPaths[0];
299
- for(let i = 1; i < splitPaths.length; i++){
300
- const currentPath = splitPaths[i];
301
- const minLength = Math.min(lcaFragments.length, currentPath.length);
302
- let j = 0;
303
- while(j < minLength && lcaFragments[j] === currentPath[j])j++;
304
- lcaFragments = lcaFragments.slice(0, j);
305
- }
306
- let lca = lcaFragments.length > 0 ? lcaFragments.join(sep) : sep;
307
- const stats = await promises.stat(lca);
308
- if (stats?.isFile()) lca = node_path.dirname(lca);
309
- return lca;
310
- }
311
- const globDtsFiles = async (dir, patterns)=>{
312
- const dtsFiles = await Promise.all(patterns.map(async (pattern)=>glob(convertPath(join(dir, pattern)), {
313
- absolute: true,
314
- dot: true
315
- })));
316
- return dtsFiles.flat();
317
- };
318
- async function cleanDtsFiles(dir) {
319
- const patterns = [
320
- '/**/*.d.ts',
321
- '/**/*.d.cts',
322
- '/**/*.d.mts',
323
- '/**/*.d.ts.map',
324
- '/**/*.d.cts.map',
325
- '/**/*.d.mts.map'
326
- ];
327
- const allFiles = await globDtsFiles(dir, patterns);
328
- await Promise.all(allFiles.map(async (file)=>promises.rm(file, {
329
- force: true
330
- })));
331
- }
332
- async function cleanTsBuildInfoFile(tsconfigPath, compilerOptions) {
333
- const tsconfigDir = dirname(tsconfigPath);
334
- const { outDir, rootDir, tsBuildInfoFile } = compilerOptions;
335
- let tsbuildInfoFilePath;
336
- if (tsBuildInfoFile && isAbsolute(tsBuildInfoFile)) tsbuildInfoFilePath = tsBuildInfoFile;
337
- else {
338
- const defaultFileName = `${basename(tsconfigPath, '.json')}${tsBuildInfoFile ?? '.tsbuildinfo'}`;
339
- tsbuildInfoFilePath = outDir ? rootDir ? join(outDir, relative(resolve(tsconfigDir, rootDir), tsconfigDir), defaultFileName) : join(outDir, defaultFileName) : join(tsconfigDir, defaultFileName);
340
- }
341
- if (await pathExists(tsbuildInfoFilePath)) await promises.rm(tsbuildInfoFilePath, {
342
- force: true
343
- });
344
- }
345
- function getDtsEmitPath(pathFromPlugin, declarationDir, distPathRoot) {
346
- return pathFromPlugin ?? declarationDir ?? distPathRoot;
347
- }
348
- function warnIfOutside(cwd, dir, label) {
349
- if (dir) {
350
- const normalizedCwd = normalize(cwd);
351
- const normalizedDir = normalize(dir);
352
- const relDir = relative(normalizedCwd, normalizedDir);
353
- if (relDir.startsWith('..')) logger.warn(`The resolved ${label} ${picocolors.cyan(normalizedDir)} is outside the project root ${picocolors.cyan(normalizedCwd)}, please check your tsconfig file.`);
354
- }
355
- }
356
- function renameDtsFile(fileName, dtsExtension, bundle) {
357
- if (bundle) return fileName;
358
- if (fileName.endsWith('.d.ts.map')) return fileName.replace(/\.d\.ts\.map$/, `${dtsExtension}.map`);
359
- return fileName.replace(/\.d\.ts$/, dtsExtension);
360
- }
361
- function updateDeclarationMapContent(fileName, content, dtsExtension, bundle, hasDeclarationMap = false) {
362
- if (bundle || !hasDeclarationMap) return content;
363
- if (fileName.endsWith('.d.ts')) return content.replace(/(\/\/# sourceMappingURL=.+)\.d\.ts\.map/g, `$1${dtsExtension}.map`);
364
- if (fileName.endsWith('.d.ts.map')) return content.replace(/("file":"[^"]*)\.d\.ts"/g, `$1${dtsExtension}"`);
365
- return content;
366
- }
367
- export { JS_EXTENSIONS_PATTERN, TEMP_DTS_DIR, TEMP_FOLDER, addBannerAndFooter, calcLongestCommonPath, cleanDtsFiles, cleanTsBuildInfoFile, clearTempDeclarationDir, emptyDir, ensureTempDeclarationDir, getDtsEmitPath, getFileLoc, getTimeCost, globDtsFiles, isDirectory, loadTsconfig, mergeAliasWithTsConfigPaths, pathExists, prettyTime, processDtsFiles, processSourceEntry, redirectDtsImports, renameDtsFile, ts, updateDeclarationMapContent, warnIfOutside };