@tinta-lang/syntax 0.0.0-stage → 0.1.0-dev.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.
- package/LICENSE +21 -0
- package/THIRD_PARTY_NOTICES.txt +13651 -0
- package/dist/directive.d.ts +40 -0
- package/dist/editing.d.ts +46 -0
- package/dist/enrichment.d.ts +5 -0
- package/dist/expression.d.ts +26 -0
- package/dist/image-destinations.d.ts +3 -0
- package/dist/index.d.ts +8 -0
- package/dist/index.js +10118 -0
- package/dist/parser.d.ts +40 -0
- package/dist/registry.d.ts +144 -0
- package/dist/source.d.ts +28 -0
- package/package.json +280 -3
- package/parser-provenance.json +1419 -0
- package/patches/README.md +5 -0
- package/patches/micromark.patch +84 -0
- package/vendor/@noble/hashes/LICENSE +21 -0
- package/vendor/@noble/hashes/_md.js +209 -0
- package/vendor/@noble/hashes/_u64.js +77 -0
- package/vendor/@noble/hashes/package.json +91 -0
- package/vendor/@noble/hashes/sha2.js +446 -0
- package/vendor/@noble/hashes/utils.js +687 -0
- package/vendor/character-entities/index.js +2132 -0
- package/vendor/character-entities/license +22 -0
- package/vendor/character-entities/package.json +78 -0
- package/vendor/decode-named-character-reference/index.js +19 -0
- package/vendor/decode-named-character-reference/license +22 -0
- package/vendor/decode-named-character-reference/package.json +90 -0
- package/vendor/devlop/lib/default.js +9 -0
- package/vendor/devlop/license +22 -0
- package/vendor/devlop/package.json +80 -0
- package/vendor/longest-streak/index.js +36 -0
- package/vendor/longest-streak/license +22 -0
- package/vendor/longest-streak/package.json +73 -0
- package/vendor/markdown-table/index.js +393 -0
- package/vendor/markdown-table/license +22 -0
- package/vendor/markdown-table/package.json +77 -0
- package/vendor/mdast-util-from-markdown/index.js +2 -0
- package/vendor/mdast-util-from-markdown/lib/index.js +1270 -0
- package/vendor/mdast-util-from-markdown/license +22 -0
- package/vendor/mdast-util-from-markdown/package.json +98 -0
- package/vendor/mdast-util-gfm-strikethrough/index.js +5 -0
- package/vendor/mdast-util-gfm-strikethrough/lib/index.js +133 -0
- package/vendor/mdast-util-gfm-strikethrough/license +22 -0
- package/vendor/mdast-util-gfm-strikethrough/package.json +84 -0
- package/vendor/mdast-util-gfm-table/index.js +2 -0
- package/vendor/mdast-util-gfm-table/lib/index.js +300 -0
- package/vendor/mdast-util-gfm-table/license +22 -0
- package/vendor/mdast-util-gfm-table/package.json +101 -0
- package/vendor/mdast-util-gfm-task-list-item/index.js +4 -0
- package/vendor/mdast-util-gfm-task-list-item/lib/index.js +141 -0
- package/vendor/mdast-util-gfm-task-list-item/license +22 -0
- package/vendor/mdast-util-gfm-task-list-item/package.json +90 -0
- package/vendor/mdast-util-phrasing/index.js +1 -0
- package/vendor/mdast-util-phrasing/lib/index.js +45 -0
- package/vendor/mdast-util-phrasing/license +23 -0
- package/vendor/mdast-util-phrasing/package.json +78 -0
- package/vendor/mdast-util-to-markdown/index.js +3 -0
- package/vendor/mdast-util-to-markdown/lib/configure.js +98 -0
- package/vendor/mdast-util-to-markdown/lib/handle/blockquote.js +40 -0
- package/vendor/mdast-util-to-markdown/lib/handle/break.js +41 -0
- package/vendor/mdast-util-to-markdown/lib/handle/code.js +86 -0
- package/vendor/mdast-util-to-markdown/lib/handle/definition.js +83 -0
- package/vendor/mdast-util-to-markdown/lib/handle/emphasis.js +67 -0
- package/vendor/mdast-util-to-markdown/lib/handle/heading.js +84 -0
- package/vendor/mdast-util-to-markdown/lib/handle/html.js +27 -0
- package/vendor/mdast-util-to-markdown/lib/handle/image-reference.js +78 -0
- package/vendor/mdast-util-to-markdown/lib/handle/image.js +92 -0
- package/vendor/mdast-util-to-markdown/lib/handle/index.js +45 -0
- package/vendor/mdast-util-to-markdown/lib/handle/inline-code.js +86 -0
- package/vendor/mdast-util-to-markdown/lib/handle/link-reference.js +78 -0
- package/vendor/mdast-util-to-markdown/lib/handle/link.js +129 -0
- package/vendor/mdast-util-to-markdown/lib/handle/list-item.js +73 -0
- package/vendor/mdast-util-to-markdown/lib/handle/list.js +107 -0
- package/vendor/mdast-util-to-markdown/lib/handle/paragraph.js +27 -0
- package/vendor/mdast-util-to-markdown/lib/handle/root.js +34 -0
- package/vendor/mdast-util-to-markdown/lib/handle/strong.js +67 -0
- package/vendor/mdast-util-to-markdown/lib/handle/text.js +30 -0
- package/vendor/mdast-util-to-markdown/lib/handle/thematic-break.js +27 -0
- package/vendor/mdast-util-to-markdown/lib/index.js +213 -0
- package/vendor/mdast-util-to-markdown/lib/join.js +56 -0
- package/vendor/mdast-util-to-markdown/lib/unsafe.js +160 -0
- package/vendor/mdast-util-to-markdown/lib/util/association.js +33 -0
- package/vendor/mdast-util-to-markdown/lib/util/character.js +32 -0
- package/vendor/mdast-util-to-markdown/lib/util/check-bullet-ordered.js +25 -0
- package/vendor/mdast-util-to-markdown/lib/util/check-bullet-other.js +42 -0
- package/vendor/mdast-util-to-markdown/lib/util/check-bullet.js +25 -0
- package/vendor/mdast-util-to-markdown/lib/util/check-emphasis.js +25 -0
- package/vendor/mdast-util-to-markdown/lib/util/check-fence.js +25 -0
- package/vendor/mdast-util-to-markdown/lib/util/check-list-item-indent.js +25 -0
- package/vendor/mdast-util-to-markdown/lib/util/check-quote.js +25 -0
- package/vendor/mdast-util-to-markdown/lib/util/check-rule-repetition.js +25 -0
- package/vendor/mdast-util-to-markdown/lib/util/check-rule.js +25 -0
- package/vendor/mdast-util-to-markdown/lib/util/check-strong.js +25 -0
- package/vendor/mdast-util-to-markdown/lib/util/compile-pattern.js +30 -0
- package/vendor/mdast-util-to-markdown/lib/util/container-flow.js +93 -0
- package/vendor/mdast-util-to-markdown/lib/util/container-phrasing.js +704 -0
- package/vendor/mdast-util-to-markdown/lib/util/encode-character-reference.js +11 -0
- package/vendor/mdast-util-to-markdown/lib/util/encode-info.js +82 -0
- package/vendor/mdast-util-to-markdown/lib/util/format-code-as-indented.js +27 -0
- package/vendor/mdast-util-to-markdown/lib/util/format-heading-as-setext.js +39 -0
- package/vendor/mdast-util-to-markdown/lib/util/format-link-as-autolink.js +39 -0
- package/vendor/mdast-util-to-markdown/lib/util/html-kind.js +63 -0
- package/vendor/mdast-util-to-markdown/lib/util/indent-lines.js +40 -0
- package/vendor/mdast-util-to-markdown/lib/util/pattern-in-scope.js +52 -0
- package/vendor/mdast-util-to-markdown/lib/util/safe.js +263 -0
- package/vendor/mdast-util-to-markdown/lib/util/track.js +55 -0
- package/vendor/mdast-util-to-markdown/license +22 -0
- package/vendor/mdast-util-to-markdown/package.json +88 -0
- package/vendor/mdast-util-to-string/index.js +5 -0
- package/vendor/mdast-util-to-string/lib/index.js +108 -0
- package/vendor/mdast-util-to-string/license +22 -0
- package/vendor/mdast-util-to-string/package.json +78 -0
- package/vendor/micromark/index.js +60 -0
- package/vendor/micromark/lib/compile.js +1068 -0
- package/vendor/micromark/lib/constructs.js +85 -0
- package/vendor/micromark/lib/create-tokenizer.js +615 -0
- package/vendor/micromark/lib/initialize/content.js +79 -0
- package/vendor/micromark/lib/initialize/document.js +370 -0
- package/vendor/micromark/lib/initialize/flow.js +58 -0
- package/vendor/micromark/lib/initialize/text.js +216 -0
- package/vendor/micromark/lib/parse.js +56 -0
- package/vendor/micromark/lib/postprocess.js +18 -0
- package/vendor/micromark/lib/preprocess.js +112 -0
- package/vendor/micromark/license +22 -0
- package/vendor/micromark/package.json +87 -0
- package/vendor/micromark-core-commonmark/index.js +22 -0
- package/vendor/micromark-core-commonmark/lib/attention.js +231 -0
- package/vendor/micromark-core-commonmark/lib/autolink.js +233 -0
- package/vendor/micromark-core-commonmark/lib/blank-line.js +61 -0
- package/vendor/micromark-core-commonmark/lib/block-quote.js +143 -0
- package/vendor/micromark-core-commonmark/lib/character-escape.js +64 -0
- package/vendor/micromark-core-commonmark/lib/character-reference.js +149 -0
- package/vendor/micromark-core-commonmark/lib/code-fenced.js +422 -0
- package/vendor/micromark-core-commonmark/lib/code-indented.js +159 -0
- package/vendor/micromark-core-commonmark/lib/code-text.js +225 -0
- package/vendor/micromark-core-commonmark/lib/content.js +163 -0
- package/vendor/micromark-core-commonmark/lib/definition.js +254 -0
- package/vendor/micromark-core-commonmark/lib/hard-break-escape.js +60 -0
- package/vendor/micromark-core-commonmark/lib/heading-atx.js +191 -0
- package/vendor/micromark-core-commonmark/lib/html-flow.js +827 -0
- package/vendor/micromark-core-commonmark/lib/html-text.js +678 -0
- package/vendor/micromark-core-commonmark/lib/label-end.js +561 -0
- package/vendor/micromark-core-commonmark/lib/label-start-image.js +110 -0
- package/vendor/micromark-core-commonmark/lib/label-start-link.js +63 -0
- package/vendor/micromark-core-commonmark/lib/line-ending.js +33 -0
- package/vendor/micromark-core-commonmark/lib/list.js +213 -0
- package/vendor/micromark-core-commonmark/lib/partial-non-lazy-continuation.js +61 -0
- package/vendor/micromark-core-commonmark/lib/setext-underline.js +187 -0
- package/vendor/micromark-core-commonmark/lib/thematic-break.js +102 -0
- package/vendor/micromark-core-commonmark/license +22 -0
- package/vendor/micromark-core-commonmark/package.json +62 -0
- package/vendor/micromark-extension-gfm-strikethrough/index.js +3 -0
- package/vendor/micromark-extension-gfm-strikethrough/lib/html.js +26 -0
- package/vendor/micromark-extension-gfm-strikethrough/lib/syntax.js +142 -0
- package/vendor/micromark-extension-gfm-strikethrough/license +22 -0
- package/vendor/micromark-extension-gfm-strikethrough/package.json +129 -0
- package/vendor/micromark-extension-gfm-table/index.js +2 -0
- package/vendor/micromark-extension-gfm-table/lib/edit-map.js +222 -0
- package/vendor/micromark-extension-gfm-table/lib/html.js +135 -0
- package/vendor/micromark-extension-gfm-table/lib/infer.js +52 -0
- package/vendor/micromark-extension-gfm-table/lib/syntax.js +846 -0
- package/vendor/micromark-extension-gfm-table/license +22 -0
- package/vendor/micromark-extension-gfm-table/package.json +86 -0
- package/vendor/micromark-extension-gfm-task-list-item/index.js +2 -0
- package/vendor/micromark-extension-gfm-task-list-item/lib/html.js +29 -0
- package/vendor/micromark-extension-gfm-task-list-item/lib/syntax.js +158 -0
- package/vendor/micromark-extension-gfm-task-list-item/license +22 -0
- package/vendor/micromark-extension-gfm-task-list-item/package.json +131 -0
- package/vendor/micromark-factory-destination/index.js +206 -0
- package/vendor/micromark-factory-destination/license +22 -0
- package/vendor/micromark-factory-destination/package.json +57 -0
- package/vendor/micromark-factory-label/index.js +148 -0
- package/vendor/micromark-factory-label/license +22 -0
- package/vendor/micromark-factory-label/package.json +60 -0
- package/vendor/micromark-factory-space/index.js +116 -0
- package/vendor/micromark-factory-space/license +22 -0
- package/vendor/micromark-factory-space/package.json +46 -0
- package/vendor/micromark-factory-title/index.js +158 -0
- package/vendor/micromark-factory-title/license +22 -0
- package/vendor/micromark-factory-title/package.json +58 -0
- package/vendor/micromark-factory-whitespace/index.js +44 -0
- package/vendor/micromark-factory-whitespace/license +22 -0
- package/vendor/micromark-factory-whitespace/package.json +57 -0
- package/vendor/micromark-util-character/index.js +246 -0
- package/vendor/micromark-util-character/license +22 -0
- package/vendor/micromark-util-character/package.json +57 -0
- package/vendor/micromark-util-chunked/index.js +81 -0
- package/vendor/micromark-util-chunked/license +22 -0
- package/vendor/micromark-util-chunked/package.json +57 -0
- package/vendor/micromark-util-classify-character/index.js +27 -0
- package/vendor/micromark-util-classify-character/license +22 -0
- package/vendor/micromark-util-classify-character/package.json +59 -0
- package/vendor/micromark-util-combine-extensions/index.js +143 -0
- package/vendor/micromark-util-combine-extensions/license +22 -0
- package/vendor/micromark-util-combine-extensions/package.json +52 -0
- package/vendor/micromark-util-decode-numeric-character-reference/index.js +32 -0
- package/vendor/micromark-util-decode-numeric-character-reference/license +22 -0
- package/vendor/micromark-util-decode-numeric-character-reference/package.json +59 -0
- package/vendor/micromark-util-decode-string/index.js +45 -0
- package/vendor/micromark-util-decode-string/license +22 -0
- package/vendor/micromark-util-decode-string/package.json +63 -0
- package/vendor/micromark-util-edit-map/index.js +225 -0
- package/vendor/micromark-util-edit-map/license +22 -0
- package/vendor/micromark-util-edit-map/package.json +48 -0
- package/vendor/micromark-util-encode/index.js +33 -0
- package/vendor/micromark-util-encode/license +22 -0
- package/vendor/micromark-util-encode/package.json +47 -0
- package/vendor/micromark-util-html-tag-name/index.js +93 -0
- package/vendor/micromark-util-html-tag-name/license +22 -0
- package/vendor/micromark-util-html-tag-name/package.json +47 -0
- package/vendor/micromark-util-normalize-identifier/index.js +33 -0
- package/vendor/micromark-util-normalize-identifier/license +22 -0
- package/vendor/micromark-util-normalize-identifier/package.json +58 -0
- package/vendor/micromark-util-resolve-all/index.js +32 -0
- package/vendor/micromark-util-resolve-all/license +22 -0
- package/vendor/micromark-util-resolve-all/package.json +48 -0
- package/vendor/micromark-util-sanitize-uri/index.js +107 -0
- package/vendor/micromark-util-sanitize-uri/license +22 -0
- package/vendor/micromark-util-sanitize-uri/package.json +59 -0
- package/vendor/micromark-util-subtokenize/index.js +228 -0
- package/vendor/micromark-util-subtokenize/lib/splice-buffer.js +251 -0
- package/vendor/micromark-util-subtokenize/license +22 -0
- package/vendor/micromark-util-subtokenize/package.json +60 -0
- package/vendor/unist-util-is/index.js +7 -0
- package/vendor/unist-util-is/lib/index.js +296 -0
- package/vendor/unist-util-is/license +22 -0
- package/vendor/unist-util-is/package.json +103 -0
- package/vendor/unist-util-stringify-position/index.js +1 -0
- package/vendor/unist-util-stringify-position/lib/index.js +84 -0
- package/vendor/unist-util-stringify-position/license +22 -0
- package/vendor/unist-util-stringify-position/package.json +80 -0
- package/vendor/unist-util-visit/index.js +2 -0
- package/vendor/unist-util-visit/lib/index.js +312 -0
- package/vendor/unist-util-visit/license +22 -0
- package/vendor/unist-util-visit/package.json +108 -0
- package/vendor/unist-util-visit-parents/index.js +2 -0
- package/vendor/unist-util-visit-parents/lib/color.js +7 -0
- package/vendor/unist-util-visit-parents/lib/index.js +399 -0
- package/vendor/unist-util-visit-parents/license +22 -0
- package/vendor/unist-util-visit-parents/package.json +106 -0
- package/vendor/zwitch/index.js +118 -0
- package/vendor/zwitch/license +22 -0
- package/vendor/zwitch/package.json +72 -0
- package/README.md +0 -3
|
@@ -0,0 +1,687 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Checks if something is Uint8Array. Be careful: nodejs Buffer will return true.
|
|
3
|
+
* @param a - value to test
|
|
4
|
+
* @returns `true` when the value is a Uint8Array-compatible view.
|
|
5
|
+
* @example
|
|
6
|
+
* Check whether a value is a Uint8Array-compatible view.
|
|
7
|
+
* ```ts
|
|
8
|
+
* isBytes(new Uint8Array([1, 2, 3]));
|
|
9
|
+
* ```
|
|
10
|
+
*/
|
|
11
|
+
export function isBytes(a) {
|
|
12
|
+
// Plain `instanceof Uint8Array` is too strict for some Buffer / proxy / cross-realm cases.
|
|
13
|
+
// The fallback still requires a real ArrayBuffer view, so plain
|
|
14
|
+
// JSON-deserialized `{ constructor: ... }` spoofing is rejected, and
|
|
15
|
+
// `BYTES_PER_ELEMENT === 1` keeps the fallback on byte-oriented views.
|
|
16
|
+
return (a instanceof Uint8Array ||
|
|
17
|
+
(ArrayBuffer.isView(a) &&
|
|
18
|
+
a.constructor.name === 'Uint8Array' &&
|
|
19
|
+
'BYTES_PER_ELEMENT' in a &&
|
|
20
|
+
a.BYTES_PER_ELEMENT === 1));
|
|
21
|
+
}
|
|
22
|
+
// Shared error-message prefix builder. Only called on throw paths, so assert
|
|
23
|
+
// success paths never pay for the string concatenation.
|
|
24
|
+
const atitle = (title) => (title ? `"${title}" ` : '');
|
|
25
|
+
/**
|
|
26
|
+
* Asserts something is a non-negative integer.
|
|
27
|
+
* @param n - number to validate
|
|
28
|
+
* @param title - label included in thrown errors
|
|
29
|
+
* @returns The validated number.
|
|
30
|
+
* @throws On wrong argument types. {@link TypeError}
|
|
31
|
+
* @throws On wrong argument ranges or values. {@link RangeError}
|
|
32
|
+
* @example
|
|
33
|
+
* Validate a non-negative integer option.
|
|
34
|
+
* ```ts
|
|
35
|
+
* anumber(32, 'length');
|
|
36
|
+
* ```
|
|
37
|
+
*/
|
|
38
|
+
export function anumber(n, title = '') {
|
|
39
|
+
if (typeof n !== 'number')
|
|
40
|
+
throw new TypeError(atitle(title) + 'expected number, got ' + typeof n);
|
|
41
|
+
if (!Number.isSafeInteger(n) || n < 0)
|
|
42
|
+
throw new RangeError(atitle(title) + 'expected integer >= 0, got ' + n);
|
|
43
|
+
return n;
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Asserts something is a boolean.
|
|
47
|
+
* @param value - value to validate
|
|
48
|
+
* @param title - label included in thrown errors
|
|
49
|
+
* @returns The validated boolean.
|
|
50
|
+
* @throws On wrong argument types. {@link TypeError}
|
|
51
|
+
* @example
|
|
52
|
+
* Validate a boolean option.
|
|
53
|
+
* ```ts
|
|
54
|
+
* abool(true, 'enableXOF');
|
|
55
|
+
* ```
|
|
56
|
+
*/
|
|
57
|
+
export function abool(value, title = '') {
|
|
58
|
+
if (typeof value !== 'boolean')
|
|
59
|
+
throw new TypeError(atitle(title) + 'expected boolean, got type=' + typeof value);
|
|
60
|
+
return value;
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* Asserts something is Uint8Array.
|
|
64
|
+
* @param value - value to validate
|
|
65
|
+
* @param length - optional exact length constraint
|
|
66
|
+
* @param title - label included in thrown errors
|
|
67
|
+
* @returns The validated byte array.
|
|
68
|
+
* @throws On wrong argument types. {@link TypeError}
|
|
69
|
+
* @throws On wrong argument ranges or values. {@link RangeError}
|
|
70
|
+
* @example
|
|
71
|
+
* Validate that a value is a byte array.
|
|
72
|
+
* ```ts
|
|
73
|
+
* abytes(new Uint8Array([1, 2, 3]));
|
|
74
|
+
* ```
|
|
75
|
+
*/
|
|
76
|
+
export function abytes(value, length, title = '') {
|
|
77
|
+
// Success path first: this runs at the start of every update() / digestInto(), and the
|
|
78
|
+
// common `abytes(data)` form must not pay for length handling it does not use.
|
|
79
|
+
if (isBytes(value) && (length === undefined || value.length === length))
|
|
80
|
+
return value;
|
|
81
|
+
// Error path: recompute freely to build the exact message.
|
|
82
|
+
if (length !== undefined)
|
|
83
|
+
anumber(length, 'length');
|
|
84
|
+
const bytes = isBytes(value);
|
|
85
|
+
const ofLen = length !== undefined ? ` of length ${length}` : '';
|
|
86
|
+
const got = bytes ? `length=${value.length}` : `type=${typeof value}`;
|
|
87
|
+
const message = atitle(title) + 'expected Uint8Array' + ofLen + ', got ' + got;
|
|
88
|
+
if (!bytes)
|
|
89
|
+
throw new TypeError(message);
|
|
90
|
+
throw new RangeError(message);
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
93
|
+
* Copies bytes into a fresh Uint8Array.
|
|
94
|
+
* Buffer-style slices can alias the same backing store, so callers that need ownership should copy.
|
|
95
|
+
* @param bytes - source bytes to clone
|
|
96
|
+
* @returns Freshly allocated copy of `bytes`.
|
|
97
|
+
* @throws On wrong argument types. {@link TypeError}
|
|
98
|
+
* @example
|
|
99
|
+
* Clone a byte array before mutating it.
|
|
100
|
+
* ```ts
|
|
101
|
+
* const copy = copyBytes(new Uint8Array([1, 2, 3]));
|
|
102
|
+
* ```
|
|
103
|
+
*/
|
|
104
|
+
export function copyBytes(bytes) {
|
|
105
|
+
// `Uint8Array.from(...)` would also accept arrays / other typed arrays. Keep this helper strict
|
|
106
|
+
// because callers use it at byte-validation boundaries before mutating the detached copy.
|
|
107
|
+
return Uint8Array.from(abytes(bytes));
|
|
108
|
+
}
|
|
109
|
+
/**
|
|
110
|
+
* Asserts something is a wrapped hash constructor.
|
|
111
|
+
* @param h - hash constructor to validate
|
|
112
|
+
* @throws On wrong argument types or invalid hash wrapper shape. {@link TypeError}
|
|
113
|
+
* @throws On invalid hash metadata ranges or values. {@link RangeError}
|
|
114
|
+
* @throws If the hash metadata allows empty outputs or block sizes. {@link Error}
|
|
115
|
+
* @example
|
|
116
|
+
* Validate a callable hash wrapper.
|
|
117
|
+
* ```ts
|
|
118
|
+
* import { ahash } from '@noble/hashes/utils.js';
|
|
119
|
+
* import { sha256 } from '@noble/hashes/sha2.js';
|
|
120
|
+
* ahash(sha256);
|
|
121
|
+
* ```
|
|
122
|
+
*/
|
|
123
|
+
export function ahash(h) {
|
|
124
|
+
if (typeof h !== 'function' || typeof h.create !== 'function')
|
|
125
|
+
throw new TypeError('expected hash wrapped by utils.createHasher');
|
|
126
|
+
anumber(h.outputLen);
|
|
127
|
+
anumber(h.blockLen);
|
|
128
|
+
// HMAC and KDF callers treat these as real byte lengths; allowing zero lets fake wrappers pass
|
|
129
|
+
// validation and can produce empty outputs instead of failing fast.
|
|
130
|
+
if (h.outputLen < 1 || h.blockLen < 1)
|
|
131
|
+
throw new Error('hash blockLen / outputLen must be >= 1');
|
|
132
|
+
}
|
|
133
|
+
const aobject = (value, label) => {
|
|
134
|
+
if (value === null || typeof value !== 'object' || Array.isArray(value))
|
|
135
|
+
throw new TypeError((label === 'object' ? '' : `"${label}" `) + 'expected object, got type=' + typeof value);
|
|
136
|
+
};
|
|
137
|
+
const aopts = (value, label) => {
|
|
138
|
+
aobject(value, label);
|
|
139
|
+
const proto = Object.getPrototypeOf(value);
|
|
140
|
+
if (proto !== Object.prototype && proto !== null)
|
|
141
|
+
throw new TypeError(`"${label}" expected plain object`);
|
|
142
|
+
// Object.assign() treats an own "__proto__" source key as a write to the target's legacy
|
|
143
|
+
// prototype setter. Reject it before merging so inherited option values cannot be injected.
|
|
144
|
+
if (Object.hasOwn(value, '__proto__'))
|
|
145
|
+
throw new TypeError(`"${label}.__proto__" is not allowed`);
|
|
146
|
+
};
|
|
147
|
+
/**
|
|
148
|
+
* Asserts a hash instance has not been destroyed or finished.
|
|
149
|
+
* @param instance - hash instance to validate
|
|
150
|
+
* @param checkFinished - whether to reject finalized instances
|
|
151
|
+
* @throws If the hash instance has already been destroyed or finalized. {@link Error}
|
|
152
|
+
* @example
|
|
153
|
+
* Validate that a hash instance is still usable.
|
|
154
|
+
* ```ts
|
|
155
|
+
* import { aexists } from '@noble/hashes/utils.js';
|
|
156
|
+
* import { sha256 } from '@noble/hashes/sha2.js';
|
|
157
|
+
* const hash = sha256.create();
|
|
158
|
+
* aexists(hash);
|
|
159
|
+
* ```
|
|
160
|
+
*/
|
|
161
|
+
export function aexists(instance, checkFinished = true) {
|
|
162
|
+
// Runs on every update()/digestInto(); the flags are library-owned booleans, so only their
|
|
163
|
+
// truthiness is checked - re-validating their type per call was pure hot-path overhead.
|
|
164
|
+
if (instance.destroyed)
|
|
165
|
+
throw new Error('hash was destroyed');
|
|
166
|
+
if (checkFinished && instance.finished)
|
|
167
|
+
throw new Error('digest() was already called');
|
|
168
|
+
}
|
|
169
|
+
/**
|
|
170
|
+
* Asserts output is a sufficiently-sized byte array.
|
|
171
|
+
* @param out - destination buffer
|
|
172
|
+
* @param instance - hash instance providing output length
|
|
173
|
+
* Oversized buffers are allowed; downstream code only promises to fill the first `outputLen` bytes.
|
|
174
|
+
* @throws On wrong argument types. {@link TypeError}
|
|
175
|
+
* @throws On wrong argument ranges or values. {@link RangeError}
|
|
176
|
+
* @example
|
|
177
|
+
* Validate a caller-provided digest buffer.
|
|
178
|
+
* ```ts
|
|
179
|
+
* import { aoutput } from '@noble/hashes/utils.js';
|
|
180
|
+
* import { sha256 } from '@noble/hashes/sha2.js';
|
|
181
|
+
* const hash = sha256.create();
|
|
182
|
+
* aoutput(new Uint8Array(hash.outputLen), hash);
|
|
183
|
+
* ```
|
|
184
|
+
*/
|
|
185
|
+
export function aoutput(out, instance) {
|
|
186
|
+
abytes(out, undefined, 'output');
|
|
187
|
+
// `outputLen` is a library-owned readonly number; the negated comparison keeps failing fast
|
|
188
|
+
// when it is missing/NaN (comparisons with undefined/NaN are false) without an anumber() call.
|
|
189
|
+
const min = instance.outputLen;
|
|
190
|
+
if (!(out.length >= min)) {
|
|
191
|
+
throw new RangeError('"output" expected length >= ' + min);
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
/**
|
|
195
|
+
* Casts a typed array view to Uint8Array.
|
|
196
|
+
* @param arr - source typed array
|
|
197
|
+
* @returns Uint8Array view over the same buffer.
|
|
198
|
+
* @example
|
|
199
|
+
* Reinterpret a typed array as bytes.
|
|
200
|
+
* ```ts
|
|
201
|
+
* u8(new Uint32Array([1, 2]));
|
|
202
|
+
* ```
|
|
203
|
+
*/
|
|
204
|
+
export function u8(arr) {
|
|
205
|
+
return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);
|
|
206
|
+
}
|
|
207
|
+
/**
|
|
208
|
+
* Casts a typed array view to Uint32Array.
|
|
209
|
+
* `arr.byteOffset` must already be 4-byte aligned or the platform
|
|
210
|
+
* Uint32Array constructor will throw.
|
|
211
|
+
* @param arr - source typed array
|
|
212
|
+
* @returns Uint32Array view over the same buffer.
|
|
213
|
+
* @example
|
|
214
|
+
* Reinterpret a byte array as 32-bit words.
|
|
215
|
+
* ```ts
|
|
216
|
+
* u32(new Uint8Array(8));
|
|
217
|
+
* ```
|
|
218
|
+
*/
|
|
219
|
+
export function u32(arr) {
|
|
220
|
+
return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
|
|
221
|
+
}
|
|
222
|
+
/**
|
|
223
|
+
* Zeroizes typed arrays in place. Warning: JS provides no guarantees.
|
|
224
|
+
* @param arrays - arrays to overwrite with zeros
|
|
225
|
+
* @example
|
|
226
|
+
* Zeroize sensitive buffers in place.
|
|
227
|
+
* ```ts
|
|
228
|
+
* clean(new Uint8Array([1, 2, 3]));
|
|
229
|
+
* ```
|
|
230
|
+
*/
|
|
231
|
+
export function clean(...arrays) {
|
|
232
|
+
for (let i = 0; i < arrays.length; i++) {
|
|
233
|
+
arrays[i].fill(0);
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
/**
|
|
237
|
+
* Creates a DataView for byte-level manipulation.
|
|
238
|
+
* @param arr - source typed array
|
|
239
|
+
* @returns DataView over the same buffer region.
|
|
240
|
+
* @example
|
|
241
|
+
* Create a DataView over an existing buffer.
|
|
242
|
+
* ```ts
|
|
243
|
+
* createView(new Uint8Array(4));
|
|
244
|
+
* ```
|
|
245
|
+
*/
|
|
246
|
+
export function createView(arr) {
|
|
247
|
+
return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
|
|
248
|
+
}
|
|
249
|
+
/**
|
|
250
|
+
* Rotate-right operation for uint32 values.
|
|
251
|
+
* @param word - source word
|
|
252
|
+
* @param shift - shift amount in bits
|
|
253
|
+
* @returns Rotated word.
|
|
254
|
+
* @example
|
|
255
|
+
* Rotate a 32-bit word to the right.
|
|
256
|
+
* ```ts
|
|
257
|
+
* rotr(0x12345678, 8);
|
|
258
|
+
* ```
|
|
259
|
+
*/
|
|
260
|
+
export function rotr(word, shift) {
|
|
261
|
+
return (word << (32 - shift)) | (word >>> shift);
|
|
262
|
+
}
|
|
263
|
+
/**
|
|
264
|
+
* Rotate-left operation for uint32 values.
|
|
265
|
+
* @param word - source word
|
|
266
|
+
* @param shift - shift amount in bits
|
|
267
|
+
* @returns Rotated word.
|
|
268
|
+
* @example
|
|
269
|
+
* Rotate a 32-bit word to the left.
|
|
270
|
+
* ```ts
|
|
271
|
+
* rotl(0x12345678, 8);
|
|
272
|
+
* ```
|
|
273
|
+
*/
|
|
274
|
+
export function rotl(word, shift) {
|
|
275
|
+
return (word << shift) | ((word >>> (32 - shift)) >>> 0);
|
|
276
|
+
}
|
|
277
|
+
/** Whether the current platform is little-endian. */
|
|
278
|
+
export const isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();
|
|
279
|
+
/**
|
|
280
|
+
* Byte-swap operation for uint32 values.
|
|
281
|
+
* @param word - source word
|
|
282
|
+
* @returns Word with reversed byte order.
|
|
283
|
+
* @example
|
|
284
|
+
* Reverse the byte order of a 32-bit word.
|
|
285
|
+
* ```ts
|
|
286
|
+
* byteSwap(0x11223344);
|
|
287
|
+
* ```
|
|
288
|
+
*/
|
|
289
|
+
export function byteSwap(word) {
|
|
290
|
+
return (((word << 24) & 0xff000000) |
|
|
291
|
+
((word << 8) & 0xff0000) |
|
|
292
|
+
((word >>> 8) & 0xff00) |
|
|
293
|
+
((word >>> 24) & 0xff));
|
|
294
|
+
}
|
|
295
|
+
/**
|
|
296
|
+
* Conditionally byte-swaps one 32-bit word on big-endian platforms.
|
|
297
|
+
* @param n - source word
|
|
298
|
+
* @returns Original or byte-swapped word depending on platform endianness.
|
|
299
|
+
* @example
|
|
300
|
+
* Normalize a 32-bit word for host endianness.
|
|
301
|
+
* ```ts
|
|
302
|
+
* swap8IfBE(0x11223344);
|
|
303
|
+
* ```
|
|
304
|
+
*/
|
|
305
|
+
export const swap8IfBE = isLE
|
|
306
|
+
? (n) => n
|
|
307
|
+
: (n) => byteSwap(n) >>> 0;
|
|
308
|
+
/**
|
|
309
|
+
* Byte-swaps every word of a Uint32Array in place.
|
|
310
|
+
* @param arr - array to mutate
|
|
311
|
+
* @returns The same array after mutation; callers pass live state arrays here.
|
|
312
|
+
* @example
|
|
313
|
+
* Reverse the byte order of every word in place.
|
|
314
|
+
* ```ts
|
|
315
|
+
* byteSwap32(new Uint32Array([0x11223344]));
|
|
316
|
+
* ```
|
|
317
|
+
*/
|
|
318
|
+
export function byteSwap32(arr) {
|
|
319
|
+
for (let i = 0; i < arr.length; i++) {
|
|
320
|
+
arr[i] = byteSwap(arr[i]);
|
|
321
|
+
}
|
|
322
|
+
return arr;
|
|
323
|
+
}
|
|
324
|
+
/**
|
|
325
|
+
* Conditionally byte-swaps a Uint32Array on big-endian platforms.
|
|
326
|
+
* @param u - array to normalize for host endianness
|
|
327
|
+
* @returns Original or byte-swapped array depending on platform endianness.
|
|
328
|
+
* On big-endian runtimes this mutates `u` in place via `byteSwap32(...)`.
|
|
329
|
+
* @example
|
|
330
|
+
* Normalize a word array for host endianness.
|
|
331
|
+
* ```ts
|
|
332
|
+
* swap32IfBE(new Uint32Array([0x11223344]));
|
|
333
|
+
* ```
|
|
334
|
+
*/
|
|
335
|
+
export const swap32IfBE = isLE
|
|
336
|
+
? (u) => u
|
|
337
|
+
: byteSwap32;
|
|
338
|
+
// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex
|
|
339
|
+
const hasHexBuiltin = /* @__PURE__ */ (() =>
|
|
340
|
+
// @ts-ignore
|
|
341
|
+
typeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();
|
|
342
|
+
// Array where index 0xf0 (240) is mapped to string 'f0'
|
|
343
|
+
const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));
|
|
344
|
+
/**
|
|
345
|
+
* Convert byte array to hex string.
|
|
346
|
+
* Uses the built-in function when available and assumes it matches the tested
|
|
347
|
+
* fallback semantics.
|
|
348
|
+
* @param bytes - bytes to encode
|
|
349
|
+
* @returns Lowercase hexadecimal string.
|
|
350
|
+
* @throws On wrong argument types. {@link TypeError}
|
|
351
|
+
* @example
|
|
352
|
+
* Convert bytes to lowercase hexadecimal.
|
|
353
|
+
* ```ts
|
|
354
|
+
* bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])); // 'cafe0123'
|
|
355
|
+
* ```
|
|
356
|
+
*/
|
|
357
|
+
export function bytesToHex(bytes) {
|
|
358
|
+
abytes(bytes);
|
|
359
|
+
// @ts-ignore
|
|
360
|
+
if (hasHexBuiltin)
|
|
361
|
+
return bytes.toHex();
|
|
362
|
+
// pre-caching improves the speed 6x
|
|
363
|
+
let hex = '';
|
|
364
|
+
for (let i = 0; i < bytes.length; i++) {
|
|
365
|
+
hex += hexes[bytes[i]];
|
|
366
|
+
}
|
|
367
|
+
return hex;
|
|
368
|
+
}
|
|
369
|
+
// Strict ASCII nibble parser: non-ASCII hex lookalikes are rejected as undefined.
|
|
370
|
+
// ASCII codes: '0'..'9' = 48..57, 'A'..'F' = 65..70, 'a'..'f' = 97..102.
|
|
371
|
+
// prettier-ignore
|
|
372
|
+
function asciiToBase16(ch) {
|
|
373
|
+
return ch >= 48 && ch <= 57 ? ch - 48 // '2' => 50-48
|
|
374
|
+
: ch >= 65 && ch <= 70 ? ch - (65 - 10) // 'B' => 66-(65-10)
|
|
375
|
+
: ch >= 97 && ch <= 102 ? ch - (97 - 10) // 'b' => 98-(97-10)
|
|
376
|
+
: undefined;
|
|
377
|
+
}
|
|
378
|
+
/**
|
|
379
|
+
* Convert hex string to byte array. Uses built-in function, when available.
|
|
380
|
+
* @param hex - hexadecimal string to decode
|
|
381
|
+
* @returns Decoded bytes.
|
|
382
|
+
* @throws On wrong argument types. {@link TypeError}
|
|
383
|
+
* @throws On wrong argument ranges or values. {@link RangeError}
|
|
384
|
+
* @example
|
|
385
|
+
* Decode lowercase hexadecimal into bytes.
|
|
386
|
+
* ```ts
|
|
387
|
+
* hexToBytes('cafe0123'); // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])
|
|
388
|
+
* ```
|
|
389
|
+
*/
|
|
390
|
+
export function hexToBytes(hex) {
|
|
391
|
+
if (typeof hex !== 'string')
|
|
392
|
+
throw new TypeError('hex string expected, got ' + typeof hex);
|
|
393
|
+
if (hasHexBuiltin) {
|
|
394
|
+
try {
|
|
395
|
+
return Uint8Array.fromHex(hex);
|
|
396
|
+
}
|
|
397
|
+
catch (error) {
|
|
398
|
+
if (error instanceof SyntaxError)
|
|
399
|
+
throw new RangeError(error.message);
|
|
400
|
+
throw error;
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
const hl = hex.length;
|
|
404
|
+
const al = hl / 2;
|
|
405
|
+
if (hl % 2)
|
|
406
|
+
throw new RangeError('hex string expected, got unpadded hex of length ' + hl);
|
|
407
|
+
const array = new Uint8Array(al);
|
|
408
|
+
for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
|
|
409
|
+
const n1 = asciiToBase16(hex.charCodeAt(hi)); // parse first char, multiply it by 16
|
|
410
|
+
const n2 = asciiToBase16(hex.charCodeAt(hi + 1)); // parse second char
|
|
411
|
+
if (n1 === undefined || n2 === undefined) {
|
|
412
|
+
const char = hex[hi] + hex[hi + 1];
|
|
413
|
+
throw new RangeError('hex string expected, got non-hex character "' + char + '" at index ' + hi);
|
|
414
|
+
}
|
|
415
|
+
array[ai] = n1 * 16 + n2; // example: 'A9' => 10*16 + 9
|
|
416
|
+
}
|
|
417
|
+
return array;
|
|
418
|
+
}
|
|
419
|
+
/**
|
|
420
|
+
* Yields to the host task scheduler so timers, I/O, and rendering can make progress.
|
|
421
|
+
* Uses the Web Scheduling API when available or `setTimeout` as a cross-platform fallback.
|
|
422
|
+
* Host-task yields are much slower than microtasks (roughly 1ms with the timer fallback), so
|
|
423
|
+
* async loops should use `asyncTick >= 10` to amortize scheduling overhead to about 10% while
|
|
424
|
+
* still allowing other event-loop work to proceed.
|
|
425
|
+
* @param onReject - optional cleanup invoked only if the host yield fails
|
|
426
|
+
* @example
|
|
427
|
+
* Yield to the next scheduler tick.
|
|
428
|
+
* ```ts
|
|
429
|
+
* await nextTick();
|
|
430
|
+
* ```
|
|
431
|
+
*/
|
|
432
|
+
export function nextTick(onReject) {
|
|
433
|
+
const host = globalThis;
|
|
434
|
+
if (typeof host.scheduler?.yield === 'function') {
|
|
435
|
+
const promise = host.scheduler.yield();
|
|
436
|
+
// Keep the original scheduler rejection; this handler exists only for cleanup.
|
|
437
|
+
if (onReject)
|
|
438
|
+
promise.catch(onReject);
|
|
439
|
+
return promise;
|
|
440
|
+
}
|
|
441
|
+
return new Promise((resolve) => host.setTimeout(resolve, 0));
|
|
442
|
+
}
|
|
443
|
+
/**
|
|
444
|
+
* Returns control to the host event loop every `tick` milliseconds to avoid blocking long loops.
|
|
445
|
+
* @param iters - number of loop iterations to run
|
|
446
|
+
* @param tick - maximum time slice in milliseconds
|
|
447
|
+
* @param cb - callback executed on each iteration
|
|
448
|
+
* @param onReject - optional cleanup invoked only if a host yield fails
|
|
449
|
+
* @throws On wrong argument types. {@link TypeError}
|
|
450
|
+
* @throws On wrong argument ranges or values. {@link RangeError}
|
|
451
|
+
* @example
|
|
452
|
+
* Run a loop that periodically yields back to the event loop.
|
|
453
|
+
* ```ts
|
|
454
|
+
* await asyncLoop(2, 0, () => {});
|
|
455
|
+
* ```
|
|
456
|
+
*/
|
|
457
|
+
export async function asyncLoop(iters, tick, cb, onReject) {
|
|
458
|
+
anumber(iters, 'iters');
|
|
459
|
+
anumber(tick, 'tick');
|
|
460
|
+
if (typeof cb !== 'function')
|
|
461
|
+
throw new TypeError('callback must be a function');
|
|
462
|
+
// Callback is synchronous by contract; asyncLoop only yields between sync work windows.
|
|
463
|
+
let ts = Date.now();
|
|
464
|
+
for (let i = 0; i < iters; i++) {
|
|
465
|
+
cb(i);
|
|
466
|
+
// Date.now() is not monotonic, so in case if clock goes backwards we return return control too
|
|
467
|
+
const diff = Date.now() - ts;
|
|
468
|
+
if (diff >= 0 && diff < tick)
|
|
469
|
+
continue;
|
|
470
|
+
await nextTick(onReject);
|
|
471
|
+
// Track only synchronous work time; scheduler delay after yielding is outside our budget.
|
|
472
|
+
ts = Date.now();
|
|
473
|
+
}
|
|
474
|
+
}
|
|
475
|
+
/**
|
|
476
|
+
* Converts string to bytes using UTF8 encoding.
|
|
477
|
+
* Built-in doesn't validate input to be string: we do the check.
|
|
478
|
+
* Non-ASCII details are delegated to the platform `TextEncoder`.
|
|
479
|
+
* @param str - string to encode
|
|
480
|
+
* @returns UTF-8 encoded bytes.
|
|
481
|
+
* @throws On wrong argument types. {@link TypeError}
|
|
482
|
+
* @example
|
|
483
|
+
* Encode a string as UTF-8 bytes.
|
|
484
|
+
* ```ts
|
|
485
|
+
* utf8ToBytes('abc'); // Uint8Array.from([97, 98, 99])
|
|
486
|
+
* ```
|
|
487
|
+
*/
|
|
488
|
+
export function utf8ToBytes(str) {
|
|
489
|
+
if (typeof str !== 'string')
|
|
490
|
+
throw new TypeError('string expected');
|
|
491
|
+
const encoded = new TextEncoder().encode(str);
|
|
492
|
+
try {
|
|
493
|
+
// Copy into the current realm for Firefox extension contexts. Callers that own the returned
|
|
494
|
+
// buffer can then wipe it independently of TextEncoder's temporary result.
|
|
495
|
+
return new Uint8Array(encoded); // https://bugzil.la/1681809
|
|
496
|
+
}
|
|
497
|
+
finally {
|
|
498
|
+
clean(encoded);
|
|
499
|
+
}
|
|
500
|
+
}
|
|
501
|
+
/**
|
|
502
|
+
* Helper for KDFs: consumes Uint8Array or string.
|
|
503
|
+
* String inputs are UTF-8 encoded; byte-array inputs stay aliased to the caller buffer.
|
|
504
|
+
* @param data - user-provided KDF input
|
|
505
|
+
* @param errorTitle - label included in thrown errors
|
|
506
|
+
* @returns Byte representation of the input.
|
|
507
|
+
* @throws On wrong argument types. {@link TypeError}
|
|
508
|
+
* @example
|
|
509
|
+
* Normalize KDF input to bytes.
|
|
510
|
+
* ```ts
|
|
511
|
+
* kdfInputToBytes('password');
|
|
512
|
+
* ```
|
|
513
|
+
*/
|
|
514
|
+
export function kdfInputToBytes(data, errorTitle = '') {
|
|
515
|
+
if (typeof data === 'string')
|
|
516
|
+
return utf8ToBytes(data);
|
|
517
|
+
return abytes(data, undefined, errorTitle);
|
|
518
|
+
}
|
|
519
|
+
/**
|
|
520
|
+
* Copies several Uint8Arrays into one.
|
|
521
|
+
* @param arrays - arrays to concatenate
|
|
522
|
+
* @returns Concatenated byte array.
|
|
523
|
+
* @throws On wrong argument types. {@link TypeError}
|
|
524
|
+
* @example
|
|
525
|
+
* Concatenate multiple byte arrays.
|
|
526
|
+
* ```ts
|
|
527
|
+
* concatBytes(new Uint8Array([1]), new Uint8Array([2]));
|
|
528
|
+
* ```
|
|
529
|
+
*/
|
|
530
|
+
export function concatBytes(...arrays) {
|
|
531
|
+
let sum = 0;
|
|
532
|
+
for (let i = 0; i < arrays.length; i++) {
|
|
533
|
+
const a = arrays[i];
|
|
534
|
+
abytes(a);
|
|
535
|
+
sum += a.length;
|
|
536
|
+
}
|
|
537
|
+
const res = new Uint8Array(sum);
|
|
538
|
+
for (let i = 0, pad = 0; i < arrays.length; i++) {
|
|
539
|
+
const a = arrays[i];
|
|
540
|
+
res.set(a, pad);
|
|
541
|
+
pad += a.length;
|
|
542
|
+
}
|
|
543
|
+
return res;
|
|
544
|
+
}
|
|
545
|
+
/**
|
|
546
|
+
* Validates declared required and optional field types on a plain object.
|
|
547
|
+
* This walks field schemas and formats detailed errors, so avoid it on hot paths; use direct
|
|
548
|
+
* one-line guards such as `abytes()`, `abool()`, or `anumber()` instead.
|
|
549
|
+
* @param object - object to validate
|
|
550
|
+
* @param fields - map of required field names to expected types
|
|
551
|
+
* @param optFields - map of optional field names to expected types
|
|
552
|
+
* @param title - label included in thrown errors
|
|
553
|
+
* @throws On wrong argument types. {@link TypeError}
|
|
554
|
+
* @example
|
|
555
|
+
* Validate required and optional option fields.
|
|
556
|
+
* ```ts
|
|
557
|
+
* validateObject({ N: 1024, dkLen: 32 }, { N: 'number' }, { dkLen: 'number' });
|
|
558
|
+
* ```
|
|
559
|
+
*/
|
|
560
|
+
export const validateObject = (object, fields = {}, optFields = {}, title = 'object') => {
|
|
561
|
+
aobject(object, title);
|
|
562
|
+
aobject(fields, 'fields');
|
|
563
|
+
aobject(optFields, 'optFields');
|
|
564
|
+
function checkField(fieldName, expectedType, isOpt) {
|
|
565
|
+
const label = title === 'object' ? `param "${String(fieldName)}"` : `"${title}.${String(fieldName)}"`;
|
|
566
|
+
// Config fields must be explicit own properties. Optional inherited values are rejected too
|
|
567
|
+
// because callers keep reading the same options object after validation.
|
|
568
|
+
const val = object[fieldName];
|
|
569
|
+
// Runtime objects such as Field instances intentionally satisfy required method slots
|
|
570
|
+
// via their shared prototype.
|
|
571
|
+
if (!Object.hasOwn(object, fieldName) &&
|
|
572
|
+
(isOpt ? val !== undefined : expectedType !== 'function')) {
|
|
573
|
+
throw new TypeError(`${label} is invalid: expected own property`);
|
|
574
|
+
}
|
|
575
|
+
if (isOpt && val === undefined)
|
|
576
|
+
return;
|
|
577
|
+
const current = typeof val;
|
|
578
|
+
if (current !== expectedType || val === null)
|
|
579
|
+
throw new TypeError(`${label} is invalid: expected ${expectedType}, got ${current}`);
|
|
580
|
+
}
|
|
581
|
+
const iter = (f, isOpt) => Object.entries(f).forEach(([k, v]) => checkField(k, v, isOpt));
|
|
582
|
+
iter(fields, false);
|
|
583
|
+
iter(optFields, true);
|
|
584
|
+
};
|
|
585
|
+
/**
|
|
586
|
+
* Merges default options and passed options.
|
|
587
|
+
* @param defaults - base option object
|
|
588
|
+
* @param opts - user overrides
|
|
589
|
+
* @param title - label included in thrown override errors
|
|
590
|
+
* @returns Fresh merged option object with a null prototype.
|
|
591
|
+
* @throws On wrong argument types. {@link TypeError}
|
|
592
|
+
* @example
|
|
593
|
+
* Merge user overrides onto default options.
|
|
594
|
+
* ```ts
|
|
595
|
+
* checkOpts({ dkLen: 32 }, { asyncTick: 10 });
|
|
596
|
+
* ```
|
|
597
|
+
*/
|
|
598
|
+
export function checkOpts(defaults, opts, title = 'opts') {
|
|
599
|
+
aopts(defaults, 'defaults');
|
|
600
|
+
if (opts !== undefined)
|
|
601
|
+
aopts(opts, title);
|
|
602
|
+
// Callers read optional fields directly, so omitted values must not fall through to ambient
|
|
603
|
+
// Object.prototype pollution (for example a forged `dkLen` changing SHAKE's default output).
|
|
604
|
+
const merged = Object.assign(Object.create(null), defaults, opts);
|
|
605
|
+
return merged;
|
|
606
|
+
}
|
|
607
|
+
/**
|
|
608
|
+
* Creates a callable hash function from a stateful class constructor.
|
|
609
|
+
* @param hashCons - hash constructor or factory
|
|
610
|
+
* @param info - optional metadata such as DER OID
|
|
611
|
+
* @returns Frozen callable hash wrapper with `.create()`.
|
|
612
|
+
* Wrapper construction eagerly calls `hashCons(undefined)` once to read
|
|
613
|
+
* `outputLen` / `blockLen`, so constructor side effects happen at module
|
|
614
|
+
* init time.
|
|
615
|
+
* @throws On wrong argument types. {@link TypeError}
|
|
616
|
+
* @example
|
|
617
|
+
* Wrap a stateful hash constructor into a callable helper.
|
|
618
|
+
* ```ts
|
|
619
|
+
* import { createHasher } from '@noble/hashes/utils.js';
|
|
620
|
+
* import { sha256 } from '@noble/hashes/sha2.js';
|
|
621
|
+
* const wrapped = createHasher(sha256.create, { oid: sha256.oid });
|
|
622
|
+
* wrapped(new Uint8Array([1]));
|
|
623
|
+
* ```
|
|
624
|
+
*/
|
|
625
|
+
export function createHasher(hashCons, info = {}) {
|
|
626
|
+
if (typeof hashCons !== 'function')
|
|
627
|
+
throw new TypeError('"hashCons" expected function, got type=' + typeof hashCons);
|
|
628
|
+
info = checkOpts({}, info, 'info');
|
|
629
|
+
const hashC = (msg, opts) => hashCons(opts)
|
|
630
|
+
.update(msg)
|
|
631
|
+
.digest();
|
|
632
|
+
const tmp = hashCons(undefined);
|
|
633
|
+
hashC.outputLen = tmp.outputLen;
|
|
634
|
+
hashC.blockLen = tmp.blockLen;
|
|
635
|
+
hashC.canXOF = tmp.canXOF;
|
|
636
|
+
hashC.create = (opts) => hashCons(opts);
|
|
637
|
+
Object.assign(hashC, info);
|
|
638
|
+
return Object.freeze(hashC);
|
|
639
|
+
}
|
|
640
|
+
/**
|
|
641
|
+
* Cryptographically secure PRNG backed by `crypto.getRandomValues`.
|
|
642
|
+
* @param bytesLength - number of random bytes to generate
|
|
643
|
+
* @returns Random bytes.
|
|
644
|
+
* The platform `getRandomValues()` implementation still defines any
|
|
645
|
+
* single-call length cap, and this helper rejects oversize requests
|
|
646
|
+
* with a stable library `RangeError` instead of host-specific errors.
|
|
647
|
+
* @throws On wrong argument types. {@link TypeError}
|
|
648
|
+
* @throws On wrong argument ranges or values. {@link RangeError}
|
|
649
|
+
* @throws If the current runtime does not provide `crypto.getRandomValues`. {@link Error}
|
|
650
|
+
* @example
|
|
651
|
+
* Generate a fresh random key or nonce.
|
|
652
|
+
* ```ts
|
|
653
|
+
* const key = randomBytes(16);
|
|
654
|
+
* ```
|
|
655
|
+
*/
|
|
656
|
+
export function randomBytes(bytesLength = 32) {
|
|
657
|
+
// Match the repo's other length-taking helpers instead of relying on Uint8Array coercion.
|
|
658
|
+
anumber(bytesLength, 'bytesLength');
|
|
659
|
+
const cr = typeof globalThis === 'object' ? globalThis.crypto : null;
|
|
660
|
+
if (typeof cr?.getRandomValues !== 'function')
|
|
661
|
+
throw new Error('crypto.getRandomValues must be defined');
|
|
662
|
+
// Web Cryptography API Level 2 §10.1.1:
|
|
663
|
+
// if `byteLength > 65536`, throw `QuotaExceededError`.
|
|
664
|
+
// Keep the guard explicit so callers can see the quota in code
|
|
665
|
+
// instead of discovering it by reading the spec or host errors.
|
|
666
|
+
// This wrapper surfaces the same quota as a stable library RangeError.
|
|
667
|
+
if (bytesLength > 65536)
|
|
668
|
+
throw new RangeError(`"bytesLength" expected <= 65536, got ${bytesLength}`);
|
|
669
|
+
return cr.getRandomValues(new Uint8Array(bytesLength));
|
|
670
|
+
}
|
|
671
|
+
/**
|
|
672
|
+
* Creates OID metadata for NIST hashes with prefix `06 09 60 86 48 01 65 03 04 02`.
|
|
673
|
+
* @param suffix - final OID byte for the selected hash.
|
|
674
|
+
* The helper accepts any byte even though only the documented NIST hash
|
|
675
|
+
* suffixes are meaningful downstream.
|
|
676
|
+
* @returns Object containing the DER-encoded OID.
|
|
677
|
+
* @example
|
|
678
|
+
* Build OID metadata for a NIST hash.
|
|
679
|
+
* ```ts
|
|
680
|
+
* oidNist(0x01);
|
|
681
|
+
* ```
|
|
682
|
+
*/
|
|
683
|
+
export const oidNist = (suffix) => ({
|
|
684
|
+
// Current NIST hashAlgs suffixes used here fit in one DER subidentifier octet.
|
|
685
|
+
// Larger suffix values would need base-128 OID encoding and a different length byte.
|
|
686
|
+
oid: Uint8Array.from([0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, suffix]),
|
|
687
|
+
});
|