@oh-my-pi-zen/pi-utils 16.3.6-zen.1
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.
- package/CHANGELOG.md +245 -0
- package/README.md +36 -0
- package/dist/types/abortable.d.ts +32 -0
- package/dist/types/async.d.ts +6 -0
- package/dist/types/binary.d.ts +17 -0
- package/dist/types/cli.d.ts +117 -0
- package/dist/types/color.d.ts +102 -0
- package/dist/types/dirs.d.ts +260 -0
- package/dist/types/env.d.ts +74 -0
- package/dist/types/fetch-retry.d.ts +94 -0
- package/dist/types/format.d.ts +37 -0
- package/dist/types/frontmatter.d.ts +25 -0
- package/dist/types/fs-error.d.ts +31 -0
- package/dist/types/glob.d.ts +28 -0
- package/dist/types/index.d.ts +35 -0
- package/dist/types/json-parse.d.ts +48 -0
- package/dist/types/json.d.ts +4 -0
- package/dist/types/logger.d.ts +83 -0
- package/dist/types/loop-phase.d.ts +10 -0
- package/dist/types/mermaid-ascii.d.ts +11 -0
- package/dist/types/mime.d.ts +29 -0
- package/dist/types/module-timer.d.ts +1 -0
- package/dist/types/path-tree.d.ts +76 -0
- package/dist/types/path.d.ts +2 -0
- package/dist/types/peek-file.d.ts +29 -0
- package/dist/types/postmortem.d.ts +37 -0
- package/dist/types/procmgr.d.ts +29 -0
- package/dist/types/prompt.d.ts +18 -0
- package/dist/types/ptree.d.ts +108 -0
- package/dist/types/ring.d.ts +93 -0
- package/dist/types/runtime-install.d.ts +68 -0
- package/dist/types/sanitize-text.d.ts +29 -0
- package/dist/types/snowflake.d.ts +25 -0
- package/dist/types/stream.d.ts +68 -0
- package/dist/types/tab-spacing.d.ts +24 -0
- package/dist/types/temp.d.ts +17 -0
- package/dist/types/timing-buffer.d.ts +22 -0
- package/dist/types/tls-fetch.d.ts +37 -0
- package/dist/types/type-guards.d.ts +3 -0
- package/dist/types/vendor/mermaid-ascii/ascii/ansi.d.ts +41 -0
- package/dist/types/vendor/mermaid-ascii/ascii/canvas.d.ts +89 -0
- package/dist/types/vendor/mermaid-ascii/ascii/class-diagram.d.ts +7 -0
- package/dist/types/vendor/mermaid-ascii/ascii/converter.d.ts +12 -0
- package/dist/types/vendor/mermaid-ascii/ascii/draw.d.ts +66 -0
- package/dist/types/vendor/mermaid-ascii/ascii/edge-bundling.d.ts +48 -0
- package/dist/types/vendor/mermaid-ascii/ascii/edge-routing.d.ts +43 -0
- package/dist/types/vendor/mermaid-ascii/ascii/er-diagram.d.ts +7 -0
- package/dist/types/vendor/mermaid-ascii/ascii/grid.d.ts +56 -0
- package/dist/types/vendor/mermaid-ascii/ascii/index.d.ts +65 -0
- package/dist/types/vendor/mermaid-ascii/ascii/multiline-utils.d.ts +27 -0
- package/dist/types/vendor/mermaid-ascii/ascii/pathfinder.d.ts +17 -0
- package/dist/types/vendor/mermaid-ascii/ascii/sequence.d.ts +7 -0
- package/dist/types/vendor/mermaid-ascii/ascii/shapes/circle.d.ts +11 -0
- package/dist/types/vendor/mermaid-ascii/ascii/shapes/corners.d.ts +34 -0
- package/dist/types/vendor/mermaid-ascii/ascii/shapes/diamond.d.ts +11 -0
- package/dist/types/vendor/mermaid-ascii/ascii/shapes/hexagon.d.ts +11 -0
- package/dist/types/vendor/mermaid-ascii/ascii/shapes/index.d.ts +26 -0
- package/dist/types/vendor/mermaid-ascii/ascii/shapes/rectangle.d.ts +31 -0
- package/dist/types/vendor/mermaid-ascii/ascii/shapes/rounded.d.ts +11 -0
- package/dist/types/vendor/mermaid-ascii/ascii/shapes/special.d.ts +59 -0
- package/dist/types/vendor/mermaid-ascii/ascii/shapes/stadium.d.ts +17 -0
- package/dist/types/vendor/mermaid-ascii/ascii/shapes/state.d.ts +30 -0
- package/dist/types/vendor/mermaid-ascii/ascii/shapes/types.d.ts +55 -0
- package/dist/types/vendor/mermaid-ascii/ascii/types.d.ts +206 -0
- package/dist/types/vendor/mermaid-ascii/ascii/validate.d.ts +51 -0
- package/dist/types/vendor/mermaid-ascii/ascii/xychart.d.ts +2 -0
- package/dist/types/vendor/mermaid-ascii/class/parser.d.ts +6 -0
- package/dist/types/vendor/mermaid-ascii/class/types.d.ts +102 -0
- package/dist/types/vendor/mermaid-ascii/er/parser.d.ts +6 -0
- package/dist/types/vendor/mermaid-ascii/er/types.d.ts +76 -0
- package/dist/types/vendor/mermaid-ascii/index.d.ts +1 -0
- package/dist/types/vendor/mermaid-ascii/multiline-utils.d.ts +9 -0
- package/dist/types/vendor/mermaid-ascii/parser.d.ts +7 -0
- package/dist/types/vendor/mermaid-ascii/sequence/parser.d.ts +6 -0
- package/dist/types/vendor/mermaid-ascii/sequence/types.d.ts +130 -0
- package/dist/types/vendor/mermaid-ascii/text-metrics.d.ts +21 -0
- package/dist/types/vendor/mermaid-ascii/types.d.ts +114 -0
- package/dist/types/vendor/mermaid-ascii/xychart/colors.d.ts +25 -0
- package/dist/types/vendor/mermaid-ascii/xychart/parser.d.ts +6 -0
- package/dist/types/vendor/mermaid-ascii/xychart/types.d.ts +145 -0
- package/dist/types/which.d.ts +37 -0
- package/dist/types/worker-host.d.ts +47 -0
- package/package.json +62 -0
- package/src/abortable.ts +109 -0
- package/src/async.ts +50 -0
- package/src/binary.ts +50 -0
- package/src/cli.ts +457 -0
- package/src/color.ts +302 -0
- package/src/dirs.ts +925 -0
- package/src/env.ts +226 -0
- package/src/fetch-retry.ts +355 -0
- package/src/format.ts +113 -0
- package/src/frontmatter.ts +162 -0
- package/src/fs-error.ts +56 -0
- package/src/glob.ts +189 -0
- package/src/index.ts +55 -0
- package/src/json-parse.ts +612 -0
- package/src/json.ts +10 -0
- package/src/logger.ts +672 -0
- package/src/loop-phase.ts +49 -0
- package/src/mermaid-ascii.ts +31 -0
- package/src/mime.ts +159 -0
- package/src/module-timer.ts +148 -0
- package/src/path-tree.ts +147 -0
- package/src/path.ts +28 -0
- package/src/peek-file.ts +188 -0
- package/src/postmortem.ts +222 -0
- package/src/procmgr.ts +195 -0
- package/src/prompt.ts +562 -0
- package/src/ptree.ts +395 -0
- package/src/ring.ts +169 -0
- package/src/runtime-install.ts +372 -0
- package/src/sanitize-text.ts +96 -0
- package/src/snowflake.ts +121 -0
- package/src/stream.ts +432 -0
- package/src/tab-spacing.ts +336 -0
- package/src/temp.ts +134 -0
- package/src/timing-buffer.ts +47 -0
- package/src/tls-fetch.ts +178 -0
- package/src/type-guards.ts +11 -0
- package/src/vendor/mermaid-ascii/NOTICE +33 -0
- package/src/vendor/mermaid-ascii/ascii/ansi.ts +409 -0
- package/src/vendor/mermaid-ascii/ascii/canvas.ts +476 -0
- package/src/vendor/mermaid-ascii/ascii/class-diagram.ts +699 -0
- package/src/vendor/mermaid-ascii/ascii/converter.ts +271 -0
- package/src/vendor/mermaid-ascii/ascii/draw.ts +1382 -0
- package/src/vendor/mermaid-ascii/ascii/edge-bundling.ts +328 -0
- package/src/vendor/mermaid-ascii/ascii/edge-routing.ts +297 -0
- package/src/vendor/mermaid-ascii/ascii/er-diagram.ts +441 -0
- package/src/vendor/mermaid-ascii/ascii/grid.ts +578 -0
- package/src/vendor/mermaid-ascii/ascii/index.ts +187 -0
- package/src/vendor/mermaid-ascii/ascii/multiline-utils.ts +78 -0
- package/src/vendor/mermaid-ascii/ascii/pathfinder.ts +215 -0
- package/src/vendor/mermaid-ascii/ascii/sequence.ts +460 -0
- package/src/vendor/mermaid-ascii/ascii/shapes/circle.ts +27 -0
- package/src/vendor/mermaid-ascii/ascii/shapes/corners.ts +127 -0
- package/src/vendor/mermaid-ascii/ascii/shapes/diamond.ts +27 -0
- package/src/vendor/mermaid-ascii/ascii/shapes/hexagon.ts +27 -0
- package/src/vendor/mermaid-ascii/ascii/shapes/index.ts +101 -0
- package/src/vendor/mermaid-ascii/ascii/shapes/rectangle.ts +175 -0
- package/src/vendor/mermaid-ascii/ascii/shapes/rounded.ts +27 -0
- package/src/vendor/mermaid-ascii/ascii/shapes/special.ts +296 -0
- package/src/vendor/mermaid-ascii/ascii/shapes/stadium.ts +114 -0
- package/src/vendor/mermaid-ascii/ascii/shapes/state.ts +192 -0
- package/src/vendor/mermaid-ascii/ascii/shapes/types.ts +73 -0
- package/src/vendor/mermaid-ascii/ascii/types.ts +273 -0
- package/src/vendor/mermaid-ascii/ascii/validate.ts +120 -0
- package/src/vendor/mermaid-ascii/ascii/xychart.ts +875 -0
- package/src/vendor/mermaid-ascii/class/parser.ts +290 -0
- package/src/vendor/mermaid-ascii/class/types.ts +121 -0
- package/src/vendor/mermaid-ascii/er/parser.ts +181 -0
- package/src/vendor/mermaid-ascii/er/types.ts +91 -0
- package/src/vendor/mermaid-ascii/index.ts +14 -0
- package/src/vendor/mermaid-ascii/multiline-utils.ts +30 -0
- package/src/vendor/mermaid-ascii/parser.ts +645 -0
- package/src/vendor/mermaid-ascii/sequence/parser.ts +207 -0
- package/src/vendor/mermaid-ascii/sequence/types.ts +146 -0
- package/src/vendor/mermaid-ascii/text-metrics.ts +71 -0
- package/src/vendor/mermaid-ascii/types.ts +164 -0
- package/src/vendor/mermaid-ascii/xychart/colors.ts +140 -0
- package/src/vendor/mermaid-ascii/xychart/parser.ts +115 -0
- package/src/vendor/mermaid-ascii/xychart/types.ts +150 -0
- package/src/which.ts +232 -0
- package/src/worker-host.ts +92 -0
|
@@ -0,0 +1,372 @@
|
|
|
1
|
+
import * as fs from "node:fs";
|
|
2
|
+
import * as fsp from "node:fs/promises";
|
|
3
|
+
import * as Module from "node:module";
|
|
4
|
+
import * as path from "node:path";
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* On-demand runtime dependency support for native-heavy optional packages
|
|
8
|
+
* (Transformers.js, fastembed) that are never bundled into the CLI or the
|
|
9
|
+
* compiled binary. Consumers `bun install` a pinned dependency set into a
|
|
10
|
+
* cache directory on first use ({@link ensureRuntimeInstalled}) and load the
|
|
11
|
+
* entrypoint via `createRequire`.
|
|
12
|
+
*
|
|
13
|
+
* Bun's compiled-binary module resolver only finds `<pkg>/index.js` for bare
|
|
14
|
+
* specifiers loaded from the *real* filesystem — it ignores `main`/`exports`
|
|
15
|
+
* (issue #1763). Runtime-installed graphs (`@huggingface/transformers` →
|
|
16
|
+
* `onnxruntime-node` → `onnxruntime-common`, `fastembed` →
|
|
17
|
+
* `@anush008/tokenizers` → platform binding) all point `main`/`exports` at
|
|
18
|
+
* nested files, so the stock resolver cannot load any of them. We patch
|
|
19
|
+
* `Module._resolveFilename` to resolve those bare specifiers against the
|
|
20
|
+
* registered runtime caches ourselves, honoring `main`/`exports`.
|
|
21
|
+
*
|
|
22
|
+
* This module is filesystem-pure aside from {@link installRuntimeModuleResolver}
|
|
23
|
+
* mutating the `node:module` resolver, so the resolution logic is unit-testable
|
|
24
|
+
* without a compiled binary.
|
|
25
|
+
*/
|
|
26
|
+
|
|
27
|
+
/** Conditions honored when resolving an `exports` map for a CommonJS `require`. */
|
|
28
|
+
const RUNTIME_CONDITIONS: Record<string, true> = { node: true, require: true, default: true };
|
|
29
|
+
|
|
30
|
+
/** Extension probes appended to a `main`/`exports` target that lacks one. */
|
|
31
|
+
const RUNTIME_EXTENSIONS: readonly string[] = [".js", ".cjs", ".mjs", ".json", ".node"];
|
|
32
|
+
|
|
33
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
34
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Walk a conditional `exports` target (string, array of fallbacks, or a
|
|
39
|
+
* condition object) and return the first relative path that matches a runtime
|
|
40
|
+
* condition in declaration order. Returns `null` when nothing applies (e.g.
|
|
41
|
+
* an `import`-only entry).
|
|
42
|
+
*/
|
|
43
|
+
export function selectConditionalTarget(target: unknown): string | null {
|
|
44
|
+
if (typeof target === "string") return target;
|
|
45
|
+
if (Array.isArray(target)) {
|
|
46
|
+
for (const entry of target) {
|
|
47
|
+
const resolved = selectConditionalTarget(entry);
|
|
48
|
+
if (resolved) return resolved;
|
|
49
|
+
}
|
|
50
|
+
return null;
|
|
51
|
+
}
|
|
52
|
+
if (isRecord(target)) {
|
|
53
|
+
for (const condition in target) {
|
|
54
|
+
if (!RUNTIME_CONDITIONS[condition]) continue;
|
|
55
|
+
const resolved = selectConditionalTarget(target[condition]);
|
|
56
|
+
if (resolved) return resolved;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
return null;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** Resolve a relative target inside a package to a concrete file path, probing extensions and `index`. */
|
|
63
|
+
function resolveFileTarget(pkgDir: string, relative: string): string | null {
|
|
64
|
+
const base = path.join(pkgDir, relative);
|
|
65
|
+
const candidates = [base, ...RUNTIME_EXTENSIONS.map(ext => base + ext)];
|
|
66
|
+
for (const candidate of candidates) {
|
|
67
|
+
try {
|
|
68
|
+
const stat = fs.statSync(candidate);
|
|
69
|
+
if (stat.isFile()) return candidate;
|
|
70
|
+
if (stat.isDirectory()) {
|
|
71
|
+
const indexed = resolveFileTarget(candidate, "index");
|
|
72
|
+
if (indexed) return indexed;
|
|
73
|
+
}
|
|
74
|
+
} catch {
|
|
75
|
+
// missing candidate — keep probing
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
return null;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function resolveExportsEntry(
|
|
82
|
+
pkgDir: string,
|
|
83
|
+
exports: Record<string, unknown>,
|
|
84
|
+
subpath: string | undefined,
|
|
85
|
+
): string | null {
|
|
86
|
+
let subpathMap = false;
|
|
87
|
+
for (const key in exports) {
|
|
88
|
+
subpathMap = key === "." || key.startsWith("./");
|
|
89
|
+
break;
|
|
90
|
+
}
|
|
91
|
+
if (subpathMap) {
|
|
92
|
+
const key = subpath ? `./${subpath}` : ".";
|
|
93
|
+
if (!(key in exports)) return null;
|
|
94
|
+
const target = selectConditionalTarget(exports[key]);
|
|
95
|
+
return target ? resolveFileTarget(pkgDir, target) : null;
|
|
96
|
+
}
|
|
97
|
+
// A bare condition map only describes the package root, so a subpath
|
|
98
|
+
// request falls through to plain path joining at the call site.
|
|
99
|
+
if (subpath) return null;
|
|
100
|
+
const target = selectConditionalTarget(exports);
|
|
101
|
+
return target ? resolveFileTarget(pkgDir, target) : null;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* Split a bare specifier into its package name and optional subpath, handling
|
|
106
|
+
* scoped packages (`@scope/name/sub` → `@scope/name` + `sub`).
|
|
107
|
+
*/
|
|
108
|
+
export function splitBareSpecifier(specifier: string): { packageName: string; subpath: string | undefined } {
|
|
109
|
+
const segments = specifier.split("/");
|
|
110
|
+
const take = specifier.startsWith("@") ? 2 : 1;
|
|
111
|
+
const packageName = segments.slice(0, take).join("/");
|
|
112
|
+
const subpath = segments.length > take ? segments.slice(take).join("/") : undefined;
|
|
113
|
+
return { packageName, subpath };
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* Resolve a bare specifier against an installed `node_modules` directory,
|
|
118
|
+
* honoring `exports` (CommonJS conditions), then `main`, then `index.js`.
|
|
119
|
+
* Returns an absolute file path, or `null` when the package/entry is absent.
|
|
120
|
+
*/
|
|
121
|
+
export function resolveRuntimeModule(runtimeNodeModules: string, specifier: string): string | null {
|
|
122
|
+
const { packageName, subpath } = splitBareSpecifier(specifier);
|
|
123
|
+
const pkgDir = path.join(runtimeNodeModules, ...packageName.split("/"));
|
|
124
|
+
const manifest = readManifest(pkgDir);
|
|
125
|
+
if (!manifest) return subpath ? resolveFileTarget(pkgDir, subpath) : null;
|
|
126
|
+
|
|
127
|
+
const { exports } = manifest;
|
|
128
|
+
if (typeof exports === "string" || isRecord(exports)) {
|
|
129
|
+
const map = typeof exports === "string" ? { ".": exports } : exports;
|
|
130
|
+
const resolved = resolveExportsEntry(pkgDir, map, subpath);
|
|
131
|
+
if (resolved) return resolved;
|
|
132
|
+
}
|
|
133
|
+
if (subpath) return resolveFileTarget(pkgDir, subpath);
|
|
134
|
+
if (typeof manifest.main === "string") {
|
|
135
|
+
const resolved = resolveFileTarget(pkgDir, manifest.main);
|
|
136
|
+
if (resolved) return resolved;
|
|
137
|
+
}
|
|
138
|
+
return resolveFileTarget(pkgDir, "index.js");
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
function readManifest(pkgDir: string): Record<string, unknown> | null {
|
|
142
|
+
try {
|
|
143
|
+
const parsed: unknown = JSON.parse(fs.readFileSync(path.join(pkgDir, "package.json"), "utf8"));
|
|
144
|
+
return isRecord(parsed) ? parsed : null;
|
|
145
|
+
} catch {
|
|
146
|
+
return null;
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
interface ModuleResolver {
|
|
151
|
+
_resolveFilename(request: string, parent: unknown, isMain: boolean, options?: unknown): string;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
interface ResolverRegistration {
|
|
155
|
+
runtimeNodeModules: string;
|
|
156
|
+
stubs: Record<string, string>;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
const REGISTRY = Symbol.for("omp.runtimeModuleResolver.registry");
|
|
160
|
+
const PATCHED = Symbol.for("omp.runtimeModuleResolver.patched");
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* The registration list lives on `globalThis` so a bundled copy and a
|
|
164
|
+
* source copy of this module in one process share the same registry — the
|
|
165
|
+
* resolver is patched once per process, and the patched closure must see
|
|
166
|
+
* every registration.
|
|
167
|
+
*/
|
|
168
|
+
function resolverRegistry(): ResolverRegistration[] {
|
|
169
|
+
const holder = globalThis as { [REGISTRY]?: ResolverRegistration[] };
|
|
170
|
+
holder[REGISTRY] ??= [];
|
|
171
|
+
return holder[REGISTRY];
|
|
172
|
+
}
|
|
173
|
+
function pathContains(root: string, candidate: string): boolean {
|
|
174
|
+
const relative = path.relative(root, candidate);
|
|
175
|
+
return relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative));
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
function parentFilename(parent: unknown): string | null {
|
|
179
|
+
if (!isRecord(parent)) return null;
|
|
180
|
+
const filename = parent.filename;
|
|
181
|
+
return typeof filename === "string" ? filename : null;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
export interface RuntimeResolverOptions {
|
|
185
|
+
/** Absolute path to the runtime cache's `node_modules`. */
|
|
186
|
+
runtimeNodeModules: string;
|
|
187
|
+
/** Bare specifier → absolute file path overrides (e.g. `sharp` → no-op stub). */
|
|
188
|
+
stubs?: Record<string, string>;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/**
|
|
192
|
+
* Patch `node:module`'s resolver (idempotently) so bare specifiers that the
|
|
193
|
+
* stock compiled-binary resolver cannot find fall back to the registered
|
|
194
|
+
* runtime caches. Stock resolution is tried first and kept for anything
|
|
195
|
+
* outside the registered roots (bundled imports, node builtins, host or
|
|
196
|
+
* extension trees). Multiple runtime roots may register; they are consulted
|
|
197
|
+
* in registration order.
|
|
198
|
+
*
|
|
199
|
+
* One stock "success" is distrusted: the compiled-binary resolver ignores
|
|
200
|
+
* `main`/`exports` for real-FS packages (Bun #1763), so a package shipping
|
|
201
|
+
* its TS source next to `dist/` (e.g. `@huggingface/hub`'s root `index.ts`)
|
|
202
|
+
* resolves to the wrong file. When the stock hit lands inside a registered
|
|
203
|
+
* runtime root, the manifest-aware resolution wins.
|
|
204
|
+
*/
|
|
205
|
+
export function installRuntimeModuleResolver({ runtimeNodeModules, stubs = {} }: RuntimeResolverOptions): void {
|
|
206
|
+
const registry = resolverRegistry();
|
|
207
|
+
const existing = registry.find(entry => entry.runtimeNodeModules === runtimeNodeModules);
|
|
208
|
+
if (existing) Object.assign(existing.stubs, stubs);
|
|
209
|
+
else registry.push({ runtimeNodeModules, stubs: { ...stubs } });
|
|
210
|
+
|
|
211
|
+
const resolver = (Module as unknown as { default?: ModuleResolver } & ModuleResolver).default ?? Module;
|
|
212
|
+
const target = resolver as unknown as ModuleResolver & { [PATCHED]?: boolean };
|
|
213
|
+
if (target[PATCHED]) return;
|
|
214
|
+
const original = target._resolveFilename.bind(target);
|
|
215
|
+
target._resolveFilename = (request: string, parent: unknown, isMain: boolean, options?: unknown): string => {
|
|
216
|
+
let stockResolved: string | null = null;
|
|
217
|
+
let stockError: unknown;
|
|
218
|
+
try {
|
|
219
|
+
stockResolved = original(request, parent, isMain, options);
|
|
220
|
+
} catch (error) {
|
|
221
|
+
stockError = error;
|
|
222
|
+
}
|
|
223
|
+
const bare = !request.startsWith(".") && !request.startsWith("node:") && !path.isAbsolute(request);
|
|
224
|
+
if (bare) {
|
|
225
|
+
const parentFile = parentFilename(parent);
|
|
226
|
+
for (const registration of resolverRegistry()) {
|
|
227
|
+
const parentInRuntime = parentFile !== null && pathContains(registration.runtimeNodeModules, parentFile);
|
|
228
|
+
if (parentInRuntime) {
|
|
229
|
+
const stub = registration.stubs[request];
|
|
230
|
+
if (stub) return stub;
|
|
231
|
+
if (!stockResolved || !pathContains(registration.runtimeNodeModules, stockResolved)) {
|
|
232
|
+
const fallback = resolveRuntimeModule(registration.runtimeNodeModules, request);
|
|
233
|
+
if (fallback) return fallback;
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
if (stockResolved) {
|
|
237
|
+
// Correct a stock hit only inside the top-level package the
|
|
238
|
+
// request names. A hit in a nested node_modules (e.g. tar's
|
|
239
|
+
// minizlib resolving its own minipass@3 under
|
|
240
|
+
// <root>/minizlib/node_modules/) is version-correct — overriding
|
|
241
|
+
// it with the top-level instance would cross major versions.
|
|
242
|
+
const { packageName } = splitBareSpecifier(request);
|
|
243
|
+
const pkgDir = path.join(registration.runtimeNodeModules, ...packageName.split("/"));
|
|
244
|
+
if (!stockResolved.startsWith(pkgDir + path.sep)) continue;
|
|
245
|
+
if (path.relative(pkgDir, stockResolved).split(path.sep).includes("node_modules")) continue;
|
|
246
|
+
const expected = resolveRuntimeModule(registration.runtimeNodeModules, request);
|
|
247
|
+
if (expected) return expected;
|
|
248
|
+
} else {
|
|
249
|
+
const stub = registration.stubs[request];
|
|
250
|
+
if (stub) return stub;
|
|
251
|
+
const fallback = resolveRuntimeModule(registration.runtimeNodeModules, request);
|
|
252
|
+
if (fallback) return fallback;
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
if (stockResolved) return stockResolved;
|
|
257
|
+
throw stockError;
|
|
258
|
+
};
|
|
259
|
+
target[PATCHED] = true;
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
/** Pinned dependency set materialized into a runtime cache directory. */
|
|
263
|
+
export interface RuntimeInstallSpec {
|
|
264
|
+
dependencies: Record<string, string>;
|
|
265
|
+
/** Version pins forced across the whole runtime tree (bun `overrides`), e.g. dislodging a transitive dep. */
|
|
266
|
+
overrides?: Record<string, string>;
|
|
267
|
+
/** Packages whose lifecycle scripts bun may run during the install. */
|
|
268
|
+
trustedDependencies?: string[];
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
export type RuntimeInstallPhase = "initiate" | "download" | "done";
|
|
272
|
+
|
|
273
|
+
export interface EnsureRuntimeInstalledOptions {
|
|
274
|
+
/** Directory owning the runtime `package.json` + `node_modules`. */
|
|
275
|
+
runtimeDir: string;
|
|
276
|
+
install: RuntimeInstallSpec;
|
|
277
|
+
/** Package whose installed manifest marks the runtime complete; defaults to the first dependency. */
|
|
278
|
+
probePackage?: string;
|
|
279
|
+
/** Phase notifications (progress UI); not emitted when already installed. */
|
|
280
|
+
onPhase?: (phase: RuntimeInstallPhase) => void;
|
|
281
|
+
lockAttempts?: number;
|
|
282
|
+
lockSleepMs?: number;
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
function isErrnoCode(error: unknown, code: string): boolean {
|
|
286
|
+
return typeof error === "object" && error !== null && "code" in error && error.code === code;
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
async function acquireInstallLock(runtimeDir: string, attempts: number, sleepMs: number): Promise<() => Promise<void>> {
|
|
290
|
+
const lockDir = `${runtimeDir}.lock`;
|
|
291
|
+
await fsp.mkdir(path.dirname(lockDir), { recursive: true });
|
|
292
|
+
for (let attempt = 0; attempt < attempts; attempt++) {
|
|
293
|
+
try {
|
|
294
|
+
await fsp.mkdir(lockDir);
|
|
295
|
+
return async () => {
|
|
296
|
+
await fsp.rm(lockDir, { recursive: true, force: true });
|
|
297
|
+
};
|
|
298
|
+
} catch (error) {
|
|
299
|
+
if (!isErrnoCode(error, "EEXIST")) throw error;
|
|
300
|
+
await Bun.sleep(sleepMs);
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
throw new Error(`Timed out waiting for runtime install lock: ${lockDir}`);
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
export async function writeRuntimeManifest(runtimeDir: string, install: RuntimeInstallSpec): Promise<void> {
|
|
307
|
+
await fsp.mkdir(runtimeDir, { recursive: true });
|
|
308
|
+
const manifest: Record<string, unknown> = {
|
|
309
|
+
private: true,
|
|
310
|
+
type: "module",
|
|
311
|
+
dependencies: install.dependencies,
|
|
312
|
+
};
|
|
313
|
+
if (install.overrides && Object.keys(install.overrides).length) manifest.overrides = install.overrides;
|
|
314
|
+
if (install.trustedDependencies?.length) manifest.trustedDependencies = install.trustedDependencies;
|
|
315
|
+
await Bun.write(path.join(runtimeDir, "package.json"), `${JSON.stringify(manifest, null, "\t")}\n`);
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
async function readPipe(stream: ReadableStream<Uint8Array> | null): Promise<string> {
|
|
319
|
+
if (!stream) return "";
|
|
320
|
+
return new Response(stream).text();
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
async function runRuntimeInstall(runtimeDir: string): Promise<void> {
|
|
324
|
+
// `process.execPath` is plain bun in source/bundle mode and the compiled
|
|
325
|
+
// binary otherwise; BUN_BE_BUN makes the compiled binary act as bun.
|
|
326
|
+
const proc = Bun.spawn([process.execPath, "install", "--cwd", runtimeDir, "--production"], {
|
|
327
|
+
env: { ...Bun.env, BUN_BE_BUN: "1" },
|
|
328
|
+
stdout: "pipe",
|
|
329
|
+
stderr: "pipe",
|
|
330
|
+
});
|
|
331
|
+
const [stdout, stderr, exitCode] = await Promise.all([
|
|
332
|
+
readPipe(proc.stdout as ReadableStream<Uint8Array> | null),
|
|
333
|
+
readPipe(proc.stderr as ReadableStream<Uint8Array> | null),
|
|
334
|
+
proc.exited,
|
|
335
|
+
]);
|
|
336
|
+
if (exitCode === 0) return;
|
|
337
|
+
const output = `${stdout}\n${stderr}`.trim();
|
|
338
|
+
throw new Error(
|
|
339
|
+
`Failed to install runtime at ${runtimeDir} with ${process.execPath} install (exit ${exitCode}): ${output}`,
|
|
340
|
+
);
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
/**
|
|
344
|
+
* Materialize a pinned dependency set into `runtimeDir` (idempotent,
|
|
345
|
+
* cross-process safe via a lock directory). Returns `runtimeDir`.
|
|
346
|
+
*/
|
|
347
|
+
export async function ensureRuntimeInstalled(options: EnsureRuntimeInstalledOptions): Promise<string> {
|
|
348
|
+
const { runtimeDir, install, onPhase, lockAttempts = 240, lockSleepMs = 250 } = options;
|
|
349
|
+
let probePackage = options.probePackage;
|
|
350
|
+
if (!probePackage) {
|
|
351
|
+
for (const name in install.dependencies) {
|
|
352
|
+
probePackage = name;
|
|
353
|
+
break;
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
if (!probePackage) throw new Error(`Runtime install at ${runtimeDir} declares no dependencies`);
|
|
357
|
+
const probeManifest = Bun.file(path.join(runtimeDir, "node_modules", ...probePackage.split("/"), "package.json"));
|
|
358
|
+
if (await probeManifest.exists()) return runtimeDir;
|
|
359
|
+
|
|
360
|
+
onPhase?.("initiate");
|
|
361
|
+
const releaseLock = await acquireInstallLock(runtimeDir, lockAttempts, lockSleepMs);
|
|
362
|
+
try {
|
|
363
|
+
if (await probeManifest.exists()) return runtimeDir;
|
|
364
|
+
await writeRuntimeManifest(runtimeDir, install);
|
|
365
|
+
onPhase?.("download");
|
|
366
|
+
await runRuntimeInstall(runtimeDir);
|
|
367
|
+
onPhase?.("done");
|
|
368
|
+
return runtimeDir;
|
|
369
|
+
} finally {
|
|
370
|
+
await releaseLock();
|
|
371
|
+
}
|
|
372
|
+
}
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Strip ANSI escape sequences, remove control characters / lone surrogates,
|
|
3
|
+
* and normalize line endings.
|
|
4
|
+
*
|
|
5
|
+
* Bun-native implementation of the former native `sanitizeText` (see
|
|
6
|
+
* `crates/pi-natives/src/text.rs::sanitize_text`). JavaScript strings are
|
|
7
|
+
* already UTF-16 code-unit arrays. `toWellFormed()` handles the uncommon
|
|
8
|
+
* malformed path; when it changes the input, replacement characters are
|
|
9
|
+
* dropped and the normalized result goes through the well-formed sanitizer.
|
|
10
|
+
*
|
|
11
|
+
* Fast path: well-formed input with no controls or ANSI returns the original
|
|
12
|
+
* string after the control probe.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
const ESC_CHAR = "\x1b";
|
|
16
|
+
|
|
17
|
+
// Well-formed strings only need control/ANSI detection: C0 (excl. \t \n),
|
|
18
|
+
// CR, DEL, and C1. ESC (0x1B) is in \x0B-\x1F.
|
|
19
|
+
const CONTROL_RE = /[\x00-\x08\x0B-\x1F\x7F-\x9F]/g;
|
|
20
|
+
|
|
21
|
+
const REPLACEMENT_CHAR = "\ufffd";
|
|
22
|
+
|
|
23
|
+
export function sanitizeText(text: string): string {
|
|
24
|
+
const wellFormed = text.toWellFormed();
|
|
25
|
+
if (wellFormed !== text) {
|
|
26
|
+
return sanitizeWellFormedText(wellFormed.replaceAll(REPLACEMENT_CHAR, ""));
|
|
27
|
+
}
|
|
28
|
+
return sanitizeWellFormedText(text);
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function sanitizeWellFormedText(text: string): string {
|
|
32
|
+
CONTROL_RE.lastIndex = 0;
|
|
33
|
+
if (CONTROL_RE.exec(text) === null) return text;
|
|
34
|
+
|
|
35
|
+
const stripped = text.indexOf(ESC_CHAR) === -1 ? text : Bun.stripANSI(text);
|
|
36
|
+
CONTROL_RE.lastIndex = 0;
|
|
37
|
+
return stripped.replace(CONTROL_RE, "");
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Escape the three XML-significant characters (`&`, `<`, `>`) in text destined
|
|
42
|
+
* for an XML/markup element body. Allocation-conscious: returns the input
|
|
43
|
+
* unchanged (same reference) when nothing needs escaping. Quotes are left as-is
|
|
44
|
+
* — use it for element text, not attribute values.
|
|
45
|
+
*/
|
|
46
|
+
export function escapeXmlText(input: string): string {
|
|
47
|
+
let firstEscapable = -1;
|
|
48
|
+
for (let index = 0; index < input.length; index++) {
|
|
49
|
+
const char = input.charCodeAt(index);
|
|
50
|
+
if (char === 38 || char === 60 || char === 62) {
|
|
51
|
+
firstEscapable = index;
|
|
52
|
+
break;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
if (firstEscapable === -1) return input;
|
|
56
|
+
|
|
57
|
+
let output = input.slice(0, firstEscapable);
|
|
58
|
+
for (let index = firstEscapable; index < input.length; index++) {
|
|
59
|
+
const char = input[index];
|
|
60
|
+
if (char === "&") output += "&";
|
|
61
|
+
else if (char === "<") output += "<";
|
|
62
|
+
else if (char === ">") output += ">";
|
|
63
|
+
else output += char;
|
|
64
|
+
}
|
|
65
|
+
return output;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Escape XML-significant characters for an attribute VALUE: the three body
|
|
70
|
+
* characters (`&`, `<`, `>`) plus the double quote (`"` → `"`) that would
|
|
71
|
+
* otherwise close the attribute. Allocation-conscious: returns the input
|
|
72
|
+
* unchanged (same reference) when nothing needs escaping. Use it for attribute
|
|
73
|
+
* values; {@link escapeXmlText} is for element bodies and leaves `"` intact.
|
|
74
|
+
*/
|
|
75
|
+
export function escapeXmlAttribute(input: string): string {
|
|
76
|
+
let firstEscapable = -1;
|
|
77
|
+
for (let index = 0; index < input.length; index++) {
|
|
78
|
+
const char = input.charCodeAt(index);
|
|
79
|
+
if (char === 38 || char === 60 || char === 62 || char === 34) {
|
|
80
|
+
firstEscapable = index;
|
|
81
|
+
break;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
if (firstEscapable === -1) return input;
|
|
85
|
+
|
|
86
|
+
let output = input.slice(0, firstEscapable);
|
|
87
|
+
for (let index = firstEscapable; index < input.length; index++) {
|
|
88
|
+
const char = input[index];
|
|
89
|
+
if (char === "&") output += "&";
|
|
90
|
+
else if (char === "<") output += "<";
|
|
91
|
+
else if (char === ">") output += ">";
|
|
92
|
+
else if (char === '"') output += """;
|
|
93
|
+
else output += char;
|
|
94
|
+
}
|
|
95
|
+
return output;
|
|
96
|
+
}
|
package/src/snowflake.ts
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
function randu32() {
|
|
2
|
+
return crypto.getRandomValues(new Uint32Array(1))[0];
|
|
3
|
+
}
|
|
4
|
+
|
|
5
|
+
const EPOCH = 1420070400000;
|
|
6
|
+
const MAX_SEQ = 0x3fffff;
|
|
7
|
+
|
|
8
|
+
// Snowflake as a hex string (16 chars, zero-padded).
|
|
9
|
+
//
|
|
10
|
+
// Since this is not distributed (no machine ID needed), we use an extended
|
|
11
|
+
// 22-bit sequence instead of the standard 10-bit machine ID + 12-bit sequence.
|
|
12
|
+
//
|
|
13
|
+
type Snowflake = string & { readonly __brand: unique symbol };
|
|
14
|
+
|
|
15
|
+
namespace Snowflake {
|
|
16
|
+
// Hex string validation pattern (16 lowercase hex chars).
|
|
17
|
+
//
|
|
18
|
+
export const PATTERN = /^[0-9a-f]{16}$/;
|
|
19
|
+
|
|
20
|
+
// Epoch timestamp.
|
|
21
|
+
//
|
|
22
|
+
export const EPOCH_TIMESTAMP = EPOCH;
|
|
23
|
+
|
|
24
|
+
// Maximum sequence number.
|
|
25
|
+
//
|
|
26
|
+
export const MAX_SEQUENCE = MAX_SEQ;
|
|
27
|
+
|
|
28
|
+
// Formats a sequence and timestamp into a snowflake hex string.
|
|
29
|
+
//
|
|
30
|
+
// dt fits well within BigInt range: (dt << 22) | seq stays under 2^64 for
|
|
31
|
+
// any dt < 2^42 (~year 2154), so a single 64-bit format is exact — and
|
|
32
|
+
// measures ~1.7x faster than stitching four 16-bit hex segments.
|
|
33
|
+
//
|
|
34
|
+
export function formatParts(dt: number, seq: number): Snowflake {
|
|
35
|
+
return ((BigInt(dt) << 22n) | BigInt(seq)).toString(16).padStart(16, "0") as Snowflake;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
// Snowflake generator type.
|
|
39
|
+
//
|
|
40
|
+
export class Source {
|
|
41
|
+
#seq = 0;
|
|
42
|
+
constructor(sequence: number = randu32() & MAX_SEQ) {
|
|
43
|
+
this.#seq = sequence & MAX_SEQ;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
// Sequence number.
|
|
47
|
+
//
|
|
48
|
+
get sequence() {
|
|
49
|
+
return this.#seq & MAX_SEQ;
|
|
50
|
+
}
|
|
51
|
+
set sequence(v: number) {
|
|
52
|
+
this.#seq = v & MAX_SEQ;
|
|
53
|
+
}
|
|
54
|
+
reset() {
|
|
55
|
+
this.#seq = 0;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
// Generates the next value as a hex string.
|
|
59
|
+
//
|
|
60
|
+
generate(timestamp: number): Snowflake {
|
|
61
|
+
const seq = (this.#seq + 1) & MAX_SEQ;
|
|
62
|
+
const dt = timestamp - EPOCH;
|
|
63
|
+
this.#seq = seq;
|
|
64
|
+
return formatParts(dt, seq);
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
// Gets the next snowflake given the timestamp.
|
|
69
|
+
//
|
|
70
|
+
let defaultSource: Source | undefined;
|
|
71
|
+
export function next(timestamp = Date.now()): Snowflake {
|
|
72
|
+
defaultSource ??= new Source();
|
|
73
|
+
return defaultSource.generate(timestamp);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
// Validates a snowflake hex string.
|
|
77
|
+
//
|
|
78
|
+
export function valid(value: string): value is Snowflake {
|
|
79
|
+
return value.length === 16 && PATTERN.test(value);
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
// Returns the upper/lower boundaries for the given timestamp.
|
|
83
|
+
//
|
|
84
|
+
export function lowerbound(timelike: Date | number | Snowflake): Snowflake {
|
|
85
|
+
switch (typeof timelike) {
|
|
86
|
+
case "object": // Date
|
|
87
|
+
return formatParts(timelike.getTime() - EPOCH, 0);
|
|
88
|
+
case "number":
|
|
89
|
+
return formatParts(timelike - EPOCH, 0);
|
|
90
|
+
case "string": // Snowflake hex string
|
|
91
|
+
return timelike;
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
export function upperbound(timelike: Date | number | Snowflake): Snowflake {
|
|
95
|
+
switch (typeof timelike) {
|
|
96
|
+
case "object": // Date
|
|
97
|
+
return formatParts(timelike.getTime() - EPOCH, MAX_SEQ);
|
|
98
|
+
case "number":
|
|
99
|
+
return formatParts(timelike - EPOCH, MAX_SEQ);
|
|
100
|
+
case "string": // Snowflake hex string
|
|
101
|
+
return timelike;
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
// Returns the individual bits given the snowflake.
|
|
106
|
+
//
|
|
107
|
+
export function getSequence(value: Snowflake) {
|
|
108
|
+
return Number.parseInt(value.substring(8, 16), 16) & MAX_SEQ;
|
|
109
|
+
}
|
|
110
|
+
export function getTimestamp(value: Snowflake) {
|
|
111
|
+
const hi = Number.parseInt(value.substring(0, 8), 16);
|
|
112
|
+
const lo = Number.parseInt(value.substring(8, 16), 16);
|
|
113
|
+
// (hi:lo) >> 22 == hi * 2^10 + (lo >>> 22); at most ~2^42, exact in a double.
|
|
114
|
+
return hi * 1024 + (lo >>> 22) + EPOCH;
|
|
115
|
+
}
|
|
116
|
+
export function getDate(value: Snowflake) {
|
|
117
|
+
return new Date(getTimestamp(value));
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
export { Snowflake };
|