-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathbuild.publish.ts
2207 lines (2032 loc) · 64.5 KB
/
build.publish.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Build and Publish Script
* This script bundles, bumps versions, and publishes the project
* with its optional libraries to the NPM and/or JSR registries.
*/
import { re } from "@reliverse/relico";
import { build as bunBuild } from "bun";
import { parseJSONC, parseJSON5 } from "confbox";
import { destr } from "destr";
import { execaCommand } from "execa";
import fs from "fs-extra";
import mri from "mri";
import path from "pathe";
import {
readPackageJSON,
defineTSConfig,
definePackageJSON,
type PackageJson,
} from "pkg-types";
import semver from "semver";
import { glob } from "tinyglobby";
import { fileURLToPath } from "url";
import {
pubConfig,
getBunSourcemapOption,
type BuildPublishConfig,
} from "./build.config.js";
// ============================
// Constants & Global Setup
// ============================
const tsconfigJson = "tsconfig.json";
const cliConfigJsonc = "cli.config.jsonc";
const cliDomainDocs = "https://docs.reliverse.org";
const ROOT_DIR = path.dirname(fileURLToPath(import.meta.url));
const DIST_FOLDERS = ["dist-npm", "dist-jsr", "dist-libs"];
const JSON_FILE_PATTERN = "**/*.{ts,json,jsonc,json5}";
const TEST_FILE_PATTERNS = [
"**/*.test.js",
"**/*.test.ts",
"**/*.test.d.ts",
"**/*-temp.js",
"**/*-temp.ts",
"**/*-temp.d.ts",
"**/__snapshots__/**",
];
const IGNORE_PATTERNS = [
"**/node_modules/**",
"**/.git/**",
"**/dist/**",
"**/build/**",
"**/.next/**",
"**/coverage/**",
"**/.cache/**",
"**/tmp/**",
"**/.temp/**",
"**/package-lock.json",
"**/pnpm-lock.yaml",
"**/yarn.lock",
"**/bun.lock",
];
// Regex constants for version updates
const JSON_VERSION_REGEX = (oldVer: string) =>
new RegExp(`"version"\\s*:\\s*"${oldVer}"`, "g");
const TS_VERSION_REGEXES = [
(oldVer: string) =>
new RegExp(`(export\\s+const\\s+version\\s*=\\s*["'])${oldVer}(["'])`, "g"),
(oldVer: string) =>
new RegExp(`(const\\s+version\\s*=\\s*["'])${oldVer}(["'])`, "g"),
(oldVer: string) => new RegExp(`(version\\s*:\\s*["'])${oldVer}(["'])`, "g"),
(oldVer: string) => new RegExp(`(VERSION\\s*=\\s*["'])${oldVer}(["'])`, "g"),
(oldVer: string) =>
new RegExp(
`(export\\s+const\\s+cliVersion\\s*=\\s*["'])${oldVer}(["'])`,
"g",
),
(oldVer: string) =>
new RegExp(`(const\\s+cliVersion\\s*=\\s*["'])${oldVer}(["'])`, "g"),
];
// ============================
// CLI Flags Parsing & Help
// ============================
const cliFlags = mri(process.argv.slice(2), {
string: ["bump", "registry"],
boolean: ["verbose", "dryRun", "allowDirty", "jsrSlowTypes", "help"],
alias: {
v: "verbose",
d: "dryRun",
r: "registry",
h: "help",
},
default: {},
});
// Display help if requested
if (cliFlags["help"]) {
console.log(`
Usage: build.publish.ts [options]
Options:
--bump <version> Specify a version to bump to.
--registry <npm|jsr|npm-jsr> Select the registry to publish to.
--verbose, -v Enable verbose logging.
--dryRun, -d Run in dry run mode (no actual publish).
--allowDirty Allow publishing from a dirty working directory.
--jsrSlowTypes Enable slow type-checking for JSR.
--help, -h Display this help message.
`);
process.exit(0);
}
// Override pubConfig values with CLI flags if provided.
if (cliFlags["verbose"] !== undefined) {
pubConfig.verbose = cliFlags["verbose"];
}
if (cliFlags["dryRun"] !== undefined) {
pubConfig.dryRun = cliFlags["dryRun"];
}
if (cliFlags["registry"]) {
if (["npm", "jsr", "npm-jsr"].includes(cliFlags["registry"])) {
pubConfig.registry = cliFlags["registry"];
} else {
console.warn(
`Warning: Unrecognized registry "${cliFlags["registry"]}". Using default: ${pubConfig.registry}`,
);
}
}
if (cliFlags["allowDirty"] !== undefined) {
pubConfig.allowDirty = cliFlags["allowDirty"];
}
if (cliFlags["jsrSlowTypes"] !== undefined) {
pubConfig.jsrSlowTypes = cliFlags["jsrSlowTypes"];
}
// ============================
// Logger Utility (with timestamps)
// ============================
const getTimestamp = () => new Date().toISOString();
const logger = {
info: (msg: string, newLine = false) =>
console.log(
`${newLine ? "\n" : ""}[${getTimestamp()}] 📝 ${re.cyanBright(msg)}`,
),
success: (msg: string, newLine = false) =>
console.log(
`${newLine ? "\n" : ""}[${getTimestamp()}] ✅ ${re.greenBright(msg)}`,
),
warn: (msg: string, newLine = false) =>
console.warn(
`${newLine ? "\n" : ""}[${getTimestamp()}] 🔔 ${re.yellowBright(msg)}`,
),
error: (msg: string, err?: unknown, newLine = false) =>
console.error(
`${newLine ? "\n" : ""}[${getTimestamp()}] ❌ ${msg}`,
err instanceof Error ? err.message : err,
),
verbose: (msg: string, newLine = false) => {
if (pubConfig.verbose) {
console.log(
`${newLine ? "\n" : ""}[${getTimestamp()}] 🔍 ${re.magentaBright(msg)}`,
);
}
},
};
// ============================
// Utility Helpers
// ============================
/**
* Runs an async function within a given working directory,
* ensuring that the original directory is restored afterward.
*/
async function withWorkingDirectory<T>(
targetDir: string,
fn: () => Promise<T>,
): Promise<T> {
const originalDir = process.cwd();
try {
process.chdir(targetDir);
logger.verbose(`Changed working directory to: ${targetDir}`, true);
return await fn();
} catch (error) {
logger.error(`Error in directory ${targetDir}:`, error, true);
throw error;
} finally {
process.chdir(originalDir);
logger.verbose(`Restored working directory to: ${originalDir}`, true);
}
}
/**
* Ensures a directory is clean by removing it if it exists and recreating it.
*/
async function cleanDir(dirPath: string): Promise<void> {
await fs.remove(dirPath);
await fs.ensureDir(dirPath);
logger.verbose(`Cleaned directory: ${dirPath}`, true);
}
/**
* Recursively removes any existing distribution folders.
*/
async function removeDistFolders(): Promise<boolean> {
const existingFolders: string[] = [];
for (const folder of DIST_FOLDERS) {
const folderPath = path.resolve(ROOT_DIR, folder);
if (await fs.pathExists(folderPath)) {
existingFolders.push(folder);
}
}
if (existingFolders.length > 0) {
logger.verbose(
`Found existing distribution folders: ${existingFolders.join(", ")}`,
true,
);
await Promise.all(
DIST_FOLDERS.map(async (folder) => {
const folderPath = path.resolve(ROOT_DIR, folder);
if (await fs.pathExists(folderPath)) {
await fs.remove(folderPath);
logger.verbose(`Removed: ${folderPath}`, true);
}
}),
);
logger.success("Distribution folders cleaned up successfully", true);
}
return true;
}
/**
* Deletes specific test and temporary files from a given directory.
*/
async function deleteSpecificFiles(outdirBin: string): Promise<void> {
// Get all test files and snapshot directories
const files = await glob(TEST_FILE_PATTERNS, {
cwd: outdirBin,
absolute: true,
});
// Find all __snapshots__ directories for separate handling
const snapshotDirs = await glob("**/__snapshots__", {
cwd: outdirBin,
absolute: true,
onlyDirectories: true,
});
// Filter out regular .d.ts files that aren't test or temp files
const filesToDelete = files.filter((file) => {
if (file.endsWith(".d.ts")) {
// Only delete .d.ts files that match test or temp patterns
return file.includes(".test.d.ts") || file.includes("-temp.d.ts");
}
return true;
});
// Delete individual files
if (filesToDelete.length > 0) {
await Promise.all(filesToDelete.map((file) => fs.remove(file)));
logger.verbose(`Deleted files:\n${filesToDelete.join("\n")}`, true);
}
// Delete snapshot directories
if (snapshotDirs.length > 0) {
await Promise.all(snapshotDirs.map((dir) => fs.remove(dir)));
logger.verbose(
`Deleted snapshot directories:\n${snapshotDirs.join("\n")}`,
true,
);
}
}
/**
* Updates version strings in files based on file type.
*/
async function bumpVersions(
oldVersion: string,
newVersion: string,
): Promise<void> {
try {
const codebase = await glob([JSON_FILE_PATTERN], {
ignore: IGNORE_PATTERNS,
});
const updateFile = async (
filePath: string,
content: string,
): Promise<boolean> => {
try {
if (/\.(json|jsonc|json5)$/.test(filePath)) {
let parsed: { version?: string } | null = null;
if (filePath.endsWith(".json")) {
parsed = destr(content);
} else if (filePath.endsWith(".jsonc")) {
parsed = parseJSONC(content);
} else if (filePath.endsWith(".json5")) {
parsed = parseJSON5(content);
}
if (!parsed || typeof parsed !== "object") {
return false;
}
if (parsed.version === oldVersion) {
const updated = content.replace(
JSON_VERSION_REGEX(oldVersion),
`"version": "${newVersion}"`,
);
await fs.writeFile(filePath, updated, "utf8");
logger.verbose(`Updated version in ${filePath}`, true);
return true;
}
} else if (filePath.endsWith(".ts")) {
let updated = content;
let hasChanges = false;
for (const regexFactory of TS_VERSION_REGEXES) {
const regex = regexFactory(oldVersion);
if (regex.test(content)) {
updated = updated.replace(regex, `$1${newVersion}$2`);
hasChanges = true;
}
}
if (hasChanges) {
await fs.writeFile(filePath, updated, "utf8");
logger.verbose(`Updated version in ${filePath}`, true);
return true;
}
}
return false;
} catch (error) {
logger.warn(
`Failed to process ${filePath}: ${error instanceof Error ? error.message : String(error)}`,
true,
);
return false;
}
};
const results = await Promise.all(
codebase.map(async (file) => {
const content = await fs.readFile(file, "utf8");
return updateFile(file, content);
}),
);
const updatedCount = results.filter(Boolean).length;
if (updatedCount > 0) {
logger.success(
`Updated version from ${oldVersion} to ${newVersion} in ${updatedCount} file(s)`,
true,
);
} else {
logger.warn("No files were updated with the new version", true);
}
} catch (error) {
logger.error("Failed to bump versions:", error, true);
throw error;
}
}
/**
* Auto-increments a semantic version based on the specified bump mode.
*/
function autoIncrementVersion(
oldVersion: string,
mode: "autoPatch" | "autoMinor" | "autoMajor",
): string {
if (!semver.valid(oldVersion)) {
throw new Error(`Can't auto-increment invalid version: ${oldVersion}`);
}
const releaseTypeMap = {
autoPatch: "patch",
autoMinor: "minor",
autoMajor: "major",
} as const;
const newVer = semver.inc(oldVersion, releaseTypeMap[mode]);
if (!newVer) {
throw new Error(`semver.inc failed for ${oldVersion} and mode ${mode}`);
}
return newVer;
}
/**
* Updates the "disableBump" flag in the build configuration file.
*/
async function setBumpDisabled(value: boolean): Promise<void> {
if (pubConfig.pausePublish && value) {
logger.verbose("Skipping disableBump toggle due to pausePublish", true);
return;
}
const tsConfigPath = path.join(ROOT_DIR, "build.config.ts");
const jsConfigPath = path.join(ROOT_DIR, "build.config.js");
const configPath = (await fs.pathExists(tsConfigPath))
? tsConfigPath
: jsConfigPath;
if (!(await fs.pathExists(configPath))) {
logger.warn(
"No build.config.ts or build.config.js found to update disableBump",
true,
);
return;
}
let content = await fs.readFile(configPath, "utf-8");
content = content.replace(
/disableBump\s*:\s*(true|false)/,
`disableBump: ${value}`,
);
await fs.writeFile(configPath, content, "utf-8");
logger.verbose(`Updated disableBump to ${value} in ${configPath}`, true);
}
/**
* Handles version bumping.
*/
async function bumpHandler(): Promise<void> {
if (pubConfig.disableBump || pubConfig.pausePublish) {
logger.info(
"Skipping version bump because it is either disabled or paused in config.",
true,
);
return;
}
const cliVersion = cliFlags["bump"];
const pkgPath = path.resolve("package.json");
if (!(await fs.pathExists(pkgPath))) {
throw new Error("package.json not found");
}
const pkgJson = await readPackageJSON();
if (!pkgJson.version) {
throw new Error("No version field found in package.json");
}
const oldVersion = pkgJson.version;
if (cliVersion) {
if (!semver.valid(cliVersion)) {
throw new Error(`Invalid version format for --bump: "${cliVersion}"`);
}
if (oldVersion !== cliVersion) {
await bumpVersions(oldVersion, cliVersion);
await setBumpDisabled(true);
} else {
logger.info(`Version is already at ${oldVersion}, no bump needed.`, true);
}
} else {
if (!semver.valid(oldVersion)) {
throw new Error(
`Invalid existing version in package.json: ${oldVersion}`,
);
}
logger.info(
`Auto-incrementing version from ${oldVersion} using "${pubConfig.bump}"`,
true,
);
const incremented = autoIncrementVersion(oldVersion, pubConfig.bump);
if (oldVersion !== incremented) {
await bumpVersions(oldVersion, incremented);
await setBumpDisabled(true);
} else {
logger.info(`Version is already at ${oldVersion}, no bump needed.`, true);
}
}
}
/**
* Returns a build configuration based on the target registry.
*/
function defineConfig(isJSR: boolean): BuildPublishConfig {
return {
...pubConfig,
isJSR,
lastBuildFor: isJSR ? "jsr" : "npm",
};
}
/**
* Creates common package.json fields based on the original package.json.
*/
async function createCommonPackageFields(): Promise<Partial<PackageJson>> {
const originalPkg = await readPackageJSON();
const { name, author, version, license, description, keywords } = originalPkg;
const pkgHomepage = cliDomainDocs;
const commonFields: Partial<PackageJson> = {
name,
version,
license: license || "MIT",
description,
homepage: pkgHomepage,
dependencies: originalPkg.dependencies || {},
type: "module",
};
if (author) {
// Extract organization name for GitHub URLs
const repoOwner = author;
// Remove scope prefix for repo name if it exists
const repoName = originalPkg.name
? originalPkg.name.startsWith("@")
? originalPkg.name.split("/").pop() || originalPkg.name
: originalPkg.name
: "";
Object.assign(commonFields, {
author,
repository: {
type: "git",
url: `git+https://github.com/${repoOwner}/${repoName}.git`,
},
bugs: {
url: `https://github.com/${repoOwner}/${repoName}/issues`,
},
keywords: [...new Set([...(keywords || []), author])],
});
} else if (keywords && keywords.length > 0) {
commonFields.keywords = keywords;
}
return commonFields;
}
/**
* Extracts the package name from an import path.
* For scoped packages (starting with "@"), returns the first two segments.
*/
function extractPackageName(importPath: string | undefined): string | null {
if (!importPath || importPath.startsWith(".")) return null;
const parts = importPath.split("/");
if (importPath.startsWith("@") && parts.length >= 2) {
return `${parts[0]}/${parts[1]}`;
}
return parts[0] || null;
}
/**
* Filters out development dependencies (like eslint and prettier) from a dependency record.
* Optionally filters out unused dependencies from a dependency record.
*/
async function filterDeps(
deps: Record<string, string> | undefined,
clearUnused: boolean,
outdirBin: string,
): Promise<Record<string, string>> {
if (!deps) return {};
if (!clearUnused) {
// Only filter out eslint and prettier
return Object.entries(deps).reduce<Record<string, string>>(
(acc, [k, v]) => {
if (
!k.toLowerCase().includes("eslint") &&
!k.toLowerCase().includes("prettier")
) {
acc[k] = v;
}
return acc;
},
{},
);
}
// Get all JS/TS files in outdirBin
const files = await glob("**/*.{js,ts}", {
cwd: outdirBin,
absolute: true,
});
// Extract all imports from files
const usedPackages = new Set<string>();
for (const file of files) {
const content = await fs.readFile(file, "utf8");
// Match import statements
const importMatches = content.matchAll(
/from\s+['"](\.|\.\/|\.\\)?src(\/|\\)/g,
);
for (const match of importMatches) {
const importPath = match[1];
const pkg = extractPackageName(importPath);
if (pkg) {
usedPackages.add(pkg);
}
}
}
// Keep only used packages and always filter out eslint/prettier
return Object.entries(deps).reduce<Record<string, string>>((acc, [k, v]) => {
if (
usedPackages.has(k) &&
!k.toLowerCase().includes("eslint") &&
!k.toLowerCase().includes("prettier")
) {
acc[k] = v;
}
return acc;
}, {});
}
// ============================
// Package & TSConfig Generation
// ============================
/**
* Creates a package.json for the main distribution.
*/
async function createPackageJSON(
outdirRoot: string,
isJSR: boolean,
): Promise<void> {
logger.info(
"Generating distribution package.json and tsconfig.json...",
true,
);
const commonPkg = await createCommonPackageFields();
const originalPkg = await readPackageJSON();
// Extract CLI command name from package.json name
// If it's a scoped package like @reliverse/cleaner, extract "cleaner"
// Otherwise use the name as is
const packageName = originalPkg.name || "";
const cliCommandName = packageName.startsWith("@")
? packageName.split("/").pop() || "cli"
: packageName;
const outdirBin = path.join(outdirRoot, "bin");
if (isJSR) {
const jsrPkg = definePackageJSON({
...commonPkg,
exports: {
".": "./bin/main.ts",
},
dependencies: await filterDeps(
originalPkg.dependencies,
false,
outdirBin,
),
devDependencies: await filterDeps(
originalPkg.devDependencies,
false,
outdirBin,
),
});
await fs.writeJSON(path.join(outdirRoot, "package.json"), jsrPkg, {
spaces: 2,
});
} else {
const npmPkg = definePackageJSON({
...commonPkg,
main: "./bin/main.js",
module: "./bin/main.js",
exports: {
".": "./bin/main.js",
},
bin: pubConfig.isCLI
? {
[cliCommandName]: "bin/main.js",
}
: undefined,
files: ["bin", "package.json", "README.md", "LICENSE"],
publishConfig: {
access: "public",
},
});
await fs.writeJSON(path.join(outdirRoot, "package.json"), npmPkg, {
spaces: 2,
});
}
}
/**
* Creates a tsconfig.json file for the distribution.
*/
async function createTSConfig(
outdirRoot: string,
allowImportingTsExtensions: boolean,
): Promise<void> {
const tsConfig = defineTSConfig({
compilerOptions: {
allowImportingTsExtensions,
target: "ES2023",
module: "NodeNext",
moduleResolution: "nodenext",
lib: ["DOM", "DOM.Iterable", "ES2023"],
resolveJsonModule: true,
verbatimModuleSyntax: true,
isolatedModules: true,
noPropertyAccessFromIndexSignature: true,
forceConsistentCasingInFileNames: true,
noFallthroughCasesInSwitch: true,
esModuleInterop: true,
skipLibCheck: true,
jsx: "preserve",
allowJs: true,
strict: true,
noEmit: true,
noImplicitOverride: true,
noImplicitReturns: true,
noUnusedLocals: true,
noUnusedParameters: true,
noUncheckedIndexedAccess: true,
strictNullChecks: true,
noImplicitAny: true,
exactOptionalPropertyTypes: true,
allowUnreachableCode: false,
allowUnusedLabels: false,
},
include: ["./bin/**/*.ts"],
exclude: ["**/node_modules"],
});
await fs.writeJSON(path.join(outdirRoot, tsconfigJson), tsConfig, {
spaces: 2,
});
}
/**
* Finds a file in the current directory regardless of case.
*/
async function findFileCaseInsensitive(
targetFile: string,
): Promise<string | null> {
const files = await fs.readdir(".");
const found = files.find(
(file) => file.toLowerCase() === targetFile.toLowerCase(),
);
return found || null;
}
/**
* Copies README and LICENSE files to the output directory.
*/
async function copyReadmeLicense(outdirRoot: string): Promise<void> {
logger.info("Copying README.md and LICENSE files...", true);
const readmeFile = await findFileCaseInsensitive("README.md");
if (readmeFile) {
await fs.copy(readmeFile, path.join(outdirRoot, "README.md"));
logger.verbose(`Copied ${readmeFile} as README.md`, true);
} else {
logger.warn("README.md not found", true);
}
let licenseFile = await findFileCaseInsensitive("LICENSE");
if (!licenseFile) {
licenseFile = await findFileCaseInsensitive("LICENSE.md");
}
if (licenseFile) {
await fs.copy(licenseFile, path.join(outdirRoot, "LICENSE"));
logger.verbose(`Copied ${licenseFile} as LICENSE`, true);
} else {
logger.warn("No license file found", true);
}
}
// ============================
// File Conversion & Renaming
// ============================
/**
* Converts .js import paths to .ts in files within the given directory for JSR builds.
* Also fixes relative paths for subdirectory files.
*/
async function convertJsToTsImports(
outdirBin: string,
isJSR: boolean,
): Promise<void> {
const entries = await fs.readdir(outdirBin);
for (const entry of entries) {
const filePath = path.join(outdirBin, entry);
const stat = await fs.stat(filePath);
if (stat.isDirectory()) {
await convertJsToTsImports(filePath, isJSR);
} else if (
stat.isFile() &&
/\.(ts|tsx|js|jsx|mts|cts|mjs|cjs)$/.test(entry)
) {
if (filePath.includes("template/")) continue;
const content = await fs.readFile(filePath, "utf8");
if (isJSR) {
// Fix import paths for JSR distribution
let finalContent = content;
// Convert src to bin in import paths
finalContent = finalContent.replace(
/(from\s*['"])(\.|\.\/|\.\\)?src(\/|\\)/g,
"$1$2bin$3",
);
// Convert .js to .ts in all import statements
finalContent = finalContent.replace(
/(from\s*['"].*?)\.js(['"]\s*;?)/g,
"$1.ts$2",
);
// Fix relative paths for subdirectory files
// Check if the file is inside a subdirectory of outdirBin
const relativePath = path.relative(outdirBin, filePath);
if (
(filePath.includes("/bin/") || filePath.includes("\\bin\\")) &&
relativePath.includes(path.sep) && // indicates file is in a subdirectory
(finalContent.includes("../libs/") ||
finalContent.includes("../libs\\")) &&
(filePath.includes("/libs/") || filePath.includes("\\libs\\"))
) {
// Throw error for libraries with subdirectories
throw new Error(
`Subdirectories in libraries are not currently supported. Found subdirectory in: ${filePath}`,
);
}
logger.verbose("Converted .js imports to .ts for JSR build", true);
await fs.writeFile(filePath, finalContent, "utf8");
} else {
await fs.writeFile(filePath, content, "utf8");
}
}
}
}
/**
* Renames .tsx files by replacing the .tsx extension with -tsx.txt.
*/
async function renameTsxFiles(dir: string): Promise<void> {
const files = await glob(["**/*.tsx"], {
cwd: dir,
absolute: true,
});
await Promise.all(
files.map(async (filePath) => {
const newPath = filePath.replace(/\.tsx$/, "-tsx.txt");
await fs.rename(filePath, newPath);
logger.verbose(`Renamed: ${filePath} -> ${newPath}`, true);
}),
);
}
/**
* Generates a jsr.jsonc configuration file for JSR distributions.
*/
async function createJsrConfig(
outdirRoot: string,
projectName: string,
isLib: boolean,
): Promise<void> {
const originalPkg = await readPackageJSON();
let { name, description } = originalPkg;
const { author, version, license } = originalPkg;
if (isLib) {
name = projectName;
description = "A helper library for the Reliverse CLI";
}
const pkgHomepage = cliDomainDocs;
const jsrConfig = {
name,
author,
version,
license: license || "MIT",
description,
homepage: pkgHomepage,
exports: "./bin/main.ts",
publish: {
exclude: ["!.", "node_modules/**", ".env"],
},
};
await fs.writeJSON(path.join(outdirRoot, "jsr.jsonc"), jsrConfig, {
spaces: 2,
});
logger.verbose("Generated jsr.jsonc file", true);
}
/**
* Copies additional JSR-specific files to the output directory.
*/
async function copyJsrFiles(
outdirRoot: string,
projectName: string,
isLib: boolean,
): Promise<void> {
logger.info(
`Copying JSR files (isCLI=${pubConfig.isCLI}, isLib=${isLib})`,
true,
);
if (pubConfig.isCLI) {
await fs.writeFile(
path.join(outdirRoot, ".gitignore"),
"node_modules/\n.env\n",
"utf-8",
);
logger.verbose("Generated .gitignore for JSR", true);
}
await createJsrConfig(outdirRoot, projectName, isLib);
let jsrFiles: string[];
if (pubConfig.isCLI) {
jsrFiles = [cliConfigJsonc, "bun.lock", "drizzle.config.ts", "schema.json"];
logger.verbose(
`Will copy CLI-specific files: ${jsrFiles.join(", ")}`,
true,
);
} else {
jsrFiles = [cliConfigJsonc];
logger.verbose(`Will only copy common files: ${jsrFiles.join(", ")}`, true);
}
let copiedCount = 0;
await Promise.all(
jsrFiles.map(async (file) => {
if (await fs.pathExists(file)) {
await fs.copy(file, path.join(outdirRoot, file));
copiedCount++;
logger.verbose(`Copied JSR file: ${file}`, true);
} else {
logger.verbose(`JSR file not found (skipped): ${file}`, true);
}
}),
);
logger.info(`Copied ${copiedCount} JSR files to ${outdirRoot}`, true);
}
/**
* Calculates the total size (in bytes) of a directory.
*/
async function getDirectorySize(outdirRoot: string): Promise<number> {
try {
const files = await fs.readdir(outdirRoot);
const sizes = await Promise.all(
files.map(async (file) => {
const fp = path.join(outdirRoot, file);
const stats = await fs.stat(fp);
return stats.isDirectory() ? getDirectorySize(fp) : stats.size;
}),
);
return sizes.reduce((total, s) => total + s, 0);
} catch (error) {
logger.error(
`Failed to calculate directory size for ${outdirRoot}`,
error,
true,
);
return 0;
}
}
/**
* Computes a relative import path from a source file to a target sub-path.
*/
function getRelativeImportPath(
sourceFile: string,
subPath: string,
baseDir: string,
prefix = "",
): string {
const targetPath = path.join(baseDir, subPath);
let relativePath = path
.relative(path.dirname(sourceFile), targetPath)
.replace(/\\/g, "/");
if (!relativePath.startsWith(".") && !relativePath.startsWith("/")) {
relativePath = `./${relativePath}`;
}
return prefix ? `${prefix}${relativePath}` : relativePath;
}
/**
* Replaces symbol paths (e.g. "~/...") with relative paths.
*/
function replaceSymbolPaths(
content: string,
sourceFile: string,
baseDir: string,
symbolPrefix = "~/",
): { changed: boolean; newContent: string } {
const escapedSymbol = symbolPrefix.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
const symbolRegex = new RegExp(`(['"])(${escapedSymbol}[^'"]+)\\1`, "g");
let changed = false;
const newContent = content.replace(
symbolRegex,
(_match, quote, matchedSymbol) => {
const subPath = matchedSymbol.slice(symbolPrefix.length);
const relativeImport = getRelativeImportPath(
sourceFile,
subPath,
baseDir,
);
changed = true;
return `${quote}${relativeImport}${quote}`;
},
);
return { changed, newContent };