@mirascript/mirascript 0.1.15 → 0.1.16

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 (216) hide show
  1. package/dist/{chunk-NT235HY3.js → chunk-LU4ZKFF6.js} +1411 -608
  2. package/dist/chunk-LU4ZKFF6.js.map +6 -0
  3. package/dist/chunk-RIT53WVY.js +1 -0
  4. package/dist/chunk-RLWIIOH5.js +12 -0
  5. package/dist/chunk-RLWIIOH5.js.map +6 -0
  6. package/dist/{chunk-JVFUK7AN.js → chunk-YZGL3D7L.js} +739 -1366
  7. package/dist/chunk-YZGL3D7L.js.map +6 -0
  8. package/dist/cli/index.js +11 -67
  9. package/dist/cli/index.js.map +2 -2
  10. package/dist/compiler/compile-fast.d.ts +1 -1
  11. package/dist/compiler/compile-fast.d.ts.map +1 -1
  12. package/dist/compiler/create-script.d.ts +10 -1
  13. package/dist/compiler/create-script.d.ts.map +1 -1
  14. package/dist/compiler/diagnostic.d.ts +1 -1
  15. package/dist/compiler/diagnostic.d.ts.map +1 -1
  16. package/dist/compiler/emit/constants.d.ts +3 -0
  17. package/dist/compiler/emit/constants.d.ts.map +1 -0
  18. package/dist/compiler/emit/consts.d.ts +6 -0
  19. package/dist/compiler/emit/consts.d.ts.map +1 -0
  20. package/dist/compiler/emit/globals.d.ts +17 -0
  21. package/dist/compiler/emit/globals.d.ts.map +1 -0
  22. package/dist/compiler/emit/index.d.ts +58 -0
  23. package/dist/compiler/emit/index.d.ts.map +1 -0
  24. package/dist/compiler/emit/sourcemap.d.ts +6 -0
  25. package/dist/compiler/emit/sourcemap.d.ts.map +1 -0
  26. package/dist/compiler/index.d.ts +3 -2
  27. package/dist/compiler/index.d.ts.map +1 -1
  28. package/dist/compiler/worker.js +1 -1
  29. package/dist/helpers/constants.d.ts +10 -0
  30. package/dist/helpers/constants.d.ts.map +1 -1
  31. package/dist/helpers/convert.d.ts +12 -0
  32. package/dist/helpers/convert.d.ts.map +1 -0
  33. package/dist/{vm → helpers}/error.d.ts +1 -1
  34. package/dist/helpers/error.d.ts.map +1 -0
  35. package/dist/helpers/serialize.d.ts +13 -4
  36. package/dist/helpers/serialize.d.ts.map +1 -1
  37. package/dist/helpers/types.d.ts +54 -0
  38. package/dist/helpers/types.d.ts.map +1 -0
  39. package/dist/index.js +11 -17
  40. package/dist/subtle.d.ts +3 -2
  41. package/dist/subtle.d.ts.map +1 -1
  42. package/dist/subtle.js +21 -15
  43. package/dist/vm/checkpoint.d.ts +9 -0
  44. package/dist/vm/checkpoint.d.ts.map +1 -0
  45. package/dist/vm/helpers.d.ts +4 -10
  46. package/dist/vm/helpers.d.ts.map +1 -1
  47. package/dist/vm/index.d.ts +3 -3
  48. package/dist/vm/index.d.ts.map +1 -1
  49. package/dist/vm/lib/global/bit.d.ts +7 -7
  50. package/dist/vm/lib/global/bit.d.ts.map +1 -1
  51. package/dist/vm/lib/global/debug.d.ts +2 -2
  52. package/dist/vm/lib/global/debug.d.ts.map +1 -1
  53. package/dist/vm/lib/global/index.d.ts +0 -1
  54. package/dist/vm/lib/global/index.d.ts.map +1 -1
  55. package/dist/vm/lib/global/json.d.ts +2 -2
  56. package/dist/vm/lib/global/json.d.ts.map +1 -1
  57. package/dist/vm/lib/global/math-additional.d.ts +1 -1
  58. package/dist/vm/lib/global/math-additional.d.ts.map +1 -1
  59. package/dist/vm/lib/global/math-arr.d.ts +5 -5
  60. package/dist/vm/lib/global/math-arr.d.ts.map +1 -1
  61. package/dist/vm/lib/global/math-unary.d.ts +26 -26
  62. package/dist/vm/lib/global/math-unary.d.ts.map +1 -1
  63. package/dist/vm/lib/global/math.d.ts +3 -3
  64. package/dist/vm/lib/global/math.d.ts.map +1 -1
  65. package/dist/vm/lib/global/sequence/all-any.d.ts +2 -2
  66. package/dist/vm/lib/global/sequence/all-any.d.ts.map +1 -1
  67. package/dist/vm/lib/global/sequence/entries.d.ts +5 -5
  68. package/dist/vm/lib/global/sequence/entries.d.ts.map +1 -1
  69. package/dist/vm/lib/global/sequence/find.d.ts +3 -3
  70. package/dist/vm/lib/global/sequence/find.d.ts.map +1 -1
  71. package/dist/vm/lib/global/sequence/flatten.d.ts +1 -1
  72. package/dist/vm/lib/global/sequence/flatten.d.ts.map +1 -1
  73. package/dist/vm/lib/global/sequence/len.d.ts +1 -1
  74. package/dist/vm/lib/global/sequence/len.d.ts.map +1 -1
  75. package/dist/vm/lib/global/sequence/map-filter.d.ts +3 -3
  76. package/dist/vm/lib/global/sequence/map-filter.d.ts.map +1 -1
  77. package/dist/vm/lib/global/sequence/repeat.d.ts +1 -1
  78. package/dist/vm/lib/global/sequence/repeat.d.ts.map +1 -1
  79. package/dist/vm/lib/global/sequence/reverse.d.ts +1 -1
  80. package/dist/vm/lib/global/sequence/reverse.d.ts.map +1 -1
  81. package/dist/vm/lib/global/sequence/sort.d.ts +2 -2
  82. package/dist/vm/lib/global/sequence/sort.d.ts.map +1 -1
  83. package/dist/vm/lib/global/sequence/with.d.ts +2 -2
  84. package/dist/vm/lib/global/sequence/with.d.ts.map +1 -1
  85. package/dist/vm/lib/global/sequence/zip.d.ts +1 -1
  86. package/dist/vm/lib/global/sequence/zip.d.ts.map +1 -1
  87. package/dist/vm/lib/global/string.d.ts +10 -10
  88. package/dist/vm/lib/global/string.d.ts.map +1 -1
  89. package/dist/vm/lib/global/time.d.ts +3 -13
  90. package/dist/vm/lib/global/time.d.ts.map +1 -1
  91. package/dist/vm/lib/global/to-primitive.d.ts +4 -4
  92. package/dist/vm/lib/global/to-primitive.d.ts.map +1 -1
  93. package/dist/vm/lib/helpers.d.ts +53 -0
  94. package/dist/vm/lib/helpers.d.ts.map +1 -0
  95. package/dist/vm/lib/index.d.ts +4 -0
  96. package/dist/vm/lib/index.d.ts.map +1 -0
  97. package/dist/vm/lib/{_loader.d.ts → loader.d.ts} +5 -5
  98. package/dist/vm/lib/loader.d.ts.map +1 -0
  99. package/dist/vm/lib/mod/index.d.ts +2 -0
  100. package/dist/vm/lib/mod/index.d.ts.map +1 -0
  101. package/dist/vm/lib/mod/matrix.d.ts +15 -0
  102. package/dist/vm/lib/mod/matrix.d.ts.map +1 -0
  103. package/dist/vm/operations.d.ts +2 -4
  104. package/dist/vm/operations.d.ts.map +1 -1
  105. package/dist/vm/types/boundary.d.ts +1 -1
  106. package/dist/vm/types/boundary.d.ts.map +1 -1
  107. package/dist/vm/types/context.d.ts +10 -9
  108. package/dist/vm/types/context.d.ts.map +1 -1
  109. package/dist/vm/types/extern.d.ts +1 -3
  110. package/dist/vm/types/extern.d.ts.map +1 -1
  111. package/dist/vm/types/function.d.ts +1 -6
  112. package/dist/vm/types/function.d.ts.map +1 -1
  113. package/dist/vm/types/index.d.ts +31 -17
  114. package/dist/vm/types/index.d.ts.map +1 -1
  115. package/dist/vm/types/module.d.ts +2 -4
  116. package/dist/vm/types/module.d.ts.map +1 -1
  117. package/dist/vm/types/wrapper.d.ts +0 -2
  118. package/dist/vm/types/wrapper.d.ts.map +1 -1
  119. package/package.json +7 -3
  120. package/src/cli/index.ts +1 -1
  121. package/src/compiler/compile-fast.ts +1 -2
  122. package/src/compiler/create-script.ts +12 -2
  123. package/src/compiler/diagnostic.ts +17 -8
  124. package/src/compiler/emit/constants.ts +2 -0
  125. package/src/compiler/emit/consts.ts +47 -0
  126. package/src/compiler/emit/globals.ts +39 -0
  127. package/src/compiler/{emit.ts → emit/index.ts} +16 -200
  128. package/src/compiler/emit/sourcemap.ts +163 -0
  129. package/src/compiler/index.ts +9 -9
  130. package/src/compiler/worker.ts +1 -1
  131. package/src/helpers/constants.ts +12 -0
  132. package/src/helpers/convert.ts +128 -0
  133. package/src/{vm → helpers}/error.ts +1 -1
  134. package/src/helpers/serialize.ts +71 -24
  135. package/src/helpers/types.ts +267 -0
  136. package/src/subtle.ts +3 -1
  137. package/src/vm/checkpoint.ts +42 -0
  138. package/src/vm/helpers.ts +9 -53
  139. package/src/vm/index.ts +3 -3
  140. package/src/vm/lib/global/bit.ts +8 -9
  141. package/src/vm/lib/global/debug.ts +5 -4
  142. package/src/vm/lib/global/index.ts +0 -1
  143. package/src/vm/lib/global/json.ts +2 -2
  144. package/src/vm/lib/global/math-additional.ts +2 -4
  145. package/src/vm/lib/global/math-arr.ts +1 -1
  146. package/src/vm/lib/global/math-unary.ts +2 -4
  147. package/src/vm/lib/global/math.ts +3 -4
  148. package/src/vm/lib/global/sequence/all-any.ts +11 -6
  149. package/src/vm/lib/global/sequence/entries.ts +1 -1
  150. package/src/vm/lib/global/sequence/find.ts +4 -3
  151. package/src/vm/lib/global/sequence/flatten.ts +2 -3
  152. package/src/vm/lib/global/sequence/len.ts +1 -1
  153. package/src/vm/lib/global/sequence/map-filter.ts +4 -3
  154. package/src/vm/lib/global/sequence/repeat.ts +2 -4
  155. package/src/vm/lib/global/sequence/reverse.ts +1 -1
  156. package/src/vm/lib/global/sequence/sort.ts +6 -5
  157. package/src/vm/lib/global/sequence/with.ts +21 -20
  158. package/src/vm/lib/global/sequence/zip.ts +3 -3
  159. package/src/vm/lib/global/string.ts +16 -27
  160. package/src/vm/lib/global/time.ts +59 -30
  161. package/src/vm/lib/global/to-primitive.ts +27 -18
  162. package/src/vm/lib/{_helpers.ts → helpers.ts} +129 -41
  163. package/src/vm/lib/index.ts +16 -0
  164. package/src/vm/lib/{_loader.ts → loader.ts} +3 -11
  165. package/src/vm/lib/mod/index.ts +1 -0
  166. package/src/vm/lib/{global/mod → mod}/matrix.ts +9 -7
  167. package/src/vm/operations.ts +31 -126
  168. package/src/vm/types/boundary.ts +10 -13
  169. package/src/vm/types/context.ts +17 -24
  170. package/src/vm/types/extern.ts +8 -15
  171. package/src/vm/types/function.ts +4 -19
  172. package/src/vm/types/index.ts +47 -25
  173. package/src/vm/types/module.ts +3 -7
  174. package/src/vm/types/wrapper.ts +1 -5
  175. package/dist/chunk-35JGBXRE.js +0 -1
  176. package/dist/chunk-JVFUK7AN.js.map +0 -6
  177. package/dist/chunk-NT235HY3.js.map +0 -6
  178. package/dist/compiler/emit.d.ts +0 -5
  179. package/dist/compiler/emit.d.ts.map +0 -1
  180. package/dist/vm/error.d.ts.map +0 -1
  181. package/dist/vm/lib/_helpers.d.ts +0 -35
  182. package/dist/vm/lib/_helpers.d.ts.map +0 -1
  183. package/dist/vm/lib/_loader.d.ts.map +0 -1
  184. package/dist/vm/lib/global/mod/index.d.ts +0 -3
  185. package/dist/vm/lib/global/mod/index.d.ts.map +0 -1
  186. package/dist/vm/lib/global/mod/matrix.d.ts +0 -15
  187. package/dist/vm/lib/global/mod/matrix.d.ts.map +0 -1
  188. package/dist/vm/types/any.d.ts +0 -10
  189. package/dist/vm/types/any.d.ts.map +0 -1
  190. package/dist/vm/types/array.d.ts +0 -12
  191. package/dist/vm/types/array.d.ts.map +0 -1
  192. package/dist/vm/types/callable.d.ts +0 -5
  193. package/dist/vm/types/callable.d.ts.map +0 -1
  194. package/dist/vm/types/const.d.ts +0 -15
  195. package/dist/vm/types/const.d.ts.map +0 -1
  196. package/dist/vm/types/immutable.d.ts +0 -15
  197. package/dist/vm/types/immutable.d.ts.map +0 -1
  198. package/dist/vm/types/primitive.d.ts +0 -7
  199. package/dist/vm/types/primitive.d.ts.map +0 -1
  200. package/dist/vm/types/record.d.ts +0 -20
  201. package/dist/vm/types/record.d.ts.map +0 -1
  202. package/dist/vm/types/script.d.ts +0 -14
  203. package/dist/vm/types/script.d.ts.map +0 -1
  204. package/dist/vm/types/value.d.ts +0 -14
  205. package/dist/vm/types/value.d.ts.map +0 -1
  206. package/src/vm/lib/global/mod/index.ts +0 -4
  207. package/src/vm/types/any.ts +0 -33
  208. package/src/vm/types/array.ts +0 -19
  209. package/src/vm/types/callable.ts +0 -10
  210. package/src/vm/types/const.ts +0 -109
  211. package/src/vm/types/immutable.ts +0 -22
  212. package/src/vm/types/primitive.ts +0 -14
  213. package/src/vm/types/record.ts +0 -53
  214. package/src/vm/types/script.ts +0 -18
  215. package/src/vm/types/value.ts +0 -22
  216. /package/dist/{chunk-35JGBXRE.js.map → chunk-RIT53WVY.js.map} +0 -0
