@danielsimonjr/mathts-core 0.18.1 → 0.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/README.md +30 -5
  2. package/dist/collection.d.ts +35 -23
  3. package/dist/collection.d.ts.map +1 -1
  4. package/dist/index.d.ts +3 -1
  5. package/dist/index.d.ts.map +1 -1
  6. package/dist/index.js +1348 -1534
  7. package/dist/internal.d.ts +3 -2
  8. package/dist/internal.d.ts.map +1 -1
  9. package/dist/internal.js +1021 -1514
  10. package/dist/numeric/rng.d.ts +88 -0
  11. package/dist/numeric/rng.d.ts.map +1 -0
  12. package/dist/numeric/strides.d.ts +18 -0
  13. package/dist/numeric/strides.d.ts.map +1 -0
  14. package/dist/object.d.ts +20 -2
  15. package/dist/object.d.ts.map +1 -1
  16. package/dist/shared.d.ts +19 -0
  17. package/dist/shared.d.ts.map +1 -1
  18. package/dist/switch.d.ts +2 -4
  19. package/dist/switch.d.ts.map +1 -1
  20. package/dist/types/bignumber.d.ts +7 -0
  21. package/dist/types/bignumber.d.ts.map +1 -1
  22. package/dist/types/complex.d.ts +20 -18
  23. package/dist/types/complex.d.ts.map +1 -1
  24. package/dist/types/fraction.d.ts +5 -0
  25. package/dist/types/fraction.d.ts.map +1 -1
  26. package/dist/types/si-dimension-vector.d.ts +62 -7
  27. package/dist/types/si-dimension-vector.d.ts.map +1 -1
  28. package/dist/types/unit/Unit.d.ts.map +1 -1
  29. package/dist/types/unit/index.d.ts +1 -1
  30. package/dist/types/unit/index.d.ts.map +1 -1
  31. package/dist/types/unit/unit-table.d.ts +8 -2
  32. package/dist/types/unit/unit-table.d.ts.map +1 -1
  33. package/dist/types/unit/unit-types.d.ts +10 -0
  34. package/dist/types/unit/unit-types.d.ts.map +1 -1
  35. package/dist/types/unit.d.ts +1 -1
  36. package/dist/types/unit.d.ts.map +1 -1
  37. package/dist/unit-Dul_E1rh.js +5946 -0
  38. package/dist/wasm-as-header.d.ts +17 -0
  39. package/dist/wasm-as-header.d.ts.map +1 -0
  40. package/dist/wasm-loader.d.ts +33 -1
  41. package/dist/wasm-loader.d.ts.map +1 -1
  42. package/package.json +6 -5
  43. package/dist/chunk-36FOYJAP.js +0 -6091
