@fastkit/plugboy 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/LICENSE +21 -0
  2. package/cli.mjs +2 -0
  3. package/dist/chunk-QSOC5WYP.mjs +1493 -0
  4. package/dist/chunk-QSOC5WYP.mjs.map +1 -0
  5. package/dist/cli.d.ts +3 -0
  6. package/dist/cli.mjs +142 -0
  7. package/dist/cli.mjs.map +1 -0
  8. package/dist/dependencies/bundle-require.d.ts +1 -0
  9. package/dist/dependencies/bundle-require.mjs +3 -0
  10. package/dist/dependencies/bundle-require.mjs.map +1 -0
  11. package/dist/dependencies/cac.d.ts +1 -0
  12. package/dist/dependencies/cac.mjs +3 -0
  13. package/dist/dependencies/cac.mjs.map +1 -0
  14. package/dist/dependencies/esbuild.d.ts +1 -0
  15. package/dist/dependencies/esbuild.mjs +3 -0
  16. package/dist/dependencies/esbuild.mjs.map +1 -0
  17. package/dist/dependencies/glob.d.ts +1 -0
  18. package/dist/dependencies/glob.mjs +3 -0
  19. package/dist/dependencies/glob.mjs.map +1 -0
  20. package/dist/dependencies/inquirer.d.ts +3 -0
  21. package/dist/dependencies/inquirer.mjs +8 -0
  22. package/dist/dependencies/inquirer.mjs.map +1 -0
  23. package/dist/dependencies/pkg-types.d.ts +1 -0
  24. package/dist/dependencies/pkg-types.mjs +3 -0
  25. package/dist/dependencies/pkg-types.mjs.map +1 -0
  26. package/dist/dependencies/sort-package-json.d.ts +2 -0
  27. package/dist/dependencies/sort-package-json.mjs +7 -0
  28. package/dist/dependencies/sort-package-json.mjs.map +1 -0
  29. package/dist/dependencies/tsup.d.ts +1 -0
  30. package/dist/dependencies/tsup.mjs +3 -0
  31. package/dist/dependencies/tsup.mjs.map +1 -0
  32. package/dist/plugboy.d.ts +619 -0
  33. package/dist/plugboy.mjs +97 -0
  34. package/dist/plugboy.mjs.map +1 -0
  35. package/env.d.ts +35 -0
  36. package/package.json +93 -0
