@mark1russell7/rigor-generators 0.1.6 → 0.1.8

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/README.md CHANGED
@@ -27,7 +27,7 @@ r.normal(10, 2); // a normal value with the mean 10 and the standard deviation 2
27
27
  r.fork("lanes"); // an independent generator for one part of the work
28
28
  r.seed; // the 32-bit seed: write it in each failure message
29
29
 
30
- // The seeds of a run: the seed of the environment variable SEED, else the defaults.
30
+ // The seeds of a run: the seeds of the environment variable SEED (for example "7" or "1,3,9-11"), else the defaults.
31
31
  for (const seed of seedsFrom(process.env.SEED, [1, 2, 3, 4, 5])) {
32
32
  // ...
33
33
  }
@@ -104,6 +104,27 @@ The option `input` of `fnv1a32` selects the units that the hash reads. Use it to
104
104
 
105
105
  For a string without a lone surrogate, `"utf8"` and `"wtf8"` give the same hash.
106
106
 
107
+ ## A content hash
108
+
109
+ `canonicalHash(value)` gives the SHA-256 digest of the canonical form of a value. Equal values give equal hashes, also when the keys of their objects have another order.
110
+
111
+ ```ts
112
+ import { canonicalHash, canonicalJson, sha256Hex } from "@mark1russell7/rigor-generators";
113
+
114
+ canonicalJson({ b: [1, undefined], a: "x" }); // '{"a":"x","b":[1,null]}'
115
+ canonicalHash({ b: 1, a: 2 }) === canonicalHash({ a: 2, b: 1 }); // true
116
+ sha256Hex("abc"); // "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
117
+ ```
118
+
119
+ The default form of `canonicalJson` is RFC 8785 (JCS). Two options change it:
120
+
121
+ | Option | The default | The other value |
122
+ | --- | --- | --- |
123
+ | `form` | `"jcs"`: `NaN`, an infinite number and a lone surrogate cause a `RangeError` | `"json"`: the form of `JSON.stringify`, so these values become `null` or an escape |
124
+ | `bigint` | `"error"`: a `bigint` causes a `TypeError` | `"suffix"`: the digits and `n`, for example `12n`. This text is not JSON, so use it only for a key |
125
+
126
+ The option `input` of `sha256Hex` has the values `"utf8"` and `"wtf8"` of `fnv1a32`. The two functions use no API of Node or of the browser. `sha256Hex` is not for passwords.
127
+
107
128
  ## Move from a copy of mulberry32
108
129
 
109
130
  Each common form of mulberry32 gives the same numbers as `random(seed).next`: the first published form (`| 0` on the state) and the form with `>>> 0`. These also give the same values:
