tsdown 0.18.2 → 0.18.4

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,672 +1,32 @@
1
1
  import { createRequire as __cjs_createRequire } from "node:module";
2
2
  const __cjs_require = __cjs_createRequire(import.meta.url);
3
- import { a as getNameLabel, c as importWithError, d as pkgExists, f as promiseWithResolvers, g as toArray, h as slash, i as generateColor, l as matchPattern, m as resolveRegex, n as LogLevels, o as globalLogger, p as resolveComma, r as createLogger, s as prettyFormat, t as version, u as noop } from "./package-CpLZpKe2.mjs";
3
+ import { a as globalLogger, c as matchPattern, d as promiseWithResolvers, f as resolveComma, h as toArray, l as noop, m as slash, o as prettyFormat, s as importWithError, t as LogLevels } from "./logger-s1ImI5j1.mjs";
4
+ import { a as loadConfigFile, c as formatBytes, d as cleanOutDir, f as fsCopy, h as lowestCommonAncestor, i as resolveUserConfig, l as CssCodeSplitPlugin, m as fsRemove, o as getPackageType, p as fsExists, r as mergeUserOptions, s as writeExports, u as cleanChunks } from "./config-DlCfPR2i.mjs";
5
+ import { t as version } from "./package-BZkqghxy.mjs";
4
6
  import { builtinModules, isBuiltin } from "node:module";
5
- import path, { dirname, extname, join, normalize, sep } from "node:path";
6
- import { fileURLToPath, pathToFileURL } from "node:url";
7
+ import { chmod, mkdtemp, readFile, writeFile } from "node:fs/promises";
8
+ import path, { join } from "node:path";
9
+ import process from "node:process";
10
+ import util, { formatWithOptions, promisify } from "node:util";
7
11
  import { blue, bold, dim, green, underline } from "ansis";
8
- import { clearRequireCache, init, isSupported } from "import-without-cache";
9
- import * as Rolldown from "rolldown";
10
- import { VERSION, build, watch } from "rolldown";
11
12
  import { createDebug } from "obug";
12
- import { access, chmod, cp, mkdtemp, readFile, rm, stat, writeFile } from "node:fs/promises";
13
- import process, { env } from "node:process";
14
- import { createConfigCoreLoader } from "unconfig-core";
15
- const picomatch = __cjs_require("picomatch");
16
- import { createDefu } from "defu";
17
13
  import { glob, isDynamicPattern } from "tinyglobby";
18
14
  import { RE_CSS, RE_DTS, RE_JS, RE_NODE_MODULES } from "rolldown-plugin-dts/filename";
19
- const minVersion = __cjs_require("semver/ranges/min-version.js");
20
- import { up } from "empathic/find";
21
- import { up as up$1 } from "empathic/package";
15
+ import { fileURLToPath } from "node:url";
16
+ import { clearRequireCache } from "import-without-cache";
17
+ import * as Rolldown from "rolldown";
18
+ import { VERSION, build, watch } from "rolldown";
22
19
  const coerce = __cjs_require("semver/functions/coerce.js");
23
20
  const satisfies = __cjs_require("semver/functions/satisfies.js");
24
21
  import { Hookable } from "hookable";
25
22
  import { exec } from "tinyexec";
26
23
  const treeKill = __cjs_require("tree-kill");
27
- import util, { formatWithOptions, promisify } from "node:util";
28
24
  import { tmpdir } from "node:os";
29
25
  import { importGlobPlugin } from "rolldown/experimental";
30
26
  import { Buffer } from "node:buffer";
31
27
  import { brotliCompress, gzip } from "node:zlib";
32
28
  import readline from "node:readline";
33
29
 
