@venizia/ignis-helpers 0.4.8-7 → 0.4.8-9

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 (59) hide show
  1. package/dist/esm/common/constants/http.d.ts +2 -0
  2. package/dist/esm/common/constants/http.js +2 -0
  3. package/dist/esm/common/constants/http.js.map +1 -1
  4. package/dist/esm/modules/storage/base.d.ts +9 -4
  5. package/dist/esm/modules/storage/base.js +10 -4
  6. package/dist/esm/modules/storage/base.js.map +1 -1
  7. package/dist/esm/modules/storage/bun-s3/helper.d.ts +2 -3
  8. package/dist/esm/modules/storage/bun-s3/helper.js +6 -5
  9. package/dist/esm/modules/storage/bun-s3/helper.js.map +1 -1
  10. package/dist/esm/modules/storage/bun-s3/utility.d.ts +2 -1
  11. package/dist/esm/modules/storage/bun-s3/utility.js +4 -3
  12. package/dist/esm/modules/storage/bun-s3/utility.js.map +1 -1
  13. package/dist/esm/modules/storage/common/constants.d.ts +7 -0
  14. package/dist/esm/modules/storage/common/constants.js +5 -0
  15. package/dist/esm/modules/storage/common/constants.js.map +1 -1
  16. package/dist/esm/modules/storage/common/errors.d.ts +17 -0
  17. package/dist/esm/modules/storage/common/errors.js +14 -0
  18. package/dist/esm/modules/storage/common/errors.js.map +1 -1
  19. package/dist/esm/modules/storage/common/types.d.ts +17 -4
  20. package/dist/esm/modules/storage/common/types.js.map +1 -1
  21. package/dist/esm/modules/storage/disk/helper.d.ts +1 -0
  22. package/dist/esm/modules/storage/disk/helper.js +2 -1
  23. package/dist/esm/modules/storage/disk/helper.js.map +1 -1
  24. package/dist/esm/modules/uid/common/constants.d.ts +26 -0
  25. package/dist/esm/modules/uid/common/constants.js +27 -0
  26. package/dist/esm/modules/uid/common/constants.js.map +1 -1
  27. package/dist/esm/modules/uid/common/crc32.d.ts +22 -0
  28. package/dist/esm/modules/uid/common/crc32.js +39 -0
  29. package/dist/esm/modules/uid/common/crc32.js.map +1 -0
  30. package/dist/esm/modules/uid/common/random.d.ts +46 -0
  31. package/dist/esm/modules/uid/common/random.js +94 -0
  32. package/dist/esm/modules/uid/common/random.js.map +1 -0
  33. package/dist/esm/modules/uid/common/segments.d.ts +36 -0
  34. package/dist/esm/modules/uid/common/segments.js +81 -0
  35. package/dist/esm/modules/uid/common/segments.js.map +1 -0
  36. package/dist/esm/modules/uid/common/types.d.ts +45 -1
  37. package/dist/esm/modules/uid/common/types.js.map +1 -1
  38. package/dist/esm/modules/uid/index.d.ts +2 -0
  39. package/dist/esm/modules/uid/index.js +2 -0
  40. package/dist/esm/modules/uid/index.js.map +1 -1
  41. package/dist/esm/modules/uid/numeric.d.ts +18 -0
  42. package/dist/esm/modules/uid/numeric.js +31 -0
  43. package/dist/esm/modules/uid/numeric.js.map +1 -0
  44. package/dist/esm/modules/uid/opaque.d.ts +0 -15
  45. package/dist/esm/modules/uid/opaque.js +17 -107
  46. package/dist/esm/modules/uid/opaque.js.map +1 -1
  47. package/dist/esm/modules/uid/token.d.ts +57 -0
  48. package/dist/esm/modules/uid/token.js +218 -0
  49. package/dist/esm/modules/uid/token.js.map +1 -0
  50. package/dist/esm/modules/uid/uuid/helper.d.ts +2 -1
  51. package/dist/esm/modules/uid/uuid/helper.js +2 -1
  52. package/dist/esm/modules/uid/uuid/helper.js.map +1 -1
  53. package/dist/esm/utilities/parse.utility.d.ts +5 -0
  54. package/dist/esm/utilities/parse.utility.js +17 -1
  55. package/dist/esm/utilities/parse.utility.js.map +1 -1
  56. package/dist/esm/utilities/request.utility.d.ts +4 -0
  57. package/dist/esm/utilities/request.utility.js +10 -1
  58. package/dist/esm/utilities/request.utility.js.map +1 -1
  59. package/package.json +2 -2