package/dist/internal.js CHANGED
@@ -1,1640 +1,1147 @@
1
- import {
2
- DEFAULT_CONFIG,
3
- MathjsError,
4
- Unit,
5
- acosh,
6
- asinh,
7
- assertDependencies,
8
- atanh,
9
- canDefineProperty,
10
- cbrt,
11
- clone,
12
- copysign,
13
- cosh,
14
- create,
15
- createUnitClass,
16
- deepExtend,
17
- deepFlatten,
18
- deepStrictEqual,
19
- digits,
20
- endsWith,
21
- expm1,
22
- extend,
23
- factory,
24
- format,
25
- get,
26
- hasOwnProperty,
27
- isArray,
28
- isBigInt,
29
- isBigNumber,
30
- isBoolean,
31
- isCollection,
32
- isComplex,
33
- isDate,
34
- isDenseMatrix,
35
- isFactory,
36
- isFraction,
37
- isFunction,
38
- isIndex,
39
- isInteger,
40
- isLegacyFactory,
41
- isMap,
42
- isMatrix,
43
- isNull,
44
- isNumber,
45
- isObject,
46
- isOptionalDependency,
47
- isPowZeroAtInfinity,
48
- isRange,
49
- isRegExp,
50
- isSparseMatrix,
51
- isString,
52
- isUndefined,
53
- isUnit,
54
- lazy,
55
- log10,
56
- log1p,
57
- log2,
58
- mapObject,
59
- memoize,
60
- nearlyEqual,
61
- normalizeFormatOptions,
62
- pick,
63
- pickShallow,
64
- roundDigits,
65
- safeNumberType,
66
- set,
67
- sign,
68
- sinh,
69
- sortFactories,
70
- splitNumber,
71
- stripOptionalNotation,
72
- tanh,
73
- toEngineering,
74
- toExponential,
75
- toFixed,
76
- toPrecision,
77
- traverse,
78
- typeOf,
79
- unitDependencies,
80
- warnOnce
81
- } from "./chunk-36FOYJAP.js";
82
-
83
- // src/error/DimensionError.ts
84
- var DimensionError = class _DimensionError extends RangeError {
85
- actual;
86
- expected;
87
- relation;
88
- isDimensionError = true;
89
- /**
90
- * Create a DimensionError. When `actual` is a string and `expected` is not given, the string is the message.
91
- *
92
- * @param actual - The actual size or custom error message
93
- * @param expected - The expected size (optional if actual is a custom message)
94
- * @param relation - Optional relation between actual and expected size: '!=', '<', etc.
95
- */
96
- constructor(actual, expected, relation) {
97
- let message;
98
- if (typeof actual === "string" && expected === void 0) {
99
- message = actual;
100
- } else {
101
- message = "Dimension mismatch (" + (Array.isArray(actual) ? "[" + actual.join(", ") + "]" : actual) + " " + (relation || "!=") + " " + (Array.isArray(expected) ? "[" + expected.join(", ") + "]" : expected) + ")";
102
- }
103
- super(message);
104
- this.name = "DimensionError";
105
- if (typeof actual === "string" && expected === void 0) {
106
- this.actual = void 0;
107
- this.expected = void 0;
108
- this.relation = void 0;
109
- } else {
110
- this.actual = actual;
111
- this.expected = expected;
112
- this.relation = relation;
113
- }
114
- const ErrorWithCapture = Error;
115
- if (ErrorWithCapture.captureStackTrace) {
116
- ErrorWithCapture.captureStackTrace(this, _DimensionError);
117
- }
118
- }
1
+ import { $t as log1p, An as isRegExp, At as isLegacyFactory, Bt as warnOnce, Cn as isIndex, Ct as canDefineProperty, Dn as isNumber, Dt as deepStrictEqual, En as isNull, Et as deepFlatten, Fn as typeOf, Ft as set, Gt as copysign, Ht as asinh, It as traverse, Jt as expm1, Kt as cosh, Lt as endsWith, Mn as isString, Mt as mapObject, Nn as isUndefined, Nt as pick, On as isObject, Ot as extend, Pn as isUnit, Pt as pickShallow, Qt as log10, Rt as hasOwnProperty, Sn as isFunction, St as MathjsError, Tn as isMatrix, Tt as deepExtend, Ut as atanh, Vt as acosh, Wt as cbrt, X as DEFAULT_CONFIG, Xt as isInteger, Yt as format, Zt as isPowZeroAtInfinity, _n as isCollection, _t as factory, an as sign, bn as isDenseMatrix, bt as sortFactories, cn as tanh, dn as toFixed, en as log2, fn as toPrecision, gn as isBoolean, gt as create, hn as isBigNumber, ht as assertDependencies, in as safeNumberType, jn as isSparseMatrix, jt as lazy, kn as isRange, kt as get, ln as toEngineering, mn as isBigInt, n as unitDependencies, nn as normalizeFormatOptions, on as sinh, pn as isArray, qt as digits, r as createUnitClass, rn as roundDigits, sn as splitNumber, t as Unit, tn as nearlyEqual, un as toExponential, vn as isComplex, vt as isFactory, wn as isMap, wt as clone, xn as isFraction, xt as stripOptionalNotation, yn as isDate, yt as isOptionalDependency, zt as memoize } from "./unit-Dul_E1rh.js";
2
+ //#region src/error/DimensionError.ts
3
+ var DimensionError = class DimensionError extends RangeError {
4
+ actual;
5
+ expected;
6
+ relation;
7
+ isDimensionError = true;
8
+ constructor(actual, expected, relation) {
9
+ let message;
10
+ if (typeof actual === "string" && expected === void 0) message = actual;
11
+ else message = "Dimension mismatch (" + (Array.isArray(actual) ? "[" + actual.join(", ") + "]" : actual) + " " + (relation || "!=") + " " + (Array.isArray(expected) ? "[" + expected.join(", ") + "]" : expected) + ")";
12
+ super(message);
13
+ this.name = "DimensionError";
14
+ if (typeof actual === "string" && expected === void 0) {
15
+ this.actual = void 0;
16
+ this.expected = void 0;
17
+ this.relation = void 0;
18
+ } else {
19
+ this.actual = actual;
20
+ this.expected = expected;
21
+ this.relation = relation;
22
+ }
23
+ const ErrorWithCapture = Error;
24
+ if (ErrorWithCapture.captureStackTrace) ErrorWithCapture.captureStackTrace(this, DimensionError);
25
+ }
119
26
  };
120
-
121
- // src/error/IndexError.ts
122
- var IndexError = class _IndexError extends RangeError {
123
- index;
124
- min;
125
- max;
126
- isIndexError = true;
127
- /**
128
- * Create an IndexError
129
- *
130
- * Can be called in two ways:
131
- * - IndexError(index, max) - assumes min=0
132
- * - IndexError(index, min, max)
133
- *
134
- * @param index The actual index
135
- * @param min Minimum index (included), or max if only 2 args provided
136
- * @param max Maximum index (excluded)
137
- */
138
- constructor(index, min, max) {
139
- let actualMin;
140
- let actualMax;
141
- if (max === void 0) {
142
- actualMin = 0;
143
- actualMax = min;
144
- } else {
145
- actualMin = min;
146
- actualMax = max;
147
- }
148
- let message;
149
- if (actualMin !== void 0 && index < actualMin) {
150
- message = "Index out of range (" + index + " < " + actualMin + ")";
151
- } else if (actualMax !== void 0 && index >= actualMax) {
152
- message = "Index out of range (" + index + " > " + (actualMax - 1) + ")";
153
- } else {
154
- message = "Index out of range (" + index + ")";
155
- }
156
- super(message);
157
- this.index = index;
158
- this.min = actualMin;
159
- this.max = actualMax;
160
- this.name = "IndexError";
161
- const ErrorWithCapture = Error;
162
- if (ErrorWithCapture.captureStackTrace) {
163
- ErrorWithCapture.captureStackTrace(this, _IndexError);
164
- }
165
- }
27
+ //#endregion
28
+ //#region src/error/IndexError.ts
29
+ var IndexError = class IndexError extends RangeError {
30
+ index;
31
+ min;
32
+ max;
33
+ isIndexError = true;
34
+ constructor(index, min, max) {
35
+ let actualMin;
36
+ let actualMax;
37
+ if (max === void 0) {
38
+ actualMin = 0;
39
+ actualMax = min;
40
+ } else {
41
+ actualMin = min;
42
+ actualMax = max;
43
+ }
44
+ let message;
45
+ if (actualMin !== void 0 && index < actualMin) message = "Index out of range (" + index + " < " + actualMin + ")";
46
+ else if (actualMax !== void 0 && index >= actualMax) message = "Index out of range (" + index + " > " + (actualMax - 1) + ")";
47
+ else message = "Index out of range (" + index + ")";
48
+ super(message);
49
+ this.index = index;
50
+ this.min = actualMin;
51
+ this.max = actualMax;
52
+ this.name = "IndexError";
53
+ const ErrorWithCapture = Error;
54
+ if (ErrorWithCapture.captureStackTrace) ErrorWithCapture.captureStackTrace(this, IndexError);
55
+ }
166
56
  };
167
57
  function createIndexError(index, min, max) {
168
- return new IndexError(index, min, max);
58
+ return new IndexError(index, min, max);
169
59
  }
170
-
171
- // src/bignumber-formatter.ts
60
+ //#endregion
61
+ //#region src/bignumber-formatter.ts
172
62
  function ctorOf(n) {
173
- return n.constructor;
63
+ return n.constructor;
174
64
  }
175
65
  function formatBigNumberToBase(n, base, size) {
176
- const BigNumberCtor = ctorOf(n);
177
- const big2 = new BigNumberCtor(2);
178
- let suffix = "";
179
- if (size) {
180
- if (size < 1) {
181
- throw new Error("size must be in greater than 0");
182
- }
183
- if (!isInteger(size)) {
184
- throw new Error("size must be an integer");
185
- }
186
- if (n.greaterThan(big2.pow(size - 1).sub(1)) || n.lessThan(big2.pow(size - 1).mul(-1))) {
187
- throw new Error(`Value must be in range [-2^${size - 1}, 2^${size - 1}-1]`);
188
- }
189
- if (!n.isInteger()) {
190
- throw new Error("Value must be an integer");
191
- }
192
- if (n.lessThan(0)) {
193
- n = n.add(big2.pow(size));
194
- }
195
- suffix = `i${size}`;
196
- }
197
- switch (base) {
198
- case 2:
199
- return `${n.toBinary()}${suffix}`;
200
- case 8:
201
- return `${n.toOctal()}${suffix}`;
202
- case 16:
203
- return `${n.toHexadecimal()}${suffix}`;
204
- default:
205
- throw new Error(`Base ${base} not supported `);
206
- }
207
- }
208
- function format2(value, options) {
209
- const v = value;
210
- if (typeof options === "function") {
211
- return options(value);
212
- }
213
- if (!v.isFinite()) {
214
- return v.isNaN() ? "NaN" : v.gt(0) ? "Infinity" : "-Infinity";
215
- }
216
- const { notation, precision, wordSize } = normalizeFormatOptions(
217
- options
218
- );
219
- switch (notation) {
220
- case "fixed":
221
- return toFixed2(v, precision);
222
- case "exponential":
223
- return toExponential2(v, precision);
224
- case "engineering":
225
- return toEngineering2(v, precision);
226
- case "bin":
227
- return formatBigNumberToBase(v, 2, wordSize);
228
- case "oct":
229
- return formatBigNumberToBase(v, 8, wordSize);
230
- case "hex":
231
- return formatBigNumberToBase(v, 16, wordSize);
232
- case "auto": {
233
- const optionsObj = options;
234
- const lowerExp = isNumber(optionsObj?.lowerExp) || isBigNumber(optionsObj?.lowerExp) ? optionsObj?.lowerExp : -3;
235
- const upperExp = isNumber(optionsObj?.upperExp) || isBigNumber(optionsObj?.upperExp) ? optionsObj?.upperExp : 5;
236
- if (v.isZero()) return "0";
237
- let str;
238
- const rounded = v.toSignificantDigits(precision);
239
- const exp = rounded.e;
240
- let condition;
241
- if (isBigNumber(lowerExp) && isBigNumber(upperExp)) {
242
- const lowerExpBn = lowerExp;
243
- const upperExpBn = upperExp;
244
- condition = !lowerExpBn.greaterThan(exp) && upperExpBn.greaterThan(exp);
245
- } else if (isBigNumber(lowerExp)) {
246
- const lowerExpBn = lowerExp;
247
- const upperExpNum = upperExp;
248
- condition = !lowerExpBn.greaterThan(exp) && exp < upperExpNum;
249
- } else if (isBigNumber(upperExp)) {
250
- const upperExpBn = upperExp;
251
- const lowerExpNum = lowerExp;
252
- condition = exp >= lowerExpNum && upperExpBn.greaterThan(exp);
253
- } else {
254
- const lowerExpNum = lowerExp;
255
- const upperExpNum = upperExp;
256
- condition = exp >= lowerExpNum && exp < upperExpNum;
257
- }
258
- if (condition) {
259
- str = rounded.toFixed();
260
- } else {
261
- str = toExponential2(v, precision);
262
- }
263
- return str.replace(
264
- /((\.\d*?)(0+))($|e)/,
265
- function(_match, _g1, digits2, _g3, e) {
266
- return digits2 !== "." ? digits2 + e : e;
267
- }
268
- );
269
- }
270
- default:
271
- throw new Error(
272
- 'Unknown notation "' + notation + '". Choose "auto", "exponential", "fixed", "bin", "oct", or "hex.'
273
- );
274
- }
275
- }
276
- function toEngineering2(value, precision) {
277
- const e = value.e;
278
- const newExp = e % 3 === 0 ? e : e < 0 ? e - 3 - e % 3 : e - e % 3;
279
- const valueWithoutExp = value.mul(Math.pow(10, -newExp));
280
- let valueStr = valueWithoutExp.toPrecision(precision);
281
- if (valueStr.includes("e")) {
282
- const BigNumberCtor = ctorOf(value);
283
- valueStr = new BigNumberCtor(valueStr).toFixed();
284
- }
285
- return valueStr + "e" + (e >= 0 ? "+" : "") + newExp.toString();
286
- }
287
- function toExponential2(value, precision) {
288
- if (precision !== void 0) {
289
- return value.toExponential(precision - 1);
290
- } else {
291
- return value.toExponential();
292
- }
293
- }
294
- function toFixed2(value, precision) {
295
- return value.toFixed(precision);
296
- }
297
-
298
- // src/string.ts
299
- function format3(value, options) {
300
- const result = _format(value, options);
301
- if (options && typeof options === "object" && "truncate" in options) {
302
- const truncate = options.truncate;
303
- if (typeof truncate === "number" && result.length > truncate) {
304
- return result.substring(0, truncate - 3) + "...";
305
- }
306
- }
307
- return result;
66
+ const big2 = new (ctorOf(n))(2);
67
+ let suffix = "";
68
+ if (size) {
69
+ if (size < 1) throw new Error("size must be in greater than 0");
70
+ if (!isInteger(size)) throw new Error("size must be an integer");
71
+ if (n.greaterThan(big2.pow(size - 1).sub(1)) || n.lessThan(big2.pow(size - 1).mul(-1))) throw new Error(`Value must be in range [-2^${size - 1}, 2^${size - 1}-1]`);
72
+ if (!n.isInteger()) throw new Error("Value must be an integer");
73
+ if (n.lessThan(0)) n = n.add(big2.pow(size));
74
+ suffix = `i${size}`;
75
+ }
76
+ switch (base) {
77
+ case 2: return `${n.toBinary()}${suffix}`;
78
+ case 8: return `${n.toOctal()}${suffix}`;
79
+ case 16: return `${n.toHexadecimal()}${suffix}`;
80
+ default: throw new Error(`Base ${base} not supported `);
81
+ }
82
+ }
83
+ function format$1(value, options) {
84
+ const v = value;
85
+ if (typeof options === "function") return options(value);
86
+ if (!v.isFinite()) return v.isNaN() ? "NaN" : v.gt(0) ? "Infinity" : "-Infinity";
87
+ const { notation, precision, wordSize } = normalizeFormatOptions(options);
88
+ switch (notation) {
89
+ case "fixed": return toFixed$1(v, precision);
90
+ case "exponential": return toExponential$1(v, precision);
91
+ case "engineering": return toEngineering$1(v, precision);
92
+ case "bin": return formatBigNumberToBase(v, 2, wordSize);
93
+ case "oct": return formatBigNumberToBase(v, 8, wordSize);
94
+ case "hex": return formatBigNumberToBase(v, 16, wordSize);
95
+ case "auto": {
96
+ const optionsObj = options;
97
+ const lowerExp = isNumber(optionsObj?.lowerExp) || isBigNumber(optionsObj?.lowerExp) ? optionsObj?.lowerExp : -3;
98
+ const upperExp = isNumber(optionsObj?.upperExp) || isBigNumber(optionsObj?.upperExp) ? optionsObj?.upperExp : 5;
99
+ if (v.isZero()) return "0";
100
+ let str;
101
+ const rounded = v.toSignificantDigits(precision);
102
+ const exp = rounded.e;
103
+ let condition;
104
+ if (isBigNumber(lowerExp) && isBigNumber(upperExp)) {
105
+ const lowerExpBn = lowerExp;
106
+ const upperExpBn = upperExp;
107
+ condition = !lowerExpBn.greaterThan(exp) && upperExpBn.greaterThan(exp);
108
+ } else if (isBigNumber(lowerExp)) {
109
+ const lowerExpBn = lowerExp;
110
+ const upperExpNum = upperExp;
111
+ condition = !lowerExpBn.greaterThan(exp) && exp < upperExpNum;
112
+ } else if (isBigNumber(upperExp)) condition = exp >= lowerExp && upperExp.greaterThan(exp);
113
+ else condition = exp >= lowerExp && exp < upperExp;
114
+ if (condition) str = rounded.toFixed();
115
+ else str = toExponential$1(v, precision);
116
+ return str.replace(/((\.\d*?)(0+))($|e)/, function(_match, _g1, digits, _g3, e) {
117
+ return digits !== "." ? digits + e : e;
118
+ });
119
+ }
120
+ default: throw new Error("Unknown notation \"" + notation + "\". Choose \"auto\", \"exponential\", \"fixed\", \"bin\", \"oct\", or \"hex.");
121
+ }
122
+ }
123
+ function toEngineering$1(value, precision) {
124
+ const e = value.e;
125
+ const newExp = e % 3 === 0 ? e : e < 0 ? e - 3 - e % 3 : e - e % 3;
126
+ let valueStr = value.mul(Math.pow(10, -newExp)).toPrecision(precision);
127
+ if (valueStr.includes("e")) valueStr = new (ctorOf(value))(valueStr).toFixed();
128
+ return valueStr + "e" + (e >= 0 ? "+" : "") + newExp.toString();
129
+ }
130
+ function toExponential$1(value, precision) {
131
+ if (precision !== void 0) return value.toExponential(precision - 1);
132
+ else return value.toExponential();
133
+ }
134
+ function toFixed$1(value, precision) {
135
+ return value.toFixed(precision);
136
+ }
137
+ //#endregion
138
+ //#region src/string.ts
139
+ function format$2(value, options) {
140
+ const result = _format(value, options);
141
+ if (options && typeof options === "object" && "truncate" in options) {
142
+ const truncate = options.truncate;
143
+ if (typeof truncate === "number" && result.length > truncate) return result.substring(0, truncate - 3) + "...";
144
+ }
145
+ return result;
308
146
  }
309
147
  function _format(value, options) {
310
- if (typeof value === "number") {
311
- return format(value, options);
312
- }
313
- if (isBigNumber(value)) {
314
- return format2(value, options);
315
- }
316
- if (looksLikeFraction(value)) {
317
- if (!options || options.fraction !== "decimal") {
318
- const signedNumerator = typeof value.n === "bigint" ? BigInt(value.s) * value.n : value.s * value.n;
319
- return `${signedNumerator}/${value.d}`;
320
- } else {
321
- return value.toString();
322
- }
323
- }
324
- if (Array.isArray(value)) {
325
- return formatArray(value, options);
326
- }
327
- if (isString(value)) {
328
- return stringify(value);
329
- }
330
- if (typeof value === "function") {
331
- const syntax = value.syntax;
332
- return syntax ? String(syntax) : "function";
333
- }
334
- if (value && typeof value === "object") {
335
- const obj = value;
336
- if (typeof obj.format === "function") {
337
- return obj.format(options);
338
- } else if (obj.toString(options) !== {}.toString()) {
339
- return obj.toString(options);
340
- } else {
341
- const entries = Object.keys(obj).map((key) => {
342
- return stringify(key) + ": " + format3(obj[key], options);
343
- });
344
- return "{" + entries.join(", ") + "}";
345
- }
346
- }
347
- return String(value);
148
+ if (typeof value === "number") return format(value, options);
149
+ if (isBigNumber(value)) return format$1(value, options);
150
+ if (looksLikeFraction(value)) {
151
+ if (!options || options.fraction !== "decimal") return `${typeof value.n === "bigint" ? BigInt(value.s) * value.n : value.s * value.n}/${value.d}`;
152
+ else return value.toString();
153
+ }
154
+ if (Array.isArray(value)) return formatArray(value, options);
155
+ if (isString(value)) return stringify(value);
156
+ if (typeof value === "function") {
157
+ const syntax = value.syntax;
158
+ return syntax ? String(syntax) : "function";
159
+ }
160
+ if (value && typeof value === "object") {
161
+ const obj = value;
162
+ if (typeof obj.format === "function") return obj.format(options);
163
+ else if (obj.toString(options) !== {}.toString()) return obj.toString(options);
164
+ else return "{" + Object.keys(obj).map((key) => {
165
+ return stringify(key) + ": " + format$2(obj[key], options);
166
+ }).join(", ") + "}";
167
+ }
168
+ return String(value);
348
169
  }
349
170
  function stringify(value) {
350
- const text = String(value);
351
- let escaped = "";
352
- let i = 0;
353
- while (i < text.length) {
354
- const c = text.charAt(i);
355
- escaped += c in controlCharacters ? controlCharacters[c] : c;
356
- i++;
357
- }
358
- return '"' + escaped + '"';
359
- }
360
- var controlCharacters = {
361
- '"': '\\"',
362
- "\\": "\\\\",
363
- "\b": "\\b",
364
- "\f": "\\f",
365
- "\n": "\\n",
366
- "\r": "\\r",
367
- " ": "\\t"
171
+ const text = String(value);
172
+ let escaped = "";
173
+ let i = 0;
174
+ while (i < text.length) {
175
+ const c = text.charAt(i);
176
+ escaped += c in controlCharacters ? controlCharacters[c] : c;
177
+ i++;
178
+ }
179
+ return "\"" + escaped + "\"";
180
+ }
181
+ const controlCharacters = {
182
+ "\"": "\\\"",
183
+ "\\": "\\\\",
184
+ "\b": "\\b",
185
+ "\f": "\\f",
186
+ "\n": "\\n",
187
+ "\r": "\\r",
188
+ " ": "\\t"
368
189
  };
369
190
  function escape(value) {
370
- let text = String(value);
371
- text = text.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/'/g, "&#39;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
372
- return text;
191
+ let text = String(value);
192
+ text = text.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/'/g, "&#39;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
193
+ return text;
373
194
  }
374
195
  function formatArray(array, options) {
375
- if (Array.isArray(array)) {
376
- let str = "[";
377
- const len = array.length;
378
- for (let i = 0; i < len; i++) {
379
- if (i !== 0) {
380
- str += ", ";
381
- }
382
- str += formatArray(array[i], options);
383
- }
384
- str += "]";
385
- return str;
386
- } else {
387
- return format3(array, options);
388
- }
196
+ if (Array.isArray(array)) {
197
+ let str = "[";
198
+ const len = array.length;
199
+ for (let i = 0; i < len; i++) {
200
+ if (i !== 0) str += ", ";
201
+ str += formatArray(array[i], options);
202
+ }
203
+ str += "]";
204
+ return str;
205
+ } else return format$2(array, options);
389
206
  }
390
207
  function looksLikeFraction(value) {
391
- const frac = value;
392
- return !!frac && typeof frac === "object" && typeof frac.s === "bigint" && typeof frac.n === "bigint" && typeof frac.d === "bigint" || false;
208
+ const frac = value;
209
+ return !!frac && typeof frac === "object" && typeof frac.s === "bigint" && typeof frac.n === "bigint" && typeof frac.d === "bigint" || false;
393
210
  }
394
211
  function compareText(x, y) {
395
- if (!isString(x)) {
396
- throw new TypeError(
397
- "Unexpected type of argument in function compareText (expected: string or Array or Matrix, actual: " + typeOf(x) + ", index: 0)"
398
- );
399
- }
400
- if (!isString(y)) {
401
- throw new TypeError(
402
- "Unexpected type of argument in function compareText (expected: string or Array or Matrix, actual: " + typeOf(y) + ", index: 1)"
403
- );
404
- }
405
- return x === y ? 0 : x > y ? 1 : -1;
406
- }
407
-
408
- // src/array.ts
212
+ if (!isString(x)) throw new TypeError("Unexpected type of argument in function compareText (expected: string or Array or Matrix, actual: " + typeOf(x) + ", index: 0)");
213
+ if (!isString(y)) throw new TypeError("Unexpected type of argument in function compareText (expected: string or Array or Matrix, actual: " + typeOf(y) + ", index: 1)");
214
+ return x === y ? 0 : x > y ? 1 : -1;
215
+ }
216
+ //#endregion
217
+ //#region src/array.ts
409
218
  function arraySize(x) {
410
- const s = [];
411
- let current = x;
412
- while (Array.isArray(current)) {
413
- s.push(current.length);
414
- current = current[0];
415
- }
416
- return s;
219
+ const s = [];
220
+ let current = x;
221
+ while (Array.isArray(current)) {
222
+ s.push(current.length);
223
+ current = current[0];
224
+ }
225
+ return s;
417
226
  }
418
227
  function _validate(array, size, dim) {
419
- let i;
420
- const len = array.length;
421
- if (len !== size[dim]) {
422
- throw new DimensionError(len, size[dim]);
423
- }
424
- if (dim < size.length - 1) {
425
- const dimNext = dim + 1;
426
- for (i = 0; i < len; i++) {
427
- const child = array[i];
428
- if (!Array.isArray(child)) {
429
- throw new DimensionError(size.length - 1, size.length, "<");
430
- }
431
- _validate(array[i], size, dimNext);
432
- }
433
- } else {
434
- for (i = 0; i < len; i++) {
435
- if (Array.isArray(array[i])) {
436
- throw new DimensionError(size.length + 1, size.length, ">");
437
- }
438
- }
439
- }
228
+ let i;
229
+ const len = array.length;
230
+ if (len !== size[dim]) throw new DimensionError(len, size[dim]);
231
+ if (dim < size.length - 1) {
232
+ const dimNext = dim + 1;
233
+ for (i = 0; i < len; i++) {
234
+ const child = array[i];
235
+ if (!Array.isArray(child)) throw new DimensionError(size.length - 1, size.length, "<");
236
+ _validate(array[i], size, dimNext);
237
+ }
238
+ } else for (i = 0; i < len; i++) if (Array.isArray(array[i])) throw new DimensionError(size.length + 1, size.length, ">");
440
239
  }
441
240
  function validate(array, size) {
442
- const isScalar = size.length === 0;
443
- if (isScalar) {
444
- if (Array.isArray(array)) {
445
- throw new DimensionError(array.length, 0);
446
- }
447
- } else {
448
- _validate(array, size, 0);
449
- }
241
+ if (size.length === 0) {
242
+ if (Array.isArray(array)) throw new DimensionError(array.length, 0);
243
+ } else _validate(array, size, 0);
450
244
  }
451
245
  function validateIndexSourceSize(value, index) {
452
- const valueSize = value.isMatrix ? value._size : arraySize(value);
453
- const sourceSize = index._sourceSize;
454
- sourceSize.forEach((sourceDim, i) => {
455
- if (sourceDim !== null && sourceDim !== valueSize[i]) {
456
- throw new DimensionError(sourceDim, valueSize[i]);
457
- }
458
- });
246
+ const valueSize = value.isMatrix ? value._size : arraySize(value);
247
+ index._sourceSize.forEach((sourceDim, i) => {
248
+ if (sourceDim !== null && sourceDim !== valueSize[i]) throw new DimensionError(sourceDim, valueSize[i]);
249
+ });
459
250
  }
460
251
  function validateIndex(index, length) {
461
- if (index !== void 0) {
462
- if (!isNumber(index) || !isInteger(index)) {
463
- throw new TypeError("Index must be an integer (value: " + index + ")");
464
- }
465
- if (index < 0 || typeof length === "number" && index >= length) {
466
- throw new IndexError(index, length);
467
- }
468
- }
252
+ if (index !== void 0) {
253
+ if (!isNumber(index) || !isInteger(index)) throw new TypeError("Index must be an integer (value: " + index + ")");
254
+ if (index < 0 || typeof length === "number" && index >= length) throw new IndexError(index, length);
255
+ }
469
256
  }
470
257
  function isEmptyIndex(index) {
471
- for (let i = 0; i < index._dimensions.length; ++i) {
472
- const dimension = index._dimensions[i];
473
- if (isString(dimension)) {
474
- if (dimension.length === 0) {
475
- return true;
476
- }
477
- } else {
478
- const dim = dimension;
479
- if (dim._data && isArray(dim._data)) {
480
- if (dim._size[0] === 0) {
481
- return true;
482
- }
483
- } else if (dim.isRange) {
484
- if (dim.start === dim.end) {
485
- return true;
486
- }
487
- }
488
- }
489
- }
490
- return false;
258
+ for (let i = 0; i < index._dimensions.length; ++i) {
259
+ const dimension = index._dimensions[i];
260
+ if (isString(dimension)) {
261
+ if (dimension.length === 0) return true;
262
+ } else {
263
+ const dim = dimension;
264
+ if (dim._data && isArray(dim._data)) {
265
+ if (dim._size[0] === 0) return true;
266
+ } else if (dim.isRange) {
267
+ if (dim.start === dim.end) return true;
268
+ }
269
+ }
270
+ }
271
+ return false;
491
272
  }
492
273
  function resize(array, size, defaultValue) {
493
- if (!Array.isArray(size)) {
494
- throw new TypeError("Array expected");
495
- }
496
- if (size.length === 0) {
497
- throw new Error("Resizing to scalar is not supported");
498
- }
499
- size.forEach(function(value) {
500
- if (!isNumber(value) || !isInteger(value) || value < 0) {
501
- throw new TypeError(
502
- "Invalid size, must contain positive integers (size: " + format3(size, {}) + ")"
503
- );
504
- }
505
- });
506
- let arr = array;
507
- if (isNumber(array) || isBigNumber(array)) {
508
- arr = [array];
509
- }
510
- const _defaultValue = defaultValue !== void 0 ? defaultValue : 0;
511
- _resize(arr, size, 0, _defaultValue);
512
- return arr;
274
+ if (!Array.isArray(size)) throw new TypeError("Array expected");
275
+ if (size.length === 0) throw new Error("Resizing to scalar is not supported");
276
+ size.forEach(function(value) {
277
+ if (!isNumber(value) || !isInteger(value) || value < 0) throw new TypeError("Invalid size, must contain positive integers (size: " + format$2(size, {}) + ")");
278
+ });
279
+ let arr = array;
280
+ if (isNumber(array) || isBigNumber(array)) arr = [array];
281
+ _resize(arr, size, 0, defaultValue !== void 0 ? defaultValue : 0);
282
+ return arr;
513
283
  }
514
284
  function _resize(array, size, dim, defaultValue) {
515
- let i;
516
- let elem;
517
- const oldLen = array.length;
518
- const newLen = size[dim];
519
- const minLen = Math.min(oldLen, newLen);
520
- array.length = newLen;
521
- if (dim < size.length - 1) {
522
- const dimNext = dim + 1;
523
- for (i = 0; i < minLen; i++) {
524
- let current = array[i];
525
- if (!Array.isArray(current)) {
526
- current = [current];
527
- array[i] = current;
528
- }
529
- _resize(current, size, dimNext, defaultValue);
530
- }
531
- for (i = minLen; i < newLen; i++) {
532
- elem = [];
533
- array[i] = elem;
534
- _resize(elem, size, dimNext, defaultValue);
535
- }
536
- } else {
537
- for (i = 0; i < minLen; i++) {
538
- let value = array[i];
539
- while (Array.isArray(value)) {
540
- value = value[0];
541
- }
542
- array[i] = value;
543
- }
544
- for (i = minLen; i < newLen; i++) {
545
- array[i] = defaultValue;
546
- }
547
- }
285
+ let i;
286
+ let elem;
287
+ const oldLen = array.length;
288
+ const newLen = size[dim];
289
+ const minLen = Math.min(oldLen, newLen);
290
+ array.length = newLen;
291
+ if (dim < size.length - 1) {
292
+ const dimNext = dim + 1;
293
+ for (i = 0; i < minLen; i++) {
294
+ let current = array[i];
295
+ if (!Array.isArray(current)) {
296
+ current = [current];
297
+ array[i] = current;
298
+ }
299
+ _resize(current, size, dimNext, defaultValue);
300
+ }
301
+ for (i = minLen; i < newLen; i++) {
302
+ elem = [];
303
+ array[i] = elem;
304
+ _resize(elem, size, dimNext, defaultValue);
305
+ }
306
+ } else {
307
+ for (i = 0; i < minLen; i++) {
308
+ let value = array[i];
309
+ while (Array.isArray(value)) value = value[0];
310
+ array[i] = value;
311
+ }
312
+ for (i = minLen; i < newLen; i++) array[i] = defaultValue;
313
+ }
548
314
  }
549
315
  function reshape(array, sizes) {
550
- const flatArray = flatten(array, true);
551
- const currentLength = flatArray.length;
552
- if (!Array.isArray(array) || !Array.isArray(sizes)) {
553
- throw new TypeError("Array expected");
554
- }
555
- if (sizes.length === 0) {
556
- throw new DimensionError(0, currentLength, "!=");
557
- }
558
- const processedSizes = processSizesWildcard(sizes, currentLength);
559
- const newLength = product(processedSizes);
560
- if (currentLength !== newLength) {
561
- throw new DimensionError(newLength, currentLength, "!=");
562
- }
563
- try {
564
- return _reshape(flatArray, processedSizes);
565
- } catch (e) {
566
- if (e instanceof DimensionError) {
567
- const dimErr = new DimensionError(newLength, currentLength, "!=");
568
- dimErr.cause = e;
569
- throw dimErr;
570
- }
571
- throw e;
572
- }
316
+ const flatArray = flatten(array, true);
317
+ const currentLength = flatArray.length;
318
+ if (!Array.isArray(array) || !Array.isArray(sizes)) throw new TypeError("Array expected");
319
+ if (sizes.length === 0) throw new DimensionError(0, currentLength, "!=");
320
+ const processedSizes = processSizesWildcard(sizes, currentLength);
321
+ const newLength = product(processedSizes);
322
+ if (currentLength !== newLength) throw new DimensionError(newLength, currentLength, "!=");
323
+ try {
324
+ return _reshape(flatArray, processedSizes);
325
+ } catch (e) {
326
+ if (e instanceof DimensionError) {
327
+ const dimErr = new DimensionError(newLength, currentLength, "!=");
328
+ dimErr.cause = e;
329
+ throw dimErr;
330
+ }
331
+ throw e;
332
+ }
573
333
  }
574
334
  function processSizesWildcard(sizes, currentLength) {
575
- const newLength = product(sizes);
576
- const processedSizes = sizes.slice();
577
- const WILDCARD = -1;
578
- const wildCardIndex = sizes.indexOf(WILDCARD);
579
- const isMoreThanOneWildcard = sizes.indexOf(WILDCARD, wildCardIndex + 1) >= 0;
580
- if (isMoreThanOneWildcard) {
581
- throw new Error("More than one wildcard in sizes");
582
- }
583
- const hasWildcard = wildCardIndex >= 0;
584
- const canReplaceWildcard = currentLength % newLength === 0;
585
- if (hasWildcard) {
586
- if (canReplaceWildcard) {
587
- processedSizes[wildCardIndex] = -currentLength / newLength;
588
- } else {
589
- throw new Error(
590
- "Could not replace wildcard, since " + currentLength + " is no multiple of " + -newLength
591
- );
592
- }
593
- }
594
- return processedSizes;
335
+ const newLength = product(sizes);
336
+ const processedSizes = sizes.slice();
337
+ const WILDCARD = -1;
338
+ const wildCardIndex = sizes.indexOf(WILDCARD);
339
+ if (sizes.indexOf(WILDCARD, wildCardIndex + 1) >= 0) throw new Error("More than one wildcard in sizes");
340
+ const hasWildcard = wildCardIndex >= 0;
341
+ const canReplaceWildcard = currentLength % newLength === 0;
342
+ if (hasWildcard) {
343
+ if (canReplaceWildcard) processedSizes[wildCardIndex] = -currentLength / newLength;
344
+ else throw new Error("Could not replace wildcard, since " + currentLength + " is no multiple of " + -newLength);
345
+ }
346
+ return processedSizes;
595
347
  }
596
348
  function product(array) {
597
- return array.reduce((prev, curr) => prev * curr, 1);
349
+ return array.reduce((prev, curr) => prev * curr, 1);
598
350
  }
599
351
  function _reshape(array, sizes) {
600
- let tmpArray = array;
601
- let tmpArray2;
602
- for (let sizeIndex = sizes.length - 1; sizeIndex > 0; sizeIndex--) {
603
- const size = sizes[sizeIndex];
604
- tmpArray2 = [];
605
- const length = tmpArray.length / size;
606
- for (let i = 0; i < length; i++) {
607
- tmpArray2.push(tmpArray.slice(i * size, (i + 1) * size));
608
- }
609
- tmpArray = tmpArray2;
610
- }
611
- return tmpArray;
352
+ let tmpArray = array;
353
+ let tmpArray2;
354
+ for (let sizeIndex = sizes.length - 1; sizeIndex > 0; sizeIndex--) {
355
+ const size = sizes[sizeIndex];
356
+ tmpArray2 = [];
357
+ const length = tmpArray.length / size;
358
+ for (let i = 0; i < length; i++) tmpArray2.push(tmpArray.slice(i * size, (i + 1) * size));
359
+ tmpArray = tmpArray2;
360
+ }
361
+ return tmpArray;
612
362
  }
613
363
  function squeeze(array, size) {
614
- const s = size || arraySize(array);
615
- let arr = array;
616
- while (Array.isArray(arr) && arr.length === 1) {
617
- arr = arr[0];
618
- s.shift();
619
- }
620
- let dims = s.length;
621
- while (s[dims - 1] === 1) {
622
- dims--;
623
- }
624
- if (dims < s.length) {
625
- arr = _squeeze(arr, dims, 0);
626
- s.length = dims;
627
- }
628
- return arr;
364
+ const s = size || arraySize(array);
365
+ let arr = array;
366
+ while (Array.isArray(arr) && arr.length === 1) {
367
+ arr = arr[0];
368
+ s.shift();
369
+ }
370
+ let dims = s.length;
371
+ while (s[dims - 1] === 1) dims--;
372
+ if (dims < s.length) {
373
+ arr = _squeeze(arr, dims, 0);
374
+ s.length = dims;
375
+ }
376
+ return arr;
629
377
  }
630
378
  function _squeeze(array, dims, dim) {
631
- if (dim < dims) {
632
- const next = dim + 1;
633
- const arr = array;
634
- for (let i = 0, ii = arr.length; i < ii; i++) {
635
- arr[i] = _squeeze(arr[i], dims, next);
636
- }
637
- return arr;
638
- } else {
639
- let result = array;
640
- while (Array.isArray(result)) {
641
- result = result[0];
642
- }
643
- return result;
644
- }
379
+ if (dim < dims) {
380
+ const next = dim + 1;
381
+ const arr = array;
382
+ for (let i = 0, ii = arr.length; i < ii; i++) arr[i] = _squeeze(arr[i], dims, next);
383
+ return arr;
384
+ } else {
385
+ let result = array;
386
+ while (Array.isArray(result)) result = result[0];
387
+ return result;
388
+ }
645
389
  }
646
390
  function unsqueeze(array, dims, outer, size) {
647
- const s = size || arraySize(array);
648
- let arr = array;
649
- if (outer) {
650
- for (let i = 0; i < outer; i++) {
651
- arr = [arr];
652
- s.unshift(1);
653
- }
654
- }
655
- arr = _unsqueeze(arr, dims, 0);
656
- while (s.length < dims) {
657
- s.push(1);
658
- }
659
- return arr;
391
+ const s = size || arraySize(array);
392
+ let arr = array;
393
+ if (outer) for (let i = 0; i < outer; i++) {
394
+ arr = [arr];
395
+ s.unshift(1);
396
+ }
397
+ arr = _unsqueeze(arr, dims, 0);
398
+ while (s.length < dims) s.push(1);
399
+ return arr;
660
400
  }
661
401
  function _unsqueeze(array, dims, dim) {
662
- if (Array.isArray(array)) {
663
- const next = dim + 1;
664
- const arr = array;
665
- for (let i = 0, ii = arr.length; i < ii; i++) {
666
- arr[i] = _unsqueeze(arr[i], dims, next);
667
- }
668
- return arr;
669
- } else {
670
- let result = array;
671
- for (let d = dim; d < dims; d++) {
672
- result = [result];
673
- }
674
- return result;
675
- }
402
+ if (Array.isArray(array)) {
403
+ const next = dim + 1;
404
+ const arr = array;
405
+ for (let i = 0, ii = arr.length; i < ii; i++) arr[i] = _unsqueeze(arr[i], dims, next);
406
+ return arr;
407
+ } else {
408
+ let result = array;
409
+ for (let d = dim; d < dims; d++) result = [result];
410
+ return result;
411
+ }
676
412
  }
677
413
  function flatten(array, isRectangular = false) {
678
- if (!Array.isArray(array)) {
679
- return array;
680
- }
681
- if (typeof isRectangular !== "boolean") {
682
- throw new TypeError("Boolean expected for second argument of flatten");
683
- }
684
- const flat = [];
685
- if (isRectangular) {
686
- _flattenRectangular(array);
687
- } else {
688
- _flatten(array);
689
- }
690
- return flat;
691
- function _flatten(arr) {
692
- for (let i = 0; i < arr.length; i++) {
693
- const item = arr[i];
694
- if (Array.isArray(item)) {
695
- _flatten(item);
696
- } else {
697
- flat.push(item);
698
- }
699
- }
700
- }
701
- function _flattenRectangular(arr) {
702
- if (Array.isArray(arr[0])) {
703
- for (let i = 0; i < arr.length; i++) {
704
- _flattenRectangular(arr[i]);
705
- }
706
- } else {
707
- for (let i = 0; i < arr.length; i++) {
708
- flat.push(arr[i]);
709
- }
710
- }
711
- }
414
+ if (!Array.isArray(array)) return array;
415
+ if (typeof isRectangular !== "boolean") throw new TypeError("Boolean expected for second argument of flatten");
416
+ const flat = [];
417
+ if (isRectangular) _flattenRectangular(array);
418
+ else _flatten(array);
419
+ return flat;
420
+ function _flatten(arr) {
421
+ for (let i = 0; i < arr.length; i++) {
422
+ const item = arr[i];
423
+ if (Array.isArray(item)) _flatten(item);
424
+ else flat.push(item);
425
+ }
426
+ }
427
+ function _flattenRectangular(arr) {
428
+ if (Array.isArray(arr[0])) for (let i = 0; i < arr.length; i++) _flattenRectangular(arr[i]);
429
+ else for (let i = 0; i < arr.length; i++) flat.push(arr[i]);
430
+ }
712
431
  }
713
432
  function map(array, callback) {
714
- return Array.prototype.map.call(array, callback);
433
+ return Array.prototype.map.call(array, callback);
715
434
  }
716
435
  function forEach(array, callback) {
717
- Array.prototype.forEach.call(array, callback);
436
+ Array.prototype.forEach.call(array, callback);
718
437
  }
719
438
  function filter(array, callback) {
720
- if (arraySize(array).length !== 1) {
721
- throw new Error("Only one dimensional matrices supported");
722
- }
723
- return Array.prototype.filter.call(array, callback);
439
+ if (arraySize(array).length !== 1) throw new Error("Only one dimensional matrices supported");
440
+ return Array.prototype.filter.call(array, callback);
724
441
  }
725
442
  function filterRegExp(array, regexp) {
726
- if (arraySize(array).length !== 1) {
727
- throw new Error("Only one dimensional matrices supported");
728
- }
729
- return Array.prototype.filter.call(array, (entry) => regexp.test(entry));
443
+ if (arraySize(array).length !== 1) throw new Error("Only one dimensional matrices supported");
444
+ return Array.prototype.filter.call(array, (entry) => regexp.test(entry));
730
445
  }
731
446
  function join(array, separator) {
732
- return Array.prototype.join.call(array, separator);
447
+ return Array.prototype.join.call(array, separator);
733
448
  }
734
449
  function identify(a) {
735
- if (!Array.isArray(a)) {
736
- throw new TypeError("Array input expected");
737
- }
738
- if (a.length === 0) {
739
- return [];
740
- }
741
- const b = [];
742
- let count = 0;
743
- b[0] = { value: a[0], identifier: 0 };
744
- for (let i = 1; i < a.length; i++) {
745
- if (a[i] === a[i - 1]) {
746
- count++;
747
- } else {
748
- count = 0;
749
- }
750
- b.push({ value: a[i], identifier: count });
751
- }
752
- return b;
450
+ if (!Array.isArray(a)) throw new TypeError("Array input expected");
451
+ if (a.length === 0) return [];
452
+ const b = [];
453
+ let count = 0;
454
+ b[0] = {
455
+ value: a[0],
456
+ identifier: 0
457
+ };
458
+ for (let i = 1; i < a.length; i++) {
459
+ if (a[i] === a[i - 1]) count++;
460
+ else count = 0;
461
+ b.push({
462
+ value: a[i],
463
+ identifier: count
464
+ });
465
+ }
466
+ return b;
753
467
  }
754
468
  function generalize(a) {
755
- if (!Array.isArray(a)) {
756
- throw new TypeError("Array input expected");
757
- }
758
- if (a.length === 0) {
759
- return [];
760
- }
761
- const b = [];
762
- for (let i = 0; i < a.length; i++) {
763
- b.push(a[i].value);
764
- }
765
- return b;
766
- }
767
- function getArrayDataType(array, typeOf2) {
768
- let type;
769
- let length = 0;
770
- for (let i = 0; i < array.length; i++) {
771
- const item = array[i];
772
- const isArray2 = Array.isArray(item);
773
- if (i === 0 && isArray2) {
774
- length = item.length;
775
- }
776
- if (isArray2 && item.length !== length) {
777
- return void 0;
778
- }
779
- const itemType = isArray2 ? getArrayDataType(item, typeOf2) : typeOf2(item);
780
- if (type === void 0) {
781
- type = itemType;
782
- } else if (type !== itemType) {
783
- return "mixed";
784
- } else {
785
- }
786
- }
787
- return type;
469
+ if (!Array.isArray(a)) throw new TypeError("Array input expected");
470
+ if (a.length === 0) return [];
471
+ const b = [];
472
+ for (let i = 0; i < a.length; i++) b.push(a[i].value);
473
+ return b;
474
+ }
475
+ function getArrayDataType(array, typeOf) {
476
+ let type;
477
+ let length = 0;
478
+ for (let i = 0; i < array.length; i++) {
479
+ const item = array[i];
480
+ const isArray = Array.isArray(item);
481
+ if (i === 0 && isArray) length = item.length;
482
+ if (isArray && item.length !== length) return;
483
+ const itemType = isArray ? getArrayDataType(item, typeOf) : typeOf(item);
484
+ if (type === void 0) type = itemType;
485
+ else if (type !== itemType) return "mixed";
486
+ }
487
+ return type;
788
488
  }
789
489
  function last(array) {
790
- return array[array.length - 1];
490
+ return array[array.length - 1];
791
491
  }
792
492
  function initial(array) {
793
- return array.slice(0, array.length - 1);
493
+ return array.slice(0, array.length - 1);
794
494
  }
795
495
  function concatRecursive(a, b, concatDim, dim) {
796
- if (dim < concatDim) {
797
- if (a.length !== b.length) {
798
- throw new DimensionError(a.length, b.length);
799
- }
800
- const c = [];
801
- for (let i = 0; i < a.length; i++) {
802
- c[i] = concatRecursive(
803
- a[i],
804
- b[i],
805
- concatDim,
806
- dim + 1
807
- );
808
- }
809
- return c;
810
- } else {
811
- return a.concat(b);
812
- }
496
+ if (dim < concatDim) {
497
+ if (a.length !== b.length) throw new DimensionError(a.length, b.length);
498
+ const c = [];
499
+ for (let i = 0; i < a.length; i++) c[i] = concatRecursive(a[i], b[i], concatDim, dim + 1);
500
+ return c;
501
+ } else return a.concat(b);
813
502
  }
814
503
  function concat(...args) {
815
- const arrays = Array.prototype.slice.call(args, 0, -1);
816
- const concatDim = Array.prototype.slice.call(args, -1)[0];
817
- if (arrays.length === 1) {
818
- return arrays[0];
819
- }
820
- if (arrays.length > 1) {
821
- return arrays.slice(1).reduce(function(A, B) {
822
- return concatRecursive(A, B, concatDim, 0);
823
- }, arrays[0]);
824
- } else {
825
- throw new Error("Wrong number of arguments in function concat");
826
- }
504
+ const arrays = Array.prototype.slice.call(args, 0, -1);
505
+ const concatDim = Array.prototype.slice.call(args, -1)[0];
506
+ if (arrays.length === 1) return arrays[0];
507
+ if (arrays.length > 1) return arrays.slice(1).reduce(function(A, B) {
508
+ return concatRecursive(A, B, concatDim, 0);
509
+ }, arrays[0]);
510
+ else throw new Error("Wrong number of arguments in function concat");
827
511
  }
828
512
  function broadcastSizes(...sizes) {
829
- const dimensions = sizes.map((s) => s.length);
830
- const N = Math.max(...dimensions);
831
- const sizeMax = new Array(N).fill(null);
832
- for (let i = 0; i < sizes.length; i++) {
833
- const size = sizes[i];
834
- const dim = dimensions[i];
835
- for (let j = 0; j < dim; j++) {
836
- const n = N - dim + j;
837
- if (size[j] > sizeMax[n]) {
838
- sizeMax[n] = size[j];
839
- }
840
- }
841
- }
842
- for (let i = 0; i < sizes.length; i++) {
843
- checkBroadcastingRules(sizes[i], sizeMax);
844
- }
845
- return sizeMax;
513
+ const dimensions = sizes.map((s) => s.length);
514
+ const N = Math.max(...dimensions);
515
+ const sizeMax = new Array(N).fill(null);
516
+ for (let i = 0; i < sizes.length; i++) {
517
+ const size = sizes[i];
518
+ const dim = dimensions[i];
519
+ for (let j = 0; j < dim; j++) {
520
+ const n = N - dim + j;
521
+ if (size[j] > sizeMax[n]) sizeMax[n] = size[j];
522
+ }
523
+ }
524
+ for (let i = 0; i < sizes.length; i++) checkBroadcastingRules(sizes[i], sizeMax);
525
+ return sizeMax;
846
526
  }
847
527
  function checkBroadcastingRules(size, toSize) {
848
- const N = toSize.length;
849
- const dim = size.length;
850
- for (let j = 0; j < dim; j++) {
851
- const n = N - dim + j;
852
- if (size[j] < toSize[n] && size[j] > 1 || size[j] > toSize[n]) {
853
- throw new Error(
854
- `shape mismatch: mismatch is found in arg with shape (${size}) not possible to broadcast dimension ${dim} with size ${size[j]} to size ${toSize[n]}`
855
- );
856
- }
857
- }
528
+ const N = toSize.length;
529
+ const dim = size.length;
530
+ for (let j = 0; j < dim; j++) {
531
+ const n = N - dim + j;
532
+ if (size[j] < toSize[n] && size[j] > 1 || size[j] > toSize[n]) throw new Error(`shape mismatch: mismatch is found in arg with shape (${size}) not possible to broadcast dimension ${dim} with size ${size[j]} to size ${toSize[n]}`);
533
+ }
858
534
  }
859
535
  function broadcastTo(array, toSize) {
860
- let Asize = arraySize(array);
861
- if (deepStrictEqual(Asize, toSize)) {
862
- return array;
863
- }
864
- checkBroadcastingRules(Asize, toSize);
865
- const broadcastedSize = broadcastSizes(Asize, toSize);
866
- const N = broadcastedSize.length;
867
- const paddedSize = [...Array(N - Asize.length).fill(1), ...Asize];
868
- let A = clone2(array);
869
- if (Asize.length < N) {
870
- A = reshape(A, paddedSize);
871
- Asize = arraySize(A);
872
- }
873
- for (let dim = 0; dim < N; dim++) {
874
- if (Asize[dim] < broadcastedSize[dim]) {
875
- A = stretch(A, broadcastedSize[dim], dim);
876
- Asize = arraySize(A);
877
- }
878
- }
879
- return A;
536
+ let Asize = arraySize(array);
537
+ if (deepStrictEqual(Asize, toSize)) return array;
538
+ checkBroadcastingRules(Asize, toSize);
539
+ const broadcastedSize = broadcastSizes(Asize, toSize);
540
+ const N = broadcastedSize.length;
541
+ const paddedSize = [...Array(N - Asize.length).fill(1), ...Asize];
542
+ let A = clone$1(array);
543
+ if (Asize.length < N) {
544
+ A = reshape(A, paddedSize);
545
+ Asize = arraySize(A);
546
+ }
547
+ for (let dim = 0; dim < N; dim++) if (Asize[dim] < broadcastedSize[dim]) {
548
+ A = stretch(A, broadcastedSize[dim], dim);
549
+ Asize = arraySize(A);
550
+ }
551
+ return A;
880
552
  }
881
553
  function broadcastArrays(...arrays) {
882
- if (arrays.length === 0) {
883
- throw new Error("Insufficient number of arguments in function broadcastArrays");
884
- }
885
- if (arrays.length === 1) {
886
- return arrays[0];
887
- }
888
- const sizes = arrays.map(function(array) {
889
- return arraySize(array);
890
- });
891
- const broadcastedSize = broadcastSizes(...sizes);
892
- const broadcastedArrays = [];
893
- arrays.forEach(function(array) {
894
- broadcastedArrays.push(broadcastTo(array, broadcastedSize));
895
- });
896
- return broadcastedArrays;
554
+ if (arrays.length === 0) throw new Error("Insufficient number of arguments in function broadcastArrays");
555
+ if (arrays.length === 1) return arrays[0];
556
+ const broadcastedSize = broadcastSizes(...arrays.map(function(array) {
557
+ return arraySize(array);
558
+ }));
559
+ const broadcastedArrays = [];
560
+ arrays.forEach(function(array) {
561
+ broadcastedArrays.push(broadcastTo(array, broadcastedSize));
562
+ });
563
+ return broadcastedArrays;
897
564
  }
898
565
  function stretch(arrayToStretch, sizeToStretch, dimToStretch) {
899
- return concat(...Array(sizeToStretch).fill(arrayToStretch), dimToStretch);
900
- }
901
- function get2(array, index) {
902
- if (!Array.isArray(array)) {
903
- throw new Error("Array expected");
904
- }
905
- const size = arraySize(array);
906
- if (index.length !== size.length) {
907
- throw new DimensionError(index.length, size.length);
908
- }
909
- for (let x = 0; x < index.length; x++) {
910
- validateIndex(index[x], size[x]);
911
- }
912
- return index.reduce((acc, curr) => acc[curr], array);
913
- }
914
- function deepMap(array, callback, skipIndex = false) {
915
- if (Array.isArray(array) && array.length === 0) {
916
- return [];
917
- }
918
- if (skipIndex) {
919
- return recursiveMap(array);
920
- }
921
- const index = [];
922
- return recursiveMapWithIndex(array, 0);
923
- function recursiveMapWithIndex(value, depth) {
924
- if (Array.isArray(value)) {
925
- const N = value.length;
926
- const result = Array(N);
927
- for (let i = 0; i < N; i++) {
928
- index[depth] = i;
929
- result[i] = recursiveMapWithIndex(value[i], depth + 1);
930
- }
931
- return result;
932
- } else {
933
- return callback(
934
- value,
935
- index.slice(0, depth),
936
- array
937
- );
938
- }
939
- }
940
- function recursiveMap(value) {
941
- if (Array.isArray(value)) {
942
- const N = value.length;
943
- const result = Array(N);
944
- for (let i = 0; i < N; i++) {
945
- result[i] = recursiveMap(value[i]);
946
- }
947
- return result;
948
- } else {
949
- return callback(value);
950
- }
951
- }
952
- }
953
- function deepForEach(array, callback, skipIndex = false) {
954
- if (Array.isArray(array) && array.length === 0) {
955
- return;
956
- }
957
- if (skipIndex) {
958
- recursiveForEach(array);
959
- return;
960
- }
961
- const index = [];
962
- recursiveForEachWithIndex(array, 0);
963
- function recursiveForEachWithIndex(value, depth) {
964
- if (Array.isArray(value)) {
965
- const N = value.length;
966
- for (let i = 0; i < N; i++) {
967
- index[depth] = i;
968
- recursiveForEachWithIndex(value[i], depth + 1);
969
- }
970
- } else {
971
- callback(
972
- value,
973
- index.slice(0, depth),
974
- array
975
- );
976
- }
977
- }
978
- function recursiveForEach(value) {
979
- if (Array.isArray(value)) {
980
- const N = value.length;
981
- for (let i = 0; i < N; i++) {
982
- recursiveForEach(value[i]);
983
- }
984
- } else {
985
- callback(value);
986
- }
987
- }
988
- }
989
- function clone2(array) {
990
- return Object.assign([], array);
991
- }
992
-
993
- // src/switch.ts
566
+ return concat(...Array(sizeToStretch).fill(arrayToStretch), dimToStretch);
567
+ }
568
+ function get$1(array, index) {
569
+ if (!Array.isArray(array)) throw new Error("Array expected");
570
+ const size = arraySize(array);
571
+ if (index.length !== size.length) throw new DimensionError(index.length, size.length);
572
+ for (let x = 0; x < index.length; x++) validateIndex(index[x], size[x]);
573
+ return index.reduce((acc, curr) => acc[curr], array);
574
+ }
575
+ function deepMap$1(array, callback, skipIndex = false) {
576
+ if (Array.isArray(array) && array.length === 0) return [];
577
+ if (skipIndex) return recursiveMap(array);
578
+ const index = [];
579
+ return recursiveMapWithIndex(array, 0);
580
+ function recursiveMapWithIndex(value, depth) {
581
+ if (Array.isArray(value)) {
582
+ const N = value.length;
583
+ const result = Array(N);
584
+ for (let i = 0; i < N; i++) {
585
+ index[depth] = i;
586
+ result[i] = recursiveMapWithIndex(value[i], depth + 1);
587
+ }
588
+ return result;
589
+ } else return callback(value, index.slice(0, depth), array);
590
+ }
591
+ function recursiveMap(value) {
592
+ if (Array.isArray(value)) {
593
+ const N = value.length;
594
+ const result = Array(N);
595
+ for (let i = 0; i < N; i++) result[i] = recursiveMap(value[i]);
596
+ return result;
597
+ } else return callback(value);
598
+ }
599
+ }
600
+ function deepForEach$1(array, callback, skipIndex = false) {
601
+ if (Array.isArray(array) && array.length === 0) return;
602
+ if (skipIndex) {
603
+ recursiveForEach(array);
604
+ return;
605
+ }
606
+ const index = [];
607
+ recursiveForEachWithIndex(array, 0);
608
+ function recursiveForEachWithIndex(value, depth) {
609
+ if (Array.isArray(value)) {
610
+ const N = value.length;
611
+ for (let i = 0; i < N; i++) {
612
+ index[depth] = i;
613
+ recursiveForEachWithIndex(value[i], depth + 1);
614
+ }
615
+ } else callback(value, index.slice(0, depth), array);
616
+ }
617
+ function recursiveForEach(value) {
618
+ if (Array.isArray(value)) {
619
+ const N = value.length;
620
+ for (let i = 0; i < N; i++) recursiveForEach(value[i]);
621
+ } else callback(value);
622
+ }
623
+ }
624
+ function clone$1(array) {
625
+ return Object.assign([], array);
626
+ }
627
+ //#endregion
628
+ //#region src/switch.ts
994
629
  function _switch(mat) {
995
- const I = mat.length;
996
- const J = mat[0].length;
997
- let i, j;
998
- const ret = [];
999
- for (j = 0; j < J; j++) {
1000
- const tmp = [];
1001
- for (i = 0; i < I; i++) {
1002
- tmp.push(mat[i][j]);
1003
- }
1004
- ret.push(tmp);
1005
- }
1006
- return ret;
1007
- }
1008
-
1009
- // src/collection.ts
630
+ const I = mat.length;
631
+ const J = mat[0].length;
632
+ let i, j;
633
+ const ret = [];
634
+ for (j = 0; j < J; j++) {
635
+ const tmp = [];
636
+ for (i = 0; i < I; i++) tmp.push(mat[i][j]);
637
+ ret.push(tmp);
638
+ }
639
+ return ret;
640
+ }
641
+ //#endregion
642
+ //#region src/collection.ts
1010
643
  function containsCollections(array) {
1011
- for (let i = 0; i < array.length; i++) {
1012
- if (isCollection(array[i])) {
1013
- return true;
1014
- }
1015
- }
1016
- return false;
1017
- }
1018
- function deepForEach2(array, callback) {
1019
- if (isMatrix(array)) {
1020
- array.forEach((x) => callback(x), false, true);
1021
- } else {
1022
- deepForEach(array, callback, true);
1023
- }
1024
- }
1025
- function deepMap2(array, callback, skipZeros) {
1026
- if (!skipZeros) {
1027
- if (isMatrix(array)) {
1028
- return array.map((x) => callback(x), false, true);
1029
- } else {
1030
- return deepMap(array, callback, true);
1031
- }
1032
- }
1033
- const skipZerosCallback = (x) => x === 0 ? x : callback(x);
1034
- if (isMatrix(array)) {
1035
- return array.map((x) => skipZerosCallback(x), false, true);
1036
- } else {
1037
- return deepMap(array, skipZerosCallback, true);
1038
- }
644
+ for (let i = 0; i < array.length; i++) if (isCollection(array[i])) return true;
645
+ return false;
646
+ }
647
+ function deepForEach(array, callback) {
648
+ if (isMatrix(array)) array.forEach((x) => callback(x), false, true);
649
+ else deepForEach$1(array, callback, true);
650
+ }
651
+ function deepMap(array, callback, skipZeros) {
652
+ if (!skipZeros) {
653
+ if (isMatrix(array)) return array.map((x) => callback(x), false, true);
654
+ else return deepMap$1(array, callback, true);
655
+ }
656
+ const skipZerosCallback = (x) => x === 0 ? x : callback(x);
657
+ if (isMatrix(array)) return array.map((x) => skipZerosCallback(x), false, true);
658
+ else return deepMap$1(array, skipZerosCallback, true);
1039
659
  }
