tsdown 0.19.0-beta.2 → 0.19.0-beta.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,21 +1,21 @@
1
1
  import { createRequire as __cjs_createRequire } from "node:module";
2
2
  const __cjs_require = __cjs_createRequire(import.meta.url);
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-D_2uXZBG.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-CQ0WjrHu.mjs";
5
- import { t as version } from "./package-PFFWH-Jh.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-C5G3WyAl.mjs";
4
+ import { a as getPackageType, c as defaultCssBundleName, d as loadConfigFile, f as fsCopy, h as lowestCommonAncestor, i as resolveUserConfig, l as cleanChunks, m as fsRemove, o as writeExports, p as fsExists, r as mergeUserOptions, s as formatBytes, u as cleanOutDir } from "./config-DCPo70ac.mjs";
5
+ import { n as version } from "./debug-C60bWO35.mjs";
6
6
  import { builtinModules, isBuiltin } from "node:module";
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";
11
7
  import { blue, bold, dim, green, underline } from "ansis";
12
- import { createDebug } from "obug";
13
- import { glob, isDynamicPattern } from "tinyglobby";
14
- import { fileURLToPath } from "node:url";
15
- import { RE_CSS, RE_DTS, RE_JS, RE_NODE_MODULES } from "rolldown-plugin-dts/filename";
16
8
  import { clearRequireCache } from "import-without-cache";
17
9
  import * as Rolldown from "rolldown";
18
10
  import { VERSION, build, watch } from "rolldown";
11
+ import path from "node:path";
12
+ import { createDebug } from "obug";
13
+ import { chmod, mkdtemp, readFile, writeFile } from "node:fs/promises";
14
+ import process from "node:process";
15
+ import { fileURLToPath } from "node:url";
16
+ import { formatWithOptions, inspect, promisify } from "node:util";
17
+ import { glob, isDynamicPattern } from "tinyglobby";
18
+ import { RE_CSS, RE_DTS, RE_JS, RE_NODE_MODULES } from "rolldown-plugin-dts/filename";
19
19
  const coerce = __cjs_require("semver/functions/coerce.js");
20
20
  const satisfies = __cjs_require("semver/functions/satisfies.js");
21
21
  import { Hookable } from "hookable";
@@ -407,6 +407,143 @@ function dedupeConfigs(configs, key) {
407
407
  return results;
408
408
  }
409
409
 
410
+ //#endregion
411
+ //#region src/utils/lightningcss.ts
412
+ /**
413
+ * Converts esbuild target [^1] (which is also used by Rolldown [^2]) to Lightning CSS targets [^3].
414
+ *
415
+ * [^1]: https://esbuild.github.io/api/#target
416
+ * [^2]: https://github.com/rolldown/rolldown/blob/v1.0.0-beta.8/packages/rolldown/src/binding.d.ts#L1429-L1431
417
+ * [^3]: https://lightningcss.dev/transpilation.html
418
+ */
419
+ function esbuildTargetToLightningCSS(target) {
420
+ let targets;
421
+ const matches = [...target.join(" ").toLowerCase().matchAll(TARGET_REGEX)];
422
+ for (const match of matches) {
423
+ const browser = ESBUILD_LIGHTNINGCSS_MAPPING[match[1]];
424
+ if (!browser) continue;
425
+ const version$1 = match[2];
426
+ const versionInt = parseVersion(version$1);
427
+ if (versionInt == null) continue;
428
+ targets = targets || {};
429
+ targets[browser] = versionInt;
430
+ }
431
+ return targets;
432
+ }
433
+ const TARGET_REGEX = /([a-z]+)(\d+(?:\.\d+)*)/g;
434
+ const ESBUILD_LIGHTNINGCSS_MAPPING = {
435
+ chrome: "chrome",
436
+ edge: "edge",
437
+ firefox: "firefox",
438
+ ie: "ie",
439
+ ios: "ios_saf",
440
+ opera: "opera",
441
+ safari: "safari"
442
+ };
443
+ function parseVersion(version$1) {
444
+ const [major, minor = 0, patch = 0] = version$1.split("-")[0].split(".").map((v) => Number.parseInt(v, 10));
445
+ if (Number.isNaN(major) || Number.isNaN(minor) || Number.isNaN(patch)) return null;
446
+ return major << 16 | minor << 8 | patch;
447
+ }
448
+
449
+ //#endregion
450
+ //#region src/features/css/lightningcss.ts
451
+ async function LightningCSSPlugin(options) {
452
+ const LightningCSS = await import("unplugin-lightningcss/rolldown").catch(() => void 0);
453
+ if (!LightningCSS) return;
454
+ const targets = options.target && esbuildTargetToLightningCSS(options.target);
455
+ if (!targets) return;
456
+ return LightningCSS.default({ options: { targets } });
457
+ }
458
+
459
+ //#endregion
460
+ //#region src/features/css/splitting.ts
461
+ /**
462
+ * CSS Code Split Plugin
463
+ *
464
+ * When css.splitting is false, this plugin merges all CSS files into a single file.
465
+ * When css.splitting is true (default), CSS code splitting is preserved.
466
+ * Based on Vite's implementation.
467
+ */
468
+ function CssCodeSplitPlugin(config) {
469
+ const { splitting, fileName } = config.css;
470
+ if (splitting) return;
471
+ return {
472
+ name: "tsdown:css:splitting",
473
+ generateBundle(_outputOptions, bundle) {
474
+ const chunks = Object.values(bundle);
475
+ const cssAssets = /* @__PURE__ */ new Map();
476
+ for (const asset of chunks) if (asset.type === "asset" && typeof asset.source === "string" && RE_CSS.test(fileName)) cssAssets.set(asset.fileName, asset.source);
477
+ if (!cssAssets.size) return;
478
+ const chunkCSSMap = /* @__PURE__ */ new Map();
479
+ for (const chunk of chunks) {
480
+ if (chunk.type !== "chunk") continue;
481
+ for (const moduleId of chunk.moduleIds) if (RE_CSS.test(moduleId)) {
482
+ if (!chunkCSSMap.has(chunk.fileName)) chunkCSSMap.set(chunk.fileName, []);
483
+ break;
484
+ }
485
+ }
486
+ for (const cssFileName of cssAssets.keys()) {
487
+ const cssBaseName = normalizeCssFileName(cssFileName);
488
+ for (const chunkFileName of chunkCSSMap.keys()) if (normalizeChunkFileName(chunkFileName) === cssBaseName || chunkFileName.startsWith(`${cssBaseName}-`)) {
489
+ chunkCSSMap.get(chunkFileName).push(cssFileName);
490
+ break;
491
+ }
492
+ }
493
+ let extractedCss = "";
494
+ const collected = /* @__PURE__ */ new Set();
495
+ const dynamicImports = /* @__PURE__ */ new Set();
496
+ function collect(chunk) {
497
+ if (!chunk || chunk.type !== "chunk" || collected.has(chunk)) return;
498
+ collected.add(chunk);
499
+ chunk.imports.forEach((importName) => {
500
+ collect(bundle[importName]);
501
+ });
502
+ chunk.dynamicImports.forEach((importName) => {
503
+ dynamicImports.add(importName);
504
+ });
505
+ const files = chunkCSSMap.get(chunk.fileName);
506
+ if (files && files.length > 0) for (const filename of files) extractedCss += cssAssets.get(filename) ?? "";
507
+ }
508
+ for (const chunk of chunks) if (chunk.type === "chunk" && chunk.isEntry) collect(chunk);
509
+ for (const chunkName of dynamicImports) collect(bundle[chunkName]);
510
+ if (extractedCss) {
511
+ for (const fileName$1 of cssAssets.keys()) delete bundle[fileName$1];
512
+ this.emitFile({
513
+ type: "asset",
514
+ source: extractedCss,
515
+ fileName,
516
+ originalFileName: defaultCssBundleName
517
+ });
518
+ }
519
+ }
520
+ };
521
+ }
522
+ const RE_CSS_HASH = /-[\w-]+\.css$/;
523
+ const RE_CHUNK_HASH = /-[\w-]+\.(m?js|cjs)$/;
524
+ const RE_CHUNK_EXT = /\.(m?js|cjs)$/;
525
+ /**
526
+ * Normalize CSS file name by removing hash pattern and extension.
527
+ * e.g., "async-DcjEOEdU.css" -> "async"
528
+ */
529
+ function normalizeCssFileName(cssFileName) {
530
+ return cssFileName.replace(RE_CSS_HASH, "").replace(RE_CSS, "");
531
+ }
532
+ /**
533
+ * Normalize chunk file name by removing hash pattern and extension.
534
+ * e.g., "async-CvIfFAic.mjs" -> "async"
535
+ */
536
+ function normalizeChunkFileName(chunkFileName) {
537
+ return chunkFileName.replace(RE_CHUNK_HASH, "").replace(RE_CHUNK_EXT, "");
538
+ }
539
+
540
+ //#endregion
541
+ //#region src/index.ts
542
+ const dirname = path.dirname(fileURLToPath(import.meta.url));
543
+ const pkgRoot = path.resolve(dirname, "..");
544
+ /** @internal */
545
+ const shimFile = path.resolve(pkgRoot, "esm-shims.js");
546
+
410
547
  //#endregion