@@ -1,42 +1,31 @@
1
1
  import {
2
- $Add,
3
- $Call,
4
- $Div,
5
- $Format,
6
- $Mul,
7
- $Same,
8
- $Sub,
9
- $ToBoolean,
10
- $ToNumber,
11
- $ToString,
12
- $Type,
13
- Cp,
14
2
  DiagnosticCode,
15
- Element,
16
- GlobalFallback,
17
3
  VM_ARRAY_MAX_LENGTH,
4
+ VM_FUNCTION_ANONYMOUS_NAME,
5
+ VM_SCRIPT_NAME,
18
6
  VmError,
19
- VmFunction,
20
- VmModule,
21
- VmSharedContext,
22
7
  __export,
8
+ apply,
23
9
  create,
24
10
  defineProperty,
11
+ display,
25
12
  emit,
26
13
  entries,
27
- formatDiagnostic,
14
+ formatDiagnostics,
28
15
  fromEntries,
29
16
  generateBytecode,
30
17
  generateBytecodeSync,
18
+ getPrototypeOf,
31
19
  hasOwn,
32
- helpers_exports,
20
+ hasOwnEnumerable,
21
+ innerToString,
33
22
  isArray,
34
23
  isFinite,
35
24
  isInteger,
36
25
  isNaN,
37
26
  isSafeInteger,
27
+ isVmAny,
38
28
  isVmArray,
39
- isVmArrayLikeRecordByEntires,
40
29
  isVmCallable,
41
30
  isVmConst,
42
31
  isVmExtern,
@@ -44,40 +33,1163 @@ import {
44
33
  isVmModule,
45
34
  isVmPrimitive,
46
35
  isVmRecord,
36
+ isVmWrapper,
37
+ kVmContext,
38
+ kVmExtern,
39
+ kVmFunction,
40
+ kVmFunctionProxy,
41
+ kVmModule,
42
+ kVmScript,
43
+ kVmWrapper,
47
44
  keys,
48
- operations_exports,
49
45
  parseDiagnostics,
46
+ toBoolean,
47
+ toFormat,
48
+ toNumber,
49
+ toString,
50
50
  values
51
- } from "./chunk-JVFUK7AN.js";
51
+ } from "./chunk-YZGL3D7L.js";
52
52
 
53
- // src/subtle.ts
54
- import { getModule } from "@mirascript/bindings";
53
+ // src/vm/operations.ts
54
+ var operations_exports = {};
55
+ __export(operations_exports, {
56
+ $Add: () => $Add,
57
+ $Aeq: () => $Aeq,
58
+ $And: () => $And,
59
+ $ArraySpread: () => $ArraySpread,
60
+ $AssertInit: () => $AssertInit,
61
+ $AssertNonNil: () => $AssertNonNil,
62
+ $Call: () => $Call,
63
+ $Concat: () => $Concat,
64
+ $Div: () => $Div,
65
+ $Eq: () => $Eq,
66
+ $Format: () => $Format,
67
+ $Get: () => $Get,
68
+ $Gt: () => $Gt,
69
+ $Gte: () => $Gte,
70
+ $Has: () => $Has,
71
+ $In: () => $In,
72
+ $IsArray: () => $IsArray,
73
+ $IsBoolean: () => $IsBoolean,
74
+ $IsNumber: () => $IsNumber,
75
+ $IsRecord: () => $IsRecord,
76
+ $IsString: () => $IsString,
77
+ $Iterable: () => $Iterable,
78
+ $Length: () => $Length,
79
+ $Lt: () => $Lt,
80
+ $Lte: () => $Lte,
81
+ $Mod: () => $Mod,
82
+ $Mul: () => $Mul,
83
+ $Naeq: () => $Naeq,
84
+ $Neg: () => $Neg,
85
+ $Neq: () => $Neq,
86
+ $Not: () => $Not,
87
+ $Nsame: () => $Nsame,
88
+ $Omit: () => $Omit,
89
+ $Or: () => $Or,
90
+ $Pick: () => $Pick,
91
+ $Pos: () => $Pos,
92
+ $Pow: () => $Pow,
93
+ $RecordSpread: () => $RecordSpread,
94
+ $Same: () => $Same,
95
+ $Set: () => $Set,
96
+ $Slice: () => $Slice,
97
+ $SliceExclusive: () => $SliceExclusive,
98
+ $Sub: () => $Sub,
99
+ $ToBoolean: () => $ToBoolean,
100
+ $ToNumber: () => $ToNumber,
101
+ $ToString: () => $ToString,
102
+ $Type: () => $Type
103
+ });
104
+ var { abs, min, trunc, ceil } = Math;
105
+ var { slice, at } = Array.prototype;
106
+ var isSame = (a, b) => {
107
+ if (typeof a == "number" && typeof b == "number") return a === b || isNaN(a) && isNaN(b);
108
+ if (a === b) return true;
109
+ if (a == null || typeof a != "object" || b == null || typeof b != "object") return false;
110
+ if (isVmWrapper(a)) return a.same(b);
111
+ if (isVmWrapper(b)) return b.same(a);
112
+ if (isVmArray(a) && isVmArray(b)) {
113
+ const len2 = a.length;
114
+ if (len2 !== b.length) {
115
+ return false;
116
+ }
117
+ for (let i = 0; i < len2; i++) {
118
+ if (!isSame(a[i] ?? null, b[i] ?? null)) {
119
+ return false;
120
+ }
121
+ }
122
+ return true;
123
+ }
124
+ if (!isVmArray(a) && !isVmArray(b)) {
125
+ const aKeys = keys(a);
126
+ const bKeys = keys(b);
127
+ if (aKeys.length !== bKeys.length) {
128
+ return false;
129
+ }
130
+ for (const key of aKeys) {
131
+ if (!hasOwnEnumerable(b, key)) {
132
+ return false;
133
+ }
134
+ const av = a[key] ?? null;
135
+ const bv = b[key] ?? null;
136
+ if (!isSame(av, bv)) {
137
+ return false;
138
+ }
139
+ }
140
+ return true;
141
+ }
142
+ return false;
143
+ };
144
+ var overloadNumberString = (a, b) => {
145
+ if (typeof a == "number" || typeof b == "number") return true;
146
+ if (typeof a == "string" || typeof b == "string") return false;
147
+ return true;
148
+ };
149
+ var $Add = (a, b) => {
150
+ return $ToNumber(a) + $ToNumber(b);
151
+ };
152
+ var $Sub = (a, b) => {
153
+ return $ToNumber(a) - $ToNumber(b);
154
+ };
155
+ var $Mul = (a, b) => {
156
+ return $ToNumber(a) * $ToNumber(b);
157
+ };
158
+ var $Div = (a, b) => {
159
+ return $ToNumber(a) / $ToNumber(b);
160
+ };
161
+ var $Mod = (a, b) => {
162
+ return $ToNumber(a) % $ToNumber(b);
163
+ };
164
+ var $Pow = (a, b) => {
165
+ return $ToNumber(a) ** $ToNumber(b);
166
+ };
167
+ var $And = (a, b) => {
168
+ return $ToBoolean(a) && $ToBoolean(b);
169
+ };
170
+ var $Or = (a, b) => {
171
+ return $ToBoolean(a) || $ToBoolean(b);
172
+ };
173
+ var $Gt = (a, b) => {
174
+ if (overloadNumberString(a, b)) {
175
+ return $ToNumber(a) > $ToNumber(b);
176
+ } else {
177
+ return $ToString(a) > $ToString(b);
178
+ }
179
+ };
180
+ var $Gte = (a, b) => {
181
+ if (overloadNumberString(a, b)) {
182
+ return $ToNumber(a) >= $ToNumber(b);
183
+ } else {
184
+ return $ToString(a) >= $ToString(b);
185
+ }
186
+ };
187
+ var $Lt = (a, b) => {
188
+ if (overloadNumberString(a, b)) {
189
+ return $ToNumber(a) < $ToNumber(b);
190
+ } else {
191
+ return $ToString(a) < $ToString(b);
192
+ }
193
+ };
194
+ var $Lte = (a, b) => {
195
+ if (overloadNumberString(a, b)) {
196
+ return $ToNumber(a) <= $ToNumber(b);
197
+ } else {
198
+ return $ToString(a) <= $ToString(b);
199
+ }
200
+ };
201
+ var $Eq = (a, b) => {
202
+ $AssertInit(a);
203
+ $AssertInit(b);
204
+ if (typeof a == "number" && typeof b == "number") return a === b;
205
+ return isSame(a, b);
206
+ };
207
+ var $Neq = (a, b) => {
208
+ return !$Eq(a, b);
209
+ };
210
+ var $Aeq = (a, b) => {
211
+ if (overloadNumberString(a, b)) {
212
+ const an = $ToNumber(a);
213
+ const bn = $ToNumber(b);
214
+ const EPS = 1e-15;
215
+ if (isNaN(an) || isNaN(bn)) return false;
216
+ if (an === bn) return true;
217
+ const absoluteDifference = abs(an - bn);
218
+ if (absoluteDifference < EPS) return true;
219
+ const base = min(abs(an), abs(bn));
220
+ return absoluteDifference < base * EPS;
221
+ } else {
222
+ const as = $ToString(a);
223
+ const bs = $ToString(b);
224
+ if (as === bs) return true;
225
+ const ai = as.toLowerCase();
226
+ const bi = bs.toLowerCase();
227
+ if (ai === bi) return true;
228
+ const an = ai.normalize("NFC");
229
+ const bn = bi.normalize("NFC");
230
+ return an === bn;
231
+ }
232
+ };
233
+ var $Naeq = (a, b) => {
234
+ return !$Aeq(a, b);
235
+ };
236
+ var $Same = (a, b) => {
237
+ $AssertInit(a);
238
+ $AssertInit(b);
239
+ return isSame(a, b);
240
+ };
241
+ var $Nsame = (a, b) => {
242
+ return !$Same(a, b);
243
+ };
244
+ var $In = (value, iterable) => {
245
+ $AssertInit(value);
246
+ $AssertInit(iterable);
247
+ if (iterable == null) return false;
248
+ if (typeof iterable != "object") return false;
249
+ if (isVmArray(iterable)) {
250
+ if (value == null) {
251
+ for (const item of iterable) if (item == null) return true;
252
+ return false;
253
+ }
254
+ if (isVmPrimitive(value)) return iterable.includes(value);
255
+ return iterable.some((item = null) => isSame(item, value));
256
+ }
257
+ const key = toString(value, void 0);
258
+ if (isVmWrapper(iterable)) return iterable.has(key);
259
+ return hasOwnEnumerable(iterable, key);
260
+ };
261
+ var $Concat = (...args) => {
262
+ return args.map((a) => toFormat(a, null)).join("");
263
+ };
264
+ var $Pos = (a) => {
265
+ return $ToNumber(a);
266
+ };
267
+ var $Neg = (a) => {
268
+ return -$ToNumber(a);
269
+ };
270
+ var $Not = (a) => {
271
+ return !$ToBoolean(a);
272
+ };
273
+ var $Length = (value) => {
274
+ $AssertInit(value);
275
+ if (isVmArray(value)) return value.length;
276
+ if (isVmRecord(value)) return keys(value).length;
277
+ if (isVmWrapper(value)) {
278
+ return value.keys().length;
279
+ }
280
+ return Number.NaN;
281
+ };
282
+ var $Omit = (value, omitted) => {
283
+ $AssertInit(value);
284
+ if (value == null || !isVmRecord(value)) return {};
285
+ const result = {};
286
+ const valueKeys = keys(value);
287
+ const omittedSet = new Set(omitted.map($ToString));
288
+ for (const key of valueKeys) {
289
+ if (!omittedSet.has(key)) {
290
+ result[key] = value[key] ?? null;
291
+ }
292
+ }
293
+ return result;
294
+ };
295
+ var $Pick = (value, picked) => {
296
+ $AssertInit(value);
297
+ if (value == null || !isVmRecord(value)) return {};
298
+ const result = {};
299
+ for (const key of picked) {
300
+ const k = $ToString(key);
301
+ if (hasOwnEnumerable(value, k)) {
302
+ result[k] = value[k] ?? null;
303
+ }
304
+ }
305
+ return result;
306
+ };
307
+ var sliceCore = (value, start, end, exclusive) => {
308
+ const { length } = value;
309
+ if (isNaN(start)) start = 0;
310
+ else if (start < 0) start = length + start;
311
+ if (isNaN(end)) end = exclusive ? length : length - 1;
312
+ else if (end < 0) end = length + end;
313
+ start = ceil(start);
314
+ if (exclusive || !isSafeInteger(end)) {
315
+ end = ceil(end);
316
+ } else {
317
+ end = end + 1;
318
+ }
319
+ return slice.call(value, start, end);
320
+ };
321
+ var $Slice = (value, start, end) => {
322
+ $AssertInit(value);
323
+ if (!isVmArray(value)) throw new VmError(`Expected array, got ${$Type(value)}`, []);
324
+ const s = start != null ? $ToNumber(start) : 0;
325
+ const e = end != null ? $ToNumber(end) : value.length - 1;
326
+ return sliceCore(value, s, e, false);
327
+ };
328
+ var $SliceExclusive = (value, start, end) => {
329
+ $AssertInit(value);
330
+ if (!isVmArray(value)) throw new VmError(`Expected array, got ${$Type(value)}`, []);
331
+ const s = start != null ? $ToNumber(start) : 0;
332
+ const e = end != null ? $ToNumber(end) : value.length;
333
+ return sliceCore(value, s, e, true);
334
+ };
335
+ var $AssertInit = (value) => {
336
+ if (value === void 0) throw new VmError(`Uninitialized value`, null);
337
+ };
338
+ var $Call = (func, args) => {
339
+ for (const a of args) {
340
+ $AssertInit(a);
341
+ }
342
+ if (isVmExtern(func)) {
343
+ return func.call(args) ?? null;
344
+ }
345
+ if (isVmFunction(func)) {
346
+ return func(...args) ?? null;
347
+ }
348
+ throw new VmError(`Value is not callable: ${display(func)}`, null);
349
+ };
350
+ var $Type = (value) => {
351
+ if (value == null) return "nil";
352
+ if (isVmWrapper(value)) return value.type;
353
+ if (isVmArray(value)) return "array";
354
+ if (typeof value == "object") return "record";
355
+ return typeof value;
356
+ };
357
+ var $ToBoolean = (value) => {
358
+ if (typeof value == "boolean") return value;
359
+ $AssertInit(value);
360
+ return toBoolean(value, void 0);
361
+ };
362
+ var $ToString = (value) => {
363
+ if (typeof value == "string") return value;
364
+ $AssertInit(value);
365
+ return toString(value, void 0);
366
+ };
367
+ var $ToNumber = (value) => {
368
+ if (typeof value == "number") return value;
369
+ $AssertInit(value);
370
+ return toNumber(value, void 0);
371
+ };
372
+ var $IsBoolean = (value) => {
373
+ $AssertInit(value);
374
+ return typeof value == "boolean";
375
+ };
376
+ var $IsNumber = (value) => {
377
+ $AssertInit(value);
378
+ return typeof value == "number";
379
+ };
380
+ var $IsString = (value) => {
381
+ $AssertInit(value);
382
+ return typeof value == "string";
383
+ };
384
+ var $IsRecord = (value) => {
385
+ $AssertInit(value);
386
+ return isVmRecord(value);
387
+ };
388
+ var $IsArray = (value) => {
389
+ $AssertInit(value);
390
+ return isVmArray(value);
391
+ };
392
+ var $AssertNonNil = (value) => {
393
+ $AssertInit(value);
394
+ if (value !== null) return;
395
+ throw new VmError("Expected non-nil value", null);
396
+ };
397
+ var $Has = (obj, key) => {
398
+ $AssertInit(obj);
399
+ const pk = $ToString(key);
400
+ if (obj == null || typeof obj != "object") return false;
401
+ if (isVmWrapper(obj)) return obj.has(pk);
402
+ return hasOwnEnumerable(obj, pk);
403
+ };
404
+ var $Get = (obj, key) => {
405
+ $AssertInit(obj);
406
+ if (isVmArray(obj)) {
407
+ const index = $ToNumber(key);
408
+ if (isNaN(index)) return null;
409
+ return at.call(obj, trunc(index)) ?? null;
410
+ }
411
+ const pk = $ToString(key);
412
+ if (obj == null || typeof obj != "object") return null;
413
+ if (isVmWrapper(obj)) return obj.get(pk) ?? null;
414
+ if (!hasOwnEnumerable(obj, pk)) return null;
415
+ return obj[pk] ?? null;
416
+ };
417
+ var $Set = (obj, key, value) => {
418
+ $AssertInit(obj);
419
+ $AssertInit(value);
420
+ const pk = $ToString(key);
421
+ if (obj == null) return;
422
+ if (!isVmExtern(obj)) throw new VmError(`Expected extern, got ${$Type(obj)}`, void 0);
423
+ obj.set(pk, value);
424
+ };
425
+ var $Iterable = (value) => {
426
+ $AssertInit(value);
427
+ if (isVmWrapper(value)) return value.keys();
428
+ if (isVmArray(value)) return value;
429
+ if (value != null && typeof value == "object") return keys(value);
430
+ throw new VmError(`Value is not iterable`, isVmFunction(value) ? [] : [value]);
431
+ };
432
+ var $RecordSpread = (record) => {
433
+ $AssertInit(record);
434
+ if (record == null || isVmRecord(record)) return record;
435
+ if (isVmArray(record)) {
436
+ const result = {};
437
+ const len2 = record.length;
438
+ for (let i = 0; i < len2; i++) {
439
+ const item = record[i];
440
+ result[i] = item ?? null;
441
+ }
442
+ return result;
443
+ }
444
+ if (isVmExtern(record)) {
445
+ const result = create(null);
446
+ for (const key of record.keys()) {
447
+ const value = record.get(key) ?? null;
448
+ if (isVmPrimitive(value)) {
449
+ result[key] = value;
450
+ }
451
+ }
452
+ return result;
453
+ }
454
+ throw new VmError(`Expected record, array, extern or nil, got ${$Type(record)}`, null);
455
+ };
456
+ var $ArraySpread = (array) => {
457
+ $AssertInit(array);
458
+ if (array == null) return [];
459
+ if (isVmArray(array)) return array;
460
+ if (isVmExtern(array) && typeof array.value[Symbol.iterator] == "function") {
461
+ const result = [];
462
+ for (const item of array.value) {
463
+ if (isVmPrimitive(item)) {
464
+ result.push(item);
465
+ } else {
466
+ result.push(null);
467
+ }
468
+ }
469
+ return result;
470
+ }
471
+ throw new VmError(`Expected array, iterable extern or nil, got ${$Type(array)}`, []);
472
+ };
473
+ var $Format = (value, format2) => {
474
+ $AssertInit(value);
475
+ const f = format2 == null ? "" : $ToString(format2);
476
+ return toFormat(value, f);
477
+ };
478
+
479
+ // src/vm/types/wrapper.ts
480
+ var VmWrapper = class {
481
+ constructor(value) {
482
+ this.value = value;
483
+ }
484
+ /** Convert the object to JSON */
485
+ toJSON() {
486
+ return void 0;
487
+ }
488
+ /** 转为字符串 */
489
+ toString(useBraces) {
490
+ const { type, describe } = this;
491
+ if (!describe) return `<${type}>`;
492
+ return `<${type} ${describe}>`;
493
+ }
494
+ };
495
+ Object.defineProperty(VmWrapper.prototype, kVmWrapper, { value: true });
496
+
497
+ // src/vm/types/boundary.ts
498
+ function toVmFunctionProxy(fn) {
499
+ const cached = fn[kVmFunctionProxy];
500
+ if (cached != null) return cached;
501
+ const proxy = (...args) => {
502
+ const ret = $Call(
503
+ fn,
504
+ // 作为函数参数传入的值一定丢失了它的 this
505
+ args.map((v) => wrapToVmValue(v, null))
506
+ );
507
+ return unwrapFromVmValue(ret);
508
+ };
509
+ defineProperty(fn, kVmFunctionProxy, { value: proxy });
510
+ defineProperty(proxy, kVmFunctionProxy, { value: fn });
511
+ defineProperty(proxy, "name", {
512
+ value: fn.name,
513
+ configurable: true
514
+ });
515
+ return proxy;
516
+ }
517
+ function fromVmFunctionProxy(fn) {
518
+ if (isVmFunction(fn)) return fn;
519
+ const original = fn[kVmFunctionProxy];
520
+ if (original && isVmFunction(original)) return original;
521
+ return void 0;
522
+ }
523
+ function wrapToVmValue(value, thisArg = null, assumeVmValue) {
524
+ if (value == null) return null;
525
+ switch (typeof value) {
526
+ case "function": {
527
+ const unwrapped = fromVmFunctionProxy(value);
528
+ if (unwrapped) return unwrapped;
529
+ return new VmExtern(value, thisArg);
530
+ }
531
+ case "object": {
532
+ if (isVmWrapper(value)) return value;
533
+ if (value instanceof Date) return value.valueOf();
534
+ if (assumeVmValue?.(value)) return value;
535
+ return new VmExtern(value);
536
+ }
537
+ case "string":
538
+ case "number":
539
+ case "boolean":
540
+ return value;
541
+ case "bigint":
542
+ return Number(value);
543
+ case "symbol":
544
+ case "undefined":
545
+ default:
546
+ return null;
547
+ }
548
+ }
549
+ function unwrapFromVmValue(value) {
550
+ if (isVmFunction(value)) {
551
+ return toVmFunctionProxy(value);
552
+ }
553
+ if (value == null || typeof value != "object") return value;
554
+ if (!isVmExtern(value)) return value;
555
+ if (value.thisArg == null || typeof value.value != "function") {
556
+ return value.value;
557
+ }
558
+ const f = value;
559
+ const caller = f.thisArg.value;
560
+ return new Proxy(f.value, {
561
+ apply(target, thisArg, args) {
562
+ return apply(target, caller, args);
563
+ }
564
+ });
565
+ }
566
+
567
+ // src/vm/types/extern.ts
568
+ var ObjectPrototype = Object.prototype;
569
+ var ObjectToString = ObjectPrototype.toString;
570
+ var FunctionToString = Function.prototype.toString;
571
+ var ArrayToString = Array.prototype.toString;
572
+ var ArrayMap = Array.prototype.map;
573
+ var VmExtern = class extends VmWrapper {
574
+ constructor(value, thisArg = null) {
575
+ super(value);
576
+ this.thisArg = thisArg;
577
+ }
578
+ /** Check if the object has a property */
579
+ access(key, read) {
580
+ if (key.startsWith("_")) return false;
581
+ if (typeof this.value == "function" && (key === "prototype" || key === "arguments" || key === "caller"))
582
+ return false;
583
+ if (hasOwn(this.value, key)) return true;
584
+ if (!read) return true;
585
+ if (!(key in this.value)) return false;
586
+ if (key === "constructor") return false;
587
+ const prop = this.value[key];
588
+ if (key in Function.prototype && prop === Function.prototype[key]) return false;
589
+ if (key in Array.prototype && prop === Array.prototype[key]) return false;
590
+ if (key in Object.prototype && prop === Object.prototype[key]) return false;
591
+ return true;
592
+ }
593
+ /** 决定是否对属性进行包装 */
594
+ assumeVmValue(value, key) {
595
+ return false;
596
+ }
597
+ /** @inheritdoc */
598
+ has(key) {
599
+ return this.access(key, true);
600
+ }
601
+ /** @inheritdoc */
602
+ get(key) {
603
+ if (!this.has(key)) return void 0;
604
+ const prop = this.value[key];
605
+ return wrapToVmValue(prop, this, (v) => this.assumeVmValue(v, key));
606
+ }
607
+ /** Set a property on the object */
608
+ set(key, value) {
609
+ if (!this.access(key, false)) return false;
610
+ const prop = unwrapFromVmValue(value);
611
+ this.value[key] = prop;
612
+ return true;
613
+ }
614
+ /** Call extern value */
615
+ call(args) {
616
+ const { value } = this;
617
+ if (typeof value != "function") {
618
+ throw VmError.from(`Not a callable extern`, null, null);
619
+ }
620
+ const caller = this.thisArg?.value ?? null;
621
+ const unwrappedArgs = args.map(unwrapFromVmValue);
622
+ let ret;
623
+ try {
624
+ ret = apply(value, caller, unwrappedArgs);
625
+ } catch (ex) {
626
+ throw VmError.from(`Callable extern`, ex, null);
627
+ }
628
+ return wrapToVmValue(ret, null, (obj) => this.assumeVmValue(obj, void 0));
629
+ }
630
+ /** @inheritdoc */
631
+ keys() {
632
+ const keys4 = [];
633
+ for (const key in this.value) {
634
+ if (this.has(key)) keys4.push(key);
635
+ }
636
+ return keys4;
637
+ }
638
+ /** @inheritdoc */
639
+ same(other) {
640
+ if (!isVmExtern(other)) return false;
641
+ return this.value === other.value && this.thisArg === other.thisArg;
642
+ }
643
+ /** @inheritdoc */
644
+ toString(useBraces) {
645
+ const { toString: toString2 } = this.value;
646
+ if (typeof toString2 != "function" || toString2 === ObjectToString || toString2 === FunctionToString) {
647
+ return super.toString(useBraces);
648
+ }
649
+ if (toString2 === ArrayToString && isArray(this.value)) {
650
+ const mapped = ArrayMap.call(this.value, (item) => {
651
+ if (item === void 0) return "";
652
+ return innerToString(wrapToVmValue(item ?? null, null), true);
653
+ });
654
+ const str = mapped.join(", ");
655
+ if (useBraces) return `[${str}]`;
656
+ return str;
657
+ }
658
+ return String(this.value);
659
+ }
660
+ /** @inheritdoc */
661
+ get type() {
662
+ return "extern";
663
+ }
664
+ /** @inheritdoc */
665
+ get describe() {
666
+ const tag = ObjectToString.call(this.value).slice(8, -1);
667
+ if (isArray(this.value)) {
668
+ return `${tag}(${this.value.length})`;
669
+ } else if (tag === "Object") {
670
+ const proto = getPrototypeOf(this.value);
671
+ if (proto === ObjectPrototype) {
672
+ return "Object";
673
+ }
674
+ if (proto == null) {
675
+ return "Object: null prototype";
676
+ }
677
+ if (typeof proto.constructor === "function" && proto.constructor.name) {
678
+ return proto.constructor.name;
679
+ }
680
+ } else if (tag === "Function" && "prototype" in this.value && typeof this.value.prototype == "object") {
681
+ const { name } = this.value;
682
+ return `class ${name || "<anonymous>"}`;
683
+ } else if (tag === "Function") {
684
+ const { name } = this.value;
685
+ return `function ${name || "<anonymous>"}()`;
686
+ } else if (tag === "AsyncFunction") {
687
+ const { name } = this.value;
688
+ return `async function ${name || "<anonymous>"}()`;
689
+ } else if (tag === "GeneratorFunction") {
690
+ const { name } = this.value;
691
+ return `function* ${name || "<anonymous>"}()`;
692
+ } else if (tag === "AsyncGeneratorFunction") {
693
+ const { name } = this.value;
694
+ return `async function* ${name || "<anonymous>"}()`;
695
+ }
696
+ return tag;
697
+ }
698
+ };
699
+ Object.defineProperty(VmExtern.prototype, kVmExtern, { value: true });
55
700
 