@@ -1 +1 @@
1
- {"version":3,"file":"constants.js","sourceRoot":"","sources":["../../../../../src/modules/uid/common/constants.ts"],"names":[],"mappings":"AAEA,gEAAgE;AAChE;;;;GAIG;AACH,MAAM,OAAO,YAAY;IACvB,kHAAkH;aAClG,WAAM,GAAG,gEAAgE,CAAC;IAE1F,2FAA2F;aAC3E,WAAM,GAAG,4DAA4D,CAAC;IAEtF,uNAAuN;aACvM,cAAS,GAAG,kCAAkC,CAAC;IAE/D,sGAAsG;aACtF,aAAQ,GAAG,oDAAoD,CAAC;;AAGlF,gEAAgE;AAChE;;;;;GAKG;AACH,MAAM,OAAO,YAAY;aACP,UAAK,GAAG,OAAO,CAAC;aAChB,UAAK,GAAG,OAAO,CAAC;aAChB,UAAK,GAAG,OAAO,CAAC;aAEhB,eAAU,GAAG,IAAI,GAAG,CAAC,CAAC,IAAI,CAAC,KAAK,EAAE,IAAI,CAAC,KAAK,EAAE,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC;IAE3E,MAAM,CAAC,OAAO,CAAC,KAAa;QAC1B,OAAO,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;IACpC,CAAC;;AAMH,gEAAgE;AAChE;;;;;;;;;;;;;;;;GAgBG;AACH,MAAM,CAAC,MAAM,kBAAkB,GAAG,CAAC,CAAC;AAEpC,uFAAuF;AACvF,MAAM,CAAC,MAAM,qBAAqB,GAAG,EAAE,CAAC;AAExC,iLAAiL;AACjL,MAAM,CAAC,MAAM,wBAAwB,GAAG,EAAE,CAAC;AAE3C,yIAAyI;AACzI,MAAM,CAAC,MAAM,qBAAqB,GAAG,GAAG,CAAC","sourcesContent":["import { type TConstValue } from '@/common/types';\n\n// -------------------------------------------------------------\n/**\n * Which characters an id may be built from. Every set here drops the pairs that collide in common\n * fonts - zero against capital O, one against capital I and lowercase L - so a human copying an id\n * off a screen cannot produce a different one.\n */\nexport class UidAlphabets {\n /** Digits and both cases, nothing removed. Densest, and the only set here a human should not be asked to read. */\n static readonly BASE62 = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';\n\n /** BASE62 minus `0`, `O`, `I`, `l`. 58 characters - the Bitcoin/Stripe-shaped alphabet. */\n static readonly BASE58 = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';\n\n /** Crockford's base32: uppercase only, without `I`, `L`, `O` (ambiguous) and `U` (so no word can read as an obscenity). Case-insensitive by construction, which is what makes it safe in a CI column or a hostname. */\n static readonly CROCKFORD = '0123456789ABCDEFGHJKMNPQRSTVWXYZ';\n\n /** BASE58 without vowels, so no real word - and no accidental obscenity - can form. 50 characters. */\n static readonly NO_VOWEL = '123456789BCDFGHJKLMNPQRSTVWXYZbcdfghjkmnpqrstvwxyz';\n}\n\n// -------------------------------------------------------------\n/**\n * Whether an id mixes letter cases. Applied to the ALPHABET before sampling, never to the finished\n * string: folding the output would silently halve the entropy the caller thinks they asked for, and\n * would fold an excluded character back in - uppercasing a lowercase alphabet reintroduces `I` and\n * `O` that {@link UidAlphabets} took out.\n */\nexport class UidCaseForms {\n static readonly UPPER = 'upper';\n static readonly LOWER = 'lower';\n static readonly MIXED = 'mixed';\n\n static readonly SCHEME_SET = new Set([this.UPPER, this.LOWER, this.MIXED]);\n\n static isValid(input: string): input is TUidCaseForm {\n return this.SCHEME_SET.has(input);\n }\n}\n\n/** A value of {@link UidCaseForms}. */\nexport type TUidCaseForm = TConstValue<typeof UidCaseForms>;\n\n// -------------------------------------------------------------\n/**\n * Six characters of {@link UidAlphabets.CROCKFORD} is 2^30 combinations, which is an airline record\n * locator - and it works for the same three reasons, not because 2^30 is large:\n *\n * 1. SCOPED. A record locator is unique per carrier, not worldwide. Use `prefix` per entity type so\n * each kind of id gets its own space.\n * 2. RECYCLED. Airlines reuse a locator once the trip is over.\n * 3. RETRIED. The reservation system regenerates on conflict.\n *\n * Measured, so nobody has to guess: a 1% chance of at least one collision arrives at roughly 4,600\n * ids in ONE space, and 50% at roughly 38,000.\n *\n * A `prefix` PARTITIONS the space - `INV-7K2MQ9` cannot collide with `CUS-7K2MQ9` - so each entity\n * type gets its own. It does NOT make an id unique inside that space, and no length does: this\n * generator is probabilistic by construction. The column needs a unique index, and the insert needs\n * to regenerate on violation rather than checking first, which races.\n */\nexport const DEFAULT_UID_LENGTH = 6;\n\n/** Below this an `exclude` list has eaten the alphabet, and the ids stop being ids. */\nexport const MIN_UID_ALPHABET_SIZE = 16;\n\n/** Draws allowed when an `isAvailable` check keeps rejecting. Bounded rather than endless: a space with no room left would otherwise hang the caller instead of telling them. */\nexport const DEFAULT_UID_MAX_ATTEMPTS = 10;\n\n/** Separates the prefix from the body when both are enabled. Not in any {@link UidAlphabets} set, so an id splits back apart cleanly. */\nexport const DEFAULT_UID_DELIMITER = '_';\n"]}
1
+ {"version":3,"file":"constants.js","sourceRoot":"","sources":["../../../../../src/modules/uid/common/constants.ts"],"names":[],"mappings":"AAEA,gEAAgE;AAChE;;;;GAIG;AACH,MAAM,OAAO,YAAY;IACvB,kHAAkH;aAClG,WAAM,GAAG,gEAAgE,CAAC;IAE1F,2FAA2F;aAC3E,WAAM,GAAG,4DAA4D,CAAC;IAEtF,uNAAuN;aACvM,cAAS,GAAG,kCAAkC,CAAC;IAE/D,sGAAsG;aACtF,aAAQ,GAAG,oDAAoD,CAAC;;AAGlF,gEAAgE;AAChE;;;;;GAKG;AACH,MAAM,OAAO,YAAY;aACP,UAAK,GAAG,OAAO,CAAC;aAChB,UAAK,GAAG,OAAO,CAAC;aAChB,UAAK,GAAG,OAAO,CAAC;aAEhB,eAAU,GAAG,IAAI,GAAG,CAAC,CAAC,IAAI,CAAC,KAAK,EAAE,IAAI,CAAC,KAAK,EAAE,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC;IAE3E,MAAM,CAAC,OAAO,CAAC,KAAa;QAC1B,OAAO,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;IACpC,CAAC;;AAMH,gEAAgE;AAChE;;;;;;;;;;;;;;;;GAgBG;AACH,MAAM,CAAC,MAAM,kBAAkB,GAAG,CAAC,CAAC;AAEpC,uFAAuF;AACvF,MAAM,CAAC,MAAM,qBAAqB,GAAG,EAAE,CAAC;AAExC,iLAAiL;AACjL,MAAM,CAAC,MAAM,wBAAwB,GAAG,EAAE,CAAC;AAE3C,yIAAyI;AACzI,MAAM,CAAC,MAAM,qBAAqB,GAAG,GAAG,CAAC;AAEzC,gEAAgE;AAChE,sCAAsC;AACtC,MAAM,OAAO,iBAAiB;IAC5B;;;OAGG;aACa,WAAM,GAAG,QAAQ,CAAC;IAElC,kHAAkH;aAClG,QAAG,GAAG,KAAK,CAAC;IAE5B;;;;OAIG;aACa,cAAS,GAAG,WAAW,CAAC;aAExB,eAAU,GAAG,IAAI,GAAG,CAAC,CAAC,IAAI,CAAC,MAAM,EAAE,IAAI,CAAC,GAAG,EAAE,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC;IAE9E,MAAM,CAAC,OAAO,CAAC,KAAa;QAC1B,OAAO,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;IACpC,CAAC;;AAMH,2GAA2G;AAC3G,MAAM,CAAC,MAAM,mBAAmB,GAAG,EAAE,CAAC;AAEtC,0FAA0F;AAC1F,MAAM,CAAC,MAAM,eAAe,GAAG,EAAE,CAAC;AAElC,kJAAkJ;AAClJ,MAAM,CAAC,MAAM,sBAAsB,GAAG,CAAC,CAAC","sourcesContent":["import { type TConstValue } from '@/common/types';\n\n// -------------------------------------------------------------\n/**\n * Which characters an id may be built from. Every set here drops the pairs that collide in common\n * fonts - zero against capital O, one against capital I and lowercase L - so a human copying an id\n * off a screen cannot produce a different one.\n */\nexport class UidAlphabets {\n /** Digits and both cases, nothing removed. Densest, and the only set here a human should not be asked to read. */\n static readonly BASE62 = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';\n\n /** BASE62 minus `0`, `O`, `I`, `l`. 58 characters - the Bitcoin/Stripe-shaped alphabet. */\n static readonly BASE58 = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';\n\n /** Crockford's base32: uppercase only, without `I`, `L`, `O` (ambiguous) and `U` (so no word can read as an obscenity). Case-insensitive by construction, which is what makes it safe in a CI column or a hostname. */\n static readonly CROCKFORD = '0123456789ABCDEFGHJKMNPQRSTVWXYZ';\n\n /** BASE58 without vowels, so no real word - and no accidental obscenity - can form. 50 characters. */\n static readonly NO_VOWEL = '123456789BCDFGHJKLMNPQRSTVWXYZbcdfghjkmnpqrstvwxyz';\n}\n\n// -------------------------------------------------------------\n/**\n * Whether an id mixes letter cases. Applied to the ALPHABET before sampling, never to the finished\n * string: folding the output would silently halve the entropy the caller thinks they asked for, and\n * would fold an excluded character back in - uppercasing a lowercase alphabet reintroduces `I` and\n * `O` that {@link UidAlphabets} took out.\n */\nexport class UidCaseForms {\n static readonly UPPER = 'upper';\n static readonly LOWER = 'lower';\n static readonly MIXED = 'mixed';\n\n static readonly SCHEME_SET = new Set([this.UPPER, this.LOWER, this.MIXED]);\n\n static isValid(input: string): input is TUidCaseForm {\n return this.SCHEME_SET.has(input);\n }\n}\n\n/** A value of {@link UidCaseForms}. */\nexport type TUidCaseForm = TConstValue<typeof UidCaseForms>;\n\n// -------------------------------------------------------------\n/**\n * Six characters of {@link UidAlphabets.CROCKFORD} is 2^30 combinations, which is an airline record\n * locator - and it works for the same three reasons, not because 2^30 is large:\n *\n * 1. SCOPED. A record locator is unique per carrier, not worldwide. Use `prefix` per entity type so\n * each kind of id gets its own space.\n * 2. RECYCLED. Airlines reuse a locator once the trip is over.\n * 3. RETRIED. The reservation system regenerates on conflict.\n *\n * Measured, so nobody has to guess: a 1% chance of at least one collision arrives at roughly 4,600\n * ids in ONE space, and 50% at roughly 38,000.\n *\n * A `prefix` PARTITIONS the space - `INV-7K2MQ9` cannot collide with `CUS-7K2MQ9` - so each entity\n * type gets its own. It does NOT make an id unique inside that space, and no length does: this\n * generator is probabilistic by construction. The column needs a unique index, and the insert needs\n * to regenerate on violation rather than checking first, which races.\n */\nexport const DEFAULT_UID_LENGTH = 6;\n\n/** Below this an `exclude` list has eaten the alphabet, and the ids stop being ids. */\nexport const MIN_UID_ALPHABET_SIZE = 16;\n\n/** Draws allowed when an `isAvailable` check keeps rejecting. Bounded rather than endless: a space with no room left would otherwise hang the caller instead of telling them. */\nexport const DEFAULT_UID_MAX_ATTEMPTS = 10;\n\n/** Separates the prefix from the body when both are enabled. Not in any {@link UidAlphabets} set, so an id splits back apart cleanly. */\nexport const DEFAULT_UID_DELIMITER = '_';\n\n// -------------------------------------------------------------\n/** How a token is written as text. */\nexport class UidTokenEncodings {\n /**\n * `0-9 A-Z a-z`, each character equally likely ({@link UidAlphabets.BASE62}). 32 bytes of entropy is\n * 43 characters. The default: its alphabet holds no `_` or `-`, so a prefix delimiter and a URL both take it cleanly.\n */\n static readonly BASE62 = 'base62';\n\n /** Lowercase `0-9 a-f`. 32 bytes is 64 characters. Safe anywhere text is, including a case-insensitive column. */\n static readonly HEX = 'hex';\n\n /**\n * URL-safe base64 without padding: `A-Z a-z 0-9 - _`. 32 bytes is 43 characters. Kept for a token\n * whose format already is base64url (the mail verification token). It holds `-` and `_`, the\n * characters a delimiter is made of, so a prefix delimiter is refused unless it avoids both.\n */\n static readonly BASE64URL = 'base64url';\n\n static readonly SCHEME_SET = new Set([this.BASE62, this.HEX, this.BASE64URL]);\n\n static isValid(input: string): input is TUidTokenEncoding {\n return this.SCHEME_SET.has(input);\n }\n}\n\n/** A value of {@link UidTokenEncodings}. */\nexport type TUidTokenEncoding = TConstValue<typeof UidTokenEncodings>;\n\n/** 32 bytes is 256 bits, the size of a SHA-256 output and of an AES-256 key: no brute force reaches it. */\nexport const DEFAULT_TOKEN_BYTES = 32;\n\n/** 128 bits. Below this a token can be guessed offline, so the constructor refuses it. */\nexport const MIN_TOKEN_BYTES = 16;\n\n/** Six digits is the length of a one-time code in an email or an app: 10^6 combinations, which is why it needs an expiry and an attempt limit. */\nexport const DEFAULT_NUMERIC_LENGTH = 6;\n"]}
@@ -0,0 +1,22 @@
1
+ /**
2
+ * CRC-32 (IEEE 802.3, reflected polynomial `0xEDB88320`), the checksum of zlib, PNG and Ethernet.
3
+ * Internal: not exported from the barrel. Pure JS, so the `uid` module stays browser-pure - no
4
+ * `node:zlib`, no `Bun.hash`.
5
+ *
6
+ * A CRC detects a typo; it does not authenticate. The polynomial is public, so anyone can compute
7
+ * the checksum of any text.
8
+ */
9
+ export declare class Crc32 {
10
+ private static readonly POLYNOMIAL;
11
+ private static readonly TABLE_SIZE;
12
+ private static readonly BITS_PER_BYTE;
13
+ private static readonly INITIAL;
14
+ /** Built on first use, one entry per byte value. */
15
+ private static table?;
16
+ private static getTable;
17
+ /** The unsigned 32-bit CRC of the UTF-8 bytes of `text`. `''` is `0`. */
18
+ static of(opts: {
19
+ text: string;
20
+ }): number;
21
+ }
22
+ //# sourceMappingURL=crc32.d.ts.map
@@ -0,0 +1,39 @@
1
+ /**
2
+ * CRC-32 (IEEE 802.3, reflected polynomial `0xEDB88320`), the checksum of zlib, PNG and Ethernet.
3
+ * Internal: not exported from the barrel. Pure JS, so the `uid` module stays browser-pure - no
4
+ * `node:zlib`, no `Bun.hash`.
5
+ *
6
+ * A CRC detects a typo; it does not authenticate. The polynomial is public, so anyone can compute
7
+ * the checksum of any text.
8
+ */
9
+ export class Crc32 {
10
+ static { this.POLYNOMIAL = 0xedb88320; }
11
+ static { this.TABLE_SIZE = 256; }
12
+ static { this.BITS_PER_BYTE = 8; }
13
+ static { this.INITIAL = 0xffffffff; }
14
+ static getTable() {
15
+ if (Crc32.table) {
16
+ return Crc32.table;
17
+ }
18
+ const table = new Uint32Array(Crc32.TABLE_SIZE);
19
+ for (let index = 0; index < Crc32.TABLE_SIZE; index++) {
20
+ let value = index;
21
+ for (let bit = 0; bit < Crc32.BITS_PER_BYTE; bit++) {
22
+ value = value & 1 ? (value >>> 1) ^ Crc32.POLYNOMIAL : value >>> 1;
23
+ }
24
+ table[index] = value >>> 0;
25
+ }
26
+ Crc32.table = table;
27
+ return table;
28
+ }
29
+ /** The unsigned 32-bit CRC of the UTF-8 bytes of `text`. `''` is `0`. */
30
+ static of(opts) {
31
+ const table = Crc32.getTable();
32
+ let crc = Crc32.INITIAL;
33
+ for (const byte of new TextEncoder().encode(opts.text)) {
34
+ crc = table[(crc ^ byte) & 0xff] ^ (crc >>> Crc32.BITS_PER_BYTE);
35
+ }
36
+ return (crc ^ Crc32.INITIAL) >>> 0;
37
+ }
38
+ }
39
+ //# sourceMappingURL=crc32.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"crc32.js","sourceRoot":"","sources":["../../../../../src/modules/uid/common/crc32.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AACH,MAAM,OAAO,KAAK;aACQ,eAAU,GAAG,UAAU,CAAC;aACxB,eAAU,GAAG,GAAG,CAAC;aACjB,kBAAa,GAAG,CAAC,CAAC;aAClB,YAAO,GAAG,UAAU,CAAC;IAKrC,MAAM,CAAC,QAAQ;QACrB,IAAI,KAAK,CAAC,KAAK,EAAE,CAAC;YAChB,OAAO,KAAK,CAAC,KAAK,CAAC;QACrB,CAAC;QAED,MAAM,KAAK,GAAG,IAAI,WAAW,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC;QAEhD,KAAK,IAAI,KAAK,GAAG,CAAC,EAAE,KAAK,GAAG,KAAK,CAAC,UAAU,EAAE,KAAK,EAAE,EAAE,CAAC;YACtD,IAAI,KAAK,GAAG,KAAK,CAAC;YAElB,KAAK,IAAI,GAAG,GAAG,CAAC,EAAE,GAAG,GAAG,KAAK,CAAC,aAAa,EAAE,GAAG,EAAE,EAAE,CAAC;gBACnD,KAAK,GAAG,KAAK,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,KAAK,KAAK,CAAC,CAAC,GAAG,KAAK,CAAC,UAAU,CAAC,CAAC,CAAC,KAAK,KAAK,CAAC,CAAC;YACrE,CAAC;YAED,KAAK,CAAC,KAAK,CAAC,GAAG,KAAK,KAAK,CAAC,CAAC;QAC7B,CAAC;QAED,KAAK,CAAC,KAAK,GAAG,KAAK,CAAC;QAEpB,OAAO,KAAK,CAAC;IACf,CAAC;IAED,yEAAyE;IACzE,MAAM,CAAC,EAAE,CAAC,IAAsB;QAC9B,MAAM,KAAK,GAAG,KAAK,CAAC,QAAQ,EAAE,CAAC;QAC/B,IAAI,GAAG,GAAG,KAAK,CAAC,OAAO,CAAC;QAExB,KAAK,MAAM,IAAI,IAAI,IAAI,WAAW,EAAE,CAAC,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC;YACvD,GAAG,GAAG,KAAK,CAAC,CAAC,GAAG,GAAG,IAAI,CAAC,GAAG,IAAI,CAAC,GAAG,CAAC,GAAG,KAAK,KAAK,CAAC,aAAa,CAAC,CAAC;QACnE,CAAC;QAED,OAAO,CAAC,GAAG,GAAG,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;IACrC,CAAC","sourcesContent":["/**\n * CRC-32 (IEEE 802.3, reflected polynomial `0xEDB88320`), the checksum of zlib, PNG and Ethernet.\n * Internal: not exported from the barrel. Pure JS, so the `uid` module stays browser-pure - no\n * `node:zlib`, no `Bun.hash`.\n *\n * A CRC detects a typo; it does not authenticate. The polynomial is public, so anyone can compute\n * the checksum of any text.\n */\nexport class Crc32 {\n private static readonly POLYNOMIAL = 0xedb88320;\n private static readonly TABLE_SIZE = 256;\n private static readonly BITS_PER_BYTE = 8;\n private static readonly INITIAL = 0xffffffff;\n\n /** Built on first use, one entry per byte value. */\n private static table?: Uint32Array;\n\n private static getTable(): Uint32Array {\n if (Crc32.table) {\n return Crc32.table;\n }\n\n const table = new Uint32Array(Crc32.TABLE_SIZE);\n\n for (let index = 0; index < Crc32.TABLE_SIZE; index++) {\n let value = index;\n\n for (let bit = 0; bit < Crc32.BITS_PER_BYTE; bit++) {\n value = value & 1 ? (value >>> 1) ^ Crc32.POLYNOMIAL : value >>> 1;\n }\n\n table[index] = value >>> 0;\n }\n\n Crc32.table = table;\n\n return table;\n }\n\n /** The unsigned 32-bit CRC of the UTF-8 bytes of `text`. `''` is `0`. */\n static of(opts: { text: string }): number {\n const table = Crc32.getTable();\n let crc = Crc32.INITIAL;\n\n for (const byte of new TextEncoder().encode(opts.text)) {\n crc = table[(crc ^ byte) & 0xff] ^ (crc >>> Crc32.BITS_PER_BYTE);\n }\n\n return (crc ^ Crc32.INITIAL) >>> 0;\n }\n}\n"]}
@@ -0,0 +1,46 @@
1
+ /**
2
+ * The one place the `uid` module draws randomness. Internal: not exported from the barrel, so it is
3
+ * not API. Every helper here (`OpaqueUidHelper`, `TokenUidHelper`, `NumericUidHelper`) draws through it, which is
4
+ * what keeps `Math.random` out of an identifier.
5
+ */
6
+ export declare class UidRandom {
7
+ /** `crypto.getRandomValues` refuses more than this per call (a browser throws `QuotaExceededError`). */
8
+ private static readonly MAX_BYTES_PER_CALL;
9
+ /** `crypto.randomInt` draws a 48-bit value; `below` keeps the same width, so `max` goes up to 2 ** 48. */
10
+ private static readonly DRAW_BYTES;
11
+ private static readonly BYTE_RANGE;
12
+ /** The largest `max` {@link UidRandom.below} accepts. */
13
+ static readonly MAX_BELOW: number;
14
+ /**
15
+ * `crypto.getRandomValues`, never `Math.random`. Unlike `crypto.randomUUID`, this one is NOT
16
+ * restricted to a secure context, so it works on a plain-http origin and inside a browser Worker.
17
+ * Throws when Web Crypto is missing instead of falling back to something weaker.
18
+ */
19
+ static bytes(opts: {
20
+ count: number;
21
+ }): Uint8Array;
22
+ /** How many random bytes to draw per refill, per remaining character. Rejection throws some away, so asking for exactly `length` would round-trip to the entropy source repeatedly. */
23
+ private static readonly SAMPLING_OVERDRAW;
24
+ /**
25
+ * `length` characters of `alphabet`, each equally likely. A draw is masked to the smallest
26
+ * `2^n - 1` that covers every alphabet index and an index past the alphabet is discarded, because
27
+ * a plain `byte % size` would favour the first `256 % size` characters - a bias a caller cannot see
28
+ * and cannot undo.
29
+ */
30
+ static sample(opts: {
31
+ alphabet: string;
32
+ length: number;
33
+ }): string;
34
+ /** Whether `max` is a usable bound for {@link UidRandom.below}: an integer from 1 to {@link UidRandom.MAX_BELOW}. */
35
+ static isValidMax(opts: {
36
+ max: number;
37
+ }): boolean;
38
+ /**
39
+ * A uniform integer in `[0, max)`. A draw at or above the largest multiple of `max` is thrown away
40
+ * and drawn again, so no value is likelier than another (`value % max` alone favours the low ones).
41
+ */
42
+ static below(opts: {
43
+ max: number;
44
+ }): number;
45
+ }
46
+ //# sourceMappingURL=random.d.ts.map
@@ -0,0 +1,94 @@
1
+ import { HTTP } from '../../../common/constants/index.js';
2
+ import { getError } from '../../error/index.js';
3
+ /**
4
+ * The one place the `uid` module draws randomness. Internal: not exported from the barrel, so it is
5
+ * not API. Every helper here (`OpaqueUidHelper`, `TokenUidHelper`, `NumericUidHelper`) draws through it, which is
6
+ * what keeps `Math.random` out of an identifier.
7
+ */
8
+ export class UidRandom {
9
+ /** `crypto.getRandomValues` refuses more than this per call (a browser throws `QuotaExceededError`). */
10
+ static { this.MAX_BYTES_PER_CALL = 65_536; }
11
+ /** `crypto.randomInt` draws a 48-bit value; `below` keeps the same width, so `max` goes up to 2 ** 48. */
12
+ static { this.DRAW_BYTES = 6; }
13
+ static { this.BYTE_RANGE = 256; }
14
+ /** The largest `max` {@link UidRandom.below} accepts. */
15
+ static { this.MAX_BELOW = 2 ** (UidRandom.DRAW_BYTES * 8); }
16
+ /**
17
+ * `crypto.getRandomValues`, never `Math.random`. Unlike `crypto.randomUUID`, this one is NOT
18
+ * restricted to a secure context, so it works on a plain-http origin and inside a browser Worker.
19
+ * Throws when Web Crypto is missing instead of falling back to something weaker.
20
+ */
21
+ static bytes(opts) {
22
+ const source = globalThis.crypto;
23
+ if (typeof source?.getRandomValues !== 'function') {
24
+ throw getError({
25
+ statusCode: HTTP.ResultCodes.RS_5.InternalServerError,
26
+ message: `[${UidRandom.name}] No Web Crypto available | \`crypto.getRandomValues\` is required and \`Math.random\` is not an acceptable substitute for an identifier`,
27
+ });
28
+ }
29
+ const result = new Uint8Array(opts.count);
30
+ for (let offset = 0; offset < opts.count; offset += UidRandom.MAX_BYTES_PER_CALL) {
31
+ source.getRandomValues(result.subarray(offset, Math.min(offset + UidRandom.MAX_BYTES_PER_CALL, opts.count)));
32
+ }
33
+ return result;
34
+ }
35
+ /** How many random bytes to draw per refill, per remaining character. Rejection throws some away, so asking for exactly `length` would round-trip to the entropy source repeatedly. */
36
+ static { this.SAMPLING_OVERDRAW = 2; }
37
+ /**
38
+ * `length` characters of `alphabet`, each equally likely. A draw is masked to the smallest
39
+ * `2^n - 1` that covers every alphabet index and an index past the alphabet is discarded, because
40
+ * a plain `byte % size` would favour the first `256 % size` characters - a bias a caller cannot see
41
+ * and cannot undo.
42
+ */
43
+ static sample(opts) {
44
+ const { alphabet, length } = opts;
45
+ const size = alphabet.length;
46
+ const mask = (1 << Math.ceil(Math.log2(size))) - 1;
47
+ let body = '';
48
+ while (body.length < length) {
49
+ const bytes = UidRandom.bytes({
50
+ count: (length - body.length) * UidRandom.SAMPLING_OVERDRAW,
51
+ });
52
+ for (const byte of bytes) {
53
+ const index = byte & mask;
54
+ if (index >= size) {
55
+ continue;
56
+ }
57
+ body += alphabet[index];
58
+ if (body.length === length) {
59
+ break;
60
+ }
61
+ }
62
+ }
63
+ return body;
64
+ }
65
+ /** Whether `max` is a usable bound for {@link UidRandom.below}: an integer from 1 to {@link UidRandom.MAX_BELOW}. */
66
+ static isValidMax(opts) {
67
+ const { max } = opts;
68
+ return Number.isSafeInteger(max) && max > 0 && max <= UidRandom.MAX_BELOW;
69
+ }
70
+ /**
71
+ * A uniform integer in `[0, max)`. A draw at or above the largest multiple of `max` is thrown away
72
+ * and drawn again, so no value is likelier than another (`value % max` alone favours the low ones).
73
+ */
74
+ static below(opts) {
75
+ const { max } = opts;
76
+ if (!UidRandom.isValidMax({ max })) {
77
+ throw getError({
78
+ statusCode: HTTP.ResultCodes.RS_5.InternalServerError,
79
+ message: `[${UidRandom.name}][below] Invalid max | must be an integer from 1 to ${UidRandom.MAX_BELOW} | Got: ${max}`,
80
+ });
81
+ }
82
+ const limit = UidRandom.MAX_BELOW - (UidRandom.MAX_BELOW % max);
83
+ for (;;) {
84
+ let value = 0;
85
+ for (const byte of UidRandom.bytes({ count: UidRandom.DRAW_BYTES })) {
86
+ value = value * UidRandom.BYTE_RANGE + byte;
87
+ }
88
+ if (value < limit) {
89
+ return value % max;
90
+ }
91
+ }
92
+ }
93
+ }
94
+ //# sourceMappingURL=random.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"random.js","sourceRoot":"","sources":["../../../../../src/modules/uid/common/random.ts"],"names":[],"mappings":"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","sourcesContent":["import { HTTP } from '@/common/constants';\nimport { getError } from '../../error';\n\n/**\n * The one place the `uid` module draws randomness. Internal: not exported from the barrel, so it is\n * not API. Every helper here (`OpaqueUidHelper`, `TokenUidHelper`, `NumericUidHelper`) draws through it, which is\n * what keeps `Math.random` out of an identifier.\n */\nexport class UidRandom {\n /** `crypto.getRandomValues` refuses more than this per call (a browser throws `QuotaExceededError`). */\n private static readonly MAX_BYTES_PER_CALL = 65_536;\n\n /** `crypto.randomInt` draws a 48-bit value; `below` keeps the same width, so `max` goes up to 2 ** 48. */\n private static readonly DRAW_BYTES = 6;\n private static readonly BYTE_RANGE = 256;\n\n /** The largest `max` {@link UidRandom.below} accepts. */\n static readonly MAX_BELOW = 2 ** (UidRandom.DRAW_BYTES * 8);\n\n /**\n * `crypto.getRandomValues`, never `Math.random`. Unlike `crypto.randomUUID`, this one is NOT\n * restricted to a secure context, so it works on a plain-http origin and inside a browser Worker.\n * Throws when Web Crypto is missing instead of falling back to something weaker.\n */\n static bytes(opts: { count: number }): Uint8Array {\n const source = globalThis.crypto;\n\n if (typeof source?.getRandomValues !== 'function') {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[${UidRandom.name}] No Web Crypto available | \\`crypto.getRandomValues\\` is required and \\`Math.random\\` is not an acceptable substitute for an identifier`,\n });\n }\n\n const result = new Uint8Array(opts.count);\n\n for (let offset = 0; offset < opts.count; offset += UidRandom.MAX_BYTES_PER_CALL) {\n source.getRandomValues(\n result.subarray(offset, Math.min(offset + UidRandom.MAX_BYTES_PER_CALL, opts.count)),\n );\n }\n\n return result;\n }\n\n /** How many random bytes to draw per refill, per remaining character. Rejection throws some away, so asking for exactly `length` would round-trip to the entropy source repeatedly. */\n private static readonly SAMPLING_OVERDRAW = 2;\n\n /**\n * `length` characters of `alphabet`, each equally likely. A draw is masked to the smallest\n * `2^n - 1` that covers every alphabet index and an index past the alphabet is discarded, because\n * a plain `byte % size` would favour the first `256 % size` characters - a bias a caller cannot see\n * and cannot undo.\n */\n static sample(opts: { alphabet: string; length: number }): string {\n const { alphabet, length } = opts;\n const size = alphabet.length;\n const mask = (1 << Math.ceil(Math.log2(size))) - 1;\n let body = '';\n\n while (body.length < length) {\n const bytes = UidRandom.bytes({\n count: (length - body.length) * UidRandom.SAMPLING_OVERDRAW,\n });\n\n for (const byte of bytes) {\n const index = byte & mask;\n\n if (index >= size) {\n continue;\n }\n\n body += alphabet[index];\n\n if (body.length === length) {\n break;\n }\n }\n }\n\n return body;\n }\n\n /** Whether `max` is a usable bound for {@link UidRandom.below}: an integer from 1 to {@link UidRandom.MAX_BELOW}. */\n static isValidMax(opts: { max: number }): boolean {\n const { max } = opts;\n\n return Number.isSafeInteger(max) && max > 0 && max <= UidRandom.MAX_BELOW;\n }\n\n /**\n * A uniform integer in `[0, max)`. A draw at or above the largest multiple of `max` is thrown away\n * and drawn again, so no value is likelier than another (`value % max` alone favours the low ones).\n */\n static below(opts: { max: number }): number {\n const { max } = opts;\n\n if (!UidRandom.isValidMax({ max })) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[${UidRandom.name}][below] Invalid max | must be an integer from 1 to ${UidRandom.MAX_BELOW} | Got: ${max}`,\n });\n }\n\n const limit = UidRandom.MAX_BELOW - (UidRandom.MAX_BELOW % max);\n\n for (;;) {\n let value = 0;\n\n for (const byte of UidRandom.bytes({ count: UidRandom.DRAW_BYTES })) {\n value = value * UidRandom.BYTE_RANGE + byte;\n }\n\n if (value < limit) {\n return value % max;\n }\n }\n }\n}\n"]}
@@ -0,0 +1,36 @@
1
+ import type { TUidCaseForm } from './constants.js';
2
+ import type { IUidSegment } from './types.js';
3
+ /**
4
+ * The prefix and delimiter rules every prefixed id shares, so `OpaqueUidHelper` and
5
+ * `TokenUidHelper` refuse the same things for the same reasons. Internal: not exported from the
6
+ * barrel. `scope` is the calling helper's name, which is what an error message leads with.
7
+ */
8
+ export declare class UidSegments {
9
+ /** An enabled prefix in the wrong case defeats the reason for choosing one: an id meant to survive a case-insensitive column stops being one the moment its prefix disagrees. */
10
+ static resolvePrefix(opts: {
11
+ scope: string;
12
+ prefix?: IUidSegment;
13
+ caseForm: TUidCaseForm;
14
+ }): string;
15
+ /**
16
+ * Two refusals here, both because the alternative fails silently: a delimiter with no prefix is a
17
+ * leading character that separates nothing, and a delimiter drawn from the alphabet makes the id
18
+ * impossible to split back into prefix and body.
19
+ */
20
+ static resolveDelimiter(opts: {
21
+ scope: string;
22
+ delimiter?: IUidSegment;
23
+ hasPrefix: boolean;
24
+ alphabet: string;
25
+ /** Appended to the refusal that names shared characters, for a caller who can act on it. */
26
+ hint?: string;
27
+ }): string;
28
+ /** The text in front of the body: the per-call `override` or the configured `prefix`, then the delimiter. Empty when there is no prefix. */
29
+ static resolveHead(opts: {
30
+ scope: string;
31
+ override?: string;
32
+ prefix: string;
33
+ delimiter: string;
34
+ }): string;
35
+ }
36
+ //# sourceMappingURL=segments.d.ts.map
@@ -0,0 +1,81 @@
1
+ import { HTTP } from '../../../common/constants/index.js';
2
+ import { getError } from '../../error/index.js';
3
+ import { DEFAULT_UID_DELIMITER, UidCaseForms } from './constants.js';
4
+ /**
5
+ * The prefix and delimiter rules every prefixed id shares, so `OpaqueUidHelper` and
6
+ * `TokenUidHelper` refuse the same things for the same reasons. Internal: not exported from the
7
+ * barrel. `scope` is the calling helper's name, which is what an error message leads with.
8
+ */
9
+ export class UidSegments {
10
+ /** An enabled prefix in the wrong case defeats the reason for choosing one: an id meant to survive a case-insensitive column stops being one the moment its prefix disagrees. */
11
+ static resolvePrefix(opts) {
12
+ const { scope, prefix, caseForm } = opts;
13
+ if (!prefix?.enable) {
14
+ return '';
15
+ }
16
+ const value = prefix.value ?? '';
17
+ if (value.length === 0) {
18
+ throw getError({
19
+ statusCode: HTTP.ResultCodes.RS_5.InternalServerError,
20
+ message: `[${scope}] prefix is enabled but carries no value`,
21
+ });
22
+ }
23
+ const expected = caseForm === UidCaseForms.UPPER
24
+ ? value.toUpperCase()
25
+ : caseForm === UidCaseForms.LOWER
26
+ ? value.toLowerCase()
27
+ : value;
28
+ if (value !== expected) {
29
+ throw getError({
30
+ statusCode: HTTP.ResultCodes.RS_5.InternalServerError,
31
+ message: `[${scope}] prefix does not match caseForm | prefix: ${value} | caseForm: ${caseForm} | expected: ${expected}`,
32
+ });
33
+ }
34
+ return value;
35
+ }
36
+ /**
37
+ * Two refusals here, both because the alternative fails silently: a delimiter with no prefix is a
38
+ * leading character that separates nothing, and a delimiter drawn from the alphabet makes the id
39
+ * impossible to split back into prefix and body.
40
+ */
41
+ static resolveDelimiter(opts) {
42
+ const { scope, delimiter, hasPrefix, alphabet, hint } = opts;
43
+ if (!delimiter?.enable) {
44
+ return '';
45
+ }
46
+ if (!hasPrefix) {
47
+ throw getError({
48
+ statusCode: HTTP.ResultCodes.RS_5.InternalServerError,
49
+ message: `[${scope}] delimiter is enabled without a prefix | It would lead the id and separate nothing | Put the character in \`prefix.value\` if that is what you want`,
50
+ });
51
+ }
52
+ const value = delimiter.value ?? DEFAULT_UID_DELIMITER;
53
+ if (value.length === 0) {
54
+ throw getError({
55
+ statusCode: HTTP.ResultCodes.RS_5.InternalServerError,
56
+ message: `[${scope}] delimiter is enabled but carries no value`,
57
+ });
58
+ }
59
+ const shared = [...new Set(value)].filter((character) => alphabet.includes(character));
60
+ if (shared.length > 0) {
61
+ throw getError({
62
+ statusCode: HTTP.ResultCodes.RS_5.InternalServerError,
63
+ message: `[${scope}] delimiter shares characters with the alphabet | shared: ${shared.join('')} | An id built with it cannot be split back into prefix and body${hint ? ` | ${hint}` : ''}`,
64
+ });
65
+ }
66
+ return value;
67
+ }
68
+ /** The text in front of the body: the per-call `override` or the configured `prefix`, then the delimiter. Empty when there is no prefix. */
69
+ static resolveHead(opts) {
70
+ const { scope, override, delimiter } = opts;
71
+ if (override === '') {
72
+ throw getError({
73
+ statusCode: HTTP.ResultCodes.RS_5.InternalServerError,
74
+ message: `[${scope}][nextId] An empty prefix is not how a prefix is turned off | Construct with \`prefix: { enable: false }\``,
75
+ });
76
+ }
77
+ const prefix = override ?? opts.prefix;
78
+ return prefix.length > 0 ? `${prefix}${delimiter}` : '';
79
+ }
80
+ }
81
+ //# sourceMappingURL=segments.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"segments.js","sourceRoot":"","sources":["../../../../../src/modules/uid/common/segments.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,oBAAoB,CAAC;AAC1C,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AACvC,OAAO,EAAE,qBAAqB,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAIlE;;;;GAIG;AACH,MAAM,OAAO,WAAW;IACtB,iLAAiL;IACjL,MAAM,CAAC,aAAa,CAAC,IAIpB;QACC,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,QAAQ,EAAE,GAAG,IAAI,CAAC;QAEzC,IAAI,CAAC,MAAM,EAAE,MAAM,EAAE,CAAC;YACpB,OAAO,EAAE,CAAC;QACZ,CAAC;QAED,MAAM,KAAK,GAAG,MAAM,CAAC,KAAK,IAAI,EAAE,CAAC;QAEjC,IAAI,KAAK,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;YACvB,MAAM,QAAQ,CAAC;gBACb,UAAU,EAAE,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,mBAAmB;gBACrD,OAAO,EAAE,IAAI,KAAK,0CAA0C;aAC7D,CAAC,CAAC;QACL,CAAC;QAED,MAAM,QAAQ,GACZ,QAAQ,KAAK,YAAY,CAAC,KAAK;YAC7B,CAAC,CAAC,KAAK,CAAC,WAAW,EAAE;YACrB,CAAC,CAAC,QAAQ,KAAK,YAAY,CAAC,KAAK;gBAC/B,CAAC,CAAC,KAAK,CAAC,WAAW,EAAE;gBACrB,CAAC,CAAC,KAAK,CAAC;QAEd,IAAI,KAAK,KAAK,QAAQ,EAAE,CAAC;YACvB,MAAM,QAAQ,CAAC;gBACb,UAAU,EAAE,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,mBAAmB;gBACrD,OAAO,EAAE,IAAI,KAAK,8CAA8C,KAAK,gBAAgB,QAAQ,gBAAgB,QAAQ,EAAE;aACxH,CAAC,CAAC;QACL,CAAC;QAED,OAAO,KAAK,CAAC;IACf,CAAC;IAED;;;;OAIG;IACH,MAAM,CAAC,gBAAgB,CAAC,IAOvB;QACC,MAAM,EAAE,KAAK,EAAE,SAAS,EAAE,SAAS,EAAE,QAAQ,EAAE,IAAI,EAAE,GAAG,IAAI,CAAC;QAE7D,IAAI,CAAC,SAAS,EAAE,MAAM,EAAE,CAAC;YACvB,OAAO,EAAE,CAAC;QACZ,CAAC;QAED,IAAI,CAAC,SAAS,EAAE,CAAC;YACf,MAAM,QAAQ,CAAC;gBACb,UAAU,EAAE,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,mBAAmB;gBACrD,OAAO,EAAE,IAAI,KAAK,sJAAsJ;aACzK,CAAC,CAAC;QACL,CAAC;QAED,MAAM,KAAK,GAAG,SAAS,CAAC,KAAK,IAAI,qBAAqB,CAAC;QAEvD,IAAI,KAAK,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;YACvB,MAAM,QAAQ,CAAC;gBACb,UAAU,EAAE,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,mBAAmB;gBACrD,OAAO,EAAE,IAAI,KAAK,6CAA6C;aAChE,CAAC,CAAC;QACL,CAAC;QAED,MAAM,MAAM,GAAG,CAAC,GAAG,IAAI,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,SAAS,EAAE,EAAE,CAAC,QAAQ,CAAC,QAAQ,CAAC,SAAS,CAAC,CAAC,CAAC;QAEvF,IAAI,MAAM,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;YACtB,MAAM,QAAQ,CAAC;gBACb,UAAU,EAAE,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,mBAAmB;gBACrD,OAAO,EAAE,IAAI,KAAK,6DAA6D,MAAM,CAAC,IAAI,CAAC,EAAE,CAAC,mEAAmE,IAAI,CAAC,CAAC,CAAC,MAAM,IAAI,EAAE,CAAC,CAAC,CAAC,EAAE,EAAE;aAC5L,CAAC,CAAC;QACL,CAAC;QAED,OAAO,KAAK,CAAC;IACf,CAAC;IAED,4IAA4I;IAC5I,MAAM,CAAC,WAAW,CAAC,IAKlB;QACC,MAAM,EAAE,KAAK,EAAE,QAAQ,EAAE,SAAS,EAAE,GAAG,IAAI,CAAC;QAE5C,IAAI,QAAQ,KAAK,EAAE,EAAE,CAAC;YACpB,MAAM,QAAQ,CAAC;gBACb,UAAU,EAAE,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,mBAAmB;gBACrD,OAAO,EAAE,IAAI,KAAK,4GAA4G;aAC/H,CAAC,CAAC;QACL,CAAC;QAED,MAAM,MAAM,GAAG,QAAQ,IAAI,IAAI,CAAC,MAAM,CAAC;QAEvC,OAAO,MAAM,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,MAAM,GAAG,SAAS,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;IAC1D,CAAC;CACF","sourcesContent":["import { HTTP } from '@/common/constants';\nimport { getError } from '../../error';\nimport { DEFAULT_UID_DELIMITER, UidCaseForms } from './constants';\nimport type { TUidCaseForm } from './constants';\nimport type { IUidSegment } from './types';\n\n/**\n * The prefix and delimiter rules every prefixed id shares, so `OpaqueUidHelper` and\n * `TokenUidHelper` refuse the same things for the same reasons. Internal: not exported from the\n * barrel. `scope` is the calling helper's name, which is what an error message leads with.\n */\nexport class UidSegments {\n /** An enabled prefix in the wrong case defeats the reason for choosing one: an id meant to survive a case-insensitive column stops being one the moment its prefix disagrees. */\n static resolvePrefix(opts: {\n scope: string;\n prefix?: IUidSegment;\n caseForm: TUidCaseForm;\n }): string {\n const { scope, prefix, caseForm } = opts;\n\n if (!prefix?.enable) {\n return '';\n }\n\n const value = prefix.value ?? '';\n\n if (value.length === 0) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[${scope}] prefix is enabled but carries no value`,\n });\n }\n\n const expected =\n caseForm === UidCaseForms.UPPER\n ? value.toUpperCase()\n : caseForm === UidCaseForms.LOWER\n ? value.toLowerCase()\n : value;\n\n if (value !== expected) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[${scope}] prefix does not match caseForm | prefix: ${value} | caseForm: ${caseForm} | expected: ${expected}`,\n });\n }\n\n return value;\n }\n\n /**\n * Two refusals here, both because the alternative fails silently: a delimiter with no prefix is a\n * leading character that separates nothing, and a delimiter drawn from the alphabet makes the id\n * impossible to split back into prefix and body.\n */\n static resolveDelimiter(opts: {\n scope: string;\n delimiter?: IUidSegment;\n hasPrefix: boolean;\n alphabet: string;\n /** Appended to the refusal that names shared characters, for a caller who can act on it. */\n hint?: string;\n }): string {\n const { scope, delimiter, hasPrefix, alphabet, hint } = opts;\n\n if (!delimiter?.enable) {\n return '';\n }\n\n if (!hasPrefix) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[${scope}] delimiter is enabled without a prefix | It would lead the id and separate nothing | Put the character in \\`prefix.value\\` if that is what you want`,\n });\n }\n\n const value = delimiter.value ?? DEFAULT_UID_DELIMITER;\n\n if (value.length === 0) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[${scope}] delimiter is enabled but carries no value`,\n });\n }\n\n const shared = [...new Set(value)].filter((character) => alphabet.includes(character));\n\n if (shared.length > 0) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[${scope}] delimiter shares characters with the alphabet | shared: ${shared.join('')} | An id built with it cannot be split back into prefix and body${hint ? ` | ${hint}` : ''}`,\n });\n }\n\n return value;\n }\n\n /** The text in front of the body: the per-call `override` or the configured `prefix`, then the delimiter. Empty when there is no prefix. */\n static resolveHead(opts: {\n scope: string;\n override?: string;\n prefix: string;\n delimiter: string;\n }): string {\n const { scope, override, delimiter } = opts;\n\n if (override === '') {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[${scope}][nextId] An empty prefix is not how a prefix is turned off | Construct with \\`prefix: { enable: false }\\``,\n });\n }\n\n const prefix = override ?? opts.prefix;\n\n return prefix.length > 0 ? `${prefix}${delimiter}` : '';\n }\n}\n"]}
@@ -1,5 +1,5 @@
1
1
  import type { ValueOrPromise } from '../../../common/types/index.js';