34
- //#region node_modules/.pnpm/is-in-ci@2.0.0/node_modules/is-in-ci/index.js
35
- const check = (key) => key in env && env[key] !== "0" && env[key] !== "false";
36
- const isInCi = check("CI") || check("CONTINUOUS_INTEGRATION");
37
- var is_in_ci_default = isInCi;
38
-
39
- //#endregion
40
- //#region src/utils/fs.ts
41
- function fsExists(path$1) {
42
- return access(path$1).then(() => true, () => false);
43
- }
44
- function fsStat(path$1) {
45
- return stat(path$1).catch(() => null);
46
- }
47
- function fsRemove(path$1) {
48
- return rm(path$1, {
49
- force: true,
50
- recursive: true
51
- }).catch(() => {});
52
- }
53
- function fsCopy(from, to) {
54
- return cp(from, to, {
55
- recursive: true,
56
- force: true
57
- });
58
- }
59
- function lowestCommonAncestor(...filepaths) {
60
- if (filepaths.length === 0) return "";
61
- if (filepaths.length === 1) return dirname(filepaths[0]);
62
- filepaths = filepaths.map(normalize);
63
- const [first, ...rest] = filepaths;
64
- let ancestor = first.split(sep);
65
- for (const filepath of rest) {
66
- const directories = filepath.split(sep, ancestor.length);
67
- let index = 0;
68
- for (const directory of directories) if (directory === ancestor[index]) index += 1;
69
- else {
70
- ancestor = ancestor.slice(0, index);
71
- break;
72
- }
73
- ancestor = ancestor.slice(0, index);
74
- }
75
- return ancestor.length <= 1 && ancestor[0] === "" ? sep + ancestor[0] : ancestor.join(sep);
76
- }
77
- function stripExtname(filePath) {
78
- const ext = extname(filePath);
79
- if (!ext.length) return filePath;
80
- return filePath.slice(0, -ext.length);
81
- }
82
-
83
- //#endregion
84
- //#region src/config/file.ts
85
- const debug$9 = createDebug("tsdown:config:file");
86
- async function loadViteConfig(prefix, cwd, configLoader) {
87
- const loader = resolveConfigLoader(configLoader);
88
- debug$9("Loading Vite config via loader: ", loader);
89
- const parser = createParser(loader);
90
- const [result] = await createConfigCoreLoader({
91
- sources: [{
92
- files: [`${prefix}.config`],
93
- extensions: [
94
- "js",
95
- "mjs",
96
- "ts",
97
- "cjs",
98
- "mts",
99
- "mts"
100
- ],
101
- parser
102
- }],
103
- cwd
104
- }).load(true);
105
- if (!result) return;
106
- const { config, source } = result;
107
- globalLogger.info(`Using Vite config: ${underline(source)}`);
108
- const resolved = await config;
109
- if (typeof resolved === "function") return resolved({
110
- command: "build",
111
- mode: "production"
112
- });
113
- return resolved;
114
- }
115
- const configPrefix = "tsdown.config";
116
- async function loadConfigFile(inlineConfig, workspace) {
117
- let cwd = inlineConfig.cwd || process.cwd();
118
- let overrideConfig = false;
119
- let { config: filePath } = inlineConfig;
120
- if (filePath === false) return { configs: [{}] };
121
- if (typeof filePath === "string") {
122
- const stats = await fsStat(filePath);
123
- if (stats) {
124
- const resolved = path.resolve(filePath);
125
- if (stats.isFile()) {
126
- overrideConfig = true;
127
- filePath = resolved;
128
- cwd = path.dirname(filePath);
129
- } else if (stats.isDirectory()) cwd = resolved;
130
- }
131
- }
132
- const loader = resolveConfigLoader(inlineConfig.configLoader);
133
- debug$9("Using config loader:", loader);
134
- const parser = createParser(loader);
135
- const [result] = await createConfigCoreLoader({
136
- sources: overrideConfig ? [{
137
- files: [filePath],
138
- extensions: [],
139
- parser
140
- }] : [{
141
- files: [configPrefix],
142
- extensions: [
143
- "ts",
144
- "mts",
145
- "cts",
146
- "js",
147
- "mjs",
148
- "cjs",
149
- "json"
150
- ],
151
- parser
152
- }, {
153
- files: ["package.json"],
154
- parser
155
- }],
156
- cwd,
157
- stopAt: workspace && path.dirname(workspace)
158
- }).load(true);
159
- let exported = [];
160
- let file;
161
- if (result) {
162
- ({config: exported, source: file} = result);
163
- globalLogger.info(`config file: ${underline(file)}`, loader === "native" ? "" : `(${loader})`);
164
- exported = await exported;
165
- if (typeof exported === "function") exported = await exported(inlineConfig, { ci: is_in_ci_default });
166
- }
167
- exported = toArray(exported);
168
- if (exported.length === 0) exported.push({});
169
- if (exported.some((config) => typeof config === "function")) throw new Error("Function should not be nested within multiple tsdown configurations. It must be at the top level.\nExample: export default defineConfig(() => [...])");
170
- return {
171
- configs: exported.map((config) => ({
172
- ...config,
173
- cwd: config.cwd ? path.resolve(cwd, config.cwd) : cwd
174
- })),
175
- file
176
- };
177
- }
178
- const isBun = !!process.versions.bun;
179
- const nativeTS = process.features.typescript || process.versions.deno;
180
- const autoLoader = isBun || nativeTS && isSupported ? "native" : "unrun";
181
- function resolveConfigLoader(configLoader = "auto") {
182
- if (configLoader === "auto") return autoLoader;
183
- else return configLoader === "native" ? "native" : "unrun";
184
- }
185
- function createParser(loader) {
186
- return async (filepath) => {
187
- const basename = path.basename(filepath);
188
- const isPkgJson = basename === "package.json";
189
- if (basename === configPrefix || isPkgJson || basename.endsWith(".json")) {
190
- const contents = await readFile(filepath, "utf8");
191
- const parsed = JSON.parse(contents);
192
- if (isPkgJson) return parsed?.tsdown;
193
- return parsed;
194
- }
195
- if (loader === "native") return nativeImport(filepath);
196
- return unrunImport(filepath);
197
- };
198
- }
199
- async function nativeImport(id) {
200
- const url = pathToFileURL(id);
201
- const importAttributes = Object.create(null);
202
- if (isSupported) {
203
- importAttributes.cache = "no";
204
- init({ skipNodeModules: true });
205
- } else if (!isBun) url.searchParams.set("no-cache", crypto.randomUUID());
206
- const mod = await import(url.href, { with: importAttributes }).catch((error) => {
207
- if (error?.message?.includes?.("Cannot find module")) throw new Error(`Failed to load the config file. Try setting the --config-loader CLI flag to \`unrun\`.\n\n${error.message}`, { cause: error });
208
- else throw error;
209
- });
210
- return mod.default || mod;
211
- }
212
- async function unrunImport(id) {
213
- const { unrun } = await import("unrun");
214
- const { module: module$1 } = await unrun({ path: pathToFileURL(id).href });
215
- return module$1;
216
- }
217
-
218
- //#endregion
219
- //#region src/features/clean.ts
220
- const debug$8 = createDebug("tsdown:clean");
221
- const RE_LAST_SLASH = /[/\\]$/;
222
- async function cleanOutDir(configs) {
223
- const removes = /* @__PURE__ */ new Set();
224
- for (const config of configs) {
225
- if (config.debug && (config.debug.clean ?? true)) config.clean.push(".rolldown");
226
- if (!config.clean.length) continue;
227
- const files = await glob(config.clean, {
228
- cwd: config.cwd,
229
- absolute: true,
230
- onlyFiles: false,
231
- dot: true
232
- });
233
- const normalizedOutDir = config.outDir.replace(RE_LAST_SLASH, "");
234
- for (const file of files) if (file.replace(RE_LAST_SLASH, "") !== normalizedOutDir) removes.add(file);
235
- }
236
- if (!removes.size) return;
237
- globalLogger.info(`Cleaning ${removes.size} files`);
238
- await Promise.all([...removes].map(async (file) => {
239
- debug$8("Removing", file);
240
- await fsRemove(file);
241
- }));
242
- debug$8("Removed %d files", removes.size);
243
- }
244
- function resolveClean(clean, outDir, cwd) {
245
- if (clean === true) clean = [slash(outDir)];
246
- else if (!clean) clean = [];
247
- if (clean.some((item) => path.resolve(item) === cwd)) throw new Error("Cannot clean the current working directory. Please specify a different path to clean option.");
248
- return clean;
249
- }
250
- async function cleanChunks(outDir, chunks) {
251
- await Promise.all(chunks.map(async (chunk) => {
252
- const filePath = path.resolve(outDir, chunk.fileName);
253
- debug$8("Removing chunk file", filePath);
254
- await fsRemove(filePath);
255
- }));
256
- }
257
-
258
- //#endregion
259
- //#region src/features/entry.ts
260
- async function resolveEntry(logger, entry, cwd, color, nameLabel) {
261
- if (!entry || Object.keys(entry).length === 0) {
262
- const defaultEntry = path.resolve(cwd, "src/index.ts");
263
- if (await fsExists(defaultEntry)) entry = { index: defaultEntry };
264
- else throw new Error(`${nameLabel} No input files, try "tsdown <your-file>" or create src/index.ts`);
265
- }
266
- const entryMap = await toObjectEntry(entry, cwd);
267
- const entries = Object.values(entryMap);
268
- if (entries.length === 0) throw new Error(`${nameLabel} Cannot find entry: ${JSON.stringify(entry)}`);
269
- logger.info(nameLabel, `entry: ${color(entries.map((entry$1) => path.relative(cwd, entry$1)).join(", "))}`);
270
- return entryMap;
271
- }
272
- async function toObjectEntry(entry, cwd) {
273
- if (typeof entry === "string") entry = [entry];
274
- if (!Array.isArray(entry)) return Object.fromEntries((await Promise.all(Object.entries(entry).map(async ([key, value]) => {
275
- if (!key.includes("*")) {
276
- if (Array.isArray(value)) throw new TypeError(`Object entry "${key}" cannot have an array value when the key is not a glob pattern.`);
277
- return [[key, value]];
278
- }
279
- const patterns = toArray(value);
280
- const positivePatterns = patterns.filter((p) => !p.startsWith("!"));
281
- if (positivePatterns.length === 0) throw new TypeError(`Object entry "${key}" has no positive pattern. At least one positive pattern is required.`);
282
- if (positivePatterns.length > 1) throw new TypeError(`Object entry "${key}" has multiple positive patterns: ${positivePatterns.join(", ")}. Only one positive pattern is allowed. Use negation patterns (prefixed with "!") to exclude files.`);
283
- const valueGlob = picomatch.scan(positivePatterns[0]);
284
- return (await glob(patterns, {
285
- cwd,
286
- expandDirectories: false
287
- })).map((file) => [slash(key.replaceAll("*", stripExtname(path.relative(valueGlob.base, file)))), path.resolve(cwd, file)]);
288
- }))).flat());
289
- const isGlob = entry.some((e) => isDynamicPattern(e));
290
- let resolvedEntry;
291
- if (isGlob) resolvedEntry = (await glob(entry, {
292
- cwd,
293
- expandDirectories: false,
294
- absolute: true
295
- })).map((file) => path.resolve(file));
296
- else resolvedEntry = entry;
297
- const base = lowestCommonAncestor(...resolvedEntry);
298
- return Object.fromEntries(resolvedEntry.map((file) => {
299
- return [slash(stripExtname(path.relative(base, file))), file];
300
- }));
301
- }
302
-
303
- //#endregion
304
- //#region src/utils/format.ts
305
- function formatBytes(bytes) {
306
- if (bytes === Infinity) return void 0;
307
- return `${(bytes / 1e3).toFixed(2)} kB`;
308
- }
309
- function detectIndentation(jsonText) {
310
- const lines = jsonText.split(/\r?\n/);
311
- for (const line of lines) {
312
- const match = line.match(/^(\s+)\S/);
313
- if (!match) continue;
314
- if (match[1].includes(" ")) return " ";
315
- return match[1].length;
316
- }
317
- return 2;
318
- }
319
-
320
- //#endregion
321
- //#region src/features/pkg/exports.ts
322
- async function writeExports(options, chunks) {
323
- const pkg = options.pkg;
324
- const exports = options.exports;
325
- const { publishExports, ...generated } = await generateExports(pkg, chunks, exports);
326
- const updatedPkg = {
327
- ...pkg,
328
- ...generated,
329
- packageJsonPath: void 0
330
- };
331
- if (publishExports) {
332
- updatedPkg.publishConfig ||= {};
333
- updatedPkg.publishConfig.exports = publishExports;
334
- }
335
- const original = await readFile(pkg.packageJsonPath, "utf8");
336
- let contents = JSON.stringify(updatedPkg, null, detectIndentation(original));
337
- if (original.endsWith("\n")) contents += "\n";
338
- if (contents !== original) await writeFile(pkg.packageJsonPath, contents, "utf8");
339
- }
340
- function shouldExclude(fileName, exclude) {
341
- if (!exclude?.length) return false;
342
- return matchPattern(fileName, exclude);
343
- }
344
- async function generateExports(pkg, chunks, { devExports, all, exclude, customExports }) {
345
- const pkgRoot$1 = path.dirname(pkg.packageJsonPath);
346
- let main, module$1, cjsTypes, esmTypes;
347
- const exportsMap = /* @__PURE__ */ new Map();
348
- for (const [format, chunksByFormat] of Object.entries(chunks)) {
349
- if (format !== "es" && format !== "cjs") continue;
350
- const filteredChunks = chunksByFormat.filter((chunk) => chunk.type === "chunk" && chunk.isEntry && !shouldExclude(chunk.fileName, exclude));
351
- const onlyOneEntry = filteredChunks.filter((chunk) => !RE_DTS.test(chunk.fileName)).length === 1;
352
- for (const chunk of filteredChunks) {
353
- const normalizedName = slash(chunk.fileName);
354
- let name = stripExtname(normalizedName);
355
- const isDts = name.endsWith(".d");
356
- if (isDts) name = name.slice(0, -2);
357
- const isIndex = onlyOneEntry || name === "index";
358
- const outDirRelative = slash(path.relative(pkgRoot$1, chunk.outDir));
359
- const distFile = `${outDirRelative ? `./${outDirRelative}` : "."}/${normalizedName}`;
360
- if (isIndex) {
361
- name = ".";
362
- if (format === "cjs") if (isDts) cjsTypes = distFile;
363
- else main = distFile;
364
- else if (format === "es") if (isDts) esmTypes = distFile;
365
- else module$1 = distFile;
366
- } else if (name.endsWith("/index")) name = `./${name.slice(0, -6)}`;
367
- else name = `./${name}`;
368
- let subExport = exportsMap.get(name);
369
- if (!subExport) {
370
- subExport = {};
371
- exportsMap.set(name, subExport);
372
- }
373
- if (!isDts) {
374
- subExport[format] = distFile;
375
- if (chunk.facadeModuleId && !subExport.src) subExport.src = `./${slash(path.relative(pkgRoot$1, chunk.facadeModuleId))}`;
376
- }
377
- }
378
- }
379
- const sortedExportsMap = Array.from(exportsMap.entries()).toSorted(([a], [b]) => {
380
- if (a === "index") return -1;
381
- return a.localeCompare(b);
382
- });
383
- let exports = Object.fromEntries(sortedExportsMap.map(([name, subExport]) => [name, genSubExport(devExports, subExport)]));
384
- exportMeta(exports, all);
385
- if (customExports) exports = await customExports(exports, {
386
- pkg,
387
- chunks,
388
- isPublish: false
389
- });
390
- let publishExports;
391
- if (devExports) {
392
- publishExports = Object.fromEntries(sortedExportsMap.map(([name, subExport]) => [name, genSubExport(false, subExport)]));
393
- exportMeta(publishExports, all);
394
- if (customExports) publishExports = await customExports(publishExports, {
395
- pkg,
396
- chunks,
397
- isPublish: true
398
- });
399
- }
400
- return {
401
- main: main || module$1 || pkg.main,
402
- module: module$1 || pkg.module,
403
- types: cjsTypes || esmTypes || pkg.types,
404
- exports,
405
- publishExports
406
- };
407
- }
408
- function genSubExport(devExports, { src, es, cjs }) {
409
- if (devExports === true) return src;
410
- let value;
411
- const dualFormat = es && cjs;
412
- if (!dualFormat && !devExports) value = cjs || es;
413
- else {
414
- value = {};
415
- if (typeof devExports === "string") value[devExports] = src;
416
- if (cjs) value[dualFormat ? "require" : "default"] = cjs;
417
- if (es) value[dualFormat ? "import" : "default"] = es;
418
- }
419
- return value;
420
- }
421
- function exportMeta(exports, all) {
422
- if (all) exports["./*"] = "./*";
423
- else exports["./package.json"] = "./package.json";
424
- }
425
- function hasExportsTypes(pkg) {
426
- const exports = pkg?.exports;
427
- if (!exports) return false;
428
- if (typeof exports === "object" && exports !== null && !Array.isArray(exports)) {
429
- if ("types" in exports) return true;
430
- if ("." in exports) {
431
- const mainExport = exports["."];
432
- if (typeof mainExport === "object" && mainExport !== null && "types" in mainExport) return true;
433
- }
434
- }
435
- return false;
436
- }
437
-
438
- //#endregion
439
- //#region src/features/target.ts
440
- function resolveTarget(logger, target, color, pkg, nameLabel) {
441
- if (target === false) return;
442
- if (target == null) {
443
- const pkgTarget = resolvePackageTarget(pkg);
444
- if (pkgTarget) target = pkgTarget;
445
- else return;
446
- }
447
- if (typeof target === "number") throw new TypeError(`Invalid target: ${target}`);
448
- const targets = resolveComma(toArray(target));
449
- if (targets.length) logger.info(nameLabel, `target${targets.length > 1 ? "s" : ""}: ${color(targets.join(", "))}`);
450
- return targets;
451
- }
452
- function resolvePackageTarget(pkg) {
453
- const nodeVersion = pkg?.engines?.node;
454
- if (!nodeVersion) return;
455
- const nodeMinVersion = minVersion(nodeVersion);
456
- if (!nodeMinVersion) return;
457
- if (nodeMinVersion.version === "0.0.0") return;
458
- return `node${nodeMinVersion.version}`;
459
- }
460
-
461
- //#endregion
462
- //#region src/features/tsconfig.ts
463
- function findTsconfig(cwd, name = "tsconfig.json") {
464
- return up(name, { cwd }) || false;
465
- }
466
- async function resolveTsconfig(logger, tsconfig, cwd, color, nameLabel) {
467
- const original = tsconfig;
468
- if (tsconfig !== false) {
469
- if (tsconfig === true || tsconfig == null) {
470
- tsconfig = findTsconfig(cwd);
471
- if (original && !tsconfig) logger.warn(`No tsconfig found in ${blue(cwd)}`);
472
- } else {
473
- const tsconfigPath = path.resolve(cwd, tsconfig);
474
- const stat$1 = await fsStat(tsconfigPath);
475
- if (stat$1?.isFile()) tsconfig = tsconfigPath;
476
- else if (stat$1?.isDirectory()) {
477
- tsconfig = findTsconfig(tsconfigPath);
478
- if (!tsconfig) logger.warn(`No tsconfig found in ${blue(tsconfigPath)}`);
479
- } else {
480
- tsconfig = findTsconfig(cwd, tsconfig);
481
- if (!tsconfig) logger.warn(`tsconfig ${blue(original)} doesn't exist`);
482
- }
483
- }
484
- if (tsconfig) logger.info(nameLabel, `tsconfig: ${color(path.relative(cwd, tsconfig))}`);
485
- }
486
- return tsconfig;
487
- }
488
-
489
- //#endregion
490
- //#region src/utils/package.ts
491
- const debug$7 = createDebug("tsdown:package");
492
- async function readPackageJson(dir) {
493
- const packageJsonPath = up$1({ cwd: dir });
494
- if (!packageJsonPath) return;
495
- debug$7("Reading package.json:", packageJsonPath);
496
- const contents = await readFile(packageJsonPath, "utf8");
497
- return {
498
- ...JSON.parse(contents),
499
- packageJsonPath
500
- };
501
- }
502
- function getPackageType(pkg) {
503
- if (pkg?.type) {
504
- if (!["module", "commonjs"].includes(pkg.type)) throw new Error(`Invalid package.json type: ${pkg.type}`);
505
- return pkg.type;
506
- }
507
- }
508
- function normalizeFormat(format) {
509
- switch (format) {
510
- case "es":
511
- case "esm":
512
- case "module": return "es";
513
- case "cjs":
514
- case "commonjs": return "cjs";
515
- default: return format;
516
- }
517
- }
518
-
519
- //#endregion
520
- //#region src/config/options.ts
521
- const debugLog = createDebug("tsdown:config:options");
522
- async function resolveUserConfig(userConfig, inlineConfig) {
523
- let { entry, format = ["es"], plugins = [], clean = true, silent = false, logLevel = silent ? "silent" : "info", failOnWarn = "ci-only", customLogger, treeshake = true, platform = "node", outDir = "dist", sourcemap = false, dts, unused = false, watch: watch$1 = false, ignoreWatch, shims = false, skipNodeModulesBundle = false, publint: publint$1 = false, attw: attw$1 = false, fromVite, alias, tsconfig, report = true, target, env: env$1 = {}, copy: copy$1, publicDir, hash = true, cwd = process.cwd(), name, workspace, external, noExternal, exports = false, bundle, unbundle = typeof bundle === "boolean" ? !bundle : false, removeNodeProtocol, nodeProtocol, cjsDefault = true, globImport = true, inlineOnly, fixedExtension = platform === "node", debug: debug$10 = false, write = true } = userConfig;
524
- const pkg = await readPackageJson(cwd);
525
- if (workspace) name ||= pkg?.name;
526
- const color = generateColor(name);
527
- const nameLabel = getNameLabel(color, name);
528
- if (!filterConfig(inlineConfig.filter, cwd, name)) {
529
- debugLog("[filter] skipping config %s", cwd);
530
- return [];
531
- }
532
- const logger = createLogger(logLevel, {
533
- customLogger,
534
- failOnWarn: resolveFeatureOption(failOnWarn, true)
535
- });
536
- if (typeof bundle === "boolean") logger.warn("`bundle` option is deprecated. Use `unbundle` instead.");
537
- if (removeNodeProtocol && nodeProtocol) throw new TypeError("`removeNodeProtocol` is deprecated. Please only use `nodeProtocol` instead.");
538
- nodeProtocol = nodeProtocol ?? (removeNodeProtocol ? "strip" : false);
539
- outDir = path.resolve(cwd, outDir);
540
- clean = resolveClean(clean, outDir, cwd);
541
- const resolvedEntry = await resolveEntry(logger, entry, cwd, color, nameLabel);
542
- if (dts == null) dts = !!(pkg?.types || pkg?.typings || hasExportsTypes(pkg));
543
- target = resolveTarget(logger, target, color, pkg, nameLabel);
544
- tsconfig = await resolveTsconfig(logger, tsconfig, cwd, color, nameLabel);
545
- if (typeof external === "string") external = resolveRegex(external);
546
- if (typeof noExternal === "string") noExternal = resolveRegex(noExternal);
547
- publint$1 = resolveFeatureOption(publint$1, {});
548
- attw$1 = resolveFeatureOption(attw$1, {});
549
- exports = resolveFeatureOption(exports, {});
550
- unused = resolveFeatureOption(unused, {});
551
- report = resolveFeatureOption(report, {});
552
- dts = resolveFeatureOption(dts, {});
553
- if (!pkg) {
554
- if (exports) throw new Error("`package.json` not found, cannot write exports");
555
- if (publint$1) logger.warn(nameLabel, "publint is enabled but package.json is not found");
556
- if (attw$1) logger.warn(nameLabel, "attw is enabled but package.json is not found");
557
- }
558
- if (publicDir) if (copy$1) throw new TypeError("`publicDir` is deprecated. Cannot be used with `copy`");
559
- else logger.warn(`${blue`publicDir`} is deprecated. Use ${blue`copy`} instead.`);
560
- if (fromVite) {
561
- const viteUserConfig = await loadViteConfig(fromVite === true ? "vite" : fromVite, cwd, inlineConfig.configLoader);
562
- if (viteUserConfig) {
563
- const viteAlias = viteUserConfig.resolve?.alias;
564
- if (Array.isArray(viteAlias)) throw new TypeError("Unsupported resolve.alias in Vite config. Use object instead of array");
565
- if (viteAlias) alias = {
566
- ...alias,
567
- ...viteAlias
568
- };
569
- if (viteUserConfig.plugins) plugins = [viteUserConfig.plugins, plugins];
570
- }
571
- }
572
- ignoreWatch = toArray(ignoreWatch).map((ignore) => {
573
- ignore = resolveRegex(ignore);
574
- if (typeof ignore === "string") return path.resolve(cwd, ignore);
575
- return ignore;
576
- });
577
- if (noExternal != null && typeof noExternal !== "function") {
578
- const noExternalPatterns = toArray(noExternal);
579
- noExternal = (id) => matchPattern(id, noExternalPatterns);
580
- }
581
- if (inlineOnly != null) inlineOnly = toArray(inlineOnly);
582
- debug$10 = resolveFeatureOption(debug$10, {});
583
- if (debug$10) if (watch$1) {
584
- if (debug$10.devtools) logger.warn("Devtools is not supported in watch mode, disabling it.");
585
- debug$10.devtools = false;
586
- } else debug$10.devtools ??= !!pkgExists("@vitejs/devtools/cli");
587
- const config = {
588
- ...userConfig,
589
- alias,
590
- attw: attw$1,
591
- cjsDefault,
592
- clean,
593
- copy: publicDir || copy$1,
594
- cwd,
595
- debug: debug$10,
596
- dts,
597
- entry: resolvedEntry,
598
- env: env$1,
599
- exports,
600
- external,
601
- fixedExtension,
602
- globImport,
603
- hash,
604
- ignoreWatch,
605
- inlineOnly,
606
- logger,
607
- name,
608
- nameLabel,
609
- nodeProtocol,
610
- noExternal,
611
- outDir,
612
- pkg,
613
- platform,
614
- plugins,
615
- publint: publint$1,
616
- report,
617
- shims,
618
- skipNodeModulesBundle,
619
- sourcemap,
620
- target,
621
- treeshake,
622
- tsconfig,
623
- unbundle,
624
- unused,
625
- watch: watch$1,
626
- write
627
- };
628
- const objectFormat = typeof format === "object" && !Array.isArray(format);
629
- return (objectFormat ? Object.keys(format) : resolveComma(toArray(format, "es"))).map((fmt, idx) => {
630
- const once = idx === 0;
631
- const overrides = objectFormat ? format[fmt] : void 0;
632
- return {
633
- ...config,
634
- copy: once ? config.copy : void 0,
635
- onSuccess: once ? config.onSuccess : void 0,
636
- format: normalizeFormat(fmt),
637
- ...overrides
638
- };
639
- });
640
- }
641
- const defu = createDefu((obj, key, value) => {
642
- if (Array.isArray(obj[key]) && Array.isArray(value)) {
643
- obj[key] = value;
644
- return true;
645
- }
646
- });
647
- async function mergeUserOptions(defaults, user, args) {
648
- const userOutputOptions = typeof user === "function" ? await user(defaults, ...args) : user;
649
- if (!userOutputOptions) return defaults;
650
- return defu(userOutputOptions, defaults);
651
- }
652
- function resolveFeatureOption(value, defaults) {
653
- if (typeof value === "object" && value !== null) return resolveCIOption(value.enabled ?? true) ? value : false;
654
- return resolveCIOption(value) ? defaults : false;
655
- }
656
- function resolveCIOption(value) {
657
- if (value === "ci-only") return is_in_ci_default ? true : false;
658
- if (value === "local-only") return is_in_ci_default ? false : true;
659
- return value;
660
- }
661
- function filterConfig(filter, configCwd, name) {
662
- if (!filter) return true;
663
- let cwd = path.relative(process.cwd(), configCwd);
664
- if (cwd === "") cwd = ".";
665
- if (filter instanceof RegExp) return name && filter.test(name) || filter.test(cwd);
666
- return toArray(filter).some((value) => name && name === value || cwd === value);
667
- }
668
-
669
- //#endregion
670
30
  //#region src/config/workspace.ts
