@elaraai/east-web-std 1.0.85

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (102) hide show
  1. package/CLA.md +26 -0
  2. package/CONTRIBUTING.md +28 -0
  3. package/LICENSE.md +31 -0
  4. package/README.md +191 -0
  5. package/THIRD_PARTY_NOTICES.md +123 -0
  6. package/dist/src/compliance.spec.d.ts +6 -0
  7. package/dist/src/compliance.spec.d.ts.map +1 -0
  8. package/dist/src/compliance.spec.js +89 -0
  9. package/dist/src/compliance.spec.js.map +1 -0
  10. package/dist/src/console.d.ts +237 -0
  11. package/dist/src/console.d.ts.map +1 -0
  12. package/dist/src/console.js +260 -0
  13. package/dist/src/console.js.map +1 -0
  14. package/dist/src/crypto.d.ts +224 -0
  15. package/dist/src/crypto.d.ts.map +1 -0
  16. package/dist/src/crypto.js +295 -0
  17. package/dist/src/crypto.js.map +1 -0
  18. package/dist/src/fetch.d.ts +383 -0
  19. package/dist/src/fetch.d.ts.map +1 -0
  20. package/dist/src/fetch.js +412 -0
  21. package/dist/src/fetch.js.map +1 -0
  22. package/dist/src/index.d.ts +106 -0
  23. package/dist/src/index.d.ts.map +1 -0
  24. package/dist/src/index.js +93 -0
  25. package/dist/src/index.js.map +1 -0
  26. package/dist/src/path.d.ts +243 -0
  27. package/dist/src/path.d.ts.map +1 -0
  28. package/dist/src/path.js +562 -0
  29. package/dist/src/path.js.map +1 -0
  30. package/dist/src/random/crypto-rng.d.ts +38 -0
  31. package/dist/src/random/crypto-rng.d.ts.map +1 -0
  32. package/dist/src/random/crypto-rng.js +55 -0
  33. package/dist/src/random/crypto-rng.js.map +1 -0
  34. package/dist/src/random/distributions/bates.d.ts +17 -0
  35. package/dist/src/random/distributions/bates.d.ts.map +1 -0
  36. package/dist/src/random/distributions/bates.js +15 -0
  37. package/dist/src/random/distributions/bates.js.map +1 -0
  38. package/dist/src/random/distributions/bernoulli.d.ts +17 -0
  39. package/dist/src/random/distributions/bernoulli.d.ts.map +1 -0
  40. package/dist/src/random/distributions/bernoulli.js +13 -0
  41. package/dist/src/random/distributions/bernoulli.js.map +1 -0
  42. package/dist/src/random/distributions/binomial.d.ts +17 -0
  43. package/dist/src/random/distributions/binomial.d.ts.map +1 -0
  44. package/dist/src/random/distributions/binomial.js +24 -0
  45. package/dist/src/random/distributions/binomial.js.map +1 -0
  46. package/dist/src/random/distributions/exponential.d.ts +17 -0
  47. package/dist/src/random/distributions/exponential.d.ts.map +1 -0
  48. package/dist/src/random/distributions/exponential.js +13 -0
  49. package/dist/src/random/distributions/exponential.js.map +1 -0
  50. package/dist/src/random/distributions/geometric.d.ts +17 -0
  51. package/dist/src/random/distributions/geometric.d.ts.map +1 -0
  52. package/dist/src/random/distributions/geometric.js +14 -0
  53. package/dist/src/random/distributions/geometric.js.map +1 -0
  54. package/dist/src/random/distributions/irwin-hall.d.ts +17 -0
  55. package/dist/src/random/distributions/irwin-hall.d.ts.map +1 -0
  56. package/dist/src/random/distributions/irwin-hall.js +18 -0
  57. package/dist/src/random/distributions/irwin-hall.js.map +1 -0
  58. package/dist/src/random/distributions/log-normal.d.ts +17 -0
  59. package/dist/src/random/distributions/log-normal.d.ts.map +1 -0
  60. package/dist/src/random/distributions/log-normal.js +12 -0
  61. package/dist/src/random/distributions/log-normal.js.map +1 -0
  62. package/dist/src/random/distributions/normal.d.ts +18 -0
  63. package/dist/src/random/distributions/normal.d.ts.map +1 -0
  64. package/dist/src/random/distributions/normal.js +16 -0
  65. package/dist/src/random/distributions/normal.js.map +1 -0
  66. package/dist/src/random/distributions/pareto.d.ts +17 -0
  67. package/dist/src/random/distributions/pareto.d.ts.map +1 -0
  68. package/dist/src/random/distributions/pareto.js +14 -0
  69. package/dist/src/random/distributions/pareto.js.map +1 -0
  70. package/dist/src/random/distributions/poisson.d.ts +17 -0
  71. package/dist/src/random/distributions/poisson.d.ts.map +1 -0
  72. package/dist/src/random/distributions/poisson.js +81 -0
  73. package/dist/src/random/distributions/poisson.js.map +1 -0
  74. package/dist/src/random/distributions/uniform-int.d.ts +17 -0
  75. package/dist/src/random/distributions/uniform-int.d.ts.map +1 -0
  76. package/dist/src/random/distributions/uniform-int.js +16 -0
  77. package/dist/src/random/distributions/uniform-int.js.map +1 -0
  78. package/dist/src/random/distributions/uniform.d.ts +17 -0
  79. package/dist/src/random/distributions/uniform.d.ts.map +1 -0
  80. package/dist/src/random/distributions/uniform.js +10 -0
  81. package/dist/src/random/distributions/uniform.js.map +1 -0
  82. package/dist/src/random/rng.d.ts +21 -0
  83. package/dist/src/random/rng.d.ts.map +1 -0
  84. package/dist/src/random/rng.js +7 -0
  85. package/dist/src/random/rng.js.map +1 -0
  86. package/dist/src/random/xorshift128.d.ts +42 -0
  87. package/dist/src/random/xorshift128.d.ts.map +1 -0
  88. package/dist/src/random/xorshift128.js +119 -0
  89. package/dist/src/random/xorshift128.js.map +1 -0
  90. package/dist/src/random.d.ts +822 -0
  91. package/dist/src/random.d.ts.map +1 -0
  92. package/dist/src/random.js +992 -0
  93. package/dist/src/random.js.map +1 -0
  94. package/dist/src/test.d.ts +86 -0
  95. package/dist/src/test.d.ts.map +1 -0
  96. package/dist/src/test.js +160 -0
  97. package/dist/src/test.js.map +1 -0
  98. package/dist/src/time.d.ts +201 -0
  99. package/dist/src/time.d.ts.map +1 -0
  100. package/dist/src/time.js +300 -0
  101. package/dist/src/time.js.map +1 -0
  102. package/package.json +64 -0
