@di-framework/cli-plugin-platform 6.1.1 → 6.2.0

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 (43) hide show
  1. package/README.md +259 -2
  2. package/dist/assets/http-adapter.js +6 -6
  3. package/dist/assets/sqlite/BUILD-INFO.txt +1 -1
  4. package/dist/assets/wit/deps/di-framework-pglite/package.wit +175 -0
  5. package/dist/bindings.js +7 -6
  6. package/dist/build.d.ts +31 -0
  7. package/dist/build.js +192 -12
  8. package/dist/console/catalog.js +2 -1
  9. package/dist/console/cluster.d.ts +3 -0
  10. package/dist/console/cluster.js +57 -4
  11. package/dist/control/auth.js +14 -2
  12. package/dist/deploy.d.ts +6 -0
  13. package/dist/deploy.js +27 -5
  14. package/dist/deps.js +1 -1
  15. package/dist/environment-names.d.ts +6 -0
  16. package/dist/environment-names.js +10 -0
  17. package/dist/index.d.ts +1 -1
  18. package/dist/index.js +1 -1
  19. package/dist/node-compat/console.js +16 -1
  20. package/dist/node-compat/crypto-subtle.d.ts +6 -0
  21. package/dist/node-compat/crypto-subtle.js +41 -4
  22. package/dist/node-compat/crypto.d.ts +3 -2
  23. package/dist/node-compat/crypto.js +66 -17
  24. package/dist/node-compat/fs.d.ts +24 -2
  25. package/dist/node-compat/fs.js +137 -15
  26. package/dist/node-compat/node-errors.d.ts +20 -0
  27. package/dist/node-compat/node-errors.js +73 -0
  28. package/dist/node-compat/storage.d.ts +3 -3
  29. package/dist/node-compat/wasi-random.d.ts +21 -1
  30. package/dist/node-compat/wasi-random.js +45 -12
  31. package/dist/pglite-encryption.d.ts +79 -0
  32. package/dist/pglite-encryption.js +196 -0
  33. package/dist/pglite.d.ts +153 -0
  34. package/dist/pglite.js +423 -0
  35. package/dist/project.d.ts +18 -0
  36. package/dist/project.js +49 -1
  37. package/dist/secret-admission.d.ts +21 -0
  38. package/dist/secret-admission.js +29 -0
  39. package/dist/wit.d.ts +3 -0
  40. package/dist/wit.js +12 -0
  41. package/dist/workload.d.ts +51 -0
  42. package/dist/workload.js +320 -40
  43. package/package.json +2 -2
@@ -5,7 +5,7 @@ import { hmac } from '@noble/hashes/hmac.js';
5
5
  import { sha256, sha384, sha512 } from '@noble/hashes/sha2.js';
6
6
  import { toArrayBuffer, toBytes } from './bytes.js';
7
7
  import { digestSync, hashFunction, normalizeHashName } from './crypto-hash.js';
