@exortek/apikey 1.1.1 → 1.1.3

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/index.mjs CHANGED
@@ -349,20 +349,33 @@ class ApiKeyError extends BaseError {
349
349
  * `@exortek/shared/validate`: **schema** for whole options objects,
350
350
  * **asserts** for one-liner argument guards at the call site.
351
351
  *
352
- * The consumer surface is {@link defineGuards} (or the raw
353
- * {@link bindAsserts} for full control). Each package binds the assert
354
- * set to its own typed error class once (in `internal/guards.js`), so
355
- * every argument failure throws that package's class —
356
- * `err instanceof CryptoError` holds and users see at a glance which
357
- * package raised the error. The bound `parse` bridges
358
- * `@exortek/shared/validate` schemas to the same error class.
352
+ * Every guard is exported as a `make…` **factory** taking the binding
353
+ * package's `wrap` and returning the guard itself. A package binds the
354
+ * guards it calls once, in its `internal/guards.js`, so every argument
355
+ * failure throws that package's error class — `err instanceof
356
+ * CryptoError` holds, and users see at a glance which package raised it.
357
+ *
358
+ * // packages/<pkg>/src/internal/guards.js
359
+ * import { makeAssertString, makeInvalidArgument } from '@exortek/shared/asserts';
360
+ * import { CryptoError, ErrorCode } from '../errors.js';
361
+ *
362
+ * const wrap = (message, extra) => new CryptoError(ErrorCode.INVALID_ARGUMENT, message, extra);
363
+ *
364
+ * export const assertString = makeAssertString(wrap);
365
+ * export const invalidArgument = makeInvalidArgument(wrap);
366
+ *
367
+ * Importing each factory by name is what makes the module
368
+ * tree-shakeable. An earlier version handed back one object carrying
369
+ * every guard, so all of them shipped in every package's bundle no
370
+ * matter how few were used — `assertBoolean` reached fifteen published
371
+ * packages without a single call site. Import what you call.
359
372
  *
360
373
  * **Path naming convention** (used as the `name` argument):
361
374
  *
362
375
  * `<publicFunction>[.options|.config][.<field>]`
363
376
  *
364
- * - `assertString(name, 'createUser.name')` — top-level arg
365
- * - `assertPositiveInt(n, 'scrypt.options.r')` — nested option
377
+ * - `assertString(name, 'createUser.name')` — top-level arg
378
+ * - `assertPositiveInt(n, 'scrypt.options.r')` — nested option
366
379
  * - `assertBytesOrString(pwd, 'pepper.wrap.password')` — method arg
367
380
  *
368
381
  * Keep the path short: the emitted error is `"<name> must be <desc>"`,
@@ -371,301 +384,34 @@ class ApiKeyError extends BaseError {
371
384
  * encryptSymmetric()"), not for restating the field.
372
385
  */
373
386
 
374
- /**
375
- * @typedef {{ cause?: unknown }} WrapExtra
376
- * Extra options forwarded to the wrap function, so `invalidArgument`
377
- * sites that catch an underlying error can preserve the `cause` chain
378
- * without falling back to a raw `new PackageError(...)`.
379
- *
380
- * @typedef {(message: string, extra?: WrapExtra) => Error} WrapFn
381
- * Constructs (never throws) the binding package's error, e.g.
382
- * `(m, { cause } = {}) => new CryptoError(ErrorCode.INVALID_ARGUMENT, m, { cause })`.
383
- *
384
- * @typedef {{ hint?: string }} AssertOptions
385
- * `hint` is appended to the message after an em-dash — use it for
386
- * actionable guidance ("pass the exact bytes returned by …").
387
- *
388
- * @typedef {{ safeParse: (input: unknown, path?: string) => { ok: true, value: unknown } | { ok: false, errors: string[] } }} ParseableSchema
389
- */
390
387
 
391
388
  /**
392
- * Build the failure message. `description` completes the sentence
393
- * `"<name> must be <description>"`; `hint` (optional) follows an
394
- * em-dash.
389
+ * Construct (not throw) the bound error with a free-form message — for
390
+ * `throw invalidArgument('…')` sites that don't fit the `X must be Y`
391
+ * shape (canonicalisation errors, cross-field constraint failures). Pass
392
+ * `{ cause }` when the failure was triggered by an underlying throw whose
393
+ * chain matters (e.g. `JSON.stringify` on a bigint).
395
394
  *
396
- * @param {string} name
397
- * @param {string} description
398
- * @param {string} [hint]
399
- * @returns {string}
395
+ * @type {(wrap: WrapFn) => (msg: string, extra?: WrapExtra) => Error}
400
396
  */
401
- function message(name, description, hint) {
402
- return `${name} must be ${description}${hint ? ` — ${hint}` : ''}`;
403
- }
404
-
405
- const ENCODINGS = new Set(['hex', 'base64', 'base64url']);
397
+ const makeInvalidArgument = wrap => (msg, extra) => wrap(msg, extra);
406
398
 
407
399
  /**
408
- * Bind the assert set to a package's error class. Call once per
409
- * package (conventionally in `internal/guards.js`) and import the
410
- * bound object everywhere:
411
- *
412
- * import { bindAsserts } from '@exortek/shared/asserts';
413
- * import { CryptoError, ErrorCode } from '../errors.js';
414
- * export const g = bindAsserts((m) => new CryptoError(ErrorCode.INVALID_ARGUMENT, m));
415
- *
416
- * // call sites:
417
- * g.assertPositiveInt(options.iterations, 'options.iterations');
418
- * const cfg = g.parse(OptionsSchema, options, 'options');
419
- *
420
- * @param {WrapFn} wrap
400
+ * Argument guards bound to `ApiKeyError` — the package-wide binding of
401
+ * `@exortek/shared/asserts`. Import guards from here, never from the
402
+ * shared module directly.
421
403
  */
422
- function bindAsserts(wrap) {
423
- /**
424
- * @param {string} name
425
- * @param {string} description
426
- * @param {AssertOptions} [opts]
427
- * @returns {never}
428
- */
429
- function fail(name, description, opts) {
430
- throw wrap(message(name, description, opts?.hint));
431
- }
432
404
 
433
- /**
434
- * Assert that `value` is a plain object (not `null`, not an array,
435
- * not a primitive).
436
- * @param {unknown} value
437
- * @param {string} name
438
- * @param {AssertOptions} [opts]
439
- */
440
- function assertObject(value, name, opts) {
441
- if (value === null || typeof value !== 'object' || Array.isArray(value)) {
442
- fail(name, 'an object', opts);
443
- }
444
- }
445
-
446
- return {
447
- /**
448
- * Construct (not throw) the bound error with a free-form message —
449
- * for `throw g.invalidArgument('…')` sites that don't fit the
450
- * `X must be Y` shape (canonicalisation errors, cross-field
451
- * constraint failures). Pass `{ cause }` when the argument-shape
452
- * failure was triggered by an underlying throw whose chain matters
453
- * (e.g. `JSON.stringify` on a bigint).
454
- *
455
- * @param {string} msg
456
- * @param {WrapExtra} [extra]
457
- * @returns {Error}
458
- */
459
- invalidArgument(msg, extra) {
460
- return wrap(msg, extra);
461
- },
462
-
463
- /**
464
- * Validate `input` against a `@exortek/shared/validate` schema;
465
- * failures throw the bound error carrying every collected message.
466
- * The bridge that keeps schema validation on the package's own
467
- * error surface.
468
- *
469
- * @param {ParseableSchema} schema
470
- * @param {unknown} input
471
- * @param {string} [path='options']
472
- * @returns {unknown} the parsed (possibly defaulted) value
473
- */
474
- parse(schema, input, path = 'options') {
475
- const r = schema.safeParse(input, path);
476
- if (!r.ok) {
477
- throw wrap(r.errors.join('; '));
478
- }
479
- return r.value;
480
- },
481
-
482
- /**
483
- * Assert that `value` is a non-negative safe integer (`0, 1, 2, …`).
484
- * @param {unknown} value
485
- * @param {string} name Argument name to include in the error message.
486
- * @param {AssertOptions} [opts]
487
- */
488
- assertNonNegativeInt(value, name, opts) {
489
- if (!Number.isSafeInteger(value) || /** @type {number} */ (value) < 0) {
490
- fail(name, 'a non-negative safe integer', opts);
491
- }
492
- },
493
-
494
- /**
495
- * Assert that `value` is a strictly positive safe integer (`1, 2, 3, …`).
496
- * @param {unknown} value
497
- * @param {string} name
498
- * @param {AssertOptions} [opts]
499
- */
500
- assertPositiveInt(value, name, opts) {
501
- if (!Number.isSafeInteger(value) || /** @type {number} */ (value) <= 0) {
502
- fail(name, 'a positive integer', opts);
503
- }
504
- },
505
-
506
- /**
507
- * Assert that `value` fits in a 48-bit unsigned integer (`0 … 2^48 − 1`).
508
- * Used for Unix millisecond timestamps in UUID v7 / ULID.
509
- * @param {unknown} value
510
- * @param {string} name
511
- * @param {AssertOptions} [opts]
512
- */
513
- assertUint48(value, name, opts) {
514
- if (
515
- !Number.isSafeInteger(value) ||
516
- /** @type {number} */ (value) < 0 ||
517
- /** @type {number} */ (value) > 0xffffffffffff
518
- ) {
519
- fail(name, 'a non-negative safe integer ≤ 2^48 − 1 (Unix ms since epoch)', opts);
520
- }
521
- },
522
-
523
- /**
524
- * Assert that `value` is a string (may be empty).
525
- * @param {unknown} value
526
- * @param {string} name
527
- * @param {AssertOptions} [opts]
528
- */
529
- assertString(value, name, opts) {
530
- if (typeof value !== 'string') {
531
- fail(name, 'a string', opts);
532
- }
533
- },
534
-
535
- /**
536
- * Assert that `value` is a non-empty string.
537
- * @param {unknown} value
538
- * @param {string} name
539
- * @param {AssertOptions} [opts]
540
- */
541
- assertNonEmptyString(value, name, opts) {
542
- if (typeof value !== 'string' || value.length === 0) {
543
- fail(name, 'a non-empty string', opts);
544
- }
545
- },
546
-
547
- /**
548
- * Assert that `value` is a boolean.
549
- * @param {unknown} value
550
- * @param {string} name
551
- * @param {AssertOptions} [opts]
552
- */
553
- assertBoolean(value, name, opts) {
554
- if (typeof value !== 'boolean') {
555
- fail(name, 'a boolean', opts);
556
- }
557
- },
558
-
559
- /**
560
- * Assert that `value` is a function.
561
- * @param {unknown} value
562
- * @param {string} name
563
- * @param {AssertOptions} [opts]
564
- */
565
- assertFunction(value, name, opts) {
566
- if (typeof value !== 'function') {
567
- fail(name, 'a function', opts);
568
- }
569
- },
570
-
571
- assertObject,
572
-
573
- /**
574
- * Assert that `value` is either `undefined` or a plain object —
575
- * the "optional options object" pattern.
576
- * @param {unknown} value
577
- * @param {string} name
578
- * @param {AssertOptions} [opts]
579
- */
580
- assertOptionalObject(value, name, opts) {
581
- if (value === undefined) {
582
- return;
583
- }
584
- assertObject(value, name, opts);
585
- },
586
-
587
- /**
588
- * Assert that `value` is a byte buffer (`Buffer` or `Uint8Array`) —
589
- * strings are NOT accepted. For already-encoded material where a
590
- * string would be ambiguous (ciphertext, signatures, raw key bytes).
591
- * @param {unknown} value
592
- * @param {string} name
593
- * @param {AssertOptions} [opts]
594
- */
595
- assertBytes(value, name, opts) {
596
- if (!Buffer.isBuffer(value) && !(value instanceof Uint8Array)) {
597
- fail(name, 'a Buffer or Uint8Array', opts);
598
- }
599
- },
600
-
601
- /**
602
- * Assert that `value` is either a string or a byte buffer (`Buffer`
603
- * or `Uint8Array`).
604
- * @param {unknown} value
605
- * @param {string} name
606
- * @param {AssertOptions} [opts]
607
- */
608
- assertBytesOrString(value, name, opts) {
609
- if (typeof value !== 'string' && !Buffer.isBuffer(value) && !(value instanceof Uint8Array)) {
610
- fail(name, 'a string or Buffer', opts);
611
- }
612
- },
613
-
614
- /**
615
- * Assert that `encoding` is one of the accepted output/input
616
- * encodings. Pass `allowBuffer: false` where a `Buffer` output makes
617
- * no sense (verifying a string signature, decoding a token payload).
618
- *
619
- * @param {unknown} encoding
620
- * @param {string} name
621
- * @param {AssertOptions & { allowBuffer?: boolean }} [opts]
622
- */
623
- assertEncoding(encoding, name, opts) {
624
- const allowBuffer = opts?.allowBuffer !== false;
625
- const valid = (typeof encoding === 'string' && ENCODINGS.has(encoding)) || (allowBuffer && encoding === 'buffer');
626
- if (!valid) {
627
- const list = allowBuffer ? "'hex', 'base64', 'base64url', or 'buffer'" : "'hex', 'base64', or 'base64url'";
628
- fail(name, list, opts);
629
- }
630
- },
631
- };
632
- }
633
405
 
634
406
  /**
635
- * One-line sugar over {@link bindAsserts} — the overwhelmingly common
636
- * pattern where a package binds every argument-shape failure to its
637
- * own error class + `INVALID_ARGUMENT` code. Emits the standard
638
- * `new ErrorClass(code, message, { cause })` shape, so the underlying
639
- * `BaseError` `{ cause, status, details }` options object is respected.
640
- *
641
- * // packages/<pkg>/src/internal/guards.js
642
- * import { defineGuards } from '@exortek/shared/asserts';
643
- * import { PasswordError, ErrorCode } from '../errors.js';
407
+ * Bind every guard this package calls to ApiKeyError, so an argument-shape
408
+ * failure anywhere carries one class and one code to branch on.
644
409
  *
645
- * export const { assertString, invalidArgument, parse } =
646
- * defineGuards(PasswordError, ErrorCode.INVALID_ARGUMENT);
647
- *
648
- * Reach for the raw {@link bindAsserts} when you need a different
649
- * mapping (an alt code, a decorated message) — it stays available.
650
- *
651
- * @param {new (code: string, message: string, options?: { cause?: unknown }) => Error} ErrorClass
652
- * @param {string} code
653
- */
654
- function defineGuards(ErrorClass, code) {
655
- return bindAsserts((message, extra) => new ErrorClass(code, message, extra));
656
- }
657
-
658
- /**
659
- * Argument guards bound to `ApiKeyError` — the package-wide binding of
660
- * `@exortek/shared/asserts`. Import guards from here, never from the
661
- * shared module directly.
410
+ * @type {import('@exortek/shared/asserts').WrapFn}
662
411
  */
412
+ const wrap = (message, extra) => new ApiKeyError(ErrorCode.INVALID_ARGUMENT, message, extra);
663
413
 
664
-
665
- const { invalidArgument} = defineGuards(
666
- ApiKeyError,
667
- ErrorCode.INVALID_ARGUMENT,
668
- );
414
+ const invalidArgument = makeInvalidArgument(wrap);
669
415
 
670
416
  /**
671
417
  * Scope match helpers.
@@ -1,4 +1,4 @@
1
1
  export const invalidArgument: (msg: string, extra?: WrapExtra) => Error;
2
2
  export const parse: (schema: ParseableSchema, input: unknown, path?: string) => unknown;
3
- export const assertObject: (value: unknown, name: string, opts?: AssertOptions) => void;
4
- export const assertNonEmptyString: (value: unknown, name: string, opts?: AssertOptions) => void;
3
+ export const assertObject: Function;
4
+ export const assertNonEmptyString: Function;