mvp-ai's picture
download
raw
8.82 kB
// Copyright (c) 2026 the Zuke contributors
// SPDX-License-Identifier: MIT
/**
* Small utilities shared across core modules. This module is **internal**: it is
* not an entrypoint, and only the few helpers `mod.ts` names one by one
* (`defaultReadEnv`, `sha256Hex`, `readBytesBounded`) are public API — each
* because a wrapper package needed it and may depend on core alone. It exists to consolidate helpers that were previously copy-pasted per
* module (env reads, error-message extraction, a delay, a SHA-256 hex digest,
* the `NotFound → null` filesystem readers, the mkdir-parent writers, and a
* timeout wrapper) so the copies can't drift out of sync.
*
* @module
*/
/**
* Read an environment variable, tolerating a denied `--allow-env` permission by
* returning `undefined` rather than throwing. The default env reader every
* command uses when the caller doesn't inject one.
*/
export function defaultReadEnv(name: string): string | undefined {
try {
return Deno.env.get(name);
} catch {
return undefined;
}
}
/**
* Whether a forward-slashed path is already absolute — a leading `/` (POSIX,
* and a UNC share) or a `C:`-style drive letter. The one implementation of the
* test: a path composer that joins an already-absolute path onto a base
* produces something that exists nowhere, which is a silent empty result rather
* than an error.
*/
export function isAbsolutePath(slashed: string): boolean {
return slashed.startsWith("/") || /^[A-Za-z]:/.test(slashed);
}
/**
* Whether an environment variable is set to an "on" value.
*
* Unset and empty mean off, as do the conventional negatives — case- and
* whitespace-insensitively, so `FALSE` cannot mean the opposite of `false`.
* Anything else counts as on: an environment flag someone exported as `yes`,
* `on` or `please` means they want it, and refusing to guess would be a
* silent no.
*
* Deliberately not `params.ts`'s `parseBoolean`, which throws on a value it
* does not recognise. That is right for a typed build parameter, where a typo
* should be reported, and wrong for an environment flag, where an unfamiliar
* value still says the variable was set on purpose.
*/
export function envFlag(value: string | undefined): boolean {
if (value === undefined) return false;
const normalised = value.trim().toLowerCase();
if (normalised === "") return false;
return normalised !== "false" && normalised !== "0" && normalised !== "no";
}
/** The message of an `Error`, or the `String(...)` form of any other value. */
export function messageOf(value: unknown): string {
return value instanceof Error ? value.message : String(value);
}
/** Resolve after `ms` milliseconds (a `setTimeout`-backed sleep). */
export function delay(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
/** The CRC-32 lookup table (reflected polynomial `0xedb88320`). */
const CRC_TABLE = Uint32Array.from({ length: 256 }, (_, n) => {
let c = n;
for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
return c >>> 0;
});
/** The CRC-32 of `data` — what zip headers and xz block checks carry. */
export function crc32(data: Uint8Array): number {
let c = 0xffffffff;
for (const byte of data) c = CRC_TABLE[(c ^ byte) & 0xff] ^ (c >>> 8);
return (c ^ 0xffffffff) >>> 0;
}
/** Shared encoder for {@link sha256Hex} (a `TextEncoder` is stateless and reusable). */
const encoder = new TextEncoder();
/**
* The SHA-256 digest of `data` — a UTF-8 string or raw bytes — as a lowercase
* hex string.
*
* Bytes are copied into a fresh `ArrayBuffer`-backed view so the digest input
* type is unambiguous whatever buffer the source view sits on (e.g. a
* `SharedArrayBuffer`).
*/
export async function sha256Hex(data: string | Uint8Array): Promise<string> {
const bytes = typeof data === "string"
? encoder.encode(data)
: new Uint8Array(data);
const digest = await crypto.subtle.digest("SHA-256", bytes);
return Array.from(
new Uint8Array(digest),
(b) => b.toString(16).padStart(2, "0"),
).join("");
}
/** Read a file's bytes, or `null` when it does not exist. */
export async function readFileOrNull(
path: string,
): Promise<Uint8Array | null> {
try {
return await Deno.readFile(path);
} catch (error) {
if (error instanceof Deno.errors.NotFound) return null;
throw error;
}
}
/** Read a file's text, or `null` when it does not exist. */
export async function readTextOrNull(path: string): Promise<string | null> {
try {
return await Deno.readTextFile(path);
} catch (error) {
if (error instanceof Deno.errors.NotFound) return null;
throw error;
}
}
/**
* Stat a path, or `null` when it does not exist. `Deno.stat`, not `lstat`, so a
* symlink to an existing file counts as present — which is what an installed
* `bin` symlink needs.
*/
export async function statOrNull(path: string): Promise<Deno.FileInfo | null> {
try {
return await Deno.stat(path);
} catch (error) {
if (error instanceof Deno.errors.NotFound) return null;
throw error;
}
}
/**
* Stat a path *without* following a final symlink, or `null` when it does not
* exist. The counterpart to {@link statOrNull}: this describes the link itself,
* which is what a guard against writing *through* a link needs — `statOrNull`
* would report the target and so answer the wrong question.
*/
export async function lstatOrNull(path: string): Promise<Deno.FileInfo | null> {
try {
return await Deno.lstat(path);
} catch (error) {
if (error instanceof Deno.errors.NotFound) return null;
throw error;
}
}
/**
* Read `body` into memory, or return `null` once it exceeds `limit` bytes.
*
* Reads incrementally and abandons the stream at the cap, so an oversized
* stream — a chunked HTTP body that declares no `content-length`, or a small
* archive that decompresses to gigabytes — is never buffered whole just to be
* rejected. A `null` body reads as empty.
*/
export async function readBytesBounded(
body: ReadableStream<Uint8Array> | null,
limit: number,
): Promise<Uint8Array | null> {
if (body === null) return new Uint8Array(0);
const reader = body.getReader();
const chunks: Uint8Array[] = [];
let total = 0;
while (true) {
const { done, value } = await reader.read();
if (done) break;
total += value.byteLength;
if (total > limit) {
await reader.cancel();
return null;
}
chunks.push(value);
}
const joined = new Uint8Array(total);
let offset = 0;
for (const chunk of chunks) {
joined.set(chunk, offset);
offset += chunk.byteLength;
}
return joined;
}
/**
* The parent directory of a `/`- or `\`-separated path, or `null` when the path
* has no parent to create (a bare name, or a root-level entry).
*/
function parentOf(path: string): string | null {
const slashed = path.replace(/\\/g, "/");
const slash = slashed.lastIndexOf("/");
return slash > 0 ? path.slice(0, slash) : null;
}
/** Write text to `path`, creating its parent directory first. */
export async function writeTextEnsuringDir(
path: string,
content: string,
): Promise<void> {
const parent = parentOf(path);
if (parent !== null) await Deno.mkdir(parent, { recursive: true });
await Deno.writeTextFile(path, content);
}
/**
* Write bytes to `path`, creating its parent directory first. `mode` sets the
* file's permission bits where the platform has them (Windows ignores it).
*/
export async function writeFileEnsuringDir(
path: string,
bytes: Uint8Array,
mode?: number,
): Promise<void> {
const parent = parentOf(path);
if (parent !== null) await Deno.mkdir(parent, { recursive: true });
await Deno.writeFile(path, bytes, { mode });
}
/**
* Run `fn`, rejecting if it takes longer than `timeoutMs` (`undefined` → no
* bound, so `fn` runs to completion). On a timeout the work keeps running in the
* background but is orphaned — only the returned promise settles (with a
* `timed out after <ms>ms` error).
*/
export function runWithTimeout(
fn: () => unknown,
timeoutMs: number | undefined,
): Promise<void> {
// `.then(fn)` awaits a returned thenable (so the timeout still bounds an
// async body); the second `.then` discards the value — a body's return is
// ignored (see `TargetFn`).
const result = Promise.resolve().then(fn).then(() => undefined);
if (timeoutMs === undefined) return result;
return new Promise<void>((resolve, reject) => {
const timer = setTimeout(
() => reject(new Error(`timed out after ${timeoutMs}ms`)),
timeoutMs,
);
result.then(
() => {
clearTimeout(timer);
resolve();
},
(error) => {
clearTimeout(timer);
reject(error);
},
);
});
}

Xet Storage Details

Size:
8.82 kB
·
Xet hash:
db164c35598ae53553f9268c88a625b80590b8c3cbb28a349e1cce5cfba7a08c

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.