@@ -0,0 +1,47 @@
1
+ /** The options of `sha256Hex`. */
2
+ export interface Sha256Options {
3
+ /**
4
+ * The bytes that the hash reads, as in `fnv1a32`:
5
+ *
6
+ * - `"utf8"` (the default): the UTF-8 bytes. A lone surrogate becomes the bytes of U+FFFD, as `TextEncoder` writes them.
7
+ * - `"wtf8"`: the UTF-8 bytes of each code point. A lone surrogate becomes its own 3 bytes (WTF-8).
8
+ *
9
+ * For a string without a lone surrogate, the two inputs give the same hash.
10
+ */
11
+ readonly input?: "utf8" | "wtf8";
12
+ }
13
+ /**
14
+ * This function gives the SHA-256 digest of the bytes of a string, as 64 lowercase hex characters.
15
+ * The option `input` selects the bytes of a lone surrogate. It is not for passwords: it has no salt and no cost.
16
+ */
17
+ export declare function sha256Hex(text: string, options?: Sha256Options): string;
18
+ /** The options of `canonicalJson` and `canonicalHash`. */
19
+ export interface CanonicalOptions {
20
+ /**
21
+ * The form of the values that JSON does not have:
22
+ *
23
+ * - `"jcs"` (the default): RFC 8785. `NaN`, an infinite number and a string with a lone surrogate cause a `RangeError`.
24
+ * - `"json"`: the form of `JSON.stringify`. `NaN` and an infinite number become `null`, and a lone surrogate becomes an escape.
25
+ */
26
+ readonly form?: "jcs" | "json";
27
+ /**
28
+ * The form of a `bigint`. `"error"` (the default) causes a `TypeError`, as `JSON.stringify` does.
29
+ * `"suffix"` writes the digits and the letter `n`, for example `12n`. This text is not JSON, so use it only for a key.
30
+ */
31
+ readonly bigint?: "error" | "suffix";
32
+ }
33
+ /**
34
+ * This function gives the canonical form of a value. The default form is RFC 8785 (JCS):
35
+ *
36
+ * - The keys of each object are in the order of their UTF-16 code units, with no whitespace.
37
+ * - The numbers and the strings have the form of `JSON.stringify`, which is the form of RFC 8785.
38
+ * - A key with the value `undefined` is not in the form. An `undefined` in an array, or as the value, becomes `null`.
39
+ * - An object with a method `toJSON`, for example a `Date`, gives the form of the result of that method.
40
+ * - A function, a symbol and a cycle cause a `TypeError`.
41
+ *
42
+ * `canonicalJson(JSON.parse(canonicalJson(v)))` is equal to `canonicalJson(v)`.
43
+ */
44
+ export declare function canonicalJson(value: unknown, options?: CanonicalOptions): string;
45
+ /** This function gives the content hash of a value: `sha256Hex(canonicalJson(value, options))`. */
46
+ export declare function canonicalHash(value: unknown, options?: CanonicalOptions): string;
47
+ //# sourceMappingURL=hash.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hash.d.ts","names":[],"sources":["../src/hash.ts"],"mappings":";iBAiBiB;;;;;;;;;WASN;;;;;;wBAmDK,UAAU,cAAc,UAAU;;iBAwDjC;;;;;;;WAON;;;;;WAKA;;;;;;;;;;;;;wBAcK,cAAc,gBAAgB,UAAU;;wBAgDxC,cAAc,gBAAgB,UAAU"}
package/build/hash.js ADDED
@@ -0,0 +1,240 @@
1
+ // src/hash.ts
2
+ /**
3
+ * The content hash of a document: SHA-256 of a string, and a canonical JSON form of a value.
4
+ *
5
+ * The two functions use no API of Node or of the browser, so a hash is the same on each platform.
6
+ * `canonicalHash(value)` is `sha256Hex(canonicalJson(value))`: equal values give equal hashes, also when their keys have another order.
7
+ */
8
+ /** The round constants of SHA-256. */
9
+ const K = [
10
+ 1116352408,
11
+ 1899447441,
12
+ 3049323471,
13
+ 3921009573,
14
+ 961987163,
15
+ 1508970993,
16
+ 2453635748,
17
+ 2870763221,
18
+ 3624381080,
19
+ 310598401,
20
+ 607225278,
21
+ 1426881987,
22
+ 1925078388,
23
+ 2162078206,
24
+ 2614888103,
25
+ 3248222580,
26
+ 3835390401,
27
+ 4022224774,
28
+ 264347078,
29
+ 604807628,
30
+ 770255983,
31
+ 1249150122,
32
+ 1555081692,
33
+ 1996064986,
34
+ 2554220882,
35
+ 2821834349,
36
+ 2952996808,
37
+ 3210313671,
38
+ 3336571891,
39
+ 3584528711,
40
+ 113926993,
41
+ 338241895,
42
+ 666307205,
43
+ 773529912,
44
+ 1294757372,
45
+ 1396182291,
46
+ 1695183700,
47
+ 1986661051,
48
+ 2177026350,
49
+ 2456956037,
50
+ 2730485921,
51
+ 2820302411,
52
+ 3259730800,
53
+ 3345764771,
54
+ 3516065817,
55
+ 3600352804,
56
+ 4094571909,
57
+ 275423344,
58
+ 430227734,
59
+ 506948616,
60
+ 659060556,
61
+ 883997877,
62
+ 958139571,
63
+ 1322822218,
64
+ 1537002063,
65
+ 1747873779,
66
+ 1955562222,
67
+ 2024104815,
68
+ 2227730452,
69
+ 2361852424,
70
+ 2428436474,
71
+ 2756734187,
72
+ 3204031479,
73
+ 3329325298
74
+ ];
75
+ /**
76
+ * This function writes the bytes of a string into `out` and gives the count of the bytes. With no `out`, it only counts.
77
+ * It reads the UTF-16 code units, so it makes no string for each character.
78
+ */
79
+ function writeBytes(text, wtf8, out) {
80
+ let n = 0;
81
+ for (let i = 0; i < text.length; i++) {
82
+ let c = text.charCodeAt(i);
83
+ if (c >= 55296 && c < 57344) {
84
+ const low = i + 1 < text.length ? text.charCodeAt(i + 1) : 0;
85
+ if (c < 56320 && low >= 56320 && low < 57344) {
86
+ c = 65536 + (c - 55296 << 10) + (low - 56320);
87
+ i++;
88
+ } else if (!wtf8) c = 65533;
89
+ }
90
+ if (c < 128) {
91
+ if (out !== void 0) out[n] = c;
92
+ n += 1;
93
+ } else if (c < 2048) {
94
+ if (out !== void 0) {
95
+ out[n] = 192 | c >> 6;
96
+ out[n + 1] = 128 | c & 63;
97
+ }
98
+ n += 2;
99
+ } else if (c < 65536) {
100
+ if (out !== void 0) {
101
+ out[n] = 224 | c >> 12;
102
+ out[n + 1] = 128 | c >> 6 & 63;
103
+ out[n + 2] = 128 | c & 63;
104
+ }
105
+ n += 3;
106
+ } else {
107
+ if (out !== void 0) {
108
+ out[n] = 240 | c >> 18;
109
+ out[n + 1] = 128 | c >> 12 & 63;
110
+ out[n + 2] = 128 | c >> 6 & 63;
111
+ out[n + 3] = 128 | c & 63;
112
+ }
113
+ n += 4;
114
+ }
115
+ }
116
+ return n;
117
+ }
118
+ /**
119
+ * This function gives the SHA-256 digest of the bytes of a string, as 64 lowercase hex characters.
120
+ * The option `input` selects the bytes of a lone surrogate. It is not for passwords: it has no salt and no cost.
121
+ */
122
+ function sha256Hex(text, options) {
123
+ const input = options?.input ?? "utf8";
124
+ if (input !== "utf8" && input !== "wtf8") throw new RangeError(`sha256Hex: input is "utf8" or "wtf8", not ${String(input)}.`);
125
+ const wtf8 = input === "wtf8";
126
+ const length = writeBytes(text, wtf8);
127
+ const bits = length * 8;
128
+ const total = Math.ceil((length + 9) / 64) * 64;
129
+ const data = new Uint8Array(total);
130
+ writeBytes(text, wtf8, data);
131
+ data[length] = 128;
132
+ const view = new DataView(data.buffer);
133
+ view.setUint32(total - 8, Math.floor(bits / 4294967296));
134
+ view.setUint32(total - 4, bits >>> 0);
135
+ const h = [
136
+ 1779033703,
137
+ 3144134277,
138
+ 1013904242,
139
+ 2773480762,
140
+ 1359893119,
141
+ 2600822924,
142
+ 528734635,
143
+ 1541459225
144
+ ];
145
+ const w = /* @__PURE__ */ new Uint32Array(64);
146
+ const rotr = (x, n) => x >>> n | x << 32 - n;
147
+ for (let off = 0; off < total; off += 64) {
148
+ for (let i = 0; i < 16; i++) w[i] = view.getUint32(off + 4 * i);
149
+ for (let i = 16; i < 64; i++) {
150
+ const a = w[i - 15];
151
+ const b = w[i - 2];
152
+ const s0 = rotr(a, 7) ^ rotr(a, 18) ^ a >>> 3;
153
+ const s1 = rotr(b, 17) ^ rotr(b, 19) ^ b >>> 10;
154
+ w[i] = w[i - 16] + s0 + w[i - 7] + s1 >>> 0;
155
+ }
156
+ let [a, b, c, d, e, f, g, k] = h;
157
+ for (let i = 0; i < 64; i++) {
158
+ const s1 = rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25);
159
+ const ch = e & f ^ ~e & g;
160
+ const t1 = k + s1 + ch + K[i] + w[i] >>> 0;
161
+ const t2 = (rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22)) + (a & b ^ a & c ^ b & c) >>> 0;
162
+ k = g;
163
+ g = f;
164
+ f = e;
165
+ e = d + t1 >>> 0;
166
+ d = c;
167
+ c = b;
168
+ b = a;
169
+ a = t1 + t2 >>> 0;
170
+ }
171
+ h[0] = h[0] + a >>> 0;
172
+ h[1] = h[1] + b >>> 0;
173
+ h[2] = h[2] + c >>> 0;
174
+ h[3] = h[3] + d >>> 0;
175
+ h[4] = h[4] + e >>> 0;
176
+ h[5] = h[5] + f >>> 0;
177
+ h[6] = h[6] + g >>> 0;
178
+ h[7] = h[7] + k >>> 0;
179
+ }
180
+ return h.map((x) => x.toString(16).padStart(8, "0")).join("");
181
+ }
182
+ /**
183
+ * This function gives the canonical form of a value. The default form is RFC 8785 (JCS):
184
+ *
185
+ * - The keys of each object are in the order of their UTF-16 code units, with no whitespace.
186
+ * - The numbers and the strings have the form of `JSON.stringify`, which is the form of RFC 8785.
187
+ * - A key with the value `undefined` is not in the form. An `undefined` in an array, or as the value, becomes `null`.
188
+ * - An object with a method `toJSON`, for example a `Date`, gives the form of the result of that method.
189
+ * - A function, a symbol and a cycle cause a `TypeError`.
190
+ *
191
+ * `canonicalJson(JSON.parse(canonicalJson(v)))` is equal to `canonicalJson(v)`.
192
+ */
193
+ function canonicalJson(value, options) {
194
+ const form = options?.form ?? "jcs";
195
+ const bigint = options?.bigint ?? "error";
196
+ if (form !== "jcs" && form !== "json") throw new RangeError(`canonicalJson: form is "jcs" or "json", not ${String(form)}.`);
197
+ if (bigint !== "error" && bigint !== "suffix") throw new RangeError(`canonicalJson: bigint is "error" or "suffix", not ${String(bigint)}.`);
198
+ const jcs = form === "jcs";
199
+ const open = /* @__PURE__ */ new Set();
200
+ const text = (s) => {
201
+ if (jcs && !s.isWellFormed()) throw new RangeError(`canonicalJson: the string ${JSON.stringify(s)} has a lone surrogate, which RFC 8785 does not allow.`);
202
+ return JSON.stringify(s);
203
+ };
204
+ const write = (v, key) => {
205
+ if (v !== null && typeof v === "object" && typeof v.toJSON === "function") v = v.toJSON(key);
206
+ if (v === void 0 || v === null) return "null";
207
+ switch (typeof v) {
208
+ case "boolean": return v ? "true" : "false";
209
+ case "number":
210
+ if (Number.isFinite(v)) return JSON.stringify(v);
211
+ if (jcs) throw new RangeError(`canonicalJson: ${String(v)} is not a JSON number.`);
212
+ return "null";
213
+ case "string": return text(v);
214
+ case "bigint":
215
+ if (bigint === "suffix") return `${v}n`;
216
+ throw new TypeError(`canonicalJson: the bigint ${v}n has no JSON form. Use the option bigint: "suffix" for a key.`);
217
+ case "object": break;
218
+ default: throw new TypeError(`canonicalJson: a ${typeof v} has no JSON form.`);
219
+ }
220
+ const o = v;
221
+ if (open.has(o)) throw new TypeError("canonicalJson: the value has a cycle.");
222
+ open.add(o);
223
+ let out;
224
+ if (Array.isArray(o)) out = `[${o.map((item, i) => write(item, String(i))).join(",")}]`;
225
+ else {
226
+ const r = o;
227
+ out = `{${Object.keys(r).filter((k) => r[k] !== void 0).sort().map((k) => `${text(k)}:${write(r[k], k)}`).join(",")}}`;
228
+ }
229
+ open.delete(o);
230
+ return out;
231
+ };
232
+ return write(value, "");
233
+ }
234
+ /** This function gives the content hash of a value: `sha256Hex(canonicalJson(value, options))`. */
235
+ function canonicalHash(value, options) {
236
+ return sha256Hex(canonicalJson(value, options));
237
+ }
238
+ export { canonicalHash, canonicalJson, sha256Hex };
239
+
240
+ //# sourceMappingURL=hash.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hash.js","names":[],"sources":["../src/hash.ts"],"sourcesContent":["/**\n * The content hash of a document: SHA-256 of a string, and a canonical JSON form of a value.\n *\n * The two functions use no API of Node or of the browser, so a hash is the same on each platform.\n * `canonicalHash(value)` is `sha256Hex(canonicalJson(value))`: equal values give equal hashes, also when their keys have another order.\n */\n\n/** The round constants of SHA-256. */\nconst K: readonly number[] = [\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe,\n 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,\n 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b,\n 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,\n];\n\n/** The options of `sha256Hex`. */\nexport interface Sha256Options {\n /**\n * The bytes that the hash reads, as in `fnv1a32`:\n *\n * - `\"utf8\"` (the default): the UTF-8 bytes. A lone surrogate becomes the bytes of U+FFFD, as `TextEncoder` writes them.\n * - `\"wtf8\"`: the UTF-8 bytes of each code point. A lone surrogate becomes its own 3 bytes (WTF-8).\n *\n * For a string without a lone surrogate, the two inputs give the same hash.\n */\n readonly input?: \"utf8\" | \"wtf8\";\n}\n\n/**\n * This function writes the bytes of a string into `out` and gives the count of the bytes. With no `out`, it only counts.\n * It reads the UTF-16 code units, so it makes no string for each character.\n */\nfunction writeBytes(text: string, wtf8: boolean, out?: Uint8Array): number {\n let n = 0;\n for (let i = 0; i < text.length; i++) {\n let c = text.charCodeAt(i);\n if (c >= 0xd800 && c < 0xe000) {\n const low = i + 1 < text.length ? text.charCodeAt(i + 1) : 0;\n if (c < 0xdc00 && low >= 0xdc00 && low < 0xe000) {\n c = 0x10000 + ((c - 0xd800) << 10) + (low - 0xdc00);\n i++;\n } else if (!wtf8) c = 0xfffd;\n }\n if (c < 0x80) {\n if (out !== undefined) out[n] = c;\n n += 1;\n } else if (c < 0x800) {\n if (out !== undefined) {\n out[n] = 0xc0 | (c >> 6);\n out[n + 1] = 0x80 | (c & 63);\n }\n n += 2;\n } else if (c < 0x10000) {\n if (out !== undefined) {\n out[n] = 0xe0 | (c >> 12);\n out[n + 1] = 0x80 | ((c >> 6) & 63);\n out[n + 2] = 0x80 | (c & 63);\n }\n n += 3;\n } else {\n if (out !== undefined) {\n out[n] = 0xf0 | (c >> 18);\n out[n + 1] = 0x80 | ((c >> 12) & 63);\n out[n + 2] = 0x80 | ((c >> 6) & 63);\n out[n + 3] = 0x80 | (c & 63);\n }\n n += 4;\n }\n }\n return n;\n}\n\n/**\n * This function gives the SHA-256 digest of the bytes of a string, as 64 lowercase hex characters.\n * The option `input` selects the bytes of a lone surrogate. It is not for passwords: it has no salt and no cost.\n */\nexport function sha256Hex(text: string, options?: Sha256Options): string {\n const input = options?.input ?? \"utf8\";\n if (input !== \"utf8\" && input !== \"wtf8\") throw new RangeError(`sha256Hex: input is \"utf8\" or \"wtf8\", not ${String(input)}.`);\n const wtf8 = input === \"wtf8\";\n // The bytes go straight into the padded buffer, so the digest makes one array, not a list of the bytes and a copy.\n const length = writeBytes(text, wtf8);\n const bits = length * 8;\n const total = Math.ceil((length + 9) / 64) * 64;\n const data = new Uint8Array(total);\n writeBytes(text, wtf8, data);\n data[length] = 0x80;\n const view = new DataView(data.buffer);\n view.setUint32(total - 8, Math.floor(bits / 0x100000000));\n view.setUint32(total - 4, bits >>> 0);\n const h = [0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19];\n const w = new Uint32Array(64);\n const rotr = (x: number, n: number): number => (x >>> n) | (x << (32 - n));\n for (let off = 0; off < total; off += 64) {\n for (let i = 0; i < 16; i++) w[i] = view.getUint32(off + 4 * i);\n for (let i = 16; i < 64; i++) {\n const a = w[i - 15]!;\n const b = w[i - 2]!;\n const s0 = rotr(a, 7) ^ rotr(a, 18) ^ (a >>> 3);\n const s1 = rotr(b, 17) ^ rotr(b, 19) ^ (b >>> 10);\n w[i] = (w[i - 16]! + s0 + w[i - 7]! + s1) >>> 0;\n }\n let [a, b, c, d, e, f, g, k] = h as [number, number, number, number, number, number, number, number];\n for (let i = 0; i < 64; i++) {\n const s1 = rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25);\n const ch = (e & f) ^ (~e & g);\n const t1 = (k + s1 + ch + K[i]! + w[i]!) >>> 0;\n const s0 = rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22);\n const maj = (a & b) ^ (a & c) ^ (b & c);\n const t2 = (s0 + maj) >>> 0;\n k = g;\n g = f;\n f = e;\n e = (d + t1) >>> 0;\n d = c;\n c = b;\n b = a;\n a = (t1 + t2) >>> 0;\n }\n h[0] = (h[0]! + a) >>> 0;\n h[1] = (h[1]! + b) >>> 0;\n h[2] = (h[2]! + c) >>> 0;\n h[3] = (h[3]! + d) >>> 0;\n h[4] = (h[4]! + e) >>> 0;\n h[5] = (h[5]! + f) >>> 0;\n h[6] = (h[6]! + g) >>> 0;\n h[7] = (h[7]! + k) >>> 0;\n }\n return h.map((x) => x.toString(16).padStart(8, \"0\")).join(\"\");\n}\n\n/** The options of `canonicalJson` and `canonicalHash`. */\nexport interface CanonicalOptions {\n /**\n * The form of the values that JSON does not have:\n *\n * - `\"jcs\"` (the default): RFC 8785. `NaN`, an infinite number and a string with a lone surrogate cause a `RangeError`.\n * - `\"json\"`: the form of `JSON.stringify`. `NaN` and an infinite number become `null`, and a lone surrogate becomes an escape.\n */\n readonly form?: \"jcs\" | \"json\";\n /**\n * The form of a `bigint`. `\"error\"` (the default) causes a `TypeError`, as `JSON.stringify` does.\n * `\"suffix\"` writes the digits and the letter `n`, for example `12n`. This text is not JSON, so use it only for a key.\n */\n readonly bigint?: \"error\" | \"suffix\";\n}\n\n/**\n * This function gives the canonical form of a value. The default form is RFC 8785 (JCS):\n *\n * - The keys of each object are in the order of their UTF-16 code units, with no whitespace.\n * - The numbers and the strings have the form of `JSON.stringify`, which is the form of RFC 8785.\n * - A key with the value `undefined` is not in the form. An `undefined` in an array, or as the value, becomes `null`.\n * - An object with a method `toJSON`, for example a `Date`, gives the form of the result of that method.\n * - A function, a symbol and a cycle cause a `TypeError`.\n *\n * `canonicalJson(JSON.parse(canonicalJson(v)))` is equal to `canonicalJson(v)`.\n */\nexport function canonicalJson(value: unknown, options?: CanonicalOptions): string {\n const form = options?.form ?? \"jcs\";\n const bigint = options?.bigint ?? \"error\";\n if (form !== \"jcs\" && form !== \"json\") throw new RangeError(`canonicalJson: form is \"jcs\" or \"json\", not ${String(form)}.`);\n if (bigint !== \"error\" && bigint !== \"suffix\") throw new RangeError(`canonicalJson: bigint is \"error\" or \"suffix\", not ${String(bigint)}.`);\n const jcs = form === \"jcs\";\n const open = new Set<object>();\n const text = (s: string): string => {\n if (jcs && !(s as string & { isWellFormed(): boolean }).isWellFormed()) throw new RangeError(`canonicalJson: the string ${JSON.stringify(s)} has a lone surrogate, which RFC 8785 does not allow.`);\n return JSON.stringify(s);\n };\n const write = (v: unknown, key: string): string => {\n if (v !== null && typeof v === \"object\" && typeof (v as { toJSON?: unknown }).toJSON === \"function\") v = (v as { toJSON(key: string): unknown }).toJSON(key);\n if (v === undefined || v === null) return \"null\";\n switch (typeof v) {\n case \"boolean\":\n return v ? \"true\" : \"false\";\n case \"number\":\n if (Number.isFinite(v)) return JSON.stringify(v);\n if (jcs) throw new RangeError(`canonicalJson: ${String(v)} is not a JSON number.`);\n return \"null\";\n case \"string\":\n return text(v);\n case \"bigint\":\n if (bigint === \"suffix\") return `${v}n`;\n throw new TypeError(`canonicalJson: the bigint ${v}n has no JSON form. Use the option bigint: \"suffix\" for a key.`);\n case \"object\":\n break;\n default:\n throw new TypeError(`canonicalJson: a ${typeof v} has no JSON form.`);\n }\n const o = v as object;\n if (open.has(o)) throw new TypeError(\"canonicalJson: the value has a cycle.\");\n open.add(o);\n let out: string;\n if (Array.isArray(o)) out = `[${o.map((item: unknown, i) => write(item, String(i))).join(\",\")}]`;\n else {\n const r = o as Record<string, unknown>;\n const keys = Object.keys(r).filter((k) => r[k] !== undefined).sort();\n out = `{${keys.map((k) => `${text(k)}:${write(r[k], k)}`).join(\",\")}}`;\n }\n open.delete(o);\n return out;\n };\n return write(value, \"\");\n}\n\n/** This function gives the content hash of a value: `sha256Hex(canonicalJson(value, options))`. */\nexport function canonicalHash(value: unknown, options?: CanonicalOptions): string {\n return sha256Hex(canonicalJson(value, options));\n}\n"],"mappings":";;;;;;;;AAQA,MAAM,IAAuB;CAC3B;CAAY;CAAY;CAAY;CAAY;CAAY;CAAY;CAAY;CAAY;CAAY;CAAY;CAAY;CAAY;CAAY;CAC5J;CAAY;CAAY;CAAY;CAAY;CAAY;CAAY;CAAY;CAAY;CAAY;CAAY;CAAY;CAAY;CAAY;CAC5J;CAAY;CAAY;CAAY;CAAY;CAAY;CAAY;CAAY;CAAY;CAAY;CAAY;CAAY;CAAY;CAAY;CAC5J;CAAY;CAAY;CAAY;CAAY;CAAY;CAAY;CAAY;CAAY;CAAY;CAAY;CAAY;CAAY;CAAY;CAC5J;CAAY;CAAY;CAAY;CAAY;CAAY;CAAY;CAAY;AACtF;;;;;AAmBA,SAAS,WAAW,MAAc,MAAe,KAA0B;CACzE,IAAI,IAAI;CACR,KAAK,IAAI,IAAI,GAAG,IAAI,KAAK,QAAQ,KAAK;EACpC,IAAI,IAAI,KAAK,WAAW,CAAC;EACzB,IAAI,KAAK,SAAU,IAAI,OAAQ;GAC7B,MAAM,MAAM,IAAI,IAAI,KAAK,SAAS,KAAK,WAAW,IAAI,CAAC,IAAI;G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I,OAAO,SAAS,CAAC,GAAG,OAAO,KAAK,UAAU,CAAC;IAC/C,IAAI,KAAK,MAAM,IAAI,WAAW,kBAAkB,OAAO,CAAC,EAAE,uBAAuB;IACjF,OAAO;GACT,KAAK,UACH,OAAO,KAAK,CAAC;GACf,KAAK;IACH,IAAI,WAAW,UAAU,OAAO,GAAG,EAAE;IACrC,MAAM,IAAI,UAAU,6BAA6B,EAAE,+DAA+D;GACpH,KAAK,UACH;GACF,SACE,MAAM,IAAI,UAAU,oBAAoB,OAAO,EAAE,mBAAmB;EACxE;EACA,MAAM,IAAI;EACV,IAAI,KAAK,IAAI,CAAC,GAAG,MAAM,IAAI,UAAU,uCAAuC;EAC5E,KAAK,IAAI,CAAC;EACV,IAAI;EACJ,IAAI,MAAM,QAAQ,CAAC,GAAG,MAAM,IAAI,EAAE,KAAK,MAAe,MAAM,MAAM,MAAM,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC,KAAK,GAAG,EAAE;OACzF;GACH,MAAM,IAAI;GAEV,MAAM,IADO,OAAO,KAAK,CAAC,CAAC,CAAC,QAAQ,MAAM,EAAE,OAAO,KAAA,CAAS,CAAC,CAAC,KACjD,CAAC,CAAC,KAAK,MAAM,GAAG,KAAK,CAAC,EAAE,GAAG,MAAM,EAAE,IAAI,CAAC,GAAG,CAAC,CAAC,KAAK,GAAG,EAAE;EACtE;EACA,KAAK,OAAO,CAAC;EACb,OAAO;CACT;CACA,OAAO,MAAM,OAAO,EAAE;AACxB;;AAGA,SAAgB,cAAc,OAAgB,SAAoC;CAChF,OAAO,UAAU,cAAc,OAAO,OAAO,CAAC;AAChD"}
package/build/index.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { Random, Source, deriveSeed, fnv1a32, mulberry32, random, randomOf, seedOf, seedsFrom, stablePick } from "./random.js";
2
2
  import { DistributionSpec, Param, dependsOnLibm, sampler } from "./distributions.js";
