-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathcommands.ts
222 lines (195 loc) · 6.27 KB
/
commands.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
// Copyright 2024 the JSR authors. MIT license.
import * as path from "node:path";
import * as fs from "node:fs";
import * as kl from "kolorist";
import {
exec,
fileExists,
getNewLineChars,
JsrPackage,
NpmPackage,
timeAgo,
} from "./utils";
import { Bun, getPkgManager, PkgManagerName, YarnBerry } from "./pkg_manager";
import { downloadDeno, getDenoDownloadUrl } from "./download";
import { getNpmPackageInfo, getPackageMeta } from "./api";
const NPMRC_FILE = ".npmrc";
const BUNFIG_FILE = "bunfig.toml";
const JSR_NPM_REGISTRY_URL = "https://npm.jsr.io";
const JSR_NPMRC = `@jsr:registry=${JSR_NPM_REGISTRY_URL}\n`;
const JSR_BUNFIG = `[install.scopes]\n"@jsr" = "${JSR_NPM_REGISTRY_URL}"\n`;
const JSR_YARN_BERRY_CONFIG_KEY = "npmScopes.jsr.npmRegistryServer";
async function wrapWithStatus(msg: string, fn: () => Promise<void>) {
process.stdout.write(msg + "...");
try {
await fn();
process.stdout.write(kl.green("ok") + "\n");
} catch (err) {
process.stdout.write(kl.red("error") + "\n");
throw err;
}
}
export async function setupNpmRc(dir: string) {
const npmRcPath = path.join(dir, NPMRC_FILE);
const msg = `Setting up ${NPMRC_FILE}`;
try {
let content = await fs.promises.readFile(npmRcPath, "utf-8");
if (!content.includes("@jsr:registry=")) {
const nl = getNewLineChars(content);
const spacer = (!content.endsWith(nl)) ? nl : "";
content += spacer + JSR_NPMRC;
await wrapWithStatus(msg, async () => {
await fs.promises.writeFile(npmRcPath, content);
});
}
} catch (err) {
if (err instanceof Error && (err as any).code === "ENOENT") {
await wrapWithStatus(msg, async () => {
await fs.promises.writeFile(npmRcPath, JSR_NPMRC);
});
} else {
throw err;
}
}
}
export async function setupBunfigToml(dir: string) {
const bunfigPath = path.join(dir, BUNFIG_FILE);
const msg = `Setting up ${BUNFIG_FILE}`;
try {
let content = await fs.promises.readFile(bunfigPath, "utf-8");
if (!/^"@jsr"\s+=/gm.test(content)) {
content += JSR_BUNFIG;
await wrapWithStatus(msg, async () => {
await fs.promises.writeFile(bunfigPath, content);
});
}
} catch (err) {
if (err instanceof Error && (err as any).code === "ENOENT") {
await wrapWithStatus(msg, async () => {
await fs.promises.writeFile(bunfigPath, JSR_BUNFIG);
});
} else {
throw err;
}
}
}
export interface BaseOptions {
pkgManagerName: PkgManagerName | null;
}
export interface InstallOptions extends BaseOptions {
mode: "dev" | "prod" | "optional";
global: boolean;
}
export async function install(
packages: Array<JsrPackage | NpmPackage>,
options: InstallOptions,
) {
const pkgManager = await getPkgManager(process.cwd(), options.pkgManagerName);
if (pkgManager instanceof Bun) {
// Bun doesn't support reading from .npmrc yet
await setupBunfigToml(pkgManager.cwd);
} else if (pkgManager instanceof YarnBerry) {
// Yarn v2+ does not read from .npmrc intentionally
// https://yarnpkg.com/migration/guide#update-your-configuration-to-the-new-settings
await pkgManager.setConfigValue(
JSR_YARN_BERRY_CONFIG_KEY,
JSR_NPM_REGISTRY_URL,
);
} else {
await setupNpmRc(pkgManager.cwd);
}
console.log(`Installing ${kl.cyan(packages.join(", "))}...`);
await pkgManager.install(packages, options);
}
export async function remove(
packages: Array<JsrPackage | NpmPackage>,
options: BaseOptions,
) {
const pkgManager = await getPkgManager(process.cwd(), options.pkgManagerName);
console.log(`Removing ${kl.cyan(packages.join(", "))}...`);
await pkgManager.remove(packages);
}
export interface PublishOptions {
binFolder: string;
publishArgs: string[];
}
async function getOrDownloadBinPath(binFolder: string) {
const info = await getDenoDownloadUrl();
const binPath = path.join(
binFolder,
info.version,
// Ensure each binary has their own folder to avoid overwriting it
// in case jsr gets added to a project as a dependency where
// developers use multiple OSes
process.platform,
process.platform === "win32" ? "deno.exe" : "deno",
);
// Check if deno executable is available, download it if not.
if (!(await fileExists(binPath))) {
// Clear folder first to get rid of old download artifacts
// to avoid taking up lots of disk space.
try {
await fs.promises.rm(binFolder, { recursive: true });
} catch (err) {
if (!(err instanceof Error) || (err as any).code !== "ENOENT") {
throw err;
}
}
await downloadDeno(binPath, info);
}
return binPath;
}
export async function publish(cwd: string, options: PublishOptions) {
const binPath = process.env.DENO_BIN_PATH ??
await getOrDownloadBinPath(options.binFolder);
// Ready to publish now!
const args = [
"publish",
"--unstable-bare-node-builtins",
"--unstable-sloppy-imports",
"--no-check",
...options.publishArgs,
];
await exec(binPath, args, cwd, {
...process.env,
DENO_DISABLE_PEDANTIC_NODE_WARNINGS: "true",
});
}
export async function runScript(
cwd: string,
script: string,
options: BaseOptions,
) {
const pkgManager = await getPkgManager(cwd, options.pkgManagerName);
await pkgManager.runScript(script);
}
export async function showPackageInfo(raw: string) {
const pkg = JsrPackage.from(raw);
const meta = await getPackageMeta(pkg);
if (pkg.version === null) {
if (meta.latest === undefined) {
throw new Error(`Missing latest version for ${pkg}`);
}
pkg.version = meta.latest!;
}
const versionCount = Object.keys(meta.versions).length;
const npmInfo = await getNpmPackageInfo(pkg);
const versionInfo = npmInfo.versions[pkg.version]!;
const time = npmInfo.time[pkg.version];
const publishTime = new Date(time).getTime();
console.log();
console.log(
kl.cyan(`@${pkg.scope}/${pkg.name}@${pkg.version}`) +
` | latest: ${kl.magenta(meta.latest ?? "-")} | versions: ${
kl.magenta(versionCount)
}`,
);
console.log(npmInfo.description);
console.log();
console.log(`npm tarball: ${kl.cyan(versionInfo.dist.tarball)}`);
console.log(`npm integrity: ${kl.cyan(versionInfo.dist.integrity)}`);
console.log();
console.log(
`published: ${kl.magenta(timeAgo(Date.now() - publishTime))}`,
);
}