gofront 1.5.1 → 1.6.1

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 (91) hide show
  1. package/README.md +174 -466
  2. package/package.json +16 -20
  3. package/src/backend/js/expressions.js +288 -128
  4. package/src/backend/js/index.js +138 -56
  5. package/src/backend/js/runtime.js +1055 -53
  6. package/src/backend/js/source-map.js +32 -0
  7. package/src/backend/js/statements.js +151 -83
  8. package/src/backend/js/stdlib/base64.js +12 -0
  9. package/src/backend/js/stdlib/binary.js +102 -0
  10. package/src/backend/js/stdlib/bits.js +15 -1
  11. package/src/backend/js/stdlib/builder.js +28 -9
  12. package/src/backend/js/stdlib/bytes.js +75 -18
  13. package/src/backend/js/stdlib/errors.js +22 -3
  14. package/src/backend/js/stdlib/fmt.js +95 -20
  15. package/src/backend/js/stdlib/hex.js +17 -0
  16. package/src/backend/js/stdlib/html.js +1 -1
  17. package/src/backend/js/stdlib/index.js +19 -0
  18. package/src/backend/js/stdlib/io.js +105 -3
  19. package/src/backend/js/stdlib/maps.js +1 -1
  20. package/src/backend/js/stdlib/math.js +13 -1
  21. package/src/backend/js/stdlib/path.js +20 -6
  22. package/src/backend/js/stdlib/rand.js +10 -5
  23. package/src/backend/js/stdlib/sha256.js +12 -0
  24. package/src/backend/js/stdlib/shared.js +17 -0
  25. package/src/backend/js/stdlib/slices.js +53 -27
  26. package/src/backend/js/stdlib/sort.js +1 -1
  27. package/src/backend/js/stdlib/strconv.js +52 -11
  28. package/src/backend/js/stdlib/strings.js +152 -16
  29. package/src/backend/js/stdlib/sync.js +13 -0
  30. package/src/backend/js/stdlib/testing.js +2 -2
  31. package/src/backend/js/stdlib/time.js +93 -22
  32. package/src/backend/js/stdlib/unicode.js +2 -2
  33. package/src/backend/js/templ.js +1 -1
  34. package/src/backend/wasm/boundary.js +1677 -58
  35. package/src/backend/wasm/const-fold.js +205 -0
  36. package/src/backend/wasm/emit-builtins.js +1230 -0
  37. package/src/backend/wasm/emit-exprs.js +2096 -0
  38. package/src/backend/wasm/emit-maps.js +1999 -0
  39. package/src/backend/wasm/emit-shared.js +519 -0
  40. package/src/backend/wasm/emit-stdlib.js +13 -0
  41. package/src/backend/wasm/emit-stmts.js +2466 -0
  42. package/src/backend/wasm/emit.js +656 -5031
  43. package/src/backend/wasm/encode.js +259 -85
  44. package/src/backend/wasm/glue.js +19 -5
  45. package/src/backend/wasm/index.js +2432 -86
  46. package/src/backend/wasm/monomorph.js +711 -0
  47. package/src/backend/wasm/optimize.js +236 -0
  48. package/src/backend/wasm/stdlib/bytes.js +5039 -0
  49. package/src/backend/wasm/stdlib/core.js +8903 -0
  50. package/src/backend/wasm/stdlib/index.js +40 -0
  51. package/src/backend/wasm/stdlib/io.js +2161 -0
  52. package/src/backend/wasm/stdlib/packages.js +2400 -0
  53. package/src/backend/wasm/stdlib/pure.js +720 -0
  54. package/src/backend/wasm/stdlib/time.js +1200 -0
  55. package/src/backend/wasm/types.js +312 -36
  56. package/src/backend/wasm/wat.js +49 -2
  57. package/src/cli-core.js +276 -73
  58. package/src/compiler.js +162 -25
  59. package/src/dts-parser.js +79 -126
  60. package/src/index.js +88 -121
  61. package/src/lexer.js +80 -29
  62. package/src/lower/boxing.js +4 -6
  63. package/src/lower/captures.js +12 -23
  64. package/src/lower/escape.js +4 -9
  65. package/src/lower/functions.js +277 -5
  66. package/src/lower/globals.js +7 -15
  67. package/src/lower/index.js +5 -2
  68. package/src/lower/ownership.js +35 -19
  69. package/src/lower/range.js +2 -5
  70. package/src/lower/walk.js +25 -0
  71. package/src/minifier.js +20 -68
  72. package/src/parser/declarations.js +3 -6
  73. package/src/parser/expressions.js +3 -8
  74. package/src/parser/index.js +18 -3
  75. package/src/parser/statements.js +25 -38
  76. package/src/parser/types.js +1 -2
  77. package/src/resolver.js +3 -27
  78. package/src/templ-lexer.js +29 -63
  79. package/src/templ-parser.js +22 -45
  80. package/src/test-runner.js +20 -0
  81. package/src/typechecker/assignability.js +123 -14
  82. package/src/typechecker/expressions.js +244 -4
  83. package/src/typechecker/index.js +27 -1
  84. package/src/typechecker/resolve.js +71 -12
  85. package/src/typechecker/statements.js +0 -7
  86. package/src/typechecker/stdlib/core.js +292 -103
  87. package/src/typechecker/stdlib/extended.js +471 -4
  88. package/src/typechecker/stdlib/shared.js +53 -0
  89. package/src/typechecker/stdlib.js +2 -0
  90. package/src/typechecker/types.js +545 -8
  91. package/src/vendor.js +2 -2