3
+ import { CanonicalOptions, Sha256Options, canonicalHash, canonicalJson, sha256Hex } from "./hash.js";
3
4
  import { DIAGRAM_BOX_AREA, GIT_BLOB_BYTES, RECORDED_TABLES, RecordedTable, recordedSpec } from "./recorded.js";
4
- export { DIAGRAM_BOX_AREA, type DistributionSpec, GIT_BLOB_BYTES, type Param, RECORDED_TABLES, type Random, type RecordedTable, type Source, dependsOnLibm, deriveSeed, fnv1a32, mulberry32, random, randomOf, recordedSpec, sampler, seedOf, seedsFrom, stablePick };
5
+ export { type CanonicalOptions, DIAGRAM_BOX_AREA, type DistributionSpec, GIT_BLOB_BYTES, type Param, RECORDED_TABLES, type Random, type RecordedTable, type Sha256Options, type Source, canonicalHash, canonicalJson, dependsOnLibm, deriveSeed, fnv1a32, mulberry32, random, randomOf, recordedSpec, sampler, seedOf, seedsFrom, sha256Hex, stablePick };
package/build/index.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { dependsOnLibm, sampler } from "./distributions.js";
2
+ import { canonicalHash, canonicalJson, sha256Hex } from "./hash.js";
2
3
  import { DIAGRAM_BOX_AREA, GIT_BLOB_BYTES, RECORDED_TABLES, recordedSpec } from "./recorded.js";
