@rslib/core 0.0.5 → 0.0.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,6 +1,4 @@
1
- import * as __WEBPACK_EXTERNAL_MODULE_process__ from "process";
2
- import * as __WEBPACK_EXTERNAL_MODULE_os__ from "os";
3
- import * as __WEBPACK_EXTERNAL_MODULE_tty__ from "tty";
1
+ import * as __WEBPACK_EXTERNAL_MODULE__compiled_rslog_index_js__ from "../compiled/rslog/index.js";
4
2
  import * as __WEBPACK_EXTERNAL_MODULE_node_fs__ from "node:fs";
5
3
  import * as __WEBPACK_EXTERNAL_MODULE_node_fs_promises__ from "node:fs/promises";
6
4
  import * as __WEBPACK_EXTERNAL_MODULE_node_path__ from "node:path";
@@ -8,281 +6,12 @@ import * as __WEBPACK_EXTERNAL_MODULE__compiled_picocolors_index_js__ from "../c
8
6
  import * as __WEBPACK_EXTERNAL_MODULE__compiled_commander_index_js__ from "../compiled/commander/index.js";
9
7
  import * as __WEBPACK_EXTERNAL_MODULE__rsbuild_core__ from "@rsbuild/core";
10
8
  import * as __WEBPACK_EXTERNAL_MODULE__compiled_fast_glob_index_js__ from "../compiled/fast-glob/index.js";
11
- var __webpack_modules__ = {
12
- "rsbuild-plugin-dts": function(module) {
13
- module.exports = import("rsbuild-plugin-dts");
14
- }
15
- };
16
- /************************************************************************/ // The module cache
17
- var __webpack_module_cache__ = {};
18
- // The require function
19
- function __webpack_require__(moduleId) {
20
- // Check if module is in cache
21
- var cachedModule = __webpack_module_cache__[moduleId];
22
- if (void 0 !== cachedModule) return cachedModule.exports;
23
- // Create a new module (and put it into the cache)
24
- var module = __webpack_module_cache__[moduleId] = {
25
- exports: {}
26
- };
27
- // Execute the module function
28
- __webpack_modules__[moduleId](module, module.exports, __webpack_require__);
29
- // Return the exports of the module
30
- return module.exports;
31
- } /************************************************************************/
32
- var external_process_namespaceObject = __WEBPACK_EXTERNAL_MODULE_process__;
33
- var external_os_namespaceObject = __WEBPACK_EXTERNAL_MODULE_os__;
34
- var external_tty_namespaceObject = __WEBPACK_EXTERNAL_MODULE_tty__;
35
- // node_modules/.pnpm/supports-color@9.4.0/node_modules/supports-color/index.js
36
- function hasFlag(flag, argv = globalThis.Deno ? globalThis.Deno.args : external_process_namespaceObject["default"].argv) {
37
- const prefix = flag.startsWith("-") ? "" : 1 === flag.length ? "-" : "--";
38
- const position = argv.indexOf(prefix + flag);
39
- const terminatorPosition = argv.indexOf("--");
40
- return -1 !== position && (-1 === terminatorPosition || position < terminatorPosition);
41
- }
42
- var { env } = external_process_namespaceObject["default"];
43
- var flagForceColor;
44
- if (hasFlag("no-color") || hasFlag("no-colors") || hasFlag("color=false") || hasFlag("color=never")) flagForceColor = 0;
45
- else if (hasFlag("color") || hasFlag("colors") || hasFlag("color=true") || hasFlag("color=always")) flagForceColor = 1;
46
- function envForceColor() {
47
- if ("FORCE_COLOR" in env) {
48
- if ("true" === env.FORCE_COLOR) return 1;
49
- if ("false" === env.FORCE_COLOR) return 0;
50
- return 0 === env.FORCE_COLOR.length ? 1 : Math.min(Number.parseInt(env.FORCE_COLOR, 10), 3);
51
- }
52
- }
53
- function translateLevel(level) {
54
- if (0 === level) return false;
55
- return {
56
- level,
57
- hasBasic: true,
58
- has256: level >= 2,
59
- has16m: level >= 3
60
- };
61
- }
62
- function _supportsColor(haveStream, { streamIsTTY, sniffFlags = true } = {}) {
63
- const noFlagForceColor = envForceColor();
64
- if (void 0 !== noFlagForceColor) flagForceColor = noFlagForceColor;
65
- const forceColor = sniffFlags ? flagForceColor : noFlagForceColor;
66
- if (0 === forceColor) return 0;
67
- if (sniffFlags) {
68
- if (hasFlag("color=16m") || hasFlag("color=full") || hasFlag("color=truecolor")) return 3;
69
- if (hasFlag("color=256")) return 2;
70
- }
71
- if ("TF_BUILD" in env && "AGENT_NAME" in env) return 1;
72
- if (haveStream && !streamIsTTY && void 0 === forceColor) return 0;
73
- const min = forceColor || 0;
74
- if ("dumb" === env.TERM) return min;
75
- if ("win32" === external_process_namespaceObject["default"].platform) {
76
- const osRelease = external_os_namespaceObject["default"].release().split(".");
77
- if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) return Number(osRelease[2]) >= 14931 ? 3 : 2;
78
- return 1;
79
- }
80
- if ("CI" in env) {
81
- if ("GITHUB_ACTIONS" in env || "GITEA_ACTIONS" in env) return 3;
82
- if ([
83
- "TRAVIS",
84
- "CIRCLECI",
85
- "APPVEYOR",
86
- "GITLAB_CI",
87
- "BUILDKITE",
88
- "DRONE"
89
- ].some((sign)=>sign in env) || "codeship" === env.CI_NAME) return 1;
90
- return min;
91
- }
92
- if ("TEAMCITY_VERSION" in env) return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;
93
- if ("truecolor" === env.COLORTERM) return 3;
94
- if ("xterm-kitty" === env.TERM) return 3;
95
- if ("TERM_PROGRAM" in env) {
96
- const version = Number.parseInt((env.TERM_PROGRAM_VERSION || "").split(".")[0], 10);
97
- switch(env.TERM_PROGRAM){
98
- case "iTerm.app":
99
- return version >= 3 ? 3 : 2;
100
- case "Apple_Terminal":
101
- return 2;
102
- }
103
- }
104
- if (/-256(color)?$/i.test(env.TERM)) return 2;
105
- if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) return 1;
106
- if ("COLORTERM" in env) return 1;
107
- return min;
108
- }
109
- function createSupportsColor(stream, options = {}) {
110
- const level = _supportsColor(stream, {
111
- streamIsTTY: stream && stream.isTTY,
112
- ...options
113
- });
114
- return translateLevel(level);
115
- }
116
- var supportsColor = {
117
- stdout: createSupportsColor({
118
- isTTY: external_tty_namespaceObject["default"].isatty(1)
119
- }),
120
- stderr: createSupportsColor({
121
- isTTY: external_tty_namespaceObject["default"].isatty(2)
122
- })
123
- };
124
- var supports_color_default = supportsColor;
125
- // src/utils.ts
126
- var colorLevel = supports_color_default.stdout ? supports_color_default.stdout.level : 0;
127
- var errorStackRegExp = /at\s.*:\d+:\d+[\s\)]*$/;
128
- var anonymousErrorStackRegExp = /at\s.*\(<anonymous>\)$/;
129
- var isErrorStackMessage = (message)=>errorStackRegExp.test(message) || anonymousErrorStackRegExp.test(message);
130
- // src/color.ts
131
- var formatter = (open, close, replace = open)=>colorLevel >= 2 ? (input)=>{
132
- let string = "" + input;
133
- let index = string.indexOf(close, open.length);
134
- return ~index ? open + replaceClose(string, close, replace, index) + close : open + string + close;
135
- } : String;
136
- var replaceClose = (string, close, replace, index)=>{
137
- let start = string.substring(0, index) + replace;
138
- let end = string.substring(index + close.length);
139
- let nextIndex = end.indexOf(close);
140
- return ~nextIndex ? start + replaceClose(end, close, replace, nextIndex) : start + end;
141
- };
142
- var bold = formatter("\x1B[1m", "\x1B[22m", "\x1B[22m\x1B[1m");
143
- var red = formatter("\x1B[31m", "\x1B[39m");
144
- var green = formatter("\x1B[32m", "\x1B[39m");
145
- var yellow = formatter("\x1B[33m", "\x1B[39m");
146
- var magenta = formatter("\x1B[35m", "\x1B[39m");
147
- var cyan = formatter("\x1B[36m", "\x1B[39m");
148
- var gray = formatter("\x1B[90m", "\x1B[39m");
149
- // src/gradient.ts
150
- var startColor = [
151
- 189,
152
- 255,
153
- 243
154
- ];
155
- var endColor = [
156
- 74,
157
- 194,
158
- 154
159
- ];
160
- var isWord = (char)=>!/[\s\n]/.test(char);
161
- var gradient = (message)=>{
162
- if (colorLevel < 3) return 2 === colorLevel ? bold(cyan(message)) : message;
163
- let chars = [
164
- ...message
165
- ];
166
- let steps = chars.filter(isWord).length;
167
- let r = startColor[0];
168
- let g = startColor[1];
169
- let b = startColor[2];
170
- let rStep = (endColor[0] - r) / steps;
171
- let gStep = (endColor[1] - g) / steps;
172
- let bStep = (endColor[2] - b) / steps;
173
- let output = "";
174
- for (let char of chars){
175
- if (isWord(char)) {
176
- r += rStep;
177
- g += gStep;
178
- b += bStep;
179
- }
180
- output += `\x1B[38;2;${Math.round(r)};${Math.round(g)};${Math.round(b)}m${char}\x1B[39m`;
181
- }
182
- return bold(output);
183
- };
184
- // src/constants.ts
185
- var LOG_LEVEL = {
186
- error: 0,
187
- warn: 1,
188
- info: 2,
189
- log: 3,
190
- verbose: 4
191
- };
192
- var LOG_TYPES = {
193
- // Level error
194
- error: {
195
- label: "error",
196
- level: "error",
197
- color: red
198
- },
199
- // Level warn
200
- warn: {
201
- label: "warn",
202
- level: "warn",
203
- color: yellow
204
- },
205
- // Level info
206
- info: {
207
- label: "info",
208
- level: "info",
209
- color: cyan
210
- },
211
- start: {
212
- label: "start",
213
- level: "info",
214
- color: cyan
215
- },
216
- ready: {
217
- label: "ready",
218
- level: "info",
219
- color: green
220
- },
221
- success: {
222
- label: "success",
223
- level: "info",
224
- color: green
225
- },
226
- // Level log
227
- log: {
228
- level: "log"
229
- },
230
- // Level debug
231
- debug: {
232
- label: "debug",
233
- level: "verbose",
234
- color: magenta
235
- }
236
- };
237
- // src/createLogger.ts
238
- var createLogger = (options = {})=>{
239
- let maxLevel = options.level || "log";
240
- let log = (type, message, ...args)=>{
241
- if (LOG_LEVEL[LOG_TYPES[type].level] > LOG_LEVEL[maxLevel]) return;
242
- if (null == message) return console.log();
243
- let logType = LOG_TYPES[type];
244
- let label = "";
245
- let text = "";
246
- if ("label" in logType) {
247
- label = (logType.label || "").padEnd(7);
248
- label = bold(logType.color ? logType.color(label) : label);
249
- }
250
- if (message instanceof Error) {
251
- if (message.stack) {
252
- let [name, ...rest] = message.stack.split("\n");
253
- if (name.startsWith("Error: ")) name = name.slice(7);
254
- text = `${name}
255
- ${gray(rest.join("\n"))}`;
256
- } else text = message.message;
257
- } else if ("error" === logType.level && "string" == typeof message) {
258
- let lines = message.split("\n");
259
- text = lines.map((line)=>isErrorStackMessage(line) ? gray(line) : line).join("\n");
260
- } else text = `${message}`;
261
- console.log(label.length ? `${label} ${text}` : text, ...args);
262
- };
263
- let logger2 = {
264
- greet: (message)=>log("log", gradient(message))
265
- };
266
- Object.keys(LOG_TYPES).forEach((key)=>{
267
- logger2[key] = (...args)=>log(key, ...args);
268
- });
269
- Object.defineProperty(logger2, "level", {
270
- get: ()=>maxLevel,
271
- set (val) {
272
- maxLevel = val;
273
- }
274
- });
275
- logger2.override = (customLogger)=>{
276
- Object.assign(logger2, customLogger);
277
- };
278
- return logger2;
279
- };
280
- // src/index.ts
281
- var dist_logger = createLogger();
9
+ import * as __WEBPACK_EXTERNAL_MODULE_module__ from "module";
10
+ var index_js_namespaceObject = __WEBPACK_EXTERNAL_MODULE__compiled_rslog_index_js__;
282
11
  var external_node_fs_namespaceObject = __WEBPACK_EXTERNAL_MODULE_node_fs__;
