@danielx/civet 0.6.2 → 0.6.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 (4) hide show
  1. package/dist/browser.js +2172 -2128
  2. package/dist/main.js +2172 -2128
  3. package/dist/main.mjs +2172 -2128
  4. package/package.json +1 -1
package/dist/main.mjs CHANGED
@@ -28,6 +28,119 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
28
28
  var require_lib = __commonJS({
29
29
  "source/lib.js"(exports, module) {
30
30
  "use strict";
31
+ function addParentPointers(node, parent) {
32
+ if (node == null)
33
+ return;
34
+ if (typeof node !== "object")
35
+ return;
36
+ if (Array.isArray(node)) {
37
+ for (const child of node) {
38
+ addParentPointers(child, parent);
39
+ }
40
+ return;
41
+ }
42
+ node.parent = parent;
43
+ if (node.children) {
44
+ for (const child of node.children) {
45
+ addParentPointers(child, node);
46
+ }
47
+ }
48
+ }
49
+ function addPostfixStatement(statement, ws, post) {
50
+ let children, expressions;
51
+ if (post.blockPrefix?.length) {
52
+ let indent = post.blockPrefix[0][0];
53
+ expressions = [...post.blockPrefix, [indent, statement]];
54
+ children = [" {\n", ...expressions, "\n", indent?.slice?.(0, -2), "}"];
55
+ } else {
56
+ expressions = [["", statement]];
57
+ children = [" { ", ...expressions, " }"];
58
+ }
59
+ const block = {
60
+ type: "BlockStatement",
61
+ children,
62
+ expressions
63
+ };
64
+ children = [...post.children];
65
+ children.push(block);
66
+ if (!isWhitespaceOrEmpty(ws))
67
+ children.push(ws);
68
+ post = { ...post, children, block };
69
+ if (post.type === "IfStatement") {
70
+ post.then = block;
71
+ }
72
+ return post;
73
+ }
74
+ function adjustAtBindings(statements, asThis = false) {
75
+ gatherRecursiveAll(statements, (n) => n.type === "AtBindingProperty").forEach((binding) => {
76
+ const { ref } = binding;
77
+ if (asThis) {
78
+ const atBinding = binding.binding;
79
+ atBinding.children.pop();
80
+ atBinding.type = void 0;
81
+ binding.children.unshift(ref.id, ": this.", ref.base);
82
+ binding.type = "Property";
83
+ binding.ref = void 0;
84
+ return;
85
+ }
86
+ if (ref.names[0] !== ref.base) {
87
+ binding.children.unshift(ref.base, ": ");
88
+ }
89
+ });
90
+ }
91
+ function adjustBindingElements(elements) {
92
+ const names = elements.flatMap((p) => p.names || []), { length } = elements;
93
+ let blockPrefix, restIndex = -1, restCount = 0;
94
+ elements.forEach(({ type }, i) => {
95
+ if (type === "BindingRestElement") {
96
+ if (restIndex < 0)
97
+ restIndex = i;
98
+ restCount++;
99
+ }
100
+ });
101
+ if (restCount === 0) {
102
+ return {
103
+ children: elements,
104
+ names,
105
+ blockPrefix,
106
+ length
107
+ };
108
+ } else if (restCount === 1) {
109
+ const rest = elements[restIndex];
110
+ const after = elements.slice(restIndex + 1);
111
+ const restIdentifier = rest.binding.ref || rest.binding;
112
+ names.push(...rest.names || []);
113
+ let l = after.length;
114
+ if (l) {
115
+ if (arrayElementHasTrailingComma(after[l - 1]))
116
+ l++;
117
+ blockPrefix = {
118
+ type: "PostRestBindingElements",
119
+ children: ["[", insertTrimmingSpace(after, ""), "] = ", restIdentifier, ".splice(-", l.toString(), ")"],
120
+ names: after.flatMap((p) => p.names)
121
+ };
122
+ }
123
+ return {
124
+ names,
125
+ children: [...elements.slice(0, restIndex), {
126
+ ...rest,
127
+ children: rest.children.slice(0, -1)
128
+ }],
129
+ blockPrefix,
130
+ length
131
+ };
132
+ }
133
+ const err = {
134
+ type: "Error",
135
+ children: ["Multiple rest elements in array pattern"]
136
+ };
137
+ return {
138
+ names,
139
+ children: [...elements, err],
140
+ blockPrefix,
141
+ length
142
+ };
143
+ }
31
144
  function aliasBinding(p, ref) {
32
145
  if (p.type === "Identifier") {
33
146
  p.children[0] = ref;
@@ -40,6 +153,24 @@ var require_lib = __commonJS({
40
153
  p.children.push(": ", ref);
41
154
  }
42
155
  }
156
+ function arrayElementHasTrailingComma(elementNode) {
157
+ const { children } = elementNode, { length } = children;
158
+ const lastChild = children[length - 1];
159
+ if (lastChild) {
160
+ const l2 = lastChild.length;
161
+ if (lastChild[l2 - 1]?.token === ",") {
162
+ return true;
163
+ }
164
+ }
165
+ return false;
166
+ }
167
+ var assert = {
168
+ equal(a, b, msg) {
169
+ if (a !== b) {
170
+ throw new Error(`Assertion failed [${msg}]: ${a} !== ${b}`);
171
+ }
172
+ }
173
+ };
43
174
  function blockWithPrefix(prefixStatements, block) {
44
175
  if (prefixStatements && prefixStatements.length) {
45
176
  const indent = getIndent(block.expressions[0]);
@@ -70,6 +201,126 @@ var require_lib = __commonJS({
70
201
  removeParentPointers(node);
71
202
  return deepCopy(node);
72
203
  }
204
+ function constructInvocation(fn, arg) {
205
+ const fnArr = [fn.leadingComment, fn.expr, fn.trailingComment];
206
+ let expr = fn.expr;
207
+ while (expr.type === "ParenthesizedExpression") {
208
+ expr = expr.expression;
209
+ }
210
+ if (expr.ampersandBlock) {
211
+ const { ref, body } = expr;
212
+ ref.type = "PipedExpression";
213
+ ref.children = [makeLeftHandSideExpression(arg)];
214
+ return {
215
+ type: "UnwrappedExpression",
216
+ children: [skipIfOnlyWS(fn.leadingComment), ...body, skipIfOnlyWS(fn.trailingComment)]
217
+ };
218
+ }
219
+ expr = fn.expr;
220
+ const lhs = makeLeftHandSideExpression(expr);
221
+ let comment = skipIfOnlyWS(fn.trailingComment);
222
+ if (comment)
223
+ lhs.children.splice(2, 0, comment);
224
+ comment = skipIfOnlyWS(fn.leadingComment);
225
+ if (comment)
226
+ lhs.children.splice(1, 0, comment);
227
+ switch (arg.type) {
228
+ case "CommaExpression":
229
+ arg = makeLeftHandSideExpression(arg);
230
+ break;
231
+ }
232
+ return {
233
+ type: "CallExpression",
234
+ children: [lhs, "(", arg, ")"]
235
+ };
236
+ }
237
+ function constructPipeStep(fn, arg, returning) {
238
+ const children = [[fn.leadingComment, fn.expr, fn.trailingComment].map(skipIfOnlyWS), " ", arg];
239
+ switch (fn.expr.token) {
240
+ case "yield":
241
+ case "await":
242
+ if (returning) {
243
+ return [
244
+ children,
245
+ returning
246
+ ];
247
+ }
248
+ return [
249
+ children,
250
+ null
251
+ ];
252
+ case "return":
253
+ return [{
254
+ type: "ReturnStatement",
255
+ children
256
+ }, null];
257
+ }
258
+ if (returning) {
259
+ return [
260
+ constructInvocation(fn, arg),
261
+ returning
262
+ ];
263
+ }
264
+ return [constructInvocation(fn, arg), null];
265
+ }
266
+ var initialSpacingRe = /^(?:\r?\n|\n)*((?:\r?\n|\n)\s+)/;
267
+ function dedentBlockString({ $loc, token: str }, spacing, trim = true) {
268
+ if (spacing == null)
269
+ spacing = str.match(initialSpacingRe);
270
+ if (spacing) {
271
+ str = str.replaceAll(spacing[1], "\n");
272
+ const l = spacing.length;
273
+ $loc.pos += l;
274
+ $loc.length -= l;
275
+ }
276
+ if (trim) {
277
+ str = str.replace(/^(\r?\n|\n)/, "").replace(/(\r?\n|\n)[ \t]*$/, "");
278
+ }
279
+ str = str.replace(/(\\.|`|\$\{)/g, (s) => {
280
+ if (s[0] === "\\") {
281
+ return s;
282
+ }
283
+ return `\\${s}`;
284
+ });
285
+ return {
286
+ $loc,
287
+ token: str
288
+ };
289
+ }
290
+ function dedentBlockSubstitutions($0) {
291
+ const [s, strWithSubstitutions, e] = $0;
292
+ if (strWithSubstitutions.length === 0) {
293
+ return $0;
294
+ }
295
+ let initialSpacing, i = 0, l = strWithSubstitutions.length, results = [s];
296
+ const { token } = strWithSubstitutions[0];
297
+ if (token) {
298
+ initialSpacing = token.match(initialSpacingRe);
299
+ } else {
300
+ initialSpacing = false;
301
+ }
302
+ while (i < l) {
303
+ let segment = strWithSubstitutions[i];
304
+ if (segment.token) {
305
+ segment = dedentBlockString(segment, initialSpacing, false);
306
+ if (i === 0) {
307
+ segment.token = segment.token.replace(/^(\r?\n|\n)/, "");
308
+ }
309
+ if (i === l - 1) {
310
+ segment.token = segment.token.replace(/(\r?\n|\n)[ \t]*$/, "");
311
+ }
312
+ results.push(segment);
313
+ } else {
314
+ results.push(segment);
315
+ }
316
+ i++;
317
+ }
318
+ results.push(e);
319
+ return {
320
+ type: "TemplateLiteral",
321
+ children: results
322
+ };
323
+ }
73
324
  function deepCopy(node) {
74
325
  if (node == null)
75
326
  return node;
@@ -84,6 +335,356 @@ var require_lib = __commonJS({
84
335
  })
85
336
  );
86
337
  }
338
+ function expressionizeIfClause(clause, b, e) {
339
+ const children = clause.children.slice(1);
340
+ children.push("?", b);
341
+ if (e) {
342
+ children.push(e[0], ":", ...e.slice(2));
343
+ } else {
344
+ children.push(":void 0");
345
+ }
346
+ return {
347
+ type: "IfExpression",
348
+ children
349
+ };
350
+ }
351
+ function expressionizeIteration(exp) {
352
+ const i = exp.children.indexOf(exp.block);
353
+ if (exp.subtype === "DoStatement") {
354
+ insertReturn(exp.block);
355
+ exp.children.splice(i, 1, ...wrapIIFE(exp.children, exp.async));
356
+ return;
357
+ }
358
+ const resultsRef = {
359
+ type: "Ref",
360
+ base: "results",
361
+ id: "results"
362
+ };
363
+ insertPush(exp.block, resultsRef);
364
+ exp.children.splice(
365
+ i,
366
+ 1,
367
+ wrapIIFE([
368
+ "const ",
369
+ resultsRef,
370
+ "=[];",
371
+ ...exp.children,
372
+ "; return ",
373
+ resultsRef
374
+ ], exp.async)
375
+ );
376
+ }
377
+ function processBinaryOpExpression($0) {
378
+ const expandedOps = expandChainedComparisons($0);
379
+ let i = 2;
380
+ while (i < expandedOps.length) {
381
+ const op = expandedOps[i];
382
+ if (op.special) {
383
+ let [a, wsOp, op2, wsB, b] = expandedOps.slice(i - 2, i + 3);
384
+ if (op2.token === "instanceof" && b.type === "Literal" && b.children?.[0]?.type === "StringLiteral") {
385
+ a = ["typeof ", makeLeftHandSideExpression(a)];
386
+ if (op2.negated) {
387
+ op2 = { ...op2, token: "!==", negated: false };
388
+ } else {
389
+ op2 = { ...op2, token: "===" };
390
+ }
391
+ }
392
+ if (op2.asConst) {
393
+ a = makeAsConst(a);
394
+ b = makeAsConst(b);
395
+ }
396
+ let children;
397
+ if (op2.call) {
398
+ wsOp = insertTrimmingSpace(wsOp, "");
399
+ if (op2.reversed) {
400
+ wsB = insertTrimmingSpace(wsB, "");
401
+ children = [wsOp, op2.call, "(", wsB, b, ", ", a, ")", op2.suffix];
402
+ } else {
403
+ children = [wsOp, op2.call, "(", a, ",", wsB, b, ")", op2.suffix];
404
+ }
405
+ } else if (op2.method) {
406
+ wsOp = insertTrimmingSpace(wsOp, "");
407
+ wsB = insertTrimmingSpace(wsB, "");
408
+ if (op2.reversed) {
409
+ children = [wsB, b, wsOp, ".", op2.method, "(", a, ")"];
410
+ } else {
411
+ children = [a, wsOp, ".", op2.method, "(", wsB, b, ")"];
412
+ }
413
+ } else if (op2.token) {
414
+ children = [a, wsOp, op2, wsB, b];
415
+ if (op2.negated)
416
+ children = ["(", ...children, ")"];
417
+ } else {
418
+ throw new Error("Unknown operator: " + JSON.stringify(op2));
419
+ }
420
+ if (op2.negated)
421
+ children.unshift("!");
422
+ expandedOps.splice(i - 2, 5, {
423
+ children
424
+ });
425
+ } else {
426
+ i += 4;
427
+ }
428
+ }
429
+ return expandedOps;
430
+ }
431
+ function processCallMemberExpression(node) {
432
+ const { children } = node;
433
+ for (let i = 0; i < children.length; i++) {
434
+ const glob = children[i];
435
+ if (glob?.type === "PropertyGlob") {
436
+ const prefix = children.slice(0, i).concat(glob.dot);
437
+ const parts = [];
438
+ for (const part of glob.object.properties) {
439
+ if (part.type === "MethodDefinition") {
440
+ throw new Error("Glob pattern cannot have method definition");
441
+ }
442
+ if (part.value && !["CallExpression", "MemberExpression", "Identifier"].includes(part.value.type)) {
443
+ throw new Error("Glob pattern must have call or member expression value");
444
+ }
445
+ let value = part.value ?? part.name;
446
+ const wValue = getTrimmingSpace(part.value);
447
+ value = prefix.concat(insertTrimmingSpace(value, ""));
448
+ if (wValue)
449
+ value.unshift(wValue);
450
+ if (part.type === "SpreadProperty") {
451
+ parts.push({
452
+ type: part.type,
453
+ value,
454
+ dots: part.dots,
455
+ delim: part.delim,
456
+ names: part.names,
457
+ children: part.children.slice(0, 2).concat(value, part.delim)
458
+ });
459
+ } else {
460
+ parts.push({
461
+ type: part.type === "Identifier" ? "Property" : part.type,
462
+ name: part.name,
463
+ value,
464
+ delim: part.delim,
465
+ names: part.names,
466
+ children: [
467
+ isWhitespaceOrEmpty(part.children[0]) && part.children[0],
468
+ part.name,
469
+ isWhitespaceOrEmpty(part.children[2]) && part.children[2],
470
+ part.children[3]?.token === ":" ? part.children[3] : ":",
471
+ value,
472
+ part.delim
473
+ ]
474
+ });
475
+ }
476
+ }
477
+ const object = {
478
+ type: "ObjectExpression",
479
+ children: [
480
+ glob.object.children[0],
481
+ ...parts,
482
+ glob.object.children.at(-1)
483
+ ],
484
+ properties: parts
485
+ };
486
+ if (i === children.length - 1)
487
+ return object;
488
+ return processCallMemberExpression({
489
+ ...node,
490
+ children: [object, ...children.slice(i + 1)]
491
+ });
492
+ } else if (glob?.type === "PropertyBind") {
493
+ const prefix = children.slice(0, i);
494
+ return processCallMemberExpression({
495
+ ...node,
496
+ children: [
497
+ prefix,
498
+ {
499
+ ...glob,
500
+ type: "PropertyAccess",
501
+ children: [...glob.children, ".bind(", prefix, ")"]
502
+ },
503
+ ...children.slice(i + 1)
504
+ ]
505
+ });
506
+ }
507
+ }
508
+ return node;
509
+ }
510
+ function wrapIterationReturningResults(statement, outerRef) {
511
+ if (statement.type === "DoStatement") {
512
+ if (outerRef) {
513
+ insertPush(statement.block, outerRef);
514
+ } else {
515
+ insertReturn(statement.block);
516
+ }
517
+ return;
518
+ }
519
+ const resultsRef = {
520
+ type: "Ref",
521
+ base: "results",
522
+ id: "results"
523
+ };
524
+ const declaration = {
525
+ type: "Declaration",
526
+ children: ["const ", resultsRef, "=[];"]
527
+ };
528
+ insertPush(statement.block, resultsRef);
529
+ statement.children.unshift(declaration);
530
+ if (outerRef) {
531
+ statement.children.push(";", outerRef, ".push(", resultsRef, ");");
532
+ } else {
533
+ statement.children.push(";return ", resultsRef, ";");
534
+ }
535
+ }
536
+ function insertPush(node, ref) {
537
+ if (!node)
538
+ return;
539
+ switch (node.type) {
540
+ case "BlockStatement":
541
+ if (node.expressions.length) {
542
+ const last = node.expressions[node.expressions.length - 1];
543
+ insertPush(last, ref);
544
+ } else {
545
+ node.expressions.push([ref, ".push(void 0);"]);
546
+ }
547
+ return;
548
+ case "CaseBlock":
549
+ node.clauses.forEach((clause) => {
550
+ insertPush(clause, ref);
551
+ });
552
+ return;
553
+ case "WhenClause":
554
+ insertPush(node.block, ref);
555
+ return;
556
+ case "DefaultClause":
557
+ insertPush(node.block, ref);
558
+ return;
559
+ }
560
+ if (!Array.isArray(node))
561
+ return;
562
+ const [, exp] = node;
563
+ if (!exp)
564
+ return;
565
+ const indent = getIndent(node);
566
+ switch (exp.type) {
567
+ case "BreakStatement":
568
+ case "ContinueStatement":
569
+ case "DebuggerStatement":
570
+ case "EmptyStatement":
571
+ case "ReturnStatement":
572
+ case "ThrowStatement":
573
+ case "Declaration":
574
+ return;
575
+ case "ForStatement":
576
+ case "IterationStatement":
577
+ case "DoStatement":
578
+ wrapIterationReturningResults(exp, ref);
579
+ return;
580
+ case "BlockStatement":
581
+ insertPush(exp.expressions[exp.expressions.length - 1], ref);
582
+ return;
583
+ case "IfStatement":
584
+ insertPush(exp.then, ref);
585
+ if (exp.else)
586
+ insertPush(exp.else[2], ref);
587
+ else
588
+ exp.children.push([" else {\n", indent, ref, ".push(undefined)\n", indent, "}"]);
589
+ return;
590
+ case "PatternMatchingStatement":
591
+ insertPush(exp.children[0][0], ref);
592
+ return;
593
+ case "SwitchStatement":
594
+ insertPush(exp.children[2], ref);
595
+ return;
596
+ case "TryStatement":
597
+ exp.blocks.forEach((block) => insertPush(block, ref));
598
+ return;
599
+ }
600
+ if (node[node.length - 1]?.type === "SemicolonDelimiter")
601
+ return;
602
+ node.splice(1, 0, ref, ".push(");
603
+ node.push(")");
604
+ }
605
+ function wrapWithReturn(expression) {
606
+ const children = expression ? ["return ", expression] : ["return"];
607
+ return {
608
+ type: "ReturnStatement",
609
+ children
610
+ };
611
+ }
612
+ function expandChainedComparisons([first, binops]) {
613
+ const relationalOps = ["==", "===", "!=", "!==", "<", "<=", ">", ">=", "in"];
614
+ const lowerPrecedenceOps = ["??", "&&", "||", "&", "|", "^"];
615
+ let results = [];
616
+ let i = 0;
617
+ let l = binops.length;
618
+ let start = 0;
619
+ let chains = [];
620
+ while (i < l) {
621
+ const [, op] = binops[i];
622
+ if (relationalOps.includes(op.token) || op.relational) {
623
+ chains.push(i);
624
+ } else if (lowerPrecedenceOps.includes(op.token)) {
625
+ processChains();
626
+ first = [];
627
+ }
628
+ i++;
629
+ }
630
+ processChains();
631
+ return results;
632
+ function processChains() {
633
+ if (chains.length > 1) {
634
+ chains.forEach((index, k) => {
635
+ if (k > 0) {
636
+ results.push(" ", "&&", " ");
637
+ }
638
+ const [pre, op, post, exp] = binops[index];
639
+ let endIndex;
640
+ if (k < chains.length - 1) {
641
+ endIndex = chains[k + 1];
642
+ } else {
643
+ endIndex = i + 1;
644
+ }
645
+ results = results.concat(first, ...binops.slice(start, endIndex));
646
+ first = [exp].concat(binops.slice(index + 1, endIndex));
647
+ start = endIndex;
648
+ });
649
+ } else {
650
+ results = results.concat(first, ...binops.slice(start, i + 1));
651
+ start = i + 1;
652
+ }
653
+ chains.length = 0;
654
+ }
655
+ }
656
+ function processParams(f) {
657
+ const { type, parameters, block } = f;
658
+ if (type === "ArrowFunction" && parameters && parameters.tp && parameters.tp.parameters.length === 1) {
659
+ parameters.tp.parameters.push(",");
660
+ }
661
+ if (!block)
662
+ return;
663
+ const { expressions } = block;
664
+ if (!expressions)
665
+ return;
666
+ const { blockPrefix } = parameters;
667
+ let indent;
668
+ if (!expressions.length) {
669
+ indent = "";
670
+ } else {
671
+ indent = expressions[0][0];
672
+ }
673
+ const [splices, thisAssignments] = gatherBindingCode(parameters, {
674
+ injectParamProps: f.name === "constructor"
675
+ });
676
+ const delimiter = {
677
+ type: "SemicolonDelimiter",
678
+ children: [";"]
679
+ };
680
+ const prefix = splices.map((s) => ["let ", s]).concat(thisAssignments).map(
681
+ (s) => s.type ? {
682
+ ...s,
683
+ children: [indent, ...s.children, delimiter]
684
+ } : [indent, s, delimiter]
685
+ );
686
+ expressions.unshift(...prefix);
687
+ }
87
688
  function removeParentPointers(node) {
88
689
  if (node == null)
89
690
  return;
@@ -182,7 +783,7 @@ var require_lib = __commonJS({
182
783
  function hoistRefDecs(statements) {
183
784
  gatherRecursiveAll(statements, (s) => s.hoistDec).forEach((node) => {
184
785
  const { hoistDec } = node;
185
- const outer = closest(node, ["IfStatement", "IterationStatement"]);
786
+ let outer = closest(node, ["IfStatement", "IterationStatement"]);
186
787
  if (!outer) {
187
788
  node.children.push({
188
789
  type: "Error",
@@ -190,7 +791,11 @@ var require_lib = __commonJS({
190
791
  });
191
792
  return;
192
793
  }
193
- const block = outer.parent;
794
+ let block = outer.parent;
795
+ if (block.type === "PatternMatchingStatement") {
796
+ outer = block;
797
+ block = block.parent;
798
+ }
194
799
  const { expressions } = block;
195
800
  const index = expressions.findIndex(([, s]) => outer === s);
196
801
  if (index < 0)
@@ -201,11 +806,124 @@ var require_lib = __commonJS({
201
806
  node.hoistDec = null;
202
807
  });
203
808
  }
809
+ function insertReturn(node) {
810
+ if (!node)
811
+ return;
812
+ switch (node.type) {
813
+ case "BlockStatement":
814
+ if (node.expressions.length) {
815
+ const last = node.expressions[node.expressions.length - 1];
816
+ insertReturn(last);
817
+ } else {
818
+ if (node.parent.type === "CatchClause") {
819
+ node.expressions.push(["return"]);
820
+ }
821
+ }
822
+ return;
823
+ case "WhenClause":
824
+ node.children.splice(node.children.indexOf(node.break), 1);
825
+ if (node.block.expressions.length) {
826
+ insertReturn(node.block);
827
+ } else {
828
+ node.block.expressions.push(wrapWithReturn());
829
+ }
830
+ return;
831
+ case "DefaultClause":
832
+ insertReturn(node.block);
833
+ return;
834
+ }
835
+ if (!Array.isArray(node))
836
+ return;
837
+ const [, exp, semi] = node;
838
+ if (semi?.type === "SemicolonDelimiter")
839
+ return;
840
+ let indent = getIndent(node);
841
+ if (!exp)
842
+ return;
843
+ switch (exp.type) {
844
+ case "BreakStatement":
845
+ case "ContinueStatement":
846
+ case "DebuggerStatement":
847
+ case "EmptyStatement":
848
+ case "ReturnStatement":
849
+ case "ThrowStatement":
850
+ case "Declaration":
851
+ return;
852
+ case "ForStatement":
853
+ case "IterationStatement":
854
+ case "DoStatement":
855
+ wrapIterationReturningResults(exp);
856
+ return;
857
+ case "BlockStatement":
858
+ insertReturn(exp.expressions[exp.expressions.length - 1]);
859
+ return;
860
+ case "IfStatement":
861
+ insertReturn(exp.then);
862
+ if (exp.else)
863
+ insertReturn(exp.else[2]);
864
+ else
865
+ exp.children.push(["", {
866
+ type: "ReturnStatement",
867
+ children: [";return"]
868
+ }]);
869
+ return;
870
+ case "PatternMatchingStatement":
871
+ insertReturn(exp.children[0][0]);
872
+ return;
873
+ case "SwitchStatement":
874
+ insertSwitchReturns(exp);
875
+ return;
876
+ case "TryStatement":
877
+ exp.blocks.forEach((block) => insertReturn(block));
878
+ return;
879
+ }
880
+ if (node[node.length - 1]?.type === "SemicolonDelimiter")
881
+ return;
882
+ const returnStatement = wrapWithReturn(node[1]);
883
+ node.splice(1, 1, returnStatement);
884
+ }
885
+ function insertSwitchReturns(exp) {
886
+ switch (exp.type) {
887
+ case "SwitchStatement":
888
+ exp.caseBlock.clauses.forEach((clause) => {
889
+ insertReturn(clause);
890
+ });
891
+ return;
892
+ case "SwitchExpression":
893
+ exp.caseBlock.clauses.forEach(insertReturn);
894
+ return;
895
+ }
896
+ }
897
+ function isEmptyBareBlock(node) {
898
+ if (node?.type !== "BlockStatement")
899
+ return false;
900
+ const { bare, expressions } = node;
901
+ return bare && (expressions.length === 0 || expressions.length === 1 && expressions[0][1]?.type === "EmptyStatement");
902
+ }
204
903
  function isFunction(node) {
205
904
  const { type } = node;
206
905
  return type === "FunctionExpression" || type === "ArrowFunction" || type === "MethodDefinition" || node.async;
207
906
  }
208
- function gatherRecursiveWithinFunction(node, predicate) {
907
+ function isVoidType(t) {
908
+ return t?.type === "LiteralType" && t.t.type === "VoidType";
909
+ }
910
+ function isWhitespaceOrEmpty(node) {
911
+ if (!node)
912
+ return true;
913
+ if (node.type === "Ref")
914
+ return false;
915
+ if (node.token)
916
+ return node.token.match(/^\s*$/);
917
+ if (node.children)
918
+ node = node.children;
919
+ if (!node.length)
920
+ return true;
921
+ if (typeof node === "string")
922
+ return node.match(/^\s*$/);
923
+ if (Array.isArray(node))
924
+ return node.every(isWhitespaceOrEmpty);
925
+ }
926
+ function gatherRecursiveWithinFunction(node, predicate) {
209
927
  return gatherRecursive(node, predicate, isFunction);
210
928
  }
211
929
  function insertTrimmingSpace(target, c) {
@@ -241,62 +959,6 @@ var require_lib = __commonJS({
241
959
  if (target.token)
242
960
  return target.token.match(/^ ?/)[0];
243
961
  }
244
- function needsRef(exp) {
245
- switch (exp.type) {
246
- case "Identifier":
247
- case "Literal":
248
- case "Ref":
249
- return false;
250
- default:
251
- return true;
252
- }
253
- }
254
- function maybeRef(exp, base = "ref") {
255
- if (!needsRef(exp))
256
- return exp;
257
- return {
258
- type: "Ref",
259
- base,
260
- id: base
261
- };
262
- }
263
- function literalValue(literal) {
264
- let { raw } = literal;
265
- switch (raw) {
266
- case "null":
267
- return null;
268
- case "true":
269
- return true;
270
- case "false":
271
- return false;
272
- }
273
- if (raw.startsWith('"') && raw.endsWith('"') || raw.startsWith("'") && raw.endsWith("'")) {
274
- return raw.slice(1, -1);
275
- }
276
- const numeric = literal.children.find(
277
- (child) => child.type === "NumericLiteral"
278
- );
279
- if (numeric) {
280
- raw = raw.replace(/_/g, "");
281
- const { token } = numeric;
282
- if (token.endsWith("n")) {
283
- return BigInt(raw.slice(0, -1));
284
- } else if (token.match(/[\.eE]/)) {
285
- return parseFloat(raw);
286
- } else if (token.startsWith("0")) {
287
- switch (token.charAt(1).toLowerCase()) {
288
- case "x":
289
- return parseInt(raw.replace(/0[xX]/, ""), 16);
290
- case "b":
291
- return parseInt(raw.replace(/0[bB]/, ""), 2);
292
- case "o":
293
- return parseInt(raw.replace(/0[oO]/, ""), 8);
294
- }
295
- }
296
- return parseInt(raw, 10);
297
- }
298
- throw new Error("Unrecognized literal " + JSON.stringify(literal));
299
- }
300
962
  function forRange(open, forDeclaration, range, stepExp, close) {
301
963
  const { start, end, inclusive } = range;
302
964
  const counterRef = {
@@ -384,6 +1046,79 @@ var require_lib = __commonJS({
384
1046
  insertRestSplices(statements, splices, thisAssignments);
385
1047
  return [splices, thisAssignments];
386
1048
  }
1049
+ function literalValue(literal) {
1050
+ let { raw } = literal;
1051
+ switch (raw) {
1052
+ case "null":
1053
+ return null;
1054
+ case "true":
1055
+ return true;
1056
+ case "false":
1057
+ return false;
1058
+ }
1059
+ if (raw.startsWith('"') && raw.endsWith('"') || raw.startsWith("'") && raw.endsWith("'")) {
1060
+ return raw.slice(1, -1);
1061
+ }
1062
+ const numeric = literal.children.find(
1063
+ (child) => child.type === "NumericLiteral"
1064
+ );
1065
+ if (numeric) {
1066
+ raw = raw.replace(/_/g, "");
1067
+ const { token } = numeric;
1068
+ if (token.endsWith("n")) {
1069
+ return BigInt(raw.slice(0, -1));
1070
+ } else if (token.match(/[\.eE]/)) {
1071
+ return parseFloat(raw);
1072
+ } else if (token.startsWith("0")) {
1073
+ switch (token.charAt(1).toLowerCase()) {
1074
+ case "x":
1075
+ return parseInt(raw.replace(/0[xX]/, ""), 16);
1076
+ case "b":
1077
+ return parseInt(raw.replace(/0[bB]/, ""), 2);
1078
+ case "o":
1079
+ return parseInt(raw.replace(/0[oO]/, ""), 8);
1080
+ }
1081
+ }
1082
+ return parseInt(raw, 10);
1083
+ }
1084
+ throw new Error("Unrecognized literal " + JSON.stringify(literal));
1085
+ }
1086
+ var asConst = {
1087
+ ts: true,
1088
+ children: [" as const"]
1089
+ };
1090
+ function makeAsConst(node) {
1091
+ if (node.type === "Literal" && node.raw !== "null" || node.type === "ArrayExpression" || node.type === "ObjectExpression") {
1092
+ return { ...node, children: [...node.children, asConst] };
1093
+ }
1094
+ return node;
1095
+ }
1096
+ function makeLeftHandSideExpression(expression) {
1097
+ switch (expression.type) {
1098
+ case "Ref":
1099
+ case "Identifier":
1100
+ case "Literal":
1101
+ case "CallExpression":
1102
+ case "MemberExpression":
1103
+ case "ParenthesizedExpression":
1104
+ return expression;
1105
+ default:
1106
+ return {
1107
+ type: "ParenthesizedExpression",
1108
+ children: ["(", expression, ")"],
1109
+ expression
1110
+ };
1111
+ }
1112
+ }
1113
+ function maybeRef(exp, base = "ref") {
1114
+ if (!needsRef(exp))
1115
+ return exp;
1116
+ return {
1117
+ type: "Ref",
1118
+ base,
1119
+ id: base
1120
+ };
1121
+ }
387
1122
  function modifyString(str) {
388
1123
  return str.replace(/(^.?|[^\\]{2})(\\\\)*\n/g, "$1$2\\n");
389
1124
  }
@@ -471,6 +1206,20 @@ var require_lib = __commonJS({
471
1206
  }
472
1207
  return parts;
473
1208
  }
1209
+ function needsRef(expression, base = "ref") {
1210
+ switch (expression.type) {
1211
+ case "Ref":
1212
+ case "Identifier":
1213
+ case "Literal":
1214
+ return;
1215
+ default:
1216
+ return {
1217
+ type: "Ref",
1218
+ base,
1219
+ id: base
1220
+ };
1221
+ }
1222
+ }
474
1223
  function processCoffeeInterpolation(s, parts, e, $loc) {
475
1224
  if (parts.length === 0 || parts.length === 1 && parts[0].token != null) {
476
1225
  return {
@@ -559,55 +1308,914 @@ var require_lib = __commonJS({
559
1308
  thisAssignments
560
1309
  };
561
1310
  }
562
- function processUnaryExpression(pre, exp, post) {
563
- if (!(pre.length || post))
564
- return exp;
565
- if (post?.token === "?") {
566
- post = {
567
- $loc: post.$loc,
568
- token: " != null"
569
- };
1311
+ function processFunctions(statements, config) {
1312
+ gatherRecursiveAll(statements, ({ type }) => type === "FunctionExpression" || type === "ArrowFunction").forEach((f) => {
1313
+ processParams(f);
1314
+ if (!processReturnValue(f) && config.implicitReturns) {
1315
+ const { block, returnType } = f;
1316
+ const isVoid = isVoidType(returnType?.t);
1317
+ const isBlock = block?.type === "BlockStatement";
1318
+ if (!isVoid && isBlock) {
1319
+ insertReturn(block);
1320
+ }
1321
+ }
1322
+ });
1323
+ gatherRecursiveAll(statements, ({ type }) => type === "MethodDefinition").forEach((f) => {
1324
+ processParams(f);
1325
+ if (!processReturnValue(f) && config.implicitReturns) {
1326
+ const { signature, block } = f;
1327
+ const isConstructor = signature.name === "constructor";
1328
+ const isVoid = isVoidType(signature.returnType?.t);
1329
+ const isSet = signature.modifier?.set;
1330
+ if (!isConstructor && !isSet && !isVoid) {
1331
+ insertReturn(block);
1332
+ }
1333
+ }
1334
+ });
1335
+ }
1336
+ function processSwitchExpressions(statements) {
1337
+ gatherRecursiveAll(statements, (n) => n.type === "SwitchExpression").forEach(insertSwitchReturns);
1338
+ }
1339
+ function processTryExpressions(statements) {
1340
+ gatherRecursiveAll(statements, (n) => n.type === "TryExpression").forEach(({ blocks }) => {
1341
+ blocks.forEach(insertReturn);
1342
+ });
1343
+ }
1344
+ function processBindingPatternLHS(lhs, tail) {
1345
+ adjustAtBindings(lhs, true);
1346
+ const [splices, thisAssignments] = gatherBindingCode(lhs);
1347
+ tail.push(...splices.map((s) => [", ", s]), ...thisAssignments.map((a) => [", ", a]));
1348
+ }
1349
+ function processAssignments(statements) {
1350
+ gatherRecursiveAll(statements, (n) => n.type === "AssignmentExpression" && n.names === null).forEach((exp) => {
1351
+ let { lhs: $1, exp: $2 } = exp, tail = [], i = 0, len = $1.length;
1352
+ if ($1.some((left) => left[left.length - 1].special)) {
1353
+ if ($1.length !== 1) {
1354
+ throw new Error("Only one assignment with id= is allowed");
1355
+ }
1356
+ const [, lhs, , op] = $1[0];
1357
+ const { call } = op;
1358
+ op[op.length - 1] = "=";
1359
+ $2 = [call, "(", lhs, ", ", $2, ")"];
1360
+ }
1361
+ let wrapped = false;
1362
+ while (i < len) {
1363
+ const lastAssignment = $1[i++];
1364
+ const [, lhs, , op] = lastAssignment;
1365
+ if (op.token !== "=")
1366
+ continue;
1367
+ if (lhs.type === "ObjectExpression" || lhs.type === "ObjectBindingPattern") {
1368
+ if (!wrapped) {
1369
+ wrapped = true;
1370
+ lhs.children.splice(0, 0, "(");
1371
+ tail.push(")");
1372
+ }
1373
+ }
1374
+ }
1375
+ i = len - 1;
1376
+ while (i >= 0) {
1377
+ const lastAssignment = $1[i];
1378
+ if (lastAssignment[3].token === "=") {
1379
+ const lhs = lastAssignment[1];
1380
+ if (lhs.type === "MemberExpression") {
1381
+ const members = lhs.children;
1382
+ const lastMember = members[members.length - 1];
1383
+ if (lastMember.type === "SliceExpression") {
1384
+ const { start, end, children: c } = lastMember;
1385
+ c[0].token = ".splice(";
1386
+ c[1] = start;
1387
+ c[2] = ", ";
1388
+ if (end)
1389
+ c[3] = [end, " - ", start];
1390
+ else
1391
+ c[3] = ["1/0"];
1392
+ c[4] = [", ...", $2];
1393
+ c[5] = ")";
1394
+ lastAssignment.pop();
1395
+ if (isWhitespaceOrEmpty(lastAssignment[2]))
1396
+ lastAssignment.pop();
1397
+ if ($1.length > 1) {
1398
+ throw new Error("Not implemented yet! TODO: Handle multiple splice assignments");
1399
+ }
1400
+ exp.children = [$1];
1401
+ exp.names = [];
1402
+ return;
1403
+ }
1404
+ } else if (lhs.type === "ObjectBindingPattern" || lhs.type === "ArrayBindingPattern") {
1405
+ processBindingPatternLHS(lhs, tail);
1406
+ }
1407
+ }
1408
+ i--;
1409
+ }
1410
+ const names = $1.flatMap(([, l]) => l.names || []);
1411
+ exp.children = [$1, $2, ...tail];
1412
+ exp.names = names;
1413
+ });
1414
+ gatherRecursiveAll(statements, (n) => n.type === "AssignmentExpression" || n.type === "UpdateExpression").forEach((exp) => {
1415
+ function extractAssignment(lhs) {
1416
+ let expr = lhs;
1417
+ while (expr.type === "ParenthesizedExpression") {
1418
+ expr = expr.expression;
1419
+ }
1420
+ if (expr.type === "AssignmentExpression" || expr.type === "UpdateExpression") {
1421
+ if (expr.type === "UpdateExpression" && expr.children[0] === expr.assigned) {
1422
+ post.push([", ", lhs]);
1423
+ } else {
1424
+ pre.push([lhs, ", "]);
1425
+ }
1426
+ return expr.assigned;
1427
+ }
1428
+ }
1429
+ const pre = [], post = [];
570
1430
  switch (exp.type) {
571
- case "Identifier":
1431
+ case "AssignmentExpression":
1432
+ if (!exp.lhs)
1433
+ return;
1434
+ exp.lhs.forEach((lhsPart, i) => {
1435
+ let newLhs2 = extractAssignment(lhsPart[1]);
1436
+ if (newLhs2) {
1437
+ lhsPart[1] = newLhs2;
1438
+ }
1439
+ });
1440
+ break;
1441
+ case "UpdateExpression":
1442
+ let newLhs = extractAssignment(exp.assigned);
1443
+ if (newLhs) {
1444
+ const i = exp.children.indexOf(exp.assigned);
1445
+ exp.assigned = exp.children[i] = newLhs;
1446
+ }
1447
+ break;
1448
+ }
1449
+ if (pre.length)
1450
+ exp.children.unshift(...pre);
1451
+ if (post.length)
1452
+ exp.children.push(...post);
1453
+ });
1454
+ }
1455
+ function attachPostfixStatementAsExpression(exp, post) {
1456
+ let clause;
1457
+ switch (post[1].type) {
1458
+ case "ForStatement":
1459
+ case "IterationStatement":
1460
+ case "DoStatement":
1461
+ clause = addPostfixStatement(exp, ...post);
1462
+ return {
1463
+ type: "IterationExpression",
1464
+ children: [clause],
1465
+ block: clause.block
1466
+ };
1467
+ case "IfStatement":
1468
+ clause = expressionizeIfClause(post[1], exp);
1469
+ return clause;
1470
+ default:
1471
+ throw new Error("Unknown postfix statement");
1472
+ }
1473
+ }
1474
+ function getPatternConditions(pattern, ref, conditions) {
1475
+ if (pattern.rest)
1476
+ return;
1477
+ switch (pattern.type) {
1478
+ case "ArrayBindingPattern": {
1479
+ const { elements, length } = pattern, hasRest = elements.some((e) => e.rest), comparator = hasRest ? " >= " : " === ", l = [comparator, (length - hasRest).toString()];
1480
+ conditions.push(
1481
+ ["Array.isArray(", ref, ")"],
1482
+ [ref, ".length", l]
1483
+ );
1484
+ elements.forEach(({ children: [, e] }, i) => {
1485
+ const subRef = [ref, "[", i.toString(), "]"];
1486
+ getPatternConditions(e, subRef, conditions);
1487
+ });
1488
+ const postRest = pattern.children.find((c) => c?.blockPrefix);
1489
+ if (postRest) {
1490
+ const postElements = postRest.blockPrefix.children[1], { length: postLength } = postElements;
1491
+ postElements.forEach(({ children: [, e] }, i) => {
1492
+ const subRef = [ref, "[", ref, ".length - ", (postLength + i).toString(), "]"];
1493
+ getPatternConditions(e, subRef, conditions);
1494
+ });
1495
+ }
1496
+ break;
1497
+ }
1498
+ case "ObjectBindingPattern": {
1499
+ conditions.push(
1500
+ ["typeof ", ref, " === 'object'"],
1501
+ [ref, " != null"]
1502
+ );
1503
+ pattern.properties.forEach((p) => {
1504
+ switch (p.type) {
1505
+ case "PinProperty":
1506
+ case "BindingProperty": {
1507
+ const { name, value } = p;
1508
+ let subRef;
1509
+ switch (name.type) {
1510
+ case "ComputedPropertyName":
1511
+ conditions.push([name.expression, " in ", ref]);
1512
+ subRef = [ref, name];
1513
+ break;
1514
+ case "Literal":
1515
+ case "StringLiteral":
1516
+ case "NumericLiteral":
1517
+ conditions.push([name, " in ", ref]);
1518
+ subRef = [ref, "[", name, "]"];
1519
+ break;
1520
+ default:
1521
+ conditions.push(["'", name, "' in ", ref]);
1522
+ subRef = [ref, ".", name];
1523
+ }
1524
+ if (value) {
1525
+ getPatternConditions(value, subRef, conditions);
1526
+ }
1527
+ break;
1528
+ }
1529
+ }
1530
+ });
1531
+ break;
1532
+ }
1533
+ case "ConditionFragment":
1534
+ conditions.push(
1535
+ [ref, " ", pattern.children]
1536
+ );
1537
+ break;
1538
+ case "RegularExpressionLiteral": {
1539
+ conditions.push(
1540
+ ["typeof ", ref, " === 'string'"],
1541
+ [pattern, ".test(", ref, ")"]
1542
+ );
1543
+ break;
1544
+ }
1545
+ case "PinPattern":
1546
+ conditions.push([
1547
+ ref,
1548
+ " === ",
1549
+ pattern.identifier
1550
+ ]);
1551
+ break;
1552
+ case "Literal":
1553
+ conditions.push([
1554
+ ref,
1555
+ " === ",
1556
+ pattern
1557
+ ]);
1558
+ break;
1559
+ default:
1560
+ break;
1561
+ }
1562
+ }
1563
+ function elideMatchersFromArrayBindings(elements) {
1564
+ return elements.map((el) => {
1565
+ if (el.type === "BindingRestElement") {
1566
+ return ["", el, void 0];
1567
+ }
1568
+ const { children: [ws, e, sep] } = el;
1569
+ switch (e.type) {
572
1570
  case "Literal":
573
- return {
574
- ...exp,
575
- children: [...pre, ...exp.children, post]
576
- };
1571
+ case "RegularExpressionLiteral":
1572
+ case "StringLiteral":
1573
+ case "PinPattern":
1574
+ return sep;
577
1575
  default:
578
- const expression = {
579
- ...exp,
580
- children: [...pre, "(", exp.children, ")", post]
581
- };
582
- return {
583
- type: "ParenthesizedExpression",
584
- children: ["(", expression, ")"],
585
- expression
586
- };
1576
+ return [ws, nonMatcherBindings(e), sep];
587
1577
  }
588
- }
589
- if (exp.type === "Literal") {
590
- if (pre.length === 1 && pre[0].token === "-") {
591
- const children = [pre[0], ...exp.children];
592
- if (post)
593
- exp.children.push(post);
1578
+ });
1579
+ }
1580
+ function elideMatchersFromPropertyBindings(properties) {
1581
+ return properties.map((p) => {
1582
+ switch (p.type) {
1583
+ case "BindingProperty": {
1584
+ const { children, name, value } = p;
1585
+ const [ws] = children;
1586
+ const sep = children[children.length - 1];
1587
+ switch (value && value.type) {
1588
+ case "ArrayBindingPattern":
1589
+ case "ObjectBindingPattern":
1590
+ return {
1591
+ ...p,
1592
+ children: [ws, name, ": ", nonMatcherBindings(value)]
1593
+ };
1594
+ case "Identifier":
1595
+ return p;
1596
+ case "Literal":
1597
+ case "RegularExpressionLiteral":
1598
+ case "StringLiteral":
1599
+ default:
1600
+ return {
1601
+ ...p,
1602
+ children: [ws, name, sep]
1603
+ };
1604
+ }
1605
+ }
1606
+ case "PinProperty":
1607
+ case "BindingRestProperty":
1608
+ default:
1609
+ return p;
1610
+ }
1611
+ });
1612
+ }
1613
+ function nonMatcherBindings(pattern) {
1614
+ switch (pattern.type) {
1615
+ case "ArrayBindingPattern": {
1616
+ const elements = elideMatchersFromArrayBindings(pattern.elements);
1617
+ const children = ["[", elements, "]"];
594
1618
  return {
595
- type: "Literal",
1619
+ ...pattern,
596
1620
  children,
597
- raw: `-${exp.raw}`
1621
+ elements
598
1622
  };
599
1623
  }
600
- }
601
- const l = pre.length;
602
- if (l) {
603
- const last = pre[l - 1];
604
- if (last.type === "Await" && last.op) {
605
- if (exp.type !== "ParenthesizedExpression") {
606
- exp = ["(", exp, ")"];
607
- }
608
- exp = {
609
- type: "CallExpression",
610
- children: [" Promise", last.op, exp]
1624
+ case "PostRestBindingElements": {
1625
+ const els = elideMatchersFromArrayBindings(pattern.children[1]);
1626
+ return {
1627
+ ...pattern,
1628
+ children: [
1629
+ pattern.children[0],
1630
+ els,
1631
+ ...pattern.children.slice(2)
1632
+ ]
1633
+ };
1634
+ }
1635
+ case "ObjectBindingPattern":
1636
+ return ["{", elideMatchersFromPropertyBindings(pattern.properties), "}"];
1637
+ default:
1638
+ return pattern;
1639
+ }
1640
+ }
1641
+ function aggregateDuplicateBindings(bindings, ReservedWord) {
1642
+ const props = gatherRecursiveAll(bindings, (n) => n.type === "BindingProperty");
1643
+ const arrayBindings = gatherRecursiveAll(bindings, (n) => n.type === "ArrayBindingPattern");
1644
+ arrayBindings.forEach((a) => {
1645
+ const { elements } = a;
1646
+ elements.forEach((element) => {
1647
+ if (Array.isArray(element)) {
1648
+ const [, e] = element;
1649
+ if (e.type === "Identifier") {
1650
+ props.push(e);
1651
+ } else if (e.type === "BindingRestElement") {
1652
+ props.push(e);
1653
+ }
1654
+ }
1655
+ });
1656
+ });
1657
+ const declarations = [];
1658
+ const propsGroupedByName = /* @__PURE__ */ new Map();
1659
+ for (const p of props) {
1660
+ const { name, value } = p;
1661
+ const key = value?.name || name?.name || name;
1662
+ if (propsGroupedByName.has(key)) {
1663
+ propsGroupedByName.get(key).push(p);
1664
+ } else {
1665
+ propsGroupedByName.set(key, [p]);
1666
+ }
1667
+ }
1668
+ propsGroupedByName.forEach((shared, key) => {
1669
+ if (!key)
1670
+ return;
1671
+ if (ReservedWord({
1672
+ pos: 0,
1673
+ input: key
1674
+ })) {
1675
+ shared.forEach((p) => {
1676
+ const ref = {
1677
+ type: "Ref",
1678
+ base: `_${key}`,
1679
+ id: key
1680
+ };
1681
+ aliasBinding(p, ref);
1682
+ });
1683
+ return;
1684
+ }
1685
+ if (shared.length === 1)
1686
+ return;
1687
+ const refs = shared.map((p) => {
1688
+ const ref = {
1689
+ type: "Ref",
1690
+ base: key,
1691
+ id: key
1692
+ };
1693
+ aliasBinding(p, ref);
1694
+ return ref;
1695
+ });
1696
+ declarations.push(["const ", key, " = [", ...refs.map((r, i) => {
1697
+ return i === 0 ? r : [", ", r];
1698
+ }), "]"]);
1699
+ });
1700
+ return declarations;
1701
+ }
1702
+ function processPatternMatching(statements, ReservedWord) {
1703
+ gatherRecursiveAll(statements, (n) => n.type === "SwitchStatement" || n.type === "SwitchExpression").forEach((s) => {
1704
+ const { caseBlock } = s;
1705
+ const { clauses } = caseBlock;
1706
+ let errors = false;
1707
+ let isPattern = false;
1708
+ if (clauses.some((c) => c.type === "PatternClause")) {
1709
+ isPattern = true;
1710
+ clauses.forEach((c) => {
1711
+ if (!(c.type === "PatternClause" || c.type === "DefaultClause")) {
1712
+ errors = true;
1713
+ c.children.push({
1714
+ type: "Error",
1715
+ message: "Can't mix pattern matching and non-pattern matching clauses"
1716
+ });
1717
+ }
1718
+ });
1719
+ }
1720
+ if (errors || !isPattern)
1721
+ return;
1722
+ let { expression } = s;
1723
+ if (expression.type === "ParenthesizedExpression") {
1724
+ expression = expression.expression;
1725
+ }
1726
+ let ref = needsRef(expression, "m") || expression;
1727
+ let hoistDec = ref !== expression ? [["", ["const ", ref, " = ", expression], ";"]] : void 0;
1728
+ let prev = [], root = prev;
1729
+ const l = clauses.length;
1730
+ clauses.forEach((c, i) => {
1731
+ if (c.type === "DefaultClause") {
1732
+ prev.push(c.block);
1733
+ return;
1734
+ }
1735
+ let { patterns, block } = c;
1736
+ let pattern = patterns[0];
1737
+ const indent = block.expressions?.[0]?.[0] || "";
1738
+ const alternativeConditions = patterns.map((pattern2, i2) => {
1739
+ const conditions = [];
1740
+ getPatternConditions(pattern2, ref, conditions);
1741
+ return conditions;
1742
+ });
1743
+ const conditionExpression = alternativeConditions.map((conditions, i2) => {
1744
+ const conditionArray = conditions.map((c2, i3) => {
1745
+ if (i3 === 0)
1746
+ return c2;
1747
+ return [" && ", ...c2];
1748
+ });
1749
+ if (i2 === 0)
1750
+ return conditionArray;
1751
+ return [" || ", ...conditionArray];
1752
+ });
1753
+ const condition = {
1754
+ type: "ParenthesizedExpression",
1755
+ children: ["(", conditionExpression, ")"],
1756
+ expression: conditionExpression
1757
+ };
1758
+ const prefix = [];
1759
+ switch (pattern.type) {
1760
+ case "ArrayBindingPattern":
1761
+ if (pattern.length === 0)
1762
+ break;
1763
+ case "ObjectBindingPattern": {
1764
+ if (pattern.properties?.length === 0)
1765
+ break;
1766
+ let [splices, thisAssignments] = gatherBindingCode(pattern);
1767
+ const patternBindings = nonMatcherBindings(pattern);
1768
+ splices = splices.map((s2) => [", ", nonMatcherBindings(s2)]);
1769
+ thisAssignments = thisAssignments.map((a) => [indent, a, ";"]);
1770
+ const duplicateDeclarations = aggregateDuplicateBindings([patternBindings, splices], ReservedWord);
1771
+ prefix.push([indent, "const ", patternBindings, " = ", ref, splices, ";"]);
1772
+ prefix.push(...thisAssignments);
1773
+ prefix.push(...duplicateDeclarations.map((d) => [indent, d, ";"]));
1774
+ break;
1775
+ }
1776
+ }
1777
+ block.expressions.unshift(...prefix);
1778
+ const next = [];
1779
+ if (block.bare) {
1780
+ block.children.unshift(" {");
1781
+ block.children.push("}");
1782
+ block.bare = false;
1783
+ }
1784
+ if (i < l - 1)
1785
+ next.push("\n", "else ");
1786
+ prev.push(["", {
1787
+ type: "IfStatement",
1788
+ children: ["if", condition, block, next],
1789
+ then: block,
1790
+ else: next,
1791
+ hoistDec
1792
+ }]);
1793
+ hoistDec = void 0;
1794
+ prev = next;
1795
+ });
1796
+ if (s.type === "SwitchExpression") {
1797
+ insertReturn(root[0]);
1798
+ root.splice(0, 1, wrapIIFE(root[0]));
1799
+ }
1800
+ s.type = "PatternMatchingStatement";
1801
+ s.children = [root];
1802
+ addParentPointers(s, s.parent);
1803
+ });
1804
+ }
1805
+ function processPipelineExpressions(statements) {
1806
+ gatherRecursiveAll(statements, (n) => n.type === "PipelineExpression").forEach((s) => {
1807
+ const [ws, , body] = s.children;
1808
+ let [, arg] = s.children;
1809
+ let i = 0, l = body.length;
1810
+ const refDec = [];
1811
+ const children = [ws, refDec];
1812
+ let usingRef = null;
1813
+ for (i = 0; i < l; i++) {
1814
+ const step = body[i];
1815
+ const [leadingComment, pipe, trailingComment, expr] = step;
1816
+ const returns = pipe.token === "||>";
1817
+ let ref, result, returning = returns ? arg : null;
1818
+ if (pipe.token === "|>=") {
1819
+ let initRef;
1820
+ if (i === 0) {
1821
+ outer:
1822
+ switch (arg.type) {
1823
+ case "MemberExpression":
1824
+ if (arg.children.length <= 2)
1825
+ break;
1826
+ case "CallExpression":
1827
+ const access = arg.children.pop();
1828
+ switch (access.type) {
1829
+ case "PropertyAccess":
1830
+ case "SliceExpression":
1831
+ break;
1832
+ default:
1833
+ children.unshift({
1834
+ type: "Error",
1835
+ $loc: pipe.token.$loc,
1836
+ message: `Can't assign to ${access.type}`
1837
+ });
1838
+ arg.children.push(access);
1839
+ break outer;
1840
+ }
1841
+ usingRef = needsRef({});
1842
+ initRef = {
1843
+ type: "AssignmentExpression",
1844
+ children: [usingRef, " = ", arg, ","]
1845
+ };
1846
+ arg = {
1847
+ type: "MemberExpression",
1848
+ children: [usingRef, access]
1849
+ };
1850
+ break;
1851
+ }
1852
+ children.pop();
1853
+ const lhs = [[
1854
+ [refDec, initRef],
1855
+ arg,
1856
+ [],
1857
+ { token: "=", children: [" = "] }
1858
+ ]];
1859
+ Object.assign(s, {
1860
+ type: "AssignmentExpression",
1861
+ children: [lhs, children],
1862
+ names: null,
1863
+ lhs,
1864
+ assigned: arg,
1865
+ exp: children
1866
+ });
1867
+ arg = clone(arg);
1868
+ if (arg.children[0].type === "Ref") {
1869
+ arg.children[0] = usingRef;
1870
+ }
1871
+ } else {
1872
+ children.unshift({
1873
+ type: "Error",
1874
+ $loc: pipe.token.$loc,
1875
+ message: "Can't use |>= in the middle of a pipeline"
1876
+ });
1877
+ }
1878
+ } else {
1879
+ s.children = children;
1880
+ }
1881
+ if (returns && (ref = needsRef(arg))) {
1882
+ usingRef = usingRef || ref;
1883
+ arg = {
1884
+ type: "ParenthesizedExpression",
1885
+ children: ["(", {
1886
+ type: "AssignmentExpression",
1887
+ children: [usingRef, " = ", arg]
1888
+ }, ")"]
1889
+ };
1890
+ returning = usingRef;
1891
+ }
1892
+ [result, returning] = constructPipeStep(
1893
+ {
1894
+ leadingComment: skipIfOnlyWS(leadingComment),
1895
+ trailingComment: skipIfOnlyWS(trailingComment),
1896
+ expr
1897
+ },
1898
+ arg,
1899
+ returning
1900
+ );
1901
+ if (result.type === "ReturnStatement") {
1902
+ if (i < l - 1) {
1903
+ result.children.push({
1904
+ type: "Error",
1905
+ message: "Can't continue a pipeline after returning"
1906
+ });
1907
+ }
1908
+ arg = result;
1909
+ if (children[children.length - 1] === ",") {
1910
+ children.pop();
1911
+ children.push(";");
1912
+ }
1913
+ break;
1914
+ }
1915
+ if (returning) {
1916
+ arg = returning;
1917
+ children.push(result, ",");
1918
+ } else {
1919
+ arg = result;
1920
+ }
1921
+ }
1922
+ if (usingRef) {
1923
+ refDec.unshift("let ", usingRef, ";");
1924
+ }
1925
+ children.push(arg);
1926
+ addParentPointers(s, s.parent);
1927
+ });
1928
+ }
1929
+ function processProgram(root, config, m, ReservedWord) {
1930
+ assert.equal(m.forbidClassImplicitCall.length, 1, "forbidClassImplicitCall");
1931
+ assert.equal(m.forbidIndentedApplication.length, 1, "forbidIndentedApplication");
1932
+ assert.equal(m.forbidTrailingMemberProperty.length, 1, "forbidTrailingMemberProperty");
1933
+ assert.equal(m.forbidMultiLineImplicitObjectLiteral.length, 1, "forbidMultiLineImplicitObjectLiteral");
1934
+ assert.equal(m.JSXTagStack.length, 0, "JSXTagStack should be empty");
1935
+ addParentPointers(root);
1936
+ const { expressions: statements } = root;
1937
+ processPipelineExpressions(statements);
1938
+ processAssignments(statements);
1939
+ processPatternMatching(statements, ReservedWord);
1940
+ processFunctions(statements, config);
1941
+ processSwitchExpressions(statements);
1942
+ processTryExpressions(statements);
1943
+ hoistRefDecs(statements);
1944
+ gatherRecursiveAll(statements, (n) => n.type === "IterationExpression").forEach((e) => expressionizeIteration(e));
1945
+ statements.unshift(...m.prelude);
1946
+ if (config.autoLet) {
1947
+ createLetDecs(statements, []);
1948
+ } else if (config.autoVar) {
1949
+ createVarDecs(statements, []);
1950
+ }
1951
+ populateRefs(statements);
1952
+ adjustAtBindings(statements);
1953
+ }
1954
+ function findDecs(statements) {
1955
+ const declarationNames = gatherNodes(statements, ({ type }) => type === "Declaration").flatMap((d) => d.names);
1956
+ return new Set(declarationNames);
1957
+ }
1958
+ function populateRefs(statements) {
1959
+ const refNodes = gatherRecursive(statements, ({ type }) => type === "Ref");
1960
+ if (refNodes.length) {
1961
+ const ids = gatherRecursive(statements, (s) => s.type === "Identifier");
1962
+ const names = new Set(ids.flatMap(({ names: names2 }) => names2 || []));
1963
+ refNodes.forEach((ref) => {
1964
+ const { type, base } = ref;
1965
+ if (type !== "Ref")
1966
+ return;
1967
+ ref.type = "Identifier";
1968
+ let n = 0;
1969
+ let name = base;
1970
+ while (names.has(name)) {
1971
+ n++;
1972
+ name = `${base}${n}`;
1973
+ }
1974
+ names.add(name);
1975
+ ref.children = ref.names = [name];
1976
+ });
1977
+ }
1978
+ }
1979
+ function createVarDecs(statements, scopes, pushVar) {
1980
+ function hasDec(name) {
1981
+ return scopes.some((s) => s.has(name));
1982
+ }
1983
+ function findAssignments(statements2, decs2) {
1984
+ let assignmentStatements2 = gatherNodes(statements2, (node) => {
1985
+ return node.type === "AssignmentExpression";
1986
+ });
1987
+ if (assignmentStatements2.length) {
1988
+ assignmentStatements2 = assignmentStatements2.concat(findAssignments(assignmentStatements2.map((s) => s.children), decs2));
1989
+ }
1990
+ return assignmentStatements2;
1991
+ }
1992
+ if (!pushVar) {
1993
+ pushVar = function(name) {
1994
+ varIds.push(name);
1995
+ decs.add(name);
1996
+ };
1997
+ }
1998
+ const decs = findDecs(statements);
1999
+ scopes.push(decs);
2000
+ const varIds = [];
2001
+ const assignmentStatements = findAssignments(statements, scopes);
2002
+ const undeclaredIdentifiers = assignmentStatements.flatMap((a) => a.names);
2003
+ undeclaredIdentifiers.filter((x, i, a) => {
2004
+ if (!hasDec(x))
2005
+ return a.indexOf(x) === i;
2006
+ }).forEach(pushVar);
2007
+ const fnNodes = gatherNodes(statements, (s) => s.type === "FunctionExpression");
2008
+ const forNodes = gatherNodes(statements, (s) => s.type === "ForStatement");
2009
+ const blockNodes = new Set(gatherNodes(statements, (s) => s.type === "BlockStatement"));
2010
+ fnNodes.forEach(({ block }) => blockNodes.delete(block));
2011
+ forNodes.forEach(({ block }) => blockNodes.delete(block));
2012
+ blockNodes.forEach((block) => {
2013
+ createVarDecs(block.expressions, scopes, pushVar);
2014
+ });
2015
+ forNodes.forEach(({ block, declaration }) => {
2016
+ scopes.push(new Set(declaration.names));
2017
+ createVarDecs(block.expressions, scopes, pushVar);
2018
+ scopes.pop();
2019
+ });
2020
+ fnNodes.forEach(({ block, parameters }) => {
2021
+ scopes.push(new Set(parameters.names));
2022
+ createVarDecs(block.expressions, scopes);
2023
+ scopes.pop();
2024
+ });
2025
+ if (varIds.length) {
2026
+ const indent = getIndent(statements[0]);
2027
+ let delimiter = ";";
2028
+ if (statements[0][1]?.parent?.root) {
2029
+ delimiter = ";\n";
2030
+ }
2031
+ statements.unshift([indent, "var ", varIds.join(", "), delimiter]);
2032
+ }
2033
+ scopes.pop();
2034
+ }
2035
+ function createLetDecs(statements, scopes) {
2036
+ function findVarDecs(statements2, decs) {
2037
+ const declarationNames = gatherRecursive(
2038
+ statements2,
2039
+ (node) => node.type === "Declaration" && node.children && node.children.length > 0 && node.children[0].token && node.children[0].token.startsWith("var") || node.type === "FunctionExpression"
2040
+ ).filter((node) => node.type === "Declaration").flatMap((node) => node.names);
2041
+ return new Set(declarationNames);
2042
+ }
2043
+ let declaredIdentifiers = findVarDecs(statements);
2044
+ function hasDec(name) {
2045
+ return declaredIdentifiers.has(name) || scopes.some((s) => s.has(name));
2046
+ }
2047
+ function gatherBlockOrOther(statement) {
2048
+ return gatherNodes(statement, (s) => s.type === "BlockStatement" || s.type === "AssignmentExpression" || s.type === "Declaration").flatMap((node) => {
2049
+ if (node.type == "BlockStatement")
2050
+ return node.bare ? gatherBlockOrOther(node.expressions) : node;
2051
+ else if (node.children && node.children.length)
2052
+ return [...gatherBlockOrOther(node.children), node];
2053
+ else
2054
+ return [];
2055
+ });
2056
+ }
2057
+ let currentScope = /* @__PURE__ */ new Set();
2058
+ scopes.push(currentScope);
2059
+ const fnNodes = gatherNodes(statements, (s) => s.type === "FunctionExpression");
2060
+ const forNodes = gatherNodes(statements, (s) => s.type === "ForStatement");
2061
+ let targetStatements = [];
2062
+ for (const statement of statements) {
2063
+ const nodes = gatherBlockOrOther(statement);
2064
+ let undeclaredIdentifiers = [];
2065
+ for (const node of nodes) {
2066
+ if (node.type == "BlockStatement") {
2067
+ let block = node;
2068
+ let fnNode = fnNodes.find((fnNode2) => fnNode2.block === block);
2069
+ let forNode = forNodes.find((forNode2) => forNode2.block === block);
2070
+ if (fnNode != null) {
2071
+ scopes.push(new Set(fnNode.parameters.names));
2072
+ createLetDecs(block.expressions, scopes);
2073
+ scopes.pop();
2074
+ } else if (forNode != null) {
2075
+ scopes.push(new Set(forNode.declaration.names));
2076
+ createLetDecs(block.expressions, scopes);
2077
+ scopes.pop();
2078
+ } else
2079
+ createLetDecs(block.expressions, scopes);
2080
+ continue;
2081
+ }
2082
+ if (node.names == null)
2083
+ continue;
2084
+ let names = node.names.filter((name) => !hasDec(name));
2085
+ if (node.type == "AssignmentExpression")
2086
+ undeclaredIdentifiers.push(...names);
2087
+ names.forEach((name) => currentScope.add(name));
2088
+ }
2089
+ if (undeclaredIdentifiers.length > 0) {
2090
+ let indent = statement[0];
2091
+ let firstIdentifier = gatherNodes(statement[1], (node) => node.type == "Identifier")[0];
2092
+ if (undeclaredIdentifiers.length == 1 && statement[1].type == "AssignmentExpression" && statement[1].names.length == 1 && statement[1].names[0] == undeclaredIdentifiers[0] && firstIdentifier && firstIdentifier.names == undeclaredIdentifiers[0] && gatherNodes(statement[1], (node) => node.type === "ObjectBindingPattern").length == 0)
2093
+ statement[1].children.unshift(["let "]);
2094
+ else {
2095
+ let tail = "\n";
2096
+ if (gatherNodes(indent, (node) => node.token && node.token.endsWith("\n")).length > 0)
2097
+ tail = void 0;
2098
+ targetStatements.push([indent, "let ", undeclaredIdentifiers.join(", "), tail]);
2099
+ }
2100
+ }
2101
+ targetStatements.push(statement);
2102
+ }
2103
+ scopes.pop();
2104
+ statements.splice(0, statements.length, targetStatements);
2105
+ }
2106
+ function processReturnValue(func) {
2107
+ const { block } = func;
2108
+ const values = gatherRecursiveWithinFunction(
2109
+ block,
2110
+ ({ type }) => type === "ReturnValue"
2111
+ );
2112
+ if (!values.length)
2113
+ return false;
2114
+ const ref = {
2115
+ type: "Ref",
2116
+ base: "ret",
2117
+ id: "ret"
2118
+ };
2119
+ let declared;
2120
+ values.forEach((value) => {
2121
+ value.children = [ref];
2122
+ const ancestor = findAncestor(
2123
+ value,
2124
+ ({ type }) => type === "Declaration",
2125
+ isFunction
2126
+ );
2127
+ if (ancestor)
2128
+ declared = true;
2129
+ });
2130
+ if (!declared) {
2131
+ let returnType = func.returnType ?? func.signature?.returnType;
2132
+ if (returnType) {
2133
+ const { t } = returnType;
2134
+ if (t.type === "TypePredicate") {
2135
+ returnType = ": boolean";
2136
+ } else if (t.type === "AssertsType") {
2137
+ returnType = void 0;
2138
+ }
2139
+ }
2140
+ block.expressions.unshift([
2141
+ getIndent(block.expressions[0]),
2142
+ {
2143
+ type: "Declaration",
2144
+ children: ["let ", ref, returnType],
2145
+ names: []
2146
+ },
2147
+ ";"
2148
+ ]);
2149
+ }
2150
+ gatherRecursiveWithinFunction(
2151
+ block,
2152
+ (r) => r.type === "ReturnStatement" && !r.expression
2153
+ ).forEach((r) => {
2154
+ r.expression = ref;
2155
+ r.children.splice(-1, 1, " ", ref);
2156
+ });
2157
+ if (block.children.at(-2)?.type !== "ReturnStatement") {
2158
+ block.expressions.push([
2159
+ [getIndent(block.expressions.at(-1))],
2160
+ {
2161
+ type: "ReturnStatement",
2162
+ expression: ref,
2163
+ children: ["return ", ref]
2164
+ }
2165
+ ]);
2166
+ }
2167
+ return true;
2168
+ }
2169
+ function processUnaryExpression(pre, exp, post) {
2170
+ if (!(pre.length || post))
2171
+ return exp;
2172
+ if (post?.token === "?") {
2173
+ post = {
2174
+ $loc: post.$loc,
2175
+ token: " != null"
2176
+ };
2177
+ switch (exp.type) {
2178
+ case "Identifier":
2179
+ case "Literal":
2180
+ case "AmpersandRef":
2181
+ return {
2182
+ ...exp,
2183
+ children: [...pre, ...exp.children, post]
2184
+ };
2185
+ default:
2186
+ const expression = {
2187
+ ...exp,
2188
+ children: [...pre, "(", exp.children, ")", post]
2189
+ };
2190
+ return {
2191
+ type: "ParenthesizedExpression",
2192
+ children: ["(", expression, ")"],
2193
+ expression
2194
+ };
2195
+ }
2196
+ }
2197
+ if (exp.type === "Literal") {
2198
+ if (pre.length === 1 && pre[0].token === "-") {
2199
+ const children = [pre[0], ...exp.children];
2200
+ if (post)
2201
+ exp.children.push(post);
2202
+ return {
2203
+ type: "Literal",
2204
+ children,
2205
+ raw: `-${exp.raw}`
2206
+ };
2207
+ }
2208
+ }
2209
+ const l = pre.length;
2210
+ if (l) {
2211
+ const last = pre[l - 1];
2212
+ if (last.type === "Await" && last.op) {
2213
+ if (exp.type !== "ParenthesizedExpression") {
2214
+ exp = ["(", exp, ")"];
2215
+ }
2216
+ exp = {
2217
+ type: "CallExpression",
2218
+ children: [" Promise", last.op, exp]
611
2219
  };
612
2220
  }
613
2221
  }
@@ -616,13 +2224,198 @@ var require_lib = __commonJS({
616
2224
  children: [...pre, exp, post]
617
2225
  };
618
2226
  }
2227
+ function prune2(node) {
2228
+ if (node === null || node === void 0)
2229
+ return;
2230
+ if (node.length === 0)
2231
+ return;
2232
+ if (Array.isArray(node)) {
2233
+ const a = node.map((n) => prune2(n)).filter((n) => !!n);
2234
+ if (a.length > 1)
2235
+ return a;
2236
+ if (a.length === 1)
2237
+ return a[0];
2238
+ return;
2239
+ }
2240
+ if (node.children != null) {
2241
+ node.children = prune2(node.children);
2242
+ return node;
2243
+ }
2244
+ return node;
2245
+ }
2246
+ function reorderBindingRestProperty(props) {
2247
+ const names = props.flatMap((p) => p.names);
2248
+ let restIndex = -1;
2249
+ let restCount = 0;
2250
+ props.forEach(({ type }, i) => {
2251
+ if (type === "BindingRestProperty") {
2252
+ if (restIndex < 0)
2253
+ restIndex = i;
2254
+ restCount++;
2255
+ }
2256
+ });
2257
+ if (restCount === 0) {
2258
+ return {
2259
+ children: props,
2260
+ names
2261
+ };
2262
+ } else if (restCount === 1) {
2263
+ let after = props.slice(restIndex + 1);
2264
+ let rest = props[restIndex];
2265
+ props = props.slice(0, restIndex);
2266
+ if (after.length) {
2267
+ const [restDelim] = rest.children.slice(-1), lastAfterProp = after[after.length - 1], lastAfterChildren = lastAfterProp.children, [lastDelim] = lastAfterChildren.slice(-1);
2268
+ rest = { ...rest, children: [...rest.children.slice(0, -1), lastDelim] };
2269
+ after = [...after.slice(0, -1), { ...lastAfterProp, children: [...lastAfterChildren.slice(0, -1), restDelim] }];
2270
+ }
2271
+ const children = [...props, ...after, rest];
2272
+ return {
2273
+ children,
2274
+ names
2275
+ };
2276
+ }
2277
+ return {
2278
+ children: [{
2279
+ type: "Error",
2280
+ message: "Multiple rest properties in object pattern"
2281
+ }, props]
2282
+ };
2283
+ }
2284
+ function replaceNodes(root, predicate, replacer) {
2285
+ if (root == null)
2286
+ return root;
2287
+ const array = Array.isArray(root) ? root : root.children;
2288
+ if (!array)
2289
+ return root;
2290
+ array.forEach((node, i) => {
2291
+ if (node == null)
2292
+ return;
2293
+ if (predicate(node)) {
2294
+ array[i] = replacer(node, root);
2295
+ } else {
2296
+ replaceNodes(node, predicate, replacer);
2297
+ }
2298
+ });
2299
+ return root;
2300
+ }
2301
+ function skipIfOnlyWS(target) {
2302
+ if (!target)
2303
+ return target;
2304
+ if (Array.isArray(target)) {
2305
+ if (target.length === 1) {
2306
+ return skipIfOnlyWS(target[0]);
2307
+ } else if (target.every((e) => skipIfOnlyWS(e) === void 0)) {
2308
+ return void 0;
2309
+ }
2310
+ return target;
2311
+ }
2312
+ if (target.token != null && target.token.trim() === "") {
2313
+ return void 0;
2314
+ }
2315
+ return target;
2316
+ }
2317
+ function typeOfJSX(node, config, getRef) {
2318
+ switch (node.type) {
2319
+ case "JSXElement":
2320
+ return typeOfJSXElement(node, config, getRef);
2321
+ case "JSXFragment":
2322
+ return typeOfJSXFragment(node, config, getRef);
2323
+ }
2324
+ }
2325
+ function typeOfJSXElement(node, config, getRef) {
2326
+ if (config.solid) {
2327
+ if (config.server && !config.client) {
2328
+ return ["string"];
2329
+ }
2330
+ let { tag } = node;
2331
+ const clientType = tag[0] === tag[0].toLowerCase() ? [getRef("IntrinsicElements"), '<"', tag, '">'] : ["ReturnType<typeof ", tag, ">"];
2332
+ if (config.server) {
2333
+ return ["string", " | ", clientType];
2334
+ } else {
2335
+ return clientType;
2336
+ }
2337
+ }
2338
+ }
2339
+ function typeOfJSXFragment(node, config, getRef) {
2340
+ if (config.solid) {
2341
+ let type = [];
2342
+ let lastType;
2343
+ for (let child of node.jsxChildren) {
2344
+ switch (child.type) {
2345
+ case "JSXText":
2346
+ if (lastType !== "JSXText") {
2347
+ type.push("string");
2348
+ }
2349
+ break;
2350
+ case "JSXElement":
2351
+ type.push(typeOfJSXElement(child, config, getRef));
2352
+ break;
2353
+ case "JSXFragment":
2354
+ type.push(...typeOfJSXFragment(child, config, getRef));
2355
+ break;
2356
+ case "JSXChildExpression":
2357
+ if (child.expression) {
2358
+ type.push(["typeof ", child.expression]);
2359
+ }
2360
+ break;
2361
+ default:
2362
+ throw new Error(`unknown child in JSXFragment: ${JSON.stringify(child)}`);
2363
+ }
2364
+ lastType = child.type;
2365
+ }
2366
+ if (type.length === 1) {
2367
+ return type[0];
2368
+ } else {
2369
+ type = type.flatMap((t) => [t, ", "]);
2370
+ type.pop();
2371
+ return ["[", type, "]"];
2372
+ }
2373
+ }
2374
+ }
2375
+ function wrapIIFE(exp, async) {
2376
+ let prefix, suffix;
2377
+ if (async) {
2378
+ prefix = "(async ()=>";
2379
+ suffix = ")()";
2380
+ } else if (hasAwait(exp)) {
2381
+ prefix = "(await (async ()=>";
2382
+ suffix = ")())";
2383
+ } else {
2384
+ prefix = "(()=>";
2385
+ suffix = ")()";
2386
+ }
2387
+ const expressions = Array.isArray(exp) ? [[...exp]] : [exp];
2388
+ const block = {
2389
+ type: "BlockStatement",
2390
+ expressions,
2391
+ children: ["{", expressions, "}"],
2392
+ bare: false
2393
+ };
2394
+ return [
2395
+ prefix,
2396
+ block,
2397
+ suffix
2398
+ ];
2399
+ }
619
2400
  module.exports = {
2401
+ addParentPointers,
2402
+ addPostfixStatement,
2403
+ adjustAtBindings,
2404
+ adjustBindingElements,
620
2405
  aliasBinding,
2406
+ arrayElementHasTrailingComma,
2407
+ attachPostfixStatementAsExpression,
621
2408
  blockWithPrefix,
622
2409
  clone,
2410
+ constructInvocation,
2411
+ constructPipeStep,
623
2412
  convertMethodToFunction,
624
2413
  convertObjectToJSXAttributes,
2414
+ dedentBlockString,
2415
+ dedentBlockSubstitutions,
625
2416
  deepCopy,
2417
+ expressionizeIfClause,
2418
+ expressionizeIteration,
626
2419
  findAncestor,
627
2420
  forRange,
628
2421
  gatherBindingCode,
@@ -635,17 +2428,36 @@ var require_lib = __commonJS({
635
2428
  hasAwait,
636
2429
  hasYield,
637
2430
  hoistRefDecs,
2431
+ insertReturn,
2432
+ insertSwitchReturns,
638
2433
  insertTrimmingSpace,
2434
+ isEmptyBareBlock,
639
2435
  isFunction,
2436
+ isVoidType,
2437
+ isWhitespaceOrEmpty,
640
2438
  lastAccessInCallExpression,
641
2439
  literalValue,
2440
+ makeAsConst,
2441
+ makeLeftHandSideExpression,
642
2442
  modifyString,
2443
+ needsRef,
2444
+ processBinaryOpExpression,
2445
+ processCallMemberExpression,
643
2446
  processCoffeeInterpolation,
644
2447
  processConstAssignmentDeclaration,
645
2448
  processLetAssignmentDeclaration,
2449
+ processParams,
2450
+ processProgram,
2451
+ processReturnValue,
646
2452
  processUnaryExpression,
2453
+ prune: prune2,
647
2454
  quoteString,
648
- removeParentPointers
2455
+ removeParentPointers,
2456
+ reorderBindingRestProperty,
2457
+ replaceNodes,
2458
+ skipIfOnlyWS,
2459
+ typeOfJSX,
2460
+ wrapIIFE
649
2461
  };
650
2462
  }
651
2463
  });
@@ -1940,13 +3752,13 @@ ${input.slice(result.pos)}
1940
3752
  var $R65 = $R(new RegExp("[ \\t]*", "suy"));
1941
3753
  var Program$0 = $TS($S(Reset, Init, $E(EOS), TopLevelStatements, __), function($skip, $loc, $0, $1, $2, $3, $4, $5) {
1942
3754
  var statements = $4;
1943
- module.processProgram({
3755
+ processProgram({
1944
3756
  type: "BlockStatement",
1945
3757
  expressions: statements,
1946
3758
  children: [statements],
1947
3759
  bare: true,
1948
3760
  root: true
1949
- });
3761
+ }, module.config, module, ReservedWord);
1950
3762
  return $0;
1951
3763
  });
1952
3764
  function Program(state) {
@@ -2321,7 +4133,7 @@ ${input.slice(result.pos)}
2321
4133
  var ws = $4;
2322
4134
  var args = $5;
2323
4135
  var close = $6;
2324
- if (args.length === 1 && args[0].type === "IterationExpression" && args[0].subtype !== "DoStatement" && !args[0].async && module.isEmptyBareBlock(args[0].block)) {
4136
+ if (args.length === 1 && args[0].type === "IterationExpression" && args[0].subtype !== "DoStatement" && !args[0].async && isEmptyBareBlock(args[0].block)) {
2325
4137
  return $skip;
2326
4138
  }
2327
4139
  return [ta?.[0], open, insertTrimmingSpace(ws, ""), args, close];
@@ -2726,7 +4538,7 @@ ${input.slice(result.pos)}
2726
4538
  }
2727
4539
  var BinaryOpExpression$0 = $TS($S(UnaryExpression, $Q(BinaryOpRHS)), function($skip, $loc, $0, $1, $2) {
2728
4540
  if ($2.length)
2729
- return module.processBinaryOpExpression($0);
4541
+ return processBinaryOpExpression($0);
2730
4542
  return $1;
2731
4543
  });
2732
4544
  function BinaryOpExpression(state) {
@@ -3716,7 +5528,7 @@ ${input.slice(result.pos)}
3716
5528
  var ExtendsTarget$0 = $TS($S(ExpressionWithIndentedApplicationForbidden, $E(TypeArguments)), function($skip, $loc, $0, $1, $2) {
3717
5529
  var exp = $1;
3718
5530
  var ta = $2;
3719
- exp = module.makeLeftHandSideExpression(exp);
5531
+ exp = makeLeftHandSideExpression(exp);
3720
5532
  if (ta)
3721
5533
  return [exp, ta];
3722
5534
  return exp;
@@ -4267,14 +6079,14 @@ ${input.slice(result.pos)}
4267
6079
  }
4268
6080
  var CallExpression$0 = $TS($S($EXPECT($L14, fail, 'CallExpression "super"'), ArgumentsWithTrailingMemberExpressions, $Q(CallExpressionRest)), function($skip, $loc, $0, $1, $2, $3) {
4269
6081
  var rest = $3;
4270
- return module.processCallMemberExpression({
6082
+ return processCallMemberExpression({
4271
6083
  type: "CallExpression",
4272
6084
  children: [$1, ...$2, ...rest.flat()]
4273
6085
  });
4274
6086
  });
4275
6087
  var CallExpression$1 = $TS($S($EXPECT($L15, fail, 'CallExpression "import"'), ArgumentsWithTrailingMemberExpressions, $Q(CallExpressionRest)), function($skip, $loc, $0, $1, $2, $3) {
4276
6088
  var rest = $3;
4277
- return module.processCallMemberExpression({
6089
+ return processCallMemberExpression({
4278
6090
  type: "CallExpression",
4279
6091
  children: [$1, ...$2, ...rest.flat()]
4280
6092
  });
@@ -4285,7 +6097,7 @@ ${input.slice(result.pos)}
4285
6097
  var rest = $3;
4286
6098
  if (rest.length || trailing.length) {
4287
6099
  rest = rest.flat();
4288
- return module.processCallMemberExpression({
6100
+ return processCallMemberExpression({
4289
6101
  type: "CallExpression",
4290
6102
  children: [member, ...trailing, ...rest]
4291
6103
  });
@@ -4428,7 +6240,7 @@ ${input.slice(result.pos)}
4428
6240
  var MemberExpression$0 = $TS($S($C(PrimaryExpression, SuperProperty, MetaProperty), $Q(MemberExpressionRest)), function($skip, $loc, $0, $1, $2) {
4429
6241
  var rest = $2;
4430
6242
  if (rest.length || Array.isArray($1)) {
4431
- return module.processCallMemberExpression({
6243
+ return processCallMemberExpression({
4432
6244
  type: "MemberExpression",
4433
6245
  children: [$1, ...rest].flat()
4434
6246
  });
@@ -5239,7 +7051,7 @@ ${input.slice(result.pos)}
5239
7051
  var props = $0;
5240
7052
  if (!props)
5241
7053
  return { children: [], names: [] };
5242
- return module.reorderBindingRestProperty(props);
7054
+ return reorderBindingRestProperty(props);
5243
7055
  });
5244
7056
  function ObjectBindingPatternContent(state) {
5245
7057
  let eventData;
@@ -5331,7 +7143,7 @@ ${input.slice(result.pos)}
5331
7143
  var elements = $0;
5332
7144
  if (!elements)
5333
7145
  return { children: [], names: [], length: 0 };
5334
- return module.adjustBindingElements(elements);
7146
+ return adjustBindingElements(elements);
5335
7147
  });
5336
7148
  function ArrayBindingPatternContent(state) {
5337
7149
  let eventData;
@@ -5447,7 +7259,7 @@ ${input.slice(result.pos)}
5447
7259
  var props = $2;
5448
7260
  if (!props.length)
5449
7261
  return $skip;
5450
- return module.reorderBindingRestProperty(props.flat());
7262
+ return reorderBindingRestProperty(props.flat());
5451
7263
  });
5452
7264
  function NestedBindingProperties(state) {
5453
7265
  let eventData;
@@ -5623,7 +7435,7 @@ ${input.slice(result.pos)}
5623
7435
  var elements = $2;
5624
7436
  if (!elements.length)
5625
7437
  return $skip;
5626
- return module.adjustBindingElements(elements.flat());
7438
+ return adjustBindingElements(elements.flat());
5627
7439
  });
5628
7440
  function NestedBindingElements(state) {
5629
7441
  let eventData;
@@ -5810,7 +7622,7 @@ ${input.slice(result.pos)}
5810
7622
  var FunctionDeclaration$0 = $TS($S(FunctionExpression), function($skip, $loc, $0, $1) {
5811
7623
  if ($1.id)
5812
7624
  return $1;
5813
- return module.makeLeftHandSideExpression($1);
7625
+ return makeLeftHandSideExpression($1);
5814
7626
  });
5815
7627
  function FunctionDeclaration(state) {
5816
7628
  let eventData;
@@ -6096,9 +7908,10 @@ ${input.slice(result.pos)}
6096
7908
  return result;
6097
7909
  }
6098
7910
  }
6099
- var AmpersandBlockRHSBody$0 = $TS($S($E($S($N(_), $P(CallExpressionRest))), $E($S($N($EXPECT($R3, fail, "AmpersandBlockRHSBody /[&]/")), $P(BinaryOpRHS)))), function($skip, $loc, $0, $1, $2) {
7911
+ var AmpersandBlockRHSBody$0 = $TS($S($E($S($N(_), $P(CallExpressionRest))), $E(QuestionMark), $E($S($N($EXPECT($R3, fail, "AmpersandBlockRHSBody /[&]/")), $P(BinaryOpRHS)))), function($skip, $loc, $0, $1, $2, $3) {
6100
7912
  var callExpRest = $1;
6101
- var binopRHS = $2;
7913
+ var unaryPostfix = $2;
7914
+ var binopRHS = $3;
6102
7915
  if (!callExpRest && !binopRHS)
6103
7916
  return $skip;
6104
7917
  const ref = {
@@ -6106,7 +7919,7 @@ ${input.slice(result.pos)}
6106
7919
  base: "$",
6107
7920
  id: "$"
6108
7921
  };
6109
- const exp = {
7922
+ let exp = {
6110
7923
  type: "AmpersandRef",
6111
7924
  children: [ref],
6112
7925
  names: [],
@@ -6115,9 +7928,12 @@ ${input.slice(result.pos)}
6115
7928
  if (callExpRest) {
6116
7929
  exp.children.push(...callExpRest[1]);
6117
7930
  }
7931
+ if (unaryPostfix) {
7932
+ exp = processUnaryExpression([], exp, unaryPostfix);
7933
+ }
6118
7934
  if (binopRHS) {
6119
7935
  return {
6120
- children: module.processBinaryOpExpression([exp, binopRHS[1]]),
7936
+ children: processBinaryOpExpression([exp, binopRHS[1]]),
6121
7937
  ref
6122
7938
  };
6123
7939
  }
@@ -8969,7 +10785,7 @@ ${input.slice(result.pos)}
8969
10785
  var statement = $1;
8970
10786
  var post = $2;
8971
10787
  if (post)
8972
- return module.addPostfixStatement(statement, ...post);
10788
+ return addPostfixStatement(statement, ...post);
8973
10789
  return statement;
8974
10790
  });
8975
10791
  function PostfixedStatement(state) {
@@ -8998,7 +10814,7 @@ ${input.slice(result.pos)}
8998
10814
  var expression = $1;
8999
10815
  var post = $2;
9000
10816
  if (post)
9001
- return module.attachPostfixStatementAsExpression(expression, post);
10817
+ return attachPostfixStatementAsExpression(expression, post);
9002
10818
  return expression;
9003
10819
  });
9004
10820
  function PostfixedExpression(state) {
@@ -9027,7 +10843,7 @@ ${input.slice(result.pos)}
9027
10843
  var expression = $1;
9028
10844
  var post = $2;
9029
10845
  if (post)
9030
- return module.attachPostfixStatementAsExpression(expression, post);
10846
+ return attachPostfixStatementAsExpression(expression, post);
9031
10847
  return expression;
9032
10848
  });
9033
10849
  function NonPipelinePostfixedExpression(state) {
@@ -9089,7 +10905,7 @@ ${input.slice(result.pos)}
9089
10905
  var Statement$7 = LabelledStatement;
9090
10906
  var Statement$8 = $TS($S(ExpressionStatement), function($skip, $loc, $0, $1) {
9091
10907
  if ($1.type === "ObjectExpression" || $1.type === "FunctionExpression" && !$1.id) {
9092
- return module.makeLeftHandSideExpression($1);
10908
+ return makeLeftHandSideExpression($1);
9093
10909
  }
9094
10910
  return $1;
9095
10911
  });
@@ -9372,7 +11188,7 @@ ${input.slice(result.pos)}
9372
11188
  var clause = $1;
9373
11189
  var b = $2;
9374
11190
  var e = $3;
9375
- return module.expressionizeIfClause(clause, b, e);
11191
+ return expressionizeIfClause(clause, b, e);
9376
11192
  });
9377
11193
  function IfExpression(state) {
9378
11194
  let eventData;
@@ -9400,7 +11216,7 @@ ${input.slice(result.pos)}
9400
11216
  var clause = $1;
9401
11217
  var b = $2;
9402
11218
  var e = $3;
9403
- return module.expressionizeIfClause(clause, b, e);
11219
+ return expressionizeIfClause(clause, b, e);
9404
11220
  });
9405
11221
  function UnlessExpression(state) {
9406
11222
  let eventData;
@@ -10501,7 +12317,7 @@ ${input.slice(result.pos)}
10501
12317
  var e = $0;
10502
12318
  return {
10503
12319
  type: "SwitchExpression",
10504
- children: module.wrapIIFE(e.children),
12320
+ children: wrapIIFE(e.children),
10505
12321
  expression: e.expression,
10506
12322
  caseBlock: e.caseBlock
10507
12323
  };
@@ -10868,7 +12684,7 @@ ${input.slice(result.pos)}
10868
12684
  return {
10869
12685
  type: "TryExpression",
10870
12686
  blocks: t.blocks,
10871
- children: module.wrapIIFE(t)
12687
+ children: wrapIIFE(t)
10872
12688
  };
10873
12689
  });
10874
12690
  function TryExpression(state) {
@@ -11832,7 +13648,7 @@ ${input.slice(result.pos)}
11832
13648
  var DebuggerExpression$0 = $TS($S(Debugger), function($skip, $loc, $0, $1) {
11833
13649
  return {
11834
13650
  type: "DebuggerExpression",
11835
- children: module.wrapIIFE($1)
13651
+ children: wrapIIFE($1)
11836
13652
  };
11837
13653
  });
11838
13654
  function DebuggerExpression(state) {
@@ -11860,7 +13676,7 @@ ${input.slice(result.pos)}
11860
13676
  var ThrowExpression$0 = $TS($S(Throw, ExtendedExpression), function($skip, $loc, $0, $1, $2) {
11861
13677
  return {
11862
13678
  type: "ThrowExpression",
11863
- children: module.wrapIIFE($0)
13679
+ children: wrapIIFE($0)
11864
13680
  };
11865
13681
  });
11866
13682
  function ThrowExpression(state) {
@@ -13741,7 +15557,7 @@ ${input.slice(result.pos)}
13741
15557
  }
13742
15558
  }
13743
15559
  var TemplateLiteral$0 = $TS($S(TripleTick, $Q($C(TemplateBlockCharacters, TemplateSubstitution)), TripleTick), function($skip, $loc, $0, $1, $2, $3) {
13744
- return module.dedentBlockSubstitutions($0);
15560
+ return dedentBlockSubstitutions($0);
13745
15561
  });
13746
15562
  var TemplateLiteral$1 = $TS($S(Backtick, $Q($C(TemplateCharacters, TemplateSubstitution)), Backtick), function($skip, $loc, $0, $1, $2, $3) {
13747
15563
  return {
@@ -13750,7 +15566,7 @@ ${input.slice(result.pos)}
13750
15566
  };
13751
15567
  });
13752
15568
  var TemplateLiteral$2 = $TS($S(TripleDoubleQuote, $Q($C(TripleDoubleStringCharacters, CoffeeStringSubstitution)), TripleDoubleQuote), function($skip, $loc, $0, $1, $2, $3) {
13753
- return module.dedentBlockSubstitutions($0);
15569
+ return dedentBlockSubstitutions($0);
13754
15570
  });
13755
15571
  var TemplateLiteral$3 = $TS($S(TripleSingleQuote, TripleSingleStringCharacters, TripleSingleQuote), function($skip, $loc, $0, $1, $2, $3) {
13756
15572
  var s = $1;
@@ -13758,7 +15574,7 @@ ${input.slice(result.pos)}
13758
15574
  var e = $3;
13759
15575
  return {
13760
15576
  type: "TemplateLiteral",
13761
- children: [s, module.dedentBlockString(str), e]
15577
+ children: [s, dedentBlockString(str), e]
13762
15578
  };
13763
15579
  });
13764
15580
  var TemplateLiteral$4 = CoffeeInterpolatedDoubleQuotedString;
@@ -16525,7 +18341,7 @@ ${input.slice(result.pos)}
16525
18341
  ],
16526
18342
  jsxChildren: [$1].concat($2.map(([, tag]) => tag))
16527
18343
  };
16528
- const type = module.typeOfJSX(jsx);
18344
+ const type = typeOfJSX(jsx, module.config, module.getRef);
16529
18345
  return type ? [
16530
18346
  { ts: true, children: ["("] },
16531
18347
  jsx,
@@ -17005,7 +18821,7 @@ ${input.slice(result.pos)}
17005
18821
  }
17006
18822
  if (exprs.length === 1) {
17007
18823
  let root = exprs[0];
17008
- while (root.length && module.isWhitespaceOrEmpty(root[root.length - 1])) {
18824
+ while (root.length && isWhitespaceOrEmpty(root[root.length - 1])) {
17009
18825
  root = root.slice(0, -1);
17010
18826
  }
17011
18827
  while (root?.length === 1)
@@ -17085,7 +18901,7 @@ ${input.slice(result.pos)}
17085
18901
  children: [".", id],
17086
18902
  name: id
17087
18903
  };
17088
- const expr = module.processCallMemberExpression({
18904
+ const expr = processCallMemberExpression({
17089
18905
  type: "CallExpression",
17090
18906
  children: [at, access, ...rest.flat()]
17091
18907
  });
@@ -17109,7 +18925,7 @@ ${input.slice(result.pos)}
17109
18925
  var JSXAttribute$4 = $TS($S(Identifier, $P(InlineJSXCallExpressionRest), $Y(JSXAttributeSpace)), function($skip, $loc, $0, $1, $2, $3) {
17110
18926
  var id = $1;
17111
18927
  var rest = $2;
17112
- const expr = module.processCallMemberExpression({
18928
+ const expr = processCallMemberExpression({
17113
18929
  type: "CallExpression",
17114
18930
  children: [id, ...rest.flat()]
17115
18931
  });
@@ -17307,7 +19123,7 @@ ${input.slice(result.pos)}
17307
19123
  }
17308
19124
  var InlineJSXAttributeValue$0 = $TS($S(InlineJSXUnaryExpression, $Q(InlineJSXBinaryOpRHS)), function($skip, $loc, $0, $1, $2) {
17309
19125
  if ($2.length)
17310
- return module.processBinaryOpExpression($0);
19126
+ return processBinaryOpExpression($0);
17311
19127
  return $1;
17312
19128
  });
17313
19129
  function InlineJSXAttributeValue(state) {
@@ -17466,7 +19282,7 @@ ${input.slice(result.pos)}
17466
19282
  var InlineJSXCallExpression$0 = $TS($S($EXPECT($L14, fail, 'InlineJSXCallExpression "super"'), ExplicitArguments, $Q(InlineJSXCallExpressionRest)), function($skip, $loc, $0, $1, $2, $3) {
17467
19283
  var args = $2;
17468
19284
  var rest = $3;
17469
- return module.processCallMemberExpression({
19285
+ return processCallMemberExpression({
17470
19286
  type: "CallExpression",
17471
19287
  children: [
17472
19288
  $1,
@@ -17478,7 +19294,7 @@ ${input.slice(result.pos)}
17478
19294
  var InlineJSXCallExpression$1 = $TS($S($EXPECT($L15, fail, 'InlineJSXCallExpression "import"'), ExplicitArguments, $Q(InlineJSXCallExpressionRest)), function($skip, $loc, $0, $1, $2, $3) {
17479
19295
  var args = $2;
17480
19296
  var rest = $3;
17481
- return module.processCallMemberExpression({
19297
+ return processCallMemberExpression({
17482
19298
  type: "CallExpression",
17483
19299
  children: [
17484
19300
  $1,
@@ -17492,7 +19308,7 @@ ${input.slice(result.pos)}
17492
19308
  var rest = $2;
17493
19309
  if (rest.length) {
17494
19310
  rest = rest.flat();
17495
- return module.processCallMemberExpression({
19311
+ return processCallMemberExpression({
17496
19312
  type: "CallExpression",
17497
19313
  children: [member, ...rest]
17498
19314
  });
@@ -17560,7 +19376,7 @@ ${input.slice(result.pos)}
17560
19376
  var InlineJSXMemberExpression$0 = $TS($S($C(InlineJSXPrimaryExpression, SuperProperty, MetaProperty), $Q(InlineJSXMemberExpressionRest)), function($skip, $loc, $0, $1, $2) {
17561
19377
  var rest = $2;
17562
19378
  if (rest.length || Array.isArray($1)) {
17563
- return module.processCallMemberExpression({
19379
+ return processCallMemberExpression({
17564
19380
  type: "MemberExpression",
17565
19381
  children: [$1, ...rest].flat()
17566
19382
  });
@@ -18653,7 +20469,7 @@ ${input.slice(result.pos)}
18653
20469
  ...block.properties.map((property, i) => {
18654
20470
  let init, isString;
18655
20471
  if (property.init) {
18656
- init = module.replaceNodes(
20472
+ init = replaceNodes(
18657
20473
  deepCopy(property.init),
18658
20474
  (n) => n.type === "Identifier" && names.has(n.name),
18659
20475
  (n) => [id, '["', n.name, '"]']
@@ -19270,7 +21086,10 @@ ${input.slice(result.pos)}
19270
21086
  var dots = $2;
19271
21087
  if (!dots)
19272
21088
  return type;
19273
- return [dots, type];
21089
+ const ws = getTrimmingSpace(type);
21090
+ if (!ws)
21091
+ return [dots[1], dots[0], type];
21092
+ return [ws, dots[1], dots[0], insertTrimmingSpace(type, "")];
19274
21093
  });
19275
21094
  function TypeElement(state) {
19276
21095
  let eventData;
@@ -20995,1987 +22814,215 @@ ${input.slice(result.pos)}
20995
22814
  },
20996
22815
  multiLineImplicitObjectLiteralForbidden: {
20997
22816
  get() {
20998
- const { forbidMultiLineImplicitObjectLiteral: s } = module;
20999
- return s[s.length - 1];
21000
- }
21001
- },
21002
- newlineBinaryOpForbidden: {
21003
- get() {
21004
- const { forbidNewlineBinaryOp: s } = module;
21005
- return s[s.length - 1];
21006
- }
21007
- },
21008
- currentJSXTag: {
21009
- get() {
21010
- const { JSXTagStack: s } = module;
21011
- return s[s.length - 1];
21012
- }
21013
- }
21014
- });
21015
- }
21016
- module.config = parse2.config = {
21017
- autoVar: false,
21018
- autoLet: false,
21019
- coffeeBinaryExistential: false,
21020
- coffeeBooleans: false,
21021
- coffeeClasses: false,
21022
- coffeeComment: false,
21023
- coffeeDo: false,
21024
- coffeeEq: false,
21025
- coffeeForLoops: false,
21026
- coffeeInterpolation: false,
21027
- coffeeIsnt: false,
21028
- coffeeJSX: false,
21029
- coffeeLineContinuation: false,
21030
- coffeeNot: false,
21031
- coffeeOf: false,
21032
- coffeePrototype: false,
21033
- defaultElement: "div",
21034
- implicitReturns: true,
21035
- objectIs: false,
21036
- react: false,
21037
- solid: false,
21038
- client: false,
21039
- rewriteTsImports: true,
21040
- server: false,
21041
- tab: void 0,
21042
- verbose: false
21043
- };
21044
- module.asAny = {
21045
- ts: true,
21046
- children: [" as any"]
21047
- };
21048
- module.asConst = {
21049
- ts: true,
21050
- children: [" as const"]
21051
- };
21052
- module.prelude = [];
21053
- const preludeVar = "var ";
21054
- const declareRef = {
21055
- indexOf(indexOfRef) {
21056
- const typeSuffix = {
21057
- ts: true,
21058
- children: [": <T>(this: T[], searchElement: T) => boolean"]
21059
- };
21060
- module.prelude.push(["", [preludeVar, indexOfRef, typeSuffix, " = [].indexOf", module.asAny, ";\n"]]);
21061
- },
21062
- hasProp(hasPropRef) {
21063
- const typeSuffix = {
21064
- ts: true,
21065
- children: [": <T>(this: T, prop: keyof T) => boolean"]
21066
- };
21067
- module.prelude.push(["", [preludeVar, hasPropRef, typeSuffix, " = {}.hasOwnProperty", module.asAny, ";\n"]]);
21068
- },
21069
- is(isRef) {
21070
- const typeSuffix = {
21071
- ts: true,
21072
- children: [": { <B, A extends B> (a: A, b: B): b is A, <A, B> (a: A, b: B): a is A & B }"]
21073
- };
21074
- module.prelude.push(["", [preludeVar, isRef, typeSuffix, " = Object.is", module.asAny, ";\n"]]);
21075
- },
21076
- modulo(moduloRef) {
21077
- const typeSuffix = {
21078
- ts: true,
21079
- children: [": (a: number, b: number) => number"]
21080
- };
21081
- module.prelude.push(["", [preludeVar, moduloRef, typeSuffix, " = (a, b) => (a % b + b) % b;", "\n"]]);
21082
- },
21083
- xor(xorRef) {
21084
- const typeSuffix = {
21085
- ts: true,
21086
- children: [": (a: unknown, b: unknown) => boolean"]
21087
- };
21088
- module.prelude.push(["", [preludeVar, xorRef, typeSuffix, " = (a, b) => a ? !b && a : b;", "\n"]]);
21089
- },
21090
- xnor(xnorRef) {
21091
- const typeSuffix = {
21092
- ts: true,
21093
- children: [": (a: unknown, b: unknown) => boolean"]
21094
- };
21095
- module.prelude.push(["", [preludeVar, xnorRef, typeSuffix, " = (a, b) => a ? b : !b || a;", "\n"]]);
21096
- },
21097
- returnSymbol(ref) {
21098
- module.prelude.push({
21099
- children: [
21100
- preludeVar,
21101
- ref,
21102
- ` = Symbol("return")';
21103
- `
21104
- ]
21105
- });
21106
- },
21107
- JSX(jsxRef) {
21108
- module.prelude.push({
21109
- ts: true,
21110
- children: [
21111
- "import type { JSX as ",
21112
- jsxRef,
21113
- " } from 'solid-js';\n"
21114
- ]
21115
- });
21116
- },
21117
- IntrinsicElements(intrinsicElementsRef) {
21118
- const JSX = module.getRef("JSX");
21119
- module.prelude.push({
21120
- ts: true,
21121
- children: [
21122
- "type ",
21123
- intrinsicElementsRef,
21124
- "<K extends keyof ",
21125
- JSX,
21126
- ".IntrinsicElements> =\n",
21127
- " ",
21128
- JSX,
21129
- ".IntrinsicElements[K] extends ",
21130
- JSX,
21131
- ".DOMAttributes<infer T> ? T : unknown;\n"
21132
- ]
21133
- });
21134
- }
21135
- };
21136
- const refs = {};
21137
- module.getRef = function(base) {
21138
- if (refs.hasOwnProperty(base))
21139
- return refs[base];
21140
- const ref = {
21141
- type: "Ref",
21142
- base,
21143
- id: base
21144
- };
21145
- if (declareRef.hasOwnProperty(base))
21146
- declareRef[base](ref);
21147
- return refs[base] = ref;
21148
- };
21149
- module.makeAsConst = function(node) {
21150
- if (node.type === "Literal" && node.raw !== "null" || node.type === "ArrayExpression" || node.type === "ObjectExpression") {
21151
- return { ...node, children: [...node.children, module.asConst] };
21152
- }
21153
- return node;
21154
- };
21155
- module.typeOfJSX = function(node) {
21156
- switch (node.type) {
21157
- case "JSXElement":
21158
- return module.typeOfJSXElement(node);
21159
- case "JSXFragment":
21160
- return module.typeOfJSXFragment(node);
21161
- }
21162
- };
21163
- module.typeOfJSXElement = function(node) {
21164
- if (module.config.solid) {
21165
- if (module.config.server && !module.config.client) {
21166
- return ["string"];
21167
- }
21168
- let { tag } = node;
21169
- const clientType = tag[0] === tag[0].toLowerCase() ? [module.getRef("IntrinsicElements"), '<"', tag, '">'] : ["ReturnType<typeof ", tag, ">"];
21170
- if (module.config.server) {
21171
- return ["string", " | ", clientType];
21172
- } else {
21173
- return clientType;
21174
- }
21175
- }
21176
- };
21177
- module.typeOfJSXFragment = function(node) {
21178
- if (module.config.solid) {
21179
- let type = [];
21180
- let lastType;
21181
- for (let child of node.jsxChildren) {
21182
- switch (child.type) {
21183
- case "JSXText":
21184
- if (lastType !== "JSXText") {
21185
- type.push("string");
21186
- }
21187
- break;
21188
- case "JSXElement":
21189
- type.push(module.typeOfJSXElement(child));
21190
- break;
21191
- case "JSXFragment":
21192
- type.push(...module.typeOfJSXFragment(child));
21193
- break;
21194
- case "JSXChildExpression":
21195
- if (child.expression) {
21196
- type.push(["typeof ", child.expression]);
21197
- }
21198
- break;
21199
- default:
21200
- throw new Error(`unknown child in JSXFragment: ${JSON.stringify(child)}`);
21201
- }
21202
- lastType = child.type;
21203
- }
21204
- if (type.length === 1) {
21205
- return type[0];
21206
- } else {
21207
- type = type.flatMap((t) => [t, ", "]);
21208
- type.pop();
21209
- return ["[", type, "]"];
21210
- }
21211
- }
21212
- };
21213
- Object.defineProperty(module.config, "deno", {
21214
- set(b) {
21215
- module.config.rewriteTsImports = !b;
21216
- }
21217
- });
21218
- module.config.deno = typeof Deno !== "undefined";
21219
- Object.defineProperty(module.config, "coffeeCompat", {
21220
- set(b) {
21221
- for (const option of [
21222
- "autoVar",
21223
- "coffeeBinaryExistential",
21224
- "coffeeBooleans",
21225
- "coffeeClasses",
21226
- "coffeeComment",
21227
- "coffeeDo",
21228
- "coffeeEq",
21229
- "coffeeForLoops",
21230
- "coffeeInterpolation",
21231
- "coffeeIsnt",
21232
- "coffeeJSX",
21233
- "coffeeLineContinuation",
21234
- "coffeeNot",
21235
- "coffeeOf",
21236
- "coffeePrototype"
21237
- ]) {
21238
- module.config[option] = b;
21239
- }
21240
- if (b) {
21241
- module.config.objectIs = false;
21242
- }
21243
- }
21244
- });
21245
- });
21246
- function Reset(state) {
21247
- let eventData;
21248
- if (state.events) {
21249
- const result = state.events.enter?.("Reset", state);
21250
- if (result) {
21251
- if (result.cache)
21252
- return result.cache;
21253
- eventData = result.data;
21254
- }
21255
- }
21256
- if (state.tokenize) {
21257
- const result = $TOKEN("Reset", state, Reset$0(state));
21258
- if (state.events)
21259
- state.events.exit?.("Reset", state, result, eventData);
21260
- return result;
21261
- } else {
21262
- const result = Reset$0(state);
21263
- if (state.events)
21264
- state.events.exit?.("Reset", state, result, eventData);
21265
- return result;
21266
- }
21267
- }
21268
- var Init$0 = $TS($S($E(Shebang), $Q(DirectivePrologue), $EXPECT($L0, fail, 'Init ""')), function($skip, $loc, $0, $1, $2, $3) {
21269
- var directives = $2;
21270
- directives.forEach((directive) => {
21271
- if (directive.type === "CivetPrologue") {
21272
- Object.assign(module.config, directive.config);
21273
- }
21274
- });
21275
- module.processCallMemberExpression = (node) => {
21276
- const { children } = node;
21277
- for (let i = 0; i < children.length; i++) {
21278
- const glob = children[i];
21279
- if (glob?.type === "PropertyGlob") {
21280
- const prefix = children.slice(0, i).concat(glob.dot);
21281
- const parts = [];
21282
- for (const part of glob.object.properties) {
21283
- if (part.type === "MethodDefinition") {
21284
- throw new Error("Glob pattern cannot have method definition");
21285
- }
21286
- if (part.value && !["CallExpression", "MemberExpression", "Identifier"].includes(part.value.type)) {
21287
- throw new Error("Glob pattern must have call or member expression value");
21288
- }
21289
- let value = part.value ?? part.name;
21290
- const wValue = getTrimmingSpace(part.value);
21291
- value = prefix.concat(insertTrimmingSpace(value, ""));
21292
- if (wValue)
21293
- value.unshift(wValue);
21294
- if (part.type === "SpreadProperty") {
21295
- parts.push({
21296
- type: part.type,
21297
- value,
21298
- dots: part.dots,
21299
- delim: part.delim,
21300
- names: part.names,
21301
- children: part.children.slice(0, 2).concat(value, part.delim)
21302
- });
21303
- } else {
21304
- parts.push({
21305
- type: part.type === "Identifier" ? "Property" : part.type,
21306
- name: part.name,
21307
- value,
21308
- delim: part.delim,
21309
- names: part.names,
21310
- children: [
21311
- module.isWhitespaceOrEmpty(part.children[0]) && part.children[0],
21312
- part.name,
21313
- module.isWhitespaceOrEmpty(part.children[2]) && part.children[2],
21314
- part.children[3]?.token === ":" ? part.children[3] : ":",
21315
- value,
21316
- part.delim
21317
- ]
21318
- });
21319
- }
21320
- }
21321
- const object = {
21322
- type: "ObjectExpression",
21323
- children: [
21324
- glob.object.children[0],
21325
- ...parts,
21326
- glob.object.children.at(-1)
21327
- ],
21328
- properties: parts
21329
- };
21330
- if (i === children.length - 1)
21331
- return object;
21332
- return module.processCallMemberExpression({
21333
- ...node,
21334
- children: [object, ...children.slice(i + 1)]
21335
- });
21336
- } else if (glob?.type === "PropertyBind") {
21337
- const prefix = children.slice(0, i);
21338
- return module.processCallMemberExpression({
21339
- ...node,
21340
- children: [
21341
- prefix,
21342
- {
21343
- ...glob,
21344
- type: "PropertyAccess",
21345
- children: [...glob.children, ".bind(", prefix, ")"]
21346
- },
21347
- ...children.slice(i + 1)
21348
- ]
21349
- });
21350
- }
21351
- }
21352
- return node;
21353
- };
21354
- module.needsRef = function(expression, base = "ref") {
21355
- switch (expression.type) {
21356
- case "Ref":
21357
- case "Identifier":
21358
- case "Literal":
21359
- return;
21360
- default:
21361
- return {
21362
- type: "Ref",
21363
- base,
21364
- id: base
21365
- };
21366
- }
21367
- };
21368
- module.expressionizeIfClause = function(clause, b, e) {
21369
- const children = clause.children.slice(1);
21370
- children.push("?", b);
21371
- if (e) {
21372
- children.push(e[0], ":", ...e.slice(2));
21373
- } else {
21374
- children.push(":void 0");
21375
- }
21376
- return {
21377
- type: "IfExpression",
21378
- children
21379
- };
21380
- };
21381
- module.addPostfixStatement = function(statement, ws, post) {
21382
- let children, expressions;
21383
- if (post.blockPrefix?.length) {
21384
- let indent = post.blockPrefix[0][0];
21385
- expressions = [...post.blockPrefix, [indent, statement]];
21386
- children = [" {\n", ...expressions, "\n", indent?.slice?.(0, -2), "}"];
21387
- } else {
21388
- expressions = [["", statement]];
21389
- children = [" { ", ...expressions, " }"];
21390
- }
21391
- const block = {
21392
- type: "BlockStatement",
21393
- children,
21394
- expressions
21395
- };
21396
- children = [...post.children];
21397
- children.push(block);
21398
- if (!module.isWhitespaceOrEmpty(ws))
21399
- children.push(ws);
21400
- post = { ...post, children, block };
21401
- if (post.type === "IfStatement") {
21402
- post.then = block;
21403
- }
21404
- return post;
21405
- };
21406
- function expressionizeIteration(exp) {
21407
- const i = exp.children.indexOf(exp.block);
21408
- if (exp.subtype === "DoStatement") {
21409
- insertReturn(exp.block);
21410
- exp.children.splice(i, 1, ...module.wrapIIFE(exp.children, exp.async));
21411
- return;
21412
- }
21413
- const resultsRef = {
21414
- type: "Ref",
21415
- base: "results",
21416
- id: "results"
21417
- };
21418
- insertPush(exp.block, resultsRef);
21419
- exp.children.splice(
21420
- i,
21421
- 1,
21422
- module.wrapIIFE([
21423
- "const ",
21424
- resultsRef,
21425
- "=[];",
21426
- ...exp.children,
21427
- "; return ",
21428
- resultsRef
21429
- ], exp.async)
21430
- );
21431
- }
21432
- module.wrapIIFE = (exp, async) => {
21433
- let prefix, suffix;
21434
- if (async) {
21435
- prefix = "(async ()=>{";
21436
- suffix = "})()";
21437
- } else if (hasAwait(exp)) {
21438
- prefix = "(await (async ()=>{";
21439
- suffix = "})())";
21440
- } else {
21441
- prefix = "(()=>{";
21442
- suffix = "})()";
21443
- }
21444
- if (Array.isArray(exp)) {
21445
- return [prefix, ...exp, suffix];
21446
- } else {
21447
- return [prefix, exp, suffix];
21448
- }
21449
- };
21450
- function wrapIterationReturningResults(statement, outerRef) {
21451
- if (statement.type === "DoStatement") {
21452
- if (outerRef) {
21453
- insertPush(statement.block, outerRef);
21454
- } else {
21455
- insertReturn(statement.block);
21456
- }
21457
- return;
21458
- }
21459
- const resultsRef = {
21460
- type: "Ref",
21461
- base: "results",
21462
- id: "results"
21463
- };
21464
- const declaration = {
21465
- type: "Declaration",
21466
- children: ["const ", resultsRef, "=[];"]
21467
- };
21468
- insertPush(statement.block, resultsRef);
21469
- statement.children.unshift(declaration);
21470
- if (outerRef) {
21471
- statement.children.push(";", outerRef, ".push(", resultsRef, ");");
21472
- } else {
21473
- statement.children.push(";return ", resultsRef, ";");
21474
- }
21475
- }
21476
- function insertPush(node, ref) {
21477
- if (!node)
21478
- return;
21479
- switch (node.type) {
21480
- case "BlockStatement":
21481
- if (node.expressions.length) {
21482
- const last = node.expressions[node.expressions.length - 1];
21483
- insertPush(last, ref);
21484
- } else {
21485
- node.expressions.push([ref, ".push(void 0);"]);
21486
- }
21487
- return;
21488
- case "CaseBlock":
21489
- node.clauses.forEach((clause) => {
21490
- insertPush(clause, ref);
21491
- });
21492
- return;
21493
- case "WhenClause":
21494
- insertPush(node.block, ref);
21495
- return;
21496
- case "DefaultClause":
21497
- insertPush(node.block, ref);
21498
- return;
21499
- }
21500
- if (!Array.isArray(node))
21501
- return;
21502
- const [, exp] = node;
21503
- if (!exp)
21504
- return;
21505
- const indent = getIndent(node);
21506
- switch (exp.type) {
21507
- case "BreakStatement":
21508
- case "ContinueStatement":
21509
- case "DebuggerStatement":
21510
- case "EmptyStatement":
21511
- case "ReturnStatement":
21512
- case "ThrowStatement":
21513
- case "Declaration":
21514
- return;
21515
- case "ForStatement":
21516
- case "IterationStatement":
21517
- case "DoStatement":
21518
- wrapIterationReturningResults(exp, ref);
21519
- return;
21520
- case "BlockStatement":
21521
- insertPush(exp.expressions[exp.expressions.length - 1], ref);
21522
- return;
21523
- case "IfStatement":
21524
- insertPush(exp.then, ref);
21525
- if (exp.else)
21526
- insertPush(exp.else[2], ref);
21527
- else
21528
- exp.children.push([" else {\n", indent, ref, ".push(undefined)\n", indent, "}"]);
21529
- return;
21530
- case "PatternMatchingStatement":
21531
- insertPush(exp.children[0][0], ref);
21532
- return;
21533
- case "SwitchStatement":
21534
- insertPush(exp.children[2], ref);
21535
- return;
21536
- case "TryStatement":
21537
- exp.blocks.forEach((block) => insertPush(block, ref));
21538
- return;
21539
- }
21540
- if (node[node.length - 1]?.type === "SemicolonDelimiter")
21541
- return;
21542
- node.splice(1, 0, ref, ".push(");
21543
- node.push(")");
21544
- }
21545
- function wrapWithReturn(expression) {
21546
- const children = expression ? ["return ", expression] : ["return"];
21547
- return {
21548
- type: "ReturnStatement",
21549
- children
21550
- };
21551
- }
21552
- function insertSwitchReturns(exp) {
21553
- switch (exp.type) {
21554
- case "SwitchStatement":
21555
- exp.caseBlock.clauses.forEach((clause) => {
21556
- insertReturn(clause);
21557
- });
21558
- return;
21559
- case "SwitchExpression":
21560
- exp.caseBlock.clauses.forEach(insertReturn);
21561
- return;
21562
- }
21563
- }
21564
- function insertReturn(node) {
21565
- if (!node)
21566
- return;
21567
- switch (node.type) {
21568
- case "BlockStatement":
21569
- if (node.expressions.length) {
21570
- const last = node.expressions[node.expressions.length - 1];
21571
- insertReturn(last);
21572
- } else {
21573
- if (node.parent.type === "CatchClause") {
21574
- node.expressions.push(["return"]);
21575
- }
21576
- }
21577
- return;
21578
- case "WhenClause":
21579
- node.children.splice(node.children.indexOf(node.break), 1);
21580
- if (node.block.expressions.length) {
21581
- insertReturn(node.block);
21582
- } else {
21583
- node.block.expressions.push(wrapWithReturn());
21584
- }
21585
- return;
21586
- case "DefaultClause":
21587
- insertReturn(node.block);
21588
- return;
21589
- }
21590
- if (!Array.isArray(node))
21591
- return;
21592
- const [, exp, semi] = node;
21593
- if (semi?.type === "SemicolonDelimiter")
21594
- return;
21595
- let indent = getIndent(node);
21596
- if (!exp)
21597
- return;
21598
- switch (exp.type) {
21599
- case "BreakStatement":
21600
- case "ContinueStatement":
21601
- case "DebuggerStatement":
21602
- case "EmptyStatement":
21603
- case "ReturnStatement":
21604
- case "ThrowStatement":
21605
- case "Declaration":
21606
- return;
21607
- case "ForStatement":
21608
- case "IterationStatement":
21609
- case "DoStatement":
21610
- wrapIterationReturningResults(exp);
21611
- return;
21612
- case "BlockStatement":
21613
- insertReturn(exp.expressions[exp.expressions.length - 1]);
21614
- return;
21615
- case "IfStatement":
21616
- insertReturn(exp.then);
21617
- if (exp.else)
21618
- insertReturn(exp.else[2]);
21619
- else
21620
- exp.children.push(["", {
21621
- type: "ReturnStatement",
21622
- children: [";return"]
21623
- }]);
21624
- return;
21625
- case "PatternMatchingStatement":
21626
- insertReturn(exp.children[0][0]);
21627
- return;
21628
- case "SwitchStatement":
21629
- insertSwitchReturns(exp);
21630
- return;
21631
- case "TryStatement":
21632
- exp.blocks.forEach((block) => insertReturn(block));
21633
- return;
21634
- }
21635
- if (node[node.length - 1]?.type === "SemicolonDelimiter")
21636
- return;
21637
- const returnStatement = wrapWithReturn(node[1]);
21638
- node.splice(1, 1, returnStatement);
21639
- }
21640
- module.makeLeftHandSideExpression = function(expression) {
21641
- switch (expression.type) {
21642
- case "Ref":
21643
- case "Identifier":
21644
- case "Literal":
21645
- case "CallExpression":
21646
- case "MemberExpression":
21647
- case "ParenthesizedExpression":
21648
- return expression;
21649
- default:
21650
- return {
21651
- type: "ParenthesizedExpression",
21652
- children: ["(", expression, ")"],
21653
- expression
21654
- };
21655
- }
21656
- };
21657
- module.isWhitespaceOrEmpty = function(node) {
21658
- if (!node)
21659
- return true;
21660
- if (node.type === "Ref")
21661
- return false;
21662
- if (node.token)
21663
- return node.token.match(/^\s*$/);
21664
- if (node.children)
21665
- node = node.children;
21666
- if (!node.length)
21667
- return true;
21668
- if (typeof node === "string")
21669
- return node.match(/^\s*$/);
21670
- if (Array.isArray(node))
21671
- return node.every(module.isWhitespaceOrEmpty);
21672
- };
21673
- module.isTemplateLiteral = function(node) {
21674
- let s = node;
21675
- while (s && s[0] && !s.token)
21676
- s = s[0];
21677
- return s.token?.startsWith?.("`");
21678
- };
21679
- module.isEmptyBareBlock = function(node) {
21680
- if (node?.type !== "BlockStatement")
21681
- return false;
21682
- const { bare, expressions } = node;
21683
- return bare && (expressions.length === 0 || expressions.length === 1 && expressions[0][1]?.type === "EmptyStatement");
21684
- };
21685
- module.processBinaryOpExpression = function($02) {
21686
- const expandedOps = module.expandChainedComparisons($02);
21687
- let i = 2;
21688
- while (i < expandedOps.length) {
21689
- const op = expandedOps[i];
21690
- if (op.special) {
21691
- let [a, wsOp, op2, wsB, b] = expandedOps.slice(i - 2, i + 3);
21692
- if (op2.token === "instanceof" && b.type === "Literal" && b.children?.[0]?.type === "StringLiteral") {
21693
- a = ["typeof ", module.makeLeftHandSideExpression(a)];
21694
- if (op2.negated) {
21695
- op2 = { ...op2, token: "!==", negated: false };
21696
- } else {
21697
- op2 = { ...op2, token: "===" };
21698
- }
21699
- }
21700
- if (op2.asConst) {
21701
- a = module.makeAsConst(a);
21702
- b = module.makeAsConst(b);
21703
- }
21704
- let children;
21705
- if (op2.call) {
21706
- wsOp = insertTrimmingSpace(wsOp, "");
21707
- if (op2.reversed) {
21708
- wsB = insertTrimmingSpace(wsB, "");
21709
- children = [wsOp, op2.call, "(", wsB, b, ", ", a, ")", op2.suffix];
21710
- } else {
21711
- children = [wsOp, op2.call, "(", a, ",", wsB, b, ")", op2.suffix];
21712
- }
21713
- } else if (op2.method) {
21714
- wsOp = insertTrimmingSpace(wsOp, "");
21715
- wsB = insertTrimmingSpace(wsB, "");
21716
- if (op2.reversed) {
21717
- children = [wsB, b, wsOp, ".", op2.method, "(", a, ")"];
21718
- } else {
21719
- children = [a, wsOp, ".", op2.method, "(", wsB, b, ")"];
21720
- }
21721
- } else if (op2.token) {
21722
- children = [a, wsOp, op2, wsB, b];
21723
- if (op2.negated)
21724
- children = ["(", ...children, ")"];
21725
- } else {
21726
- throw new Error("Unknown operator: " + JSON.stringify(op2));
21727
- }
21728
- if (op2.negated)
21729
- children.unshift("!");
21730
- expandedOps.splice(i - 2, 5, {
21731
- children
21732
- });
21733
- } else {
21734
- i += 4;
21735
- }
21736
- }
21737
- return expandedOps;
21738
- };
21739
- module.expandChainedComparisons = function([first, binops]) {
21740
- const relationalOps = ["==", "===", "!=", "!==", "<", "<=", ">", ">=", "in"];
21741
- const lowerPrecedenceOps = ["??", "&&", "||", "&", "|", "^"];
21742
- let results = [];
21743
- let i = 0;
21744
- let l = binops.length;
21745
- let start = 0;
21746
- let chains = [];
21747
- while (i < l) {
21748
- const [, op] = binops[i];
21749
- if (relationalOps.includes(op.token) || op.relational) {
21750
- chains.push(i);
21751
- } else if (lowerPrecedenceOps.includes(op.token)) {
21752
- processChains();
21753
- first = [];
21754
- }
21755
- i++;
21756
- }
21757
- processChains();
21758
- return results;
21759
- function processChains() {
21760
- if (chains.length > 1) {
21761
- chains.forEach((index, k) => {
21762
- if (k > 0) {
21763
- results.push(" ", "&&", " ");
21764
- }
21765
- const [pre, op, post, exp] = binops[index];
21766
- let endIndex;
21767
- if (k < chains.length - 1) {
21768
- endIndex = chains[k + 1];
21769
- } else {
21770
- endIndex = i + 1;
21771
- }
21772
- results = results.concat(first, ...binops.slice(start, endIndex));
21773
- first = [exp].concat(binops.slice(index + 1, endIndex));
21774
- start = endIndex;
21775
- });
21776
- } else {
21777
- results = results.concat(first, ...binops.slice(start, i + 1));
21778
- start = i + 1;
21779
- }
21780
- chains.length = 0;
21781
- }
21782
- };
21783
- module.parsePosition = function() {
21784
- let s = Error().stack.split(/\n at /);
21785
- s.shift();
21786
- s = s.filter((e) => !e.match(/^eval/)).map((e) => e.split(" ")[0]);
21787
- s = s.slice(1, s.indexOf("Program") + 1);
21788
- return s;
21789
- };
21790
- module.prune = function(node) {
21791
- if (node === null || node === void 0)
21792
- return;
21793
- if (node.length === 0)
21794
- return;
21795
- if (Array.isArray(node)) {
21796
- const a = node.map((n) => module.prune(n)).filter((n) => !!n);
21797
- if (a.length > 1)
21798
- return a;
21799
- if (a.length === 1)
21800
- return a[0];
21801
- return;
21802
- }
21803
- if (node.children != null) {
21804
- node.children = module.prune(node.children);
21805
- return node;
21806
- }
21807
- return node;
21808
- };
21809
- module.skipIfOnlyWS = function(target) {
21810
- if (!target)
21811
- return target;
21812
- if (Array.isArray(target)) {
21813
- if (target.length === 1) {
21814
- return module.skipIfOnlyWS(target[0]);
21815
- } else if (target.every((e) => module.skipIfOnlyWS(e) === void 0)) {
21816
- return void 0;
21817
- }
21818
- return target;
21819
- }
21820
- if (target.token != null && target.token.trim() === "") {
21821
- return void 0;
21822
- }
21823
- return target;
21824
- };
21825
- const initialSpacingRe = /^(?:\r?\n|\n)*((?:\r?\n|\n)\s+)/;
21826
- module.dedentBlockSubstitutions = function($02) {
21827
- const [s, strWithSubstitutions, e] = $02;
21828
- if (strWithSubstitutions.length === 0) {
21829
- return $02;
21830
- }
21831
- let initialSpacing, i = 0, l = strWithSubstitutions.length, results = [s];
21832
- const { token } = strWithSubstitutions[0];
21833
- if (token) {
21834
- initialSpacing = token.match(initialSpacingRe);
21835
- } else {
21836
- initialSpacing = false;
21837
- }
21838
- while (i < l) {
21839
- let segment = strWithSubstitutions[i];
21840
- if (segment.token) {
21841
- segment = module.dedentBlockString(segment, initialSpacing, false);
21842
- if (i === 0) {
21843
- segment.token = segment.token.replace(/^(\r?\n|\n)/, "");
21844
- }
21845
- if (i === l - 1) {
21846
- segment.token = segment.token.replace(/(\r?\n|\n)[ \t]*$/, "");
21847
- }
21848
- results.push(segment);
21849
- } else {
21850
- results.push(segment);
21851
- }
21852
- i++;
21853
- }
21854
- results.push(e);
21855
- return {
21856
- type: "TemplateLiteral",
21857
- children: results
21858
- };
21859
- };
21860
- module.dedentBlockString = function({ $loc: $loc2, token: str }, spacing, trim = true) {
21861
- if (spacing == null)
21862
- spacing = str.match(initialSpacingRe);
21863
- if (spacing) {
21864
- str = str.replaceAll(spacing[1], "\n");
21865
- const l = spacing.length;
21866
- $loc2.pos += l;
21867
- $loc2.length -= l;
21868
- }
21869
- if (trim) {
21870
- str = str.replace(/^(\r?\n|\n)/, "").replace(/(\r?\n|\n)[ \t]*$/, "");
21871
- }
21872
- str = str.replace(/(\\.|`|\$\{)/g, (s) => {
21873
- if (s[0] === "\\") {
21874
- return s;
21875
- }
21876
- return `\\${s}`;
21877
- });
21878
- return {
21879
- $loc: $loc2,
21880
- token: str
21881
- };
21882
- };
21883
- module.adjustBindingElements = function(elements) {
21884
- const names = elements.flatMap((p) => p.names || []), { length } = elements;
21885
- let blockPrefix, restIndex = -1, restCount = 0;
21886
- elements.forEach(({ type }, i) => {
21887
- if (type === "BindingRestElement") {
21888
- if (restIndex < 0)
21889
- restIndex = i;
21890
- restCount++;
21891
- }
21892
- });
21893
- if (restCount === 0) {
21894
- return {
21895
- children: elements,
21896
- names,
21897
- blockPrefix,
21898
- length
21899
- };
21900
- } else if (restCount === 1) {
21901
- const rest = elements[restIndex];
21902
- const after = elements.slice(restIndex + 1);
21903
- const restIdentifier = rest.binding.ref || rest.binding;
21904
- names.push(...rest.names || []);
21905
- if (after.length) {
21906
- blockPrefix = {
21907
- type: "PostRestBindingElements",
21908
- children: ["[", insertTrimmingSpace(after, ""), "] = ", restIdentifier, ".splice(-", after.length.toString(), ")"],
21909
- names: after.flatMap((p) => p.names)
21910
- };
21911
- }
21912
- return {
21913
- names,
21914
- children: [...elements.slice(0, restIndex), {
21915
- ...rest,
21916
- children: rest.children.slice(0, -1)
21917
- }],
21918
- blockPrefix,
21919
- length
21920
- };
21921
- }
21922
- const err = {
21923
- type: "Error",
21924
- children: ["Multiple rest elements in array pattern"]
21925
- };
21926
- return {
21927
- names,
21928
- children: [...elements, err],
21929
- blockPrefix,
21930
- length
21931
- };
21932
- };
21933
- module.reorderBindingRestProperty = function(props) {
21934
- const names = props.flatMap((p) => p.names);
21935
- let restIndex = -1;
21936
- let restCount = 0;
21937
- props.forEach(({ type }, i) => {
21938
- if (type === "BindingRestProperty") {
21939
- if (restIndex < 0)
21940
- restIndex = i;
21941
- restCount++;
21942
- }
21943
- });
21944
- if (restCount === 0) {
21945
- return {
21946
- children: props,
21947
- names
21948
- };
21949
- } else if (restCount === 1) {
21950
- let after = props.slice(restIndex + 1);
21951
- let rest = props[restIndex];
21952
- props = props.slice(0, restIndex);
21953
- if (after.length) {
21954
- const [restDelim] = rest.children.slice(-1), lastAfterProp = after[after.length - 1], lastAfterChildren = lastAfterProp.children, [lastDelim] = lastAfterChildren.slice(-1);
21955
- rest = { ...rest, children: [...rest.children.slice(0, -1), lastDelim] };
21956
- after = [...after.slice(0, -1), { ...lastAfterProp, children: [...lastAfterChildren.slice(0, -1), restDelim] }];
21957
- }
21958
- const children = [...props, ...after, rest];
21959
- return {
21960
- children,
21961
- names
21962
- };
21963
- }
21964
- return {
21965
- children: [{
21966
- type: "Error",
21967
- message: "Multiple rest properties in object pattern"
21968
- }, props]
21969
- };
21970
- };
21971
- function addParentPointers(node, parent) {
21972
- if (node == null)
21973
- return;
21974
- if (typeof node !== "object")
21975
- return;
21976
- if (Array.isArray(node)) {
21977
- for (const child of node) {
21978
- addParentPointers(child, parent);
21979
- }
21980
- return;
21981
- }
21982
- node.parent = parent;
21983
- if (node.children) {
21984
- for (const child of node.children) {
21985
- addParentPointers(child, node);
21986
- }
21987
- }
21988
- }
21989
- module.replaceNodes = (root, predicate, replacer) => {
21990
- if (root == null)
21991
- return root;
21992
- const array = Array.isArray(root) ? root : root.children;
21993
- if (!array)
21994
- return root;
21995
- array.forEach((node, i) => {
21996
- if (node == null)
21997
- return;
21998
- if (predicate(node)) {
21999
- array[i] = replacer(node, root);
22000
- } else {
22001
- module.replaceNodes(node, predicate, replacer);
22002
- }
22003
- });
22004
- return root;
22005
- };
22006
- function processParams(f) {
22007
- const { type, parameters, block } = f;
22008
- if (type === "ArrowFunction" && parameters && parameters.tp && parameters.tp.parameters.length === 1) {
22009
- parameters.tp.parameters.push(",");
22010
- }
22011
- if (!block)
22012
- return;
22013
- const { expressions } = block;
22014
- if (!expressions)
22015
- return;
22016
- const { blockPrefix } = parameters;
22017
- let indent;
22018
- if (!expressions.length) {
22019
- indent = "";
22020
- } else {
22021
- indent = expressions[0][0];
22022
- }
22023
- const [splices, thisAssignments] = gatherBindingCode(parameters, {
22024
- injectParamProps: f.name === "constructor"
22025
- });
22026
- const delimiter = {
22027
- type: "SemicolonDelimiter",
22028
- children: [";"]
22029
- };
22030
- const prefix = splices.map((s) => ["let ", s]).concat(thisAssignments).map(
22031
- (s) => s.type ? {
22032
- ...s,
22033
- children: [indent, ...s.children, delimiter]
22034
- } : [indent, s, delimiter]
22035
- );
22036
- expressions.unshift(...prefix);
22037
- }
22038
- function adjustAtBindings(statements, asThis = false) {
22039
- gatherRecursiveAll(statements, (n) => n.type === "AtBindingProperty").forEach((binding) => {
22040
- const { ref } = binding;
22041
- if (asThis) {
22042
- const atBinding = binding.binding;
22043
- atBinding.children.pop();
22044
- atBinding.type = void 0;
22045
- binding.children.unshift(ref.id, ": this.", ref.base);
22046
- binding.type = "Property";
22047
- binding.ref = void 0;
22048
- return;
22049
- }
22050
- if (ref.names[0] !== ref.base) {
22051
- binding.children.unshift(ref.base, ": ");
22052
- }
22053
- });
22054
- }
22055
- function processReturnValue(func) {
22056
- const { block } = func;
22057
- const values = gatherRecursiveWithinFunction(
22058
- block,
22059
- ({ type }) => type === "ReturnValue"
22060
- );
22061
- if (!values.length)
22062
- return false;
22063
- const ref = {
22064
- type: "Ref",
22065
- base: "ret",
22066
- id: "ret"
22067
- };
22068
- let declared;
22069
- values.forEach((value) => {
22070
- value.children = [ref];
22071
- const ancestor = findAncestor(
22072
- value,
22073
- ({ type }) => type === "Declaration",
22074
- isFunction
22075
- );
22076
- if (ancestor)
22077
- declared = true;
22078
- });
22079
- if (!declared) {
22080
- let returnType = func.returnType ?? func.signature?.returnType;
22081
- if (returnType) {
22082
- const { t } = returnType;
22083
- if (t.type === "TypePredicate") {
22084
- returnType = ": boolean";
22085
- } else if (t.type === "AssertsType") {
22086
- returnType = void 0;
22087
- }
22088
- }
22089
- block.expressions.unshift([
22090
- getIndent(block.expressions[0]),
22091
- {
22092
- type: "Declaration",
22093
- children: ["let ", ref, returnType],
22094
- names: []
22095
- },
22096
- ";"
22097
- ]);
22098
- }
22099
- gatherRecursiveWithinFunction(
22100
- block,
22101
- (r) => r.type === "ReturnStatement" && !r.expression
22102
- ).forEach((r) => {
22103
- r.expression = ref;
22104
- r.children.splice(-1, 1, " ", ref);
22105
- });
22106
- if (block.children.at(-2)?.type !== "ReturnStatement") {
22107
- block.expressions.push([
22108
- [getIndent(block.expressions.at(-1))],
22109
- {
22110
- type: "ReturnStatement",
22111
- expression: ref,
22112
- children: ["return ", ref]
22113
- }
22114
- ]);
22115
- }
22116
- return true;
22117
- }
22118
- function isVoidType(t) {
22119
- return t?.type === "LiteralType" && t.t.type === "VoidType";
22120
- }
22121
- function processFunctions(statements) {
22122
- gatherRecursiveAll(statements, ({ type }) => type === "FunctionExpression" || type === "ArrowFunction").forEach((f) => {
22123
- processParams(f);
22124
- if (!processReturnValue(f) && module.config.implicitReturns) {
22125
- const { block, returnType } = f;
22126
- const isVoid = isVoidType(returnType?.t);
22127
- const isBlock = block?.type === "BlockStatement";
22128
- if (!isVoid && isBlock) {
22129
- insertReturn(block);
22130
- }
22131
- }
22132
- });
22133
- gatherRecursiveAll(statements, ({ type }) => type === "MethodDefinition").forEach((f) => {
22134
- processParams(f);
22135
- if (!processReturnValue(f) && module.config.implicitReturns) {
22136
- const { signature, block } = f;
22137
- const isConstructor = signature.name === "constructor";
22138
- const isVoid = isVoidType(signature.returnType?.t);
22139
- const isSet = signature.modifier?.set;
22140
- if (!isConstructor && !isSet && !isVoid) {
22141
- insertReturn(block);
22142
- }
22143
- }
22144
- });
22145
- }
22146
- function processSwitchExpressions(statements) {
22147
- if (module.config.implicitReturns) {
22148
- gatherRecursiveAll(statements, (n) => n.type === "SwitchExpression").forEach(insertSwitchReturns);
22149
- }
22150
- }
22151
- function processTryExpressions(statements) {
22152
- if (module.config.implicitReturns) {
22153
- gatherRecursiveAll(statements, (n) => n.type === "TryExpression").forEach(({ blocks }) => {
22154
- blocks.forEach(insertReturn);
22155
- });
22156
- }
22157
- }
22158
- function processBindingPatternLHS(lhs, tail) {
22159
- adjustAtBindings(lhs, true);
22160
- const [splices, thisAssignments] = gatherBindingCode(lhs);
22161
- tail.push(...splices.map((s) => [", ", s]), ...thisAssignments.map((a) => [", ", a]));
22162
- }
22163
- function processAssignments(statements) {
22164
- gatherRecursiveAll(statements, (n) => n.type === "AssignmentExpression" && n.names === null).forEach((exp) => {
22165
- let { lhs: $12, exp: $22 } = exp, tail = [], i = 0, len = $12.length;
22166
- if ($12.some((left) => left[left.length - 1].special)) {
22167
- if ($12.length !== 1) {
22168
- throw new Error("Only one assignment with id= is allowed");
22169
- }
22170
- const [, lhs, , op] = $12[0];
22171
- const { call } = op;
22172
- op[op.length - 1] = "=";
22173
- $22 = [call, "(", lhs, ", ", $22, ")"];
22174
- }
22175
- let wrapped = false;
22176
- while (i < len) {
22177
- const lastAssignment = $12[i++];
22178
- const [, lhs, , op] = lastAssignment;
22179
- if (op.token !== "=")
22180
- continue;
22181
- if (lhs.type === "ObjectExpression" || lhs.type === "ObjectBindingPattern") {
22182
- if (!wrapped) {
22183
- wrapped = true;
22184
- lhs.children.splice(0, 0, "(");
22185
- tail.push(")");
22186
- }
22187
- }
22188
- }
22189
- i = len - 1;
22190
- while (i >= 0) {
22191
- const lastAssignment = $12[i];
22192
- if (lastAssignment[3].token === "=") {
22193
- const lhs = lastAssignment[1];
22194
- if (lhs.type === "MemberExpression") {
22195
- const members = lhs.children;
22196
- const lastMember = members[members.length - 1];
22197
- if (lastMember.type === "SliceExpression") {
22198
- const { start, end, children: c } = lastMember;
22199
- c[0].token = ".splice(";
22200
- c[1] = start;
22201
- c[2] = ", ";
22202
- if (end)
22203
- c[3] = [end, " - ", start];
22204
- else
22205
- c[3] = ["1/0"];
22206
- c[4] = [", ...", $22];
22207
- c[5] = ")";
22208
- lastAssignment.pop();
22209
- if (module.isWhitespaceOrEmpty(lastAssignment[2]))
22210
- lastAssignment.pop();
22211
- if ($12.length > 1) {
22212
- throw new Error("Not implemented yet! TODO: Handle multiple splice assignments");
22213
- }
22214
- exp.children = [$12];
22215
- exp.names = [];
22216
- return;
22217
- }
22218
- } else if (lhs.type === "ObjectBindingPattern" || lhs.type === "ArrayBindingPattern") {
22219
- processBindingPatternLHS(lhs, tail);
22220
- }
22221
- }
22222
- i--;
22223
- }
22224
- const names = $12.flatMap(([, l]) => l.names || []);
22225
- exp.children = [$12, $22, ...tail];
22226
- exp.names = names;
22227
- });
22228
- gatherRecursiveAll(statements, (n) => n.type === "AssignmentExpression" || n.type === "UpdateExpression").forEach((exp) => {
22229
- function extractAssignment(lhs) {
22230
- let expr = lhs;
22231
- while (expr.type === "ParenthesizedExpression") {
22232
- expr = expr.expression;
22233
- }
22234
- if (expr.type === "AssignmentExpression" || expr.type === "UpdateExpression") {
22235
- if (expr.type === "UpdateExpression" && expr.children[0] === expr.assigned) {
22236
- post.push([", ", lhs]);
22237
- } else {
22238
- pre.push([lhs, ", "]);
22239
- }
22240
- return expr.assigned;
22241
- }
22242
- }
22243
- const pre = [], post = [];
22244
- switch (exp.type) {
22245
- case "AssignmentExpression":
22246
- if (!exp.lhs)
22247
- return;
22248
- exp.lhs.forEach((lhsPart, i) => {
22249
- let newLhs2 = extractAssignment(lhsPart[1]);
22250
- if (newLhs2) {
22251
- lhsPart[1] = newLhs2;
22252
- }
22253
- });
22254
- break;
22255
- case "UpdateExpression":
22256
- let newLhs = extractAssignment(exp.assigned);
22257
- if (newLhs) {
22258
- const i = exp.children.indexOf(exp.assigned);
22259
- exp.assigned = exp.children[i] = newLhs;
22260
- }
22261
- break;
22262
- }
22263
- if (pre.length)
22264
- exp.children.unshift(...pre);
22265
- if (post.length)
22266
- exp.children.push(...post);
22267
- });
22268
- }
22269
- module.attachPostfixStatementAsExpression = function(exp, post) {
22270
- let clause;
22271
- switch (post[1].type) {
22272
- case "ForStatement":
22273
- case "IterationStatement":
22274
- case "DoStatement":
22275
- clause = module.addPostfixStatement(exp, ...post);
22276
- return {
22277
- type: "IterationExpression",
22278
- children: [clause],
22279
- block: clause.block
22280
- };
22281
- case "IfStatement":
22282
- clause = module.expressionizeIfClause(post[1], exp);
22283
- return clause;
22284
- default:
22285
- throw new Error("Unknown postfix statement");
22286
- }
22287
- };
22288
- function getPatternConditions(pattern, ref, conditions) {
22289
- if (pattern.rest)
22290
- return;
22291
- switch (pattern.type) {
22292
- case "ArrayBindingPattern": {
22293
- const { elements, length } = pattern, hasRest = elements.some((e) => e.rest), comparator = hasRest ? " >= " : " === ", l = [comparator, (length - hasRest).toString()];
22294
- conditions.push(
22295
- ["Array.isArray(", ref, ")"],
22296
- [ref, ".length", l]
22297
- );
22298
- elements.forEach(({ children: [, e] }, i) => {
22299
- const subRef = [ref, "[", i.toString(), "]"];
22300
- getPatternConditions(e, subRef, conditions);
22301
- });
22302
- const postRest = pattern.children.find((c) => c?.blockPrefix);
22303
- if (postRest) {
22304
- const postElements = postRest.blockPrefix.children[1], { length: postLength } = postElements;
22305
- postElements.forEach(({ children: [, e] }, i) => {
22306
- const subRef = [ref, "[", ref, ".length - ", (postLength + i).toString(), "]"];
22307
- getPatternConditions(e, subRef, conditions);
22308
- });
22309
- }
22310
- break;
22311
- }
22312
- case "ObjectBindingPattern": {
22313
- conditions.push(
22314
- ["typeof ", ref, " === 'object'"],
22315
- [ref, " != null"]
22316
- );
22317
- pattern.properties.forEach((p) => {
22318
- switch (p.type) {
22319
- case "PinProperty":
22320
- case "BindingProperty": {
22321
- const { name, value } = p;
22322
- let subRef;
22323
- switch (name.type) {
22324
- case "ComputedPropertyName":
22325
- conditions.push([name.expression, " in ", ref]);
22326
- subRef = [ref, name];
22327
- break;
22328
- case "Literal":
22329
- case "StringLiteral":
22330
- case "NumericLiteral":
22331
- conditions.push([name, " in ", ref]);
22332
- subRef = [ref, "[", name, "]"];
22333
- break;
22334
- default:
22335
- conditions.push(["'", name, "' in ", ref]);
22336
- subRef = [ref, ".", name];
22337
- }
22338
- if (value) {
22339
- getPatternConditions(value, subRef, conditions);
22340
- }
22341
- break;
22342
- }
22343
- }
22344
- });
22345
- break;
22346
- }
22347
- case "ConditionFragment":
22348
- conditions.push(
22349
- [ref, " ", pattern.children]
22350
- );
22351
- break;
22352
- case "RegularExpressionLiteral": {
22353
- conditions.push(
22354
- ["typeof ", ref, " === 'string'"],
22355
- [pattern, ".test(", ref, ")"]
22356
- );
22357
- break;
22358
- }
22359
- case "PinPattern":
22360
- conditions.push([
22361
- ref,
22362
- " === ",
22363
- pattern.identifier
22364
- ]);
22365
- break;
22366
- case "Literal":
22367
- conditions.push([
22368
- ref,
22369
- " === ",
22370
- pattern
22371
- ]);
22372
- break;
22373
- default:
22374
- break;
22375
- }
22376
- }
22377
- function elideMatchersFromArrayBindings(elements) {
22378
- return elements.map((el) => {
22379
- if (el.type === "BindingRestElement") {
22380
- return ["", el, void 0];
22381
- }
22382
- const { children: [ws, e, sep] } = el;
22383
- switch (e.type) {
22384
- case "Literal":
22385
- case "RegularExpressionLiteral":
22386
- case "StringLiteral":
22387
- case "PinPattern":
22388
- return sep;
22389
- default:
22390
- return [ws, nonMatcherBindings(e), sep];
22391
- }
22392
- });
22393
- }
22394
- function elideMatchersFromPropertyBindings(properties) {
22395
- return properties.map((p) => {
22396
- switch (p.type) {
22397
- case "BindingProperty": {
22398
- const { children, name, value } = p;
22399
- const [ws] = children;
22400
- const sep = children[children.length - 1];
22401
- switch (value && value.type) {
22402
- case "ArrayBindingPattern":
22403
- case "ObjectBindingPattern":
22404
- return {
22405
- ...p,
22406
- children: [ws, name, ": ", nonMatcherBindings(value)]
22407
- };
22408
- case "Identifier":
22409
- return p;
22410
- case "Literal":
22411
- case "RegularExpressionLiteral":
22412
- case "StringLiteral":
22413
- default:
22414
- return {
22415
- ...p,
22416
- children: [ws, name, sep]
22417
- };
22418
- }
22419
- }
22420
- case "PinProperty":
22421
- case "BindingRestProperty":
22422
- default:
22423
- return p;
22424
- }
22425
- });
22426
- }
22427
- function nonMatcherBindings(pattern) {
22428
- switch (pattern.type) {
22429
- case "ArrayBindingPattern": {
22430
- const elements = elideMatchersFromArrayBindings(pattern.elements);
22431
- const children = ["[", elements, "]"];
22432
- return {
22433
- ...pattern,
22434
- children,
22435
- elements
22436
- };
22437
- }
22438
- case "PostRestBindingElements": {
22439
- const els = elideMatchersFromArrayBindings(pattern.children[1]);
22440
- return {
22441
- ...pattern,
22442
- children: [
22443
- pattern.children[0],
22444
- els,
22445
- ...pattern.children.slice(2)
22446
- ]
22447
- };
22448
- }
22449
- case "ObjectBindingPattern":
22450
- return ["{", elideMatchersFromPropertyBindings(pattern.properties), "}"];
22451
- default:
22452
- return pattern;
22453
- }
22454
- }
22455
- function aggregateDuplicateBindings(bindings) {
22456
- const props = gatherRecursiveAll(bindings, (n) => n.type === "BindingProperty");
22457
- const arrayBindings = gatherRecursiveAll(bindings, (n) => n.type === "ArrayBindingPattern");
22458
- arrayBindings.forEach((a) => {
22459
- const { elements } = a;
22460
- elements.forEach((element) => {
22461
- if (Array.isArray(element)) {
22462
- const [, e] = element;
22463
- if (e.type === "Identifier") {
22464
- props.push(e);
22465
- } else if (e.type === "BindingRestElement") {
22466
- props.push(e);
22467
- }
22468
- }
22469
- });
22470
- });
22471
- const declarations = [];
22472
- const propsGroupedByName = /* @__PURE__ */ new Map();
22473
- for (const p of props) {
22474
- const { name, value } = p;
22475
- const key = value?.name || name?.name || name;
22476
- if (propsGroupedByName.has(key)) {
22477
- propsGroupedByName.get(key).push(p);
22478
- } else {
22479
- propsGroupedByName.set(key, [p]);
22480
- }
22481
- }
22482
- propsGroupedByName.forEach((shared, key) => {
22483
- if (!key)
22484
- return;
22485
- if (ReservedWord({
22486
- pos: 0,
22487
- input: key
22488
- })) {
22489
- shared.forEach((p) => {
22490
- const ref = {
22491
- type: "Ref",
22492
- base: `_${key}`,
22493
- id: key
22494
- };
22495
- aliasBinding(p, ref);
22496
- });
22497
- return;
22498
- }
22499
- if (shared.length === 1)
22500
- return;
22501
- const refs = shared.map((p) => {
22502
- const ref = {
22503
- type: "Ref",
22504
- base: key,
22505
- id: key
22506
- };
22507
- aliasBinding(p, ref);
22508
- return ref;
22509
- });
22510
- declarations.push(["const ", key, " = [", ...refs.map((r, i) => {
22511
- return i === 0 ? r : [", ", r];
22512
- }), "]"]);
22513
- });
22514
- return declarations;
22515
- }
22516
- function processPatternMatching(statements) {
22517
- gatherRecursiveAll(statements, (n) => n.type === "SwitchStatement" || n.type === "SwitchExpression").forEach((s) => {
22518
- const { caseBlock } = s;
22519
- const { clauses } = caseBlock;
22520
- let errors = false;
22521
- let isPattern = false;
22522
- if (clauses.some((c) => c.type === "PatternClause")) {
22523
- isPattern = true;
22524
- clauses.forEach((c) => {
22525
- if (!(c.type === "PatternClause" || c.type === "DefaultClause")) {
22526
- errors = true;
22527
- c.children.push({
22528
- type: "Error",
22529
- message: "Can't mix pattern matching and non-pattern matching clauses"
22530
- });
22531
- }
22532
- });
22533
- }
22534
- if (errors || !isPattern)
22535
- return;
22536
- let { expression } = s;
22537
- if (expression.type === "ParenthesizedExpression") {
22538
- expression = expression.expression;
22539
- }
22540
- let ref = module.needsRef(expression, "m") || expression;
22541
- let prev = [], root = prev;
22542
- const l = clauses.length;
22543
- clauses.forEach((c, i) => {
22544
- if (c.type === "DefaultClause") {
22545
- prev.push(c.block);
22546
- return;
22547
- }
22548
- let { patterns, block } = c;
22549
- let pattern = patterns[0];
22550
- const indent = block.expressions?.[0]?.[0] || "";
22551
- const alternativeConditions = patterns.map((pattern2, i2) => {
22552
- const conditions = [];
22553
- getPatternConditions(pattern2, ref, conditions);
22554
- return conditions;
22555
- });
22556
- const conditionExpression = alternativeConditions.map((conditions, i2) => {
22557
- const conditionArray = conditions.map((c2, i3) => {
22558
- if (i3 === 0)
22559
- return c2;
22560
- return [" && ", ...c2];
22561
- });
22562
- if (i2 === 0)
22563
- return conditionArray;
22564
- return [" || ", ...conditionArray];
22565
- });
22566
- const condition = {
22567
- type: "ParenthesizedExpression",
22568
- children: ["(", conditionExpression, ")"],
22569
- expression: conditionExpression
22570
- };
22571
- const prefix = [];
22572
- switch (pattern.type) {
22573
- case "ArrayBindingPattern":
22574
- if (pattern.length === 0)
22575
- break;
22576
- case "ObjectBindingPattern": {
22577
- if (pattern.properties?.length === 0)
22578
- break;
22579
- let [splices, thisAssignments] = gatherBindingCode(pattern);
22580
- const patternBindings = nonMatcherBindings(pattern);
22581
- splices = splices.map((s2) => [", ", nonMatcherBindings(s2)]);
22582
- thisAssignments = thisAssignments.map((a) => [indent, a, ";"]);
22583
- const duplicateDeclarations = aggregateDuplicateBindings([patternBindings, splices]);
22584
- prefix.push([indent, "const ", patternBindings, " = ", ref, splices, ";"]);
22585
- prefix.push(...thisAssignments);
22586
- prefix.push(...duplicateDeclarations.map((d) => [indent, d, ";"]));
22587
- break;
22588
- }
22589
- }
22590
- block.expressions.unshift(...prefix);
22591
- const next = [];
22592
- if (block.bare) {
22593
- block.children.unshift(" {");
22594
- block.children.push("}");
22595
- block.bare = false;
22596
- }
22597
- if (i < l - 1)
22598
- next.push("\n", "else ");
22599
- prev.push(["", {
22600
- type: "IfStatement",
22601
- children: ["if", condition, block, next],
22602
- then: block,
22603
- else: next
22604
- }]);
22605
- prev = next;
22606
- });
22607
- if (module.config.implicitReturns && s.type === "SwitchExpression") {
22608
- insertReturn(root[0]);
22609
- root.splice(0, 1, module.wrapIIFE(root[0]));
22610
- }
22611
- s.type = "PatternMatchingStatement";
22612
- s.children = [root];
22613
- addParentPointers(s, s.parent);
22614
- });
22615
- }
22616
- function processPipelineExpressions(statements) {
22617
- gatherRecursiveAll(statements, (n) => n.type === "PipelineExpression").forEach((s) => {
22618
- const [ws, , body] = s.children;
22619
- let [, arg] = s.children;
22620
- let i = 0, l = body.length;
22621
- const refDec = [];
22622
- const children = [ws, refDec];
22623
- let usingRef = null;
22624
- for (i = 0; i < l; i++) {
22625
- const step = body[i];
22626
- const [leadingComment, pipe, trailingComment, expr] = step;
22627
- const returns = pipe.token === "||>";
22628
- let ref, result, returning = returns ? arg : null;
22629
- if (pipe.token === "|>=") {
22630
- let initRef;
22631
- if (i === 0) {
22632
- outer:
22633
- switch (arg.type) {
22634
- case "MemberExpression":
22635
- if (arg.children.length <= 2)
22636
- break;
22637
- case "CallExpression":
22638
- const access = arg.children.pop();
22639
- switch (access.type) {
22640
- case "PropertyAccess":
22641
- case "SliceExpression":
22642
- break;
22643
- default:
22644
- children.unshift({
22645
- type: "Error",
22646
- $loc: pipe.token.$loc,
22647
- message: `Can't assign to ${access.type}`
22648
- });
22649
- arg.children.push(access);
22650
- break outer;
22651
- }
22652
- usingRef = module.needsRef({});
22653
- initRef = {
22654
- type: "AssignmentExpression",
22655
- children: [usingRef, " = ", arg, ","]
22656
- };
22657
- arg = {
22658
- type: "MemberExpression",
22659
- children: [usingRef, access]
22660
- };
22661
- break;
22662
- }
22663
- children.pop();
22664
- const lhs = [[
22665
- [refDec, initRef],
22666
- arg,
22667
- [],
22668
- { token: "=", children: [" = "] }
22669
- ]];
22670
- Object.assign(s, {
22671
- type: "AssignmentExpression",
22672
- children: [lhs, children],
22673
- names: null,
22674
- lhs,
22675
- assigned: arg,
22676
- exp: children
22677
- });
22678
- arg = clone(arg);
22679
- if (arg.children[0].type === "Ref") {
22680
- arg.children[0] = usingRef;
22681
- }
22682
- } else {
22683
- children.unshift({
22684
- type: "Error",
22685
- $loc: pipe.token.$loc,
22686
- message: "Can't use |>= in the middle of a pipeline"
22687
- });
22688
- }
22689
- } else {
22690
- s.children = children;
22691
- }
22692
- if (returns && (ref = module.needsRef(arg))) {
22693
- usingRef = usingRef || ref;
22694
- arg = {
22695
- type: "ParenthesizedExpression",
22696
- children: ["(", {
22697
- type: "AssignmentExpression",
22698
- children: [usingRef, " = ", arg]
22699
- }, ")"]
22700
- };
22701
- returning = usingRef;
22817
+ const { forbidMultiLineImplicitObjectLiteral: s } = module;
22818
+ return s[s.length - 1];
22702
22819
  }
22703
- [result, returning] = module.constructPipeStep(
22704
- {
22705
- leadingComment: module.skipIfOnlyWS(leadingComment),
22706
- trailingComment: module.skipIfOnlyWS(trailingComment),
22707
- expr
22708
- },
22709
- arg,
22710
- returning
22711
- );
22712
- if (result.type === "ReturnStatement") {
22713
- if (i < l - 1) {
22714
- result.children.push({
22715
- type: "Error",
22716
- message: "Can't continue a pipeline after returning"
22717
- });
22718
- }
22719
- arg = result;
22720
- if (children[children.length - 1] === ",") {
22721
- children.pop();
22722
- children.push(";");
22723
- }
22724
- break;
22820
+ },
22821
+ newlineBinaryOpForbidden: {
22822
+ get() {
22823
+ const { forbidNewlineBinaryOp: s } = module;
22824
+ return s[s.length - 1];
22725
22825
  }
22726
- if (returning) {
22727
- arg = returning;
22728
- children.push(result, ",");
22729
- } else {
22730
- arg = result;
22826
+ },
22827
+ currentJSXTag: {
22828
+ get() {
22829
+ const { JSXTagStack: s } = module;
22830
+ return s[s.length - 1];
22731
22831
  }
22732
22832
  }
22733
- if (usingRef) {
22734
- refDec.unshift("let ", usingRef, ";");
22735
- }
22736
- children.push(arg);
22737
- addParentPointers(s, s.parent);
22738
22833
  });
22739
22834
  }
22740
- module.processProgram = function(root) {
22741
- assert.equal(module.forbidClassImplicitCall.length, 1, "forbidClassImplicitCall");
22742
- assert.equal(module.forbidIndentedApplication.length, 1, "forbidIndentedApplication");
22743
- assert.equal(module.forbidTrailingMemberProperty.length, 1, "forbidTrailingMemberProperty");
22744
- assert.equal(module.forbidMultiLineImplicitObjectLiteral.length, 1, "forbidMultiLineImplicitObjectLiteral");
22745
- assert.equal(module.JSXTagStack.length, 0, "JSXTagStack should be empty");
22746
- addParentPointers(root);
22747
- const { expressions: statements } = root;
22748
- processPipelineExpressions(statements);
22749
- processAssignments(statements);
22750
- processPatternMatching(statements);
22751
- processFunctions(statements);
22752
- processSwitchExpressions(statements);
22753
- processTryExpressions(statements);
22754
- hoistRefDecs(statements);
22755
- gatherRecursiveAll(statements, (n) => n.type === "IterationExpression").forEach((e) => expressionizeIteration(e));
22756
- statements.unshift(...module.prelude);
22757
- if (module.config.autoLet) {
22758
- createLetDecs(statements, []);
22759
- } else if (module.config.autoVar) {
22760
- createVarDecs(statements, []);
22761
- }
22762
- populateRefs(statements);
22763
- adjustAtBindings(statements);
22764
- };
22765
- function findDecs(statements) {
22766
- const declarationNames = gatherNodes(statements, ({ type }) => type === "Declaration").flatMap((d) => d.names);
22767
- return new Set(declarationNames);
22768
- }
22769
- function populateRefs(statements) {
22770
- const refNodes = gatherRecursive(statements, ({ type }) => type === "Ref");
22771
- if (refNodes.length) {
22772
- const ids = gatherRecursive(statements, (s) => s.type === "Identifier");
22773
- const names = new Set(ids.flatMap(({ names: names2 }) => names2 || []));
22774
- refNodes.forEach((ref) => {
22775
- const { type, base } = ref;
22776
- if (type !== "Ref")
22777
- return;
22778
- ref.type = "Identifier";
22779
- let n = 0;
22780
- let name = base;
22781
- while (names.has(name)) {
22782
- n++;
22783
- name = `${base}${n}`;
22784
- }
22785
- names.add(name);
22786
- ref.children = ref.names = [name];
22835
+ module.config = parse2.config = {
22836
+ autoVar: false,
22837
+ autoLet: false,
22838
+ coffeeBinaryExistential: false,
22839
+ coffeeBooleans: false,
22840
+ coffeeClasses: false,
22841
+ coffeeComment: false,
22842
+ coffeeDo: false,
22843
+ coffeeEq: false,
22844
+ coffeeForLoops: false,
22845
+ coffeeInterpolation: false,
22846
+ coffeeIsnt: false,
22847
+ coffeeJSX: false,
22848
+ coffeeLineContinuation: false,
22849
+ coffeeNot: false,
22850
+ coffeeOf: false,
22851
+ coffeePrototype: false,
22852
+ defaultElement: "div",
22853
+ implicitReturns: true,
22854
+ objectIs: false,
22855
+ react: false,
22856
+ solid: false,
22857
+ client: false,
22858
+ rewriteTsImports: true,
22859
+ server: false,
22860
+ tab: void 0,
22861
+ verbose: false
22862
+ };
22863
+ const asAny = {
22864
+ ts: true,
22865
+ children: [" as any"]
22866
+ };
22867
+ module.prelude = [];
22868
+ const preludeVar = "var ";
22869
+ const declareRef = {
22870
+ indexOf(indexOfRef) {
22871
+ const typeSuffix = {
22872
+ ts: true,
22873
+ children: [": <T>(this: T[], searchElement: T) => boolean"]
22874
+ };
22875
+ module.prelude.push(["", [preludeVar, indexOfRef, typeSuffix, " = [].indexOf", asAny, ";\n"]]);
22876
+ },
22877
+ hasProp(hasPropRef) {
22878
+ const typeSuffix = {
22879
+ ts: true,
22880
+ children: [": <T>(this: T, prop: keyof T) => boolean"]
22881
+ };
22882
+ module.prelude.push(["", [preludeVar, hasPropRef, typeSuffix, " = {}.hasOwnProperty", asAny, ";\n"]]);
22883
+ },
22884
+ is(isRef) {
22885
+ const typeSuffix = {
22886
+ ts: true,
22887
+ children: [": { <B, A extends B> (a: A, b: B): b is A, <A, B> (a: A, b: B): a is A & B }"]
22888
+ };
22889
+ module.prelude.push(["", [preludeVar, isRef, typeSuffix, " = Object.is", asAny, ";\n"]]);
22890
+ },
22891
+ modulo(moduloRef) {
22892
+ const typeSuffix = {
22893
+ ts: true,
22894
+ children: [": (a: number, b: number) => number"]
22895
+ };
22896
+ module.prelude.push(["", [preludeVar, moduloRef, typeSuffix, " = (a, b) => (a % b + b) % b;", "\n"]]);
22897
+ },
22898
+ xor(xorRef) {
22899
+ const typeSuffix = {
22900
+ ts: true,
22901
+ children: [": (a: unknown, b: unknown) => boolean"]
22902
+ };
22903
+ module.prelude.push(["", [preludeVar, xorRef, typeSuffix, " = (a, b) => a ? !b && a : b;", "\n"]]);
22904
+ },
22905
+ xnor(xnorRef) {
22906
+ const typeSuffix = {
22907
+ ts: true,
22908
+ children: [": (a: unknown, b: unknown) => boolean"]
22909
+ };
22910
+ module.prelude.push(["", [preludeVar, xnorRef, typeSuffix, " = (a, b) => a ? b : !b || a;", "\n"]]);
22911
+ },
22912
+ returnSymbol(ref) {
22913
+ module.prelude.push({
22914
+ children: [
22915
+ preludeVar,
22916
+ ref,
22917
+ ` = Symbol("return")';
22918
+ `
22919
+ ]
22787
22920
  });
22788
- }
22789
- }
22790
- function createVarDecs(statements, scopes, pushVar) {
22791
- function hasDec(name) {
22792
- return scopes.some((s) => s.has(name));
22793
- }
22794
- function findAssignments(statements2, decs2) {
22795
- let assignmentStatements2 = gatherNodes(statements2, (node) => {
22796
- return node.type === "AssignmentExpression";
22921
+ },
22922
+ JSX(jsxRef) {
22923
+ module.prelude.push({
22924
+ ts: true,
22925
+ children: [
22926
+ "import type { JSX as ",
22927
+ jsxRef,
22928
+ " } from 'solid-js';\n"
22929
+ ]
22797
22930
  });
22798
- if (assignmentStatements2.length) {
22799
- assignmentStatements2 = assignmentStatements2.concat(findAssignments(assignmentStatements2.map((s) => s.children), decs2));
22800
- }
22801
- return assignmentStatements2;
22802
- }
22803
- if (!pushVar) {
22804
- pushVar = function(name) {
22805
- varIds.push(name);
22806
- decs.add(name);
22807
- };
22808
- }
22809
- const decs = findDecs(statements);
22810
- scopes.push(decs);
22811
- const varIds = [];
22812
- const assignmentStatements = findAssignments(statements, scopes);
22813
- const undeclaredIdentifiers = assignmentStatements.flatMap((a) => a.names);
22814
- undeclaredIdentifiers.filter((x, i, a) => {
22815
- if (!hasDec(x))
22816
- return a.indexOf(x) === i;
22817
- }).forEach(pushVar);
22818
- const fnNodes = gatherNodes(statements, (s) => s.type === "FunctionExpression");
22819
- const forNodes = gatherNodes(statements, (s) => s.type === "ForStatement");
22820
- const blockNodes = new Set(gatherNodes(statements, (s) => s.type === "BlockStatement"));
22821
- fnNodes.forEach(({ block }) => blockNodes.delete(block));
22822
- forNodes.forEach(({ block }) => blockNodes.delete(block));
22823
- blockNodes.forEach((block) => {
22824
- createVarDecs(block.expressions, scopes, pushVar);
22825
- });
22826
- forNodes.forEach(({ block, declaration }) => {
22827
- scopes.push(new Set(declaration.names));
22828
- createVarDecs(block.expressions, scopes, pushVar);
22829
- scopes.pop();
22830
- });
22831
- fnNodes.forEach(({ block, parameters }) => {
22832
- scopes.push(new Set(parameters.names));
22833
- createVarDecs(block.expressions, scopes);
22834
- scopes.pop();
22835
- });
22836
- if (varIds.length) {
22837
- const indent = getIndent(statements[0]);
22838
- let delimiter = ";";
22839
- if (statements[0][1]?.parent?.root) {
22840
- delimiter = ";\n";
22841
- }
22842
- statements.unshift([indent, "var ", varIds.join(", "), delimiter]);
22843
- }
22844
- scopes.pop();
22845
- }
22846
- function createLetDecs(statements, scopes) {
22847
- function findVarDecs(statements2, decs) {
22848
- const declarationNames = gatherRecursive(
22849
- statements2,
22850
- (node) => node.type === "Declaration" && node.children && node.children.length > 0 && node.children[0].token && node.children[0].token.startsWith("var") || node.type === "FunctionExpression"
22851
- ).filter((node) => node.type === "Declaration").flatMap((node) => node.names);
22852
- return new Set(declarationNames);
22853
- }
22854
- let declaredIdentifiers = findVarDecs(statements);
22855
- function hasDec(name) {
22856
- return declaredIdentifiers.has(name) || scopes.some((s) => s.has(name));
22857
- }
22858
- function gatherBlockOrOther(statement) {
22859
- return gatherNodes(statement, (s) => s.type === "BlockStatement" || s.type === "AssignmentExpression" || s.type === "Declaration").flatMap((node) => {
22860
- if (node.type == "BlockStatement")
22861
- return node.bare ? gatherBlockOrOther(node.expressions) : node;
22862
- else if (node.children && node.children.length)
22863
- return [...gatherBlockOrOther(node.children), node];
22864
- else
22865
- return [];
22931
+ },
22932
+ IntrinsicElements(intrinsicElementsRef) {
22933
+ const JSX = module.getRef("JSX");
22934
+ module.prelude.push({
22935
+ ts: true,
22936
+ children: [
22937
+ "type ",
22938
+ intrinsicElementsRef,
22939
+ "<K extends keyof ",
22940
+ JSX,
22941
+ ".IntrinsicElements> =\n",
22942
+ " ",
22943
+ JSX,
22944
+ ".IntrinsicElements[K] extends ",
22945
+ JSX,
22946
+ ".DOMAttributes<infer T> ? T : unknown;\n"
22947
+ ]
22866
22948
  });
22867
22949
  }
22868
- let currentScope = /* @__PURE__ */ new Set();
22869
- scopes.push(currentScope);
22870
- const fnNodes = gatherNodes(statements, (s) => s.type === "FunctionExpression");
22871
- const forNodes = gatherNodes(statements, (s) => s.type === "ForStatement");
22872
- let targetStatements = [];
22873
- for (const statement of statements) {
22874
- const nodes = gatherBlockOrOther(statement);
22875
- let undeclaredIdentifiers = [];
22876
- for (const node of nodes) {
22877
- if (node.type == "BlockStatement") {
22878
- let block = node;
22879
- let fnNode = fnNodes.find((fnNode2) => fnNode2.block === block);
22880
- let forNode = forNodes.find((forNode2) => forNode2.block === block);
22881
- if (fnNode != null) {
22882
- scopes.push(new Set(fnNode.parameters.names));
22883
- createLetDecs(block.expressions, scopes);
22884
- scopes.pop();
22885
- } else if (forNode != null) {
22886
- scopes.push(new Set(forNode.declaration.names));
22887
- createLetDecs(block.expressions, scopes);
22888
- scopes.pop();
22889
- } else
22890
- createLetDecs(block.expressions, scopes);
22891
- continue;
22892
- }
22893
- if (node.names == null)
22894
- continue;
22895
- let names = node.names.filter((name) => !hasDec(name));
22896
- if (node.type == "AssignmentExpression")
22897
- undeclaredIdentifiers.push(...names);
22898
- names.forEach((name) => currentScope.add(name));
22950
+ };
22951
+ const refs = {};
22952
+ module.getRef = function(base) {
22953
+ if (refs.hasOwnProperty(base))
22954
+ return refs[base];
22955
+ const ref = {
22956
+ type: "Ref",
22957
+ base,
22958
+ id: base
22959
+ };
22960
+ if (declareRef.hasOwnProperty(base))
22961
+ declareRef[base](ref);
22962
+ return refs[base] = ref;
22963
+ };
22964
+ Object.defineProperty(module.config, "deno", {
22965
+ set(b) {
22966
+ module.config.rewriteTsImports = !b;
22967
+ }
22968
+ });
22969
+ module.config.deno = typeof Deno !== "undefined";
22970
+ Object.defineProperty(module.config, "coffeeCompat", {
22971
+ set(b) {
22972
+ for (const option of [
22973
+ "autoVar",
22974
+ "coffeeBinaryExistential",
22975
+ "coffeeBooleans",
22976
+ "coffeeClasses",
22977
+ "coffeeComment",
22978
+ "coffeeDo",
22979
+ "coffeeEq",
22980
+ "coffeeForLoops",
22981
+ "coffeeInterpolation",
22982
+ "coffeeIsnt",
22983
+ "coffeeJSX",
22984
+ "coffeeLineContinuation",
22985
+ "coffeeNot",
22986
+ "coffeeOf",
22987
+ "coffeePrototype"
22988
+ ]) {
22989
+ module.config[option] = b;
22899
22990
  }
22900
- if (undeclaredIdentifiers.length > 0) {
22901
- let indent = statement[0];
22902
- let firstIdentifier = gatherNodes(statement[1], (node) => node.type == "Identifier")[0];
22903
- if (undeclaredIdentifiers.length == 1 && statement[1].type == "AssignmentExpression" && statement[1].names.length == 1 && statement[1].names[0] == undeclaredIdentifiers[0] && firstIdentifier && firstIdentifier.names == undeclaredIdentifiers[0] && gatherNodes(statement[1], (node) => node.type === "ObjectBindingPattern").length == 0)
22904
- statement[1].children.unshift(["let "]);
22905
- else {
22906
- let tail = "\n";
22907
- if (gatherNodes(indent, (node) => node.token && node.token.endsWith("\n")).length > 0)
22908
- tail = void 0;
22909
- targetStatements.push([indent, "let ", undeclaredIdentifiers.join(", "), tail]);
22910
- }
22991
+ if (b) {
22992
+ module.config.objectIs = false;
22911
22993
  }
22912
- targetStatements.push(statement);
22913
- }
22914
- scopes.pop();
22915
- statements.splice(0, statements.length, targetStatements);
22916
- }
22917
- module.constructInvocation = function(fn, arg) {
22918
- const fnArr = [fn.leadingComment, fn.expr, fn.trailingComment];
22919
- let expr = fn.expr;
22920
- while (expr.type === "ParenthesizedExpression") {
22921
- expr = expr.expression;
22922
- }
22923
- if (expr.ampersandBlock) {
22924
- const { ref, body } = expr;
22925
- ref.type = "PipedExpression";
22926
- ref.children = [module.makeLeftHandSideExpression(arg)];
22927
- return {
22928
- type: "UnwrappedExpression",
22929
- children: [module.skipIfOnlyWS(fn.leadingComment), ...body, module.skipIfOnlyWS(fn.trailingComment)]
22930
- };
22931
- }
22932
- expr = fn.expr;
22933
- const lhs = module.makeLeftHandSideExpression(expr);
22934
- let comment = module.skipIfOnlyWS(fn.trailingComment);
22935
- if (comment)
22936
- lhs.children.splice(2, 0, comment);
22937
- comment = module.skipIfOnlyWS(fn.leadingComment);
22938
- if (comment)
22939
- lhs.children.splice(1, 0, comment);
22940
- switch (arg.type) {
22941
- case "CommaExpression":
22942
- arg = module.makeLeftHandSideExpression(arg);
22943
- break;
22944
22994
  }
22945
- return {
22946
- type: "CallExpression",
22947
- children: [lhs, "(", arg, ")"]
22948
- };
22949
- };
22950
- module.constructPipeStep = function(fn, arg, returning) {
22951
- const children = [[fn.leadingComment, fn.expr, fn.trailingComment].map(module.skipIfOnlyWS), " ", arg];
22952
- switch (fn.expr.token) {
22953
- case "yield":
22954
- case "await":
22955
- if (returning) {
22956
- return [
22957
- children,
22958
- returning
22959
- ];
22960
- }
22961
- return [
22962
- children,
22963
- null
22964
- ];
22965
- case "return":
22966
- return [{
22967
- type: "ReturnStatement",
22968
- children
22969
- }, null];
22995
+ });
22996
+ });
22997
+ function Reset(state) {
22998
+ let eventData;
22999
+ if (state.events) {
23000
+ const result = state.events.enter?.("Reset", state);
23001
+ if (result) {
23002
+ if (result.cache)
23003
+ return result.cache;
23004
+ eventData = result.data;
22970
23005
  }
22971
- if (returning) {
22972
- return [
22973
- module.constructInvocation(fn, arg),
22974
- returning
22975
- ];
23006
+ }
23007
+ if (state.tokenize) {
23008
+ const result = $TOKEN("Reset", state, Reset$0(state));
23009
+ if (state.events)
23010
+ state.events.exit?.("Reset", state, result, eventData);
23011
+ return result;
23012
+ } else {
23013
+ const result = Reset$0(state);
23014
+ if (state.events)
23015
+ state.events.exit?.("Reset", state, result, eventData);
23016
+ return result;
23017
+ }
23018
+ }
23019
+ var Init$0 = $TS($S($E(Shebang), $Q(DirectivePrologue), $EXPECT($L0, fail, 'Init ""')), function($skip, $loc, $0, $1, $2, $3) {
23020
+ var directives = $2;
23021
+ directives.forEach((directive) => {
23022
+ if (directive.type === "CivetPrologue") {
23023
+ Object.assign(module.config, directive.config);
22976
23024
  }
22977
- return [module.constructInvocation(fn, arg), null];
22978
- };
23025
+ });
22979
23026
  return $0;
22980
23027
  });
22981
23028
  function Init(state) {
@@ -23280,43 +23327,40 @@ ${input.slice(result.pos)}
23280
23327
  exports.parse = parse2;
23281
23328
  exports.default = { parse: parse2 };
23282
23329
  var {
23283
- aliasBinding,
23330
+ addPostfixStatement,
23331
+ adjustBindingElements,
23332
+ attachPostfixStatementAsExpression,
23284
23333
  blockWithPrefix,
23285
- clone,
23286
- convertMethodToFunction,
23287
23334
  convertObjectToJSXAttributes,
23288
23335
  deepCopy,
23289
- findAncestor,
23336
+ dedentBlockString,
23337
+ dedentBlockSubstitutions,
23338
+ expressionizeIfClause,
23290
23339
  forRange,
23291
23340
  gatherBindingCode,
23292
- gatherNodes,
23293
- gatherRecursive,
23294
- gatherRecursiveAll,
23295
- gatherRecursiveWithinFunction,
23296
- getIndent,
23297
23341
  getTrimmingSpace,
23298
23342
  hasAwait,
23299
23343
  hasYield,
23300
- hoistRefDecs,
23301
23344
  insertTrimmingSpace,
23302
- isFunction,
23345
+ isEmptyBareBlock,
23346
+ isWhitespaceOrEmpty,
23303
23347
  lastAccessInCallExpression,
23304
23348
  literalValue,
23349
+ makeLeftHandSideExpression,
23305
23350
  modifyString,
23351
+ processBinaryOpExpression,
23352
+ processCallMemberExpression,
23306
23353
  processCoffeeInterpolation,
23307
23354
  processConstAssignmentDeclaration,
23308
23355
  processLetAssignmentDeclaration,
23356
+ processProgram,
23309
23357
  processUnaryExpression,
23310
23358
  quoteString,
23311
- removeParentPointers
23359
+ reorderBindingRestProperty,
23360
+ replaceNodes,
23361
+ typeOfJSX,
23362
+ wrapIIFE
23312
23363
  } = require_lib();
23313
- var assert = {
23314
- equal(a, b, msg) {
23315
- if (a !== b) {
23316
- throw new Error(`Assertion failed [${msg}]: ${a} !== ${b}`);
23317
- }
23318
- }
23319
- };
23320
23364
  }
23321
23365
  });
23322
23366