@foundry-rs/chisel 1.4.4-nightly.20251028.9273fd8 → 1.4.4-nightly.20251028.c2a3538

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.
Files changed (3) hide show
  1. package/bin.mjs +117 -0
  2. package/package.json +12 -9
  3. package/postinstall.mjs +265 -0
package/bin.mjs ADDED
@@ -0,0 +1,117 @@
1
+ import { BINARY_NAME, colors, KNOWN_TOOLS, PLATFORM_SPECIFIC_PACKAGE_NAME, resolveTargetTool } from './postinstall.mjs'
2
+ import * as NodeChildProcess from 'node:child_process'
3
+ import * as NodeFS from 'node:fs'
4
+ import * as NodeModule from 'node:module'
5
+ import * as NodePath from 'node:path'
6
+ import { fileURLToPath } from 'node:url'
7
+
8
+ /**
9
+ * @typedef {import('./postinstall.mjs').Tool} Tool
10
+ */
11
+
12
+ const require = NodeModule.createRequire(import.meta.url)
13
+ const __dirname = NodePath.dirname(fileURLToPath(import.meta.url))
14
+
15
+ const targetTool = resolveTool()
16
+ process.env.TARGET_TOOL ??= targetTool
17
+
18
+ const binaryName = BINARY_NAME(targetTool)
19
+ const platformPackage = PLATFORM_SPECIFIC_PACKAGE_NAME(targetTool)
20
+
21
+ if (!platformPackage) {
22
+ console.error(colors.red, 'Platform not supported!')
23
+ console.error(colors.reset)
24
+ console.error(colors.yellow, `Platform: ${process.platform}, Architecture: ${process.arch}`)
25
+ console.error(colors.reset)
26
+ process.exit(1)
27
+ }
28
+
29
+ NodeChildProcess.spawn(selectBinaryPath(), process.argv.slice(2), { stdio: 'inherit' })
30
+
31
+ /**
32
+ * Determines which tool wrapper is executing.
33
+ * @returns {Tool}
34
+ */
35
+ function resolveTool() {
36
+ const candidates = [
37
+ process.env.TARGET_TOOL,
38
+ toolFromPackageName(process.env.npm_package_name),
39
+ toolFromLocalPackage(),
40
+ toolFromPath()
41
+ ]
42
+
43
+ for (const candidate of candidates) {
44
+ if (!candidate) continue
45
+ try {
46
+ return resolveTargetTool(candidate)
47
+ } catch {
48
+ // try next
49
+ }
50
+ }
51
+
52
+ throw new Error('TARGET_TOOL must be set to one of: ' + KNOWN_TOOLS.join(', '))
53
+ }
54
+
55
+ /**
56
+ * Attempts to read the tool name from the nearest package.json.
57
+ * @returns {Tool | undefined}
58
+ */
59
+ function toolFromLocalPackage() {
60
+ try {
61
+ const packageJsonPath = NodePath.join(__dirname, 'package.json')
62
+ if (!NodeFS.existsSync(packageJsonPath)) return undefined
63
+ const pkg = require(packageJsonPath)
64
+ return toolFromPackageName(pkg?.name)
65
+ } catch {
66
+ return undefined
67
+ }
68
+ }
69
+
70
+ /**
71
+ * Extracts the tool name from an @foundry-rs scoped package identifier.
72
+ * @param {unknown} name
73
+ * @returns {Tool | undefined}
74
+ */
75
+ function toolFromPackageName(name) {
76
+ if (typeof name !== 'string') return undefined
77
+ const match = name.match(/^@foundry-rs\/(forge|cast|anvil|chisel)(?:$|-)/)
78
+ return match ? /** @type {Tool} */ (match[1]) : undefined
79
+ }
80
+
81
+ /**
82
+ * Walks up the directory tree to infer the tool name from the folder structure.
83
+ * @returns {Tool | undefined}
84
+ */
85
+ function toolFromPath() {
86
+ const segments = NodePath.resolve(__dirname).split(NodePath.sep)
87
+ for (let i = segments.length - 1; i >= 0; i--) {
88
+ const candidate = segments[i]
89
+ if (isTool(candidate)) return candidate
90
+ }
91
+ return undefined
92
+ }
93
+
94
+ /**
95
+ * Type guard verifying a candidate string is a known tool.
96
+ * @param {string | undefined} candidate
97
+ * @returns {candidate is Tool}
98
+ */
99
+ function isTool(candidate) {
100
+ if (typeof candidate !== 'string') return false
101
+ return KNOWN_TOOLS.includes(/** @type {Tool} */ (candidate))
102
+ }
103
+
104
+ /**
105
+ * Determines the executable file path for the current platform.
106
+ * @returns {string}
107
+ */
108
+ function selectBinaryPath() {
109
+ try {
110
+ const candidate = require.resolve(`${platformPackage}/bin/${binaryName}`)
111
+ if (NodeFS.existsSync(candidate)) return candidate
112
+ } catch {
113
+ // fall through to dist/ binary
114
+ }
115
+
116
+ return NodePath.join(__dirname, '..', 'dist', binaryName)
117
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@foundry-rs/chisel",
3
- "version": "1.4.4-nightly.20251028.9273fd8",
3
+ "version": "1.4.4-nightly.20251028.c2a3538",
4
4
  "type": "module",
5
5
  "homepage": "https://getfoundry.sh/chisel",
6
6
  "description": "Chisel is a fast, utilitarian, and verbose Solidity REPL",
@@ -8,18 +8,18 @@
8
8
  "chisel": "./bin.mjs"
9
9
  },