@@ -0,0 +1,1493 @@
1
+ // src/types/hook.ts
2
+ function createHooksDefaults() {
3
+ return {
4
+ setupWorkspace: [],
5
+ createWorkspace: [],
6
+ preparePackageJSON: []
7
+ };
8
+ }
9
+
10
+ // src/types/dts.ts
11
+ function normalizeDTSPreserveTypeTarget(target) {
12
+ const { from, typeName } = target;
13
+ return {
14
+ from: typeof from === "string" ? new RegExp(`${from}`, "g") : from,
15
+ typeName
16
+ };
17
+ }
18
+ function normalizeDTSPreserveTypeSettings(settings) {
19
+ return {
20
+ ...settings,
21
+ targets: settings.targets.map(normalizeDTSPreserveTypeTarget)
22
+ };
23
+ }
24
+ function normalizeDTSSettings(settings) {
25
+ const { inline = false, preserveType = [] } = settings || {};
26
+ return {
27
+ inline,
28
+ preserveType: preserveType.map(normalizeDTSPreserveTypeSettings)
29
+ };
30
+ }
31
+ function mergeDTSSettingsList(...settingsList) {
32
+ const merged = {};
33
+ settingsList.forEach((settings) => {
34
+ if (!settings)
35
+ return;
36
+ const { inline, preserveType } = settings;
37
+ if (inline !== void 0)
38
+ merged.inline = inline;
39
+ if (preserveType) {
40
+ merged.preserveType = merged.preserveType || [];
41
+ merged.preserveType.push(...preserveType);
42
+ }
43
+ });
44
+ return normalizeDTSSettings(merged);
45
+ }
46
+
47
+ // src/types/workspace.ts
48
+ var WORKSPACE_REQUIRED_FIELDS = ["name", "version"];
49
+ var TSUP_SYNC_OPTIONS = [
50
+ "define",
51
+ "noExternal",
52
+ "external",
53
+ "replaceNodeEnv",
54
+ "skipNodeModulesBundle"
55
+ ];
56
+
57
+ // src/types/project.ts
58
+ var PROJECT_REQUIRED_FIELDS = ["name"];
59
+
60
+ // src/utils/general.ts
61
+ function isPromise(obj) {
62
+ return !!obj && (typeof obj === "object" || typeof obj === "function") && typeof obj.then === "function";
63
+ }
64
+ async function resolveListable(raw) {
65
+ const result = [];
66
+ const list = Array.isArray(raw) ? raw : [raw];
67
+ for (let row of list) {
68
+ if (isPromise(row)) {
69
+ row = await row;
70
+ }
71
+ if (!row)
72
+ continue;
73
+ if (Array.isArray(row)) {
74
+ result.push(...await resolveListable(row));
75
+ continue;
76
+ }
77
+ result.push(row);
78
+ }
79
+ return result;
80
+ }
81
+
82
+ // src/utils/file.ts
83
+ import fs from "node:fs";
84
+ import path from "node:path";
85
+ import { fileURLToPath } from "node:url";
86
+ function getFilename(importMetaURL) {
87
+ return fileURLToPath(importMetaURL);
88
+ }
89
+ function getDirname(importMetaURL) {
90
+ return path.dirname(getFilename(importMetaURL));
91
+ }
92
+ var FILE_NOT_FOUND_EXCEPTION_CODES = ["ENOTDIR", "ENOENT"];
93
+ function isFileNotFoundException(source) {
94
+ return !!source && typeof source === "object" && FILE_NOT_FOUND_EXCEPTION_CODES.includes(
95
+ source.code
96
+ );
97
+ }
98
+ async function pathExists(target, type) {
99
+ try {
100
+ const stats = await fs.promises.stat(target);
101
+ if (!type)
102
+ return true;
103
+ return type === "file" ? stats.isFile() : stats.isDirectory();
104
+ } catch (err) {
105
+ if (isFileNotFoundException(err))
106
+ return false;
107
+ throw err;
108
+ }
109
+ }
110
+ function normalizeFileMatcher(matcher) {
111
+ if (typeof matcher === "function") {
112
+ return matcher;
113
+ }
114
+ if (typeof matcher === "string") {
115
+ return (file) => file.name.includes(matcher);
116
+ }
117
+ return (file) => matcher.test(file.name);
118
+ }
119
+ async function findFile(dir, matcher, recursive = true) {
120
+ const files = await fs.promises.readdir(dir, { withFileTypes: true });
121
+ const _matcher = normalizeFileMatcher(matcher);
122
+ const dirs = recursive ? [] : void 0;
123
+ for (const file of files) {
124
+ if (dirs && file.isDirectory()) {
125
+ dirs.push(file);
126
+ continue;
127
+ }
128
+ if (await _matcher(file, dir)) {
129
+ return path.join(dir, file.name);
130
+ }
131
+ }
132
+ if (dirs) {
133
+ for (const subDir of dirs) {
134
+ const hit = await findFile(
135
+ path.join(dir, subDir.name),
136
+ _matcher,
137
+ recursive
138
+ );
139
+ if (hit)
140
+ return hit;
141
+ }
142
+ }
143
+ }
144
+ var FIND_CONFIG_OR_RE = /\(.+?\)/g;
145
+ function parseFindConfigFileName(source) {
146
+ const matches = source.match(FIND_CONFIG_OR_RE);
147
+ if (!matches)
148
+ return [source];
149
+ return matches.map((matched) => {
150
+ const parts = matched.slice(1, matched.length - 1).split("|");
151
+ return parts.map((part) => {
152
+ const chunk = source.replace(matched, part);
153
+ return parseFindConfigFileName(chunk);
154
+ }).flat();
155
+ }).flat();
156
+ }
157
+ function parseRawFindConfigFileName(source) {
158
+ return Array.isArray(source) ? source.map(parseFindConfigFileName).flat() : parseFindConfigFileName(source);
159
+ }
160
+ async function findConfig(fileNameOrSettings, dir = process.cwd(), currentDepth = 0) {
161
+ const settings = typeof fileNameOrSettings === "object" && !Array.isArray(fileNameOrSettings) ? fileNameOrSettings : { fileName: fileNameOrSettings };
162
+ const { fileName, test, depth = 10, allowMissing } = settings;
163
+ const fileNames = parseRawFindConfigFileName(fileName);
164
+ if (depth && currentDepth === depth) {
165
+ if (allowMissing)
166
+ return null;
167
+ throw new Error(
168
+ `Failed to retrieve the "${fileName}" file because the maximum depth was reached.`
169
+ );
170
+ }
171
+ const next = (err) => {
172
+ const nextDir = path.dirname(dir);
173
+ if (nextDir !== dir) {
174
+ return findConfig(fileName, nextDir, currentDepth + 1);
175
+ }
176
+ if (allowMissing)
177
+ return null;
178
+ throw err || new Error(`missing config "${fileName}"`);
179
+ };
180
+ const result = await (async () => {
181
+ for (const fileName2 of fileNames) {
182
+ try {
183
+ const _path = path.join(dir, fileName2);
184
+ const code = await fs.promises.readFile(_path, "utf-8");
185
+ const result2 = {
186
+ fileName: fileName2,
187
+ dir,
188
+ path: _path,
189
+ code
190
+ };
191
+ if (!test || test(result2)) {
192
+ return result2;
193
+ }
194
+ } catch (err) {
195
+ if (!isFileNotFoundException(err)) {
196
+ throw err;
197
+ }
198
+ }
199
+ }
200
+ })();
201
+ if (!result) {
202
+ return next();
203
+ }
204
+ return result;
205
+ }
206
+ function _rmrf(path9) {
207
+ return fs.promises.rm(path9, {
208
+ recursive: true,
209
+ force: true
210
+ }).catch((err) => {
211
+ if (isFileNotFoundException(err))
212
+ return;
213
+ throw err;
214
+ });
215
+ }
216
+ async function rmrf(...paths) {
217
+ await Promise.all(paths.map((path9) => _rmrf(path9)));
218
+ }
219
+ function copyDirSync(srcDir, destDir) {
220
+ if (!fs.existsSync(srcDir))
221
+ return;
222
+ fs.mkdirSync(destDir, { recursive: true });
223
+ for (const file of fs.readdirSync(srcDir)) {
224
+ const srcFile = path.resolve(srcDir, file);
225
+ if (srcFile === destDir) {
226
+ continue;
227
+ }
228
+ const destFile = path.resolve(destDir, file);
229
+ const stat = fs.statSync(srcFile);
230
+ if (stat.isDirectory()) {
231
+ copyDirSync(srcFile, destFile);
232
+ } else {
233
+ fs.copyFileSync(srcFile, destFile);
234
+ }
235
+ }
236
+ }
237
+
238
+ // src/utils/project.ts
239
+ import { bundleRequire } from "bundle-require";
240
+
241
+ // src/constants.ts
242
+ var PROJECT_CONFIG_BASENAME = "plugboy.project";
243
+ var WORKSPACE_CONFIG_BASENAME = "plugboy.workspace";
244
+ var PACKAGE_JSON_FILENAME = "package.json";
245
+ var WORKSPACE_SPEC_PREFIX = "workspace:";
246
+ var SEARCH_BUNDLE_EXTENSIONS_MATCH = "(ts|mjs|js|json)";
247
+
248
+ // src/utils/plugin.ts
249
+ async function resolveUserPluginOptions(pluginOptions) {
250
+ if (!pluginOptions)
251
+ return [];
252
+ return resolveListable(pluginOptions);
253
+ }
254
+ function definePlugin(options) {
255
+ return options;
256
+ }
257
+ async function extractProjectPlugins(searchDir) {
258
+ const config = await loadProjectConfig(searchDir);
259
+ return config ? config.plugins : [];
260
+ }
261
+ async function findProjectPlugin(pluginName, searchDir) {
262
+ const plugins = await extractProjectPlugins(searchDir);
263
+ return plugins.find((plugin) => plugin.name === pluginName);
264
+ }
265
+
266
+ // src/utils/project.ts
267
+ function isProjectPackageJson(json) {
268
+ return !!json.private && PROJECT_REQUIRED_FIELDS.every((filed) => !!json[filed]);
269
+ }
270
+ async function resolveUserProjectConfig(userConfig) {
271
+ const {
272
+ workspacesDir = "packages",
273
+ scripts = [],
274
+ peerDependencies = {},
275
+ tsconfig,
276
+ readme = (json) => `# ${json.name}
277
+ `,
278
+ plugins
279
+ } = userConfig;
280
+ return {
281
+ workspacesDir,
282
+ scripts: Array.isArray(scripts) ? scripts : [{ name: "", scripts }],
283
+ peerDependencies,
284
+ tsconfig,
285
+ readme,
286
+ plugins: await resolveUserPluginOptions(plugins)
287
+ };
288
+ }
289
+ function defineProjectConfig(config) {
290
+ return resolveUserProjectConfig(config);
291
+ }
292
+ async function loadProjectConfig(searchDir, depth) {
293
+ const hit = await findConfig(
294
+ {
295
+ fileName: `${PROJECT_CONFIG_BASENAME}.${SEARCH_BUNDLE_EXTENSIONS_MATCH}`,
296
+ depth,
297
+ allowMissing: true
298
+ },
299
+ searchDir
300
+ );
301
+ const userConfig = hit ? (await bundleRequire({
302
+ filepath: hit.path
303
+ })).mod.default : {};
304
+ return resolveUserProjectConfig(await userConfig);
305
+ }
306
+
307
+ // src/utils/workspace.ts
308
+ import { bundleRequire as bundleRequire2 } from "bundle-require";
309
+ function isWorkspacePackageJson(json) {
310
+ return !json.private && WORKSPACE_REQUIRED_FIELDS.every((filed) => !!json[filed]);
311
+ }
312
+ function resolveRawWorkspaceEntry(entry) {
313
+ const { src, css } = typeof entry === "string" ? { src: entry } : entry;
314
+ return {
315
+ src,
316
+ css: css || src.endsWith(".css") || src.endsWith(".scss")
317
+ };
318
+ }
319
+ function resolveRawWorkspaceEntries(entries) {
320
+ if (!entries)
321
+ return {};
322
+ return Object.fromEntries(
323
+ Object.entries(entries).map(([name, raw]) => [
324
+ name,
325
+ resolveRawWorkspaceEntry(raw)
326
+ ])
327
+ );
328
+ }
329
+ async function resolveUserWorkspaceConfig(userConfig) {
330
+ const { ignoreProjectConfig = false, entries, plugins } = userConfig;
331
+ return {
332
+ ...userConfig,
333
+ ignoreProjectConfig,
334
+ entries: resolveRawWorkspaceEntries(entries),
335
+ plugins: await resolveUserPluginOptions(plugins)
336
+ };
337
+ }
338
+ function defineWorkspaceConfig(config) {
339
+ return resolveUserWorkspaceConfig(config);
340
+ }
341
+ async function loadWorkspaceConfig(searchDir, depth) {
342
+ const hit = await findConfig(
343
+ {
344
+ fileName: `${WORKSPACE_CONFIG_BASENAME}.${SEARCH_BUNDLE_EXTENSIONS_MATCH}`,
345
+ depth,
346
+ allowMissing: true
347
+ },
348
+ searchDir
349
+ );
350
+ const userConfig = hit ? (await bundleRequire2({
351
+ filepath: hit.path
352
+ })).mod.default : {};
353
+ return resolveUserWorkspaceConfig(await userConfig);
354
+ }
355
+
356
+ // src/utils/hook.ts
357
+ async function resolveUserHooks(...userHooks) {
358
+ const hooks = createHooksDefaults();
359
+ if (!userHooks)
360
+ return hooks;
361
+ for (const userHook of userHooks) {
362
+ if (!userHook)
363
+ continue;
364
+ for (const [hookName, _hooks] of Object.entries(userHook)) {
365
+ if (hooks) {
366
+ hooks[hookName].push(...await resolveListable(_hooks));
367
+ }
368
+ }
369
+ }
370
+ return hooks;
371
+ }
372
+ function buildHooks(resolvedHooks) {
373
+ const hooks = {};
374
+ Object.entries(resolvedHooks).forEach(([hookName, fns]) => {
375
+ hooks[hookName] = async (...args) => {
376
+ const results = [];
377
+ for (const fn of fns) {
378
+ results.push(await fn(...args));
379
+ }
380
+ return results;
381
+ };
382
+ });
383
+ return hooks;
384
+ }
385
+
386
+ // src/path.ts
387
+ import path2 from "node:path";
388
+ import fs2 from "node:fs";
389
+ var Path = class {
390
+ _value;
391
+ _stats;
392
+ get value() {
393
+ return this._value;
394
+ }
395
+ set value(value) {
396
+ const _value = path2.resolve(value);
397
+ if (_value === this._value)
398
+ return;
399
+ this._value = path2.resolve(value);
400
+ delete this._stats;
401
+ }
402
+ get dirname() {
403
+ return path2.dirname(this.value);
404
+ }
405
+ get basename() {
406
+ return path2.basename(this.value);
407
+ }
408
+ get extname() {
409
+ return path2.extname(this.value);
410
+ }
411
+ get stats() {
412
+ let { _stats } = this;
413
+ if (!_stats) {
414
+ _stats = fs2.statSync(this.value);
415
+ this._stats = _stats;
416
+ }
417
+ return _stats;
418
+ }
419
+ get isDirectory() {
420
+ return this.stats.isDirectory;
421
+ }
422
+ get isFile() {
423
+ return this.stats.isFile;
424
+ }
425
+ constructor(value) {
426
+ this._value = path2.resolve(value);
427
+ }
428
+ toString() {
429
+ return this.value;
430
+ }
431
+ valueOf() {
432
+ return this.value;
433
+ }
434
+ toJSON() {
435
+ return this.value;
436
+ }
437
+ relative(to) {
438
+ return new Path(path2.relative(this.value, to));
439
+ }
440
+ join(...paths) {
441
+ return new Path(path2.join(this.value, ...paths));
442
+ }
443
+ resolve(...paths) {
444
+ return new Path(path2.resolve(this.value, ...paths));
445
+ }
446
+ _join(...paths) {
447
+ const _paths = paths.filter((path9) => !!path9);
448
+ return _paths.length ? path2.join(this.value, ..._paths) : this.value;
449
+ }
450
+ async readdir(...paths) {
451
+ const dir = this._join(...paths);
452
+ const files = await fs2.promises.readdir(dir);
453
+ return files.map((file) => {
454
+ return new Path(path2.join(dir, file));
455
+ });
456
+ }
457
+ readFile(pathAppend, defaults) {
458
+ return new Promise((resolve, reject) => {
459
+ fs2.readFile(this._join(pathAppend), "utf-8", (err, data) => {
460
+ if (err) {
461
+ if (defaults !== void 0 && isFileNotFoundException(err)) {
462
+ return resolve(defaults);
463
+ }
464
+ return reject(err);
465
+ }
466
+ resolve(data);
467
+ });
468
+ });
469
+ }
470
+ async readJSON(pathAppend, defaults) {
471
+ try {
472
+ const file = await this.readFile(pathAppend);
473
+ return JSON.parse(file);
474
+ } catch (err) {
475
+ if (defaults === void 0) {
476
+ throw err;
477
+ }
478
+ return defaults;
479
+ }
480
+ }
481
+ };
482
+
483
+ // src/package.ts
484
+ import fs3 from "node:fs/promises";
485
+ import path3 from "node:path";
486
+ async function getProjectPackageJson(searchDir, allowMissing) {
487
+ const hit = await findConfig(
488
+ {
489
+ fileName: PACKAGE_JSON_FILENAME,
490
+ allowMissing,
491
+ test: (result) => isProjectPackageJson(JSON.parse(result.code))
492
+ },
493
+ searchDir
494
+ );
495
+ if (!hit) {
496
+ if (allowMissing)
497
+ return null;
498
+ throw new Error("missing project package.");
499
+ }
500
+ return {
501
+ dir: new Path(hit.dir),
502
+ json: JSON.parse(hit.code)
503
+ };
504
+ }
505
+ async function getWorkspacePackageJson(searchDir, allowMissing) {
506
+ const hit = await findConfig(
507
+ {
508
+ fileName: PACKAGE_JSON_FILENAME,
509
+ allowMissing,
510
+ test: (result) => isWorkspacePackageJson(JSON.parse(result.code))
511
+ },
512
+ searchDir
513
+ );
514
+ if (!hit) {
515
+ if (allowMissing)
516
+ return null;
517
+ throw new Error("missing workspace package.");
518
+ }
519
+ return {
520
+ dir: new Path(hit.dir),
521
+ json: JSON.parse(hit.code)
522
+ };
523
+ }
524
+ async function findWorkspacePackages(dir) {
525
+ const results = [];
526
+ const searchDir = path3.resolve(dir);
527
+ const dirs = await fs3.readdir(searchDir);
528
+ const pkgs = await Promise.all(
529
+ dirs.map(
530
+ (dirName) => getWorkspacePackageJson(path3.join(searchDir, dirName), true)
531
+ )
532
+ );
533
+ pkgs.forEach((pkg) => {
534
+ pkg && results.push(pkg);
535
+ });
536
+ return results;
537
+ }
538
+
539
+ // src/workspace/builder.ts
540
+ import { build } from "tsup";
541
+ import fs4 from "node:fs/promises";
542
+ import path5 from "node:path";
543
+
544
+ // src/workspace/dts.ts
545
+ import { execa } from "execa";
546
+ import path4 from "node:path";
547
+ async function emitDTS(opts = {}) {
548
+ const { cwd = process.cwd(), outDir = path4.join(cwd, "dist/dts") } = opts;
549
+ await execa(
550
+ "tsc",
551
+ [
552
+ "--declaration true",
553
+ "--skipLibCheck",
554
+ "--noEmit false",
555
+ "--emitDeclarationOnly",
556
+ `--outDir ${outDir}`
557
+ ],
558
+ { cwd, shell: true, stdio: "inherit" }
559
+ );
560
+ }
561
+
562
+ // src/workspace/builder.ts
563
+ import { glob } from "glob";
564
+ var SHEBANG_MATCH_RE = /^(#!.+?)\n/;
565
+ var Builder = class {
566
+ workspace;
567
+ _tsupOptions;
568
+ get entry() {
569
+ return this.workspace.entry;
570
+ }
571
+ get dts() {
572
+ return this.workspace.dts;
573
+ }
574
+ constructor(workspace) {
575
+ this.workspace = workspace;
576
+ }
577
+ async tsupOptions(overrides) {
578
+ let { _tsupOptions } = this;
579
+ if (_tsupOptions)
580
+ return _tsupOptions;
581
+ const { entry, dts } = this;
582
+ const esbuildPlugins = await this.workspace.getESBuildPlugins();
583
+ _tsupOptions = {
584
+ publicDir: true,
585
+ format: ["esm"],
586
+ dts: dts.inline ? false : {
587
+ resolve: ["@fastkit/plugboy"]
588
+ },
589
+ treeshake: true,
590
+ esbuildPlugins,
591
+ entry,
592
+ splitting: true,
593
+ outExtension: ({ format }) => ({
594
+ js: `.mjs`
595
+ }),
596
+ sourcemap: true,
597
+ clean: true,
598
+ ...overrides
599
+ };
600
+ for (const opt of TSUP_SYNC_OPTIONS) {
601
+ _tsupOptions[opt] = this.workspace.config[opt];
602
+ }
603
+ const PLUGBOY_VAR_ENVS = {
604
+ __PLUGBOY_DEV__: "false",
605
+ __PLUGBOY_STUB__: "false"
606
+ };
607
+ const DEFINE_VAR_INJECTS = Object.fromEntries(
608
+ Object.keys(PLUGBOY_VAR_ENVS).map((envName) => [envName, `$$${envName}`])
609
+ );
610
+ _tsupOptions.define = {
611
+ ..._tsupOptions.define,
612
+ ...DEFINE_VAR_INJECTS
613
+ };
614
+ const PLUGBOY_VAR_ENVS_BANNER = [
615
+ ...Object.entries(PLUGBOY_VAR_ENVS).map(
616
+ ([envName, variable]) => `const $$${envName} = /* @PLUGBOY:${envName}:start */${variable}/* @PLUGBOY:${envName}:end */;`
617
+ ),
618
+ `const $$__PLUGBOY_RELATIVE_PATH_FOR_WORKSPACE__ = '@@__PLUGBOY_RELATIVE_PATH_FOR_WORKSPACE__';`
619
+ ].join("\n");
620
+ const ENV_FN_INJECTS = `
621
+ import __plugboy_path from 'node:path';
622
+ import { fileURLToPath as __plugboy_fileURLToPath } from 'node:url';
623
+
624
+ function __plugboyFilename() {
625
+ return __plugboy_fileURLToPath(import.meta.url);
626
+ }
627
+
628
+ function __plugboyDirname() {
629
+ return __plugboy_path.dirname(__plugboyFilename());
630
+ }
631
+
632
+ function __plugboyWorkspaceDir(...paths) {
633
+ return __plugboy_path.join(__plugboy_path.resolve(__plugboyDirname(), $$__PLUGBOY_RELATIVE_PATH_FOR_WORKSPACE__), ...paths);
634
+ }
635
+
636
+ function __plugboySrcDir(...paths) {
637
+ return __plugboy_path.join(__plugboyWorkspaceDir(), 'src', ...paths);
638
+ }
639
+
640
+ function __plugboyPublicDir(...paths) {
641
+ return __plugboy_path.join(__plugboyWorkspaceDir(), 'dist', ...paths);
642
+ }
643
+ `.trim();
644
+ const banner = { ..._tsupOptions.banner };
645
+ banner.js = `${banner.js ? banner.js + "\n\n" : ""}${PLUGBOY_VAR_ENVS_BANNER}
646
+
647
+ ${ENV_FN_INJECTS}`;
648
+ _tsupOptions.banner = banner;
649
+ _tsupOptions.external = _tsupOptions.external || [];
650
+ _tsupOptions.external.push(
651
+ /^(@fastkit\/)?plugboy/,
652
+ ...this.workspace.dependencies
653
+ );
654
+ this._tsupOptions = _tsupOptions;
655
+ return _tsupOptions;
656
+ }
657
+ async _stubLinkJS(from, to) {
658
+ const fromParsed = path5.parse(from);
659
+ const fromDir = fromParsed.dir;
660
+ const toParsed = path5.parse(to);
661
+ const toRelativeDir = path5.relative(fromDir, toParsed.dir);
662
+ const location = path5.join(toRelativeDir, toParsed.base);
663
+ const source = await fs4.readFile(to, "utf-8");
664
+ const shebang = source.match(SHEBANG_MATCH_RE)?.[1];
665
+ const STUB_FN_ERROR = `() => { throw new Error('Path resolution methods cannot be executed in stub mode.') }`;
666
+ const PLUGBOY_ENVS = {
667
+ __PLUGBOY_DEV__: "true",
668
+ __PLUGBOY_STUB__: "true",
669
+ __plugboyWorkspaceDir: STUB_FN_ERROR,
670
+ __plugboySrcDir: STUB_FN_ERROR,
671
+ __plugboyPublicDir: STUB_FN_ERROR
672
+ // __plugboyWorkspaceDir: `(...paths) => path.join('${this.workspace.dir.value}', ...paths)`,
673
+ // __plugboySrcDir: `(...paths) => path.join(__plugboySrcDir(), 'src', ...paths)`,
674
+ // __plugboyPublicDir: `(...paths) => path.join(__plugboySrcDir(), 'dist', ...paths)`,
675
+ };
676
+ const ENV_INJECTS = Object.entries(PLUGBOY_ENVS).map(([envName, variable]) => `globalThis.${envName} = ${variable};`).join("\n");
677
+ const disableChecks = "/* eslint-disable */\n// @ts-nocheck\n";
678
+ const code = `${disableChecks}${ENV_INJECTS}
679
+ export * from '${location}';`;
680
+ const dtsPath = path5.join(fromDir, `${fromParsed.name}.d.ts`);
681
+ const dtsCode = `${disableChecks}export * from '${location.replace(
682
+ /\.ts$/,
683
+ ""
684
+ )}';`;
685
+ await Promise.all([
686
+ fs4.writeFile(from, `${shebang ? shebang + "\n" : ""}${code}`),
687
+ fs4.writeFile(dtsPath, dtsCode)
688
+ ]);
689
+ }
690
+ async _stubLinkCSS(from) {
691
+ const code = `/* noop */`;
692
+ await fs4.writeFile(from, code);
693
+ }
694
+ async copyPublicDir() {
695
+ const publicDir = this.workspace.dir.join("public").value;
696
+ await copyDirSync(publicDir, this.workspace.dirs.dist.value);
697
+ }
698
+ async stub() {
699
+ const links = this.workspace.getStubLinks();
700
+ await this.copyPublicDir();
701
+ await Promise.all(
702
+ links.map((link) => {
703
+ if (link.type === "js") {
704
+ return this._stubLinkJS(link.from, link.to);
705
+ } else if (link.type === "css") {
706
+ return this._stubLinkCSS(link.from);
707
+ }
708
+ })
709
+ );
710
+ }
711
+ normalizeDTSBySettings(dts, settings) {
712
+ const { targets, pkg } = settings;
713
+ const myPackageName = this.workspace.json.name;
714
+ const packageIsOwn = myPackageName === pkg;
715
+ const pkgImports = (() => {
716
+ if (!pkg || packageIsOwn)
717
+ return;
718
+ const importRe = new RegExp(`import {([^\\{\\}]+)} from '${pkg}'`);
719
+ const importMatched = dts.match(importRe);
720
+ const imports = importMatched && importMatched[1];
721
+ if (!imports)
722
+ return;
723
+ return {
724
+ pkg,
725
+ importRe,
726
+ imports
727
+ };
728
+ })();
729
+ const hitTypeNames = [];
730
+ targets.forEach(({ from, typeName }) => {
731
+ const matched = dts.match(from);
732
+ if (matched) {
733
+ hitTypeNames.push(typeName);
734
+ dts = dts.replace(from, typeName);
735
+ }
736
+ });
737
+ if (!hitTypeNames.length)
738
+ return;
739
+ if (pkgImports) {
740
+ const { pkg: pkg2, imports, importRe } = pkgImports;
741
+ const mods = imports.trim().split(",").map((row) => {
742
+ row = row.split(" as ")[0].trim();
743
+ return row;
744
+ });
745
+ const appends = [];
746
+ hitTypeNames.forEach((typeName) => {
747
+ const re = new RegExp(`(^|
748
+ )import { ${typeName} } from '${pkg2}'`);
749
+ if (!re.test(dts) && !mods.includes(typeName)) {
750
+ appends.push(typeName);
751
+ }
752
+ });
753
+ if (appends.length) {
754
+ dts = dts.replace(
755
+ importRe,
756
+ `import { $1, ${appends.join(", ")} } from '${pkg2}'`
757
+ );
758
+ }
759
+ } else if (pkg && !packageIsOwn) {
760
+ const mods = [];
761
+ hitTypeNames.forEach((typeName) => {
762
+ if (!dts.includes(`export declare type ${typeName} = `)) {
763
+ mods.push(typeName);
764
+ }
765
+ });
766
+ if (mods.length) {
767
+ dts = `import { ${mods.join(", ")} } from '${pkg}';
768
+ ${dts}`;
769
+ }
770
+ }
771
+ return dts;
772
+ }
773
+ async normalizeDTSFile(filePath) {
774
+ const dts = await fs4.readFile(filePath, "utf-8");
775
+ const { preserveType } = this.dts;
776
+ let normalized = dts;
777
+ let processed = false;
778
+ for (const settings of preserveType) {
779
+ const _normalized = this.normalizeDTSBySettings(normalized, settings);
780
+ if (_normalized) {
781
+ processed = true;
782
+ normalized = _normalized;
783
+ }
784
+ }
785
+ if (!processed) {
786
+ return;
787
+ }
788
+ await fs4.writeFile(filePath, normalized, "utf-8");
789
+ }
790
+ async normalizeDTSFiles(dtsFiles = this.workspace.dtsFiles) {
791
+ const { preserveType } = this.dts;
792
+ if (!preserveType.length || !dtsFiles.length)
793
+ return;
794
+ await Promise.all(
795
+ dtsFiles.map((filePath) => this.normalizeDTSFile(filePath))
796
+ );
797
+ }
798
+ async emitInlineDTS() {
799
+ const { dir, dirs, exports } = this.workspace;
800
+ const cwd = dir.value;
801
+ const outDir = dirs.dist.join(".dts-generate").value;
802
+ const dtsSrcDir = path5.join(outDir, "src");
803
+ const dtsDest = dirs.dist.join(".dts").value;
804
+ await emitDTS({
805
+ cwd,
806
+ outDir
807
+ });
808
+ await fs4.rename(dtsSrcDir, dtsDest);
809
+ await rmrf(outDir);
810
+ const objectExports = [];
811
+ exports.forEach(({ at }) => {
812
+ typeof at === "object" && objectExports.push(at);
813
+ });
814
+ await Promise.all(
815
+ objectExports.map(async (at) => {
816
+ const typesDir = path5.dirname(at.types);
817
+ const dtsDestDir = path5.dirname(at.dtsDest);
818
+ const relativeDir = path5.relative(typesDir, dtsDestDir);
819
+ const relativePath = path5.join(
820
+ relativeDir,
821
+ path5.basename(at.dtsDest).replace(/\.d\.ts$/, "")
822
+ );
823
+ const code = `export * from './${relativePath}';`;
824
+ await fs4.writeFile(at.types, code, "utf-8");
825
+ })
826
+ );
827
+ const dtsFiles = await glob(path5.join(dtsDest, "**/*.d.ts"));
828
+ await this.normalizeDTSFiles(dtsFiles);
829
+ }
830
+ async build() {
831
+ const _outputFiles = [];
832
+ const options = await this.tsupOptions();
833
+ await build({
834
+ ...options,
835
+ esbuildPlugins: [
836
+ ...options.esbuildPlugins,
837
+ {
838
+ name: "output-collection",
839
+ setup(build2) {
840
+ build2.onEnd((result) => {
841
+ const { outputFiles } = result;
842
+ if (!outputFiles)
843
+ return;
844
+ _outputFiles.push(...outputFiles);
845
+ });
846
+ }
847
+ }
848
+ ],
849
+ onSuccess: async () => {
850
+ const emptyNativeNodeModuleRe = /(^|\n)import 'node:.+?';?/g;
851
+ await Promise.all(
852
+ _outputFiles.map(async ({ path: filePath }) => {
853
+ if (!filePath.endsWith(".mjs"))
854
+ return;
855
+ const code = await fs4.readFile(filePath, "utf-8");
856
+ const replaced = code.replace(emptyNativeNodeModuleRe, "");
857
+ if (code === replaced)
858
+ return;
859
+ await fs4.writeFile(filePath, replaced.trimStart(), "utf-8");
860
+ })
861
+ );
862
+ }
863
+ });
864
+ if (this.dts.inline) {
865
+ await this.emitInlineDTS();
866
+ } else {
867
+ await this.normalizeDTSFiles();
868
+ }
869
+ }
870
+ };
871
+
872
+ // src/project/project.ts
873
+ import fs5 from "node:fs/promises";
874
+ import path6 from "node:path";
875
+ import glob2 from "glob";
876
+ var PlugboyProject = class {
877
+ /** Path instance of the project directory */
878
+ dir;
879
+ /** package.json */
880
+ json;
881
+ /**
882
+ * Project Configuration
883
+ * @see {@link ResolvedProjectConfig}
884
+ */
885
+ config;
886
+ /** Names of all packages on which the project depends */
887
+ dependencies;
888
+ /** Directory names of all workspaces owned by the project */
889
+ resolvedWorkspaces;
890
+ /**
891
+ * Name of the project's package.json
892
+ */
893
+ get name() {
894
+ return this.json.name;
895
+ }
896
+ /**
897
+ * Plug-in List
898
+ * @see {@link ResolvedProjectConfig.plugins}
899
+ */
900
+ get plugins() {
901
+ return this.config.plugins;
902
+ }
903
+ /**
904
+ * List of all user hook settings
905
+ * @see {@link UserHooks}
906
+ */
907
+ get hooks() {
908
+ const { hooks: _hooks, plugins } = this.config;
909
+ const pluginHooks = plugins.map((plugin) => plugin.hooks);
910
+ return [_hooks, ...pluginHooks].filter((hook) => !!hook);
911
+ }
912
+ constructor(ctx) {
913
+ const { dir, json, config, resolvedWorkspaces } = ctx;
914
+ this.dir = dir;
915
+ this.json = json;
916
+ this.config = config;
917
+ const allDeps = {
918
+ ...json.dependencies,
919
+ ...json.devDependencies
920
+ };
921
+ this.dependencies = Object.keys(allDeps);
922
+ this.resolvedWorkspaces = resolvedWorkspaces;
923
+ }
924
+ };
925
+ async function getProject(searchDir, allowMissing, skipLoadConfig) {
926
+ const hit = await getProjectPackageJson(searchDir, allowMissing);
927
+ if (!hit) {
928
+ return null;
929
+ }
930
+ const { dir, json } = hit;
931
+ const resolvedWorkspaces = [];
932
+ const { workspaces = [] } = json;
933
+ const workspacesPattern = workspaces.map(
934
+ (workspace) => dir.join(workspace, PACKAGE_JSON_FILENAME).value
935
+ );
936
+ const workspaceHits = await glob2(workspacesPattern);
937
+ for (const hit2 of workspaceHits) {
938
+ const json2 = JSON.parse(await fs5.readFile(hit2, "utf-8"));
939
+ if (!isWorkspacePackageJson(json2)) {
940
+ continue;
941
+ }
942
+ resolvedWorkspaces.push(path6.dirname(hit2));
943
+ }
944
+ resolvedWorkspaces.sort((a, b) => {
945
+ if (a < b)
946
+ return -1;
947
+ if (a > b)
948
+ return 1;
949
+ return 0;
950
+ });
951
+ const config = skipLoadConfig ? await resolveUserProjectConfig({}) : await loadProjectConfig(dir.value, 0);
952
+ const ctx = {
953
+ dir,
954
+ json,
955
+ config,
956
+ resolvedWorkspaces
957
+ };
958
+ return new PlugboyProject(ctx);
959
+ }
960
+
961
+ // src/workspace/workspace.ts
962
+ import sortPackageJson from "sort-package-json";
963
+ import fs6 from "node:fs/promises";
964
+ import path7 from "node:path";
965
+ function extractWorkspaceObjectExport(at) {
966
+ if (typeof at === "string")
967
+ return at;
968
+ const { types, import: _import } = at;
969
+ return {
970
+ types,
971
+ import: _import
972
+ };
973
+ }
974
+ var WORKSPACE_PACKAGE_SYNC_FIELDS = [
975
+ "repository",
976
+ "author",
977
+ "publishConfig",
978
+ "license"
979
+ ];
980
+ function syncWorkspacePackageFields(projectJSON, workspaceJSON) {
981
+ for (const field of WORKSPACE_PACKAGE_SYNC_FIELDS) {
982
+ const value = projectJSON[field];
983
+ if (value && !workspaceJSON[field]) {
984
+ workspaceJSON[field] = value;
985
+ }
986
+ }
987
+ }
988
+ var BUILD_TARGET_SRC_MATCH_RE = /\.(tsx?|s?css)$/;
989
+ var PlugboyWorkspace = class {
990
+ name;
991
+ dir;
992
+ config;
993
+ project;
994
+ dirs;
995
+ dependencies;
996
+ projectDependencies;
997
+ meta;
998
+ entry;
999
+ exports;
1000
+ builder;
1001
+ plugins;
1002
+ hooks;
1003
+ dtsFiles = [];
1004
+ dts;
1005
+ _json;
1006
+ get json() {
1007
+ return this._json;
1008
+ }
1009
+ constructor(ctx) {
1010
+ const {
1011
+ dir,
1012
+ json,
1013
+ config,
1014
+ project,
1015
+ dirs,
1016
+ dependencies,
1017
+ projectDependencies,
1018
+ meta,
1019
+ plugins,
1020
+ hooks,
1021
+ dts
1022
+ } = ctx;
1023
+ this.name = dir.basename;
1024
+ this.dir = dir;
1025
+ this._json = json;
1026
+ this.project = project;
1027
+ this.dirs = dirs;
1028
+ this.dependencies = dependencies;
1029
+ this.projectDependencies = projectDependencies;
1030
+ this.meta = meta;
1031
+ this.config = config;
1032
+ this.plugins = plugins;
1033
+ this.hooks = hooks;
1034
+ this.dts = dts;
1035
+ const entry = {};
1036
+ const exports = [
1037
+ {
1038
+ id: `./${PACKAGE_JSON_FILENAME}`,
1039
+ at: `./${PACKAGE_JSON_FILENAME}`
1040
+ }
1041
+ ];
1042
+ Object.entries(config.entries).forEach(([id, { src, css }]) => {
1043
+ if (!BUILD_TARGET_SRC_MATCH_RE.test(src))
1044
+ return;
1045
+ const isMainEntry = id === ".";
1046
+ const normalizedId = isMainEntry ? this.name : id;
1047
+ const exportId = id.startsWith(".") ? id : `./${id}`;
1048
+ const srcIsCSS = src.endsWith(".css") || src.endsWith(".scss");
1049
+ const ext = srcIsCSS ? "css" : "mjs";
1050
+ const dest = `./dist/${normalizedId}.${ext}`;
1051
+ const destFullPath = dir.join(dest).value;
1052
+ entry[normalizedId] = src;
1053
+ if (css) {
1054
+ const cssDest = `./dist/${normalizedId}.css`;
1055
+ exports.push({
1056
+ id: `./${normalizedId}.css`,
1057
+ at: cssDest,
1058
+ stubLink: {
1059
+ type: "css",
1060
+ from: cssDest
1061
+ }
1062
+ });
1063
+ if (srcIsCSS)
1064
+ return;
1065
+ }
1066
+ const types = `./dist/${normalizedId}.d.ts`;
1067
+ const dtsDest = `./dist/${src.replace(/^\.\/src/, ".dts").replace(/\.ts$/, ".d.ts")}`;
1068
+ this.dtsFiles.push(dir.join(types).value);
1069
+ exports.push({
1070
+ id: exportId,
1071
+ at: {
1072
+ src,
1073
+ types,
1074
+ dtsDest,
1075
+ import: {
1076
+ default: dest
1077
+ }
1078
+ },
1079
+ stubLink: {
1080
+ from: destFullPath,
1081
+ to: dir.join(src).value,
1082
+ type: "js"
1083
+ }
1084
+ });
1085
+ });
1086
+ this.entry = entry;
1087
+ this.exports = exports;
1088
+ this.builder = new Builder(this);
1089
+ }
1090
+ clean(withDepsAndCache) {
1091
+ const { dir, dirs } = this;
1092
+ const paths = [dirs.dist.value];
1093
+ if (withDepsAndCache) {
1094
+ paths.push(dir.join("node_modules").value, dir.join(".turbo").value);
1095
+ }
1096
+ return rmrf(...paths);
1097
+ }
1098
+ async preparePackageJSON() {
1099
+ const { exports, json, project } = this;
1100
+ const _exports = {};
1101
+ const typesVersions = {};
1102
+ let main;
1103
+ let mainTypes;
1104
+ exports.forEach(({ id, at }) => {
1105
+ const _at = extractWorkspaceObjectExport(at);
1106
+ _exports[id] = _at;
1107
+ if (typeof _at !== "object")
1108
+ return;
1109
+ const isMainExport = id === ".";
1110
+ const trimedId = isMainExport ? id : id.replace(/^\.\//, "");
1111
+ typesVersions[trimedId] = [_at.types];
1112
+ if (isMainExport) {
1113
+ main = _at.import.default;
1114
+ mainTypes = _at.types;
1115
+ }
1116
+ });
1117
+ _exports["./*"] = "./dist/*";
1118
+ const cloned = JSON.parse(JSON.stringify(json));
1119
+ cloned.exports = _exports;
1120
+ cloned.typesVersions = {
1121
+ "*": typesVersions
1122
+ };
1123
+ if (main)
1124
+ cloned.main = main;
1125
+ if (mainTypes)
1126
+ cloned.types = mainTypes;
1127
+ const projectPeerDependencies = project?.config.peerDependencies;
1128
+ ["dependencies", "devDependencies", "peerDependencies"].forEach(
1129
+ (prop) => {
1130
+ const deps = cloned[prop];
1131
+ if (!deps)
1132
+ return;
1133
+ Object.keys(deps).forEach((dep) => {
1134
+ const version = deps[dep];
1135
+ if (version.startsWith("workspace:")) {
1136
+ deps[dep] = "workspace:*";
1137
+ } else if (projectPeerDependencies && projectPeerDependencies[dep]) {
1138
+ deps[dep] = projectPeerDependencies[dep];
1139
+ }
1140
+ });
1141
+ }
1142
+ );
1143
+ cloned.files = cloned.files || [];
1144
+ if (!cloned.files.some((file) => /(\.\/)?dist\/?/.test(file))) {
1145
+ cloned.files.unshift("dist");
1146
+ }
1147
+ if (project) {
1148
+ syncWorkspacePackageFields(project.json, cloned);
1149
+ }
1150
+ cloned.type = cloned.type || "module";
1151
+ await this.hooks.preparePackageJSON(json, this);
1152
+ const sorted = sortPackageJson(cloned);
1153
+ const fromStr = JSON.stringify(cloned, null, 2);
1154
+ const toStr = JSON.stringify(sorted, null, 2);
1155
+ if (fromStr !== toStr || process) {
1156
+ await fs6.writeFile(this.dir.join(PACKAGE_JSON_FILENAME).value, toStr);
1157
+ this._json = sorted;
1158
+ }
1159
+ return sorted;
1160
+ }
1161
+ getStubLinks() {
1162
+ const links = [];
1163
+ this.exports.forEach(({ stubLink }) => {
1164
+ stubLink && links.push(stubLink);
1165
+ });
1166
+ return links;
1167
+ }
1168
+ async stub() {
1169
+ await this.clean();
1170
+ await fs6.mkdir(this.dirs.dist.value);
1171
+ return this.builder.stub();
1172
+ }
1173
+ async getESBuildPlugins() {
1174
+ const results = [];
1175
+ results.push({
1176
+ name: "plugboy-workspace-env",
1177
+ setup: (build2) => {
1178
+ const isJS = /\.m?js$/;
1179
+ const RELATIVE_PATH_FOR_WORKSPACE = "@@__PLUGBOY_RELATIVE_PATH_FOR_WORKSPACE__";
1180
+ const encoder = new TextEncoder();
1181
+ build2.onEnd(({ outputFiles, errors, warnings }) => {
1182
+ const result = { errors, warnings };
1183
+ if (!outputFiles || !outputFiles.length || errors.length)
1184
+ return result;
1185
+ for (const file of outputFiles) {
1186
+ const { path: filePath, text } = file;
1187
+ if (!isJS.test(filePath) || !text.includes(RELATIVE_PATH_FOR_WORKSPACE)) {
1188
+ continue;
1189
+ }
1190
+ const relativePath = path7.relative(
1191
+ path7.dirname(filePath),
1192
+ this.dir.value
1193
+ );
1194
+ const content = text.replace(
1195
+ RELATIVE_PATH_FOR_WORKSPACE,
1196
+ relativePath
1197
+ );
1198
+ file.contents = encoder.encode(content);
1199
+ }
1200
+ return result;
1201
+ });
1202
+ }
1203
+ });
1204
+ const { plugins } = this;
1205
+ for (const plugin of plugins) {
1206
+ const { esbuildPlugins } = plugin;
1207
+ if (!esbuildPlugins)
1208
+ continue;
1209
+ for (const chunk of esbuildPlugins) {
1210
+ const esbuildPlugin = typeof chunk === "function" ? await chunk(this) : await chunk;
1211
+ if (esbuildPlugin) {
1212
+ results.push(esbuildPlugin);
1213
+ }
1214
+ }
1215
+ }
1216
+ return results;
1217
+ }
1218
+ async build() {
1219
+ await this.clean();
1220
+ return this.builder.build();
1221
+ }
1222
+ };
1223
+ async function getWorkspace(searchDir, allowMissing) {
1224
+ const hit = await getWorkspacePackageJson(searchDir, allowMissing);
1225
+ if (!hit) {
1226
+ return null;
1227
+ }
1228
+ const { dir, json } = hit;
1229
+ const config = await loadWorkspaceConfig(dir.value, 0);
1230
+ const project = await getProject(dir.value, true, config.ignoreProjectConfig);
1231
+ const dirs = {
1232
+ src: dir.join("src"),
1233
+ dist: dir.join("dist")
1234
+ };
1235
+ const { dependencies, peerDependencies, optionalDependencies } = json;
1236
+ const allDeps = {
1237
+ ...dependencies,
1238
+ ...peerDependencies,
1239
+ ...optionalDependencies
1240
+ };
1241
+ const _dependencies = Object.keys(allDeps);
1242
+ const projectDependencies = Object.entries(allDeps).filter(([dep, spec]) => spec.startsWith(WORKSPACE_SPEC_PREFIX)).map(([dep]) => dep);
1243
+ const meta = {};
1244
+ const packagePlugins = project?.plugins || [];
1245
+ const packageHooks = project?.hooks || [];
1246
+ const plugins = [...packagePlugins, ...config.plugins];
1247
+ const _hooks = [...packageHooks];
1248
+ if (config.hooks) {
1249
+ _hooks.push(config.hooks);
1250
+ }
1251
+ const resolvedHooks = await resolveUserHooks(..._hooks);
1252
+ const hooks = buildHooks(resolvedHooks);
1253
+ const dts = mergeDTSSettingsList(project?.config.dts, config.dts);
1254
+ const ctx = {
1255
+ dir,
1256
+ json,
1257
+ config,
1258
+ project,
1259
+ dirs,
1260
+ dependencies: _dependencies,
1261
+ projectDependencies,
1262
+ meta,
1263
+ plugins,
1264
+ hooks,
1265
+ dts
1266
+ };
1267
+ await hooks.setupWorkspace(ctx);
1268
+ const workspace = new PlugboyWorkspace(ctx);
1269
+ await hooks.createWorkspace(workspace);
1270
+ return workspace;
1271
+ }
1272
+
1273
+ // src/workspace/generate.ts
1274
+ import path8 from "node:path";
1275
+ import fs7 from "node:fs/promises";
1276
+ import sortPackageJson2 from "sort-package-json";
1277
+ import inquirer from "inquirer";
1278
+ async function generateWorkspace(workspaceName, cwd = process.cwd()) {
1279
+ const project = await getProject(cwd);
1280
+ const { config } = project;
1281
+ while (!workspaceName) {
1282
+ const { value } = await inquirer.prompt({
1283
+ type: "input",
1284
+ name: "value",
1285
+ message: "Enter a workspace name"
1286
+ });
1287
+ if (value) {
1288
+ workspaceName = value;
1289
+ }
1290
+ }
1291
+ const { description } = await inquirer.prompt({
1292
+ type: "input",
1293
+ name: "description",
1294
+ default: workspaceName,
1295
+ message: "Please enter a description of your package"
1296
+ });
1297
+ let version;
1298
+ while (!version) {
1299
+ const { value } = await inquirer.prompt({
1300
+ type: "input",
1301
+ name: "value",
1302
+ default: "0.0.0",
1303
+ message: "Please enter the initial version"
1304
+ });
1305
+ if (value) {
1306
+ version = value;
1307
+ }
1308
+ }
1309
+ const { rawKeywords } = await inquirer.prompt({
1310
+ type: "input",
1311
+ name: "rawKeywords",
1312
+ message: "Enter as many keywords, if any, as needed, separated by commas"
1313
+ });
1314
+ const keywords = rawKeywords.split(",").map((word) => word.trim()).filter((word) => word.length);
1315
+ const scriptsTemplates = config.scripts;
1316
+ let scriptsTemplate;
1317
+ if (scriptsTemplates && scriptsTemplates.length) {
1318
+ const { value } = await inquirer.prompt({
1319
+ type: "rawlist",
1320
+ message: "Select a scripts template",
1321
+ name: "value",
1322
+ choices: [
1323
+ { name: "None", value: "" },
1324
+ ...scriptsTemplates.map((tpl) => ({
1325
+ name: tpl.name,
1326
+ value: tpl.name
1327
+ }))
1328
+ ]
1329
+ });
1330
+ scriptsTemplate = scriptsTemplates.find((tpl) => tpl.name === value);
1331
+ }
1332
+ const scripts = scriptsTemplate?.scripts || {};
1333
+ const peerDependencies = await (async () => {
1334
+ const { deps } = await inquirer.prompt({
1335
+ type: "checkbox",
1336
+ message: "Select the dependent packages, if any, to be used in the package",
1337
+ name: "deps",
1338
+ choices: Object.keys(config.peerDependencies).map((dep) => {
1339
+ return {
1340
+ name: dep,
1341
+ value: dep
1342
+ };
1343
+ })
1344
+ });
1345
+ if (!deps.length)
1346
+ return;
1347
+ return Object.fromEntries(
1348
+ deps.map((dep) => [dep, config.peerDependencies[dep]])
1349
+ );
1350
+ })();
1351
+ const dependencies = await (async () => {
1352
+ const { deps } = await inquirer.prompt({
1353
+ type: "checkbox",
1354
+ message: "Select the internal package to be used, if any.",
1355
+ name: "deps",
1356
+ choices: project.resolvedWorkspaces.map((workspace) => {
1357
+ const name = path8.basename(workspace);
1358
+ return {
1359
+ name,
1360
+ value: name
1361
+ };
1362
+ })
1363
+ });
1364
+ if (!deps.length)
1365
+ return;
1366
+ return Object.fromEntries(
1367
+ deps.map((dep) => [`@${project.name}/${dep}`, "workspace:*"])
1368
+ );
1369
+ })();
1370
+ const { withGenSource } = await inquirer.prompt({
1371
+ type: "confirm",
1372
+ name: "withGenSource",
1373
+ message: "Generate source files?",
1374
+ default: true
1375
+ });
1376
+ const _json = {
1377
+ name: `@${project.name}/${workspaceName}`,
1378
+ type: "module",
1379
+ description,
1380
+ version,
1381
+ keywords,
1382
+ scripts,
1383
+ peerDependencies,
1384
+ dependencies
1385
+ };
1386
+ syncWorkspacePackageFields(project.json, _json);
1387
+ const json = sortPackageJson2(_json);
1388
+ const workspaceDir = path8.join(config.workspacesDir, workspaceName);
1389
+ console.log("");
1390
+ console.log("========================================");
1391
+ console.log(`Directory: ${workspaceDir}`);
1392
+ console.log(`Generate source: ${withGenSource ? "Yes" : "No"}`);
1393
+ console.log(json);
1394
+ console.log("========================================");
1395
+ const { confirmation } = await inquirer.prompt({
1396
+ type: "confirm",
1397
+ name: "confirmation",
1398
+ message: "Is this OK?",
1399
+ default: true
1400
+ });
1401
+ if (!confirmation) {
1402
+ console.log("Skiped.");
1403
+ process.exit(1);
1404
+ }
1405
+ await fs7.mkdir(workspaceDir);
1406
+ await fs7.writeFile(
1407
+ path8.join(workspaceDir, "package.json"),
1408
+ JSON.stringify(json, null, 2)
1409
+ );
1410
+ await fs7.writeFile(path8.join(workspaceDir, "README.md"), config.readme(json));
1411
+ if (withGenSource) {
1412
+ const srcDir = path8.join(workspaceDir, "src");
1413
+ await fs7.mkdir(srcDir);
1414
+ const indexCode = `export * from './${workspaceName}';
1415
+ `;
1416
+ const modCode = `export const PACKAGE_NAME = './${workspaceName}';
1417
+ `;
1418
+ await fs7.writeFile(path8.join(srcDir, "index.ts"), indexCode);
1419
+ await fs7.writeFile(path8.join(srcDir, `${workspaceName}.ts`), modCode);
1420
+ const { tsconfig } = config;
1421
+ if (tsconfig) {
1422
+ await fs7.writeFile(
1423
+ path8.join(workspaceDir, "tsconfig.json"),
1424
+ JSON.stringify(tsconfig, null, 2)
1425
+ );
1426
+ }
1427
+ const configFileCode = `
1428
+ import { defineWorkspaceConfig } from '@fastkit/plugboy';
1429
+
1430
+ export default defineWorkspaceConfig({
1431
+ entries: {
1432
+ '.': './src/index.ts',
1433
+ },
1434
+ });
1435
+ `.trim() + "\n";
1436
+ await fs7.writeFile(
1437
+ path8.join(workspaceDir, `${WORKSPACE_CONFIG_BASENAME}.ts`),
1438
+ configFileCode
1439
+ );
1440
+ const workspace = await getWorkspace(workspaceDir);
1441
+ await workspace.preparePackageJSON();
1442
+ }
1443
+ }
1444
+
1445
+ export {
1446
+ createHooksDefaults,
1447
+ normalizeDTSPreserveTypeTarget,
1448
+ normalizeDTSPreserveTypeSettings,
1449
+ normalizeDTSSettings,
1450
+ mergeDTSSettingsList,
1451
+ WORKSPACE_REQUIRED_FIELDS,
1452
+ TSUP_SYNC_OPTIONS,
1453
+ PROJECT_REQUIRED_FIELDS,
1454
+ isPromise,
1455
+ resolveListable,
1456
+ getFilename,
1457
+ getDirname,
1458
+ isFileNotFoundException,
1459
+ pathExists,
1460
+ findFile,
1461
+ findConfig,
1462
+ rmrf,
1463
+ copyDirSync,
1464
+ isProjectPackageJson,
1465
+ resolveUserProjectConfig,
1466
+ defineProjectConfig,
1467
+ loadProjectConfig,
1468
+ resolveUserPluginOptions,
1469
+ definePlugin,
1470
+ extractProjectPlugins,
1471
+ findProjectPlugin,
1472
+ isWorkspacePackageJson,
1473
+ resolveRawWorkspaceEntry,
1474
+ resolveRawWorkspaceEntries,
1475
+ resolveUserWorkspaceConfig,
1476
+ defineWorkspaceConfig,
1477
+ loadWorkspaceConfig,
1478
+ resolveUserHooks,
1479
+ buildHooks,
1480
+ Path,
1481
+ getProjectPackageJson,
1482
+ getWorkspacePackageJson,
1483
+ findWorkspacePackages,
1484
+ Builder,
1485
+ PlugboyProject,
1486
+ getProject,
1487
+ WORKSPACE_PACKAGE_SYNC_FIELDS,
1488
+ syncWorkspacePackageFields,
1489
+ PlugboyWorkspace,
1490
+ getWorkspace,
1491
+ generateWorkspace
1492
+ };
1493
+ //# sourceMappingURL=chunk-QSOC5WYP.mjs.map