3
4
  import { deriveSeed, fnv1a32, mulberry32, random, randomOf, seedOf, seedsFrom, stablePick } from "./random.js";
4
- export { DIAGRAM_BOX_AREA, GIT_BLOB_BYTES, RECORDED_TABLES, dependsOnLibm, deriveSeed, fnv1a32, mulberry32, random, randomOf, recordedSpec, sampler, seedOf, seedsFrom, stablePick };
5
+ export { DIAGRAM_BOX_AREA, GIT_BLOB_BYTES, RECORDED_TABLES, canonicalHash, canonicalJson, dependsOnLibm, deriveSeed, fnv1a32, mulberry32, random, randomOf, recordedSpec, sampler, seedOf, seedsFrom, sha256Hex, stablePick };
package/build/random.d.ts CHANGED
@@ -66,8 +66,12 @@ export declare function random(seed: number | string, source?: (seed: number) =>
66
66
  /** A generator with draws, from a source that you give. `fork` uses `source` for the new streams. */
67
67
  export declare function randomOf(next: Source, seed: number, source?: (seed: number) => Source): Random;
68
68
  /**
69
- * The seeds of a run: the seed in `given` (the text of an environment variable, for example
69
+ * The seeds of a run: the seeds in `given` (the text of an environment variable, for example
70
70
  * `process.env.SEED`), else the default seeds. An empty text gives the defaults.
71
+ *
72
+ * The text is one seed (`17`) or a list of seeds and ranges with commas (`1,3,9-11` gives 1, 3, 9, 10
73
+ * and 11), in the order of the list. A range has two whole numbers, the low one first. An empty part, a
74
+ * part that is not an integer and a range with the low end last are each a `RangeError`.
71
75
  */
72
76
  export declare function seedsFrom(given: string | undefined, defaults: readonly number[]): number[];
73
77
  //# sourceMappingURL=random.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"random.d.ts","names":[],"sources":["../src/random.ts"],"mappings":";;;;;;;;YASY;;wBAGI,WAAW,eAAe;;;;;;;;;;wBAsB1B,QAAQ,cAAc;WAAqB;;;wBAiC3C,OAAO;;wBAOP,WAAW,cAAc;;;;;;;;;;wBAazB,WAAW,GAAG,cAAc,gBAAgB,KAAK,SAAQ,MAAM,eAAwB;iBAetF;;WAEN;;EAET;;EAEA,IAAI,aAAa;;EAEjB,MAAM;;EAEN,MAAM,aAAa;;EAEnB,OAAO;;EAEP,KAAK,GAAG,gBAAgB,MAAM;;EAE9B,SAAS;;EAET,QAAQ,GAAG,gBAAgB,MAAM;;EAEjC,OAAO,GAAG,gBAAgB,KAAK,YAAY;;EAE3C,OAAO,eAAe;;EAEtB,KAAK,gBAAgB;;;wBAQP,OAAO,uBAAuB,UAAS,iBAAiB,SAAsB;;wBAM9E,SAAS,MAAM,QAAQ,cAAc,UAAS,iBAAiB,SAAsB;;;;;wBAuErF,UAAU,2BAA2B"}
1
+ {"version":3,"file":"random.d.ts","names":[],"sources":["../src/random.ts"],"mappings":";;;;;;;;YASY;;wBAGI,WAAW,eAAe;;;;;;;;;;wBAsB1B,QAAQ,cAAc;WAAqB;;;wBAiC3C,OAAO;;wBAOP,WAAW,cAAc;;;;;;;;;;wBAazB,WAAW,GAAG,cAAc,gBAAgB,KAAK,SAAQ,MAAM,eAAwB;iBAetF;;WAEN;;EAET;;EAEA,IAAI,aAAa;;EAEjB,MAAM;;EAEN,MAAM,aAAa;;EAEnB,OAAO;;EAEP,KAAK,GAAG,gBAAgB,MAAM;;EAE9B,SAAS;;EAET,QAAQ,GAAG,gBAAgB,MAAM;;EAEjC,OAAO,GAAG,gBAAgB,KAAK,YAAY;;EAE3C,OAAO,eAAe;;EAEtB,KAAK,gBAAgB;;;wBAQP,OAAO,uBAAuB,UAAS,iBAAiB,SAAsB;;wBAM9E,SAAS,MAAM,QAAQ,cAAc,UAAS,iBAAiB,SAAsB;;;;;;;;;wBA8ErF,UAAU,2BAA2B"}
package/build/random.js CHANGED
@@ -162,15 +162,30 @@ function randomOf(next, seed, source = mulberry32) {
162
162
  }
163
163
  };