1040
660
  function reduce(mat, dim, callback) {
1041
- const size = Array.isArray(mat) ? arraySize(mat) : mat.size();
1042
- if (dim < 0 || dim >= size.length) {
1043
- throw new DimensionError(dim, size.length, "<");
1044
- }
1045
- if (isMatrix(mat)) {
1046
- const reduced = _reduce(mat.valueOf(), dim, callback);
1047
- return mat.create(
1048
- reduced,
1049
- mat.datatype()
1050
- );
1051
- } else {
1052
- return _reduce(mat, dim, callback);
1053
- }
661
+ const size = Array.isArray(mat) ? arraySize(mat) : mat.size();
662
+ if (dim < 0 || dim >= size.length) throw new DimensionError(dim, size.length, "<");
663
+ if (isMatrix(mat)) {
664
+ const reduced = _reduce(mat.valueOf(), dim, callback);
665
+ return mat.create(reduced, mat.datatype());
666
+ } else return _reduce(mat, dim, callback);
1054
667
  }
1055
668
  function _reduce(mat, dim, callback) {
1056
- let i;
1057
- let ret;
1058
- let val;
1059
- let tran;
1060
- if (dim <= 0) {
1061
- if (!Array.isArray(mat[0])) {
1062
- val = mat[0];
1063
- for (i = 1; i < mat.length; i++) {
1064
- val = callback(val, mat[i]);
1065
- }
1066
- return val;
1067
- } else {
1068
- tran = _switch(mat);
1069
- ret = [];
1070
- for (i = 0; i < tran.length; i++) {
1071
- ret[i] = _reduce(tran[i], dim - 1, callback);
1072
- }
1073
- return ret;
1074
- }
1075
- } else {
1076
- ret = [];
1077
- for (i = 0; i < mat.length; i++) {
1078
- ret[i] = _reduce(mat[i], dim - 1, callback);
1079
- }
1080
- return ret;
1081
- }
669
+ let i;
670
+ let ret;
671
+ let val;
672
+ let tran;
673
+ if (dim <= 0) {
674
+ if (!Array.isArray(mat[0])) {
675
+ val = mat[0];
676
+ for (i = 1; i < mat.length; i++) val = callback(val, mat[i]);
677
+ return val;
678
+ } else {
679
+ tran = _switch(mat);
680
+ ret = [];
681
+ for (i = 0; i < tran.length; i++) ret[i] = _reduce(tran[i], dim - 1, callback);
682
+ return ret;
683
+ }
684
+ } else {
685
+ ret = [];
686
+ for (i = 0; i < mat.length; i++) ret[i] = _reduce(mat[i], dim - 1, callback);
687
+ return ret;
688
+ }
1082
689
  }
