@storm-software/esbuild 0.4.1 → 0.14.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (89) hide show
  1. package/README.md +1 -1
  2. package/dist/build.cjs +15 -11
  3. package/dist/build.d.cts +3 -3
  4. package/dist/build.d.ts +3 -3
  5. package/dist/build.js +14 -10
  6. package/dist/{chunk-WCQVDF3K.js → chunk-3GQAWCBQ.js} +0 -1
  7. package/dist/chunk-4JLYXTKD.cjs +26 -0
  8. package/dist/chunk-5I2MGPRN.cjs +919 -0
  9. package/dist/{chunk-CMWXE5MF.js → chunk-7KR3YBS6.js} +5 -3
  10. package/dist/chunk-7MDMXJ5V.js +26 -0
  11. package/dist/{chunk-WGEGR3DF.cjs → chunk-BGYQAVKQ.cjs} +0 -1
  12. package/dist/{chunk-J34FQYKV.cjs → chunk-CGFDQ5AJ.cjs} +8 -5
  13. package/dist/{chunk-TTHABTDU.js → chunk-DAGDNKO5.js} +8 -6
  14. package/dist/{chunk-DFGHPRBD.cjs → chunk-EZGTDCYM.cjs} +6 -6
  15. package/dist/chunk-GGNOJ77I.js +0 -0
  16. package/dist/{chunk-YQBU3FSL.js → chunk-GWG4HOQ6.js} +4 -4
  17. package/dist/chunk-HQGUIF4U.js +537 -0
  18. package/dist/{chunk-X5TLV7MF.js → chunk-KE5DL2BG.js} +11 -6
  19. package/dist/{chunk-KJ7ZHAFS.js → chunk-KOK4WCHS.js} +52 -28
  20. package/dist/chunk-LVWQSCJM.cjs +26 -0
  21. package/dist/chunk-LYDEMC26.js +23 -0
  22. package/dist/chunk-MAMLS55E.js +582 -0
  23. package/dist/chunk-NVWDQVN6.js +21 -0
  24. package/dist/chunk-PQ6YIJ72.cjs +136 -0
  25. package/dist/{chunk-BF5W6GVP.cjs → chunk-RMB62XEL.cjs} +10 -8
  26. package/dist/chunk-S6M44SSZ.cjs +60 -0
  27. package/dist/chunk-SFZRYJZ2.cjs +1 -0
  28. package/dist/chunk-T5272PC2.js +60 -0
  29. package/dist/chunk-TP5EOMRD.cjs +21 -0
  30. package/dist/chunk-VBINBV4Z.cjs +537 -0
  31. package/dist/chunk-VLP3P6HF.js +919 -0
  32. package/dist/{chunk-KVBDKVBU.cjs → chunk-VZBOWHCM.cjs} +9 -7
  33. package/dist/chunk-WRBUO7H6.cjs +23 -0
  34. package/dist/chunk-WYMD6YG2.cjs +582 -0
  35. package/dist/{chunk-437F3SFI.js → chunk-YNQ45EAM.js} +7 -4
  36. package/dist/clean.cjs +9 -0
  37. package/dist/clean.d.cts +1194 -0
  38. package/dist/clean.d.ts +1194 -0
  39. package/dist/clean.js +9 -0
  40. package/dist/config.cjs +14 -4
  41. package/dist/config.d.cts +8 -13
  42. package/dist/config.d.ts +8 -13
  43. package/dist/config.js +15 -5
  44. package/dist/esbuild.cjs +1185 -0
  45. package/dist/index.cjs +21 -12
  46. package/dist/index.d.cts +7 -5
  47. package/dist/index.d.ts +7 -5
  48. package/dist/index.js +22 -13
  49. package/dist/types.cjs +1 -2
  50. package/dist/types.d.cts +84 -1177
  51. package/dist/types.d.ts +84 -1177
  52. package/dist/types.js +1 -2
  53. package/package.json +1 -222
  54. package/dist/build.cjs.map +0 -1
  55. package/dist/build.js.map +0 -1
  56. package/dist/chunk-263L44RM.cjs +0 -112
  57. package/dist/chunk-263L44RM.cjs.map +0 -1
  58. package/dist/chunk-437F3SFI.js.map +0 -1
  59. package/dist/chunk-BF5W6GVP.cjs.map +0 -1
  60. package/dist/chunk-CMEDJ4L4.js +0 -352
  61. package/dist/chunk-CMEDJ4L4.js.map +0 -1
  62. package/dist/chunk-CMWXE5MF.js.map +0 -1
  63. package/dist/chunk-D5PRB2E2.cjs +0 -40
  64. package/dist/chunk-D5PRB2E2.cjs.map +0 -1
  65. package/dist/chunk-DFGHPRBD.cjs.map +0 -1
  66. package/dist/chunk-DRRPNILS.js +0 -40
  67. package/dist/chunk-DRRPNILS.js.map +0 -1
  68. package/dist/chunk-J34FQYKV.cjs.map +0 -1
  69. package/dist/chunk-KJ7ZHAFS.js.map +0 -1
  70. package/dist/chunk-KVBDKVBU.cjs.map +0 -1
  71. package/dist/chunk-MUYXFAKB.cjs +0 -1
  72. package/dist/chunk-MUYXFAKB.cjs.map +0 -1
  73. package/dist/chunk-MVLEDP7K.cjs +0 -21
  74. package/dist/chunk-MVLEDP7K.cjs.map +0 -1
  75. package/dist/chunk-PBHOTQGA.cjs +0 -352
  76. package/dist/chunk-PBHOTQGA.cjs.map +0 -1
  77. package/dist/chunk-QNDLJ2W7.js +0 -1
  78. package/dist/chunk-QNDLJ2W7.js.map +0 -1
  79. package/dist/chunk-TTHABTDU.js.map +0 -1
  80. package/dist/chunk-WCQVDF3K.js.map +0 -1
  81. package/dist/chunk-WGEGR3DF.cjs.map +0 -1
  82. package/dist/chunk-X5TLV7MF.js.map +0 -1
  83. package/dist/chunk-YQBU3FSL.js.map +0 -1
  84. package/dist/config.cjs.map +0 -1
  85. package/dist/config.js.map +0 -1
  86. package/dist/index.cjs.map +0 -1
  87. package/dist/index.js.map +0 -1
  88. package/dist/types.cjs.map +0 -1
  89. package/dist/types.js.map +0 -1
