@vite-hub/runtime 0.0.3 → 0.0.4

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/dist/node.d.ts ADDED
@@ -0,0 +1,35 @@
1
+ import { _t as RuntimeResourceInspector } from "./index-tBKyUP1T.js";
2
+
3
+ //#region src/node.d.ts
4
+ type ReadText = (path: string, options?: {
5
+ signal?: AbortSignal;
6
+ }) => Promise<string>;
7
+ interface NodeRuntimeResourceInspectorOptions {
8
+ now?: () => Date;
9
+ readText?: ReadText;
10
+ }
11
+ declare function resolveLinuxCgroupV2Path(mountinfo: string, membership: string): string | undefined;
12
+ declare function nodeRuntimeResources(options?: NodeRuntimeResourceInspectorOptions): RuntimeResourceInspector;
13
+ type ProcessReconcilerStatus = "accepting" | "drained" | "draining" | "failed";
14
+ type ProcessReconcilerSignal = Exclude<NodeJS.Signals, "SIGKILL" | "SIGSTOP">;
15
+ interface ProcessReconcilerRunContext {
16
+ track<T>(work: Promise<T>): Promise<T>;
17
+ }
18
+ interface ProcessReconcilerOptions {
19
+ intervalMs: number;
20
+ onDrained?: () => Promise<void> | void;
21
+ onError?: (error: unknown, reason: string) => Promise<void> | void;
22
+ onQuiesce?: () => Promise<void> | void;
23
+ repairReason?: string;
24
+ run: (reason: string, context: ProcessReconcilerRunContext) => Promise<void> | void;
25
+ signal?: false | ProcessReconcilerSignal;
26
+ }
27
+ interface ProcessReconciler extends ProcessReconcilerRunContext {
28
+ close: () => Promise<void>;
29
+ drain: () => Promise<void>;
30
+ status: () => ProcessReconcilerStatus;
31
+ wake: (reason: string) => void;
32
+ }
33
+ declare function createProcessReconciler(options: ProcessReconcilerOptions): ProcessReconciler;
34
+ //#endregion
35
+ export { NodeRuntimeResourceInspectorOptions, ProcessReconciler, ProcessReconcilerOptions, ProcessReconcilerRunContext, ProcessReconcilerSignal, ProcessReconcilerStatus, createProcessReconciler, nodeRuntimeResources, resolveLinuxCgroupV2Path };
package/dist/node.js ADDED
@@ -0,0 +1,396 @@
1
+ import { t as hasRuntimeType } from "./runtime-type-ovvOd6m5.js";
2
+ import { AsyncLocalStorage } from "node:async_hooks";
3
+ import { readFile } from "node:fs/promises";
4
+ import { join } from "node:path";
5
+ import { availableMemory, memoryUsage, resourceUsage } from "node:process";
6
+ //#region src/node.ts
7
+ function observation(name, value, scope, source, unit) {
8
+ return value === void 0 || !Number.isFinite(value) ? [] : [{
9
+ name,
10
+ scope,
11
+ source,
12
+ unit,
13
+ value
14
+ }];
15
+ }
16
+ async function readResult(readText, path, signal) {
17
+ try {
18
+ return { value: await readText(path, { signal }) };
19
+ } catch (error) {
20
+ return { error };
21
+ }
22
+ }
23
+ function readErrorCode(error) {
24
+ if (!error || !hasRuntimeType(error, "object")) return;
25
+ try {
26
+ return hasRuntimeType(error.code, "string") ? error.code : void 0;
27
+ } catch {
28
+ return;
29
+ }
30
+ }
31
+ function readFailureReason(results, missing) {
32
+ const codes = results.flatMap((result) => readErrorCode(result.error) || []);
33
+ if (codes.some((code) => code === "EACCES" || code === "EPERM")) return "permission-denied";
34
+ if (codes.length && codes.every((code) => code === "ENOENT" || code === "ENOTDIR")) return missing;
35
+ return "collection-failed";
36
+ }
37
+ function mountInfoPath(value) {
38
+ return value.replace(/\\([0-7]{3})/g, (_match, octal) => String.fromCharCode(Number.parseInt(octal, 8)));
39
+ }
40
+ function resolveLinuxCgroupV2Path(mountinfo, membership) {
41
+ const mount = mountinfo.trim().split("\n").flatMap((line) => {
42
+ const fields = line.trim().split(/\s+/);
43
+ const separator = fields.indexOf("-");
44
+ if (separator < 6 || fields[separator + 1] !== "cgroup2") return [];
45
+ const root = mountInfoPath(fields[3]);
46
+ const mountPoint = mountInfoPath(fields[4]);
47
+ if (membership !== root && root !== "/" && !membership.startsWith(`${root}/`)) return [];
48
+ return [{
49
+ mountPoint,
50
+ root
51
+ }];
52
+ }).sort((left, right) => right.root.length - left.root.length)[0];
53
+ if (!mount) return;
54
+ const relative = mount.root === "/" ? membership : membership.slice(mount.root.length);
55
+ return join(mount.mountPoint, relative.replace(/^\/+/, ""));
56
+ }
57
+ function numericFile(value) {
58
+ if (!value || value.trim() === "max") return;
59
+ const result = Number(value.trim());
60
+ return Number.isFinite(result) ? result : void 0;
61
+ }
62
+ function pairs(value) {
63
+ return Object.fromEntries((value || "").trim().split("\n").flatMap((line) => {
64
+ const [key, raw] = line.trim().split(/\s+/, 2);
65
+ const count = Number(raw);
66
+ return key && Number.isFinite(count) ? [[key, count]] : [];
67
+ }));
68
+ }
69
+ function meminfo(value) {
70
+ return Object.fromEntries((value || "").trim().split("\n").flatMap((line) => {
71
+ const match = /^(\w+):\s+(\d+)\s+kB$/.exec(line);
72
+ return match ? [[match[1], Number(match[2]) * 1024]] : [];
73
+ }));
74
+ }
75
+ async function cgroupObservations(readText, signal) {
76
+ const membershipRead = await readResult(readText, "/proc/self/cgroup", signal);
77
+ if (membershipRead.value === void 0) return {
78
+ observations: [],
79
+ support: {
80
+ reason: readFailureReason([membershipRead], "unsupported-runtime"),
81
+ scope: "service",
82
+ source: "linux-cgroup-v2",
83
+ supported: false
84
+ }
85
+ };
86
+ const relative = membershipRead.value.split("\n").find((line) => line.startsWith("0::"))?.slice(3);
87
+ if (relative === void 0) return {
88
+ observations: [],
89
+ support: {
90
+ reason: "unsupported-runtime",
91
+ scope: "service",
92
+ source: "linux-cgroup-v2",
93
+ supported: false
94
+ }
95
+ };
96
+ const mountinfoRead = await readResult(readText, "/proc/self/mountinfo", signal);
97
+ if (mountinfoRead.value === void 0) return {
98
+ observations: [],
99
+ support: {
100
+ reason: readFailureReason([mountinfoRead], "mount-unavailable"),
101
+ scope: "service",
102
+ source: "linux-cgroup-v2",
103
+ supported: false
104
+ }
105
+ };
106
+ const root = resolveLinuxCgroupV2Path(mountinfoRead.value, relative);
107
+ if (!root) return {
108
+ observations: [],
109
+ support: {
110
+ reason: "mount-unavailable",
111
+ scope: "service",
112
+ source: "linux-cgroup-v2",
113
+ supported: false
114
+ }
115
+ };
116
+ const reads = await Promise.all([
117
+ readResult(readText, join(root, "memory.current"), signal),
118
+ readResult(readText, join(root, "memory.peak"), signal),
119
+ readResult(readText, join(root, "memory.high"), signal),
120
+ readResult(readText, join(root, "memory.max"), signal),
121
+ readResult(readText, join(root, "memory.swap.current"), signal),
122
+ readResult(readText, join(root, "memory.swap.peak"), signal),
123
+ readResult(readText, join(root, "memory.events"), signal),
124
+ readResult(readText, join(root, "cpu.stat"), signal)
125
+ ]);
126
+ const [current, peak, high, max, swapCurrent, swapPeak, events, cpu] = reads.map((result) => result.value);
127
+ if (current === void 0 && events === void 0 && cpu === void 0) return {
128
+ observations: [],
129
+ support: {
130
+ reason: readFailureReason(reads, "interfaces-unavailable"),
131
+ scope: "service",
132
+ source: "linux-cgroup-v2",
133
+ supported: false
134
+ }
135
+ };
136
+ const memoryEvents = pairs(events);
137
+ const cpuValues = pairs(cpu);
138
+ return {
139
+ observations: [
140
+ ...observation("memory.current", numericFile(current), "service", "linux-cgroup-v2", "bytes"),
141
+ ...observation("memory.peak", numericFile(peak), "service", "linux-cgroup-v2", "bytes"),
142
+ ...observation("memory.high", numericFile(high), "service", "linux-cgroup-v2", "bytes"),
143
+ ...observation("memory.max", numericFile(max), "service", "linux-cgroup-v2", "bytes"),
144
+ ...observation("memory.swap.current", numericFile(swapCurrent), "service", "linux-cgroup-v2", "bytes"),
145
+ ...observation("memory.swap.peak", numericFile(swapPeak), "service", "linux-cgroup-v2", "bytes"),
146
+ ...observation("memory.events.high", memoryEvents.high, "service", "linux-cgroup-v2", "count"),
147
+ ...observation("memory.events.max", memoryEvents.max, "service", "linux-cgroup-v2", "count"),
148
+ ...observation("memory.events.oom", memoryEvents.oom, "service", "linux-cgroup-v2", "count"),
149
+ ...observation("memory.events.oom_kill", memoryEvents.oom_kill, "service", "linux-cgroup-v2", "count"),
150
+ ...observation("cpu.usage", cpuValues.usage_usec, "service", "linux-cgroup-v2", "microseconds")
151
+ ],
152
+ support: {
153
+ scope: "service",
154
+ source: "linux-cgroup-v2",
155
+ supported: true
156
+ }
157
+ };
158
+ }
159
+ function nodeRuntimeResources(options = {}) {
160
+ const now = options.now || (() => /* @__PURE__ */ new Date());
161
+ const readText = options.readText || (async (path, readOptions) => await readFile(path, {
162
+ encoding: "utf8",
163
+ signal: readOptions?.signal
164
+ }));
165
+ return { async inspect(inspectOptions) {
166
+ const memory = memoryUsage();
167
+ const usage = resourceUsage();
168
+ const linux = process.platform === "linux";
169
+ const [cgroup, linuxMeminfo] = linux ? await Promise.all([cgroupObservations(readText, inspectOptions?.signal), readResult(readText, "/proc/meminfo", inspectOptions?.signal)]) : [{
170
+ observations: [],
171
+ support: {
172
+ reason: "unsupported-runtime",
173
+ scope: "service",
174
+ source: "linux-cgroup-v2",
175
+ supported: false
176
+ }
177
+ }, {}];
178
+ const host = meminfo(linuxMeminfo.value);
179
+ return {
180
+ observedAt: now().toISOString(),
181
+ observations: [
182
+ ...observation("memory.rss", memory.rss, "process", "node", "bytes"),
183
+ ...observation("memory.heap.total", memory.heapTotal, "process", "node", "bytes"),
184
+ ...observation("memory.heap.used", memory.heapUsed, "process", "node", "bytes"),
185
+ ...observation("memory.external", memory.external, "process", "node", "bytes"),
186
+ ...observation("memory.array_buffers", memory.arrayBuffers, "process", "node", "bytes"),
187
+ ...observation("memory.max_rss", usage.maxRSS * 1024, "process", "node", "bytes"),
188
+ ...observation("cpu.user", usage.userCPUTime, "process", "node", "microseconds"),
189
+ ...observation("cpu.system", usage.systemCPUTime, "process", "node", "microseconds"),
190
+ ...observation("memory.available", availableMemory(), "process", "node", "bytes"),
191
+ ...observation("memory.available", host.MemAvailable, "host", "linux-proc", "bytes"),
192
+ ...observation("memory.swap.free", host.SwapFree, "host", "linux-proc", "bytes"),
193
+ ...cgroup.observations
194
+ ],
195
+ support: [
196
+ {
197
+ scope: "process",
198
+ source: "node",
199
+ supported: true
200
+ },
201
+ {
202
+ ...linuxMeminfo.value === void 0 ? { reason: linux ? readFailureReason([linuxMeminfo], "unsupported-runtime") : "unsupported-runtime" } : {},
203
+ scope: "host",
204
+ source: "linux-proc",
205
+ supported: linuxMeminfo.value !== void 0
206
+ },
207
+ cgroup.support
208
+ ]
209
+ };
210
+ } };
211
+ }
212
+ function createProcessReconciler(options) {
213
+ if (!Number.isFinite(options.intervalMs) || options.intervalMs < 1 || options.intervalMs > 2147483647) throw new TypeError("Process reconciler intervalMs must be between 1 and 2,147,483,647 milliseconds.");
214
+ const configuredSignal = options.signal;
215
+ if (configuredSignal === "SIGKILL" || configuredSignal === "SIGSTOP") throw new TypeError(`Process reconciler signal ${configuredSignal} cannot be handled.`);
216
+ let closed = false;
217
+ let drainPromise;
218
+ let queued = false;
219
+ let reason = "coalesced";
220
+ let rerun = false;
221
+ let running;
222
+ let status = "accepting";
223
+ let timer;
224
+ const activeCallbacks = /* @__PURE__ */ new Set();
225
+ const callbackContext = new AsyncLocalStorage();
226
+ const settlements = /* @__PURE__ */ new Map();
227
+ const invokeCallback = async (callback) => {
228
+ const token = {};
229
+ activeCallbacks.add(token);
230
+ try {
231
+ return await callbackContext.run(token, callback);
232
+ } finally {
233
+ activeCallbacks.delete(token);
234
+ }
235
+ };
236
+ const track = (work) => {
237
+ const promise = Promise.resolve(work);
238
+ if (status === "drained" || status === "failed") return promise;
239
+ const settlement = promise.then((value) => ({
240
+ status: "fulfilled",
241
+ value
242
+ }), (reason) => ({
243
+ reason,
244
+ status: "rejected"
245
+ }));
246
+ settlements.set(promise, settlement);
247
+ settlement.then(() => {
248
+ if (status === "accepting") settlements.delete(promise);
249
+ });
250
+ return promise;
251
+ };
252
+ const scheduleRepair = () => {
253
+ if (closed || timer) return;
254
+ timer = setTimeout(() => {
255
+ timer = void 0;
256
+ wake(options.repairReason || "repair");
257
+ }, options.intervalMs);
258
+ timer.unref?.();
259
+ };
260
+ const execute = async () => {
261
+ queued = false;
262
+ if (running) {
263
+ rerun = true;
264
+ return await running;
265
+ }
266
+ let resolveActive;
267
+ let rejectActive;
268
+ const active = new Promise((resolve, reject) => {
269
+ resolveActive = resolve;
270
+ rejectActive = reject;
271
+ });
272
+ running = active;
273
+ const runAdmitted = async () => {
274
+ let failure;
275
+ let hasFailure = false;
276
+ do {
277
+ rerun = false;
278
+ const currentReason = reason;
279
+ reason = "coalesced";
280
+ try {
281
+ await invokeCallback(() => options.run(currentReason, { track }));
282
+ } catch (error) {
283
+ if (options.onError) try {
284
+ await invokeCallback(() => options.onError(error, currentReason));
285
+ } catch (reportingError) {
286
+ if (!hasFailure) {
287
+ failure = reportingError;
288
+ hasFailure = true;
289
+ }
290
+ }
291
+ }
292
+ } while (rerun);
293
+ if (hasFailure) throw failure;
294
+ };
295
+ const complete = (failure, hasFailure = false) => {
296
+ if (rerun) {
297
+ runAdmitted().then(() => complete(failure, hasFailure), (error) => complete(hasFailure ? failure : error, true));
298
+ return;
299
+ }
300
+ running = void 0;
301
+ scheduleRepair();
302
+ if (hasFailure) rejectActive(failure);
303
+ else resolveActive();
304
+ };
305
+ runAdmitted().then(() => complete(), (error) => complete(error, true));
306
+ await active;
307
+ };
308
+ const wake = (nextReason) => {
309
+ if (closed) return;
310
+ reason = nextReason;
311
+ if (timer) clearTimeout(timer);
312
+ timer = void 0;
313
+ if (running) {
314
+ rerun = true;
315
+ return;
316
+ }
317
+ if (queued) return;
318
+ queued = true;
319
+ queueMicrotask(() => void execute().catch(() => {}));
320
+ };
321
+ const drain = () => {
322
+ const caller = callbackContext.getStore();
323
+ if (caller && activeCallbacks.has(caller)) return Promise.reject(/* @__PURE__ */ new TypeError("Process reconciler callbacks cannot call drain() while active."));
324
+ if (drainPromise) return drainPromise;
325
+ drainPromise = (async () => {
326
+ let failure;
327
+ let hasFailure = false;
328
+ const retainFailure = (error) => {
329
+ if (hasFailure) return;
330
+ failure = error;
331
+ hasFailure = true;
332
+ };
333
+ const settleTrackedWork = async (final) => {
334
+ while (true) {
335
+ if (settlements.size === 0) {
336
+ if (final) status = hasFailure ? "failed" : "drained";
337
+ return;
338
+ }
339
+ const batch = [...settlements.entries()];
340
+ const results = await Promise.all(batch.map(([, settlement]) => settlement));
341
+ for (const [promise] of batch) settlements.delete(promise);
342
+ const rejected = results.find((result) => result.status === "rejected");
343
+ if (rejected) retainFailure(rejected.reason);
344
+ }
345
+ };
346
+ status = "draining";
347
+ closed = true;
348
+ if (queued && !running) await Promise.resolve();
349
+ const admittedRun = running;
350
+ if (timer) clearTimeout(timer);
351
+ timer = void 0;
352
+ try {
353
+ if (options.onQuiesce) await invokeCallback(options.onQuiesce);
354
+ } catch (error) {
355
+ retainFailure(error);
356
+ }
357
+ try {
358
+ await admittedRun;
359
+ } catch (error) {
360
+ retainFailure(error);
361
+ }
362
+ await settleTrackedWork(false);
363
+ if (!hasFailure && options.onDrained) try {
364
+ await invokeCallback(options.onDrained);
365
+ await new Promise((resolve) => setImmediate(resolve));
366
+ } catch (error) {
367
+ retainFailure(error);
368
+ }
369
+ await settleTrackedWork(true);
370
+ if (hasFailure) throw failure;
371
+ })();
372
+ return drainPromise;
373
+ };
374
+ const signal = options.signal === false ? void 0 : options.signal;
375
+ const listener = signal ? () => {
376
+ drain().catch(async (error) => {
377
+ try {
378
+ await options.onError?.(error, "drain");
379
+ } catch {}
380
+ });
381
+ } : void 0;
382
+ if (signal && listener) process.on(signal, listener);
383
+ scheduleRepair();
384
+ return {
385
+ async close() {
386
+ await drain();
387
+ if (signal && listener) process.off(signal, listener);
388
+ },
389
+ drain,
390
+ status: () => status,
391
+ track,
392
+ wake
393
+ };
394
+ }
395
+ //#endregion
396
+ export { createProcessReconciler, nodeRuntimeResources, resolveLinuxCgroupV2Path };
@@ -0,0 +1,37 @@
1
+ //#region src/internal/runtime-type.ts
2
+ function isCallableRepresentation(value) {
3
+ if (value === null || value === void 0 || Object(value) !== value) return false;
4
+ try {
5
+ Function.prototype.toString.call(value);
6
+ return true;
7
+ } catch {
8
+ return false;
9
+ }
10
+ }
11
+ /** Parses JavaScript runtime representation categories at Runtime boundaries. */
12
+ function hasRuntimeType(value, expected) {
13
+ if (expected === "undefined") return value === void 0;
14
+ if (expected === "object" && value === null) return true;
15
+ if (value === null || value === void 0) return false;
16
+ const isPrimitive = Object(value) !== value;
17
+ if (!isPrimitive) {
18
+ if (expected === "function") return isCallableRepresentation(value);
19
+ return expected === "object" && !isCallableRepresentation(value);
20
+ }
21
+ const tag = Object.prototype.toString.call(value);
22
+ switch (expected) {
23
+ case "bigint": return isPrimitive && tag === "[object BigInt]";
24
+ case "boolean": return isPrimitive && tag === "[object Boolean]";
25
+ case "function": return false;
26
+ case "number": return isPrimitive && tag === "[object Number]";
27
+ case "object": return false;
28
+ case "string": return isPrimitive && tag === "[object String]";
29
+ case "symbol": return isPrimitive && tag === "[object Symbol]";
30
+ }
31
+ throw new TypeError(`Unsupported runtime type: ${expected}`);
32
+ }
33
+ function isRuntimeObject(value) {
34
+ return value !== null && Object(value) === value;
35
+ }
36
+ //#endregion
37
+ export { isRuntimeObject as n, hasRuntimeType as t };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vite-hub/runtime",
3
- "version": "0.0.3",
3
+ "version": "0.0.4",
4
4
  "description": "Shared runtime context, capability, policy, approval, and tracing primitives for ViteHub.",
5
5
  "keywords": [
6
6
  "approvals",
@@ -23,10 +23,16 @@
23
23
  "package.json"
24
24
  ],
25
25
  "type": "module",
26
- "sideEffects": false,
26
+ "sideEffects": [
27
+ "./dist/drain.js"
28
+ ],
29
+ "bin": {
30
+ "vitehub-drain": "./dist/drain.js"
31
+ },
27
32
  "types": "./dist/index.d.ts",
28
33
  "exports": {
29
34
  ".": "./dist/index.js",
35
+ "./node": "./dist/node.js",
30
36
  "./package.json": "./package.json"
31
37
  },
32
38
  "devDependencies": {