Skip to content

Commit 2ac7b98

Browse files
committed
chore: improve publish scripts
1 parent 198bce1 commit 2ac7b98

File tree

3 files changed

+135
-84
lines changed

3 files changed

+135
-84
lines changed

biome.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
"includes": [
77
"packages/**/*.{ts,tsx,js,jsx,mjs,cjs,json}",
88
"examples/**/*.{ts,tsx,js,jsx,mjs,cjs,json}",
9+
"scripts/**/*.{ts,tsx}",
910
"*.{ts,tsx,js,jsx,mjs,cjs,json}",
1011
"!**/*/target/**",
1112
"!**/*/dist/**",

scripts/prepare-publish.ts

Lines changed: 99 additions & 56 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
11
#!/usr/bin/env bun
22

3-
import fs from 'fs';
4-
import path from 'path';
3+
import fs from "fs";
4+
import path from "path";
55

6-
const rootDir = path.resolve(import.meta.dir, '..');
7-
const BACKUP_DIR = path.join(rootDir, '.package-backups');
6+
const rootDir = path.resolve(import.meta.dir, "..");
7+
const BACKUP_DIR = path.join(rootDir, ".package-backups");
88

99
interface PackageJson {
1010
name: string;
@@ -28,139 +28,182 @@ interface RootPackageJson extends PackageJson {
2828
}
2929

3030
function readJSON<T = any>(filePath: string): T {
31-
return JSON.parse(fs.readFileSync(filePath, 'utf8'));
31+
return JSON.parse(fs.readFileSync(filePath, "utf8"));
3232
}
3333

3434
function writeJSON(filePath: string, data: any): void {
35-
fs.writeFileSync(filePath, JSON.stringify(data, null, 4) + '\n');
35+
fs.writeFileSync(filePath, JSON.stringify(data, null, 4) + "\n");
3636
}
3737

3838
function getWorkspacePackages(): Map<string, WorkspacePackageInfo> {
3939
const packages = new Map<string, WorkspacePackageInfo>();
40-
const packagesDir = path.join(rootDir, 'packages');
41-
42-
const dirs = fs.readdirSync(packagesDir)
43-
.filter(dir => fs.statSync(path.join(packagesDir, dir)).isDirectory());
44-
40+
const packagesDir = path.join(rootDir, "packages");
41+
42+
const dirs = fs
43+
.readdirSync(packagesDir)
44+
.filter((dir) =>
45+
fs.statSync(path.join(packagesDir, dir)).isDirectory()
46+
);
47+
4548
for (const dir of dirs) {
46-
const pkgPath = path.join(packagesDir, dir, 'package.json');
49+
const pkgPath = path.join(packagesDir, dir, "package.json");
4750
if (fs.existsSync(pkgPath)) {
4851
const pkg = readJSON<PackageJson>(pkgPath);
4952
packages.set(pkg.name, {
5053
version: pkg.version,
51-
path: pkgPath
54+
path: pkgPath,
5255
});
5356
}
5457
}
55-
58+
5659
return packages;
5760
}
5861

5962
function getCatalogVersions(): Record<string, string> {
60-
const rootPkg = readJSON<RootPackageJson>(path.join(rootDir, 'package.json'));
63+
const rootPkg = readJSON<RootPackageJson>(
64+
path.join(rootDir, "package.json")
65+
);
6166
return rootPkg.workspaces?.catalog || {};
6267
}
6368

64-
function resolveWorkspaceVersion(depName: string, workspacePackages: Map<string, WorkspacePackageInfo>): string | null {
69+
function resolveWorkspaceVersion(
70+
depName: string,
71+
workspacePackages: Map<string, WorkspacePackageInfo>
72+
): string | null {
6573
const pkg = workspacePackages.get(depName);
6674
return pkg ? pkg.version : null;
6775
}
6876

69-
function resolveCatalogVersion(depName: string, catalogVersions: Record<string, string>): string | null {
77+
function resolveCatalogVersion(
78+
depName: string,
79+
catalogVersions: Record<string, string>
80+
): string | null {
7081
return catalogVersions[depName] || null;
7182
}
7283

7384
function backupPackageJson(filePath: string): void {
7485
if (!fs.existsSync(BACKUP_DIR)) {
7586
fs.mkdirSync(BACKUP_DIR, { recursive: true });
7687
}
77-
88+
7889
const relativePath = path.relative(rootDir, filePath);
7990
const backupPath = path.join(BACKUP_DIR, relativePath);
8091
const backupDir = path.dirname(backupPath);
81-
92+
8293
if (!fs.existsSync(backupDir)) {
8394
fs.mkdirSync(backupDir, { recursive: true });
8495
}
85-
96+
8697
fs.copyFileSync(filePath, backupPath);
8798
}
99+
function handleDependency<T>(
100+
type: string,
101+
deps: Record<string, string>,
102+
name: string,
103+
version: string,
104+
catalogVersions: T,
105+
resolverFn: (name: string, version: T) => string | null
106+
): { modified: boolean; deps: Record<string, string> } {
107+
if (version !== type) {
108+
return { modified: false, deps };
109+
}
110+
const resolvedVersion = resolverFn(name, catalogVersions);
111+
if (!resolvedVersion) {
112+
console.warn(` ! Could not resolve ${type} version for ${name}`);
113+
return { modified: false, deps };
114+
}
115+
deps[name] = resolvedVersion;
116+
console.log(` ✓ Resolved ${name}: ${type}${resolvedVersion}`);
117+
return { modified: true, deps };
118+
}
88119

89120
function processPackageJson(
90-
pkgPath: string,
91-
workspacePackages: Map<string, WorkspacePackageInfo>,
121+
pkgPath: string,
122+
workspacePackages: Map<string, WorkspacePackageInfo>,
92123
catalogVersions: Record<string, string>
93124
): boolean {
94125
const pkg = readJSON<PackageJson>(pkgPath);
95126
let modified = false;
96-
127+
97128
backupPackageJson(pkgPath);
98-
129+
99130
const processDeps = (deps?: Record<string, string>) => {
100131
if (!deps) return;
101-
132+
102133
for (const [name, version] of Object.entries(deps)) {
103-
if (version === 'workspace:*') {
104-
const resolvedVersion = resolveWorkspaceVersion(name, workspacePackages);
105-
if (resolvedVersion) {
106-
deps[name] = `^${resolvedVersion}`;
107-
modified = true;
108-
console.log(` ✓ Resolved ${name}: workspace:* → ^${resolvedVersion}`);
109-
} else {
110-
console.warn(` ⚠ Could not resolve workspace version for ${name}`);
111-
}
112-
} else if (version === 'catalog:') {
113-
const resolvedVersion = resolveCatalogVersion(name, catalogVersions);
114-
if (resolvedVersion) {
115-
deps[name] = resolvedVersion;
116-
modified = true;
117-
console.log(` ✓ Resolved ${name}: catalog: → ${resolvedVersion}`);
118-
} else {
119-
console.warn(` ⚠ Could not resolve catalog version for ${name}`);
120-
}
134+
const workspaceDep = handleDependency(
135+
"workspace:*",
136+
deps!,
137+
name,
138+
version,
139+
workspacePackages,
140+
resolveWorkspaceVersion
141+
);
142+
deps = workspaceDep.deps;
143+
if (workspaceDep.modified) {
144+
modified = true;
145+
continue;
146+
}
147+
const catalogDep = handleDependency(
148+
"catalog:",
149+
deps!,
150+
name,
151+
version,
152+
catalogVersions,
153+
resolveCatalogVersion
154+
);
155+
deps = catalogDep.deps;
156+
if (catalogDep.modified) {
157+
modified = true;
158+
continue;
121159
}
122160
}
123161
};
124-
162+
125163
processDeps(pkg.dependencies);
126164
processDeps(pkg.devDependencies);
127165
processDeps(pkg.peerDependencies);
128166
processDeps(pkg.optionalDependencies);
129-
167+
130168
if (modified) {
131169
writeJSON(pkgPath, pkg);
132170
console.log(` ✅ Updated ${path.relative(rootDir, pkgPath)}`);
133171
}
134-
172+
135173
return modified;
136174
}
137175

138176
function main(): void {
139-
console.log('🔧 Preparing packages for publishing...\n');
140-
177+
console.log("🔧 Preparing packages for publishing...\n");
178+
141179
const workspacePackages = getWorkspacePackages();
142180
const catalogVersions = getCatalogVersions();
143-
181+
144182
console.log(`📦 Found ${workspacePackages.size} workspace packages`);
145-
console.log(`📚 Found ${Object.keys(catalogVersions).length} catalog entries\n`);
146-
183+
console.log(
184+
`📚 Found ${Object.keys(catalogVersions).length} catalog entries\n`
185+
);
186+
147187
let packagesModified = 0;
148-
188+
149189
for (const [name, info] of workspacePackages) {
150190
console.log(`Processing ${name}...`);
151191
if (processPackageJson(info.path, workspacePackages, catalogVersions)) {
152192
packagesModified++;
153193
}
154-
console.log('');
194+
console.log("");
155195
}
156-
196+
157197
console.log(`✅ Prepared ${packagesModified} packages for publishing`);
158198
console.log(`📁 Backups saved to ${path.relative(rootDir, BACKUP_DIR)}`);
159199
}
160200

161201
try {
162202
main();
163203
} catch (error) {
164-
console.error('❌ Error preparing packages:', error instanceof Error ? error.message : error);
204+
console.error(
205+
"❌ Error preparing packages:",
206+
error instanceof Error ? error.message : error
207+
);
165208
process.exit(1);
166-
}
209+
}

scripts/restore-packages.ts

Lines changed: 35 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -1,33 +1,36 @@
11
#!/usr/bin/env bun
22

3-
import fs from 'fs';
4-
import path from 'path';
3+
import fs from "fs";
4+
import path from "path";
55

6-
const rootDir = path.resolve(import.meta.dir, '..');
7-
const BACKUP_DIR = path.join(rootDir, '.package-backups');
6+
const rootDir = path.resolve(import.meta.dir, "..");
7+
const BACKUP_DIR = path.join(rootDir, ".package-backups");
88

99
function restorePackages(): void {
1010
if (!fs.existsSync(BACKUP_DIR)) {
11-
console.log('ℹ️ No backup directory found. Nothing to restore.');
11+
console.log("i No backup directory found. Nothing to restore.");
1212
return;
1313
}
14-
15-
console.log('🔄 Restoring original package.json files...\n');
16-
14+
15+
console.log("🔄 Restoring original package.json files...\n");
16+
1717
let restoredCount = 0;
18-
19-
function restoreFiles(dir: string, baseBackupPath: string = BACKUP_DIR): void {
18+
19+
function restoreFiles(
20+
dir: string,
21+
baseBackupPath: string = BACKUP_DIR
22+
): void {
2023
const entries = fs.readdirSync(dir, { withFileTypes: true });
21-
24+
2225
for (const entry of entries) {
2326
const backupPath = path.join(dir, entry.name);
24-
27+
2528
if (entry.isDirectory()) {
2629
restoreFiles(backupPath, baseBackupPath);
27-
} else if (entry.name === 'package.json') {
30+
} else if (entry.name === "package.json") {
2831
const relativePath = path.relative(baseBackupPath, backupPath);
2932
const originalPath = path.join(rootDir, relativePath);
30-
33+
3134
if (fs.existsSync(originalPath)) {
3235
fs.copyFileSync(backupPath, originalPath);
3336
console.log(` ✓ Restored ${relativePath}`);
@@ -36,35 +39,39 @@ function restorePackages(): void {
3639
}
3740
}
3841
}
39-
42+
4043
restoreFiles(BACKUP_DIR);
41-
44+
4245
console.log(`\n✅ Restored ${restoredCount} package.json files`);
4346
}
4447

4548
function cleanupBackups(): void {
46-
if (fs.existsSync(BACKUP_DIR)) {
47-
fs.rmSync(BACKUP_DIR, { recursive: true, force: true });
48-
console.log(`🧹 Cleaned up backup directory`);
49+
if (!fs.existsSync(BACKUP_DIR)) {
50+
return;
4951
}
52+
fs.rmSync(BACKUP_DIR, { recursive: true, force: true });
53+
console.log(`🧹 Cleaned up backup directory`);
5054
}
5155

5256
function main(): void {
5357
const args = process.argv.slice(2);
54-
const shouldCleanup = args.includes('--cleanup');
55-
58+
const shouldCleanup = args.includes("--cleanup");
59+
5660
try {
5761
restorePackages();
58-
59-
if (shouldCleanup) {
60-
cleanupBackups();
61-
} else {
62-
console.log('\nℹ️ Run with --cleanup flag to remove backup directory');
62+
if (!shouldCleanup) {
63+
console.log(
64+
"\n Run with --cleanup flag to remove backup directory"
65+
);
6366
}
67+
cleanupBackups();
6468
} catch (error) {
65-
console.error('❌ Error restoring packages:', error instanceof Error ? error.message : error);
69+
console.error(
70+
"❌ Error restoring packages:",
71+
error instanceof Error ? error.message : error
72+
);
6673
process.exit(1);
6774
}
6875
}
6976

70-
main();
77+
main();

0 commit comments

Comments
 (0)