2
- import type { TUidCaseForm } from './constants.js';
2
+ import type { TUidCaseForm, TUidTokenEncoding } from './constants.js';
3
3
  /**
4
4
  * A segment an id may or may not carry. `enable` decides; `value` survives being turned off, so a
5
5
  * caller can flip a configured delimiter back on without having to remember what it was.
@@ -69,4 +69,48 @@ export interface INextOpaqueUidOptions<TVerdict extends ValueOrPromise<boolean>
69
69
  */
70
70
  maxAttempts?: number;
71
71
  }
72
+ /** Options for generating a secret token. Every field is optional. */
73
+ export interface ITokenUidOptions {
74
+ /**
75
+ * Random bytes before encoding. At least `MIN_TOKEN_BYTES`.
76
+ *
77
+ * @default DEFAULT_TOKEN_BYTES
78
+ */
79
+ bytes?: number;
80
+ /** @default UidTokenEncodings.BASE62 */
81
+ encoding?: TUidTokenEncoding;
82
+ /** Same rules as {@link IOpaqueUidOptions.prefix}. @default { enable: false } */
83
+ prefix?: IUidSegment;
84
+ /**
85
+ * Same rules as {@link IOpaqueUidOptions.delimiter}, checked against the characters of `encoding`:
86
+ * `_` (the default) and `-` work with `base62` and `hex`. `base64url` holds both, so with it only a
87
+ * character outside `A-Z a-z 0-9 - _` (for example `.`) is accepted.
88
+ *
89
+ * @default { enable: false }
90
+ */
91
+ delimiter?: IUidSegment;
92
+ /**
93
+ * Appends a fixed-width CRC-32 of the body, GitHub-style: 6 base62 characters (`base62`) or 8 hex
94
+ * characters (`hex`). `isWellFormed` then rejects a mistyped token without a database lookup, and a
95
+ * secret scanner can spot the token by its shape. Refused with `base64url`, whose alphabet has no
96
+ * fixed width to give it. The checksum covers the body only, never the prefix.
97
+ *
98
+ * @default false
99
+ */
100
+ checksum?: boolean;
101
+ }
102
+ /** Per-call options of `TokenUidHelper.nextId`. */
103
+ export interface INextTokenUidOptions {
104
+ /** Replaces the configured prefix for this call and turns it on. An empty string is refused. */
105
+ prefix?: string;
106
+ }
107
+ /** Options for generating a numeric code. */
108
+ export interface INumericUidOptions {
109
+ /**
110
+ * Digits in the code. `10 ** length` must not exceed `2 ** 48`, so 14 at most.
111
+ *
112
+ * @default DEFAULT_NUMERIC_LENGTH
113
+ */
114
+ length?: number;
115
+ }
72
116
  //# sourceMappingURL=types.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["../../../../../src/modules/uid/common/types.ts"],"names":[],"mappings":"","sourcesContent":["import type { ValueOrPromise } from '@/common/types';\nimport type { TUidCaseForm } from './constants';\n\n/**\n * A segment an id may or may not carry. `enable` decides; `value` survives being turned off, so a\n * caller can flip a configured delimiter back on without having to remember what it was.\n *\n * An empty string is NOT the off switch. That conflates \"no prefix\" with \"a prefix I have not filled\n * in yet\", and the second one is a bug worth reporting rather than silently accepting.\n */\nexport interface IUidSegment {\n enable: boolean;\n value?: string;\n}\n\n/** Options for generating an opaque id. Every field is optional. */\nexport interface IOpaqueUidOptions {\n /** @default { enable: false } */\n prefix?: IUidSegment;\n\n /**\n * Meaningless without a prefix, and refused there. Enabled without a `value`, it is {@link DEFAULT_UID_DELIMITER}.\n *\n * @default { enable: false }\n */\n delimiter?: IUidSegment;\n\n /**\n * Characters in the BODY. The prefix and the delimiter are not counted.\n *\n * @default DEFAULT_UID_LENGTH\n */\n length?: number;\n\n /**\n * Upper is the default because the default alphabet is uppercase-only, so anything else would widen it.\n *\n * @default UidCaseForms.UPPER\n */\n caseForm?: TUidCaseForm;\n\n /** @default UidAlphabets.CROCKFORD */\n alphabet?: string;\n\n /**\n * Removed from `alphabet` on top of whatever the set already drops.\n *\n * @default ''\n */\n exclude?: string;\n}\n\n/**\n * `TVerdict` is what `isAvailable` returns, and it decides what `nextId` returns: a synchronous\n * check keeps the call synchronous, an asynchronous one makes it a promise. See the overloads on\n * `OpaqueUidHelper.nextId`.\n */\nexport interface INextOpaqueUidOptions<\n TVerdict extends ValueOrPromise<boolean> = ValueOrPromise<boolean>,\n> {\n /** Replaces the configured prefix for this call and turns it on. An empty string is refused - that is what the toggle is for. */\n prefix?: string;\n\n /**\n * Whether the drawn id may be used. `true` accepts it, `false` means taken and draws another.\n *\n * Named for what it RETURNS, not for the question it answers: an `exists` callback returning\n * `true` for a usable id is the sort of inverted polarity a reader gets wrong once and debugs for\n * an hour.\n *\n * An ASYNCHRONOUS check does not make an id safe. Against a database it is a read and then a\n * write with a gap in between, and another request can take the id inside that gap. It lowers the\n * collision rate; the unique index and the regenerate-on-violation insert are what remove it.\n */\n isAvailable?: (id: string) => TVerdict;\n\n /**\n * Draws before giving up, when `isAvailable` is supplied.\n *\n * @default DEFAULT_UID_MAX_ATTEMPTS\n */\n maxAttempts?: number;\n}\n"]}
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../../../../src/modules/uid/common/types.ts"],"names":[],"mappings":"","sourcesContent":["import type { ValueOrPromise } from '@/common/types';\nimport type { TUidCaseForm, TUidTokenEncoding } from './constants';\n\n/**\n * A segment an id may or may not carry. `enable` decides; `value` survives being turned off, so a\n * caller can flip a configured delimiter back on without having to remember what it was.\n *\n * An empty string is NOT the off switch. That conflates \"no prefix\" with \"a prefix I have not filled\n * in yet\", and the second one is a bug worth reporting rather than silently accepting.\n */\nexport interface IUidSegment {\n enable: boolean;\n value?: string;\n}\n\n/** Options for generating an opaque id. Every field is optional. */\nexport interface IOpaqueUidOptions {\n /** @default { enable: false } */\n prefix?: IUidSegment;\n\n /**\n * Meaningless without a prefix, and refused there. Enabled without a `value`, it is {@link DEFAULT_UID_DELIMITER}.\n *\n * @default { enable: false }\n */\n delimiter?: IUidSegment;\n\n /**\n * Characters in the BODY. The prefix and the delimiter are not counted.\n *\n * @default DEFAULT_UID_LENGTH\n */\n length?: number;\n\n /**\n * Upper is the default because the default alphabet is uppercase-only, so anything else would widen it.\n *\n * @default UidCaseForms.UPPER\n */\n caseForm?: TUidCaseForm;\n\n /** @default UidAlphabets.CROCKFORD */\n alphabet?: string;\n\n /**\n * Removed from `alphabet` on top of whatever the set already drops.\n *\n * @default ''\n */\n exclude?: string;\n}\n\n/**\n * `TVerdict` is what `isAvailable` returns, and it decides what `nextId` returns: a synchronous\n * check keeps the call synchronous, an asynchronous one makes it a promise. See the overloads on\n * `OpaqueUidHelper.nextId`.\n */\nexport interface INextOpaqueUidOptions<\n TVerdict extends ValueOrPromise<boolean> = ValueOrPromise<boolean>,\n> {\n /** Replaces the configured prefix for this call and turns it on. An empty string is refused - that is what the toggle is for. */\n prefix?: string;\n\n /**\n * Whether the drawn id may be used. `true` accepts it, `false` means taken and draws another.\n *\n * Named for what it RETURNS, not for the question it answers: an `exists` callback returning\n * `true` for a usable id is the sort of inverted polarity a reader gets wrong once and debugs for\n * an hour.\n *\n * An ASYNCHRONOUS check does not make an id safe. Against a database it is a read and then a\n * write with a gap in between, and another request can take the id inside that gap. It lowers the\n * collision rate; the unique index and the regenerate-on-violation insert are what remove it.\n */\n isAvailable?: (id: string) => TVerdict;\n\n /**\n * Draws before giving up, when `isAvailable` is supplied.\n *\n * @default DEFAULT_UID_MAX_ATTEMPTS\n */\n maxAttempts?: number;\n}\n\n/** Options for generating a secret token. Every field is optional. */\nexport interface ITokenUidOptions {\n /**\n * Random bytes before encoding. At least `MIN_TOKEN_BYTES`.\n *\n * @default DEFAULT_TOKEN_BYTES\n */\n bytes?: number;\n\n /** @default UidTokenEncodings.BASE62 */\n encoding?: TUidTokenEncoding;\n\n /** Same rules as {@link IOpaqueUidOptions.prefix}. @default { enable: false } */\n prefix?: IUidSegment;\n\n /**\n * Same rules as {@link IOpaqueUidOptions.delimiter}, checked against the characters of `encoding`:\n * `_` (the default) and `-` work with `base62` and `hex`. `base64url` holds both, so with it only a\n * character outside `A-Z a-z 0-9 - _` (for example `.`) is accepted.\n *\n * @default { enable: false }\n */\n delimiter?: IUidSegment;\n\n /**\n * Appends a fixed-width CRC-32 of the body, GitHub-style: 6 base62 characters (`base62`) or 8 hex\n * characters (`hex`). `isWellFormed` then rejects a mistyped token without a database lookup, and a\n * secret scanner can spot the token by its shape. Refused with `base64url`, whose alphabet has no\n * fixed width to give it. The checksum covers the body only, never the prefix.\n *\n * @default false\n */\n checksum?: boolean;\n}\n\n/** Per-call options of `TokenUidHelper.nextId`. */\nexport interface INextTokenUidOptions {\n /** Replaces the configured prefix for this call and turns it on. An empty string is refused. */\n prefix?: string;\n}\n\n/** Options for generating a numeric code. */\nexport interface INumericUidOptions {\n /**\n * Digits in the code. `10 ** length` must not exceed `2 ** 48`, so 14 at most.\n *\n * @default DEFAULT_NUMERIC_LENGTH\n */\n length?: number;\n}\n"]}
@@ -1,6 +1,8 @@
1
1
  export * from './common/index.js';
