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