411
548
  //#region src/features/external.ts
412
549
  const debug$2 = createDebug("tsdown:external");
@@ -449,7 +586,7 @@ Imported by ${underline(importer)}`);
449
586
  const resolved = await context.resolve(id, importer, extraOptions);
450
587
  if (resolved && (resolved.external || RE_NODE_MODULES.test(resolved.id))) return true;
451
588
  }
452
- if (deps && deps.some((dep) => id === dep || id.startsWith(`${dep}/`))) return true;
589
+ if (deps && (deps.includes(id) || deps.some((dep) => id.startsWith(`${dep}/`)))) return true;
453
590
  return false;
454
591
  }
455
592
  }
@@ -457,83 +594,26 @@ function getProductionDeps(pkg) {
457
594
  return new Set([...Object.keys(pkg.dependencies || {}), ...Object.keys(pkg.peerDependencies || {})]);
458
595
  }
459
596
 
460
- //#endregion
461
- //#region src/utils/lightningcss.ts
462
- /**
463
- * Converts esbuild target [^1] (which is also used by Rolldown [^2]) to Lightning CSS targets [^3].
464
- *
465
- * [^1]: https://esbuild.github.io/api/#target
466
- * [^2]: https://github.com/rolldown/rolldown/blob/v1.0.0-beta.8/packages/rolldown/src/binding.d.ts#L1429-L1431
467
- * [^3]: https://lightningcss.dev/transpilation.html
468
- */
469
- function esbuildTargetToLightningCSS(target) {
470
- let targets;
471
- const matches = [...target.join(" ").toLowerCase().matchAll(TARGET_REGEX)];
472
- for (const match of matches) {
473
- const browser = ESBUILD_LIGHTNINGCSS_MAPPING[match[1]];
474
- if (!browser) continue;
475
- const version$1 = match[2];
476
- const versionInt = parseVersion(version$1);
477
- if (versionInt == null) continue;
478
- targets = targets || {};
479
- targets[browser] = versionInt;
480
- }
481
- return targets;
482
- }
483
- const TARGET_REGEX = /([a-z]+)(\d+(?:\.\d+)*)/g;
484
- const ESBUILD_LIGHTNINGCSS_MAPPING = {
485
- chrome: "chrome",
486
- edge: "edge",
487
- firefox: "firefox",
488
- ie: "ie",
489
- ios: "ios_saf",
490
- opera: "opera",
491
- safari: "safari"
492
- };
493
- function parseVersion(version$1) {
494
- const [major, minor = 0, patch = 0] = version$1.split("-")[0].split(".").map((v) => Number.parseInt(v, 10));
495
- if (Number.isNaN(major) || Number.isNaN(minor) || Number.isNaN(patch)) return null;
496
- return major << 16 | minor << 8 | patch;
497
- }
498
-
499
- //#endregion
500
- //#region src/features/lightningcss.ts
501
- async function LightningCSSPlugin(options) {
502
- const LightningCSS = await import("unplugin-lightningcss/rolldown").catch(() => void 0);
503
- if (!LightningCSS) return;
504
- const targets = options.target && esbuildTargetToLightningCSS(options.target);
505
- if (!targets) return;
506
- return LightningCSS.default({ options: { targets } });
507
- }
508
-
509
597
  //#endregion
510
598
  //#region src/features/node-protocol.ts
511
- const modulesWithoutProtocol = builtinModules.filter((mod) => !mod.startsWith("node:"));
512
599
  /**
513
600
  * The `node:` protocol was added in Node.js v14.18.0.
514
601
  * @see https://nodejs.org/api/esm.html#node-imports
515
602
  */
516
603
  function NodeProtocolPlugin(nodeProtocolOption) {
517
- if (nodeProtocolOption === "strip") return {
518
- name: "tsdown:node-protocol:strip",
604
+ const modulesWithoutProtocol = builtinModules.filter((mod) => !mod.startsWith("node:"));
605
+ return {
606
+ name: `tsdown:node-protocol`,
519
607
  resolveId: {
520
608
  order: "pre",
521
- filter: { id: /* @__PURE__ */ new RegExp(`^node:(${modulesWithoutProtocol.join("|")})$`) },
522
- handler(id) {
609
+ filter: { id: nodeProtocolOption === "strip" ? /* @__PURE__ */ new RegExp(`^node:(${modulesWithoutProtocol.join("|")})$`) : /* @__PURE__ */ new RegExp(`^(${modulesWithoutProtocol.join("|")})$`) },
610
+ handler: nodeProtocolOption === "strip" ? (id) => {
523
611
  return {
524
612
  id: id.slice(5),
525
613
  external: true,
526
614
  moduleSideEffects: false
527
615
  };
528
- }
529
- }
530
- };
531
- return {
532
- name: "tsdown:node-protocol:add",
533
- resolveId: {
534
- order: "pre",
535
- filter: { id: /* @__PURE__ */ new RegExp(`^(${modulesWithoutProtocol.join("|")})$`) },
536
- handler(id) {
616
+ } : (id) => {
537
617
  return {
538
618
  id: `node:${id}`,
539
619
  external: true,
@@ -841,12 +921,12 @@ async function resolveOutputOptions(inputOptions, config, format, cjsDts) {
841
921
  }
842
922
  async function getDebugRolldownDir() {
843
923
  if (!debug.enabled) return;
844
- return await mkdtemp(join(tmpdir(), "tsdown-config-"));
924
+ return await mkdtemp(path.join(tmpdir(), "tsdown-config-"));
845
925
  }
846
926
  async function debugBuildOptions(dir, name, format, buildOptions) {
847
- const outFile = join(dir, `rolldown.config.${format}.js`);
927
+ const outFile = path.join(dir, `rolldown.config.${format}.js`);
848
928
  handlePluginInspect(buildOptions.plugins);
849
- const serialized = util.formatWithOptions({
929
+ const serialized = formatWithOptions({
850
930
  depth: null,
851
931
  maxArrayLength: null,
852
932
  maxStringLength: null
@@ -863,8 +943,8 @@ export default ${serialized}\n`);
863
943
  }
