@storm-software/unbuild 0.25.2 → 0.26.0

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 (90) hide show
  1. package/README.md +1 -1
  2. package/bin/unbuild.cjs +3366 -0
  3. package/bin/unbuild.js +2713 -62900
  4. package/dist/build.cjs +14 -0
  5. package/dist/{build.d.mts → build.d.cts} +1 -3
  6. package/dist/build.d.ts +0 -2
  7. package/dist/build.js +14 -20
  8. package/dist/chunk-3GQAWCBQ.js +13 -0
  9. package/dist/{chunk-4BAUMYRN.mjs → chunk-4RR7YISH.js} +9 -8
  10. package/dist/chunk-BRHZNXQM.js +603 -0
  11. package/dist/chunk-DRQUQQ5D.js +2459 -0
  12. package/dist/{chunk-4ENAOJ33.mjs → chunk-ESRR2FD2.js} +2 -4
  13. package/dist/chunk-GHVDJY3S.cjs +603 -0
  14. package/dist/chunk-HO6B5DC7.cjs +27 -0
  15. package/dist/{chunk-6UMHN4KS.mjs → chunk-JIVM7FQJ.js} +3 -5
  16. package/dist/chunk-KAXKUEZ7.cjs +63 -0
  17. package/dist/chunk-ORA4UQMU.cjs +1 -0
  18. package/dist/chunk-OULCUN6I.js +0 -0
  19. package/dist/{chunk-P6LWSWAQ.js → chunk-SHHAZOHN.cjs} +2 -4
  20. package/dist/{chunk-ESGPHEWU.mjs → chunk-TFMXUACY.js} +6 -8
  21. package/dist/{chunk-PVZYPNLZ.js → chunk-TRA2WJ3W.cjs} +6 -8
  22. package/dist/{chunk-BUCFGCTW.js → chunk-UV35N5R4.cjs} +5 -7
  23. package/dist/chunk-VEX5RCZW.js +63 -0
  24. package/dist/chunk-XGMJ3OUH.cjs +2460 -0
  25. package/dist/{chunk-SQOZCV36.js → chunk-XKHSZIHP.cjs} +8 -7
  26. package/dist/{chunk-WXJPXYHF.mjs → chunk-YCGXRIUD.js} +3 -5
  27. package/dist/chunk-YDYGZTJK.cjs +18 -0
  28. package/dist/clean.cjs +10 -0
  29. package/dist/clean.js +10 -10
  30. package/dist/config.cjs +12 -0
  31. package/dist/{config.d.mts → config.d.cts} +1 -3
  32. package/dist/config.d.ts +0 -2
  33. package/dist/config.js +12 -12
  34. package/dist/index.cjs +28 -0
  35. package/dist/{index.d.mts → index.d.cts} +4 -6
  36. package/dist/index.d.ts +0 -2
  37. package/dist/index.js +28 -39
  38. package/dist/types.cjs +2 -0
  39. package/dist/{types.d.mts → types.d.cts} +0 -4
  40. package/dist/types.d.ts +0 -4
  41. package/dist/types.js +1 -2
  42. package/package.json +38 -37
  43. package/bin/unbuild.mjs +0 -63530
  44. package/dist/build.mjs +0 -20
  45. package/dist/chunk-3TNHGERR.mjs +0 -49
  46. package/dist/chunk-44VTNVZA.js +0 -29
  47. package/dist/chunk-45FJ3WQ6.js +0 -7528
  48. package/dist/chunk-4HFICKAT.js +0 -451
  49. package/dist/chunk-4IU7LXNH.mjs +0 -4054
  50. package/dist/chunk-523YIUTF.js +0 -19937
  51. package/dist/chunk-7G3WYTPJ.js +0 -6
  52. package/dist/chunk-AMTVM7UD.js +0 -4054
  53. package/dist/chunk-DIRFSBOA.mjs +0 -84
  54. package/dist/chunk-EGCWTBMT.mjs +0 -1120
  55. package/dist/chunk-EKTZK3IJ.mjs +0 -765
  56. package/dist/chunk-FAXWFK7Q.mjs +0 -7528
  57. package/dist/chunk-G6BE6UP3.mjs +0 -2481
  58. package/dist/chunk-K5SQO3GD.mjs +0 -451
  59. package/dist/chunk-MCNTIU52.js +0 -3050
  60. package/dist/chunk-NMYL4VJJ.js +0 -84
  61. package/dist/chunk-NOVWJHZD.mjs +0 -6
  62. package/dist/chunk-Q4GMTWGF.mjs +0 -19937
  63. package/dist/chunk-RBSVNX4W.js +0 -49
  64. package/dist/chunk-RM7SW35Z.js +0 -1120
  65. package/dist/chunk-S532A3LO.js +0 -510
  66. package/dist/chunk-TEEYWCSY.mjs +0 -3050
  67. package/dist/chunk-VJI72AA6.mjs +0 -510
  68. package/dist/chunk-W7YS7HE5.js +0 -765
  69. package/dist/chunk-YIP6AERX.js +0 -2484
  70. package/dist/clean.mjs +0 -10
  71. package/dist/config.mjs +0 -12
  72. package/dist/dist-JWSUGJW5.js +0 -17571
  73. package/dist/dist-LXRVOZWD.mjs +0 -17570
  74. package/dist/esm-2JSYGY2W.js +0 -1716
  75. package/dist/esm-2LICJFKF.mjs +0 -1716
  76. package/dist/execa-2KYLC5PR.mjs +0 -2424
  77. package/dist/execa-QRX32ES4.js +0 -2424
  78. package/dist/index.mjs +0 -39
  79. package/dist/json5-JI6Y4EBT.mjs +0 -10
  80. package/dist/json5-ZRUT32KA.js +0 -10
  81. package/dist/jsonc-2MC7UMCL.js +0 -15
  82. package/dist/jsonc-PDDMSRDH.mjs +0 -15
  83. package/dist/multipart-parser-FQDS23TV.mjs +0 -187
  84. package/dist/multipart-parser-IX66WIWH.js +0 -187
  85. package/dist/toml-IHKP66UV.mjs +0 -10
  86. package/dist/toml-MDHAEB3G.js +0 -10
  87. package/dist/types.mjs +0 -2
  88. package/dist/yaml-GMY56OHD.mjs +0 -10
  89. package/dist/yaml-UTMAXQ2T.js +0 -10
  90. /package/dist/{clean.d.mts → clean.d.cts} +0 -0
