@tochii/build 2.1.0 → 2.2.1

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.
@@ -0,0 +1,1707 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; } var _class;
2
+
3
+ var _chunkBYH4XDRHjs = require('./chunk-BYH4XDRH.js');
4
+
5
+
6
+
7
+
8
+
9
+
10
+
11
+
12
+
13
+ var _chunkVGC3FXLUjs = require('./chunk-VGC3FXLU.js');
14
+
15
+
16
+
17
+ var _chunkJZ25TPTYjs = require('./chunk-JZ25TPTY.js');
18
+
19
+
20
+
21
+
22
+
23
+
24
+
25
+
26
+
27
+
28
+
29
+
30
+
31
+
32
+
33
+
34
+ var _chunkTWFEYLU4js = require('./chunk-TWFEYLU4.js');
35
+
36
+ // src/index.ts
37
+ var _path = require('path'); var _path2 = _interopRequireDefault(_path);
38
+ var _fs = require('fs'); var _fs2 = _interopRequireDefault(_fs);
39
+ var _worker_threads = require('worker_threads');
40
+ var _bundlerequire = require('bundle-require');
41
+ var _tinyexec = require('tinyexec');
42
+ var _tinyglobby = require('tinyglobby');
43
+ var _treekill = require('tree-kill'); var _treekill2 = _interopRequireDefault(_treekill);
44
+
45
+ // src/esbuild/index.ts
46
+
47
+
48
+
49
+
50
+
51
+ var _esbuild = require('esbuild');
52
+ var _consola = require('consola'); var _consola2 = _interopRequireDefault(_consola);
53
+
54
+ // src/esbuild/node-protocol.ts
55
+ var nodeProtocolPlugin = () => {
56
+ const nodeProtocol = "node:";
57
+ return {
58
+ name: "node-protocol-plugin",
59
+ setup({ onResolve }) {
60
+ onResolve(
61
+ {
62
+ filter: /^node:/
63
+ },
64
+ ({ path: path12 }) => ({
65
+ path: path12.slice(nodeProtocol.length),
66
+ external: true
67
+ })
68
+ );
69
+ }
70
+ };
71
+ };
72
+
73
+ // src/esbuild/external.ts
74
+
75
+ var NON_NODE_MODULE_RE = /^[A-Z]:[/\\]|^\.{0,2}\/|^\.{1,2}$/;
76
+ var externalPlugin = ({
77
+ external,
78
+ noExternal,
79
+ skipNodeModulesBundle,
80
+ tsconfigResolvePaths
81
+ }) => {
82
+ return {
83
+ name: `external`,
84
+ setup(build2) {
85
+ if (skipNodeModulesBundle) {
86
+ const resolvePatterns = _bundlerequire.tsconfigPathsToRegExp.call(void 0,
87
+ tsconfigResolvePaths || {}
88
+ );
89
+ build2.onResolve({ filter: /.*/ }, (args) => {
90
+ if (_bundlerequire.match.call(void 0, args.path, resolvePatterns)) {
91
+ return;
92
+ }
93
+ if (_bundlerequire.match.call(void 0, args.path, noExternal)) {
94
+ return;
95
+ }
96
+ if (_bundlerequire.match.call(void 0, args.path, external)) {
97
+ return { external: true };
98
+ }
99
+ if (!NON_NODE_MODULE_RE.test(args.path)) {
100
+ return {
101
+ path: args.path,
102
+ external: true
103
+ };
104
+ }
105
+ });
106
+ } else {
107
+ build2.onResolve({ filter: /.*/ }, (args) => {
108
+ if (_bundlerequire.match.call(void 0, args.path, noExternal)) {
109
+ return;
110
+ }
111
+ if (_bundlerequire.match.call(void 0, args.path, external)) {
112
+ return { external: true };
113
+ }
114
+ });
115
+ }
116
+ }
117
+ };
118
+ };
119
+
120
+ // src/esbuild/postcss.ts
121
+
122
+
123
+ var postcssPlugin = ({
124
+ css,
125
+ inject,
126
+ cssLoader
127
+ }) => {
128
+ return {
129
+ name: "postcss",
130
+ setup(build2) {
131
+ let configCache;
132
+ const getPostcssConfig = async () => {
133
+ const loadConfig = _chunkTWFEYLU4js.__require.call(void 0, "postcss-load-config");
134
+ if (configCache) {
135
+ return configCache;
136
+ }
137
+ try {
138
+ const result = await loadConfig({}, process.cwd());
139
+ configCache = result;
140
+ return result;
141
+ } catch (error) {
142
+ if (error.message.includes("No PostCSS Config found in")) {
143
+ const result = { plugins: [], options: {} };
144
+ return result;
145
+ }
146
+ throw error;
147
+ }
148
+ };
149
+ build2.onResolve({ filter: /^#style-inject$/ }, () => {
150
+ return { path: "#style-inject", namespace: "#style-inject" };
151
+ });
152
+ build2.onLoad(
153
+ { filter: /^#style-inject$/, namespace: "#style-inject" },
154
+ () => {
155
+ return {
156
+ // Taken from https://github.com/egoist/style-inject/blob/master/src/index.js (MIT)
157
+ contents: `
158
+ export default function styleInject(css, { insertAt } = {}) {
159
+ if (!css || typeof document === 'undefined') return
160
+
161
+ const head = document.head || document.getElementsByTagName('head')[0]
162
+ const style = document.createElement('style')
163
+ style.type = 'text/css'
164
+
165
+ if (insertAt === 'top') {
166
+ if (head.firstChild) {
167
+ head.insertBefore(style, head.firstChild)
168
+ } else {
169
+ head.appendChild(style)
170
+ }
171
+ } else {
172
+ head.appendChild(style)
173
+ }
174
+
175
+ if (style.styleSheet) {
176
+ style.styleSheet.cssText = css
177
+ } else {
178
+ style.appendChild(document.createTextNode(css))
179
+ }
180
+ }
181
+ `,
182
+ loader: "js"
183
+ };
184
+ }
185
+ );
186
+ build2.onLoad({ filter: /\.css$/ }, async (args) => {
187
+ let contents;
188
+ if (css && args.path.endsWith(".svelte.css")) {
189
+ contents = css.get(args.path);
190
+ } else {
191
+ contents = await _fs2.default.promises.readFile(args.path, "utf8");
192
+ }
193
+ const { plugins, options } = await getPostcssConfig();
194
+ if (plugins && plugins.length > 0) {
195
+ const postcss = _chunkTWFEYLU4js.getPostcss.call(void 0, );
196
+ if (!postcss) {
197
+ return {
198
+ errors: [
199
+ {
200
+ text: `postcss is not installed`
201
+ }
202
+ ]
203
+ };
204
+ }
205
+ const result = await _optionalChain([postcss, 'optionalAccess', _2 => _2.default, 'call', _3 => _3(plugins), 'access', _4 => _4.process, 'call', _5 => _5(contents, { ...options, from: args.path })]);
206
+ contents = result.css;
207
+ }
208
+ if (inject) {
209
+ contents = (await _esbuild.transform.call(void 0, contents, {
210
+ minify: build2.initialOptions.minify,
211
+ minifyIdentifiers: build2.initialOptions.minifyIdentifiers,
212
+ minifySyntax: build2.initialOptions.minifySyntax,
213
+ minifyWhitespace: build2.initialOptions.minifyWhitespace,
214
+ logLevel: build2.initialOptions.logLevel,
215
+ loader: "css"
216
+ })).code;
217
+ contents = typeof inject === "function" ? await inject(JSON.stringify(contents), args.path) : `import styleInject from '#style-inject';styleInject(${JSON.stringify(
218
+ contents
219
+ )})`;
220
+ return {
221
+ contents,
222
+ loader: "js"
223
+ };
224
+ }
225
+ return {
226
+ contents,
227
+ loader: _nullishCoalesce(cssLoader, () => ( "css"))
228
+ };
229
+ });
230
+ }
231
+ };
232
+ };
233
+
234
+ // src/esbuild/svelte.ts
235
+
236
+
237
+
238
+ var useSvelteCssExtension = (p) => p.replace(/\.svelte$/, ".svelte.css");
239
+ var sveltePlugin = ({
240
+ css
241
+ }) => {
242
+ return {
243
+ name: "svelte",
244
+ setup(build2) {
245
+ let svelte;
246
+ let sveltePreprocessor;
247
+ build2.onResolve({ filter: /\.svelte\.css$/ }, (args) => {
248
+ return {
249
+ path: _path2.default.relative(
250
+ process.cwd(),
251
+ _path2.default.join(args.resolveDir, args.path)
252
+ ),
253
+ namespace: "svelte-css"
254
+ };
255
+ });
256
+ build2.onLoad({ filter: /\.svelte$/ }, async (args) => {
257
+ svelte = svelte || _chunkTWFEYLU4js.localRequire.call(void 0, "svelte/compiler");
258
+ sveltePreprocessor = sveltePreprocessor || _chunkTWFEYLU4js.localRequire.call(void 0, "svelte-preprocess");
259
+ if (!svelte) {
260
+ return {
261
+ errors: [{ text: `You need to install "svelte" in your project` }]
262
+ };
263
+ }
264
+ const convertMessage = ({ message, start, end }) => {
265
+ let location;
266
+ if (start && end) {
267
+ const lineText = source.split(/\r\n|\r|\n/g)[start.line - 1];
268
+ const lineEnd = start.line === end.line ? end.column : lineText.length;
269
+ location = {
270
+ file: filename,
271
+ line: start.line,
272
+ column: start.column,
273
+ length: lineEnd - start.column,
274
+ lineText
275
+ };
276
+ }
277
+ return { text: message, location };
278
+ };
279
+ const source = await _fs2.default.promises.readFile(args.path, "utf8");
280
+ const filename = _path2.default.relative(process.cwd(), args.path);
281
+ try {
282
+ const preprocess = await svelte.preprocess(
283
+ source,
284
+ sveltePreprocessor ? sveltePreprocessor({
285
+ sourceMap: true,
286
+ typescript: {
287
+ compilerOptions: {
288
+ verbatimModuleSyntax: true
289
+ }
290
+ }
291
+ }) : {
292
+ async script({ content, attributes }) {
293
+ if (attributes.lang !== "ts") return { code: content };
294
+ const { code, map } = await _esbuild.transform.call(void 0, content, {
295
+ sourcefile: args.path,
296
+ loader: "ts",
297
+ sourcemap: true,
298
+ tsconfigRaw: {
299
+ compilerOptions: {
300
+ verbatimModuleSyntax: true
301
+ }
302
+ },
303
+ logLevel: build2.initialOptions.logLevel
304
+ });
305
+ return {
306
+ code,
307
+ map
308
+ };
309
+ }
310
+ },
311
+ {
312
+ filename: args.path
313
+ }
314
+ );
315
+ const result = svelte.compile(preprocess.code, {
316
+ filename,
317
+ css: "external"
318
+ });
319
+ let contents = result.js.code;
320
+ if (css && result.css && result.css.code) {
321
+ const cssPath = useSvelteCssExtension(filename);
322
+ css.set(cssPath, result.css.code);
323
+ contents = `import '${useSvelteCssExtension(_path2.default.basename(args.path))}';${contents}`;
324
+ }
325
+ return { contents, warnings: result.warnings.map(convertMessage) };
326
+ } catch (error) {
327
+ return { errors: [convertMessage(error)] };
328
+ }
329
+ });
330
+ }
331
+ };
332
+ };
333
+
334
+ // src/esbuild/swc.ts
335
+
336
+ var swcPlugin = ({ logger: logger3 }) => {
337
+ return {
338
+ name: "swc",
339
+ setup(build2) {
340
+ const swc = _chunkTWFEYLU4js.localRequire.call(void 0, "@swc/core");
341
+ if (!swc) {
342
+ logger3.warn(
343
+ build2.initialOptions.format,
344
+ `You have emitDecoratorMetadata enabled but @swc/core was not installed, skipping swc plugin`
345
+ );
346
+ return;
347
+ }
348
+ build2.initialOptions.keepNames = true;
349
+ build2.onLoad({ filter: /\.[jt]sx?$/ }, async (args) => {
350
+ const isTs = /\.tsx?$/.test(args.path);
351
+ const jsc = {
352
+ parser: {
353
+ syntax: isTs ? "typescript" : "ecmascript",
354
+ decorators: true
355
+ },
356
+ transform: {
357
+ legacyDecorator: true,
358
+ decoratorMetadata: true
359
+ },
360
+ keepClassNames: true,
361
+ target: "es2022"
362
+ };
363
+ const result = await swc.transformFile(args.path, {
364
+ jsc,
365
+ sourceMaps: true,
366
+ configFile: false,
367
+ swcrc: false
368
+ });
369
+ let code = result.code;
370
+ if (result.map) {
371
+ const map = JSON.parse(result.map);
372
+ map.sources = map.sources.map((source) => {
373
+ return _path2.default.isAbsolute(source) ? _path2.default.relative(_path2.default.dirname(args.path), source) : source;
374
+ });
375
+ code += `//# sourceMappingURL=data:application/json;base64,${Buffer.from(
376
+ JSON.stringify(map)
377
+ ).toString("base64")}`;
378
+ }
379
+ return {
380
+ contents: code
381
+ };
382
+ });
383
+ }
384
+ };
385
+ };
386
+
387
+ // src/esbuild/native-node-module.ts
388
+
389
+ var nativeNodeModulesPlugin = () => {
390
+ return {
391
+ name: "native-node-modules",
392
+ setup(build2) {
393
+ build2.onResolve({ filter: /\.node$/, namespace: "file" }, (args) => {
394
+ const resolvedId = _chunkTWFEYLU4js.__require.resolve(args.path, {
395
+ paths: [args.resolveDir]
396
+ });
397
+ if (resolvedId.endsWith(".node")) {
398
+ return {
399
+ path: resolvedId,
400
+ namespace: "node-file"
401
+ };
402
+ }
403
+ return {
404
+ path: resolvedId
405
+ };
406
+ });
407
+ build2.onLoad({ filter: /.*/, namespace: "node-file" }, (args) => {
408
+ return {
409
+ contents: `
410
+ import path from ${JSON.stringify(args.path)}
411
+ try { module.exports = require(path) }
412
+ catch {}
413
+ `,
414
+ resolveDir: _path2.default.dirname(args.path)
415
+ };
416
+ });
417
+ build2.onResolve(
418
+ { filter: /\.node$/, namespace: "node-file" },
419
+ (args) => ({
420
+ path: args.path,
421
+ namespace: "file"
422
+ })
423
+ );
424
+ const opts = build2.initialOptions;
425
+ opts.loader = opts.loader || {};
426
+ opts.loader[".node"] = "file";
427
+ }
428
+ };
429
+ };
430
+
431
+ // src/esbuild/index.ts
432
+ var getOutputExtensionMap = (options, format, pkgType) => {
433
+ const outExtension = options.outExtension || _chunkTWFEYLU4js.defaultOutExtension;
434
+ const defaultExtension = _chunkTWFEYLU4js.defaultOutExtension.call(void 0, { format, pkgType });
435
+ const extension = outExtension({ options, format, pkgType });
436
+ return {
437
+ ".js": extension.js || defaultExtension.js
438
+ };
439
+ };
440
+ var generateExternal = async (external) => {
441
+ const result = [];
442
+ for (const item of external) {
443
+ if (typeof item !== "string" || !item.endsWith("package.json")) {
444
+ result.push(item);
445
+ continue;
446
+ }
447
+ const pkgPath = _path2.default.isAbsolute(item) ? _path2.default.dirname(item) : _path2.default.dirname(_path2.default.resolve(process.cwd(), item));
448
+ const deps = await _chunkVGC3FXLUjs.getProductionDeps.call(void 0, pkgPath);
449
+ result.push(...deps);
450
+ }
451
+ return result;
452
+ };
453
+ async function runEsbuild(options, {
454
+ format,
455
+ css,
456
+ logger: logger3,
457
+ buildDependencies,
458
+ pluginContainer
459
+ }) {
460
+ const pkg = await _chunkVGC3FXLUjs.loadPkg.call(void 0, process.cwd());
461
+ const deps = await _chunkVGC3FXLUjs.getProductionDeps.call(void 0, process.cwd());
462
+ const external = [
463
+ // Exclude dependencies, e.g. `lodash`, `lodash/get`
464
+ ...deps.map((dep) => new RegExp(`^${dep}($|\\/|\\\\)`)),
465
+ ...await generateExternal(options.external || [])
466
+ ];
467
+ const outDir = options.outDir;
468
+ const outExtension = getOutputExtensionMap(options, format, pkg.type);
469
+ const env = {
470
+ ...options.env
471
+ };
472
+ if (options.replaceNodeEnv) {
473
+ env.NODE_ENV = options.minify || options.minifyWhitespace ? "production" : "development";
474
+ }
475
+ logger3.info(format, "Build start");
476
+ const startTime = Date.now();
477
+ let result;
478
+ const splitting = format === "iife" ? false : typeof options.splitting === "boolean" ? options.splitting : format === "esm";
479
+ const platform = options.platform || "node";
480
+ const loader = options.loader || {};
481
+ const injectShims = options.shims;
482
+ pluginContainer.setContext({
483
+ format,
484
+ splitting,
485
+ options,
486
+ logger: logger3
487
+ });
488
+ await pluginContainer.buildStarted();
489
+ const esbuildPlugins = [
490
+ format === "cjs" && options.removeNodeProtocol && nodeProtocolPlugin(),
491
+ {
492
+ name: "modify-options",
493
+ setup(build2) {
494
+ pluginContainer.modifyEsbuildOptions(build2.initialOptions);
495
+ if (options.esbuildOptions) {
496
+ options.esbuildOptions(build2.initialOptions, { format });
497
+ }
498
+ }
499
+ },
500
+ // esbuild's `external` option doesn't support RegExp
501
+ // So here we use a custom plugin to implement it
502
+ format !== "iife" && externalPlugin({
503
+ external,
504
+ noExternal: options.noExternal,
505
+ skipNodeModulesBundle: options.skipNodeModulesBundle,
506
+ tsconfigResolvePaths: options.tsconfigResolvePaths
507
+ }),
508
+ options.tsconfigDecoratorMetadata && swcPlugin({ logger: logger3 }),
509
+ nativeNodeModulesPlugin(),
510
+ postcssPlugin({
511
+ css,
512
+ inject: options.injectStyle,
513
+ cssLoader: loader[".css"]
514
+ }),
515
+ sveltePlugin({ css }),
516
+ ...options.esbuildPlugins || []
517
+ ];
518
+ const banner = typeof options.banner === "function" ? options.banner({ format }) : options.banner;
519
+ const footer = typeof options.footer === "function" ? options.footer({ format }) : options.footer;
520
+ try {
521
+ result = await _esbuild.build.call(void 0, {
522
+ entryPoints: options.entry,
523
+ format: format === "cjs" && splitting || options.treeshake ? "esm" : format,
524
+ bundle: typeof options.bundle === "undefined" ? true : options.bundle,
525
+ platform,
526
+ globalName: options.globalName,
527
+ jsxFactory: options.jsxFactory,
528
+ jsxFragment: options.jsxFragment,
529
+ sourcemap: options.sourcemap ? "external" : false,
530
+ target: options.target,
531
+ banner,
532
+ footer,
533
+ tsconfig: options.tsconfig,
534
+ loader: {
535
+ ".aac": "file",
536
+ ".css": "file",
537
+ ".eot": "file",
538
+ ".flac": "file",
539
+ ".gif": "file",
540
+ ".jpeg": "file",
541
+ ".jpg": "file",
542
+ ".mp3": "file",
543
+ ".mp4": "file",
544
+ ".ogg": "file",
545
+ ".otf": "file",
546
+ ".png": "file",
547
+ ".svg": "file",
548
+ ".ttf": "file",
549
+ ".wav": "file",
550
+ ".webm": "file",
551
+ ".webp": "file",
552
+ ".woff": "file",
553
+ ".woff2": "file",
554
+ ...loader
555
+ },
556
+ mainFields: platform === "node" ? ["module", "main"] : ["browser", "module", "main"],
557
+ plugins: esbuildPlugins.filter(_chunkTWFEYLU4js.truthy),
558
+ define: {
559
+ TSUP_FORMAT: JSON.stringify(format),
560
+ ...format === "cjs" && injectShims ? {
561
+ "import.meta.url": "importMetaUrl"
562
+ } : {},
563
+ ...options.define,
564
+ ...Object.keys(env).reduce((res, key) => {
565
+ const value = JSON.stringify(env[key]);
566
+ return {
567
+ ...res,
568
+ [`process.env.${key}`]: value,
569
+ [`import.meta.env.${key}`]: value
570
+ };
571
+ }, {})
572
+ },
573
+ inject: [
574
+ format === "cjs" && injectShims ? _path2.default.join(__dirname, "../assets/cjs_shims.js") : "",
575
+ format === "esm" && injectShims && platform === "node" ? _path2.default.join(__dirname, "../assets/esm_shims.js") : "",
576
+ ...options.inject || []
577
+ ].filter(Boolean),
578
+ outdir: options.legacyOutput && format !== "cjs" ? _path2.default.join(outDir, format) : outDir,
579
+ outExtension: options.legacyOutput ? void 0 : outExtension,
580
+ write: false,
581
+ splitting,
582
+ logLevel: "error",
583
+ minify: options.minify === "terser" ? false : options.minify,
584
+ minifyWhitespace: options.minifyWhitespace,
585
+ minifyIdentifiers: options.minifyIdentifiers,
586
+ minifySyntax: options.minifySyntax,
587
+ keepNames: options.keepNames,
588
+ pure: typeof options.pure === "string" ? [options.pure] : options.pure,
589
+ metafile: true
590
+ });
591
+ } catch (error) {
592
+ logger3.error(format, "Build failed");
593
+ throw error;
594
+ }
595
+ if (result && result.warnings && !_chunkVGC3FXLUjs.getSilent.call(void 0, )) {
596
+ const messages = result.warnings.filter((warning) => {
597
+ if (warning.text.includes(
598
+ `This call to "require" will not be bundled because`
599
+ ) || warning.text.includes(`Indirect calls to "require" will not be bundled`))
600
+ return false;
601
+ return true;
602
+ });
603
+ const formatted = await _esbuild.formatMessages.call(void 0, messages, {
604
+ kind: "warning",
605
+ color: true
606
+ });
607
+ formatted.forEach((message) => {
608
+ _consola2.default.warn(message);
609
+ });
610
+ }
611
+ if (result && result.outputFiles) {
612
+ await pluginContainer.buildFinished({
613
+ outputFiles: result.outputFiles,
614
+ metafile: result.metafile
615
+ });
616
+ const timeInMs = Date.now() - startTime;
617
+ logger3.success(format, `\u26A1\uFE0F Build success in ${Math.floor(timeInMs)}ms`);
618
+ }
619
+ if (result.metafile) {
620
+ for (const file of Object.keys(result.metafile.inputs)) {
621
+ buildDependencies.add(file);
622
+ }
623
+ if (options.metafile) {
624
+ const outPath = _path2.default.resolve(outDir, `metafile-${format}.json`);
625
+ await _fs2.default.promises.mkdir(_path2.default.dirname(outPath), { recursive: true });
626
+ await _fs2.default.promises.writeFile(
627
+ outPath,
628
+ JSON.stringify(result.metafile),
629
+ "utf8"
630
+ );
631
+ }
632
+ }
633
+ }
634
+
635
+ // src/plugins/shebang.ts
636
+ var shebang = () => {
637
+ return {
638
+ name: "shebang",
639
+ renderChunk(_, info) {
640
+ if (info.type === "chunk" && /\.(cjs|js|mjs)$/.test(info.path) && info.code.startsWith("#!")) {
641
+ info.mode = 493;
642
+ }
643
+ }
644
+ };
645
+ };
646
+
647
+ // src/plugins/cjs-splitting.ts
648
+ var cjsSplitting = () => {
649
+ return {
650
+ name: "cjs-splitting",
651
+ async renderChunk(code, info) {
652
+ if (!this.splitting || this.options.treeshake || // <-- handled by rollup
653
+ this.format !== "cjs" || info.type !== "chunk" || !/\.(js|cjs)$/.test(info.path)) {
654
+ return;
655
+ }
656
+ const { transform: transform3 } = await Promise.resolve().then(() => _interopRequireWildcard(require("sucrase")));
657
+ const result = transform3(code, {
658
+ filePath: info.path,
659
+ transforms: ["imports"],
660
+ sourceMapOptions: this.options.sourcemap ? {
661
+ compiledFilename: info.path
662
+ } : void 0
663
+ });
664
+ return {
665
+ code: result.code,
666
+ map: result.sourceMap
667
+ };
668
+ }
669
+ };
670
+ };
671
+
672
+ // src/plugin.ts
673
+
674
+
675
+
676
+
677
+ var _sourcemap = require('source-map');
678
+
679
+ // src/fs.ts
680
+
681
+
682
+ var outputFile = async (filepath, data, options) => {
683
+ await _fs2.default.promises.mkdir(_path2.default.dirname(filepath), { recursive: true });
684
+ await _fs2.default.promises.writeFile(filepath, data, options);
685
+ };
686
+ function copyDirSync(srcDir, destDir) {
687
+ if (!_fs2.default.existsSync(srcDir)) return;
688
+ _fs2.default.mkdirSync(destDir, { recursive: true });
689
+ for (const file of _fs2.default.readdirSync(srcDir)) {
690
+ const srcFile = _path2.default.resolve(srcDir, file);
691
+ if (srcFile === destDir) {
692
+ continue;
693
+ }
694
+ const destFile = _path2.default.resolve(destDir, file);
695
+ const stat = _fs2.default.statSync(srcFile);
696
+ if (stat.isDirectory()) {
697
+ copyDirSync(srcFile, destFile);
698
+ } else {
699
+ _fs2.default.copyFileSync(srcFile, destFile);
700
+ }
701
+ }
702
+ }
703
+
704
+ // src/plugin.ts
705
+ var parseSourceMap = (map) => {
706
+ return typeof map === "string" ? JSON.parse(map) : map;
707
+ };
708
+ var isJS = (path12) => /\.(js|mjs|cjs)$/.test(path12);
709
+ var isCSS = (path12) => /\.css$/.test(path12);
710
+ var PluginContainer = class {
711
+
712
+
713
+ constructor(plugins) {
714
+ this.plugins = plugins;
715
+ }
716
+ setContext(context) {
717
+ this.context = context;
718
+ }
719
+ getContext() {
720
+ if (!this.context) throw new Error(`Plugin context is not set`);
721
+ return this.context;
722
+ }
723
+ modifyEsbuildOptions(options) {
724
+ for (const plugin of this.plugins) {
725
+ if (plugin.esbuildOptions) {
726
+ plugin.esbuildOptions.call(this.getContext(), options);
727
+ }
728
+ }
729
+ }
730
+ async buildStarted() {
731
+ for (const plugin of this.plugins) {
732
+ if (plugin.buildStart) {
733
+ await plugin.buildStart.call(this.getContext());
734
+ }
735
+ }
736
+ }
737
+ async buildFinished({
738
+ outputFiles,
739
+ metafile
740
+ }) {
741
+ const files = outputFiles.filter((file) => !file.path.endsWith(".map")).map((file) => {
742
+ if (isJS(file.path) || isCSS(file.path)) {
743
+ const relativePath = _chunkTWFEYLU4js.slash.call(void 0, _path2.default.relative(process.cwd(), file.path));
744
+ const meta = _optionalChain([metafile, 'optionalAccess', _6 => _6.outputs, 'access', _7 => _7[relativePath]]);
745
+ return {
746
+ type: "chunk",
747
+ path: file.path,
748
+ code: file.text,
749
+ map: _optionalChain([outputFiles, 'access', _8 => _8.find, 'call', _9 => _9((f) => f.path === `${file.path}.map`), 'optionalAccess', _10 => _10.text]),
750
+ entryPoint: _optionalChain([meta, 'optionalAccess', _11 => _11.entryPoint]),
751
+ exports: _optionalChain([meta, 'optionalAccess', _12 => _12.exports]),
752
+ imports: _optionalChain([meta, 'optionalAccess', _13 => _13.imports])
753
+ };
754
+ } else {
755
+ return { type: "asset", path: file.path, contents: file.contents };
756
+ }
757
+ });
758
+ const writtenFiles = [];
759
+ await Promise.all(
760
+ files.map(async (info) => {
761
+ for (const plugin of this.plugins) {
762
+ if (info.type === "chunk" && plugin.renderChunk) {
763
+ const result = await plugin.renderChunk.call(
764
+ this.getContext(),
765
+ info.code,
766
+ info
767
+ );
768
+ if (result) {
769
+ info.code = result.code;
770
+ if (result.map) {
771
+ const originalConsumer = await new (0, _sourcemap.SourceMapConsumer)(
772
+ parseSourceMap(info.map)
773
+ );
774
+ const newConsumer = await new (0, _sourcemap.SourceMapConsumer)(
775
+ parseSourceMap(result.map)
776
+ );
777
+ const generator = _sourcemap.SourceMapGenerator.fromSourceMap(newConsumer);
778
+ generator.applySourceMap(originalConsumer, info.path);
779
+ info.map = generator.toJSON();
780
+ originalConsumer.destroy();
781
+ newConsumer.destroy();
782
+ }
783
+ }
784
+ }
785
+ }
786
+ const inlineSourceMap = this.context.options.sourcemap === "inline";
787
+ const contents = info.type === "chunk" ? info.code + getSourcemapComment(
788
+ inlineSourceMap,
789
+ info.map,
790
+ info.path,
791
+ isCSS(info.path)
792
+ ) : info.contents;
793
+ await outputFile(info.path, contents, {
794
+ mode: info.type === "chunk" ? info.mode : void 0
795
+ });
796
+ writtenFiles.push({
797
+ get name() {
798
+ return _path2.default.relative(process.cwd(), info.path);
799
+ },
800
+ get size() {
801
+ return contents.length;
802
+ }
803
+ });
804
+ if (info.type === "chunk" && info.map && !inlineSourceMap) {
805
+ const map = typeof info.map === "string" ? JSON.parse(info.map) : info.map;
806
+ const outPath = `${info.path}.map`;
807
+ const contents2 = JSON.stringify(map);
808
+ await outputFile(outPath, contents2);
809
+ writtenFiles.push({
810
+ get name() {
811
+ return _path2.default.relative(process.cwd(), outPath);
812
+ },
813
+ get size() {
814
+ return contents2.length;
815
+ }
816
+ });
817
+ }
818
+ })
819
+ );
820
+ for (const plugin of this.plugins) {
821
+ if (plugin.buildEnd) {
822
+ await plugin.buildEnd.call(this.getContext(), { writtenFiles });
823
+ }
824
+ }
825
+ }
826
+ };
827
+ var getSourcemapComment = (inline, map, filepath, isCssFile) => {
828
+ if (!map) return "";
829
+ const prefix = isCssFile ? "/*" : "//";
830
+ const suffix = isCssFile ? " */" : "";
831
+ const url = inline ? `data:application/json;base64,${Buffer.from(
832
+ typeof map === "string" ? map : JSON.stringify(map)
833
+ ).toString("base64")}` : `${_path2.default.basename(filepath)}.map`;
834
+ return `${prefix}# sourceMappingURL=${url}${suffix}`;
835
+ };
836
+
837
+ // src/plugins/swc-target.ts
838
+ var TARGETS = ["es5", "es3"];
839
+ var swcTarget = () => {
840
+ let enabled = false;
841
+ let target;
842
+ return {
843
+ name: "swc-target",
844
+ esbuildOptions(options) {
845
+ if (typeof options.target === "string" && TARGETS.includes(options.target)) {
846
+ target = options.target;
847
+ options.target = "es2020";
848
+ enabled = true;
849
+ }
850
+ },
851
+ async renderChunk(code, info) {
852
+ if (!enabled || !/\.(cjs|mjs|js)$/.test(info.path)) {
853
+ return;
854
+ }
855
+ const swc = _chunkTWFEYLU4js.localRequire.call(void 0, "@swc/core");
856
+ if (!swc) {
857
+ throw new (0, _chunkJZ25TPTYjs.PrettyError)(
858
+ `@swc/core is required for ${target} target. Please install it with \`npm install @swc/core -D\``
859
+ );
860
+ }
861
+ const result = await swc.transform(code, {
862
+ filename: info.path,
863
+ sourceMaps: this.options.sourcemap,
864
+ minify: Boolean(this.options.minify),
865
+ jsc: {
866
+ target,
867
+ parser: {
868
+ syntax: "ecmascript"
869
+ },
870
+ minify: this.options.minify === true ? {
871
+ compress: false,
872
+ mangle: {
873
+ reserved: this.options.globalName ? [this.options.globalName] : []
874
+ }
875
+ } : void 0
876
+ },
877
+ module: {
878
+ type: this.format === "cjs" ? "commonjs" : "es6"
879
+ }
880
+ });
881
+ return {
882
+ code: result.code,
883
+ map: result.map
884
+ };
885
+ }
886
+ };
887
+ };
888
+
889
+ // src/plugins/size-reporter.ts
890
+ var sizeReporter = () => {
891
+ return {
892
+ name: "size-reporter",
893
+ buildEnd({ writtenFiles }) {
894
+ _chunkVGC3FXLUjs.reportSize.call(void 0,
895
+ this.logger,
896
+ this.format,
897
+ writtenFiles.reduce((res, file) => {
898
+ return {
899
+ ...res,
900
+ [file.name]: file.size
901
+ };
902
+ }, {})
903
+ );
904
+ }
905
+ };
906
+ };
907
+
908
+ // src/plugins/tree-shaking.ts
909
+
910
+ var _rollup = require('rollup');
911
+ var treeShakingPlugin = ({
912
+ treeshake,
913
+ name,
914
+ silent
915
+ }) => {
916
+ return {
917
+ name: "tree-shaking",
918
+ async renderChunk(code, info) {
919
+ if (!treeshake || !/\.(cjs|js|mjs)$/.test(info.path)) return;
920
+ const bundle = await _rollup.rollup.call(void 0, {
921
+ input: [info.path],
922
+ plugins: [
923
+ {
924
+ name: "tsup",
925
+ resolveId(source) {
926
+ if (source === info.path) return source;
927
+ return false;
928
+ },
929
+ load(id) {
930
+ if (id === info.path) return { code, map: info.map };
931
+ }
932
+ }
933
+ ],
934
+ treeshake,
935
+ makeAbsoluteExternalsRelative: false,
936
+ preserveEntrySignatures: "exports-only",
937
+ onwarn: silent ? () => {
938
+ } : void 0
939
+ });
940
+ const result = await bundle.generate({
941
+ interop: "auto",
942
+ format: this.format,
943
+ file: info.path,
944
+ sourcemap: !!this.options.sourcemap,
945
+ compact: !!this.options.minify,
946
+ name
947
+ });
948
+ for (const file of result.output) {
949
+ if (file.type === "chunk" && file.fileName === _path2.default.basename(info.path)) {
950
+ return {
951
+ code: file.code,
952
+ map: file.map
953
+ };
954
+ }
955
+ }
956
+ }
957
+ };
958
+ };
959
+
960
+ // src/lib/public-dir.ts
961
+
962
+ var copyPublicDir = (publicDir, outDir) => {
963
+ if (!publicDir) return;
964
+ copyDirSync(_path2.default.resolve(publicDir === true ? "public" : publicDir), outDir);
965
+ };
966
+ var isInPublicDir = (publicDir, filePath) => {
967
+ if (!publicDir) return false;
968
+ const publicPath = _chunkTWFEYLU4js.slash.call(void 0,
969
+ _path2.default.resolve(publicDir === true ? "public" : publicDir)
970
+ );
971
+ return _chunkTWFEYLU4js.slash.call(void 0, _path2.default.resolve(filePath)).startsWith(`${publicPath}/`);
972
+ };
973
+
974
+ // src/plugins/terser.ts
975
+ var terserPlugin = ({
976
+ minifyOptions,
977
+ format,
978
+ terserOptions = {},
979
+ globalName,
980
+ logger: logger3
981
+ }) => {
982
+ return {
983
+ name: "terser",
984
+ async renderChunk(code, info) {
985
+ if (minifyOptions !== "terser" || !/\.(cjs|js|mjs)$/.test(info.path))
986
+ return;
987
+ const terser = _chunkTWFEYLU4js.localRequire.call(void 0, "terser");
988
+ if (!terser) {
989
+ throw new (0, _chunkJZ25TPTYjs.PrettyError)(
990
+ "terser is required for terser minification. Please install it with `npm install terser -D`"
991
+ );
992
+ }
993
+ const { minify } = terser;
994
+ const defaultOptions = {};
995
+ if (format === "esm") {
996
+ defaultOptions.module = true;
997
+ } else if (!(format === "iife" && globalName !== void 0)) {
998
+ defaultOptions.toplevel = true;
999
+ }
1000
+ try {
1001
+ const minifiedOutput = await minify(
1002
+ { [info.path]: code },
1003
+ { ...defaultOptions, ...terserOptions }
1004
+ );
1005
+ logger3.info("TERSER", "Minifying with Terser");
1006
+ if (!minifiedOutput.code) {
1007
+ logger3.error("TERSER", "Failed to minify with terser");
1008
+ }
1009
+ logger3.success("TERSER", "Terser Minification success");
1010
+ return { code: minifiedOutput.code, map: minifiedOutput.map };
1011
+ } catch (error) {
1012
+ logger3.error("TERSER", "Failed to minify with terser");
1013
+ logger3.error("TERSER", error);
1014
+ }
1015
+ return { code, map: info.map };
1016
+ }
1017
+ };
1018
+ };
1019
+
1020
+ // src/tsc.ts
1021
+
1022
+
1023
+ var _typescript = require('typescript'); var _typescript2 = _interopRequireDefault(_typescript);
1024
+ var logger = _chunkVGC3FXLUjs.createLogger.call(void 0, );
1025
+ var AliasPool = (_class = class {constructor() { _class.prototype.__init.call(this); }
1026
+ __init() {this.seen = /* @__PURE__ */ new Set()}
1027
+ assign(name) {
1028
+ let suffix = 0;
1029
+ let alias = name === "default" ? "default_alias" : name;
1030
+ while (this.seen.has(alias)) {
1031
+ alias = `${name}_alias_${++suffix}`;
1032
+ if (suffix >= 1e3) {
1033
+ throw new Error(
1034
+ "Alias generation exceeded limit. Possible infinite loop detected."
1035
+ );
1036
+ }
1037
+ }
1038
+ this.seen.add(alias);
1039
+ return alias;
1040
+ }
1041
+ }, _class);
1042
+ function getExports(program, fileMapping) {
1043
+ const checker = program.getTypeChecker();
1044
+ const aliasPool = new AliasPool();
1045
+ const assignAlias = aliasPool.assign.bind(aliasPool);
1046
+ function extractExports(sourceFileName) {
1047
+ const cwd = program.getCurrentDirectory();
1048
+ sourceFileName = _chunkTWFEYLU4js.toAbsolutePath.call(void 0, sourceFileName, cwd);
1049
+ const sourceFile = program.getSourceFile(sourceFileName);
1050
+ if (!sourceFile) {
1051
+ return [];
1052
+ }
1053
+ const destFileName = fileMapping.get(sourceFileName);
1054
+ if (!destFileName) {
1055
+ return [];
1056
+ }
1057
+ const moduleSymbol = checker.getSymbolAtLocation(sourceFile);
1058
+ if (!moduleSymbol) {
1059
+ return [];
1060
+ }
1061
+ const exports = [];
1062
+ const exportSymbols = checker.getExportsOfModule(moduleSymbol);
1063
+ exportSymbols.forEach((symbol) => {
1064
+ const name = symbol.getName();
1065
+ exports.push({
1066
+ kind: "named",
1067
+ sourceFileName,
1068
+ destFileName,
1069
+ name,
1070
+ alias: assignAlias(name),
1071
+ isTypeOnly: false
1072
+ });
1073
+ });
1074
+ return exports;
1075
+ }
1076
+ return program.getRootFileNames().flatMap(extractExports);
1077
+ }
1078
+ function emitDtsFiles(program, host) {
1079
+ const fileMapping = /* @__PURE__ */ new Map();
1080
+ const writeFile = (fileName, text, writeByteOrderMark, onError, sourceFiles, data) => {
1081
+ const sourceFile = _optionalChain([sourceFiles, 'optionalAccess', _14 => _14[0]]);
1082
+ const sourceFileName = _optionalChain([sourceFile, 'optionalAccess', _15 => _15.fileName]);
1083
+ if (sourceFileName && !fileName.endsWith(".map")) {
1084
+ const cwd = program.getCurrentDirectory();
1085
+ fileMapping.set(
1086
+ _chunkTWFEYLU4js.toAbsolutePath.call(void 0, sourceFileName, cwd),
1087
+ _chunkTWFEYLU4js.toAbsolutePath.call(void 0, fileName, cwd)
1088
+ );
1089
+ }
1090
+ return host.writeFile(
1091
+ fileName,
1092
+ text,
1093
+ writeByteOrderMark,
1094
+ onError,
1095
+ sourceFiles,
1096
+ data
1097
+ );
1098
+ };
1099
+ const emitResult = program.emit(void 0, writeFile, void 0, true);
1100
+ const diagnostics = _typescript2.default.getPreEmitDiagnostics(program).concat(emitResult.diagnostics);
1101
+ const diagnosticMessages = [];
1102
+ diagnostics.forEach((diagnostic) => {
1103
+ if (diagnostic.file) {
1104
+ const { line, character } = _typescript2.default.getLineAndCharacterOfPosition(
1105
+ diagnostic.file,
1106
+ diagnostic.start
1107
+ );
1108
+ const message = _typescript2.default.flattenDiagnosticMessageText(
1109
+ diagnostic.messageText,
1110
+ "\n"
1111
+ );
1112
+ diagnosticMessages.push(
1113
+ `${diagnostic.file.fileName} (${line + 1},${character + 1}): ${message}`
1114
+ );
1115
+ } else {
1116
+ const message = _typescript2.default.flattenDiagnosticMessageText(
1117
+ diagnostic.messageText,
1118
+ "\n"
1119
+ );
1120
+ diagnosticMessages.push(message);
1121
+ }
1122
+ });
1123
+ const diagnosticMessage = diagnosticMessages.join("\n");
1124
+ if (diagnosticMessage) {
1125
+ logger.error(
1126
+ "TSC",
1127
+ `Failed to emit declaration files.
1128
+
1129
+ ${diagnosticMessage}`
1130
+ );
1131
+ throw new Error("TypeScript compilation failed");
1132
+ }
1133
+ return fileMapping;
1134
+ }
1135
+ function emit(compilerOptions, tsconfig) {
1136
+ const cwd = process.cwd();
1137
+ const rawTsconfig = _bundlerequire.loadTsConfig.call(void 0, cwd, tsconfig);
1138
+ if (!rawTsconfig) {
1139
+ throw new Error(`Unable to find ${tsconfig || "tsconfig.json"} in ${cwd}`);
1140
+ }
1141
+ const declarationDir = _chunkTWFEYLU4js.ensureTempDeclarationDir.call(void 0, );
1142
+ const parsedTsconfig = _typescript2.default.parseJsonConfigFileContent(
1143
+ {
1144
+ ...rawTsconfig.data,
1145
+ compilerOptions: {
1146
+ ..._optionalChain([rawTsconfig, 'access', _16 => _16.data, 'optionalAccess', _17 => _17.compilerOptions]),
1147
+ ...compilerOptions,
1148
+ // Enable declaration emit and disable javascript emit
1149
+ noEmit: false,
1150
+ declaration: true,
1151
+ declarationMap: true,
1152
+ declarationDir,
1153
+ emitDeclarationOnly: true
1154
+ }
1155
+ },
1156
+ _typescript2.default.sys,
1157
+ tsconfig ? _path.dirname.call(void 0, tsconfig) : "./"
1158
+ );
1159
+ const options = parsedTsconfig.options;
1160
+ const host = _typescript2.default.createCompilerHost(options);
1161
+ const program = _typescript2.default.createProgram(
1162
+ parsedTsconfig.fileNames,
1163
+ options,
1164
+ host
1165
+ );
1166
+ const fileMapping = emitDtsFiles(program, host);
1167
+ return getExports(program, fileMapping);
1168
+ }
1169
+ function runTypeScriptCompiler(options) {
1170
+ try {
1171
+ const start = Date.now();
1172
+ const getDuration = () => {
1173
+ return `${Math.floor(Date.now() - start)}ms`;
1174
+ };
1175
+ logger.info("tsc", "Build start");
1176
+ const dtsOptions = options.experimentalDts;
1177
+ const exports = emit(dtsOptions.compilerOptions, options.tsconfig);
1178
+ logger.success("tsc", `\u26A1\uFE0F Build success in ${getDuration()}`);
1179
+ return exports;
1180
+ } catch (error) {
1181
+ _chunkJZ25TPTYjs.handleError.call(void 0, error);
1182
+ logger.error("tsc", "Build error");
1183
+ }
1184
+ }
1185
+
1186
+ // src/api-extractor.ts
1187
+
1188
+
1189
+ // src/exports.ts
1190
+
1191
+ function formatAggregationExports(exports, declarationDirPath) {
1192
+ const lines = exports.map(
1193
+ (declaration) => formatAggregationExport(declaration, declarationDirPath)
1194
+ ).filter(_chunkTWFEYLU4js.truthy);
1195
+ if (lines.length === 0) {
1196
+ lines.push("export {};");
1197
+ }
1198
+ return `${lines.join("\n")}
1199
+ `;
1200
+ }
1201
+ function formatAggregationExport(declaration, declarationDirPath) {
1202
+ const dest = _chunkTWFEYLU4js.replaceDtsWithJsExtensions.call(void 0,
1203
+ `./${_path2.default.posix.normalize(
1204
+ _chunkTWFEYLU4js.slash.call(void 0, _path2.default.relative(declarationDirPath, declaration.destFileName))
1205
+ )}`
1206
+ );
1207
+ if (declaration.kind === "module") {
1208
+ return "";
1209
+ } else if (declaration.kind === "named") {
1210
+ return [
1211
+ "export",
1212
+ declaration.isTypeOnly ? "type" : "",
1213
+ "{",
1214
+ declaration.name,
1215
+ declaration.name === declaration.alias ? "" : `as ${declaration.alias}`,
1216
+ "} from",
1217
+ `'${dest}';`
1218
+ ].filter(_chunkTWFEYLU4js.truthy).join(" ");
1219
+ } else {
1220
+ throw new Error("Unknown declaration");
1221
+ }
1222
+ }
1223
+ function formatDistributionExports(exports, fromFilePath, toFilePath) {
1224
+ let importPath = _chunkTWFEYLU4js.replaceDtsWithJsExtensions.call(void 0,
1225
+ _path2.default.posix.relative(
1226
+ _path2.default.posix.dirname(_path2.default.posix.normalize(_chunkTWFEYLU4js.slash.call(void 0, fromFilePath))),
1227
+ _path2.default.posix.normalize(_chunkTWFEYLU4js.slash.call(void 0, toFilePath))
1228
+ )
1229
+ );
1230
+ if (!/^\.+\//.test(importPath)) {
1231
+ importPath = `./${importPath}`;
1232
+ }
1233
+ const seen = {
1234
+ named: /* @__PURE__ */ new Set(),
1235
+ module: /* @__PURE__ */ new Set()
1236
+ };
1237
+ const lines = exports.filter((declaration) => {
1238
+ if (declaration.kind === "module") {
1239
+ if (seen.module.has(declaration.moduleName)) {
1240
+ return false;
1241
+ }
1242
+ seen.module.add(declaration.moduleName);
1243
+ return true;
1244
+ } else if (declaration.kind === "named") {
1245
+ if (seen.named.has(declaration.name)) {
1246
+ return false;
1247
+ }
1248
+ seen.named.add(declaration.name);
1249
+ return true;
1250
+ } else {
1251
+ return false;
1252
+ }
1253
+ }).map((declaration) => formatDistributionExport(declaration, importPath)).filter(_chunkTWFEYLU4js.truthy);
1254
+ if (lines.length === 0) {
1255
+ lines.push("export {};");
1256
+ }
1257
+ return `${lines.join("\n")}
1258
+ `;
1259
+ }
1260
+ function formatDistributionExport(declaration, dest) {
1261
+ if (declaration.kind === "named") {
1262
+ return [
1263
+ "export",
1264
+ declaration.isTypeOnly ? "type" : "",
1265
+ "{",
1266
+ declaration.alias,
1267
+ declaration.name === declaration.alias ? "" : `as ${declaration.name}`,
1268
+ "} from",
1269
+ `'${dest}';`
1270
+ ].filter(_chunkTWFEYLU4js.truthy).join(" ");
1271
+ } else if (declaration.kind === "module") {
1272
+ return `export * from '${declaration.moduleName}';`;
1273
+ }
1274
+ return "";
1275
+ }
1276
+
1277
+ // src/api-extractor.ts
1278
+ var logger2 = _chunkVGC3FXLUjs.createLogger.call(void 0, );
1279
+ function rollupDtsFile(inputFilePath, outputFilePath, tsconfigFilePath) {
1280
+ const cwd = process.cwd();
1281
+ const packageJsonFullPath = _path2.default.join(cwd, "package.json");
1282
+ const configObject = {
1283
+ mainEntryPointFilePath: inputFilePath,
1284
+ apiReport: {
1285
+ enabled: false,
1286
+ // `reportFileName` is not been used. It's just to fit the requirement of API Extractor.
1287
+ reportFileName: "tsup-report.api.md"
1288
+ },
1289
+ docModel: { enabled: false },
1290
+ dtsRollup: {
1291
+ enabled: true,
1292
+ untrimmedFilePath: outputFilePath
1293
+ },
1294
+ tsdocMetadata: { enabled: false },
1295
+ compiler: {
1296
+ tsconfigFilePath
1297
+ },
1298
+ projectFolder: cwd,
1299
+ newlineKind: "lf"
1300
+ };
1301
+ const prepareOptions = {
1302
+ configObject,
1303
+ configObjectFullPath: void 0,
1304
+ packageJsonFullPath
1305
+ };
1306
+ const imported = _chunkTWFEYLU4js.getApiExtractor.call(void 0, );
1307
+ if (!imported) {
1308
+ throw new Error(
1309
+ `@microsoft/api-extractor is not installed. Please install it first.`
1310
+ );
1311
+ }
1312
+ const { ExtractorConfig, Extractor } = imported;
1313
+ const extractorConfig = ExtractorConfig.prepare(prepareOptions);
1314
+ const extractorResult = Extractor.invoke(extractorConfig, {
1315
+ // Equivalent to the "--local" command-line parameter
1316
+ localBuild: true,
1317
+ // Equivalent to the "--verbose" command-line parameter
1318
+ showVerboseMessages: true
1319
+ });
1320
+ if (!extractorResult.succeeded) {
1321
+ throw new Error(
1322
+ `API Extractor completed with ${extractorResult.errorCount} errors and ${extractorResult.warningCount} warnings when processing ${inputFilePath}`
1323
+ );
1324
+ }
1325
+ }
1326
+ async function rollupDtsFiles(options, exports, format) {
1327
+ if (!options.experimentalDts || !_optionalChain([options, 'access', _18 => _18.experimentalDts, 'optionalAccess', _19 => _19.entry])) {
1328
+ return;
1329
+ }
1330
+ const declarationDir = _chunkTWFEYLU4js.ensureTempDeclarationDir.call(void 0, );
1331
+ const outDir = options.outDir || "dist";
1332
+ const pkg = await _chunkVGC3FXLUjs.loadPkg.call(void 0, process.cwd());
1333
+ const dtsExtension = _chunkTWFEYLU4js.defaultOutExtension.call(void 0, { format, pkgType: pkg.type }).dts;
1334
+ const tsconfig = options.tsconfig || "tsconfig.json";
1335
+ let dtsInputFilePath = _path2.default.join(
1336
+ declarationDir,
1337
+ `_tsup-dts-aggregation${dtsExtension}`
1338
+ );
1339
+ dtsInputFilePath = dtsInputFilePath.replace(/\.d\.mts$/, ".dmts.d.ts").replace(/\.d\.cts$/, ".dcts.d.ts");
1340
+ const dtsOutputFilePath = _path2.default.join(outDir, `_tsup-dts-rollup${dtsExtension}`);
1341
+ _chunkTWFEYLU4js.writeFileSync.call(void 0,
1342
+ dtsInputFilePath,
1343
+ formatAggregationExports(exports, declarationDir)
1344
+ );
1345
+ rollupDtsFile(dtsInputFilePath, dtsOutputFilePath, tsconfig);
1346
+ for (let [out, sourceFileName] of Object.entries(
1347
+ options.experimentalDts.entry
1348
+ )) {
1349
+ sourceFileName = _chunkTWFEYLU4js.toAbsolutePath.call(void 0, sourceFileName);
1350
+ const outFileName = _path2.default.join(outDir, out + dtsExtension);
1351
+ const currentExports = exports.filter(
1352
+ (declaration) => declaration.sourceFileName === sourceFileName
1353
+ );
1354
+ _chunkTWFEYLU4js.writeFileSync.call(void 0,
1355
+ outFileName,
1356
+ formatDistributionExports(currentExports, outFileName, dtsOutputFilePath)
1357
+ );
1358
+ }
1359
+ }
1360
+ async function cleanDtsFiles(options) {
1361
+ if (options.clean) {
1362
+ await _chunkTWFEYLU4js.removeFiles.call(void 0, ["**/*.d.{ts,mts,cts}"], options.outDir);
1363
+ }
1364
+ }
1365
+ async function runDtsRollup(options, exports) {
1366
+ try {
1367
+ const start = Date.now();
1368
+ const getDuration = () => {
1369
+ return `${Math.floor(Date.now() - start)}ms`;
1370
+ };
1371
+ logger2.info("dts", "Build start");
1372
+ if (!exports) {
1373
+ throw new Error("Unexpected internal error: dts exports is not define");
1374
+ }
1375
+ await cleanDtsFiles(options);
1376
+ for (const format of options.format) {
1377
+ await rollupDtsFiles(options, exports, format);
1378
+ }
1379
+ logger2.success("dts", `\u26A1\uFE0F Build success in ${getDuration()}`);
1380
+ } catch (error) {
1381
+ _chunkJZ25TPTYjs.handleError.call(void 0, error);
1382
+ logger2.error("dts", "Build error");
1383
+ }
1384
+ }
1385
+
1386
+ // src/plugins/cjs-interop.ts
1387
+ var cjsInterop = () => {
1388
+ return {
1389
+ name: "cjs-interop",
1390
+ renderChunk(code, info) {
1391
+ if (!this.options.cjsInterop || this.format !== "cjs" || info.type !== "chunk" || !/\.(js|cjs)$/.test(info.path) || !info.entryPoint || _optionalChain([info, 'access', _20 => _20.exports, 'optionalAccess', _21 => _21.length]) !== 1 || info.exports[0] !== "default") {
1392
+ return;
1393
+ }
1394
+ return {
1395
+ code: `${code}
1396
+ module.exports = exports.default;
1397
+ `,
1398
+ map: info.map
1399
+ };
1400
+ }
1401
+ };
1402
+ };
1403
+
1404
+ // src/index.ts
1405
+ var defineConfig = (options) => options;
1406
+ var isTaskkillCmdProcessNotFoundError = (err) => {
1407
+ return process.platform === "win32" && "cmd" in err && "code" in err && typeof err.cmd === "string" && err.cmd.startsWith("taskkill") && err.code === 128;
1408
+ };
1409
+ var killProcess = ({ pid, signal }) => new Promise((resolve, reject) => {
1410
+ _treekill2.default.call(void 0, pid, signal, (err) => {
1411
+ if (err && !isTaskkillCmdProcessNotFoundError(err)) return reject(err);
1412
+ resolve();
1413
+ });
1414
+ });
1415
+ var normalizeOptions = async (logger3, optionsFromConfigFile, optionsOverride) => {
1416
+ const _options = {
1417
+ ...optionsFromConfigFile,
1418
+ ...optionsOverride
1419
+ };
1420
+ const options = {
1421
+ outDir: "dist",
1422
+ removeNodeProtocol: true,
1423
+ ..._options,
1424
+ format: typeof _options.format === "string" ? [_options.format] : _options.format || ["cjs"],
1425
+ dts: typeof _options.dts === "boolean" ? _options.dts ? {} : void 0 : typeof _options.dts === "string" ? { entry: _options.dts } : _options.dts,
1426
+ experimentalDts: await _chunkTWFEYLU4js.resolveInitialExperimentalDtsConfig.call(void 0,
1427
+ _options.experimentalDts
1428
+ )
1429
+ };
1430
+ _chunkVGC3FXLUjs.setSilent.call(void 0, options.silent);
1431
+ const entry = options.entry || options.entryPoints;
1432
+ if (!entry || Object.keys(entry).length === 0) {
1433
+ throw new (0, _chunkJZ25TPTYjs.PrettyError)(`No input files, try "tsup <your-file>" instead`);
1434
+ }
1435
+ if (Array.isArray(entry)) {
1436
+ options.entry = await _tinyglobby.glob.call(void 0, entry);
1437
+ if (!options.entry || options.entry.length === 0) {
1438
+ throw new (0, _chunkJZ25TPTYjs.PrettyError)(`Cannot find ${entry}`);
1439
+ } else {
1440
+ logger3.info("CLI", `Building entry: ${options.entry.join(", ")}`);
1441
+ }
1442
+ } else {
1443
+ Object.keys(entry).forEach((alias) => {
1444
+ const filename = entry[alias];
1445
+ if (!_fs2.default.existsSync(filename)) {
1446
+ throw new (0, _chunkJZ25TPTYjs.PrettyError)(`Cannot find ${alias}: ${filename}`);
1447
+ }
1448
+ });
1449
+ options.entry = entry;
1450
+ logger3.info("CLI", `Building entry: ${JSON.stringify(entry)}`);
1451
+ }
1452
+ const tsconfig = _bundlerequire.loadTsConfig.call(void 0, process.cwd(), options.tsconfig);
1453
+ if (tsconfig) {
1454
+ logger3.info(
1455
+ "CLI",
1456
+ `Using tsconfig: ${_path2.default.relative(process.cwd(), tsconfig.path)}`
1457
+ );
1458
+ options.tsconfig = tsconfig.path;
1459
+ options.tsconfigResolvePaths = _optionalChain([tsconfig, 'access', _22 => _22.data, 'optionalAccess', _23 => _23.compilerOptions, 'optionalAccess', _24 => _24.paths]) || {};
1460
+ options.tsconfigDecoratorMetadata = _optionalChain([tsconfig, 'access', _25 => _25.data, 'optionalAccess', _26 => _26.compilerOptions, 'optionalAccess', _27 => _27.emitDecoratorMetadata]);
1461
+ if (options.dts) {
1462
+ options.dts.compilerOptions = {
1463
+ ...tsconfig.data.compilerOptions || {},
1464
+ ...options.dts.compilerOptions || {}
1465
+ };
1466
+ }
1467
+ if (options.experimentalDts) {
1468
+ options.experimentalDts = await _chunkTWFEYLU4js.resolveExperimentalDtsConfig.call(void 0,
1469
+ options,
1470
+ tsconfig
1471
+ );
1472
+ }
1473
+ if (!options.target) {
1474
+ options.target = _optionalChain([tsconfig, 'access', _28 => _28.data, 'optionalAccess', _29 => _29.compilerOptions, 'optionalAccess', _30 => _30.target, 'optionalAccess', _31 => _31.toLowerCase, 'call', _32 => _32()]);
1475
+ }
1476
+ } else if (options.tsconfig) {
1477
+ throw new (0, _chunkJZ25TPTYjs.PrettyError)(`Cannot find tsconfig: ${options.tsconfig}`);
1478
+ }
1479
+ if (!options.target) {
1480
+ options.target = "node16";
1481
+ }
1482
+ return options;
1483
+ };
1484
+ async function build(_options) {
1485
+ const config = _options.config === false ? {} : await _chunkVGC3FXLUjs.loadTsupConfig.call(void 0,
1486
+ process.cwd(),
1487
+ _options.config === true ? void 0 : _options.config
1488
+ );
1489
+ const configData = typeof config.data === "function" ? await config.data(_options) : config.data;
1490
+ await Promise.all(
1491
+ [...Array.isArray(configData) ? configData : [configData]].map(
1492
+ async (item) => {
1493
+ const logger3 = _chunkVGC3FXLUjs.createLogger.call(void 0, _optionalChain([item, 'optionalAccess', _33 => _33.name]));
1494
+ const options = await normalizeOptions(logger3, item, _options);
1495
+ logger3.info("CLI", `tsup v${_chunkBYH4XDRHjs.version}`);
1496
+ if (config.path) {
1497
+ logger3.info("CLI", `Using tsup config: ${config.path}`);
1498
+ }
1499
+ if (options.watch) {
1500
+ logger3.info("CLI", "Running in watch mode");
1501
+ }
1502
+ const experimentalDtsTask = async () => {
1503
+ if (!options.dts && options.experimentalDts) {
1504
+ const exports = runTypeScriptCompiler(options);
1505
+ await runDtsRollup(options, exports);
1506
+ }
1507
+ };
1508
+ const dtsTask = async () => {
1509
+ if (options.dts && options.experimentalDts) {
1510
+ throw new Error(
1511
+ "You can't use both `dts` and `experimentalDts` at the same time"
1512
+ );
1513
+ }
1514
+ await experimentalDtsTask();
1515
+ if (options.dts) {
1516
+ await new Promise((resolve, reject) => {
1517
+ const worker = new (0, _worker_threads.Worker)(_path2.default.join(__dirname, "./rollup.js"));
1518
+ const terminateWorker = () => {
1519
+ if (options.watch) return;
1520
+ worker.terminate();
1521
+ };
1522
+ worker.postMessage({
1523
+ configName: _optionalChain([item, 'optionalAccess', _34 => _34.name]),
1524
+ options: {
1525
+ ...options,
1526
+ // functions cannot be cloned
1527
+ injectStyle: typeof options.injectStyle === "function" ? void 0 : options.injectStyle,
1528
+ banner: void 0,
1529
+ footer: void 0,
1530
+ esbuildPlugins: void 0,
1531
+ esbuildOptions: void 0,
1532
+ plugins: void 0,
1533
+ treeshake: void 0,
1534
+ onSuccess: void 0,
1535
+ outExtension: void 0
1536
+ }
1537
+ });
1538
+ worker.on("message", (data) => {
1539
+ if (data === "error") {
1540
+ terminateWorker();
1541
+ reject(new Error("error occurred in dts build"));
1542
+ } else if (data === "success") {
1543
+ terminateWorker();
1544
+ resolve();
1545
+ } else {
1546
+ const { type, text } = data;
1547
+ if (type === "log") {
1548
+ console.log(text);
1549
+ } else if (type === "error") {
1550
+ console.error(text);
1551
+ }
1552
+ }
1553
+ });
1554
+ });
1555
+ }
1556
+ };
1557
+ const mainTasks = async () => {
1558
+ if (!_optionalChain([options, 'access', _35 => _35.dts, 'optionalAccess', _36 => _36.only])) {
1559
+ let onSuccessProcess;
1560
+ let onSuccessCleanup;
1561
+ const buildDependencies = /* @__PURE__ */ new Set();
1562
+ let depsHash = await _chunkVGC3FXLUjs.getAllDepsHash.call(void 0, process.cwd());
1563
+ const doOnSuccessCleanup = async () => {
1564
+ if (onSuccessProcess) {
1565
+ await killProcess({
1566
+ pid: onSuccessProcess.pid,
1567
+ signal: options.killSignal || "SIGTERM"
1568
+ });
1569
+ } else if (onSuccessCleanup) {
1570
+ await onSuccessCleanup();
1571
+ }
1572
+ onSuccessProcess = void 0;
1573
+ onSuccessCleanup = void 0;
1574
+ };
1575
+ const debouncedBuildAll = _chunkTWFEYLU4js.debouncePromise.call(void 0,
1576
+ () => {
1577
+ return buildAll();
1578
+ },
1579
+ 100,
1580
+ _chunkJZ25TPTYjs.handleError
1581
+ );
1582
+ const buildAll = async () => {
1583
+ await doOnSuccessCleanup();
1584
+ const previousBuildDependencies = new Set(buildDependencies);
1585
+ buildDependencies.clear();
1586
+ if (options.clean) {
1587
+ const extraPatterns = Array.isArray(options.clean) ? options.clean : [];
1588
+ if (options.dts || options.experimentalDts) {
1589
+ extraPatterns.unshift("!**/*.d.{ts,cts,mts}");
1590
+ }
1591
+ await _chunkTWFEYLU4js.removeFiles.call(void 0, ["**/*", ...extraPatterns], options.outDir);
1592
+ logger3.info("CLI", "Cleaning output folder");
1593
+ }
1594
+ const css = /* @__PURE__ */ new Map();
1595
+ await Promise.all([
1596
+ ...options.format.map(async (format, index) => {
1597
+ const pluginContainer = new PluginContainer([
1598
+ shebang(),
1599
+ ...options.plugins || [],
1600
+ treeShakingPlugin({
1601
+ treeshake: options.treeshake,
1602
+ name: options.globalName,
1603
+ silent: options.silent
1604
+ }),
1605
+ cjsSplitting(),
1606
+ cjsInterop(),
1607
+ swcTarget(),
1608
+ sizeReporter(),
1609
+ terserPlugin({
1610
+ minifyOptions: options.minify,
1611
+ format,
1612
+ terserOptions: options.terserOptions,
1613
+ globalName: options.globalName,
1614
+ logger: logger3
1615
+ })
1616
+ ]);
1617
+ await runEsbuild(options, {
1618
+ pluginContainer,
1619
+ format,
1620
+ css: index === 0 || options.injectStyle ? css : void 0,
1621
+ logger: logger3,
1622
+ buildDependencies
1623
+ }).catch((error) => {
1624
+ previousBuildDependencies.forEach(
1625
+ (v) => buildDependencies.add(v)
1626
+ );
1627
+ throw error;
1628
+ });
1629
+ })
1630
+ ]);
1631
+ if (options.onSuccess) {
1632
+ if (typeof options.onSuccess === "function") {
1633
+ onSuccessCleanup = await options.onSuccess();
1634
+ } else {
1635
+ onSuccessProcess = _tinyexec.exec.call(void 0, options.onSuccess, [], {
1636
+ nodeOptions: { shell: true, stdio: "inherit" }
1637
+ });
1638
+ _optionalChain([onSuccessProcess, 'access', _37 => _37.process, 'optionalAccess', _38 => _38.on, 'call', _39 => _39("exit", (code) => {
1639
+ if (code && code !== 0) {
1640
+ process.exitCode = code;
1641
+ }
1642
+ })]);
1643
+ }
1644
+ }
1645
+ };
1646
+ const startWatcher = async () => {
1647
+ if (!options.watch) return;
1648
+ const { watch } = await Promise.resolve().then(() => _interopRequireWildcard(require("chokidar")));
1649
+ const customIgnores = options.ignoreWatch ? Array.isArray(options.ignoreWatch) ? options.ignoreWatch : [options.ignoreWatch] : [];
1650
+ const ignored = [
1651
+ "**/{.git,node_modules}/**",
1652
+ options.outDir,
1653
+ ...customIgnores
1654
+ ];
1655
+ const watchPaths = typeof options.watch === "boolean" ? "." : Array.isArray(options.watch) ? options.watch.filter((path12) => typeof path12 === "string") : options.watch;
1656
+ logger3.info(
1657
+ "CLI",
1658
+ `Watching for changes in ${Array.isArray(watchPaths) ? watchPaths.map((v) => `"${v}"`).join(" | ") : `"${watchPaths}"`}`
1659
+ );
1660
+ logger3.info(
1661
+ "CLI",
1662
+ `Ignoring changes in ${ignored.map((v) => `"${v}"`).join(" | ")}`
1663
+ );
1664
+ const watcher = watch(await _tinyglobby.glob.call(void 0, watchPaths), {
1665
+ ignoreInitial: true,
1666
+ ignorePermissionErrors: true,
1667
+ ignored: (p) => _tinyglobby.globSync.call(void 0, p, { ignore: ignored }).length === 0
1668
+ });
1669
+ watcher.on("all", async (type, file) => {
1670
+ file = _chunkTWFEYLU4js.slash.call(void 0, file);
1671
+ if (options.publicDir && isInPublicDir(options.publicDir, file)) {
1672
+ logger3.info("CLI", `Change in public dir: ${file}`);
1673
+ copyPublicDir(options.publicDir, options.outDir);
1674
+ return;
1675
+ }
1676
+ let shouldSkipChange = false;
1677
+ if (options.watch === true) {
1678
+ if (file === "package.json" && !buildDependencies.has(file)) {
1679
+ const currentHash = await _chunkVGC3FXLUjs.getAllDepsHash.call(void 0, process.cwd());
1680
+ shouldSkipChange = currentHash === depsHash;
1681
+ depsHash = currentHash;
1682
+ } else if (!buildDependencies.has(file)) {
1683
+ shouldSkipChange = true;
1684
+ }
1685
+ }
1686
+ if (shouldSkipChange) {
1687
+ return;
1688
+ }
1689
+ logger3.info("CLI", `Change detected: ${type} ${file}`);
1690
+ debouncedBuildAll();
1691
+ });
1692
+ };
1693
+ logger3.info("CLI", `Target: ${options.target}`);
1694
+ await buildAll();
1695
+ copyPublicDir(options.publicDir, options.outDir);
1696
+ startWatcher();
1697
+ }
1698
+ };
1699
+ await Promise.all([dtsTask(), mainTasks()]);
1700
+ }
1701
+ )
1702
+ );
1703
+ }
1704
+
1705
+
1706
+
1707
+ exports.build = build; exports.defineConfig = defineConfig;