@b9g/libuild 0.1.3 → 0.1.5

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.
@@ -1,713 +0,0 @@
1
- import {
2
- umdPlugin
3
- } from "./chunk-EVLPGECD.js";
4
-
5
- // src/libuild.ts
6
- import * as FS from "fs/promises";
7
- import * as Path from "path";
8
- import { spawn } from "child_process";
9
- import * as ESBuild from "esbuild";
10
- import * as TS from "typescript";
11
- function isValidEntrypoint(filename) {
12
- if (!filename.endsWith(".ts") && !filename.endsWith(".js"))
13
- return false;
14
- if (filename.endsWith(".d.ts"))
15
- return false;
16
- if (filename.startsWith("_"))
17
- return false;
18
- if (filename.startsWith("."))
19
- return false;
20
- return true;
21
- }
22
- async function findEntryPoints(srcDir) {
23
- const files = await FS.readdir(srcDir);
24
- return files.filter(isValidEntrypoint).map((file) => Path.basename(file, Path.extname(file))).sort();
25
- }
26
- async function detectMainEntry(pkg, entries) {
27
- if (pkg.exports && pkg.exports["."]) {
28
- const dotExport = pkg.exports["."];
29
- let importPath;
30
- if (typeof dotExport === "string") {
31
- importPath = dotExport;
32
- } else if (typeof dotExport === "object" && dotExport.import) {
33
- importPath = dotExport.import;
34
- }
35
- if (importPath) {
36
- const match = importPath.match(/\.\/src\/([^.]+)/);
37
- if (match && entries.includes(match[1])) {
38
- return match[1];
39
- }
40
- }
41
- }
42
- if (pkg.main && typeof pkg.main === "string") {
43
- const mainBase = Path.basename(pkg.main, Path.extname(pkg.main));
44
- if (entries.includes(mainBase)) {
45
- return mainBase;
46
- }
47
- }
48
- if (entries.includes("index")) {
49
- return "index";
50
- }
51
- if (entries.length === 1) {
52
- return entries[0];
53
- }
54
- const pkgNameParts = pkg.name.split("/");
55
- const pkgName = pkgNameParts[pkgNameParts.length - 1];
56
- if (!pkgName) {
57
- throw new Error(`Invalid package name: ${pkg.name}`);
58
- }
59
- if (entries.includes(pkgName)) {
60
- return pkgName;
61
- }
62
- return entries[0];
63
- }
64
- function checkIfExportIsStale(exportKey, exportValue, entries) {
65
- if (exportKey === "./package.json" || typeof exportValue === "string" && (exportValue === "./package.json" || exportValue.endsWith("/package.json"))) {
66
- return false;
67
- }
68
- let entryName;
69
- let hasInvalidPath = false;
70
- if (typeof exportValue === "string") {
71
- if (exportValue.match(/\.\/src\/.*\/.*\.(ts|js)$/)) {
72
- hasInvalidPath = true;
73
- } else {
74
- const match = exportValue.match(/\.\/src\/([^/]+)\.(ts|js)$/);
75
- if (match) {
76
- const filename = match[1] + "." + match[2];
77
- if (!isValidEntrypoint(filename)) {
78
- hasInvalidPath = true;
79
- } else {
80
- entryName = match[1];
81
- }
82
- }
83
- }
84
- } else if (typeof exportValue === "object" && exportValue !== null) {
85
- const importPath = exportValue.import || exportValue.require;
86
- if (typeof importPath === "string") {
87
- if (importPath.match(/\.\/src\/.*\/.*\.(ts|js|cjs)$/)) {
88
- hasInvalidPath = true;
89
- } else {
90
- const match = importPath.match(/\.\/src\/([^/]+)\.(ts|js|cjs)$/);
91
- if (match) {
92
- const filename = match[1] + "." + match[2].replace("cjs", "js");
93
- if (!isValidEntrypoint(filename)) {
94
- hasInvalidPath = true;
95
- } else {
96
- entryName = match[1];
97
- }
98
- }
99
- }
100
- }
101
- }
102
- if (!entryName && !hasInvalidPath && exportKey.startsWith("./") && exportKey !== ".") {
103
- const keyName = exportKey.slice(2).replace(/\.js$/, "");
104
- if (keyName && !keyName.includes("/")) {
105
- entryName = keyName;
106
- }
107
- }
108
- if (hasInvalidPath) {
109
- return false;
110
- }
111
- return entryName ? !entries.includes(entryName) : false;
112
- }
113
- function generateExports(entries, mainEntry, options, existingExports = {}) {
114
- const exports = {};
115
- const staleExports = [];
116
- function createExportEntry(entry) {
117
- const exportEntry = {
118
- types: `./src/${entry}.d.ts`,
119
- import: `./src/${entry}.js`
120
- };
121
- if (options.formats.cjs) {
122
- exportEntry.require = `./src/${entry}.cjs`;
123
- }
124
- return exportEntry;
125
- }
126
- function expandExistingExport(existing, entryFromPath) {
127
- var _a;
128
- if (typeof existing === "string") {
129
- if (existing === "./package.json" || existing.endsWith("/package.json")) {
130
- return existing;
131
- }
132
- const match = existing.match(/\.\/src\/([^/]+\.(?:ts|js))$/);
133
- if (match) {
134
- const filename = match[1];
135
- if (!isValidEntrypoint(filename)) {
136
- throw new Error(`Export path '${existing}' references '${filename}' which is not a valid entrypoint. Valid entrypoints cannot start with '_' or '.' and must be .ts/.js files in src/.`);
137
- }
138
- const entry = Path.basename(filename, Path.extname(filename));
139
- return options.formats.cjs ? {
140
- types: `./src/${entry}.d.ts`,
141
- import: existing,
142
- require: `./src/${entry}.cjs`
143
- } : {
144
- types: `./src/${entry}.d.ts`,
145
- import: existing
146
- };
147
- }
148
- if (entryFromPath) {
149
- return options.formats.cjs ? {
150
- types: `./src/${entryFromPath}.d.ts`,
151
- import: existing,
152
- require: `./src/${entryFromPath}.cjs`
153
- } : {
154
- types: `./src/${entryFromPath}.d.ts`,
155
- import: existing
156
- };
157
- }
158
- throw new Error(`Export path '${existing}' must point to a valid entrypoint in src/ (e.g., './src/utils.js'). Nested directories and internal files (starting with '_' or '.') are not allowed.`);
159
- } else if (typeof existing === "object" && existing !== null) {
160
- if (options.formats.cjs && !existing.require && existing.import) {
161
- const match = (_a = existing.import) == null ? void 0 : _a.match(/\.\/src\/([^/]+\.(?:ts|js))$/);
162
- if (match) {
163
- const filename = match[1];
164
- if (!isValidEntrypoint(filename)) {
165
- throw new Error(`Export import path '${existing.import}' references '${filename}' which is not a valid entrypoint. Valid entrypoints cannot start with '_' or '.' and must be .ts/.js files in src/.`);
166
- }
167
- const entry = Path.basename(filename, Path.extname(filename));
168
- return {
169
- ...existing,
170
- types: existing.types || `./src/${entry}.d.ts`,
171
- require: `./src/${entry}.cjs`
172
- };
173
- }
174
- if (entryFromPath) {
175
- return {
176
- ...existing,
177
- types: existing.types || `./src/${entryFromPath}.d.ts`,
178
- require: `./src/${entryFromPath}.cjs`
179
- };
180
- }
181
- throw new Error(`Export import path '${existing.import}' must point to a valid entrypoint in src/ (e.g., './src/utils.js'). Nested directories and internal files are not allowed.`);
182
- }
183
- return {
184
- types: existing.types || `./src/${entryFromPath}.d.ts`,
185
- ...existing
186
- };
187
- }
188
- return existing;
189
- }
190
- for (const [key, value] of Object.entries(existingExports)) {
191
- const isStale = checkIfExportIsStale(key, value, entries);
192
- if (isStale) {
193
- staleExports.push(key);
194
- } else {
195
- exports[key] = expandExistingExport(value);
196
- }
197
- }
198
- if (!exports["."]) {
199
- exports["."] = createExportEntry(mainEntry);
200
- } else {
201
- exports["."] = expandExistingExport(exports["."], mainEntry);
202
- }
203
- for (const entry of entries) {
204
- if (entry === "umd")
205
- continue;
206
- const key = `./${entry}`;
207
- if (!exports[key]) {
208
- exports[key] = createExportEntry(entry);
209
- } else {
210
- exports[key] = expandExistingExport(exports[key], entry);
211
- }
212
- if (!exports[`${key}.js`]) {
213
- exports[`${key}.js`] = exports[key];
214
- }
215
- if (entry === "jsx-runtime") {
216
- if (!exports["./jsx-dev-runtime"]) {
217
- exports["./jsx-dev-runtime"] = exports[key];
218
- }
219
- if (!exports["./jsx-dev-runtime.js"]) {
220
- exports["./jsx-dev-runtime.js"] = exports[key];
221
- }
222
- }
223
- }
224
- if (options.formats.umd && !exports["./umd"]) {
225
- exports["./umd"] = {
226
- require: "./src/umd.js"
227
- };
228
- if (!exports["./umd.js"]) {
229
- exports["./umd.js"] = exports["./umd"];
230
- }
231
- }
232
- if (!exports["./package.json"]) {
233
- exports["./package.json"] = "./package.json";
234
- }
235
- return { exports, staleExports };
236
- }
237
- function transformSrcToDist(value) {
238
- if (typeof value === "string") {
239
- if (value.startsWith("src/") || value === "src") {
240
- return "./" + value;
241
- }
242
- return value;
243
- } else if (Array.isArray(value)) {
244
- return value.map(transformSrcToDist);
245
- } else if (typeof value === "object" && value !== null) {
246
- const transformed = {};
247
- for (const [key, val] of Object.entries(value)) {
248
- transformed[key] = transformSrcToDist(val);
249
- }
250
- return transformed;
251
- }
252
- return value;
253
- }
254
- function fixExportsForDist(obj) {
255
- if (typeof obj === "string") {
256
- if (obj.includes("/dist/") && obj.includes("/src/")) {
257
- const match = obj.match(/.*\/src\/(.*)$/);
258
- if (match) {
259
- return `./src/${match[1]}`;
260
- }
261
- }
262
- if (obj.startsWith("./dist/src/")) {
263
- return obj.replace("./dist/src/", "./src/");
264
- }
265
- if (obj.includes("/dist/") && obj.endsWith("/package.json")) {
266
- return "./package.json";
267
- }
268
- return obj;
269
- } else if (Array.isArray(obj)) {
270
- return obj.map(fixExportsForDist);
271
- } else if (typeof obj === "object" && obj !== null) {
272
- const fixed = {};
273
- for (const [key, val] of Object.entries(obj)) {
274
- if (key === "files" && Array.isArray(val)) {
275
- fixed[key] = val.filter((file) => file !== "dist/" && file !== "dist").concat(val.includes("dist/") || val.includes("dist") ? ["src/"] : []);
276
- } else {
277
- fixed[key] = fixExportsForDist(val);
278
- }
279
- }
280
- return fixed;
281
- }
282
- return obj;
283
- }
284
- function cleanPackageJSON(pkg, mainEntry, options) {
285
- const cleaned = {
286
- name: pkg.name,
287
- version: pkg.version
288
- };
289
- const fieldsToKeep = [
290
- "description",
291
- "keywords",
292
- "author",
293
- "contributors",
294
- "maintainers",
295
- "license",
296
- "repository",
297
- "bugs",
298
- "homepage",
299
- "funding",
300
- "bin",
301
- "scripts",
302
- "dependencies",
303
- "peerDependencies",
304
- "optionalDependencies",
305
- "bundledDependencies",
306
- "engines",
307
- "cpu",
308
- "os",
309
- "type",
310
- "types",
311
- "files",
312
- "sideEffects",
313
- "browserslist"
314
- ];
315
- const pathFields = ["files", "types", "scripts"];
316
- for (const field of fieldsToKeep) {
317
- if (pkg[field] !== void 0) {
318
- if (field === "scripts") {
319
- const npmLifecycleScripts = ["postinstall", "preinstall", "install", "preuninstall", "postuninstall", "shrinkwrap"];
320
- const filteredScripts = {};
321
- for (const [scriptName, scriptValue] of Object.entries(pkg[field] || {})) {
322
- if (npmLifecycleScripts.includes(scriptName)) {
323
- filteredScripts[scriptName] = scriptValue;
324
- }
325
- }
326
- if (Object.keys(filteredScripts).length > 0) {
327
- cleaned[field] = transformSrcToDist(filteredScripts);
328
- }
329
- } else if (field === "bin") {
330
- cleaned[field] = transformSrcToDist(pkg[field]);
331
- } else if (pathFields.includes(field)) {
332
- cleaned[field] = transformSrcToDist(pkg[field]);
333
- } else {
334
- cleaned[field] = pkg[field];
335
- }
336
- }
337
- }
338
- if (!cleaned.type) {
339
- cleaned.type = "module";
340
- }
341
- if (options.formats.cjs) {
342
- cleaned.main = `src/${mainEntry}.cjs`;
343
- }
344
- cleaned.module = `src/${mainEntry}.js`;
345
- cleaned.types = `src/${mainEntry}.d.ts`;
346
- return cleaned;
347
- }
348
- async function fileExists(filePath) {
349
- try {
350
- await FS.access(filePath);
351
- return true;
352
- } catch {
353
- return false;
354
- }
355
- }
356
- async function build2(cwd, save = false) {
357
- console.log("Building with libuild...");
358
- const srcDir = Path.join(cwd, "src");
359
- const distDir = Path.join(cwd, "dist");
360
- const distSrcDir = Path.join(distDir, "src");
361
- if (!await fileExists(srcDir)) {
362
- throw new Error("No src/ directory found");
363
- }
364
- const pkgPath = Path.join(cwd, "package.json");
365
- const pkg = JSON.parse(await FS.readFile(pkgPath, "utf-8"));
366
- if (!pkg.private) {
367
- console.warn("\u26A0\uFE0F WARNING: Root package.json is not private - this could lead to accidental publishing of development package.json");
368
- console.warn(" Consider setting 'private: true' in your root package.json");
369
- }
370
- const gitignorePath = Path.join(cwd, ".gitignore");
371
- if (await fileExists(gitignorePath)) {
372
- const gitignoreContent = await FS.readFile(gitignorePath, "utf-8");
373
- const isDistIgnored = gitignoreContent.includes("dist/") || gitignoreContent.includes("/dist") || gitignoreContent.includes("dist\n") || gitignoreContent.includes("dist\r\n");
374
- if (!isDistIgnored) {
375
- console.warn("\u26A0\uFE0F WARNING: dist/ directory is not in .gitignore - built files should not be committed");
376
- console.warn(" Add 'dist/' to your .gitignore file");
377
- }
378
- }
379
- const entries = await findEntryPoints(srcDir);
380
- if (entries.length === 0) {
381
- throw new Error("No entry points found in src/");
382
- }
383
- const options = {
384
- formats: {
385
- esm: true,
386
- // Always build ESM
387
- cjs: !!pkg.main,
388
- // Generate CJS only if main field exists
389
- umd: entries.includes("umd")
390
- }
391
- };
392
- const mainEntry = await detectMainEntry(pkg, entries);
393
- console.log(" Found entries:", entries.join(", "));
394
- console.log(" Main entry:", mainEntry);
395
- if (options.formats.cjs) {
396
- console.log(" Formats: ESM, CJS" + (options.formats.umd ? ", UMD" : ""));
397
- } else {
398
- console.log(" Formats: ESM" + (options.formats.umd ? ", UMD" : "") + " (no main field - CJS disabled)");
399
- }
400
- if (await fileExists(distDir)) {
401
- await FS.rm(distDir, { recursive: true });
402
- }
403
- await FS.mkdir(distDir, { recursive: true });
404
- const entryPoints = [];
405
- const umdEntries = [];
406
- for (const entry of entries) {
407
- const entryPath = Path.join(srcDir, `${entry}.ts`);
408
- const jsEntryPath = Path.join(srcDir, `${entry}.js`);
409
- const actualPath = await fileExists(entryPath) ? entryPath : jsEntryPath;
410
- if (!await fileExists(actualPath)) {
411
- throw new Error(`Entry point file not found: ${actualPath}. Expected ${entry}.ts or ${entry}.js in src/ directory.`);
412
- }
413
- if (entry === "umd") {
414
- umdEntries.push(actualPath);
415
- } else {
416
- entryPoints.push(actualPath);
417
- }
418
- }
419
- if (entryPoints.length > 0) {
420
- console.log(` Building ${entryPoints.length} entries (ESM)...`);
421
- await ESBuild.build({
422
- entryPoints,
423
- outdir: distSrcDir,
424
- format: "esm",
425
- entryNames: "[name]",
426
- outExtension: { ".js": ".js" },
427
- bundle: true,
428
- splitting: true,
429
- // Enable shared chunk extraction
430
- minify: false,
431
- sourcemap: true,
432
- external: Object.keys(pkg.dependencies || {}),
433
- platform: "node",
434
- target: "node16"
435
- });
436
- if (options.formats.cjs) {
437
- console.log(` Building ${entryPoints.length} entries (CJS)...`);
438
- await ESBuild.build({
439
- entryPoints,
440
- outdir: distSrcDir,
441
- format: "cjs",
442
- entryNames: "[name]",
443
- outExtension: { ".js": ".cjs" },
444
- bundle: true,
445
- minify: false,
446
- sourcemap: true,
447
- external: Object.keys(pkg.dependencies || {}),
448
- platform: "node",
449
- target: "node16"
450
- // Note: CJS doesn't support splitting, but building together still helps with consistency
451
- });
452
- }
453
- }
454
- for (const umdPath of umdEntries) {
455
- const entry = Path.basename(umdPath, Path.extname(umdPath));
456
- console.log(` Building ${entry} (UMD)...`);
457
- const globalName = pkg.name.includes("/") ? pkg.name.split("/").pop().replace(/-/g, "").charAt(0).toUpperCase() + pkg.name.split("/").pop().replace(/-/g, "").slice(1) : pkg.name.replace(/-/g, "").charAt(0).toUpperCase() + pkg.name.replace(/-/g, "").slice(1);
458
- await ESBuild.build({
459
- entryPoints: [umdPath],
460
- outdir: distSrcDir,
461
- format: "cjs",
462
- entryNames: "[name]",
463
- bundle: true,
464
- minify: false,
465
- sourcemap: true,
466
- external: Object.keys(pkg.dependencies || {}),
467
- platform: "node",
468
- target: "node16",
469
- plugins: [umdPlugin({ globalName })]
470
- });
471
- }
472
- console.log(" Generating TypeScript declarations...");
473
- const allTsFiles = [...entryPoints, ...umdEntries].filter((file) => file.endsWith(".ts"));
474
- if (allTsFiles.length > 0) {
475
- const compilerOptions = {
476
- declaration: true,
477
- emitDeclarationOnly: true,
478
- outDir: distSrcDir,
479
- rootDir: srcDir,
480
- skipLibCheck: true,
481
- esModuleInterop: true,
482
- target: TS.ScriptTarget.ES2020,
483
- module: TS.ModuleKind.ESNext
484
- };
485
- const program = TS.createProgram(allTsFiles, compilerOptions);
486
- const emitResult = program.emit();
487
- if (emitResult.diagnostics.length > 0) {
488
- const diagnostics = TS.formatDiagnosticsWithColorAndContext(emitResult.diagnostics, {
489
- getCanonicalFileName: (path) => path,
490
- getCurrentDirectory: () => cwd,
491
- getNewLine: () => "\n"
492
- });
493
- throw new Error(`TypeScript declaration generation failed:
494
- ${diagnostics}`);
495
- }
496
- }
497
- for (const entry of entries) {
498
- if (entry === "umd")
499
- continue;
500
- const jsPath = Path.join(distSrcDir, `${entry}.js`);
501
- const dtsPath = Path.join(distSrcDir, `${entry}.d.ts`);
502
- if (await fileExists(jsPath) && await fileExists(dtsPath)) {
503
- const content = await FS.readFile(jsPath, "utf-8");
504
- if (content.startsWith("#!")) {
505
- const lines = content.split("\n");
506
- const shebang = lines[0];
507
- const rest = lines.slice(1).join("\n");
508
- await FS.writeFile(jsPath, `${shebang}
509
- /// <reference types="./${entry}.d.ts" />
510
- ${rest}`);
511
- } else {
512
- await FS.writeFile(jsPath, `/// <reference types="./${entry}.d.ts" />
513
- ${content}`);
514
- }
515
- }
516
- }
517
- const autoDiscoveredFiles = [];
518
- console.log(" Generating package.json...");
519
- const cleanedPkg = cleanPackageJSON(pkg, mainEntry, options);
520
- const exportsResult = generateExports(entries, mainEntry, options, pkg.exports);
521
- cleanedPkg.exports = fixExportsForDist(exportsResult.exports);
522
- if (exportsResult.staleExports.length > 0) {
523
- console.warn(`\u26A0\uFE0F WARNING: Found ${exportsResult.staleExports.length} stale export(s) pointing to missing src/ files:`);
524
- for (const staleExport of exportsResult.staleExports) {
525
- console.warn(` - ${staleExport}`);
526
- }
527
- if (save) {
528
- console.log(" Removing stale exports from root package.json (--save mode)");
529
- } else {
530
- console.warn(" Use --save to remove these from root package.json");
531
- }
532
- }
533
- if (cleanedPkg.files && Array.isArray(cleanedPkg.files)) {
534
- for (const autoFile of autoDiscoveredFiles) {
535
- if (!cleanedPkg.files.includes(autoFile)) {
536
- cleanedPkg.files.push(autoFile);
537
- }
538
- }
539
- }
540
- const fixedDistPkg = fixExportsForDist(cleanedPkg);
541
- await FS.writeFile(
542
- Path.join(distDir, "package.json"),
543
- JSON.stringify(fixedDistPkg, null, 2) + "\n"
544
- );
545
- const defaultFilesToCopy = ["README.md", "LICENSE", "CHANGELOG.md"];
546
- for (const file of defaultFilesToCopy) {
547
- const srcPath = Path.join(cwd, file);
548
- if (await fileExists(srcPath)) {
549
- console.log(` Copying ${file}...`);
550
- await FS.copyFile(srcPath, Path.join(distDir, file));
551
- }
552
- }
553
- const commonFiles = ["README.md", "LICENSE", "CHANGELOG.md", "COPYING", "AUTHORS"];
554
- if (pkg.files && Array.isArray(pkg.files)) {
555
- for (const commonFile of commonFiles) {
556
- const commonPath = Path.join(cwd, commonFile);
557
- if (await fileExists(commonPath) && !pkg.files.includes(commonFile)) {
558
- console.log(` Auto-discovered ${commonFile}, adding to files field...`);
559
- pkg.files.push(commonFile);
560
- autoDiscoveredFiles.push(commonFile);
561
- }
562
- }
563
- }
564
- if (pkg.files && Array.isArray(pkg.files)) {
565
- console.log(" Copying files from package.json files field...");
566
- for (const pattern of pkg.files) {
567
- if (typeof pattern === "string" && (pattern.includes("src") || pattern.includes("dist"))) {
568
- continue;
569
- }
570
- if (typeof pattern === "string") {
571
- const srcPath = Path.join(cwd, pattern);
572
- const destPath = Path.join(distDir, pattern);
573
- if (await fileExists(srcPath)) {
574
- const stat2 = await FS.stat(srcPath);
575
- if (stat2.isDirectory()) {
576
- console.log(` Copying directory ${pattern}/...`);
577
- await FS.mkdir(Path.dirname(destPath), { recursive: true });
578
- await FS.cp(srcPath, destPath, { recursive: true });
579
- } else {
580
- console.log(` Copying ${pattern}...`);
581
- await FS.mkdir(Path.dirname(destPath), { recursive: true });
582
- await FS.copyFile(srcPath, destPath);
583
- }
584
- } else if (pattern.includes("*")) {
585
- const baseDir = pattern.split("*")[0].replace(/\/$/, "");
586
- if (baseDir && await fileExists(Path.join(cwd, baseDir))) {
587
- console.log(` Copying pattern ${pattern}...`);
588
- const baseSrcPath = Path.join(cwd, baseDir);
589
- const baseDestPath = Path.join(distDir, baseDir);
590
- await FS.mkdir(Path.dirname(baseDestPath), { recursive: true });
591
- await FS.cp(baseSrcPath, baseDestPath, { recursive: true });
592
- } else {
593
- throw new Error(`Pattern base directory not found for "${pattern}". Expected directory: ${Path.join(cwd, baseDir)}`);
594
- }
595
- } else {
596
- throw new Error(`File specified in files field not found: ${srcPath}. Remove "${pattern}" from package.json files field or create the file.`);
597
- }
598
- } else {
599
- throw new Error(`Invalid files field entry: ${JSON.stringify(pattern)}. Files field entries must be strings.`);
600
- }
601
- }
602
- }
603
- if (save) {
604
- console.log(" Updating root package.json...");
605
- const rootPkg2 = { ...pkg };
606
- rootPkg2.private = true;
607
- if (options.formats.cjs) {
608
- rootPkg2.main = `./dist/src/${mainEntry}.cjs`;
609
- }
610
- rootPkg2.module = `./dist/src/${mainEntry}.js`;
611
- rootPkg2.types = `./dist/src/${mainEntry}.d.ts`;
612
- if (rootPkg2.typings && typeof rootPkg2.typings === "string") {
613
- rootPkg2.typings = rootPkg2.typings.startsWith("./dist/") ? rootPkg2.typings : "./" + Path.join("dist", rootPkg2.typings);
614
- }
615
- const rootExports = {};
616
- for (const [key, value] of Object.entries(cleanedPkg.exports)) {
617
- if (typeof value === "string") {
618
- rootExports[key] = value.startsWith("./dist/") ? value : `./dist${value.startsWith(".") ? value.slice(1) : value}`;
619
- } else if (typeof value === "object" && value !== null) {
620
- rootExports[key] = {};
621
- for (const [subKey, subValue] of Object.entries(value)) {
622
- if (typeof subValue === "string") {
623
- rootExports[key][subKey] = subValue.startsWith("./dist/") ? subValue : `./dist${subValue.startsWith(".") ? subValue.slice(1) : subValue}`;
624
- }
625
- }
626
- }
627
- }
628
- rootPkg2.exports = rootExports;
629
- if (rootPkg2.bin) {
630
- if (typeof rootPkg2.bin === "string") {
631
- if (!rootPkg2.bin.startsWith("./dist/")) {
632
- rootPkg2.bin = "./" + Path.join("dist", rootPkg2.bin);
633
- }
634
- } else {
635
- for (const [name, binPath] of Object.entries(rootPkg2.bin)) {
636
- if (typeof binPath === "string" && !binPath.startsWith("./dist/")) {
637
- rootPkg2.bin[name] = "./" + Path.join("dist", binPath);
638
- }
639
- }
640
- }
641
- }
642
- if (pkg.files !== void 0) {
643
- if (!rootPkg2.files) {
644
- rootPkg2.files = [];
645
- } else if (!Array.isArray(rootPkg2.files)) {
646
- rootPkg2.files = [rootPkg2.files];
647
- }
648
- for (const autoFile of autoDiscoveredFiles) {
649
- if (!rootPkg2.files.includes(autoFile)) {
650
- rootPkg2.files.push(autoFile);
651
- }
652
- }
653
- if (!rootPkg2.files.includes("dist/") && !rootPkg2.files.includes("dist")) {
654
- rootPkg2.files.push("dist/");
655
- }
656
- }
657
- await FS.writeFile(pkgPath, JSON.stringify(rootPkg2, null, 2) + "\n");
658
- } else {
659
- console.log(" Skipping root package.json update (use --save to enable)");
660
- }
661
- console.log("\nBuild complete!");
662
- console.log(`
663
- Output: ${distDir}`);
664
- console.log(`
665
- Entries: ${entries.length}`);
666
- if (options.formats.cjs) {
667
- console.log(`
668
- Formats: ESM, CJS${options.formats.umd ? ", UMD" : ""}`);
669
- } else {
670
- console.log(`
671
- Formats: ESM${options.formats.umd ? ", UMD" : ""}`);
672
- }
673
- let rootPkg = pkg;
674
- if (save) {
675
- rootPkg = JSON.parse(await FS.readFile(pkgPath, "utf-8"));
676
- }
677
- return { distPkg: fixedDistPkg, rootPkg };
678
- }
679
- async function publish(cwd, save = true) {
680
- await build2(cwd, save);
681
- console.log("\nPublishing to npm...");
682
- const distDir = Path.join(cwd, "dist");
683
- const distPkgPath = Path.join(distDir, "package.json");
684
- if (!await fileExists(distPkgPath)) {
685
- throw new Error("No dist/package.json found. Run 'libuild build' first.");
686
- }
687
- const distPkg = JSON.parse(await FS.readFile(distPkgPath, "utf-8"));
688
- const publishArgs = ["publish"];
689
- if (distPkg.name.startsWith("@")) {
690
- publishArgs.push("--access", "public");
691
- }
692
- const proc = spawn("npm", publishArgs, {
693
- cwd: distDir,
694
- stdio: "inherit"
695
- });
696
- const exitCode = await new Promise((resolve) => {
697
- proc.on("close", resolve);
698
- });
699
- if (exitCode === 0) {
700
- const distPkg2 = JSON.parse(await FS.readFile(distPkgPath, "utf-8"));
701
- console.log(`
702
- Published ${distPkg2.name}@${distPkg2.version}!`);
703
- } else {
704
- throw new Error("npm publish failed");
705
- }
706
- }
707
-
708
- export {
709
- transformSrcToDist,
710
- build2 as build,
711
- publish
712
- };
713
- //# sourceMappingURL=chunk-YRPHTAV4.js.map