1083
690
  function scatter(a, j, w, x, u, mark, cindex, f, inverse, update, value) {
1084
- const avalues = a._values;
1085
- const aindex = a._index;
1086
- const aptr = a._ptr;
1087
- let k;
1088
- let k0;
1089
- let k1;
1090
- let i;
1091
- if (x) {
1092
- for (k0 = aptr[j], k1 = aptr[j + 1], k = k0; k < k1; k++) {
1093
- i = aindex[k];
1094
- if (w[i] !== mark) {
1095
- w[i] = mark;
1096
- cindex.push(i);
1097
- if (update && f) {
1098
- x[i] = inverse ? f(avalues[k], value) : f(value, avalues[k]);
1099
- u[i] = mark;
1100
- } else {
1101
- x[i] = avalues[k];
1102
- }
1103
- } else {
1104
- if (f) {
1105
- x[i] = inverse ? f(avalues[k], x[i]) : f(x[i], avalues[k]);
1106
- }
1107
- u[i] = mark;
1108
- }
1109
- }
1110
- } else {
1111
- for (k0 = aptr[j], k1 = aptr[j + 1], k = k0; k < k1; k++) {
1112
- i = aindex[k];
1113
- if (w[i] !== mark) {
1114
- w[i] = mark;
1115
- cindex.push(i);
1116
- } else {
1117
- u[i] = mark;
1118
- }
1119
- }
1120
- }
1121
- }
1122
-
1123
- // src/customs.ts
691
+ const avalues = a._values;
692
+ const aindex = a._index;
693
+ const aptr = a._ptr;
694
+ let k;
695
+ let k0;
696
+ let k1;
697
+ let i;
698
+ if (x) for (k0 = aptr[j], k1 = aptr[j + 1], k = k0; k < k1; k++) {
699
+ i = aindex[k];
700
+ if (w[i] !== mark) {
701
+ w[i] = mark;
702
+ cindex.push(i);
703
+ if (update && f) {
704
+ x[i] = inverse ? f(avalues[k], value) : f(value, avalues[k]);
705
+ u[i] = mark;
706
+ } else x[i] = avalues[k];
707
+ } else {
708
+ if (f) x[i] = inverse ? f(avalues[k], x[i]) : f(x[i], avalues[k]);
709
+ u[i] = mark;
710
+ }
711
+ }
712
+ else for (k0 = aptr[j], k1 = aptr[j + 1], k = k0; k < k1; k++) {
713
+ i = aindex[k];
714
+ if (w[i] !== mark) {
715
+ w[i] = mark;
716
+ cindex.push(i);
717
+ } else u[i] = mark;
718
+ }
719
+ }
720
+ //#endregion
721
+ //#region src/customs.ts
1124
722
  function getSafeProperty(object, prop) {
1125
- const obj = object;
1126
- if (isSafeProperty(object, prop)) {
1127
- return obj[prop];
1128
- }
1129
- if (typeof obj[prop] === "function" && isSafeMethod(object, prop)) {
1130
- throw new Error('Cannot access method "' + prop + '" as a property');
1131
- }
1132
- throw new Error('No access to property "' + prop + '"');
723
+ const obj = object;
724
+ if (isSafeProperty(object, prop)) return obj[prop];
725
+ if (typeof obj[prop] === "function" && isSafeMethod(object, prop)) throw new Error("Cannot access method \"" + prop + "\" as a property");
726
+ throw new Error("No access to property \"" + prop + "\"");
1133
727
  }
