Skip to content

Commit e19db78

Browse files
committed
feat(rari-npm): add initial support for npm
Also renames the workflows
1 parent 45f66b1 commit e19db78

15 files changed

+1184
-3
lines changed

.github/workflows/build_and_upload.yml .github/workflows/build-and-upload-binaries.yml

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
name: ship binaries
1+
name: build-and-upload-binaries
22

33
permissions:
44
contents: write

.github/workflows/publish-npm.yml

+13
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
name: publish-npm
2+
3+
on:
4+
workflow_run:
5+
workflows: [build-and-upload-binaries]
6+
types: [completed]
7+
8+
jobs:
9+
on-success:
10+
runs-on: ubuntu-latest
11+
if: ${{ github.event.workflow_run.conclusion == 'success' }}
12+
steps:
13+
- run: echo 'This would run npm publish.'

.release-please-manifest.json

+2-1
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
11
{
2-
".": "0.0.13"
2+
".": "0.0.13",
3+
"rari-npm": "0.0.13"
34
}

LICENSE

+3
Original file line numberDiff line numberDiff line change
@@ -3,3 +3,6 @@ See LICENSE.MPL-2.0 file for more information.
33

44
This project includes code from Comrak licensed under the BSD 2-Clause License.
55
See LICENSE.BSD-2-Clause file for more information.
6+
7+
This project includes code from vscode-ripgrep licensed under the MIT License.
8+
See LICENSE.MIT file for more information.

LICENSE.MIT

+13
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
vscode-ripgrep
2+
3+
Copyright (c) Microsoft Corporation
4+
5+
All rights reserved.
6+
7+
MIT License
8+
9+
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the ""Software""), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
10+
11+
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
12+
13+
THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

rari-npm/.gitignore

+2
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
node_modules
2+
bin

rari-npm/lib/download.js