164
164
  }
165
+ /** The largest count of seeds that one range gives. A larger range is an error, not a long run. */
166
+ const MAX_RANGE = 1e6;
165
167
  /**
166
- * The seeds of a run: the seed in `given` (the text of an environment variable, for example
168
+ * The seeds of a run: the seeds in `given` (the text of an environment variable, for example
167
169
  * `process.env.SEED`), else the default seeds. An empty text gives the defaults.
170
+ *
171
+ * The text is one seed (`17`) or a list of seeds and ranges with commas (`1,3,9-11` gives 1, 3, 9, 10
172
+ * and 11), in the order of the list. A range has two whole numbers, the low one first. An empty part, a
173
+ * part that is not an integer and a range with the low end last are each a `RangeError`.
168
174
  */
169
175
  function seedsFrom(given, defaults) {
170
176
  if (given === void 0 || given.trim() === "") return [...defaults];
171
- const seed = Number(given);
172
- if (!Number.isSafeInteger(seed)) throw new RangeError(`seedsFrom: a seed is an integer, not ${given}.`);
173
- return [seed];
177
+ return given.split(",").flatMap((raw) => {
178
+ const part = raw.trim();
179
+ const range = /^(\d+)\s*-\s*(\d+)$/u.exec(part);
180
+ if (range !== null) {
181
+ const [low, high] = [Number(range[1]), Number(range[2])];
182
+ if (!Number.isSafeInteger(high) || high < low || high - low >= MAX_RANGE) throw new RangeError(`seedsFrom: the range ${part} is not low-high with at most ${MAX_RANGE} seeds.`);
183
+ return Array.from({ length: high - low + 1 }, (_, i) => low + i);
184
+ }
185
+ const seed = part === "" ? NaN : Number(part);
186
+ if (!Number.isSafeInteger(seed)) throw new RangeError(`seedsFrom: a seed is an integer, not ${part === "" ? "an empty part" : part}.`);
187
+ return [seed];
188
+ });
174
189
  }
175
190
  export { deriveSeed, fnv1a32, mulberry32, random, randomOf, seedOf, seedsFrom, stablePick };
176
191
 