1134
728
  function setSafeProperty(object, prop, value) {
1135
- if (isSafeProperty(object, prop)) {
1136
- object[prop] = value;
1137
- return value;
1138
- }
1139
- throw new Error('No access to property "' + prop + '"');
729
+ if (isSafeProperty(object, prop)) {
730
+ object[prop] = value;
731
+ return value;
732
+ }
733
+ throw new Error("No access to property \"" + prop + "\"");
1140
734
  }
1141
735
  function isSafeProperty(object, prop) {
1142
- if (!isPlainObject(object) && !Array.isArray(object)) {
1143
- return false;
1144
- }
1145
- if (hasOwnProperty(safeNativeProperties, prop)) {
1146
- return true;
1147
- }
1148
- if (prop in Object.prototype) {
1149
- return false;
1150
- }
1151
- if (prop in Function.prototype) {
1152
- return false;
1153
- }
1154
- return true;
736
+ if (!isPlainObject(object) && !Array.isArray(object)) return false;
737
+ if (hasOwnProperty(safeNativeProperties, prop)) return true;
738
+ if (prop in Object.prototype) return false;
739
+ if (prop in Function.prototype) return false;
740
+ return true;
1155
741
  }
1156
742
  function isSafeMethod(object, method) {
1157
- if (object === null || object === void 0 || typeof object[method] !== "function") {
1158
- return false;
1159
- }
1160
- if (hasOwnProperty(object, method) && Object.getPrototypeOf && method in Object.getPrototypeOf(object)) {
1161
- return false;
1162
- }
1163
- if (hasOwnProperty(safeNativeMethods, method)) {
1164
- return true;
1165
- }
1166
- if (method in Object.prototype) {
1167
- return false;
1168
- }
1169
- if (method in Function.prototype) {
1170
- return false;
1171
- }
1172
- return true;
743
+ if (object === null || object === void 0 || typeof object[method] !== "function") return false;
744
+ if (hasOwnProperty(object, method) && Object.getPrototypeOf && method in Object.getPrototypeOf(object)) return false;
745
+ if (hasOwnProperty(safeNativeMethods, method)) return true;
746
+ if (method in Object.prototype) return false;
747
+ if (method in Function.prototype) return false;
748
+ return true;
1173
749
  }