56
- // src/helpers/constants.ts
57
- var constants_exports = {};
58
- __export(constants_exports, {
59
- REG_BIN: () => REG_BIN,
60
- REG_HEX: () => REG_HEX,
61
- REG_IDENTIFIER: () => REG_IDENTIFIER,
62
- REG_NUMBER: () => REG_NUMBER,
63
- REG_OCT: () => REG_OCT,
64
- REG_ORDINAL: () => REG_ORDINAL,
65
- REG_WHITESPACE: () => REG_WHITESPACE
701
+ // src/vm/checkpoint.ts
702
+ var MAX_DEPTH = 128;
703
+ var cpDepth = 0;
704
+ var cp = Number.NaN;
705
+ var cpTimeout = 100;
706
+ function Cp() {
707
+ if (!cp) {
708
+ cp = Date.now();
709
+ } else if (Date.now() - cp > cpTimeout) {
710
+ throw new RangeError("Execution timeout");
711
+ }
712
+ }
713
+ function CpEnter() {
714
+ cpDepth++;
715
+ if (cpDepth <= 1) {
716
+ cp = Date.now();
717
+ cpDepth = 1;
718
+ } else if (cpDepth > MAX_DEPTH) {
719
+ throw new RangeError("Maximum call depth exceeded");
720
+ } else {
721
+ Cp();
722
+ }
723
+ }
724
+ function CpExit() {
725
+ cpDepth--;
726
+ if (cpDepth < 1) {
727
+ cp = Number.NaN;
728
+ cpDepth = 0;
729
+ } else {
730
+ Cp();
731
+ }
732
+ }
733
+ function configCheckpoint(timeout = 100) {
734
+ if (typeof timeout !== "number" || timeout <= 0 || Number.isNaN(timeout)) {
735
+ throw new RangeError("Invalid timeout value");
736
+ }
737
+ cpTimeout = timeout;
738
+ }
739
+
740
+ // src/vm/types/function.ts
741
+ function VmFunction(fn, option = {}) {
742
+ if (typeof fn != "function") {
743
+ throw new TypeError("Invalid function");
744
+ }
745
+ const exists = fromVmFunctionProxy(fn);
746
+ if (exists) return exists;
747
+ const info = {
748
+ fullName: option.fullName ?? (fn.name === VM_FUNCTION_ANONYMOUS_NAME ? "" : fn.name),
749
+ isLib: option.isLib ?? false,
750
+ summary: option.summary || void 0,
751
+ params: option.params,
752
+ paramsType: option.paramsType,
753
+ returns: option.returns || void 0,
754
+ returnsType: option.returnsType || void 0,
755
+ examples: option.examples?.length ? option.examples : void 0
756
+ };
757
+ if (option.injectCp) {
758
+ const original = fn;
759
+ info.original = original;
760
+ fn = ((...args) => {
761
+ try {
762
+ CpEnter();
763
+ const ret = original(...args);
764
+ return ret;
765
+ } finally {
766
+ CpExit();
767
+ }
768
+ });
769
+ defineProperty(fn, "name", { value: original.name });
770
+ }
771
+ defineProperty(fn, kVmFunction, {
772
+ value: Object.freeze(info)
773
+ });
774
+ return fn;
775
+ }
776
+
777
+ // src/vm/types/context.ts
778
+ var VmSharedContext = create(null);
779
+ var VmSharedContextKeys = null;
780
+ function globalVarNotFound(name) {
781
+ throw new VmError(`Global variable '${name}' is not defined.`, null);
782
+ }
783
+ function defineVmContextValue(name, value, override = false) {
784
+ if (!override && name in VmSharedContext) throw new Error(`Global variable '${name}' is already defined.`);
785
+ let v;
786
+ if (typeof value == "function") {
787
+ v = VmFunction(value, {
788
+ isLib: true,
789
+ fullName: `global.${name}`
790
+ });
791
+ } else {
792
+ v = value;
793
+ }
794
+ VmSharedContext[name] = v ?? null;
795
+ VmSharedContextKeys = null;
796
+ }
797
+ var DefaultVmContext = Object.freeze({
798
+ [kVmContext]: true,
799
+ /** @inheritdoc */
800
+ keys() {
801
+ VmSharedContextKeys ??= Object.freeze(keys(VmSharedContext));
802
+ return VmSharedContextKeys;
803
+ },
804
+ /** @inheritdoc */
805
+ get(key) {
806
+ const val = VmSharedContext[key];
807
+ if (val === void 0) globalVarNotFound(key);
808
+ return val;
809
+ },
810
+ /** @inheritdoc */
811
+ has(key) {
812
+ return key in VmSharedContext;
813
+ }
66
814
  });
67
- var REG_IDENTIFIER = /(?:_+|@+|\$+|\p{XID_Start})\p{XID_Continue}*/u;
68
- var REG_ORDINAL = /(?:214748364[0-7]|21474836[0-3]\d|2147483[0-5]\d{2}|214748[0-2]\d{3}|21474[0-7]\d{4}|2147[0-3]\d{5}|214[0-6]\d{6}|21[0-3]\d{7}|20\d{8}|1\d{9}|[1-9]\d{0,8}|0)/;
69
- var REG_WHITESPACE = /[ \t\v\f\r\n]/u;
70
- var REG_HEX = /0[xX][a-fA-F0-9_]*[a-fA-F0-9]/;
71
- var REG_OCT = /0[oO][0-7_]*[0-7]/;
72
- var REG_BIN = /0[bB][01_]*[01]/;
73
- var REG_NUMBER = /\d[\d_]*(?:\.[\d_]+)?(?:[eE][+-]?[\d_]*\d)?/u;
815
+ var _a;
816
+ _a = kVmContext;
817
+ var ValueVmContext = class {
818
+ constructor(env, describe) {
819
+ this.env = env;
820
+ this.describe = describe;
821
+ this[_a] = true;
822
+ this.cachedKeys = null;
823
+ }
824
+ /** @inheritdoc */
825
+ keys() {
826
+ this.cachedKeys ??= keys(this.env);
827
+ return [...this.cachedKeys, ...DefaultVmContext.keys()];
828
+ }
829
+ /** @inheritdoc */
830
+ get(key) {
831
+ const val = this.env[key];
832
+ if (val === void 0) globalVarNotFound(key);
833
+ return val;
834
+ }
835
+ /** @inheritdoc */
836
+ has(key) {
837
+ return key in this.env;
838
+ }
839
+ };
840
+ var _a2;
841
+ _a2 = kVmContext;
842
+ var FactoryVmContext = class {
843
+ constructor(getter, enumerator, describe) {
844
+ this.getter = getter;
845
+ this.enumerator = enumerator;
846
+ this.describe = describe;
847
+ this[_a2] = true;
848
+ }
849
+ /** @inheritdoc */
850
+ keys() {
851
+ if (!this.enumerator) return DefaultVmContext.keys();
852
+ return [...this.enumerator(), ...DefaultVmContext.keys()];
853
+ }
854
+ /** @inheritdoc */
855
+ get(key) {
856
+ const value = this.getter(key);
857
+ if (value !== void 0) return value;
858
+ return DefaultVmContext.get(key);
859
+ }
860
+ /** @inheritdoc */
861
+ has(key) {
862
+ return this.getter(key) !== void 0 || DefaultVmContext.has(key);
863
+ }
864
+ };
865
+ function createVmContext(...args) {
866
+ if (args[0] == null && args[1] == null) {
867
+ return { ...DefaultVmContext };
868
+ }
869
+ if (typeof args[0] == "function") {
870
+ const [getter, enumerator, describer2] = args;
871
+ return new FactoryVmContext(getter, enumerator ?? void 0, describer2 ?? void 0);
872
+ }
873
+ const [vmValues, externValues, describer] = args;
874
+ const env = create(VmSharedContext);
875
+ if (vmValues) {
876
+ for (const [key, value] of entries(vmValues)) {
877
+ if (!isVmAny(value, false)) continue;
878
+ env[key] = value ?? null;
879
+ }
880
+ }
881
+ if (externValues) {
882
+ for (const [key, value] of entries(externValues)) {
883
+ env[key] = value == null ? null : wrapToVmValue(value, null);
884
+ }
885
+ }
886
+ return new ValueVmContext(env, describer ?? void 0);
887
+ }
888
+
889
+ // src/compiler/index.ts
890
+ import { loadModule } from "@mirascript/bindings";
891
+
892
+ // src/vm/helpers.ts
893
+ var helpers_exports = {};
894
+ __export(helpers_exports, {
895
+ ArrayRange: () => ArrayRange,
896
+ ArrayRangeExclusive: () => ArrayRangeExclusive,
897
+ Cp: () => Cp,
898
+ CpEnter: () => CpEnter,
899
+ CpExit: () => CpExit,
900
+ Element: () => Element,
901
+ ElementOpt: () => ElementOpt,
902
+ Function: () => Function2,
903
+ GlobalFallback: () => GlobalFallback,
904
+ Upvalue: () => Upvalue,
905
+ Vargs: () => Vargs
906
+ });
907
+ var Vargs = (varags) => {
908
+ for (let i = 0, l = varags.length; i < l; i++) {
909
+ const el = varags[i];
910
+ if (!isVmConst(el)) {
911
+ varags[i] = null;
912
+ }
913
+ }
914
+ return varags;
915
+ };
916
+ var Element = (value) => {
917
+ $AssertInit(value);
918
+ if (!isVmConst(value)) return null;
919
+ return value;
920
+ };
921
+ var ElementOpt = (key, value) => {
922
+ $AssertInit(value);
923
+ if (value == null || !isVmConst(value)) return {};
924
+ return { [key]: value };
925
+ };
926
+ var Function2 = (fn, name = VM_FUNCTION_ANONYMOUS_NAME) => {
927
+ defineProperty(fn, "name", { value: name });
928
+ return VmFunction(fn, { isLib: false, injectCp: false });
929
+ };
930
+ var Upvalue = (value) => {
931
+ $AssertInit(value);
932
+ return value;
933
+ };
934
+ var assertArrayLength = (start, end) => {
935
+ if (end - start > VM_ARRAY_MAX_LENGTH) {
936
+ throw new RangeError(`Array length exceeds maximum limit of ${VM_ARRAY_MAX_LENGTH}`);
937
+ }
938
+ };
939
+ var isEmptyRange = (start, end) => {
940
+ return !isFinite(start) || !isFinite(end) || start > end;
941
+ };
942
+ var ArrayRange = (start, end) => {
943
+ const s = $ToNumber(start);
944
+ const e = $ToNumber(end);
945
+ if (isEmptyRange(s, e)) return [];
946
+ assertArrayLength(s, e);
947
+ const arr = [];
948
+ for (let i = s; i <= e; i++) {
949
+ arr.push(i);
950
+ }
951
+ return arr;
952
+ };
953
+ var ArrayRangeExclusive = (start, end) => {
954
+ const s = $ToNumber(start);
955
+ const e = $ToNumber(end);
956
+ if (isEmptyRange(s, e)) return [];
957
+ assertArrayLength(s, e);
958
+ const arr = [];
959
+ for (let i = s; i < e; i++) {
960
+ arr.push(i);
961
+ }
962
+ return arr;
963
+ };
964
+ function GlobalFallback() {
965
+ return DefaultVmContext;
966
+ }
967
+
968
+ // src/vm/env.ts
969
+ var keys2 = [];
970
+ var values2 = [];
971
+ for (const [key, value] of entries(operations_exports)) {
972
+ keys2.push(key);
973
+ values2.push(value);
974
+ }
975
+ for (const [key, value] of entries(helpers_exports)) {
976
+ keys2.push(key);
977
+ values2.push(value);
978
+ }
979
+
980
+ // src/compiler/create-script.ts
981
+ function wrapScript(source, script) {
982
+ if (kVmScript in script) {
983
+ return script;
984
+ }
985
+ defineProperty(script, "name", { value: VM_SCRIPT_NAME });
986
+ defineProperty(script, kVmScript, { value: true });
987
+ if (typeof source === "string") {
988
+ defineProperty(script, "source", { value: source, configurable: true });
989
+ } else if (source instanceof Uint8Array) {
990
+ defineProperty(script, "source", { value: "<buffer>", configurable: true });
991
+ }
992
+ return script;
993
+ }
994
+ function createScript(source, code) {
995
+ let script;
996
+ try {
997
+ script = new Function(...keys2, code)(...values2);
998
+ } catch (error) {
999
+ throw new Error(`Failed to create script`, { cause: error });
1000
+ }
1001
+ return wrapScript(source, script);
1002
+ }
1003
+
1004
+ // src/compiler/compile-fast.ts
1005
+ var REG_NUMBER_FULL = /^\d+(?:\.\d+)?(?:[eE][+-]?\d+)?$/;
1006
+ var REG_IDENTIFIER_FAST = /^(?:\$+|@+)[a-zA-Z0-9_]*$/;
1007
+ var FAST_SCRIPT_MAX_LEN = 32;
1008
+ function compileScriptFast(code, options) {
1009
+ if (code.length > FAST_SCRIPT_MAX_LEN) return void 0;
1010
+ const trimmedCode = code.trim();
1011
+ if (!trimmedCode) {
1012
+ return wrapScript(code, () => null);
1013
+ }
1014
+ switch (trimmedCode) {
1015
+ case "nil":
1016
+ return wrapScript(code, () => null);
1017
+ case "true":
1018
+ return wrapScript(code, () => true);
1019
+ case "false":
1020
+ return wrapScript(code, () => false);
1021
+ case "nan":
1022
+ return wrapScript(code, () => 0 / 0);
1023
+ case "inf":
1024
+ case "+inf":
1025
+ return wrapScript(code, () => 1 / 0);
1026
+ case "-inf":
1027
+ return wrapScript(code, () => -1 / 0);
1028
+ }
1029
+ if (REG_IDENTIFIER_FAST.test(trimmedCode)) {
1030
+ const id = trimmedCode;
1031
+ return wrapScript(code, (global = GlobalFallback()) => global.get(id));
1032
+ }
1033
+ if (REG_NUMBER_FULL.test(trimmedCode)) {
1034
+ const num2 = Number(trimmedCode);
1035
+ if (!isFinite(num2)) return void 0;
1036
+ return wrapScript(code, () => num2);
1037
+ }
1038
+ return void 0;
1039
+ }
1040
+ var FAST_TEMPLATE_MAX_LEN = 1024;
1041
+ function compileTemplateFast(code, options) {
1042
+ if (code.length > FAST_TEMPLATE_MAX_LEN) return void 0;
1043
+ if (!code.includes("$")) {
1044
+ return wrapScript(code, () => code);
1045
+ }
1046
+ return void 0;
1047
+ }
1048
+ function compileFast(code, options) {
1049
+ if (options.sourceMap) return void 0;
1050
+ return (options.input_mode === "Template" ? compileTemplateFast : compileScriptFast)(code, options);
1051
+ }
1052
+
1053
+ // src/compiler/worker-manager.ts
1054
+ var worker;
1055
+ async function getWorker() {
1056
+ if (worker) return worker;
1057
+ worker = new Promise((resolve, reject) => {
1058
+ const w = new Worker(new URL("#compiler/worker", import.meta.url), {
1059
+ type: "module",
1060
+ name: "@mirascript/compiler"
1061
+ });
1062
+ const onError = (e) => {
1063
+ cleanUp();
1064
+ reject(new Error(`Worker failed to start: ${e.message}`));
1065
+ };
1066
+ const onMessage = (e) => {
1067
+ if (e.data === "ready") {
1068
+ cleanUp();
1069
+ resolve(w);
1070
+ } else if (e.data instanceof Error) {
1071
+ cleanUp();
1072
+ reject(e.data);
1073
+ }
1074
+ };
1075
+ w.addEventListener("error", onError);
1076
+ w.addEventListener("message", onMessage);
1077
+ const cleanUp = () => {
1078
+ w.removeEventListener("error", onError);
1079
+ w.removeEventListener("message", onMessage);
1080
+ };
1081
+ setTimeout(() => {
1082
+ onError(new ErrorEvent("error", { message: "Worker did not respond in time" }));
1083
+ }, 3e4);
1084
+ });
1085
+ return worker;
1086
+ }
1087
+ async function compileWorker(...args) {
1088
+ const worker2 = await getWorker();
1089
+ const seq = Math.random();
1090
+ worker2.postMessage([seq, ...args]);
1091
+ return await new Promise((resolve, reject) => {
1092
+ const callback = (ev) => {
1093
+ const data = ev.data;
1094
+ if (!Array.isArray(data)) return;
1095
+ const [retSeq, ...rest] = data;
1096
+ if (seq !== retSeq) return;
1097
+ worker2.removeEventListener("message", callback);
1098
+ if (rest.length === 2) {
1099
+ resolve(rest);
1100
+ } else {
1101
+ reject(rest[0]);
1102
+ }
1103
+ };
1104
+ worker2.addEventListener("message", callback);
1105
+ });
1106
+ }
1107
+
1108
+ // src/compiler/index.ts
1109
+ await loadModule();
1110
+ var WORKER_MIN_LEN = typeof Worker != "function" ? Number.MAX_VALUE : 1024;
1111
+ function reportDiagnostic(source, diagnostics, fileName) {
1112
+ const parsed = parseDiagnostics(source, diagnostics);
1113
+ const messages = formatDiagnostics(parsed.errors, source, fileName);
1114
+ throw new Error(`Failed to compile:
1115
+ ${messages.join("\n")}`);
1116
+ }
1117
+ function emitScript(source, [code, diagnostics], options) {
1118
+ if (!code) {
1119
+ reportDiagnostic(source, diagnostics, options.fileName);
1120
+ }
1121
+ const sourcemaps = options.sourceMap ? parseDiagnostics(source, diagnostics, (c) => c === DiagnosticCode.SourceMap).sourcemaps : [];
1122
+ const target = emit(source, code, sourcemaps, options);
1123
+ return createScript(source, target);
1124
+ }
1125
+ async function compile(source, options = {}) {
1126
+ if (options.sourceMap) {
1127
+ options.diagnostic_sourcemap = true;
1128
+ options.diagnostic_position_encoding ??= "Utf16";
1129
+ }
1130
+ if (typeof source == "string") {
1131
+ const result = compileFast(source, options);
1132
+ if (result) return result;
1133
+ }
1134
+ if (source.length < WORKER_MIN_LEN) {
1135
+ const bc = await generateBytecode(source, options);
1136
+ return emitScript(source, bc, options);
1137
+ }
1138
+ const [target, diagnostics] = await compileWorker(source, options);
1139
+ if (target == null) {
1140
+ reportDiagnostic(source, diagnostics, options.fileName);
1141
+ }
1142
+ return createScript(source, target);
1143
+ }
1144
+ function compileSync(source, options = {}) {
1145
+ if (typeof source == "string") {
1146
+ const result = compileFast(source, options);
1147
+ if (result) return result;
1148
+ }
1149
+ const bc = generateBytecodeSync(source, options);
1150
+ return emitScript(source, bc, options);
1151
+ }
1152
+
1153
+ // src/vm/types/module.ts
1154
+ var VmModule = class extends VmWrapper {
1155
+ constructor(name, value) {
1156
+ super(value);
1157
+ this.name = name;
1158
+ }
1159
+ /** @inheritdoc */
1160
+ has(key) {
1161
+ return hasOwnEnumerable(this.value, key);
1162
+ }
1163
+ /** @inheritdoc */
1164
+ get(key) {
1165
+ if (!this.has(key)) return void 0;
1166
+ return this.value[key] ?? null;
1167
+ }
1168
+ /** @inheritdoc */
1169
+ keys() {
1170
+ return keys(this.value);
1171
+ }
1172
+ /** @inheritdoc */
1173
+ same(other) {
1174
+ return this === other;
1175
+ }
1176
+ /** @inheritdoc */
1177
+ get type() {
1178
+ return "module";
1179
+ }
1180
+ /** @inheritdoc */
1181
+ get describe() {
1182
+ return this.name;
1183
+ }
1184
+ };
1185
+ Object.defineProperty(VmModule.prototype, kVmModule, { value: true });
74
1186
 
75
1187
  // src/vm/lib/global/index.ts
76
1188
  var global_exports = {};
77
1189
  __export(global_exports, {
78
1190
  "@e": () => E,
79
1191
  "@pi": () => PI,
80
- abs: () => abs,
1192
+ abs: () => abs2,
81
1193
  acos: () => acos,
82
1194
  acosh: () => acosh,
83
1195
  all: () => all,
@@ -92,7 +1204,7 @@ __export(global_exports, {
92
1204
  b_or: () => b_or,
93
1205
  b_xor: () => b_xor,
94
1206
  cbrt: () => cbrt,
95
- ceil: () => ceil,
1207
+ ceil: () => ceil2,
96
1208
  chars: () => chars,
97
1209
  contains: () => contains,
98
1210
  cos: () => cos,
@@ -112,16 +1224,15 @@ __export(global_exports, {
112
1224
  from_json: () => from_json,
113
1225
  hypot: () => hypot,
114
1226
  join: () => join,
115
- keys: () => keys2,
1227
+ keys: () => keys3,
116
1228
  len: () => len,
117
1229
  log: () => log,
118
1230
  log10: () => log10,
119
1231
  log1p: () => log1p,
120
1232
  log2: () => log2,
121
1233
  map: () => map2,
122
- matrix: () => matrix,
123
1234
  max: () => max,
124
- min: () => min,
1235
+ min: () => min2,
125
1236
  panic: () => panic,
126
1237
  pow: () => pow2,
127
1238
  product: () => product,
@@ -154,22 +1265,31 @@ __export(global_exports, {
154
1265
  trim: () => trim,
155
1266
  trim_end: () => trim_end,
156
1267
  trim_start: () => trim_start,
157
- trunc: () => trunc,
158
- values: () => values2,
1268
+ trunc: () => trunc2,
1269
+ values: () => values3,
159
1270
  with: () => _with,
160
1271
  zip: () => zip
161
1272
  });
162
1273
 
163
- // src/vm/lib/_helpers.ts
1274
+ // src/vm/lib/helpers.ts
164
1275
  function throwError(message, recovered) {
165
1276
  const recoveredValue = typeof recovered === "function" && !isVmFunction(recovered) ? recovered() : recovered;
166
1277
  throw new VmError(message, recoveredValue);
167
1278
  }
1279
+ function describeParam(name) {
1280
+ if (name == null) return "Value";
1281
+ if (typeof name == "string") {
1282
+ if (!name) return "Argument";
1283
+ return `Argument '${name}'`;
1284
+ }
1285
+ const pos = name <= 0 ? "first" : name <= 1 ? "second" : `${name + 1}th`;
1286
+ return `Argument at the ${pos} position`;
1287
+ }
168
1288
  function throwUnexpectedTypeError(name, expected, value, recovered) {
169
- const actual = $Type(value);
170
- if (typeof name == "string") throwError(`Expected ${expected} for parameter '${name}', got ${actual}`, recovered);
171
- const pos = name <= 0 ? "first" : name <= 1 ? "second" : name + 1 + "th";
172
- throwError(`Expected ${expected} at the ${pos} position, got ${actual}`, recovered);
1289
+ throwError(`${describeParam(name)} is not ${expected}: ${display(value)}`, recovered);
1290
+ }
1291
+ function throwUnconvertedTypeError(name, expected, value, recovered) {
1292
+ throwError(`${describeParam(name)} cannot be converted to ${expected}: ${display(value)}`, recovered);
173
1293
  }
174
1294
  function rethrowError(prefix, error, recovered) {
175
1295
  const recoveredValue = typeof recovered === "function" && !isVmFunction(recovered) ? recovered() : recovered;
@@ -177,10 +1297,49 @@ function rethrowError(prefix, error, recovered) {
177
1297
  }
178
1298
  function required(name, value, recovered) {
179
1299
  if (value === void 0) {
180
- if (typeof name == "string") throwError(`Missing required parameter '${name}'`, recovered);
181
- const pos = name <= 0 ? "first" : name <= 1 ? "second" : name + 1 + "th";
182
- throwError(`Missing required parameter at the ${pos} position`, recovered);
1300
+ throwError(`${describeParam(name)} is required`, recovered);
1301
+ }
1302
+ }
1303
+ function expectNumber(name, value) {
1304
+ required(name, value, Number.NaN);
1305
+ const v = toNumber(value, null);
1306
+ if (v == null) {
1307
+ throwUnconvertedTypeError(name, "number", value, Number.NaN);
1308
+ }
1309
+ return v;
1310
+ }
1311
+ function expectNumberRange(name, value, min3, max2) {
1312
+ const v = expectNumber(name, value);
1313
+ if (!isFinite(v)) {
1314
+ throwError(`${describeParam(name)} is not a finite number: ${display(value)}`, Number.NaN);
1315
+ }
1316
+ if (v < min3) {
1317
+ throwError(`${describeParam(name)} is less than minimum value ${min3}: ${display(value)}`, min3);
1318
+ }
1319
+ if (v > max2) {
1320
+ throwError(`${describeParam(name)} is greater than maximum value ${max2}: ${display(value)}`, max2);
183
1321
  }
1322
+ return v;
1323
+ }
1324
+ function expectInteger(name, value) {
1325
+ required(name, value, 0);
1326
+ const v = toNumber(value, null);
1327
+ if (v == null) {
1328
+ throwUnconvertedTypeError(name, "integer", value, 0);
1329
+ }
1330
+ const i = Math.trunc(v);
1331
+ if (!isSafeInteger(i)) {
1332
+ throwUnconvertedTypeError(name, "integer", value, 0);
1333
+ }
1334
+ return i;
1335
+ }
1336
+ function expectString(name, value) {
1337
+ required(name, value, "");
1338
+ const v = toString(value, null);
1339
+ if (v == null) {
1340
+ throwUnconvertedTypeError(name, "string", value, "");
1341
+ }
1342
+ return v;
184
1343
  }
185
1344
  function expectArray(name, value, recovered) {
186
1345
  required(name, value, recovered);
@@ -214,18 +1373,25 @@ function expectCallable(name, value, recovered) {
214
1373
  }
215
1374
  function getNumbers(args) {
216
1375
  if (args.length === 0) return [];
217
- if (args.length === 1 && isVmArray(args[0])) args = args[0];
1376
+ let useFirst = false;
1377
+ if (args.length === 1 && isVmArray(args[0])) {
1378
+ args = args[0];
1379
+ useFirst = true;
1380
+ }
218
1381
  const numbers = [];
219
- for (const arg of args) {
220
- if (arg == null) continue;
221
- numbers.push($ToNumber(arg));
1382
+ for (let len2 = args.length, i = 0; i < len2; i++) {
1383
+ numbers.push(expectNumber(useFirst ? null : i, args[i]));
222
1384
  }
223
1385
  return numbers;
224
1386
  }
225
1387
  function arrayLen(len2) {
226
- if (len2 == null || isNaN(len2) || len2 <= 0) return 0;
1388
+ if (len2 == null || isNaN(len2) || len2 <= -1) {
1389
+ throwError("Array length must be a non-negative integer", null);
1390
+ }
227
1391
  len2 = Math.trunc(len2);
228
- if (len2 > VM_ARRAY_MAX_LENGTH) throwError(`Array length exceeds maximum limit of ${VM_ARRAY_MAX_LENGTH}`, null);
1392
+ if (len2 > VM_ARRAY_MAX_LENGTH) {
1393
+ throwError(`Array length exceeds maximum limit of ${VM_ARRAY_MAX_LENGTH}`, null);
1394
+ }
229
1395
  return len2;
230
1396
  }
231
1397
  function map(data, mapper) {
@@ -281,7 +1447,7 @@ var max = VmLib(build(Math.max), {
281
1447
  returnsType: "number",
282
1448
  examples: ["max(3, 7, 2) // 7"]
283
1449
  });
284
- var min = VmLib(build(Math.min), {
1450
+ var min2 = VmLib(build(Math.min), {
285
1451
  summary: "返回一组数中的最小值",
286
1452
  params: { "..values": "要比较的数值" },
287
1453
  paramsType: { "..values": "number[]" },
@@ -328,11 +1494,10 @@ var { PI, E } = Math;
328
1494
  // src/vm/lib/global/math-unary.ts
329
1495
  function build2(f) {
330
1496
  return (x) => {
331
- required("x", x, Number.NaN);
332
- return f($ToNumber(x));
1497
+ return f(expectNumber("x", x));
333
1498
  };
334
1499
  }
335
- var trunc = VmLib(build2(Math.trunc), {
1500
+ var trunc2 = VmLib(build2(Math.trunc), {
336
1501
  summary: "返回数值的整数部分(去除小数)",
337
1502
  params: { x: "要取整数部分的数" },
338
1503
  paramsType: { x: "number" },
@@ -344,7 +1509,7 @@ var floor = VmLib(build2(Math.floor), {
344
1509
  paramsType: { x: "number" },
345
1510
  returnsType: "number"
346
1511
  });
347
- var ceil = VmLib(build2(Math.ceil), {
1512
+ var ceil2 = VmLib(build2(Math.ceil), {
348
1513
  summary: "返回大于等于给定数的最小整数",
349
1514
  params: { x: "要向上取整的数" },
350
1515
  paramsType: { x: "number" },
@@ -373,7 +1538,7 @@ var sign = VmLib(build2(Math.sign), {
373
1538
  paramsType: { x: "number" },
374
1539
  returnsType: "number"
375
1540
  });
376
- var abs = VmLib(build2(Math.abs), {
1541
+ var abs2 = VmLib(build2(Math.abs), {
377
1542
  summary: "返回数值的绝对值",
378
1543
  params: { x: "要取绝对值的数" },
379
1544
  paramsType: { x: "number" },
@@ -523,8 +1688,7 @@ var GAMMA_P = [
523
1688
  var SQRT_2_PI = sqrt2(2 * Math.PI);
524
1689
  var factorial = VmLib(
525
1690
  (x) => {
526
- required("x", x, Number.NaN);
527
- let n = $ToNumber(x);
1691
+ let n = expectNumber("x", x);
528
1692
  if (isNaN(n) || n < 0) return Number.NaN;
529
1693
  if (n >= 171) return Number.POSITIVE_INFINITY;
530
1694
  if (isInteger(n)) {
@@ -561,13 +1725,13 @@ var factorial = VmLib(
561
1725
 
562
1726
  // src/vm/lib/global/math.ts
563
1727
  var { atan2: _atan2, pow: _pow } = Math;
564
- var atan2 = VmLib((x, y) => _atan2($ToNumber(x), $ToNumber(y)), {
1728
+ var atan2 = VmLib((x, y) => _atan2(expectNumber(0, x), expectNumber(1, y)), {
565
1729
  summary: "返回从原点到点 (x, y) 的角度(弧度)",
566
1730
  params: { x: "x 坐标", y: "y 坐标" },
567
1731
  paramsType: { x: "number", y: "number" },
568
1732
  returnsType: "number"
569
1733
  });
570
- var pow2 = VmLib((x, y) => _pow($ToNumber(x), $ToNumber(y)), {
1734
+ var pow2 = VmLib((x, y) => _pow(expectNumber(0, x), expectNumber(1, y)), {
571
1735
  summary: "返回 x 的 y 次幂",
572
1736
  params: { x: "底数", y: "指数" },
573
1737
  paramsType: { x: "number", y: "number" },
@@ -583,7 +1747,7 @@ var random = VmLib(Math.random, {
583
1747
  // src/vm/lib/global/bit.ts
584
1748
  var b_and = VmLib(
585
1749
  (x, y) => {
586
- return $ToNumber(x) & $ToNumber(y);
1750
+ return expectNumber(0, x) & expectNumber(1, y);
587
1751
  },
588
1752
  {
589
1753
  summary: "返回两个数的按位与",
@@ -595,7 +1759,7 @@ var b_and = VmLib(
595
1759
  );
596
1760
  var b_or = VmLib(
597
1761
  (x, y) => {
598
- return $ToNumber(x) | $ToNumber(y);
1762
+ return expectNumber(0, x) | expectNumber(1, y);
599
1763
  },
600
1764
  {
601
1765
  summary: "返回两个数的按位或",
@@ -607,7 +1771,7 @@ var b_or = VmLib(
607
1771
  );
608
1772
  var b_not = VmLib(
609
1773
  (x) => {
610
- return ~$ToNumber(x);
1774
+ return ~expectNumber("x", x);
611
1775
  },
612
1776
  {
613
1777
  summary: "返回一个数的按位取反",
@@ -619,7 +1783,7 @@ var b_not = VmLib(
619
1783
  );
620
1784
  var b_xor = VmLib(
621
1785
  (x, y) => {
622
- return $ToNumber(x) ^ $ToNumber(y);
1786
+ return expectNumber(0, x) ^ expectNumber(1, y);
623
1787
  },
624
1788
  {
625
1789
  summary: "返回两个数的按位异或",
@@ -631,7 +1795,7 @@ var b_xor = VmLib(
631
1795
  );
632
1796
  var shl = VmLib(
633
1797
  (x, y) => {
634
- return $ToNumber(x) << $ToNumber(y);
1798
+ return expectNumber(0, x) << expectNumber(1, y);
635
1799
  },
636
1800
  {
637
1801
  summary: "返回第一个操作数左移指定的位数",
@@ -643,7 +1807,7 @@ var shl = VmLib(
643
1807
  );
644
1808
  var sar = VmLib(
645
1809
  (x, y) => {
646
- return $ToNumber(x) >> $ToNumber(y);
1810
+ return expectNumber(0, x) >> expectNumber(1, y);
647
1811
  },
648
1812
  {
649
1813
  summary: "返回第一个操作数右移指定的位数",
@@ -655,7 +1819,7 @@ var sar = VmLib(
655
1819
  );
656
1820
  var shr = VmLib(
657
1821
  (x, y) => {
658
- return $ToNumber(x) >>> $ToNumber(y);
1822
+ return expectNumber(0, x) >>> expectNumber(1, y);
659
1823
  },
660
1824
  {
661
1825
  summary: "返回第一个操作数无符号右移指定的位数",
@@ -668,12 +1832,19 @@ var shr = VmLib(
668
1832
 
669
1833
  // src/vm/lib/global/sequence/with.ts
670
1834
  var arrIndex = (index) => {
671
- const idx = Math.trunc($ToNumber(index));
672
- if (!isSafeInteger(idx) || idx < 0 || idx >= VM_ARRAY_MAX_LENGTH) {
673
- return -1;
1835
+ const idx = Math.trunc(toNumber(index, Number.NaN));
1836
+ if (isNaN(idx) || idx < 0) {
1837
+ throwError("Array index must be a non-negative integer", index);
1838
+ }
1839
+ if (idx >= VM_ARRAY_MAX_LENGTH) {
1840
+ throwError(`Array index exceeds maximum limit of ${VM_ARRAY_MAX_LENGTH}`, index);
674
1841
  }
675
1842
  return idx;
676
1843
  };
1844
+ var isArrIndex = (key) => {
1845
+ if (typeof key != "number") return false;
1846
+ return isInteger(key) && key >= 0 && key < VM_ARRAY_MAX_LENGTH;
1847
+ };
677
1848
  var withInner = (obj, key, keyIndex, value) => {
678
1849
  if (keyIndex >= key.length) {
679
1850
  return value;
@@ -684,7 +1855,7 @@ var withInner = (obj, key, keyIndex, value) => {
684
1855
  result = [...obj];
685
1856
  } else if (isVmRecord(obj)) {
686
1857
  result = { ...obj };
687
- } else if (arrIndex(k) === k) {
1858
+ } else if (isArrIndex(k)) {
688
1859
  result = [];
689
1860
  } else {
690
1861
  result = {};
@@ -696,7 +1867,7 @@ var withInner = (obj, key, keyIndex, value) => {
696
1867
  }
697
1868
  result[index] = withInner(result[index], key, keyIndex + 1, value);
698
1869
  } else {
699
- const prop = $ToString(k);
1870
+ const prop = toString(k, void 0);
700
1871
  result[prop] = withInner(result[prop], key, keyIndex + 1, value);
701
1872
  }
702
1873
  return result;
@@ -738,11 +1909,9 @@ var _with = VmLib(
738
1909
  let val;
739
1910
  if (isVmArray(key)) {
740
1911
  index = arrIndex(key[0]);
741
- if (index < 0) continue;
742
1912
  val = withInner(result[index], key, 1, value);
743
1913
  } else {
744
1914
  index = arrIndex(key);
745
- if (index < 0) continue;
746
1915
  val = value;
747
1916
  }
748
1917
  while (index > result.length) {
@@ -758,10 +1927,10 @@ var _with = VmLib(
758
1927
  let val;
759
1928
  if (isVmArray(key)) {
760
1929
  const firstKey = key[0];
761
- prop = $ToString(firstKey);
1930
+ prop = toString(firstKey, void 0);
762
1931
  val = withInner(result[prop], key, 1, value);
763
1932
  } else {
764
- prop = $ToString(key);
1933
+ prop = toString(key, void 0);
765
1934
  val = value;
766
1935
  }
767
1936
  result[prop] = val;
@@ -788,7 +1957,7 @@ var _with = VmLib(
788
1957
  );
789
1958
 
790
1959
  // src/vm/lib/global/sequence/entries.ts
791
- var keys2 = VmLib(
1960
+ var keys3 = VmLib(
792
1961
  (data) => {
793
1962
  expectCompound("data", data, []);
794
1963
  if (isVmArray(data)) {
@@ -812,7 +1981,7 @@ var keys2 = VmLib(
812
1981
  examples: ["keys([10, 20]) // [0, 1]", 'keys((10, 20)) // ["0", "1"]']
813
1982
  }
814
1983
  );
815
- var values2 = VmLib(
1984
+ var values3 = VmLib(
816
1985
  (data) => {
817
1986
  expectArrayOrRecord("data", data, []);
818
1987
  if (isVmArray(data)) {
@@ -894,7 +2063,7 @@ var map2 = VmLib(
894
2063
  var filter = VmLib(
895
2064
  (data, predicate) => mapImplWrapped(data, "predicate", predicate, (fn, value, key, data2) => {
896
2065
  const ret = $Call(fn, [value, key, data2]);
897
- return $ToBoolean(ret) ? value : void 0;
2066
+ return toBoolean(ret, void 0) ? value : void 0;
898
2067
  }),
899
2068
  {
900
2069
  summary: "过滤数组或记录中的元素,返回满足条件的元素",
@@ -937,7 +2106,7 @@ var find = VmLib(
937
2106
  required("predicate", predicate, null);
938
2107
  const p = isVmCallable(predicate) ? (value, key, data2) => {
939
2108
  const ret = $Call(predicate, [value, key, data2]);
940
- return $ToBoolean(ret);
2109
+ return toBoolean(ret, void 0);
941
2110
  } : (value) => $Same(predicate, value);
942
2111
  if (isVmArray(data)) {
943
2112
  const { length } = data;
@@ -979,7 +2148,7 @@ var find = VmLib(
979
2148
  var flatten = VmLib(
980
2149
  (data, depth = 1) => {
981
2150
  expectArray("data", data, data);
982
- return data.flat($ToNumber(depth));
2151
+ return data.flat(expectNumber("depth", depth));
983
2152
  },
984
2153
  {
985
2154
  summary: "将数组扁平化",
@@ -1014,7 +2183,7 @@ var zip = VmLib(
1014
2183
  let len2 = 0;
1015
2184
  for (const { 0: key, 1: arr } of ets) {
1016
2185
  if (!isVmArray(arr)) {
1017
- throwError(`data[${serialize(key)}] is not an array`, null);
2186
+ throwError(`data[${display(key)}] is not an array: ${display(arr)}`, null);
1018
2187
  }
1019
2188
  len2 = Math.max(len2, arr.length);
1020
2189
  }
@@ -1053,7 +2222,7 @@ var all = VmLib(
1053
2222
  Cp();
1054
2223
  const value = data[i] ?? null;
1055
2224
  const ret = $Call(predicate, [value, i, data]);
1056
- if (!$ToBoolean(ret)) return false;
2225
+ if (!toBoolean(ret, void 0)) return false;
1057
2226
  }
1058
2227
  return true;
1059
2228
  } else {
@@ -1061,7 +2230,7 @@ var all = VmLib(
1061
2230
  Cp();
1062
2231
  const value = v ?? null;
1063
2232
  const ret = $Call(predicate, [value, key, data]);
1064
- if (!$ToBoolean(ret)) return false;
2233
+ if (!toBoolean(ret, void 0)) return false;
1065
2234
  }
1066
2235
  return true;
1067
2236
  }
@@ -1086,7 +2255,7 @@ var any = VmLib(
1086
2255
  Cp();
1087
2256
  const value = data[i] ?? null;
1088
2257
  const ret = $Call(predicate, [value, i, data]);
1089
- if ($ToBoolean(ret)) return true;
2258
+ if (toBoolean(ret, void 0)) return true;
1090
2259
  }
1091
2260
  return false;
1092
2261
  } else {
@@ -1094,7 +2263,7 @@ var any = VmLib(
1094
2263
  Cp();
1095
2264
  const value = v ?? null;
1096
2265
  const ret = $Call(predicate, [value, key, data]);
1097
- if ($ToBoolean(ret)) return true;
2266
+ if (toBoolean(ret, void 0)) return true;
1098
2267
  }
1099
2268
  return false;
1100
2269
  }
@@ -1121,8 +2290,8 @@ function defaultCompare(a = null, b = null) {
1121
2290
  if (a > b) return 1;
1122
2291
  return 0;
1123
2292
  }
1124
- const an = $ToNumber(a) || 0;
1125
- const bn = $ToNumber(b) || 0;
2293
+ const an = toNumber(a, 0) || 0;
2294
+ const bn = toNumber(b, 0) || 0;
1126
2295
  if (an < bn) return -1;
1127
2296
  if (an > bn) return 1;
1128
2297
  return 0;
@@ -1132,7 +2301,7 @@ function cmp(comparator, recovered) {
1132
2301
  expectCallable("comparator", comparator, recovered);
1133
2302
  return (a = null, b = null) => {
1134
2303
  const ret = $Call(comparator, [a, b]);
1135
- return $ToNumber(ret);
2304
+ return toNumber(ret, 0);
1136
2305
  };
1137
2306
  }
1138
2307
  var sort = VmLib(
@@ -1198,8 +2367,7 @@ var sort_by = VmLib(
1198
2367
  var repeat = VmLib(
1199
2368
  (data, times) => {
1200
2369
  expectConst("data", data, []);
1201
- required("times", times, []);
1202
- const n = arrayLen($ToNumber(times));
2370
+ const n = arrayLen(expectNumber("times", times));
1203
2371
  const result = [];
1204
2372
  result.length = n;
1205
2373
  result.fill(data);
@@ -1241,7 +2409,8 @@ var panic = VmLib(
1241
2409
  (message) => {
1242
2410
  if (message === void 0) console.error(...panic.prefix);
1243
2411
  else console.error(...panic.prefix, message);
1244
- const error = message == null ? "panic" : "panic: " + $ToString(message);
2412
+ const mgsStr = toString(message, null);
2413
+ const error = !mgsStr ? "panic" : "panic: " + mgsStr;
1245
2414
  throw new VmError(error, void 0);
1246
2415
  },
1247
2416
  {
@@ -1299,7 +2468,7 @@ var from_json = VmLib(
1299
2468
  try {
1300
2469
  return parse(json);
1301
2470
  } catch (ex) {
1302
- if (fallback != null) return fallback;
2471
+ if (fallback !== void 0) return fallback;
1303
2472
  rethrowError("Invalid JSON", ex, null);
1304
2473
  }
1305
2474
  },
@@ -1314,48 +2483,57 @@ var from_json = VmLib(
1314
2483
 
1315
2484
  // src/vm/lib/global/to-primitive.ts
1316
2485
  var to_string = VmLib(
1317
- (data) => {
2486
+ (data, fallback) => {
1318
2487
  required("data", data, "");
1319
- return $ToString(data);
2488
+ return toString(data, fallback);
1320
2489
  },
1321
2490
  {
1322
2491
  summary: "将数据转换为字符串",
1323
- params: { data: "要转换的数据" },
1324
- paramsType: { data: "any" },
1325
- returnsType: "string",
2492
+ params: {
2493
+ data: "要转换的数据",
2494
+ fallback: "转换失败时的返回值"
2495
+ },
2496
+ paramsType: { data: "any", fallback: "any" },
2497
+ returnsType: "string | type(fallback)",
1326
2498
  examples: ['to_string([1, 2]) // "1, 2"']
1327
2499
  }
1328
2500
  );
1329
2501
  var to_number = VmLib(
1330
- (data) => {
2502
+ (data, fallback) => {
1331
2503
  required("data", data, Number.NaN);
1332
- return $ToNumber(data);
2504
+ return toNumber(data, fallback);
1333
2505
  },
1334
2506
  {
1335
2507
  summary: "将数据转换为数字",
1336
- params: { data: "要转换的数据" },
1337
- paramsType: { data: "any" },
1338
- returnsType: "number",
2508
+ params: {
2509
+ data: "要转换的数据",
2510
+ fallback: "转换失败时的返回值"
2511
+ },
2512
+ paramsType: { data: "any", fallback: "any" },
2513
+ returnsType: "number | type(fallback)",
1339
2514
  examples: ['to_number("1.5") // 1.5']
1340
2515
  }
1341
2516
  );
1342
2517
  var to_boolean = VmLib(
1343
- (data) => {
2518
+ (data, fallback) => {
1344
2519
  required("data", data, false);
1345
- return $ToBoolean(data);
2520
+ return toBoolean(data, fallback);
1346
2521
  },
1347
2522
  {
1348
2523
  summary: "将数据转换为布尔值",
1349
- params: { data: "要转换的数据" },
1350
- paramsType: { data: "any" },
1351
- returnsType: "boolean",
2524
+ params: {
2525
+ data: "要转换的数据",
2526
+ fallback: "转换失败时的返回值"
2527
+ },
2528
+ paramsType: { data: "any", fallback: "any" },
2529
+ returnsType: "boolean | type(fallback)",
1352
2530
  examples: ["to_boolean(nil) // false"]
1353
2531
  }
1354
2532
  );
1355
2533
  var format = VmLib(
1356
2534
  (data, format2) => {
1357
2535
  required("data", data, "");
1358
- return $Format(data, format2);
2536
+ return toFormat(data, expectString("format", format2));
1359
2537
  },
1360
2538
  {
1361
2539
  summary: "将数据格式化为指定格式的字符串",
@@ -1369,8 +2547,7 @@ var format = VmLib(
1369
2547
  // src/vm/lib/global/string.ts
1370
2548
  var chars = VmLib(
1371
2549
  (str) => {
1372
- required("str", str, null);
1373
- return [...$ToString(str)];
2550
+ return [...expectString("str", str)];
1374
2551
  },
1375
2552
  {
1376
2553
  summary: "将字符串转换为字符数组",
@@ -1382,9 +2559,7 @@ var chars = VmLib(
1382
2559
  );
1383
2560
  var starts_with = VmLib(
1384
2561
  (str, search) => {
1385
- required("str", str, null);
1386
- required("search", search, null);
1387
- return $ToString(str).startsWith($ToString(search));
2562
+ return expectString("str", str).startsWith(expectString("search", search));
1388
2563
  },
1389
2564
  {
1390
2565
  summary: "检查字符串是否以指定子串开头",
@@ -1396,9 +2571,7 @@ var starts_with = VmLib(
1396
2571
  );
1397
2572
  var ends_with = VmLib(
1398
2573
  (str, search) => {
1399
- required("str", str, null);
1400
- required("search", search, null);
1401
- return $ToString(str).endsWith($ToString(search));
2574
+ return expectString("str", str).endsWith(expectString("search", search));
1402
2575
  },
1403
2576
  {
1404
2577
  summary: "检查字符串是否以指定子串结尾",
@@ -1410,9 +2583,7 @@ var ends_with = VmLib(
1410
2583
  );
1411
2584
  var contains = VmLib(
1412
2585
  (str, search) => {
1413
- required("str", str, null);
1414
- required("search", search, null);
1415
- return $ToString(str).includes($ToString(search));
2586
+ return expectString("str", str).includes(expectString("search", search));
1416
2587
  },
1417
2588
  {
1418
2589
  summary: "检查字符串是否包含指定子串",
@@ -1424,8 +2595,7 @@ var contains = VmLib(
1424
2595
  );
1425
2596
  var trim_start = VmLib(
1426
2597
  (str) => {
1427
- required("str", str, null);
1428
- return $ToString(str).trimStart();
2598
+ return expectString("str", str).trimStart();
1429
2599
  },
1430
2600
  {
1431
2601
  summary: "去除字符串开头的空白字符",
@@ -1437,8 +2607,7 @@ var trim_start = VmLib(
1437
2607
  );
1438
2608
  var trim_end = VmLib(
1439
2609
  (str) => {
1440
- required("str", str, null);
1441
- return $ToString(str).trimEnd();
2610
+ return expectString("str", str).trimEnd();
1442
2611
  },
1443
2612
  {
1444
2613
  summary: "去除字符串结尾的空白字符",
@@ -1450,8 +2619,7 @@ var trim_end = VmLib(
1450
2619
  );
1451
2620
  var trim = VmLib(
1452
2621
  (str) => {
1453
- required("str", str, null);
1454
- return $ToString(str).trim();
2622
+ return expectString("str", str).trim();
1455
2623
  },
1456
2624
  {
1457
2625
  summary: "去除字符串两端的空白字符",
@@ -1463,9 +2631,10 @@ var trim = VmLib(
1463
2631
  );
1464
2632
  var replace = VmLib(
1465
2633
  (str, search, replacement = "") => {
1466
- required("str", str, null);
1467
- required("search", search, str);
1468
- return $ToString(str).replaceAll($ToString(search), $ToString(replacement));
2634
+ return expectString("str", str).replaceAll(
2635
+ expectString("search", search),
2636
+ expectString("replacement", replacement)
2637
+ );
1469
2638
  },
1470
2639
  {
1471
2640
  summary: "替换字符串中的指定子串",
@@ -1477,9 +2646,8 @@ var replace = VmLib(
1477
2646
  );
1478
2647
  var split = VmLib(
1479
2648
  (str, separator = "") => {
1480
- required("str", str, null);
1481
- const s = $ToString(str);
1482
- const p = $ToString(separator);
2649
+ const s = expectString("str", str);
2650
+ const p = expectString("separator", separator);
1483
2651
  if (!p) return [...s];
1484
2652
  return s.split(p);
1485
2653
  },
@@ -1494,8 +2662,8 @@ var split = VmLib(
1494
2662
  var join = VmLib(
1495
2663
  (arr, separator = "") => {
1496
2664
  expectArray("arr", arr, null);
1497
- const s = $ToString(separator);
1498
- return arr.map((v) => $ToString(v)).join(s);
2665
+ const s = expectString("separator", separator);
2666
+ return arr.map((v) => expectString(null, v)).join(s);
1499
2667
  },
1500
2668
  {
1501
2669
  summary: "将字符串数组连接为单个字符串",
@@ -1507,33 +2675,54 @@ var join = VmLib(
1507
2675
  );
1508
2676
 
1509
2677
  // src/vm/lib/global/time.ts
2678
+ var fromNumber = (datetime, fallback) => {
2679
+ const n = new Date(datetime).getTime();
2680
+ if (isFinite(n)) return n;
2681
+ if (fallback) return null;
2682
+ throwError(`${describeParam("datetime")} is an invalid timestamp: ${display(datetime)}`, Number.NaN);
2683
+ };
2684
+ var getTimestamp = (datetime, fallback) => {
2685
+ if (datetime == null) {
2686
+ return Date.now();
2687
+ }
2688
+ if (typeof datetime == "number") {
2689
+ return fromNumber(datetime, fallback);
2690
+ }
2691
+ if (typeof datetime != "string") {
2692
+ if (fallback) return null;
2693
+ throwUnexpectedTypeError("datetime", "number | string", datetime, Number.NaN);
2694
+ }
2695
+ const num2 = toNumber(datetime, Number.NaN);
2696
+ if (!isNaN(num2)) {
2697
+ return fromNumber(num2, fallback);
2698
+ }
2699
+ const parsed = Date.parse(datetime);
2700
+ if (isFinite(parsed)) return parsed;
2701
+ if (fallback) return null;
2702
+ throwError(`${describeParam("datetime")} cannot be parsed as datetime: ${display(datetime)}`, Number.NaN);
2703
+ };
1510
2704
  var to_timestamp = VmLib(
1511
- (datetime) => {
1512
- if (datetime == null) {
1513
- return Date.now();
1514
- }
1515
- if (typeof datetime == "number") {
1516
- return new Date(datetime).getTime();
1517
- }
1518
- const str = $ToString(datetime);
1519
- if (!str) return Number.NaN;
1520
- const num2 = $ToNumber(str);
1521
- if (isFinite(num2)) return num2;
1522
- return Date.parse(str);
2705
+ (datetime, fallback) => {
2706
+ const timestamp = getTimestamp(datetime, fallback !== void 0);
2707
+ if (timestamp == null) return fallback;
2708
+ return timestamp;
1523
2709
  },
1524
2710
  {
1525
2711
  summary: "将数据转换为 Unix 毫秒时间戳",
1526
- params: { datetime: "要转换的数据,默认为当前时间" },
1527
- paramsType: { datetime: "number | string" },
1528
- returnsType: "number",
2712
+ params: {
2713
+ datetime: "要转换的数据,默认为当前时间",
2714
+ fallback: "转换失败时的返回值"
2715
+ },
2716
+ paramsType: { datetime: "number | string", fallback: "any" },
2717
+ returnsType: "number | type(fallback)",
1529
2718
  examples: ['to_timestamp("1970-01-01T00:00:00Z") // 0']
1530
2719
  }
1531
2720
  );
1532
2721
  var to_datetime = VmLib(
1533
- (datetime, offset) => {
1534
- const timestamp = to_timestamp(datetime);
1535
- if (!isFinite(timestamp)) return null;
1536
- const o = $ToNumber(offset ?? 0) || 0;
2722
+ (datetime, offset, fallback) => {
2723
+ const timestamp = getTimestamp(datetime, fallback !== void 0);
2724
+ if (timestamp == null) return fallback;
2725
+ const o = expectNumberRange("offset", offset ?? 0, -24, 24);
1537
2726
  const dateOffset = new Date(timestamp + o * 1e3 * 60 * 60);
1538
2727
  return {
1539
2728
  year: dateOffset.getUTCFullYear(),
@@ -1551,10 +2740,11 @@ var to_datetime = VmLib(
1551
2740
  summary: "将数据转换为 Date 记录",
1552
2741
  params: {
1553
2742
  datetime: "要转换的数据,默认为当前时间",
1554
- offset: "时区偏移量(单位:小时),默认为 0"
2743
+ offset: "时区偏移量(单位:小时),默认为 0",
2744
+ fallback: "转换失败时的返回值"
1555
2745
  },
1556
- paramsType: { datetime: "number | string", offset: "number" },
1557
- returnsType: "Date",
2746
+ paramsType: { datetime: "number | string", offset: "number", fallback: "any" },
2747
+ returnsType: "Date | type(fallback)",
1558
2748
  examples: [
1559
2749
  `
1560
2750
  to_datetime(0)
@@ -1568,21 +2758,30 @@ to_datetime(0)
1568
2758
  }
1569
2759
  );
1570
2760
  var to_iso8601 = VmLib(
1571
- (datetime) => {
1572
- const timestamp = to_timestamp(datetime);
1573
- if (!isFinite(timestamp)) return null;
2761
+ (datetime, fallback) => {
2762
+ const timestamp = getTimestamp(datetime, fallback !== void 0);
2763
+ if (timestamp == null) return fallback;
1574
2764
  return new Date(timestamp).toISOString();
1575
2765
  },
1576
2766
  {
1577
2767
  summary: "将数据转换为 ISO 8601 格式的字符串",
1578
- params: { datetime: "要转换的数据,默认为当前时间" },
1579
- paramsType: { datetime: "number | string" },
1580
- returnsType: "string",
2768
+ params: {
2769
+ datetime: "要转换的数据,默认为当前时间",
2770
+ fallback: "转换失败时的返回值"
2771
+ },
2772
+ paramsType: { datetime: "number | string", fallback: "any" },
2773
+ returnsType: "string | type(fallback)",
1581
2774
  examples: ['to_iso8601(0) // "1970-01-01T00:00:00.000Z"']
1582
2775
  }
1583
2776
  );
1584
2777
 
1585
- // src/vm/lib/global/mod/matrix.ts
2778
+ // src/vm/lib/mod/index.ts
2779
+ var mod_exports = {};
2780
+ __export(mod_exports, {
2781
+ matrix: () => matrix_exports
2782
+ });
2783
+
2784
+ // src/vm/lib/mod/matrix.ts
1586
2785
  var matrix_exports = {};
1587
2786
  __export(matrix_exports, {
1588
2787
  add: () => add,
@@ -1599,12 +2798,12 @@ __export(matrix_exports, {
1599
2798
  transpose: () => transpose,
1600
2799
  zeros: () => zeros
1601
2800
  });
1602
- function sizeImpl(matrix2) {
1603
- if (!isVmArray(matrix2)) return [];
1604
- if (matrix2.length === 0) return [0];
1605
- const numRows = matrix2.length;
2801
+ function sizeImpl(matrix) {
2802
+ if (!isVmArray(matrix)) return [];
2803
+ if (matrix.length === 0) return [0];
2804
+ const numRows = matrix.length;
1606
2805
  let numCols = 0;
1607
- for (const row of matrix2) {
2806
+ for (const row of matrix) {
1608
2807
  if (isVmArray(row)) {
1609
2808
  numCols = Math.max(numCols, row.length);
1610
2809
  } else {
@@ -1614,12 +2813,12 @@ function sizeImpl(matrix2) {
1614
2813
  return [numRows, numCols];
1615
2814
  }
1616
2815
  function num(v) {
1617
- return $ToNumber(v ?? null);
2816
+ return toNumber(v, void 0);
1618
2817
  }
1619
2818
  var size = VmLib(
1620
- (matrix2) => {
1621
- required("matrix", matrix2, []);
1622
- return sizeImpl(matrix2);
2819
+ (matrix) => {
2820
+ required("matrix", matrix, []);
2821
+ return sizeImpl(matrix);
1623
2822
  },
1624
2823
  {
1625
2824
  summary: "获取矩阵尺寸",
@@ -1630,16 +2829,16 @@ var size = VmLib(
1630
2829
  }
1631
2830
  );
1632
2831
  var transpose = VmLib(
1633
- (matrix2) => {
1634
- required("matrix", matrix2, []);
1635
- const [numRows, numCols] = sizeImpl(matrix2);
1636
- if (numRows == null || numCols == null) return matrix2;
2832
+ (matrix) => {
2833
+ required("matrix", matrix, []);
2834
+ const [numRows, numCols] = sizeImpl(matrix);
2835
+ if (numRows == null || numCols == null) return matrix;
1637
2836
  const transposed = [];
1638
2837
  for (let j = 0; j < numCols; j++) {
1639
2838
  Cp();
1640
2839
  const tj = [];
1641
2840
  for (let i = 0; i < numRows; i++) {
1642
- const row = matrix2[i] ?? null;
2841
+ const row = matrix[i] ?? null;
1643
2842
  const item = row?.[j] ?? null;
1644
2843
  tj[i] = item;
1645
2844
  }
@@ -2039,7 +3238,7 @@ var identity = VmLib(
2039
3238
  var diagonal = VmLib(
2040
3239
  (x, k = 0) => {
2041
3240
  expectArray("x", x, []);
2042
- const fk = Math.round($ToNumber(k) || 0);
3241
+ const fk = expectInteger("k", k);
2043
3242
  if (x.every((e) => isArray(e))) {
2044
3243
  const diag = [];
2045
3244
  for (let i = 0; i < x.length; i++) {
@@ -2080,13 +3279,7 @@ var diagonal = VmLib(
2080
3279
  }
2081
3280
  );
2082
3281
 
2083
- // src/vm/lib/global/mod/index.ts
2084
- var matrix = createModule("matrix", matrix_exports);
2085
-
2086
- // src/vm/lib/_loader.ts
2087
- for (const [name, value] of entries(global_exports)) {
2088
- VmSharedContext[name] = wrapEntry(name, value, "global");
2089
- }
3282
+ // src/vm/lib/loader.ts
2090
3283
  function wrapEntry(name, value, module) {
2091
3284
  if (typeof value == "function") {
2092
3285
  if (value.name !== name) {
@@ -2112,423 +3305,33 @@ function createModule(name, lib2) {
2112
3305
  }
2113
3306
  return new VmModule(name, mod);
2114
3307
  }
2115
- var lib = global_exports;
2116
-
2117
- // src/helpers/serialize.ts
2118
- var REG_IDENTIFIER_FULL = new RegExp(`^${REG_IDENTIFIER.source}$`, REG_IDENTIFIER.flags);
2119
- var REG_ORDINAL_FULL = new RegExp(`^${REG_ORDINAL.source}$`, REG_ORDINAL.flags);
2120
- var DEFAULT_OPTIONS = Object.freeze({
2121
- maxDepth: 128,
2122
- serializeNil,
2123
- serializeBoolean,
2124
- serializeNumber,
2125
- serializeString: serializeStringImpl,
2126
- serializeStringQuote: (value) => value,
2127
- serializeStringEscape: (value) => value,
2128
- serializeStringContent: (value) => value,
2129
- serializeArray,
2130
- serializeRecord,
2131
- serializePropName: String,
2132
- serializeFunction: serializeNil,
2133
- serializeModule: serializeNil,
2134
- serializeExtern: serializeNil
2135
- });
2136
- function isDefaultOptions(options) {
2137
- return options == null || options === DEFAULT_OPTIONS;
2138
- }
2139
- function getSerializeOptions(options) {
2140
- if (isDefaultOptions(options)) return DEFAULT_OPTIONS;
2141
- let opt = null;
2142
- for (const key in options) {
2143
- if (!hasOwn(options, key) || !hasOwn(DEFAULT_OPTIONS, key)) continue;
2144
- const el = options[key];
2145
- if (el == null) continue;
2146
- opt ??= { ...DEFAULT_OPTIONS };
2147
- opt[key] = el;
2148
- }
2149
- return opt ? Object.freeze(opt) : DEFAULT_OPTIONS;
2150
- }
2151
- function serializeStringImpl(value, options) {
2152
- if (!/[\p{C}'"`$\\]/u.test(value)) {
2153
- const oq = options.serializeStringQuote(`'`, true, options);
2154
- const cq = options.serializeStringQuote(`'`, false, options);
2155
- const c = options.serializeStringContent(value, options);
2156
- return oq + c + cq;
2157
- }
2158
- let ret = options.serializeStringQuote(`'`, true, options);
2159
- for (const char of value) {
2160
- if (char === "'") {
2161
- ret += options.serializeStringEscape(String.raw`\'`, options);
2162
- } else if (char === "\0") {
2163
- ret += options.serializeStringEscape(String.raw`\0`, options);
2164
- } else if (char === "\n") {
2165
- ret += options.serializeStringEscape(String.raw`\n`, options);
2166
- } else if (char === "\r") {
2167
- ret += options.serializeStringEscape(String.raw`\r`, options);
2168
- } else if (char === " ") {
2169
- ret += options.serializeStringEscape(String.raw`\t`, options);
2170
- } else if (char === "\b") {
2171
- ret += options.serializeStringEscape(String.raw`\b`, options);
2172
- } else if (char === "\f") {
2173
- ret += options.serializeStringEscape(String.raw`\f`, options);
2174
- } else if (char === "\v") {
2175
- ret += options.serializeStringEscape(String.raw`\v`, options);
2176
- } else if (char === "\\") {
2177
- ret += options.serializeStringEscape(String.raw`\\`, options);
2178
- } else if (char === "$") {
2179
- ret += options.serializeStringEscape(String.raw`\$`, options);
2180
- } else if (/\p{C}/u.test(char)) {
2181
- const code = char.codePointAt(0);
2182
- if (code <= 127) {
2183
- ret += options.serializeStringEscape(String.raw`\x${code.toString(16).padStart(2, "0")}`, options);
2184
- } else if (code >= 55296 && code <= 57343) {
2185
- ret += options.serializeStringContent("�", options);
2186
- } else {
2187
- ret += options.serializeStringEscape(String.raw`\u{${code.toString(16)}}`, options);
2188
- }
2189
- } else {
2190
- ret += options.serializeStringContent(char, options);
2191
- }
2192
- }
2193
- ret += options.serializeStringQuote(`'`, false, options);
2194
- return ret;
2195
- }
2196
- function serializeString(value, options) {
2197
- return serializeStringImpl(value, getSerializeOptions(options));
2198
- }
2199
- function serializeRecordKeyDefault(key) {
2200
- if (REG_ORDINAL_FULL.test(key) || REG_IDENTIFIER_FULL.test(key)) {
2201
- return key;
2202
- }
2203
- return serializeStringImpl(key, DEFAULT_OPTIONS);
2204
- }
2205
- function serializeRecordKeyOpt(value, options) {
2206
- if (isDefaultOptions(options)) {
2207
- return serializeRecordKeyDefault(value);
2208
- }
2209
- if (REG_ORDINAL_FULL.test(value)) {
2210
- return options.serializePropName(Number(value), options);
2211
- }
2212
- if (REG_IDENTIFIER_FULL.test(value)) {
2213
- return options.serializePropName(value, options);
2214
- }
2215
- return options.serializeString(value, options);
2216
- }
2217
- function serializeRecordKey(key, options) {
2218
- if (isDefaultOptions(options)) {
2219
- return serializeRecordKeyDefault(key);
2220
- }
2221
- return serializeRecordKeyOpt(key, getSerializeOptions(options));
2222
- }
2223
- function serializeNil() {
2224
- return "nil";
2225
- }
2226
- function serializeBoolean(value) {
2227
- return value ? "true" : "false";
2228
- }
2229
- function serializeNumber(value) {
2230
- if (isNaN(value)) return "nan";
2231
- if (!isFinite(value)) return value < 0 ? "-inf" : "inf";
2232
- if (value === 0) {
2233
- if (1 / value < 0) return "-0";
2234
- return "0";
2235
- }
2236
- return String(value);
2237
- }
2238
- function serializeArray(value, depth, options) {
2239
- if (depth > options.maxDepth) return `[]`;
2240
- if (value.length === 0) return "[]";
2241
- let str = "[";
2242
- for (let i = 0; i < value.length; i++) {
2243
- if (i > 0) str += ", ";
2244
- str += serializeImpl(value[i], depth, options);
2245
- }
2246
- str += "]";
2247
- return str;
2248
- }
2249
- var { valueOf } = Object.prototype;
2250
- function customValueOf(value) {
2251
- const thisValueOf = value.valueOf;
2252
- if (typeof thisValueOf != "function" || thisValueOf === valueOf) {
2253
- return void 0;
2254
- }
2255
- const customValue = thisValueOf.call(value);
2256
- if (customValue === value) return void 0;
2257
- return customValue;
2258
- }
2259
- function serializeRecord(value, depth, options) {
2260
- const customValue = customValueOf(value);
2261
- if (customValue !== void 0) {
2262
- return serializeImpl(customValue, depth - 1, options);
2263
- }
2264
- if (depth > options.maxDepth) return `()`;
2265
- const e = entries(value);
2266
- if (e.length === 0) return "()";
2267
- if (e.length === 1) {
2268
- const [k, v] = e[0];
2269
- if (k === "0") {
2270
- return `(${serializeImpl(v, depth, options)},)`;
2271
- }
2272
- return `(${serializeRecordKeyOpt(k, options)}: ${serializeImpl(v, depth, options)})`;
2273
- }
2274
- const omitKey = isVmArrayLikeRecordByEntires(e);
2275
- let str = "(";
2276
- for (const [key, val] of e) {
2277
- if (str.length > 1) str += ", ";
2278
- if (omitKey) {
2279
- str += serializeImpl(val, depth, options);
2280
- } else {
2281
- str += `${serializeRecordKeyOpt(key, options)}: ${serializeImpl(val, depth, options)}`;
2282
- }
2283
- }
2284
- str += ")";
2285
- return str;
2286
- }
2287
- function serializeImpl(value, depth, options) {
2288
- if (value == null) {
2289
- return options.serializeNil(options);
2290
- }
2291
- if (typeof value == "boolean") {
2292
- return options.serializeBoolean(value, options);
2293
- }
2294
- if (typeof value == "number") {
2295
- return options.serializeNumber(value, options);
2296
- }
2297
- if (typeof value == "string") {
2298
- return options.serializeString(value, options);
2299
- }
2300
- if (isVmFunction(value)) {
2301
- return options.serializeFunction(value, options);
2302
- }
2303
- if (isVmModule(value)) {
2304
- return options.serializeModule(value, depth + 1, options);
2305
- }
2306
- if (isVmExtern(value)) {
2307
- return options.serializeExtern(value, depth + 1, options);
2308
- }
2309
- if (isVmArray(value)) {
2310
- return options.serializeArray(value, depth + 1, options);
2311
- }
2312
- if (isVmRecord(value)) {
2313
- return options.serializeRecord(value, depth + 1, options);
2314
- }
2315
- value;
2316
- return options.serializeNil(options);
2317
- }
2318
- function serialize(value, options) {
2319
- return serializeImpl(value, 0, getSerializeOptions(options));
2320
- }
2321
-
2322
- // src/compiler/index.ts
2323
- import { loadModule } from "@mirascript/bindings";
2324
-
2325
- // src/vm/env.ts
2326
- var keys3 = [];
2327
- var values3 = [];
2328
- for (const [key, value] of entries(operations_exports)) {
2329
- keys3.push(key);
2330
- values3.push(value);
2331
- }
2332
- for (const [key, value] of entries(helpers_exports)) {
2333
- keys3.push(key);
2334
- values3.push(value);
2335
- }
2336
-
2337
- // src/compiler/create-script.ts
2338
- var kVmScript = Symbol.for("mirascript.vm.script");
2339
- function wrapScript(source, script) {
2340
- if (kVmScript in script) {
2341
- return script;
2342
- }
2343
- defineProperty(script, kVmScript, { value: true });
2344
- if (typeof source === "string") {
2345
- defineProperty(script, "source", { value: source, configurable: true });
2346
- } else if (source instanceof Uint8Array) {
2347
- defineProperty(script, "source", { value: "<buffer>", configurable: true });
2348
- }
2349
- return script;
2350
- }
2351
- function createScript(source, code) {
2352
- let script;
2353
- try {
2354
- script = new Function(...keys3, code)(...values3);
2355
- } catch (error) {
2356
- throw new Error(`Failed to create script`, { cause: error });
2357
- }
2358
- return wrapScript(source, script);
2359
- }
2360
-
2361
- // src/compiler/compile-fast.ts
2362
- var REG_NUMBER_FULL = /^\d+(?:\.\d+)?(?:[eE][+-]?\d+)?$/;
2363
- var REG_IDENTIFIER_FAST = /^(?:\$+|@+)[a-zA-Z0-9_]*$/;
2364
- var FAST_SCRIPT_MAX_LEN = 32;
2365
- function compileScriptFast(code, options) {
2366
- if (code.length > FAST_SCRIPT_MAX_LEN) return void 0;
2367
- const trimmedCode = code.trim();
2368
- if (!trimmedCode) {
2369
- return wrapScript(code, () => null);
2370
- }
2371
- switch (trimmedCode) {
2372
- case "nil":
2373
- return wrapScript(code, () => null);
2374
- case "true":
2375
- return wrapScript(code, () => true);
2376
- case "false":
2377
- return wrapScript(code, () => false);
2378
- case "nan":
2379
- return wrapScript(code, () => 0 / 0);
2380
- case "inf":
2381
- case "+inf":
2382
- return wrapScript(code, () => 1 / 0);
2383
- case "-inf":
2384
- return wrapScript(code, () => -1 / 0);
2385
- }
2386
- if (REG_IDENTIFIER_FAST.test(trimmedCode)) {
2387
- const id = trimmedCode;
2388
- return wrapScript(code, (global = GlobalFallback()) => global.get(id));
2389
- }
2390
- if (REG_NUMBER_FULL.test(trimmedCode)) {
2391
- const num2 = Number(trimmedCode);
2392
- if (!isFinite(num2)) return void 0;
2393
- return wrapScript(code, () => num2);
2394
- }
2395
- return void 0;
2396
- }
2397
- var FAST_TEMPLATE_MAX_LEN = 1024;
2398
- function compileTemplateFast(code, options) {
2399
- if (code.length > FAST_TEMPLATE_MAX_LEN) return void 0;
2400
- if (!code.includes("$")) {
2401
- return wrapScript(code, () => code);
2402
- }
2403
- return void 0;
2404
- }
2405
- function compileFast(code, options) {
2406
- if (options.sourceMap) return void 0;
2407
- return (options.input_mode === "Template" ? compileTemplateFast : compileScriptFast)(code, options);
2408
- }
2409
-
2410
- // src/compiler/worker-manager.ts
2411
- var worker;
2412
- async function getWorker() {
2413
- if (worker) return worker;
2414
- worker = new Promise((resolve, reject) => {
2415
- const w = new Worker(new URL("#compiler/worker", import.meta.url), {
2416
- type: "module",
2417
- name: "@mirascript/compiler"
2418
- });
2419
- const onError = (e) => {
2420
- cleanUp();
2421
- reject(new Error(`Worker failed to start: ${e.message}`));
2422
- };
2423
- const onMessage = (e) => {
2424
- if (e.data === "ready") {
2425
- cleanUp();
2426
- resolve(w);
2427
- } else if (e.data instanceof Error) {
2428
- cleanUp();
2429
- reject(e.data);
2430
- }
2431
- };
2432
- w.addEventListener("error", onError);
2433
- w.addEventListener("message", onMessage);
2434
- const cleanUp = () => {
2435
- w.removeEventListener("error", onError);
2436
- w.removeEventListener("message", onMessage);
2437
- };
2438
- setTimeout(() => {
2439
- onError(new ErrorEvent("error", { message: "Worker did not respond in time" }));
2440
- }, 3e4);
2441
- });
2442
- return worker;
2443
- }
2444
- async function compileWorker(...args) {
2445
- const worker2 = await getWorker();
2446
- const seq = Math.random();
2447
- worker2.postMessage([seq, ...args]);
2448
- return await new Promise((resolve, reject) => {
2449
- const callback = (ev) => {
2450
- const data = ev.data;
2451
- if (!Array.isArray(data)) return;
2452
- const [retSeq, ...rest] = data;
2453
- if (seq !== retSeq) return;
2454
- worker2.removeEventListener("message", callback);
2455
- if (rest.length === 2) {
2456
- resolve(rest);
2457
- } else {
2458
- reject(rest[0]);
2459
- }
2460
- };
2461
- worker2.addEventListener("message", callback);
2462
- });
2463
- }
2464
3308
 
2465
- // src/compiler/index.ts
2466
- await loadModule();
2467
- var WORKER_MIN_LEN = typeof Worker != "function" ? Number.MAX_VALUE : 1024;
2468
- function reportDiagnostic(source, diagnostics) {
2469
- const parsed = parseDiagnostics(source, diagnostics);
2470
- const messages = parsed.errors.map(formatDiagnostic);
2471
- throw new Error(`Failed to compile:
2472
- ${messages.join("\n")}`);
2473
- }
2474
- function emitScript(source, [code, diagnostics], options) {
2475
- if (!code) {
2476
- reportDiagnostic(source, diagnostics);
2477
- }
2478
- const sourcemaps = options.sourceMap ? parseDiagnostics(source, diagnostics, (c) => c === DiagnosticCode.SourceMap).sourcemaps : [];
2479
- const target = emit(source, code, sourcemaps, options);
2480
- return createScript(source, target);
2481
- }
2482
- async function compile(source, options = {}) {
2483
- if (options.sourceMap) {
2484
- options.diagnostic_sourcemap = true;
2485
- options.diagnostic_position_encoding ??= "Utf16";
2486
- }
2487
- if (typeof source == "string") {
2488
- const result = compileFast(source, options);
2489
- if (result) return result;
2490
- }
2491
- if (source.length < WORKER_MIN_LEN) {
2492
- const bc = await generateBytecode(source, options);
2493
- return emitScript(source, bc, options);
2494
- }
2495
- const [target, diagnostics] = await compileWorker(source, options);
2496
- if (target == null) {
2497
- reportDiagnostic(source, diagnostics);
2498
- }
2499
- return createScript(source, target);
3309
+ // src/vm/lib/index.ts
3310
+ for (const [name, value] of entries(global_exports)) {
3311
+ VmSharedContext[name] = wrapEntry(name, value, "global");
2500
3312
  }
2501
- function compileSync(source, options = {}) {
2502
- if (typeof source == "string") {
2503
- const result = compileFast(source, options);
2504
- if (result) return result;
2505
- }
2506
- const bc = generateBytecodeSync(source, options);
2507
- return emitScript(source, bc, options);
3313
+ for (const [name, value] of entries(mod_exports)) {
3314
+ const mod = createModule(name, value);
3315
+ VmSharedContext[name] = wrapEntry(name, mod, "global");
2508
3316
  }
2509
-
2510
- // src/subtle.ts
2511
- var keywords = () => {
2512
- const kw = Object.freeze(getModule().keywords());
2513
- keywords = () => kw;
2514
- return kw;
2515
- };
3317
+ var lib = Object.freeze(Object.assign(create(null), global_exports, mod_exports));
2516
3318
 
2517
3319
  export {
2518
- constants_exports,
3320
+ operations_exports,
3321
+ VmExtern,
3322
+ wrapToVmValue,
3323
+ unwrapFromVmValue,
3324
+ configCheckpoint,
3325
+ VmFunction,
3326
+ VmSharedContext,
3327
+ defineVmContextValue,
3328
+ DefaultVmContext,
3329
+ createVmContext,
2519
3330
  emitScript,
2520
3331
  compile,
2521
3332
  compileSync,
2522
- keywords,
3333
+ VmModule,
2523
3334
  debug_print,
2524
- lib,
2525
- serializeString,
2526
- serializeRecordKey,
2527
- serializeNil,
2528
- serializeBoolean,
2529
- serializeNumber,
2530
- serializeArray,
2531
- serializeRecord,
2532
- serialize
2533
- };
2534
- //# sourceMappingURL=chunk-NT235HY3.js.map
3335
+ lib
3336
+ };
3337
+ //# sourceMappingURL=chunk-LU4ZKFF6.js.map