283
12
  var promises_namespaceObject = __WEBPACK_EXTERNAL_MODULE_node_fs_promises__;
284
13
  var external_node_path_namespaceObject = __WEBPACK_EXTERNAL_MODULE_node_path__;
285
- var index_js_namespaceObject = __WEBPACK_EXTERNAL_MODULE__compiled_picocolors_index_js__;
14
+ var picocolors_index_js_namespaceObject = __WEBPACK_EXTERNAL_MODULE__compiled_picocolors_index_js__;
286
15
  /**
287
16
  * Node.js built-in modules.
288
17
  * Copied from https://github.com/webpack/webpack/blob/dd44b206a9c50f4b4cb4d134e1a0bd0387b159a3/lib/node/NodeTargetPlugin.js#L12-L72
@@ -369,13 +98,13 @@ async function calcLongestCommonPath(absPaths) {
369
98
  const readPackageJson = (rootPath)=>{
370
99
  const pkgJsonPath = external_node_path_namespaceObject["default"].join(rootPath, './package.json');
371
100
  if (!external_node_fs_namespaceObject["default"].existsSync(pkgJsonPath)) {
372
- dist_logger.warn(`package.json does not exist in the ${rootPath} directory`);
101
+ index_js_namespaceObject.logger.warn(`package.json does not exist in the ${rootPath} directory`);
373
102
  return;
374
103
  }
375
104
  try {
376
105
  return JSON.parse(external_node_fs_namespaceObject["default"].readFileSync(pkgJsonPath, 'utf8'));
377
106
  } catch (err) {
378
- dist_logger.warn(`Failed to parse ${pkgJsonPath}, it might not be valid JSON`);
107
+ index_js_namespaceObject.logger.warn(`Failed to parse ${pkgJsonPath}, it might not be valid JSON`);
379
108
  return;
380
109
  }
381
110
  };
@@ -394,15 +123,22 @@ function omit(obj, keys) {
394
123
  }, {});
395
124
  }
396
125
  // setup the logger level
397
- if (process.env.DEBUG) dist_logger.level = 'verbose';
398
- function initNodeEnv() {}
126
+ if (process.env.DEBUG) index_js_namespaceObject.logger.level = 'verbose';
127
+ function initNodeEnv() {
128
+ if (!process.env.NODE_ENV) {
129
+ const command = process.argv[2] ?? '';
130
+ process.env.NODE_ENV = [
131
+ 'build'
132
+ ].includes(command) ? 'production' : 'development';
133
+ }
134
+ }
399
135
  function prepareCli() {
400
136
  initNodeEnv();
401
137
  // Print a blank line to keep the greet log nice.
402
138
  // Some package managers automatically output a blank line, some do not.
403
139
  const { npm_execpath } = process.env;
404
140
  if (!npm_execpath || npm_execpath.includes('npx-cli.js') || npm_execpath.includes('.bun')) console.log();
405
- dist_logger.greet(` Rslib v0.0.5\n`);
141
+ index_js_namespaceObject.logger.greet(` Rslib v0.0.6\n`);
406
142
  }
407
143
  var commander_index_js_namespaceObject = __WEBPACK_EXTERNAL_MODULE__compiled_commander_index_js__;
408
144
  var core_namespaceObject = __WEBPACK_EXTERNAL_MODULE__rsbuild_core__;
@@ -426,7 +162,7 @@ const getDefaultExtension = (options)=>{
426
162
  dtsExtension
427
163
  };
428
164
  if (!pkgJson) {
429
- dist_logger.warn('autoExtension configuration will not be applied due to read package.json failed');
165
+ index_js_namespaceObject.logger.warn('autoExtension configuration will not be applied due to read package.json failed');
430
166
  return {
431
167
  jsExtension,
432
168
  dtsExtension
@@ -447,6 +183,30 @@ const getDefaultExtension = (options)=>{
447
183
  isModule
448
184
  };
449
185
  };
186
+ const LATEST_TARGET_VERSIONS = {
187
+ node: [
188
+ 'last 1 node versions'
189
+ ],
190
+ web: [
191
+ 'last 1 Chrome versions',
192
+ 'last 1 Firefox versions',
193
+ 'last 1 Edge versions',
194
+ 'last 1 Safari versions',
195
+ 'last 1 ios_saf versions',
196
+ 'not dead'
197
+ ],
198
+ get 'web-worker' () {
199
+ return LATEST_TARGET_VERSIONS.web;
200
+ }
201
+ };
202
+ const calcEsnextBrowserslistByTarget = (target)=>{
203
+ if (!target) return [
204
+ ...LATEST_TARGET_VERSIONS.node,
205
+ ...LATEST_TARGET_VERSIONS.web
206
+ ];
207
+ if ('node' === target) return LATEST_TARGET_VERSIONS.node;
208
+ return LATEST_TARGET_VERSIONS.web;
209
+ };
450
210
  /**
451
211
  * The esX to browserslist mapping is transformed from esbuild:
452
212
  * https://github.com/evanw/esbuild/blob/main/internal/compat/js_table.go
@@ -551,8 +311,8 @@ const getDefaultExtension = (options)=>{
551
311
  Opera: '62.0.0',
552
312
  Safari: '13.1.0'
553
313
  },
554
- es2024: {},
555
- esnext: {},
314
+ es2024: calcEsnextBrowserslistByTarget,
315
+ esnext: calcEsnextBrowserslistByTarget,
556
316
  es5: {
557
317
  Chrome: '5.0.0',
558
318
  Edge: '12.0.0',
@@ -564,13 +324,18 @@ const getDefaultExtension = (options)=>{
564
324
  Safari: '3.1.0'
565
325
  }
566
326
  };
567
- const transformSyntaxToBrowserslist = (syntax)=>{
327
+ function transformSyntaxToBrowserslist(syntax, target) {
568
328
  const handleSyntaxItem = (syntaxItem)=>{
569
- if ('string' == typeof syntaxItem && syntaxItem.toLowerCase().startsWith('es')) {
570
- if (syntaxItem.toLowerCase() in ESX_TO_BROWSERSLIST) return Object.entries(ESX_TO_BROWSERSLIST[syntaxItem]).flatMap(([engine, version])=>{
571
- if (Array.isArray(version)) return version;
572
- return `${engine} >= ${version}`;
573
- });
329
+ const normalizedSyntaxItem = syntaxItem.toLowerCase();
330
+ if (normalizedSyntaxItem.startsWith('es')) {
331
+ if (normalizedSyntaxItem in ESX_TO_BROWSERSLIST) {
332
+ const browserslistItem = ESX_TO_BROWSERSLIST[normalizedSyntaxItem];
333
+ if ('function' == typeof browserslistItem) return browserslistItem(target);
334
+ return Object.entries(browserslistItem).flatMap(([engine, version])=>{
335
+ if (Array.isArray(version)) return version;
336
+ return `${engine} >= ${version}`;
337
+ });
338
+ }
574
339
  throw new Error(`Unsupported ES version: ${syntaxItem}`);
575
340
  }
576
341
  return [
@@ -579,7 +344,721 @@ const transformSyntaxToBrowserslist = (syntax)=>{
579
344
  };
580
345
  if (Array.isArray(syntax)) return syntax.flatMap(handleSyntaxItem);
581
346
  return handleSyntaxItem(syntax);
347
+ }
348
+ const POSIX_SEP_RE = new RegExp('\\' + external_node_path_namespaceObject["default"].posix.sep, 'g');
349
+ const NATIVE_SEP_RE = new RegExp('\\' + external_node_path_namespaceObject["default"].sep, 'g');
350
+ /** @type {Map<string,RegExp>}*/ const PATTERN_REGEX_CACHE = new Map();
351
+ const GLOB_ALL_PATTERN = "**/*";
352
+ const TS_EXTENSIONS = [
353
+ '.ts',
354
+ '.tsx',
355
+ '.mts',
356
+ '.cts'
357
+ ];
358
+ const JS_EXTENSIONS = [
359
+ '.js',
360
+ '.jsx',
361
+ '.mjs',
362
+ '.cjs'
363
+ ];
364
+ const TSJS_EXTENSIONS = TS_EXTENSIONS.concat(JS_EXTENSIONS);
365
+ const TS_EXTENSIONS_RE_GROUP = `\\.(?:${TS_EXTENSIONS.map((ext)=>ext.substring(1)).join('|')})`;
366
+ const TSJS_EXTENSIONS_RE_GROUP = `\\.(?:${TSJS_EXTENSIONS.map((ext)=>ext.substring(1)).join('|')})`;
367
+ const IS_POSIX = external_node_path_namespaceObject["default"].posix.sep === external_node_path_namespaceObject["default"].sep;
368
+ /**
369
+ * @template T
370
+ * @returns {{resolve:(result:T)=>void, reject:(error:any)=>void, promise: Promise<T>}}
371
+ */ function util_makePromise() {
372
+ let resolve, reject;
373
+ const promise = new Promise((res, rej)=>{
374
+ resolve = res;
375
+ reject = rej;
376
+ });
377
+ return {
378
+ promise,
379
+ resolve,
380
+ reject
381
+ };
382
+ }
383
+ /**
384
+ * @param {string} filename
385
+ * @param {import('./cache.js').TSConfckCache} [cache]
386
+ * @returns {Promise<string|void>}
387
+ */ async function util_resolveTSConfigJson(filename, cache) {
388
+ if ('.json' !== external_node_path_namespaceObject["default"].extname(filename)) return; // ignore files that are not json
389
+ const tsconfig = external_node_path_namespaceObject["default"].resolve(filename);
390
+ if (cache && (cache.hasParseResult(tsconfig) || cache.hasParseResult(filename))) return tsconfig;
391
+ return external_node_fs_namespaceObject.promises.stat(tsconfig).then((stat)=>{
392
+ if (stat.isFile() || stat.isFIFO()) return tsconfig;
393
+ throw new Error(`${filename} exists but is not a regular file.`);
394
+ });
395
+ }
396
+ /**
397
+ *
398
+ * @param {string} dir an absolute directory path
399
+ * @returns {boolean} if dir path includes a node_modules segment
400
+ */ const util_isInNodeModules = IS_POSIX ? (dir)=>dir.includes('/node_modules/') : (dir)=>dir.match(/[/\\]node_modules[/\\]/);
401
+ /**
402
+ * convert posix separator to native separator
403
+ *
404
+ * eg.
405
+ * windows: C:/foo/bar -> c:\foo\bar
406
+ * linux: /foo/bar -> /foo/bar
407
+ *
408
+ * @param {string} filename with posix separators
409
+ * @returns {string} filename with native separators
410
+ */ const posix2native = IS_POSIX ? (filename)=>filename : (filename)=>filename.replace(POSIX_SEP_RE, external_node_path_namespaceObject["default"].sep);
411
+ /**
412
+ * convert native separator to posix separator
413
+ *
414
+ * eg.
415
+ * windows: C:\foo\bar -> c:/foo/bar
416
+ * linux: /foo/bar -> /foo/bar
417
+ *
418
+ * @param {string} filename - filename with native separators
419
+ * @returns {string} filename with posix separators
420
+ */ const util_native2posix = IS_POSIX ? (filename)=>filename : (filename)=>filename.replace(NATIVE_SEP_RE, external_node_path_namespaceObject["default"].posix.sep);
421
+ /**
422
+ * converts params to native separator, resolves path and converts native back to posix
423
+ *
424
+ * needed on windows to handle posix paths in tsconfig
425
+ *
426
+ * @param dir {string|null} directory to resolve from
427
+ * @param filename {string} filename or pattern to resolve
428
+ * @returns string
429
+ */ const resolve2posix = IS_POSIX ? (dir, filename)=>dir ? external_node_path_namespaceObject["default"].resolve(dir, filename) : external_node_path_namespaceObject["default"].resolve(filename) : (dir, filename)=>util_native2posix(dir ? external_node_path_namespaceObject["default"].resolve(posix2native(dir), posix2native(filename)) : external_node_path_namespaceObject["default"].resolve(posix2native(filename)));
430
+ /**
431
+ *
432
+ * @param {import('./public.d.ts').TSConfckParseResult} result
433
+ * @param {import('./public.d.ts').TSConfckParseOptions} [options]
434
+ * @returns {string[]}
435
+ */ function util_resolveReferencedTSConfigFiles(result, options) {
436
+ const dir = external_node_path_namespaceObject["default"].dirname(result.tsconfigFile);
437
+ return result.tsconfig.references.map((ref)=>{
438
+ const refPath = ref.path.endsWith('.json') ? ref.path : external_node_path_namespaceObject["default"].join(ref.path, options?.configName ?? 'tsconfig.json');
439
+ return resolve2posix(dir, refPath);
440
+ });
441
+ }
442
+ /**
443
+ * @param {string} filename
444
+ * @param {import('./public.d.ts').TSConfckParseResult} result
445
+ * @returns {import('./public.d.ts').TSConfckParseResult}
446
+ */ function util_resolveSolutionTSConfig(filename, result) {
447
+ const allowJs = result.tsconfig.compilerOptions?.allowJs;
448
+ const extensions = allowJs ? TSJS_EXTENSIONS : TS_EXTENSIONS;
449
+ if (result.referenced && extensions.some((ext)=>filename.endsWith(ext)) && !util_isIncluded(filename, result)) {
450
+ const solutionTSConfig = result.referenced.find((referenced)=>util_isIncluded(filename, referenced));
451
+ if (solutionTSConfig) return solutionTSConfig;
452
+ }
453
+ return result;
454
+ }
455
+ /**
456
+ *
457
+ * @param {string} filename
458
+ * @param {import('./public.d.ts').TSConfckParseResult} result
459
+ * @returns {boolean}
460
+ */ function util_isIncluded(filename, result) {
461
+ const dir = util_native2posix(external_node_path_namespaceObject["default"].dirname(result.tsconfigFile));
462
+ const files = (result.tsconfig.files || []).map((file)=>resolve2posix(dir, file));
463
+ const absoluteFilename = resolve2posix(null, filename);
464
+ if (files.includes(filename)) return true;
465
+ const allowJs = result.tsconfig.compilerOptions?.allowJs;
466
+ const isIncluded = isGlobMatch(absoluteFilename, dir, result.tsconfig.include || (result.tsconfig.files ? [] : [
467
+ GLOB_ALL_PATTERN
468
+ ]), allowJs);
469
+ if (isIncluded) {
470
+ const isExcluded = isGlobMatch(absoluteFilename, dir, result.tsconfig.exclude || [], allowJs);
471
+ return !isExcluded;
472
+ }
473
+ return false;
474
+ }
475
+ /**
476
+ * test filenames agains glob patterns in tsconfig
477
+ *
478
+ * @param filename {string} posix style abolute path to filename to test
479
+ * @param dir {string} posix style absolute path to directory of tsconfig containing patterns
480
+ * @param patterns {string[]} glob patterns to match against
481
+ * @param allowJs {boolean} allowJs setting in tsconfig to include js extensions in checks
482
+ * @returns {boolean} true when at least one pattern matches filename
483
+ */ function isGlobMatch(filename, dir, patterns, allowJs) {
484
+ const extensions = allowJs ? TSJS_EXTENSIONS : TS_EXTENSIONS;
485
+ return patterns.some((pattern)=>{
486
+ // filename must end with part of pattern that comes after last wildcard
487
+ let lastWildcardIndex = pattern.length;
488
+ let hasWildcard = false;
489
+ for(let i = pattern.length - 1; i > -1; i--)if ('*' === pattern[i] || '?' === pattern[i]) {
490
+ lastWildcardIndex = i;
491
+ hasWildcard = true;
492
+ break;
493
+ }
494
+ // if pattern does not end with wildcard, filename must end with pattern after last wildcard
495
+ if (lastWildcardIndex < pattern.length - 1 && !filename.endsWith(pattern.slice(lastWildcardIndex + 1))) return false;
496
+ // if pattern ends with *, filename must end with a default extension
497
+ if (pattern.endsWith('*') && !extensions.some((ext)=>filename.endsWith(ext))) return false;
498
+ // for **/* , filename must start with the dir
499
+ if (pattern === GLOB_ALL_PATTERN) return filename.startsWith(`${dir}/`);
500
+ const resolvedPattern = resolve2posix(dir, pattern);
501
+ // filename must start with part of pattern that comes before first wildcard
502
+ let firstWildcardIndex = -1;
503
+ for(let i = 0; i < resolvedPattern.length; i++)if ('*' === resolvedPattern[i] || '?' === resolvedPattern[i]) {
504
+ firstWildcardIndex = i;
505
+ hasWildcard = true;
506
+ break;
507
+ }
508
+ if (firstWildcardIndex > 1 && !filename.startsWith(resolvedPattern.slice(0, firstWildcardIndex - 1))) return false;
509
+ // if no wildcard in pattern, filename must be equal to resolved pattern
510
+ if (!hasWildcard) return filename === resolvedPattern;
511
+ // complex pattern, use regex to check it
512
+ if (PATTERN_REGEX_CACHE.has(resolvedPattern)) return PATTERN_REGEX_CACHE.get(resolvedPattern).test(filename);
513
+ const regex = pattern2regex(resolvedPattern, allowJs);
514
+ PATTERN_REGEX_CACHE.set(resolvedPattern, regex);
515
+ return regex.test(filename);
516
+ });
517
+ }
518
+ /**
519
+ * @param {string} resolvedPattern
520
+ * @param {boolean} allowJs
521
+ * @returns {RegExp}
522
+ */ function pattern2regex(resolvedPattern, allowJs) {
523
+ let regexStr = '^';
524
+ for(let i = 0; i < resolvedPattern.length; i++){
525
+ const char = resolvedPattern[i];
526
+ if ('?' === char) {
527
+ regexStr += '[^\\/]';
528
+ continue;
529
+ }
530
+ if ('*' === char) {
531
+ if ('*' === resolvedPattern[i + 1] && '/' === resolvedPattern[i + 2]) {
532
+ i += 2;
533
+ regexStr += '(?:[^\\/]*\\/)*'; // zero or more path segments
534
+ continue;
535
+ }
536
+ regexStr += '[^\\/]*';
537
+ continue;
538
+ }
539
+ if ('/.+^${}()|[]\\'.includes(char)) regexStr += "\\";
540
+ regexStr += char;
541
+ }
542
+ // add known file endings if pattern ends on *
543
+ if (resolvedPattern.endsWith('*')) regexStr += allowJs ? TSJS_EXTENSIONS_RE_GROUP : TS_EXTENSIONS_RE_GROUP;
544
+ regexStr += '$';
545
+ return new RegExp(regexStr);
546
+ }
547
+ /**
548
+ * replace tokens like ${configDir}
549
+ * @param {any} tsconfig
550
+ * @param {string} configDir
551
+ * @returns {any}
552
+ */ function util_replaceTokens(tsconfig, configDir) {
553
+ return JSON.parse(JSON.stringify(tsconfig)// replace ${configDir}
554
+ .replaceAll(/"\${configDir}/g, `"${util_native2posix(configDir)}`));
555
+ }
556
+ /**
557
+ * find the closest tsconfig.json file
558
+ *
559
+ * @param {string} filename - path to file to find tsconfig for (absolute or relative to cwd)
560
+ * @param {import('./public.d.ts').TSConfckFindOptions} [options] - options
561
+ * @returns {Promise<string|null>} absolute path to closest tsconfig.json or null if not found
562
+ */ async function find(filename, options) {
563
+ let dir = external_node_path_namespaceObject["default"].dirname(external_node_path_namespaceObject["default"].resolve(filename));
564
+ if (options?.ignoreNodeModules && util_isInNodeModules(dir)) return null;
565
+ const cache = options?.cache;
566
+ const configName = options?.configName ?? 'tsconfig.json';
567
+ if (cache?.hasConfigPath(dir, configName)) return cache.getConfigPath(dir, configName);
568
+ const { promise, resolve, reject } = util_makePromise();
569
+ if (options?.root && !external_node_path_namespaceObject["default"].isAbsolute(options.root)) options.root = external_node_path_namespaceObject["default"].resolve(options.root);
570
+ findUp(dir, {
571
+ promise,
572
+ resolve,
573
+ reject
574
+ }, options);
575
+ return promise;
576
+ }
577
+ /**
578
+ *
579
+ * @param {string} dir
580
+ * @param {{promise:Promise<string|null>,resolve:(result:string|null)=>void,reject:(err:any)=>void}} madePromise
581
+ * @param {import('./public.d.ts').TSConfckFindOptions} [options] - options
582
+ */ function findUp(dir, { resolve, reject, promise }, options) {
583
+ const { cache, root, configName } = options ?? {};
584
+ if (cache) {
585
+ if (cache.hasConfigPath(dir, configName)) {
586
+ let cached;
587
+ try {
588
+ cached = cache.getConfigPath(dir, configName);
589
+ } catch (e) {
590
+ reject(e);
591
+ return;
592
+ }
593
+ if (cached?.then) cached.then(resolve).catch(reject);
594
+ else resolve(cached);
595
+ } else cache.setConfigPath(dir, promise, configName);
596
+ }
597
+ const tsconfig = external_node_path_namespaceObject["default"].join(dir, options?.configName ?? 'tsconfig.json');
598
+ external_node_fs_namespaceObject["default"].stat(tsconfig, (err, stats)=>{
599
+ if (stats && (stats.isFile() || stats.isFIFO())) resolve(tsconfig);
600
+ else if (err?.code !== 'ENOENT') reject(err);
601
+ else {
602
+ let parent;
603
+ if (root === dir || (parent = external_node_path_namespaceObject["default"].dirname(dir)) === dir) resolve(null);
604
+ else findUp(parent, {
605
+ promise,
606
+ resolve,
607
+ reject
608
+ }, options);
609
+ }
610
+ });
611
+ }
612
+ /**
613
+ * @typedef WalkState
614
+ * @interface
615
+ * @property {string[]} files - files
616
+ * @property {number} calls - number of ongoing calls
617
+ * @property {(dir: string)=>boolean} skip - function to skip dirs
618
+ * @property {boolean} err - error flag
619
+ * @property {string[]} configNames - config file names
620
+ */ external_node_path_namespaceObject["default"].sep;
621
+ /*
622
+ this file contains code from strip-bom and strip-json-comments by Sindre Sorhus
623
+ https://github.com/sindresorhus/strip-json-comments/blob/v4.0.0/index.js
624
+ https://github.com/sindresorhus/strip-bom/blob/v5.0.0/index.js
625
+ licensed under MIT, see ../LICENSE
626
+ */ /**
627
+ * convert content of tsconfig.json to regular json
628
+ *
629
+ * @param {string} tsconfigJson - content of tsconfig.json
630
+ * @returns {string} content as regular json, comments and dangling commas have been replaced with whitespace
631
+ */ function toJson(tsconfigJson) {
632
+ const stripped = stripDanglingComma(stripJsonComments(stripBom(tsconfigJson)));
633
+ if ('' === stripped.trim()) // only whitespace left after stripping, return empty object so that JSON.parse still works
634
+ return '{}';
635
+ return stripped;
636
+ }
637
+ /**
638
+ * replace dangling commas from pseudo-json string with single space
639
+ * implementation heavily inspired by strip-json-comments
640
+ *
641
+ * @param {string} pseudoJson
642
+ * @returns {string}
643
+ */ function stripDanglingComma(pseudoJson) {
644
+ let insideString = false;
645
+ let offset = 0;
646
+ let result = '';
647
+ let danglingCommaPos = null;
648
+ for(let i = 0; i < pseudoJson.length; i++){
649
+ const currentCharacter = pseudoJson[i];
650
+ if ('"' === currentCharacter) {
651
+ const escaped = isEscaped(pseudoJson, i);
652
+ if (!escaped) insideString = !insideString;
653
+ }
654
+ if (insideString) {
655
+ danglingCommaPos = null;
656
+ continue;
657
+ }
658
+ if (',' === currentCharacter) {
659
+ danglingCommaPos = i;
660
+ continue;
661
+ }
662
+ if (danglingCommaPos) {
663
+ if ('}' === currentCharacter || ']' === currentCharacter) {
664
+ result += pseudoJson.slice(offset, danglingCommaPos) + ' ';
665
+ offset = danglingCommaPos + 1;
666
+ danglingCommaPos = null;
667
+ } else if (!currentCharacter.match(/\s/)) danglingCommaPos = null;
668
+ }
669
+ }
670
+ return result + pseudoJson.substring(offset);
671
+ }
672
+ // start strip-json-comments
673
+ /**
674
+ *
675
+ * @param {string} jsonString
676
+ * @param {number} quotePosition
677
+ * @returns {boolean}
678
+ */ function isEscaped(jsonString, quotePosition) {
679
+ let index = quotePosition - 1;
680
+ let backslashCount = 0;
681
+ while('\\' === jsonString[index]){
682
+ index -= 1;
683
+ backslashCount += 1;
684
+ }
685
+ return Boolean(backslashCount % 2);
686
+ }
687
+ /**
688
+ *
689
+ * @param {string} string
690
+ * @param {number?} start
691
+ * @param {number?} end
692
+ */ function strip(string, start, end) {
693
+ return string.slice(start, end).replace(/\S/g, ' ');
694
+ }
695
+ const singleComment = Symbol('singleComment');
696
+ const multiComment = Symbol('multiComment');
697
+ /**
698
+ * @param {string} jsonString
699
+ * @returns {string}
700
+ */ function stripJsonComments(jsonString) {
701
+ let isInsideString = false;
702
+ /** @type {false | symbol} */ let isInsideComment = false;
703
+ let offset = 0;
704
+ let result = '';
705
+ for(let index = 0; index < jsonString.length; index++){
706
+ const currentCharacter = jsonString[index];
707
+ const nextCharacter = jsonString[index + 1];
708
+ if (!isInsideComment && '"' === currentCharacter) {
709
+ const escaped = isEscaped(jsonString, index);
710
+ if (!escaped) isInsideString = !isInsideString;
711
+ }
712
+ if (!isInsideString) if (isInsideComment || currentCharacter + nextCharacter !== '//') {
713
+ if (isInsideComment === singleComment && currentCharacter + nextCharacter === '\r\n') {
714
+ index++;
715
+ isInsideComment = false;
716
+ result += strip(jsonString, offset, index);
717
+ offset = index;
718
+ } else if (isInsideComment === singleComment && '\n' === currentCharacter) {
719
+ isInsideComment = false;
720
+ result += strip(jsonString, offset, index);
721
+ offset = index;
722
+ } else if (isInsideComment || currentCharacter + nextCharacter !== '/*') {
723
+ if (isInsideComment === multiComment && currentCharacter + nextCharacter === '*/') {
724
+ index++;
725
+ isInsideComment = false;
726
+ result += strip(jsonString, offset, index + 1);
727
+ offset = index + 1;
728
+ }
729
+ } else {
730
+ result += jsonString.slice(offset, index);
731
+ offset = index;
732
+ isInsideComment = multiComment;
733
+ index++;
734
+ }
735
+ } else {
736
+ result += jsonString.slice(offset, index);
737
+ offset = index;
738
+ isInsideComment = singleComment;
739
+ index++;
740
+ }
741
+ }
742
+ return result + (isInsideComment ? strip(jsonString.slice(offset)) : jsonString.slice(offset));
743
+ }
744
+ // end strip-json-comments
745
+ // start strip-bom
746
+ /**
747
+ * @param {string} string
748
+ * @returns {string}
749
+ */ function stripBom(string) {
750
+ // Catches EFBBBF (UTF-8 BOM) because the buffer-to-string
751
+ // conversion translates it to FEFF (UTF-16 BOM).
752
+ if (0xfeff === string.charCodeAt(0)) return string.slice(1);
753
+ return string;
754
+ }
755
+ var external_module_namespaceObject = __WEBPACK_EXTERNAL_MODULE_module__;
756
+ const not_found_result = {
757
+ tsconfigFile: null,
758
+ tsconfig: {}
759
+ };
760
+ /**
761
+ * parse the closest tsconfig.json file
762
+ *
763
+ * @param {string} filename - path to a tsconfig .json or a source file or directory (absolute or relative to cwd)
764
+ * @param {import('./public.d.ts').TSConfckParseOptions} [options] - options
765
+ * @returns {Promise<import('./public.d.ts').TSConfckParseResult>}
766
+ * @throws {TSConfckParseError}
767
+ */ async function parse(filename, options) {
768
+ /** @type {import('./cache.js').TSConfckCache} */ const cache = options?.cache;
769
+ if (cache?.hasParseResult(filename)) return getParsedDeep(filename, cache, options);
770
+ const { resolve, reject, /** @type {Promise<import('./public.d.ts').TSConfckParseResult>}*/ promise } = util_makePromise();
771
+ cache?.setParseResult(filename, promise, true);
772
+ try {
773
+ let tsconfigFile = await util_resolveTSConfigJson(filename, cache) || await find(filename, options);
774
+ if (!tsconfigFile) {
775
+ resolve(not_found_result);
776
+ return promise;
777
+ }
778
+ let result;
779
+ if (filename !== tsconfigFile && cache?.hasParseResult(tsconfigFile)) result = await getParsedDeep(tsconfigFile, cache, options);
780
+ else {
781
+ result = await parseFile(tsconfigFile, cache, filename === tsconfigFile);
782
+ await Promise.all([
783
+ parseExtends(result, cache),
784
+ parseReferences(result, options)
785
+ ]);
786
+ }
787
+ result.tsconfig = util_replaceTokens(result.tsconfig, external_node_path_namespaceObject["default"].dirname(tsconfigFile));
788
+ resolve(util_resolveSolutionTSConfig(filename, result));
789
+ } catch (e) {
790
+ reject(e);
791
+ }
792
+ return promise;
793
+ }
794
+ /**
795
+ * ensure extends and references are parsed
796
+ *
797
+ * @param {string} filename - cached file
798
+ * @param {import('./cache.js').TSConfckCache} cache - cache
799
+ * @param {import('./public.d.ts').TSConfckParseOptions} options - options
800
+ */ async function getParsedDeep(filename, cache, options) {
801
+ const result = await cache.getParseResult(filename);
802
+ if (result.tsconfig.extends && !result.extended || result.tsconfig.references && !result.referenced) {
803
+ const promise = Promise.all([
804
+ parseExtends(result, cache),
805
+ parseReferences(result, options)
806
+ ]).then(()=>result);
807
+ cache.setParseResult(filename, promise, true);
808
+ return promise;
809
+ }
810
+ return result;
811
+ }
812
+ /**
813
+ *
814
+ * @param {string} tsconfigFile - path to tsconfig file
815
+ * @param {import('./cache.js').TSConfckCache} [cache] - cache
816
+ * @param {boolean} [skipCache] - skip cache
817
+ * @returns {Promise<import('./public.d.ts').TSConfckParseResult>}
818
+ */ async function parseFile(tsconfigFile, cache, skipCache) {
819
+ if (!skipCache && cache?.hasParseResult(tsconfigFile) && !cache.getParseResult(tsconfigFile)._isRootFile_) return cache.getParseResult(tsconfigFile);
820
+ const promise = external_node_fs_namespaceObject.promises.readFile(tsconfigFile, 'utf-8').then(toJson).then((json)=>{
821
+ const parsed = JSON.parse(json);
822
+ applyDefaults(parsed, tsconfigFile);
823
+ return {
824
+ tsconfigFile,
825
+ tsconfig: normalizeTSConfig(parsed, external_node_path_namespaceObject["default"].dirname(tsconfigFile))
826
+ };
827
+ }).catch((e)=>{
828
+ throw new TSConfckParseError(`parsing ${tsconfigFile} failed: ${e}`, 'PARSE_FILE', tsconfigFile, e);
829
+ });
830
+ if (!skipCache && (!cache?.hasParseResult(tsconfigFile) || !cache.getParseResult(tsconfigFile)._isRootFile_)) cache?.setParseResult(tsconfigFile, promise);
831
+ return promise;
832
+ }
833
+ /**
834
+ * normalize to match the output of ts.parseJsonConfigFileContent
835
+ *
836
+ * @param {any} tsconfig - typescript tsconfig output
837
+ * @param {string} dir - directory
838
+ */ function normalizeTSConfig(tsconfig, dir) {
839
+ // set baseUrl to absolute path
840
+ const baseUrl = tsconfig.compilerOptions?.baseUrl;
841
+ if (baseUrl && !baseUrl.startsWith('${') && !external_node_path_namespaceObject["default"].isAbsolute(baseUrl)) tsconfig.compilerOptions.baseUrl = resolve2posix(dir, baseUrl);
842
+ return tsconfig;
843
+ }
844
+ /**
845
+ *
846
+ * @param {import('./public.d.ts').TSConfckParseResult} result
847
+ * @param {import('./public.d.ts').TSConfckParseOptions} [options]
848
+ * @returns {Promise<void>}
849
+ */ async function parseReferences(result, options) {
850
+ if (!result.tsconfig.references) return;
851
+ const referencedFiles = util_resolveReferencedTSConfigFiles(result, options);
852
+ const referenced = await Promise.all(referencedFiles.map((file)=>parseFile(file, options?.cache)));
853
+ await Promise.all(referenced.map((ref)=>parseExtends(ref, options?.cache)));
854
+ referenced.forEach((ref)=>{
855
+ ref.solution = result;
856
+ });
857
+ result.referenced = referenced;
858
+ }
859
+ /**
860
+ * @param {import('./public.d.ts').TSConfckParseResult} result
861
+ * @param {import('./cache.js').TSConfckCache}[cache]
862
+ * @returns {Promise<void>}
863
+ */ async function parseExtends(result, cache) {
864
+ if (!result.tsconfig.extends) return;
865
+ // use result as first element in extended
866
+ // but dereference tsconfig so that mergeExtended can modify the original without affecting extended[0]
867
+ /** @type {import('./public.d.ts').TSConfckParseResult[]} */ const extended = [
868
+ {
869
+ tsconfigFile: result.tsconfigFile,
870
+ tsconfig: JSON.parse(JSON.stringify(result.tsconfig))
871
+ }
872
+ ];
873
+ // flatten extends graph into extended
874
+ let pos = 0;
875
+ /** @type {string[]} */ const extendsPath = [];
876
+ let currentBranchDepth = 0;
877
+ while(pos < extended.length){
878
+ const extending = extended[pos];
879
+ extendsPath.push(extending.tsconfigFile);
880
+ if (extending.tsconfig.extends) {
881
+ // keep following this branch
882
+ currentBranchDepth += 1;
883
+ /** @type {string[]} */ let resolvedExtends;
884
+ // reverse because typescript 5.0 treats ['a','b','c'] as c extends b extends a
885
+ resolvedExtends = Array.isArray(extending.tsconfig.extends) ? extending.tsconfig.extends.reverse().map((ex)=>resolveExtends(ex, extending.tsconfigFile)) : [
886
+ resolveExtends(extending.tsconfig.extends, extending.tsconfigFile)
887
+ ];
888
+ const circularExtends = resolvedExtends.find((tsconfigFile)=>extendsPath.includes(tsconfigFile));
889
+ if (circularExtends) {
890
+ const circle = extendsPath.concat([
891
+ circularExtends
892
+ ]).join(' -> ');
893
+ throw new TSConfckParseError(`Circular dependency in "extends": ${circle}`, 'EXTENDS_CIRCULAR', result.tsconfigFile);
894
+ }
895
+ // add new extends to the list directly after current
896
+ extended.splice(pos + 1, 0, ...await Promise.all(resolvedExtends.map((file)=>parseFile(file, cache))));
897
+ } else {
898
+ // reached a leaf, backtrack to the last branching point and continue
899
+ extendsPath.splice(-currentBranchDepth);
900
+ currentBranchDepth = 0;
901
+ }
902
+ pos += 1;
903
+ }
904
+ result.extended = extended;
905
+ // skip first as it is the original config
906
+ for (const ext of result.extended.slice(1))extendTSConfig(result, ext);
907
+ }
908
+ /**
909
+ *
910
+ * @param {string} extended
911
+ * @param {string} from
912
+ * @returns {string}
913
+ */ function resolveExtends(extended, from) {
914
+ if ('..' === extended) // see #149
915
+ extended = '../tsconfig.json';
916
+ const req = (0, external_module_namespaceObject.createRequire)(from);
917
+ let error;
918
+ try {
919
+ return req.resolve(extended);
920
+ } catch (e) {
921
+ error = e;
922
+ }
923
+ if ('.' !== extended[0] && !external_node_path_namespaceObject["default"].isAbsolute(extended)) try {
924
+ return req.resolve(`${extended}/tsconfig.json`);
925
+ } catch (e) {
926
+ error = e;
927
+ }
928
+ throw new TSConfckParseError(`failed to resolve "extends":"${extended}" in ${from}`, 'EXTENDS_RESOLVE', from, error);
929
+ }
930
+ // references, extends and custom keys are not carried over
931
+ const EXTENDABLE_KEYS = [
932
+ 'compilerOptions',
933
+ 'files',
934
+ 'include',
935
+ 'exclude',
936
+ 'watchOptions',
937
+ 'compileOnSave',
938
+ 'typeAcquisition',
939
+ 'buildOptions'
940
+ ];
941
+ /**
942
+ *
943
+ * @param {import('./public.d.ts').TSConfckParseResult} extending
944
+ * @param {import('./public.d.ts').TSConfckParseResult} extended
945
+ * @returns void
946
+ */ function extendTSConfig(extending, extended) {
947
+ const extendingConfig = extending.tsconfig;
948
+ const extendedConfig = extended.tsconfig;
949
+ const relativePath = util_native2posix(external_node_path_namespaceObject["default"].relative(external_node_path_namespaceObject["default"].dirname(extending.tsconfigFile), external_node_path_namespaceObject["default"].dirname(extended.tsconfigFile)));
950
+ for (const key of Object.keys(extendedConfig).filter((key)=>EXTENDABLE_KEYS.includes(key)))if ('compilerOptions' === key) {
951
+ if (!extendingConfig.compilerOptions) extendingConfig.compilerOptions = {};
952
+ for (const option of Object.keys(extendedConfig.compilerOptions)){
953
+ if (!Object.prototype.hasOwnProperty.call(extendingConfig.compilerOptions, option)) extendingConfig.compilerOptions[option] = rebaseRelative(option, extendedConfig.compilerOptions[option], relativePath);
954
+ }
955
+ } else if (void 0 === extendingConfig[key]) {
956
+ if ('watchOptions' === key) {
957
+ extendingConfig.watchOptions = {};
958
+ for (const option of Object.keys(extendedConfig.watchOptions))extendingConfig.watchOptions[option] = rebaseRelative(option, extendedConfig.watchOptions[option], relativePath);
959
+ } else extendingConfig[key] = rebaseRelative(key, extendedConfig[key], relativePath);
960
+ }
961
+ }
962
+ const REBASE_KEYS = [
963
+ // root
964
+ 'files',
965
+ 'include',
966
+ 'exclude',
967
+ // compilerOptions
968
+ 'baseUrl',
969
+ 'rootDir',
970
+ 'rootDirs',
971
+ 'typeRoots',
972
+ 'outDir',
973
+ 'outFile',
974
+ 'declarationDir',
975
+ // watchOptions
976
+ 'excludeDirectories',
977
+ 'excludeFiles'
978
+ ];
979
+ /** @typedef {string | string[]} PathValue */ /**
980
+ *
981
+ * @param {string} key
982
+ * @param {PathValue} value
983
+ * @param {string} prependPath
984
+ * @returns {PathValue}
985
+ */ function rebaseRelative(key, value, prependPath) {
986
+ if (!REBASE_KEYS.includes(key)) return value;
987
+ if (Array.isArray(value)) return value.map((x)=>rebasePath(x, prependPath));
988
+ return rebasePath(value, prependPath);
989
+ }
990
+ /**
991
+ *
992
+ * @param {string} value
993
+ * @param {string} prependPath
994
+ * @returns {string}
995
+ */ function rebasePath(value, prependPath) {
996
+ if (external_node_path_namespaceObject["default"].isAbsolute(value) || value.startsWith('${configDir}')) return value;
997
+ // relative paths use posix syntax in tsconfig
998
+ return external_node_path_namespaceObject["default"].posix.normalize(external_node_path_namespaceObject["default"].posix.join(prependPath, value));
999
+ }
1000
+ class TSConfckParseError extends Error {
1001
+ /**
1002
+ * error code
1003
+ * @type {string}
1004
+ */ code;
1005
+ /**
1006
+ * error cause
1007
+ * @type { Error | undefined}
1008
+ */ cause;
1009
+ /**
1010
+ * absolute path of tsconfig file where the error happened
1011
+ * @type {string}
1012
+ */ tsconfigFile;
1013
+ /**
1014
+ *
1015
+ * @param {string} message - error message
1016
+ * @param {string} code - error code
1017
+ * @param {string} tsconfigFile - path to tsconfig file
1018
+ * @param {Error?} cause - cause of this error
1019
+ */ constructor(message, code, tsconfigFile, cause){
1020
+ super(message);
1021
+ // Set the prototype explicitly.
1022
+ Object.setPrototypeOf(this, TSConfckParseError.prototype);
1023
+ this.name = TSConfckParseError.name;
1024
+ this.code = code;
1025
+ this.cause = cause;
1026
+ this.tsconfigFile = tsconfigFile;
1027
+ }
1028
+ }
1029
+ /**
1030
+ *
1031
+ * @param {any} tsconfig
1032
+ * @param {string} tsconfigFile
1033
+ */ function applyDefaults(tsconfig, tsconfigFile) {
1034
+ if (isJSConfig(tsconfigFile)) tsconfig.compilerOptions = {
1035
+ ...DEFAULT_JSCONFIG_COMPILER_OPTIONS,
1036
+ ...tsconfig.compilerOptions
1037
+ };
1038
+ }
1039
+ const DEFAULT_JSCONFIG_COMPILER_OPTIONS = {
1040
+ allowJs: true,
1041
+ maxNodeModuleJsDepth: 2,
1042
+ allowSyntheticDefaultImports: true,
1043
+ skipLibCheck: true,
1044
+ noEmit: true
582
1045
  };
1046
+ /**
1047
+ * @param {string} configFileName
1048
+ */ function isJSConfig(configFileName) {
1049
+ return 'jsconfig.json' === external_node_path_namespaceObject["default"].basename(configFileName);
1050
+ }
1051
+ async function loadTsconfig(root, tsconfigPath = 'tsconfig.json') {
1052
+ const tsconfigFileName = await find((0, external_node_path_namespaceObject.join)(root, tsconfigPath), {
1053
+ root,
1054
+ configName: (0, external_node_path_namespaceObject.basename)(tsconfigPath)
1055
+ });
1056
+ if (tsconfigFileName) {
1057
+ const { tsconfig } = await parse(tsconfigFileName);
1058
+ return tsconfig;
1059
+ }
1060
+ return {};
1061
+ }
583
1062
  /**
584
1063
  * This function helps you to autocomplete configuration types.
585
1064
  * It accepts a Rslib config object, or a function that returns a config.
@@ -591,7 +1070,7 @@ const resolveConfigPath = (root, customConfig)=>{
591
1070
  if (customConfig) {
592
1071
  const customConfigPath = (0, external_node_path_namespaceObject.isAbsolute)(customConfig) ? customConfig : (0, external_node_path_namespaceObject.join)(root, customConfig);
593
1072
  if (external_node_fs_namespaceObject["default"].existsSync(customConfigPath)) return customConfigPath;
594
- dist_logger.warn(`Cannot find config file: ${index_js_namespaceObject["default"].dim(customConfigPath)}\n`);
1073
+ index_js_namespaceObject.logger.warn(`Cannot find config file: ${picocolors_index_js_namespaceObject["default"].dim(customConfigPath)}\n`);
595
1074
  }
596
1075
  const configFilePath = findConfig((0, external_node_path_namespaceObject.join)(root, DEFAULT_CONFIG_NAME));
597
1076
  if (configFilePath) return configFilePath;
@@ -666,7 +1145,7 @@ const composeExternalsWarnConfig = (format, ...externalsArray)=>{
666
1145
  };
667
1146
  if (contextInfo.issuer && 'commonjs' === dependencyType) {
668
1147
  matchUserExternals(externals, request, _callback);
669
- if (externalized) dist_logger.warn(composeModuleImportWarn(request));
1148
+ if (externalized) index_js_namespaceObject.logger.warn(composeModuleImportWarn(request));
670
1149
  }
671
1150
  callback();
672
1151
  }
@@ -678,7 +1157,7 @@ const composeAutoExternalConfig = (options)=>{
678
1157
  const { autoExternal, pkgJson, userExternals } = options;
679
1158
  if (!autoExternal) return {};
680
1159
  if (!pkgJson) {
681
- dist_logger.warn('autoExternal configuration will not be applied due to read package.json failed');
1160
+ index_js_namespaceObject.logger.warn('autoExternal configuration will not be applied due to read package.json failed');
682
1161
  return {};
683
1162
  }
684
1163
  const externalOptions = {
@@ -788,6 +1267,16 @@ function composeBannerFooterConfig(banner, footer) {
788
1267
  }
789
1268
  };
790
1269
  }
1270
+ function composeDecoratorsConfig(compilerOptions, version) {
1271
+ if (version || !compilerOptions?.experimentalDecorators) return {};
1272
+ return {
1273
+ source: {
1274
+ decorators: {
1275
+ version: 'legacy'
1276
+ }
1277
+ }
1278
+ };
1279
+ }
791
1280
  async function createConstantRsbuildConfig() {
792
1281
  return (0, core_namespaceObject.defineConfig)({
793
1282
  mode: 'production',
@@ -901,7 +1390,7 @@ const composeFormatConfig = (format)=>{
901
1390
  throw new Error(`Unsupported format: ${format}`);
902
1391
  }
903
1392
  };
904
- const composeModuleImportWarn = (request)=>`The externalized commonjs request ${index_js_namespaceObject["default"].green(`"${request}"`)} will use ${index_js_namespaceObject["default"].blue('"module"')} external type in ESM format. If you want to specify other external type, considering set the request and type with ${index_js_namespaceObject["default"].blue('"output.externals"')}.`;
1393
+ const composeModuleImportWarn = (request)=>`The externalized commonjs request ${picocolors_index_js_namespaceObject["default"].green(`"${request}"`)} will use ${picocolors_index_js_namespaceObject["default"].blue('"module"')} external type in ESM format. If you want to specify other external type, considering set the request and type with ${picocolors_index_js_namespaceObject["default"].blue('"output.externals"')}.`;
905
1394
  const composeExternalsConfig = (format, externals)=>{
906
1395
  // TODO: Define the internal externals config in Rsbuild's externals instead
907
1396
  // Rspack's externals as they will not be merged from different fields. All externals
@@ -963,23 +1452,9 @@ const composeSyntaxConfig = (syntax, target)=>{
963
1452
  }
964
1453
  },
965
1454
  output: {
966
- overrideBrowserslist: transformSyntaxToBrowserslist(syntax)
1455
+ overrideBrowserslist: transformSyntaxToBrowserslist(syntax, target)
967
1456
  }
968
1457
  };
969
- // If `syntax` is not defined, Rslib will try to determine by the `target`, with the last version of the target.
970
- const lastTargetVersions = {
971
- node: [
972
- 'last 1 node versions'
973
- ],
974
- web: [
975
- 'last 1 Chrome versions',
976
- 'last 1 Firefox versions',
977
- 'last 1 Edge versions',
978
- 'last 1 Safari versions',
979
- 'last 1 ios_saf versions',
980
- 'not dead'
981
- ]
982
- };
983
1458
  return {
984
1459
  tools: {
985
1460
  rspack: (config)=>{
@@ -990,10 +1465,8 @@ const composeSyntaxConfig = (syntax, target)=>{
990
1465
  }
991
1466
  },
992
1467
  output: {
993
- overrideBrowserslist: 'web' === target ? lastTargetVersions.web : 'node' === target ? lastTargetVersions.node : [
994
- ...lastTargetVersions.node,
995
- ...lastTargetVersions.web
996
- ]
1468
+ // If `syntax` is not defined, Rslib will try to determine by the `target`, with the last version of the target.
1469
+ overrideBrowserslist: ESX_TO_BROWSERSLIST.esnext(target)
997
1470
  }
998
1471
  };
999
1472
  };
@@ -1066,7 +1539,7 @@ const composeBundleConfig = (jsExtension, bundle = true)=>{
1066
1539
  const composeDtsConfig = async (libConfig, dtsExtension)=>{
1067
1540
  const { dts, bundle, output, autoExternal, banner, footer } = libConfig;
1068
1541
  if (false === dts || void 0 === dts) return {};
1069
- const { pluginDts } = await Promise.resolve().then(__webpack_require__.bind(__webpack_require__, "rsbuild-plugin-dts"));
1542
+ const { pluginDts } = await import("rsbuild-plugin-dts");
1070
1543
  return {
1071
1544
  plugins: [
1072
1545
  pluginDts({
@@ -1113,17 +1586,15 @@ const composeTargetConfig = (target = 'web')=>{
1113
1586
  target: 'node'
1114
1587
  }
1115
1588
  };
1116
- case 'neutral':
1117
- return {
1118
- tools: {
1119
- rspack: {
1120
- target: [
1121
- 'web',
1122
- 'node'
1123
- ]
1124
- }
1125
- }
1126
- };
1589
+ // TODO: Support `neutral` target, however Rsbuild don't list it as an option in the target field.
1590
+ // case 'neutral':
1591
+ // return {
1592
+ // tools: {
1593
+ // rspack: {
1594
+ // target: ['web', 'node'],
1595
+ // },
1596
+ // },
1597
+ // };
1127
1598
  default:
1128
1599
  throw new Error(`Unsupported platform: ${target}`);
1129
1600
  }
@@ -1144,7 +1615,7 @@ const composeExternalHelpersConfig = (externalHelpers, pkgJson)=>{
1144
1615
  ...Object.keys(pkgJson?.devDependencies ?? [])
1145
1616
  ];
1146
1617
  if (!deps.includes(SWC_HELPERS)) {
1147
- dist_logger.error(`${index_js_namespaceObject["default"].green('externalHelpers')} is enabled, but the ${index_js_namespaceObject["default"].blue(SWC_HELPERS)} dependency declaration was not found in package.json.`);
1618
+ index_js_namespaceObject.logger.error(`${picocolors_index_js_namespaceObject["default"].green('externalHelpers')} is enabled, but the ${picocolors_index_js_namespaceObject["default"].blue(SWC_HELPERS)} dependency declaration was not found in package.json.`);
1148
1619
  process.exit(1);
1149
1620
  }
1150
1621
  defaultConfig = Object.assign(defaultConfig, {
@@ -1159,6 +1630,7 @@ const composeExternalHelpersConfig = (externalHelpers, pkgJson)=>{
1159
1630
  async function composeLibRsbuildConfig(config, configPath) {
1160
1631
  const rootPath = (0, external_node_path_namespaceObject.dirname)(configPath);
1161
1632
  const pkgJson = readPackageJson(rootPath);
1633
+ const { compilerOptions } = await loadTsconfig(rootPath, config.source?.tsconfigPath);
1162
1634
  const { format, banner = {}, footer = {}, autoExtension = true, autoExternal = true, externalHelpers = false } = config;
1163
1635
  const formatConfig = composeFormatConfig(format);
1164
1636
  const externalHelpersConfig = composeExternalHelpersConfig(externalHelpers, pkgJson);
@@ -1177,7 +1649,8 @@ async function composeLibRsbuildConfig(config, configPath) {
1177
1649
  const externalsWarnConfig = composeExternalsWarnConfig(format, autoExternalConfig?.output?.externals, externalsConfig?.output?.externals);
1178
1650
  const minifyConfig = composeMinifyConfig(config.output?.minify);
1179
1651
  const bannerFooterConfig = composeBannerFooterConfig(banner, footer);
1180
- return (0, core_namespaceObject.mergeRsbuildConfig)(formatConfig, externalHelpersConfig, externalsWarnConfig, externalsConfig, autoExternalConfig, autoExtensionConfig, syntaxConfig, bundleConfig, targetConfig, entryConfig, minifyConfig, dtsConfig, bannerFooterConfig);
1652
+ const decoratorsConfig = composeDecoratorsConfig(compilerOptions, config.source?.decorators?.version);
1653
+ return (0, core_namespaceObject.mergeRsbuildConfig)(formatConfig, externalHelpersConfig, externalsWarnConfig, externalsConfig, autoExternalConfig, autoExtensionConfig, syntaxConfig, bundleConfig, targetConfig, entryConfig, minifyConfig, dtsConfig, bannerFooterConfig, decoratorsConfig);
1181
1654
  }
1182
1655
  async function composeCreateRsbuildConfig(rslibConfig, path) {
1183
1656
  const constantRsbuildConfig = await createConstantRsbuildConfig();
@@ -1257,7 +1730,7 @@ const applyCommonOptions = (command)=>{
1257
1730
  command.option('-c --config <config>', 'specify the configuration file, can be a relative or absolute path').option('--env-mode <mode>', 'specify the env mode to load the `.env.[mode]` file');
1258
1731
  };
1259
1732
  function runCli() {
1260
- commander_index_js_namespaceObject.program.name('rslib').usage('<command> [options]').version("0.0.5");
1733
+ commander_index_js_namespaceObject.program.name('rslib').usage('<command> [options]').version("0.0.6");
1261
1734
  const buildCommand = commander_index_js_namespaceObject.program.command('build');
1262
1735
  const inspectCommand = commander_index_js_namespaceObject.program.command('inspect');
1263
1736
  [
@@ -1272,8 +1745,8 @@ function runCli() {
1272
1745
  });
1273
1746
  await build(rslibConfig, options);
1274
1747
  } catch (err) {
1275
- dist_logger.error('Failed to build.');
1276
- dist_logger.error(err);
1748
+ index_js_namespaceObject.logger.error('Failed to build.');
1749
+ index_js_namespaceObject.logger.error(err);
1277
1750
  process.exit(1);
1278
1751
  }
1279
1752
  });
@@ -1292,12 +1765,13 @@ function runCli() {
1292
1765
  writeToDisk: true
1293
1766
  });
1294
1767
  } catch (err) {
1295
- dist_logger.error('Failed to inspect config.');
1296
- dist_logger.error(err);
1768
+ index_js_namespaceObject.logger.error('Failed to inspect config.');
1769
+ index_js_namespaceObject.logger.error(err);
1297
1770
  process.exit(1);
1298
1771
  }
1299
1772
  });
1300
1773
  commander_index_js_namespaceObject.program.parse();
1301
1774
  }
1302
- const src_version = "0.0.5";
1303
- export { build, defineConfig, loadConfig, dist_logger as logger, prepareCli, runCli, src_version as version };
1775
+ const src_version = "0.0.6";
1776
+ var __webpack_exports__logger = index_js_namespaceObject.logger;
1777
+ export { build, defineConfig, loadConfig, prepareCli, runCli, src_version as version, __webpack_exports__logger as logger };