@@ -0,0 +1,1185 @@
1
+ #!/usr/bin/env node
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
9
+ var __copyProps = (to, from, except, desc) => {
10
+ if (from && typeof from === "object" || typeof from === "function") {
11
+ for (let key of __getOwnPropNames(from))
12
+ if (!__hasOwnProp.call(to, key) && key !== except)
13
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
14
+ }
15
+ return to;
16
+ };
17
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
18
+ // If the importer is in node compatibility mode or this is not an ESM
19
+ // file that has been converted to a CommonJS file using a Babel-
20
+ // compatible transform (i.e. "__esModule" has not been set), then set
21
+ // "default" to the CommonJS "module.exports" for node compatibility.
22
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
23
+ mod
24
+ ));
25
+
26
+ // bin/esbuild.ts
27
+ var import_create_storm_config2 = require("@storm-software/config-tools/create-storm-config");
28
+ var import_console3 = require("@storm-software/config-tools/logger/console");
29
+ var import_find_workspace_root2 = require("@storm-software/config-tools/utilities/find-workspace-root");
30
+ var import_process_handler = require("@storm-software/config-tools/utilities/process-handler");
31
+ var import_commander = require("commander");
32
+
33
+ // src/build.ts
34
+ var import_node3 = require("@humanfs/node");
35
+ var import_devkit = require("@nx/devkit");
36
+ var import_build_tools = require("@storm-software/build-tools");
37
+ var import_create_storm_config = require("@storm-software/config-tools/create-storm-config");
38
+ var import_console2 = require("@storm-software/config-tools/logger/console");
39
+ var import_get_log_level = require("@storm-software/config-tools/logger/get-log-level");
40
+ var import_correct_paths2 = require("@storm-software/config-tools/utilities/correct-paths");
41
+ var import_chokidar = require("chokidar");
42
+
43
+ // ../../node_modules/.pnpm/defu@6.1.4/node_modules/defu/dist/defu.mjs
44
+ function isPlainObject(value) {
45
+ if (value === null || typeof value !== "object") {
46
+ return false;
47
+ }
48
+ const prototype = Object.getPrototypeOf(value);
49
+ if (prototype !== null && prototype !== Object.prototype && Object.getPrototypeOf(prototype) !== null) {
50
+ return false;
51
+ }
52
+ if (Symbol.iterator in value) {
53
+ return false;
54
+ }
55
+ if (Symbol.toStringTag in value) {
56
+ return Object.prototype.toString.call(value) === "[object Module]";
57
+ }
58
+ return true;
59
+ }
60
+ __name(isPlainObject, "isPlainObject");
61
+ function _defu(baseObject, defaults, namespace = ".", merger) {
62
+ if (!isPlainObject(defaults)) {
63
+ return _defu(baseObject, {}, namespace, merger);
64
+ }
65
+ const object = Object.assign({}, defaults);
66
+ for (const key in baseObject) {
67
+ if (key === "__proto__" || key === "constructor") {
68
+ continue;
69
+ }
70
+ const value = baseObject[key];
71
+ if (value === null || value === void 0) {
72
+ continue;
73
+ }
74
+ if (merger && merger(object, key, value, namespace)) {
75
+ continue;
76
+ }
77
+ if (Array.isArray(value) && Array.isArray(object[key])) {
78
+ object[key] = [...value, ...object[key]];
79
+ } else if (isPlainObject(value) && isPlainObject(object[key])) {
80
+ object[key] = _defu(
81
+ value,
82
+ object[key],
83
+ (namespace ? `${namespace}.` : "") + key.toString(),
84
+ merger
85
+ );
86
+ } else {
87
+ object[key] = value;
88
+ }
89
+ }
90
+ return object;
91
+ }
92
+ __name(_defu, "_defu");
93
+ function createDefu(merger) {
94
+ return (...arguments_) => (
95
+ // eslint-disable-next-line unicorn/no-array-reduce
96
+ arguments_.reduce((p, c) => _defu(p, c, "", merger), {})
97
+ );
98
+ }
99
+ __name(createDefu, "createDefu");
100
+ var defu = createDefu();
101
+ var defuFn = createDefu((object, key, currentValue) => {
102
+ if (object[key] !== void 0 && typeof currentValue === "function") {
103
+ object[key] = currentValue(object[key]);
104
+ return true;
105
+ }
106
+ });
107
+ var defuArrayFn = createDefu((object, key, currentValue) => {
108
+ if (Array.isArray(object[key]) && typeof currentValue === "function") {
109
+ object[key] = currentValue(object[key]);
110
+ return true;
111
+ }
112
+ });
113
+
114
+ // src/build.ts
115
+ var import_es_toolkit = require("es-toolkit");
116
+ var import_compat = require("es-toolkit/compat");
117
+ var esbuild2 = __toESM(require("esbuild"), 1);
118
+ var import_globby = require("globby");
119
+ var import_find_workspace_root = require("nx/src/utils/find-workspace-root");
120
+
121
+ // src/base/renderer-engine.ts
122
+ var import_node_path2 = __toESM(require("path"), 1);
123
+ var import_source_map = require("source-map");
124
+
125
+ // src/utilities/output-file.ts
126
+ var import_node_fs = __toESM(require("fs"), 1);
127
+ var import_node_path = __toESM(require("path"), 1);
128
+ var outputFile = /* @__PURE__ */ __name(async (filepath, data, options) => {
129
+ await import_node_fs.default.promises.mkdir(import_node_path.default.dirname(filepath), {
130
+ recursive: true
131
+ });
132
+ await import_node_fs.default.promises.writeFile(filepath, data, options);
133
+ }, "outputFile");
134
+
135
+ // src/base/renderer-engine.ts
136
+ var parseSourceMap = /* @__PURE__ */ __name((map2) => {
137
+ return typeof map2 === "string" ? JSON.parse(map2) : map2;
138
+ }, "parseSourceMap");
139
+ var isJS = /* @__PURE__ */ __name((path5) => /\.(js|mjs|cjs)$/.test(path5), "isJS");
140
+ var isCSS = /* @__PURE__ */ __name((path5) => /\.css$/.test(path5), "isCSS");
141
+ var getSourcemapComment = /* @__PURE__ */ __name((inline, map2, filepath, isCssFile) => {
142
+ if (!map2) return "";
143
+ const prefix = isCssFile ? "/*" : "//";
144
+ const suffix = isCssFile ? " */" : "";
145
+ const url = inline ? `data:application/json;base64,${Buffer.from(typeof map2 === "string" ? map2 : JSON.stringify(map2)).toString("base64")}` : `${import_node_path2.default.basename(filepath)}.map`;
146
+ return `${prefix}# sourceMappingURL=${url}${suffix}`;
147
+ }, "getSourcemapComment");
148
+ var RendererEngine = class {
149
+ static {
150
+ __name(this, "RendererEngine");
151
+ }
152
+ #renderers;
153
+ #options;
154
+ constructor(renderers) {
155
+ this.#renderers = renderers;
156
+ }
157
+ setOptions(options) {
158
+ this.#options = options;
159
+ }
160
+ getOptions() {
161
+ if (!this.#options) {
162
+ throw new Error(`Renderer options is not set`);
163
+ }
164
+ return this.#options;
165
+ }
166
+ modifyEsbuildOptions(options) {
167
+ for (const renderer of this.#renderers) {
168
+ if (renderer.esbuildOptions) {
169
+ renderer.esbuildOptions.call(this.getOptions(), options);
170
+ }
171
+ }
172
+ }
173
+ async buildStarted() {
174
+ for (const renderer of this.#renderers) {
175
+ if (renderer.buildStart) {
176
+ await renderer.buildStart.call(this.getOptions());
177
+ }
178
+ }
179
+ }
180
+ async buildFinished({ outputFiles, metafile }) {
181
+ const files = outputFiles.filter((file) => !file.path.endsWith(".map")).map((file) => {
182
+ if (isJS(file.path) || isCSS(file.path)) {
183
+ let relativePath = import_node_path2.default.relative(this.getOptions().config.workspaceRoot, file.path);
184
+ if (!relativePath.startsWith("\\\\?\\")) {
185
+ relativePath = relativePath.replace(/\\/g, "/");
186
+ }
187
+ const meta = metafile?.outputs[relativePath];
188
+ return {
189
+ type: "chunk",
190
+ path: file.path,
191
+ code: file.text,
192
+ map: outputFiles.find((f) => f.path === `${file.path}.map`)?.text,
193
+ entryPoint: meta?.entryPoint,
194
+ exports: meta?.exports,
195
+ imports: meta?.imports
196
+ };
197
+ } else {
198
+ return {
199
+ type: "asset",
200
+ path: file.path,
201
+ contents: file.contents
202
+ };
203
+ }
204
+ });
205
+ const writtenFiles = [];
206
+ await Promise.all(files.map(async (info) => {
207
+ for (const renderer of this.#renderers) {
208
+ if (info.type === "chunk" && renderer.renderChunk) {
209
+ const result = await renderer.renderChunk.call(this.getOptions(), info.code, info);
210
+ if (result) {
211
+ info.code = result.code;
212
+ if (result.map) {
213
+ const originalConsumer = await new import_source_map.SourceMapConsumer(parseSourceMap(info.map));
214
+ const newConsumer = await new import_source_map.SourceMapConsumer(parseSourceMap(result.map));
215
+ const generator = import_source_map.SourceMapGenerator.fromSourceMap(newConsumer);
216
+ generator.applySourceMap(originalConsumer, info.path);
217
+ info.map = generator.toJSON();
218
+ originalConsumer.destroy();
219
+ newConsumer.destroy();
220
+ }
221
+ }
222
+ }
223
+ }
224
+ const inlineSourceMap = this.#options.sourcemap === "inline";
225
+ const contents = info.type === "chunk" ? info.code + getSourcemapComment(inlineSourceMap, info.map, info.path, isCSS(info.path)) : info.contents;
226
+ await outputFile(info.path, contents, {
227
+ mode: info.type === "chunk" ? info.mode : void 0
228
+ });
229
+ writtenFiles.push({
230
+ get name() {
231
+ return import_node_path2.default.relative(process.cwd(), info.path);
232
+ },
233
+ get size() {
234
+ return contents.length;
235
+ }
236
+ });
237
+ if (info.type === "chunk" && info.map && !inlineSourceMap) {
238
+ const map2 = typeof info.map === "string" ? JSON.parse(info.map) : info.map;
239
+ const outPath = `${info.path}.map`;
240
+ const contents2 = JSON.stringify(map2);
241
+ await outputFile(outPath, contents2);
242
+ writtenFiles.push({
243
+ get name() {
244
+ return import_node_path2.default.relative(process.cwd(), outPath);
245
+ },
246
+ get size() {
247
+ return contents2.length;
248
+ }
249
+ });
250
+ }
251
+ }));
252
+ for (const renderer of this.#renderers) {
253
+ if (renderer.buildEnd) {
254
+ await renderer.buildEnd.call(this.getOptions(), {
255
+ writtenFiles
256
+ });
257
+ }
258
+ }
259
+ }
260
+ };
261
+
262
+ // src/clean.ts
263
+ var import_node = require("@humanfs/node");
264
+ var import_console = require("@storm-software/config-tools/logger/console");
265
+ async function clean(name = "ESBuild", directory, config) {
266
+ (0, import_console.writeDebug)(` \u{1F9F9} Cleaning ${name} output path: ${directory}`, config);
267
+ const stopwatch = (0, import_console.getStopwatch)(`${name} output clean`);
268
+ await import_node.hfs.deleteAll(directory);
269
+ stopwatch();
270
+ }
271
+ __name(clean, "clean");
272
+
273
+ // src/config.ts
274
+ var import_get_out_extension = require("@storm-software/build-tools/utilities/get-out-extension");
275
+
276
+ // src/plugins/esm-split-code-to-cjs.ts
277
+ var esbuild = __toESM(require("esbuild"), 1);
278
+ var esmSplitCodeToCjsPlugin = /* @__PURE__ */ __name((options, resolvedOptions) => ({
279
+ name: "storm:esm-split-code-to-cjs",
280
+ setup(build4) {
281
+ build4.onEnd(async (result) => {
282
+ const outFiles = Object.keys(result.metafile?.outputs ?? {});
283
+ const jsFiles = outFiles.filter((f) => f.endsWith("js"));
284
+ await esbuild.build({
285
+ outdir: resolvedOptions.outdir,
286
+ entryPoints: jsFiles,
287
+ allowOverwrite: true,
288
+ format: "cjs",
289
+ logLevel: "error",
290
+ packages: "external"
291
+ });
292
+ });
293
+ }
294
+ }), "esmSplitCodeToCjsPlugin");
295
+
296
+ // src/plugins/fix-imports.ts
297
+ var fixImportsPlugin = /* @__PURE__ */ __name((options, resolvedOptions) => ({
298
+ name: "storm:fix-imports",
299
+ setup(build4) {
300
+ build4.onResolve({
301
+ filter: /^spdx-exceptions/
302
+ }, () => {
303
+ return {
304
+ path: require.resolve("spdx-exceptions")
305
+ };
306
+ });
307
+ build4.onResolve({
308
+ filter: /^spdx-license-ids/
309
+ }, () => {
310
+ return {
311
+ path: require.resolve("spdx-license-ids")
312
+ };
313
+ });
314
+ }
315
+ }), "fixImportsPlugin");
316
+
317
+ // src/plugins/native-node-module.ts
318
+ var import_node_path3 = require("path");
319
+ var nativeNodeModulesPlugin = /* @__PURE__ */ __name((options, resolvedOptions) => {
320
+ return {
321
+ name: "native-node-modules",
322
+ setup(build4) {
323
+ build4.onResolve({
324
+ filter: /\.node$/,
325
+ namespace: "file"
326
+ }, (args) => {
327
+ const resolvedId = require.resolve(args.path, {
328
+ paths: [
329
+ args.resolveDir
330
+ ]
331
+ });
332
+ if (resolvedId.endsWith(".node")) {
333
+ return {
334
+ path: resolvedId,
335
+ namespace: "node-file"
336
+ };
337
+ }
338
+ return {
339
+ path: resolvedId
340
+ };
341
+ });
342
+ build4.onLoad({
343
+ filter: /.*/,
344
+ namespace: "node-file"
345
+ }, (args) => {
346
+ return {
347
+ contents: `
348
+ import path from ${JSON.stringify(args.path)}
349
+ try { module.exports = require(path) }
350
+ catch {}
351
+ `,
352
+ resolveDir: (0, import_node_path3.dirname)(args.path)
353
+ };
354
+ });
355
+ build4.onResolve({
356
+ filter: /\.node$/,
357
+ namespace: "node-file"
358
+ }, (args) => ({
359
+ path: args.path,
360
+ namespace: "file"
361
+ }));
362
+ const opts = build4.initialOptions;
363
+ opts.loader = opts.loader || {};
364
+ opts.loader[".node"] = "file";
365
+ }
366
+ };
367
+ }, "nativeNodeModulesPlugin");
368
+
369
+ // src/plugins/node-protocol.ts
370
+ var nodeProtocolPlugin = /* @__PURE__ */ __name((options, resolvedOptions) => {
371
+ const nodeProtocol = "node:";
372
+ return {
373
+ name: "node-protocol-plugin",
374
+ setup({ onResolve }) {
375
+ onResolve({
376
+ filter: /^node:/
377
+ }, ({ path: path5 }) => ({
378
+ path: path5.slice(nodeProtocol.length),
379
+ external: true
380
+ }));
381
+ }
382
+ };
383
+ }, "nodeProtocolPlugin");
384
+
385
+ // src/plugins/on-error.ts
386
+ var import_config_tools = require("@storm-software/config-tools");
387
+ var onErrorPlugin = /* @__PURE__ */ __name((options, resolvedOptions) => ({
388
+ name: "storm:on-error",
389
+ setup(build4) {
390
+ build4.onEnd((result) => {
391
+ if (result.errors.length > 0 && process.env.WATCH !== "true") {
392
+ (0, import_config_tools.writeError)(`The following errors occurred during the build:
393
+ ${result.errors.map((error) => error.text).join("\n")}
394
+
395
+ `, resolvedOptions.config);
396
+ throw new Error("Storm esbuild process failed with errors.");
397
+ }
398
+ });
399
+ }
400
+ }), "onErrorPlugin");
401
+
402
+ // src/plugins/resolve-paths.ts
403
+ var import_correct_paths = require("@storm-software/config-tools/utilities/correct-paths");
404
+ var import_node_path4 = __toESM(require("path"), 1);
405
+ function resolvePathsConfig(options, cwd) {
406
+ if (options?.compilerOptions?.paths) {
407
+ const paths = Object.entries(options.compilerOptions.paths);
408
+ const resolvedPaths = paths.map(([key, paths2]) => {
409
+ return [
410
+ key,
411
+ paths2.map((v) => import_node_path4.default.resolve(cwd, v))
412
+ ];
413
+ });
414
+ return Object.fromEntries(resolvedPaths);
415
+ }
416
+ if (options.extends) {
417
+ const extendsPath = import_node_path4.default.resolve(cwd, options.extends);
418
+ const extendsDir = import_node_path4.default.dirname(extendsPath);
419
+ const extendsConfig = require(extendsPath);
420
+ return resolvePathsConfig(extendsConfig, extendsDir);
421
+ }
422
+ return [];
423
+ }
424
+ __name(resolvePathsConfig, "resolvePathsConfig");
425
+ var resolvePathsPlugin = /* @__PURE__ */ __name((options, resolvedOptions) => ({
426
+ name: "storm:resolve-paths",
427
+ setup(build4) {
428
+ const parentTsConfig = build4.initialOptions.tsconfig ? require((0, import_correct_paths.joinPaths)(resolvedOptions.config.workspaceRoot, build4.initialOptions.tsconfig)) : require((0, import_correct_paths.joinPaths)(resolvedOptions.config.workspaceRoot, "tsconfig.json"));
429
+ const resolvedTsPaths = resolvePathsConfig(parentTsConfig, options.projectRoot);
430
+ const packagesRegex = new RegExp(`^(${Object.keys(resolvedTsPaths).join("|")})$`);
431
+ build4.onResolve({
432
+ filter: packagesRegex
433
+ }, (args) => {
434
+ if (build4.initialOptions.external?.includes(args.path)) {
435
+ return {
436
+ path: args.path,
437
+ external: true
438
+ };
439
+ }
440
+ return {
441
+ path: `${resolvedTsPaths[args.path][0]}/index.ts`
442
+ };
443
+ });
444
+ }
445
+ }), "resolvePathsPlugin");
446
+
447
+ // src/plugins/tsc.ts
448
+ var import_node2 = require("@humanfs/node");
449
+ var import_api_extractor = require("@microsoft/api-extractor");
450
+ var import_config_tools2 = require("@storm-software/config-tools");
451
+ function bundleTypeDefinitions(filename, outfile, externals, options) {
452
+ const { dependencies, peerDependencies, devDependencies } = require((0, import_config_tools2.joinPaths)(options.projectRoot, "package.json"));
453
+ const dependenciesKeys = Object.keys(dependencies ?? {}).flatMap((p) => [
454
+ p,
455
+ getTypeDependencyPackageName(p)
456
+ ]);
457
+ const peerDependenciesKeys = Object.keys(peerDependencies ?? {}).flatMap((p) => [
458
+ p,
459
+ getTypeDependencyPackageName(p)
460
+ ]);
461
+ const devDependenciesKeys = Object.keys(devDependencies ?? {}).flatMap((p) => [
462
+ p,
463
+ getTypeDependencyPackageName(p)
464
+ ]);
465
+ const includeDeps = devDependenciesKeys;
466
+ const excludeDeps = /* @__PURE__ */ new Set([
467
+ ...dependenciesKeys,
468
+ ...peerDependenciesKeys,
469
+ ...externals
470
+ ]);
471
+ const bundledPackages = includeDeps.filter((dep) => !excludeDeps.has(dep));
472
+ const extractorConfig = import_api_extractor.ExtractorConfig.prepare({
473
+ configObject: {
474
+ projectFolder: options.projectRoot,
475
+ mainEntryPointFilePath: filename,
476
+ bundledPackages,
477
+ compiler: {
478
+ tsconfigFilePath: options.tsconfig,
479
+ overrideTsconfig: {
480
+ compilerOptions: {
481
+ paths: {}
482
+ // bug with api extract + paths
483
+ }
484
+ }
485
+ },
486
+ dtsRollup: {
487
+ enabled: true,
488
+ untrimmedFilePath: (0, import_config_tools2.joinPaths)(options.outdir, `${outfile}.d.ts`)
489
+ },
490
+ tsdocMetadata: {
491
+ enabled: false
492
+ }
493
+ },
494
+ packageJsonFullPath: (0, import_config_tools2.joinPaths)(options.projectRoot, "package.json"),
495
+ configObjectFullPath: void 0
496
+ });
497
+ const extractorResult = import_api_extractor.Extractor.invoke(extractorConfig, {
498
+ showVerboseMessages: true,
499
+ localBuild: true
500
+ });
501
+ if (extractorResult.succeeded === false) {
502
+ (0, import_config_tools2.writeError)(`API Extractor completed with ${extractorResult.errorCount} ${extractorResult.errorCount === 1 ? "error" : "errors"}`);
503
+ throw new Error("API Extractor completed with errors");
504
+ }
505
+ }
506
+ __name(bundleTypeDefinitions, "bundleTypeDefinitions");
507
+ var tscPlugin = /* @__PURE__ */ __name((options, resolvedOptions) => ({
508
+ name: "storm:tsc",
509
+ setup(build4) {
510
+ if (options.emitTypes === false) {
511
+ return;
512
+ }
513
+ build4.onStart(async () => {
514
+ if (process.env.WATCH !== "true" && process.env.DEV !== "true") {
515
+ await (0, import_config_tools2.run)(resolvedOptions.config, `pnpm exec tsc --project ${resolvedOptions.tsconfig}`, resolvedOptions.config.workspaceRoot);
516
+ }
517
+ if (resolvedOptions.bundle && resolvedOptions.entryPoints && resolvedOptions.entryPoints.length > 0 && resolvedOptions.entryPoints[0] && resolvedOptions.entryPoints[0].endsWith(".ts")) {
518
+ const sourceRoot = resolvedOptions.sourceRoot.replaceAll(resolvedOptions.projectRoot, "");
519
+ const typeOutDir = resolvedOptions.outdir;
520
+ const entryPoint = resolvedOptions.entryPoints[0].replace(sourceRoot, "").replace(/\.ts$/, "");
521
+ const bundlePath = (0, import_config_tools2.joinPaths)(resolvedOptions.outdir, entryPoint);
522
+ let dtsPath;
523
+ if (await import_node2.hfs.isFile((0, import_config_tools2.joinPaths)(resolvedOptions.config.workspaceRoot, typeOutDir, `${entryPoint}.d.ts`))) {
524
+ dtsPath = (0, import_config_tools2.joinPaths)(resolvedOptions.config.workspaceRoot, typeOutDir, `${entryPoint}.d.ts`);
525
+ } else if (await import_node2.hfs.isFile((0, import_config_tools2.joinPaths)(resolvedOptions.config.workspaceRoot, typeOutDir, `${entryPoint.replace(/^src\//, "")}.d.ts`))) {
526
+ dtsPath = (0, import_config_tools2.joinPaths)(resolvedOptions.config.workspaceRoot, typeOutDir, `${entryPoint.replace(/^src\//, "")}.d.ts`);
527
+ }
528
+ const ext = resolvedOptions.outExtension.dts || resolvedOptions.format === "esm" ? "d.mts" : "d.ts";
529
+ if (process.env.WATCH !== "true" && process.env.DEV !== "true") {
530
+ bundleTypeDefinitions(dtsPath, bundlePath, resolvedOptions.external ?? [], resolvedOptions);
531
+ const dtsContents = await import_node2.hfs.text(`${bundlePath}.d.ts`);
532
+ await import_node2.hfs.write(`${bundlePath}.${ext}`, dtsContents);
533
+ } else {
534
+ await import_node2.hfs.write(`${bundlePath}.${ext}`, `export * from './${entryPoint}'`);
535
+ }
536
+ }
537
+ });
538
+ }
539
+ }), "tscPlugin");
540
+ function getTypeDependencyPackageName(npmPackage) {
541
+ if (npmPackage.startsWith("@")) {
542
+ const [scope, name] = npmPackage.split("/");
543
+ return `@types/${scope?.slice(1)}__${name}`;
544
+ }
545
+ return `@types/${npmPackage}`;
546
+ }
547
+ __name(getTypeDependencyPackageName, "getTypeDependencyPackageName");
548
+
549
+ // src/config.ts
550
+ var getOutputExtensionMap = /* @__PURE__ */ __name((options, pkgType) => {
551
+ return options.outExtension ? options.outExtension(options.format, pkgType) : (0, import_get_out_extension.getOutExtension)(options.format, pkgType);
552
+ }, "getOutputExtensionMap");
553
+ var getDefaultBuildPlugins = /* @__PURE__ */ __name((options, resolvedOptions) => [
554
+ nodeProtocolPlugin(options, resolvedOptions),
555
+ resolvePathsPlugin(options, resolvedOptions),
556
+ fixImportsPlugin(options, resolvedOptions),
557
+ nativeNodeModulesPlugin(options, resolvedOptions),
558
+ esmSplitCodeToCjsPlugin(options, resolvedOptions),
559
+ tscPlugin(options, resolvedOptions),
560
+ onErrorPlugin(options, resolvedOptions)
561
+ ], "getDefaultBuildPlugins");
562
+ var DEFAULT_BUILD_OPTIONS = {
563
+ platform: "node",
564
+ target: "node22",
565
+ format: "cjs",
566
+ external: [],
567
+ logLevel: "error",
568
+ tsconfig: "tsconfig.json",
569
+ environment: "production",
570
+ keepNames: true,
571
+ metafile: true,
572
+ injectShims: true,
573
+ color: true,
574
+ watch: false,
575
+ bundle: true,
576
+ clean: true,
577
+ debug: false,
578
+ loader: {
579
+ ".aac": "file",
580
+ ".css": "file",
581
+ ".eot": "file",
582
+ ".flac": "file",
583
+ ".gif": "file",
584
+ ".jpeg": "file",
585
+ ".jpg": "file",
586
+ ".mp3": "file",
587
+ ".mp4": "file",
588
+ ".ogg": "file",
589
+ ".otf": "file",
590
+ ".png": "file",
591
+ ".svg": "file",
592
+ ".ttf": "file",
593
+ ".wav": "file",
594
+ ".webm": "file",
595
+ ".webp": "file",
596
+ ".woff": "file",
597
+ ".woff2": "file"
598
+ },
599
+ banner: import_get_out_extension.DEFAULT_COMPILED_BANNER
600
+ };
601
+
602
+ // src/plugins/deps-check.ts
603
+ var import_config_tools3 = require("@storm-software/config-tools");
604
+ var import_node_module = require("module");
605
+ var import_node_path5 = __toESM(require("path"), 1);
606
+ var unusedIgnore = [
607
+ // these are our dev dependencies
608
+ /@types\/.*?/,
609
+ /@typescript-eslint.*?/,
610
+ /eslint.*?/,
611
+ "esbuild",
612
+ "husky",
613
+ "is-ci",
614
+ "lint-staged",
615
+ "prettier",
616
+ "typescript",
617
+ "ts-node",
618
+ "ts-jest",
619
+ "@swc/core",
620
+ "@swc/jest",
621
+ "jest",
622
+ // these are missing 3rd party deps
623
+ "spdx-exceptions",
624
+ "spdx-license-ids",
625
+ // type-only, so it is not detected
626
+ "ts-toolbelt",
627
+ // these are indirectly used by build
628
+ "buffer"
629
+ ];
630
+ var missingIgnore = [
631
+ ".prisma",
632
+ "@prisma/client",
633
+ "ts-toolbelt"
634
+ ];
635
+ var depsCheckPlugin = /* @__PURE__ */ __name((bundle) => ({
636
+ name: "storm:deps-check",
637
+ setup(build4) {
638
+ const pkgJsonPath = import_node_path5.default.join(process.cwd(), "package.json");
639
+ const pkgContents = require(pkgJsonPath);
640
+ const regDependencies = Object.keys(pkgContents["dependencies"] ?? {});
641
+ const devDependencies = Object.keys(pkgContents["devDependencies"] ?? {});
642
+ const peerDependencies = Object.keys(pkgContents["peerDependencies"] ?? {});
643
+ const dependencies = [
644
+ ...regDependencies,
645
+ ...bundle ? devDependencies : []
646
+ ];
647
+ const collectedDependencies = /* @__PURE__ */ new Set();
648
+ const onlyPackages = /^[^./](?!:)|^\.[^./]|^\.\.[^/]/;
649
+ build4.onResolve({
650
+ filter: onlyPackages
651
+ }, (args) => {
652
+ if (args.importer.includes(process.cwd())) {
653
+ if (args.path[0] === "@") {
654
+ const [org, pkg] = args.path.split("/");
655
+ collectedDependencies.add(`${org}/${pkg}`);
656
+ } else {
657
+ const [pkg] = args.path.split("/");
658
+ collectedDependencies.add(pkg);
659
+ }
660
+ }
661
+ return {
662
+ external: true
663
+ };
664
+ });
665
+ build4.onEnd(() => {
666
+ const unusedDependencies = [
667
+ ...dependencies
668
+ ].filter((dep) => {
669
+ return !collectedDependencies.has(dep) || import_node_module.builtinModules.includes(dep);
670
+ });
671
+ const missingDependencies = [
672
+ ...collectedDependencies
673
+ ].filter((dep) => {
674
+ return !dependencies.includes(dep) && !import_node_module.builtinModules.includes(dep);
675
+ });
676
+ const filteredUnusedDeps = unusedDependencies.filter((dep) => {
677
+ return !unusedIgnore.some((pattern) => dep.match(pattern));
678
+ });
679
+ const filteredMissingDeps = missingDependencies.filter((dep) => {
680
+ return !missingIgnore.some((pattern) => dep.match(pattern)) && !peerDependencies.includes(dep);
681
+ });
682
+ (0, import_config_tools3.writeWarning)(`Unused Dependencies: ${JSON.stringify(filteredUnusedDeps)}`);
683
+ (0, import_config_tools3.writeError)(`Missing Dependencies: ${JSON.stringify(filteredMissingDeps)}`);
684
+ if (filteredMissingDeps.length > 0) {
685
+ throw new Error(`Missing dependencies detected - please install them:
686
+ ${JSON.stringify(filteredMissingDeps)}
687
+ `);
688
+ }
689
+ });
690
+ }
691
+ }), "depsCheckPlugin");
692
+
693
+ // src/renderers/shebang.ts
694
+ var shebangRenderer = {
695
+ name: "shebang",
696
+ renderChunk(_, __, info) {
697
+ if (info.type === "chunk" && /\.(cjs|js|mjs)$/.test(info.path) && info.code.startsWith("#!")) {
698
+ info.mode = 493;
699
+ }
700
+ }
701
+ };
702
+
703
+ // src/utilities/helpers.ts
704
+ function handleSync(fn) {
705
+ try {
706
+ return fn();
707
+ } catch (error_) {
708
+ return error_;
709
+ }
710
+ }
711
+ __name(handleSync, "handleSync");
712
+ async function handleAsync(fn) {
713
+ try {
714
+ return await fn();
715
+ } catch (error_) {
716
+ return error_;
717
+ }
718
+ }
719
+ __name(handleAsync, "handleAsync");
720
+ var handle = handleSync;
721
+ handle.async = handleAsync;
722
+ var skip = Symbol("skip");
723
+ function transduceSync(list, transformer) {
724
+ const transduced = [];
725
+ for (const [i, element_] of list.entries()) {
726
+ const transformed = transformer(element_, i);
727
+ if (transformed !== skip) {
728
+ transduced[transduced.length] = transformed;
729
+ }
730
+ }
731
+ return transduced;
732
+ }
733
+ __name(transduceSync, "transduceSync");
734
+ async function transduceAsync(list, transformer) {
735
+ const transduced = [];
736
+ await Promise.all(list.entries().map(async ([i, element_]) => {
737
+ const transformed = await transformer(element_, i);
738
+ if (transformed !== skip) {
739
+ transduced[transduced.length] = transformed;
740
+ }
741
+ }));
742
+ return transduced;
743
+ }
744
+ __name(transduceAsync, "transduceAsync");
745
+ var transduce = transduceSync;
746
+ transduce.async = transduceAsync;
747
+ function pipeSync(fn, ...fns) {
748
+ return (...args) => {
749
+ let result = fn(...args);
750
+ for (let i = 0; result !== skip && i < fns.length; ++i) {
751
+ result = fns[i]?.(result);
752
+ }
753
+ return result;
754
+ };
755
+ }
756
+ __name(pipeSync, "pipeSync");
757
+ function pipeAsync(fn, ...fns) {
758
+ return async (...args) => {
759
+ let result = await fn(...args);
760
+ for (let i = 0; result !== skip && i < fns.length; ++i) {
761
+ result = await fns[i]?.(result);
762
+ }
763
+ return result;
764
+ };
765
+ }
766
+ __name(pipeAsync, "pipeAsync");
767
+ var pipe = pipeSync;
768
+ pipe.async = pipeAsync;
769
+
770
+ // src/build.ts
771
+ var resolveOptions = /* @__PURE__ */ __name(async (userOptions) => {
772
+ const projectRoot = userOptions.projectRoot;
773
+ const workspaceRoot = (0, import_find_workspace_root.findWorkspaceRoot)(projectRoot);
774
+ if (!workspaceRoot) {
775
+ throw new Error("Cannot find Nx workspace root");
776
+ }
777
+ const config = await (0, import_create_storm_config.loadStormConfig)(workspaceRoot.dir);
778
+ (0, import_console2.writeDebug)(" \u2699\uFE0F Resolving build options", config);
779
+ const stopwatch = (0, import_console2.getStopwatch)("Build options resolution");
780
+ const projectGraph = await (0, import_devkit.createProjectGraphAsync)({
781
+ exitOnError: true
782
+ });
783
+ const projectJsonPath = (0, import_correct_paths2.joinPaths)(workspaceRoot.dir, projectRoot, "project.json");
784
+ if (!await import_node3.hfs.isFile(projectJsonPath)) {
785
+ throw new Error("Cannot find project.json configuration");
786
+ }
787
+ const projectJson = await import_node3.hfs.json(projectJsonPath);
788
+ const projectName = projectJson.name;
789
+ const projectConfigurations = (0, import_devkit.readProjectsConfigurationFromProjectGraph)(projectGraph);
790
+ if (!projectConfigurations?.projects?.[projectName]) {
791
+ throw new Error("The Build process failed because the project does not have a valid configuration in the project.json file. Check if the file exists in the root of the project.");
792
+ }
793
+ const options = defu(userOptions, DEFAULT_BUILD_OPTIONS);
794
+ options.name ??= `${projectName}-${options.format}`;
795
+ options.target ??= import_build_tools.DEFAULT_TARGET;
796
+ const packageJsonPath = (0, import_correct_paths2.joinPaths)(workspaceRoot.dir, options.projectRoot, "package.json");
797
+ if (!await import_node3.hfs.isFile(packageJsonPath)) {
798
+ throw new Error("Cannot find package.json configuration");
799
+ }
800
+ const packageJson = await import_node3.hfs.json(packageJsonPath);
801
+ const outExtension = getOutputExtensionMap(options, packageJson.type);
802
+ const env = (0, import_build_tools.getEnv)("esbuild", options);
803
+ const result = {
804
+ ...options,
805
+ config,
806
+ mainFields: options.platform === "node" ? [
807
+ "module",
808
+ "main"
809
+ ] : [
810
+ "browser",
811
+ "module",
812
+ "main"
813
+ ],
814
+ resolveExtensions: [
815
+ ".ts",
816
+ ".js",
817
+ ".node"
818
+ ],
819
+ ...userOptions,
820
+ tsconfig: (0, import_correct_paths2.joinPaths)(projectRoot, userOptions.tsconfig ? userOptions.tsconfig.replace(projectRoot, "") : "tsconfig.json"),
821
+ format: options.format || "cjs",
822
+ entryPoints: await (0, import_build_tools.getEntryPoints)(config, projectRoot, projectJson.sourceRoot, userOptions.entry || [
823
+ "./src/index.ts"
824
+ ], userOptions.emitOnAll),
825
+ outdir: userOptions.outputPath || (0, import_correct_paths2.joinPaths)("dist", projectRoot),
826
+ plugins: [],
827
+ name: userOptions.name || projectName,
828
+ projectConfigurations,
829
+ projectName,
830
+ projectGraph,
831
+ sourceRoot: userOptions.sourceRoot || projectJson.sourceRoot || (0, import_correct_paths2.joinPaths)(projectRoot, "src"),
832
+ minify: userOptions.minify || !userOptions.debug,
833
+ verbose: userOptions.verbose || (0, import_get_log_level.isVerbose)() || userOptions.debug === true,
834
+ includeSrc: userOptions.includeSrc === true,
835
+ metafile: userOptions.metafile !== false,
836
+ generatePackageJson: userOptions.generatePackageJson !== false,
837
+ clean: userOptions.clean !== false,
838
+ emitOnAll: userOptions.emitOnAll === true,
839
+ assets: userOptions.assets ?? [],
840
+ injectShims: userOptions.injectShims !== true,
841
+ bundle: userOptions.bundle !== false,
842
+ keepNames: true,
843
+ watch: userOptions.watch === true,
844
+ outExtension,
845
+ footer: userOptions.footer,
846
+ banner: {
847
+ js: options.banner || import_build_tools.DEFAULT_COMPILED_BANNER,
848
+ css: options.banner || import_build_tools.DEFAULT_COMPILED_BANNER
849
+ },
850
+ splitting: options.format === "iife" ? false : typeof options.splitting === "boolean" ? options.splitting : options.format === "esm",
851
+ treeShaking: options.format === "esm",
852
+ env,
853
+ define: {
854
+ STORM_FORMAT: JSON.stringify(options.format || "cjs"),
855
+ ...options.format === "cjs" && options.injectShims ? {
856
+ "import.meta.url": "importMetaUrl"
857
+ } : {},
858
+ ...options.define,
859
+ ...Object.keys(env || {}).reduce((res, key) => {
860
+ const value = JSON.stringify(env[key]);
861
+ return {
862
+ ...res,
863
+ [`process.env.${key}`]: value,
864
+ [`import.meta.env.${key}`]: value
865
+ };
866
+ }, {})
867
+ },
868
+ inject: [
869
+ options.format === "cjs" && options.injectShims ? (0, import_correct_paths2.joinPaths)(__dirname, "../assets/cjs_shims.js") : "",
870
+ options.format === "esm" && options.injectShims && options.platform === "node" ? (0, import_correct_paths2.joinPaths)(__dirname, "../assets/esm_shims.js") : "",
871
+ ...options.inject ?? []
872
+ ].filter(Boolean)
873
+ };
874
+ result.plugins = userOptions.plugins ?? getDefaultBuildPlugins(userOptions, result);
875
+ stopwatch();
876
+ return result;
877
+ }, "resolveOptions");
878
+ async function generatePackageJson(context2) {
879
+ if (context2.options.generatePackageJson !== false && await import_node3.hfs.isFile((0, import_correct_paths2.joinPaths)(context2.options.projectRoot, "package.json"))) {
880
+ (0, import_console2.writeDebug)(" \u270D\uFE0F Writing package.json file", context2.options.config);
881
+ const stopwatch = (0, import_console2.getStopwatch)("Write package.json file");
882
+ const packageJsonPath = (0, import_correct_paths2.joinPaths)(context2.options.projectRoot, "project.json");
883
+ if (!await import_node3.hfs.isFile(packageJsonPath)) {
884
+ throw new Error("Cannot find package.json configuration");
885
+ }
886
+ let packageJson = await import_node3.hfs.json((0, import_correct_paths2.joinPaths)(context2.options.config.workspaceRoot, context2.options.projectRoot, "package.json"));
887
+ if (!packageJson) {
888
+ throw new Error("Cannot find package.json configuration file");
889
+ }
890
+ packageJson = await (0, import_build_tools.addPackageDependencies)(context2.options.config.workspaceRoot, context2.options.projectRoot, context2.options.projectName, packageJson);
891
+ packageJson = await (0, import_build_tools.addWorkspacePackageJsonFields)(context2.options.config, context2.options.projectRoot, context2.options.sourceRoot, context2.options.projectName, false, packageJson);
892
+ packageJson.exports ??= {};
893
+ packageJson.exports["./package.json"] ??= "./package.json";
894
+ packageJson.exports["."] ??= (0, import_build_tools.addPackageJsonExport)("index", packageJson.type, context2.options.sourceRoot);
895
+ let entryPoints = [
896
+ {
897
+ in: "./src/index.ts",
898
+ out: "./src/index.ts"
899
+ }
900
+ ];
901
+ if (context2.options.entryPoints) {
902
+ if (Array.isArray(context2.options.entryPoints)) {
903
+ entryPoints = context2.options.entryPoints.map((entryPoint) => typeof entryPoint === "string" ? {
904
+ in: entryPoint,
905
+ out: entryPoint
906
+ } : entryPoint);
907
+ }
908
+ for (const entryPoint of entryPoints) {
909
+ const split = entryPoint.out.split(".");
910
+ split.pop();
911
+ const entry = split.join(".").replaceAll("\\", "/");
912
+ packageJson.exports[`./${entry}`] ??= (0, import_build_tools.addPackageJsonExport)(entry, packageJson.type, context2.options.sourceRoot);
913
+ }
914
+ }
915
+ packageJson.main = packageJson.type === "commonjs" ? "./dist/index.js" : "./dist/index.cjs";
916
+ packageJson.module = packageJson.type === "module" ? "./dist/index.js" : "./dist/index.mjs";
917
+ packageJson.types = "./dist/index.d.ts";
918
+ packageJson.exports = Object.keys(packageJson.exports).reduce((ret, key) => {
919
+ if (key.endsWith("/index") && !ret[key.replace("/index", "")]) {
920
+ ret[key.replace("/index", "")] = packageJson.exports[key];
921
+ }
922
+ return ret;
923
+ }, packageJson.exports);
924
+ await (0, import_devkit.writeJsonFile)((0, import_correct_paths2.joinPaths)(context2.options.outdir, "package.json"), packageJson);
925
+ stopwatch();
926
+ }
927
+ return context2;
928
+ }
929
+ __name(generatePackageJson, "generatePackageJson");
930
+ async function createOptions(options) {
931
+ return (0, import_es_toolkit.flatten)(await Promise.all((0, import_compat.map)(options, (opt) => [
932
+ // we defer it so that we don't trigger glob immediately
933
+ () => resolveOptions(opt)
934
+ ])));
935
+ }
936
+ __name(createOptions, "createOptions");
937
+ async function generateContext(getOptions) {
938
+ const options = await getOptions();
939
+ const rendererEngine = new RendererEngine([
940
+ shebangRenderer,
941
+ ...options.renderers || []
942
+ ]);
943
+ return {
944
+ options,
945
+ rendererEngine
946
+ };
947
+ }
948
+ __name(generateContext, "generateContext");
949
+ async function executeEsBuild(context2) {
950
+ (0, import_console2.writeDebug)(` \u{1F680} Running ${context2.options.name} build`, context2.options.config);
951
+ const stopwatch = (0, import_console2.getStopwatch)(`${context2.options.name} build`);
952
+ if (process.env.WATCH === "true") {
953
+ const ctx = await esbuild2.context(context2.options);
954
+ watch(ctx, context2.options);
955
+ }
956
+ const result = await esbuild2.build(context2.options);
957
+ if (result.metafile) {
958
+ const metafilePath = `${context2.options.outdir}/${context2.options.name}.meta.json`;
959
+ await import_node3.hfs.write(metafilePath, JSON.stringify(result.metafile));
960
+ }
961
+ stopwatch();
962
+ return context2;
963
+ }
964
+ __name(executeEsBuild, "executeEsBuild");
965
+ async function copyBuildAssets(context2) {
966
+ if (context2.result?.errors.length === 0) {
967
+ (0, import_console2.writeDebug)(` \u{1F4CB} Copying asset files to output directory: ${context2.options.outdir}`, context2.options.config);
968
+ const stopwatch = (0, import_console2.getStopwatch)(`${context2.options.name} asset copy`);
969
+ await (0, import_build_tools.copyAssets)(context2.options.config, context2.options.assets ?? [], context2.options.outdir, context2.options.projectRoot, context2.options.projectName, context2.options.sourceRoot, true, false);
970
+ stopwatch();
971
+ }
972
+ return context2;
973
+ }
974
+ __name(copyBuildAssets, "copyBuildAssets");
975
+ async function reportResults(context2) {
976
+ if (context2.result?.errors.length === 0) {
977
+ if (context2.result.warnings.length > 0) {
978
+ (0, import_console2.writeWarning)(` \u{1F6A7} The following warnings occurred during the build: ${context2.result.warnings.map((warning) => warning.text).join("\n")}`, context2.options.config);
979
+ }
980
+ (0, import_console2.writeSuccess)(` \u{1F4E6} The ${context2.options.name} build completed successfully`, context2.options.config);
981
+ }
982
+ }
983
+ __name(reportResults, "reportResults");
984
+ async function dependencyCheck(options) {
985
+ if (process.env.DEV === "true") {
986
+ return void 0;
987
+ }
988
+ if (process.env.CI && !process.env.BUILDKITE) {
989
+ return void 0;
990
+ }
991
+ const buildPromise = esbuild2.build({
992
+ entryPoints: (0, import_globby.globbySync)("**/*.{j,t}s", {
993
+ // We don't check dependencies in ecosystem tests because tests are isolated from the build.
994
+ ignore: [
995
+ "./src/__tests__/**/*",
996
+ "./tests/e2e/**/*",
997
+ "./dist/**/*"
998
+ ],
999
+ gitignore: true
1000
+ }),
1001
+ logLevel: "silent",
1002
+ bundle: true,
1003
+ write: false,
1004
+ outdir: "out",
1005
+ plugins: [
1006
+ depsCheckPlugin(options.bundle)
1007
+ ]
1008
+ });
1009
+ await buildPromise.catch(() => {
1010
+ });
1011
+ return void 0;
1012
+ }
1013
+ __name(dependencyCheck, "dependencyCheck");
1014
+ async function cleanOutputPath(context2) {
1015
+ if (context2.options.clean !== false && context2.options.outdir) {
1016
+ await clean(context2.options.name, context2.options.outdir, context2.options.config);
1017
+ }
1018
+ return context2;
1019
+ }
1020
+ __name(cleanOutputPath, "cleanOutputPath");
1021
+ async function build3(options) {
1022
+ (0, import_console2.writeDebug)(` \u26A1 Executing Storm ESBuild pipeline`);
1023
+ const stopwatch = (0, import_console2.getStopwatch)("ESBuild pipeline");
1024
+ try {
1025
+ const opts = Array.isArray(options) ? options : [
1026
+ options
1027
+ ];
1028
+ if (opts.length === 0) {
1029
+ throw new Error("No build options were provided");
1030
+ }
1031
+ void transduce.async(opts, dependencyCheck);
1032
+ await transduce.async(await createOptions(opts), pipe.async(generateContext, cleanOutputPath, generatePackageJson, executeEsBuild, copyBuildAssets, reportResults));
1033
+ (0, import_console2.writeSuccess)(" \u{1F3C1} ESBuild pipeline build completed successfully");
1034
+ } catch (error) {
1035
+ (0, import_console2.writeFatal)(" \u274C Fatal errors occurred during the build that could not be recovered from. The build process has been terminated.");
1036
+ throw error;
1037
+ } finally {
1038
+ stopwatch();
1039
+ }
1040
+ }
1041
+ __name(build3, "build");
1042
+ var watch = /* @__PURE__ */ __name((context2, options) => {
1043
+ if (!options.watch) {
1044
+ return context2;
1045
+ }
1046
+ const config = {
1047
+ ignoreInitial: true,
1048
+ useFsEvents: true,
1049
+ ignored: [
1050
+ "./src/__tests__/**/*",
1051
+ "./package.json"
1052
+ ]
1053
+ };
1054
+ const changeWatcher = (0, import_chokidar.watch)([
1055
+ "./src/**/*"
1056
+ ], config);
1057
+ const fastRebuild = (0, import_es_toolkit.debounce)(async () => {
1058
+ const timeBefore = Date.now();
1059
+ const rebuildResult = await handle.async(() => {
1060
+ return context2.rebuild();
1061
+ });
1062
+ if (rebuildResult instanceof Error) {
1063
+ (0, import_console2.writeError)(rebuildResult.message);
1064
+ }
1065
+ (0, import_console2.writeTrace)(`${Date.now() - timeBefore}ms [${options.name ?? ""}]`);
1066
+ }, 10);
1067
+ changeWatcher.on("change", fastRebuild);
1068
+ return void 0;
1069
+ }, "watch");
1070
+
1071
+ // bin/esbuild.ts
1072
+ async function createProgram(config) {
1073
+ try {
1074
+ (0, import_console3.writeInfo)("\u26A1 Running Storm ESBuild pipeline", config);
1075
+ const root = (0, import_find_workspace_root2.findWorkspaceRootSafe)();
1076
+ process.env.STORM_WORKSPACE_ROOT ??= root;
1077
+ process.env.NX_WORKSPACE_ROOT_PATH ??= root;
1078
+ root && process.chdir(root);
1079
+ const program = new import_commander.Command("storm-esbuild");
1080
+ program.version("1.0.0", "-v --version", "display CLI version");
1081
+ program.description("\u26A1 Run the Storm ESBuild pipeline").showHelpAfterError().showSuggestionAfterError();
1082
+ const projectRootOption = new import_commander.Option("-p --project-root <path>", "The path to the root of the project to build. This path is defined relative to the workspace root.").makeOptionMandatory(true);
1083
+ const sourceRootOption = new import_commander.Option("-s --source-root <path>", "The path of the project's source folder to build");
1084
+ const nameOption = new import_commander.Option("-n --name <value>", "The name of the project to build");
1085
+ const outputPathOption = new import_commander.Option("-o --output-path <path>", "The path of the project's source folder to build").default("dist/{projectRoot}");
1086
+ const platformOption = new import_commander.Option("-p --platform <value>", "The platform to build the distribution for").choices([
1087
+ "node",
1088
+ "neutral",
1089
+ "browser"
1090
+ ]).default("node");
1091
+ const formatOption = new import_commander.Option("-f, --format <value...>", "The format to build the distribution in").choices([
1092
+ "esm",
1093
+ "cjs",
1094
+ "iife"
1095
+ ]).argParser((value, previous) => {
1096
+ if (previous === void 0) {
1097
+ return [
1098
+ value
1099
+ ];
1100
+ } else if (!previous.includes(value)) {
1101
+ previous.push(value);
1102
+ }
1103
+ return previous;
1104
+ }).default("esm");
1105
+ const cleanOption = new import_commander.Option("-c --clean", "Should the output directory be cleaned before building").default(true);
1106
+ const noCleanOption = new import_commander.Option("--no-clean", "Should the output directory be cleaned before building").default(false);
1107
+ const bundleOption = new import_commander.Option("-b --bundle", "Should the output be bundled").default(true);
1108
+ const noBundleOption = new import_commander.Option("--no-bundle", "Should the output be bundled").default(false);
1109
+ const targetOption = new import_commander.Option("-t --target <value>", "The target to build the distribution for").choices([
1110
+ "ESNext",
1111
+ "ES2015",
1112
+ "ES2016",
1113
+ "ES2017",
1114
+ "ES2018",
1115
+ "ES2019",
1116
+ "ES2020",
1117
+ "ES2021",
1118
+ "ES2022",
1119
+ "ES2023"
1120
+ ]).default("ESNext");
1121
+ const watchOption = new import_commander.Option("-w --watch", "Should the build process watch for changes").default(false);
1122
+ const debugOption = new import_commander.Option("-d --debug", "Should the build process run in debug mode").default(false);
1123
+ const bannerOption = new import_commander.Option("--banner <value>", "The banner to prepend to the output");
1124
+ const footerOption = new import_commander.Option("--footer <value>", "The footer to prepend to the output");
1125
+ const splittingOption = new import_commander.Option("--splitting", "Should the output be split into multiple files").default(true);
1126
+ const treeShakingOption = new import_commander.Option("--tree-shaking", "Should tree shaking be enabled").default(true);
1127
+ const generatePackageJsonOption = new import_commander.Option("--generate-package-json", "Should a package.json be generated for the output").default(true);
1128
+ const emitOnAllOption = new import_commander.Option("--emit-on-all", "Should the output be emitted on all platforms").default(false);
1129
+ const metafileOption = new import_commander.Option("--metafile", "Should a metafile be generated for the output").default(true);
1130
+ const minifyOption = new import_commander.Option("--minify", "Should the output be minified").default(true);
1131
+ const includeSrcOption = new import_commander.Option("--include-src", "Should the source files be included in the output").default(false);
1132
+ const verboseOption = new import_commander.Option("--verbose", "Should the build process be verbose").default(false);
1133
+ const injectShimsOption = new import_commander.Option("--inject-shims", "Should shims be injected into the output").default(true);
1134
+ const emitTypesOption = new import_commander.Option("--emit-types", "Should types be emitted for the output").default(true);
1135
+ program.command("build", {
1136
+ isDefault: true
1137
+ }).alias("bundle").description("Run a TypeScript build using ESBuild, API-Extractor, and TSC (for type generation).").addOption(nameOption).addOption(projectRootOption).addOption(sourceRootOption).addOption(outputPathOption).addOption(platformOption).addOption(formatOption).addOption(targetOption).addOption(bundleOption).addOption(noBundleOption).addOption(cleanOption).addOption(noCleanOption).addOption(watchOption).addOption(debugOption).addOption(bannerOption).addOption(footerOption).addOption(splittingOption).addOption(treeShakingOption).addOption(generatePackageJsonOption).addOption(emitOnAllOption).addOption(metafileOption).addOption(minifyOption).addOption(includeSrcOption).addOption(verboseOption).addOption(injectShimsOption).addOption(emitTypesOption).action(buildAction(config));
1138
+ program.command("clean").alias("clear").description("Clean the output directory of the project. This command will remove the 'dist' folder.").addOption(nameOption).action(cleanAction(config));
1139
+ return program;
1140
+ } catch (e) {
1141
+ (0, import_console3.writeFatal)(`A fatal error occurred while running the program: ${e.message}`, config);
1142
+ process.exit(1);
1143
+ }
1144
+ }
1145
+ __name(createProgram, "createProgram");
1146
+ var buildAction = /* @__PURE__ */ __name((config) => async (options) => {
1147
+ try {
1148
+ await build3({
1149
+ ...options,
1150
+ format: options.format
1151
+ });
1152
+ } catch (e) {
1153
+ (0, import_console3.writeFatal)(`A fatal error occurred while cleaning the ESBuild output directory: ${e.message}`, config);
1154
+ (0, import_process_handler.exitWithError)(config);
1155
+ process.exit(1);
1156
+ }
1157
+ }, "buildAction");
1158
+ var cleanAction = /* @__PURE__ */ __name((config) => async (options) => {
1159
+ try {
1160
+ await clean(options.name, options.output, config);
1161
+ } catch (e) {
1162
+ (0, import_console3.writeFatal)(`A fatal error occurred while cleaning the ESBuild output directory: ${e.message}`, config);
1163
+ (0, import_process_handler.exitWithError)(config);
1164
+ process.exit(1);
1165
+ }
1166
+ }, "cleanAction");
1167
+ void (async () => {
1168
+ const config = await (0, import_create_storm_config2.loadStormConfig)();
1169
+ const stopwatch = (0, import_console3.getStopwatch)("Storm ESBuild executable");
1170
+ try {
1171
+ (0, import_process_handler.handleProcess)(config);
1172
+ const program = await createProgram(config);
1173
+ await program.parseAsync(process.argv);
1174
+ (0, import_console3.writeSuccess)(`\u{1F389} Storm ESBuild executable has completed successfully!`, config);
1175
+ (0, import_process_handler.exitWithSuccess)(config);
1176
+ } catch (error) {
1177
+ (0, import_console3.writeFatal)(`A fatal error occurred while running Storm ESBuild executable:
1178
+
1179
+ ${error.message}`, config);
1180
+ (0, import_process_handler.exitWithError)(config);
1181
+ process.exit(1);
1182
+ } finally {
1183
+ stopwatch();
1184
+ }
1185
+ })();