10
10
  "files": [
11
- "bin",
12
- "dist"
11
+ "bin.mjs",
12
+ "postinstall.mjs"
13
13
  ],
14
14
  "scripts": {
15
- "postinstall": "node ./dist/install.mjs"
15
+ "postinstall": "node ./postinstall.mjs"
16
16
  },
17
17
  "optionalDependencies": {
18
- "@foundry-rs/chisel-darwin-arm64": "1.4.4-nightly.20251028.9273fd8",
19
- "@foundry-rs/chisel-darwin-amd64": "1.4.4-nightly.20251028.9273fd8",
20
- "@foundry-rs/chisel-linux-arm64": "1.4.4-nightly.20251028.9273fd8",
21
- "@foundry-rs/chisel-linux-amd64": "1.4.4-nightly.20251028.9273fd8",
22
- "@foundry-rs/chisel-win32-amd64": "1.4.4-nightly.20251028.9273fd8"
18
+ "@foundry-rs/chisel-darwin-arm64": "1.4.4-nightly.20251028.c2a3538",
19
+ "@foundry-rs/chisel-darwin-amd64": "1.4.4-nightly.20251028.c2a3538",
20
+ "@foundry-rs/chisel-linux-arm64": "1.4.4-nightly.20251028.c2a3538",
21
+ "@foundry-rs/chisel-linux-amd64": "1.4.4-nightly.20251028.c2a3538",
22
+ "@foundry-rs/chisel-win32-amd64": "1.4.4-nightly.20251028.c2a3538"
23
23
  },
24
24
  "publishConfig": {
25
25
  "access": "public",
@@ -30,5 +30,8 @@
30
30
  "repository": {
31
31
  "directory": "npm",
32
32
  "url": "https://github.com/foundry-rs/foundry"
33
+ },
34
+ "imports": {
35
+ "#const.mjs": "./postinstall.mjs"
33
36
  }
34
37
  }