@@ -0,0 +1,992 @@
1
+ /**
2
+ * Copyright (c) 2025 Elara AI Pty Ltd
3
+ * Dual-licensed under AGPL-3.0 and commercial license. See LICENSE for details.
4
+ */
5
+ /**
6
+ * Random number generation for East programs in a browser.
7
+ *
8
+ * Ported from east-node-std's src/random.ts
9
+ * (libs/east-node/packages/east-node-std/src/random.ts): the same platform
10
+ * functions, types and algorithms, so a seed gives the stream east-node-std
11
+ * gives, bit for bit (test/random.spec.ts checks it). One thing differs:
12
+ * east-node-std keeps one generator for its process, and a browser keeps the
13
+ * generator in the implementation, so each {@link createRandomImpl} starts
14
+ * unseeded, as a new east-node process does.
15
+ *
16
+ * @packageDocumentation
17
+ */
18
+ import { East, FloatType, IntegerType, NullType } from "@elaraai/east";
19
+ import { EastError } from "@elaraai/east/internal";
20
+ import CryptoRNG from "./random/crypto-rng.js";
21
+ import XorShift128RNG from "./random/xorshift128.js";
22
+ import uniformDist from "./random/distributions/uniform.js";
23
+ import uniformIntDist from "./random/distributions/uniform-int.js";
24
+ import normalDist from "./random/distributions/normal.js";
25
+ import exponentialDist from "./random/distributions/exponential.js";
26
+ import bernoulliDist from "./random/distributions/bernoulli.js";
27
+ import binomialDist from "./random/distributions/binomial.js";
28
+ import geometricDist from "./random/distributions/geometric.js";
29
+ import poissonDist from "./random/distributions/poisson.js";
30
+ import paretoDist from "./random/distributions/pareto.js";
31
+ import logNormalDist from "./random/distributions/log-normal.js";
32
+ import irwinHallDist from "./random/distributions/irwin-hall.js";
33
+ import batesDist from "./random/distributions/bates.js";
34
+ // Platform Function Definitions
35
+ /**
36
+ * Generates a uniform random float in the range [0.0, 1.0).
37
+ *
38
+ * Returns a uniformly distributed random floating-point number greater than or equal to 0.0
39
+ * and strictly less than 1.0. Uses cryptographically secure random number generation by default.
40
+ *
41
+ * This is a platform function for the East language, enabling secure random number generation
42
+ * in East programs running in a browser.
43
+ *
44
+ * @returns A random float in [0.0, 1.0)
45
+ *
46
+ * @example
47
+ * ```ts
48
+ * const generateRandom = East.function([], FloatType, $ => {
49
+ * return Random.uniform();
50
+ * });
51
+ * ```
52
+ *
53
+ * @remarks
54
+ * - Uses the web-standard crypto.getRandomValues for cryptographic security
55
+ * - Uniform distribution across the range
56
+ * - Never returns exactly 1.0
57
+ */
58
+ export const random_uniform = East.platform("random_uniform", [], FloatType);
59
+ /**
60
+ * Generates a random float from a standard normal distribution (mean=0, standard deviation=1).
61
+ *
62
+ * Returns a random floating-point number drawn from a normal (Gaussian) distribution
63
+ * with mean 0.0 and standard deviation 1.0. Uses the Marsaglia polar method for
64
+ * high-quality normal distribution sampling.
65
+ *
66
+ * This is a platform function for the East language, enabling normal distribution sampling
67
+ * in East programs running in a browser.
68
+ *
69
+ * @returns A random float from N(0, 1)
70
+ *
71
+ * @example
72
+ * ```ts
73
+ * const generateNormal = East.function([], FloatType, $ => {
74
+ * const z = $.let(Random.normal());
75
+ * // Scale and shift: z * stddev + mean
76
+ * return z.multiply(2.5).add(10.0); // N(10, 2.5)
77
+ * });
78
+ * ```
79
+ *
80
+ * @remarks
81
+ * - Uses Marsaglia polar method for high-quality normal distribution
82
+ * - Mean: 0.0, Standard deviation: 1.0
83
+ * - Can return any real number (unbounded range)
84
+ * - Use `.multiply(stddev).add(mean)` to scale/shift distribution
85
+ */
86
+ export const random_normal = East.platform("random_normal", [], FloatType);
87
+ /**
88
+ * Generates a random integer in the range [min, max] (both endpoints inclusive).
89
+ *
90
+ * Returns a uniformly distributed random integer between min and max (both inclusive).
91
+ * Uses cryptographically secure random number generation. The range must be valid (min ≤ max).
92
+ *
93
+ * This is a platform function for the East language, enabling random integer generation
94
+ * in East programs running in a browser.
95
+ *
96
+ * @param min - The minimum value (inclusive)
97
+ * @param max - The maximum value (inclusive)
98
+ * @returns A random integer in [min, max]
99
+ *
100
+ * @throws {EastError} When min > max
101
+ *
102
+ * @example
103
+ * ```ts
104
+ * const rollDice = East.function([], IntegerType, $ => {
105
+ * return Random.range(1n, 6n); // 1-6 inclusive
106
+ * });
107
+ * ```
108
+ *
109
+ * @remarks
110
+ * - Both min and max are inclusive
111
+ * - Uniform distribution across the range
112
+ * - Uses floor method to avoid modulo bias
113
+ */
114
+ export const random_range = East.platform("random_range", [IntegerType, IntegerType], IntegerType);
115
+ /**
116
+ * Generates a random float from an exponential distribution.
117
+ *
118
+ * Returns a random floating-point number drawn from an exponential distribution
119
+ * with rate parameter lambda (λ). The mean of the distribution is 1/λ.
120
+ * Commonly used for modeling time between events in a Poisson process.
121
+ *
122
+ * This is a platform function for the East language, enabling exponential distribution sampling
123
+ * in East programs running in a browser.
124
+ *
125
+ * @param lambda - Rate parameter (λ > 0), default 1.0. Mean = 1/λ
126
+ * @returns A random float from Exp(λ)
127
+ *
128
+ * @throws {EastError} When lambda ≤ 0
129
+ *
130
+ * @example
131
+ * ```ts
132
+ * const waitTime = East.function([], FloatType, $ => {
133
+ * // Average wait time of 5 minutes (lambda = 0.2)
134
+ * return Random.exponential(0.2);
135
+ * });
136
+ * ```
137
+ *
138
+ * @remarks
139
+ * - Uses inverse transform sampling: -ln(U) / λ
140
+ * - Always returns positive values
141
+ * - Mean = 1/λ, Variance = 1/λ²
142
+ * - Memoryless property: P(X > s + t | X > s) = P(X > t)
143
+ */
144
+ export const random_exponential = East.platform("random_exponential", [FloatType], FloatType);
145
+ /**
146
+ * Generates a random float from a Weibull distribution.
147
+ *
148
+ * Returns a random floating-point number drawn from a Weibull distribution
149
+ * with shape parameter k. Uses exponential distribution transformation.
150
+ * Commonly used for modeling failure rates and lifetime distributions.
151
+ *
152
+ * This is a platform function for the East language, enabling Weibull distribution sampling
153
+ * in East programs running in a browser.
154
+ *
155
+ * @param shape - Shape parameter (k > 0). k=1 gives exponential, k>1 increases failure rate
156
+ * @returns A random float from Weibull(k, 1)
157
+ *
158
+ * @throws {EastError} When shape ≤ 0
159
+ *
160
+ * @example
161
+ * ```ts
162
+ * const lifetime = East.function([], FloatType, $ => {
163
+ * // Shape=2 models wear-out failures
164
+ * return Random.weibull(2.0);
165
+ * });
166
+ * ```
167
+ *
168
+ * @remarks
169
+ * - Uses transformation: exponential() ^ (1/shape)
170
+ * - Shape < 1: decreasing failure rate
171
+ * - Shape = 1: constant failure rate (exponential)
172
+ * - Shape > 1: increasing failure rate
173
+ */
174
+ export const random_weibull = East.platform("random_weibull", [FloatType], FloatType);
175
+ /**
176
+ * Generates a binary random outcome (0 or 1).
177
+ *
178
+ * Returns 0 or 1 based on success probability p. This models a single
179
+ * Bernoulli trial, like a biased coin flip.
180
+ *
181
+ * This is a platform function for the East language, enabling binary random outcomes
182
+ * in East programs running in a browser.
183
+ *
184
+ * @param p - Success probability (0 ≤ p < 1), default 0.5
185
+ * @returns 0 or 1 (as integer)
186
+ *
187
+ * @throws {EastError} When p < 0 or p ≥ 1
188
+ *
189
+ * @example
190
+ * ```ts
191
+ * const coinFlip = East.function([], IntegerType, $ => {
192
+ * // Fair coin: 50% chance of 1
193
+ * return Random.bernoulli(0.5);
194
+ * });
195
+ * ```
196
+ *
197
+ * @remarks
198
+ * - Returns 1 with probability p, 0 with probability (1-p)
199
+ * - Mean = p, Variance = p(1-p)
200
+ * - Special case of binomial with n=1
201
+ */
202
+ export const random_bernoulli = East.platform("random_bernoulli", [FloatType], IntegerType);
203
+ /**
204
+ * Generates the number of successes in n independent Bernoulli trials.
205
+ *
206
+ * Returns an integer count of successes when performing n independent trials,
207
+ * each with success probability p. Models scenarios like coin flips, pass/fail tests.
208
+ *
209
+ * This is a platform function for the East language, enabling binomial distribution sampling
210
+ * in East programs running in a browser.
211
+ *
212
+ * @param n - Number of trials (integer > 0)
213
+ * @param p - Success probability per trial (0 ≤ p < 1), default 0.5
214
+ * @returns Number of successes (integer in [0, n])
215
+ *
216
+ * @throws {EastError} When n ≤ 0, not an integer, or p < 0 or p ≥ 1
217
+ *
218
+ * @example
219
+ * ```ts
220
+ * const heads = East.function([], IntegerType, $ => {
221
+ * // Number of heads in 10 coin flips
222
+ * return Random.binomial(10n, 0.5);
223
+ * });
224
+ * ```
225
+ *
226
+ * @remarks
227
+ * - Mean = n × p, Variance = n × p × (1-p)
228
+ * - Returns value in range [0, n]
229
+ * - Sum of n independent Bernoulli(p) trials
230
+ */
231
+ export const random_binomial = East.platform("random_binomial", [IntegerType, FloatType], IntegerType);
232
+ /**
233
+ * Generates the number of trials until the first success.
234
+ *
235
+ * Returns an integer representing the number of independent Bernoulli trials
236
+ * needed to get the first success, where each trial has success probability p.
237
+ * Models scenarios like "how many attempts until success?"
238
+ *
239
+ * This is a platform function for the East language, enabling geometric distribution sampling
240
+ * in East programs running in a browser.
241
+ *
242
+ * @param p - Success probability per trial (0 < p < 1), default 0.5
243
+ * @returns Number of trials until first success (integer ≥ 1)
244
+ *
245
+ * @throws {EastError} When p ≤ 0 or p ≥ 1
246
+ *
247
+ * @example
248
+ * ```ts
249
+ * const attempts = East.function([], IntegerType, $ => {
250
+ * // Rolls until getting a 6 (p = 1/6)
251
+ * return Random.geometric(1.0 / 6.0);
252
+ * });
253
+ * ```
254
+ *
255
+ * @remarks
256
+ * - Mean = 1/p, Variance = (1-p)/p²
257
+ * - Always returns integer ≥ 1
258
+ * - Memoryless property like exponential distribution
259
+ * - Uses inverse transform sampling
260
+ */
261
+ export const random_geometric = East.platform("random_geometric", [FloatType], IntegerType);
262
+ /**
263
+ * Generates the number of events in a fixed interval from a Poisson process.
264
+ *
265
+ * Returns an integer count of events occurring in a fixed interval,
266
+ * where events occur independently at a constant average rate λ (lambda).
267
+ * Commonly used for modeling rare events, arrivals, or counts.
268
+ *
269
+ * This is a platform function for the East language, enabling Poisson distribution sampling
270
+ * in East programs running in a browser.
271
+ *
272
+ * @param lambda - Average rate of events (λ > 0), default 1.0
273
+ * @returns Number of events (integer ≥ 0)
274
+ *
275
+ * @throws {EastError} When lambda ≤ 0
276
+ *
277
+ * @example
278
+ * ```ts
279
+ * const customers = East.function([], IntegerType, $ => {
280
+ * // Average 3 customers per hour
281
+ * return Random.poisson(3.0);
282
+ * });
283
+ * ```
284
+ *
285
+ * @remarks
286
+ * - Mean = λ, Variance = λ
287
+ * - Always returns non-negative integer
288
+ * - Uses inversion method for λ < 10, generative method for λ ≥ 10
289
+ * - Approximates binomial when n is large and p is small
290
+ */
291
+ export const random_poisson = East.platform("random_poisson", [FloatType], IntegerType);
292
+ /**
293
+ * Generates a random float from a Pareto distribution (power law).
294
+ *
295
+ * Returns a random floating-point number drawn from a Pareto distribution
296
+ * with shape parameter α (alpha). Models phenomena following power laws,
297
+ * like wealth distribution, city sizes, or word frequencies.
298
+ *
299
+ * This is a platform function for the East language, enabling Pareto distribution sampling
300
+ * in East programs running in a browser.
301
+ *
302
+ * @param alpha - Shape parameter (α ≥ 0), default 1.0. Smaller α = heavier tail
303
+ * @returns A random float from Pareto(α) (value ≥ 1.0)
304
+ *
305
+ * @throws {EastError} When alpha < 0
306
+ *
307
+ * @example
308
+ * ```ts
309
+ * const wealth = East.function([], FloatType, $ => {
310
+ * // Heavy-tailed distribution (80/20 rule)
311
+ * return Random.pareto(1.16);
312
+ * });
313
+ * ```
314
+ *
315
+ * @remarks
316
+ * - Always returns value ≥ 1.0
317
+ * - Mean = α/(α-1) for α > 1, infinite otherwise
318
+ * - Heavier tail as α decreases
319
+ * - Models "80/20 rule" and power law phenomena
320
+ */
321
+ export const random_pareto = East.platform("random_pareto", [FloatType], FloatType);
322
+ /**
323
+ * Generates a random float whose logarithm is normally distributed.
324
+ *
325
+ * Returns a random floating-point number from a log-normal distribution,
326
+ * where ln(X) ~ N(μ, σ²). Commonly used for modeling multiplicative processes,
327
+ * stock prices, or quantities that can't be negative.
328
+ *
329
+ * This is a platform function for the East language, enabling log-normal distribution sampling
330
+ * in East programs running in a browser.
331
+ *
332
+ * @param mu - Mean of underlying normal distribution, default 0.0
333
+ * @param sigma - Standard deviation of underlying normal, default 1.0
334
+ * @returns A random float from LogNormal(μ, σ) (always positive)
335
+ *
336
+ * @example
337
+ * ```ts
338
+ * const stockPrice = East.function([], FloatType, $ => {
339
+ * // Log-normal with ln(X) ~ N(0, 0.2)
340
+ * return Random.logNormal(0.0, 0.2);
341
+ * });
342
+ * ```
343
+ *
344
+ * @remarks
345
+ * - Always returns positive values
346
+ * - If ln(X) ~ N(μ, σ²), then X ~ LogNormal(μ, σ)
347
+ * - Median = exp(μ), Mean = exp(μ + σ²/2)
348
+ * - Right-skewed distribution
349
+ */
350
+ export const random_log_normal = East.platform("random_log_normal", [FloatType, FloatType], FloatType);
351
+ /**
352
+ * Generates the sum of n independent uniform random variables.
353
+ *
354
+ * Returns the sum of n independent uniform(0,1) random variables.
355
+ * This is the Irwin-Hall distribution. As n increases, approaches
356
+ * normal distribution by Central Limit Theorem.
357
+ *
358
+ * This is a platform function for the East language, enabling Irwin-Hall distribution sampling
359
+ * in East programs running in a browser.
360
+ *
361
+ * @param n - Number of uniform variables to sum (integer ≥ 0), default 1
362
+ * @returns Sum of n uniform(0,1) random variables (float in [0, n])
363
+ *
364
+ * @throws {EastError} When n < 0 or not an integer
365
+ *
366
+ * @example
367
+ * ```ts
368
+ * const irwinHall = East.function([], FloatType, $ => {
369
+ * // Sum of 12 uniform variables
370
+ * return Random.irwinHall(12n);
371
+ * });
372
+ * ```
373
+ *
374
+ * @remarks
375
+ * - Range: [0, n]
376
+ * - Mean = n/2, Variance = n/12
377
+ * - Approximates N(n/2, n/12) for large n
378
+ * - Related to Bates distribution (divided by n)
379
+ */
380
+ export const random_irwin_hall = East.platform("random_irwin_hall", [IntegerType], FloatType);
381
+ /**
382
+ * Generates the average of n independent uniform random variables.
383
+ *
384
+ * Returns the average of n independent uniform(0,1) random variables.
385
+ * This is the Bates distribution. Approaches normal distribution as
386
+ * n increases (Central Limit Theorem).
387
+ *
388
+ * This is a platform function for the East language, enabling Bates distribution sampling
389
+ * in East programs running in a browser.
390
+ *
391
+ * @param n - Number of uniform variables to average (integer > 0), default 1
392
+ * @returns Average of n uniform(0,1) random variables (float in [0, 1])
393
+ *
394
+ * @throws {EastError} When n ≤ 0 or not an integer
395
+ *
396
+ * @example
397
+ * ```ts
398
+ * const bates = East.function([], FloatType, $ => {
399
+ * // Average of 12 uniform variables (smoother than single uniform)
400
+ * return Random.bates(12n);
401
+ * });
402
+ * ```
403
+ *
404
+ * @remarks
405
+ * - Range: [0, 1]
406
+ * - Mean = 0.5, Variance = 1/(12n)
407
+ * - Approximates N(0.5, 1/(12n)) for large n
408
+ * - More concentrated around 0.5 as n increases
409
+ */
410
+ export const random_bates = East.platform("random_bates", [IntegerType], FloatType);
411
+ /**
412
+ * Seeds the random number generator.
413
+ *
414
+ * Sets the seed for the random number generator, allowing reproducible random sequences.
415
+ * All subsequent random operations will use this seeded RNG until a new seed is set.
416
+ *
417
+ * This is a platform function for the East language, enabling reproducible randomness
418
+ * in East programs running in a browser.
419
+ *
420
+ * @param seed - Seed value (integer)
421
+ * @returns null
422
+ *
423
+ * @example
424
+ * ```ts
425
+ * const seedAndGenerate = East.function([], FloatType, $ => {
426
+ * $(Random.seed(12345n));
427
+ * return Random.uniform(); // Will be reproducible
428
+ * });
429
+ * ```
430
+ *
431
+ * @remarks
432
+ * - IMPORTANT: Seeding switches from cryptographically secure random to a deterministic
433
+ * PRNG (xorshift128+). This is essential for reproducible simulations but should not
434
+ * be used when cryptographic security is required.
435
+ * - Same seed produces same sequence of random numbers, and the same sequence
436
+ * east-node-std produces for it
437
+ * - The seed holds for the implementation that was seeded: each
438
+ * {@link createRandomImpl} (and so each `createWebPlatform()`) starts unseeded
439
+ */
440
+ export const random_seed = East.platform("random_seed", [IntegerType], NullType);
441
+ /**
442
+ * The Random platform functions, drawing from `state`.
443
+ *
444
+ * Each implementation is east-node-std's, with `state.rng` where
445
+ * east-node-std reads its process-wide generator.
446
+ */
447
+ function implementRandom(state) {
448
+ return [
449
+ random_uniform.implement(() => {
450
+ return uniformDist(state.rng, 0, 1)();
451
+ }),
452
+ random_normal.implement(() => {
453
+ return normalDist(state.rng, 0, 1)();
454
+ }),
455
+ random_range.implement((min, max) => {
456
+ if (min > max) {
457
+ throw new EastError(`Invalid range: min (${min}) > max (${max})`, {
458
+ location: [{ filename: "random_range", line: 0n, column: 0n }],
459
+ });
460
+ }
461
+ try {
462
+ return BigInt(uniformIntDist(state.rng, min, max)());
463
+ }
464
+ catch (err) {
465
+ throw new EastError(`Random range generation failed: ${err.message}`, {
466
+ location: [{ filename: "random_range", line: 0n, column: 0n }],
467
+ cause: err
468
+ });
469
+ }
470
+ }),
471
+ random_exponential.implement((lambda) => {
472
+ try {
473
+ return exponentialDist(state.rng, lambda)();
474
+ }
475
+ catch (err) {
476
+ throw new EastError(`Random exponential generation failed: ${err.message}`, {
477
+ location: [{ filename: "random_exponential", line: 0n, column: 0n }],
478
+ cause: err
479
+ });
480
+ }
481
+ }),
482
+ random_weibull.implement((shape) => {
483
+ try {
484
+ // Weibull = exponential() ^ (1/shape)
485
+ const exp = exponentialDist(state.rng, 1);
486
+ return Math.pow(exp(), 1 / shape);
487
+ }
488
+ catch (err) {
489
+ throw new EastError(`Random Weibull generation failed: ${err.message}`, {
490
+ location: [{ filename: "random_weibull", line: 0n, column: 0n }],
491
+ cause: err
492
+ });
493
+ }
494
+ }),
495
+ random_bernoulli.implement((p) => {
496
+ try {
497
+ return BigInt(bernoulliDist(state.rng, p)());
498
+ }
499
+ catch (err) {
500
+ throw new EastError(`Random Bernoulli generation failed: ${err.message}`, {
501
+ location: [{ filename: "random_bernoulli", line: 0n, column: 0n }],
502
+ cause: err
503
+ });
504
+ }
505
+ }),
506
+ random_binomial.implement((n, p) => {
507
+ try {
508
+ return BigInt(binomialDist(state.rng, n, p)());
509
+ }
510
+ catch (err) {
511
+ throw new EastError(`Random binomial generation failed: ${err.message}`, {
512
+ location: [{ filename: "random_binomial", line: 0n, column: 0n }],
513
+ cause: err
514
+ });
515
+ }
516
+ }),
517
+ random_geometric.implement((p) => {
518
+ try {
519
+ return BigInt(geometricDist(state.rng, p)());
520
+ }
521
+ catch (err) {
522
+ throw new EastError(`Random geometric generation failed: ${err.message}`, {
523
+ location: [{ filename: "random_geometric", line: 0n, column: 0n }],
524
+ cause: err
525
+ });
526
+ }
527
+ }),
528
+ random_poisson.implement((lambda) => {
529
+ try {
530
+ return BigInt(poissonDist(state.rng, lambda)());
531
+ }
532
+ catch (err) {
533
+ throw new EastError(`Random Poisson generation failed: ${err.message}`, {
534
+ location: [{ filename: "random_poisson", line: 0n, column: 0n }],
535
+ cause: err
536
+ });
537
+ }
538
+ }),
539
+ random_pareto.implement((alpha) => {
540
+ try {
541
+ return paretoDist(state.rng, alpha)();
542
+ }
543
+ catch (err) {
544
+ throw new EastError(`Random Pareto generation failed: ${err.message}`, {
545
+ location: [{ filename: "random_pareto", line: 0n, column: 0n }],
546
+ cause: err
547
+ });
548
+ }
549
+ }),
550
+ random_log_normal.implement((mu, sigma) => {
551
+ try {
552
+ return logNormalDist(state.rng, mu, sigma)();
553
+ }
554
+ catch (err) {
555
+ throw new EastError(`Random log-normal generation failed: ${err.message}`, {
556
+ location: [{ filename: "random_log_normal", line: 0n, column: 0n }],
557
+ cause: err
558
+ });
559
+ }
560
+ }),
561
+ random_irwin_hall.implement((n) => {
562
+ try {
563
+ return irwinHallDist(state.rng, n)();
564
+ }
565
+ catch (err) {
566
+ throw new EastError(`Random Irwin-Hall generation failed: ${err.message}`, {
567
+ location: [{ filename: "random_irwin_hall", line: 0n, column: 0n }],
568
+ cause: err
569
+ });
570
+ }
571
+ }),
572
+ random_bates.implement((n) => {
573
+ try {
574
+ return batesDist(state.rng, n)();
575
+ }
576
+ catch (err) {
577
+ throw new EastError(`Random Bates generation failed: ${err.message}`, {
578
+ location: [{ filename: "random_bates", line: 0n, column: 0n }],
579
+ cause: err
580
+ });
581
+ }
582
+ }),
583
+ random_seed.implement((seed) => {
584
+ // Switch to seedable PRNG (xorshift128+) and set the seed
585
+ // IMPORTANT: This disables cryptographic security for reproducible simulations
586
+ state.rng = new XorShift128RNG(seed);
587
+ }),
588
+ ];
589
+ }
590
+ /**
591
+ * Creates a Random implementation with its own generator, unseeded.
592
+ *
593
+ * Every Random platform function in the returned array draws from one
594
+ * generator that no other implementation shares: it is cryptographically
595
+ * secure until the program calls {@link Random.seed}. A host running one
596
+ * program after another in the same worker creates one per program, so a
597
+ * seed one program set never reaches the next — as each east-node process
598
+ * starts unseeded.
599
+ *
600
+ * @returns The Random platform functions, drawing from a new generator
601
+ *
602
+ * @example
603
+ * ```ts
604
+ * import { East, FloatType } from "@elaraai/east";
605
+ * import { Random, createRandomImpl } from "@elaraai/east-web-std";
606
+ *
607
+ * const draw = East.function([], FloatType, $ => {
608
+ * $(Random.seed(42n));
609
+ * return Random.uniform();
610
+ * });
611
+ *
612
+ * const compiled = East.compile(draw, createRandomImpl());
613
+ * compiled(); // The value east-node-std draws for seed 42
614
+ * ```
615
+ */
616
+ export function createRandomImpl() {
617
+ return implementRandom({ rng: new CryptoRNG() });
618
+ }
619
+ /** The generator {@link RandomImpl} draws from. */
620
+ const defaultState = { rng: new CryptoRNG() };
621
+ /**
622
+ * Reset {@link RandomImpl}'s generator to cryptographically secure mode.
623
+ * Primarily for testing to avoid test pollution.
624
+ */
625
+ export function resetToCryptoRNG() {
626
+ defaultState.rng = new CryptoRNG();
627
+ }
628
+ /**
629
+ * Browser implementation of the random platform functions, sharing one
630
+ * generator between every program compiled with it.
631
+ *
632
+ * Pass this array to {@link East.compile} to enable random operations, or
633
+ * use {@link createRandomImpl} for a generator of the program's own.
634
+ */
635
+ const RandomImpl = implementRandom(defaultState);
636
+ /**
637
+ * Grouped random platform functions.
638
+ *
639
+ * Provides random number generation and sampling operations for East programs,
640
+ * including multiple probability distributions and collection sampling.
641
+ *
642
+ * @example
643
+ * ```ts
644
+ * import { East, FloatType, IntegerType } from "@elaraai/east";
645
+ * import { Random } from "@elaraai/east-web-std";
646
+ *
647
+ * const rollDice = East.function([], IntegerType, $ => {
648
+ * return Random.range(1n, 6n);
649
+ * });
650
+ *
651
+ * const compiled = East.compile(rollDice, Random.Implementation);
652
+ * const result = compiled(); // Random integer from 1 to 6
653
+ * ```
654
+ */
655
+ export const Random = {
656
+ /**
657
+ * Generates a uniform random float in the range [0.0, 1.0).
658
+ *
659
+ * Returns a uniformly distributed random floating-point number greater than or equal to 0.0
660
+ * and strictly less than 1.0. Uses cryptographically secure random number generation.
661
+ *
662
+ * @returns A random float in [0.0, 1.0)
663
+ *
664
+ * @example
665
+ * ```ts
666
+ * const generateRandom = East.function([], FloatType, $ => {
667
+ * return Random.uniform();
668
+ * });
669
+ *
670
+ * const compiled = East.compile(generateRandom, Random.Implementation);
671
+ * const result = compiled(); // e.g., 0.7234891234
672
+ * ```
673
+ */
674
+ uniform: random_uniform,
675
+ /**
676
+ * Generates a random float from a standard normal distribution (mean=0, standard deviation=1).
677
+ *
678
+ * Returns a random floating-point number drawn from a normal (Gaussian) distribution
679
+ * with mean 0.0 and standard deviation 1.0. Use multiplication and addition to scale
680
+ * and shift to different mean/standard deviation.
681
+ *
682
+ * @returns A random float from N(0, 1)
683
+ *
684
+ * @example
685
+ * ```ts
686
+ * const generateNormal = East.function([], FloatType, $ => {
687
+ * const z = $.let(Random.normal());
688
+ * // Scale and shift: z * stddev + mean
689
+ * return z.multiply(2.5).add(10.0); // N(10, 2.5)
690
+ * });
691
+ *
692
+ * const compiled = East.compile(generateNormal, Random.Implementation);
693
+ * const result = compiled(); // e.g., 9.234 (from N(10, 2.5))
694
+ * ```
695
+ */
696
+ normal: random_normal,
697
+ /**
698
+ * Generates a random integer in the range [min, max] (both endpoints inclusive).
699
+ *
700
+ * Returns a uniformly distributed random integer between min and max (both inclusive).
701
+ * Uses cryptographically secure random number generation.
702
+ *
703
+ * @param min - The minimum value (inclusive)
704
+ * @param max - The maximum value (inclusive, must be >= min)
705
+ * @returns A random integer in [min, max]
706
+ *
707
+ * @throws {EastError} When min > max
708
+ *
709
+ * @example
710
+ * ```ts
711
+ * const rollDice = East.function([], IntegerType, $ => {
712
+ * return Random.range(1n, 6n); // 1-6 inclusive
713
+ * });
714
+ *
715
+ * const compiled = East.compile(rollDice, Random.Implementation);
716
+ * const result = compiled(); // e.g., 4n
717
+ * ```
718
+ */
719
+ range: random_range,
720
+ /**
721
+ * Generates a random float from an exponential distribution.
722
+ *
723
+ * Returns a random floating-point number drawn from an exponential distribution
724
+ * with rate parameter lambda (λ). The mean of the distribution is 1/λ.
725
+ * Commonly used for modeling time between events in a Poisson process.
726
+ *
727
+ * @param lambda - Rate parameter (λ > 0), where mean = 1/λ
728
+ * @returns A random float from Exp(λ)
729
+ *
730
+ * @throws {EastError} When lambda <= 0
731
+ *
732
+ * @example
733
+ * ```ts
734
+ * const waitTime = East.function([], FloatType, $ => {
735
+ * // Average wait time of 5 minutes (lambda = 0.2)
736
+ * return Random.exponential(0.2);
737
+ * });
738
+ *
739
+ * const compiled = East.compile(waitTime, Random.Implementation);
740
+ * const result = compiled(); // e.g., 3.7 minutes
741
+ * ```
742
+ */
743
+ exponential: random_exponential,
744
+ /**
745
+ * Generates a random float from a Weibull distribution.
746
+ *
747
+ * Returns a random floating-point number drawn from a Weibull distribution
748
+ * with shape parameter k. Commonly used for modeling failure rates and lifetime distributions.
749
+ *
750
+ * @param shape - Shape parameter (k > 0). k=1 gives exponential, k>1 increases failure rate
751
+ * @returns A random float from Weibull(k, 1)
752
+ *
753
+ * @throws {EastError} When shape <= 0
754
+ *
755
+ * @example
756
+ * ```ts
757
+ * const lifetime = East.function([], FloatType, $ => {
758
+ * // Shape=2 models wear-out failures
759
+ * return Random.weibull(2.0);
760
+ * });
761
+ *
762
+ * const compiled = East.compile(lifetime, Random.Implementation);
763
+ * const result = compiled(); // e.g., 1.23
764
+ * ```
765
+ */
766
+ weibull: random_weibull,
767
+ /**
768
+ * Generates a binary random outcome (0 or 1).
769
+ *
770
+ * Returns 0 or 1 based on success probability p. This models a single
771
+ * Bernoulli trial, like a biased coin flip.
772
+ *
773
+ * @param p - Success probability (0 <= p < 1)
774
+ * @returns 0 or 1 (as integer)
775
+ *
776
+ * @throws {EastError} When p < 0 or p >= 1
777
+ *
778
+ * @example
779
+ * ```ts
780
+ * const coinFlip = East.function([], IntegerType, $ => {
781
+ * // Fair coin: 50% chance of 1
782
+ * return Random.bernoulli(0.5);
783
+ * });
784
+ *
785
+ * const compiled = East.compile(coinFlip, Random.Implementation);
786
+ * const result = compiled(); // e.g., 1n or 0n
787
+ * ```
788
+ */
789
+ bernoulli: random_bernoulli,
790
+ /**
791
+ * Generates the number of successes in n independent Bernoulli trials.
792
+ *
793
+ * Returns an integer count of successes when performing n independent trials,
794
+ * each with success probability p. Models scenarios like coin flips, pass/fail tests.
795
+ *
796
+ * @param n - Number of trials (integer > 0)
797
+ * @param p - Success probability per trial (0 <= p < 1)
798
+ * @returns Number of successes (integer in [0, n])
799
+ *
800
+ * @throws {EastError} When n <= 0, not an integer, or p < 0 or p >= 1
801
+ *
802
+ * @example
803
+ * ```ts
804
+ * const heads = East.function([], IntegerType, $ => {
805
+ * // Number of heads in 10 coin flips
806
+ * return Random.binomial(10n, 0.5);
807
+ * });
808
+ *
809
+ * const compiled = East.compile(heads, Random.Implementation);
810
+ * const result = compiled(); // e.g., 6n
811
+ * ```
812
+ */
813
+ binomial: random_binomial,
814
+ /**
815
+ * Generates the number of trials until the first success.
816
+ *
817
+ * Returns an integer representing the number of independent Bernoulli trials
818
+ * needed to get the first success, where each trial has success probability p.
819
+ * Models scenarios like "how many attempts until success?"
820
+ *
821
+ * @param p - Success probability per trial (0 < p < 1)
822
+ * @returns Number of trials until first success (integer >= 1)
823
+ *
824
+ * @throws {EastError} When p <= 0 or p >= 1
825
+ *
826
+ * @example
827
+ * ```ts
828
+ * const attempts = East.function([], IntegerType, $ => {
829
+ * // Rolls until getting a 6 (p = 1/6)
830
+ * return Random.geometric(1.0 / 6.0);
831
+ * });
832
+ *
833
+ * const compiled = East.compile(attempts, Random.Implementation);
834
+ * const result = compiled(); // e.g., 4n
835
+ * ```
836
+ */
837
+ geometric: random_geometric,
838
+ /**
839
+ * Generates the number of events in a fixed interval from a Poisson process.
840
+ *
841
+ * Returns an integer count of events occurring in a fixed interval,
842
+ * where events occur independently at a constant average rate λ (lambda).
843
+ * Commonly used for modeling rare events, arrivals, or counts.
844
+ *
845
+ * @param lambda - Average rate of events (λ > 0)
846
+ * @returns Number of events (integer >= 0)
847
+ *
848
+ * @throws {EastError} When lambda <= 0
849
+ *
850
+ * @example
851
+ * ```ts
852
+ * const customers = East.function([], IntegerType, $ => {
853
+ * // Average 3 customers per hour
854
+ * return Random.poisson(3.0);
855
+ * });
856
+ *
857
+ * const compiled = East.compile(customers, Random.Implementation);
858
+ * const result = compiled(); // e.g., 2n
859
+ * ```
860
+ */
861
+ poisson: random_poisson,
862
+ /**
863
+ * Generates a random float from a Pareto distribution (power law).
864
+ *
865
+ * Returns a random floating-point number drawn from a Pareto distribution
866
+ * with shape parameter α (alpha). Models phenomena following power laws,
867
+ * like wealth distribution, city sizes, or word frequencies.
868
+ *
869
+ * @param alpha - Shape parameter (α >= 0). Smaller α = heavier tail
870
+ * @returns A random float from Pareto(α) (value >= 1.0)
871
+ *
872
+ * @throws {EastError} When alpha < 0
873
+ *
874
+ * @example
875
+ * ```ts
876
+ * const wealth = East.function([], FloatType, $ => {
877
+ * // Heavy-tailed distribution (80/20 rule)
878
+ * return Random.pareto(1.16);
879
+ * });
880
+ *
881
+ * const compiled = East.compile(wealth, Random.Implementation);
882
+ * const result = compiled(); // e.g., 2.45
883
+ * ```
884
+ */
885
+ pareto: random_pareto,
886
+ /**
887
+ * Generates a random float whose logarithm is normally distributed.
888
+ *
889
+ * Returns a random floating-point number from a log-normal distribution,
890
+ * where ln(X) ~ N(μ, σ²). Commonly used for modeling multiplicative processes,
891
+ * stock prices, or quantities that can't be negative.
892
+ *
893
+ * @param mu - Mean of underlying normal distribution
894
+ * @param sigma - Standard deviation of underlying normal (must be > 0)
895
+ * @returns A random float from LogNormal(μ, σ) (always positive)
896
+ *
897
+ * @example
898
+ * ```ts
899
+ * const stockPrice = East.function([], FloatType, $ => {
900
+ * // Log-normal with ln(X) ~ N(0, 0.2)
901
+ * return Random.logNormal(0.0, 0.2);
902
+ * });
903
+ *
904
+ * const compiled = East.compile(stockPrice, Random.Implementation);
905
+ * const result = compiled(); // e.g., 1.15
906
+ * ```
907
+ */
908
+ logNormal: random_log_normal,
909
+ /**
910
+ * Generates the sum of n independent uniform random variables.
911
+ *
912
+ * Returns the sum of n independent uniform(0,1) random variables.
913
+ * This is the Irwin-Hall distribution. As n increases, approaches
914
+ * normal distribution by Central Limit Theorem.
915
+ *
916
+ * @param n - Number of uniform variables to sum (integer >= 0)
917
+ * @returns Sum of n uniform(0,1) random variables (float in [0, n])
918
+ *
919
+ * @throws {EastError} When n < 0 or not an integer
920
+ *
921
+ * @example
922
+ * ```ts
923
+ * const irwinHall = East.function([], FloatType, $ => {
924
+ * // Sum of 12 uniform variables
925
+ * return Random.irwinHall(12n);
926
+ * });
927
+ *
928
+ * const compiled = East.compile(irwinHall, Random.Implementation);
929
+ * const result = compiled(); // e.g., 6.234 (approximately N(6, 1))
930
+ * ```
931
+ */
932
+ irwinHall: random_irwin_hall,
933
+ /**
934
+ * Generates the average of n independent uniform random variables.
935
+ *
936
+ * Returns the average of n independent uniform(0,1) random variables.
937
+ * This is the Bates distribution. Approaches normal distribution as
938
+ * n increases (Central Limit Theorem).
939
+ *
940
+ * @param n - Number of uniform variables to average (integer > 0)
941
+ * @returns Average of n uniform(0,1) random variables (float in [0, 1])
942
+ *
943
+ * @throws {EastError} When n <= 0 or not an integer
944
+ *
945
+ * @example
946
+ * ```ts
947
+ * const bates = East.function([], FloatType, $ => {
948
+ * // Average of 12 uniform variables (smoother than single uniform)
949
+ * return Random.bates(12n);
950
+ * });
951
+ *
952
+ * const compiled = East.compile(bates, Random.Implementation);
953
+ * const result = compiled(); // e.g., 0.523 (approximately N(0.5, 1/144))
954
+ * ```
955
+ */
956
+ bates: random_bates,
957
+ /**
958
+ * Seeds the random number generator.
959
+ *
960
+ * Sets the seed for the random number generator, allowing reproducible random sequences.
961
+ * All subsequent random operations will use this seeded RNG until a new seed is set.
962
+ *
963
+ * @param seed - Seed value (integer)
964
+ * @returns null
965
+ *
966
+ * @example
967
+ * ```ts
968
+ * const seedAndGenerate = East.function([], FloatType, $ => {
969
+ * $(Random.seed(12345n));
970
+ * return Random.uniform(); // Will be reproducible
971
+ * });
972
+ *
973
+ * const compiled = East.compile(seedAndGenerate, Random.Implementation);
974
+ * const result = compiled(); // Same result every time with same seed
975
+ * ```
976
+ *
977
+ * @remarks
978
+ * IMPORTANT: Seeding switches from cryptographically secure random to a deterministic
979
+ * PRNG (xorshift128+). Essential for reproducible simulations. A seed gives the
980
+ * sequence east-node-std gives for it.
981
+ */
982
+ seed: random_seed,
983
+ /**
984
+ * Browser implementation of random platform functions.
985
+ *
986
+ * Pass this to {@link East.compile} to enable random operations.
987
+ */
988
+ Implementation: RandomImpl,
989
+ };
990
+ // Exported beside `Random.Implementation`, as east-node-std exports them
991
+ export { RandomImpl, XorShift128RNG };
992
+ //# sourceMappingURL=random.js.map