@@ -0,0 +1,3366 @@
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
+ // ../../node_modules/.pnpm/tsup@8.3.5_@microsoft+api-extractor@7.49.1_@types+node@22.10.7__@swc+core@1.7.26_@swc+helpers_ekim6y52mwpq6ssxiprcp44dam/node_modules/tsup/assets/cjs_shims.js
27
+ var getImportMetaUrl = /* @__PURE__ */ __name(() => typeof document === "undefined" ? new URL(`file:${__filename}`).href : document.currentScript && document.currentScript.src || new URL("main.js", document.baseURI).href, "getImportMetaUrl");
28
+ var importMetaUrl = /* @__PURE__ */ getImportMetaUrl();
29
+
30
+ // ../config/src/schema.ts
31
+ var import_zod = __toESM(require("zod"));
32
+
33
+ // ../config/src/constants.ts
34
+ var STORM_DEFAULT_DOCS = "https://docs.stormsoftware.com";
35
+ var STORM_DEFAULT_HOMEPAGE = "https://stormsoftware.com";
36
+ var STORM_DEFAULT_LICENSING = "https://license.stormsoftware.com";
37
+ var STORM_DEFAULT_LICENSE = "Apache-2.0";
38
+
39
+ // ../config/src/schema.ts
40
+ var DarkColorSchema = import_zod.default.string().trim().toLowerCase().regex(/^#([0-9a-f]{3}){1,2}$/i).length(7).default("#1d1e22").describe("The dark background color of the workspace");
41
+ var LightColorSchema = import_zod.default.string().trim().toLowerCase().regex(/^#([0-9a-f]{3}){1,2}$/i).length(7).default("#f4f4f5").describe("The light background color of the workspace");
42
+ var BrandColorSchema = import_zod.default.string().trim().toLowerCase().regex(/^#([0-9a-f]{3}){1,2}$/i).length(7).default("#1fb2a6").describe("The primary brand specific color of the workspace");
43
+ var AlternateColorSchema = import_zod.default.string().trim().toLowerCase().regex(/^#([0-9a-f]{3}){1,2}$/i).length(7).optional().describe("The alternate brand specific color of the workspace");
44
+ var AccentColorSchema = import_zod.default.string().trim().toLowerCase().regex(/^#([0-9a-f]{3}){1,2}$/i).length(7).optional().describe("The secondary brand specific color of the workspace");
45
+ var LinkColorSchema = import_zod.default.string().trim().toLowerCase().regex(/^#([0-9a-f]{3}){1,2}$/i).length(7).optional().describe("The color used to display hyperlink text");
46
+ var HelpColorSchema = import_zod.default.string().trim().toLowerCase().regex(/^#([0-9a-f]{3}){1,2}$/i).length(7).default("#8256D0").describe("The second brand specific color of the workspace");
47
+ var SuccessColorSchema = import_zod.default.string().trim().toLowerCase().regex(/^#([0-9a-f]{3}){1,2}$/i).length(7).default("#12B66A").describe("The success color of the workspace");
48
+ var InfoColorSchema = import_zod.default.string().trim().toLowerCase().regex(/^#([0-9a-f]{3}){1,2}$/i).length(7).default("#0070E0").describe("The informational color of the workspace");
49
+ var WarningColorSchema = import_zod.default.string().trim().toLowerCase().regex(/^#([0-9a-f]{3}){1,2}$/i).length(7).default("#fcc419").describe("The warning color of the workspace");
50
+ var DangerColorSchema = import_zod.default.string().trim().toLowerCase().regex(/^#([0-9a-f]{3}){1,2}$/i).length(7).default("#D8314A").describe("The danger color of the workspace");
51
+ var FatalColorSchema = import_zod.default.string().trim().toLowerCase().regex(/^#([0-9a-f]{3}){1,2}$/i).length(7).optional().describe("The fatal color of the workspace");
52
+ var PositiveColorSchema = import_zod.default.string().trim().toLowerCase().regex(/^#([0-9a-f]{3}){1,2}$/i).length(7).default("#4ade80").describe("The positive number color of the workspace");
53
+ var NegativeColorSchema = import_zod.default.string().trim().toLowerCase().regex(/^#([0-9a-f]{3}){1,2}$/i).length(7).default("#ef4444").describe("The negative number color of the workspace");
54
+ var DarkThemeColorConfigSchema = import_zod.default.object({
55
+ foreground: LightColorSchema,
56
+ background: DarkColorSchema,
57
+ brand: BrandColorSchema,
58
+ alternate: AlternateColorSchema,
59
+ accent: AccentColorSchema,
60
+ link: LinkColorSchema,
61
+ help: HelpColorSchema,
62
+ success: SuccessColorSchema,
63
+ info: InfoColorSchema,
64
+ warning: WarningColorSchema,
65
+ danger: DangerColorSchema,
66
+ fatal: FatalColorSchema,
67
+ positive: PositiveColorSchema,
68
+ negative: NegativeColorSchema
69
+ });
70
+ var LightThemeColorConfigSchema = import_zod.default.object({
71
+ foreground: DarkColorSchema,
72
+ background: LightColorSchema,
73
+ brand: BrandColorSchema,
74
+ alternate: AlternateColorSchema,
75
+ accent: AccentColorSchema,
76
+ link: LinkColorSchema,
77
+ help: HelpColorSchema,
78
+ success: SuccessColorSchema,
79
+ info: InfoColorSchema,
80
+ warning: WarningColorSchema,
81
+ danger: DangerColorSchema,
82
+ fatal: FatalColorSchema,
83
+ positive: PositiveColorSchema,
84
+ negative: NegativeColorSchema
85
+ });
86
+ var MultiThemeColorConfigSchema = import_zod.default.object({
87
+ dark: DarkThemeColorConfigSchema,
88
+ light: LightThemeColorConfigSchema
89
+ });
90
+ var SingleThemeColorConfigSchema = import_zod.default.object({
91
+ dark: DarkColorSchema,
92
+ light: LightColorSchema,
93
+ brand: BrandColorSchema,
94
+ alternate: AlternateColorSchema,
95
+ accent: AccentColorSchema,
96
+ link: LinkColorSchema,
97
+ help: HelpColorSchema,
98
+ success: SuccessColorSchema,
99
+ info: InfoColorSchema,
100
+ warning: WarningColorSchema,
101
+ danger: DangerColorSchema,
102
+ fatal: FatalColorSchema,
103
+ positive: PositiveColorSchema,
104
+ negative: NegativeColorSchema
105
+ });
106
+ var RegistryUrlConfigSchema = import_zod.default.string().trim().toLowerCase().url().optional().describe("A remote registry URL used to publish distributable packages");
107
+ var RegistryConfigSchema = import_zod.default.object({
108
+ github: RegistryUrlConfigSchema,
109
+ npm: RegistryUrlConfigSchema,
110
+ cargo: RegistryUrlConfigSchema,
111
+ cyclone: RegistryUrlConfigSchema,
112
+ container: RegistryUrlConfigSchema
113
+ }).default({}).describe("A list of remote registry URLs used by Storm Software");
114
+ var ColorConfigSchema = SingleThemeColorConfigSchema.or(MultiThemeColorConfigSchema).describe("Colors used for various workspace elements");
115
+ var ColorConfigMapSchema = import_zod.default.union([
116
+ import_zod.default.object({
117
+ "base": ColorConfigSchema
118
+ }),
119
+ import_zod.default.record(import_zod.default.string(), ColorConfigSchema)
120
+ ]);
121
+ var WorkspaceBotConfigSchema = import_zod.default.object({
122
+ name: import_zod.default.string().trim().default("Stormie-Bot").describe("The workspace bot user's name (this is the bot that will be used to perform various tasks)"),
123
+ email: import_zod.default.string().trim().email().default("bot@stormsoftware.com").describe("The email of the workspace bot")
124
+ }).describe("The workspace's bot user's config used to automated various operations tasks");
125
+ var WorkspaceDirectoryConfigSchema = import_zod.default.object({
126
+ cache: import_zod.default.string().trim().optional().describe("The directory used to store the environment's cached file data"),
127
+ data: import_zod.default.string().trim().optional().describe("The directory used to store the environment's data files"),
128
+ config: import_zod.default.string().trim().optional().describe("The directory used to store the environment's configuration files"),
129
+ temp: import_zod.default.string().trim().optional().describe("The directory used to store the environment's temp files"),
130
+ log: import_zod.default.string().trim().optional().describe("The directory used to store the environment's temp files"),
131
+ build: import_zod.default.string().trim().default("dist").describe("The directory used to store the workspace's distributable files after a build (relative to the workspace root)")
132
+ }).describe("Various directories used by the workspace to store data, cache, and configuration files");
133
+ var StormConfigSchema = import_zod.default.object({
134
+ $schema: import_zod.default.string().trim().default("https://cdn.jsdelivr.net/npm/@storm-software/config/schemas/storm.schema.json").optional().nullish().describe("The URL to the JSON schema file that describes the Storm configuration file"),
135
+ extends: import_zod.default.string().trim().optional().describe("The path to a base JSON file to use as a configuration preset file"),
136
+ name: import_zod.default.string().trim().toLowerCase().optional().describe("The name of the service/package/scope using this configuration"),
137
+ namespace: import_zod.default.string().trim().toLowerCase().optional().describe("The namespace of the package"),
138
+ organization: import_zod.default.string().trim().default("storm-software").describe("The organization of the workspace"),
139
+ repository: import_zod.default.string().trim().url().optional().describe("The repo URL of the workspace (i.e. GitHub)"),
140
+ license: import_zod.default.string().trim().default("Apache-2.0").describe("The license type of the package"),
141
+ homepage: import_zod.default.string().trim().url().default(STORM_DEFAULT_HOMEPAGE).describe("The homepage of the workspace"),
142
+ docs: import_zod.default.string().trim().url().default(STORM_DEFAULT_DOCS).describe("The base documentation site for the workspace"),
143
+ licensing: import_zod.default.string().trim().url().default(STORM_DEFAULT_LICENSING).describe("The base licensing site for the workspace"),
144
+ branch: import_zod.default.string().trim().default("main").describe("The branch of the workspace"),
145
+ preid: import_zod.default.string().optional().describe("A tag specifying the version pre-release identifier"),
146
+ owner: import_zod.default.string().trim().default("@storm-software/admin").describe("The owner of the package"),
147
+ bot: WorkspaceBotConfigSchema,
148
+ env: import_zod.default.enum([
149
+ "development",
150
+ "staging",
151
+ "production"
152
+ ]).default("production").describe("The current runtime environment name for the package"),
153
+ workspaceRoot: import_zod.default.string().trim().default("").describe("The root directory of the workspace"),
154
+ externalPackagePatterns: import_zod.default.array(import_zod.default.string()).default([]).describe("The build will use these package patterns to determine if they should be external to the bundle"),
155
+ skipCache: import_zod.default.boolean().default(false).describe("Should all known types of workspace caching be skipped?"),
156
+ directories: WorkspaceDirectoryConfigSchema,
157
+ packageManager: import_zod.default.enum([
158
+ "npm",
159
+ "yarn",
160
+ "pnpm",
161
+ "bun"
162
+ ]).default("npm").describe("The JavaScript/TypeScript package manager used by the repository"),
163
+ timezone: import_zod.default.string().trim().default("America/New_York").describe("The default timezone of the workspace"),
164
+ locale: import_zod.default.string().trim().default("en-US").describe("The default locale of the workspace"),
165
+ logLevel: import_zod.default.enum([
166
+ "silent",
167
+ "fatal",
168
+ "error",
169
+ "warn",
170
+ "success",
171
+ "info",
172
+ "debug",
173
+ "trace",
174
+ "all"
175
+ ]).default("info").describe("The log level used to filter out lower priority log messages. If not provided, this is defaulted using the `environment` config value (if `environment` is set to `production` then `level` is `error`, else `level` is `debug`)."),
176
+ registry: RegistryConfigSchema,
177
+ configFile: import_zod.default.string().trim().nullable().default(null).describe("The filepath of the Storm config. When this field is null, no config file was found in the current workspace."),
178
+ colors: ColorConfigSchema.or(ColorConfigMapSchema).describe("Storm theme config values used for styling various package elements"),
179
+ extensions: import_zod.default.record(import_zod.default.any()).optional().default({}).describe("Configuration of each used extension")
180
+ }).describe("Storm Workspace config values used during various dev-ops processes. This type is a combination of the StormPackageConfig and StormProject types. It represents the config of the entire monorepo.");
181
+
182
+ // ../config-tools/src/create-storm-config.ts
183
+ var import_defu2 = __toESM(require("defu"), 1);
184
+
185
+ // ../config-tools/src/config-file/get-config-file.ts
186
+ var import_c12 = require("c12");
187
+ var import_defu = __toESM(require("defu"), 1);
188
+
189
+ // ../config-tools/src/types.ts
190
+ var LogLevel = {
191
+ SILENT: 0,
192
+ FATAL: 10,
193
+ ERROR: 20,
194
+ WARN: 30,
195
+ SUCCESS: 35,
196
+ INFO: 40,
197
+ DEBUG: 60,
198
+ TRACE: 70,
199
+ ALL: 100
200
+ };
201
+ var LogLevelLabel = {
202
+ SILENT: "silent",
203
+ FATAL: "fatal",
204
+ ERROR: "error",
205
+ WARN: "warn",
206
+ SUCCESS: "success",
207
+ INFO: "info",
208
+ DEBUG: "debug",
209
+ TRACE: "trace",
210
+ ALL: "all"
211
+ };
212
+
213
+ // ../config/src/types.ts
214
+ var COLOR_KEYS = [
215
+ "dark",
216
+ "light",
217
+ "base",
218
+ "brand",
219
+ "alternate",
220
+ "accent",
221
+ "link",
222
+ "success",
223
+ "help",
224
+ "info",
225
+ "warning",
226
+ "danger",
227
+ "fatal",
228
+ "positive",
229
+ "negative"
230
+ ];
231
+
232
+ // ../config-tools/src/utilities/get-default-config.ts
233
+ var import_node_fs2 = require("fs");
234
+ var import_node_path2 = require("path");
235
+
236
+ // ../config-tools/src/utilities/correct-paths.ts
237
+ var import_devkit = require("@nx/devkit");
238
+ var correctPaths = /* @__PURE__ */ __name((path2) => {
239
+ if (!path2) {
240
+ return "";
241
+ }
242
+ if (!path2.toUpperCase().startsWith("C:") && path2.includes("\\")) {
243
+ path2 = `C:${path2}`;
244
+ }
245
+ return path2.replaceAll("\\", "/");
246
+ }, "correctPaths");
247
+ var joinPaths = /* @__PURE__ */ __name((...paths) => {
248
+ if (!paths || paths.length === 0) {
249
+ return "";
250
+ }
251
+ return correctPaths((0, import_devkit.joinPathFragments)(...paths.map((path2) => correctPaths(path2))));
252
+ }, "joinPaths");
253
+
254
+ // ../config-tools/src/utilities/find-up.ts
255
+ var import_node_fs = require("fs");
256
+ var import_node_path = require("path");
257
+ var MAX_PATH_SEARCH_DEPTH = 30;
258
+ var depth = 0;
259
+ function findFolderUp(startPath, endFileNames) {
260
+ const _startPath = startPath ?? process.cwd();
261
+ if (endFileNames.some((endFileName) => (0, import_node_fs.existsSync)((0, import_node_path.join)(_startPath, endFileName)))) {
262
+ return _startPath;
263
+ }
264
+ if (_startPath !== "/" && depth++ < MAX_PATH_SEARCH_DEPTH) {
265
+ const parent = (0, import_node_path.join)(_startPath, "..");
266
+ return findFolderUp(parent, endFileNames);
267
+ }
268
+ return void 0;
269
+ }
270
+ __name(findFolderUp, "findFolderUp");
271
+
272
+ // ../config-tools/src/utilities/find-workspace-root.ts
273
+ var rootFiles = [
274
+ "storm.json",
275
+ "storm.json",
276
+ "storm.yaml",
277
+ "storm.yml",
278
+ "storm.js",
279
+ "storm.ts",
280
+ ".storm.json",
281
+ ".storm.yaml",
282
+ ".storm.yml",
283
+ ".storm.js",
284
+ ".storm.ts",
285
+ "lerna.json",
286
+ "nx.json",
287
+ "turbo.json",
288
+ "npm-workspace.json",
289
+ "yarn-workspace.json",
290
+ "pnpm-workspace.json",
291
+ "npm-workspace.yaml",
292
+ "yarn-workspace.yaml",
293
+ "pnpm-workspace.yaml",
294
+ "npm-workspace.yml",
295
+ "yarn-workspace.yml",
296
+ "pnpm-workspace.yml",
297
+ "npm-lock.json",
298
+ "yarn-lock.json",
299
+ "pnpm-lock.json",
300
+ "npm-lock.yaml",
301
+ "yarn-lock.yaml",
302
+ "pnpm-lock.yaml",
303
+ "npm-lock.yml",
304
+ "yarn-lock.yml",
305
+ "pnpm-lock.yml",
306
+ "bun.lockb"
307
+ ];
308
+ function findWorkspaceRootSafe(pathInsideMonorepo) {
309
+ if (process.env.STORM_WORKSPACE_ROOT || process.env.NX_WORKSPACE_ROOT_PATH) {
310
+ return correctPaths(process.env.STORM_WORKSPACE_ROOT ?? process.env.NX_WORKSPACE_ROOT_PATH);
311
+ }
312
+ return correctPaths(findFolderUp(pathInsideMonorepo ?? process.cwd(), rootFiles));
313
+ }
314
+ __name(findWorkspaceRootSafe, "findWorkspaceRootSafe");
315
+ function findWorkspaceRoot(pathInsideMonorepo) {
316
+ const result = findWorkspaceRootSafe(pathInsideMonorepo);
317
+ if (!result) {
318
+ throw new Error(`Cannot find workspace root upwards from known path. Files search list includes:
319
+ ${rootFiles.join("\n")}
320
+ Path: ${pathInsideMonorepo ? pathInsideMonorepo : process.cwd()}`);
321
+ }
322
+ return result;
323
+ }
324
+ __name(findWorkspaceRoot, "findWorkspaceRoot");
325
+
326
+ // ../config-tools/src/utilities/get-default-config.ts
327
+ var DEFAULT_COLOR_CONFIG = {
328
+ "light": {
329
+ "background": "#fafafa",
330
+ "foreground": "#1d1e22",
331
+ "brand": "#1fb2a6",
332
+ "alternate": "#db2777",
333
+ "help": "#5C4EE5",
334
+ "success": "#087f5b",
335
+ "info": "#0550ae",
336
+ "warning": "#e3b341",
337
+ "danger": "#D8314A",
338
+ "positive": "#22c55e",
339
+ "negative": "#dc2626"
340
+ },
341
+ "dark": {
342
+ "background": "#1d1e22",
343
+ "foreground": "#cbd5e1",
344
+ "brand": "#2dd4bf",
345
+ "alternate": "#db2777",
346
+ "help": "#818cf8",
347
+ "success": "#10b981",
348
+ "info": "#58a6ff",
349
+ "warning": "#f3d371",
350
+ "danger": "#D8314A",
351
+ "positive": "#22c55e",
352
+ "negative": "#dc2626"
353
+ }
354
+ };
355
+ var getDefaultConfig = /* @__PURE__ */ __name((root) => {
356
+ let license = STORM_DEFAULT_LICENSE;
357
+ let homepage = STORM_DEFAULT_HOMEPAGE;
358
+ let name;
359
+ let namespace;
360
+ let repository;
361
+ const workspaceRoot = findWorkspaceRoot(root);
362
+ if ((0, import_node_fs2.existsSync)((0, import_node_path2.join)(workspaceRoot, "package.json"))) {
363
+ const file = (0, import_node_fs2.readFileSync)((0, import_node_path2.join)(workspaceRoot, "package.json"), {
364
+ encoding: "utf8"
365
+ });
366
+ if (file) {
367
+ const packageJson = JSON.parse(file);
368
+ if (packageJson.name) {
369
+ name = packageJson.name;
370
+ }
371
+ if (packageJson.namespace) {
372
+ namespace = packageJson.namespace;
373
+ }
374
+ if (packageJson.repository?.url) {
375
+ repository = packageJson.repository?.url;
376
+ }
377
+ if (packageJson.license) {
378
+ license = packageJson.license;
379
+ }
380
+ if (packageJson.homepage) {
381
+ homepage = packageJson.homepage;
382
+ }
383
+ }
384
+ }
385
+ return {
386
+ workspaceRoot,
387
+ name,
388
+ namespace,
389
+ repository,
390
+ license,
391
+ homepage,
392
+ docs: `${homepage || STORM_DEFAULT_HOMEPAGE}/docs`,
393
+ licensing: `${homepage || STORM_DEFAULT_HOMEPAGE}/license`
394
+ };
395
+ }, "getDefaultConfig");
396
+
397
+ // ../config-tools/src/logger/chalk.ts
398
+ var import_chalk = __toESM(require("chalk"), 1);
399
+ var chalkDefault = {
400
+ hex: /* @__PURE__ */ __name((_) => (message) => message, "hex"),
401
+ bgHex: /* @__PURE__ */ __name((_) => ({
402
+ whiteBright: /* @__PURE__ */ __name((message) => message, "whiteBright")
403
+ }), "bgHex"),
404
+ whiteBright: /* @__PURE__ */ __name((message) => message, "whiteBright"),
405
+ gray: /* @__PURE__ */ __name((message) => message, "gray"),
406
+ bold: {
407
+ hex: /* @__PURE__ */ __name((_) => (message) => message, "hex"),
408
+ bgHex: /* @__PURE__ */ __name((_) => ({
409
+ whiteBright: /* @__PURE__ */ __name((message) => message, "whiteBright")
410
+ }), "bgHex"),
411
+ whiteBright: /* @__PURE__ */ __name((message) => message, "whiteBright")
412
+ },
413
+ dim: {
414
+ hex: /* @__PURE__ */ __name((_) => (message) => message, "hex"),
415
+ gray: /* @__PURE__ */ __name((message) => message, "gray")
416
+ }
417
+ };
418
+ var getChalk = /* @__PURE__ */ __name(() => {
419
+ let _chalk = import_chalk.default;
420
+ if (!_chalk?.hex || !_chalk?.bold?.hex || !_chalk?.bgHex || !_chalk?.whiteBright) {
421
+ _chalk = chalkDefault;
422
+ }
423
+ return _chalk;
424
+ }, "getChalk");
425
+
426
+ // ../config-tools/src/logger/is-unicode-supported.ts
427
+ var import_node_process = __toESM(require("process"), 1);
428
+ function isUnicodeSupported() {
429
+ const { env } = import_node_process.default;
430
+ const { TERM, TERM_PROGRAM } = env;
431
+ if (import_node_process.default.platform !== "win32") {
432
+ return TERM !== "linux";
433
+ }
434
+ return Boolean(env.WT_SESSION) || // Windows Terminal
435
+ Boolean(env.TERMINUS_SUBLIME) || // Terminus (<0.2.27)
436
+ env.ConEmuTask === "{cmd::Cmder}" || // ConEmu and cmder
437
+ TERM_PROGRAM === "Terminus-Sublime" || TERM_PROGRAM === "vscode" || TERM === "xterm-256color" || TERM === "alacritty" || TERM === "rxvt-unicode" || TERM === "rxvt-unicode-256color" || env.TERMINAL_EMULATOR === "JetBrains-JediTerm";
438
+ }
439
+ __name(isUnicodeSupported, "isUnicodeSupported");
440
+
441
+ // ../config-tools/src/logger/console-icons.ts
442
+ var useIcon = /* @__PURE__ */ __name((c, fallback) => isUnicodeSupported() ? c : fallback, "useIcon");
443
+ var CONSOLE_ICONS = {
444
+ [LogLevelLabel.ERROR]: useIcon("\u2718", "\xD7"),
445
+ [LogLevelLabel.FATAL]: useIcon("\u{1F480}", "\xD7"),
446
+ [LogLevelLabel.WARN]: useIcon("\u26A0", "\u203C"),
447
+ [LogLevelLabel.INFO]: useIcon("\u2139", "i"),
448
+ [LogLevelLabel.SUCCESS]: useIcon("\u2714", "\u221A"),
449
+ [LogLevelLabel.DEBUG]: useIcon("\u{1F6E0}", "D"),
450
+ [LogLevelLabel.TRACE]: useIcon("\u{1F6E0}", "T"),
451
+ [LogLevelLabel.ALL]: useIcon("\u2709", "\u2192")
452
+ };
453
+
454
+ // ../config-tools/src/logger/format-timestamp.ts
455
+ var formatTimestamp = /* @__PURE__ */ __name((date = /* @__PURE__ */ new Date()) => {
456
+ return `${date.toLocaleDateString()} ${date.toLocaleTimeString()}`;
457
+ }, "formatTimestamp");
458
+
459
+ // ../config-tools/src/logger/get-log-level.ts
460
+ var getLogLevel = /* @__PURE__ */ __name((label) => {
461
+ switch (label) {
462
+ case "all":
463
+ return LogLevel.ALL;
464
+ case "trace":
465
+ return LogLevel.TRACE;
466
+ case "debug":
467
+ return LogLevel.DEBUG;
468
+ case "info":
469
+ return LogLevel.INFO;
470
+ case "warn":
471
+ return LogLevel.WARN;
472
+ case "error":
473
+ return LogLevel.ERROR;
474
+ case "fatal":
475
+ return LogLevel.FATAL;
476
+ case "silent":
477
+ return LogLevel.SILENT;
478
+ default:
479
+ return LogLevel.INFO;
480
+ }
481
+ }, "getLogLevel");
482
+ var getLogLevelLabel = /* @__PURE__ */ __name((logLevel = LogLevel.INFO) => {
483
+ if (logLevel >= LogLevel.ALL) {
484
+ return LogLevelLabel.ALL;
485
+ }
486
+ if (logLevel >= LogLevel.TRACE) {
487
+ return LogLevelLabel.TRACE;
488
+ }
489
+ if (logLevel >= LogLevel.DEBUG) {
490
+ return LogLevelLabel.DEBUG;
491
+ }
492
+ if (logLevel >= LogLevel.INFO) {
493
+ return LogLevelLabel.INFO;
494
+ }
495
+ if (logLevel >= LogLevel.WARN) {
496
+ return LogLevelLabel.WARN;
497
+ }
498
+ if (logLevel >= LogLevel.ERROR) {
499
+ return LogLevelLabel.ERROR;
500
+ }
501
+ if (logLevel >= LogLevel.FATAL) {
502
+ return LogLevelLabel.FATAL;
503
+ }
504
+ if (logLevel <= LogLevel.SILENT) {
505
+ return LogLevelLabel.SILENT;
506
+ }
507
+ return LogLevelLabel.INFO;
508
+ }, "getLogLevelLabel");
509
+ var isVerbose = /* @__PURE__ */ __name((label = LogLevelLabel.SILENT) => {
510
+ const logLevel = typeof label === "string" ? getLogLevel(label) : label;
511
+ return logLevel >= LogLevel.DEBUG;
512
+ }, "isVerbose");
513
+
514
+ // ../config-tools/src/logger/console.ts
515
+ var getLogFn = /* @__PURE__ */ __name((logLevel = LogLevel.INFO, config = {}, _chalk = getChalk()) => {
516
+ const colors2 = !config.colors?.dark && !config.colors?.["base"] && !config.colors?.["base"]?.dark ? DEFAULT_COLOR_CONFIG : config.colors?.dark && typeof config.colors.dark === "string" ? config.colors : config.colors?.["base"]?.dark && typeof config.colors["base"].dark === "string" ? config.colors["base"].dark : config.colors?.["base"] ? config.colors?.["base"] : DEFAULT_COLOR_CONFIG;
517
+ const configLogLevel = config.logLevel || process.env.STORM_LOG_LEVEL || LogLevelLabel.INFO;
518
+ if (typeof logLevel === "number" && (logLevel >= getLogLevel(configLogLevel) || logLevel <= LogLevel.SILENT) || typeof logLevel === "string" && getLogLevel(logLevel) >= getLogLevel(configLogLevel)) {
519
+ return (_) => {
520
+ };
521
+ }
522
+ if (typeof logLevel === "number" && LogLevel.FATAL >= logLevel || typeof logLevel === "string" && LogLevel.FATAL >= getLogLevel(logLevel)) {
523
+ return (message) => {
524
+ console.error(`
525
+ ${_chalk.gray(formatTimestamp())} ${_chalk.hex(colors2.fatal ?? "#7d1a1a")(`[${CONSOLE_ICONS[LogLevelLabel.FATAL]} Fatal]`)} ${_chalk.bold.whiteBright(formatLogMessage(message))}
526
+ `);
527
+ };
528
+ }
529
+ if (typeof logLevel === "number" && LogLevel.ERROR >= logLevel || typeof logLevel === "string" && LogLevel.ERROR >= getLogLevel(logLevel)) {
530
+ return (message) => {
531
+ console.error(`
532
+ ${_chalk.gray(formatTimestamp())} ${_chalk.hex(colors2.danger ?? "#f85149")(`[${CONSOLE_ICONS[LogLevelLabel.ERROR]} Error]`)} ${_chalk.bold.whiteBright(formatLogMessage(message))}
533
+ `);
534
+ };
535
+ }
536
+ if (typeof logLevel === "number" && LogLevel.WARN >= logLevel || typeof logLevel === "string" && LogLevel.WARN >= getLogLevel(logLevel)) {
537
+ return (message) => {
538
+ console.warn(`
539
+ ${_chalk.gray(formatTimestamp())} ${_chalk.hex(colors2.warning ?? "#e3b341")(`[${CONSOLE_ICONS[LogLevelLabel.WARN]} Warn]`)} ${_chalk.bold.whiteBright(formatLogMessage(message))}
540
+ `);
541
+ };
542
+ }
543
+ if (typeof logLevel === "number" && LogLevel.SUCCESS >= logLevel || typeof logLevel === "string" && LogLevel.SUCCESS >= getLogLevel(logLevel)) {
544
+ return (message) => {
545
+ console.info(`
546
+ ${_chalk.gray(formatTimestamp())} ${_chalk.hex(colors2.success ?? "#56d364")(`[${CONSOLE_ICONS[LogLevelLabel.SUCCESS]} Success]`)} ${_chalk.bold.whiteBright(formatLogMessage(message))}
547
+ `);
548
+ };
549
+ }
550
+ if (typeof logLevel === "number" && LogLevel.INFO >= logLevel || typeof logLevel === "string" && LogLevel.INFO >= getLogLevel(logLevel)) {
551
+ return (message) => {
552
+ console.info(`
553
+ ${_chalk.gray(formatTimestamp())} ${_chalk.hex(colors2.info ?? "#58a6ff")(`[${CONSOLE_ICONS[LogLevelLabel.INFO]} Info]`)} ${_chalk.bold.whiteBright(formatLogMessage(message))}
554
+ `);
555
+ };
556
+ }
557
+ if (typeof logLevel === "number" && LogLevel.TRACE >= logLevel || typeof logLevel === "string" && LogLevel.TRACE >= getLogLevel(logLevel)) {
558
+ return (message) => {
559
+ console.debug(`
560
+ ${_chalk.gray(formatTimestamp())} ${_chalk.hex(colors2.brand ?? "#1fb2a6")(`[${CONSOLE_ICONS[LogLevelLabel.DEBUG]} Debug]`)} ${_chalk.bold.whiteBright(formatLogMessage(message))}
561
+ `);
562
+ };
563
+ }
564
+ return (message) => {
565
+ console.log(`
566
+ ${_chalk.gray(formatTimestamp())} ${_chalk.hex(colors2.brand ?? "#1fb2a6")(`[${CONSOLE_ICONS[LogLevelLabel.ALL]} System]`)} ${_chalk.bold.whiteBright(formatLogMessage(message))}
567
+ `);
568
+ };
569
+ }, "getLogFn");
570
+ var writeFatal = /* @__PURE__ */ __name((message, config) => getLogFn(LogLevel.FATAL, config)(message), "writeFatal");
571
+ var writeError = /* @__PURE__ */ __name((message, config) => getLogFn(LogLevel.ERROR, config)(message), "writeError");
572
+ var writeWarning = /* @__PURE__ */ __name((message, config) => getLogFn(LogLevel.WARN, config)(message), "writeWarning");
573
+ var writeInfo = /* @__PURE__ */ __name((message, config) => getLogFn(LogLevel.INFO, config)(message), "writeInfo");
574
+ var writeSuccess = /* @__PURE__ */ __name((message, config) => getLogFn(LogLevel.SUCCESS, config)(message), "writeSuccess");
575
+ var writeDebug = /* @__PURE__ */ __name((message, config) => getLogFn(LogLevel.DEBUG, config)(message), "writeDebug");
576
+ var writeTrace = /* @__PURE__ */ __name((message, config) => getLogFn(LogLevel.TRACE, config)(message), "writeTrace");
577
+ var writeSystem = /* @__PURE__ */ __name((message, config) => getLogFn(LogLevel.ALL, config)(message), "writeSystem");
578
+ var getStopwatch = /* @__PURE__ */ __name((name) => {
579
+ const start = process.hrtime();
580
+ return () => {
581
+ const end = process.hrtime(start);
582
+ console.info(`
583
+ > \u23F1\uFE0F The${name ? ` ${name}` : ""} process took ${Math.round(end[0] * 1e3 + end[1] / 1e6)}ms to complete
584
+
585
+ `);
586
+ };
587
+ }, "getStopwatch");
588
+ var MAX_DEPTH = 4;
589
+ var formatLogMessage = /* @__PURE__ */ __name((message, options = {}, depth2 = 0) => {
590
+ if (depth2 > MAX_DEPTH) {
591
+ return "<max depth>";
592
+ }
593
+ const prefix = options.prefix ?? "-";
594
+ const skip = options.skip ?? [];
595
+ return typeof message === "undefined" || message === null || !message && typeof message !== "boolean" ? "<none>" : typeof message === "string" ? message : Array.isArray(message) ? `
596
+ ${message.map((item, index) => ` ${prefix}> #${index} = ${formatLogMessage(item, {
597
+ prefix: `${prefix}-`,
598
+ skip
599
+ }, depth2 + 1)}`).join("\n")}` : typeof message === "object" ? `
600
+ ${Object.keys(message).filter((key) => !skip.includes(key)).map((key) => ` ${prefix}> ${key} = ${_isFunction(message[key]) ? "<function>" : typeof message[key] === "object" ? formatLogMessage(message[key], {
601
+ prefix: `${prefix}-`,
602
+ skip
603
+ }, depth2 + 1) : message[key]}`).join("\n")}` : message;
604
+ }, "formatLogMessage");
605
+ var _isFunction = /* @__PURE__ */ __name((value) => {
606
+ try {
607
+ return value instanceof Function || typeof value === "function" || !!(value?.constructor && value?.call && value?.apply);
608
+ } catch (e) {
609
+ return false;
610
+ }
611
+ }, "_isFunction");
612
+
613
+ // ../config-tools/src/utilities/process-handler.ts
614
+ var exitWithError = /* @__PURE__ */ __name((config) => {
615
+ writeFatal("Exiting script with an error status...", config);
616
+ process.exit(1);
617
+ }, "exitWithError");
618
+ var exitWithSuccess = /* @__PURE__ */ __name((config) => {
619
+ writeSuccess("Script completed successfully. Exiting...", config);
620
+ process.exit(0);
621
+ }, "exitWithSuccess");
622
+ var handleProcess = /* @__PURE__ */ __name((config) => {
623
+ writeTrace(`Using the following arguments to process the script: ${process.argv.join(", ")}`, config);
624
+ process.on("unhandledRejection", (error) => {
625
+ writeError(`An Unhandled Rejection occurred while running the program: ${error}`, config);
626
+ exitWithError(config);
627
+ });
628
+ process.on("uncaughtException", (error) => {
629
+ writeError(`An Uncaught Exception occurred while running the program: ${error.message}
630
+ Stacktrace: ${error.stack}`, config);
631
+ exitWithError(config);
632
+ });
633
+ process.on("SIGTERM", (signal) => {
634
+ writeError(`The program terminated with signal code: ${signal}`, config);
635
+ exitWithError(config);
636
+ });
637
+ process.on("SIGINT", (signal) => {
638
+ writeError(`The program terminated with signal code: ${signal}`, config);
639
+ exitWithError(config);
640
+ });
641
+ process.on("SIGHUP", (signal) => {
642
+ writeError(`The program terminated with signal code: ${signal}`, config);
643
+ exitWithError(config);
644
+ });
645
+ }, "handleProcess");
646
+
647
+ // ../config-tools/src/config-file/get-config-file.ts
648
+ var getConfigFileByName = /* @__PURE__ */ __name(async (fileName, filePath, options = {}) => {
649
+ const workspacePath = filePath || findWorkspaceRoot(filePath);
650
+ let config = await (0, import_c12.loadConfig)({
651
+ cwd: workspacePath,
652
+ packageJson: true,
653
+ name: fileName,
654
+ envName: fileName?.toUpperCase(),
655
+ jitiOptions: {
656
+ debug: false,
657
+ fsCache: process.env.STORM_SKIP_CACHE === "true" ? false : joinPaths(process.env.STORM_CACHE_DIR || "node_modules/.cache/storm", "jiti")
658
+ },
659
+ ...options
660
+ });
661
+ if (!config || Object.keys(config).length === 0) {
662
+ config = await (0, import_c12.loadConfig)({
663
+ cwd: workspacePath,
664
+ packageJson: true,
665
+ name: fileName,
666
+ envName: fileName?.toUpperCase(),
667
+ jitiOptions: {
668
+ debug: false,
669
+ fsCache: process.env.STORM_SKIP_CACHE === "true" ? false : joinPaths(process.env.STORM_CACHE_DIR || "node_modules/.cache/storm", "jiti")
670
+ },
671
+ configFile: fileName,
672
+ ...options
673
+ });
674
+ }
675
+ return config;
676
+ }, "getConfigFileByName");
677
+ var getConfigFile = /* @__PURE__ */ __name(async (filePath, additionalFileNames = []) => {
678
+ const workspacePath = filePath ? filePath : findWorkspaceRoot(filePath);
679
+ const result = await getConfigFileByName("storm", workspacePath);
680
+ let config = result.config;
681
+ const configFile = result.configFile;
682
+ if (config && configFile && Object.keys(config).length > 0) {
683
+ writeSystem(`Found Storm configuration file "${configFile.includes(`${workspacePath}/`) ? configFile.replace(`${workspacePath}/`, "") : configFile}" at "${workspacePath}"`, {
684
+ logLevel: "all"
685
+ });
686
+ }
687
+ if (additionalFileNames && additionalFileNames.length > 0) {
688
+ const results = await Promise.all(additionalFileNames.map((fileName) => getConfigFileByName(fileName, workspacePath)));
689
+ for (const result2 of results) {
690
+ if (result2?.config && result2?.configFile && Object.keys(result2.config).length > 0) {
691
+ writeSystem(`Found alternative configuration file "${result2.configFile.includes(`${workspacePath}/`) ? result2.configFile.replace(`${workspacePath}/`, "") : result2.configFile}" at "${workspacePath}"`, {
692
+ logLevel: "all"
693
+ });
694
+ config = (0, import_defu.default)(result2.config ?? {}, config ?? {});
695
+ }
696
+ }
697
+ }
698
+ if (!config) {
699
+ return void 0;
700
+ }
701
+ config.configFile = configFile;
702
+ return config;
703
+ }, "getConfigFile");
704
+
705
+ // ../config-tools/src/env/get-env.ts
706
+ var getConfigEnv = /* @__PURE__ */ __name(() => {
707
+ const prefix = "STORM_";
708
+ let config = {
709
+ extends: process.env[`${prefix}EXTENDS`] || void 0,
710
+ name: process.env[`${prefix}NAME`] || void 0,
711
+ namespace: process.env[`${prefix}NAMESPACE`] || void 0,
712
+ owner: process.env[`${prefix}OWNER`] || void 0,
713
+ bot: {
714
+ name: process.env[`${prefix}BOT_NAME`] || void 0,
715
+ email: process.env[`${prefix}BOT_EMAIL`] || void 0
716
+ },
717
+ organization: process.env[`${prefix}ORGANIZATION`] || void 0,
718
+ packageManager: process.env[`${prefix}PACKAGE_MANAGER`] || void 0,
719
+ license: process.env[`${prefix}LICENSE`] || void 0,
720
+ homepage: process.env[`${prefix}HOMEPAGE`] || void 0,
721
+ docs: process.env[`${prefix}DOCS`] || void 0,
722
+ licensing: process.env[`${prefix}LICENSING`] || void 0,
723
+ timezone: process.env[`${prefix}TIMEZONE`] || process.env.TZ || void 0,
724
+ locale: process.env[`${prefix}LOCALE`] || process.env.LOCALE || void 0,
725
+ configFile: process.env[`${prefix}CONFIG_FILE`] ? correctPaths(process.env[`${prefix}CONFIG_FILE`]) : void 0,
726
+ workspaceRoot: process.env[`${prefix}WORKSPACE_ROOT`] ? correctPaths(process.env[`${prefix}WORKSPACE_ROOT`]) : void 0,
727
+ directories: {
728
+ cache: process.env[`${prefix}CACHE_DIR`] ? correctPaths(process.env[`${prefix}CACHE_DIR`]) : void 0,
729
+ data: process.env[`${prefix}DATA_DIR`] ? correctPaths(process.env[`${prefix}DATA_DIR`]) : void 0,
730
+ config: process.env[`${prefix}CONFIG_DIR`] ? correctPaths(process.env[`${prefix}CONFIG_DIR`]) : void 0,
731
+ temp: process.env[`${prefix}TEMP_DIR`] ? correctPaths(process.env[`${prefix}TEMP_DIR`]) : void 0,
732
+ log: process.env[`${prefix}LOG_DIR`] ? correctPaths(process.env[`${prefix}LOG_DIR`]) : void 0,
733
+ build: process.env[`${prefix}BUILD_DIR`] ? correctPaths(process.env[`${prefix}BUILD_DIR`]) : void 0
734
+ },
735
+ skipCache: process.env[`${prefix}SKIP_CACHE`] !== void 0 ? Boolean(process.env[`${prefix}SKIP_CACHE`]) : void 0,
736
+ env: (process.env[`${prefix}ENV`] ?? process.env.NODE_ENV ?? process.env.ENVIRONMENT) || void 0,
737
+ // ci:
738
+ // process.env[`${prefix}CI`] !== undefined
739
+ // ? Boolean(
740
+ // process.env[`${prefix}CI`] ??
741
+ // process.env.CI ??
742
+ // process.env.CONTINUOUS_INTEGRATION
743
+ // )
744
+ // : undefined,
745
+ repository: process.env[`${prefix}REPOSITORY`] || void 0,
746
+ branch: process.env[`${prefix}BRANCH`] || void 0,
747
+ preid: process.env[`${prefix}PRE_ID`] || void 0,
748
+ externalPackagePatterns: process.env[`${prefix}EXTERNAL_PACKAGE_PATTERNS`] ? JSON.parse(process.env[`${prefix}EXTERNAL_PACKAGE_PATTERNS`]) : [],
749
+ registry: {
750
+ github: process.env[`${prefix}REGISTRY_GITHUB`] || void 0,
751
+ npm: process.env[`${prefix}REGISTRY_NPM`] || void 0,
752
+ cargo: process.env[`${prefix}REGISTRY_CARGO`] || void 0,
753
+ cyclone: process.env[`${prefix}REGISTRY_CYCLONE`] || void 0,
754
+ container: process.env[`${prefix}REGISTRY_CONTAINER`] || void 0
755
+ },
756
+ logLevel: process.env[`${prefix}LOG_LEVEL`] !== null && process.env[`${prefix}LOG_LEVEL`] !== void 0 ? process.env[`${prefix}LOG_LEVEL`] && Number.isSafeInteger(Number.parseInt(process.env[`${prefix}LOG_LEVEL`])) ? getLogLevelLabel(Number.parseInt(process.env[`${prefix}LOG_LEVEL`])) : process.env[`${prefix}LOG_LEVEL`] : void 0
757
+ };
758
+ const themeNames = Object.keys(process.env).filter((envKey) => envKey.startsWith(`${prefix}COLOR_`) && COLOR_KEYS.every((colorKey) => !envKey.startsWith(`${prefix}COLOR_LIGHT_${colorKey}`) && !envKey.startsWith(`${prefix}COLOR_DARK_${colorKey}`)));
759
+ config.colors = themeNames.length > 0 ? themeNames.reduce((ret, themeName) => {
760
+ ret[themeName] = getThemeColorConfigEnv(prefix, themeName);
761
+ return ret;
762
+ }, {}) : getThemeColorConfigEnv(prefix);
763
+ if (config.docs === STORM_DEFAULT_DOCS) {
764
+ if (config.homepage === STORM_DEFAULT_HOMEPAGE) {
765
+ config.docs = `${STORM_DEFAULT_HOMEPAGE}/projects/${config.name}/docs`;
766
+ } else {
767
+ config.docs = `${config.homepage}/docs`;
768
+ }
769
+ }
770
+ if (config.licensing === STORM_DEFAULT_LICENSING) {
771
+ if (config.homepage === STORM_DEFAULT_HOMEPAGE) {
772
+ config.licensing = `${STORM_DEFAULT_HOMEPAGE}/projects/${config.name}/licensing`;
773
+ } else {
774
+ config.licensing = `${config.homepage}/docs`;
775
+ }
776
+ }
777
+ const serializedConfig = process.env[`${prefix}CONFIG`];
778
+ if (serializedConfig) {
779
+ const parsed = JSON.parse(serializedConfig);
780
+ config = {
781
+ ...config,
782
+ ...parsed,
783
+ colors: {
784
+ ...config.colors,
785
+ ...parsed.colors
786
+ },
787
+ extensions: {
788
+ ...config.extensions,
789
+ ...parsed.extensions
790
+ }
791
+ };
792
+ }
793
+ return config;
794
+ }, "getConfigEnv");
795
+ var getThemeColorConfigEnv = /* @__PURE__ */ __name((prefix, theme) => {
796
+ const themeName = `COLOR_${theme && theme !== "base" ? `${theme}_` : ""}`.toUpperCase();
797
+ return process.env[`${prefix}${themeName}LIGHT_BRAND`] || process.env[`${prefix}${themeName}DARK_BRAND`] ? getMultiThemeColorConfigEnv(prefix + themeName) : getSingleThemeColorConfigEnv(prefix + themeName);
798
+ }, "getThemeColorConfigEnv");
799
+ var getSingleThemeColorConfigEnv = /* @__PURE__ */ __name((prefix) => {
800
+ return {
801
+ dark: process.env[`${prefix}DARK`],
802
+ light: process.env[`${prefix}LIGHT`],
803
+ brand: process.env[`${prefix}BRAND`],
804
+ alternate: process.env[`${prefix}ALTERNATE`],
805
+ accent: process.env[`${prefix}ACCENT`],
806
+ link: process.env[`${prefix}LINK`],
807
+ help: process.env[`${prefix}HELP`],
808
+ success: process.env[`${prefix}SUCCESS`],
809
+ info: process.env[`${prefix}INFO`],
810
+ warning: process.env[`${prefix}WARNING`],
811
+ danger: process.env[`${prefix}DANGER`],
812
+ fatal: process.env[`${prefix}FATAL`],
813
+ positive: process.env[`${prefix}POSITIVE`],
814
+ negative: process.env[`${prefix}NEGATIVE`]
815
+ };
816
+ }, "getSingleThemeColorConfigEnv");
817
+ var getMultiThemeColorConfigEnv = /* @__PURE__ */ __name((prefix) => {
818
+ return {
819
+ light: getBaseThemeColorConfigEnv(`${prefix}_LIGHT_`),
820
+ dark: getBaseThemeColorConfigEnv(`${prefix}_DARK_`)
821
+ };
822
+ }, "getMultiThemeColorConfigEnv");
823
+ var getBaseThemeColorConfigEnv = /* @__PURE__ */ __name((prefix) => {
824
+ return {
825
+ foreground: process.env[`${prefix}FOREGROUND`],
826
+ background: process.env[`${prefix}BACKGROUND`],
827
+ brand: process.env[`${prefix}BRAND`],
828
+ alternate: process.env[`${prefix}ALTERNATE`],
829
+ accent: process.env[`${prefix}ACCENT`],
830
+ link: process.env[`${prefix}LINK`],
831
+ help: process.env[`${prefix}HELP`],
832
+ success: process.env[`${prefix}SUCCESS`],
833
+ info: process.env[`${prefix}INFO`],
834
+ warning: process.env[`${prefix}WARNING`],
835
+ danger: process.env[`${prefix}DANGER`],
836
+ fatal: process.env[`${prefix}FATAL`],
837
+ positive: process.env[`${prefix}POSITIVE`],
838
+ negative: process.env[`${prefix}NEGATIVE`]
839
+ };
840
+ }, "getBaseThemeColorConfigEnv");
841
+
842
+ // ../config-tools/src/env/set-env.ts
843
+ var setExtensionEnv = /* @__PURE__ */ __name((extensionName, extension) => {
844
+ for (const key of Object.keys(extension ?? {})) {
845
+ if (extension[key]) {
846
+ const result = key?.replace(/([A-Z])+/g, (input) => input ? input[0]?.toUpperCase() + input.slice(1) : "").split(/(?=[A-Z])|[.\-\s_]/).map((x) => x.toLowerCase()) ?? [];
847
+ let extensionKey;
848
+ if (result.length === 0) {
849
+ return;
850
+ }
851
+ if (result.length === 1) {
852
+ extensionKey = result[0]?.toUpperCase() ?? "";
853
+ } else {
854
+ extensionKey = result.reduce((ret, part) => {
855
+ return `${ret}_${part.toLowerCase()}`;
856
+ });
857
+ }
858
+ process.env[`STORM_EXTENSION_${extensionName.toUpperCase()}_${extensionKey.toUpperCase()}`] = extension[key];
859
+ }
860
+ }
861
+ }, "setExtensionEnv");
862
+ var setConfigEnv = /* @__PURE__ */ __name((config) => {
863
+ const prefix = "STORM_";
864
+ if (config.extends) {
865
+ process.env[`${prefix}EXTENDS`] = config.extends;
866
+ }
867
+ if (config.name) {
868
+ process.env[`${prefix}NAME`] = config.name;
869
+ }
870
+ if (config.namespace) {
871
+ process.env[`${prefix}NAMESPACE`] = config.namespace;
872
+ }
873
+ if (config.owner) {
874
+ process.env[`${prefix}OWNER`] = config.owner;
875
+ }
876
+ if (config.bot) {
877
+ process.env[`${prefix}BOT_NAME`] = config.bot.name;
878
+ process.env[`${prefix}BOT_EMAIL`] = config.bot.email;
879
+ }
880
+ if (config.organization) {
881
+ process.env[`${prefix}ORGANIZATION`] = config.organization;
882
+ }
883
+ if (config.packageManager) {
884
+ process.env[`${prefix}PACKAGE_MANAGER`] = config.packageManager;
885
+ }
886
+ if (config.license) {
887
+ process.env[`${prefix}LICENSE`] = config.license;
888
+ }
889
+ if (config.homepage) {
890
+ process.env[`${prefix}HOMEPAGE`] = config.homepage;
891
+ }
892
+ if (config.docs) {
893
+ process.env[`${prefix}DOCS`] = config.docs;
894
+ }
895
+ if (config.licensing) {
896
+ process.env[`${prefix}LICENSING`] = config.licensing;
897
+ }
898
+ if (config.timezone) {
899
+ process.env[`${prefix}TIMEZONE`] = config.timezone;
900
+ process.env.TZ = config.timezone;
901
+ process.env.DEFAULT_TIMEZONE = config.timezone;
902
+ }
903
+ if (config.locale) {
904
+ process.env[`${prefix}LOCALE`] = config.locale;
905
+ process.env.LOCALE = config.locale;
906
+ process.env.DEFAULT_LOCALE = config.locale;
907
+ process.env.LANG = config.locale ? `${config.locale.replaceAll("-", "_")}.UTF-8` : "en_US.UTF-8";
908
+ }
909
+ if (config.configFile) {
910
+ process.env[`${prefix}CONFIG_FILE`] = correctPaths(config.configFile);
911
+ }
912
+ if (config.workspaceRoot) {
913
+ process.env[`${prefix}WORKSPACE_ROOT`] = correctPaths(config.workspaceRoot);
914
+ process.env.NX_WORKSPACE_ROOT = correctPaths(config.workspaceRoot);
915
+ process.env.NX_WORKSPACE_ROOT_PATH = correctPaths(config.workspaceRoot);
916
+ }
917
+ if (config.directories) {
918
+ if (!config.skipCache && config.directories.cache) {
919
+ process.env[`${prefix}CACHE_DIR`] = correctPaths(config.directories.cache);
920
+ }
921
+ if (config.directories.data) {
922
+ process.env[`${prefix}DATA_DIR`] = correctPaths(config.directories.data);
923
+ }
924
+ if (config.directories.config) {
925
+ process.env[`${prefix}CONFIG_DIR`] = correctPaths(config.directories.config);
926
+ }
927
+ if (config.directories.temp) {
928
+ process.env[`${prefix}TEMP_DIR`] = correctPaths(config.directories.temp);
929
+ }
930
+ if (config.directories.log) {
931
+ process.env[`${prefix}LOG_DIR`] = correctPaths(config.directories.log);
932
+ }
933
+ if (config.directories.build) {
934
+ process.env[`${prefix}BUILD_DIR`] = correctPaths(config.directories.build);
935
+ }
936
+ }
937
+ if (config.skipCache !== void 0) {
938
+ process.env[`${prefix}SKIP_CACHE`] = String(config.skipCache);
939
+ if (config.skipCache) {
940
+ process.env.NX_SKIP_NX_CACHE ??= String(config.skipCache);
941
+ process.env.NX_CACHE_PROJECT_GRAPH ??= String(config.skipCache);
942
+ }
943
+ }
944
+ if (config.env) {
945
+ process.env[`${prefix}ENV`] = config.env;
946
+ process.env.NODE_ENV = config.env;
947
+ process.env.ENVIRONMENT = config.env;
948
+ }
949
+ if (config.colors?.base?.light || config.colors?.base?.dark) {
950
+ for (const key of Object.keys(config.colors)) {
951
+ setThemeColorConfigEnv(`${prefix}COLOR_${key}_`, config.colors[key]);
952
+ }
953
+ } else {
954
+ setThemeColorConfigEnv(`${prefix}COLOR_`, config.colors);
955
+ }
956
+ if (config.repository) {
957
+ process.env[`${prefix}REPOSITORY`] = config.repository;
958
+ }
959
+ if (config.branch) {
960
+ process.env[`${prefix}BRANCH`] = config.branch;
961
+ }
962
+ if (config.preid) {
963
+ process.env[`${prefix}PRE_ID`] = String(config.preid);
964
+ }
965
+ if (config.externalPackagePatterns) {
966
+ process.env[`${prefix}EXTERNAL_PACKAGE_PATTERNS`] = JSON.stringify(config.externalPackagePatterns);
967
+ }
968
+ if (config.registry) {
969
+ if (config.registry.github) {
970
+ process.env[`${prefix}REGISTRY_GITHUB`] = String(config.registry.github);
971
+ }
972
+ if (config.registry.npm) {
973
+ process.env[`${prefix}REGISTRY_NPM`] = String(config.registry.npm);
974
+ }
975
+ if (config.registry.cargo) {
976
+ process.env[`${prefix}REGISTRY_CARGO`] = String(config.registry.cargo);
977
+ }
978
+ if (config.registry.cyclone) {
979
+ process.env[`${prefix}REGISTRY_CYCLONE`] = String(config.registry.cyclone);
980
+ }
981
+ if (config.registry.container) {
982
+ process.env[`${prefix}REGISTRY_CONTAINER`] = String(config.registry.cyclone);
983
+ }
984
+ }
985
+ if (config.logLevel) {
986
+ process.env[`${prefix}LOG_LEVEL`] = String(config.logLevel);
987
+ process.env.LOG_LEVEL = String(config.logLevel);
988
+ process.env.NX_VERBOSE_LOGGING = String(getLogLevel(config.logLevel) >= LogLevel.DEBUG ? true : false);
989
+ process.env.RUST_BACKTRACE = getLogLevel(config.logLevel) >= LogLevel.DEBUG ? "full" : "none";
990
+ }
991
+ process.env[`${prefix}CONFIG`] = JSON.stringify(config);
992
+ for (const key of Object.keys(config.extensions ?? {})) {
993
+ config.extensions[key] && Object.keys(config.extensions[key]) && setExtensionEnv(key, config.extensions[key]);
994
+ }
995
+ }, "setConfigEnv");
996
+ var setThemeColorConfigEnv = /* @__PURE__ */ __name((prefix, config) => {
997
+ return config?.light?.brand || config?.dark?.brand ? setMultiThemeColorConfigEnv(prefix, config) : setSingleThemeColorConfigEnv(prefix, config);
998
+ }, "setThemeColorConfigEnv");
999
+ var setSingleThemeColorConfigEnv = /* @__PURE__ */ __name((prefix, config) => {
1000
+ if (config.dark) {
1001
+ process.env[`${prefix}DARK`] = config.dark;
1002
+ }
1003
+ if (config.light) {
1004
+ process.env[`${prefix}LIGHT`] = config.light;
1005
+ }
1006
+ if (config.brand) {
1007
+ process.env[`${prefix}BRAND`] = config.brand;
1008
+ }
1009
+ if (config.alternate) {
1010
+ process.env[`${prefix}ALTERNATE`] = config.alternate;
1011
+ }
1012
+ if (config.accent) {
1013
+ process.env[`${prefix}ACCENT`] = config.accent;
1014
+ }
1015
+ if (config.link) {
1016
+ process.env[`${prefix}LINK`] = config.link;
1017
+ }
1018
+ if (config.help) {
1019
+ process.env[`${prefix}HELP`] = config.help;
1020
+ }
1021
+ if (config.success) {
1022
+ process.env[`${prefix}SUCCESS`] = config.success;
1023
+ }
1024
+ if (config.info) {
1025
+ process.env[`${prefix}INFO`] = config.info;
1026
+ }
1027
+ if (config.warning) {
1028
+ process.env[`${prefix}WARNING`] = config.warning;
1029
+ }
1030
+ if (config.danger) {
1031
+ process.env[`${prefix}DANGER`] = config.danger;
1032
+ }
1033
+ if (config.fatal) {
1034
+ process.env[`${prefix}FATAL`] = config.fatal;
1035
+ }
1036
+ if (config.positive) {
1037
+ process.env[`${prefix}POSITIVE`] = config.positive;
1038
+ }
1039
+ if (config.negative) {
1040
+ process.env[`${prefix}NEGATIVE`] = config.negative;
1041
+ }
1042
+ }, "setSingleThemeColorConfigEnv");
1043
+ var setMultiThemeColorConfigEnv = /* @__PURE__ */ __name((prefix, config) => {
1044
+ return {
1045
+ light: setBaseThemeColorConfigEnv(`${prefix}LIGHT_`, config.light),
1046
+ dark: setBaseThemeColorConfigEnv(`${prefix}DARK_`, config.dark)
1047
+ };
1048
+ }, "setMultiThemeColorConfigEnv");
1049
+ var setBaseThemeColorConfigEnv = /* @__PURE__ */ __name((prefix, config) => {
1050
+ if (config.foreground) {
1051
+ process.env[`${prefix}FOREGROUND`] = config.foreground;
1052
+ }
1053
+ if (config.background) {
1054
+ process.env[`${prefix}BACKGROUND`] = config.background;
1055
+ }
1056
+ if (config.brand) {
1057
+ process.env[`${prefix}BRAND`] = config.brand;
1058
+ }
1059
+ if (config.alternate) {
1060
+ process.env[`${prefix}ALTERNATE`] = config.alternate;
1061
+ }
1062
+ if (config.accent) {
1063
+ process.env[`${prefix}ACCENT`] = config.accent;
1064
+ }
1065
+ if (config.link) {
1066
+ process.env[`${prefix}LINK`] = config.link;
1067
+ }
1068
+ if (config.help) {
1069
+ process.env[`${prefix}HELP`] = config.help;
1070
+ }
1071
+ if (config.success) {
1072
+ process.env[`${prefix}SUCCESS`] = config.success;
1073
+ }
1074
+ if (config.info) {
1075
+ process.env[`${prefix}INFO`] = config.info;
1076
+ }
1077
+ if (config.warning) {
1078
+ process.env[`${prefix}WARNING`] = config.warning;
1079
+ }
1080
+ if (config.danger) {
1081
+ process.env[`${prefix}DANGER`] = config.danger;
1082
+ }
1083
+ if (config.fatal) {
1084
+ process.env[`${prefix}FATAL`] = config.fatal;
1085
+ }
1086
+ if (config.positive) {
1087
+ process.env[`${prefix}POSITIVE`] = config.positive;
1088
+ }
1089
+ if (config.negative) {
1090
+ process.env[`${prefix}NEGATIVE`] = config.negative;
1091
+ }
1092
+ }, "setBaseThemeColorConfigEnv");
1093
+
1094
+ // ../config-tools/src/create-storm-config.ts
1095
+ var _static_cache = void 0;
1096
+ var loadStormConfig = /* @__PURE__ */ __name(async (workspaceRoot) => {
1097
+ let config = {};
1098
+ if (_static_cache?.data && _static_cache?.timestamp && _static_cache.timestamp >= Date.now() + 3e4) {
1099
+ writeTrace(`Configuration cache hit - ${_static_cache.timestamp}`, _static_cache.data);
1100
+ return _static_cache.data;
1101
+ }
1102
+ let _workspaceRoot = workspaceRoot;
1103
+ if (!_workspaceRoot) {
1104
+ _workspaceRoot = findWorkspaceRoot();
1105
+ }
1106
+ const configFile = await getConfigFile(_workspaceRoot);
1107
+ if (!configFile) {
1108
+ writeWarning("No Storm config file found in the current workspace. Please ensure this is the expected behavior - you can add a `storm.json` file to the root of your workspace if it is not.\n", {
1109
+ logLevel: "all"
1110
+ });
1111
+ }
1112
+ config = (0, import_defu2.default)(getConfigEnv(), configFile, getDefaultConfig(_workspaceRoot));
1113
+ setConfigEnv(config);
1114
+ writeTrace(`\u2699\uFE0F Using Storm configuration:
1115
+ ${formatLogMessage(config)}`, config);
1116
+ return config;
1117
+ }, "loadStormConfig");
1118
+
1119
+ // bin/unbuild.ts
1120
+ var import_commander = require("commander");
1121
+
1122
+ // src/build.ts
1123
+ var import_devkit6 = require("@nx/devkit");
1124
+ var import_js2 = require("@nx/js");
1125
+ var import_buildable_libs_utils4 = require("@nx/js/src/utils/buildable-libs-utils");
1126
+
1127
+ // ../build-tools/src/plugins/swc.ts
1128
+ var import_core = require("@swc/core");
1129
+
1130
+ // ../build-tools/src/plugins/ts-resolve.ts
1131
+ var import_node_fs3 = __toESM(require("fs"));
1132
+ var import_node_module = require("module");
1133
+ var import_node_path3 = __toESM(require("path"));
1134
+ var import_resolve = __toESM(require("resolve"));
1135
+
1136
+ // ../build-tools/src/plugins/type-definitions.ts
1137
+ var import_devkit2 = require("@nx/devkit");
1138
+ var import_path = require("path");
1139
+
1140
+ // ../build-tools/src/utilities/copy-assets.ts
1141
+ var import_devkit3 = require("@nx/devkit");
1142
+ var import_js = require("@nx/js");
1143
+ var import_glob = require("glob");
1144
+ var import_promises2 = require("fs/promises");
1145
+
1146
+ // ../build-tools/src/utilities/read-nx-config.ts
1147
+ var import_node_fs4 = require("fs");
1148
+ var import_promises = require("fs/promises");
1149
+ var readNxConfig = /* @__PURE__ */ __name(async (workspaceRoot) => {
1150
+ let rootDir = workspaceRoot;
1151
+ if (!rootDir) {
1152
+ const config = await loadStormConfig();
1153
+ rootDir = config.workspaceRoot;
1154
+ }
1155
+ const nxJsonPath = joinPaths(rootDir, "nx.json");
1156
+ if (!(0, import_node_fs4.existsSync)(nxJsonPath)) {
1157
+ throw new Error("Cannot find project.json configuration");
1158
+ }
1159
+ const configContent = await (0, import_promises.readFile)(nxJsonPath, "utf8");
1160
+ return JSON.parse(configContent);
1161
+ }, "readNxConfig");
1162
+
1163
+ // ../build-tools/src/utilities/copy-assets.ts
1164
+ var copyAssets = /* @__PURE__ */ __name(async (config, assets, outputPath, projectRoot, projectName, sourceRoot, generatePackageJson2 = true, includeSrc = false, banner, footer) => {
1165
+ const pendingAssets = Array.from(assets ?? []);
1166
+ if (!pendingAssets?.some((asset) => asset?.glob === "*.md")) {
1167
+ pendingAssets.push({
1168
+ input: projectRoot,
1169
+ glob: "*.md",
1170
+ output: "/"
1171
+ });
1172
+ }
1173
+ if (generatePackageJson2 === false) {
1174
+ pendingAssets.push({
1175
+ input: sourceRoot,
1176
+ glob: "package.json",
1177
+ output: "."
1178
+ });
1179
+ }
1180
+ if (!pendingAssets?.some((asset) => asset?.glob === "LICENSE")) {
1181
+ pendingAssets.push({
1182
+ input: "",
1183
+ glob: "LICENSE",
1184
+ output: "."
1185
+ });
1186
+ }
1187
+ if (includeSrc === true) {
1188
+ pendingAssets.push({
1189
+ input: sourceRoot,
1190
+ glob: "**/{*.ts,*.tsx,*.js,*.jsx}",
1191
+ output: "src/"
1192
+ });
1193
+ }
1194
+ const nxJson = readNxConfig(config.workspaceRoot);
1195
+ const projectGraph = (0, import_devkit3.readCachedProjectGraph)();
1196
+ const projectsConfigurations = (0, import_devkit3.readProjectsConfigurationFromProjectGraph)(projectGraph);
1197
+ if (!projectsConfigurations?.projects?.[projectName]) {
1198
+ 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.");
1199
+ }
1200
+ const buildTarget = projectsConfigurations.projects[projectName].targets?.build;
1201
+ if (!buildTarget) {
1202
+ throw new Error(`The Build process failed because the project does not have a valid build target in the project.json file. Check if the file exists in the root of the project at ${joinPaths(projectRoot, "project.json")}`);
1203
+ }
1204
+ const result = await (0, import_js.copyAssets)({
1205
+ assets,
1206
+ watch: false,
1207
+ outputPath
1208
+ }, {
1209
+ root: config.workspaceRoot,
1210
+ targetName: "build",
1211
+ target: buildTarget,
1212
+ projectName,
1213
+ projectGraph,
1214
+ projectsConfigurations,
1215
+ nxJsonConfiguration: nxJson,
1216
+ cwd: config.workspaceRoot,
1217
+ isVerbose: isVerbose(config.logLevel)
1218
+ });
1219
+ if (!result.success) {
1220
+ throw new Error("The Build process failed trying to copy assets");
1221
+ }
1222
+ if (includeSrc === true) {
1223
+ writeDebug(`\u{1F4DD} Adding banner and writing source files: ${joinPaths(outputPath, "src")}`, config);
1224
+ const files = await (0, import_glob.glob)([
1225
+ joinPaths(config.workspaceRoot, outputPath, "src/**/*.ts"),
1226
+ joinPaths(config.workspaceRoot, outputPath, "src/**/*.tsx"),
1227
+ joinPaths(config.workspaceRoot, outputPath, "src/**/*.js"),
1228
+ joinPaths(config.workspaceRoot, outputPath, "src/**/*.jsx")
1229
+ ]);
1230
+ await Promise.allSettled(files.map(async (file) => (0, import_promises2.writeFile)(file, `${banner && typeof banner === "string" ? banner.startsWith("//") ? banner : `// ${banner}` : ""}
1231
+
1232
+ ${await (0, import_promises2.readFile)(file, "utf8")}
1233
+
1234
+ ${footer && typeof footer === "string" ? footer.startsWith("//") ? footer : `// ${footer}` : ""}`)));
1235
+ }
1236
+ }, "copyAssets");
1237
+
1238
+ // ../build-tools/src/utilities/generate-package-json.ts
1239
+ var import_buildable_libs_utils = require("@nx/js/src/utils/buildable-libs-utils");
1240
+ var import_glob2 = require("glob");
1241
+ var import_node_fs5 = require("fs");
1242
+ var import_promises3 = require("fs/promises");
1243
+ var import_project_graph = require("nx/src/project-graph/project-graph");
1244
+ var addPackageDependencies = /* @__PURE__ */ __name(async (workspaceRoot, projectRoot, projectName, packageJson) => {
1245
+ const projectDependencies = (0, import_buildable_libs_utils.calculateProjectBuildableDependencies)(void 0, (0, import_project_graph.readCachedProjectGraph)(), workspaceRoot, projectName, process.env.NX_TASK_TARGET_TARGET || "build", process.env.NX_TASK_TARGET_CONFIGURATION || "production", true);
1246
+ const localPackages = [];
1247
+ for (const project of projectDependencies.dependencies.filter((dep) => dep.node.type === "lib" && dep.node.data.root !== projectRoot && dep.node.data.root !== workspaceRoot)) {
1248
+ const projectNode = project.node;
1249
+ if (projectNode.data.root) {
1250
+ const projectPackageJsonPath = joinPaths(workspaceRoot, projectNode.data.root, "package.json");
1251
+ if ((0, import_node_fs5.existsSync)(projectPackageJsonPath)) {
1252
+ const projectPackageJsonContent = await (0, import_promises3.readFile)(projectPackageJsonPath, "utf8");
1253
+ const projectPackageJson = JSON.parse(projectPackageJsonContent);
1254
+ if (projectPackageJson.private !== false) {
1255
+ localPackages.push(projectPackageJson);
1256
+ }
1257
+ }
1258
+ }
1259
+ }
1260
+ if (localPackages.length > 0) {
1261
+ writeTrace(`\u{1F4E6} Adding local packages to package.json: ${localPackages.map((p) => p.name).join(", ")}`);
1262
+ packageJson.peerDependencies = localPackages.reduce((ret, localPackage) => {
1263
+ if (!ret[localPackage.name]) {
1264
+ ret[localPackage.name] = `>=${localPackage.version || "0.0.1"}`;
1265
+ }
1266
+ return ret;
1267
+ }, packageJson.peerDependencies ?? {});
1268
+ packageJson.peerDependenciesMeta = localPackages.reduce((ret, localPackage) => {
1269
+ if (!ret[localPackage.name]) {
1270
+ ret[localPackage.name] = {
1271
+ optional: false
1272
+ };
1273
+ }
1274
+ return ret;
1275
+ }, packageJson.peerDependenciesMeta ?? {});
1276
+ packageJson.devDependencies = localPackages.reduce((ret, localPackage) => {
1277
+ if (!ret[localPackage.name]) {
1278
+ ret[localPackage.name] = localPackage.version || "0.0.1";
1279
+ }
1280
+ return ret;
1281
+ }, packageJson.peerDependencies ?? {});
1282
+ } else {
1283
+ writeTrace("\u{1F4E6} No local packages dependencies to add to package.json");
1284
+ }
1285
+ return packageJson;
1286
+ }, "addPackageDependencies");
1287
+ var addWorkspacePackageJsonFields = /* @__PURE__ */ __name(async (config, projectRoot, sourceRoot, projectName, includeSrc = false, packageJson) => {
1288
+ const workspaceRoot = config.workspaceRoot ? config.workspaceRoot : findWorkspaceRoot();
1289
+ const workspacePackageJsonContent = await (0, import_promises3.readFile)(joinPaths(workspaceRoot, "package.json"), "utf8");
1290
+ const workspacePackageJson = JSON.parse(workspacePackageJsonContent);
1291
+ packageJson.type ??= "module";
1292
+ packageJson.sideEffects ??= false;
1293
+ if (includeSrc === true) {
1294
+ let distSrc = sourceRoot.replace(projectRoot, "");
1295
+ if (distSrc.startsWith("/")) {
1296
+ distSrc = distSrc.substring(1);
1297
+ }
1298
+ packageJson.source ??= `${joinPaths(distSrc, "index.ts").replaceAll("\\", "/")}`;
1299
+ }
1300
+ packageJson.files ??= [
1301
+ "dist/**/*"
1302
+ ];
1303
+ if (includeSrc === true && !packageJson.files.includes("src")) {
1304
+ packageJson.files.push("src/**/*");
1305
+ }
1306
+ packageJson.publishConfig ??= {
1307
+ access: "public"
1308
+ };
1309
+ packageJson.description ??= workspacePackageJson.description;
1310
+ packageJson.homepage ??= workspacePackageJson.homepage;
1311
+ packageJson.bugs ??= workspacePackageJson.bugs;
1312
+ packageJson.license ??= workspacePackageJson.license;
1313
+ packageJson.keywords ??= workspacePackageJson.keywords;
1314
+ packageJson.funding ??= workspacePackageJson.funding;
1315
+ packageJson.author ??= workspacePackageJson.author;
1316
+ packageJson.maintainers ??= workspacePackageJson.maintainers;
1317
+ if (!packageJson.maintainers && packageJson.author) {
1318
+ packageJson.maintainers = [
1319
+ packageJson.author
1320
+ ];
1321
+ }
1322
+ packageJson.contributors ??= workspacePackageJson.contributors;
1323
+ if (!packageJson.contributors && packageJson.author) {
1324
+ packageJson.contributors = [
1325
+ packageJson.author
1326
+ ];
1327
+ }
1328
+ packageJson.repository ??= workspacePackageJson.repository;
1329
+ packageJson.repository.directory ??= projectRoot ? projectRoot : joinPaths("packages", projectName);
1330
+ return packageJson;
1331
+ }, "addWorkspacePackageJsonFields");
1332
+ var addPackageJsonExport = /* @__PURE__ */ __name((file, type = "module", sourceRoot) => {
1333
+ let entry = file.replaceAll("\\", "/");
1334
+ if (sourceRoot) {
1335
+ entry = entry.replace(sourceRoot, "");
1336
+ }
1337
+ return {
1338
+ "import": {
1339
+ "types": `./dist/${entry}.d.${type === "module" ? "ts" : "mts"}`,
1340
+ "default": `./dist/${entry}.${type === "module" ? "js" : "mjs"}`
1341
+ },
1342
+ "require": {
1343
+ "types": `./dist/${entry}.d.${type === "commonjs" ? "ts" : "cts"}`,
1344
+ "default": `./dist/${entry}.${type === "commonjs" ? "js" : "cjs"}`
1345
+ },
1346
+ "default": {
1347
+ "types": `./dist/${entry}.d.ts`,
1348
+ "default": `./dist/${entry}.js`
1349
+ }
1350
+ };
1351
+ }, "addPackageJsonExport");
1352
+ var addPackageJsonExports = /* @__PURE__ */ __name(async (sourceRoot, packageJson) => {
1353
+ packageJson.exports ??= {};
1354
+ const files = await new import_glob2.Glob("**/*.{ts,tsx}", {
1355
+ absolute: false,
1356
+ cwd: sourceRoot,
1357
+ root: sourceRoot
1358
+ }).walk();
1359
+ files.forEach((file) => {
1360
+ addPackageJsonExport(file, packageJson.type, sourceRoot);
1361
+ const split = file.split(".");
1362
+ split.pop();
1363
+ const entry = split.join(".").replaceAll("\\", "/");
1364
+ packageJson.exports[`./${entry}`] ??= addPackageJsonExport(entry, packageJson.type, sourceRoot);
1365
+ });
1366
+ packageJson.main = packageJson.type === "commonjs" ? "./dist/index.js" : "./dist/index.cjs";
1367
+ packageJson.module = packageJson.type === "module" ? "./dist/index.js" : "./dist/index.mjs";
1368
+ packageJson.types = "./dist/index.d.ts";
1369
+ packageJson.exports ??= {};
1370
+ packageJson.exports = Object.keys(packageJson.exports).reduce((ret, key) => {
1371
+ if (key.endsWith("/index") && !ret[key.replace("/index", "")]) {
1372
+ ret[key.replace("/index", "")] = packageJson.exports[key];
1373
+ }
1374
+ return ret;
1375
+ }, packageJson.exports);
1376
+ packageJson.exports["./package.json"] ??= "./package.json";
1377
+ packageJson.exports["."] = packageJson.exports["."] ?? addPackageJsonExport("index", packageJson.type, sourceRoot);
1378
+ return packageJson;
1379
+ }, "addPackageJsonExports");
1380
+
1381
+ // ../build-tools/src/utilities/get-entry-points.ts
1382
+ var import_glob3 = require("glob");
1383
+
1384
+ // ../build-tools/src/utilities/task-graph.ts
1385
+ var import_create_task_graph = require("nx/src/tasks-runner/create-task-graph");
1386
+
1387
+ // src/build.ts
1388
+ var import_defu5 = __toESM(require("defu"), 1);
1389
+ var import_node_fs8 = require("fs");
1390
+ var import_promises7 = require("fs/promises");
1391
+ var import_node_path6 = require("path");
1392
+ var import_find_workspace_root5 = require("nx/src/utils/find-workspace-root");
1393
+
1394
+ // ../../node_modules/.pnpm/unbuild@3.3.1_sass@1.83.4_typescript@5.7.3/node_modules/unbuild/dist/shared/unbuild.B2_7OVir.mjs
1395
+ var import_node_module2 = __toESM(require("module"), 1);
1396
+ var import_node_fs6 = require("fs");
1397
+ var import_pathe = require("pathe");
1398
+ var import_utils = require("consola/utils");
1399
+ var import_consola = __toESM(require("consola"), 1);
1400
+ var import_defu3 = require("defu");
1401
+ var import_hookable = require("hookable");
1402
+ var import_pretty_bytes = __toESM(require("pretty-bytes"), 1);
1403
+ var import_tinyglobby = require("tinyglobby");
1404
+ var import_promises4 = __toESM(require("fs/promises"), 1);
1405
+ var import_jiti = require("jiti");
1406
+ var import_rollup = require("rollup");
1407
+ var import_rollup_plugin_dts = __toESM(require("rollup-plugin-dts"), 1);
1408
+ var import_plugin_commonjs = __toESM(require("@rollup/plugin-commonjs"), 1);
1409
+ var import_plugin_node_resolve = require("@rollup/plugin-node-resolve");
1410
+ var import_plugin_alias = __toESM(require("@rollup/plugin-alias"), 1);
1411
+ var import_plugin_replace = __toESM(require("@rollup/plugin-replace"), 1);
1412
+ var import_utils2 = require("pathe/utils");
1413
+ var import_mlly = require("mlly");
1414
+ var import_esbuild = require("esbuild");
1415
+ var import_pluginutils = require("@rollup/pluginutils");
1416
+ var import_plugin_json = __toESM(require("@rollup/plugin-json"), 1);
1417
+ var import_magic_string = __toESM(require("magic-string"), 1);
1418
+ var import_untyped = require("untyped");
1419
+ var import_babel_plugin = __toESM(require("untyped/babel-plugin"), 1);
1420
+ var import_scule = require("scule");
1421
+ var import_mkdist = require("mkdist");
1422
+ function definePreset(preset) {
1423
+ return preset;
1424
+ }
1425
+ __name(definePreset, "definePreset");
1426
+ var autoPreset = definePreset(() => {
1427
+ return {
1428
+ hooks: {
1429
+ "build:prepare"(ctx) {
1430
+ if (!ctx.pkg || ctx.options.entries.length > 0) {
1431
+ return;
1432
+ }
1433
+ const sourceFiles = listRecursively((0, import_pathe.join)(ctx.options.rootDir, "src"));
1434
+ const res = inferEntries(ctx.pkg, sourceFiles, ctx.options.rootDir);
1435
+ for (const message of res.warnings) {
1436
+ warn(ctx, message);
1437
+ }
1438
+ ctx.options.entries.push(...res.entries);
1439
+ if (res.cjs) {
1440
+ ctx.options.rollup.emitCJS = true;
1441
+ }
1442
+ if (ctx.options.declaration === void 0) {
1443
+ ctx.options.declaration = res.dts ? "compatible" : false;
1444
+ }
1445
+ import_consola.consola.info(
1446
+ "Automatically detected entries:",
1447
+ import_utils.colors.cyan(
1448
+ ctx.options.entries.map(
1449
+ (e) => import_utils.colors.bold(
1450
+ e.input.replace(ctx.options.rootDir + "/", "").replace(/\/$/, "/*")
1451
+ )
1452
+ ).join(", ")
1453
+ ),
1454
+ import_utils.colors.gray(
1455
+ ["esm", res.cjs && "cjs", res.dts && "dts"].filter(Boolean).map((tag) => `[${tag}]`).join(" ")
1456
+ )
1457
+ );
1458
+ }
1459
+ }
1460
+ };
1461
+ });
1462
+ function inferEntries(pkg, sourceFiles, rootDir) {
1463
+ const warnings = [];
1464
+ sourceFiles.sort((a, b) => a.split("/").length - b.split("/").length);
1465
+ const outputs = extractExportFilenames(pkg.exports);
1466
+ if (pkg.bin) {
1467
+ const binaries = typeof pkg.bin === "string" ? [pkg.bin] : Object.values(pkg.bin);
1468
+ for (const file of binaries) {
1469
+ outputs.push({ file });
1470
+ }
1471
+ }
1472
+ if (pkg.main) {
1473
+ outputs.push({ file: pkg.main });
1474
+ }
1475
+ if (pkg.module) {
1476
+ outputs.push({ type: "esm", file: pkg.module });
1477
+ }
1478
+ if (pkg.types || pkg.typings) {
1479
+ outputs.push({ file: pkg.types || pkg.typings });
1480
+ }
1481
+ const isESMPkg = pkg.type === "module";
1482
+ for (const output of outputs.filter((o) => !o.type)) {
1483
+ const isJS = output.file.endsWith(".js");
1484
+ if (isESMPkg && isJS || output.file.endsWith(".mjs")) {
1485
+ output.type = "esm";
1486
+ } else if (!isESMPkg && isJS || output.file.endsWith(".cjs")) {
1487
+ output.type = "cjs";
1488
+ }
1489
+ }
1490
+ let cjs = false;
1491
+ let dts2 = false;
1492
+ const entries = [];
1493
+ for (const output of outputs) {
1494
+ const outputSlug = output.file.replace(
1495
+ /(\*[^/\\]*|\.d\.(m|c)?ts|\.\w+)$/,
1496
+ ""
1497
+ );
1498
+ const isDir = outputSlug.endsWith("/");
1499
+ if (isDir && ["./", "/"].includes(outputSlug)) {
1500
+ continue;
1501
+ }
1502
+ const possiblePaths = getEntrypointPaths(outputSlug);
1503
+ const input = possiblePaths.reduce((source, d) => {
1504
+ if (source) {
1505
+ return source;
1506
+ }
1507
+ const SOURCE_RE = new RegExp(
1508
+ `(?<=/|$)${d}${isDir ? "" : String.raw`\.\w+`}$`
1509
+ );
1510
+ return sourceFiles.find((i) => SOURCE_RE.test(i))?.replace(/(\.d\.(m|c)?ts|\.\w+)$/, "");
1511
+ }, void 0);
1512
+ if (!input) {
1513
+ if (!(0, import_node_fs6.existsSync)((0, import_pathe.resolve)(rootDir || ".", output.file))) {
1514
+ warnings.push(`Could not find entrypoint for \`${output.file}\``);
1515
+ }
1516
+ continue;
1517
+ }
1518
+ if (output.type === "cjs") {
1519
+ cjs = true;
1520
+ }
1521
+ const entry = entries.find((i) => i.input === input) || entries[entries.push({ input }) - 1];
1522
+ if (/\.d\.(m|c)?ts$/.test(output.file)) {
1523
+ dts2 = true;
1524
+ }
1525
+ if (isDir) {
1526
+ entry.outDir = outputSlug;
1527
+ entry.format = output.type;
1528
+ }
1529
+ }
1530
+ return { entries, cjs, dts: dts2, warnings };
1531
+ }
1532
+ __name(inferEntries, "inferEntries");
1533
+ var getEntrypointPaths = /* @__PURE__ */ __name((path2) => {
1534
+ const segments = (0, import_pathe.normalize)(path2).split("/");
1535
+ return segments.map((_, index) => segments.slice(index).join("/")).filter(Boolean);
1536
+ }, "getEntrypointPaths");
1537
+ async function ensuredir(path2) {
1538
+ await import_promises4.default.mkdir((0, import_pathe.dirname)(path2), { recursive: true });
1539
+ }
1540
+ __name(ensuredir, "ensuredir");
1541
+ function warn(ctx, message) {
1542
+ if (ctx.warnings.has(message)) {
1543
+ return;
1544
+ }
1545
+ import_consola.consola.debug("[unbuild] [warn]", message);
1546
+ ctx.warnings.add(message);
1547
+ }
1548
+ __name(warn, "warn");
1549
+ async function symlink(from, to, force = true) {
1550
+ await ensuredir(to);
1551
+ if (force) {
1552
+ await import_promises4.default.unlink(to).catch(() => {
1553
+ });
1554
+ }
1555
+ await import_promises4.default.symlink(from, to, "junction");
1556
+ }
1557
+ __name(symlink, "symlink");
1558
+ function dumpObject(obj) {
1559
+ return "{ " + Object.keys(obj).map((key) => `${key}: ${JSON.stringify(obj[key])}`).join(", ") + " }";
1560
+ }
1561
+ __name(dumpObject, "dumpObject");
1562
+ function getpkg(id = "") {
1563
+ const s = id.split("/");
1564
+ return s[0][0] === "@" ? `${s[0]}/${s[1]}` : s[0];
1565
+ }
1566
+ __name(getpkg, "getpkg");
1567
+ async function rmdir(dir) {
1568
+ await import_promises4.default.unlink(dir).catch(() => {
1569
+ });
1570
+ await import_promises4.default.rm(dir, { recursive: true, force: true }).catch(() => {
1571
+ });
1572
+ }
1573
+ __name(rmdir, "rmdir");
1574
+ function listRecursively(path2) {
1575
+ const filenames = /* @__PURE__ */ new Set();
1576
+ const walk = /* @__PURE__ */ __name((path22) => {
1577
+ const files = (0, import_node_fs6.readdirSync)(path22);
1578
+ for (const file of files) {
1579
+ const fullPath = (0, import_pathe.resolve)(path22, file);
1580
+ if ((0, import_node_fs6.statSync)(fullPath).isDirectory()) {
1581
+ filenames.add(fullPath + "/");
1582
+ walk(fullPath);
1583
+ } else {
1584
+ filenames.add(fullPath);
1585
+ }
1586
+ }
1587
+ }, "walk");
1588
+ walk(path2);
1589
+ return [...filenames];
1590
+ }
1591
+ __name(listRecursively, "listRecursively");
1592
+ async function resolvePreset(preset, rootDir) {
1593
+ if (preset === "auto") {
1594
+ preset = autoPreset;
1595
+ } else if (typeof preset === "string") {
1596
+ preset = await (0, import_jiti.createJiti)(rootDir, { interopDefault: true }).import(preset, {
1597
+ default: true
1598
+ }) || {};
1599
+ }
1600
+ if (typeof preset === "function") {
1601
+ preset = preset();
1602
+ }
1603
+ return preset;
1604
+ }
1605
+ __name(resolvePreset, "resolvePreset");
1606
+ function inferExportType(condition, previousConditions = [], filename = "") {
1607
+ if (filename) {
1608
+ if (filename.endsWith(".d.ts")) {
1609
+ return "esm";
1610
+ }
1611
+ if (filename.endsWith(".mjs")) {
1612
+ return "esm";
1613
+ }
1614
+ if (filename.endsWith(".cjs")) {
1615
+ return "cjs";
1616
+ }
1617
+ }
1618
+ switch (condition) {
1619
+ case "import": {
1620
+ return "esm";
1621
+ }
1622
+ case "require": {
1623
+ return "cjs";
1624
+ }
1625
+ default: {
1626
+ if (previousConditions.length === 0) {
1627
+ return "esm";
1628
+ }
1629
+ const [newCondition, ...rest] = previousConditions;
1630
+ return inferExportType(newCondition, rest, filename);
1631
+ }
1632
+ }
1633
+ }
1634
+ __name(inferExportType, "inferExportType");
1635
+ function extractExportFilenames(exports2, conditions = []) {
1636
+ if (!exports2) {
1637
+ return [];
1638
+ }
1639
+ if (typeof exports2 === "string") {
1640
+ return [{ file: exports2, type: "esm" }];
1641
+ }
1642
+ return Object.entries(exports2).filter(([subpath]) => !subpath.endsWith(".json")).flatMap(
1643
+ ([condition, exports22]) => typeof exports22 === "string" ? {
1644
+ file: exports22,
1645
+ type: inferExportType(condition, conditions, exports22)
1646
+ } : extractExportFilenames(exports22, [...conditions, condition])
1647
+ );
1648
+ }
1649
+ __name(extractExportFilenames, "extractExportFilenames");
1650
+ function arrayIncludes(arr, searchElement) {
1651
+ return arr.some(
1652
+ (entry) => entry instanceof RegExp ? entry.test(searchElement) : entry === searchElement
1653
+ );
1654
+ }
1655
+ __name(arrayIncludes, "arrayIncludes");
1656
+ function removeExtension(filename) {
1657
+ return filename.replace(/\.(js|mjs|cjs|ts|mts|cts|json|jsx|tsx)$/, "");
1658
+ }
1659
+ __name(removeExtension, "removeExtension");
1660
+ function inferPkgExternals(pkg) {
1661
+ const externals = [
1662
+ ...Object.keys(pkg.dependencies || {}),
1663
+ ...Object.keys(pkg.peerDependencies || {}),
1664
+ ...Object.keys(pkg.devDependencies || {}).filter(
1665
+ (dep) => dep.startsWith("@types/")
1666
+ ),
1667
+ ...Object.keys(pkg.optionalDependencies || {})
1668
+ ];
1669
+ if (pkg.name) {
1670
+ externals.push(pkg.name);
1671
+ if (pkg.exports) {
1672
+ for (const subpath of Object.keys(pkg.exports)) {
1673
+ if (subpath.startsWith("./")) {
1674
+ externals.push(pathToRegex(`${pkg.name}/${subpath.slice(2)}`));
1675
+ }
1676
+ }
1677
+ }
1678
+ }
1679
+ if (pkg.imports) {
1680
+ for (const importName of Object.keys(pkg.imports)) {
1681
+ if (importName.startsWith("#")) {
1682
+ externals.push(pathToRegex(importName));
1683
+ }
1684
+ }
1685
+ }
1686
+ return [...new Set(externals)];
1687
+ }
1688
+ __name(inferPkgExternals, "inferPkgExternals");
1689
+ function pathToRegex(path2) {
1690
+ return path2.includes("*") ? new RegExp(
1691
+ `^${path2.replace(/\./g, String.raw`\.`).replace(/\*/g, ".*")}$`
1692
+ ) : path2;
1693
+ }
1694
+ __name(pathToRegex, "pathToRegex");
1695
+ function withTrailingSlash(path2) {
1696
+ return path2.endsWith("/") ? path2 : `${path2}/`;
1697
+ }
1698
+ __name(withTrailingSlash, "withTrailingSlash");
1699
+ function validateDependencies(ctx) {
1700
+ const usedDependencies = /* @__PURE__ */ new Set();
1701
+ const unusedDependencies = new Set(
1702
+ Object.keys(ctx.pkg.dependencies || {})
1703
+ );
1704
+ const implicitDependencies = /* @__PURE__ */ new Set();
1705
+ for (const id of ctx.usedImports) {
1706
+ unusedDependencies.delete(id);
1707
+ usedDependencies.add(id);
1708
+ }
1709
+ if (Array.isArray(ctx.options.dependencies)) {
1710
+ for (const id of ctx.options.dependencies) {
1711
+ unusedDependencies.delete(id);
1712
+ }
1713
+ }
1714
+ for (const id of usedDependencies) {
1715
+ if (!arrayIncludes(ctx.options.externals, id) && !id.startsWith("chunks/") && !ctx.options.dependencies.includes(getpkg(id)) && !ctx.options.peerDependencies.includes(getpkg(id))) {
1716
+ implicitDependencies.add(id);
1717
+ }
1718
+ }
1719
+ if (unusedDependencies.size > 0) {
1720
+ warn(
1721
+ ctx,
1722
+ "Potential unused dependencies found: " + [...unusedDependencies].map((id) => import_utils.colors.cyan(id)).join(", ")
1723
+ );
1724
+ }
1725
+ if (implicitDependencies.size > 0 && !ctx.options.rollup.inlineDependencies) {
1726
+ warn(
1727
+ ctx,
1728
+ "Potential implicit dependencies found: " + [...implicitDependencies].map((id) => import_utils.colors.cyan(id)).join(", ")
1729
+ );
1730
+ }
1731
+ }
1732
+ __name(validateDependencies, "validateDependencies");
1733
+ function validatePackage(pkg, rootDir, ctx) {
1734
+ if (!pkg) {
1735
+ return;
1736
+ }
1737
+ const filenames = new Set(
1738
+ [
1739
+ ...typeof pkg.bin === "string" ? [pkg.bin] : Object.values(pkg.bin || {}),
1740
+ pkg.main,
1741
+ pkg.module,
1742
+ pkg.types,
1743
+ pkg.typings,
1744
+ ...extractExportFilenames(pkg.exports).map((i) => i.file)
1745
+ ].map((i) => i && (0, import_pathe.resolve)(rootDir, i.replace(/\/[^/]*\*.*$/, "")))
1746
+ );
1747
+ const missingOutputs = [];
1748
+ for (const filename of filenames) {
1749
+ if (filename && !filename.includes("*") && !(0, import_node_fs6.existsSync)(filename)) {
1750
+ missingOutputs.push(filename.replace(rootDir + "/", ""));
1751
+ }
1752
+ }
1753
+ if (missingOutputs.length > 0) {
1754
+ warn(
1755
+ ctx,
1756
+ `Potential missing package.json files: ${missingOutputs.map((o) => import_utils.colors.cyan(o)).join(", ")}`
1757
+ );
1758
+ }
1759
+ }
1760
+ __name(validatePackage, "validatePackage");
1761
+ var SHEBANG_RE = /^#![^\n]*/;
1762
+ function shebangPlugin() {
1763
+ return {
1764
+ name: "unbuild-shebang",
1765
+ async writeBundle(options, bundle) {
1766
+ for (const [fileName, output] of Object.entries(bundle)) {
1767
+ if (output.type !== "chunk") {
1768
+ continue;
1769
+ }
1770
+ if (output.code?.match(SHEBANG_RE)) {
1771
+ const outFile = (0, import_pathe.resolve)(options.dir, fileName);
1772
+ await makeExecutable(outFile);
1773
+ }
1774
+ }
1775
+ }
1776
+ };
1777
+ }
1778
+ __name(shebangPlugin, "shebangPlugin");
1779
+ function removeShebangPlugin() {
1780
+ return {
1781
+ name: "unbuild-remove-shebang",
1782
+ renderChunk(code) {
1783
+ return code.replace(SHEBANG_RE, "");
1784
+ }
1785
+ };
1786
+ }
1787
+ __name(removeShebangPlugin, "removeShebangPlugin");
1788
+ async function makeExecutable(filePath) {
1789
+ await import_node_fs6.promises.chmod(
1790
+ filePath,
1791
+ 493
1792
+ /* rwx r-x r-x */
1793
+ ).catch(() => {
1794
+ });
1795
+ }
1796
+ __name(makeExecutable, "makeExecutable");
1797
+ function getShebang(code, append = "\n") {
1798
+ const m = code.match(SHEBANG_RE);
1799
+ return m ? m + append : "";
1800
+ }
1801
+ __name(getShebang, "getShebang");
1802
+ var DefaultLoaders = {
1803
+ ".js": "js",
1804
+ ".mjs": "js",
1805
+ ".cjs": "js",
1806
+ ".ts": "ts",
1807
+ ".mts": "ts",
1808
+ ".cts": "ts",
1809
+ ".tsx": "tsx",
1810
+ ".jsx": "jsx"
1811
+ };
1812
+ function esbuild(options) {
1813
+ const {
1814
+ include = new RegExp(Object.keys(DefaultLoaders).join("|")),
1815
+ exclude = /node_modules/,
1816
+ loaders: loaderOptions,
1817
+ ...esbuildOptions
1818
+ } = options;
1819
+ const loaders = { ...DefaultLoaders };
1820
+ if (loaderOptions) {
1821
+ for (const [key, value] of Object.entries(loaderOptions)) {
1822
+ if (typeof value === "string") {
1823
+ loaders[key] = value;
1824
+ } else if (value === false) {
1825
+ delete loaders[key];
1826
+ }
1827
+ }
1828
+ }
1829
+ const getLoader = /* @__PURE__ */ __name((id = "") => {
1830
+ return loaders[(0, import_pathe.extname)(id)];
1831
+ }, "getLoader");
1832
+ const filter = (0, import_pluginutils.createFilter)(include, exclude);
1833
+ return {
1834
+ name: "esbuild",
1835
+ async transform(code, id) {
1836
+ if (!filter(id)) {
1837
+ return null;
1838
+ }
1839
+ const loader = getLoader(id);
1840
+ if (!loader) {
1841
+ return null;
1842
+ }
1843
+ const result = await (0, import_esbuild.transform)(code, {
1844
+ ...esbuildOptions,
1845
+ loader,
1846
+ sourcefile: id
1847
+ });
1848
+ printWarnings(id, result, this);
1849
+ return {
1850
+ code: result.code || "",
1851
+ map: result.map || null
1852
+ };
1853
+ },
1854
+ async renderChunk(code, { fileName }) {
1855
+ if (!options.minify) {
1856
+ return null;
1857
+ }
1858
+ if (/\.d\.(c|m)?tsx?$/.test(fileName)) {
1859
+ return null;
1860
+ }
1861
+ const loader = getLoader(fileName);
1862
+ if (!loader) {
1863
+ return null;
1864
+ }
1865
+ const result = await (0, import_esbuild.transform)(code, {
1866
+ ...esbuildOptions,
1867
+ loader,
1868
+ sourcefile: fileName,
1869
+ minify: true
1870
+ });
1871
+ return {
1872
+ code: result.code || "",
1873
+ map: result.map || null
1874
+ };
1875
+ }
1876
+ };
1877
+ }
1878
+ __name(esbuild, "esbuild");
1879
+ function printWarnings(id, result, plugin) {
1880
+ if (result.warnings) {
1881
+ for (const warning of result.warnings) {
1882
+ let message = "[esbuild]";
1883
+ if (warning.location) {
1884
+ message += ` (${(0, import_pathe.relative)(process.cwd(), id)}:${warning.location.line}:${warning.location.column})`;
1885
+ }
1886
+ message += ` ${warning.text}`;
1887
+ plugin.warn(message);
1888
+ }
1889
+ }
1890
+ }
1891
+ __name(printWarnings, "printWarnings");
1892
+ var EXPORT_DEFAULT = "export default ";
1893
+ function JSONPlugin(options) {
1894
+ const plugin = (0, import_plugin_json.default)(options);
1895
+ return {
1896
+ ...plugin,
1897
+ name: "unbuild-json",
1898
+ transform(code, id) {
1899
+ const res = plugin.transform.call(this, code, id);
1900
+ if (res && typeof res !== "string" && "code" in res && res.code && res.code.startsWith(EXPORT_DEFAULT)) {
1901
+ res.code = res.code.replace(EXPORT_DEFAULT, "module.exports = ");
1902
+ }
1903
+ return res;
1904
+ }
1905
+ };
1906
+ }
1907
+ __name(JSONPlugin, "JSONPlugin");
1908
+ var defaults = {
1909
+ include: [/\.(md|txt|css|htm|html)$/],
1910
+ exclude: []
1911
+ };
1912
+ function rawPlugin(opts = {}) {
1913
+ opts = { ...opts, ...defaults };
1914
+ const filter = (0, import_pluginutils.createFilter)(opts.include, opts.exclude);
1915
+ return {
1916
+ name: "unbuild-raw",
1917
+ transform(code, id) {
1918
+ if (filter(id)) {
1919
+ return {
1920
+ code: `export default ${JSON.stringify(code)}`,
1921
+ map: null
1922
+ };
1923
+ }
1924
+ }
1925
+ };
1926
+ }
1927
+ __name(rawPlugin, "rawPlugin");
1928
+ function cjsPlugin(_opts) {
1929
+ return {
1930
+ name: "unbuild-cjs",
1931
+ renderChunk(code, _chunk, opts) {
1932
+ if (opts.format === "es") {
1933
+ return CJSToESM(code);
1934
+ }
1935
+ return null;
1936
+ }
1937
+ };
1938
+ }
1939
+ __name(cjsPlugin, "cjsPlugin");
1940
+ function fixCJSExportTypePlugin() {
1941
+ return {
1942
+ name: "unbuild-fix-cjs-export-type",
1943
+ renderChunk(code, info, opts) {
1944
+ if (info.type !== "chunk" || !info.fileName.endsWith(".d.cts") || !info.isEntry || info.exports?.length !== 1 || info.exports[0] !== "default") {
1945
+ return;
1946
+ }
1947
+ return code.replace(
1948
+ /(?<=(?<=[;}]|^)\s*export\s*){\s*([\w$]+)\s*as\s+default\s*}/,
1949
+ `= $1`
1950
+ );
1951
+ }
1952
+ };
1953
+ }
1954
+ __name(fixCJSExportTypePlugin, "fixCJSExportTypePlugin");
1955
+ var CJSyntaxRe = /__filename|__dirname|require\(|require\.resolve\(/;
1956
+ var CJSShim = `
1957
+
1958
+ // -- Unbuild CommonJS Shims --
1959
+ import __cjs_url__ from 'url';
1960
+ import __cjs_path__ from 'path';
1961
+ import __cjs_mod__ from 'module';
1962
+ const __filename = __cjs_url__.fileURLToPath(import.meta.url);
1963
+ const __dirname = __cjs_path__.dirname(__filename);
1964
+ const require = __cjs_mod__.createRequire(import.meta.url);
1965
+ `;
1966
+ function CJSToESM(code) {
1967
+ if (code.includes(CJSShim) || !CJSyntaxRe.test(code)) {
1968
+ return null;
1969
+ }
1970
+ const lastESMImport = (0, import_mlly.findStaticImports)(code).pop();
1971
+ const indexToAppend = lastESMImport ? lastESMImport.end : 0;
1972
+ const s = new import_magic_string.default(code);
1973
+ s.appendRight(indexToAppend, CJSShim);
1974
+ return {
1975
+ code: s.toString(),
1976
+ map: s.generateMap()
1977
+ };
1978
+ }
1979
+ __name(CJSToESM, "CJSToESM");
1980
+ var DEFAULT_EXTENSIONS = [
1981
+ ".ts",
1982
+ ".tsx",
1983
+ ".mts",
1984
+ ".cts",
1985
+ ".mjs",
1986
+ ".cjs",
1987
+ ".js",
1988
+ ".jsx",
1989
+ ".json"
1990
+ ];
1991
+ function resolveAliases(ctx) {
1992
+ const aliases = {
1993
+ [ctx.pkg.name]: ctx.options.rootDir,
1994
+ ...ctx.options.alias
1995
+ };
1996
+ if (ctx.options.rollup.alias) {
1997
+ if (Array.isArray(ctx.options.rollup.alias.entries)) {
1998
+ Object.assign(
1999
+ aliases,
2000
+ Object.fromEntries(
2001
+ ctx.options.rollup.alias.entries.map((entry) => {
2002
+ return [entry.find, entry.replacement];
2003
+ })
2004
+ )
2005
+ );
2006
+ } else {
2007
+ Object.assign(
2008
+ aliases,
2009
+ ctx.options.rollup.alias.entries || ctx.options.rollup.alias
2010
+ );
2011
+ }
2012
+ }
2013
+ return aliases;
2014
+ }
2015
+ __name(resolveAliases, "resolveAliases");
2016
+ function getChunkFilename(ctx, chunk, ext) {
2017
+ if (chunk.isDynamicEntry) {
2018
+ return `chunks/[name].${ext}`;
2019
+ }
2020
+ return `shared/${ctx.options.name}.[hash].${ext}`;
2021
+ }
2022
+ __name(getChunkFilename, "getChunkFilename");
2023
+ function getRollupOptions(ctx) {
2024
+ const _aliases = resolveAliases(ctx);
2025
+ return {
2026
+ input: Object.fromEntries(
2027
+ ctx.options.entries.filter((entry) => entry.builder === "rollup").map((entry) => [
2028
+ entry.name,
2029
+ (0, import_pathe.resolve)(ctx.options.rootDir, entry.input)
2030
+ ])
2031
+ ),
2032
+ output: [
2033
+ ctx.options.rollup.emitCJS && {
2034
+ dir: (0, import_pathe.resolve)(ctx.options.rootDir, ctx.options.outDir),
2035
+ entryFileNames: "[name].cjs",
2036
+ chunkFileNames: /* @__PURE__ */ __name((chunk) => getChunkFilename(ctx, chunk, "cjs"), "chunkFileNames"),
2037
+ format: "cjs",
2038
+ exports: "auto",
2039
+ interop: "compat",
2040
+ generatedCode: { constBindings: true },
2041
+ externalLiveBindings: false,
2042
+ freeze: false,
2043
+ sourcemap: ctx.options.sourcemap,
2044
+ ...ctx.options.rollup.output
2045
+ },
2046
+ {
2047
+ dir: (0, import_pathe.resolve)(ctx.options.rootDir, ctx.options.outDir),
2048
+ entryFileNames: "[name].mjs",
2049
+ chunkFileNames: /* @__PURE__ */ __name((chunk) => getChunkFilename(ctx, chunk, "mjs"), "chunkFileNames"),
2050
+ format: "esm",
2051
+ exports: "auto",
2052
+ generatedCode: { constBindings: true },
2053
+ externalLiveBindings: false,
2054
+ freeze: false,
2055
+ sourcemap: ctx.options.sourcemap,
2056
+ ...ctx.options.rollup.output
2057
+ }
2058
+ ].filter(Boolean),
2059
+ external(originalId) {
2060
+ const resolvedId = (0, import_utils2.resolveAlias)(originalId, _aliases);
2061
+ const pkgName = (0, import_mlly.parseNodeModulePath)(resolvedId)?.name || (0, import_mlly.parseNodeModulePath)(originalId)?.name || getpkg(originalId);
2062
+ if (arrayIncludes(ctx.options.externals, pkgName) || arrayIncludes(ctx.options.externals, originalId) || arrayIncludes(ctx.options.externals, resolvedId)) {
2063
+ return true;
2064
+ }
2065
+ for (const id of [originalId, resolvedId]) {
2066
+ if (id[0] === "." || (0, import_pathe.isAbsolute)(id) || /src[/\\]/.test(id) || id.startsWith(ctx.pkg.name)) {
2067
+ return false;
2068
+ }
2069
+ }
2070
+ if (ctx.options.rollup.inlineDependencies === true || Array.isArray(ctx.options.rollup.inlineDependencies) && (arrayIncludes(ctx.options.rollup.inlineDependencies, pkgName) || arrayIncludes(ctx.options.rollup.inlineDependencies, originalId) || arrayIncludes(ctx.options.rollup.inlineDependencies, resolvedId))) {
2071
+ return false;
2072
+ }
2073
+ warn(ctx, `Implicitly bundling "${originalId}"`);
2074
+ return false;
2075
+ },
2076
+ onwarn(warning, rollupWarn) {
2077
+ if (!warning.code || !["CIRCULAR_DEPENDENCY"].includes(warning.code)) {
2078
+ rollupWarn(warning);
2079
+ }
2080
+ },
2081
+ plugins: [
2082
+ ctx.options.rollup.replace && (0, import_plugin_replace.default)({
2083
+ ...ctx.options.rollup.replace,
2084
+ values: {
2085
+ ...ctx.options.replace,
2086
+ ...ctx.options.rollup.replace.values
2087
+ }
2088
+ }),
2089
+ ctx.options.rollup.alias && (0, import_plugin_alias.default)({
2090
+ ...ctx.options.rollup.alias,
2091
+ entries: _aliases
2092
+ }),
2093
+ ctx.options.rollup.resolve && (0, import_plugin_node_resolve.nodeResolve)({
2094
+ extensions: DEFAULT_EXTENSIONS,
2095
+ exportConditions: ["production"],
2096
+ ...ctx.options.rollup.resolve
2097
+ }),
2098
+ ctx.options.rollup.json && JSONPlugin({
2099
+ ...ctx.options.rollup.json
2100
+ }),
2101
+ shebangPlugin(),
2102
+ ctx.options.rollup.esbuild && esbuild({
2103
+ sourcemap: ctx.options.sourcemap,
2104
+ ...ctx.options.rollup.esbuild
2105
+ }),
2106
+ ctx.options.rollup.commonjs && (0, import_plugin_commonjs.default)({
2107
+ extensions: DEFAULT_EXTENSIONS,
2108
+ ...ctx.options.rollup.commonjs
2109
+ }),
2110
+ ctx.options.rollup.preserveDynamicImports && {
2111
+ renderDynamicImport() {
2112
+ return { left: "import(", right: ")" };
2113
+ }
2114
+ },
2115
+ ctx.options.rollup.cjsBridge && cjsPlugin(),
2116
+ rawPlugin()
2117
+ ].filter(Boolean)
2118
+ };
2119
+ }
2120
+ __name(getRollupOptions, "getRollupOptions");
2121
+ async function rollupStub(ctx) {
2122
+ const babelPlugins = ctx.options.stubOptions.jiti.transformOptions?.babel?.plugins;
2123
+ const importedBabelPlugins = [];
2124
+ const serializedJitiOptions = JSON.stringify(
2125
+ {
2126
+ ...ctx.options.stubOptions.jiti,
2127
+ alias: {
2128
+ ...resolveAliases(ctx),
2129
+ ...ctx.options.stubOptions.jiti.alias
2130
+ },
2131
+ transformOptions: {
2132
+ ...ctx.options.stubOptions.jiti.transformOptions,
2133
+ babel: {
2134
+ ...ctx.options.stubOptions.jiti.transformOptions?.babel,
2135
+ plugins: "__$BABEL_PLUGINS"
2136
+ }
2137
+ }
2138
+ },
2139
+ null,
2140
+ 2
2141
+ ).replace(
2142
+ '"__$BABEL_PLUGINS"',
2143
+ Array.isArray(babelPlugins) ? "[" + babelPlugins.map((plugin, i) => {
2144
+ if (Array.isArray(plugin)) {
2145
+ const [name, ...args] = plugin;
2146
+ importedBabelPlugins.push(name);
2147
+ return `[` + [
2148
+ `plugin${i}`,
2149
+ ...args.map((val) => JSON.stringify(val))
2150
+ ].join(", ") + "]";
2151
+ } else {
2152
+ importedBabelPlugins.push(plugin);
2153
+ return `plugin${i}`;
2154
+ }
2155
+ }).join(",") + "]" : "[]"
2156
+ );
2157
+ for (const entry of ctx.options.entries.filter(
2158
+ (entry2) => entry2.builder === "rollup"
2159
+ )) {
2160
+ const output = (0, import_pathe.resolve)(
2161
+ ctx.options.rootDir,
2162
+ ctx.options.outDir,
2163
+ entry.name
2164
+ );
2165
+ const isESM = ctx.pkg.type === "module";
2166
+ const resolvedEntry = (0, import_mlly.fileURLToPath)(ctx.jiti.esmResolve(entry.input));
2167
+ const resolvedEntryWithoutExt = resolvedEntry.slice(
2168
+ 0,
2169
+ Math.max(0, resolvedEntry.length - (0, import_pathe.extname)(resolvedEntry).length)
2170
+ );
2171
+ const resolvedEntryForTypeImport = isESM ? `${resolvedEntry.replace(/(\.m?)(ts)$/, "$1js")}` : resolvedEntryWithoutExt;
2172
+ const code = await import_node_fs6.promises.readFile(resolvedEntry, "utf8");
2173
+ const shebang = getShebang(code);
2174
+ await (0, import_promises4.mkdir)((0, import_pathe.dirname)(output), { recursive: true });
2175
+ if (ctx.options.rollup.emitCJS) {
2176
+ const jitiCJSPath = (0, import_pathe.relative)(
2177
+ (0, import_pathe.dirname)(output),
2178
+ await (0, import_mlly.resolvePath)("jiti", {
2179
+ url: importMetaUrl,
2180
+ conditions: ["node", "require"]
2181
+ })
2182
+ );
2183
+ await (0, import_promises4.writeFile)(
2184
+ output + ".cjs",
2185
+ shebang + [
2186
+ `const { createJiti } = require(${JSON.stringify(jitiCJSPath)})`,
2187
+ ...importedBabelPlugins.map(
2188
+ (plugin, i) => `const plugin${i} = require(${JSON.stringify(plugin)})`
2189
+ ),
2190
+ "",
2191
+ `const jiti = createJiti(__filename, ${serializedJitiOptions})`,
2192
+ "",
2193
+ `/** @type {import(${JSON.stringify(
2194
+ resolvedEntryForTypeImport
2195
+ )})} */`,
2196
+ `module.exports = jiti(${JSON.stringify(resolvedEntry)})`
2197
+ ].join("\n")
2198
+ );
2199
+ }
2200
+ const namedExports = await (0, import_mlly.resolveModuleExportNames)(
2201
+ resolvedEntry,
2202
+ {
2203
+ extensions: DEFAULT_EXTENSIONS
2204
+ }
2205
+ ).catch((error) => {
2206
+ warn(ctx, `Cannot analyze ${resolvedEntry} for exports:` + error);
2207
+ return [];
2208
+ });
2209
+ const hasDefaultExport = namedExports.includes("default") || namedExports.length === 0;
2210
+ const jitiESMPath = (0, import_pathe.relative)(
2211
+ (0, import_pathe.dirname)(output),
2212
+ await (0, import_mlly.resolvePath)("jiti", {
2213
+ url: importMetaUrl,
2214
+ conditions: ["node", "import"]
2215
+ })
2216
+ );
2217
+ await (0, import_promises4.writeFile)(
2218
+ output + ".mjs",
2219
+ shebang + [
2220
+ `import { createJiti } from ${JSON.stringify(jitiESMPath)};`,
2221
+ ...importedBabelPlugins.map(
2222
+ (plugin, i) => `import plugin${i} from ${JSON.stringify(plugin)}`
2223
+ ),
2224
+ "",
2225
+ `const jiti = createJiti(import.meta.url, ${serializedJitiOptions})`,
2226
+ "",
2227
+ `/** @type {import(${JSON.stringify(resolvedEntryForTypeImport)})} */`,
2228
+ `const _module = await jiti.import(${JSON.stringify(
2229
+ resolvedEntry
2230
+ )});`,
2231
+ hasDefaultExport ? "\nexport default _module?.default ?? _module;" : "",
2232
+ ...namedExports.filter((name) => name !== "default").map((name) => `export const ${name} = _module.${name};`)
2233
+ ].join("\n")
2234
+ );
2235
+ if (ctx.options.declaration) {
2236
+ const dtsContent = [
2237
+ `export * from ${JSON.stringify(resolvedEntryForTypeImport)};`,
2238
+ hasDefaultExport ? `export { default } from ${JSON.stringify(resolvedEntryForTypeImport)};` : ""
2239
+ ].join("\n");
2240
+ await (0, import_promises4.writeFile)(output + ".d.cts", dtsContent);
2241
+ await (0, import_promises4.writeFile)(output + ".d.mts", dtsContent);
2242
+ if (ctx.options.declaration === "compatible" || ctx.options.declaration === true) {
2243
+ await (0, import_promises4.writeFile)(output + ".d.ts", dtsContent);
2244
+ }
2245
+ }
2246
+ if (shebang) {
2247
+ await makeExecutable(output + ".cjs");
2248
+ await makeExecutable(output + ".mjs");
2249
+ }
2250
+ }
2251
+ }
2252
+ __name(rollupStub, "rollupStub");
2253
+ function rollupWatch(rollupOptions) {
2254
+ const watcher = (0, import_rollup.watch)(rollupOptions);
2255
+ let inputs;
2256
+ if (Array.isArray(rollupOptions.input)) {
2257
+ inputs = rollupOptions.input;
2258
+ } else if (typeof rollupOptions.input === "string") {
2259
+ inputs = [rollupOptions.input];
2260
+ } else {
2261
+ inputs = Object.keys(rollupOptions.input || {});
2262
+ }
2263
+ import_consola.default.info(
2264
+ `[unbuild] [rollup] Starting watchers for entries: ${inputs.map((input) => "./" + (0, import_pathe.relative)(process.cwd(), input)).join(", ")}`
2265
+ );
2266
+ import_consola.default.warn(
2267
+ "[unbuild] [rollup] Watch mode is experimental and may be unstable"
2268
+ );
2269
+ watcher.on("change", (id, { event }) => {
2270
+ import_consola.default.info(`${import_utils.colors.cyan((0, import_pathe.relative)(".", id))} was ${event}d`);
2271
+ });
2272
+ watcher.on("restart", () => {
2273
+ import_consola.default.info(import_utils.colors.gray("[unbuild] [rollup] Rebuilding bundle"));
2274
+ });
2275
+ watcher.on("event", (event) => {
2276
+ if (event.code === "END") {
2277
+ import_consola.default.success(import_utils.colors.green("[unbuild] [rollup] Rebuild finished\n"));
2278
+ }
2279
+ });
2280
+ }
2281
+ __name(rollupWatch, "rollupWatch");
2282
+ async function rollupBuild(ctx) {
2283
+ if (ctx.options.stub) {
2284
+ await rollupStub(ctx);
2285
+ await ctx.hooks.callHook("rollup:done", ctx);
2286
+ return;
2287
+ }
2288
+ const rollupOptions = getRollupOptions(ctx);
2289
+ await ctx.hooks.callHook("rollup:options", ctx, rollupOptions);
2290
+ if (Object.keys(rollupOptions.input).length === 0) {
2291
+ await ctx.hooks.callHook("rollup:done", ctx);
2292
+ return;
2293
+ }
2294
+ const buildResult = await (0, import_rollup.rollup)(rollupOptions);
2295
+ await ctx.hooks.callHook("rollup:build", ctx, buildResult);
2296
+ const allOutputOptions = rollupOptions.output;
2297
+ for (const outputOptions of allOutputOptions) {
2298
+ const { output } = await buildResult.write(outputOptions);
2299
+ const chunkFileNames = /* @__PURE__ */ new Set();
2300
+ const outputChunks = output.filter(
2301
+ (e) => e.type === "chunk"
2302
+ );
2303
+ for (const entry of outputChunks) {
2304
+ chunkFileNames.add(entry.fileName);
2305
+ for (const id of entry.imports) {
2306
+ ctx.usedImports.add(id);
2307
+ }
2308
+ if (entry.isEntry) {
2309
+ ctx.buildEntries.push({
2310
+ chunks: entry.imports.filter(
2311
+ (i) => outputChunks.find((c) => c.fileName === i)
2312
+ ),
2313
+ modules: Object.entries(entry.modules).map(([id, mod]) => ({
2314
+ id,
2315
+ bytes: mod.renderedLength
2316
+ })),
2317
+ path: entry.fileName,
2318
+ bytes: Buffer.byteLength(entry.code, "utf8"),
2319
+ exports: entry.exports
2320
+ });
2321
+ }
2322
+ }
2323
+ for (const chunkFileName of chunkFileNames) {
2324
+ ctx.usedImports.delete(chunkFileName);
2325
+ }
2326
+ }
2327
+ if (ctx.options.watch) {
2328
+ rollupWatch(rollupOptions);
2329
+ if (ctx.options.declaration && ctx.options.watch) {
2330
+ import_consola.default.warn("`rollup` DTS builder does not support watch mode yet.");
2331
+ }
2332
+ return;
2333
+ }
2334
+ if (ctx.options.declaration) {
2335
+ rollupOptions.plugins = [
2336
+ ...rollupOptions.plugins,
2337
+ (0, import_rollup_plugin_dts.default)(ctx.options.rollup.dts),
2338
+ removeShebangPlugin(),
2339
+ ctx.options.rollup.emitCJS && fixCJSExportTypePlugin()
2340
+ ].filter(Boolean);
2341
+ await ctx.hooks.callHook("rollup:dts:options", ctx, rollupOptions);
2342
+ const typesBuild2 = await (0, import_rollup.rollup)(rollupOptions);
2343
+ await ctx.hooks.callHook("rollup:dts:build", ctx, typesBuild2);
2344
+ if (ctx.options.rollup.emitCJS) {
2345
+ await typesBuild2.write({
2346
+ dir: (0, import_pathe.resolve)(ctx.options.rootDir, ctx.options.outDir),
2347
+ entryFileNames: "[name].d.cts",
2348
+ chunkFileNames: /* @__PURE__ */ __name((chunk) => getChunkFilename(ctx, chunk, "d.cts"), "chunkFileNames")
2349
+ });
2350
+ }
2351
+ await typesBuild2.write({
2352
+ dir: (0, import_pathe.resolve)(ctx.options.rootDir, ctx.options.outDir),
2353
+ entryFileNames: "[name].d.mts",
2354
+ chunkFileNames: /* @__PURE__ */ __name((chunk) => getChunkFilename(ctx, chunk, "d.mts"), "chunkFileNames")
2355
+ });
2356
+ if (ctx.options.declaration === true || ctx.options.declaration === "compatible") {
2357
+ await typesBuild2.write({
2358
+ dir: (0, import_pathe.resolve)(ctx.options.rootDir, ctx.options.outDir),
2359
+ entryFileNames: "[name].d.ts",
2360
+ chunkFileNames: /* @__PURE__ */ __name((chunk) => getChunkFilename(ctx, chunk, "d.ts"), "chunkFileNames")
2361
+ });
2362
+ }
2363
+ }
2364
+ await ctx.hooks.callHook("rollup:done", ctx);
2365
+ }
2366
+ __name(rollupBuild, "rollupBuild");
2367
+ async function typesBuild(ctx) {
2368
+ const entries = ctx.options.entries.filter(
2369
+ (entry) => entry.builder === "untyped"
2370
+ );
2371
+ await ctx.hooks.callHook("untyped:entries", ctx, entries);
2372
+ for (const entry of entries) {
2373
+ const options = {
2374
+ jiti: {
2375
+ interopDefault: true,
2376
+ transformOptions: {
2377
+ babel: {
2378
+ plugins: [import_babel_plugin.default]
2379
+ }
2380
+ }
2381
+ }
2382
+ };
2383
+ await ctx.hooks.callHook("untyped:entry:options", ctx, entry, options);
2384
+ const untypedJiti = (0, import_jiti.createJiti)(ctx.options.rootDir, options.jiti);
2385
+ const distDir = entry.outDir;
2386
+ let rawSchema = await untypedJiti.import((0, import_pathe.resolve)(ctx.options.rootDir, entry.input), {
2387
+ try: true
2388
+ }) || {};
2389
+ const rawSchemaKeys = Object.keys(rawSchema);
2390
+ if (rawSchemaKeys.length === 1 && rawSchemaKeys[0] === "default") {
2391
+ rawSchema = rawSchema.default;
2392
+ }
2393
+ const defaults2 = entry.defaults || {};
2394
+ const schema = await (0, import_untyped.resolveSchema)(rawSchema, defaults2);
2395
+ await ctx.hooks.callHook("untyped:entry:schema", ctx, entry, schema);
2396
+ const outputs = {
2397
+ markdown: {
2398
+ fileName: (0, import_pathe.resolve)(distDir, `${entry.name}.md`),
2399
+ contents: (0, import_untyped.generateMarkdown)(schema)
2400
+ },
2401
+ schema: {
2402
+ fileName: `${entry.name}.schema.json`,
2403
+ contents: JSON.stringify(schema, null, 2)
2404
+ },
2405
+ defaults: {
2406
+ fileName: `${entry.name}.defaults.json`,
2407
+ contents: JSON.stringify(defaults2, null, 2)
2408
+ },
2409
+ declaration: entry.declaration ? {
2410
+ fileName: `${entry.name}.d.ts`,
2411
+ contents: (0, import_untyped.generateTypes)(schema, {
2412
+ interfaceName: (0, import_scule.pascalCase)(entry.name + "-schema")
2413
+ })
2414
+ } : void 0
2415
+ };
2416
+ await ctx.hooks.callHook("untyped:entry:outputs", ctx, entry, outputs);
2417
+ for (const output of Object.values(outputs)) {
2418
+ if (!output) continue;
2419
+ await (0, import_promises4.writeFile)(
2420
+ (0, import_pathe.resolve)(distDir, output.fileName),
2421
+ output.contents,
2422
+ "utf8"
2423
+ );
2424
+ }
2425
+ }
2426
+ await ctx.hooks.callHook("untyped:done", ctx);
2427
+ if (entries.length > 0 && ctx.options.watch) {
2428
+ import_consola.default.warn("`untyped` builder does not support watch mode yet.");
2429
+ }
2430
+ }
2431
+ __name(typesBuild, "typesBuild");
2432
+ async function mkdistBuild(ctx) {
2433
+ const entries = ctx.options.entries.filter(
2434
+ (e) => e.builder === "mkdist"
2435
+ );
2436
+ await ctx.hooks.callHook("mkdist:entries", ctx, entries);
2437
+ for (const entry of entries) {
2438
+ const distDir = entry.outDir;
2439
+ if (ctx.options.stub) {
2440
+ await rmdir(distDir);
2441
+ await symlink(entry.input, distDir);
2442
+ } else {
2443
+ const mkdistOptions = {
2444
+ rootDir: ctx.options.rootDir,
2445
+ srcDir: entry.input,
2446
+ distDir,
2447
+ cleanDist: false,
2448
+ ...entry
2449
+ };
2450
+ await ctx.hooks.callHook(
2451
+ "mkdist:entry:options",
2452
+ ctx,
2453
+ entry,
2454
+ mkdistOptions
2455
+ );
2456
+ const output = await (0, import_mkdist.mkdist)(mkdistOptions);
2457
+ ctx.buildEntries.push({
2458
+ path: distDir,
2459
+ chunks: output.writtenFiles.map((p) => (0, import_pathe.relative)(ctx.options.outDir, p))
2460
+ });
2461
+ await ctx.hooks.callHook("mkdist:entry:build", ctx, entry, output);
2462
+ if (output.errors) {
2463
+ for (const error of output.errors) {
2464
+ warn(
2465
+ ctx,
2466
+ `mkdist build failed for \`${(0, import_pathe.relative)(ctx.options.rootDir, error.filename)}\`:
2467
+ ${error.errors.map((e) => ` - ${e}`).join("\n")}`
2468
+ );
2469
+ }
2470
+ }
2471
+ }
2472
+ }
2473
+ await ctx.hooks.callHook("mkdist:done", ctx);
2474
+ if (entries.length > 0 && ctx.options.watch) {
2475
+ import_consola.default.warn("`mkdist` builder does not support watch mode yet.");
2476
+ }
2477
+ }
2478
+ __name(mkdistBuild, "mkdistBuild");
2479
+ var copy = import_node_fs6.promises.cp || import_node_fs6.promises.copyFile;
2480
+ async function copyBuild(ctx) {
2481
+ const entries = ctx.options.entries.filter(
2482
+ (e) => e.builder === "copy"
2483
+ );
2484
+ await ctx.hooks.callHook("copy:entries", ctx, entries);
2485
+ for (const entry of entries) {
2486
+ const distDir = entry.outDir;
2487
+ if (ctx.options.stub) {
2488
+ await rmdir(distDir);
2489
+ await symlink(entry.input, distDir);
2490
+ } else {
2491
+ const patterns = Array.isArray(entry.pattern) ? entry.pattern : [entry.pattern || "**"];
2492
+ const paths = await (0, import_tinyglobby.glob)(patterns, {
2493
+ cwd: (0, import_pathe.resolve)(ctx.options.rootDir, entry.input),
2494
+ absolute: false
2495
+ });
2496
+ const outputList = await Promise.allSettled(
2497
+ paths.map(async (path2) => {
2498
+ const src = (0, import_pathe.resolve)(ctx.options.rootDir, entry.input, path2);
2499
+ const dist = (0, import_pathe.resolve)(ctx.options.rootDir, distDir, path2);
2500
+ await copy(src, dist);
2501
+ return dist;
2502
+ })
2503
+ );
2504
+ for (const output of outputList) {
2505
+ if (output.status === "rejected") {
2506
+ warn(ctx, output.reason);
2507
+ }
2508
+ }
2509
+ ctx.buildEntries.push({
2510
+ path: distDir,
2511
+ chunks: outputList.filter(({ status }) => status === "fulfilled").map(
2512
+ (p) => (0, import_pathe.relative)(
2513
+ ctx.options.outDir,
2514
+ p.value
2515
+ )
2516
+ )
2517
+ });
2518
+ }
2519
+ }
2520
+ await ctx.hooks.callHook("copy:done", ctx);
2521
+ if (entries.length > 0 && ctx.options.watch) {
2522
+ import_consola.default.warn("`untyped` builder does not support watch mode yet.");
2523
+ }
2524
+ }
2525
+ __name(copyBuild, "copyBuild");
2526
+ async function build(rootDir, stub, inputConfig = {}) {
2527
+ rootDir = (0, import_pathe.resolve)(process.cwd(), rootDir || ".");
2528
+ const jiti = (0, import_jiti.createJiti)(rootDir);
2529
+ const _buildConfig = await jiti.import(inputConfig?.config || "./build.config", {
2530
+ try: !inputConfig.config,
2531
+ default: true
2532
+ }) || {};
2533
+ const buildConfigs = (Array.isArray(_buildConfig) ? _buildConfig : [_buildConfig]).filter(Boolean);
2534
+ const pkg = await jiti.import("./package.json", {
2535
+ try: true,
2536
+ default: true
2537
+ }) || {};
2538
+ const cleanedDirs = [];
2539
+ const _watchMode = inputConfig.watch === true;
2540
+ const _stubMode = !_watchMode && (stub || inputConfig.stub === true);
2541
+ for (const buildConfig of buildConfigs) {
2542
+ await _build(
2543
+ rootDir,
2544
+ inputConfig,
2545
+ buildConfig,
2546
+ pkg,
2547
+ cleanedDirs,
2548
+ _stubMode,
2549
+ _watchMode
2550
+ );
2551
+ }
2552
+ }
2553
+ __name(build, "build");
2554
+ async function _build(rootDir, inputConfig = {}, buildConfig, pkg, cleanedDirs, _stubMode, _watchMode) {
2555
+ const preset = await resolvePreset(
2556
+ buildConfig.preset || pkg.unbuild?.preset || pkg.build?.preset || inputConfig.preset || "auto",
2557
+ rootDir
2558
+ );
2559
+ const options = (0, import_defu3.defu)(
2560
+ buildConfig,
2561
+ pkg.unbuild || pkg.build,
2562
+ inputConfig,
2563
+ preset,
2564
+ {
2565
+ name: (pkg?.name || "").split("/").pop() || "default",
2566
+ rootDir,
2567
+ entries: [],
2568
+ clean: true,
2569
+ declaration: void 0,
2570
+ outDir: "dist",
2571
+ stub: _stubMode,
2572
+ stubOptions: {
2573
+ /**
2574
+ * See https://github.com/unjs/jiti#%EF%B8%8F-options
2575
+ */
2576
+ jiti: {
2577
+ interopDefault: true,
2578
+ alias: {}
2579
+ }
2580
+ },
2581
+ watch: _watchMode,
2582
+ watchOptions: _watchMode ? {
2583
+ exclude: "node_modules/**",
2584
+ include: "src/**"
2585
+ } : void 0,
2586
+ externals: [
2587
+ ...import_node_module2.default.builtinModules,
2588
+ ...import_node_module2.default.builtinModules.map((m) => "node:" + m)
2589
+ ],
2590
+ dependencies: [],
2591
+ devDependencies: [],
2592
+ peerDependencies: [],
2593
+ alias: {},
2594
+ replace: {},
2595
+ failOnWarn: true,
2596
+ sourcemap: false,
2597
+ rollup: {
2598
+ emitCJS: false,
2599
+ watch: false,
2600
+ cjsBridge: false,
2601
+ inlineDependencies: false,
2602
+ preserveDynamicImports: true,
2603
+ output: {
2604
+ // https://v8.dev/features/import-attributes
2605
+ importAttributesKey: "with"
2606
+ },
2607
+ // Plugins
2608
+ replace: {
2609
+ preventAssignment: true
2610
+ },
2611
+ alias: {},
2612
+ resolve: {
2613
+ preferBuiltins: true
2614
+ },
2615
+ json: {
2616
+ preferConst: true
2617
+ },
2618
+ commonjs: {
2619
+ ignoreTryCatch: true
2620
+ },
2621
+ esbuild: { target: "esnext" },
2622
+ dts: {
2623
+ // https://github.com/Swatinem/rollup-plugin-dts/issues/143
2624
+ compilerOptions: { preserveSymlinks: false },
2625
+ respectExternal: true
2626
+ }
2627
+ },
2628
+ parallel: false
2629
+ }
2630
+ );
2631
+ options.outDir = (0, import_pathe.resolve)(options.rootDir, options.outDir);
2632
+ const jiti = (0, import_jiti.createJiti)(options.rootDir, { interopDefault: true });
2633
+ const ctx = {
2634
+ options,
2635
+ jiti,
2636
+ warnings: /* @__PURE__ */ new Set(),
2637
+ pkg,
2638
+ buildEntries: [],
2639
+ usedImports: /* @__PURE__ */ new Set(),
2640
+ hooks: (0, import_hookable.createHooks)()
2641
+ };
2642
+ if (preset.hooks) {
2643
+ ctx.hooks.addHooks(preset.hooks);
2644
+ }
2645
+ if (inputConfig.hooks) {
2646
+ ctx.hooks.addHooks(inputConfig.hooks);
2647
+ }
2648
+ if (buildConfig.hooks) {
2649
+ ctx.hooks.addHooks(buildConfig.hooks);
2650
+ }
2651
+ await ctx.hooks.callHook("build:prepare", ctx);
2652
+ options.entries = options.entries.map(
2653
+ (entry) => typeof entry === "string" ? { input: entry } : entry
2654
+ );
2655
+ for (const entry of options.entries) {
2656
+ if (typeof entry.name !== "string") {
2657
+ let relativeInput = (0, import_pathe.isAbsolute)(entry.input) ? (0, import_pathe.relative)(rootDir, entry.input) : (0, import_pathe.normalize)(entry.input);
2658
+ if (relativeInput.startsWith("./")) {
2659
+ relativeInput = relativeInput.slice(2);
2660
+ }
2661
+ entry.name = removeExtension(relativeInput.replace(/^src\//, ""));
2662
+ }
2663
+ if (!entry.input) {
2664
+ throw new Error("Missing entry input: " + dumpObject(entry));
2665
+ }
2666
+ if (!entry.builder) {
2667
+ entry.builder = entry.input.endsWith("/") ? "mkdist" : "rollup";
2668
+ }
2669
+ if (options.declaration !== void 0 && entry.declaration === void 0) {
2670
+ entry.declaration = options.declaration;
2671
+ }
2672
+ entry.input = (0, import_pathe.resolve)(options.rootDir, entry.input);
2673
+ entry.outDir = (0, import_pathe.resolve)(options.rootDir, entry.outDir || options.outDir);
2674
+ }
2675
+ options.dependencies = Object.keys(pkg.dependencies || {});
2676
+ options.peerDependencies = Object.keys(pkg.peerDependencies || {});
2677
+ options.devDependencies = Object.keys(pkg.devDependencies || {});
2678
+ options.externals.push(...inferPkgExternals(pkg));
2679
+ options.externals = [...new Set(options.externals)];
2680
+ await ctx.hooks.callHook("build:before", ctx);
2681
+ import_consola.consola.info(
2682
+ import_utils.colors.cyan(`${options.stub ? "Stubbing" : "Building"} ${options.name}`)
2683
+ );
2684
+ if (process.env.DEBUG) {
2685
+ import_consola.consola.info(`${import_utils.colors.bold("Root dir:")} ${options.rootDir}
2686
+ ${import_utils.colors.bold("Entries:")}
2687
+ ${options.entries.map((entry) => " " + dumpObject(entry)).join("\n ")}
2688
+ `);
2689
+ }
2690
+ if (options.clean) {
2691
+ for (const dir of new Set(
2692
+ options.entries.map((e) => e.outDir).filter(Boolean).sort()
2693
+ )) {
2694
+ if (dir === options.rootDir || options.rootDir.startsWith(withTrailingSlash(dir)) || cleanedDirs.some((c) => dir.startsWith(c))) {
2695
+ continue;
2696
+ }
2697
+ cleanedDirs.push(dir);
2698
+ import_consola.consola.info(
2699
+ `Cleaning dist directory: \`./${(0, import_pathe.relative)(process.cwd(), dir)}\``
2700
+ );
2701
+ await rmdir(dir);
2702
+ await import_node_fs6.promises.mkdir(dir, { recursive: true });
2703
+ }
2704
+ }
2705
+ const buildTasks = [
2706
+ typesBuild,
2707
+ // untyped
2708
+ mkdistBuild,
2709
+ // mkdist
2710
+ rollupBuild,
2711
+ // rollup
2712
+ copyBuild
2713
+ // copy
2714
+ ];
2715
+ if (options.parallel) {
2716
+ await Promise.all(buildTasks.map((task) => task(ctx)));
2717
+ } else {
2718
+ for (const task of buildTasks) {
2719
+ await task(ctx);
2720
+ }
2721
+ }
2722
+ if (options.stub || options.watch) {
2723
+ await ctx.hooks.callHook("build:done", ctx);
2724
+ return;
2725
+ }
2726
+ import_consola.consola.success(import_utils.colors.green("Build succeeded for " + options.name));
2727
+ const outFiles = await (0, import_tinyglobby.glob)(["**"], { cwd: options.outDir });
2728
+ for (const file of outFiles) {
2729
+ let entry = ctx.buildEntries.find((e) => e.path === file);
2730
+ if (!entry) {
2731
+ entry = {
2732
+ path: file,
2733
+ chunk: true
2734
+ };
2735
+ ctx.buildEntries.push(entry);
2736
+ }
2737
+ if (!entry.bytes) {
2738
+ const stat = await import_node_fs6.promises.stat((0, import_pathe.resolve)(options.outDir, file));
2739
+ entry.bytes = stat.size;
2740
+ }
2741
+ }
2742
+ const rPath = /* @__PURE__ */ __name((p) => (0, import_pathe.relative)(process.cwd(), (0, import_pathe.resolve)(options.outDir, p)), "rPath");
2743
+ for (const entry of ctx.buildEntries.filter((e) => !e.chunk)) {
2744
+ let totalBytes = entry.bytes || 0;
2745
+ for (const chunk of entry.chunks || []) {
2746
+ totalBytes += ctx.buildEntries.find((e) => e.path === chunk)?.bytes || 0;
2747
+ }
2748
+ let line = ` ${import_utils.colors.bold(rPath(entry.path))} (` + [
2749
+ totalBytes && `total size: ${import_utils.colors.cyan((0, import_pretty_bytes.default)(totalBytes))}`,
2750
+ entry.bytes && `chunk size: ${import_utils.colors.cyan((0, import_pretty_bytes.default)(entry.bytes))}`,
2751
+ entry.exports?.length && `exports: ${import_utils.colors.gray(entry.exports.join(", "))}`
2752
+ ].filter(Boolean).join(", ") + ")";
2753
+ if (entry.chunks?.length) {
2754
+ line += "\n" + entry.chunks.map((p) => {
2755
+ const chunk = ctx.buildEntries.find((e) => e.path === p) || {};
2756
+ return import_utils.colors.gray(
2757
+ " \u2514\u2500 " + rPath(p) + import_utils.colors.bold(
2758
+ chunk.bytes ? ` (${(0, import_pretty_bytes.default)(chunk?.bytes)})` : ""
2759
+ )
2760
+ );
2761
+ }).join("\n");
2762
+ }
2763
+ if (entry.modules?.length) {
2764
+ line += "\n" + entry.modules.filter((m) => m.id.includes("node_modules")).sort((a, b) => (b.bytes || 0) - (a.bytes || 0)).map((m) => {
2765
+ return import_utils.colors.gray(
2766
+ " \u{1F4E6} " + rPath(m.id) + import_utils.colors.bold(m.bytes ? ` (${(0, import_pretty_bytes.default)(m.bytes)})` : "")
2767
+ );
2768
+ }).join("\n");
2769
+ }
2770
+ import_consola.consola.log(entry.chunk ? import_utils.colors.gray(line) : line);
2771
+ }
2772
+ console.log(
2773
+ "\u03A3 Total dist size (byte size):",
2774
+ import_utils.colors.cyan(
2775
+ (0, import_pretty_bytes.default)(ctx.buildEntries.reduce((a, e) => a + (e.bytes || 0), 0))
2776
+ )
2777
+ );
2778
+ validateDependencies(ctx);
2779
+ validatePackage(pkg, rootDir, ctx);
2780
+ await ctx.hooks.callHook("build:done", ctx);
2781
+ import_consola.consola.log("");
2782
+ if (ctx.warnings.size > 0) {
2783
+ import_consola.consola.warn(
2784
+ "Build is done with some warnings:\n\n" + [...ctx.warnings].map((msg) => "- " + msg).join("\n")
2785
+ );
2786
+ if (ctx.options.failOnWarn) {
2787
+ import_consola.consola.error(
2788
+ "Exiting with code (1). You can change this behavior by setting `failOnWarn: false` ."
2789
+ );
2790
+ process.exit(1);
2791
+ }
2792
+ }
2793
+ }
2794
+ __name(_build, "_build");
2795
+
2796
+ // ../../node_modules/.pnpm/unbuild@3.3.1_sass@1.83.4_typescript@5.7.3/node_modules/unbuild/dist/index.mjs
2797
+ var import_node_module3 = require("module");
2798
+ var import_node_fs7 = require("fs");
2799
+ var import_pathe2 = require("pathe");
2800
+ var import_utils3 = require("consola/utils");
2801
+ var import_consola2 = require("consola");
2802
+ var import_defu4 = require("defu");
2803
+ var import_hookable2 = require("hookable");
2804
+ var import_pretty_bytes2 = require("pretty-bytes");
2805
+ var import_tinyglobby2 = require("tinyglobby");
2806
+ var import_promises5 = require("fs/promises");
2807
+ var import_jiti2 = require("jiti");
2808
+ var import_rollup2 = require("rollup");
2809
+ var import_rollup_plugin_dts2 = require("rollup-plugin-dts");
2810
+ var import_plugin_commonjs2 = require("@rollup/plugin-commonjs");
2811
+ var import_plugin_node_resolve2 = require("@rollup/plugin-node-resolve");
2812
+ var import_plugin_alias2 = require("@rollup/plugin-alias");
2813
+ var import_plugin_replace2 = require("@rollup/plugin-replace");
2814
+ var import_utils4 = require("pathe/utils");
2815
+ var import_mlly2 = require("mlly");
2816
+ var import_esbuild2 = require("esbuild");
2817
+ var import_pluginutils2 = require("@rollup/pluginutils");
2818
+ var import_plugin_json2 = require("@rollup/plugin-json");
2819
+ var import_magic_string2 = require("magic-string");
2820
+ var import_untyped2 = require("untyped");
2821
+ var import_babel_plugin2 = require("untyped/babel-plugin");
2822
+ var import_scule2 = require("scule");
2823
+ var import_mkdist2 = require("mkdist");
2824
+
2825
+ // src/clean.ts
2826
+ var import_promises6 = require("fs/promises");
2827
+ async function clean(name = "Unbuild", directory, config) {
2828
+ writeDebug(` \u{1F9F9} Cleaning ${name} output path: ${directory}`, config);
2829
+ const stopwatch = getStopwatch(`${name} output clean`);
2830
+ await cleanDirectories(name, directory, config);
2831
+ stopwatch();
2832
+ }
2833
+ __name(clean, "clean");
2834
+ async function cleanDirectories(name = "Unbuild", directory, config) {
2835
+ await (0, import_promises6.rm)(directory, {
2836
+ recursive: true,
2837
+ force: true
2838
+ });
2839
+ }
2840
+ __name(cleanDirectories, "cleanDirectories");
2841
+
2842
+ // src/plugins/analyze.ts
2843
+ var formatBytes = /* @__PURE__ */ __name((bytes) => {
2844
+ if (bytes === 0) return "0 Byte";
2845
+ const k = 1e3;
2846
+ const dm = 3;
2847
+ const sizes = [
2848
+ "Bytes",
2849
+ "KB",
2850
+ "MB",
2851
+ "GB"
2852
+ ];
2853
+ const i = Math.floor(Math.log(bytes) / Math.log(k));
2854
+ return `${parseFloat((bytes / k ** i).toFixed(dm))} ${sizes[i]}`;
2855
+ }, "formatBytes");
2856
+ var analyzePlugin = /* @__PURE__ */ __name((options, resolvedOptions) => {
2857
+ return {
2858
+ name: "storm:analyzer",
2859
+ renderChunk(source, chunk) {
2860
+ const sourceBytes = formatBytes(source.length);
2861
+ const fileName = chunk.fileName;
2862
+ writeInfo(` - ${fileName} ${sourceBytes}`, resolvedOptions.config);
2863
+ }
2864
+ };
2865
+ }, "analyzePlugin");
2866
+
2867
+ // src/plugins/on-error.ts
2868
+ var onErrorPlugin = /* @__PURE__ */ __name((options, resolvedOptions) => ({
2869
+ name: "storm:on-error",
2870
+ buildEnd(error) {
2871
+ if (error) {
2872
+ writeError(`The following errors occurred during the build:
2873
+ ${error ? error.message : "Unknown build error"}
2874
+
2875
+ `, resolvedOptions.config);
2876
+ throw new Error("Storm unbuild process failed with errors.");
2877
+ }
2878
+ },
2879
+ renderError(error) {
2880
+ writeError(`The following errors occurred during the build:
2881
+ ${error ? error.message : "Unknown build error"}
2882
+
2883
+ `, resolvedOptions.config);
2884
+ throw new Error("Storm unbuild process failed with errors.");
2885
+ }
2886
+ }), "onErrorPlugin");
2887
+
2888
+ // src/plugins/tsc.ts
2889
+ var import_devkit5 = require("@nx/devkit");
2890
+ var import_buildable_libs_utils3 = require("@nx/js/src/utils/buildable-libs-utils");
2891
+ var import_compiler_helper_dependency = require("@nx/js/src/utils/compiler-helper-dependency");
2892
+ var import_rollup_plugin_typescript2 = __toESM(require("rollup-plugin-typescript2"), 1);
2893
+
2894
+ // src/utilities/helpers.ts
2895
+ var import_devkit4 = require("@nx/devkit");
2896
+ var import_buildable_libs_utils2 = require("@nx/js/src/utils/buildable-libs-utils");
2897
+ var import_node_path4 = require("path");
2898
+ var import_node_url = require("url");
2899
+ var import_typescript = __toESM(require("typescript"), 1);
2900
+ async function loadConfig2(configPath) {
2901
+ if (!/\.(js|mjs)$/.test((0, import_node_path4.extname)(configPath))) {
2902
+ throw new Error("Unsupported config file format");
2903
+ }
2904
+ return import((0, import_node_url.pathToFileURL)(configPath).toString()).then((config) => config.default);
2905
+ }
2906
+ __name(loadConfig2, "loadConfig");
2907
+ async function createTsCompilerOptions(config, tsConfigPath, projectRoot, dependencies) {
2908
+ const tsConfigFile = import_typescript.default.readConfigFile((0, import_devkit4.joinPathFragments)(config.workspaceRoot, projectRoot, tsConfigPath), import_typescript.default.sys.readFile);
2909
+ const tsConfig = import_typescript.default.parseJsonConfigFileContent(tsConfigFile.config, import_typescript.default.sys, (0, import_node_path4.dirname)((0, import_devkit4.joinPathFragments)(config.workspaceRoot, projectRoot, tsConfigPath)));
2910
+ const compilerOptions = {
2911
+ rootDir: projectRoot,
2912
+ declaration: true,
2913
+ paths: (0, import_buildable_libs_utils2.computeCompilerOptionsPaths)(tsConfig, dependencies ?? [])
2914
+ };
2915
+ writeTrace(compilerOptions, config);
2916
+ return compilerOptions;
2917
+ }
2918
+ __name(createTsCompilerOptions, "createTsCompilerOptions");
2919
+
2920
+ // src/plugins/tsc.ts
2921
+ var tscPlugin = /* @__PURE__ */ __name(async (options, resolvedOptions) => {
2922
+ const projectGraph = (0, import_devkit5.readCachedProjectGraph)();
2923
+ const result = (0, import_buildable_libs_utils3.calculateProjectBuildableDependencies)(void 0, projectGraph, resolvedOptions.config.workspaceRoot, resolvedOptions.projectName, process.env.NX_TASK_TARGET_TARGET || "build", process.env.NX_TASK_TARGET_CONFIGURATION || "production", true);
2924
+ let dependencies = result.dependencies;
2925
+ const tsLibDependency = (0, import_compiler_helper_dependency.getHelperDependency)(import_compiler_helper_dependency.HelperDependency.tsc, resolvedOptions.tsconfig, dependencies, projectGraph, true);
2926
+ if (tsLibDependency) {
2927
+ dependencies = dependencies.filter((deps) => deps.name !== tsLibDependency.name);
2928
+ dependencies.push(tsLibDependency);
2929
+ }
2930
+ return (0, import_rollup_plugin_typescript2.default)({
2931
+ check: options.emitTypes !== false,
2932
+ tsconfig: resolvedOptions.tsconfig,
2933
+ tsconfigOverride: {
2934
+ compilerOptions: await createTsCompilerOptions(resolvedOptions.config, resolvedOptions.tsconfig, resolvedOptions.projectRoot, dependencies)
2935
+ }
2936
+ });
2937
+ }, "tscPlugin");
2938
+
2939
+ // src/plugins/type-definitions.ts
2940
+ var import_node_path5 = require("path");
2941
+ function typeDefinitions(projectRoot) {
2942
+ return {
2943
+ name: "storm:dts-bundle",
2944
+ async generateBundle(_opts, bundle) {
2945
+ for (const file of Object.values(bundle)) {
2946
+ if (file.type === "asset" || !file.isEntry || file.facadeModuleId == null) {
2947
+ continue;
2948
+ }
2949
+ const hasDefaultExport = file.exports.includes("default");
2950
+ const entrySourceFileName = (0, import_node_path5.relative)(projectRoot, file.facadeModuleId);
2951
+ const entrySourceDtsName = entrySourceFileName.replace(/\.[cm]?[jt]sx?$/, "");
2952
+ const dtsFileName = file.fileName.replace(/\.[cm]?js$/, ".d.ts");
2953
+ const relativeSourceDtsName = JSON.stringify("./" + entrySourceDtsName);
2954
+ const dtsFileSource = hasDefaultExport ? `
2955
+ export * from ${relativeSourceDtsName};
2956
+ export { default } from ${relativeSourceDtsName};
2957
+ ` : `export * from ${relativeSourceDtsName};
2958
+ `;
2959
+ this.emitFile({
2960
+ type: "asset",
2961
+ fileName: dtsFileName,
2962
+ source: dtsFileSource
2963
+ });
2964
+ }
2965
+ }
2966
+ };
2967
+ }
2968
+ __name(typeDefinitions, "typeDefinitions");
2969
+
2970
+ // src/config.ts
2971
+ var getDefaultBuildPlugins = /* @__PURE__ */ __name(async (options, resolvedOptions) => Promise.all([
2972
+ analyzePlugin(options, resolvedOptions),
2973
+ typeDefinitions(resolvedOptions.projectRoot),
2974
+ tscPlugin(options, resolvedOptions),
2975
+ onErrorPlugin(options, resolvedOptions)
2976
+ ].map((plugin) => Promise.resolve(plugin))), "getDefaultBuildPlugins");
2977
+
2978
+ // src/build.ts
2979
+ async function resolveOptions(options, config) {
2980
+ writeDebug(" \u2699\uFE0F Resolving build options", config);
2981
+ const stopwatch = getStopwatch("Build options resolution");
2982
+ if (options.configPath) {
2983
+ const configFile = await loadConfig2(options.configPath);
2984
+ if (configFile) {
2985
+ options = (0, import_defu5.default)(options, configFile);
2986
+ }
2987
+ }
2988
+ const outputPath = options.outputPath || joinPaths("dist", options.projectRoot);
2989
+ const projectGraph = (0, import_devkit6.readCachedProjectGraph)();
2990
+ const projectJsonPath = joinPaths(config.workspaceRoot, options.projectRoot, "project.json");
2991
+ if (!(0, import_node_fs8.existsSync)(projectJsonPath)) {
2992
+ throw new Error("Cannot find project.json configuration");
2993
+ }
2994
+ const projectJsonContent = await (0, import_promises7.readFile)(projectJsonPath, "utf8");
2995
+ const projectJson = JSON.parse(projectJsonContent);
2996
+ const projectName = projectJson.name;
2997
+ const packageJsonPath = joinPaths(config.workspaceRoot, options.projectRoot, "package.json");
2998
+ if (!(0, import_node_fs8.existsSync)(packageJsonPath)) {
2999
+ throw new Error("Cannot find package.json configuration");
3000
+ }
3001
+ const packageJsonContent = await (0, import_promises7.readFile)(packageJsonPath, "utf8");
3002
+ const packageJson = JSON.parse(packageJsonContent);
3003
+ let tsconfig = options.tsconfig;
3004
+ if (!tsconfig) {
3005
+ tsconfig = joinPaths(config.workspaceRoot, options.projectRoot, "tsconfig.json");
3006
+ }
3007
+ if (!(0, import_node_fs8.existsSync)(tsconfig)) {
3008
+ throw new Error("Cannot find tsconfig.json configuration");
3009
+ }
3010
+ let sourceRoot = projectJson.sourceRoot;
3011
+ if (!sourceRoot) {
3012
+ sourceRoot = joinPaths(options.projectRoot, "src");
3013
+ }
3014
+ if (!(0, import_node_fs8.existsSync)(sourceRoot)) {
3015
+ throw new Error("Cannot find sourceRoot directory");
3016
+ }
3017
+ const result = (0, import_buildable_libs_utils4.calculateProjectBuildableDependencies)(void 0, projectGraph, config.workspaceRoot, projectName, process.env.NX_TASK_TARGET_TARGET || "build", process.env.NX_TASK_TARGET_CONFIGURATION || "production", true);
3018
+ let dependencies = result.dependencies;
3019
+ const tsLibDependency = (0, import_js2.getHelperDependency)(import_js2.HelperDependency.tsc, tsconfig, dependencies, projectGraph, true);
3020
+ if (tsLibDependency) {
3021
+ dependencies = dependencies.filter((deps) => deps.name !== tsLibDependency.name);
3022
+ dependencies.push(tsLibDependency);
3023
+ }
3024
+ const resolvedOptions = {
3025
+ name: projectName,
3026
+ config,
3027
+ projectRoot: options.projectRoot,
3028
+ sourceRoot,
3029
+ projectName,
3030
+ tsconfig,
3031
+ clean: false,
3032
+ entries: [
3033
+ {
3034
+ builder: "mkdist",
3035
+ input: `.${sourceRoot.replace(options.projectRoot, "")}`,
3036
+ outDir: joinPaths((0, import_node_path6.relative)(joinPaths(config.workspaceRoot, options.projectRoot), config.workspaceRoot).replaceAll("\\", "/"), outputPath, "dist").replaceAll("\\", "/"),
3037
+ declaration: options.emitTypes !== false,
3038
+ format: "esm"
3039
+ },
3040
+ {
3041
+ builder: "mkdist",
3042
+ input: `.${sourceRoot.replace(options.projectRoot, "")}`,
3043
+ outDir: joinPaths((0, import_node_path6.relative)(joinPaths(config.workspaceRoot, options.projectRoot), config.workspaceRoot).replaceAll("\\", "/"), outputPath, "dist").replaceAll("\\", "/"),
3044
+ declaration: options.emitTypes !== false,
3045
+ format: "cjs",
3046
+ ext: "cjs"
3047
+ }
3048
+ ],
3049
+ declaration: options.emitTypes !== false ? "compatible" : false,
3050
+ failOnWarn: false,
3051
+ sourcemap: options.sourcemap ?? !!options.debug,
3052
+ outDir: outputPath,
3053
+ parallel: true,
3054
+ stub: false,
3055
+ stubOptions: {
3056
+ jiti: {}
3057
+ },
3058
+ externals: options.external ?? [],
3059
+ dependencies: [],
3060
+ peerDependencies: [],
3061
+ devDependencies: [],
3062
+ hooks: {},
3063
+ alias: {},
3064
+ replace: {},
3065
+ rollup: {
3066
+ replace: {},
3067
+ alias: {},
3068
+ json: {},
3069
+ commonjs: {
3070
+ sourceMap: options.sourcemap ?? true
3071
+ },
3072
+ emitCJS: true,
3073
+ cjsBridge: true,
3074
+ dts: {
3075
+ respectExternal: true,
3076
+ tsconfig
3077
+ },
3078
+ output: {
3079
+ banner: options.banner || `
3080
+ // \u26A1 Built by Storm Software
3081
+ `,
3082
+ footer: options.footer
3083
+ },
3084
+ resolve: {
3085
+ preferBuiltins: true,
3086
+ extensions: [
3087
+ ".cjs",
3088
+ ".mjs",
3089
+ ".js",
3090
+ ".jsx",
3091
+ ".ts",
3092
+ ".tsx",
3093
+ ".json"
3094
+ ]
3095
+ },
3096
+ esbuild: {
3097
+ minify: options.minify !== false,
3098
+ splitting: options.splitting !== false,
3099
+ treeShaking: options.treeShaking !== false,
3100
+ color: true,
3101
+ logLevel: config.logLevel === LogLevelLabel.FATAL ? LogLevelLabel.ERROR : isVerbose() ? "verbose" : config.logLevel
3102
+ }
3103
+ }
3104
+ };
3105
+ dependencies = dependencies.filter((dep) => dep.node.type === "npm" || dep.node.type === "lib" || dep.node.type === "app");
3106
+ if (dependencies.length > 0) {
3107
+ resolvedOptions.dependencies = dependencies.map((dep) => dep.name);
3108
+ }
3109
+ if (packageJson.devDependencies) {
3110
+ resolvedOptions.devDependencies = Object.keys(packageJson.devDependencies);
3111
+ }
3112
+ if (packageJson.peerDependencies) {
3113
+ resolvedOptions.peerDependencies = Object.keys(packageJson.peerDependencies);
3114
+ }
3115
+ if (options.rollup) {
3116
+ let rollup2 = {};
3117
+ if (typeof options.rollup === "string") {
3118
+ const rollupFile = await loadConfig2(options.rollup);
3119
+ if (rollupFile) {
3120
+ rollup2 = rollupFile;
3121
+ }
3122
+ } else {
3123
+ rollup2 = options.rollup;
3124
+ }
3125
+ resolvedOptions.rollup = (0, import_defu5.default)(resolvedOptions.rollup ?? {}, rollup2);
3126
+ }
3127
+ resolvedOptions.hooks = {
3128
+ "rollup:options": /* @__PURE__ */ __name(async (ctx, opts) => {
3129
+ opts.plugins = options.plugins ?? await getDefaultBuildPlugins(options, resolvedOptions);
3130
+ }, "rollup:options")
3131
+ };
3132
+ stopwatch();
3133
+ return resolvedOptions;
3134
+ }
3135
+ __name(resolveOptions, "resolveOptions");
3136
+ async function generatePackageJson(options) {
3137
+ if (options.generatePackageJson !== false && (0, import_node_fs8.existsSync)(joinPaths(options.projectRoot, "package.json"))) {
3138
+ writeDebug(" \u270D\uFE0F Writing package.json file", options.config);
3139
+ const stopwatch = getStopwatch("Write package.json file");
3140
+ const packageJsonPath = joinPaths(options.projectRoot, "project.json");
3141
+ if (!(0, import_node_fs8.existsSync)(packageJsonPath)) {
3142
+ throw new Error("Cannot find package.json configuration");
3143
+ }
3144
+ let packageJsonContent = await (0, import_promises7.readFile)(joinPaths(options.config.workspaceRoot, options.projectRoot, "package.json"), "utf8");
3145
+ if (!packageJsonContent) {
3146
+ throw new Error("Cannot find package.json configuration file");
3147
+ }
3148
+ let packageJson = JSON.parse(packageJsonContent);
3149
+ packageJson = await addPackageDependencies(options.config.workspaceRoot, options.projectRoot, options.projectName, packageJson);
3150
+ packageJson = await addWorkspacePackageJsonFields(options.config, options.projectRoot, options.sourceRoot, options.projectName, false, packageJson);
3151
+ await (0, import_devkit6.writeJsonFile)(joinPaths(options.outDir, "package.json"), await addPackageJsonExports(options.sourceRoot, packageJson));
3152
+ stopwatch();
3153
+ }
3154
+ return options;
3155
+ }
3156
+ __name(generatePackageJson, "generatePackageJson");
3157
+ async function executeUnbuild(options) {
3158
+ writeDebug(` \u{1F680} Running ${options.name} (${options.projectRoot}) build`, options.config);
3159
+ const stopwatch = getStopwatch(`${options.name} (${options.projectRoot}) build`);
3160
+ try {
3161
+ await build(options.projectRoot, false, {
3162
+ ...options,
3163
+ rootDir: options.projectRoot
3164
+ });
3165
+ } finally {
3166
+ stopwatch();
3167
+ }
3168
+ return options;
3169
+ }
3170
+ __name(executeUnbuild, "executeUnbuild");
3171
+ async function copyBuildAssets(options) {
3172
+ writeDebug(` \u{1F4CB} Copying asset files to output directory: ${options.outDir}`, options.config);
3173
+ const stopwatch = getStopwatch(`${options.name} asset copy`);
3174
+ await copyAssets(options.config, options.assets ?? [], options.outDir, options.projectRoot, options.projectName, options.sourceRoot, options.generatePackageJson, options.includeSrc);
3175
+ stopwatch();
3176
+ return options;
3177
+ }
3178
+ __name(copyBuildAssets, "copyBuildAssets");
3179
+ async function cleanOutputPath(options) {
3180
+ if (options.clean !== false && options.outDir) {
3181
+ writeDebug(` \u{1F9F9} Cleaning ${options.name} output path: ${options.outDir}`, options.config);
3182
+ const stopwatch = getStopwatch(`${options.name} output clean`);
3183
+ await cleanDirectories(options.name, options.outDir, options.config);
3184
+ stopwatch();
3185
+ }
3186
+ return options;
3187
+ }
3188
+ __name(cleanOutputPath, "cleanOutputPath");
3189
+ async function build2(options) {
3190
+ const projectRoot = options.projectRoot;
3191
+ if (!projectRoot) {
3192
+ throw new Error("Cannot find project root");
3193
+ }
3194
+ const workspaceRoot = (0, import_find_workspace_root5.findWorkspaceRoot)(projectRoot);
3195
+ if (!workspaceRoot) {
3196
+ throw new Error("Cannot find workspace root");
3197
+ }
3198
+ const config = await loadStormConfig(workspaceRoot.dir);
3199
+ writeDebug(` \u26A1 Executing Storm Unbuild pipeline`, config);
3200
+ const stopwatch = getStopwatch("Unbuild pipeline");
3201
+ try {
3202
+ options.projectRoot = projectRoot;
3203
+ const resolvedOptions = await resolveOptions(options, config);
3204
+ await cleanOutputPath(resolvedOptions);
3205
+ await generatePackageJson(resolvedOptions);
3206
+ await executeUnbuild(resolvedOptions);
3207
+ await copyBuildAssets(resolvedOptions);
3208
+ writeSuccess(` \u{1F3C1} The ${resolvedOptions.name} build completed successfully`, config);
3209
+ } catch (error) {
3210
+ writeFatal(" \u274C Fatal errors occurred during the build that could not be recovered from. The build process has been terminated.", config);
3211
+ throw error;
3212
+ } finally {
3213
+ stopwatch();
3214
+ }
3215
+ }
3216
+ __name(build2, "build");
3217
+
3218
+ // bin/unbuild.ts
3219
+ async function createProgram(config) {
3220
+ try {
3221
+ writeInfo("\u26A1 Running Storm Unbuild pipeline", config);
3222
+ const root = findWorkspaceRootSafe();
3223
+ process.env.STORM_WORKSPACE_ROOT ??= root;
3224
+ process.env.NX_WORKSPACE_ROOT_PATH ??= root;
3225
+ root && process.chdir(root);
3226
+ const program = new import_commander.Command("storm-unbuild");
3227
+ program.version("1.0.0", "-v --version", "display CLI version");
3228
+ program.description("\u26A1 Run the Storm Unbuild pipeline").showHelpAfterError().showSuggestionAfterError();
3229
+ 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);
3230
+ const sourceRootOption = new import_commander.Option("-s --source-root <path>", "The path of the project's source folder to build");
3231
+ const nameOption = new import_commander.Option("-n --name <value>", "The name of the project to build");
3232
+ const outputPathOption = new import_commander.Option("-o --output-path <path>", "The path of the project's source folder to build").default("dist/{projectRoot}");
3233
+ const platformOption = new import_commander.Option("-p --platform <value>", "The platform to build the distribution for").choices([
3234
+ "node",
3235
+ "neutral",
3236
+ "browser"
3237
+ ]).default("node");
3238
+ const formatOption = new import_commander.Option("-f, --format <value...>", "The format to build the distribution in").choices([
3239
+ "esm",
3240
+ "cjs",
3241
+ "iife"
3242
+ ]).argParser((value, previous) => {
3243
+ if (previous === void 0) {
3244
+ return [
3245
+ value
3246
+ ];
3247
+ } else if (!previous.includes(value)) {
3248
+ previous.push(value);
3249
+ }
3250
+ return previous;
3251
+ }).default("esm");
3252
+ const cleanOption = new import_commander.Option("-c --clean", "Should the output directory be cleaned before building").default(true);
3253
+ const noCleanOption = new import_commander.Option("--no-clean", "Should the output directory be cleaned before building").default(false);
3254
+ const bundleOption = new import_commander.Option("-b --bundle", "Should the output be bundled").default(true);
3255
+ const noBundleOption = new import_commander.Option("--no-bundle", "Should the output be bundled").default(false);
3256
+ const targetOption = new import_commander.Option("-t --target <value>", "The target to build the distribution for").choices([
3257
+ "ESNext",
3258
+ "ES2015",
3259
+ "ES2016",
3260
+ "ES2017",
3261
+ "ES2018",
3262
+ "ES2019",
3263
+ "ES2020",
3264
+ "ES2021",
3265
+ "ES2022",
3266
+ "ES2023"
3267
+ ]).default("ESNext");
3268
+ const watchOption = new import_commander.Option("-w --watch", "Should the build process watch for changes").default(false);
3269
+ const debugOption = new import_commander.Option("-d --debug", "Should the build process run in debug mode").default(false);
3270
+ const bannerOption = new import_commander.Option("--banner <value>", "The banner to prepend to the output");
3271
+ const footerOption = new import_commander.Option("--footer <value>", "The footer to prepend to the output");
3272
+ const splittingOption = new import_commander.Option("--splitting", "Should the output be split into multiple files").default(true);
3273
+ const treeShakingOption = new import_commander.Option("--tree-shaking", "Should tree shaking be enabled").default(true);
3274
+ const generatePackageJsonOption = new import_commander.Option("--generate-package-json", "Should a package.json be generated for the output").default(true);
3275
+ const emitOnAllOption = new import_commander.Option("--emit-on-all", "Should the output be emitted on all platforms").default(false);
3276
+ const metafileOption = new import_commander.Option("--metafile", "Should a metafile be generated for the output").default(true);
3277
+ const minifyOption = new import_commander.Option("--minify", "Should the output be minified").default(true);
3278
+ const includeSrcOption = new import_commander.Option("--include-src", "Should the source files be included in the output").default(false);
3279
+ const verboseOption = new import_commander.Option("--verbose", "Should the build process be verbose").default(false);
3280
+ const emitTypesOption = new import_commander.Option("--emit-types", "Should types be emitted for the output").default(true);
3281
+ program.command("build", {
3282
+ isDefault: true
3283
+ }).alias("bundle").description("Run a TypeScript build using Unbuild.").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(emitTypesOption).action(buildAction(config));
3284
+ 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));
3285
+ return program;
3286
+ } catch (e) {
3287
+ writeFatal(`A fatal error occurred while running the program: ${e.message}`, config);
3288
+ process.exit(1);
3289
+ }
3290
+ }
3291
+ __name(createProgram, "createProgram");
3292
+ var buildAction = /* @__PURE__ */ __name((config) => async (options) => {
3293
+ try {
3294
+ await build2({
3295
+ ...options,
3296
+ sourcemap: !!options.debug,
3297
+ replace: {},
3298
+ alias: {},
3299
+ stub: false,
3300
+ watchOptions: {
3301
+ buildDelay: 5e3,
3302
+ chokidar: {},
3303
+ clearScreen: true,
3304
+ skipWrite: true
3305
+ },
3306
+ stubOptions: {
3307
+ jiti: {}
3308
+ },
3309
+ dependencies: [],
3310
+ peerDependencies: [],
3311
+ devDependencies: [],
3312
+ rollup: {
3313
+ emitCJS: false,
3314
+ watch: false,
3315
+ cjsBridge: false,
3316
+ dts: {
3317
+ respectExternal: true
3318
+ },
3319
+ replace: {},
3320
+ alias: {},
3321
+ resolve: {},
3322
+ json: {},
3323
+ commonjs: {},
3324
+ esbuild: {
3325
+ target: options.target,
3326
+ format: "esm",
3327
+ platform: options.platform,
3328
+ minify: options.minify,
3329
+ treeShaking: options.treeShaking
3330
+ }
3331
+ }
3332
+ });
3333
+ } catch (e) {
3334
+ writeFatal(`A fatal error occurred while cleaning the Unbuild output directory: ${e.message}`, config);
3335
+ exitWithError(config);
3336
+ process.exit(1);
3337
+ }
3338
+ }, "buildAction");
3339
+ var cleanAction = /* @__PURE__ */ __name((config) => async (options) => {
3340
+ try {
3341
+ await clean(options.name, options.output, config);
3342
+ } catch (e) {
3343
+ writeFatal(`A fatal error occurred while cleaning the ESBuild output directory: ${e.message}`, config);
3344
+ exitWithError(config);
3345
+ process.exit(1);
3346
+ }
3347
+ }, "cleanAction");
3348
+ void (async () => {
3349
+ const config = await loadStormConfig();
3350
+ const stopwatch = getStopwatch("Storm ESBuild executable");
3351
+ try {
3352
+ handleProcess(config);
3353
+ const program = await createProgram(config);
3354
+ await program.parseAsync(process.argv);
3355
+ writeSuccess(`\u{1F389} Storm ESBuild executable has completed successfully!`, config);
3356
+ exitWithSuccess(config);
3357
+ } catch (error) {
3358
+ writeFatal(`A fatal error occurred while running Storm ESBuild executable:
3359
+
3360
+ ${error.message}`, config);
3361
+ exitWithError(config);
3362
+ process.exit(1);
3363
+ } finally {
3364
+ stopwatch();
3365
+ }
3366
+ })();