8
- import { getRandomBytes } from './wasi-random.js';
8
+ import { fillRandom, getRandomBytes } from './wasi-random.js';
9
9
  const HASH_OUTPUT = {
10
10
  sha256: { noble: sha256, bits: 256 },
11
11
  sha384: { noble: sha384, bits: 384 },
@@ -55,10 +55,47 @@ function asKey(key) {
55
55
  function algorithmParams(algorithm) {
56
56
  return typeof algorithm === 'string' ? { name: algorithm } : { ...algorithm };
57
57
  }
58
+ /** Web Crypto's per-call `getRandomValues` quota, in bytes. */
59
+ export const GET_RANDOM_VALUES_MAX = 65_536;
60
+ const INTEGER_ARRAYS = [
61
+ 'Int8Array',
62
+ 'Uint8Array',
63
+ 'Uint8ClampedArray',
64
+ 'Int16Array',
65
+ 'Uint16Array',
66
+ 'Int32Array',
67
+ 'Uint32Array',
68
+ 'BigInt64Array',
69
+ 'BigUint64Array',
70
+ ];
71
+ function isIntegerTypedArray(value) {
72
+ if (!ArrayBuffer.isView(value))
73
+ return false;
74
+ return INTEGER_ARRAYS.some((name) => {
75
+ const ctor = globalThis[name];
76
+ return typeof ctor === 'function' && value instanceof ctor;
77
+ });
78
+ }
79
+ /** A Web Crypto `DOMException`, or an Error with the same name and legacy code without one. */
80
+ function domException(message, name, code) {
81
+ const DOMExceptionCtor = globalThis
82
+ .DOMException;
83
+ if (typeof DOMExceptionCtor === 'function')
84
+ return new DOMExceptionCtor(message, name);
85
+ return Object.assign(new Error(message), { name, code });
86
+ }
87
+ /**
88
+ * Like Node v22's `crypto.getRandomValues`: integer-type typed arrays only
89
+ * (`TypeMismatchError`), at most 65,536 bytes (`QuotaExceededError`).
90
+ */
58
91
  export function getRandomValues(array) {
59
- const view = new Uint8Array(array.buffer, array.byteOffset, array.byteLength);
60
- const random = getRandomBytes(view.length);
61
- view.set(random);
92
+ if (!isIntegerTypedArray(array)) {
93
+ throw domException('The data argument must be an integer-type TypedArray', 'TypeMismatchError', 17);
94
+ }
95
+ if (array.byteLength > GET_RANDOM_VALUES_MAX) {
96
+ throw domException('The requested length exceeds 65,536 bytes', 'QuotaExceededError', 22);
97
+ }
98
+ fillRandom(new Uint8Array(array.buffer, array.byteOffset, array.byteLength));
62
99
  return array;
63
100
  }
64
101
  export function randomUUID() {
@@ -2,8 +2,9 @@ import { createHash, createHmac, Hash, Hmac } from './crypto-hash.js';
2
2
  import { getRandomValues, randomUUID, subtle, webcrypto } from './crypto-subtle.js';
3
3
  export { createHash, createHmac, getRandomValues, Hash, Hmac, randomUUID, subtle, webcrypto };
4
4
  export declare function randomBytes(size: number, callback?: (error: Error | null, buffer: Uint8Array) => void): Uint8Array | undefined;
5
- export declare function randomFillSync<T extends ArrayBufferView>(buffer: T, offset?: number, size?: number): T;
6
- export declare function randomFill<T extends ArrayBufferView>(buffer: T, offset?: number | ((error: Error | null, buffer: T) => void), size?: number | ((error: Error | null, buffer: T) => void), callback?: (error: Error | null, buffer: T) => void): undefined | T;
5
+ type RandomTarget = ArrayBufferView | ArrayBuffer;
6
+ export declare function randomFillSync<T extends RandomTarget>(buffer: T, offset?: number, size?: number): T;
7
+ export declare function randomFill<T extends RandomTarget>(buffer: T, offset?: number | ((error: Error | null, buffer: T) => void), size?: number | ((error: Error | null, buffer: T) => void), callback?: (error: Error | null, buffer: T) => void): undefined | T;
7
8
  export declare function randomInt(min: number, max?: number | ((error: Error | null, value: number) => void), callback?: (error: Error | null, value: number) => void): number | undefined;
8
9
  export declare function timingSafeEqual(a: ArrayBufferView, b: ArrayBufferView): boolean;
9
10
  export declare const rng: typeof randomBytes;
@@ -1,7 +1,8 @@
1
1
  import { toBytes, toNodeBuffer } from './bytes.js';
2
2
  import { createHash, createHmac, Hash, Hmac } from './crypto-hash.js';
3
3
  import { getRandomValues, randomUUID, subtle, webcrypto } from './crypto-subtle.js';
4
- import { getRandomBytes } from './wasi-random.js';
4
+ import { invalidArgType, outOfRange } from './node-errors.js';
5
+ import { fillRandom, getRandomBytes, RANDOM_SIZE_MAX } from './wasi-random.js';
5
6
  export { createHash, createHmac, getRandomValues, Hash, Hmac, randomUUID, subtle, webcrypto };
6
7
  function cryptoUnsupported(name) {
7
8
  const error = new Error(`crypto.${name} is not implemented in the wasmCloud guest`);
@@ -14,6 +15,9 @@ function notImplemented(name) {
14
15
  };
15
16
  }
16
17
  export function randomBytes(size, callback) {
18
+ if (callback !== undefined && typeof callback !== 'function') {
19
+ throw invalidArgType('callback', 'of type function', callback);
20
+ }
17
21
  const bytes = toNodeBuffer(getRandomBytes(size));
18
22
  if (typeof callback === 'function') {
19
23
  queueMicrotask(() => callback(null, bytes));
@@ -21,34 +25,79 @@ export function randomBytes(size, callback) {
21
25
  }
22
26
  return bytes;
23
27
  }
24
- export function randomFillSync(buffer, offset, size) {
25
- const view = new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);
26
- const start = offset ?? 0;
27
- const length = size ?? view.length - start;
28
- view.set(getRandomBytes(length), start);
28
+ function randomTargetBytes(buffer) {
29
+ if (ArrayBuffer.isView(buffer)) {
30
+ return {
31
+ view: new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength),
32
+ elementSize: buffer.BYTES_PER_ELEMENT || 1,
33
+ };
34
+ }
35
+ if (buffer instanceof ArrayBuffer)
36
+ return { view: new Uint8Array(buffer), elementSize: 1 };
37
+ throw invalidArgType('buf', 'an instance of ArrayBuffer or ArrayBufferView', buffer);
38
+ }
39
+ /** Node v22 `assertOffset`: offsets count elements, are bounded by the byte length, and truncate. */
40
+ function randomOffset(offset, elementSize, byteLength) {
41
+ if (typeof offset !== 'number')
42
+ throw invalidArgType('offset', 'of type number', offset);
43
+ const bytes = offset * elementSize;
44
+ const max = Math.min(byteLength, RANDOM_SIZE_MAX);
45
+ if (Number.isNaN(bytes) || bytes > max || bytes < 0) {
46
+ throw outOfRange('offset', `>= 0 && <= ${max}`, bytes);
47
+ }
48
+ return Math.trunc(bytes);
49
+ }
50
+ /** Node v22 `assertSize`: sizes count elements and must fit after the offset. */
51
+ function randomSize(size, elementSize, offset, byteLength) {
52
+ if (typeof size !== 'number')
53
+ throw invalidArgType('size', 'of type number', size);
54
+ const bytes = size * elementSize;
55
+ if (Number.isNaN(bytes) || bytes > RANDOM_SIZE_MAX || bytes < 0) {
56
+ throw outOfRange('size', `>= 0 && <= ${RANDOM_SIZE_MAX}`, bytes);
57
+ }
58
+ if (bytes + offset > byteLength)
59
+ throw outOfRange('size + offset', `<= ${byteLength}`, bytes + offset);
60
+ return Math.trunc(bytes);
61
+ }
62
+ function fillRange(view, offset, size) {
63
+ if (size > 0)
64
+ fillRandom(view.subarray(offset, offset + size));
65
+ }
66
+ export function randomFillSync(buffer, offset = 0, size) {
67
+ const { view, elementSize } = randomTargetBytes(buffer);
68
+ const start = randomOffset(offset, elementSize, view.byteLength);
69
+ const length = size === undefined
70
+ ? view.byteLength - start
71
+ : randomSize(size, elementSize, start, view.byteLength);
72
+ fillRange(view, start, length);
29
73
  return buffer;
30
74
  }
31
75
  export function randomFill(buffer, offset, size, callback) {
76
+ const { view, elementSize } = randomTargetBytes(buffer);
32
77
  let start = 0;
33
- let length;
78
+ let length = view.byteLength;
34
79
  let cb;
35
80
  if (typeof offset === 'function')
36
81
  cb = offset;
82
+ else if (typeof size === 'function') {
83
+ cb = size;
84
+ start = randomOffset(offset, elementSize, view.byteLength);
85
+ length = view.byteLength - start;
86
+ }
37
87
  else {
38
- start = offset ?? 0;
39
- if (typeof size === 'function')
40
- cb = size;
41
- else {
42
- length = size;
43
- cb = callback;
44
- }
88
+ cb = callback;
89
+ start = randomOffset(offset ?? 0, elementSize, view.byteLength);
90
+ length =
91
+ size === undefined
92
+ ? view.byteLength - start
93
+ : randomSize(size, elementSize, start, view.byteLength);
45
94
  }
46
- const filled = randomFillSync(buffer, start, length);
95
+ fillRange(view, start, length);
47
96
  if (cb !== undefined) {
48
- queueMicrotask(() => cb(null, filled));
97
+ queueMicrotask(() => cb(null, buffer));
49
98
  return undefined;
50
99
  }
51
- return filled;
100
+ return buffer;
52
101
  }
53
102
  export function randomInt(min, max, callback) {
54
103
  let low = 0;
@@ -42,8 +42,30 @@ export declare function fstatSync(fd: number): {
42
42
  };
43
43
  export declare function openSync(path: string, flags?: string | number, _mode?: number): number;
44
44
  export declare function closeSync(fd: number): void;
45
- export declare function readSync(fd: number, buffer: Uint8Array, offset?: number, length?: number, position?: number | null): number;
46
- export declare function writeSync(fd: number, data: string | Uint8Array, offset?: number, length?: number, position?: number | null): number;
45
+ type ReadOptions = {
46
+ offset?: number;
47
+ length?: number;
48
+ position?: number | bigint | null;
49
+ };
50
+ type WriteOptions = {
51
+ offset?: number;
52
+ length?: number;
53
+ position?: number | null;
54
+ };
55
+ export declare function readSync(fd: number, buffer: ArrayBufferView, ...args: [
56
+ offsetOrOptions?: number | ReadOptions | null,
57
+ length?: number,
58
+ position?: number | bigint | null
59
+ ]): number;
60
+ /**
61
+ * Node v22 `fs.writeSync`, in both forms:
62
+ * - `writeSync(fd, buffer, offset?, length?, position?)` (or an options object), and
63
+ * - `writeSync(fd, string, position?, encoding?)`.
64
+ * Like Node (and libuv), a position that is not a non-negative safe-integer Number
65
+ * (BigInt, NaN, 1.5, -1, ...) writes at the current position, so it never reaches the
66
+ * stored descriptor's u64 offset.
67
+ */
68
+ export declare function writeSync(fd: number, data: string | ArrayBufferView, offsetOrPosition?: number | WriteOptions | null, lengthOrEncoding?: number | string | null, requestedPosition?: number | bigint | null): number;
47
69
  export declare function createReadStream(path: string): {
48
70
  on(event: string, listener: (...args: unknown[]) => void): unknown;
49
71
  once(event: string, listener: (...args: unknown[]) => void): unknown;
@@ -1,3 +1,4 @@
1
+ import { invalidArgType, invalidArgValue, outOfRange, validateInteger } from './node-errors.js';
1
2
  import { nodeCompatSeed } from './seed-virtual.js';
2
3
  import { storage as wasiStorage } from './storage.js';
3
4
  /** Host-mounted storage; paths outside it stay in the in-memory filesystem below. */
@@ -229,42 +230,163 @@ export function closeSync(fd) {
229
230
  if (!openHandles.delete(fd))
230
231
  throw errno('EBADF', 'close', String(fd), -9);
231
232
  }
232
- export function readSync(fd, buffer, offset = 0, length = buffer.byteLength - offset, position = null) {
233
+ function validateView(buffer) {
234
+ if (!ArrayBuffer.isView(buffer)) {
235
+ throw invalidArgType('buffer', 'an instance of Buffer, TypedArray, or DataView', buffer);
236
+ }
237
+ }
238
+ function viewBytes(buffer) {
239
+ return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);
240
+ }
241
+ /**
242
+ * Node v22 `fs.readSync` argument handling, so only valid u64 lengths and offsets reach
243
+ * the stored descriptor (componentize-qjs 0.4.4-di.5+ traps on any other Number):
244
+ * three arguments (or an object) are options; `length` is truncated with `| 0` and a
245
+ * zero length returns before any other check; `position` `null`/`-1`/`-1n` means the
246
+ * current position. Returns `null` for a zero-length read.
247
+ */
248
+ function readRange(buffer, args) {
249
+ let offset = args[0];
250
+ let length = args[1];
251
+ let position = args[2];
252
+ if (args.length <= 1 || typeof offset === 'object') {
253
+ if (offset !== undefined && offset !== null && typeof offset !== 'object') {
254
+ throw invalidArgType('options', 'of type object', offset);
255
+ }
256
+ const options = (offset ?? {});
257
+ offset = options.offset ?? 0;
258
+ length = options.length ?? buffer.byteLength - offset;
259
+ position = options.position ?? null;
260
+ }
261
+ const start = offset === undefined ? 0 : validateInteger(offset, 'offset', 0);
262
+ const count = length | 0;
263
+ if (count === 0)
264
+ return null;
265
+ if (buffer.byteLength === 0) {
266
+ throw invalidArgValue('buffer', 'is empty and cannot be written', '<Buffer >');
267
+ }
268
+ if (count < 0)
269
+ throw outOfRange('length', '>= 0', count);
270
+ if (start + count > buffer.byteLength) {
271
+ throw outOfRange('length', `<= ${buffer.byteLength - start}`, count);
272
+ }
273
+ if (position === null || position === undefined)
274
+ return { offset: start, length: count, position: null };
275
+ if (typeof position === 'number') {
276
+ validateInteger(position, 'position', -1);
277
+ return { offset: start, length: count, position: position === -1 ? null : position };
278
+ }
279
+ if (typeof position === 'bigint') {
280
+ const max = 2n ** 63n - 1n - BigInt(count);
281
+ if (!(position >= -1n && position <= max)) {
282
+ throw outOfRange('position', `>= -1 && <= ${max}`, position);
283
+ }
284
+ return { offset: start, length: count, position: position === -1n ? null : position };
285
+ }
286
+ throw invalidArgType('position', 'of type bigint or integer', position);
287
+ }
288
+ export function readSync(fd, buffer, ...args) {
289
+ validateView(buffer);
290
+ const range = readRange(buffer, args);
291
+ if (range === null)
292
+ return 0;
233
293
  const handle = openHandles.get(fd);
234
294
  if (handle === undefined)
235
295
  throw errno('EBADF', 'read', String(fd), -9);
236
- const start = position === null ? handle.position : position;
296
+ const { offset, length, position } = range;
297
+ const start = position ?? handle.position;
237
298
  const slice = handle.stored
238
299
  ? storage.readAt(handle.path, length, start)
239
- : asBytes(nodeCompatSeed.files[handle.path] ?? '').subarray(start, start + length);
240
- buffer.set(slice, offset);
300
+ : (() => {
301
+ const content = asBytes(nodeCompatSeed.files[handle.path] ?? '');
302
+ // A BigInt position beyond MAX_SAFE_INTEGER is past the end of any in-memory file.
303
+ if (typeof start === 'bigint' && start > BigInt(content.byteLength))
304
+ return new Uint8Array();
305
+ const from = Number(start);
306
+ return content.subarray(from, from + length);
307
+ })();
308
+ viewBytes(buffer).set(slice, offset);
241
309
  if (position === null)
242
- handle.position = start + slice.byteLength;
310
+ handle.position = handle.position + slice.byteLength;
243
311
  return slice.byteLength;
244
312
  }
245
- export function writeSync(fd, data, offset, length, position) {
313
+ /** Node's `validateOffsetLengthWrite` plus `validateInt32(length)`. */
314
+ function writeRange(buffer, offsetArg, lengthArg, positionArg) {
315
+ let offset = offsetArg;
316
+ let length = lengthArg;
317
+ let position = positionArg;
318
+ if (typeof offset === 'object') {
319
+ const options = (offset ?? {});
320
+ offset = options.offset ?? 0;
321
+ length = options.length ?? buffer.byteLength - offset;
322
+ position = options.position ?? null;
323
+ }
324
+ const start = offset === undefined || offset === null ? 0 : validateInteger(offset, 'offset', 0);
325
+ const count = typeof length === 'number' ? length : buffer.byteLength - start;
326
+ if (start > buffer.byteLength)
327
+ throw outOfRange('offset', `<= ${buffer.byteLength}`, start);
328
+ if (count > buffer.byteLength - start) {
329
+ throw outOfRange('length', `<= ${buffer.byteLength - start}`, count);
330
+ }
331
+ if (count < 0)
332
+ throw outOfRange('length', '>= 0', count);
333
+ if (!Number.isInteger(count))
334
+ throw outOfRange('length', 'an integer', count);
335
+ return { bytes: viewBytes(buffer).subarray(start, start + count), position };
336
+ }
337
+ function encodeString(data, encoding) {
338
+ if (encoding === 'hex' && data.length % 2 !== 0) {
339
+ throw invalidArgValue('encoding', `is invalid for data of length ${data.length}`, "'hex'");
340
+ }
341
+ if (typeof encoding === 'string' &&
342
+ typeof Buffer !== 'undefined' &&
343
+ Buffer.isEncoding(encoding)) {
344
+ const encoded = Buffer.from(data, encoding);
345
+ return new Uint8Array(encoded.buffer, encoded.byteOffset, encoded.byteLength);
346
+ }
347
+ return new TextEncoder().encode(data);
348
+ }
349
+ /**
350
+ * Node v22 `fs.writeSync`, in both forms:
351
+ * - `writeSync(fd, buffer, offset?, length?, position?)` (or an options object), and
352
+ * - `writeSync(fd, string, position?, encoding?)`.
353
+ * Like Node (and libuv), a position that is not a non-negative safe-integer Number
354
+ * (BigInt, NaN, 1.5, -1, ...) writes at the current position, so it never reaches the
355
+ * stored descriptor's u64 offset.
356
+ */
357
+ export function writeSync(fd, data, offsetOrPosition, lengthOrEncoding, requestedPosition) {
358
+ let bytes;
359
+ let position;
360
+ if (ArrayBuffer.isView(data)) {
361
+ ({ bytes, position } = writeRange(data, offsetOrPosition, lengthOrEncoding, requestedPosition));
362
+ }
363
+ else if (typeof data === 'string') {
364
+ bytes = encodeString(data, lengthOrEncoding);
365
+ position = offsetOrPosition;
366
+ }
367
+ else {
368
+ throw invalidArgType('buffer', 'of type string or an instance of Buffer, TypedArray, or DataView', data);
369
+ }
246
370
  const handle = openHandles.get(fd);
247
371
  if (handle === undefined)
248
372
  throw errno('EBADF', 'write', String(fd), -9);
249
- const bytes = asBytes(data).subarray(offset ?? 0, (offset ?? 0) + (length ?? asBytes(data).byteLength));
373
+ const explicit = typeof position === 'number' && Number.isSafeInteger(position) && position >= 0
374
+ ? position
375
+ : null;
250
376
  if (handle.stored) {
251
- const target = position ?? (handle.flags.includes('a') ? 'end' : handle.position);
377
+ const target = explicit ?? (handle.flags.includes('a') ? 'end' : handle.position);
252
378
  const end = storage.writeAt(handle.path, bytes, target);
253
- if (position == null)
379
+ if (explicit === null)
254
380
  handle.position = end;
255
381
  return bytes.byteLength;
256
382
  }
257
383
  const existing = asBytes(nodeCompatSeed.files[handle.path] ?? '');
258
- const start = position == null
259
- ? handle.flags.includes('a')
260
- ? existing.byteLength
261
- : handle.position
262
- : position;
384
+ const start = explicit ?? (handle.flags.includes('a') ? existing.byteLength : handle.position);
263
385
  const next = new Uint8Array(Math.max(existing.byteLength, start + bytes.byteLength));
264
386
  next.set(existing, 0);
265
387
  next.set(bytes, start);
266
388
  nodeCompatSeed.files[handle.path] = new TextDecoder().decode(next);
267
- if (position == null)
389
+ if (explicit === null)
268
390
  handle.position = start + bytes.byteLength;
269
391
  return bytes.byteLength;
270
392
  }
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Node-shaped argument errors for the overlays. Messages follow Node v22's
3
+ * `ERR_OUT_OF_RANGE` / `ERR_INVALID_ARG_TYPE` / `ERR_INVALID_ARG_VALUE` text, including the
4
+ * `1_000_000` separators Node prints for values beyond 2**32. Do not import WASI from here.
5
+ */
6
+ type CodedError<E extends Error> = E & {
7
+ code: string;
8
+ };
9
+ /** `ERR_OUT_OF_RANGE`: `The value of "<name>" is out of range. It must be <range>. Received …`. */
10
+ export declare function outOfRange(name: string, range: string, received: unknown): CodedError<RangeError>;
11
+ /** `ERR_INVALID_ARG_TYPE`; `expected` is Node's phrase, e.g. `of type number`. */
12
+ export declare function invalidArgType(name: string, expected: string, received: unknown): CodedError<TypeError>;
13
+ /** `ERR_INVALID_ARG_VALUE`: `The argument '<name>' <reason>. Received …`. */
14
+ export declare function invalidArgValue(name: string, reason: string, received: string): CodedError<TypeError>;
15
+ /**
16
+ * Node's `validateInteger(value, name, min)`: a number, an integer, and within
17
+ * `[min, Number.MAX_SAFE_INTEGER]`.
18
+ */
19
+ export declare function validateInteger(value: unknown, name: string, min?: number): number;
20
+ export {};
@@ -0,0 +1,73 @@
1
+ /**
2
+ * Node-shaped argument errors for the overlays. Messages follow Node v22's
3
+ * `ERR_OUT_OF_RANGE` / `ERR_INVALID_ARG_TYPE` / `ERR_INVALID_ARG_VALUE` text, including the
4
+ * `1_000_000` separators Node prints for values beyond 2**32. Do not import WASI from here.
5
+ */
6
+ function coded(error, code) {
7
+ return Object.assign(error, { code });
8
+ }
9
+ function addNumericalSeparator(value) {
10
+ let result = '';
11
+ let i = value.length;
12
+ const start = value.startsWith('-') ? 1 : 0;
13
+ for (; i >= start + 4; i -= 3)
14
+ result = `_${value.slice(i - 3, i)}${result}`;
15
+ return `${value.slice(0, i)}${result}`;
16
+ }
17
+ function formatRangeReceived(value) {
18
+ if (typeof value === 'number' && Number.isInteger(value) && Math.abs(value) > 2 ** 32) {
19
+ return addNumericalSeparator(String(value));
20
+ }
21
+ if (typeof value === 'bigint') {
22
+ const text = String(value);
23
+ return `${value > 2n ** 32n || value < -(2n ** 32n) ? addNumericalSeparator(text) : text}n`;
24
+ }
25
+ return String(value);
26
+ }
27
+ function formatTypeReceived(value) {
28
+ if (value === null || value === undefined)
29
+ return `Received ${value}`;
30
+ if (typeof value === 'function')
31
+ return `Received function ${value.name}`;
32
+ if (typeof value === 'object') {
33
+ const name = value.constructor?.name;
34
+ return name ? `Received an instance of ${name}` : 'Received [Object: null prototype] {}';
35
+ }
36
+ let shown;
37
+ if (typeof value === 'string') {
38
+ shown = `'${value.length > 28 ? `${value.slice(0, 25)}...` : value}'`;
39
+ }
40
+ else if (typeof value === 'bigint') {
41
+ shown = `${value}n`;
42
+ }
43
+ else {
44
+ shown = String(value);
45
+ }
46
+ return `Received type ${typeof value} (${shown})`;
47
+ }
48
+ /** `ERR_OUT_OF_RANGE`: `The value of "<name>" is out of range. It must be <range>. Received …`. */
49
+ export function outOfRange(name, range, received) {
50
+ return coded(new RangeError(`The value of "${name}" is out of range. It must be ${range}. Received ${formatRangeReceived(received)}`), 'ERR_OUT_OF_RANGE');
51
+ }
52
+ /** `ERR_INVALID_ARG_TYPE`; `expected` is Node's phrase, e.g. `of type number`. */
53
+ export function invalidArgType(name, expected, received) {
54
+ return coded(new TypeError(`The "${name}" argument must be ${expected}. ${formatTypeReceived(received)}`), 'ERR_INVALID_ARG_TYPE');
55
+ }
56
+ /** `ERR_INVALID_ARG_VALUE`: `The argument '<name>' <reason>. Received …`. */
57
+ export function invalidArgValue(name, reason, received) {
58
+ return coded(new TypeError(`The argument '${name}' ${reason}. Received ${received}`), 'ERR_INVALID_ARG_VALUE');
59
+ }
60
+ /**
61
+ * Node's `validateInteger(value, name, min)`: a number, an integer, and within
62
+ * `[min, Number.MAX_SAFE_INTEGER]`.
63
+ */
64
+ export function validateInteger(value, name, min = Number.MIN_SAFE_INTEGER) {
65
+ if (typeof value !== 'number')
66
+ throw invalidArgType(name, 'of type number', value);
67
+ if (!Number.isInteger(value))
68
+ throw outOfRange(name, 'an integer', value);
69
+ if (value < min || value > Number.MAX_SAFE_INTEGER) {
70
+ throw outOfRange(name, `>= ${min} && <= ${Number.MAX_SAFE_INTEGER}`, value);
71
+ }
72
+ return value;
73
+ }
@@ -12,8 +12,8 @@ export type WasiDescriptor = {
12
12
  write?: boolean;
13
13
  mutateDirectory?: boolean;
14
14
  }): WasiDescriptor;
15
- read(length: number, offset: number): [Uint8Array | number[], boolean];
16
- write(buffer: Uint8Array, offset: number): number;
15
+ read(length: number, offset: number | bigint): [Uint8Array | number[], boolean];
16
+ write(buffer: Uint8Array, offset: number): number | bigint;
17
17
  setSize(size: number): void;
18
18
  stat(): WasiStat;
19
19
  statAt(pathFlags: {
@@ -70,7 +70,7 @@ export declare function createStorage(preopens: () => Preopen[], prefixes?: type
70
70
  readFile(path: string): Uint8Array;
71
71
  writeFile(path: string, bytes: Uint8Array): void;
72
72
  appendFile(path: string, bytes: Uint8Array): void;
73
- readAt(path: string, length: number, offset: number): Uint8Array;
73
+ readAt(path: string, length: number, offset: number | bigint): Uint8Array;
74
74
  writeAt(path: string, bytes: Uint8Array, offset: number | "end"): number;
75
75
  truncate(path: string): void;
76
76
  stat: (path: string) => StorageStat;
@@ -1,2 +1,22 @@
1
- /** Guest CSPRNG from WASI 0.3 `wasi:random/random`. */
1
+ /** Node's `kMaxPossibleLength` for `crypto.randomBytes` / `randomFillSync` sizes: 2**31 - 1. */
2
+ export declare const RANDOM_SIZE_MAX: number;
3
+ /**
4
+ * Largest `max-len` one `wasi:random` call asks for. Bigger requests are filled in
5
+ * chunks so the host never allocates more than this per call (it matches the Web
6
+ * Crypto `getRandomValues` quota).
7
+ */
8
+ export declare const RANDOM_CHUNK = 65536;
9
+ /**
10
+ * Validates a byte count exactly as Node v22's `crypto.randomBytes` does: a number
11
+ * (`ERR_INVALID_ARG_TYPE` otherwise, BigInt included) in `[0, 2**31 - 1]`
12
+ * (`ERR_OUT_OF_RANGE` otherwise, NaN included). Like Node, fractional sizes are
13
+ * accepted and truncated (`1.5` gives one byte). Returns the truncated count.
14
+ */
15
+ export declare function validateRandomSize(size: unknown, name?: string): number;
16
+ /**
17
+ * Fills `target` from the guest CSPRNG in calls of at most {@link RANDOM_CHUNK} bytes.
18
+ * Callers validate the length first.
19
+ */
20
+ export declare function fillRandom(target: Uint8Array): Uint8Array;
21
+ /** Guest CSPRNG from WASI 0.3 `wasi:random/random`, validated like `crypto.randomBytes`. */
2
22
  export declare function getRandomBytes(size: number): Uint8Array;
@@ -1,5 +1,14 @@
1
1
  import { getRandomBytes as wasiGetRandomBytes } from 'wasi:random/random@0.3.0';
2
2
  import { toBytes } from './bytes.js';
3
+ import { invalidArgType, outOfRange } from './node-errors.js';
4
+ /** Node's `kMaxPossibleLength` for `crypto.randomBytes` / `randomFillSync` sizes: 2**31 - 1. */
5
+ export const RANDOM_SIZE_MAX = 2 ** 31 - 1;
6
+ /**
7
+ * Largest `max-len` one `wasi:random` call asks for. Bigger requests are filled in
8
+ * chunks so the host never allocates more than this per call (it matches the Web
9
+ * Crypto `getRandomValues` quota).
10
+ */
11
+ export const RANDOM_CHUNK = 65_536;
3
12
  function unwrapRandom(value) {
4
13
  if (value !== null && typeof value === 'object' && 'tag' in value) {
5
14
  const result = value;
@@ -9,17 +18,41 @@ function unwrapRandom(value) {
9
18
  }
10
19
  return toBytes(value);
11
20
  }
12
- /** Guest CSPRNG from WASI 0.3 `wasi:random/random`. */
13
- export function getRandomBytes(size) {
14
- if (!Number.isFinite(size) || size < 0) {
15
- throw new RangeError(`getRandomBytes size must be a non-negative integer, received ${size}`);
21
+ /**
22
+ * Validates a byte count exactly as Node v22's `crypto.randomBytes` does: a number
23
+ * (`ERR_INVALID_ARG_TYPE` otherwise, BigInt included) in `[0, 2**31 - 1]`
24
+ * (`ERR_OUT_OF_RANGE` otherwise, NaN included). Like Node, fractional sizes are
25
+ * accepted and truncated (`1.5` gives one byte). Returns the truncated count.
26
+ */
27
+ export function validateRandomSize(size, name = 'size') {
28
+ if (typeof size !== 'number')
29
+ throw invalidArgType(name, 'of type number', size);
30
+ if (Number.isNaN(size) || size < 0 || size > RANDOM_SIZE_MAX) {
31
+ throw outOfRange(name, `>= 0 && <= ${RANDOM_SIZE_MAX}`, size);
32
+ }
33
+ return Math.trunc(size);
34
+ }
35
+ function requestRandom(length) {
36
+ // `max-len` is a WIT u64; BigInt is the canonical JS representation, and
37
+ // componentize-qjs 0.4.4-di.5+ traps on a Number that is not a safe integer.
38
+ const bytes = unwrapRandom(wasiGetRandomBytes(BigInt(length)));
39
+ if (bytes.length < length) {
40
+ throw new Error(`wasi:random returned ${bytes.length} bytes, expected ${length}`);
16
41
  }
17
- if (size === 0)
18
- return new Uint8Array();
19
- const bytes = unwrapRandom(wasiGetRandomBytes(size));
20
- if (bytes.length === size)
21
- return bytes.slice();
22
- if (bytes.length > size)
23
- return bytes.slice(0, size);
24
- throw new Error(`wasi:random returned ${bytes.length} bytes, expected ${size}`);
42
+ return bytes.length === length ? bytes : bytes.subarray(0, length);
43
+ }
44
+ /**
45
+ * Fills `target` from the guest CSPRNG in calls of at most {@link RANDOM_CHUNK} bytes.
46
+ * Callers validate the length first.
47
+ */
48
+ export function fillRandom(target) {
49
+ for (let offset = 0; offset < target.length; offset += RANDOM_CHUNK) {
50
+ target.set(requestRandom(Math.min(RANDOM_CHUNK, target.length - offset)), offset);
51
+ }
52
+ return target;
53
+ }
54
+ /** Guest CSPRNG from WASI 0.3 `wasi:random/random`, validated like `crypto.randomBytes`. */
55
+ export function getRandomBytes(size) {
56
+ const length = validateRandomSize(size);
57
+ return fillRandom(new Uint8Array(length));
25
58
  }