+275
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,275 @@
1+
import { platform, tmpdir } from "os";
2+
import { getProxyForUrl } from "proxy-from-env";
3+
import * as https from "https";
4+
import { createWriteStream } from "fs";
5+
import { unlink, access, constants, mkdir, chmod } from "fs/promises";
6+
import path from "node:path";
7+
8+
import { x } from "tar";
9+
import extract from "extract-zip";
10+
11+
import * as packageJson from "../package.json" with { type: "json" };
12+
13+
const tmpDir = path.join(tmpdir(), `rari-cache-${packageJson.version}`);
14+
const isWindows = platform() === "win32";
15+
16+
const REPO = "mdn/rari";
17+
18+
/**
19+
* This function is adapted from vscode-ripgrep (https://github.com/microsoft/vscode-ripgrep)
20+
* Copyright (c) Microsoft, licensed under the MIT License
21+
*
22+
* @param {string} url
23+
*/
24+
function isGithubUrl(url) {
25+
return URL.parse(url)?.hostname === "api.github.com";
26+
}
27+
28+
/**
29+
* @param {string} path
30+
*/
31+
export async function exists(path) {
32+
try {
33+
await access(path, constants.F_OK);
34+
return true;
35+
} catch {
36+
return false;
37+
}
38+
}
39+
40+
/**
41+
* This function is adapted from vscode-ripgrep (https://github.com/microsoft/vscode-ripgrep)
42+
* Copyright (c) Microsoft, licensed under the MIT License
43+
*
44+
* @param {string} url
45+
* @param {import("fs").PathLike} dest
46+
* @param {any} opts
47+
*/
48+
export async function do_download(url, dest, opts) {
49+
const proxy = getProxyForUrl(URL.parse(url));
50+
if (proxy !== "") {
51+
const HttpsProxyAgent = await import("https-proxy-agent");
52+
opts = {
53+
...opts,
54+
agent: new HttpsProxyAgent.HttpsProxyAgent(proxy),
55+
proxy,
56+
};
57+
}
58+
59+
if (opts.headers && opts.headers.authorization && !isGithubUrl(url)) {
60+
delete opts.headers.authorization;
61+
}
62+
63+
return await new Promise((resolve, reject) => {
64+
console.log(`Download options: ${JSON.stringify(opts)}`);
65+
const outFile = createWriteStream(dest);
66+
67+
https
68+
.get(url, opts, (response) => {
69+
console.log("statusCode: " + response.statusCode);
70+
if (response.statusCode === 302 && response.headers.location) {
71+
console.log("Following redirect to: " + response.headers.location);
72+
return do_download(response.headers.location, dest, opts).then(
73+
resolve,
74+
reject,
75+
);
76+
} else if (response.statusCode !== 200) {
77+
reject(new Error("Download failed with " + response.statusCode));
78+
return;
79+
}
80+
81+
response.pipe(outFile);
82+
outFile.on("finish", () => {
83+
resolve(null);
84+
});
85+
})
86+
.on("error", async (err) => {
87+
await unlink(dest);
88+
reject(err);
89+
});
90+
});
91+
}
92+
93+
/**
94+
* This function is adapted from vscode-ripgrep (https://github.com/microsoft/vscode-ripgrep)
95+
* Copyright (c) Microsoft, licensed under the MIT License
96+
*
97+
* @param {string} _url
98+
* @param {any} opts
99+
*/
100+
function get(_url, opts) {
101+
console.log(`GET ${_url}`);
102+
103+
const proxy = getProxyForUrl(URL.parse(_url));
104+
if (proxy !== "") {
105+
var HttpsProxyAgent = require("https-proxy-agent");
106+
opts = {
107+
...opts,
108+
agent: new HttpsProxyAgent.HttpsProxyAgent(proxy),
109+
};
110+
}
111+
112+
return new Promise((resolve, reject) => {
113+
let result = "";
114+
https.get(_url, opts, (response) => {
115+
if (response.statusCode !== 200) {
116+
reject(new Error("Request failed: " + response.statusCode));
117+
}
118+
119+
response.on("data", (d) => {
120+
result += d.toString();
121+
});
122+
123+
response.on("end", () => {
124+
resolve(result);
125+
});
126+
127+
response.on("error", (e) => {
128+
reject(e);
129+
});
130+
});
131+
});
132+
}
133+
134+
/**
135+
* @param {string} repo
136+
* @param {string} tag
137+
*/
138+
function getApiUrl(repo, tag) {
139+
return `https://api.github.com/repos/${repo}/releases/tags/${tag}`;
140+
}
141+
142+
/**
143+
* This function is adapted from vscode-ripgrep (https://github.com/microsoft/vscode-ripgrep)
144+
* Copyright (c) Microsoft, licensed under the MIT License
145+
*
146+
* @param {{ force: boolean; token: string | undefined; version: string; }} opts
147+
* @param {string} assetName
148+
* @param {string} downloadFolder
149+
*/
150+
async function getAssetFromGithubApi(opts, assetName, downloadFolder) {
151+
const assetDownloadPath = path.join(downloadFolder, assetName);
152+
153+
// We can just use the cached binary
154+
if (!opts.force && (await exists(assetDownloadPath))) {
155+
console.log("Using cached download: " + assetDownloadPath);
156+
return assetDownloadPath;
157+
}
158+
159+
const downloadOpts = {
160+
headers: {
161+
"user-agent": "rari-npm",
162+
},
163+
};
164+
165+
if (opts.token) {
166+
downloadOpts.headers.authorization = `token ${opts.token}`;
167+
}
168+
169+
console.log(`Finding release for ${opts.version}`);
170+
const release = await get(getApiUrl(REPO, opts.version), downloadOpts);
171+
let jsonRelease;
172+
try {
173+
jsonRelease = JSON.parse(release);
174+
} catch (e) {
175+
throw new Error("Malformed API response: " + e.stack);
176+
}
177+
178+
if (!jsonRelease.assets) {
179+
throw new Error("Bad API response: " + JSON.stringify(release));
180+
}
181+
182+
const asset = jsonRelease.assets.find((a) => a.name === assetName);
183+
if (!asset) {
184+
throw new Error("Asset not found with name: " + assetName);
185+
}
186+
187+
console.log(`Downloading from ${asset.url}`);
188+
console.log(`Downloading to ${assetDownloadPath}`);
189+
190+
downloadOpts.headers.accept = "application/octet-stream";
191+
await do_download(asset.url, assetDownloadPath, downloadOpts);
192+
}
193+
194+
/**
195+
* @param {string} packedFilePath
196+
* @param {string} destinationDir
197+
*/
198+
async function unpack(packedFilePath, destinationDir) {
199+
const rari_name = "rari";
200+
if (isWindows) {
201+
await extract(packedFilePath, { dir: destinationDir });
202+
} else {
203+
await x({ cwd: destinationDir, file: packedFilePath });
204+
}
205+
206+
const expectedName = path.join(destinationDir, rari_name);
207+
if (await exists(expectedName)) {
208+
return expectedName;
209+
}
210+
211+
if (await exists(expectedName + ".exe")) {
212+
return expectedName + ".exe";
213+
}
214+
215+
throw new Error(
216+
`Expecting ${rari_name} or ${rari_name}.exe unzipped into ${destinationDir}, didn't find one.`,
217+
);
218+
}
219+
220+
/**
221+
* This function is adapted from vscode-ripgrep (https://github.com/microsoft/vscode-ripgrep)
222+
* Copyright (c) Microsoft, licensed under the MIT License
223+
*
224+
* @param {{
225+
version: string;
226+
token: string | undefined;
227+
target: string;
228+
destDir: string;
229+
force: boolean;
230+
}} options
231+
*/
232+
export async function download(options) {
233+
if (!options.version) {
234+
return Promise.reject(new Error("Missing version"));
235+
}
236+
237+
if (!options.target) {
238+
return Promise.reject(new Error("Missing target"));
239+
}
240+
241+
const extension = isWindows ? ".zip" : ".tar.gz";
242+
const assetName = ["rari", options.target].join("-") + extension;
243+
244+
if (!(await exists(tmpDir))) {
245+
await mkdir(tmpDir);
246+
}
247+
248+
const assetDownloadPath = path.join(tmpDir, assetName);
249+
try {
250+
await getAssetFromGithubApi(options, assetName, tmpDir);
251+
} catch (e) {
252+
console.log("Deleting invalid download cache");
253+
try {
254+
await unlink(assetDownloadPath);
255+
} catch (e) {}
256+
257+
throw e;
258+
}
259+
260+
console.log(`Unpacking to ${options.destDir}`);
261+
try {
262+
const destinationPath = await unpack(assetDownloadPath, options.destDir);
263+
if (!isWindows) {
264+
await chmod(destinationPath, "755");
265+
}
266+
} catch (e) {
267+
console.log("Deleting invalid download");
268+
269+
try {
270+
await unlink(assetDownloadPath);
271+
} catch (e) {}
272+
273+
throw e;
274+
}
275+
}

rari-npm/lib/index.d.ts

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
export declare const rariBin: string;

rari-npm/lib/index.js

+6
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
import { join } from "node:path";
2+
3+
export const rariBin = join(
4+
import.meta.dirname,
5+
`../bin/rari${process.platform === "win32" ? ".exe" : ""}`,
6+
);

0 commit comments

Comments
 (0)