@cuxt/sandboxjs 0.1.1 → 0.1.4

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 (226) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +198 -185
  3. package/{build → dist/cjs}/Sandbox.d.ts +15 -6
  4. package/dist/cjs/Sandbox.js +126 -0
  5. package/dist/{SandboxExec.d.ts → cjs/SandboxExec.d.ts} +8 -17
  6. package/dist/cjs/SandboxExec.js +227 -0
  7. package/{build/eval.d.ts → dist/cjs/eval/index.d.ts} +10 -2
  8. package/dist/cjs/eval/index.js +233 -0
  9. package/dist/cjs/executor/executorUtils.d.ts +161 -0
  10. package/dist/cjs/executor/executorUtils.js +930 -0
  11. package/dist/cjs/executor/index.d.ts +1 -0
  12. package/dist/cjs/executor/index.js +2 -0
  13. package/dist/cjs/executor/ops/assignment.d.ts +1 -0
  14. package/dist/cjs/executor/ops/assignment.js +88 -0
  15. package/dist/cjs/executor/ops/call.d.ts +1 -0
  16. package/dist/cjs/executor/ops/call.js +160 -0
  17. package/dist/cjs/executor/ops/comparison.d.ts +1 -0
  18. package/dist/cjs/executor/ops/comparison.js +36 -0
  19. package/dist/cjs/executor/ops/control.d.ts +1 -0
  20. package/dist/cjs/executor/ops/control.js +203 -0
  21. package/dist/cjs/executor/ops/functions.d.ts +1 -0
  22. package/dist/cjs/executor/ops/functions.js +55 -0
  23. package/dist/cjs/executor/ops/index.d.ts +0 -0
  24. package/dist/cjs/executor/ops/index.js +11 -0
  25. package/dist/cjs/executor/ops/literals.d.ts +1 -0
  26. package/dist/cjs/executor/ops/literals.js +45 -0
  27. package/dist/cjs/executor/ops/misc.d.ts +1 -0
  28. package/dist/cjs/executor/ops/misc.js +25 -0
  29. package/dist/cjs/executor/ops/object.d.ts +1 -0
  30. package/dist/cjs/executor/ops/object.js +51 -0
  31. package/dist/cjs/executor/ops/prop.d.ts +1 -0
  32. package/dist/cjs/executor/ops/prop.js +70 -0
  33. package/dist/cjs/executor/ops/unary.d.ts +1 -0
  34. package/dist/cjs/executor/ops/unary.js +48 -0
  35. package/dist/cjs/executor/ops/variables.d.ts +1 -0
  36. package/dist/cjs/executor/ops/variables.js +16 -0
  37. package/dist/cjs/executor/opsRegistry.d.ts +33 -0
  38. package/dist/cjs/executor/opsRegistry.js +8 -0
  39. package/dist/cjs/package.json +3 -0
  40. package/dist/cjs/parser/index.d.ts +3 -0
  41. package/dist/cjs/parser/index.js +1 -0
  42. package/dist/{parser.d.ts → cjs/parser/lisp.d.ts} +29 -42
  43. package/dist/cjs/parser/lispTypes/conditionals.d.ts +2 -0
  44. package/dist/cjs/parser/lispTypes/conditionals.js +135 -0
  45. package/dist/cjs/parser/lispTypes/control.d.ts +2 -0
  46. package/dist/cjs/parser/lispTypes/control.js +204 -0
  47. package/dist/cjs/parser/lispTypes/declarations.d.ts +2 -0
  48. package/dist/cjs/parser/lispTypes/declarations.js +99 -0
  49. package/dist/cjs/parser/lispTypes/index.d.ts +3 -0
  50. package/dist/cjs/parser/lispTypes/index.js +17 -0
  51. package/dist/cjs/parser/lispTypes/operators.d.ts +2 -0
  52. package/dist/cjs/parser/lispTypes/operators.js +252 -0
  53. package/dist/cjs/parser/lispTypes/shared.d.ts +38 -0
  54. package/dist/cjs/parser/lispTypes/structures.d.ts +2 -0
  55. package/dist/cjs/parser/lispTypes/structures.js +188 -0
  56. package/dist/cjs/parser/lispTypes/values.d.ts +2 -0
  57. package/dist/cjs/parser/lispTypes/values.js +89 -0
  58. package/dist/cjs/parser/parserUtils.d.ts +34 -0
  59. package/dist/cjs/parser/parserUtils.js +968 -0
  60. package/dist/cjs/utils/CodeString.d.ts +16 -0
  61. package/dist/cjs/utils/CodeString.js +64 -0
  62. package/dist/cjs/utils/ExecContext.d.ts +34 -0
  63. package/dist/cjs/utils/ExecContext.js +171 -0
  64. package/dist/cjs/utils/Prop.d.ts +16 -0
  65. package/dist/cjs/utils/Prop.js +81 -0
  66. package/dist/cjs/utils/Scope.d.ts +47 -0
  67. package/dist/cjs/utils/Scope.js +127 -0
  68. package/dist/cjs/utils/errors.d.ts +10 -0
  69. package/dist/cjs/utils/errors.js +12 -0
  70. package/dist/cjs/utils/functionReplacements.d.ts +11 -0
  71. package/dist/cjs/utils/functionReplacements.js +362 -0
  72. package/dist/cjs/utils/index.d.ts +7 -0
  73. package/dist/cjs/utils/index.js +7 -0
  74. package/dist/cjs/utils/types.d.ts +221 -0
  75. package/dist/cjs/utils/types.js +164 -0
  76. package/dist/cjs/utils/unraw.js +145 -0
  77. package/dist/{node → esm}/Sandbox.d.ts +15 -6
  78. package/dist/esm/Sandbox.js +115 -0
  79. package/dist/esm/Sandbox.js.map +1 -0
  80. package/{build → dist/esm}/SandboxExec.d.ts +8 -17
  81. package/dist/esm/SandboxExec.js +224 -0
  82. package/dist/esm/SandboxExec.js.map +1 -0
  83. package/dist/{eval.d.ts → esm/eval/index.d.ts} +10 -2
  84. package/dist/esm/eval/index.js +235 -0
  85. package/dist/esm/eval/index.js.map +1 -0
  86. package/dist/esm/executor/executorUtils.d.ts +161 -0
  87. package/dist/esm/executor/executorUtils.js +898 -0
  88. package/dist/esm/executor/executorUtils.js.map +1 -0
  89. package/dist/esm/executor/index.d.ts +1 -0
  90. package/dist/esm/executor/index.js +2 -0
  91. package/dist/esm/executor/ops/assignment.d.ts +1 -0
  92. package/dist/esm/executor/ops/assignment.js +90 -0
  93. package/dist/esm/executor/ops/assignment.js.map +1 -0
  94. package/dist/esm/executor/ops/call.d.ts +1 -0
  95. package/dist/esm/executor/ops/call.js +162 -0
  96. package/dist/esm/executor/ops/call.js.map +1 -0
  97. package/dist/esm/executor/ops/comparison.d.ts +1 -0
  98. package/dist/esm/executor/ops/comparison.js +38 -0
  99. package/dist/esm/executor/ops/comparison.js.map +1 -0
  100. package/dist/esm/executor/ops/control.d.ts +1 -0
  101. package/dist/esm/executor/ops/control.js +205 -0
  102. package/dist/esm/executor/ops/control.js.map +1 -0
  103. package/dist/esm/executor/ops/functions.d.ts +1 -0
  104. package/dist/esm/executor/ops/functions.js +57 -0
  105. package/dist/esm/executor/ops/functions.js.map +1 -0
  106. package/dist/esm/executor/ops/index.d.ts +0 -0
  107. package/dist/esm/executor/ops/index.js +11 -0
  108. package/dist/esm/executor/ops/literals.d.ts +1 -0
  109. package/dist/esm/executor/ops/literals.js +47 -0
  110. package/dist/esm/executor/ops/literals.js.map +1 -0
  111. package/dist/esm/executor/ops/misc.d.ts +1 -0
  112. package/dist/esm/executor/ops/misc.js +27 -0
  113. package/dist/esm/executor/ops/misc.js.map +1 -0
  114. package/dist/esm/executor/ops/object.d.ts +1 -0
  115. package/dist/esm/executor/ops/object.js +53 -0
  116. package/dist/esm/executor/ops/object.js.map +1 -0
  117. package/dist/esm/executor/ops/prop.d.ts +1 -0
  118. package/dist/esm/executor/ops/prop.js +72 -0
  119. package/dist/esm/executor/ops/prop.js.map +1 -0
  120. package/dist/esm/executor/ops/unary.d.ts +1 -0
  121. package/dist/esm/executor/ops/unary.js +50 -0
  122. package/dist/esm/executor/ops/unary.js.map +1 -0
  123. package/dist/esm/executor/ops/variables.d.ts +1 -0
  124. package/dist/esm/executor/ops/variables.js +18 -0
  125. package/dist/esm/executor/ops/variables.js.map +1 -0
  126. package/dist/esm/executor/opsRegistry.d.ts +33 -0
  127. package/dist/esm/executor/opsRegistry.js +9 -0
  128. package/dist/esm/executor/opsRegistry.js.map +1 -0
  129. package/dist/esm/package.json +3 -0
  130. package/dist/esm/parser/index.d.ts +3 -0
  131. package/dist/esm/parser/index.js +1 -0
  132. package/{build/parser.d.ts → dist/esm/parser/lisp.d.ts} +29 -42
  133. package/dist/esm/parser/lispTypes/conditionals.d.ts +2 -0
  134. package/dist/esm/parser/lispTypes/conditionals.js +137 -0
  135. package/dist/esm/parser/lispTypes/conditionals.js.map +1 -0
  136. package/dist/esm/parser/lispTypes/control.d.ts +2 -0
  137. package/dist/esm/parser/lispTypes/control.js +206 -0
  138. package/dist/esm/parser/lispTypes/control.js.map +1 -0
  139. package/dist/esm/parser/lispTypes/declarations.d.ts +2 -0
  140. package/dist/esm/parser/lispTypes/declarations.js +101 -0
  141. package/dist/esm/parser/lispTypes/declarations.js.map +1 -0
  142. package/dist/esm/parser/lispTypes/index.d.ts +3 -0
  143. package/dist/esm/parser/lispTypes/index.js +19 -0
  144. package/dist/esm/parser/lispTypes/index.js.map +1 -0
  145. package/dist/esm/parser/lispTypes/operators.d.ts +2 -0
  146. package/dist/esm/parser/lispTypes/operators.js +254 -0
  147. package/dist/esm/parser/lispTypes/operators.js.map +1 -0
  148. package/dist/esm/parser/lispTypes/shared.d.ts +38 -0
  149. package/dist/esm/parser/lispTypes/structures.d.ts +2 -0
  150. package/dist/esm/parser/lispTypes/structures.js +190 -0
  151. package/dist/esm/parser/lispTypes/structures.js.map +1 -0
  152. package/dist/esm/parser/lispTypes/values.d.ts +2 -0
  153. package/dist/esm/parser/lispTypes/values.js +91 -0
  154. package/dist/esm/parser/lispTypes/values.js.map +1 -0
  155. package/dist/esm/parser/parserUtils.d.ts +34 -0
  156. package/dist/esm/parser/parserUtils.js +959 -0
  157. package/dist/esm/parser/parserUtils.js.map +1 -0
  158. package/dist/esm/utils/CodeString.d.ts +16 -0
  159. package/dist/esm/utils/CodeString.js +66 -0
  160. package/dist/esm/utils/CodeString.js.map +1 -0
  161. package/dist/esm/utils/ExecContext.d.ts +34 -0
  162. package/dist/esm/utils/ExecContext.js +168 -0
  163. package/dist/esm/utils/ExecContext.js.map +1 -0
  164. package/dist/esm/utils/Prop.d.ts +16 -0
  165. package/dist/esm/utils/Prop.js +80 -0
  166. package/dist/esm/utils/Prop.js.map +1 -0
  167. package/dist/esm/utils/Scope.d.ts +47 -0
  168. package/dist/esm/utils/Scope.js +122 -0
  169. package/dist/esm/utils/Scope.js.map +1 -0
  170. package/dist/esm/utils/errors.d.ts +10 -0
  171. package/dist/esm/utils/errors.js +10 -0
  172. package/dist/esm/utils/errors.js.map +1 -0
  173. package/dist/esm/utils/functionReplacements.d.ts +11 -0
  174. package/dist/esm/utils/functionReplacements.js +361 -0
  175. package/dist/esm/utils/functionReplacements.js.map +1 -0
  176. package/dist/esm/utils/index.d.ts +7 -0
  177. package/dist/esm/utils/index.js +7 -0
  178. package/dist/esm/utils/types.d.ts +221 -0
  179. package/dist/esm/utils/types.js +160 -0
  180. package/dist/esm/utils/types.js.map +1 -0
  181. package/dist/esm/utils/unraw.js +147 -0
  182. package/dist/esm/utils/unraw.js.map +1 -0
  183. package/dist/umd/Sandbox.min.js +2 -0
  184. package/dist/umd/Sandbox.min.js.map +1 -0
  185. package/dist/umd/SandboxExec.min.js +2 -0
  186. package/dist/umd/SandboxExec.min.js.map +1 -0
  187. package/package.json +17 -16
  188. package/build/Sandbox.js +0 -62
  189. package/build/SandboxExec.js +0 -214
  190. package/build/eval.js +0 -205
  191. package/build/executor.d.ts +0 -124
  192. package/build/executor.js +0 -1554
  193. package/build/parser.js +0 -1527
  194. package/build/unraw.js +0 -168
  195. package/build/utils.d.ts +0 -264
  196. package/build/utils.js +0 -362
  197. package/dist/Sandbox.d.ts +0 -25
  198. package/dist/Sandbox.js +0 -270
  199. package/dist/Sandbox.js.map +0 -1
  200. package/dist/Sandbox.min.js +0 -2
  201. package/dist/Sandbox.min.js.map +0 -1
  202. package/dist/SandboxExec.js +0 -218
  203. package/dist/SandboxExec.js.map +0 -1
  204. package/dist/SandboxExec.min.js +0 -2
  205. package/dist/SandboxExec.min.js.map +0 -1
  206. package/dist/executor.d.ts +0 -124
  207. package/dist/executor.js +0 -1558
  208. package/dist/executor.js.map +0 -1
  209. package/dist/node/Sandbox.js +0 -277
  210. package/dist/node/SandboxExec.d.ts +0 -66
  211. package/dist/node/SandboxExec.js +0 -225
  212. package/dist/node/eval.d.ts +0 -27
  213. package/dist/node/executor.d.ts +0 -124
  214. package/dist/node/executor.js +0 -1575
  215. package/dist/node/parser.d.ts +0 -154
  216. package/dist/node/parser.js +0 -1704
  217. package/dist/node/utils.d.ts +0 -264
  218. package/dist/node/utils.js +0 -385
  219. package/dist/parser.js +0 -1690
  220. package/dist/parser.js.map +0 -1
  221. package/dist/unraw.d.ts +0 -11
  222. package/dist/utils.d.ts +0 -264
  223. package/dist/utils.js +0 -365
  224. package/dist/utils.js.map +0 -1
  225. /package/{build → dist/cjs/utils}/unraw.d.ts +0 -0
  226. /package/dist/{node → esm/utils}/unraw.d.ts +0 -0