864
944
  function handlePluginInspect(plugins) {
865
945
  if (Array.isArray(plugins)) for (const plugin of plugins) handlePluginInspect(plugin);
866
- else if (typeof plugins === "object" && plugins !== null && "name" in plugins) plugins[util.inspect.custom] = function(depth, options, inspect) {
867
- if ("_options" in plugins) return inspect({
946
+ else if (typeof plugins === "object" && plugins !== null && "name" in plugins) plugins[inspect.custom] = function(depth, options, inspect$1) {
947
+ if ("_options" in plugins) return inspect$1({
868
948
  name: plugins.name,
869
949
  options: plugins._options
870
950
  }, options);
@@ -925,14 +1005,24 @@ function shortcuts(restart) {
925
1005
  }
926
1006
 
927
1007
  //#endregion
928
- //#region src/index.ts
1008
+ //#region src/build.ts
929
1009
  const asyncDispose = Symbol.asyncDispose || Symbol.for("Symbol.asyncDispose");
930
1010
  /**
931
1011
  * Build with tsdown.
932
1012
  */
933
1013
  async function build$1(userOptions = {}) {
934
- globalLogger.level = userOptions.logLevel || (userOptions.silent ? "error" : "info");
1014
+ globalLogger.level = userOptions.logLevel || "info";
935
1015
  const { configs, files: configFiles } = await resolveConfig(userOptions);
1016
+ return buildWithConfigs(configs, configFiles);
1017
+ }
1018
+ /**
1019
+ * Build with `ResolvedConfigs`.
1020
+ *
1021
+ * Internal API, not for public use
1022
+ *
1023
+ * @private
1024
+ */
1025
+ async function buildWithConfigs(configs, configFiles) {
936
1026
  let cleanPromise;
937
1027
  const clean = () => {
938
1028
  if (cleanPromise) return cleanPromise;
@@ -945,7 +1035,7 @@ async function build$1(userOptions = {}) {
945
1035
  restarting = true;
946
1036
  await Promise.all(disposeCbs.map((cb) => cb()));
947
1037
  clearRequireCache();
948
- build$1(userOptions);
1038
+ buildWithConfigs(configs, configFiles);
949
1039
  }
950
1040
  const configChunksByPkg = initBundleByPkg(configs);
951
1041
  function done(bundle) {
@@ -964,10 +1054,6 @@ async function build$1(userOptions = {}) {
964
1054
  }
965
1055
  /**
966
1056
  * Build a single configuration, without watch and shortcuts features.
967
- *
968
- * Internal API, not for public use
969
- *
970
- * @internal
971
1057
  * @param config Resolved options
972
1058
  */
973
1059
  async function buildSingle(config, configFiles, isDualFormat, clean, restart, done) {
@@ -1025,7 +1111,7 @@ async function buildSingle(config, configFiles, isDualFormat, clean, restart, do
1025
1111
  break;
1026
1112
  case "BUNDLE_START":
1027
1113
  if (changedFile.length > 0) {
1028
- console.info("");
1114
+ if (logger.level === "info") console.info("");
1029
1115
  logger.info(`Found ${bold(changedFile.join(", "))} changed, rebuilding...`);
1030
1116
  }
1031
1117
  changedFile.length = 0;
@@ -1065,10 +1151,6 @@ async function buildSingle(config, configFiles, isDualFormat, clean, restart, do
1065
1151
  ab = executeOnSuccess(config);
1066
1152
  }
1067
1153
  }
1068
- const dirname$1 = path.dirname(fileURLToPath(import.meta.url));
1069
- const pkgRoot = path.resolve(dirname$1, "..");
1070
- /** @internal */
1071
- const shimFile = path.resolve(pkgRoot, "esm-shims.js");
1072
1154
 
1073
1155
  //#endregion
1074
- export { WatchPlugin as a, NodeProtocolPlugin as c, shimFile as i, ExternalPlugin as l, build$1 as n, ShebangPlugin as o, buildSingle as r, ReportPlugin as s, Rolldown as t };
1156
+ export { ReportPlugin as a, Rolldown as c, ShebangPlugin as i, shimFile as l, buildWithConfigs as n, NodeProtocolPlugin as o, WatchPlugin as r, ExternalPlugin as s, build$1 as t };
@@ -0,0 +1,18 @@
1
+ import { i as InlineConfig, s as ResolvedConfig, w as TsdownBundle } from "./types-Dxm9xngg.mjs";
2
+
3
+ //#region src/build.d.ts
4
+
5
+ /**
6
+ * Build with tsdown.
7
+ */
8
+ declare function build(userOptions?: InlineConfig): Promise<TsdownBundle[]>;
9
+ /**
10
+ * Build with `ResolvedConfigs`.
11
+ *
12
+ * Internal API, not for public use
13
+ *
14
+ * @private
15
+ */
16
+ declare function buildWithConfigs(configs: ResolvedConfig[], configFiles: string[]): Promise<TsdownBundle[]>;
17
+ //#endregion
18
+ export { build, buildWithConfigs };
package/dist/build.mjs ADDED
@@ -0,0 +1,3 @@
1
+ import { n as buildWithConfigs, t as build } from "./build-CczdykTO.mjs";
2
+
3
+ export { build, buildWithConfigs };
@@ -1,4 +1,4 @@
1
- import { f as UserConfig, i as InlineConfig, m as UserConfigFn, p as UserConfigExport } from "./index-CMl71wtM.mjs";
1
+ import { f as UserConfig, i as InlineConfig, m as UserConfigFn, p as UserConfigExport } from "./types-Dxm9xngg.mjs";
2
2
 
3
3
  //#region src/config/options.d.ts
4
4
  declare function mergeConfig(defaults: UserConfig, overrides: UserConfig): UserConfig;
@@ -1,23 +1,23 @@
1
1
  import { createRequire as __cjs_createRequire } from "node:module";
2
2
  const __cjs_require = __cjs_createRequire(import.meta.url);
3
- import { a as globalLogger, c as matchPattern, f as resolveComma, h as toArray, i as getNameLabel, m as slash, n as createLogger, p as resolveRegex, r as generateColor, u as pkgExists } from "./logger-D_2uXZBG.mjs";
3
+ import { a as globalLogger, c as matchPattern, f as resolveComma, h as toArray, i as getNameLabel, m as slash, n as createLogger, p as resolveRegex, r as generateColor, u as pkgExists } from "./logger-C5G3WyAl.mjs";
4
+ import { blue, underline } from "ansis";
5
+ import { init, isSupported } from "import-without-cache";
6
+ import path from "node:path";
7
+ import { createDebug } from "obug";
4
8
  import { access, cp, readFile, rm, stat } from "node:fs/promises";
5
- import path, { dirname, extname, normalize, sep } from "node:path";
6
9
  import process, { env } from "node:process";
10
+ import { pathToFileURL } from "node:url";
11
+ import { createConfigCoreLoader } from "unconfig-core";
12
+ const picomatch = __cjs_require("picomatch");
7
13
  import { parseEnv } from "node:util";
8
- import { blue, underline } from "ansis";
9
14
  import { createDefu } from "defu";
10
- import { createDebug } from "obug";
11
15
  import { glob, isDynamicPattern } from "tinyglobby";
12
- import { pathToFileURL } from "node:url";
13
- const picomatch = __cjs_require("picomatch");
14
- import { RE_CSS, RE_DTS } from "rolldown-plugin-dts/filename";
15
16
  import { readFileSync, writeFileSync } from "node:fs";
17
+ import { RE_CSS, RE_DTS } from "rolldown-plugin-dts/filename";
16
18
  const minVersion = __cjs_require("semver/ranges/min-version.js");
17
19
  import { up } from "empathic/find";
18
20
  import { up as up$1 } from "empathic/package";
19
- import { init, isSupported } from "import-without-cache";
20
- import { createConfigCoreLoader } from "unconfig-core";
21
21
 
22
22
  //#region node_modules/.pnpm/is-in-ci@2.0.0/node_modules/is-in-ci/index.js
23
23
  const check = (key) => key in env && env[key] !== "0" && env[key] !== "false";
@@ -46,12 +46,12 @@ function fsCopy(from, to) {
46
46
  }
47
47
  function lowestCommonAncestor(...filepaths) {
48
48
  if (filepaths.length === 0) return "";
49
- if (filepaths.length === 1) return dirname(filepaths[0]);
50
- filepaths = filepaths.map(normalize);
49
+ if (filepaths.length === 1) return path.dirname(filepaths[0]);
50
+ filepaths = filepaths.map(path.normalize);
51
51
  const [first, ...rest] = filepaths;
52
- let ancestor = first.split(sep);
52
+ let ancestor = first.split(path.sep);
53
53
  for (const filepath of rest) {
54
- const directories = filepath.split(sep, ancestor.length);
54
+ const directories = filepath.split(path.sep, ancestor.length);
55
55
  let index = 0;
56
56
  for (const directory of directories) if (directory === ancestor[index]) index += 1;
57
57
  else {
@@ -60,17 +60,152 @@ function lowestCommonAncestor(...filepaths) {
60
60
  }
61
61
  ancestor = ancestor.slice(0, index);
62
62
  }
63
- return ancestor.length <= 1 && ancestor[0] === "" ? sep + ancestor[0] : ancestor.join(sep);
63
+ return ancestor.length <= 1 && ancestor[0] === "" ? path.sep + ancestor[0] : ancestor.join(path.sep);
64
64
  }
65
65
  function stripExtname(filePath) {
66
- const ext = extname(filePath);
66
+ const ext = path.extname(filePath);
67
67
  if (!ext.length) return filePath;
68
68
  return filePath.slice(0, -ext.length);
69
69
  }
70
70
 
71
+ //#endregion
72
+ //#region src/config/file.ts
73
+ const debug$3 = createDebug("tsdown:config:file");
74
+ async function loadViteConfig(prefix, cwd, configLoader) {
75
+ const loader = resolveConfigLoader(configLoader);
76
+ debug$3("Loading Vite config via loader: ", loader);
77
+ const parser = createParser(loader);
78
+ const [result] = await createConfigCoreLoader({
79
+ sources: [{
80
+ files: [`${prefix}.config`],
81
+ extensions: [
82
+ "js",
83
+ "mjs",
84
+ "ts",
85
+ "cjs",
86
+ "mts",
87
+ "mts"
88
+ ],
89
+ parser
90
+ }],
91
+ cwd
92
+ }).load(true);
93
+ if (!result) return;
94
+ const { config, source } = result;
95
+ globalLogger.info(`Using Vite config: ${underline(source)}`);
96
+ const resolved = await config;
97
+ if (typeof resolved === "function") return resolved({
98
+ command: "build",
99
+ mode: "production"
100
+ });
101
+ return resolved;
102
+ }
103
+ const configPrefix = "tsdown.config";
104
+ async function loadConfigFile(inlineConfig, workspace) {
105
+ let cwd = inlineConfig.cwd || process.cwd();
106
+ let overrideConfig = false;
107
+ let { config: filePath } = inlineConfig;
108
+ if (filePath === false) return { configs: [{}] };
109
+ if (typeof filePath === "string") {
110
+ const stats = await fsStat(filePath);
111
+ if (stats) {
112
+ const resolved = path.resolve(filePath);
113
+ if (stats.isFile()) {
114
+ overrideConfig = true;
115
+ filePath = resolved;
116
+ cwd = path.dirname(filePath);
117
+ } else if (stats.isDirectory()) cwd = resolved;
118
+ }
119
+ }
120
+ const loader = resolveConfigLoader(inlineConfig.configLoader);
121
+ debug$3("Using config loader:", loader);
122
+ const parser = createParser(loader);
123
+ const [result] = await createConfigCoreLoader({
124
+ sources: overrideConfig ? [{
125
+ files: [filePath],
126
+ extensions: [],
127
+ parser
128
+ }] : [{
129
+ files: [configPrefix],
130
+ extensions: [
131
+ "ts",
132
+ "mts",
133
+ "cts",
134
+ "js",
135
+ "mjs",
136
+ "cjs",
137
+ "json"
138
+ ],
139
+ parser
140
+ }, {
141
+ files: ["package.json"],
142
+ parser
143
+ }],
144
+ cwd,
145
+ stopAt: workspace && path.dirname(workspace)
146
+ }).load(true);
147
+ let exported = [];
148
+ let file;
149
+ if (result) {
150
+ ({config: exported, source: file} = result);
151
+ globalLogger.info(`config file: ${underline(file)}`, loader === "native" ? "" : `(${loader})`);
152
+ exported = await exported;
153
+ if (typeof exported === "function") exported = await exported(inlineConfig, { ci: is_in_ci_default });
154
+ }
155
+ exported = toArray(exported);
156
+ if (exported.length === 0) exported.push({});
157
+ 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(() => [...])");
158
+ return {
159
+ configs: exported.map((config) => ({
160
+ ...config,
161
+ cwd: config.cwd ? path.resolve(cwd, config.cwd) : cwd
162
+ })),
163
+ file
164
+ };
165
+ }
166
+ const isBun = !!process.versions.bun;
167
+ const nativeTS = process.features.typescript || process.versions.deno;
168
+ const autoLoader = isBun || nativeTS && isSupported ? "native" : "unrun";
169
+ function resolveConfigLoader(configLoader = "auto") {
170
+ if (configLoader === "auto") return autoLoader;
171
+ else return configLoader === "native" ? "native" : "unrun";
172
+ }
173
+ function createParser(loader) {
174
+ return async (filepath) => {
175
+ const basename = path.basename(filepath);
176
+ const isPkgJson = basename === "package.json";
177
+ if (basename === configPrefix || isPkgJson || basename.endsWith(".json")) {
178
+ const contents = await readFile(filepath, "utf8");
179
+ const parsed = JSON.parse(contents);
180
+ if (isPkgJson) return parsed?.tsdown;
181
+ return parsed;
182
+ }
183
+ if (loader === "native") return nativeImport(filepath);
184
+ return unrunImport(filepath);
185
+ };
186
+ }
187
+ async function nativeImport(id) {
188
+ const url = pathToFileURL(id);
189
+ const importAttributes = Object.create(null);
190
+ if (isSupported) {
191
+ importAttributes.cache = "no";
192
+ init({ skipNodeModules: true });
193
+ } else if (!isBun) url.searchParams.set("no-cache", crypto.randomUUID());
194
+ const mod = await import(url.href, { with: importAttributes }).catch((error) => {
195
+ 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 });
196
+ else throw error;
197
+ });
198
+ return mod.default || mod;
199
+ }
200
+ async function unrunImport(id) {
201
+ const { unrun } = await import("unrun");
202
+ const { module } = await unrun({ path: pathToFileURL(id).href });
203
+ return module;
204
+ }
205
+
71
206
  //#endregion
72
207
  //#region src/features/clean.ts
73
- const debug$3 = createDebug("tsdown:clean");
208
+ const debug$2 = createDebug("tsdown:clean");
74
209
  const RE_LAST_SLASH = /[/\\]$/;
75
210
  async function cleanOutDir(configs) {
76
211
  const removes = /* @__PURE__ */ new Set();
@@ -89,10 +224,10 @@ async function cleanOutDir(configs) {
89
224
  if (!removes.size) return;
90
225
  globalLogger.info(`Cleaning ${removes.size} files`);
91
226
  await Promise.all([...removes].map(async (file) => {
92
- debug$3("Removing", file);
227
+ debug$2("Removing", file);
93
228
  await fsRemove(file);
94
229
  }));
95
- debug$3("Removed %d files", removes.size);
230
+ debug$2("Removed %d files", removes.size);
96
231
  }
97
232
  function resolveClean(clean, outDir, cwd) {
98
233
  if (clean === true) clean = [slash(outDir)];
@@ -103,13 +238,13 @@ function resolveClean(clean, outDir, cwd) {
103
238
  async function cleanChunks(outDir, chunks) {
104
239
  await Promise.all(chunks.map(async (chunk) => {
105
240
  const filePath = path.resolve(outDir, chunk.fileName);
106
- debug$3("Removing chunk file", filePath);
241
+ debug$2("Removing chunk file", filePath);
107
242
  await fsRemove(filePath);
108
243
  }));
109
244
  }
110
245
 
111
246
  //#endregion
112
- //#region src/features/css.ts
247
+ //#region src/features/css/index.ts
113
248
  const defaultCssBundleName = "style.css";
114
249
  function resolveCssOptions(options = {}) {
115
250
  return {
@@ -117,91 +252,6 @@ function resolveCssOptions(options = {}) {
117
252
  fileName: options.fileName ?? defaultCssBundleName
118
253
  };
119
254
  }
120
- const RE_CSS_HASH = /-[\w-]+\.css$/;
121
- const RE_CHUNK_HASH = /-[\w-]+\.(m?js|cjs)$/;
122
- const RE_CHUNK_EXT = /\.(m?js|cjs)$/;
123
- /**
124
- * Normalize CSS file name by removing hash pattern and extension.
125
- * e.g., "async-DcjEOEdU.css" -> "async"
126
- */
127
- function normalizeCssFileName(cssFileName) {
128
- return cssFileName.replace(RE_CSS_HASH, "").replace(RE_CSS, "");
129
- }
130
- /**
131
- * Normalize chunk file name by removing hash pattern and extension.
132
- * e.g., "async-CvIfFAic.mjs" -> "async"
133
- */
134
- function normalizeChunkFileName(chunkFileName) {
135
- return chunkFileName.replace(RE_CHUNK_HASH, "").replace(RE_CHUNK_EXT, "");
136
- }
137
- /**
138
- * CSS Code Split Plugin
139
- *
140
- * When css.splitting is false, this plugin merges all CSS files into a single file.
141
- * When css.splitting is true (default), CSS code splitting is preserved.
142
- * Based on Vite's implementation.
143
- */
144
- function CssCodeSplitPlugin(config) {
145
- const { splitting, fileName } = config.css;
146
- if (splitting) return;
147
- let hasEmitted = false;
148
- return {
149
- name: "tsdown:css-code-split",
150
- renderStart() {
151
- hasEmitted = false;
152
- },
153
- generateBundle(_outputOptions, bundle) {
154
- if (hasEmitted) return;
155
- const cssAssets = /* @__PURE__ */ new Map();
156
- for (const [fileName$1, asset] of Object.entries(bundle)) if (asset.type === "asset" && RE_CSS.test(fileName$1)) {
157
- const source = typeof asset.source === "string" ? asset.source : new TextDecoder("utf-8").decode(asset.source);
158
- cssAssets.set(fileName$1, source);
159
- }
160
- if (!cssAssets.size) return;
161
- const chunkCSSMap = /* @__PURE__ */ new Map();
162
- for (const [chunkFileName, item] of Object.entries(bundle)) if (item.type === "chunk") {
163
- for (const moduleId of Object.keys(item.modules)) if (RE_CSS.test(moduleId)) {
164
- if (!chunkCSSMap.has(chunkFileName)) chunkCSSMap.set(chunkFileName, []);
165
- break;
166
- }
167
- }
168
- for (const [cssFileName] of cssAssets) {
169
- const cssBaseName = normalizeCssFileName(cssFileName);
170
- for (const [chunkFileName] of chunkCSSMap) if (normalizeChunkFileName(chunkFileName) === cssBaseName || chunkFileName.startsWith(`${cssBaseName}-`)) {
171
- chunkCSSMap.get(chunkFileName)?.push(cssFileName);
172
- break;
173
- }
174
- }
175
- let extractedCss = "";
176
- const collected = /* @__PURE__ */ new Set();
177
- const dynamicImports = /* @__PURE__ */ new Set();
178
- function collect(chunk) {
179
- if (!chunk || chunk.type !== "chunk" || collected.has(chunk)) return;
180
- collected.add(chunk);
181
- chunk.imports.forEach((importName) => {
182
- collect(bundle[importName]);
183
- });
184
- chunk.dynamicImports.forEach((importName) => {
185
- dynamicImports.add(importName);
186
- });
187
- const files = chunkCSSMap.get(chunk.fileName);
188
- if (files && files.length > 0) for (const filename of files) extractedCss += cssAssets.get(filename) ?? "";
189
- }
190
- for (const chunk of Object.values(bundle)) if (chunk.type === "chunk" && chunk.isEntry) collect(chunk);
191
- for (const chunkName of dynamicImports) collect(bundle[chunkName]);
192
- if (extractedCss) {
193
- hasEmitted = true;
194
- for (const fileName$1 of cssAssets.keys()) delete bundle[fileName$1];
195
- this.emitFile({
196
- type: "asset",
197
- source: extractedCss,
198
- fileName,
199
- originalFileName: defaultCssBundleName
200
- });
201
- }
202
- }
203
- };
204
- }
205
255
 
206
256
  //#endregion
207
257
  //#region src/features/entry.ts
@@ -314,7 +364,7 @@ async function generateExports(pkg, chunks, options) {
314
364
  for (const chunk of filteredChunks) {
315
365
  let [name, normalizedName, isDts] = getExportName(chunk);
316
366
  const isIndex = onlyOneEntry || name === "index";
317
- const distFile = join$1(pkgRoot, chunk.outDir, normalizedName);
367
+ const distFile = join(pkgRoot, chunk.outDir, normalizedName);
318
368
  if (isIndex) {
319
369
  name = ".";
320
370
  if (format === "cjs") if (isDts) cjsTypes = distFile;
@@ -386,7 +436,7 @@ function exportCss(exports, chunks, { splitting }, pkgRoot) {
386
436
  if (splitting) return;
387
437
  for (const chunksByFormat of Object.values(chunks)) for (const chunk of chunksByFormat) if (chunk.type === "asset" && RE_CSS.test(chunk.fileName)) {
388
438
  const filename = slash(chunk.fileName);
389
- exports[`./${filename}`] = join$1(pkgRoot, chunk.outDir, filename);
439
+ exports[`./${filename}`] = join(pkgRoot, chunk.outDir, filename);
390
440
  return;
391
441
  }
392
442
  }
@@ -413,7 +463,7 @@ function getExportName(chunk) {
413
463
  isDts
414
464
  ];
415
465
  }
416
- function join$1(pkgRoot, outDir, fileName) {
466
+ function join(pkgRoot, outDir, fileName) {
417
467
  const outDirRelative = slash(path.relative(pkgRoot, outDir));
418
468
  return `${outDirRelative ? `./${outDirRelative}` : "."}/${fileName}`;
419
469
  }
@@ -471,11 +521,11 @@ async function resolveTsconfig(logger, tsconfig, cwd, color, nameLabel) {
471
521
 
472
522
  //#endregion
473
523
  //#region src/utils/package.ts
474
- const debug$2 = createDebug("tsdown:package");
524
+ const debug$1 = createDebug("tsdown:package");
475
525
  async function readPackageJson(dir) {
476
526
  const packageJsonPath = up$1({ cwd: dir });
477
527
  if (!packageJsonPath) return;
478
- debug$2("Reading package.json:", packageJsonPath);
528
+ debug$1("Reading package.json:", packageJsonPath);
479
529
  const contents = await readFile(packageJsonPath, "utf8");
480
530
  return {
481
531
  ...JSON.parse(contents),
@@ -499,146 +549,11 @@ function normalizeFormat(format) {
499
549
  }
500
550
  }
501
551
 
502
- //#endregion
503
- //#region src/config/file.ts
504
- const debug$1 = createDebug("tsdown:config:file");
505
- async function loadViteConfig(prefix, cwd, configLoader) {
506
- const loader = resolveConfigLoader(configLoader);
507
- debug$1("Loading Vite config via loader: ", loader);
508
- const parser = createParser(loader);
509
- const [result] = await createConfigCoreLoader({
510
- sources: [{
511
- files: [`${prefix}.config`],
512
- extensions: [
513
- "js",
514
- "mjs",
515
- "ts",
516
- "cjs",
517
- "mts",
518
- "mts"
519
- ],
520
- parser
521
- }],
522
- cwd
523
- }).load(true);
524
- if (!result) return;
525
- const { config, source } = result;
526
- globalLogger.info(`Using Vite config: ${underline(source)}`);
527
- const resolved = await config;
528
- if (typeof resolved === "function") return resolved({
529
- command: "build",
530
- mode: "production"
531
- });
532
- return resolved;
533
- }
534
- const configPrefix = "tsdown.config";
535
- async function loadConfigFile(inlineConfig, workspace) {
536
- let cwd = inlineConfig.cwd || process.cwd();
537
- let overrideConfig = false;
538
- let { config: filePath } = inlineConfig;
539
- if (filePath === false) return { configs: [{}] };
540
- if (typeof filePath === "string") {
541
- const stats = await fsStat(filePath);
542
- if (stats) {
543
- const resolved = path.resolve(filePath);
544
- if (stats.isFile()) {
545
- overrideConfig = true;
546
- filePath = resolved;
547
- cwd = path.dirname(filePath);
548
- } else if (stats.isDirectory()) cwd = resolved;
549
- }
550
- }
551
- const loader = resolveConfigLoader(inlineConfig.configLoader);
552
- debug$1("Using config loader:", loader);
553
- const parser = createParser(loader);
554
- const [result] = await createConfigCoreLoader({
555
- sources: overrideConfig ? [{
556
- files: [filePath],
557
- extensions: [],
558
- parser
559
- }] : [{
560
- files: [configPrefix],
561
- extensions: [
562
- "ts",
563
- "mts",
564
- "cts",
565
- "js",
566
- "mjs",
567
- "cjs",
568
- "json"
569
- ],
570
- parser
571
- }, {
572
- files: ["package.json"],
573
- parser
574
- }],
575
- cwd,
576
- stopAt: workspace && path.dirname(workspace)
577
- }).load(true);
578
- let exported = [];
579
- let file;
580
- if (result) {
581
- ({config: exported, source: file} = result);
582
- globalLogger.info(`config file: ${underline(file)}`, loader === "native" ? "" : `(${loader})`);
583
- exported = await exported;
584
- if (typeof exported === "function") exported = await exported(inlineConfig, { ci: is_in_ci_default });
585
- }
586
- exported = toArray(exported);
587
- if (exported.length === 0) exported.push({});
588
- 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(() => [...])");
589
- return {
590
- configs: exported.map((config) => ({
591
- ...config,
592
- cwd: config.cwd ? path.resolve(cwd, config.cwd) : cwd
593
- })),
594
- file
595
- };
596
- }
597
- const isBun = !!process.versions.bun;
598
- const nativeTS = process.features.typescript || process.versions.deno;
599
- const autoLoader = isBun || nativeTS && isSupported ? "native" : "unrun";
600
- function resolveConfigLoader(configLoader = "auto") {
601
- if (configLoader === "auto") return autoLoader;
602
- else return configLoader === "native" ? "native" : "unrun";
603
- }
604
- function createParser(loader) {
605
- return async (filepath) => {
606
- const basename = path.basename(filepath);
607
- const isPkgJson = basename === "package.json";
608
- if (basename === configPrefix || isPkgJson || basename.endsWith(".json")) {
609
- const contents = await readFile(filepath, "utf8");
610
- const parsed = JSON.parse(contents);
611
- if (isPkgJson) return parsed?.tsdown;
612
- return parsed;
613
- }
614
- if (loader === "native") return nativeImport(filepath);
615
- return unrunImport(filepath);
616
- };
617
- }
618
- async function nativeImport(id) {
619
- const url = pathToFileURL(id);
620
- const importAttributes = Object.create(null);
621
- if (isSupported) {
622
- importAttributes.cache = "no";
623
- init({ skipNodeModules: true });
624
- } else if (!isBun) url.searchParams.set("no-cache", crypto.randomUUID());
625
- const mod = await import(url.href, { with: importAttributes }).catch((error) => {
626
- 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 });
627
- else throw error;
628
- });
629
- return mod.default || mod;
630
- }
631
- async function unrunImport(id) {
632
- const { unrun } = await import("unrun");
633
- const { module } = await unrun({ path: pathToFileURL(id).href });
634
- return module;
635
- }
636
-
637
552
  //#endregion
638
553
  //#region src/config/options.ts
639
554
  const debug = createDebug("tsdown:config:options");
640
555
  async function resolveUserConfig(userConfig, inlineConfig) {
641
- 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 = false, ignoreWatch, shims = false, skipNodeModulesBundle = false, publint = false, attw = false, fromVite, alias, tsconfig, report = true, target, env: env$1 = {}, envFile, envPrefix = "TSDOWN_", copy, 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, css, fixedExtension = platform === "node", devtools = false, write = true } = userConfig;
556
+ let { entry, format = ["es"], plugins = [], clean = true, logLevel = "info", failOnWarn = "ci-only", customLogger, treeshake = true, platform = "node", outDir = "dist", sourcemap = false, dts, unused = false, watch = false, ignoreWatch, shims = false, skipNodeModulesBundle = false, publint = false, attw = false, fromVite, alias, tsconfig, report = true, target, env: env$1 = {}, envFile, envPrefix = "TSDOWN_", copy, 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, css, fixedExtension = platform === "node", devtools = false, write = true } = userConfig;
642
557
  const pkg = await readPackageJson(cwd);
643
558
  if (workspace) name ||= pkg?.name;
644
559
  const color = generateColor(name);
@@ -779,7 +694,7 @@ async function resolveUserConfig(userConfig, inlineConfig) {
779
694
  /** filter env variables by prefixes */
780
695
  function filterEnv(envDict, envPrefixes) {
781
696
  const env$1 = {};
782
- for (const [key, value] of Object.entries(envDict)) if (envPrefixes.some((prefix) => key.startsWith(prefix)) && value !== void 0) env$1[key] = value;
697
+ for (const [key, value] of Object.entries(envDict)) if (value != null && envPrefixes.some((prefix) => key.startsWith(prefix))) env$1[key] = value;
783
698
  return env$1;
784
699
  }
785
700
  const defu = createDefu((obj, key, value) => {
@@ -820,4 +735,4 @@ function defineConfig(options) {
820
735
  }
821
736
 
822
737
  //#endregion
823
- export { loadConfigFile as a, formatBytes as c, cleanOutDir as d, fsCopy as f, lowestCommonAncestor as h, resolveUserConfig as i, CssCodeSplitPlugin as l, fsRemove as m, mergeConfig as n, getPackageType as o, fsExists as p, mergeUserOptions as r, writeExports as s, defineConfig as t, cleanChunks as u };
738
+ export { getPackageType as a, defaultCssBundleName as c, loadConfigFile as d, fsCopy as f, lowestCommonAncestor as h, resolveUserConfig as i, cleanChunks as l, fsRemove as m, mergeConfig as n, writeExports as o, fsExists as p, mergeUserOptions as r, formatBytes as s, defineConfig as t, cleanOutDir as u };
package/dist/config.d.mts CHANGED
@@ -1,3 +1,3 @@
1
- import { f as UserConfig, m as UserConfigFn, p as UserConfigExport } from "./index-CMl71wtM.mjs";
2
- import { n as mergeConfig, t as defineConfig } from "./config-C2C2OcsY.mjs";
1
+ import { f as UserConfig, m as UserConfigFn, p as UserConfigExport } from "./types-Dxm9xngg.mjs";
2
+ import { n as mergeConfig, t as defineConfig } from "./config-Cj-nN1Zu.mjs";
3
3
  export { UserConfig, UserConfigExport, UserConfigFn, defineConfig, mergeConfig };
package/dist/config.mjs CHANGED
@@ -1,4 +1,3 @@
1
- import "./logger-D_2uXZBG.mjs";
2
- import { n as mergeConfig, t as defineConfig } from "./config-CQ0WjrHu.mjs";
1
+ import { n as mergeConfig, t as defineConfig } from "./config-DCPo70ac.mjs";
3
2
 
4
3
  export { defineConfig, mergeConfig };
@@ -0,0 +1,22 @@
1
+ import { f as resolveComma, h as toArray } from "./logger-C5G3WyAl.mjs";
2
+ import { createDebug, enable, namespaces } from "obug";
3
+
4
+ //#region package.json
5
+ var version = "0.19.0-beta.4";
6
+
7
+ //#endregion
8
+ //#region src/features/debug.ts
9
+ const debugLog = createDebug("tsdown:debug");
10
+ function enableDebug(debug) {
11
+ if (!debug) return;
12
+ let namespace;
13
+ if (debug === true) namespace = "tsdown:*";
14
+ else namespace = resolveComma(toArray(debug)).map((v) => `tsdown:${v}`).join(",");
15
+ const ns = namespaces();
16
+ if (ns) namespace += `,${ns}`;
17
+ enable(namespace);
18
+ debugLog("Debugging enabled", namespace);
19
+ }
20
+
21
+ //#endregion
22
+ export { version as n, enableDebug as t };
package/dist/index.d.mts CHANGED
@@ -1,11 +1,9 @@
1
- import { A as OutExtensionFactory, B as CopyOptions, C as RolldownChunk, D as ChunkAddonFunction, E as ChunkAddon, F as RolldownContext, I as TsdownHooks, L as DevtoolsOptions, M as PackageJsonWithPath, N as PackageType, O as ChunkAddonObject, P as BuildContext, R as CssOptions, S as ExportsOptions, T as AttwOptions, V as CopyOptionsFn, _ as ReportOptions, a as NoExternalFn, b as globalLogger, c as Sourcemap, d as UnusedOptions, f as UserConfig, g as Workspace, h as WithEnabled, i as InlineConfig, j as OutExtensionObject, k as OutExtensionContext, l as TreeshakingOptions, m as UserConfigFn, n as DtsOptions, o as NormalizedFormat, p as UserConfigExport, r as Format, s as ResolvedConfig, t as CIOption, u as TsdownInputOption, w as TsdownBundle, x as PublintOptions, y as Logger, z as CopyEntry } from "./index-CMl71wtM.mjs";
2
- import { n as mergeConfig, t as defineConfig } from "./config-C2C2OcsY.mjs";
1
+ import { A as OutExtensionFactory, B as CopyOptions, C as RolldownChunk, D as ChunkAddonFunction, E as ChunkAddon, F as RolldownContext, H as Arrayable, I as TsdownHooks, L as DevtoolsOptions, M as PackageJsonWithPath, N as PackageType, O as ChunkAddonObject, P as BuildContext, R as CssOptions, S as ExportsOptions, T as AttwOptions, V as CopyOptionsFn, _ as ReportOptions, a as NoExternalFn, b as globalLogger, c as Sourcemap, d as UnusedOptions, f as UserConfig, g as Workspace, h as WithEnabled, i as InlineConfig, j as OutExtensionObject, k as OutExtensionContext, l as TreeshakingOptions, m as UserConfigFn, n as DtsOptions, o as NormalizedFormat, p as UserConfigExport, r as Format, s as ResolvedConfig, t as CIOption, u as TsdownInputOption, w as TsdownBundle, x as PublintOptions, y as Logger, z as CopyEntry } from "./types-Dxm9xngg.mjs";
2
+ import { build, buildWithConfigs } from "./build.mjs";
3
+ import { n as mergeConfig, t as defineConfig } from "./config-Cj-nN1Zu.mjs";
3
4
  import * as Rolldown from "rolldown";
4
5
 
5
- //#region src/index.d.ts
6
- /**
7
- * Build with tsdown.
8
- */
9
- declare function build(userOptions?: InlineConfig): Promise<TsdownBundle[]>;
6
+ //#region src/features/debug.d.ts
7
+ declare function enableDebug(debug?: boolean | Arrayable<string>): void;
10
8
  //#endregion
11
- export { AttwOptions, BuildContext, CIOption, ChunkAddon, ChunkAddonFunction, ChunkAddonObject, CopyEntry, CopyOptions, CopyOptionsFn, CssOptions, DevtoolsOptions, DtsOptions, ExportsOptions, Format, InlineConfig, type Logger, NoExternalFn, NormalizedFormat, OutExtensionContext, OutExtensionFactory, OutExtensionObject, PackageJsonWithPath, PackageType, PublintOptions, ReportOptions, ResolvedConfig, Rolldown, RolldownChunk, RolldownContext, Sourcemap, TreeshakingOptions, TsdownBundle, TsdownHooks, TsdownInputOption, UnusedOptions, UserConfig, UserConfigExport, UserConfigFn, WithEnabled, Workspace, build, defineConfig, globalLogger, mergeConfig };
9
+ export { AttwOptions, BuildContext, CIOption, ChunkAddon, ChunkAddonFunction, ChunkAddonObject, CopyEntry, CopyOptions, CopyOptionsFn, CssOptions, DevtoolsOptions, DtsOptions, ExportsOptions, Format, InlineConfig, type Logger, NoExternalFn, NormalizedFormat, OutExtensionContext, OutExtensionFactory, OutExtensionObject, PackageJsonWithPath, PackageType, PublintOptions, ReportOptions, ResolvedConfig, Rolldown, RolldownChunk, RolldownContext, Sourcemap, TreeshakingOptions, TsdownBundle, TsdownHooks, TsdownInputOption, UnusedOptions, UserConfig, UserConfigExport, UserConfigFn, WithEnabled, Workspace, build, buildWithConfigs, defineConfig, enableDebug, globalLogger, mergeConfig };
package/dist/index.mjs CHANGED
@@ -1,5 +1,6 @@
1
- import { a as globalLogger } from "./logger-D_2uXZBG.mjs";
2
- import { n as mergeConfig, t as defineConfig } from "./config-CQ0WjrHu.mjs";
3
- import { i as shimFile, n as build, r as buildSingle, t as Rolldown } from "./src-DhBpfeQw.mjs";
1
+ import { a as globalLogger } from "./logger-C5G3WyAl.mjs";
2
+ import { n as mergeConfig, t as defineConfig } from "./config-DCPo70ac.mjs";
3
+ import { c as Rolldown, l as shimFile, n as buildWithConfigs, t as build } from "./build-CczdykTO.mjs";
4
+ import { t as enableDebug } from "./debug-C60bWO35.mjs";
4
5
 
5
- export { Rolldown, build, buildSingle, defineConfig, globalLogger, mergeConfig, shimFile };
6
+ export { Rolldown, build, buildWithConfigs, defineConfig, enableDebug, globalLogger, mergeConfig, shimFile };
@@ -1,8 +1,8 @@
1
1
  import { createRequire as __cjs_createRequire } from "node:module";
2
2
  const __cjs_require = __cjs_createRequire(import.meta.url);
3
3
  import { createRequire } from "node:module";
4
- import process from "node:process";
5
4
  import { bgRed, bgYellow, blue, green, rgb, yellow } from "ansis";
5
+ import process from "node:process";
6
6
  import { pathToFileURL } from "node:url";
7
7
  const picomatch = __cjs_require("picomatch");
8
8
 
@@ -1,4 +1,4 @@
1
- import { s as ResolvedConfig, v as ReportPlugin, w as TsdownBundle, y as Logger } from "./index-CMl71wtM.mjs";
1
+ import { s as ResolvedConfig, v as ReportPlugin, w as TsdownBundle, y as Logger } from "./types-Dxm9xngg.mjs";
2
2
  import { Plugin } from "rolldown";
3
3
 
4
4
  //#region src/features/external.d.ts
package/dist/plugins.mjs CHANGED
@@ -1,5 +1,3 @@
1
- import "./logger-D_2uXZBG.mjs";
2
- import "./config-CQ0WjrHu.mjs";
3
- import { a as WatchPlugin, c as NodeProtocolPlugin, l as ExternalPlugin, o as ShebangPlugin, s as ReportPlugin } from "./src-DhBpfeQw.mjs";
1
+ import { a as ReportPlugin, i as ShebangPlugin, o as NodeProtocolPlugin, r as WatchPlugin, s as ExternalPlugin } from "./build-CczdykTO.mjs";
4
2
 
5
3
  export { ExternalPlugin, NodeProtocolPlugin, ReportPlugin, ShebangPlugin, WatchPlugin };
package/dist/run.mjs CHANGED
@@ -1,29 +1,13 @@
1
1
  #!/usr/bin/env node
2
- import { a as globalLogger, f as resolveComma, h as toArray } from "./logger-D_2uXZBG.mjs";
3
- import { t as version } from "./package-PFFWH-Jh.mjs";
2
+ import { a as globalLogger } from "./logger-C5G3WyAl.mjs";
3
+ import { n as version, t as enableDebug } from "./debug-C60bWO35.mjs";
4
4
  import module from "node:module";
5
- import process from "node:process";
6
5
  import { dim } from "ansis";
7
- import { createDebug, enable, namespaces } from "obug";
8
6
  import { VERSION } from "rolldown";
7
+ import process from "node:process";
9
8
  import { x } from "tinyexec";
10
9
  import { cac } from "cac";
11
10
 
12
- //#region src/features/debug.ts
13
- const debugLog = createDebug("tsdown:debug");
14
- function enableDebug(cliOptions) {
15
- const { debug } = cliOptions;
16
- if (!debug) return;
17
- let namespace;
18
- if (debug === true) namespace = "tsdown:*";
19
- else namespace = resolveComma(toArray(debug)).map((v) => `tsdown:${v}`).join(",");
20
- const ns = namespaces();
21
- if (ns) namespace += `,${ns}`;
22
- enable(namespace);
23
- debugLog("Debugging enabled", namespace);
24
- }
25
-
26
- //#endregion
27
11
  //#region src/cli.ts
28
12
  const cli = cac("tsdown");
29
13
  cli.help().version(version);
@@ -31,9 +15,9 @@ cli.command("[...files]", "Bundle files", {
31
15
  ignoreOptionDefaultValue: true,
32
16
  allowUnknownOptions: true
33
17
  }).option("-c, --config <filename>", "Use a custom config file").option("--config-loader <loader>", "Config loader to use: auto, native, unrun", { default: "auto" }).option("--no-config", "Disable config file").option("-f, --format <format>", "Bundle format: esm, cjs, iife, umd", { default: "esm" }).option("--clean", "Clean output directory, --no-clean to disable").option("--external <module>", "Mark dependencies as external").option("--minify", "Minify output").option("--devtools", "Enable devtools integration").option("--debug [feat]", "Show debug logs").option("--target <target>", "Bundle target, e.g \"es2015\", \"esnext\"").option("-l, --logLevel <level>", "Set log level: info, warn, error, silent").option("--fail-on-warn", "Fail on warnings", { default: true }).option("--no-write", "Disable writing files to disk, incompatible with watch mode").option("-d, --out-dir <dir>", "Output directory", { default: "dist" }).option("--treeshake", "Tree-shake bundle", { default: true }).option("--sourcemap", "Generate source map", { default: false }).option("--shims", "Enable cjs and esm shims ", { default: false }).option("--platform <platform>", "Target platform", { default: "node" }).option("--dts", "Generate dts files").option("--publint", "Enable publint", { default: false }).option("--attw", "Enable Are the types wrong integration", { default: false }).option("--unused", "Enable unused dependencies check", { default: false }).option("-w, --watch [path]", "Watch mode").option("--ignore-watch <path>", "Ignore custom paths in watch mode").option("--from-vite [vitest]", "Reuse config from Vite or Vitest").option("--report", "Size report", { default: true }).option("--env.* <value>", "Define compile-time env variables").option("--env-file <file>", "Load environment variables from a file, when used together with --env, variables in --env take precedence").option("--env-prefix <prefix>", "Prefix for env variables to inject into the bundle", { default: "TSDOWN_" }).option("--on-success <command>", "Command to run on success").option("--copy <dir>", "Copy files to output dir").option("--public-dir <dir>", "Alias for --copy, deprecated").option("--tsconfig <tsconfig>", "Set tsconfig path").option("--unbundle", "Unbundle mode").option("-W, --workspace [dir]", "Enable workspace mode").option("-F, --filter <pattern>", "Filter configs (cwd or name), e.g. /pkg-name$/ or pkg-name").option("--exports", "Generate export-related metadata for package.json (experimental)").action(async (input, flags) => {
34
- globalLogger.level = flags.logLevel || (flags.silent ? "error" : "info");
18
+ globalLogger.level = flags.logLevel || "info";
35
19
  globalLogger.info(`tsdown ${dim`v${version}`} powered by rolldown ${dim`v${VERSION}`}`);
36
- const { build: build$1 } = await import("./index.mjs");
20
+ const { build: build$1 } = await import("./build.mjs");
37
21
  if (input.length > 0) flags.entry = input;
38
22
  await build$1(flags);
39
23
  });
@@ -57,7 +41,7 @@ cli.command("migrate", "[deprecated] Migrate from tsup to tsdown. Use \"npx tsdo
57
41
  });
58
42
  async function runCLI() {
59
43
  cli.parse(process.argv, { run: false });
60
- enableDebug(cli.options);
44
+ enableDebug(cli.options.debug);
61
45
  try {
62
46
  await cli.runMatchedCommand();
63
47
  } catch (error) {
@@ -1,4 +1,3 @@
1
- import "ansis";
2
1
  import { BuildOptions, ExternalOption, InputOptions, InternalModuleFormat, MinifyOptions, ModuleFormat, ModuleTypes, OutputAsset, OutputChunk, OutputOptions, Plugin, TreeshakingOptions } from "rolldown";
3
2
  import { Hookable } from "hookable";
4
3
  import { Options as DtsOptions } from "rolldown-plugin-dts";
@@ -43,7 +42,7 @@ interface CopyEntry {
43
42
  type CopyOptions = Arrayable<string | CopyEntry>;
44
43
  type CopyOptionsFn = (options: ResolvedConfig) => Awaitable<CopyOptions>;
45
44
  //#endregion
46
- //#region src/features/css.d.ts
45
+ //#region src/features/css/index.d.ts
47
46
  interface CssOptions {
48
47
  /**
49
48
  * Enable/disable CSS code splitting.
@@ -861,11 +860,6 @@ interface UserConfig {
861
860
  */
862
861
  name?: string;
863
862
  /**
864
- * @default false
865
- * @deprecated Use `logLevel` instead.
866
- */
867
- silent?: boolean;
868
- /**
869
863
  * Log level.
870
864
  * @default 'info'
871
865
  */
@@ -1000,7 +994,7 @@ type UserConfigFn = (inlineConfig: InlineConfig, context: {
1000
994
  ci: boolean;
1001
995
  }) => Awaitable<Arrayable<UserConfig>>;
1002
996
  type UserConfigExport = Awaitable<Arrayable<UserConfig> | UserConfigFn>;
1003
- type ResolvedConfig = Overwrite<MarkPartial<Omit<UserConfig, "workspace" | "fromVite" | "publicDir" | "silent" | "bundle" | "removeNodeProtocol" | "logLevel" | "failOnWarn" | "customLogger" | "envFile" | "envPrefix">, "globalName" | "inputOptions" | "outputOptions" | "minify" | "define" | "alias" | "external" | "onSuccess" | "outExtensions" | "hooks" | "copy" | "loader" | "name" | "banner" | "footer">, {
997
+ type ResolvedConfig = Overwrite<MarkPartial<Omit<UserConfig, "workspace" | "fromVite" | "publicDir" | "bundle" | "removeNodeProtocol" | "logLevel" | "failOnWarn" | "customLogger" | "envFile" | "envPrefix">, "globalName" | "inputOptions" | "outputOptions" | "minify" | "define" | "alias" | "external" | "onSuccess" | "outExtensions" | "hooks" | "copy" | "loader" | "name" | "banner" | "footer">, {
1004
998
  /** Resolved entry map (after glob expansion) */
1005
999
  entry: Record<string, string>;
1006
1000
  nameLabel: string | undefined;
@@ -1024,4 +1018,4 @@ type ResolvedConfig = Overwrite<MarkPartial<Omit<UserConfig, "workspace" | "from
1024
1018
  unused: false | UnusedOptions;
1025
1019
  }>;
1026
1020
  //#endregion
1027
- export { OutExtensionFactory as A, CopyOptions as B, RolldownChunk as C, ChunkAddonFunction as D, ChunkAddon as E, RolldownContext as F, TsdownHooks as I, DevtoolsOptions as L, PackageJsonWithPath as M, PackageType as N, ChunkAddonObject as O, BuildContext as P, CssOptions as R, ExportsOptions as S, AttwOptions as T, CopyOptionsFn as V, ReportOptions as _, NoExternalFn as a, globalLogger as b, Sourcemap as c, UnusedOptions as d, UserConfig as f, Workspace as g, WithEnabled as h, InlineConfig as i, OutExtensionObject as j, OutExtensionContext as k, TreeshakingOptions as l, UserConfigFn as m, DtsOptions as n, NormalizedFormat as o, UserConfigExport as p, Format as r, ResolvedConfig as s, CIOption as t, TsdownInputOption as u, ReportPlugin as v, TsdownBundle as w, PublintOptions as x, Logger as y, CopyEntry as z };
1021
+ export { OutExtensionFactory as A, CopyOptions as B, RolldownChunk as C, ChunkAddonFunction as D, ChunkAddon as E, RolldownContext as F, Arrayable as H, TsdownHooks as I, DevtoolsOptions as L, PackageJsonWithPath as M, PackageType as N, ChunkAddonObject as O, BuildContext as P, CssOptions as R, ExportsOptions as S, AttwOptions as T, CopyOptionsFn as V, ReportOptions as _, NoExternalFn as a, globalLogger as b, Sourcemap as c, UnusedOptions as d, UserConfig as f, Workspace as g, WithEnabled as h, InlineConfig as i, OutExtensionObject as j, OutExtensionContext as k, TreeshakingOptions as l, UserConfigFn as m, DtsOptions as n, NormalizedFormat as o, UserConfigExport as p, Format as r, ResolvedConfig as s, CIOption as t, TsdownInputOption as u, ReportPlugin as v, TsdownBundle as w, PublintOptions as x, Logger as y, CopyEntry as z };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "tsdown",
3
3
  "type": "module",
4
- "version": "0.19.0-beta.2",
4
+ "version": "0.19.0-beta.4",
5
5
  "description": "The Elegant Bundler for Libraries",
6
6
  "author": "Kevin Deng <sxzz@sxzz.moe>",
7
7
  "license": "MIT",
@@ -16,6 +16,7 @@
16
16
  },
17
17
  "exports": {
18
18
  ".": "./dist/index.mjs",
19
+ "./build": "./dist/build.mjs",
19
20
  "./config": "./dist/config.mjs",
20
21
  "./plugins": "./dist/plugins.mjs",
21
22
  "./run": "./dist/run.mjs",
@@ -99,7 +100,7 @@
99
100
  "@types/node": "^25.0.3",
100
101
  "@types/picomatch": "^4.0.2",
101
102
  "@types/semver": "^7.7.1",
102
- "@typescript/native-preview": "7.0.0-dev.20260101.1",
103
+ "@typescript/native-preview": "7.0.0-dev.20260107.1",
103
104
  "@unocss/eslint-plugin": "^66.5.12",
104
105
  "@vitejs/devtools": "^0.0.0-alpha.22",
105
106
  "@vitest/coverage-v8": "4.0.16",
@@ -1,5 +0,0 @@
1
- //#region package.json
2
- var version = "0.19.0-beta.2";
3
-
4
- //#endregion
5
- export { version as t };