@@ -43,21 +43,98 @@ export const HELPER_SCLONE = `var __sclone = __sclone || function(x) {
43
43
 
44
44
  // Interface boxing: tag struct values (__v) vs struct pointers (__p) so type
45
45
  // switches can tell T from *T; tags are non-enumerable so __equal/JSON ignore them.
46
- export const HELPER_IFACE_BOX = `var __ifv = __ifv || function(x) {
46
+ export const HELPER_IFACE_BOX = `var __ifv = __ifv || function(x, ptrFields) {
47
47
  if (x === null || typeof x !== "object") return x;
48
48
  const c = typeof x.__clone === "function" ? x.__clone() : Object.assign(Object.create(Object.getPrototypeOf(x)), x);
49
49
  Object.defineProperty(c, "__v", { value: true, configurable: true });
50
+ if (Array.isArray(ptrFields)) {
51
+ for (const f of ptrFields) {
52
+ if (f.indexOf(".") !== -1) {
53
+ const parts = f.split(".");
54
+ let cur = c;
55
+ for (let j = 0; j < parts.length - 1; j++) cur = cur?.[parts[j]];
56
+ const last = parts[parts.length - 1];
57
+ if (cur?.[last] !== null && typeof cur?.[last] === "object") __ifp(cur[last]);
58
+ } else if (c[f] !== null && typeof c[f] === "object") {
59
+ __ifp(c[f]);
60
+ }
61
+ }
62
+ }
63
+ for (const k of Object.keys(c)) {
64
+ if (c[k] !== null && typeof c[k] === "object" && !Array.isArray(c[k]) && !ArrayBuffer.isView(c[k])) {
65
+ if (!c[k].__v && !c[k].__p && (!Array.isArray(ptrFields) || !ptrFields.includes(k))) {
66
+ Object.defineProperty(c[k], "__v", { value: true, configurable: true });
67
+ }
68
+ }
69
+ }
50
70
  return c;
51
71
  };
52
- var __ifp = __ifp || function(x) {
53
- if (x !== null && typeof x === "object" && x.__p !== true && Object.isExtensible(x))
72
+ var __ifp = __ifp || function(x, ptrFields, seen) {
73
+ if (x === null || typeof x !== "object") return x;
74
+ if (x.__p !== true && Object.isExtensible(x))
54
75
  Object.defineProperty(x, "__p", { value: true, configurable: true });
76
+ if (Array.isArray(ptrFields)) {
77
+ seen = seen || new Set();
78
+ if (seen.has(x)) return x;
79
+ seen.add(x);
80
+ for (const f of ptrFields) {
81
+ if (f.indexOf(".") !== -1) {
82
+ const parts = f.split(".");
83
+ let cur = x;
84
+ for (let j = 0; j < parts.length - 1; j++) cur = cur?.[parts[j]];
85
+ const last = parts[parts.length - 1];
86
+ if (cur?.[last] !== null && typeof cur?.[last] === "object") __ifp(cur[last]);
87
+ } else if (x[f] !== null && typeof x[f] === "object") {
88
+ __ifp(x[f]);
89
+ }
90
+ }
91
+ }
92
+ return x;
93
+ };
94
+ var __ifm = __ifm || function(x) {
95
+ if (x === null || x === undefined) return x;
96
+ if (typeof x !== "object") return x;
97
+ if (x.__map !== true && Object.isExtensible(x))
98
+ Object.defineProperty(x, "__map", { value: true, configurable: true });
99
+ return x;
100
+ };
101
+ var __ifpm = __ifpm || function(x) {
102
+ if (x === null || x === undefined) return x;
103
+ if (typeof x !== "object") return x;
104
+ if (x.__map !== true && Object.isExtensible(x)) {
105
+ Object.defineProperty(x, "__map", { value: true, configurable: true });
106
+ Object.defineProperty(x, "__ptr_map", { value: true, configurable: true });
107
+ }
108
+ return x;
109
+ };
110
+ var __ifs = __ifs || function(x, ptrFields) {
111
+ if (x === null || x === undefined) return x;
112
+ if (x.__slice !== true && Object.isExtensible(x))
113
+ Object.defineProperty(x, "__slice", { value: true, configurable: true });
114
+ if (Array.isArray(ptrFields) && Object.isExtensible(x))
115
+ Object.defineProperty(x, "__ptr_fields", { value: ptrFields, configurable: true });
116
+ return x;
117
+ };
118
+ var __ifps = __ifps || function(x) {
119
+ if (x === null || x === undefined) return x;
120
+ if (x.__slice !== true && Object.isExtensible(x)) {
121
+ Object.defineProperty(x, "__slice", { value: true, configurable: true });
122
+ Object.defineProperty(x, "__ptr_slice", { value: true, configurable: true });
123
+ }
124
+ return x;
125
+ };`;
126
+
127
+ // Nil-interface method call guard (strict mode only): matches Go's panic
128
+ // message instead of a JS TypeError.
129
+ export const HELPER_NIL_CALL = `var __nilcall = __nilcall || function(x) {
130
+ if (x == null) throw new Error("runtime error: invalid memory address or nil pointer dereference");
55
131
  return x;
56
132
  };`;
57
133
 
58
134
  export const HELPER_EQUAL = `var __equal = __equal || function __equal(a, b) {
59
135
  if (a === b) return true;
60
136
  if (a === null || b === null) return false;
137
+ if (a instanceof Date && b instanceof Date) return a.getTime() === b.getTime();
61
138
  if (ArrayBuffer.isView(a) && ArrayBuffer.isView(b)) {
62
139
  if (a.byteLength !== b.byteLength || a.length !== b.length) return false;
63
140
  for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;
@@ -86,9 +163,149 @@ export const HELPER_CDIV = `var __cdiv = __cdiv || function(a, b) {
86
163
  return { re: (a.re * b.re + a.im * b.im) / d, im: (a.im * b.re - a.re * b.im) / d };
87
164
  };`;
88
165
 
166
+ // Panic/defer runtime. \`stack\` holds the in-flight panic of every frame
167
+ // currently running its defers; \`armed\` is set right before a deferred
168
+ // function is invoked and consumed by that function's prologue, so recover()
169
+ // only takes effect when called directly by the deferred function (Go spec).
170
+ export const HELPER_PANIC = `var __gopanic = __gopanic || { stack: [], armed: false };
171
+ var __runDefers = __runDefers || function(defers, frame) {
172
+ for (let i = defers.length - 1; i >= 0; i--) {
173
+ __gopanic.armed = true;
174
+ try { defers[i](); }
175
+ catch (e) {
176
+ if (frame.pn !== null) __gopanic.stack.pop();
177
+ frame.pn = { err: e, recovered: false };
178
+ __gopanic.stack.push(frame.pn);
179
+ } finally { __gopanic.armed = false; }
180
+ }
181
+ if (frame.pn !== null) {
182
+ __gopanic.stack.pop();
183
+ if (!frame.pn.recovered) throw frame.pn.err;
184
+ }
185
+ };
186
+ var __recover = __recover || function(ok) {
187
+ if (!ok) return null;
188
+ const s = __gopanic.stack;
189
+ const top = s.length > 0 ? s[s.length - 1] : null;
190
+ if (top === null || top.recovered) return null;
191
+ top.recovered = true;
192
+ return top.err?.message ?? String(top.err);
193
+ };`;
194
+
89
195
  export const HELPER_SPRINTF = `var __sprintf = __sprintf || function(f, ...a) {
90
196
  let i = 0;
91
- return f.replace(/%([#+\\- 0]*)([0-9]*)\\.?([0-9]*)[sdvftxXqobeEgGw%]/g, (m) => {
197
+ const ptrMap = new WeakMap();
198
+ const ptrSet = new WeakSet();
199
+ let ptrCounter = 1;
200
+ const getPtr = (o) => {
201
+ let p = ptrMap.get(o);
202
+ if (!p) {
203
+ p = "0x" + (ptrCounter++).toString(16);
204
+ ptrMap.set(o, p);
205
+ }
206
+ return p;
207
+ };
208
+ const markPtr = (o) => {
209
+ if (o !== null && typeof o === "object") ptrSet.add(o);
210
+ };
211
+ const isPointer = (o) => {
212
+ return o !== null && typeof o === "object" && (o.__p === true || ptrSet.has(o));
213
+ };
214
+ const formatV = (val, isPlus, isTopLevel) => {
215
+ if (val === null || val === undefined) return "<nil>";
216
+ if (typeof val === "boolean") return String(val);
217
+ if (typeof val === "number" || typeof val === "bigint") return String(val);
218
+ if (typeof val === "string") return val;
219
+ if (typeof val === "object") {
220
+ if (val._d instanceof Date) {
221
+ return typeof __timeFmt === "function" ? __timeFmt(val, "2006-01-02 15:04:05.999999999 -0700 MST") : String(val._d);
222
+ }
223
+ if ("re" in val && "im" in val) {
224
+ const sign = val.im >= 0 ? "+" : "";
225
+ return "(" + val.re + sign + val.im + "i)";
226
+ }
227
+ if (typeof val.Error === "function") {
228
+ return String(val.Error());
229
+ }
230
+ if (Array.isArray(val) || ArrayBuffer.isView(val)) {
231
+ const isElemPtr = val.__ptr_slice === true;
232
+ const pf = val.__ptr_fields;
233
+ const parts = [];
234
+ for (let j = 0; j < val.length; j++) {
235
+ const item = val[j];
236
+ if (isElemPtr && item !== null && typeof item === "object") {
237
+ markPtr(item);
238
+ } else if (Array.isArray(pf) && item !== null && typeof item === "object") {
239
+ for (const f of pf) {
240
+ if (f.indexOf(".") !== -1) {
241
+ const fparts = f.split(".");
242
+ let cur = item;
243
+ for (let k = 0; k < fparts.length - 1; k++) cur = cur?.[fparts[k]];
244
+ const last = fparts[fparts.length - 1];
245
+ if (cur?.[last] !== null && typeof cur?.[last] === "object") markPtr(cur[last]);
246
+ } else if (item[f] !== null && typeof item[f] === "object") {
247
+ markPtr(item[f]);
248
+ }
249
+ }
250
+ }
251
+ parts.push(formatV(item, isPlus, false));
252
+ }
253
+ return "[" + parts.join(" ") + "]";
254
+ }
255
+ if (val instanceof Map || val.__map === true) {
256
+ const isElemPtr = val.__ptr_map === true;
257
+ const parts = [];
258
+ if (val instanceof Map) {
259
+ const entries = Array.from(val.entries()).sort(([k1], [k2]) => {
260
+ if (typeof k1 === "number" && typeof k2 === "number") return k1 - k2;
261
+ const na = Number(k1), nb = Number(k2);
262
+ if (!Number.isNaN(na) && !Number.isNaN(nb)) return na - nb;
263
+ return String(k1).localeCompare(String(k2));
264
+ });
265
+ for (const [k, v] of entries) {
266
+ if (isElemPtr && v !== null && typeof v === "object") {
267
+ markPtr(v);
268
+ }
269
+ parts.push(formatV(k, isPlus, false) + ":" + formatV(v, isPlus, false));
270
+ }
271
+ } else {
272
+ const keys = Object.keys(val).sort((a, b) => {
273
+ const na = Number(a), nb = Number(b);
274
+ if (!Number.isNaN(na) && !Number.isNaN(nb)) return na - nb;
275
+ return a.localeCompare(b);
276
+ });
277
+ for (const k of keys) {
278
+ const v = val[k];
279
+ if (isElemPtr && v !== null && typeof v === "object") {
280
+ markPtr(v);
281
+ }
282
+ parts.push(formatV(k, isPlus, false) + ":" + formatV(v, isPlus, false));
283
+ }
284
+ }
285
+ return "map[" + parts.join(" ") + "]";
286
+ }
287
+ if ("value" in val && (val.__box === true || (!val.__struct && !("__v" in val) && Object.keys(val).length === 1 && (val.constructor === Object || !val.constructor || val.constructor?.name === "Object")))) {
288
+ return getPtr(val);
289
+ }
290
+ const isPtr = isPointer(val);
291
+ if (isPtr) {
292
+ if (!isTopLevel) {
293
+ return getPtr(val);
294
+ }
295
+ getPtr(val);
296
+ }
297
+ const prefix = isPtr ? "&{" : "{";
298
+ const keys = Object.keys(val);
299
+ const parts = [];
300
+ for (const k of keys) {
301
+ const fv = formatV(val[k], isPlus, false);
302
+ parts.push(isPlus ? k + ":" + fv : fv);
303
+ }
304
+ return prefix + parts.join(" ") + "}";
305
+ }
306
+ return String(val);
307
+ };
308
+ return f.replace(/%([#+\\- 0]*)([0-9]*)\\.?([0-9]*)[sdvftxXqobeEgGwc%]/g, (m) => {
92
309
  if (m === "%%") return "%";
93
310
  const verb = m.slice(-1);
94
311
  const v = a[i++];
@@ -102,30 +319,46 @@ export const HELPER_SPRINTF = `var __sprintf = __sprintf || function(f, ...a) {
102
319
  };
103
320
  switch (verb) {
104
321
  case "s": return pad(String(v == null ? "<nil>" : v), width, false);
105
- case "d": return pad(String(Math.trunc(Number(v))), width, zero);
322
+ case "c": return pad(String.fromCodePoint(Number(v)), width, false);
323
+ case "d": return pad(String(typeof v === "bigint" ? v : Math.trunc(Number(v))), width, zero);
106
324
  case "v": {
107
- if (typeof v === "object" && v !== null) {
108
- if ("re" in v && "im" in v) {
109
- const sign = v.im >= 0 ? "+" : "";
110
- return pad("(" + v.re + sign + v.im + "i)", width, false);
111
- }
112
- if (typeof v.Error === "function") {
113
- return pad(String(v.Error()), width, false);
114
- }
115
- try {
116
- return pad(JSON.stringify(v), width, false);
117
- } catch {
118
- return pad(String(v), width, false);
119
- }
120
- }
121
- return pad(String(v == null ? "<nil>" : v), width, false);
325
+ const isPlus = flags?.includes("+") ?? false;
326
+ return pad(formatV(v, isPlus, true), width, false);
122
327
  }
123
328
  case "f": { const n = Number(v), p = prec !== "" ? parseInt(prec) : 6; return pad(n.toFixed(p), width, zero); }
124
329
  case "t": return pad(String(!!v), width, false);
125
- case "x": return pad((Number(v) >>> 0).toString(16), width, zero);
126
- case "X": return pad((Number(v) >>> 0).toString(16).toUpperCase(), width, zero);
127
- case "o": return pad((Number(v) >>> 0).toString(8), width, zero);
128
- case "b": return pad((Number(v) >>> 0).toString(2), width, zero);
330
+ case "x": {
331
+ let hex;
332
+ if (Array.isArray(v) || ArrayBuffer.isView(v)) {
333
+ hex = Array.from(v).map((b) => (Number(b) & 0xff).toString(16).padStart(2, "0")).join("");
334
+ } else if (typeof v === "string") {
335
+ hex = Array.from(new TextEncoder().encode(v)).map((b) => b.toString(16).padStart(2, "0")).join("");
336
+ } else if (typeof v === "bigint") {
337
+ hex = BigInt.asUintN(64, v).toString(16);
338
+ } else if (Math.abs(Number(v)) > 0xffffffff) {
339
+ hex = (Math.trunc(Number(v) / 0x100000000) >>> 0).toString(16) + (Number(v) >>> 0).toString(16).padStart(8, "0");
340
+ } else {
341
+ hex = (Number(v) >>> 0).toString(16);
342
+ }
343
+ return pad(hex, width, zero);
344
+ }
345
+ case "X": {
346
+ let hex;
347
+ if (Array.isArray(v) || ArrayBuffer.isView(v)) {
348
+ hex = Array.from(v).map((b) => (Number(b) & 0xff).toString(16).padStart(2, "0").toUpperCase()).join("");
349
+ } else if (typeof v === "string") {
350
+ hex = Array.from(new TextEncoder().encode(v)).map((b) => b.toString(16).padStart(2, "0").toUpperCase()).join("");
351
+ } else if (typeof v === "bigint") {
352
+ hex = BigInt.asUintN(64, v).toString(16).toUpperCase();
353
+ } else if (Math.abs(Number(v)) > 0xffffffff) {
354
+ hex = (Math.trunc(Number(v) / 0x100000000) >>> 0).toString(16).toUpperCase() + (Number(v) >>> 0).toString(16).padStart(8, "0").toUpperCase();
355
+ } else {
356
+ hex = (Number(v) >>> 0).toString(16).toUpperCase();
357
+ }
358
+ return pad(hex, width, zero);
359
+ }
360
+ case "o": return pad((typeof v === "bigint" ? BigInt.asUintN(64, v).toString(8) : (Number(v) >>> 0).toString(8)), width, zero);
361
+ case "b": return pad((typeof v === "bigint" ? BigInt.asUintN(64, v).toString(2) : (Number(v) >>> 0).toString(2)), width, zero);
129
362
  case "q": return pad('"' + String(v == null ? "" : v).replace(/\\\\/g, "\\\\\\\\").replace(/"/g, '\\\\"') + '"', width, false);
130
363
  case "e": case "E": { const n = Number(v), p = prec !== "" ? parseInt(prec) : 6; return pad(n.toExponential(p), width, zero); }
131
364
  case "g": case "G": { const n = Number(v); return pad(prec !== "" ? n.toPrecision(parseInt(prec)) : String(n), width, zero); }
@@ -139,17 +372,184 @@ export const HELPER_ERROR = `var __error = __error || function(msg, cause) {
139
372
  return { Error() { return msg; }, toString() { return msg; }, _msg: msg, _cause: cause ?? null };
140
373
  };`;
141
374
 
142
- export const HELPER_ERROR_IS = `var __errorIs = __errorIs || function(err, target) {
143
- while (err !== null && err !== undefined) {
144
- if (err === target) return true;
145
- if (typeof err === "object" && typeof target === "object" &&
146
- err._msg !== undefined && target._msg !== undefined &&
147
- err._msg === target._msg) return true;
148
- err = err?._cause ?? null;
375
+ export const HELPER_STRCONV_ERROR = `var __strconv_err_syntax = __strconv_err_syntax || __error("invalid syntax");
376
+ var __strconv_err_range = __strconv_err_range || __error("value out of range");`;
377
+
378
+ export const HELPER_PATH_ERROR = `var __path_err_bad_pattern = __path_err_bad_pattern || __error("syntax error in pattern");`;
379
+
380
+ export const HELPER_IO_EOF = `var __io_eof = __io_eof || __error("EOF");`;
381
+
382
+ export const HELPER_ERROR_IS = `var __errorIs = __errorIs || function __errorIs(err, target) {
383
+ if (err === null || err === undefined) return false;
384
+ if (err === target) return true;
385
+ if (typeof err === "object" && typeof target === "object" &&
386
+ err._msg !== undefined && target._msg !== undefined &&
387
+ err._msg === target._msg) return true;
388
+ if (typeof err.Is === "function" && err.Is(target)) return true;
389
+ if (Array.isArray(err._errs)) {
390
+ for (const sub of err._errs) {
391
+ if (__errorIs(sub, target)) return true;
392
+ }
393
+ }
394
+ if (typeof err.Unwrap === "function") {
395
+ const unwrapped = err.Unwrap();
396
+ if (Array.isArray(unwrapped)) {
397
+ for (const sub of unwrapped) {
398
+ if (__errorIs(sub, target)) return true;
399
+ }
400
+ } else if (unwrapped !== null && unwrapped !== undefined) {
401
+ if (__errorIs(unwrapped, target)) return true;
402
+ }
403
+ }
404
+ if (err._cause !== undefined && err._cause !== null) {
405
+ return __errorIs(err._cause, target);
149
406
  }
150
407
  return false;
151
408
  };`;
152
409
 
410
+ export const HELPER_ERROR_AS = `var __errorAs = __errorAs || function(err, target, matcher) {
411
+ if (err === null || err === undefined || target === null || typeof target !== "object") return false;
412
+ let cur = err;
413
+ while (cur !== null && cur !== undefined) {
414
+ const unboxed = cur?.value ?? cur;
415
+ if (typeof cur.As === "function" && cur.As(target)) return true;
416
+ if (matcher ? matcher(unboxed) : (unboxed !== err && typeof unboxed === "object" && !("_msg" in unboxed && "_cause" in unboxed))) {
417
+ if ("value" in target) {
418
+ target.value = unboxed;
419
+ } else {
420
+ Object.assign(target, unboxed);
421
+ }
422
+ return true;
423
+ }
424
+ if (Array.isArray(cur._errs)) {
425
+ for (const sub of cur._errs) {
426
+ if (__errorAs(sub, target, matcher)) return true;
427
+ }
428
+ }
429
+ if (typeof cur.Unwrap === "function") {
430
+ const unwrapped = cur.Unwrap();
431
+ if (Array.isArray(unwrapped)) {
432
+ for (const sub of unwrapped) {
433
+ if (__errorAs(sub, target, matcher)) return true;
434
+ }
435
+ } else if (unwrapped !== null && unwrapped !== undefined) {
436
+ if (__errorAs(unwrapped, target, matcher)) return true;
437
+ }
438
+ }
439
+ cur = cur?._cause ?? null;
440
+ }
441
+ return false;
442
+ };`;
443
+
444
+ export const HELPER_ERROR_JOIN = `var __errorJoin = __errorJoin || function(...errs) {
445
+ const filtered = [];
446
+ for (const e of errs) {
447
+ if (Array.isArray(e)) {
448
+ for (const sub of e) if (sub !== null && sub !== undefined) filtered.push(sub);
449
+ } else if (e !== null && e !== undefined) {
450
+ filtered.push(e);
451
+ }
452
+ }
453
+ if (filtered.length === 0) return null;
454
+ const msg = filtered.map(e => (typeof e === "object" && typeof e.Error === "function") ? e.Error() : String(e)).join("\\n");
455
+ const joined = __error(msg);
456
+ joined._errs = filtered;
457
+ joined.Unwrap = function() { return filtered; };
458
+ return joined;
459
+ };`;
460
+
461
+ // Go-semantics strconv parsers shared by the JS backend and the wasm runtime
462
+ // imports (boundary.js), so both targets agree. Each parser returns
463
+ // [value, errorMessage | null]; integer values are BigInt (the wasm side
464
+ // needs i64, the JS side converts with Number()).
465
+ export const HELPER_STRCONV = `var __strconv_atoi = __strconv_atoi || function(s) {
466
+ if (!/^[+-]?[0-9]+$/.test(s)) return [0n, 'strconv.Atoi: parsing "' + s + '": invalid syntax'];
467
+ const v = BigInt(s);
468
+ if (v > 9223372036854775807n || v < -9223372036854775808n) {
469
+ return [v > 0n ? 9223372036854775807n : -9223372036854775808n, 'strconv.Atoi: parsing "' + s + '": value out of range'];
470
+ }
471
+ return [v, null];
472
+ };
473
+ var __strconv_parse_int = __strconv_parse_int || function(s, base, bits) {
474
+ let str = s, neg = false;
475
+ if (str[0] === "-" || str[0] === "+") { neg = str[0] === "-"; str = str.slice(1); }
476
+ if (base === 0) {
477
+ if (/^0[xX]/.test(str)) { base = 16; str = str.slice(2); }
478
+ else if (/^0[bB]/.test(str)) { base = 2; str = str.slice(2); }
479
+ else if (/^0[oO]/.test(str)) { base = 8; str = str.slice(2); }
480
+ else if (/^0[0-9]/.test(str)) { base = 8; str = str.slice(1); }
481
+ else base = 10;
482
+ str = str.replaceAll("_", "");
483
+ }
484
+ if (base < 2 || base > 36) return [0n, 'strconv.ParseInt: parsing "' + s + '": invalid base ' + base];
485
+ const digits = "0123456789abcdefghijklmnopqrstuvwxyz".slice(0, base);
486
+ if (str === "" || [...str.toLowerCase()].some((c) => !digits.includes(c))) {
487
+ return [0n, 'strconv.ParseInt: parsing "' + s + '": invalid syntax'];
488
+ }
489
+ let v = 0n; const B = BigInt(base);
490
+ for (const c of str.toLowerCase()) v = v * B + BigInt(digits.indexOf(c));
491
+ if (neg) v = -v;
492
+ const w = bits === 0 ? 64 : bits;
493
+ const max = (1n << BigInt(w - 1)) - 1n, min = -(1n << BigInt(w - 1));
494
+ if (v > max || v < min) return [v > max ? max : min, 'strconv.ParseInt: parsing "' + s + '": value out of range'];
495
+ return [v, null];
496
+ };
497
+ var __strconv_parse_uint = __strconv_parse_uint || function(s, base, bits) {
498
+ let str = s;
499
+ if (str[0] === "+") { str = str.slice(1); }
500
+ if (str[0] === "-") {
501
+ return [0n, 'strconv.ParseUint: parsing "' + s + '": invalid syntax'];
502
+ }
503
+ if (base === 0) {
504
+ if (/^0[xX]/.test(str)) { base = 16; str = str.slice(2); }
505
+ else if (/^0[bB]/.test(str)) { base = 2; str = str.slice(2); }
506
+ else if (/^0[oO]/.test(str)) { base = 8; str = str.slice(2); }
507
+ else if (/^0[0-9]/.test(str)) { base = 8; str = str.slice(1); }
508
+ else base = 10;
509
+ str = str.replaceAll("_", "");
510
+ }
511
+ if (base < 2 || base > 36) return [0n, 'strconv.ParseUint: parsing "' + s + '": invalid base ' + base];
512
+ const digits = "0123456789abcdefghijklmnopqrstuvwxyz".slice(0, base);
513
+ if (str === "" || [...str.toLowerCase()].some((c) => !digits.includes(c))) {
514
+ return [0n, 'strconv.ParseUint: parsing "' + s + '": invalid syntax'];
515
+ }
516
+ let v = 0n; const B = BigInt(base);
517
+ for (const c of str.toLowerCase()) v = v * B + BigInt(digits.indexOf(c));
518
+ const w = bits === 0 ? 64 : bits;
519
+ const max = w >= 64 ? 18446744073709551615n : (1n << BigInt(w)) - 1n;
520
+ if (v > max) return [max, 'strconv.ParseUint: parsing "' + s + '": value out of range'];
521
+ return [v, null];
522
+ };
523
+ var __strconv_parse_float = __strconv_parse_float || function(s) {
524
+ const str = s.replaceAll("_", "");
525
+ if (/^[+-]?(inf|infinity)$/i.test(str)) return [str[0] === "-" ? -Infinity : Infinity, null];
526
+ if (/^[+-]?nan$/i.test(str)) return [NaN, null];
527
+ if (str === "" || !/^[+-]?(\\d+\\.?\\d*|\\.\\d+)([eE][+-]?\\d+)?$|^[+-]?0[xX][0-9a-fA-F]+$/.test(str)) {
528
+ return [0, 'strconv.ParseFloat: parsing "' + s + '": invalid syntax'];
529
+ }
530
+ return [Number(str), null];
531
+ };
532
+ var __strconv_parse_bool = __strconv_parse_bool || function(s) {
533
+ if (["1", "t", "T", "TRUE", "true", "True"].includes(s)) return [true, null];
534
+ if (["0", "f", "F", "FALSE", "false", "False"].includes(s)) return [false, null];
535
+ return [false, 'strconv.ParseBool: parsing "' + s + '": invalid syntax'];
536
+ };
537
+ var __strconv_format_float = __strconv_format_float || function(f, fmtc, prec) {
538
+ const c = String.fromCharCode(fmtc);
539
+ if (!Number.isFinite(f)) return f !== f ? "NaN" : (f > 0 ? "+Inf" : "-Inf");
540
+ if (c === "f") return prec < 0 ? String(f) : f.toFixed(prec);
541
+ if (c === "e" || c === "E") {
542
+ const r = prec < 0 ? f.toExponential() : f.toExponential(prec);
543
+ const o = r.replace(/e([+-])(\\d)$/, "e$10$2");
544
+ return c === "E" ? o.toUpperCase() : o;
545
+ }
546
+ if (c === "g" || c === "G") {
547
+ const r = prec < 0 ? String(f) : f.toPrecision(prec);
548
+ return c === "G" ? r.toUpperCase() : r;
549
+ }
550
+ return String(f);
551
+ };`;
552
+
153
553
  export const HELPER_PATH_CLEAN = `var __pathClean = __pathClean || function(p) {
154
554
  if (!p) return ".";
155
555
  const abs = p.startsWith("/");
@@ -162,37 +562,159 @@ export const HELPER_PATH_CLEAN = `var __pathClean = __pathClean || function(p) {
162
562
  return acc;
163
563
  }, []);
164
564
  return (abs ? "/" : "") + (parts.join("/") || ".");
565
+ };
566
+ var __pathMatch = __pathMatch || function(pat, name) {
567
+ let rx = "^";
568
+ let hasErr = false;
569
+ let i = 0;
570
+ while (i < pat.length) {
571
+ const c = pat[i];
572
+ if (c === "\\\\") {
573
+ if (i + 1 >= pat.length) { hasErr = true; break; }
574
+ const next = pat[++i];
575
+ if (/[.^$*+?()|{}\\[\\]\\\\]/.test(next)) rx += "\\\\" + next;
576
+ else rx += next;
577
+ i++;
578
+ } else if (c === "*") {
579
+ rx += "[^/]*";
580
+ i++;
581
+ } else if (c === "?") {
582
+ rx += "[^/]";
583
+ i++;
584
+ } else if (c === "[") {
585
+ i++;
586
+ let negated = false;
587
+ if (i < pat.length && pat[i] === "^") {
588
+ negated = true;
589
+ i++;
590
+ }
591
+ if (i >= pat.length || pat[i] === "]") {
592
+ return [false, true];
593
+ }
594
+ let classContent = "";
595
+ let closed = false;
596
+ while (i < pat.length) {
597
+ let ch = pat[i];
598
+ if (ch === "]") {
599
+ closed = true;
600
+ i++;
601
+ break;
602
+ }
603
+ if (ch === "\\\\") {
604
+ if (i + 1 >= pat.length) { hasErr = true; break; }
605
+ ch = pat[++i];
606
+ }
607
+ if (ch === "/") {
608
+ return [false, true];
609
+ }
610
+ i++;
611
+ if (i + 1 < pat.length && pat[i] === "-" && pat[i + 1] !== "]") {
612
+ i++;
613
+ let end = pat[i];
614
+ if (end === "\\\\") {
615
+ if (i + 1 >= pat.length) { hasErr = true; break; }
616
+ end = pat[++i];
617
+ }
618
+ if (end === "/") return [false, true];
619
+ i++;
620
+ if (ch.charCodeAt(0) > end.charCodeAt(0)) return [false, true];
621
+ if (ch.charCodeAt(0) <= 47 && 47 <= end.charCodeAt(0)) return [false, true];
622
+ const isSpec = (c) => c === "-" || c === "^" || c === "\\\\" || c === "[" || c === "]";
623
+ const escCh = isSpec(ch) ? "\\\\" + ch : ch;
624
+ const escEnd = isSpec(end) ? "\\\\" + end : end;
625
+ classContent += escCh + "-" + escEnd;
626
+ } else {
627
+ const isSpec = (c) => c === "-" || c === "^" || c === "\\\\" || c === "[" || c === "]";
628
+ const escCh = isSpec(ch) ? "\\\\" + ch : ch;
629
+ classContent += escCh;
630
+ }
631
+ }
632
+ if (!closed || hasErr) return [false, true];
633
+ if (negated) {
634
+ rx += "[^/" + classContent + "]";
635
+ } else {
636
+ rx += "[" + classContent + "]";
637
+ }
638
+ } else if (/[.^$*+?()|{}\\[\\]\\\\]/.test(c)) {
639
+ rx += "\\\\" + c;
640
+ i++;
641
+ } else {
642
+ rx += c;
643
+ i++;
644
+ }
645
+ }
646
+ if (hasErr) return [false, true];
647
+ try {
648
+ const re = new RegExp(rx + "$");
649
+ return [re.test(name), false];
650
+ } catch (e) {
651
+ return [false, true];
652
+ }
165
653
  };`;
166
654
 
167
655
  export const HELPER_TIME_FMT = `var __timeFmt = __timeFmt || function(d, layout) {
656
+ const dt = d instanceof Date ? d : (d?._d ?? d);
657
+ const isUtc = d?._offset === 0;
168
658
  const pad = (n, w = 2) => String(n).padStart(w, "0");
169
659
  const DAYS = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
170
660
  const MONTHS = ["January","February","March","April","May","June","July","August","September","October","November","December"];
171
- return layout.replace(/2006|06|Monday|Mon|January|Jan|01|1|02|2|15|PM|3|04|4|05|5|Z07:00|\\.000|\\.999/g, t => {
661
+ const getFullYear = () => isUtc ? dt.getUTCFullYear() : dt.getFullYear();
662
+ const getMonth = () => isUtc ? dt.getUTCMonth() : dt.getMonth();
663
+ const getDate = () => isUtc ? dt.getUTCDate() : dt.getDate();
664
+ const getDay = () => isUtc ? dt.getUTCDay() : dt.getDay();
665
+ const getHours = () => isUtc ? dt.getUTCHours() : dt.getHours();
666
+ const getMinutes = () => isUtc ? dt.getUTCMinutes() : dt.getMinutes();
667
+ const getSeconds = () => isUtc ? dt.getUTCSeconds() : dt.getSeconds();
668
+ const getMilliseconds = () => isUtc ? dt.getUTCMilliseconds() : dt.getMilliseconds();
669
+ const getTimezoneOffset = () => isUtc ? 0 : dt.getTimezoneOffset();
670
+ return layout.replace(/2006|06|Monday|Mon|January|Jan|01|02|15|PM|pm|03|04|05|Z07:00|-07:00|-0700|MST|\\.(?:0+|9+)|1|2|3|4|5/g, t => {
671
+ if (t.startsWith(".")) {
672
+ const isZeroPad = t.includes("0");
673
+ const maxLen = t.length - 1;
674
+ const ms = getMilliseconds();
675
+ let frac = pad(ms, 3);
676
+ if (maxLen > 3) frac = frac.padEnd(maxLen, "0");
677
+ else frac = frac.slice(0, maxLen);
678
+ if (!isZeroPad) {
679
+ frac = frac.replace(/0+$/, "");
680
+ return frac.length > 0 ? "." + frac : "";
681
+ } else {
682
+ return "." + frac;
683
+ }
684
+ }
172
685
  switch (t) {
173
- case "2006": return d.getFullYear();
174
- case "06": return String(d.getFullYear()).slice(-2);
175
- case "Monday": return DAYS[d.getDay()];
176
- case "Mon": return DAYS[d.getDay()].slice(0, 3);
177
- case "January": return MONTHS[d.getMonth()];
178
- case "Jan": return MONTHS[d.getMonth()].slice(0, 3);
179
- case "01": return pad(d.getMonth() + 1);
180
- case "1": return String(d.getMonth() + 1);
181
- case "02": return pad(d.getDate());
182
- case "2": return String(d.getDate());
183
- case "15": return pad(d.getHours());
184
- case "PM": return d.getHours() < 12 ? "AM" : "PM";
185
- case "3": return String(d.getHours() % 12 || 12);
186
- case "04": return pad(d.getMinutes());
187
- case "4": return String(d.getMinutes());
188
- case "05": return pad(d.getSeconds());
189
- case "5": return String(d.getSeconds());
686
+ case "2006": return getFullYear();
687
+ case "06": return String(getFullYear()).slice(-2);
688
+ case "Monday": return DAYS[getDay()];
689
+ case "Mon": return DAYS[getDay()].slice(0, 3);
690
+ case "January": return MONTHS[getMonth()];
691
+ case "Jan": return MONTHS[getMonth()].slice(0, 3);
692
+ case "01": return pad(getMonth() + 1);
693
+ case "1": return String(getMonth() + 1);
694
+ case "02": return pad(getDate());
695
+ case "2": return String(getDate());
696
+ case "15": return pad(getHours());
697
+ case "PM": return getHours() < 12 ? "AM" : "PM";
698
+ case "pm": return getHours() < 12 ? "am" : "pm";
699
+ case "03": return pad(getHours() % 12 || 12);
700
+ case "3": return String(getHours() % 12 || 12);
701
+ case "04": return pad(getMinutes());
702
+ case "4": return String(getMinutes());
703
+ case "05": return pad(getSeconds());
704
+ case "5": return String(getSeconds());
190
705
  case "Z07:00": {
191
- const o = -d.getTimezoneOffset();
706
+ const o = -getTimezoneOffset();
192
707
  return o === 0 ? "Z" : (o > 0 ? "+" : "-") + pad(Math.floor(Math.abs(o) / 60)) + ":" + pad(Math.abs(o) % 60);
193
708
  }
194
- case ".000": return "." + pad(d.getMilliseconds(), 3);
195
- case ".999": return d.getMilliseconds() > 0 ? "." + String(d.getMilliseconds()).replace(/0+$/, "") : "";
709
+ case "-07:00": {
710
+ const o = -getTimezoneOffset();
711
+ return (o >= 0 ? "+" : "-") + pad(Math.floor(Math.abs(o) / 60)) + ":" + pad(Math.abs(o) % 60);
712
+ }
713
+ case "-0700": {
714
+ const o = -getTimezoneOffset();
715
+ return (o >= 0 ? "+" : "-") + pad(Math.floor(Math.abs(o) / 60)) + pad(Math.abs(o) % 60);
716
+ }
717
+ case "MST": return isUtc ? "UTC" : "LOCAL";
196
718
  default: return t;
197
719
  }
198
720
  });
@@ -204,7 +726,7 @@ export const HELPER_TIME_PARSE = `var __timeParse = __timeParse || function(layo
204
726
  if (isNaN(d.getTime())) throw 0;
205
727
  return [{ _d: d }, null];
206
728
  } catch {
207
- return [{ _d: new Date(0) }, "parsing time: cannot parse"];
729
+ return [{ _d: new Date(0) }, { Error() { return "parsing time: cannot parse"; }, toString() { return "parsing time: cannot parse"; }, _msg: "parsing time: cannot parse", _cause: null }];
208
730
  }
209
731
  };`;
210
732
 
@@ -323,3 +845,483 @@ export const HELPER_INJECT_STYLES = `var __injectStyles = __injectStyles || func
323
845
  }
324
846
  s.textContent += "\\n" + css;
325
847
  };`;
848
+
849
+ export const HELPER_DURATION = `var __durationString = __durationString || function(d) {
850
+ d = BigInt(d);
851
+ if (d === 0n) return "0s";
852
+ let neg = false;
853
+ if (d < 0n) { neg = true; d = -d; }
854
+ let s = "";
855
+ const totalSec = d / 1000000000n;
856
+ const sec = totalSec % 60n;
857
+ const min = (totalSec / 60n) % 60n;
858
+ const hr = totalSec / 3600n;
859
+
860
+ if (hr > 0n) s += hr + "h";
861
+ const remAfterHr = d % 3600000000000n;
862
+ if (min > 0n || (hr > 0n && remAfterHr > 0n)) s += min + "m";
863
+ if (totalSec > 0n) {
864
+ const frac = d % 1000000000n;
865
+ if (sec > 0n || frac > 0n || (hr === 0n && min === 0n)) {
866
+ if (frac === 0n) {
867
+ s += sec + "s";
868
+ } else {
869
+ let fracStr = frac.toString().padStart(9, "0").replace(/0+$/, "");
870
+ s += sec + "." + fracStr + "s";
871
+ }
872
+ }
873
+ } else {
874
+ const ms = (d / 1000000n) % 1000n;
875
+ const us = (d / 1000n) % 1000n;
876
+ const ns = d % 1000n;
877
+ if (ms > 0n) {
878
+ const frac = d % 1000000n;
879
+ if (frac === 0n) s += ms + "ms";
880
+ else {
881
+ let fracStr = frac.toString().padStart(6, "0").replace(/0+$/, "");
882
+ s += ms + "." + fracStr + "ms";
883
+ }
884
+ } else if (us > 0n) {
885
+ const frac = d % 1000n;
886
+ if (frac === 0n) s += us + "µs";
887
+ else {
888
+ let fracStr = frac.toString().padStart(3, "0").replace(/0+$/, "");
889
+ s += us + "." + fracStr + "µs";
890
+ }
891
+ } else {
892
+ s += ns + "ns";
893
+ }
894
+ }
895
+ return neg ? "-" + s : s;
896
+ };`;
897
+
898
+ export const HELPER_SYNC = `var __sync_mutex = __sync_mutex || function() {
899
+ return { Lock() {}, Unlock() {}, TryLock() { return true; } };
900
+ };
901
+ var __sync_rwmutex = __sync_rwmutex || function() {
902
+ return { Lock() {}, Unlock() {}, RLock() {}, RUnlock() {}, TryLock() { return true; }, TryRLock() { return true; } };
903
+ };
904
+ var __sync_once = __sync_once || function() {
905
+ return { done: 0, Do(f) { if (!this.done) { this.done = 1; f(); } } };
906
+ };
907
+ var __sync_waitgroup = __sync_waitgroup || function() {
908
+ return { counter: 0, Add(d) { this.counter = (this.counter || 0) + d; }, Done() { this.counter = (this.counter || 0) - 1; }, Wait() {} };
909
+ };`;
910
+
911
+ export const HELPER_CRYPTO_RAND = `var __crypto_rand_read = __crypto_rand_read || function(b) {
912
+ if (!b || b.length === 0) return [0, null];
913
+ const u8 = ArrayBuffer.isView(b) ? b : new Uint8Array(b.length);
914
+ const c = typeof crypto !== "undefined" ? crypto : (typeof globalThis !== "undefined" ? globalThis.crypto : null);
915
+ const CHUNK = 65536;
916
+ if (c && typeof c.getRandomValues === "function") {
917
+ for (let offset = 0; offset < u8.length; offset += CHUNK) {
918
+ const slice = u8.subarray(offset, Math.min(offset + CHUNK, u8.length));
919
+ c.getRandomValues(slice);
920
+ }
921
+ } else {
922
+ for (let i = 0; i < u8.length; i++) u8[i] = Math.floor(Math.random() * 256);
923
+ }
924
+ if (!ArrayBuffer.isView(b)) {
925
+ for (let i = 0; i < u8.length; i++) b[i] = u8[i];
926
+ }
927
+ return [b.length, null];
928
+ };
929
+ var __crypto_rand_reader = __crypto_rand_reader || {
930
+ Read: function(b) { return __crypto_rand_read(b); }
931
+ };`;
932
+
933
+ export const HELPER_SHA256 = `var __sha256 = __sha256 || (function() {
934
+ const K = [
935
+ 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
936
+ 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
937
+ 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
938
+ 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
939
+ 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
940
+ 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
941
+ 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
942
+ 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
943
+ ];
944
+ function rotr(x, n) { return (x >>> n) | (x << (32 - n)); }
945
+ function block(H, M) {
946
+ const W = new Int32Array(64);
947
+ for (let i = 0; i < 16; i++) {
948
+ W[i] = (M[i * 4] << 24) | (M[i * 4 + 1] << 16) | (M[i * 4 + 2] << 8) | M[i * 4 + 3];
949
+ }
950
+ for (let i = 16; i < 64; i++) {
951
+ const s0 = rotr(W[i - 15], 7) ^ rotr(W[i - 15], 18) ^ (W[i - 15] >>> 3);
952
+ const s1 = rotr(W[i - 2], 17) ^ rotr(W[i - 2], 19) ^ (W[i - 2] >>> 10);
953
+ W[i] = (W[i - 16] + s0 + W[i - 7] + s1) | 0;
954
+ }
955
+ let [a, b, c, d, e, f, g, h] = H;
956
+ for (let i = 0; i < 64; i++) {
957
+ const S1 = rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25);
958
+ const ch = (e & f) ^ (~e & g);
959
+ const t1 = (h + S1 + ch + K[i] + W[i]) | 0;
960
+ const S0 = rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22);
961
+ const maj = (a & b) ^ (a & c) ^ (b & c);
962
+ const t2 = (S0 + maj) | 0;
963
+ h = g; g = f; f = e; e = (d + t1) | 0;
964
+ d = c; c = b; b = a; a = (t1 + t2) | 0;
965
+ }
966
+ H[0] = (H[0] + a) | 0; H[1] = (H[1] + b) | 0; H[2] = (H[2] + c) | 0; H[3] = (H[3] + d) | 0;
967
+ H[4] = (H[4] + e) | 0; H[5] = (H[5] + f) | 0; H[6] = (H[6] + g) | 0; H[7] = (H[7] + h) | 0;
968
+ }
969
+ function digest(bytes) {
970
+ const H = new Int32Array([
971
+ 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a,
972
+ 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19
973
+ ]);
974
+ const len = bytes ? bytes.length : 0;
975
+ const padLen = (len % 64 < 56) ? (56 - (len % 64)) : (120 - (len % 64));
976
+ const total = len + padLen + 8;
977
+ const buf = new Uint8Array(total);
978
+ if (bytes) {
979
+ if (ArrayBuffer.isView(bytes)) buf.set(bytes);
980
+ else for (let i = 0; i < len; i++) buf[i] = bytes[i];
981
+ }
982
+ buf[len] = 0x80;
983
+ const bits = BigInt(len) * 8n;
984
+ for (let i = 0; i < 8; i++) {
985
+ buf[total - 1 - i] = Number((bits >> BigInt(i * 8)) & 0xffn);
986
+ }
987
+ for (let i = 0; i < total; i += 64) {
988
+ block(H, buf.subarray(i, i + 64));
989
+ }
990
+ const out = new Uint8Array(32);
991
+ for (let i = 0; i < 8; i++) {
992
+ out[i * 4] = (H[i] >>> 24) & 0xff;
993
+ out[i * 4 + 1] = (H[i] >>> 16) & 0xff;
994
+ out[i * 4 + 2] = (H[i] >>> 8) & 0xff;
995
+ out[i * 4 + 3] = H[i] & 0xff;
996
+ }
997
+ return out;
998
+ }
999
+ class Hash {
1000
+ constructor() { this.Reset(); }
1001
+ Reset() { this.buf = []; }
1002
+ Write(p) {
1003
+ if (p) {
1004
+ for (let i = 0; i < p.length; i++) this.buf.push(p[i]);
1005
+ }
1006
+ return [p ? p.length : 0, null];
1007
+ }
1008
+ Sum(b) {
1009
+ const d = digest(this.buf);
1010
+ if (!b || b.length === 0) return d;
1011
+ const res = new Uint8Array(b.length + d.length);
1012
+ res.set(b, 0);
1013
+ res.set(d, b.length);
1014
+ return res;
1015
+ }
1016
+ Size() { return 32; }
1017
+ BlockSize() { return 64; }
1018
+ }
1019
+ return {
1020
+ Sum256: digest,
1021
+ New: () => new Hash()
1022
+ };
1023
+ })();`;
1024
+
1025
+ export const HELPER_BINARY = `var __binary_le = __binary_le || {
1026
+ Uint16: function(b) { return (b[0] | (b[1] << 8)) & 0xffff; },
1027
+ Uint32: function(b) { return ((b[0] | (b[1] << 8) | (b[2] << 16) | (b[3] << 24)) >>> 0); },
1028
+ Uint64: function(b) {
1029
+ const lo = BigInt((b[0] | (b[1] << 8) | (b[2] << 16) | (b[3] << 24)) >>> 0);
1030
+ const hi = BigInt((b[4] | (b[5] << 8) | (b[6] << 16) | (b[7] << 24)) >>> 0);
1031
+ return Number(lo | (hi << 32n));
1032
+ },
1033
+ PutUint16: function(b, v) { b[0] = v & 0xff; b[1] = (v >> 8) & 0xff; },
1034
+ PutUint32: function(b, v) { b[0] = v & 0xff; b[1] = (v >> 8) & 0xff; b[2] = (v >> 16) & 0xff; b[3] = (v >>> 24) & 0xff; },
1035
+ PutUint64: function(b, v) {
1036
+ const bv = BigInt(v);
1037
+ for (let i = 0n; i < 8n; i++) b[Number(i)] = Number((bv >> (i * 8n)) & 0xffn);
1038
+ },
1039
+ AppendUint16: function(b, v) {
1040
+ const len = b ? b.length : 0;
1041
+ const res = new Uint8Array(len + 2);
1042
+ if (len > 0) res.set(b, 0);
1043
+ res[len] = v & 0xff;
1044
+ res[len + 1] = (v >> 8) & 0xff;
1045
+ return res;
1046
+ },
1047
+ AppendUint32: function(b, v) {
1048
+ const len = b ? b.length : 0;
1049
+ const res = new Uint8Array(len + 4);
1050
+ if (len > 0) res.set(b, 0);
1051
+ res[len] = v & 0xff;
1052
+ res[len + 1] = (v >> 8) & 0xff;
1053
+ res[len + 2] = (v >> 16) & 0xff;
1054
+ res[len + 3] = (v >>> 24) & 0xff;
1055
+ return res;
1056
+ },
1057
+ AppendUint64: function(b, v) {
1058
+ const len = b ? b.length : 0;
1059
+ const res = new Uint8Array(len + 8);
1060
+ if (len > 0) res.set(b, 0);
1061
+ const bv = BigInt(v);
1062
+ for (let i = 0n; i < 8n; i++) res[len + Number(i)] = Number((bv >> (i * 8n)) & 0xffn);
1063
+ return res;
1064
+ },
1065
+ String: function() { return "LittleEndian"; }
1066
+ };
1067
+ var __binary_be = __binary_be || {
1068
+ Uint16: function(b) { return ((b[0] << 8) | b[1]) & 0xffff; },
1069
+ Uint32: function(b) { return (((b[0] << 24) | (b[1] << 16) | (b[2] << 8) | b[3]) >>> 0); },
1070
+ Uint64: function(b) {
1071
+ const hi = BigInt(((b[0] << 24) | (b[1] << 16) | (b[2] << 8) | b[3]) >>> 0);
1072
+ const lo = BigInt(((b[4] << 24) | (b[5] << 16) | (b[6] << 8) | b[7]) >>> 0);
1073
+ return Number((hi << 32n) | lo);
1074
+ },
1075
+ PutUint16: function(b, v) { b[0] = (v >> 8) & 0xff; b[1] = v & 0xff; },
1076
+ PutUint32: function(b, v) { b[0] = (v >>> 24) & 0xff; b[1] = (v >> 16) & 0xff; b[2] = (v >> 8) & 0xff; b[3] = v & 0xff; },
1077
+ PutUint64: function(b, v) {
1078
+ const bv = BigInt(v);
1079
+ for (let i = 0n; i < 8n; i++) b[Number(7n - i)] = Number((bv >> (i * 8n)) & 0xffn);
1080
+ },
1081
+ AppendUint16: function(b, v) {
1082
+ const len = b ? b.length : 0;
1083
+ const res = new Uint8Array(len + 2);
1084
+ if (len > 0) res.set(b, 0);
1085
+ res[len] = (v >> 8) & 0xff;
1086
+ res[len + 1] = v & 0xff;
1087
+ return res;
1088
+ },
1089
+ AppendUint32: function(b, v) {
1090
+ const len = b ? b.length : 0;
1091
+ const res = new Uint8Array(len + 4);
1092
+ if (len > 0) res.set(b, 0);
1093
+ res[len] = (v >>> 24) & 0xff;
1094
+ res[len + 1] = (v >> 16) & 0xff;
1095
+ res[len + 2] = (v >> 8) & 0xff;
1096
+ res[len + 3] = v & 0xff;
1097
+ return res;
1098
+ },
1099
+ AppendUint64: function(b, v) {
1100
+ const len = b ? b.length : 0;
1101
+ const res = new Uint8Array(len + 8);
1102
+ if (len > 0) res.set(b, 0);
1103
+ const bv = BigInt(v);
1104
+ for (let i = 0n; i < 8n; i++) res[len + Number(i)] = Number((bv >> ((7n - i) * 8n)) & 0xffn);
1105
+ return res;
1106
+ },
1107
+ String: function() { return "BigEndian"; }
1108
+ };
1109
+ var __binary_size = __binary_size || function(v) {
1110
+ if (typeof v === "number" || typeof v === "bigint") return 8;
1111
+ if (Array.isArray(v) || ArrayBuffer.isView(v)) return v.length;
1112
+ if (v && typeof v === "object") {
1113
+ let s = 0;
1114
+ for (const k of Object.keys(v)) { if (!k.startsWith("_") && typeof v[k] !== "function") s += __binary_size(v[k]); }
1115
+ return s;
1116
+ }
1117
+ return -1;
1118
+ };
1119
+ var __binary_read = __binary_read || function(r, order, data, sz, typeTag) {
1120
+ const targetR = r?.value ?? r;
1121
+ const readChunk = function(buf) {
1122
+ if (typeof targetR?.Read === "function") return targetR.Read(buf);
1123
+ if (Array.isArray(targetR?._buf)) {
1124
+ const n = Math.min(buf.length, targetR._buf.length);
1125
+ for (let i = 0; i < n; i++) buf[i] = targetR._buf.shift();
1126
+ return [n, n < buf.length ? __io_eof : null];
1127
+ }
1128
+ return [0, __error("binary.Read: unsupported reader")];
1129
+ };
1130
+ const isBox = data && typeof data === "object" && Object.prototype.hasOwnProperty.call(data, "value") && (data.__box === true || (Object.keys(data).length <= 2 && (data.constructor === Object || !data.constructor || data.constructor?.name === "Object")));
1131
+ const target = isBox ? data : null;
1132
+ if (!target && data && typeof data === "object" && !Array.isArray(data) && !ArrayBuffer.isView(data)) {
1133
+ for (const k of Object.keys(data)) {
1134
+ if (k.startsWith("_") || typeof data[k] === "function") continue;
1135
+ const fBox = { value: data[k], __box: true };
1136
+ const err = __binary_read(r, order, fBox);
1137
+ if (err) return err;
1138
+ data[k] = fBox.value;
1139
+ }
1140
+ return null;
1141
+ }
1142
+ const s = sz || (target ? (typeof target.value === "bigint" ? 8 : (typeof target.value === "number" ? 4 : 4)) : __binary_size(data?.value ?? data));
1143
+ if (s <= 0) return __error("binary.Read: invalid type");
1144
+ const buf = new Uint8Array(s);
1145
+ const [n, err] = readChunk(buf);
1146
+ if (err) return err;
1147
+ if (n < s) return __io_eof;
1148
+ if (target) {
1149
+ const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
1150
+ const isLe = order.String() === "LittleEndian";
1151
+ if (typeTag === "float32") target.value = view.getFloat32(0, isLe);
1152
+ else if (typeTag === "float64") target.value = view.getFloat64(0, isLe);
1153
+ else if (typeTag === "int8") target.value = view.getInt8(0);
1154
+ else if (typeTag === "uint8" || typeTag === "byte" || typeTag === "bool") target.value = view.getUint8(0);
1155
+ else if (typeTag === "int16") target.value = view.getInt16(0, isLe);
1156
+ else if (typeTag === "uint16") target.value = view.getUint16(0, isLe);
1157
+ else if (typeTag === "int32" || typeTag === "rune") target.value = view.getInt32(0, isLe);
1158
+ else if (typeTag === "uint32") target.value = view.getUint32(0, isLe);
1159
+ else if (typeTag === "int64") target.value = Number(view.getBigInt64(0, isLe));
1160
+ else if (typeTag === "uint64") target.value = Number(view.getBigUint64(0, isLe));
1161
+ else if (s === 1) target.value = buf[0];
1162
+ else if (s === 2) target.value = order.Uint16(buf);
1163
+ else if (s === 4) target.value = order.Uint32(buf);
1164
+ else if (s === 8) target.value = order.Uint64(buf);
1165
+ return null;
1166
+ }
1167
+ if (Array.isArray(data) || ArrayBuffer.isView(data)) {
1168
+ for (let i = 0; i < s; i++) data[i] = buf[i];
1169
+ return null;
1170
+ }
1171
+ return null;
1172
+ };
1173
+ var __binary_write = __binary_write || function(w, order, data, sz, typeTag) {
1174
+ const targetW = w?.value ?? w;
1175
+ const writeChunk = function(chunk) {
1176
+ if (typeof targetW?.Write === "function") return targetW.Write(chunk);
1177
+ if (Array.isArray(targetW?._buf)) {
1178
+ for (let i = 0; i < chunk.length; i++) targetW._buf.push(chunk[i]);
1179
+ return [chunk.length, null];
1180
+ }
1181
+ if (typeof targetW?._buf === "string") {
1182
+ targetW._buf += new TextDecoder().decode(chunk);
1183
+ return [chunk.length, null];
1184
+ }
1185
+ return [0, __error("binary.Write: unsupported writer")];
1186
+ };
1187
+ const isBox = data && typeof data === "object" && Object.prototype.hasOwnProperty.call(data, "value") && (data.__box === true || (Object.keys(data).length <= 2 && (data.constructor === Object || !data.constructor || data.constructor?.name === "Object")));
1188
+ const v = isBox ? data.value : data;
1189
+ if (!isBox && typeof data === "object" && data !== null && !Array.isArray(data) && !ArrayBuffer.isView(data)) {
1190
+ for (const k of Object.keys(data)) {
1191
+ if (k.startsWith("_") || typeof data[k] === "function") continue;
1192
+ const err = __binary_write(w, order, data[k]);
1193
+ if (err) return err;
1194
+ }
1195
+ return null;
1196
+ }
1197
+ if (typeof v === "number" || typeof v === "bigint" || typeof v === "boolean") {
1198
+ const s = sz || (typeof v === "bigint" ? 8 : (typeTag === "float64" ? 8 : 4));
1199
+ const buf = new Uint8Array(s);
1200
+ const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
1201
+ const isLe = order.String() === "LittleEndian";
1202
+ if (typeTag === "float32") view.setFloat32(0, Number(v), isLe);
1203
+ else if (typeTag === "float64") view.setFloat64(0, Number(v), isLe);
1204
+ else if (s === 1) buf[0] = Number(v) & 0xff;
1205
+ else if (s === 2) order.PutUint16(buf, Number(v));
1206
+ else if (s === 4) order.PutUint32(buf, Number(v));
1207
+ else order.PutUint64(buf, v);
1208
+ const [, err] = writeChunk(buf);
1209
+ return err;
1210
+ }
1211
+ if (Array.isArray(v) || ArrayBuffer.isView(v)) {
1212
+ const [, err] = writeChunk(v);
1213
+ return err;
1214
+ }
1215
+ return __error("binary.Write: unsupported type");
1216
+ };`;
1217
+
1218
+ export const HELPER_HEX = `var __hex_encode_to_string = __hex_encode_to_string || function(src) {
1219
+ if (!src || src.length === 0) return "";
1220
+ let s = "";
1221
+ for (let i = 0; i < src.length; i++) s += src[i].toString(16).padStart(2, "0");
1222
+ return s;
1223
+ };
1224
+ var __hex_decode_string = __hex_decode_string || function(s) {
1225
+ if (s.length % 2 !== 0) return [new Uint8Array(0), __error("encoding/hex: odd length hex string")];
1226
+ const out = new Uint8Array(s.length / 2);
1227
+ for (let i = 0; i < s.length; i += 2) {
1228
+ const pair = s.slice(i, i + 2);
1229
+ if (!/^[0-9a-fA-F]{2}$/.test(pair)) {
1230
+ return [out.subarray(0, i / 2), __error("encoding/hex: invalid byte: " + pair)];
1231
+ }
1232
+ out[i / 2] = parseInt(pair, 16);
1233
+ }
1234
+ return [out, null];
1235
+ };
1236
+ var __hex_encode = __hex_encode || function(dst, src) {
1237
+ const hex = __hex_encode_to_string(src);
1238
+ for (let i = 0; i < hex.length; i++) dst[i] = hex.charCodeAt(i);
1239
+ return hex.length;
1240
+ };
1241
+ var __hex_decode = __hex_decode || function(dst, src) {
1242
+ const str = typeof src === "string" ? src : (src instanceof Uint8Array ? new TextDecoder().decode(src) : String.fromCharCode(...src));
1243
+ const [res, err] = __hex_decode_string(str);
1244
+ for (let i = 0; i < res.length; i++) dst[i] = res[i];
1245
+ return [res.length, err];
1246
+ };`;
1247
+
1248
+ export const HELPER_BASE64 = `var __base64_make = __base64_make || function(alphabet, padChar) {
1249
+ const encMap = alphabet.split("");
1250
+ const decMap = {};
1251
+ for (let i = 0; i < 64; i++) decMap[alphabet[i]] = i;
1252
+ return {
1253
+ EncodeToString: function(src) {
1254
+ if (!src || src.length === 0) return "";
1255
+ let res = "";
1256
+ let i = 0;
1257
+ for (; i + 2 < src.length; i += 3) {
1258
+ const n = (src[i] << 16) | (src[i + 1] << 8) | src[i + 2];
1259
+ res += encMap[(n >> 18) & 63] + encMap[(n >> 12) & 63] + encMap[(n >> 6) & 63] + encMap[n & 63];
1260
+ }
1261
+ if (i < src.length) {
1262
+ if (src.length - i === 1) {
1263
+ const n = src[i] << 16;
1264
+ res += encMap[(n >> 18) & 63] + encMap[(n >> 12) & 63];
1265
+ if (padChar) res += padChar + padChar;
1266
+ } else {
1267
+ const n = (src[i] << 16) | (src[i + 1] << 8);
1268
+ res += encMap[(n >> 18) & 63] + encMap[(n >> 12) & 63] + encMap[(n >> 6) & 63];
1269
+ if (padChar) res += padChar;
1270
+ }
1271
+ }
1272
+ return res;
1273
+ },
1274
+ DecodeString: function(s) {
1275
+ let str = s.replace(/\\s+/g, "");
1276
+ if (padChar) {
1277
+ if (str.length % 4 !== 0) return [new Uint8Array(0), __error("illegal base64 data at input byte " + str.length)];
1278
+ if (str.endsWith(padChar + padChar)) {
1279
+ if (str.endsWith(padChar + padChar + padChar)) return [new Uint8Array(0), __error("illegal base64 data at input byte " + (str.length - 3))];
1280
+ str = str.slice(0, -2);
1281
+ if (str.length % 4 !== 2) return [new Uint8Array(0), __error("illegal base64 data at input byte " + str.length)];
1282
+ } else if (str.endsWith(padChar)) {
1283
+ str = str.slice(0, -1);
1284
+ if (str.length % 4 !== 3) return [new Uint8Array(0), __error("illegal base64 data at input byte " + str.length)];
1285
+ }
1286
+ }
1287
+ const out = [];
1288
+ let i = 0;
1289
+ for (; i + 3 < str.length; i += 4) {
1290
+ const c0 = decMap[str[i]], c1 = decMap[str[i+1]], c2 = decMap[str[i+2]], c3 = decMap[str[i+3]];
1291
+ if (c0 === undefined || c1 === undefined || c2 === undefined || c3 === undefined) return [new Uint8Array(out), __error("illegal base64 data at input byte " + i)];
1292
+ const n = (c0 << 18) | (c1 << 12) | (c2 << 6) | c3;
1293
+ out.push((n >> 16) & 0xff, (n >> 8) & 0xff, n & 0xff);
1294
+ }
1295
+ const rem = str.length - i;
1296
+ if (rem === 2) {
1297
+ const c0 = decMap[str[i]], c1 = decMap[str[i+1]];
1298
+ if (c0 === undefined || c1 === undefined) return [new Uint8Array(out), __error("illegal base64 data at input byte " + i)];
1299
+ out.push((c0 << 2) | (c1 >> 4));
1300
+ } else if (rem === 3) {
1301
+ const c0 = decMap[str[i]], c1 = decMap[str[i+1]], c2 = decMap[str[i+2]];
1302
+ if (c0 === undefined || c1 === undefined || c2 === undefined) return [new Uint8Array(out), __error("illegal base64 data at input byte " + i)];
1303
+ out.push((c0 << 2) | (c1 >> 4), ((c1 & 15) << 4) | (c2 >> 2));
1304
+ } else if (rem === 1) {
1305
+ return [new Uint8Array(out), __error("illegal base64 data at input byte " + i)];
1306
+ }
1307
+ return [new Uint8Array(out), null];
1308
+ },
1309
+ Encode: function(dst, src) {
1310
+ const s = this.EncodeToString(src);
1311
+ for (let i = 0; i < s.length; i++) dst[i] = s.charCodeAt(i);
1312
+ },
1313
+ Decode: function(dst, src) {
1314
+ const str = String.fromCharCode(...src);
1315
+ const [res, err] = this.DecodeString(str);
1316
+ for (let i = 0; i < res.length; i++) dst[i] = res[i];
1317
+ return [res.length, err];
1318
+ },
1319
+ EncodedLen: function(n) { return padChar ? Math.ceil(n / 3) * 4 : Math.floor((n * 8 + 5) / 6); },
1320
+ DecodedLen: function(n) { return padChar ? Math.floor(n * 3 / 4) : Math.floor(n * 6 / 8); },
1321
+ WithPadding: function(p) { return __base64_make(alphabet, p === -1 ? "" : String.fromCharCode(p)); }
1322
+ };
1323
+ };
1324
+ var __base64_std = __base64_std || __base64_make("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/", "=");
1325
+ var __base64_url = __base64_url || __base64_make("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_", "=");
1326
+ var __base64_raw_std = __base64_raw_std || __base64_make("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/", "");
1327
+ var __base64_raw_url = __base64_raw_url || __base64_make("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_", "");`;