671
31
  const debug$6 = createDebug("tsdown:config:workspace");
672
32
  const DEFAULT_EXCLUDE_WORKSPACE = [
@@ -847,6 +207,20 @@ function executeOnSuccess(config) {
847
207
  //#region src/features/pkg/attw.ts
848
208
  const debug$4 = createDebug("tsdown:attw");
849
209
  const label$1 = dim`[attw]`;
210
+ const problemFlags = {
211
+ NoResolution: "no-resolution",
212
+ UntypedResolution: "untyped-resolution",
213
+ FalseCJS: "false-cjs",
214
+ FalseESM: "false-esm",
215
+ CJSResolvesToESM: "cjs-resolves-to-esm",
216
+ FallbackCondition: "fallback-condition",
217
+ CJSOnlyExportsDefault: "cjs-only-exports-default",
218
+ NamedExports: "named-exports",
219
+ FalseExportDefault: "false-export-default",
220
+ MissingExportEquals: "missing-export-equals",
221
+ UnexpectedModuleSyntax: "unexpected-module-syntax",
222
+ InternalResolutionError: "internal-resolution-error"
223
+ };
850
224
  /**
851
225
  * ATTW profiles.
852
226
  * Defines the resolution modes to ignore for each profile.
@@ -864,11 +238,13 @@ async function attw(options) {
864
238
  options.logger.warn("attw is enabled but package.json is not found");
865
239
  return;
866
240
  }
867
- const { profile = "strict", level = "warn", ...attwOptions } = options.attw;
241
+ const { profile = "strict", level = "warn", ignoreRules = [], ...attwOptions } = options.attw;
242
+ const invalidRules = ignoreRules.filter((rule) => !Object.values(problemFlags).includes(rule));
243
+ if (invalidRules.length) options.logger.warn(`attw config option 'ignoreRules' contains invalid value '${invalidRules.join(", ")}'.`);
868
244
  const t = performance.now();
869
245
  debug$4("Running attw check");
870
246
  const tempDir = await mkdtemp(path.join(tmpdir(), "tsdown-attw-"));
871
- const attwCore = await importWithError("@arethetypeswrong/core");
247
+ const attwCore = await importWithError("@arethetypeswrong/core", options.attw.resolvePaths);
872
248
  let checkResult;
873
249
  try {
874
250
  const { stdout: tarballInfo } = await exec("npm", [
@@ -891,6 +267,7 @@ async function attw(options) {
891
267
  let errorMessage;
892
268
  if (checkResult.types) {
893
269
  const problems = checkResult.problems.filter((problem) => {
270
+ if (ignoreRules.includes(problemFlags[problem.kind])) return false;
894
271
  if ("resolutionKind" in problem) return !profiles[profile]?.includes(problem.resolutionKind);
895
272
  return true;
896
273
  });
@@ -937,8 +314,8 @@ async function publint(options) {
937
314
  }
938
315
  const t = performance.now();
939
316
  debug$3("Running publint");
940
- const { publint: publint$1 } = await importWithError("publint");
941
- const { formatMessage } = await import("publint/utils");
317
+ const { publint: publint$1 } = await importWithError("publint", options.publint.resolvePaths);
318
+ const { formatMessage } = await importWithError("publint/utils", options.publint.resolvePaths);
942
319
  const { messages } = await publint$1({
943
320
  ...options.publint,
944
321
  pkgDir: path.dirname(options.pkg.packageJsonPath)
@@ -1365,7 +742,7 @@ async function getBuildOptions(config, format, configFiles, bundle, cjsDts = fal
1365
742
  return rolldownConfig;
1366
743
  }
1367
744
  async function resolveInputOptions(config, format, configFiles, bundle, cjsDts, isDualFormat) {
1368
- const { alias, cjsDefault, cwd, debug: debug$10, dts, entry, env: env$1, external, globImport, loader, logger, nameLabel, nodeProtocol, platform, plugins: userPlugins, report, shims, target, treeshake, tsconfig, unused, watch: watch$1 } = config;
745
+ const { alias, cjsDefault, cwd, debug: debug$7, dts, entry, env: env$1, external, globImport, loader, logger, nameLabel, nodeProtocol, platform, plugins: userPlugins, report, shims, target, treeshake, tsconfig, unused, watch: watch$1 } = config;
1369
746
  const plugins = [];
1370
747
  if (nodeProtocol) plugins.push(NodeProtocolPlugin(nodeProtocol));
1371
748
  if (config.pkg || config.skipNodeModulesBundle) plugins.push(ExternalPlugin(config));
@@ -1391,6 +768,8 @@ async function resolveInputOptions(config, format, configFiles, bundle, cjsDts,
1391
768
  }));
1392
769
  }
1393
770
  if (target) plugins.push(await LightningCSSPlugin({ target }));
771
+ const cssPlugin = CssCodeSplitPlugin(config);
772
+ if (cssPlugin) plugins.push(cssPlugin);
1394
773
  plugins.push(ShebangPlugin(logger, cwd, nameLabel, isDualFormat));
1395
774
  if (globImport) plugins.push(importGlobPlugin({ root: cwd }));
1396
775
  }
@@ -1427,7 +806,7 @@ async function resolveInputOptions(config, format, configFiles, bundle, cjsDts,
1427
806
  if (log.code === "MIXED_EXPORT") return;
1428
807
  defaultHandler(level, log);
1429
808
  } : void 0,
1430
- debug: debug$10 || void 0,
809
+ debug: debug$7 || void 0,
1431
810
  checks: { pluginTimings: false }
1432
811
  }, config.inputOptions, [format, { cjsDts }]);
1433
812
  }
@@ -1585,7 +964,7 @@ async function build$1(userOptions = {}) {
1585
964
  *
1586
965
  * Internal API, not for public use
1587
966
  *
1588
- * @private
967
+ * @internal
1589
968
  * @param config Resolved options
1590
969
  */
1591
970
  async function buildSingle(config, configFiles, isDualFormat, clean, restart, done) {