@@ -1 +1 @@
1
- {"version":3,"file":"random.js","names":[],"sources":["../src/random.ts"],"sourcesContent":["/**\n * A pseudo-random number generator with a seed, and the draws that tests and benchmarks make from it.\n *\n * The generator is mulberry32. It is fast, it has 32 bits of state and it gives the same sequence for\n * the same seed on each platform. It is not for cryptography. Each repository that copied mulberry32\n * gets the same numbers from `random(seed).next`, so a move to this package keeps the records equal.\n */\n\n/** A source of uniform numbers from 0 (included) to 1 (not included). */\nexport type Source = () => number;\n\n/** The generator mulberry32. The seed is read as a 32-bit unsigned integer. */\nexport function mulberry32(seed: number): Source {\n let state = seed >>> 0;\n return () => {\n state = (state + 0x6d2b79f5) >>> 0;\n let t = state;\n t = Math.imul(t ^ (t >>> 15), t | 1);\n t ^= t + Math.imul(t ^ (t >>> 7), t | 61);\n return ((t ^ (t >>> 14)) >>> 0) / 4294967296;\n };\n}\n\nconst UTF8 = new TextEncoder();\n\n/**\n * The FNV-1a hash of 32 bits of a string. The option `input` selects the units that the hash reads:\n *\n * - `\"utf8\"` (the default): the UTF-8 bytes from `TextEncoder`. A lone surrogate becomes the bytes of U+FFFD.\n * - `\"utf16\"`: the UTF-16 code units of the string, one unit for each step, from `charCodeAt`.\n * - `\"wtf8\"`: the UTF-8 bytes of each code point. A lone surrogate becomes its own 3 bytes (WTF-8).\n *\n * For a string without a lone surrogate, `\"utf8\"` and `\"wtf8\"` give the same hash.\n */\nexport function fnv1a32(text: string, options?: { readonly input?: \"utf8\" | \"utf16\" | \"wtf8\" }): number {\n const input = options?.input ?? \"utf8\";\n let h = 0x811c9dc5;\n if (input === \"utf16\") {\n for (let i = 0; i < text.length; i++) h = Math.imul(h ^ text.charCodeAt(i), 0x01000193);\n return h >>> 0;\n }\n if (input === \"wtf8\") {\n for (const ch of text) {\n const c = ch.codePointAt(0) as number;\n if (c < 0x80) h = Math.imul(h ^ c, 0x01000193);\n else if (c < 0x800) {\n h = Math.imul(h ^ (0xc0 | (c >> 6)), 0x01000193);\n h = Math.imul(h ^ (0x80 | (c & 63)), 0x01000193);\n } else if (c < 0x10000) {\n h = Math.imul(h ^ (0xe0 | (c >> 12)), 0x01000193);\n h = Math.imul(h ^ (0x80 | ((c >> 6) & 63)), 0x01000193);\n h = Math.imul(h ^ (0x80 | (c & 63)), 0x01000193);\n } else {\n h = Math.imul(h ^ (0xf0 | (c >> 18)), 0x01000193);\n h = Math.imul(h ^ (0x80 | ((c >> 12) & 63)), 0x01000193);\n h = Math.imul(h ^ (0x80 | ((c >> 6) & 63)), 0x01000193);\n h = Math.imul(h ^ (0x80 | (c & 63)), 0x01000193);\n }\n }\n return h >>> 0;\n }\n if (input !== \"utf8\") throw new RangeError(`fnv1a32: input is \"utf8\", \"utf16\" or \"wtf8\", not ${String(input)}.`);\n for (const b of UTF8.encode(text)) h = Math.imul(h ^ b, 0x01000193) >>> 0;\n return h;\n}\n\n/** The 32-bit seed of a number (its low 32 bits, unsigned) or of a string (its FNV-1a hash). */\nexport function seedOf(seed: number | string): number {\n if (typeof seed === \"string\") return fnv1a32(seed);\n if (!Number.isFinite(seed)) throw new RangeError(`seedOf: a seed is a finite number or a string, not ${seed}.`);\n return seed >>> 0;\n}\n\n/** The seed of the stream with the name `label` under `seed`: the hash of `\"<seed>:<label>\"`. */\nexport function deriveSeed(seed: number, label: string): number {\n return fnv1a32(`${seed}:${label}`);\n}\n\n/**\n * One item of a list, chosen by highest random weight: each key has a weight from `seed`, and the largest weight wins.\n *\n * - The order of the list does not change the choice. The smaller key wins a tie of weights.\n * - When a list gains an item, only the draws that the new item wins change. For `n` items, the share of those draws is approximately `1 / (n + 1)`.\n * - When a list loses an item, only the draws of that item change.\n *\n * The function reads one hash for each item, so a choice costs O(n). The list is not empty, and each key occurs once.\n */\nexport function stablePick<T>(seed: number, items: readonly T[], keyOf: (item: T) => string = String): T {\n if (items.length === 0) throw new RangeError(\"stablePick: the list is empty.\");\n const start = seedOf(seed);\n const seen = new Set<string>();\n let best: { item: T; key: string; weight: number } | undefined;\n for (const item of items) {\n const key = keyOf(item);\n if (seen.has(key)) throw new RangeError(`stablePick: the key ${JSON.stringify(key)} occurs twice.`);\n seen.add(key);\n const weight = mulberry32(deriveSeed(start, key))();\n if (best === undefined || weight > best.weight || (weight === best.weight && key < best.key)) best = { item, key, weight };\n }\n return (best as { item: T }).item;\n}\n\nexport interface Random {\n /** The 32-bit seed that the generator started with. Write it in each failure message, so a run can replay. */\n readonly seed: number;\n /** A uniform number from 0 (included) to 1 (not included). */\n next(): number;\n /** A uniform integer from `min` to `max`, both included. */\n int(min: number, max: number): number;\n /** A uniform integer from 0 (included) to `n` (not included). */\n below(n: number): number;\n /** A uniform number from `min` (included) to `max` (not included). */\n range(min: number, max: number): number;\n /** `true` with the probability `p`. */\n chance(p: number): boolean;\n /** One item of a list that is not empty, each with the same probability. */\n pick<T>(items: readonly T[]): T;\n /** The index of a weight, with a probability in proportion to the weight. One draw. */\n weighted(weights: readonly number[]): number;\n /** A new list with the items in a uniform random order (Fisher–Yates, from the end). */\n shuffle<T>(items: readonly T[]): T[];\n /** `k` different items of a list, in the order of the draw (a partial Fisher–Yates). */\n sample<T>(items: readonly T[], k: number): T[];\n /** A normal sample (Box–Muller, two draws). */\n normal(mean?: number, sd?: number): number;\n /** An independent generator for the part of the work with the name `label`. The same labels give the same streams. */\n fork(label: string): Random;\n}\n\nfunction wholeOrThrow(name: string, value: number): void {\n if (!Number.isSafeInteger(value)) throw new RangeError(`${name}: ${value} is not a safe integer.`);\n}\n\n/** A generator with draws, from a seed. The default source is mulberry32. */\nexport function random(seed: number | string, source: (seed: number) => Source = mulberry32): Random {\n const start = seedOf(seed);\n return randomOf(source(start), start, source);\n}\n\n/** A generator with draws, from a source that you give. `fork` uses `source` for the new streams. */\nexport function randomOf(next: Source, seed: number, source: (seed: number) => Source = mulberry32): Random {\n const below = (n: number): number => {\n wholeOrThrow(\"below\", n);\n if (n < 1) throw new RangeError(`below: n is 1 or more, not ${n}.`);\n return Math.floor(next() * n);\n };\n return {\n seed,\n next,\n int(min, max) {\n wholeOrThrow(\"int\", min);\n wholeOrThrow(\"int\", max);\n if (min > max) throw new RangeError(`int: min ${min} is more than max ${max}.`);\n return min + Math.floor(next() * (max - min + 1));\n },\n below,\n range: (min, max) => min + next() * (max - min),\n chance: (p) => next() < p,\n pick(items) {\n if (items.length === 0) throw new RangeError(\"pick: the list is empty.\");\n return items[below(items.length)] as (typeof items)[number];\n },\n weighted(weights) {\n let total = 0;\n for (const w of weights) {\n if (!(Number.isFinite(w) && w >= 0)) throw new RangeError(`weighted: each weight is finite and 0 or more, not ${w}.`);\n total += w;\n }\n if (!(total > 0)) throw new RangeError(\"weighted: the sum of the weights is 0.\");\n let left = next() * total;\n for (let i = 0; i < weights.length; i++) {\n left -= weights[i] as number;\n if (left < 0) return i;\n }\n // Rounding can leave a small remainder: give the last index with a weight.\n for (let i = weights.length - 1; ; i--) if ((weights[i] as number) > 0) return i;\n },\n shuffle(items) {\n const out = [...items];\n for (let i = out.length - 1; i > 0; i--) {\n const j = below(i + 1);\n [out[i], out[j]] = [out[j] as (typeof out)[number], out[i] as (typeof out)[number]];\n }\n return out;\n },\n sample(items, k) {\n wholeOrThrow(\"sample\", k);\n if (k < 0 || k > items.length) throw new RangeError(`sample: k is from 0 to ${items.length}, not ${k}.`);\n const out = [...items];\n for (let i = 0; i < k; i++) {\n const j = i + below(out.length - i);\n [out[i], out[j]] = [out[j] as (typeof out)[number], out[i] as (typeof out)[number]];\n }\n return out.slice(0, k);\n },\n normal(mean = 0, sd = 1) {\n const u1 = Math.max(next(), 1e-12);\n const u2 = next();\n return mean + sd * Math.sqrt(-2 * Math.log(u1)) * Math.cos(2 * Math.PI * u2);\n },\n fork(label) {\n const child = deriveSeed(seed, label);\n return randomOf(source(child), child, source);\n },\n };\n}\n\n/**\n * The seeds of a run: the seed in `given` (the text of an environment variable, for example\n * `process.env.SEED`), else the default seeds. An empty text gives the defaults.\n */\nexport function seedsFrom(given: string | undefined, defaults: readonly number[]): number[] {\n if (given === undefined || given.trim() === \"\") return [...defaults];\n const seed = Number(given);\n if (!Number.isSafeInteger(seed)) throw new RangeError(`seedsFrom: a seed is an integer, not ${given}.`);\n return [seed];\n}\n"],"mappings":";;AAYA,SAAgB,WAAW,MAAsB;CAC/C,IAAI,QAAQ,SAAS;CACrB,aAAa;EACX,QAAS,QAAQ,eAAgB;EACjC,IAAI,IAAI;EACR,IAAI,KAAK,KAAK,IAAK,MAAM,IAAK,IAAI,CAAC;EACnC,KAAK,IAAI,KAAK,KAAK,IAAK,MAAM,GAAI,IAAI,EAAE;EACxC,SAAS,IAAK,MAAM,QAAS,KAAK;CACpC;AACF;AAEA,MAAM,OAAO,IAAI,YAAY;;;;;;;;;;AAW7B,SAAgB,QAAQ,MAAc,SAAkE;CACtG,MAAM,QAAQ,SAAS,SAAS;CAChC,IAAI,IAAI;CACR,IAAI,UAAU,SAAS;EACrB,KAAK,IAAI,IAAI,GAAG,IAAI,KAAK,QAAQ,KAAK,IAAI,KAAK,KAAK,IAAI,KAAK,WAAW,CAAC,GAAG,QAAU;EACtF,OAAO,MAAM;CACf;CACA,IAAI,UAAU,QAAQ;EACpB,KAAK,MAAM,MAAM,MAAM;GACrB,MAAM,IAAI,GAAG,YAAY,CAAC;GAC1B,IAAI,IAAI,KAAM,IAAI,KAAK,KAAK,IAAI,GAAG,QAAU;QACxC,IAAI,IAAI,MAAO;IAClB,IAAI,KAAK,KAAK,KAAK,MAAQ,KAAK,IAAK,QAAU;IAC/C,IAAI,KAAK,KAAK,KAAK,MAAQ,IAAI,KAAM,QAAU;GACjD,OAAO,IAAI,IAAI,OAAS;IACtB,IAAI,KAAK,KA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V,MAAM,QAAQ,WAAW,MAAM,KAAK;GACpC,OAAO,SAAS,OAAO,KAAK,GAAG,OAAO,MAAM;EAC9C;CACF;AACF;;;;;AAMA,SAAgB,UAAU,OAA2B,UAAuC;CAC1F,IAAI,UAAU,KAAA,KAAa,MAAM,KAAK,MAAM,IAAI,OAAO,CAAC,GAAG,QAAQ;CACnE,MAAM,OAAO,OAAO,KAAK;CACzB,IAAI,CAAC,OAAO,cAAc,IAAI,GAAG,MAAM,IAAI,WAAW,wCAAwC,MAAM,EAAE;CACtG,OAAO,CAAC,IAAI;AACd"}
1
+ {"version":3,"file":"random.js","names":[],"sources":["../src/random.ts"],"sourcesContent":["/**\n * A pseudo-random number generator with a seed, and the draws that tests and benchmarks make from it.\n *\n * The generator is mulberry32. It is fast, it has 32 bits of state and it gives the same sequence for\n * the same seed on each platform. It is not for cryptography. Each repository that copied mulberry32\n * gets the same numbers from `random(seed).next`, so a move to this package keeps the records equal.\n */\n\n/** A source of uniform numbers from 0 (included) to 1 (not included). */\nexport type Source = () => number;\n\n/** The generator mulberry32. The seed is read as a 32-bit unsigned integer. */\nexport function mulberry32(seed: number): Source {\n let state = seed >>> 0;\n return () => {\n state = (state + 0x6d2b79f5) >>> 0;\n let t = state;\n t = Math.imul(t ^ (t >>> 15), t | 1);\n t ^= t + Math.imul(t ^ (t >>> 7), t | 61);\n return ((t ^ (t >>> 14)) >>> 0) / 4294967296;\n };\n}\n\nconst UTF8 = new TextEncoder();\n\n/**\n * The FNV-1a hash of 32 bits of a string. The option `input` selects the units that the hash reads:\n *\n * - `\"utf8\"` (the default): the UTF-8 bytes from `TextEncoder`. A lone surrogate becomes the bytes of U+FFFD.\n * - `\"utf16\"`: the UTF-16 code units of the string, one unit for each step, from `charCodeAt`.\n * - `\"wtf8\"`: the UTF-8 bytes of each code point. A lone surrogate becomes its own 3 bytes (WTF-8).\n *\n * For a string without a lone surrogate, `\"utf8\"` and `\"wtf8\"` give the same hash.\n */\nexport function fnv1a32(text: string, options?: { readonly input?: \"utf8\" | \"utf16\" | \"wtf8\" }): number {\n const input = options?.input ?? \"utf8\";\n let h = 0x811c9dc5;\n if (input === \"utf16\") {\n for (let i = 0; i < text.length; i++) h = Math.imul(h ^ text.charCodeAt(i), 0x01000193);\n return h >>> 0;\n }\n if (input === \"wtf8\") {\n for (const ch of text) {\n const c = ch.codePointAt(0) as number;\n if (c < 0x80) h = Math.imul(h ^ c, 0x01000193);\n else if (c < 0x800) {\n h = Math.imul(h ^ (0xc0 | (c >> 6)), 0x01000193);\n h = Math.imul(h ^ (0x80 | (c & 63)), 0x01000193);\n } else if (c < 0x10000) {\n h = Math.imul(h ^ (0xe0 | (c >> 12)), 0x01000193);\n h = Math.imul(h ^ (0x80 | ((c >> 6) & 63)), 0x01000193);\n h = Math.imul(h ^ (0x80 | (c & 63)), 0x01000193);\n } else {\n h = Math.imul(h ^ (0xf0 | (c >> 18)), 0x01000193);\n h = Math.imul(h ^ (0x80 | ((c >> 12) & 63)), 0x01000193);\n h = Math.imul(h ^ (0x80 | ((c >> 6) & 63)), 0x01000193);\n h = Math.imul(h ^ (0x80 | (c & 63)), 0x01000193);\n }\n }\n return h >>> 0;\n }\n if (input !== \"utf8\") throw new RangeError(`fnv1a32: input is \"utf8\", \"utf16\" or \"wtf8\", not ${String(input)}.`);\n for (const b of UTF8.encode(text)) h = Math.imul(h ^ b, 0x01000193) >>> 0;\n return h;\n}\n\n/** The 32-bit seed of a number (its low 32 bits, unsigned) or of a string (its FNV-1a hash). */\nexport function seedOf(seed: number | string): number {\n if (typeof seed === \"string\") return fnv1a32(seed);\n if (!Number.isFinite(seed)) throw new RangeError(`seedOf: a seed is a finite number or a string, not ${seed}.`);\n return seed >>> 0;\n}\n\n/** The seed of the stream with the name `label` under `seed`: the hash of `\"<seed>:<label>\"`. */\nexport function deriveSeed(seed: number, label: string): number {\n return fnv1a32(`${seed}:${label}`);\n}\n\n/**\n * One item of a list, chosen by highest random weight: each key has a weight from `seed`, and the largest weight wins.\n *\n * - The order of the list does not change the choice. The smaller key wins a tie of weights.\n * - When a list gains an item, only the draws that the new item wins change. For `n` items, the share of those draws is approximately `1 / (n + 1)`.\n * - When a list loses an item, only the draws of that item change.\n *\n * The function reads one hash for each item, so a choice costs O(n). The list is not empty, and each key occurs once.\n */\nexport function stablePick<T>(seed: number, items: readonly T[], keyOf: (item: T) => string = String): T {\n if (items.length === 0) throw new RangeError(\"stablePick: the list is empty.\");\n const start = seedOf(seed);\n const seen = new Set<string>();\n let best: { item: T; key: string; weight: number } | undefined;\n for (const item of items) {\n const key = keyOf(item);\n if (seen.has(key)) throw new RangeError(`stablePick: the key ${JSON.stringify(key)} occurs twice.`);\n seen.add(key);\n const weight = mulberry32(deriveSeed(start, key))();\n if (best === undefined || weight > best.weight || (weight === best.weight && key < best.key)) best = { item, key, weight };\n }\n return (best as { item: T }).item;\n}\n\nexport interface Random {\n /** The 32-bit seed that the generator started with. Write it in each failure message, so a run can replay. */\n readonly seed: number;\n /** A uniform number from 0 (included) to 1 (not included). */\n next(): number;\n /** A uniform integer from `min` to `max`, both included. */\n int(min: number, max: number): number;\n /** A uniform integer from 0 (included) to `n` (not included). */\n below(n: number): number;\n /** A uniform number from `min` (included) to `max` (not included). */\n range(min: number, max: number): number;\n /** `true` with the probability `p`. */\n chance(p: number): boolean;\n /** One item of a list that is not empty, each with the same probability. */\n pick<T>(items: readonly T[]): T;\n /** The index of a weight, with a probability in proportion to the weight. One draw. */\n weighted(weights: readonly number[]): number;\n /** A new list with the items in a uniform random order (Fisher–Yates, from the end). */\n shuffle<T>(items: readonly T[]): T[];\n /** `k` different items of a list, in the order of the draw (a partial Fisher–Yates). */\n sample<T>(items: readonly T[], k: number): T[];\n /** A normal sample (Box–Muller, two draws). */\n normal(mean?: number, sd?: number): number;\n /** An independent generator for the part of the work with the name `label`. The same labels give the same streams. */\n fork(label: string): Random;\n}\n\nfunction wholeOrThrow(name: string, value: number): void {\n if (!Number.isSafeInteger(value)) throw new RangeError(`${name}: ${value} is not a safe integer.`);\n}\n\n/** A generator with draws, from a seed. The default source is mulberry32. */\nexport function random(seed: number | string, source: (seed: number) => Source = mulberry32): Random {\n const start = seedOf(seed);\n return randomOf(source(start), start, source);\n}\n\n/** A generator with draws, from a source that you give. `fork` uses `source` for the new streams. */\nexport function randomOf(next: Source, seed: number, source: (seed: number) => Source = mulberry32): Random {\n const below = (n: number): number => {\n wholeOrThrow(\"below\", n);\n if (n < 1) throw new RangeError(`below: n is 1 or more, not ${n}.`);\n return Math.floor(next() * n);\n };\n return {\n seed,\n next,\n int(min, max) {\n wholeOrThrow(\"int\", min);\n wholeOrThrow(\"int\", max);\n if (min > max) throw new RangeError(`int: min ${min} is more than max ${max}.`);\n return min + Math.floor(next() * (max - min + 1));\n },\n below,\n range: (min, max) => min + next() * (max - min),\n chance: (p) => next() < p,\n pick(items) {\n if (items.length === 0) throw new RangeError(\"pick: the list is empty.\");\n return items[below(items.length)] as (typeof items)[number];\n },\n weighted(weights) {\n let total = 0;\n for (const w of weights) {\n if (!(Number.isFinite(w) && w >= 0)) throw new RangeError(`weighted: each weight is finite and 0 or more, not ${w}.`);\n total += w;\n }\n if (!(total > 0)) throw new RangeError(\"weighted: the sum of the weights is 0.\");\n let left = next() * total;\n for (let i = 0; i < weights.length; i++) {\n left -= weights[i] as number;\n if (left < 0) return i;\n }\n // Rounding can leave a small remainder: give the last index with a weight.\n for (let i = weights.length - 1; ; i--) if ((weights[i] as number) > 0) return i;\n },\n shuffle(items) {\n const out = [...items];\n for (let i = out.length - 1; i > 0; i--) {\n const j = below(i + 1);\n [out[i], out[j]] = [out[j] as (typeof out)[number], out[i] as (typeof out)[number]];\n }\n return out;\n },\n sample(items, k) {\n wholeOrThrow(\"sample\", k);\n if (k < 0 || k > items.length) throw new RangeError(`sample: k is from 0 to ${items.length}, not ${k}.`);\n const out = [...items];\n for (let i = 0; i < k; i++) {\n const j = i + below(out.length - i);\n [out[i], out[j]] = [out[j] as (typeof out)[number], out[i] as (typeof out)[number]];\n }\n return out.slice(0, k);\n },\n normal(mean = 0, sd = 1) {\n const u1 = Math.max(next(), 1e-12);\n const u2 = next();\n return mean + sd * Math.sqrt(-2 * Math.log(u1)) * Math.cos(2 * Math.PI * u2);\n },\n fork(label) {\n const child = deriveSeed(seed, label);\n return randomOf(source(child), child, source);\n },\n };\n}\n\n/** The largest count of seeds that one range gives. A larger range is an error, not a long run. */\nconst MAX_RANGE = 1_000_000;\n\n/**\n * The seeds of a run: the seeds in `given` (the text of an environment variable, for example\n * `process.env.SEED`), else the default seeds. An empty text gives the defaults.\n *\n * The text is one seed (`17`) or a list of seeds and ranges with commas (`1,3,9-11` gives 1, 3, 9, 10\n * and 11), in the order of the list. A range has two whole numbers, the low one first. An empty part, a\n * part that is not an integer and a range with the low end last are each a `RangeError`.\n */\nexport function seedsFrom(given: string | undefined, defaults: readonly number[]): number[] {\n if (given === undefined || given.trim() === \"\") return [...defaults];\n return given.split(\",\").flatMap((raw) => {\n const part = raw.trim();\n const range = /^(\\d+)\\s*-\\s*(\\d+)$/u.exec(part);\n if (range !== null) {\n const [low, high] = [Number(range[1]), Number(range[2])];\n if (!Number.isSafeInteger(high) || high < low || high - low >= MAX_RANGE) {\n throw new RangeError(`seedsFrom: the range ${part} is not low-high with at most ${MAX_RANGE} seeds.`);\n }\n return Array.from({ length: high - low + 1 }, (_, i) => low + i);\n }\n const seed = part === \"\" ? Number.NaN : Number(part);\n if (!Number.isSafeInteger(seed)) throw new RangeError(`seedsFrom: a seed is an integer, not ${part === \"\" ? \"an empty part\" : part}.`);\n return [seed];\n });\n}\n"],"mappings":";;AAYA,SAAgB,WAAW,MAAsB;CAC/C,IAAI,QAAQ,SAAS;CACrB,aAAa;EACX,QAAS,QAAQ,eAAgB;EACjC,IAAI,IAAI;EACR,IAAI,KAAK,KAAK,IAAK,MAAM,IAAK,IAAI,CAAC;EACnC,KAAK,IAAI,KAAK,KAAK,IAAK,MAAM,GAAI,IAAI,EAAE;EACxC,SAAS,IAAK,MAAM,QAAS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AU,QAAQ;GAEtG,OAAO,MAAM,KAAK,EAAE,QAAQ,OAAO,MAAM,EAAE,IAAI,GAAG,MAAM,MAAM,CAAC;EACjE;EACA,MAAM,OAAO,SAAS,KAAK,MAAa,OAAO,IAAI;EACnD,IAAI,CAAC,OAAO,cAAc,IAAI,GAAG,MAAM,IAAI,WAAW,wCAAwC,SAAS,KAAK,kBAAkB,KAAK,EAAE;EACrI,OAAO,CAAC,IAAI;CACd,CAAC;AACH"}
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "$schema": "https://json.schemastore.org/package",
3
3
  "name": "@mark1russell7/rigor-generators",
4
- "version": "0.1.6",
5
- "description": "A seeded random number generator (mulberry32) with the draws that tests and benchmarks make: integers, picks, weights, shuffles, samples, normal values and named streams.",
4
+ "version": "0.1.8",
5
+ "description": "A seeded random number generator (mulberry32) with the draws that tests and benchmarks make: integers, picks, weights, shuffles, samples, normal values and named streams. It also gives a content hash: SHA-256 and canonical JSON (RFC 8785).",
6
6
  "keywords": [
7
7
  "random",
8
8
  "seed",
@@ -10,6 +10,9 @@
10
10
  "prng",
11
11
  "mulberry32",
12
12
  "fnv1a",
13
+ "sha256",
14
+ "canonical-json",
15
+ "jcs",
13
16
  "deterministic",
14
17
  "testing",
15
18
  "benchmark",