@@ -0,0 +1,959 @@
1
+ import unraw from "../utils/unraw.js";
2
+ import { SandboxCapabilityError } from "../utils/errors.js";
3
+ import { CodeString } from "../utils/CodeString.js";
4
+ import { LispType } from "../utils/types.js";
5
+ import { isLisp } from "../utils/ExecContext.js";
6
+ import "../utils/index.js";
7
+ import { registerLispTypes } from "./lispTypes/index.js";
8
+ //#region src/parser/parserUtils.ts
9
+ function createLisp(obj) {
10
+ return [
11
+ obj.op,
12
+ obj.a,
13
+ obj.b
14
+ ];
15
+ }
16
+ var NullLisp = createLisp({
17
+ op: LispType.None,
18
+ a: LispType.None,
19
+ b: LispType.None
20
+ });
21
+ var statementLabelRegex = /([a-zA-Z$_][\w$]*)\s*:/g;
22
+ function extractStatementLabels(prefix = "") {
23
+ return [...prefix.matchAll(statementLabelRegex)].map((match) => match[1]);
24
+ }
25
+ function wrapLabeledStatement(labels, statement) {
26
+ return labels.reduceRight((current, label) => createLisp({
27
+ op: LispType.Labeled,
28
+ a: label,
29
+ b: current
30
+ }), statement);
31
+ }
32
+ var lispTypes = /* @__PURE__ */ new Map();
33
+ var ParseError = class extends Error {
34
+ constructor(message, code) {
35
+ super(message + ": " + code.substring(0, 40));
36
+ this.code = code;
37
+ }
38
+ };
39
+ var lastType;
40
+ var space = /^\s/;
41
+ var expectTypes = {
42
+ splitter: {
43
+ types: {
44
+ power: /^(\*\*)(?!=)/,
45
+ opHigh: /^(\/|\*(?!\*)|%)(?!=)/,
46
+ op: /^(\+(?!(\+))|-(?!(-)))(?!=)/,
47
+ comparitor: /^(<=|>=|<(?!<)|>(?!>)|!==|!=(?!=)|===|==)/,
48
+ bitwiseShift: /^(<<|>>(?!>)|>>>)(?!=)/,
49
+ bitwiseAnd: /^(&(?!&))(?!=)/,
50
+ bitwiseXor: /^(\^)(?!=)/,
51
+ bitwiseOr: /^(\|(?!\|))(?!=)/,
52
+ boolOpAnd: /^(&&)(?!=)/,
53
+ boolOpOr: /^(\|\|(?!=)|instanceof(?![\w$])|in(?![\w$]))/,
54
+ nullishCoalescing: /^\?\?(?!=)/
55
+ },
56
+ next: [
57
+ "modifier",
58
+ "value",
59
+ "prop",
60
+ "incrementerBefore"
61
+ ]
62
+ },
63
+ inlineIf: {
64
+ types: { inlineIf: /^\?(?!\.(?!\d))/ },
65
+ next: ["expEnd"]
66
+ },
67
+ assignment: {
68
+ types: {
69
+ assignModify: /^(-=|\+=|\/=|\*\*=|\*=|%=|\^=|&=|\|=|>>>=|>>=|<<=|&&=|\|\|=|\?\?=)/,
70
+ assign: /^(=)(?!=)/
71
+ },
72
+ next: [
73
+ "modifier",
74
+ "value",
75
+ "prop",
76
+ "incrementerBefore"
77
+ ]
78
+ },
79
+ incrementerBefore: {
80
+ types: { incrementerBefore: /^(\+\+|--)/ },
81
+ next: ["prop"]
82
+ },
83
+ expEdge: {
84
+ types: {
85
+ call: /^(\?\.)?[(]/,
86
+ incrementerAfter: /^(\+\+|--)/,
87
+ taggedTemplate: /^`(\d+)`/
88
+ },
89
+ next: [
90
+ "splitter",
91
+ "assignment",
92
+ "expEdge",
93
+ "dot",
94
+ "inlineIf",
95
+ "expEnd"
96
+ ]
97
+ },
98
+ modifier: {
99
+ types: {
100
+ not: /^!/,
101
+ inverse: /^~/,
102
+ negative: /^-(?!-)/,
103
+ positive: /^\+(?!\+)/,
104
+ typeof: /^typeof(?![\w$])/,
105
+ delete: /^delete(?![\w$])/
106
+ },
107
+ next: [
108
+ "modifier",
109
+ "value",
110
+ "prop",
111
+ "incrementerBefore"
112
+ ]
113
+ },
114
+ dot: {
115
+ types: {
116
+ arrayProp: /^(\?\.)?\[/,
117
+ dot: /^(\?)?\.(?=\s*[a-zA-Z$_])/
118
+ },
119
+ next: [
120
+ "splitter",
121
+ "assignment",
122
+ "expEdge",
123
+ "dot",
124
+ "inlineIf",
125
+ "expEnd"
126
+ ]
127
+ },
128
+ prop: {
129
+ types: { prop: /^[a-zA-Z$_][a-zA-Z\d$_]*/ },
130
+ next: [
131
+ "splitter",
132
+ "assignment",
133
+ "expEdge",
134
+ "dot",
135
+ "inlineIf",
136
+ "expEnd"
137
+ ]
138
+ },
139
+ value: {
140
+ types: {
141
+ createObject: /^\{/,
142
+ createArray: /^\[/,
143
+ number: /^(0b[01]+(_[01]+)*|0o[0-7]+(_[0-7]+)*|0x[\da-f]+(_[\da-f]+)*|(\d+(_\d+)*(\.\d+(_\d+)*)?|\.\d+(_\d+)*))(e[+-]?\d+(_\d+)*)?(n)?(?!\d)/i,
144
+ string: /^"(\d+)"/,
145
+ literal: /^`(\d+)`/,
146
+ regex: /^\/(\d+)\/r(?![\w$])/,
147
+ boolean: /^(true|false)(?![\w$])/,
148
+ null: /^null(?![\w$])/,
149
+ und: /^undefined(?![\w$])/,
150
+ arrowFunctionSingle: /^(async\s+)?([a-zA-Z$_][a-zA-Z\d$_]*)\s*=>\s*({)?/,
151
+ arrowFunction: /^(async\s*)?\(\s*([^)(]*?)\s*\)\s*=>\s*({)?/,
152
+ inlineFunction: /^(async\s+)?function(\*\s*|\s*)([a-zA-Z$_][a-zA-Z\d$_]*)?\s*\(\s*/,
153
+ yield: /^yield\*(?![\w$])\s*|^yield(?![\w$])\s*/,
154
+ group: /^\(/,
155
+ NaN: /^NaN(?![\w$])/,
156
+ Infinity: /^Infinity(?![\w$])/,
157
+ void: /^void(?![\w$])\s*/,
158
+ await: /^await(?![\w$])\s*/,
159
+ new: /^new(?![\w$])\s*/
160
+ },
161
+ next: [
162
+ "splitter",
163
+ "expEdge",
164
+ "dot",
165
+ "inlineIf",
166
+ "expEnd"
167
+ ]
168
+ },
169
+ initialize: {
170
+ types: {
171
+ initializeDestructure: /^(var|let|const|internal)\s+([{[])/,
172
+ initialize: /^(var|let|const|internal)\s+([a-zA-Z$_][a-zA-Z\d$_]*)\s*(=)?/,
173
+ return: /^return(?![\w$])/,
174
+ throw: /^throw(?![\w$])\s*/
175
+ },
176
+ next: [
177
+ "modifier",
178
+ "value",
179
+ "prop",
180
+ "incrementerBefore",
181
+ "expEnd"
182
+ ]
183
+ },
184
+ spreadObject: {
185
+ types: { spreadObject: /^\.\.\./ },
186
+ next: ["value", "prop"]
187
+ },
188
+ spreadArray: {
189
+ types: { spreadArray: /^\.\.\./ },
190
+ next: ["value", "prop"]
191
+ },
192
+ expEnd: {
193
+ types: {},
194
+ next: []
195
+ },
196
+ expFunction: {
197
+ types: { function: /^(async\s+)?function(\*\s*|\s+)([a-zA-Z$_][a-zA-Z\d$_]*)\s*\(\s*/ },
198
+ next: ["expEdge", "expEnd"]
199
+ },
200
+ expSingle: {
201
+ types: {
202
+ for: /^((?:[a-zA-Z$_][\w$]*\s*:\s*)*)\s*for(\s+await)?\s*\(/,
203
+ do: /^((?:[a-zA-Z$_][\w$]*\s*:\s*)*)\s*do(?![\w$])\s*(\{)?/,
204
+ while: /^((?:[a-zA-Z$_][\w$]*\s*:\s*)*)\s*while\s*\(/,
205
+ loopAction: /^(break|continue)(?![\w$])\s*([a-zA-Z$_][\w$]*)?/,
206
+ if: /^((?:[a-zA-Z$_][\w$]*\s*:\s*)*)\s*if\s*\(/,
207
+ try: /^((?:[a-zA-Z$_][\w$]*\s*:\s*)*)\s*try\s*{/,
208
+ block: /^((?:[a-zA-Z$_][\w$]*\s*:\s*)*)\s*{/,
209
+ switch: /^((?:[a-zA-Z$_][\w$]*\s*:\s*)*)\s*switch\s*\(/
210
+ },
211
+ next: ["expEnd"]
212
+ }
213
+ };
214
+ var closings = {
215
+ "(": ")",
216
+ "[": "]",
217
+ "{": "}",
218
+ "'": "'",
219
+ "\"": "\"",
220
+ "`": "`"
221
+ };
222
+ function testMultiple(str, tests) {
223
+ let found = null;
224
+ for (let i = 0; i < tests.length; i++) {
225
+ found = tests[i].exec(str);
226
+ if (found) break;
227
+ }
228
+ return found;
229
+ }
230
+ var emptyString = new CodeString("");
231
+ var okFirstChars = /^[+\-~ !]/;
232
+ var aNumber = expectTypes.value.types.number;
233
+ var wordReg = /^((if|for|else|while|do|function)(?![\w$])|[\w$]+)/;
234
+ var semiColon = /^;/;
235
+ var insertedSemicolons = /* @__PURE__ */ new WeakMap();
236
+ var quoteCache = /* @__PURE__ */ new WeakMap();
237
+ function restOfExp(constants, part, tests, quote, firstOpening, closingsTests, details = {}, depth = 0) {
238
+ if (!part.length) return part;
239
+ if (depth > constants.maxDepth) throw new SandboxCapabilityError("Maximum expression depth exceeded");
240
+ details.words = details.words || [];
241
+ let isStart = true;
242
+ tests = tests || [];
243
+ const hasSemiTest = tests.includes(semiColon);
244
+ if (hasSemiTest) tests = tests.filter((a) => a !== semiColon);
245
+ const insertedSemis = insertedSemicolons.get(part.ref) || [];
246
+ const cache = quoteCache.get(part.ref) || /* @__PURE__ */ new Map();
247
+ quoteCache.set(part.ref, cache);
248
+ if (quote && cache.has(part.start - 1)) return part.substring(0, cache.get(part.start - 1) - part.start);
249
+ let escape = false;
250
+ let done = false;
251
+ let lastChar = "";
252
+ let isOneLiner = false;
253
+ let i;
254
+ let lastInertedSemi = false;
255
+ let seenKeyword = false;
256
+ let skipNextWord = false;
257
+ for (i = 0; i < part.length && !done; i++) {
258
+ let char = part.char(i);
259
+ if (quote === "\"" || quote === "'" || quote === "`") {
260
+ if (quote === "`" && char === "$" && part.char(i + 1) === "{" && !escape) {
261
+ const skip = restOfExp(constants, part.substring(i + 2), [], "{", void 0, void 0, {}, depth + 1);
262
+ i += skip.length + 2;
263
+ } else if (char === quote && !escape) return part.substring(0, i);
264
+ escape = !escape && char === "\\";
265
+ } else if (closings[char]) {
266
+ if (!lastInertedSemi && insertedSemis[i + part.start]) {
267
+ lastInertedSemi = true;
268
+ if (hasSemiTest) break;
269
+ i--;
270
+ lastChar = ";";
271
+ continue;
272
+ }
273
+ if (isOneLiner && char === "{") isOneLiner = false;
274
+ if (char === firstOpening) {
275
+ done = true;
276
+ break;
277
+ } else {
278
+ const skip = restOfExp(constants, part.substring(i + 1), [], char, void 0, void 0, {}, depth + 1);
279
+ cache.set(skip.start - 1, skip.end);
280
+ i += skip.length + 1;
281
+ isStart = false;
282
+ if (closingsTests) {
283
+ const sub = part.substring(i);
284
+ let found;
285
+ if (found = testMultiple(sub.toString(), closingsTests)) {
286
+ details.regRes = found;
287
+ done = true;
288
+ }
289
+ }
290
+ }
291
+ } else if (!quote) {
292
+ let sub = part.substring(i).toString();
293
+ let foundWord;
294
+ let foundNumber;
295
+ if (closingsTests) {
296
+ let found;
297
+ if (found = testMultiple(sub, closingsTests)) {
298
+ details.regRes = found;
299
+ i++;
300
+ done = true;
301
+ break;
302
+ }
303
+ }
304
+ if (foundNumber = aNumber.exec(sub)) {
305
+ i += foundNumber[0].length - 1;
306
+ sub = part.substring(i).toString();
307
+ if (closingsTests) {
308
+ let found;
309
+ if (found = testMultiple(sub, closingsTests)) {
310
+ details.regRes = found;
311
+ i++;
312
+ done = true;
313
+ break;
314
+ }
315
+ }
316
+ } else if (lastChar != char) {
317
+ let found = null;
318
+ if (char === ";" || insertedSemis[i + part.start] && !isStart && !lastInertedSemi) {
319
+ if (hasSemiTest) found = [";"];
320
+ else if (insertedSemis[i + part.start]) {
321
+ lastInertedSemi = true;
322
+ i--;
323
+ lastChar = ";";
324
+ continue;
325
+ }
326
+ char = sub = ";";
327
+ } else lastInertedSemi = false;
328
+ if (!found) found = testMultiple(sub, tests);
329
+ if (found) done = true;
330
+ if (!done && (foundWord = wordReg.exec(sub))) {
331
+ isOneLiner = true;
332
+ if (foundWord[2]) {
333
+ seenKeyword = true;
334
+ skipNextWord = true;
335
+ } else if (seenKeyword) if (skipNextWord) skipNextWord = false;
336
+ else details.bodyContentAfterKeyword = true;
337
+ if (foundWord[0].length > 1) {
338
+ details.words.push(foundWord[1]);
339
+ details.lastAnyWord = foundWord[1];
340
+ if (foundWord[2]) details.lastWord = foundWord[2];
341
+ }
342
+ if (foundWord[0].length > 2) i += foundWord[0].length - 2;
343
+ }
344
+ }
345
+ if (isStart) if (okFirstChars.test(sub)) done = false;
346
+ else isStart = false;
347
+ if (done) break;
348
+ } else if (char === closings[quote]) return part.substring(0, i);
349
+ lastChar = char;
350
+ }
351
+ if (quote) throw new SyntaxError("Unclosed '" + quote + "'");
352
+ if (details) details.oneliner = isOneLiner;
353
+ return part.substring(0, i);
354
+ }
355
+ restOfExp.next = [
356
+ "splitter",
357
+ "expEnd",
358
+ "inlineIf"
359
+ ];
360
+ var startingExecpted = [
361
+ "initialize",
362
+ "expSingle",
363
+ "expFunction",
364
+ "value",
365
+ "modifier",
366
+ "prop",
367
+ "incrementerBefore",
368
+ "expEnd"
369
+ ];
370
+ var setLispType = (types, fn) => {
371
+ types.forEach((type) => {
372
+ lispTypes.set(type, fn);
373
+ });
374
+ };
375
+ registerLispTypes({
376
+ NullLisp,
377
+ ParseError,
378
+ createLisp,
379
+ emptyString,
380
+ expectTypes,
381
+ expandDestructure,
382
+ expandFunctionParamDestructure,
383
+ extractStatementLabels,
384
+ findPatternEndIdx,
385
+ getDestructurePatternSource,
386
+ insertSemicolons,
387
+ lispify,
388
+ lispifyBlock,
389
+ lispifyExpr,
390
+ lispifyFunction,
391
+ lispifyReturnExpr,
392
+ restOfExp,
393
+ semiColon,
394
+ setLispType,
395
+ splitByCommasDestructure,
396
+ startingExecpted,
397
+ wrapLabeledStatement
398
+ });
399
+ function splitByCommasDestructure(s) {
400
+ const parts = [];
401
+ let depth = 0;
402
+ let cur = "";
403
+ for (let i = 0; i < s.length; i++) {
404
+ const c = s[i];
405
+ if (c === "[" || c === "{" || c === "(") depth++;
406
+ else if (c === "]" || c === "}" || c === ")") depth--;
407
+ if (c === "," && depth === 0) {
408
+ parts.push(cur);
409
+ cur = "";
410
+ } else cur += c;
411
+ }
412
+ parts.push(cur);
413
+ return parts;
414
+ }
415
+ function findFirstAtTopLevel(s, ch) {
416
+ let depth = 0;
417
+ for (let i = 0; i < s.length; i++) {
418
+ const c = s[i];
419
+ if (c === "[" || c === "{" || c === "(") depth++;
420
+ else if (c === "]" || c === "}" || c === ")") depth--;
421
+ if (c === ch && depth === 0) return i;
422
+ }
423
+ return -1;
424
+ }
425
+ function findPatternEndIdx(s) {
426
+ let depth = 0;
427
+ for (let i = 0; i < s.length; i++) {
428
+ const c = s[i];
429
+ if (c === "[" || c === "{") depth++;
430
+ else if (c === "]" || c === "}") {
431
+ depth--;
432
+ if (depth === 0) return i + 1;
433
+ }
434
+ }
435
+ return s.length;
436
+ }
437
+ var validIdentifier = /^[a-zA-Z$_][a-zA-Z\d$_]*$/;
438
+ function assertIdentifier(name) {
439
+ if (!validIdentifier.test(name)) throw new SyntaxError(`Invalid destructuring target: '${name}'`);
440
+ return name;
441
+ }
442
+ function expandDestructure(keyword, patternStr, rhsStr) {
443
+ const stmts = [];
444
+ function genTemp() {
445
+ return `$$_d${Math.random().toString(36).slice(2)}`;
446
+ }
447
+ function processPattern(pattern, src) {
448
+ pattern = pattern.trim();
449
+ if (pattern.startsWith("[")) processArrayPattern(pattern.slice(1, -1), src);
450
+ else if (pattern.startsWith("{")) processObjectPattern(pattern.slice(1, -1), src);
451
+ }
452
+ function processArrayPattern(content, src) {
453
+ const elements = splitByCommasDestructure(content);
454
+ for (let i = 0; i < elements.length; i++) {
455
+ const elem = elements[i].trim();
456
+ if (!elem) continue;
457
+ if (elem.startsWith("...")) {
458
+ const rest = elem.slice(3).trim();
459
+ if (rest.startsWith("[") || rest.startsWith("{")) {
460
+ const t = genTemp();
461
+ stmts.push(`internal ${t} = ${src}.slice(${i})`);
462
+ processPattern(rest, t);
463
+ } else stmts.push(`${keyword} ${assertIdentifier(rest)} = ${src}.slice(${i})`);
464
+ break;
465
+ }
466
+ const eqIdx = findFirstAtTopLevel(elem, "=");
467
+ const target = eqIdx !== -1 ? elem.slice(0, eqIdx).trim() : elem.trim();
468
+ const defaultVal = eqIdx !== -1 ? elem.slice(eqIdx + 1).trim() : void 0;
469
+ if (target.startsWith("[") || target.startsWith("{")) {
470
+ const t = genTemp();
471
+ stmts.push(defaultVal !== void 0 ? `internal ${t} = ${src}[${i}] !== undefined ? ${src}[${i}] : (${defaultVal})` : `internal ${t} = ${src}[${i}]`);
472
+ processPattern(target, t);
473
+ } else stmts.push(defaultVal !== void 0 ? `${keyword} ${assertIdentifier(target)} = ${src}[${i}] !== undefined ? ${src}[${i}] : (${defaultVal})` : `${keyword} ${assertIdentifier(target)} = ${src}[${i}]`);
474
+ }
475
+ }
476
+ function processObjectPattern(content, src) {
477
+ const props = splitByCommasDestructure(content);
478
+ const usedKeys = [];
479
+ for (const prop of props) {
480
+ const p = prop.trim();
481
+ if (!p) continue;
482
+ if (p.startsWith("...")) {
483
+ const restIdx = props.indexOf(prop);
484
+ if (props.slice(restIdx + 1).some((pp) => pp.trim().length > 0)) throw new SyntaxError("Rest element must be last element");
485
+ const rest = p.slice(3).trim();
486
+ const exclTemp = genTemp();
487
+ const keyTemp = genTemp();
488
+ const resTemp = genTemp();
489
+ const exclEntries = usedKeys.map((k) => `${assertIdentifier(k)}:1`).join(",");
490
+ stmts.push(`internal ${exclTemp} = {${exclEntries}}`);
491
+ stmts.push(`internal ${resTemp} = {}`);
492
+ stmts.push(`for (internal ${keyTemp} in ${src}) { if (!(${keyTemp} in ${exclTemp})) { ${resTemp}[${keyTemp}] = ${src}[${keyTemp}] } }`);
493
+ if (rest.startsWith("[") || rest.startsWith("{")) processPattern(rest, resTemp);
494
+ else stmts.push(`${keyword} ${assertIdentifier(rest)} = ${resTemp}`);
495
+ break;
496
+ }
497
+ if (p.startsWith("[")) {
498
+ let closeBracket = -1;
499
+ let depth = 1;
500
+ for (let ci = 1; ci < p.length; ci++) if (p[ci] === "[") depth++;
501
+ else if (p[ci] === "]") {
502
+ depth--;
503
+ if (depth === 0) {
504
+ closeBracket = ci;
505
+ break;
506
+ }
507
+ }
508
+ if (closeBracket !== -1) {
509
+ const computedExpr = p.slice(1, closeBracket);
510
+ const after = p.slice(closeBracket + 1).trim();
511
+ if (after.startsWith(":")) {
512
+ const valueStr = after.slice(1).trim();
513
+ const accessor = `${src}[${computedExpr}]`;
514
+ const eqIdx = findFirstAtTopLevel(valueStr, "=");
515
+ const tgt = eqIdx !== -1 && !valueStr.slice(0, eqIdx).trim().match(/^[[{]/) ? valueStr.slice(0, eqIdx).trim() : valueStr.trim();
516
+ const defVal = eqIdx !== -1 && !valueStr.slice(0, eqIdx).trim().match(/^[[{]/) ? valueStr.slice(eqIdx + 1).trim() : void 0;
517
+ if (tgt.startsWith("[") || tgt.startsWith("{")) {
518
+ const t = genTemp();
519
+ stmts.push(defVal !== void 0 ? `internal ${t} = ${accessor} !== undefined ? ${accessor} : (${defVal})` : `internal ${t} = ${accessor}`);
520
+ processPattern(tgt, t);
521
+ } else stmts.push(defVal !== void 0 ? `${keyword} ${assertIdentifier(tgt)} = ${accessor} !== undefined ? ${accessor} : (${defVal})` : `${keyword} ${assertIdentifier(tgt)} = ${accessor}`);
522
+ }
523
+ }
524
+ continue;
525
+ }
526
+ const colonIdx = findFirstAtTopLevel(p, ":");
527
+ if (colonIdx !== -1) {
528
+ const key = assertIdentifier(p.slice(0, colonIdx).trim());
529
+ const valueStr = p.slice(colonIdx + 1).trim();
530
+ usedKeys.push(key);
531
+ const accessor = `${src}.${key}`;
532
+ const eqIdx = findFirstAtTopLevel(valueStr, "=");
533
+ const beforeEq = eqIdx !== -1 ? valueStr.slice(0, eqIdx).trim() : valueStr.trim();
534
+ const isNestedPattern = beforeEq.startsWith("[") || beforeEq.startsWith("{");
535
+ const tgt = isNestedPattern ? valueStr.trim() : beforeEq;
536
+ const defVal = !isNestedPattern && eqIdx !== -1 ? valueStr.slice(eqIdx + 1).trim() : void 0;
537
+ if (tgt.startsWith("[") || tgt.startsWith("{")) {
538
+ const patEnd = findPatternEndIdx(tgt);
539
+ const finalPattern = tgt.slice(0, patEnd);
540
+ const afterPat = tgt.slice(patEnd).trim();
541
+ const nestedDef = afterPat.startsWith("=") ? afterPat.slice(1).trim() : void 0;
542
+ const t = genTemp();
543
+ stmts.push(nestedDef !== void 0 ? `internal ${t} = ${accessor} !== undefined ? ${accessor} : (${nestedDef})` : `internal ${t} = ${accessor}`);
544
+ processPattern(finalPattern, t);
545
+ } else stmts.push(defVal !== void 0 ? `${keyword} ${assertIdentifier(tgt)} = ${accessor} !== undefined ? ${accessor} : (${defVal})` : `${keyword} ${assertIdentifier(tgt)} = ${accessor}`);
546
+ continue;
547
+ }
548
+ const eqIdx = findFirstAtTopLevel(p, "=");
549
+ if (eqIdx !== -1) {
550
+ const name = assertIdentifier(p.slice(0, eqIdx).trim());
551
+ const defaultVal = p.slice(eqIdx + 1).trim();
552
+ usedKeys.push(name);
553
+ stmts.push(`${keyword} ${name} = ${src}.${name} !== undefined ? ${src}.${name} : (${defaultVal})`);
554
+ } else {
555
+ assertIdentifier(p);
556
+ usedKeys.push(p);
557
+ stmts.push(`${keyword} ${p} = ${src}.${p}`);
558
+ }
559
+ }
560
+ }
561
+ const rootTemp = genTemp();
562
+ stmts.unshift(`var ${rootTemp} = (${rhsStr})`);
563
+ processPattern(patternStr, rootTemp);
564
+ return stmts.join("; ");
565
+ }
566
+ function getDestructurePatternSource(tree) {
567
+ if (!isLisp(tree)) return null;
568
+ const source = tree.source?.trim();
569
+ if (source && (source.startsWith("[") || source.startsWith("{"))) return source;
570
+ if (tree[0] === LispType.Group) return getDestructurePatternSource(tree[2]);
571
+ return null;
572
+ }
573
+ function expandFunctionParamDestructure(args, funcBody) {
574
+ const injected = [];
575
+ const newArgs = args.map((arg, i) => {
576
+ const a = arg.trim();
577
+ if (a.startsWith("[") || a.startsWith("{")) {
578
+ const tempName = `$$_p${i}`;
579
+ const patEnd = findPatternEndIdx(a);
580
+ const patternOnly = a.slice(0, patEnd);
581
+ const afterPat = a.slice(patEnd).trim();
582
+ if (afterPat.startsWith("=")) {
583
+ const defaultVal = afterPat.slice(1).trim();
584
+ injected.push(expandDestructure("const", patternOnly, `${tempName} !== undefined ? ${tempName} : (${defaultVal})`));
585
+ } else injected.push(expandDestructure("const", patternOnly, tempName));
586
+ return tempName;
587
+ }
588
+ const eqIdx = findFirstAtTopLevel(a, "=");
589
+ if (eqIdx !== -1 && !a.startsWith("...")) {
590
+ const paramName = a.slice(0, eqIdx).trim();
591
+ const defaultVal = a.slice(eqIdx + 1).trim();
592
+ injected.push(`if (${paramName} === undefined) ${paramName} = (${defaultVal})`);
593
+ return paramName;
594
+ }
595
+ return a;
596
+ });
597
+ if (injected.length === 0) return {
598
+ args: newArgs,
599
+ body: funcBody
600
+ };
601
+ return {
602
+ args: newArgs,
603
+ body: injected.join("; ") + "; " + funcBody
604
+ };
605
+ }
606
+ function lispify(constants, part, expected, lispTree, topLevel = false, depthCtx = {
607
+ generatorDepth: 0,
608
+ asyncDepth: 0,
609
+ lispDepth: 0
610
+ }) {
611
+ if (depthCtx.lispDepth > constants.maxDepth) throw new SandboxCapabilityError("Maximum expression depth exceeded");
612
+ const { generatorDepth, asyncDepth, lispDepth } = depthCtx;
613
+ lispTree = lispTree || NullLisp;
614
+ expected = expected || expectTypes.initialize.next;
615
+ if (part === void 0) return lispTree;
616
+ part = part.trimStart();
617
+ const str = part.toString();
618
+ if (!part.length && !expected.includes("expEnd")) throw new SyntaxError("Unexpected end of expression");
619
+ if (!part.length) return lispTree;
620
+ const ctx = {
621
+ constants,
622
+ type: "",
623
+ part,
624
+ res: [],
625
+ expect: "",
626
+ lispTree,
627
+ generatorDepth,
628
+ asyncDepth,
629
+ lispDepth
630
+ };
631
+ let res;
632
+ for (const expect of expected) {
633
+ if (expect === "expEnd") continue;
634
+ for (const type in expectTypes[expect].types) {
635
+ if (type === "expEnd") continue;
636
+ if (res = expectTypes[expect].types[type].exec(str)) {
637
+ lastType = type;
638
+ ctx.type = type;
639
+ ctx.part = part;
640
+ ctx.res = res;
641
+ ctx.expect = expect;
642
+ try {
643
+ lispTypes.get(type)?.(ctx);
644
+ } catch (e) {
645
+ if (topLevel && e instanceof SyntaxError) throw new ParseError(e.message, str);
646
+ throw e;
647
+ }
648
+ break;
649
+ }
650
+ }
651
+ if (res) break;
652
+ }
653
+ if (!res && part.length) {
654
+ if (topLevel) throw new ParseError(`Unexpected token after ${lastType}: ${part.char(0)}`, str);
655
+ throw new SyntaxError(`Unexpected token after ${lastType}: ${part.char(0)}`);
656
+ }
657
+ return ctx.lispTree;
658
+ }
659
+ var startingExpectedWithoutSingle = startingExecpted.filter((r) => r !== "expSingle");
660
+ function lispifyExpr(constants, str, expected, depthCtx = {
661
+ generatorDepth: 0,
662
+ asyncDepth: 0,
663
+ lispDepth: 0
664
+ }) {
665
+ if (depthCtx.lispDepth > constants.maxDepth) throw new SandboxCapabilityError("Maximum expression depth exceeded");
666
+ if (!str.trimStart().length) return NullLisp;
667
+ const subExpressions = [];
668
+ let sub;
669
+ let pos = 0;
670
+ expected = expected || expectTypes.initialize.next;
671
+ if (expected.includes("expSingle")) {
672
+ if (testMultiple(str.toString(), Object.values(expectTypes.expSingle.types))) return lispify(constants, str, ["expSingle"], void 0, true, depthCtx);
673
+ }
674
+ if (expected === startingExecpted) expected = startingExpectedWithoutSingle;
675
+ while ((sub = restOfExp(constants, str.substring(pos), [/^,/])).length) {
676
+ subExpressions.push(sub.trimStart());
677
+ pos += sub.length + 1;
678
+ }
679
+ if (subExpressions.length === 1) return lispify(constants, str, expected, void 0, true, depthCtx);
680
+ if (expected.includes("initialize")) {
681
+ const defined = expectTypes.initialize.types.initialize.exec(subExpressions[0].toString());
682
+ if (defined) return createLisp({
683
+ op: LispType.InternalBlock,
684
+ a: subExpressions.map((str, i) => lispify(constants, i ? new CodeString(defined[1] + " " + str) : str, ["initialize"], void 0, true, depthCtx)),
685
+ b: LispType.None
686
+ });
687
+ else if (expectTypes.initialize.types.return.exec(subExpressions[0].toString())) return lispify(constants, str, expected, void 0, true, depthCtx);
688
+ }
689
+ const exprs = subExpressions.map((str) => lispify(constants, str, expected, void 0, true, depthCtx));
690
+ return createLisp({
691
+ op: LispType.Expression,
692
+ a: exprs,
693
+ b: LispType.None
694
+ });
695
+ }
696
+ function lispifyReturnExpr(constants, str) {
697
+ return createLisp({
698
+ op: LispType.Return,
699
+ a: LispType.None,
700
+ b: lispifyExpr(constants, str)
701
+ });
702
+ }
703
+ function lispifyBlock(str, constants, expression = false, depthCtx = {
704
+ generatorDepth: 0,
705
+ asyncDepth: 0,
706
+ lispDepth: 0
707
+ }) {
708
+ str = insertSemicolons(constants, str);
709
+ if (!str.trim().length) return [];
710
+ const parts = [];
711
+ let part;
712
+ let pos = 0;
713
+ let start = 0;
714
+ let details = {};
715
+ let skipped = false;
716
+ let isInserted = false;
717
+ while ((part = restOfExp(constants, str.substring(pos), [semiColon], void 0, void 0, void 0, details)).length) {
718
+ isInserted = !!(str.char(pos + part.length) && str.char(pos + part.length) !== ";");
719
+ pos += part.length + (isInserted ? 0 : 1);
720
+ if (/^\s*else(?![\w$])/.test(str.substring(pos).toString())) skipped = true;
721
+ else if (details["words"]?.includes("do") && /^\s*while(?![\w$])/.test(str.substring(pos).toString())) skipped = true;
722
+ else {
723
+ skipped = false;
724
+ parts.push(str.substring(start, pos - (isInserted ? 0 : 1)));
725
+ start = pos;
726
+ }
727
+ details = {};
728
+ if (expression) break;
729
+ }
730
+ if (skipped) parts.push(str.substring(start, pos - (isInserted ? 0 : 1)));
731
+ return parts.map((str) => str.trimStart()).filter((str) => str.length).map((str) => {
732
+ return lispifyExpr(constants, str.trimStart(), startingExecpted, depthCtx);
733
+ });
734
+ }
735
+ function lispifyFunction(str, constants, expression = false, depthCtx = {
736
+ generatorDepth: 0,
737
+ asyncDepth: 0,
738
+ lispDepth: 0
739
+ }) {
740
+ if (!str.trim().length) return [];
741
+ const tree = lispifyBlock(str, constants, expression, depthCtx);
742
+ hoist(tree);
743
+ return tree;
744
+ }
745
+ function hoist(item, res = []) {
746
+ if (isLisp(item)) {
747
+ if (!isLisp(item)) return false;
748
+ const [op, a, b] = item;
749
+ if (op === LispType.Labeled || op === LispType.Try || op === LispType.If || op === LispType.Loop || op === LispType.Switch) {
750
+ hoist(a, res);
751
+ hoist(b, res);
752
+ } else if (op === LispType.Var) res.push(createLisp({
753
+ op: LispType.Var,
754
+ a,
755
+ b: LispType.None
756
+ }));
757
+ else if (op === LispType.Function && a[2]) {
758
+ res.push(item);
759
+ return true;
760
+ }
761
+ } else if (Array.isArray(item)) {
762
+ const rep = [];
763
+ for (const it of item) if (!hoist(it, res)) rep.push(it);
764
+ if (rep.length !== item.length) {
765
+ item.length = 0;
766
+ item.push(...res, ...rep);
767
+ }
768
+ }
769
+ return false;
770
+ }
771
+ var closingsNoInsertion = /^(\})\s*(catch|finally|else|while|instanceof)(?![\w$])/;
772
+ var colonsRegex = /^((([\w$\])"'`]|\+\+|--)\s*\r?\n\s*([\w$+\-!~]))|(\}\s*[\w$!~+\-{("'`]))/;
773
+ function insertSemicolons(constants, str) {
774
+ let rest = str;
775
+ let sub = emptyString;
776
+ let details = {};
777
+ let pendingDoWhile = false;
778
+ const inserted = insertedSemicolons.get(str.ref) || new Array(str.ref.str.length);
779
+ while ((sub = restOfExp(constants, rest, [], void 0, void 0, [colonsRegex], details)).length) {
780
+ let valid = false;
781
+ let part = sub;
782
+ let edge = sub.length;
783
+ if (details.regRes) {
784
+ valid = true;
785
+ const [, , a, , , b] = details.regRes;
786
+ edge = details.regRes[3] === "++" || details.regRes[3] === "--" ? sub.length + 1 : sub.length;
787
+ part = rest.substring(0, edge);
788
+ if (b) {
789
+ const res = closingsNoInsertion.exec(rest.substring(sub.length - 1).toString());
790
+ if (res) if (res[2] === "while") if (details.lastWord === "do") {
791
+ valid = false;
792
+ pendingDoWhile = true;
793
+ } else valid = true;
794
+ else valid = false;
795
+ else if (details.lastWord === "function" && details.regRes[5][0] === "}" && details.regRes[5].slice(-1) === "(") valid = false;
796
+ } else if (a) {
797
+ if (pendingDoWhile && details.lastWord === "while") {
798
+ valid = true;
799
+ pendingDoWhile = false;
800
+ } else if (details.lastWord === "if" || details.lastWord === "while" || details.lastWord === "for" || details.lastWord === "else") valid = !!details.bodyContentAfterKeyword;
801
+ }
802
+ }
803
+ if (valid) inserted[part.end] = true;
804
+ rest = rest.substring(edge);
805
+ details = {};
806
+ }
807
+ insertedSemicolons.set(str.ref, inserted);
808
+ return str;
809
+ }
810
+ function checkRegex(str) {
811
+ let i = 1;
812
+ let escape = false;
813
+ let done = false;
814
+ let cancel = false;
815
+ while (i < str.length && !done && !cancel) {
816
+ done = str[i] === "/" && !escape;
817
+ escape = str[i] === "\\" && !escape;
818
+ cancel = str[i] === "\n";
819
+ i++;
820
+ }
821
+ const after = str.substring(i);
822
+ cancel = cancel || !done || /^\s*\d/.test(after);
823
+ if (cancel) return null;
824
+ const flags = /^[a-z]*/.exec(after);
825
+ if (/^\s+[\w$]/.test(str.substring(i + flags[0].length))) return null;
826
+ const regexPattern = str.substring(1, i - 1);
827
+ const regexFlags = flags && flags[0] || "";
828
+ try {
829
+ new RegExp(regexPattern, regexFlags);
830
+ } catch (e) {
831
+ if (e instanceof SyntaxError) throw e;
832
+ }
833
+ return {
834
+ regex: regexPattern,
835
+ flags: regexFlags,
836
+ length: i + (flags && flags[0].length || 0)
837
+ };
838
+ }
839
+ var notDivide = /(typeof|delete|instanceof|return|in|of|throw|new|void|do|if)$/;
840
+ var possibleDivide = /^([\w$\])]|\+\+|--)[\s/]/;
841
+ function extractConstants(constants, str, currentEnclosure = "", depth = 0) {
842
+ if (depth > constants.maxDepth) throw new SandboxCapabilityError("Maximum expression depth exceeded");
843
+ let quote;
844
+ let extract = [];
845
+ let escape = false;
846
+ let regexFound;
847
+ let comment = "";
848
+ let commentStart = -1;
849
+ let currJs = [];
850
+ let char = "";
851
+ const strRes = [];
852
+ const enclosures = [];
853
+ let isPossibleDivide = null;
854
+ let i = 0;
855
+ for (i = 0; i < str.length; i++) {
856
+ char = str[i];
857
+ if (comment) {
858
+ if (char === comment) {
859
+ if (comment === "*" && str[i + 1] === "/") {
860
+ comment = "";
861
+ i++;
862
+ } else if (comment === "\n") {
863
+ comment = "";
864
+ strRes.push("\n");
865
+ }
866
+ }
867
+ } else {
868
+ if (escape) {
869
+ escape = false;
870
+ extract.push(char);
871
+ continue;
872
+ }
873
+ if (quote) if (quote === "`" && char === "$" && str[i + 1] === "{") {
874
+ const skip = extractConstants(constants, str.substring(i + 2), "{", depth + 1);
875
+ if (!skip.str.trim().length) throw new SyntaxError("Unexpected end of expression");
876
+ currJs.push(skip.str);
877
+ extract.push("${", currJs.length - 1, `}`);
878
+ i += skip.length + 2;
879
+ } else if (quote === char) {
880
+ if (quote === "`") {
881
+ const li = createLisp({
882
+ op: LispType.Literal,
883
+ a: unraw(extract.join("")),
884
+ b: []
885
+ });
886
+ li.tempJsStrings = currJs;
887
+ constants.literals.push(li);
888
+ strRes.push(`\``, constants.literals.length - 1, `\``);
889
+ } else {
890
+ constants.strings.push(unraw(extract.join("")));
891
+ strRes.push(`"`, constants.strings.length - 1, `"`);
892
+ }
893
+ quote = null;
894
+ extract = [];
895
+ } else extract.push(char);
896
+ else {
897
+ if (char === "'" || char === "\"" || char === "`") {
898
+ currJs = [];
899
+ quote = char;
900
+ } else if (closings[currentEnclosure] === char && !enclosures.length) return {
901
+ str: strRes.join(""),
902
+ length: i
903
+ };
904
+ else if (closings[char]) {
905
+ enclosures.push(char);
906
+ strRes.push(char);
907
+ } else if (closings[enclosures[enclosures.length - 1]] === char) {
908
+ enclosures.pop();
909
+ strRes.push(char);
910
+ } else if (char === "/" && (str[i + 1] === "*" || str[i + 1] === "/")) {
911
+ comment = str[i + 1] === "*" ? "*" : "\n";
912
+ commentStart = i;
913
+ } else if (char === "/" && !isPossibleDivide && (regexFound = checkRegex(str.substring(i)))) {
914
+ constants.regexes.push(regexFound);
915
+ strRes.push(`/`, constants.regexes.length - 1, `/r`);
916
+ i += regexFound.length - 1;
917
+ } else strRes.push(char);
918
+ if (!isPossibleDivide || !space.test(char)) {
919
+ if (isPossibleDivide = possibleDivide.exec(str.substring(i))) {
920
+ if (notDivide.test(str.substring(0, i + isPossibleDivide[1].length))) isPossibleDivide = null;
921
+ }
922
+ }
923
+ }
924
+ escape = !!(quote && char === "\\");
925
+ }
926
+ }
927
+ if (quote) throw new SyntaxError(`Unclosed '${quote}'`);
928
+ if (comment) {
929
+ if (comment === "*") throw new SyntaxError(`Unclosed comment '/*': ${str.substring(commentStart)}`);
930
+ }
931
+ return {
932
+ str: strRes.join(""),
933
+ length: i
934
+ };
935
+ }
936
+ function parse(code, eager = false, expression = false, maxParserRecursionDepth = 256) {
937
+ if (typeof code !== "string") throw new ParseError(`Cannot parse ${code}`, String(code));
938
+ let str = " " + code;
939
+ const constants = {
940
+ strings: [],
941
+ literals: [],
942
+ regexes: [],
943
+ eager,
944
+ maxDepth: maxParserRecursionDepth
945
+ };
946
+ str = extractConstants(constants, str).str;
947
+ for (const l of constants.literals) {
948
+ l[2] = l.tempJsStrings.map((js) => lispifyExpr(constants, new CodeString(js)));
949
+ delete l.tempJsStrings;
950
+ }
951
+ return {
952
+ tree: lispifyFunction(new CodeString(str), constants, expression),
953
+ constants
954
+ };
955
+ }
956
+ //#endregion
957
+ export { ParseError, checkRegex, parse as default, expectTypes, extractConstants, insertSemicolons, lispifyBlock, lispifyFunction, lispifyReturnExpr, restOfExp, setLispType, testMultiple };
958
+
959
+ //# sourceMappingURL=parserUtils.js.map