2
2
  export * from './helper.js';
3
+ export * from './numeric.js';
3
4
  export * from './opaque.js';
4
5
  export * from './request-id.js';
6
+ export * from './token.js';
5
7
  export * from './uuid/index.js';
6
8
  //# sourceMappingURL=index.d.ts.map
@@ -1,6 +1,8 @@
1
1
  export * from './common/index.js';
2
2
  export * from './helper.js';
3
+ export * from './numeric.js';
3
4
  export * from './opaque.js';
4
5
  export * from './request-id.js';
6
+ export * from './token.js';
5
7
  export * from './uuid/index.js';
6
8
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/modules/uid/index.ts"],"names":[],"mappings":"AAAA,cAAc,UAAU,CAAC;AACzB,cAAc,UAAU,CAAC;AACzB,cAAc,UAAU,CAAC;AACzB,cAAc,cAAc,CAAC;AAC7B,cAAc,QAAQ,CAAC","sourcesContent":["export * from './common';\nexport * from './helper';\nexport * from './opaque';\nexport * from './request-id';\nexport * from './uuid';\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/modules/uid/index.ts"],"names":[],"mappings":"AAAA,cAAc,UAAU,CAAC;AACzB,cAAc,UAAU,CAAC;AACzB,cAAc,WAAW,CAAC;AAC1B,cAAc,UAAU,CAAC;AACzB,cAAc,cAAc,CAAC;AAC7B,cAAc,SAAS,CAAC;AACxB,cAAc,QAAQ,CAAC","sourcesContent":["export * from './common';\nexport * from './helper';\nexport * from './numeric';\nexport * from './opaque';\nexport * from './request-id';\nexport * from './token';\nexport * from './uuid';\n"]}
@@ -0,0 +1,18 @@
1
+ import { BaseHelper } from '../base.js';
2
+ import type { INumericUidOptions } from './common/types.js';
3
+ /**
4
+ * Zero-padded numeric codes, uniformly distributed: `042917`. Use it for a code a human types - a
5
+ * one-time password, an email verification code.
6
+ *
7
+ * Six digits is a million codes, so a code needs an expiry and an attempt limit; the digits alone
8
+ * are not the defence. For a secret that is not typed, use `TokenUidHelper`.
9
+ *
10
+ * `10 ** length` must be an integer up to `2 ** 48` (`length` 14 at most), the range one draw covers.
11
+ */
12
+ export declare class NumericUidHelper extends BaseHelper {
13
+ private readonly length;
14
+ private readonly max;
15
+ constructor(opts?: INumericUidOptions);
16
+ nextId(): string;
17
+ }
18
+ //# sourceMappingURL=numeric.d.ts.map
@@ -0,0 +1,31 @@
1
+ import { HTTP } from '../../common/constants/index.js';
2
+ import { BaseHelper } from '../base.js';
3
+ import { getError } from '../error/index.js';
4
+ import { DEFAULT_NUMERIC_LENGTH } from './common/constants.js';
5
+ import { UidRandom } from './common/random.js';
6
+ /**
7
+ * Zero-padded numeric codes, uniformly distributed: `042917`. Use it for a code a human types - a
8
+ * one-time password, an email verification code.
9
+ *
10
+ * Six digits is a million codes, so a code needs an expiry and an attempt limit; the digits alone
11
+ * are not the defence. For a secret that is not typed, use `TokenUidHelper`.
12
+ *
13
+ * `10 ** length` must be an integer up to `2 ** 48` (`length` 14 at most), the range one draw covers.
14
+ */
15
+ export class NumericUidHelper extends BaseHelper {
16
+ constructor(opts) {
17
+ super({ scope: NumericUidHelper.name });
18
+ this.length = opts?.length ?? DEFAULT_NUMERIC_LENGTH;
19
+ this.max = Math.pow(10, this.length);
20
+ if (!UidRandom.isValidMax({ max: this.max })) {
21
+ throw getError({
22
+ statusCode: HTTP.ResultCodes.RS_5.InternalServerError,
23
+ message: `[${NumericUidHelper.name}] Invalid length | 10 ** length must be an integer from 1 to ${UidRandom.MAX_BELOW} | length: ${this.length}`,
24
+ });
25
+ }
26
+ }
27
+ nextId() {
28
+ return UidRandom.below({ max: this.max }).toString().padStart(this.length, '0');
29
+ }
30
+ }
31
+ //# sourceMappingURL=numeric.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"numeric.js","sourceRoot":"","sources":["../../../../src/modules/uid/numeric.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,oBAAoB,CAAC;AAC1C,OAAO,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AACrC,OAAO,EAAE,QAAQ,EAAE,MAAM,UAAU,CAAC;AACpC,OAAO,EAAE,sBAAsB,EAAE,MAAM,oBAAoB,CAAC;AAC5D,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAG5C;;;;;;;;GAQG;AACH,MAAM,OAAO,gBAAiB,SAAQ,UAAU;IAI9C,YAAY,IAAyB;QACnC,KAAK,CAAC,EAAE,KAAK,EAAE,gBAAgB,CAAC,IAAI,EAAE,CAAC,CAAC;QAExC,IAAI,CAAC,MAAM,GAAG,IAAI,EAAE,MAAM,IAAI,sBAAsB,CAAC;QACrD,IAAI,CAAC,GAAG,GAAG,IAAI,CAAC,GAAG,CAAC,EAAE,EAAE,IAAI,CAAC,MAAM,CAAC,CAAC;QAErC,IAAI,CAAC,SAAS,CAAC,UAAU,CAAC,EAAE,GAAG,EAAE,IAAI,CAAC,GAAG,EAAE,CAAC,EAAE,CAAC;YAC7C,MAAM,QAAQ,CAAC;gBACb,UAAU,EAAE,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,mBAAmB;gBACrD,OAAO,EAAE,IAAI,gBAAgB,CAAC,IAAI,gEAAgE,SAAS,CAAC,SAAS,cAAc,IAAI,CAAC,MAAM,EAAE;aACjJ,CAAC,CAAC;QACL,CAAC;IACH,CAAC;IAED,MAAM;QACJ,OAAO,SAAS,CAAC,KAAK,CAAC,EAAE,GAAG,EAAE,IAAI,CAAC,GAAG,EAAE,CAAC,CAAC,QAAQ,EAAE,CAAC,QAAQ,CAAC,IAAI,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;IAClF,CAAC;CACF","sourcesContent":["import { HTTP } from '@/common/constants';\nimport { BaseHelper } from '../base';\nimport { getError } from '../error';\nimport { DEFAULT_NUMERIC_LENGTH } from './common/constants';\nimport { UidRandom } from './common/random';\nimport type { INumericUidOptions } from './common/types';\n\n/**\n * Zero-padded numeric codes, uniformly distributed: `042917`. Use it for a code a human types - a\n * one-time password, an email verification code.\n *\n * Six digits is a million codes, so a code needs an expiry and an attempt limit; the digits alone\n * are not the defence. For a secret that is not typed, use `TokenUidHelper`.\n *\n * `10 ** length` must be an integer up to `2 ** 48` (`length` 14 at most), the range one draw covers.\n */\nexport class NumericUidHelper extends BaseHelper {\n private readonly length: number;\n private readonly max: number;\n\n constructor(opts?: INumericUidOptions) {\n super({ scope: NumericUidHelper.name });\n\n this.length = opts?.length ?? DEFAULT_NUMERIC_LENGTH;\n this.max = Math.pow(10, this.length);\n\n if (!UidRandom.isValidMax({ max: this.max })) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[${NumericUidHelper.name}] Invalid length | 10 ** length must be an integer from 1 to ${UidRandom.MAX_BELOW} | length: ${this.length}`,\n });\n }\n }\n\n nextId(): string {\n return UidRandom.below({ max: this.max }).toString().padStart(this.length, '0');\n }\n}\n"]}
@@ -20,8 +20,6 @@ export declare class OpaqueUidHelper extends BaseHelper {
20
20
  private readonly length;
21
21
  private readonly prefix;
22
22
  private readonly delimiter;
23
- /** Rejection mask: the smallest `2^n - 1` that covers every alphabet index. A plain `byte % size` would favour the first `256 % size` characters, which is a bias a caller cannot see and cannot undo. */
24
- private readonly mask;
25
23
  constructor(opts?: IOpaqueUidOptions);
26
24
  /**
27
25
  * `prefix` replaces the configured value for this call and turns the prefix on for it; the
@@ -44,11 +42,6 @@ export declare class OpaqueUidHelper extends BaseHelper {
44
42
  /** The alphabet actually in use, after the case fold and every exclusion - what `length` is measured against. */
45
43
  getAlphabet(): string;
46
44
  private randomBody;
47
- /**
48
- * `crypto.getRandomValues`, never `Math.random`. Unlike `crypto.randomUUID`, this one is NOT
49
- * restricted to a secure context, so it works on a plain-http origin and inside a browser Worker.
50
- */
51
- private static randomBytes;
52
45
  private static hasBothCases;
53
46
  private static assertKnownCaseForm;
54
47
  /**
@@ -62,13 +55,5 @@ export declare class OpaqueUidHelper extends BaseHelper {
62
55
  * cleanly because there is nothing to collide with.
63
56
  */
64
57
  private static resolveAlphabet;
65
- /** An enabled prefix in the wrong case defeats the reason for choosing one: an id meant to survive a case-insensitive column stops being one the moment its prefix disagrees. */
66
- private static resolvePrefix;
67
- /**
68
- * Two refusals here, both because the alternative fails silently: a delimiter with no prefix is a
69
- * leading character that separates nothing, and a delimiter drawn from the alphabet makes the id
70
- * impossible to split back into prefix and body.
71
- */
72
- private static resolveDelimiter;
73
58
  }
74
59
  //# sourceMappingURL=opaque.d.ts.map