1174
750
  function isPlainObject(object) {
1175
- return typeof object === "object" && !!object && object.constructor === Object;
751
+ return typeof object === "object" && !!object && object.constructor === Object;
1176
752
  }
1177
- var safeNativeProperties = {
1178
- length: true,
1179
- name: true
753
+ const safeNativeProperties = {
754
+ length: true,
755
+ name: true
1180
756
  };
1181
- var safeNativeMethods = {
1182
- toString: true,
1183
- valueOf: true,
1184
- toLocaleString: true
757
+ const safeNativeMethods = {
758
+ toString: true,
759
+ valueOf: true,
760
+ toLocaleString: true
1185
761
  };
1186
-
1187
- // src/map.ts
762
+ //#endregion
763
+ //#region src/map.ts
1188
764
  var ObjectWrappingMap = class {
1189
- wrappedObject;
1190
- [Symbol.toStringTag] = "ObjectWrappingMap";
1191
- constructor(object) {
1192
- this.wrappedObject = object;
1193
- }
1194
- /**
1195
- * Declared as a real method rather than assigned in the constructor through a
1196
- * cast. The old form satisfied the runtime but never appeared in the emitted
1197
- * type, so `implements Map<K, V>` was a lie that only surfaced downstream:
1198
- * consumers compiling with `skipLibCheck: false` got TS2420 ("incorrectly
1199
- * implements interface 'Map'... '[Symbol.iterator]' is missing").
1200
- */
1201
- [Symbol.iterator]() {
1202
- return this.entries();
1203
- }
1204
- keys() {
1205
- return Object.keys(this.wrappedObject).filter((key) => this.has(key)).values();
1206
- }
1207
- get(key) {
1208
- return getSafeProperty(this.wrappedObject, key);
1209
- }
1210
- set(key, value) {
1211
- setSafeProperty(this.wrappedObject, key, value);
1212
- return this;
1213
- }
1214
- has(key) {
1215
- return isSafeProperty(this.wrappedObject, key) && key in this.wrappedObject;
1216
- }
1217
- /**
1218
- * Return the value for `key`; when the key is absent, set it to `defaultValue` first.
1219
- * Declared because the ESNext `Map` (TC39 upsert) has it, and `implements Map` requires it.
1220
- */
1221
- getOrInsert(key, defaultValue) {
1222
- if (!this.has(key)) this.set(key, defaultValue);
1223
- return this.get(key);
1224
- }
1225
- /**
1226
- * Return the value for `key`; when the key is absent, set it to `callback(key)` first.
1227
- * Declared because the ESNext `Map` (TC39 upsert) has it, and `implements Map` requires it.
1228
- */
1229
- getOrInsertComputed(key, callback) {
1230
- if (!this.has(key)) this.set(key, callback(key));
1231
- return this.get(key);
1232
- }
1233
- entries() {
1234
- return mapIterator(this.keys(), (key) => [key, this.get(key)]);
1235
- }
1236
- *values() {
1237
- for (const key of this.keys()) {
1238
- yield this.get(key);
1239
- }
1240
- }
1241
- forEach(callback) {
1242
- for (const key of this.keys()) {
1243
- callback(this.get(key), key, this);
1244
- }
1245
- }
1246
- delete(key) {
1247
- if (isSafeProperty(this.wrappedObject, key)) {
1248
- delete this.wrappedObject[key];
1249
- return true;
1250
- }
1251
- return false;
1252
- }
1253
- clear() {
1254
- for (const key of this.keys()) {
1255
- this.delete(key);
1256
- }
1257
- }
1258
- get size() {
1259
- return Object.keys(this.wrappedObject).length;
1260
- }
765
+ wrappedObject;
766
+ [Symbol.toStringTag] = "ObjectWrappingMap";
767
+ constructor(object) {
768
+ this.wrappedObject = object;
769
+ }
770
+ [Symbol.iterator]() {
771
+ return this.entries();
772
+ }
773
+ keys() {
774
+ return Object.keys(this.wrappedObject).filter((key) => this.has(key)).values();
775
+ }
776
+ get(key) {
777
+ return getSafeProperty(this.wrappedObject, key);
778
+ }
779
+ set(key, value) {
780
+ setSafeProperty(this.wrappedObject, key, value);
781
+ return this;
782
+ }
783
+ has(key) {
784
+ return isSafeProperty(this.wrappedObject, key) && key in this.wrappedObject;
785
+ }
786
+ getOrInsert(key, defaultValue) {
787
+ if (!this.has(key)) this.set(key, defaultValue);
788
+ return this.get(key);
789
+ }
790
+ getOrInsertComputed(key, callback) {
791
+ if (!this.has(key)) this.set(key, callback(key));
792
+ return this.get(key);
793
+ }
794
+ entries() {
795
+ return mapIterator(this.keys(), (key) => [key, this.get(key)]);
796
+ }
797
+ *values() {
798
+ for (const key of this.keys()) yield this.get(key);
799
+ }
800
+ forEach(callback) {
801
+ for (const key of this.keys()) callback(this.get(key), key, this);
802
+ }
803
+ delete(key) {
804
+ if (isSafeProperty(this.wrappedObject, key)) {
805
+ delete this.wrappedObject[key];
806
+ return true;
807
+ }
808
+ return false;
809
+ }
810
+ clear() {
811
+ for (const key of this.keys()) this.delete(key);
812
+ }
813
+ get size() {
814
+ return Object.keys(this.wrappedObject).length;
815
+ }
1261
816
  };
1262
817
  var PartitionedMap = class {
1263
- a;
1264
- b;
1265
- bKeys;
1266
- [Symbol.toStringTag] = "PartitionedMap";
1267
- /**
1268
- * Create a PartitionedMap over two maps.
1269
- *
1270
- * @param a - Primary map
1271
- * @param b - Secondary map
1272
- * @param bKeys - Set of keys that should be read/written to map b
1273
- */
1274
- constructor(a, b, bKeys) {
1275
- this.a = a;
1276
- this.b = b;
1277
- this.bKeys = bKeys;
1278
- }
1279
- /** See the note on `ObjectWrappingMap[Symbol.iterator]` — same fix. */
1280
- [Symbol.iterator]() {
1281
- return this.entries();
1282
- }
1283
- get(key) {
1284
- return this.bKeys.has(key) ? this.b.get(key) : this.a.get(key);
1285
- }
1286
- set(key, value) {
1287
- if (this.bKeys.has(key)) {
1288
- this.b.set(key, value);
1289
- } else {
1290
- this.a.set(key, value);
1291
- }
1292
- return this;
1293
- }
1294
- has(key) {
1295
- return this.b.has(key) || this.a.has(key);
1296
- }
1297
- /**
1298
- * Return the value for `key`; when the key is absent, set it to `defaultValue` first.
1299
- * Declared because the ESNext `Map` (TC39 upsert) has it, and `implements Map` requires it.
1300
- */
1301
- getOrInsert(key, defaultValue) {
1302
- if (!this.has(key)) this.set(key, defaultValue);
1303
- return this.get(key);
1304
- }
1305
- /**
1306
- * Return the value for `key`; when the key is absent, set it to `callback(key)` first.
1307
- * Declared because the ESNext `Map` (TC39 upsert) has it, and `implements Map` requires it.
1308
- */
1309
- getOrInsertComputed(key, callback) {
1310
- if (!this.has(key)) this.set(key, callback(key));
1311
- return this.get(key);
1312
- }
1313
- keys() {
1314
- return (/* @__PURE__ */ new Set([...this.a.keys(), ...this.b.keys()]))[Symbol.iterator]();
1315
- }
1316
- *values() {
1317
- for (const key of this.keys()) {
1318
- yield this.get(key);
1319
- }
1320
- }
1321
- entries() {
1322
- return mapIterator(this.keys(), (key) => [key, this.get(key)]);
1323
- }
1324
- forEach(callback) {
1325
- for (const key of this.keys()) {
1326
- callback(this.get(key), key, this);
1327
- }
1328
- }
1329
- delete(key) {
1330
- return this.bKeys.has(key) ? this.b.delete(key) : this.a.delete(key);
1331
- }
1332
- clear() {
1333
- this.a.clear();
1334
- this.b.clear();
1335
- }
1336
- get size() {
1337
- return [...this.keys()].length;
1338
- }
818
+ a;
819
+ b;
820
+ bKeys;
821
+ [Symbol.toStringTag] = "PartitionedMap";
822
+ constructor(a, b, bKeys) {
823
+ this.a = a;
824
+ this.b = b;
825
+ this.bKeys = bKeys;
826
+ }
827
+ [Symbol.iterator]() {
828
+ return this.entries();
829
+ }
830
+ get(key) {
831
+ return this.bKeys.has(key) ? this.b.get(key) : this.a.get(key);
832
+ }
833
+ set(key, value) {
834
+ if (this.bKeys.has(key)) this.b.set(key, value);
835
+ else this.a.set(key, value);
836
+ return this;
837
+ }
838
+ has(key) {
839
+ return this.b.has(key) || this.a.has(key);
840
+ }
841
+ getOrInsert(key, defaultValue) {
842
+ if (!this.has(key)) this.set(key, defaultValue);
843
+ return this.get(key);
844
+ }
845
+ getOrInsertComputed(key, callback) {
846
+ if (!this.has(key)) this.set(key, callback(key));
847
+ return this.get(key);
848
+ }
849
+ keys() {
850
+ return (/* @__PURE__ */ new Set([...this.a.keys(), ...this.b.keys()]))[Symbol.iterator]();
851
+ }
852
+ *values() {
853
+ for (const key of this.keys()) yield this.get(key);
854
+ }
855
+ entries() {
856
+ return mapIterator(this.keys(), (key) => [key, this.get(key)]);
857
+ }
858
+ forEach(callback) {
859
+ for (const key of this.keys()) callback(this.get(key), key, this);
860
+ }
861
+ delete(key) {
862
+ return this.bKeys.has(key) ? this.b.delete(key) : this.a.delete(key);
863
+ }
864
+ clear() {
865
+ this.a.clear();
866
+ this.b.clear();
867
+ }
868
+ get size() {
869
+ return [...this.keys()].length;
870
+ }
1339
871
  };
1340
872
  function* mapIterator(it, callback) {
1341
- for (const value of it) yield callback(value);
1342
- return void 0;
873
+ for (const value of it) yield callback(value);
1343
874
  }
1344
875
  function createEmptyMap() {
1345
- return /* @__PURE__ */ new Map();
876
+ return /* @__PURE__ */ new Map();
1346
877
  }
1347
878
  function createMap(mapOrObject) {
1348
- if (!mapOrObject) {
1349
- return createEmptyMap();
1350
- }
1351
- if (isMap(mapOrObject)) {
1352
- return mapOrObject;
1353
- }
1354
- if (isObject(mapOrObject)) {
1355
- return new ObjectWrappingMap(mapOrObject);
1356
- }
1357
- throw new Error("createMap can create maps from objects or Maps");
1358
- }
1359
- function toObject(map2) {
1360
- if (map2 instanceof ObjectWrappingMap) {
1361
- return map2.wrappedObject;
1362
- }
1363
- const object = {};
1364
- for (const key of map2.keys()) {
1365
- const value = map2.get(key);
1366
- setSafeProperty(object, key, value);
1367
- }
1368
- return object;
1369
- }
1370
- function assign(map2, ...objects) {
1371
- for (const args of objects) {
1372
- if (!args) {
1373
- continue;
1374
- }
1375
- if (isMap(args)) {
1376
- for (const key of args.keys()) {
1377
- map2.set(key, args.get(key));
1378
- }
1379
- } else if (isObject(args)) {
1380
- for (const key of Object.keys(args)) {
1381
- map2.set(key, args[key]);
1382
- }
1383
- }
1384
- }
1385
- return map2;
879
+ if (!mapOrObject) return createEmptyMap();
880
+ if (isMap(mapOrObject)) return mapOrObject;
881
+ if (isObject(mapOrObject)) return new ObjectWrappingMap(mapOrObject);
882
+ throw new Error("createMap can create maps from objects or Maps");
883
+ }
884
+ function toObject(map) {
885
+ if (map instanceof ObjectWrappingMap) return map.wrappedObject;
886
+ const object = {};
887
+ for (const key of map.keys()) setSafeProperty(object, key, map.get(key));
888
+ return object;
889
+ }
890
+ function assign(map, ...objects) {
891
+ for (const args of objects) {
892
+ if (!args) continue;
893
+ if (isMap(args)) for (const key of args.keys()) map.set(key, args.get(key));
894
+ else if (isObject(args)) for (const key of Object.keys(args)) map.set(key, args[key]);
895
+ }
896
+ return map;
1386
897
  }
1387
898
  function isObjectWrappingMap(object) {
1388
- if (!isMap(object)) return false;
1389
- const wrapper = object;
1390
- return isObject(wrapper.wrappedObject);
899
+ if (!isMap(object)) return false;
900
+ return isObject(object.wrappedObject);
1391
901
  }
1392
-
1393
- // src/wasm-loader.ts
1394
- var ALGO = "sha384";
902
+ //#endregion
903
+ //#region src/wasm-loader.ts
904
+ const ALGO = "sha384";
1395
905
  async function sha384OfBuffer(buffer) {
1396
- const bytes = buffer instanceof Uint8Array ? buffer : new Uint8Array(buffer);
1397
- const isNode = typeof process !== "undefined" && process.versions?.node !== void 0;
1398
- let digest;
1399
- if (isNode) {
1400
- const { createHash } = await import("crypto");
1401
- const hash = createHash(ALGO);
1402
- hash.update(bytes);
1403
- digest = new Uint8Array(hash.digest());
1404
- } else {
1405
- const copy = new ArrayBuffer(bytes.byteLength);
1406
- new Uint8Array(copy).set(bytes);
1407
- const out = await crypto.subtle.digest("SHA-384", copy);
1408
- digest = new Uint8Array(out);
1409
- }
1410
- let binary = "";
1411
- for (let i = 0; i < digest.length; i++) binary += String.fromCharCode(digest[i]);
1412
- const b64 = typeof btoa === "function" ? btoa(binary) : Buffer.from(digest).toString("base64");
1413
- return `sha384-${b64}`;
906
+ const bytes = buffer instanceof Uint8Array ? buffer : new Uint8Array(buffer);
907
+ const isNode = typeof process !== "undefined" && process.versions?.node !== void 0;
908
+ let digest;
909
+ if (isNode) {
910
+ const { createHash } = await import("crypto");
911
+ const hash = createHash(ALGO);
912
+ hash.update(bytes);
913
+ digest = new Uint8Array(hash.digest());
914
+ } else {
915
+ const copy = new ArrayBuffer(bytes.byteLength);
916
+ new Uint8Array(copy).set(bytes);
917
+ const out = await crypto.subtle.digest("SHA-384", copy);
918
+ digest = new Uint8Array(out);
919
+ }
920
+ let binary = "";
921
+ for (let i = 0; i < digest.length; i++) binary += String.fromCharCode(digest[i]);
922
+ return `sha384-${typeof btoa === "function" ? btoa(binary) : Buffer.from(digest).toString("base64")}`;
1414
923
  }
1415
924
  async function loadWasmManifest(wasmPath) {
1416
- const isNode = typeof process !== "undefined" && process.versions?.node !== void 0;
1417
- const manifestPath = wasmPath.replace(/[^/\\]+$/, "wasm-manifest.json");
1418
- try {
1419
- if (isNode) {
1420
- const fs = await import("fs");
1421
- const { promisify } = await import("util");
1422
- const readFile = promisify(fs.readFile);
1423
- const text = await readFile(manifestPath, "utf8");
1424
- return JSON.parse(text);
1425
- } else {
1426
- const res = await fetch(manifestPath);
1427
- if (!res.ok) return null;
1428
- return await res.json();
1429
- }
1430
- } catch {
1431
- return null;
1432
- }
925
+ const isNode = typeof process !== "undefined" && process.versions?.node !== void 0;
926
+ const manifestPath = wasmPath.replace(/[^/\\]+$/, "wasm-manifest.json");
927
+ try {
928
+ if (isNode) {
929
+ const fs = await import("fs");
930
+ const { promisify } = await import("util");
931
+ const text = await promisify(fs.readFile)(manifestPath, "utf8");
932
+ return JSON.parse(text);
933
+ } else {
934
+ const res = await fetch(manifestPath);
935
+ if (!res.ok) return null;
936
+ return await res.json();
937
+ }
938
+ } catch {
939
+ return null;
940
+ }
1433
941
  }
1434
942
  async function verifyWasmIntegrity(buffer, wasmPath, options = {}) {
1435
- const fileName = wasmPath.split(/[/\\]/).pop() || wasmPath;
1436
- const manifest = options.manifest !== void 0 ? options.manifest : await loadWasmManifest(wasmPath);
1437
- if (!manifest) {
1438
- if (options.required) {
1439
- throw new Error(
1440
- `WASM integrity check failed: no manifest at sibling of "${wasmPath}" (required)`
1441
- );
1442
- }
1443
- if (typeof console !== "undefined") {
1444
- console.warn(
1445
- `[wasm-integrity] no manifest found beside "${wasmPath}"; skipping SHA-384 verification (set options.required=true to fail closed)`
1446
- );
1447
- }
1448
- return;
1449
- }
1450
- const expected = manifest[fileName];
1451
- if (!expected) {
1452
- if (options.required) {
1453
- throw new Error(`WASM integrity check failed: manifest has no entry for "${fileName}"`);
1454
- }
1455
- return;
1456
- }
1457
- const actual = await sha384OfBuffer(buffer);
1458
- if (actual !== expected) {
1459
- throw new Error(
1460
- `WASM integrity check failed for "${fileName}": expected ${expected}, got ${actual}`
1461
- );
1462
- }
943
+ const fileName = wasmPath.split(/[/\\]/).pop() || wasmPath;
944
+ const manifest = options.manifest !== void 0 ? options.manifest : await loadWasmManifest(wasmPath);
945
+ if (!manifest) {
946
+ if (options.required) throw new Error(`WASM integrity check failed: no manifest at sibling of "${wasmPath}" (required)`);
947
+ if (typeof console !== "undefined") console.warn(`[wasm-integrity] no manifest found beside "${wasmPath}"; skipping SHA-384 verification (set options.required=true to fail closed)`);
948
+ return;
949
+ }
950
+ const expected = manifest[fileName];
951
+ if (!expected) {
952
+ if (options.required) throw new Error(`WASM integrity check failed: manifest has no entry for "${fileName}"`);
953
+ return;
954
+ }
955
+ const actual = await sha384OfBuffer(buffer);
956
+ if (actual !== expected) throw new Error(`WASM integrity check failed for "${fileName}": expected ${expected}, got ${actual}`);
1463
957
  }
1464
958
  async function resolvePackagedWasm(metaUrl, wasmFile) {
1465
- const isNode = typeof process !== "undefined" && process.versions?.node !== void 0;
1466
- if (!isNode) return null;
1467
- const { fileURLToPath } = await import("url");
1468
- const { dirname, join: join2 } = await import("path");
1469
- const { existsSync } = await import("fs");
1470
- let dir = dirname(fileURLToPath(metaUrl));
1471
- for (let depth = 0; depth < 8; depth++) {
1472
- const candidates = [join2(dir, "wasm", wasmFile), join2(dir, "dist", "wasm", wasmFile)];
1473
- for (const candidate of candidates) {
1474
- if (existsSync(candidate)) return candidate;
1475
- }
1476
- const parent = dirname(dir);
1477
- if (parent === dir) break;
1478
- dir = parent;
1479
- }
1480
- return null;
959
+ if (!(typeof process !== "undefined" && process.versions?.node !== void 0)) return null;
960
+ const { fileURLToPath } = await import("node:url");
961
+ const { dirname, join } = await import("node:path");
962
+ const { existsSync } = await import("node:fs");
963
+ let dir = dirname(fileURLToPath(metaUrl));
964
+ for (let depth = 0; depth < 8; depth++) {
965
+ const candidates = [join(dir, "wasm", wasmFile), join(dir, "dist", "wasm", wasmFile)];
966
+ for (const candidate of candidates) if (existsSync(candidate)) return candidate;
967
+ const parent = dirname(dir);
968
+ if (parent === dir) break;
969
+ dir = parent;
970
+ }
971
+ return null;
1481
972
  }
1482
973
  async function defaultWasmLocation(metaUrl, wasmFile, opts) {
1483
- if (opts?.browser) {
1484
- return new URL(`./wasm/${wasmFile}`, metaUrl).href;
1485
- }
1486
- const { fileURLToPath } = await import("url");
1487
- const { dirname, join: join2 } = await import("path");
1488
- const { existsSync } = await import("fs");
1489
- let dir = dirname(fileURLToPath(metaUrl));
1490
- for (let depth = 0; depth < 8; depth++) {
1491
- if (existsSync(join2(dir, "package.json"))) {
1492
- return join2(dir, "dist", "wasm", wasmFile);
1493
- }
1494
- const parent = dirname(dir);
1495
- if (parent === dir) break;
1496
- dir = parent;
1497
- }
1498
- return join2(dirname(fileURLToPath(metaUrl)), "wasm", wasmFile);
1499
- }
1500
- export {
1501
- Unit as CoreUnit,
1502
- DEFAULT_CONFIG,
1503
- DimensionError,
1504
- IndexError,
1505
- MathjsError,
1506
- ObjectWrappingMap,
1507
- PartitionedMap,
1508
- _switch,
1509
- acosh,
1510
- arraySize,
1511
- asinh,
1512
- assertDependencies,
1513
- assign as assignMap,
1514
- atanh,
1515
- broadcastArrays,
1516
- broadcastSizes,
1517
- broadcastTo,
1518
- canDefineProperty,
1519
- cbrt,
1520
- checkBroadcastingRules,
1521
- clone,
1522
- clone2 as cloneArray,
1523
- compareText,
1524
- concat,
1525
- containsCollections,
1526
- copysign,
1527
- cosh,
1528
- create,
1529
- createEmptyMap,
1530
- createIndexError,
1531
- createMap,
1532
- createUnitClass,
1533
- deepExtend,
1534
- deepFlatten,
1535
- deepForEach2 as deepForEach,
1536
- deepForEach as deepForEachArray,
1537
- deepMap2 as deepMap,
1538
- deepMap as deepMapArray,
1539
- deepStrictEqual,
1540
- defaultWasmLocation,
1541
- digits,
1542
- endsWith,
1543
- escape,
1544
- expm1,
1545
- extend,
1546
- factory,
1547
- filter,
1548
- filterRegExp,
1549
- flatten,
1550
- forEach,
1551
- format,
1552
- format2 as formatBigNumber,
1553
- format3 as formatGeneric,
1554
- generalize,
1555
- get,
1556
- getArrayDataType,
1557
- get2 as getArrayElement,
1558
- hasOwnProperty,
1559
- identify,
1560
- initial,
1561
- isArray,
1562
- isBigInt,
1563
- isBigNumber,
1564
- isBoolean,
1565
- isCollection,
1566
- isComplex,
1567
- isDate,
1568
- isDenseMatrix,
1569
- isEmptyIndex,
1570
- isFactory,
1571
- isFraction,
1572
- isFunction,
1573
- isIndex,
1574
- isInteger,
1575
- isLegacyFactory,
1576
- isMap,
1577
- isMatrix,
1578
- isNull,
1579
- isNumber,
1580
- isObject,
1581
- isObjectWrappingMap,
1582
- isOptionalDependency,
1583
- isPowZeroAtInfinity,
1584
- isRange,
1585
- isRegExp,
1586
- isSparseMatrix,
1587
- isString,
1588
- isUndefined,
1589
- isUnit,
1590
- join,
1591
- last,
1592
- lazy,
1593
- loadWasmManifest,
1594
- log10,
1595
- log1p,
1596
- log2,
1597
- map,
1598
- mapObject,
1599
- memoize,
1600
- nearlyEqual,
1601
- normalizeFormatOptions,
1602
- pick,
1603
- pickShallow,
1604
- processSizesWildcard,
1605
- reduce,
1606
- reshape,
1607
- resize,
1608
- resolvePackagedWasm,
1609
- roundDigits,
1610
- safeNumberType,
1611
- scatter,
1612
- set,
1613
- sha384OfBuffer,
1614
- sign,
1615
- sinh,
1616
- sortFactories,
1617
- splitNumber,
1618
- squeeze,
1619
- stretch,
1620
- stringify,
1621
- stripOptionalNotation,
1622
- tanh,
1623
- toEngineering,
1624
- toEngineering2 as toEngineeringBigNumber,
1625
- toExponential,
1626
- toExponential2 as toExponentialBigNumber,
1627
- toFixed,
1628
- toFixed2 as toFixedBigNumber,
1629
- toObject,
1630
- toPrecision,
1631
- traverse,
1632
- typeOf,
1633
- unitDependencies,
1634
- unsqueeze,
1635
- validate,
1636
- validateIndex,
1637
- validateIndexSourceSize,
1638
- verifyWasmIntegrity,
1639
- warnOnce
974
+ if (opts?.browser) return new URL(`./wasm/${wasmFile}`, metaUrl).href;
975
+ const { fileURLToPath } = await import("node:url");
976
+ const { dirname, join } = await import("node:path");
977
+ const { existsSync } = await import("node:fs");
978
+ let dir = dirname(fileURLToPath(metaUrl));
979
+ for (let depth = 0; depth < 8; depth++) {
980
+ if (existsSync(join(dir, "package.json"))) return join(dir, "dist", "wasm", wasmFile);
981
+ const parent = dirname(dir);
982
+ if (parent === dir) break;
983
+ dir = parent;
984
+ }
985
+ return join(dirname(fileURLToPath(metaUrl)), "wasm", wasmFile);
986
+ }
987
+ var WasmModuleLoader = class {
988
+ wasmModule = null;
989
+ compiledModule = null;
990
+ loading = null;
991
+ isNode;
992
+ lastMetrics = null;
993
+ constructor() {
994
+ this.isNode = typeof process !== "undefined" && process.versions?.node !== void 0;
995
+ }
996
+ async load(wasmPath) {
997
+ if (this.wasmModule) return this.wasmModule;
998
+ if (this.loading) return this.loading;
999
+ this.loading = this.loadModule(wasmPath);
1000
+ try {
1001
+ this.wasmModule = await this.loading;
1002
+ } catch (error) {
1003
+ this.compiledModule = null;
1004
+ throw error;
1005
+ } finally {
1006
+ this.loading = null;
1007
+ }
1008
+ return this.wasmModule;
1009
+ }
1010
+ async loadModule(wasmPath) {
1011
+ const path = wasmPath || await this.getDefaultWasmPath();
1012
+ const totalStart = performance.now();
1013
+ if (this.compiledModule) {
1014
+ const instStart = performance.now();
1015
+ const instance = await WebAssembly.instantiate(this.compiledModule, this.getImports());
1016
+ this.lastMetrics = {
1017
+ fileReadMs: 0,
1018
+ compileMs: 0,
1019
+ instantiateMs: performance.now() - instStart,
1020
+ totalMs: performance.now() - totalStart,
1021
+ fromCache: true
1022
+ };
1023
+ return instance.exports;
1024
+ }
1025
+ if (this.isNode) return this.loadNodeWasm(path, totalStart);
1026
+ return this.loadBrowserWasm(path, totalStart);
1027
+ }
1028
+ async precompile(wasmPath) {
1029
+ if (this.compiledModule) return;
1030
+ const path = wasmPath || await this.getDefaultWasmPath();
1031
+ const startTime = performance.now();
1032
+ if (this.isNode) {
1033
+ const fs = await import("fs");
1034
+ const { promisify } = await import("util");
1035
+ const buffer = await promisify(fs.readFile)(path);
1036
+ await verifyWasmIntegrity(buffer, path);
1037
+ this.compiledModule = await WebAssembly.compile(buffer);
1038
+ } else {
1039
+ const manifest = await loadWasmManifest(path);
1040
+ if (!manifest && typeof WebAssembly.compileStreaming === "function") this.compiledModule = await WebAssembly.compileStreaming(fetch(path));
1041
+ else {
1042
+ const buffer = await (await fetch(path)).arrayBuffer();
1043
+ await verifyWasmIntegrity(buffer, path, { manifest });
1044
+ this.compiledModule = await WebAssembly.compile(buffer);
1045
+ }
1046
+ }
1047
+ this.lastMetrics = {
1048
+ fileReadMs: 0,
1049
+ compileMs: performance.now() - startTime,
1050
+ instantiateMs: 0,
1051
+ totalMs: performance.now() - startTime,
1052
+ fromCache: false
1053
+ };
1054
+ }
1055
+ async loadNodeWasm(path, totalStart) {
1056
+ const fs = await import("fs");
1057
+ const { promisify } = await import("util");
1058
+ const readFile = promisify(fs.readFile);
1059
+ const readStart = performance.now();
1060
+ const buffer = await readFile(path);
1061
+ const readEnd = performance.now();
1062
+ await verifyWasmIntegrity(buffer, path);
1063
+ const compileStart = performance.now();
1064
+ this.compiledModule = await WebAssembly.compile(buffer);
1065
+ const compileEnd = performance.now();
1066
+ const instStart = performance.now();
1067
+ const instance = await WebAssembly.instantiate(this.compiledModule, this.getImports());
1068
+ const instEnd = performance.now();
1069
+ this.lastMetrics = {
1070
+ fileReadMs: readEnd - readStart,
1071
+ compileMs: compileEnd - compileStart,
1072
+ instantiateMs: instEnd - instStart,
1073
+ totalMs: performance.now() - totalStart,
1074
+ fromCache: false
1075
+ };
1076
+ return instance.exports;
1077
+ }
1078
+ async loadBrowserWasm(path, totalStart) {
1079
+ const manifest = await loadWasmManifest(path);
1080
+ if (!manifest && typeof WebAssembly.instantiateStreaming === "function") {
1081
+ const instStart = performance.now();
1082
+ const result = await WebAssembly.instantiateStreaming(fetch(path), this.getImports());
1083
+ this.compiledModule = result.module;
1084
+ this.lastMetrics = {
1085
+ fileReadMs: 0,
1086
+ compileMs: 0,
1087
+ instantiateMs: performance.now() - instStart,
1088
+ totalMs: performance.now() - totalStart,
1089
+ fromCache: false
1090
+ };
1091
+ return result.instance.exports;
1092
+ }
1093
+ const readStart = performance.now();
1094
+ const buffer = await (await fetch(path)).arrayBuffer();
1095
+ const readEnd = performance.now();
1096
+ await verifyWasmIntegrity(buffer, path, { manifest });
1097
+ const compileStart = performance.now();
1098
+ this.compiledModule = await WebAssembly.compile(buffer);
1099
+ const compileEnd = performance.now();
1100
+ const instStart = performance.now();
1101
+ const instance = await WebAssembly.instantiate(this.compiledModule, this.getImports());
1102
+ const instEnd = performance.now();
1103
+ this.lastMetrics = {
1104
+ fileReadMs: readEnd - readStart,
1105
+ compileMs: compileEnd - compileStart,
1106
+ instantiateMs: instEnd - instStart,
1107
+ totalMs: performance.now() - totalStart,
1108
+ fromCache: false
1109
+ };
1110
+ return instance.exports;
1111
+ }
1112
+ getImports() {
1113
+ return {
1114
+ env: {
1115
+ abort: (msg, file, line, column) => {
1116
+ console.error("WASM abort", {
1117
+ msg,
1118
+ file,
1119
+ line,
1120
+ column
1121
+ });
1122
+ throw new Error("WASM abort");
1123
+ },
1124
+ seed: () => Date.now()
1125
+ },
1126
+ Math,
1127
+ Date
1128
+ };
1129
+ }
1640
1130
  };
1131
+ //#endregion
1132
+ //#region src/wasm-as-header.ts
1133
+ function allocAsHeader(mod, byteLength, typeId) {
1134
+ const bufferPtr = mod.__pin(mod.__new(byteLength, 1)) >>> 0;
1135
+ const headerPtr = mod.__new(12, typeId) >>> 0;
1136
+ mod.__pin(headerPtr);
1137
+ const dv = new DataView(mod.memory.buffer);
1138
+ dv.setUint32(headerPtr + 0, bufferPtr, true);
1139
+ dv.setUint32(headerPtr + 4, bufferPtr, true);
1140
+ dv.setUint32(headerPtr + 8, byteLength, true);
1141
+ return {
1142
+ headerPtr,
1143
+ bufferPtr
1144
+ };
1145
+ }
1146
+ //#endregion
1147
+ export { Unit as CoreUnit, DEFAULT_CONFIG, DimensionError, IndexError, MathjsError, ObjectWrappingMap, PartitionedMap, WasmModuleLoader, _switch, acosh, allocAsHeader, arraySize, asinh, assertDependencies, assign as assignMap, atanh, broadcastArrays, broadcastSizes, broadcastTo, canDefineProperty, cbrt, checkBroadcastingRules, clone, clone$1 as cloneArray, compareText, concat, containsCollections, copysign, cosh, create, createEmptyMap, createIndexError, createMap, createUnitClass, deepExtend, deepFlatten, deepForEach, deepForEach$1 as deepForEachArray, deepMap, deepMap$1 as deepMapArray, deepStrictEqual, defaultWasmLocation, digits, endsWith, escape, expm1, extend, factory, filter, filterRegExp, flatten, forEach, format, format$1 as formatBigNumber, format$2 as formatGeneric, generalize, get, getArrayDataType, get$1 as getArrayElement, hasOwnProperty, identify, initial, isArray, isBigInt, isBigNumber, isBoolean, isCollection, isComplex, isDate, isDenseMatrix, isEmptyIndex, isFactory, isFraction, isFunction, isIndex, isInteger, isLegacyFactory, isMap, isMatrix, isNull, isNumber, isObject, isObjectWrappingMap, isOptionalDependency, isPowZeroAtInfinity, isRange, isRegExp, isSparseMatrix, isString, isUndefined, isUnit, join, last, lazy, loadWasmManifest, log10, log1p, log2, map, mapObject, memoize, nearlyEqual, normalizeFormatOptions, pick, pickShallow, processSizesWildcard, reduce, reshape, resize, resolvePackagedWasm, roundDigits, safeNumberType, scatter, set, sha384OfBuffer, sign, sinh, sortFactories, splitNumber, squeeze, stretch, stringify, stripOptionalNotation, tanh, toEngineering, toEngineering$1 as toEngineeringBigNumber, toExponential, toExponential$1 as toExponentialBigNumber, toFixed, toFixed$1 as toFixedBigNumber, toObject, toPrecision, traverse, typeOf, unitDependencies, unsqueeze, validate, validateIndex, validateIndexSourceSize, verifyWasmIntegrity, warnOnce };