@@ -0,0 +1,265 @@
1
+ // src/install.mjs
2
+ import * as NodeCrypto from "node:crypto";
3
+ import * as NodeFS from "node:fs";
4
+ import * as NodeHttp from "node:http";
5
+ import * as NodeHttps from "node:https";
6
+ import * as NodeModule from "node:module";
7
+ import * as NodePath2 from "node:path";
8
+ import { fileURLToPath } from "node:url";
9
+ import * as NodeZlib from "node:zlib";
10
+
11
+ // src/const.mjs
12
+ import * as NodePath from "node:path";
13
+ var KNOWN_TOOLS = Object.freeze(["forge", "cast", "anvil", "chisel"]);
14
+ var TOOL_SET = new Set(KNOWN_TOOLS);
15
+ function resolveTargetTool(raw = process.env.TARGET_TOOL) {
16
+ const value = typeof raw === "string" ? raw.trim() : "";
17
+ if (!value)
18
+ throw new Error("TARGET_TOOL must be set to one of: " + KNOWN_TOOLS.join(", "));
19
+ if (value !== NodePath.basename(value) || value.includes("..") || value.includes("/") || value.includes("\\"))
20
+ throw new Error("TARGET_TOOL contains invalid path segments");
21
+ if (!TOOL_SET.has(value))
22
+ throw new Error(`TARGET_TOOL "${value}" is not supported. Expected: ${KNOWN_TOOLS.join(", ")}`);
23
+ return value;
24
+ }
25
+ function getRegistryUrl() {
26
+ return process.env.npm_config_registry || process.env.REGISTRY_URL || "https://registry.npmjs.org";
27
+ }
28
+ var BINARY_DISTRIBUTION_PACKAGES = (tool) => ({
29
+ darwin: {
30
+ x64: `@foundry-rs/${tool}-darwin-amd64`,
31
+ arm64: `@foundry-rs/${tool}-darwin-arm64`
32
+ },
33
+ linux: {
34
+ x64: `@foundry-rs/${tool}-linux-amd64`,
35
+ arm64: `@foundry-rs/${tool}-linux-arm64`
36
+ },
37
+ win32: {
38
+ x64: `@foundry-rs/${tool}-win32-amd64`
39
+ }
40
+ });
41
+ var BINARY_NAME = (tool) => process.platform === "win32" ? `${tool}.exe` : tool;
42
+ var PLATFORM_SPECIFIC_PACKAGE_NAME = (tool) => {
43
+ const platformPackages = BINARY_DISTRIBUTION_PACKAGES(tool)[process.platform];
44
+ if (!platformPackages)
45
+ return;
46
+ return platformPackages?.[process.arch];
47
+ };
48
+ var colors = {
49
+ red: "\x1B[31m",
50
+ green: "\x1B[32m",
51
+ yellow: "\x1B[33m",
52
+ blue: "\x1B[34m",
53
+ magenta: "\x1B[35m",
54
+ cyan: "\x1B[36m",
55
+ white: "\x1B[37m",
56
+ reset: "\x1B[0m"
57
+ };
58
+
59
+ // src/install.mjs
60
+ var __dirname2 = NodePath2.dirname(fileURLToPath(import.meta.url));
61
+ var targetTool = resolveTargetTool();
62
+ var binaryName = BINARY_NAME(targetTool);
63
+ var fallbackBinaryPath = NodePath2.join(__dirname2, binaryName);
64
+ var platformSpecificPackageName = PLATFORM_SPECIFIC_PACKAGE_NAME(targetTool);
65
+ var expectedTarEntryPath = `package/bin/${binaryName}`;
66
+ if (NodePath2.relative(__dirname2, fallbackBinaryPath).startsWith(".."))
67
+ throw new Error("Resolved binary path escapes package directory");
68
+ if (!platformSpecificPackageName)
69
+ throw new Error("Platform not supported!");
70
+ var require2 = NodeModule.createRequire(import.meta.url);
71
+ function ensureSecureUrl(urlString, purpose) {
72
+ try {
73
+ const url = new URL(urlString);
74
+ if (url.protocol === "http:") {
75
+ const allowInsecure = process.env.ALLOW_INSECURE_REGISTRY === "true";
76
+ if (!["localhost", "127.0.0.1", "::1"].includes(url.hostname) && !allowInsecure) {
77
+ throw new Error(`Refusing to use insecure HTTP for ${purpose}: ${urlString}. ` + `Set ALLOW_INSECURE_REGISTRY=true to override (not recommended).`);
78
+ }
79
+ }
80
+ } catch {}
81
+ }
82
+ var MAX_REDIRECTS = 10;
83
+ var REQUEST_TIMEOUT = 30000;
84
+ var MAX_METADATA_BYTES = 5 * 1024 * 1024;
85
+ var MAX_TARBALL_BYTES = 200 * 1024 * 1024;
86
+ var MAX_BINARY_BYTES = 500 * 1024 * 1024;
87
+ function makeRequest(url, options = {}) {
88
+ const {
89
+ parentSignal,
90
+ redirectDepth = 0,
91
+ visited = new Set,
92
+ maxBytes,
93
+ collect = true,
94
+ onChunk
95
+ } = options;
96
+ if (redirectDepth > MAX_REDIRECTS)
97
+ throw new Error("Maximum redirect depth exceeded");
98
+ if (visited.has(url))
99
+ throw new Error("Circular redirect detected");
100
+ visited.add(url);
101
+ ensureSecureUrl(url, "HTTP request");
102
+ const controller = new AbortController;
103
+ const timer = setTimeout(() => controller.abort(), REQUEST_TIMEOUT);
104
+ const signal = parentSignal ? AbortSignal.any([parentSignal, controller.signal]) : controller.signal;
105
+ return new Promise((resolve, reject) => {
106
+ const client = url.startsWith("https:") ? NodeHttps : NodeHttp;
107
+ const request = client.get(url, { signal }, (response) => {
108
+ const finish = (error, value = undefined) => {
109
+ clearTimeout(timer);
110
+ if (error)
111
+ reject(error);
112
+ else
113
+ resolve(value);
114
+ };
115
+ if (response?.statusCode && response.statusCode >= 200 && response.statusCode < 300) {
116
+ let totalBytes = 0;
117
+ const chunks = collect ? [] : undefined;
118
+ response.on("data", (chunk) => {
119
+ totalBytes += chunk.length;
120
+ if (maxBytes && totalBytes > maxBytes) {
121
+ response.destroy(new Error("Response exceeded maximum allowed size"));
122
+ return;
123
+ }
124
+ if (chunks)
125
+ chunks.push(chunk);
126
+ if (onChunk) {
127
+ try {
128
+ onChunk(chunk, response);
129
+ } catch (error) {
130
+ response.destroy(error instanceof Error ? error : new Error(`Error occurred: ${error}`));
131
+ }
132
+ }
133
+ });
134
+ response.on("end", () => {
135
+ finish(null, chunks ? Buffer.concat(chunks) : undefined);
136
+ });
137
+ response.on("error", finish);
138
+ } else if (response?.statusCode && response.statusCode >= 300 && response.statusCode < 400 && response.headers.location) {
139
+ clearTimeout(timer);
140
+ const nextUrl = new URL(response.headers.location, url).href;
141
+ return makeRequest(nextUrl, {
142
+ parentSignal: signal,
143
+ redirectDepth: redirectDepth + 1,
144
+ visited,
145
+ maxBytes,
146
+ collect,
147
+ onChunk
148
+ }).then(resolve, reject);
149
+ } else {
150
+ finish(new Error(`Package registry responded with status code ${response?.statusCode ?? "(none)"} when downloading the package.`));
151
+ }
152
+ });
153
+ request.on("error", (error) => {
154
+ clearTimeout(timer);
155
+ reject(error);
156
+ });
157
+ });
158
+ }
159
+ function extractFileFromTarball(tarballBuffer, filepath) {
160
+ let offset = 0;
161
+ while (offset < tarballBuffer.length) {
162
+ const header = tarballBuffer.subarray(offset, offset + 512);
163
+ offset += 512;
164
+ const fileName = header.toString("utf-8", 0, 100).replace(/\0.*/g, "");
165
+ const fileSize = Number.parseInt(header.toString("utf-8", 124, 136).replace(/\0.*/g, ""), 8);
166
+ if (fileName === filepath) {
167
+ if (!Number.isFinite(fileSize) || Number.isNaN(fileSize) || fileSize < 0)
168
+ throw new Error(`Invalid size for ${filepath} in tarball`);
169
+ if (fileSize > MAX_BINARY_BYTES)
170
+ throw new Error(`Binary size for ${filepath} exceeds maximum allowed threshold`);
171
+ return tarballBuffer.subarray(offset, offset + fileSize);
172
+ }
173
+ offset = offset + fileSize + 511 & ~511;
174
+ }
175
+ throw new Error(`File ${filepath} not found in tarball`);
176
+ }
177
+ async function downloadBinaryFromRegistry() {
178
+ if (!platformSpecificPackageName)
179
+ throw new Error("Platform-specific package name is not defined");
180
+ const registryUrl = getRegistryUrl().replace(/\/$/, "");
181
+ ensureSecureUrl(registryUrl, "registry URL");
182
+ const encodedName = platformSpecificPackageName.startsWith("@") ? encodeURIComponent(platformSpecificPackageName) : platformSpecificPackageName;
183
+ let desiredVersion;
184
+ try {
185
+ const pkgJsonPath = NodePath2.join(__dirname2, "..", "package.json");
186
+ const pkgJson = JSON.parse(NodeFS.readFileSync(pkgJsonPath, "utf8"));
187
+ desiredVersion = pkgJson?.optionalDependencies[platformSpecificPackageName] || pkgJson?.version;
188
+ } catch {}
189
+ const metaUrl = `${registryUrl}/${encodedName}`;
190
+ const metaBuffer = await makeRequest(metaUrl, { maxBytes: MAX_METADATA_BYTES });
191
+ if (!metaBuffer)
192
+ throw new Error("Failed to download package metadata");
193
+ const metadata = JSON.parse(metaBuffer.toString("utf8"));
194
+ const version = desiredVersion || metadata?.["dist-tags"]?.latest;
195
+ const versionMeta = metadata?.versions?.[version];
196
+ const dist = versionMeta?.dist;
197
+ if (!dist?.tarball) {
198
+ throw new Error(`Could not find tarball for ${platformSpecificPackageName}@${version} from ${metaUrl}`);
199
+ }
200
+ ensureSecureUrl(dist.tarball, "tarball URL");
201
+ console.info(colors.green, `Downloading binary from:
202
+ `, dist.tarball, `
203
+ `, colors.reset);
204
+ const integrity = typeof dist.integrity === "string" ? dist.integrity : "";
205
+ const sriMatch = integrity.match(/^([a-z0-9]+)-([A-Za-z0-9+/=]+)$/i);
206
+ const allowedSRIAlgorithms = new Set(["sha512", "sha256", "sha1"]);
207
+ const sriAlgo = sriMatch && allowedSRIAlgorithms.has(sriMatch[1].toLowerCase()) ? sriMatch[1].toLowerCase() : undefined;
208
+ const expectedSri = sriAlgo ? sriMatch?.[2] : undefined;
209
+ const sriHasher = sriAlgo ? NodeCrypto.createHash(sriAlgo) : undefined;
210
+ const expectedSha1Hex = typeof dist.shasum === "string" && dist.shasum.length === 40 ? dist.shasum.toLowerCase() : undefined;
211
+ const sha1Hasher = expectedSha1Hex ? NodeCrypto.createHash("sha1") : undefined;
212
+ const tarballDownloadBuffer = await makeRequest(dist.tarball, {
213
+ maxBytes: MAX_TARBALL_BYTES,
214
+ onChunk: (chunk) => {
215
+ sriHasher?.update(chunk);
216
+ sha1Hasher?.update(chunk);
217
+ }
218
+ });
219
+ if (!tarballDownloadBuffer)
220
+ throw new Error("Failed to download tarball contents");
221
+ let verified = false;
222
+ if (sriHasher && expectedSri) {
223
+ const actual = sriHasher.digest("base64");
224
+ if (expectedSri !== actual) {
225
+ throw new Error(`Downloaded tarball failed integrity check (${sriAlgo} mismatch)`);
226
+ }
227
+ verified = true;
228
+ }
229
+ if (!verified && sha1Hasher && expectedSha1Hex) {
230
+ const actualSha1Hex = sha1Hasher.digest("hex");
231
+ if (expectedSha1Hex !== actualSha1Hex) {
232
+ throw new Error("Downloaded tarball failed integrity check (sha1 shasum mismatch)");
233
+ }
234
+ verified = true;
235
+ }
236
+ if (!verified) {
237
+ const allowNoIntegrity = process.env.ALLOW_NO_INTEGRITY === "true" || process.env.ALLOW_UNVERIFIED_TARBALL === "true";
238
+ if (!allowNoIntegrity) {
239
+ throw new Error("No integrity metadata found for downloaded tarball. " + "Set ALLOW_NO_INTEGRITY=true to bypass (not recommended).");
240
+ }
241
+ console.warn(colors.yellow, "Warning: proceeding without integrity verification (explicitly allowed).", colors.reset);
242
+ }
243
+ const tarballBuffer = NodeZlib.gunzipSync(tarballDownloadBuffer);
244
+ NodeFS.writeFileSync(fallbackBinaryPath, extractFileFromTarball(tarballBuffer, expectedTarEntryPath), { mode: 493 });
245
+ }
246
+ function isPlatformSpecificPackageInstalled() {
247
+ try {
248
+ require2.resolve(`${platformSpecificPackageName}/bin/${binaryName}`);
249
+ return true;
250
+ } catch {
251
+ return false;
252
+ }
253
+ }
254
+ if (!isPlatformSpecificPackageInstalled()) {
255
+ console.log("Platform specific package not found. Will manually download binary.");
256
+ downloadBinaryFromRegistry().catch((error) => {
257
+ console.error(colors.red, "Failed to download binary:", error, colors.reset);
258
+ process.exitCode = 1;
259
+ });
260
+ } else {
261
+ console.log("Platform specific package already installed. Skipping manual download.");
262
+ }
263
+ export {
264
+ makeRequest
265
+ };