@usecanary/browser 0.4.3 → 0.4.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.
package/dist/cli.js CHANGED
@@ -2030,7 +2030,7 @@ var require_thread_stream = __commonJS({
2030
2030
  var { version } = require_package();
2031
2031
  var { EventEmitter } = __require("events");
2032
2032
  var { Worker } = __require("worker_threads");
2033
- var { join: join4 } = __require("path");
2033
+ var { join: join3 } = __require("path");
2034
2034
  var { pathToFileURL } = __require("url");
2035
2035
  var { wait } = require_wait();
2036
2036
  var {
@@ -2066,7 +2066,7 @@ var require_thread_stream = __commonJS({
2066
2066
  function createWorker(stream, opts) {
2067
2067
  const { filename, workerData } = opts;
2068
2068
  const bundlerOverrides = "__bundlerPathsOverrides" in globalThis ? globalThis.__bundlerPathsOverrides : {};
2069
- const toExecute = bundlerOverrides["thread-stream-worker"] || join4(__dirname, "lib", "worker.js");
2069
+ const toExecute = bundlerOverrides["thread-stream-worker"] || join3(__dirname, "lib", "worker.js");
2070
2070
  const worker = new Worker(toExecute, {
2071
2071
  ...opts.workerOpts,
2072
2072
  trackUnmanagedFds: false,
@@ -2452,7 +2452,7 @@ var require_transport = __commonJS({
2452
2452
  "use strict";
2453
2453
  var { createRequire } = __require("module");
2454
2454
  var getCallers = require_caller();
2455
- var { join: join4, isAbsolute: isAbsolute2, sep: sep2 } = __require("node:path");
2455
+ var { join: join3, isAbsolute: isAbsolute2, sep: sep2 } = __require("node:path");
2456
2456
  var sleep2 = require_atomic_sleep();
2457
2457
  var onExit = require_on_exit_leak_free();
2458
2458
  var ThreadStream = require_thread_stream();
@@ -2515,7 +2515,7 @@ var require_transport = __commonJS({
2515
2515
  throw new Error("only one of target or targets can be specified");
2516
2516
  }
2517
2517
  if (targets) {
2518
- target = bundlerOverrides["pino-worker"] || join4(__dirname, "worker.js");
2518
+ target = bundlerOverrides["pino-worker"] || join3(__dirname, "worker.js");
2519
2519
  options.targets = targets.filter((dest) => dest.target).map((dest) => {
2520
2520
  return {
2521
2521
  ...dest,
@@ -2533,7 +2533,7 @@ var require_transport = __commonJS({
2533
2533
  });
2534
2534
  });
2535
2535
  } else if (pipeline) {
2536
- target = bundlerOverrides["pino-worker"] || join4(__dirname, "worker.js");
2536
+ target = bundlerOverrides["pino-worker"] || join3(__dirname, "worker.js");
2537
2537
  options.pipelines = [pipeline.map((dest) => {
2538
2538
  return {
2539
2539
  ...dest,
@@ -2555,7 +2555,7 @@ var require_transport = __commonJS({
2555
2555
  return origin;
2556
2556
  }
2557
2557
  if (origin === "pino/file") {
2558
- return join4(__dirname, "..", "file.js");
2558
+ return join3(__dirname, "..", "file.js");
2559
2559
  }
2560
2560
  let fixTarget2;
2561
2561
  for (const filePath of callers) {
@@ -3544,7 +3544,7 @@ var require_safe_stable_stringify = __commonJS({
3544
3544
  return circularValue;
3545
3545
  }
3546
3546
  let res = "";
3547
- let join4 = ",";
3547
+ let join3 = ",";
3548
3548
  const originalIndentation = indentation;
3549
3549
  if (Array.isArray(value)) {
3550
3550
  if (value.length === 0) {
@@ -3558,7 +3558,7 @@ var require_safe_stable_stringify = __commonJS({
3558
3558
  indentation += spacer;
3559
3559
  res += `
3560
3560
  ${indentation}`;
3561
- join4 = `,
3561
+ join3 = `,
3562
3562
  ${indentation}`;
3563
3563
  }
3564
3564
  const maximumValuesToStringify = Math.min(value.length, maximumBreadth);
@@ -3566,13 +3566,13 @@ ${indentation}`;
3566
3566
  for (; i < maximumValuesToStringify - 1; i++) {
3567
3567
  const tmp2 = stringifyFnReplacer(String(i), value, stack, replacer, spacer, indentation);
3568
3568
  res += tmp2 !== void 0 ? tmp2 : "null";
3569
- res += join4;
3569
+ res += join3;
3570
3570
  }
3571
3571
  const tmp = stringifyFnReplacer(String(i), value, stack, replacer, spacer, indentation);
3572
3572
  res += tmp !== void 0 ? tmp : "null";
3573
3573
  if (value.length - 1 > maximumBreadth) {
3574
3574
  const removedKeys = value.length - maximumBreadth - 1;
3575
- res += `${join4}"... ${getItemCount(removedKeys)} not stringified"`;
3575
+ res += `${join3}"... ${getItemCount(removedKeys)} not stringified"`;
3576
3576
  }
3577
3577
  if (spacer !== "") {
3578
3578
  res += `
@@ -3593,7 +3593,7 @@ ${originalIndentation}`;
3593
3593
  let separator = "";
3594
3594
  if (spacer !== "") {
3595
3595
  indentation += spacer;
3596
- join4 = `,
3596
+ join3 = `,
3597
3597
  ${indentation}`;
3598
3598
  whitespace = " ";
3599
3599
  }
@@ -3607,13 +3607,13 @@ ${indentation}`;
3607
3607
  const tmp = stringifyFnReplacer(key2, value, stack, replacer, spacer, indentation);
3608
3608
  if (tmp !== void 0) {
3609
3609
  res += `${separator}${strEscape(key2)}:${whitespace}${tmp}`;
3610
- separator = join4;
3610
+ separator = join3;
3611
3611
  }
3612
3612
  }
3613
3613
  if (keyLength > maximumBreadth) {
3614
3614
  const removedKeys = keyLength - maximumBreadth;
3615
3615
  res += `${separator}"...":${whitespace}"${getItemCount(removedKeys)} not stringified"`;
3616
- separator = join4;
3616
+ separator = join3;
3617
3617
  }
3618
3618
  if (spacer !== "" && separator.length > 1) {
3619
3619
  res = `
@@ -3654,7 +3654,7 @@ ${originalIndentation}`;
3654
3654
  }
3655
3655
  const originalIndentation = indentation;
3656
3656
  let res = "";
3657
- let join4 = ",";
3657
+ let join3 = ",";
3658
3658
  if (Array.isArray(value)) {
3659
3659
  if (value.length === 0) {
3660
3660
  return "[]";
@@ -3667,7 +3667,7 @@ ${originalIndentation}`;
3667
3667
  indentation += spacer;
3668
3668
  res += `
3669
3669
  ${indentation}`;
3670
- join4 = `,
3670
+ join3 = `,
3671
3671
  ${indentation}`;
3672
3672
  }
3673
3673
  const maximumValuesToStringify = Math.min(value.length, maximumBreadth);
@@ -3675,13 +3675,13 @@ ${indentation}`;
3675
3675
  for (; i < maximumValuesToStringify - 1; i++) {
3676
3676
  const tmp2 = stringifyArrayReplacer(String(i), value[i], stack, replacer, spacer, indentation);
3677
3677
  res += tmp2 !== void 0 ? tmp2 : "null";
3678
- res += join4;
3678
+ res += join3;
3679
3679
  }
3680
3680
  const tmp = stringifyArrayReplacer(String(i), value[i], stack, replacer, spacer, indentation);
3681
3681
  res += tmp !== void 0 ? tmp : "null";
3682
3682
  if (value.length - 1 > maximumBreadth) {
3683
3683
  const removedKeys = value.length - maximumBreadth - 1;
3684
- res += `${join4}"... ${getItemCount(removedKeys)} not stringified"`;
3684
+ res += `${join3}"... ${getItemCount(removedKeys)} not stringified"`;
3685
3685
  }
3686
3686
  if (spacer !== "") {
3687
3687
  res += `
@@ -3694,7 +3694,7 @@ ${originalIndentation}`;
3694
3694
  let whitespace = "";
3695
3695
  if (spacer !== "") {
3696
3696
  indentation += spacer;
3697
- join4 = `,
3697
+ join3 = `,
3698
3698
  ${indentation}`;
3699
3699
  whitespace = " ";
3700
3700
  }
@@ -3703,7 +3703,7 @@ ${indentation}`;
3703
3703
  const tmp = stringifyArrayReplacer(key2, value[key2], stack, replacer, spacer, indentation);
3704
3704
  if (tmp !== void 0) {
3705
3705
  res += `${separator}${strEscape(key2)}:${whitespace}${tmp}`;
3706
- separator = join4;
3706
+ separator = join3;
3707
3707
  }
3708
3708
  }
3709
3709
  if (spacer !== "" && separator.length > 1) {
@@ -3761,20 +3761,20 @@ ${originalIndentation}`;
3761
3761
  indentation += spacer;
3762
3762
  let res2 = `
3763
3763
  ${indentation}`;
3764
- const join5 = `,
3764
+ const join4 = `,
3765
3765
  ${indentation}`;
3766
3766
  const maximumValuesToStringify = Math.min(value.length, maximumBreadth);
3767
3767
  let i = 0;
3768
3768
  for (; i < maximumValuesToStringify - 1; i++) {
3769
3769
  const tmp2 = stringifyIndent(String(i), value[i], stack, spacer, indentation);
3770
3770
  res2 += tmp2 !== void 0 ? tmp2 : "null";
3771
- res2 += join5;
3771
+ res2 += join4;
3772
3772
  }
3773
3773
  const tmp = stringifyIndent(String(i), value[i], stack, spacer, indentation);
3774
3774
  res2 += tmp !== void 0 ? tmp : "null";
3775
3775
  if (value.length - 1 > maximumBreadth) {
3776
3776
  const removedKeys = value.length - maximumBreadth - 1;
3777
- res2 += `${join5}"... ${getItemCount(removedKeys)} not stringified"`;
3777
+ res2 += `${join4}"... ${getItemCount(removedKeys)} not stringified"`;
3778
3778
  }
3779
3779
  res2 += `
3780
3780
  ${originalIndentation}`;
@@ -3790,16 +3790,16 @@ ${originalIndentation}`;
3790
3790
  return '"[Object]"';
3791
3791
  }
3792
3792
  indentation += spacer;
3793
- const join4 = `,
3793
+ const join3 = `,
3794
3794
  ${indentation}`;
3795
3795
  let res = "";
3796
3796
  let separator = "";
3797
3797
  let maximumPropertiesToStringify = Math.min(keyLength, maximumBreadth);
3798
3798
  if (isTypedArrayWithEntries(value)) {
3799
- res += stringifyTypedArray(value, join4, maximumBreadth);
3799
+ res += stringifyTypedArray(value, join3, maximumBreadth);
3800
3800
  keys = keys.slice(value.length);
3801
3801
  maximumPropertiesToStringify -= value.length;
3802
- separator = join4;
3802
+ separator = join3;
3803
3803
  }
3804
3804
  if (deterministic) {
3805
3805
  keys = sort(keys, comparator);
@@ -3810,13 +3810,13 @@ ${indentation}`;
3810
3810
  const tmp = stringifyIndent(key2, value[key2], stack, spacer, indentation);
3811
3811
  if (tmp !== void 0) {
3812
3812
  res += `${separator}${strEscape(key2)}: ${tmp}`;
3813
- separator = join4;
3813
+ separator = join3;
3814
3814
  }
3815
3815
  }
3816
3816
  if (keyLength > maximumBreadth) {
3817
3817
  const removedKeys = keyLength - maximumBreadth;
3818
3818
  res += `${separator}"...": "${getItemCount(removedKeys)} not stringified"`;
3819
- separator = join4;
3819
+ separator = join3;
3820
3820
  }
3821
3821
  if (separator !== "") {
3822
3822
  res = `
@@ -14489,7 +14489,7 @@ var EMBEDDED_PACKAGE_JSON = JSON.stringify(
14489
14489
  );
14490
14490
 
14491
14491
  // ../../packages/daemon-client/src/assets/embedded.generated.ts
14492
- var DAEMON_BUNDLE2 = 'var __defProp = Object.defineProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\n\n// src/daemon.ts\nimport { spawn } from "node:child_process";\nimport { mkdir as mkdir4, unlink, writeFile as writeFile2 } from "node:fs/promises";\nimport net from "node:net";\nimport path6 from "node:path";\n\n// ../../packages/logger/src/index.ts\nimport pino from "pino";\nvar VALID_LEVELS = /* @__PURE__ */ new Set([\n "trace",\n "debug",\n "info",\n "warn",\n "error",\n "fatal",\n "silent"\n]);\nfunction resolveLevel(opts = {}) {\n if (opts.level) {\n return opts.level;\n }\n const fromEnv = process.env.CANARY_LOG_LEVEL?.trim().toLowerCase();\n if (fromEnv && VALID_LEVELS.has(fromEnv)) {\n return fromEnv;\n }\n return opts.fallbackLevel ?? "info";\n}\nfunction createLogger(opts = {}) {\n const options = {\n level: resolveLevel(opts),\n timestamp: pino.stdTimeFunctions.isoTime,\n // Serialize `err`/`error` bindings into structured { type, message, stack }.\n serializers: { err: pino.stdSerializers.err },\n formatters: {\n // Log the level name ("info") instead of the numeric code (30).\n level: (label) => ({ level: label })\n }\n };\n if (opts.name) {\n options.name = opts.name;\n }\n if (opts.redact) {\n options.redact = opts.redact;\n }\n const stream = opts.stream ?? pino.destination({\n dest: opts.destination ?? 2,\n sync: opts.sync ?? false,\n mkdir: true\n });\n const logger = pino(options, stream);\n return opts.base ? logger.child(opts.base) : logger;\n}\n\n// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/external.js\nvar external_exports = {};\n__export(external_exports, {\n BRAND: () => BRAND,\n DIRTY: () => DIRTY,\n EMPTY_PATH: () => EMPTY_PATH,\n INVALID: () => INVALID,\n NEVER: () => NEVER,\n OK: () => OK,\n ParseStatus: () => ParseStatus,\n Schema: () => ZodType,\n ZodAny: () => ZodAny,\n ZodArray: () => ZodArray,\n ZodBigInt: () => ZodBigInt,\n ZodBoolean: () => ZodBoolean,\n ZodBranded: () => ZodBranded,\n ZodCatch: () => ZodCatch,\n ZodDate: () => ZodDate,\n ZodDefault: () => ZodDefault,\n ZodDiscriminatedUnion: () => ZodDiscriminatedUnion,\n ZodEffects: () => ZodEffects,\n ZodEnum: () => ZodEnum,\n ZodError: () => ZodError,\n ZodFirstPartyTypeKind: () => ZodFirstPartyTypeKind,\n ZodFunction: () => ZodFunction,\n ZodIntersection: () => ZodIntersection,\n ZodIssueCode: () => ZodIssueCode,\n ZodLazy: () => ZodLazy,\n ZodLiteral: () => ZodLiteral,\n ZodMap: () => ZodMap,\n ZodNaN: () => ZodNaN,\n ZodNativeEnum: () => ZodNativeEnum,\n ZodNever: () => ZodNever,\n ZodNull: () => ZodNull,\n ZodNullable: () => ZodNullable,\n ZodNumber: () => ZodNumber,\n ZodObject: () => ZodObject,\n ZodOptional: () => ZodOptional,\n ZodParsedType: () => ZodParsedType,\n ZodPipeline: () => ZodPipeline,\n ZodPromise: () => ZodPromise,\n ZodReadonly: () => ZodReadonly,\n ZodRecord: () => ZodRecord,\n ZodSchema: () => ZodType,\n ZodSet: () => ZodSet,\n ZodString: () => ZodString,\n ZodSymbol: () => ZodSymbol,\n ZodTransformer: () => ZodEffects,\n ZodTuple: () => ZodTuple,\n ZodType: () => ZodType,\n ZodUndefined: () => ZodUndefined,\n ZodUnion: () => ZodUnion,\n ZodUnknown: () => ZodUnknown,\n ZodVoid: () => ZodVoid,\n addIssueToContext: () => addIssueToContext,\n any: () => anyType,\n array: () => arrayType,\n bigint: () => bigIntType,\n boolean: () => booleanType,\n coerce: () => coerce,\n custom: () => custom,\n date: () => dateType,\n datetimeRegex: () => datetimeRegex,\n defaultErrorMap: () => en_default,\n discriminatedUnion: () => discriminatedUnionType,\n effect: () => effectsType,\n enum: () => enumType,\n function: () => functionType,\n getErrorMap: () => getErrorMap,\n getParsedType: () => getParsedType,\n instanceof: () => instanceOfType,\n intersection: () => intersectionType,\n isAborted: () => isAborted,\n isAsync: () => isAsync,\n isDirty: () => isDirty,\n isValid: () => isValid,\n late: () => late,\n lazy: () => lazyType,\n literal: () => literalType,\n makeIssue: () => makeIssue,\n map: () => mapType,\n nan: () => nanType,\n nativeEnum: () => nativeEnumType,\n never: () => neverType,\n null: () => nullType,\n nullable: () => nullableType,\n number: () => numberType,\n object: () => objectType,\n objectUtil: () => objectUtil,\n oboolean: () => oboolean,\n onumber: () => onumber,\n optional: () => optionalType,\n ostring: () => ostring,\n pipeline: () => pipelineType,\n preprocess: () => preprocessType,\n promise: () => promiseType,\n quotelessJson: () => quotelessJson,\n record: () => recordType,\n set: () => setType,\n setErrorMap: () => setErrorMap,\n strictObject: () => strictObjectType,\n string: () => stringType,\n symbol: () => symbolType,\n transformer: () => effectsType,\n tuple: () => tupleType,\n undefined: () => undefinedType,\n union: () => unionType,\n unknown: () => unknownType,\n util: () => util,\n void: () => voidType\n});\n\n// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/helpers/util.js\nvar util;\n(function(util3) {\n util3.assertEqual = (_) => {\n };\n function assertIs(_arg) {\n }\n util3.assertIs = assertIs;\n function assertNever(_x) {\n throw new Error();\n }\n util3.assertNever = assertNever;\n util3.arrayToEnum = (items) => {\n const obj = {};\n for (const item of items) {\n obj[item] = item;\n }\n return obj;\n };\n util3.getValidEnumValues = (obj) => {\n const validKeys = util3.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number");\n const filtered = {};\n for (const k of validKeys) {\n filtered[k] = obj[k];\n }\n return util3.objectValues(filtered);\n };\n util3.objectValues = (obj) => {\n return util3.objectKeys(obj).map(function(e) {\n return obj[e];\n });\n };\n util3.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object) => {\n const keys = [];\n for (const key in object) {\n if (Object.prototype.hasOwnProperty.call(object, key)) {\n keys.push(key);\n }\n }\n return keys;\n };\n util3.find = (arr, checker) => {\n for (const item of arr) {\n if (checker(item))\n return item;\n }\n return void 0;\n };\n util3.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "number" && Number.isFinite(val) && Math.floor(val) === val;\n function joinValues(array, separator = " | ") {\n return array.map((val) => typeof val === "string" ? `\'${val}\'` : val).join(separator);\n }\n util3.joinValues = joinValues;\n util3.jsonStringifyReplacer = (_, value) => {\n if (typeof value === "bigint") {\n return value.toString();\n }\n return value;\n };\n})(util || (util = {}));\nvar objectUtil;\n(function(objectUtil2) {\n objectUtil2.mergeShapes = (first, second) => {\n return {\n ...first,\n ...second\n // second overwrites first\n };\n };\n})(objectUtil || (objectUtil = {}));\nvar ZodParsedType = util.arrayToEnum([\n "string",\n "nan",\n "number",\n "integer",\n "float",\n "boolean",\n "date",\n "bigint",\n "symbol",\n "function",\n "undefined",\n "null",\n "array",\n "object",\n "unknown",\n "promise",\n "void",\n "never",\n "map",\n "set"\n]);\nvar getParsedType = (data) => {\n const t = typeof data;\n switch (t) {\n case "undefined":\n return ZodParsedType.undefined;\n case "string":\n return ZodParsedType.string;\n case "number":\n return Number.isNaN(data) ? ZodParsedType.nan : ZodParsedType.number;\n case "boolean":\n return ZodParsedType.boolean;\n case "function":\n return ZodParsedType.function;\n case "bigint":\n return ZodParsedType.bigint;\n case "symbol":\n return ZodParsedType.symbol;\n case "object":\n if (Array.isArray(data)) {\n return ZodParsedType.array;\n }\n if (data === null) {\n return ZodParsedType.null;\n }\n if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") {\n return ZodParsedType.promise;\n }\n if (typeof Map !== "undefined" && data instanceof Map) {\n return ZodParsedType.map;\n }\n if (typeof Set !== "undefined" && data instanceof Set) {\n return ZodParsedType.set;\n }\n if (typeof Date !== "undefined" && data instanceof Date) {\n return ZodParsedType.date;\n }\n return ZodParsedType.object;\n default:\n return ZodParsedType.unknown;\n }\n};\n\n// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/ZodError.js\nvar ZodIssueCode = util.arrayToEnum([\n "invalid_type",\n "invalid_literal",\n "custom",\n "invalid_union",\n "invalid_union_discriminator",\n "invalid_enum_value",\n "unrecognized_keys",\n "invalid_arguments",\n "invalid_return_type",\n "invalid_date",\n "invalid_string",\n "too_small",\n "too_big",\n "invalid_intersection_types",\n "not_multiple_of",\n "not_finite"\n]);\nvar quotelessJson = (obj) => {\n const json = JSON.stringify(obj, null, 2);\n return json.replace(/"([^"]+)":/g, "$1:");\n};\nvar ZodError = class _ZodError extends Error {\n get errors() {\n return this.issues;\n }\n constructor(issues) {\n super();\n this.issues = [];\n this.addIssue = (sub) => {\n this.issues = [...this.issues, sub];\n };\n this.addIssues = (subs = []) => {\n this.issues = [...this.issues, ...subs];\n };\n const actualProto = new.target.prototype;\n if (Object.setPrototypeOf) {\n Object.setPrototypeOf(this, actualProto);\n } else {\n this.__proto__ = actualProto;\n }\n this.name = "ZodError";\n this.issues = issues;\n }\n format(_mapper) {\n const mapper = _mapper || function(issue) {\n return issue.message;\n };\n const fieldErrors = { _errors: [] };\n const processError = (error) => {\n for (const issue of error.issues) {\n if (issue.code === "invalid_union") {\n issue.unionErrors.map(processError);\n } else if (issue.code === "invalid_return_type") {\n processError(issue.returnTypeError);\n } else if (issue.code === "invalid_arguments") {\n processError(issue.argumentsError);\n } else if (issue.path.length === 0) {\n fieldErrors._errors.push(mapper(issue));\n } else {\n let curr = fieldErrors;\n let i = 0;\n while (i < issue.path.length) {\n const el = issue.path[i];\n const terminal = i === issue.path.length - 1;\n if (!terminal) {\n curr[el] = curr[el] || { _errors: [] };\n } else {\n curr[el] = curr[el] || { _errors: [] };\n curr[el]._errors.push(mapper(issue));\n }\n curr = curr[el];\n i++;\n }\n }\n }\n };\n processError(this);\n return fieldErrors;\n }\n static assert(value) {\n if (!(value instanceof _ZodError)) {\n throw new Error(`Not a ZodError: ${value}`);\n }\n }\n toString() {\n return this.message;\n }\n get message() {\n return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2);\n }\n get isEmpty() {\n return this.issues.length === 0;\n }\n flatten(mapper = (issue) => issue.message) {\n const fieldErrors = {};\n const formErrors = [];\n for (const sub of this.issues) {\n if (sub.path.length > 0) {\n const firstEl = sub.path[0];\n fieldErrors[firstEl] = fieldErrors[firstEl] || [];\n fieldErrors[firstEl].push(mapper(sub));\n } else {\n formErrors.push(mapper(sub));\n }\n }\n return { formErrors, fieldErrors };\n }\n get formErrors() {\n return this.flatten();\n }\n};\nZodError.create = (issues) => {\n const error = new ZodError(issues);\n return error;\n};\n\n// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/locales/en.js\nvar errorMap = (issue, _ctx) => {\n let message;\n switch (issue.code) {\n case ZodIssueCode.invalid_type:\n if (issue.received === ZodParsedType.undefined) {\n message = "Required";\n } else {\n message = `Expected ${issue.expected}, received ${issue.received}`;\n }\n break;\n case ZodIssueCode.invalid_literal:\n message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`;\n break;\n case ZodIssueCode.unrecognized_keys:\n message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, ", ")}`;\n break;\n case ZodIssueCode.invalid_union:\n message = `Invalid input`;\n break;\n case ZodIssueCode.invalid_union_discriminator:\n message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`;\n break;\n case ZodIssueCode.invalid_enum_value:\n message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received \'${issue.received}\'`;\n break;\n case ZodIssueCode.invalid_arguments:\n message = `Invalid function arguments`;\n break;\n case ZodIssueCode.invalid_return_type:\n message = `Invalid function return type`;\n break;\n case ZodIssueCode.invalid_date:\n message = `Invalid date`;\n break;\n case ZodIssueCode.invalid_string:\n if (typeof issue.validation === "object") {\n if ("includes" in issue.validation) {\n message = `Invalid input: must include "${issue.validation.includes}"`;\n if (typeof issue.validation.position === "number") {\n message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`;\n }\n } else if ("startsWith" in issue.validation) {\n message = `Invalid input: must start with "${issue.validation.startsWith}"`;\n } else if ("endsWith" in issue.validation) {\n message = `Invalid input: must end with "${issue.validation.endsWith}"`;\n } else {\n util.assertNever(issue.validation);\n }\n } else if (issue.validation !== "regex") {\n message = `Invalid ${issue.validation}`;\n } else {\n message = "Invalid";\n }\n break;\n case ZodIssueCode.too_small:\n if (issue.type === "array")\n message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`;\n else if (issue.type === "string")\n message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`;\n else if (issue.type === "number")\n message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;\n else if (issue.type === "bigint")\n message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;\n else if (issue.type === "date")\n message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`;\n else\n message = "Invalid input";\n break;\n case ZodIssueCode.too_big:\n if (issue.type === "array")\n message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`;\n else if (issue.type === "string")\n message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`;\n else if (issue.type === "number")\n message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;\n else if (issue.type === "bigint")\n message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;\n else if (issue.type === "date")\n message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`;\n else\n message = "Invalid input";\n break;\n case ZodIssueCode.custom:\n message = `Invalid input`;\n break;\n case ZodIssueCode.invalid_intersection_types:\n message = `Intersection results could not be merged`;\n break;\n case ZodIssueCode.not_multiple_of:\n message = `Number must be a multiple of ${issue.multipleOf}`;\n break;\n case ZodIssueCode.not_finite:\n message = "Number must be finite";\n break;\n default:\n message = _ctx.defaultError;\n util.assertNever(issue);\n }\n return { message };\n};\nvar en_default = errorMap;\n\n// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/errors.js\nvar overrideErrorMap = en_default;\nfunction setErrorMap(map) {\n overrideErrorMap = map;\n}\nfunction getErrorMap() {\n return overrideErrorMap;\n}\n\n// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/helpers/parseUtil.js\nvar makeIssue = (params) => {\n const { data, path: path7, errorMaps, issueData } = params;\n const fullPath = [...path7, ...issueData.path || []];\n const fullIssue = {\n ...issueData,\n path: fullPath\n };\n if (issueData.message !== void 0) {\n return {\n ...issueData,\n path: fullPath,\n message: issueData.message\n };\n }\n let errorMessage = "";\n const maps = errorMaps.filter((m) => !!m).slice().reverse();\n for (const map of maps) {\n errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message;\n }\n return {\n ...issueData,\n path: fullPath,\n message: errorMessage\n };\n};\nvar EMPTY_PATH = [];\nfunction addIssueToContext(ctx, issueData) {\n const overrideMap = getErrorMap();\n const issue = makeIssue({\n issueData,\n data: ctx.data,\n path: ctx.path,\n errorMaps: [\n ctx.common.contextualErrorMap,\n // contextual error map is first priority\n ctx.schemaErrorMap,\n // then schema-bound map if available\n overrideMap,\n // then global override map\n overrideMap === en_default ? void 0 : en_default\n // then global default map\n ].filter((x) => !!x)\n });\n ctx.common.issues.push(issue);\n}\nvar ParseStatus = class _ParseStatus {\n constructor() {\n this.value = "valid";\n }\n dirty() {\n if (this.value === "valid")\n this.value = "dirty";\n }\n abort() {\n if (this.value !== "aborted")\n this.value = "aborted";\n }\n static mergeArray(status, results) {\n const arrayValue = [];\n for (const s of results) {\n if (s.status === "aborted")\n return INVALID;\n if (s.status === "dirty")\n status.dirty();\n arrayValue.push(s.value);\n }\n return { status: status.value, value: arrayValue };\n }\n static async mergeObjectAsync(status, pairs) {\n const syncPairs = [];\n for (const pair of pairs) {\n const key = await pair.key;\n const value = await pair.value;\n syncPairs.push({\n key,\n value\n });\n }\n return _ParseStatus.mergeObjectSync(status, syncPairs);\n }\n static mergeObjectSync(status, pairs) {\n const finalObject = {};\n for (const pair of pairs) {\n const { key, value } = pair;\n if (key.status === "aborted")\n return INVALID;\n if (value.status === "aborted")\n return INVALID;\n if (key.status === "dirty")\n status.dirty();\n if (value.status === "dirty")\n status.dirty();\n if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) {\n finalObject[key.value] = value.value;\n }\n }\n return { status: status.value, value: finalObject };\n }\n};\nvar INVALID = Object.freeze({\n status: "aborted"\n});\nvar DIRTY = (value) => ({ status: "dirty", value });\nvar OK = (value) => ({ status: "valid", value });\nvar isAborted = (x) => x.status === "aborted";\nvar isDirty = (x) => x.status === "dirty";\nvar isValid = (x) => x.status === "valid";\nvar isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise;\n\n// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/helpers/errorUtil.js\nvar errorUtil;\n(function(errorUtil2) {\n errorUtil2.errToObj = (message) => typeof message === "string" ? { message } : message || {};\n errorUtil2.toString = (message) => typeof message === "string" ? message : message?.message;\n})(errorUtil || (errorUtil = {}));\n\n// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/types.js\nvar ParseInputLazyPath = class {\n constructor(parent, value, path7, key) {\n this._cachedPath = [];\n this.parent = parent;\n this.data = value;\n this._path = path7;\n this._key = key;\n }\n get path() {\n if (!this._cachedPath.length) {\n if (Array.isArray(this._key)) {\n this._cachedPath.push(...this._path, ...this._key);\n } else {\n this._cachedPath.push(...this._path, this._key);\n }\n }\n return this._cachedPath;\n }\n};\nvar handleResult = (ctx, result) => {\n if (isValid(result)) {\n return { success: true, data: result.value };\n } else {\n if (!ctx.common.issues.length) {\n throw new Error("Validation failed but no issues detected.");\n }\n return {\n success: false,\n get error() {\n if (this._error)\n return this._error;\n const error = new ZodError(ctx.common.issues);\n this._error = error;\n return this._error;\n }\n };\n }\n};\nfunction processCreateParams(params) {\n if (!params)\n return {};\n const { errorMap: errorMap2, invalid_type_error, required_error, description } = params;\n if (errorMap2 && (invalid_type_error || required_error)) {\n throw new Error(`Can\'t use "invalid_type_error" or "required_error" in conjunction with custom error map.`);\n }\n if (errorMap2)\n return { errorMap: errorMap2, description };\n const customMap = (iss, ctx) => {\n const { message } = params;\n if (iss.code === "invalid_enum_value") {\n return { message: message ?? ctx.defaultError };\n }\n if (typeof ctx.data === "undefined") {\n return { message: message ?? required_error ?? ctx.defaultError };\n }\n if (iss.code !== "invalid_type")\n return { message: ctx.defaultError };\n return { message: message ?? invalid_type_error ?? ctx.defaultError };\n };\n return { errorMap: customMap, description };\n}\nvar ZodType = class {\n get description() {\n return this._def.description;\n }\n _getType(input) {\n return getParsedType(input.data);\n }\n _getOrReturnCtx(input, ctx) {\n return ctx || {\n common: input.parent.common,\n data: input.data,\n parsedType: getParsedType(input.data),\n schemaErrorMap: this._def.errorMap,\n path: input.path,\n parent: input.parent\n };\n }\n _processInputParams(input) {\n return {\n status: new ParseStatus(),\n ctx: {\n common: input.parent.common,\n data: input.data,\n parsedType: getParsedType(input.data),\n schemaErrorMap: this._def.errorMap,\n path: input.path,\n parent: input.parent\n }\n };\n }\n _parseSync(input) {\n const result = this._parse(input);\n if (isAsync(result)) {\n throw new Error("Synchronous parse encountered promise.");\n }\n return result;\n }\n _parseAsync(input) {\n const result = this._parse(input);\n return Promise.resolve(result);\n }\n parse(data, params) {\n const result = this.safeParse(data, params);\n if (result.success)\n return result.data;\n throw result.error;\n }\n safeParse(data, params) {\n const ctx = {\n common: {\n issues: [],\n async: params?.async ?? false,\n contextualErrorMap: params?.errorMap\n },\n path: params?.path || [],\n schemaErrorMap: this._def.errorMap,\n parent: null,\n data,\n parsedType: getParsedType(data)\n };\n const result = this._parseSync({ data, path: ctx.path, parent: ctx });\n return handleResult(ctx, result);\n }\n "~validate"(data) {\n const ctx = {\n common: {\n issues: [],\n async: !!this["~standard"].async\n },\n path: [],\n schemaErrorMap: this._def.errorMap,\n parent: null,\n data,\n parsedType: getParsedType(data)\n };\n if (!this["~standard"].async) {\n try {\n const result = this._parseSync({ data, path: [], parent: ctx });\n return isValid(result) ? {\n value: result.value\n } : {\n issues: ctx.common.issues\n };\n } catch (err) {\n if (err?.message?.toLowerCase()?.includes("encountered")) {\n this["~standard"].async = true;\n }\n ctx.common = {\n issues: [],\n async: true\n };\n }\n }\n return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid(result) ? {\n value: result.value\n } : {\n issues: ctx.common.issues\n });\n }\n async parseAsync(data, params) {\n const result = await this.safeParseAsync(data, params);\n if (result.success)\n return result.data;\n throw result.error;\n }\n async safeParseAsync(data, params) {\n const ctx = {\n common: {\n issues: [],\n contextualErrorMap: params?.errorMap,\n async: true\n },\n path: params?.path || [],\n schemaErrorMap: this._def.errorMap,\n parent: null,\n data,\n parsedType: getParsedType(data)\n };\n const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx });\n const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult));\n return handleResult(ctx, result);\n }\n refine(check, message) {\n const getIssueProperties = (val) => {\n if (typeof message === "string" || typeof message === "undefined") {\n return { message };\n } else if (typeof message === "function") {\n return message(val);\n } else {\n return message;\n }\n };\n return this._refinement((val, ctx) => {\n const result = check(val);\n const setError = () => ctx.addIssue({\n code: ZodIssueCode.custom,\n ...getIssueProperties(val)\n });\n if (typeof Promise !== "undefined" && result instanceof Promise) {\n return result.then((data) => {\n if (!data) {\n setError();\n return false;\n } else {\n return true;\n }\n });\n }\n if (!result) {\n setError();\n return false;\n } else {\n return true;\n }\n });\n }\n refinement(check, refinementData) {\n return this._refinement((val, ctx) => {\n if (!check(val)) {\n ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData);\n return false;\n } else {\n return true;\n }\n });\n }\n _refinement(refinement) {\n return new ZodEffects({\n schema: this,\n typeName: ZodFirstPartyTypeKind.ZodEffects,\n effect: { type: "refinement", refinement }\n });\n }\n superRefine(refinement) {\n return this._refinement(refinement);\n }\n constructor(def) {\n this.spa = this.safeParseAsync;\n this._def = def;\n this.parse = this.parse.bind(this);\n this.safeParse = this.safeParse.bind(this);\n this.parseAsync = this.parseAsync.bind(this);\n this.safeParseAsync = this.safeParseAsync.bind(this);\n this.spa = this.spa.bind(this);\n this.refine = this.refine.bind(this);\n this.refinement = this.refinement.bind(this);\n this.superRefine = this.superRefine.bind(this);\n this.optional = this.optional.bind(this);\n this.nullable = this.nullable.bind(this);\n this.nullish = this.nullish.bind(this);\n this.array = this.array.bind(this);\n this.promise = this.promise.bind(this);\n this.or = this.or.bind(this);\n this.and = this.and.bind(this);\n this.transform = this.transform.bind(this);\n this.brand = this.brand.bind(this);\n this.default = this.default.bind(this);\n this.catch = this.catch.bind(this);\n this.describe = this.describe.bind(this);\n this.pipe = this.pipe.bind(this);\n this.readonly = this.readonly.bind(this);\n this.isNullable = this.isNullable.bind(this);\n this.isOptional = this.isOptional.bind(this);\n this["~standard"] = {\n version: 1,\n vendor: "zod",\n validate: (data) => this["~validate"](data)\n };\n }\n optional() {\n return ZodOptional.create(this, this._def);\n }\n nullable() {\n return ZodNullable.create(this, this._def);\n }\n nullish() {\n return this.nullable().optional();\n }\n array() {\n return ZodArray.create(this);\n }\n promise() {\n return ZodPromise.create(this, this._def);\n }\n or(option) {\n return ZodUnion.create([this, option], this._def);\n }\n and(incoming) {\n return ZodIntersection.create(this, incoming, this._def);\n }\n transform(transform) {\n return new ZodEffects({\n ...processCreateParams(this._def),\n schema: this,\n typeName: ZodFirstPartyTypeKind.ZodEffects,\n effect: { type: "transform", transform }\n });\n }\n default(def) {\n const defaultValueFunc = typeof def === "function" ? def : () => def;\n return new ZodDefault({\n ...processCreateParams(this._def),\n innerType: this,\n defaultValue: defaultValueFunc,\n typeName: ZodFirstPartyTypeKind.ZodDefault\n });\n }\n brand() {\n return new ZodBranded({\n typeName: ZodFirstPartyTypeKind.ZodBranded,\n type: this,\n ...processCreateParams(this._def)\n });\n }\n catch(def) {\n const catchValueFunc = typeof def === "function" ? def : () => def;\n return new ZodCatch({\n ...processCreateParams(this._def),\n innerType: this,\n catchValue: catchValueFunc,\n typeName: ZodFirstPartyTypeKind.ZodCatch\n });\n }\n describe(description) {\n const This = this.constructor;\n return new This({\n ...this._def,\n description\n });\n }\n pipe(target) {\n return ZodPipeline.create(this, target);\n }\n readonly() {\n return ZodReadonly.create(this);\n }\n isOptional() {\n return this.safeParse(void 0).success;\n }\n isNullable() {\n return this.safeParse(null).success;\n }\n};\nvar cuidRegex = /^c[^\\s-]{8,}$/i;\nvar cuid2Regex = /^[0-9a-z]+$/;\nvar ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i;\nvar uuidRegex = /^[0-9a-fA-F]{8}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{12}$/i;\nvar nanoidRegex = /^[a-z0-9_-]{21}$/i;\nvar jwtRegex = /^[A-Za-z0-9-_]+\\.[A-Za-z0-9-_]+\\.[A-Za-z0-9-_]*$/;\nvar durationRegex = /^[-+]?P(?!$)(?:(?:[-+]?\\d+Y)|(?:[-+]?\\d+[.,]\\d+Y$))?(?:(?:[-+]?\\d+M)|(?:[-+]?\\d+[.,]\\d+M$))?(?:(?:[-+]?\\d+W)|(?:[-+]?\\d+[.,]\\d+W$))?(?:(?:[-+]?\\d+D)|(?:[-+]?\\d+[.,]\\d+D$))?(?:T(?=[\\d+-])(?:(?:[-+]?\\d+H)|(?:[-+]?\\d+[.,]\\d+H$))?(?:(?:[-+]?\\d+M)|(?:[-+]?\\d+[.,]\\d+M$))?(?:[-+]?\\d+(?:[.,]\\d+)?S)?)??$/;\nvar emailRegex = /^(?!\\.)(?!.*\\.\\.)([A-Z0-9_\'+\\-\\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\\-]*\\.)+[A-Z]{2,}$/i;\nvar _emojiRegex = `^(\\\\p{Extended_Pictographic}|\\\\p{Emoji_Component})+$`;\nvar emojiRegex;\nvar ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;\nvar ipv4CidrRegex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\/(3[0-2]|[12]?[0-9])$/;\nvar ipv6Regex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/;\nvar ipv6CidrRegex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;\nvar base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;\nvar base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/;\nvar dateRegexSource = `((\\\\d\\\\d[2468][048]|\\\\d\\\\d[13579][26]|\\\\d\\\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\\\d|30)|(02)-(0[1-9]|1\\\\d|2[0-8])))`;\nvar dateRegex = new RegExp(`^${dateRegexSource}$`);\nfunction timeRegexSource(args) {\n let secondsRegexSource = `[0-5]\\\\d`;\n if (args.precision) {\n secondsRegexSource = `${secondsRegexSource}\\\\.\\\\d{${args.precision}}`;\n } else if (args.precision == null) {\n secondsRegexSource = `${secondsRegexSource}(\\\\.\\\\d+)?`;\n }\n const secondsQuantifier = args.precision ? "+" : "?";\n return `([01]\\\\d|2[0-3]):[0-5]\\\\d(:${secondsRegexSource})${secondsQuantifier}`;\n}\nfunction timeRegex(args) {\n return new RegExp(`^${timeRegexSource(args)}$`);\n}\nfunction datetimeRegex(args) {\n let regex = `${dateRegexSource}T${timeRegexSource(args)}`;\n const opts = [];\n opts.push(args.local ? `Z?` : `Z`);\n if (args.offset)\n opts.push(`([+-]\\\\d{2}:?\\\\d{2})`);\n regex = `${regex}(${opts.join("|")})`;\n return new RegExp(`^${regex}$`);\n}\nfunction isValidIP(ip, version) {\n if ((version === "v4" || !version) && ipv4Regex.test(ip)) {\n return true;\n }\n if ((version === "v6" || !version) && ipv6Regex.test(ip)) {\n return true;\n }\n return false;\n}\nfunction isValidJWT(jwt, alg) {\n if (!jwtRegex.test(jwt))\n return false;\n try {\n const [header] = jwt.split(".");\n if (!header)\n return false;\n const base64 = header.replace(/-/g, "+").replace(/_/g, "/").padEnd(header.length + (4 - header.length % 4) % 4, "=");\n const decoded = JSON.parse(atob(base64));\n if (typeof decoded !== "object" || decoded === null)\n return false;\n if ("typ" in decoded && decoded?.typ !== "JWT")\n return false;\n if (!decoded.alg)\n return false;\n if (alg && decoded.alg !== alg)\n return false;\n return true;\n } catch {\n return false;\n }\n}\nfunction isValidCidr(ip, version) {\n if ((version === "v4" || !version) && ipv4CidrRegex.test(ip)) {\n return true;\n }\n if ((version === "v6" || !version) && ipv6CidrRegex.test(ip)) {\n return true;\n }\n return false;\n}\nvar ZodString = class _ZodString extends ZodType {\n _parse(input) {\n if (this._def.coerce) {\n input.data = String(input.data);\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.string) {\n const ctx2 = this._getOrReturnCtx(input);\n addIssueToContext(ctx2, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.string,\n received: ctx2.parsedType\n });\n return INVALID;\n }\n const status = new ParseStatus();\n let ctx = void 0;\n for (const check of this._def.checks) {\n if (check.kind === "min") {\n if (input.data.length < check.value) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: check.value,\n type: "string",\n inclusive: true,\n exact: false,\n message: check.message\n });\n status.dirty();\n }\n } else if (check.kind === "max") {\n if (input.data.length > check.value) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: check.value,\n type: "string",\n inclusive: true,\n exact: false,\n message: check.message\n });\n status.dirty();\n }\n } else if (check.kind === "length") {\n const tooBig = input.data.length > check.value;\n const tooSmall = input.data.length < check.value;\n if (tooBig || tooSmall) {\n ctx = this._getOrReturnCtx(input, ctx);\n if (tooBig) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: check.value,\n type: "string",\n inclusive: true,\n exact: true,\n message: check.message\n });\n } else if (tooSmall) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: check.value,\n type: "string",\n inclusive: true,\n exact: true,\n message: check.message\n });\n }\n status.dirty();\n }\n } else if (check.kind === "email") {\n if (!emailRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: "email",\n code: ZodIssueCode.invalid_string,\n message: check.message\n });\n status.dirty();\n }\n } else if (check.kind === "emoji") {\n if (!emojiRegex) {\n emojiRegex = new RegExp(_emojiRegex, "u");\n }\n if (!emojiRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: "emoji",\n code: ZodIssueCode.invalid_string,\n message: check.message\n });\n status.dirty();\n }\n } else if (check.kind === "uuid") {\n if (!uuidRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: "uuid",\n code: ZodIssueCode.invalid_string,\n message: check.message\n });\n status.dirty();\n }\n } else if (check.kind === "nanoid") {\n if (!nanoidRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: "nanoid",\n code: ZodIssueCode.invalid_string,\n message: check.message\n });\n status.dirty();\n }\n } else if (check.kind === "cuid") {\n if (!cuidRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: "cuid",\n code: ZodIssueCode.invalid_string,\n message: check.message\n });\n status.dirty();\n }\n } else if (check.kind === "cuid2") {\n if (!cuid2Regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: "cuid2",\n code: ZodIssueCode.invalid_string,\n message: check.message\n });\n status.dirty();\n }\n } else if (check.kind === "ulid") {\n if (!ulidRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: "ulid",\n code: ZodIssueCode.invalid_string,\n message: check.message\n });\n status.dirty();\n }\n } else if (check.kind === "url") {\n try {\n new URL(input.data);\n } catch {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: "url",\n code: ZodIssueCode.invalid_string,\n message: check.message\n });\n status.dirty();\n }\n } else if (check.kind === "regex") {\n check.regex.lastIndex = 0;\n const testResult = check.regex.test(input.data);\n if (!testResult) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: "regex",\n code: ZodIssueCode.invalid_string,\n message: check.message\n });\n status.dirty();\n }\n } else if (check.kind === "trim") {\n input.data = input.data.trim();\n } else if (check.kind === "includes") {\n if (!input.data.includes(check.value, check.position)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: { includes: check.value, position: check.position },\n message: check.message\n });\n status.dirty();\n }\n } else if (check.kind === "toLowerCase") {\n input.data = input.data.toLowerCase();\n } else if (check.kind === "toUpperCase") {\n input.data = input.data.toUpperCase();\n } else if (check.kind === "startsWith") {\n if (!input.data.startsWith(check.value)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: { startsWith: check.value },\n message: check.message\n });\n status.dirty();\n }\n } else if (check.kind === "endsWith") {\n if (!input.data.endsWith(check.value)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: { endsWith: check.value },\n message: check.message\n });\n status.dirty();\n }\n } else if (check.kind === "datetime") {\n const regex = datetimeRegex(check);\n if (!regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: "datetime",\n message: check.message\n });\n status.dirty();\n }\n } else if (check.kind === "date") {\n const regex = dateRegex;\n if (!regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: "date",\n message: check.message\n });\n status.dirty();\n }\n } else if (check.kind === "time") {\n const regex = timeRegex(check);\n if (!regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: "time",\n message: check.message\n });\n status.dirty();\n }\n } else if (check.kind === "duration") {\n if (!durationRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: "duration",\n code: ZodIssueCode.invalid_string,\n message: check.message\n });\n status.dirty();\n }\n } else if (check.kind === "ip") {\n if (!isValidIP(input.data, check.version)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: "ip",\n code: ZodIssueCode.invalid_string,\n message: check.message\n });\n status.dirty();\n }\n } else if (check.kind === "jwt") {\n if (!isValidJWT(input.data, check.alg)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: "jwt",\n code: ZodIssueCode.invalid_string,\n message: check.message\n });\n status.dirty();\n }\n } else if (check.kind === "cidr") {\n if (!isValidCidr(input.data, check.version)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: "cidr",\n code: ZodIssueCode.invalid_string,\n message: check.message\n });\n status.dirty();\n }\n } else if (check.kind === "base64") {\n if (!base64Regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: "base64",\n code: ZodIssueCode.invalid_string,\n message: check.message\n });\n status.dirty();\n }\n } else if (check.kind === "base64url") {\n if (!base64urlRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: "base64url",\n code: ZodIssueCode.invalid_string,\n message: check.message\n });\n status.dirty();\n }\n } else {\n util.assertNever(check);\n }\n }\n return { status: status.value, value: input.data };\n }\n _regex(regex, validation, message) {\n return this.refinement((data) => regex.test(data), {\n validation,\n code: ZodIssueCode.invalid_string,\n ...errorUtil.errToObj(message)\n });\n }\n _addCheck(check) {\n return new _ZodString({\n ...this._def,\n checks: [...this._def.checks, check]\n });\n }\n email(message) {\n return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) });\n }\n url(message) {\n return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) });\n }\n emoji(message) {\n return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) });\n }\n uuid(message) {\n return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) });\n }\n nanoid(message) {\n return this._addCheck({ kind: "nanoid", ...errorUtil.errToObj(message) });\n }\n cuid(message) {\n return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) });\n }\n cuid2(message) {\n return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) });\n }\n ulid(message) {\n return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) });\n }\n base64(message) {\n return this._addCheck({ kind: "base64", ...errorUtil.errToObj(message) });\n }\n base64url(message) {\n return this._addCheck({\n kind: "base64url",\n ...errorUtil.errToObj(message)\n });\n }\n jwt(options) {\n return this._addCheck({ kind: "jwt", ...errorUtil.errToObj(options) });\n }\n ip(options) {\n return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) });\n }\n cidr(options) {\n return this._addCheck({ kind: "cidr", ...errorUtil.errToObj(options) });\n }\n datetime(options) {\n if (typeof options === "string") {\n return this._addCheck({\n kind: "datetime",\n precision: null,\n offset: false,\n local: false,\n message: options\n });\n }\n return this._addCheck({\n kind: "datetime",\n precision: typeof options?.precision === "undefined" ? null : options?.precision,\n offset: options?.offset ?? false,\n local: options?.local ?? false,\n ...errorUtil.errToObj(options?.message)\n });\n }\n date(message) {\n return this._addCheck({ kind: "date", message });\n }\n time(options) {\n if (typeof options === "string") {\n return this._addCheck({\n kind: "time",\n precision: null,\n message: options\n });\n }\n return this._addCheck({\n kind: "time",\n precision: typeof options?.precision === "undefined" ? null : options?.precision,\n ...errorUtil.errToObj(options?.message)\n });\n }\n duration(message) {\n return this._addCheck({ kind: "duration", ...errorUtil.errToObj(message) });\n }\n regex(regex, message) {\n return this._addCheck({\n kind: "regex",\n regex,\n ...errorUtil.errToObj(message)\n });\n }\n includes(value, options) {\n return this._addCheck({\n kind: "includes",\n value,\n position: options?.position,\n ...errorUtil.errToObj(options?.message)\n });\n }\n startsWith(value, message) {\n return this._addCheck({\n kind: "startsWith",\n value,\n ...errorUtil.errToObj(message)\n });\n }\n endsWith(value, message) {\n return this._addCheck({\n kind: "endsWith",\n value,\n ...errorUtil.errToObj(message)\n });\n }\n min(minLength, message) {\n return this._addCheck({\n kind: "min",\n value: minLength,\n ...errorUtil.errToObj(message)\n });\n }\n max(maxLength, message) {\n return this._addCheck({\n kind: "max",\n value: maxLength,\n ...errorUtil.errToObj(message)\n });\n }\n length(len, message) {\n return this._addCheck({\n kind: "length",\n value: len,\n ...errorUtil.errToObj(message)\n });\n }\n /**\n * Equivalent to `.min(1)`\n */\n nonempty(message) {\n return this.min(1, errorUtil.errToObj(message));\n }\n trim() {\n return new _ZodString({\n ...this._def,\n checks: [...this._def.checks, { kind: "trim" }]\n });\n }\n toLowerCase() {\n return new _ZodString({\n ...this._def,\n checks: [...this._def.checks, { kind: "toLowerCase" }]\n });\n }\n toUpperCase() {\n return new _ZodString({\n ...this._def,\n checks: [...this._def.checks, { kind: "toUpperCase" }]\n });\n }\n get isDatetime() {\n return !!this._def.checks.find((ch) => ch.kind === "datetime");\n }\n get isDate() {\n return !!this._def.checks.find((ch) => ch.kind === "date");\n }\n get isTime() {\n return !!this._def.checks.find((ch) => ch.kind === "time");\n }\n get isDuration() {\n return !!this._def.checks.find((ch) => ch.kind === "duration");\n }\n get isEmail() {\n return !!this._def.checks.find((ch) => ch.kind === "email");\n }\n get isURL() {\n return !!this._def.checks.find((ch) => ch.kind === "url");\n }\n get isEmoji() {\n return !!this._def.checks.find((ch) => ch.kind === "emoji");\n }\n get isUUID() {\n return !!this._def.checks.find((ch) => ch.kind === "uuid");\n }\n get isNANOID() {\n return !!this._def.checks.find((ch) => ch.kind === "nanoid");\n }\n get isCUID() {\n return !!this._def.checks.find((ch) => ch.kind === "cuid");\n }\n get isCUID2() {\n return !!this._def.checks.find((ch) => ch.kind === "cuid2");\n }\n get isULID() {\n return !!this._def.checks.find((ch) => ch.kind === "ulid");\n }\n get isIP() {\n return !!this._def.checks.find((ch) => ch.kind === "ip");\n }\n get isCIDR() {\n return !!this._def.checks.find((ch) => ch.kind === "cidr");\n }\n get isBase64() {\n return !!this._def.checks.find((ch) => ch.kind === "base64");\n }\n get isBase64url() {\n return !!this._def.checks.find((ch) => ch.kind === "base64url");\n }\n get minLength() {\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === "min") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n }\n return min;\n }\n get maxLength() {\n let max = null;\n for (const ch of this._def.checks) {\n if (ch.kind === "max") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return max;\n }\n};\nZodString.create = (params) => {\n return new ZodString({\n checks: [],\n typeName: ZodFirstPartyTypeKind.ZodString,\n coerce: params?.coerce ?? false,\n ...processCreateParams(params)\n });\n};\nfunction floatSafeRemainder(val, step) {\n const valDecCount = (val.toString().split(".")[1] || "").length;\n const stepDecCount = (step.toString().split(".")[1] || "").length;\n const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;\n const valInt = Number.parseInt(val.toFixed(decCount).replace(".", ""));\n const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", ""));\n return valInt % stepInt / 10 ** decCount;\n}\nvar ZodNumber = class _ZodNumber extends ZodType {\n constructor() {\n super(...arguments);\n this.min = this.gte;\n this.max = this.lte;\n this.step = this.multipleOf;\n }\n _parse(input) {\n if (this._def.coerce) {\n input.data = Number(input.data);\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.number) {\n const ctx2 = this._getOrReturnCtx(input);\n addIssueToContext(ctx2, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.number,\n received: ctx2.parsedType\n });\n return INVALID;\n }\n let ctx = void 0;\n const status = new ParseStatus();\n for (const check of this._def.checks) {\n if (check.kind === "int") {\n if (!util.isInteger(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: "integer",\n received: "float",\n message: check.message\n });\n status.dirty();\n }\n } else if (check.kind === "min") {\n const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;\n if (tooSmall) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: check.value,\n type: "number",\n inclusive: check.inclusive,\n exact: false,\n message: check.message\n });\n status.dirty();\n }\n } else if (check.kind === "max") {\n const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;\n if (tooBig) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: check.value,\n type: "number",\n inclusive: check.inclusive,\n exact: false,\n message: check.message\n });\n status.dirty();\n }\n } else if (check.kind === "multipleOf") {\n if (floatSafeRemainder(input.data, check.value) !== 0) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.not_multiple_of,\n multipleOf: check.value,\n message: check.message\n });\n status.dirty();\n }\n } else if (check.kind === "finite") {\n if (!Number.isFinite(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.not_finite,\n message: check.message\n });\n status.dirty();\n }\n } else {\n util.assertNever(check);\n }\n }\n return { status: status.value, value: input.data };\n }\n gte(value, message) {\n return this.setLimit("min", value, true, errorUtil.toString(message));\n }\n gt(value, message) {\n return this.setLimit("min", value, false, errorUtil.toString(message));\n }\n lte(value, message) {\n return this.setLimit("max", value, true, errorUtil.toString(message));\n }\n lt(value, message) {\n return this.setLimit("max", value, false, errorUtil.toString(message));\n }\n setLimit(kind, value, inclusive, message) {\n return new _ZodNumber({\n ...this._def,\n checks: [\n ...this._def.checks,\n {\n kind,\n value,\n inclusive,\n message: errorUtil.toString(message)\n }\n ]\n });\n }\n _addCheck(check) {\n return new _ZodNumber({\n ...this._def,\n checks: [...this._def.checks, check]\n });\n }\n int(message) {\n return this._addCheck({\n kind: "int",\n message: errorUtil.toString(message)\n });\n }\n positive(message) {\n return this._addCheck({\n kind: "min",\n value: 0,\n inclusive: false,\n message: errorUtil.toString(message)\n });\n }\n negative(message) {\n return this._addCheck({\n kind: "max",\n value: 0,\n inclusive: false,\n message: errorUtil.toString(message)\n });\n }\n nonpositive(message) {\n return this._addCheck({\n kind: "max",\n value: 0,\n inclusive: true,\n message: errorUtil.toString(message)\n });\n }\n nonnegative(message) {\n return this._addCheck({\n kind: "min",\n value: 0,\n inclusive: true,\n message: errorUtil.toString(message)\n });\n }\n multipleOf(value, message) {\n return this._addCheck({\n kind: "multipleOf",\n value,\n message: errorUtil.toString(message)\n });\n }\n finite(message) {\n return this._addCheck({\n kind: "finite",\n message: errorUtil.toString(message)\n });\n }\n safe(message) {\n return this._addCheck({\n kind: "min",\n inclusive: true,\n value: Number.MIN_SAFE_INTEGER,\n message: errorUtil.toString(message)\n })._addCheck({\n kind: "max",\n inclusive: true,\n value: Number.MAX_SAFE_INTEGER,\n message: errorUtil.toString(message)\n });\n }\n get minValue() {\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === "min") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n }\n return min;\n }\n get maxValue() {\n let max = null;\n for (const ch of this._def.checks) {\n if (ch.kind === "max") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return max;\n }\n get isInt() {\n return !!this._def.checks.find((ch) => ch.kind === "int" || ch.kind === "multipleOf" && util.isInteger(ch.value));\n }\n get isFinite() {\n let max = null;\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") {\n return true;\n } else if (ch.kind === "min") {\n if (min === null || ch.value > min)\n min = ch.value;\n } else if (ch.kind === "max") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return Number.isFinite(min) && Number.isFinite(max);\n }\n};\nZodNumber.create = (params) => {\n return new ZodNumber({\n checks: [],\n typeName: ZodFirstPartyTypeKind.ZodNumber,\n coerce: params?.coerce || false,\n ...processCreateParams(params)\n });\n};\nvar ZodBigInt = class _ZodBigInt extends ZodType {\n constructor() {\n super(...arguments);\n this.min = this.gte;\n this.max = this.lte;\n }\n _parse(input) {\n if (this._def.coerce) {\n try {\n input.data = BigInt(input.data);\n } catch {\n return this._getInvalidInput(input);\n }\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.bigint) {\n return this._getInvalidInput(input);\n }\n let ctx = void 0;\n const status = new ParseStatus();\n for (const check of this._def.checks) {\n if (check.kind === "min") {\n const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;\n if (tooSmall) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n type: "bigint",\n minimum: check.value,\n inclusive: check.inclusive,\n message: check.message\n });\n status.dirty();\n }\n } else if (check.kind === "max") {\n const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;\n if (tooBig) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n type: "bigint",\n maximum: check.value,\n inclusive: check.inclusive,\n message: check.message\n });\n status.dirty();\n }\n } else if (check.kind === "multipleOf") {\n if (input.data % check.value !== BigInt(0)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.not_multiple_of,\n multipleOf: check.value,\n message: check.message\n });\n status.dirty();\n }\n } else {\n util.assertNever(check);\n }\n }\n return { status: status.value, value: input.data };\n }\n _getInvalidInput(input) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.bigint,\n received: ctx.parsedType\n });\n return INVALID;\n }\n gte(value, message) {\n return this.setLimit("min", value, true, errorUtil.toString(message));\n }\n gt(value, message) {\n return this.setLimit("min", value, false, errorUtil.toString(message));\n }\n lte(value, message) {\n return this.setLimit("max", value, true, errorUtil.toString(message));\n }\n lt(value, message) {\n return this.setLimit("max", value, false, errorUtil.toString(message));\n }\n setLimit(kind, value, inclusive, message) {\n return new _ZodBigInt({\n ...this._def,\n checks: [\n ...this._def.checks,\n {\n kind,\n value,\n inclusive,\n message: errorUtil.toString(message)\n }\n ]\n });\n }\n _addCheck(check) {\n return new _ZodBigInt({\n ...this._def,\n checks: [...this._def.checks, check]\n });\n }\n positive(message) {\n return this._addCheck({\n kind: "min",\n value: BigInt(0),\n inclusive: false,\n message: errorUtil.toString(message)\n });\n }\n negative(message) {\n return this._addCheck({\n kind: "max",\n value: BigInt(0),\n inclusive: false,\n message: errorUtil.toString(message)\n });\n }\n nonpositive(message) {\n return this._addCheck({\n kind: "max",\n value: BigInt(0),\n inclusive: true,\n message: errorUtil.toString(message)\n });\n }\n nonnegative(message) {\n return this._addCheck({\n kind: "min",\n value: BigInt(0),\n inclusive: true,\n message: errorUtil.toString(message)\n });\n }\n multipleOf(value, message) {\n return this._addCheck({\n kind: "multipleOf",\n value,\n message: errorUtil.toString(message)\n });\n }\n get minValue() {\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === "min") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n }\n return min;\n }\n get maxValue() {\n let max = null;\n for (const ch of this._def.checks) {\n if (ch.kind === "max") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return max;\n }\n};\nZodBigInt.create = (params) => {\n return new ZodBigInt({\n checks: [],\n typeName: ZodFirstPartyTypeKind.ZodBigInt,\n coerce: params?.coerce ?? false,\n ...processCreateParams(params)\n });\n};\nvar ZodBoolean = class extends ZodType {\n _parse(input) {\n if (this._def.coerce) {\n input.data = Boolean(input.data);\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.boolean) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.boolean,\n received: ctx.parsedType\n });\n return INVALID;\n }\n return OK(input.data);\n }\n};\nZodBoolean.create = (params) => {\n return new ZodBoolean({\n typeName: ZodFirstPartyTypeKind.ZodBoolean,\n coerce: params?.coerce || false,\n ...processCreateParams(params)\n });\n};\nvar ZodDate = class _ZodDate extends ZodType {\n _parse(input) {\n if (this._def.coerce) {\n input.data = new Date(input.data);\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.date) {\n const ctx2 = this._getOrReturnCtx(input);\n addIssueToContext(ctx2, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.date,\n received: ctx2.parsedType\n });\n return INVALID;\n }\n if (Number.isNaN(input.data.getTime())) {\n const ctx2 = this._getOrReturnCtx(input);\n addIssueToContext(ctx2, {\n code: ZodIssueCode.invalid_date\n });\n return INVALID;\n }\n const status = new ParseStatus();\n let ctx = void 0;\n for (const check of this._def.checks) {\n if (check.kind === "min") {\n if (input.data.getTime() < check.value) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n message: check.message,\n inclusive: true,\n exact: false,\n minimum: check.value,\n type: "date"\n });\n status.dirty();\n }\n } else if (check.kind === "max") {\n if (input.data.getTime() > check.value) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n message: check.message,\n inclusive: true,\n exact: false,\n maximum: check.value,\n type: "date"\n });\n status.dirty();\n }\n } else {\n util.assertNever(check);\n }\n }\n return {\n status: status.value,\n value: new Date(input.data.getTime())\n };\n }\n _addCheck(check) {\n return new _ZodDate({\n ...this._def,\n checks: [...this._def.checks, check]\n });\n }\n min(minDate, message) {\n return this._addCheck({\n kind: "min",\n value: minDate.getTime(),\n message: errorUtil.toString(message)\n });\n }\n max(maxDate, message) {\n return this._addCheck({\n kind: "max",\n value: maxDate.getTime(),\n message: errorUtil.toString(message)\n });\n }\n get minDate() {\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === "min") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n }\n return min != null ? new Date(min) : null;\n }\n get maxDate() {\n let max = null;\n for (const ch of this._def.checks) {\n if (ch.kind === "max") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return max != null ? new Date(max) : null;\n }\n};\nZodDate.create = (params) => {\n return new ZodDate({\n checks: [],\n coerce: params?.coerce || false,\n typeName: ZodFirstPartyTypeKind.ZodDate,\n ...processCreateParams(params)\n });\n};\nvar ZodSymbol = class extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.symbol) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.symbol,\n received: ctx.parsedType\n });\n return INVALID;\n }\n return OK(input.data);\n }\n};\nZodSymbol.create = (params) => {\n return new ZodSymbol({\n typeName: ZodFirstPartyTypeKind.ZodSymbol,\n ...processCreateParams(params)\n });\n};\nvar ZodUndefined = class extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.undefined) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.undefined,\n received: ctx.parsedType\n });\n return INVALID;\n }\n return OK(input.data);\n }\n};\nZodUndefined.create = (params) => {\n return new ZodUndefined({\n typeName: ZodFirstPartyTypeKind.ZodUndefined,\n ...processCreateParams(params)\n });\n};\nvar ZodNull = class extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.null) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.null,\n received: ctx.parsedType\n });\n return INVALID;\n }\n return OK(input.data);\n }\n};\nZodNull.create = (params) => {\n return new ZodNull({\n typeName: ZodFirstPartyTypeKind.ZodNull,\n ...processCreateParams(params)\n });\n};\nvar ZodAny = class extends ZodType {\n constructor() {\n super(...arguments);\n this._any = true;\n }\n _parse(input) {\n return OK(input.data);\n }\n};\nZodAny.create = (params) => {\n return new ZodAny({\n typeName: ZodFirstPartyTypeKind.ZodAny,\n ...processCreateParams(params)\n });\n};\nvar ZodUnknown = class extends ZodType {\n constructor() {\n super(...arguments);\n this._unknown = true;\n }\n _parse(input) {\n return OK(input.data);\n }\n};\nZodUnknown.create = (params) => {\n return new ZodUnknown({\n typeName: ZodFirstPartyTypeKind.ZodUnknown,\n ...processCreateParams(params)\n });\n};\nvar ZodNever = class extends ZodType {\n _parse(input) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.never,\n received: ctx.parsedType\n });\n return INVALID;\n }\n};\nZodNever.create = (params) => {\n return new ZodNever({\n typeName: ZodFirstPartyTypeKind.ZodNever,\n ...processCreateParams(params)\n });\n};\nvar ZodVoid = class extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.undefined) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.void,\n received: ctx.parsedType\n });\n return INVALID;\n }\n return OK(input.data);\n }\n};\nZodVoid.create = (params) => {\n return new ZodVoid({\n typeName: ZodFirstPartyTypeKind.ZodVoid,\n ...processCreateParams(params)\n });\n};\nvar ZodArray = class _ZodArray extends ZodType {\n _parse(input) {\n const { ctx, status } = this._processInputParams(input);\n const def = this._def;\n if (ctx.parsedType !== ZodParsedType.array) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.array,\n received: ctx.parsedType\n });\n return INVALID;\n }\n if (def.exactLength !== null) {\n const tooBig = ctx.data.length > def.exactLength.value;\n const tooSmall = ctx.data.length < def.exactLength.value;\n if (tooBig || tooSmall) {\n addIssueToContext(ctx, {\n code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small,\n minimum: tooSmall ? def.exactLength.value : void 0,\n maximum: tooBig ? def.exactLength.value : void 0,\n type: "array",\n inclusive: true,\n exact: true,\n message: def.exactLength.message\n });\n status.dirty();\n }\n }\n if (def.minLength !== null) {\n if (ctx.data.length < def.minLength.value) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: def.minLength.value,\n type: "array",\n inclusive: true,\n exact: false,\n message: def.minLength.message\n });\n status.dirty();\n }\n }\n if (def.maxLength !== null) {\n if (ctx.data.length > def.maxLength.value) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: def.maxLength.value,\n type: "array",\n inclusive: true,\n exact: false,\n message: def.maxLength.message\n });\n status.dirty();\n }\n }\n if (ctx.common.async) {\n return Promise.all([...ctx.data].map((item, i) => {\n return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i));\n })).then((result2) => {\n return ParseStatus.mergeArray(status, result2);\n });\n }\n const result = [...ctx.data].map((item, i) => {\n return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i));\n });\n return ParseStatus.mergeArray(status, result);\n }\n get element() {\n return this._def.type;\n }\n min(minLength, message) {\n return new _ZodArray({\n ...this._def,\n minLength: { value: minLength, message: errorUtil.toString(message) }\n });\n }\n max(maxLength, message) {\n return new _ZodArray({\n ...this._def,\n maxLength: { value: maxLength, message: errorUtil.toString(message) }\n });\n }\n length(len, message) {\n return new _ZodArray({\n ...this._def,\n exactLength: { value: len, message: errorUtil.toString(message) }\n });\n }\n nonempty(message) {\n return this.min(1, message);\n }\n};\nZodArray.create = (schema, params) => {\n return new ZodArray({\n type: schema,\n minLength: null,\n maxLength: null,\n exactLength: null,\n typeName: ZodFirstPartyTypeKind.ZodArray,\n ...processCreateParams(params)\n });\n};\nfunction deepPartialify(schema) {\n if (schema instanceof ZodObject) {\n const newShape = {};\n for (const key in schema.shape) {\n const fieldSchema = schema.shape[key];\n newShape[key] = ZodOptional.create(deepPartialify(fieldSchema));\n }\n return new ZodObject({\n ...schema._def,\n shape: () => newShape\n });\n } else if (schema instanceof ZodArray) {\n return new ZodArray({\n ...schema._def,\n type: deepPartialify(schema.element)\n });\n } else if (schema instanceof ZodOptional) {\n return ZodOptional.create(deepPartialify(schema.unwrap()));\n } else if (schema instanceof ZodNullable) {\n return ZodNullable.create(deepPartialify(schema.unwrap()));\n } else if (schema instanceof ZodTuple) {\n return ZodTuple.create(schema.items.map((item) => deepPartialify(item)));\n } else {\n return schema;\n }\n}\nvar ZodObject = class _ZodObject extends ZodType {\n constructor() {\n super(...arguments);\n this._cached = null;\n this.nonstrict = this.passthrough;\n this.augment = this.extend;\n }\n _getCached() {\n if (this._cached !== null)\n return this._cached;\n const shape = this._def.shape();\n const keys = util.objectKeys(shape);\n this._cached = { shape, keys };\n return this._cached;\n }\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.object) {\n const ctx2 = this._getOrReturnCtx(input);\n addIssueToContext(ctx2, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.object,\n received: ctx2.parsedType\n });\n return INVALID;\n }\n const { status, ctx } = this._processInputParams(input);\n const { shape, keys: shapeKeys } = this._getCached();\n const extraKeys = [];\n if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === "strip")) {\n for (const key in ctx.data) {\n if (!shapeKeys.includes(key)) {\n extraKeys.push(key);\n }\n }\n }\n const pairs = [];\n for (const key of shapeKeys) {\n const keyValidator = shape[key];\n const value = ctx.data[key];\n pairs.push({\n key: { status: "valid", value: key },\n value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),\n alwaysSet: key in ctx.data\n });\n }\n if (this._def.catchall instanceof ZodNever) {\n const unknownKeys = this._def.unknownKeys;\n if (unknownKeys === "passthrough") {\n for (const key of extraKeys) {\n pairs.push({\n key: { status: "valid", value: key },\n value: { status: "valid", value: ctx.data[key] }\n });\n }\n } else if (unknownKeys === "strict") {\n if (extraKeys.length > 0) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.unrecognized_keys,\n keys: extraKeys\n });\n status.dirty();\n }\n } else if (unknownKeys === "strip") {\n } else {\n throw new Error(`Internal ZodObject error: invalid unknownKeys value.`);\n }\n } else {\n const catchall = this._def.catchall;\n for (const key of extraKeys) {\n const value = ctx.data[key];\n pairs.push({\n key: { status: "valid", value: key },\n value: catchall._parse(\n new ParseInputLazyPath(ctx, value, ctx.path, key)\n //, ctx.child(key), value, getParsedType(value)\n ),\n alwaysSet: key in ctx.data\n });\n }\n }\n if (ctx.common.async) {\n return Promise.resolve().then(async () => {\n const syncPairs = [];\n for (const pair of pairs) {\n const key = await pair.key;\n const value = await pair.value;\n syncPairs.push({\n key,\n value,\n alwaysSet: pair.alwaysSet\n });\n }\n return syncPairs;\n }).then((syncPairs) => {\n return ParseStatus.mergeObjectSync(status, syncPairs);\n });\n } else {\n return ParseStatus.mergeObjectSync(status, pairs);\n }\n }\n get shape() {\n return this._def.shape();\n }\n strict(message) {\n errorUtil.errToObj;\n return new _ZodObject({\n ...this._def,\n unknownKeys: "strict",\n ...message !== void 0 ? {\n errorMap: (issue, ctx) => {\n const defaultError = this._def.errorMap?.(issue, ctx).message ?? ctx.defaultError;\n if (issue.code === "unrecognized_keys")\n return {\n message: errorUtil.errToObj(message).message ?? defaultError\n };\n return {\n message: defaultError\n };\n }\n } : {}\n });\n }\n strip() {\n return new _ZodObject({\n ...this._def,\n unknownKeys: "strip"\n });\n }\n passthrough() {\n return new _ZodObject({\n ...this._def,\n unknownKeys: "passthrough"\n });\n }\n // const AugmentFactory =\n // <Def extends ZodObjectDef>(def: Def) =>\n // <Augmentation extends ZodRawShape>(\n // augmentation: Augmentation\n // ): ZodObject<\n // extendShape<ReturnType<Def["shape"]>, Augmentation>,\n // Def["unknownKeys"],\n // Def["catchall"]\n // > => {\n // return new ZodObject({\n // ...def,\n // shape: () => ({\n // ...def.shape(),\n // ...augmentation,\n // }),\n // }) as any;\n // };\n extend(augmentation) {\n return new _ZodObject({\n ...this._def,\n shape: () => ({\n ...this._def.shape(),\n ...augmentation\n })\n });\n }\n /**\n * Prior to zod@1.0.12 there was a bug in the\n * inferred type of merged objects. Please\n * upgrade if you are experiencing issues.\n */\n merge(merging) {\n const merged = new _ZodObject({\n unknownKeys: merging._def.unknownKeys,\n catchall: merging._def.catchall,\n shape: () => ({\n ...this._def.shape(),\n ...merging._def.shape()\n }),\n typeName: ZodFirstPartyTypeKind.ZodObject\n });\n return merged;\n }\n // merge<\n // Incoming extends AnyZodObject,\n // Augmentation extends Incoming["shape"],\n // NewOutput extends {\n // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation\n // ? Augmentation[k]["_output"]\n // : k extends keyof Output\n // ? Output[k]\n // : never;\n // },\n // NewInput extends {\n // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation\n // ? Augmentation[k]["_input"]\n // : k extends keyof Input\n // ? Input[k]\n // : never;\n // }\n // >(\n // merging: Incoming\n // ): ZodObject<\n // extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,\n // Incoming["_def"]["unknownKeys"],\n // Incoming["_def"]["catchall"],\n // NewOutput,\n // NewInput\n // > {\n // const merged: any = new ZodObject({\n // unknownKeys: merging._def.unknownKeys,\n // catchall: merging._def.catchall,\n // shape: () =>\n // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),\n // typeName: ZodFirstPartyTypeKind.ZodObject,\n // }) as any;\n // return merged;\n // }\n setKey(key, schema) {\n return this.augment({ [key]: schema });\n }\n // merge<Incoming extends AnyZodObject>(\n // merging: Incoming\n // ): //ZodObject<T & Incoming["_shape"], UnknownKeys, Catchall> = (merging) => {\n // ZodObject<\n // extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,\n // Incoming["_def"]["unknownKeys"],\n // Incoming["_def"]["catchall"]\n // > {\n // // const mergedShape = objectUtil.mergeShapes(\n // // this._def.shape(),\n // // merging._def.shape()\n // // );\n // const merged: any = new ZodObject({\n // unknownKeys: merging._def.unknownKeys,\n // catchall: merging._def.catchall,\n // shape: () =>\n // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),\n // typeName: ZodFirstPartyTypeKind.ZodObject,\n // }) as any;\n // return merged;\n // }\n catchall(index) {\n return new _ZodObject({\n ...this._def,\n catchall: index\n });\n }\n pick(mask) {\n const shape = {};\n for (const key of util.objectKeys(mask)) {\n if (mask[key] && this.shape[key]) {\n shape[key] = this.shape[key];\n }\n }\n return new _ZodObject({\n ...this._def,\n shape: () => shape\n });\n }\n omit(mask) {\n const shape = {};\n for (const key of util.objectKeys(this.shape)) {\n if (!mask[key]) {\n shape[key] = this.shape[key];\n }\n }\n return new _ZodObject({\n ...this._def,\n shape: () => shape\n });\n }\n /**\n * @deprecated\n */\n deepPartial() {\n return deepPartialify(this);\n }\n partial(mask) {\n const newShape = {};\n for (const key of util.objectKeys(this.shape)) {\n const fieldSchema = this.shape[key];\n if (mask && !mask[key]) {\n newShape[key] = fieldSchema;\n } else {\n newShape[key] = fieldSchema.optional();\n }\n }\n return new _ZodObject({\n ...this._def,\n shape: () => newShape\n });\n }\n required(mask) {\n const newShape = {};\n for (const key of util.objectKeys(this.shape)) {\n if (mask && !mask[key]) {\n newShape[key] = this.shape[key];\n } else {\n const fieldSchema = this.shape[key];\n let newField = fieldSchema;\n while (newField instanceof ZodOptional) {\n newField = newField._def.innerType;\n }\n newShape[key] = newField;\n }\n }\n return new _ZodObject({\n ...this._def,\n shape: () => newShape\n });\n }\n keyof() {\n return createZodEnum(util.objectKeys(this.shape));\n }\n};\nZodObject.create = (shape, params) => {\n return new ZodObject({\n shape: () => shape,\n unknownKeys: "strip",\n catchall: ZodNever.create(),\n typeName: ZodFirstPartyTypeKind.ZodObject,\n ...processCreateParams(params)\n });\n};\nZodObject.strictCreate = (shape, params) => {\n return new ZodObject({\n shape: () => shape,\n unknownKeys: "strict",\n catchall: ZodNever.create(),\n typeName: ZodFirstPartyTypeKind.ZodObject,\n ...processCreateParams(params)\n });\n};\nZodObject.lazycreate = (shape, params) => {\n return new ZodObject({\n shape,\n unknownKeys: "strip",\n catchall: ZodNever.create(),\n typeName: ZodFirstPartyTypeKind.ZodObject,\n ...processCreateParams(params)\n });\n};\nvar ZodUnion = class extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n const options = this._def.options;\n function handleResults(results) {\n for (const result of results) {\n if (result.result.status === "valid") {\n return result.result;\n }\n }\n for (const result of results) {\n if (result.result.status === "dirty") {\n ctx.common.issues.push(...result.ctx.common.issues);\n return result.result;\n }\n }\n const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues));\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_union,\n unionErrors\n });\n return INVALID;\n }\n if (ctx.common.async) {\n return Promise.all(options.map(async (option) => {\n const childCtx = {\n ...ctx,\n common: {\n ...ctx.common,\n issues: []\n },\n parent: null\n };\n return {\n result: await option._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: childCtx\n }),\n ctx: childCtx\n };\n })).then(handleResults);\n } else {\n let dirty = void 0;\n const issues = [];\n for (const option of options) {\n const childCtx = {\n ...ctx,\n common: {\n ...ctx.common,\n issues: []\n },\n parent: null\n };\n const result = option._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: childCtx\n });\n if (result.status === "valid") {\n return result;\n } else if (result.status === "dirty" && !dirty) {\n dirty = { result, ctx: childCtx };\n }\n if (childCtx.common.issues.length) {\n issues.push(childCtx.common.issues);\n }\n }\n if (dirty) {\n ctx.common.issues.push(...dirty.ctx.common.issues);\n return dirty.result;\n }\n const unionErrors = issues.map((issues2) => new ZodError(issues2));\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_union,\n unionErrors\n });\n return INVALID;\n }\n }\n get options() {\n return this._def.options;\n }\n};\nZodUnion.create = (types, params) => {\n return new ZodUnion({\n options: types,\n typeName: ZodFirstPartyTypeKind.ZodUnion,\n ...processCreateParams(params)\n });\n};\nvar getDiscriminator = (type) => {\n if (type instanceof ZodLazy) {\n return getDiscriminator(type.schema);\n } else if (type instanceof ZodEffects) {\n return getDiscriminator(type.innerType());\n } else if (type instanceof ZodLiteral) {\n return [type.value];\n } else if (type instanceof ZodEnum) {\n return type.options;\n } else if (type instanceof ZodNativeEnum) {\n return util.objectValues(type.enum);\n } else if (type instanceof ZodDefault) {\n return getDiscriminator(type._def.innerType);\n } else if (type instanceof ZodUndefined) {\n return [void 0];\n } else if (type instanceof ZodNull) {\n return [null];\n } else if (type instanceof ZodOptional) {\n return [void 0, ...getDiscriminator(type.unwrap())];\n } else if (type instanceof ZodNullable) {\n return [null, ...getDiscriminator(type.unwrap())];\n } else if (type instanceof ZodBranded) {\n return getDiscriminator(type.unwrap());\n } else if (type instanceof ZodReadonly) {\n return getDiscriminator(type.unwrap());\n } else if (type instanceof ZodCatch) {\n return getDiscriminator(type._def.innerType);\n } else {\n return [];\n }\n};\nvar ZodDiscriminatedUnion = class _ZodDiscriminatedUnion extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.object) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.object,\n received: ctx.parsedType\n });\n return INVALID;\n }\n const discriminator = this.discriminator;\n const discriminatorValue = ctx.data[discriminator];\n const option = this.optionsMap.get(discriminatorValue);\n if (!option) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_union_discriminator,\n options: Array.from(this.optionsMap.keys()),\n path: [discriminator]\n });\n return INVALID;\n }\n if (ctx.common.async) {\n return option._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx\n });\n } else {\n return option._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx\n });\n }\n }\n get discriminator() {\n return this._def.discriminator;\n }\n get options() {\n return this._def.options;\n }\n get optionsMap() {\n return this._def.optionsMap;\n }\n /**\n * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor.\n * However, it only allows a union of objects, all of which need to share a discriminator property. This property must\n * have a different value for each object in the union.\n * @param discriminator the name of the discriminator property\n * @param types an array of object schemas\n * @param params\n */\n static create(discriminator, options, params) {\n const optionsMap = /* @__PURE__ */ new Map();\n for (const type of options) {\n const discriminatorValues = getDiscriminator(type.shape[discriminator]);\n if (!discriminatorValues.length) {\n throw new Error(`A discriminator value for key \\`${discriminator}\\` could not be extracted from all schema options`);\n }\n for (const value of discriminatorValues) {\n if (optionsMap.has(value)) {\n throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`);\n }\n optionsMap.set(value, type);\n }\n }\n return new _ZodDiscriminatedUnion({\n typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion,\n discriminator,\n options,\n optionsMap,\n ...processCreateParams(params)\n });\n }\n};\nfunction mergeValues(a, b) {\n const aType = getParsedType(a);\n const bType = getParsedType(b);\n if (a === b) {\n return { valid: true, data: a };\n } else if (aType === ZodParsedType.object && bType === ZodParsedType.object) {\n const bKeys = util.objectKeys(b);\n const sharedKeys = util.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1);\n const newObj = { ...a, ...b };\n for (const key of sharedKeys) {\n const sharedValue = mergeValues(a[key], b[key]);\n if (!sharedValue.valid) {\n return { valid: false };\n }\n newObj[key] = sharedValue.data;\n }\n return { valid: true, data: newObj };\n } else if (aType === ZodParsedType.array && bType === ZodParsedType.array) {\n if (a.length !== b.length) {\n return { valid: false };\n }\n const newArray = [];\n for (let index = 0; index < a.length; index++) {\n const itemA = a[index];\n const itemB = b[index];\n const sharedValue = mergeValues(itemA, itemB);\n if (!sharedValue.valid) {\n return { valid: false };\n }\n newArray.push(sharedValue.data);\n }\n return { valid: true, data: newArray };\n } else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a === +b) {\n return { valid: true, data: a };\n } else {\n return { valid: false };\n }\n}\nvar ZodIntersection = class extends ZodType {\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n const handleParsed = (parsedLeft, parsedRight) => {\n if (isAborted(parsedLeft) || isAborted(parsedRight)) {\n return INVALID;\n }\n const merged = mergeValues(parsedLeft.value, parsedRight.value);\n if (!merged.valid) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_intersection_types\n });\n return INVALID;\n }\n if (isDirty(parsedLeft) || isDirty(parsedRight)) {\n status.dirty();\n }\n return { status: status.value, value: merged.data };\n };\n if (ctx.common.async) {\n return Promise.all([\n this._def.left._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx\n }),\n this._def.right._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx\n })\n ]).then(([left, right]) => handleParsed(left, right));\n } else {\n return handleParsed(this._def.left._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx\n }), this._def.right._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx\n }));\n }\n }\n};\nZodIntersection.create = (left, right, params) => {\n return new ZodIntersection({\n left,\n right,\n typeName: ZodFirstPartyTypeKind.ZodIntersection,\n ...processCreateParams(params)\n });\n};\nvar ZodTuple = class _ZodTuple extends ZodType {\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.array) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.array,\n received: ctx.parsedType\n });\n return INVALID;\n }\n if (ctx.data.length < this._def.items.length) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: this._def.items.length,\n inclusive: true,\n exact: false,\n type: "array"\n });\n return INVALID;\n }\n const rest = this._def.rest;\n if (!rest && ctx.data.length > this._def.items.length) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: this._def.items.length,\n inclusive: true,\n exact: false,\n type: "array"\n });\n status.dirty();\n }\n const items = [...ctx.data].map((item, itemIndex) => {\n const schema = this._def.items[itemIndex] || this._def.rest;\n if (!schema)\n return null;\n return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex));\n }).filter((x) => !!x);\n if (ctx.common.async) {\n return Promise.all(items).then((results) => {\n return ParseStatus.mergeArray(status, results);\n });\n } else {\n return ParseStatus.mergeArray(status, items);\n }\n }\n get items() {\n return this._def.items;\n }\n rest(rest) {\n return new _ZodTuple({\n ...this._def,\n rest\n });\n }\n};\nZodTuple.create = (schemas, params) => {\n if (!Array.isArray(schemas)) {\n throw new Error("You must pass an array of schemas to z.tuple([ ... ])");\n }\n return new ZodTuple({\n items: schemas,\n typeName: ZodFirstPartyTypeKind.ZodTuple,\n rest: null,\n ...processCreateParams(params)\n });\n};\nvar ZodRecord = class _ZodRecord extends ZodType {\n get keySchema() {\n return this._def.keyType;\n }\n get valueSchema() {\n return this._def.valueType;\n }\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.object) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.object,\n received: ctx.parsedType\n });\n return INVALID;\n }\n const pairs = [];\n const keyType = this._def.keyType;\n const valueType = this._def.valueType;\n for (const key in ctx.data) {\n pairs.push({\n key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)),\n value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)),\n alwaysSet: key in ctx.data\n });\n }\n if (ctx.common.async) {\n return ParseStatus.mergeObjectAsync(status, pairs);\n } else {\n return ParseStatus.mergeObjectSync(status, pairs);\n }\n }\n get element() {\n return this._def.valueType;\n }\n static create(first, second, third) {\n if (second instanceof ZodType) {\n return new _ZodRecord({\n keyType: first,\n valueType: second,\n typeName: ZodFirstPartyTypeKind.ZodRecord,\n ...processCreateParams(third)\n });\n }\n return new _ZodRecord({\n keyType: ZodString.create(),\n valueType: first,\n typeName: ZodFirstPartyTypeKind.ZodRecord,\n ...processCreateParams(second)\n });\n }\n};\nvar ZodMap = class extends ZodType {\n get keySchema() {\n return this._def.keyType;\n }\n get valueSchema() {\n return this._def.valueType;\n }\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.map) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.map,\n received: ctx.parsedType\n });\n return INVALID;\n }\n const keyType = this._def.keyType;\n const valueType = this._def.valueType;\n const pairs = [...ctx.data.entries()].map(([key, value], index) => {\n return {\n key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])),\n value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"]))\n };\n });\n if (ctx.common.async) {\n const finalMap = /* @__PURE__ */ new Map();\n return Promise.resolve().then(async () => {\n for (const pair of pairs) {\n const key = await pair.key;\n const value = await pair.value;\n if (key.status === "aborted" || value.status === "aborted") {\n return INVALID;\n }\n if (key.status === "dirty" || value.status === "dirty") {\n status.dirty();\n }\n finalMap.set(key.value, value.value);\n }\n return { status: status.value, value: finalMap };\n });\n } else {\n const finalMap = /* @__PURE__ */ new Map();\n for (const pair of pairs) {\n const key = pair.key;\n const value = pair.value;\n if (key.status === "aborted" || value.status === "aborted") {\n return INVALID;\n }\n if (key.status === "dirty" || value.status === "dirty") {\n status.dirty();\n }\n finalMap.set(key.value, value.value);\n }\n return { status: status.value, value: finalMap };\n }\n }\n};\nZodMap.create = (keyType, valueType, params) => {\n return new ZodMap({\n valueType,\n keyType,\n typeName: ZodFirstPartyTypeKind.ZodMap,\n ...processCreateParams(params)\n });\n};\nvar ZodSet = class _ZodSet extends ZodType {\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.set) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.set,\n received: ctx.parsedType\n });\n return INVALID;\n }\n const def = this._def;\n if (def.minSize !== null) {\n if (ctx.data.size < def.minSize.value) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: def.minSize.value,\n type: "set",\n inclusive: true,\n exact: false,\n message: def.minSize.message\n });\n status.dirty();\n }\n }\n if (def.maxSize !== null) {\n if (ctx.data.size > def.maxSize.value) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: def.maxSize.value,\n type: "set",\n inclusive: true,\n exact: false,\n message: def.maxSize.message\n });\n status.dirty();\n }\n }\n const valueType = this._def.valueType;\n function finalizeSet(elements2) {\n const parsedSet = /* @__PURE__ */ new Set();\n for (const element of elements2) {\n if (element.status === "aborted")\n return INVALID;\n if (element.status === "dirty")\n status.dirty();\n parsedSet.add(element.value);\n }\n return { status: status.value, value: parsedSet };\n }\n const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i)));\n if (ctx.common.async) {\n return Promise.all(elements).then((elements2) => finalizeSet(elements2));\n } else {\n return finalizeSet(elements);\n }\n }\n min(minSize, message) {\n return new _ZodSet({\n ...this._def,\n minSize: { value: minSize, message: errorUtil.toString(message) }\n });\n }\n max(maxSize, message) {\n return new _ZodSet({\n ...this._def,\n maxSize: { value: maxSize, message: errorUtil.toString(message) }\n });\n }\n size(size, message) {\n return this.min(size, message).max(size, message);\n }\n nonempty(message) {\n return this.min(1, message);\n }\n};\nZodSet.create = (valueType, params) => {\n return new ZodSet({\n valueType,\n minSize: null,\n maxSize: null,\n typeName: ZodFirstPartyTypeKind.ZodSet,\n ...processCreateParams(params)\n });\n};\nvar ZodFunction = class _ZodFunction extends ZodType {\n constructor() {\n super(...arguments);\n this.validate = this.implement;\n }\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.function) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.function,\n received: ctx.parsedType\n });\n return INVALID;\n }\n function makeArgsIssue(args, error) {\n return makeIssue({\n data: args,\n path: ctx.path,\n errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x) => !!x),\n issueData: {\n code: ZodIssueCode.invalid_arguments,\n argumentsError: error\n }\n });\n }\n function makeReturnsIssue(returns, error) {\n return makeIssue({\n data: returns,\n path: ctx.path,\n errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x) => !!x),\n issueData: {\n code: ZodIssueCode.invalid_return_type,\n returnTypeError: error\n }\n });\n }\n const params = { errorMap: ctx.common.contextualErrorMap };\n const fn = ctx.data;\n if (this._def.returns instanceof ZodPromise) {\n const me = this;\n return OK(async function(...args) {\n const error = new ZodError([]);\n const parsedArgs = await me._def.args.parseAsync(args, params).catch((e) => {\n error.addIssue(makeArgsIssue(args, e));\n throw error;\n });\n const result = await Reflect.apply(fn, this, parsedArgs);\n const parsedReturns = await me._def.returns._def.type.parseAsync(result, params).catch((e) => {\n error.addIssue(makeReturnsIssue(result, e));\n throw error;\n });\n return parsedReturns;\n });\n } else {\n const me = this;\n return OK(function(...args) {\n const parsedArgs = me._def.args.safeParse(args, params);\n if (!parsedArgs.success) {\n throw new ZodError([makeArgsIssue(args, parsedArgs.error)]);\n }\n const result = Reflect.apply(fn, this, parsedArgs.data);\n const parsedReturns = me._def.returns.safeParse(result, params);\n if (!parsedReturns.success) {\n throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]);\n }\n return parsedReturns.data;\n });\n }\n }\n parameters() {\n return this._def.args;\n }\n returnType() {\n return this._def.returns;\n }\n args(...items) {\n return new _ZodFunction({\n ...this._def,\n args: ZodTuple.create(items).rest(ZodUnknown.create())\n });\n }\n returns(returnType) {\n return new _ZodFunction({\n ...this._def,\n returns: returnType\n });\n }\n implement(func) {\n const validatedFunc = this.parse(func);\n return validatedFunc;\n }\n strictImplement(func) {\n const validatedFunc = this.parse(func);\n return validatedFunc;\n }\n static create(args, returns, params) {\n return new _ZodFunction({\n args: args ? args : ZodTuple.create([]).rest(ZodUnknown.create()),\n returns: returns || ZodUnknown.create(),\n typeName: ZodFirstPartyTypeKind.ZodFunction,\n ...processCreateParams(params)\n });\n }\n};\nvar ZodLazy = class extends ZodType {\n get schema() {\n return this._def.getter();\n }\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n const lazySchema = this._def.getter();\n return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx });\n }\n};\nZodLazy.create = (getter, params) => {\n return new ZodLazy({\n getter,\n typeName: ZodFirstPartyTypeKind.ZodLazy,\n ...processCreateParams(params)\n });\n};\nvar ZodLiteral = class extends ZodType {\n _parse(input) {\n if (input.data !== this._def.value) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n received: ctx.data,\n code: ZodIssueCode.invalid_literal,\n expected: this._def.value\n });\n return INVALID;\n }\n return { status: "valid", value: input.data };\n }\n get value() {\n return this._def.value;\n }\n};\nZodLiteral.create = (value, params) => {\n return new ZodLiteral({\n value,\n typeName: ZodFirstPartyTypeKind.ZodLiteral,\n ...processCreateParams(params)\n });\n};\nfunction createZodEnum(values, params) {\n return new ZodEnum({\n values,\n typeName: ZodFirstPartyTypeKind.ZodEnum,\n ...processCreateParams(params)\n });\n}\nvar ZodEnum = class _ZodEnum extends ZodType {\n _parse(input) {\n if (typeof input.data !== "string") {\n const ctx = this._getOrReturnCtx(input);\n const expectedValues = this._def.values;\n addIssueToContext(ctx, {\n expected: util.joinValues(expectedValues),\n received: ctx.parsedType,\n code: ZodIssueCode.invalid_type\n });\n return INVALID;\n }\n if (!this._cache) {\n this._cache = new Set(this._def.values);\n }\n if (!this._cache.has(input.data)) {\n const ctx = this._getOrReturnCtx(input);\n const expectedValues = this._def.values;\n addIssueToContext(ctx, {\n received: ctx.data,\n code: ZodIssueCode.invalid_enum_value,\n options: expectedValues\n });\n return INVALID;\n }\n return OK(input.data);\n }\n get options() {\n return this._def.values;\n }\n get enum() {\n const enumValues = {};\n for (const val of this._def.values) {\n enumValues[val] = val;\n }\n return enumValues;\n }\n get Values() {\n const enumValues = {};\n for (const val of this._def.values) {\n enumValues[val] = val;\n }\n return enumValues;\n }\n get Enum() {\n const enumValues = {};\n for (const val of this._def.values) {\n enumValues[val] = val;\n }\n return enumValues;\n }\n extract(values, newDef = this._def) {\n return _ZodEnum.create(values, {\n ...this._def,\n ...newDef\n });\n }\n exclude(values, newDef = this._def) {\n return _ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), {\n ...this._def,\n ...newDef\n });\n }\n};\nZodEnum.create = createZodEnum;\nvar ZodNativeEnum = class extends ZodType {\n _parse(input) {\n const nativeEnumValues = util.getValidEnumValues(this._def.values);\n const ctx = this._getOrReturnCtx(input);\n if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) {\n const expectedValues = util.objectValues(nativeEnumValues);\n addIssueToContext(ctx, {\n expected: util.joinValues(expectedValues),\n received: ctx.parsedType,\n code: ZodIssueCode.invalid_type\n });\n return INVALID;\n }\n if (!this._cache) {\n this._cache = new Set(util.getValidEnumValues(this._def.values));\n }\n if (!this._cache.has(input.data)) {\n const expectedValues = util.objectValues(nativeEnumValues);\n addIssueToContext(ctx, {\n received: ctx.data,\n code: ZodIssueCode.invalid_enum_value,\n options: expectedValues\n });\n return INVALID;\n }\n return OK(input.data);\n }\n get enum() {\n return this._def.values;\n }\n};\nZodNativeEnum.create = (values, params) => {\n return new ZodNativeEnum({\n values,\n typeName: ZodFirstPartyTypeKind.ZodNativeEnum,\n ...processCreateParams(params)\n });\n};\nvar ZodPromise = class extends ZodType {\n unwrap() {\n return this._def.type;\n }\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.promise,\n received: ctx.parsedType\n });\n return INVALID;\n }\n const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data);\n return OK(promisified.then((data) => {\n return this._def.type.parseAsync(data, {\n path: ctx.path,\n errorMap: ctx.common.contextualErrorMap\n });\n }));\n }\n};\nZodPromise.create = (schema, params) => {\n return new ZodPromise({\n type: schema,\n typeName: ZodFirstPartyTypeKind.ZodPromise,\n ...processCreateParams(params)\n });\n};\nvar ZodEffects = class extends ZodType {\n innerType() {\n return this._def.schema;\n }\n sourceType() {\n return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects ? this._def.schema.sourceType() : this._def.schema;\n }\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n const effect = this._def.effect || null;\n const checkCtx = {\n addIssue: (arg) => {\n addIssueToContext(ctx, arg);\n if (arg.fatal) {\n status.abort();\n } else {\n status.dirty();\n }\n },\n get path() {\n return ctx.path;\n }\n };\n checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx);\n if (effect.type === "preprocess") {\n const processed = effect.transform(ctx.data, checkCtx);\n if (ctx.common.async) {\n return Promise.resolve(processed).then(async (processed2) => {\n if (status.value === "aborted")\n return INVALID;\n const result = await this._def.schema._parseAsync({\n data: processed2,\n path: ctx.path,\n parent: ctx\n });\n if (result.status === "aborted")\n return INVALID;\n if (result.status === "dirty")\n return DIRTY(result.value);\n if (status.value === "dirty")\n return DIRTY(result.value);\n return result;\n });\n } else {\n if (status.value === "aborted")\n return INVALID;\n const result = this._def.schema._parseSync({\n data: processed,\n path: ctx.path,\n parent: ctx\n });\n if (result.status === "aborted")\n return INVALID;\n if (result.status === "dirty")\n return DIRTY(result.value);\n if (status.value === "dirty")\n return DIRTY(result.value);\n return result;\n }\n }\n if (effect.type === "refinement") {\n const executeRefinement = (acc) => {\n const result = effect.refinement(acc, checkCtx);\n if (ctx.common.async) {\n return Promise.resolve(result);\n }\n if (result instanceof Promise) {\n throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");\n }\n return acc;\n };\n if (ctx.common.async === false) {\n const inner = this._def.schema._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx\n });\n if (inner.status === "aborted")\n return INVALID;\n if (inner.status === "dirty")\n status.dirty();\n executeRefinement(inner.value);\n return { status: status.value, value: inner.value };\n } else {\n return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => {\n if (inner.status === "aborted")\n return INVALID;\n if (inner.status === "dirty")\n status.dirty();\n return executeRefinement(inner.value).then(() => {\n return { status: status.value, value: inner.value };\n });\n });\n }\n }\n if (effect.type === "transform") {\n if (ctx.common.async === false) {\n const base = this._def.schema._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx\n });\n if (!isValid(base))\n return INVALID;\n const result = effect.transform(base.value, checkCtx);\n if (result instanceof Promise) {\n throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);\n }\n return { status: status.value, value: result };\n } else {\n return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => {\n if (!isValid(base))\n return INVALID;\n return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({\n status: status.value,\n value: result\n }));\n });\n }\n }\n util.assertNever(effect);\n }\n};\nZodEffects.create = (schema, effect, params) => {\n return new ZodEffects({\n schema,\n typeName: ZodFirstPartyTypeKind.ZodEffects,\n effect,\n ...processCreateParams(params)\n });\n};\nZodEffects.createWithPreprocess = (preprocess, schema, params) => {\n return new ZodEffects({\n schema,\n effect: { type: "preprocess", transform: preprocess },\n typeName: ZodFirstPartyTypeKind.ZodEffects,\n ...processCreateParams(params)\n });\n};\nvar ZodOptional = class extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType === ZodParsedType.undefined) {\n return OK(void 0);\n }\n return this._def.innerType._parse(input);\n }\n unwrap() {\n return this._def.innerType;\n }\n};\nZodOptional.create = (type, params) => {\n return new ZodOptional({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodOptional,\n ...processCreateParams(params)\n });\n};\nvar ZodNullable = class extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType === ZodParsedType.null) {\n return OK(null);\n }\n return this._def.innerType._parse(input);\n }\n unwrap() {\n return this._def.innerType;\n }\n};\nZodNullable.create = (type, params) => {\n return new ZodNullable({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodNullable,\n ...processCreateParams(params)\n });\n};\nvar ZodDefault = class extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n let data = ctx.data;\n if (ctx.parsedType === ZodParsedType.undefined) {\n data = this._def.defaultValue();\n }\n return this._def.innerType._parse({\n data,\n path: ctx.path,\n parent: ctx\n });\n }\n removeDefault() {\n return this._def.innerType;\n }\n};\nZodDefault.create = (type, params) => {\n return new ZodDefault({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodDefault,\n defaultValue: typeof params.default === "function" ? params.default : () => params.default,\n ...processCreateParams(params)\n });\n};\nvar ZodCatch = class extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n const newCtx = {\n ...ctx,\n common: {\n ...ctx.common,\n issues: []\n }\n };\n const result = this._def.innerType._parse({\n data: newCtx.data,\n path: newCtx.path,\n parent: {\n ...newCtx\n }\n });\n if (isAsync(result)) {\n return result.then((result2) => {\n return {\n status: "valid",\n value: result2.status === "valid" ? result2.value : this._def.catchValue({\n get error() {\n return new ZodError(newCtx.common.issues);\n },\n input: newCtx.data\n })\n };\n });\n } else {\n return {\n status: "valid",\n value: result.status === "valid" ? result.value : this._def.catchValue({\n get error() {\n return new ZodError(newCtx.common.issues);\n },\n input: newCtx.data\n })\n };\n }\n }\n removeCatch() {\n return this._def.innerType;\n }\n};\nZodCatch.create = (type, params) => {\n return new ZodCatch({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodCatch,\n catchValue: typeof params.catch === "function" ? params.catch : () => params.catch,\n ...processCreateParams(params)\n });\n};\nvar ZodNaN = class extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.nan) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.nan,\n received: ctx.parsedType\n });\n return INVALID;\n }\n return { status: "valid", value: input.data };\n }\n};\nZodNaN.create = (params) => {\n return new ZodNaN({\n typeName: ZodFirstPartyTypeKind.ZodNaN,\n ...processCreateParams(params)\n });\n};\nvar BRAND = /* @__PURE__ */ Symbol("zod_brand");\nvar ZodBranded = class extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n const data = ctx.data;\n return this._def.type._parse({\n data,\n path: ctx.path,\n parent: ctx\n });\n }\n unwrap() {\n return this._def.type;\n }\n};\nvar ZodPipeline = class _ZodPipeline extends ZodType {\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.common.async) {\n const handleAsync = async () => {\n const inResult = await this._def.in._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx\n });\n if (inResult.status === "aborted")\n return INVALID;\n if (inResult.status === "dirty") {\n status.dirty();\n return DIRTY(inResult.value);\n } else {\n return this._def.out._parseAsync({\n data: inResult.value,\n path: ctx.path,\n parent: ctx\n });\n }\n };\n return handleAsync();\n } else {\n const inResult = this._def.in._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx\n });\n if (inResult.status === "aborted")\n return INVALID;\n if (inResult.status === "dirty") {\n status.dirty();\n return {\n status: "dirty",\n value: inResult.value\n };\n } else {\n return this._def.out._parseSync({\n data: inResult.value,\n path: ctx.path,\n parent: ctx\n });\n }\n }\n }\n static create(a, b) {\n return new _ZodPipeline({\n in: a,\n out: b,\n typeName: ZodFirstPartyTypeKind.ZodPipeline\n });\n }\n};\nvar ZodReadonly = class extends ZodType {\n _parse(input) {\n const result = this._def.innerType._parse(input);\n const freeze = (data) => {\n if (isValid(data)) {\n data.value = Object.freeze(data.value);\n }\n return data;\n };\n return isAsync(result) ? result.then((data) => freeze(data)) : freeze(result);\n }\n unwrap() {\n return this._def.innerType;\n }\n};\nZodReadonly.create = (type, params) => {\n return new ZodReadonly({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodReadonly,\n ...processCreateParams(params)\n });\n};\nfunction cleanParams(params, data) {\n const p = typeof params === "function" ? params(data) : typeof params === "string" ? { message: params } : params;\n const p2 = typeof p === "string" ? { message: p } : p;\n return p2;\n}\nfunction custom(check, _params = {}, fatal) {\n if (check)\n return ZodAny.create().superRefine((data, ctx) => {\n const r = check(data);\n if (r instanceof Promise) {\n return r.then((r2) => {\n if (!r2) {\n const params = cleanParams(_params, data);\n const _fatal = params.fatal ?? fatal ?? true;\n ctx.addIssue({ code: "custom", ...params, fatal: _fatal });\n }\n });\n }\n if (!r) {\n const params = cleanParams(_params, data);\n const _fatal = params.fatal ?? fatal ?? true;\n ctx.addIssue({ code: "custom", ...params, fatal: _fatal });\n }\n return;\n });\n return ZodAny.create();\n}\nvar late = {\n object: ZodObject.lazycreate\n};\nvar ZodFirstPartyTypeKind;\n(function(ZodFirstPartyTypeKind2) {\n ZodFirstPartyTypeKind2["ZodString"] = "ZodString";\n ZodFirstPartyTypeKind2["ZodNumber"] = "ZodNumber";\n ZodFirstPartyTypeKind2["ZodNaN"] = "ZodNaN";\n ZodFirstPartyTypeKind2["ZodBigInt"] = "ZodBigInt";\n ZodFirstPartyTypeKind2["ZodBoolean"] = "ZodBoolean";\n ZodFirstPartyTypeKind2["ZodDate"] = "ZodDate";\n ZodFirstPartyTypeKind2["ZodSymbol"] = "ZodSymbol";\n ZodFirstPartyTypeKind2["ZodUndefined"] = "ZodUndefined";\n ZodFirstPartyTypeKind2["ZodNull"] = "ZodNull";\n ZodFirstPartyTypeKind2["ZodAny"] = "ZodAny";\n ZodFirstPartyTypeKind2["ZodUnknown"] = "ZodUnknown";\n ZodFirstPartyTypeKind2["ZodNever"] = "ZodNever";\n ZodFirstPartyTypeKind2["ZodVoid"] = "ZodVoid";\n ZodFirstPartyTypeKind2["ZodArray"] = "ZodArray";\n ZodFirstPartyTypeKind2["ZodObject"] = "ZodObject";\n ZodFirstPartyTypeKind2["ZodUnion"] = "ZodUnion";\n ZodFirstPartyTypeKind2["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion";\n ZodFirstPartyTypeKind2["ZodIntersection"] = "ZodIntersection";\n ZodFirstPartyTypeKind2["ZodTuple"] = "ZodTuple";\n ZodFirstPartyTypeKind2["ZodRecord"] = "ZodRecord";\n ZodFirstPartyTypeKind2["ZodMap"] = "ZodMap";\n ZodFirstPartyTypeKind2["ZodSet"] = "ZodSet";\n ZodFirstPartyTypeKind2["ZodFunction"] = "ZodFunction";\n ZodFirstPartyTypeKind2["ZodLazy"] = "ZodLazy";\n ZodFirstPartyTypeKind2["ZodLiteral"] = "ZodLiteral";\n ZodFirstPartyTypeKind2["ZodEnum"] = "ZodEnum";\n ZodFirstPartyTypeKind2["ZodEffects"] = "ZodEffects";\n ZodFirstPartyTypeKind2["ZodNativeEnum"] = "ZodNativeEnum";\n ZodFirstPartyTypeKind2["ZodOptional"] = "ZodOptional";\n ZodFirstPartyTypeKind2["ZodNullable"] = "ZodNullable";\n ZodFirstPartyTypeKind2["ZodDefault"] = "ZodDefault";\n ZodFirstPartyTypeKind2["ZodCatch"] = "ZodCatch";\n ZodFirstPartyTypeKind2["ZodPromise"] = "ZodPromise";\n ZodFirstPartyTypeKind2["ZodBranded"] = "ZodBranded";\n ZodFirstPartyTypeKind2["ZodPipeline"] = "ZodPipeline";\n ZodFirstPartyTypeKind2["ZodReadonly"] = "ZodReadonly";\n})(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));\nvar instanceOfType = (cls, params = {\n message: `Input not instance of ${cls.name}`\n}) => custom((data) => data instanceof cls, params);\nvar stringType = ZodString.create;\nvar numberType = ZodNumber.create;\nvar nanType = ZodNaN.create;\nvar bigIntType = ZodBigInt.create;\nvar booleanType = ZodBoolean.create;\nvar dateType = ZodDate.create;\nvar symbolType = ZodSymbol.create;\nvar undefinedType = ZodUndefined.create;\nvar nullType = ZodNull.create;\nvar anyType = ZodAny.create;\nvar unknownType = ZodUnknown.create;\nvar neverType = ZodNever.create;\nvar voidType = ZodVoid.create;\nvar arrayType = ZodArray.create;\nvar objectType = ZodObject.create;\nvar strictObjectType = ZodObject.strictCreate;\nvar unionType = ZodUnion.create;\nvar discriminatedUnionType = ZodDiscriminatedUnion.create;\nvar intersectionType = ZodIntersection.create;\nvar tupleType = ZodTuple.create;\nvar recordType = ZodRecord.create;\nvar mapType = ZodMap.create;\nvar setType = ZodSet.create;\nvar functionType = ZodFunction.create;\nvar lazyType = ZodLazy.create;\nvar literalType = ZodLiteral.create;\nvar enumType = ZodEnum.create;\nvar nativeEnumType = ZodNativeEnum.create;\nvar promiseType = ZodPromise.create;\nvar effectsType = ZodEffects.create;\nvar optionalType = ZodOptional.create;\nvar nullableType = ZodNullable.create;\nvar preprocessType = ZodEffects.createWithPreprocess;\nvar pipelineType = ZodPipeline.create;\nvar ostring = () => stringType().optional();\nvar onumber = () => numberType().optional();\nvar oboolean = () => booleanType().optional();\nvar coerce = {\n string: ((arg) => ZodString.create({ ...arg, coerce: true })),\n number: ((arg) => ZodNumber.create({ ...arg, coerce: true })),\n boolean: ((arg) => ZodBoolean.create({\n ...arg,\n coerce: true\n })),\n bigint: ((arg) => ZodBigInt.create({ ...arg, coerce: true })),\n date: ((arg) => ZodDate.create({ ...arg, coerce: true }))\n};\nvar NEVER = INVALID;\n\n// ../../packages/protocol/src/index.ts\nvar RequestBaseSchema = external_exports.object({\n id: external_exports.string().min(1)\n});\nvar ExecuteRequestSchema = RequestBaseSchema.extend({\n type: external_exports.literal("execute"),\n browser: external_exports.string().min(1).default("default"),\n script: external_exports.string(),\n headless: external_exports.boolean().optional(),\n ignoreHTTPSErrors: external_exports.boolean().optional(),\n connect: external_exports.string().min(1).optional(),\n timeoutMs: external_exports.number().int().positive().optional(),\n initScripts: external_exports.array(external_exports.string()).optional(),\n // Optional step label. When the target browser is a session context, the\n // daemon wraps the run in tracing.group(step)/groupEnd and screenshots the\n // active page to the session\'s screenshots/<step>.png after a successful run.\n step: external_exports.string().min(1).max(200).optional()\n});\nvar BrowsersRequestSchema = RequestBaseSchema.extend({\n type: external_exports.literal("browsers")\n});\nvar BrowserStopRequestSchema = RequestBaseSchema.extend({\n type: external_exports.literal("browser-stop"),\n browser: external_exports.string().min(1)\n});\nvar StatusRequestSchema = RequestBaseSchema.extend({\n type: external_exports.literal("status")\n});\nvar InstallRequestSchema = RequestBaseSchema.extend({\n type: external_exports.literal("install")\n});\nvar StopRequestSchema = RequestBaseSchema.extend({\n type: external_exports.literal("stop")\n});\nvar CaptureOptionsSchema = external_exports.object({\n trace: external_exports.boolean().default(true),\n video: external_exports.boolean().default(true),\n har: external_exports.boolean().default(true),\n console: external_exports.boolean().default(true)\n});\nvar SessionIdSchema = external_exports.string().min(1).max(128).regex(/^(?!.*\\.\\.)[A-Za-z0-9._-]+$/, "invalid session id");\nvar SessionStartRequestSchema = RequestBaseSchema.extend({\n type: external_exports.literal("session-start"),\n sessionId: SessionIdSchema,\n name: external_exports.string().min(1).max(200).optional(),\n headless: external_exports.boolean().optional(),\n ignoreHTTPSErrors: external_exports.boolean().optional(),\n capture: CaptureOptionsSchema.default({})\n});\nvar SessionEndRequestSchema = RequestBaseSchema.extend({\n type: external_exports.literal("session-end"),\n sessionId: SessionIdSchema,\n reason: external_exports.enum(["end", "abort"]).default("end")\n});\nvar SessionStatusRequestSchema = RequestBaseSchema.extend({\n type: external_exports.literal("session-status"),\n sessionId: SessionIdSchema\n});\nvar SessionListRequestSchema = RequestBaseSchema.extend({\n type: external_exports.literal("session-list")\n});\nvar RequestSchema = external_exports.discriminatedUnion("type", [\n ExecuteRequestSchema,\n BrowsersRequestSchema,\n BrowserStopRequestSchema,\n StatusRequestSchema,\n InstallRequestSchema,\n StopRequestSchema,\n SessionStartRequestSchema,\n SessionEndRequestSchema,\n SessionStatusRequestSchema,\n SessionListRequestSchema\n]);\nvar ResponseBaseSchema = external_exports.object({\n id: external_exports.string().min(1)\n});\nvar StdoutMessageSchema = ResponseBaseSchema.extend({\n type: external_exports.literal("stdout"),\n data: external_exports.string()\n});\nvar StderrMessageSchema = ResponseBaseSchema.extend({\n type: external_exports.literal("stderr"),\n data: external_exports.string()\n});\nvar CompleteMessageSchema = ResponseBaseSchema.extend({\n type: external_exports.literal("complete"),\n success: external_exports.literal(true)\n});\nvar ErrorMessageSchema = ResponseBaseSchema.extend({\n type: external_exports.literal("error"),\n message: external_exports.string()\n});\nvar ResultMessageSchema = ResponseBaseSchema.extend({\n type: external_exports.literal("result"),\n data: external_exports.unknown()\n});\nvar ResponseSchema = external_exports.discriminatedUnion("type", [\n StdoutMessageSchema,\n StderrMessageSchema,\n CompleteMessageSchema,\n ErrorMessageSchema,\n ResultMessageSchema\n]);\nfunction slugHash(value) {\n let hash = 5381;\n for (let i = 0; i < value.length; i += 1) {\n hash = (hash * 33 + value.charCodeAt(i)) % 2147483647;\n }\n return hash.toString(36);\n}\nfunction sessionStepSlug(step) {\n const base = step.replace(/[^A-Za-z0-9._-]/g, "-").replace(/^-+|-+$/g, "").slice(0, 200) || "step";\n return `${base}-${slugHash(step)}`;\n}\nvar SESSION_TRACE_FILE = "trace.zip";\nvar SESSION_HAR_FILE = "network.har";\nvar SESSION_CONSOLE_FILE = "console.log";\nvar SESSION_VIDEO_DIR = "video";\nvar SESSION_VIDEO_EXT = ".webm";\nvar SESSION_SCREENSHOTS_DIR = "screenshots";\nvar SESSION_SCREENSHOT_EXT = ".png";\nvar DAEMON_RUNTIME_DEPENDENCIES = {\n pino: "^9.5.0",\n playwright: "1.58.2",\n "playwright-core": "1.58.2",\n "quickjs-emscripten": "^0.32.0"\n};\nvar EMBEDDED_PACKAGE_JSON = JSON.stringify(\n {\n name: "canary-runtime",\n private: true,\n type: "module",\n dependencies: DAEMON_RUNTIME_DEPENDENCIES\n },\n null,\n 2\n);\nfunction describeZodError(error) {\n return error.issues.map((issue) => {\n const path7 = issue.path.length > 0 ? issue.path.join(".") : "request";\n return `${path7}: ${issue.message}`;\n }).join("; ");\n}\nfunction extractId(value) {\n if (!value || typeof value !== "object") {\n return;\n }\n const maybeId = value.id;\n return typeof maybeId === "string" && maybeId.length > 0 ? maybeId : void 0;\n}\nfunction parseRequest(line) {\n let parsed;\n try {\n parsed = JSON.parse(line);\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : "Invalid JSON request"\n };\n }\n const result = RequestSchema.safeParse(parsed);\n if (!result.success) {\n const id = extractId(parsed);\n return {\n success: false,\n error: describeZodError(result.error),\n ...id === void 0 ? {} : { id }\n };\n }\n return {\n success: true,\n request: result.data\n };\n}\nfunction serialize(message) {\n return `${JSON.stringify(ResponseSchema.parse(message))}\n`;\n}\n\n// src/browser-manager.ts\nimport { createHash } from "node:crypto";\nimport { mkdir, readFile } from "node:fs/promises";\nimport os from "node:os";\nimport path from "node:path";\nimport {\n chromium\n} from "playwright";\nvar DISCOVERY_PORTS = [9222, 9223, 9224, 9225, 9226, 9227, 9228, 9229];\nvar PROBE_TIMEOUT_MS = 750;\nvar MANUAL_CONNECT_TIMEOUT_MS = 5e3;\nvar PAGE_TITLE_TIMEOUT_MS = 1500;\nvar TARGET_ID_PATTERN = /^[a-f0-9]{16,}$/i;\nfunction isIgnorableFileError(error) {\n const code = error?.code;\n return code === "ENOENT" || code === "ENOTDIR" || code === "EACCES";\n}\nfunction isHttpEndpoint(endpoint) {\n return endpoint.startsWith("http://") || endpoint.startsWith("https://");\n}\nvar BrowserManager = class {\n browsers = /* @__PURE__ */ new Map();\n baseDir;\n dependencies;\n disconnectHandlers = /* @__PURE__ */ new Set();\n constructor(baseDir = path.join(os.homedir(), ".canary", "browsers"), dependencies = {}) {\n this.baseDir = baseDir;\n this.dependencies = {\n connectOverCDP: chromium.connectOverCDP.bind(\n chromium\n ),\n fetch: globalThis.fetch,\n homedir: os.homedir,\n launchPersistentContext: chromium.launchPersistentContext.bind(\n chromium\n ),\n mkdir,\n platform: process.platform,\n readFile,\n ...dependencies\n };\n }\n // Register a callback fired when a managed browser disconnects (crash or\n // external close). SessionManager uses this to reconcile a session whose\n // capture context died out from under it.\n onBrowserDisconnect(handler) {\n this.disconnectHandlers.add(handler);\n }\n async ensureBrowser(name, options = {}) {\n await this.ensureBaseDir();\n const existing = this.browsers.get(name);\n const requestedHeadless = options.headless ?? existing?.headless ?? false;\n const requestedIgnoreHTTPSErrors = options.ignoreHTTPSErrors ?? existing?.ignoreHTTPSErrors ?? false;\n if (existing) {\n if (existing.isSession) {\n return existing;\n }\n const needsRelaunch = existing.type !== "launched" || !existing.browser.isConnected() || options.headless !== void 0 && existing.headless !== requestedHeadless || options.ignoreHTTPSErrors !== void 0 && existing.ignoreHTTPSErrors !== requestedIgnoreHTTPSErrors;\n if (!needsRelaunch) {\n return existing;\n }\n await this.stopBrowser(name);\n }\n return this.launchBrowser(name, {\n headless: requestedHeadless,\n ignoreHTTPSErrors: requestedIgnoreHTTPSErrors\n });\n }\n async autoConnect(name) {\n await this.ensureBaseDir();\n const existing = this.browsers.get(name);\n if (existing?.type === "connected" && existing.browser.isConnected()) {\n return existing;\n }\n if (existing) {\n await this.stopBrowser(name);\n }\n const attemptedEndpoints = /* @__PURE__ */ new Set();\n let lastError;\n const tryEndpoint = async (endpoint) => {\n if (!endpoint || attemptedEndpoints.has(endpoint)) {\n return null;\n }\n attemptedEndpoints.add(endpoint);\n try {\n return await this.openConnectedBrowser(name, endpoint);\n } catch (error) {\n lastError = error;\n return null;\n }\n };\n const devToolsEndpoint = await this.readDevToolsActivePort();\n const devToolsBrowser = await tryEndpoint(devToolsEndpoint);\n if (devToolsBrowser) {\n return devToolsBrowser;\n }\n for (const port of DISCOVERY_PORTS) {\n const endpoint = await this.probePort(port);\n const connectedBrowser = await tryEndpoint(endpoint);\n if (connectedBrowser) {\n return connectedBrowser;\n }\n }\n throw new Error(this.buildAutoConnectError(lastError));\n }\n async connectBrowser(name, endpoint) {\n if (endpoint === "auto") {\n return this.autoConnect(name);\n }\n await this.ensureBaseDir();\n const resolvedEndpoint = await this.resolveEndpoint(endpoint);\n const existing = this.browsers.get(name);\n if (existing) {\n const isSameConnection = existing.type === "connected" && existing.endpoint === resolvedEndpoint && existing.browser.isConnected();\n if (isSameConnection) {\n return existing;\n }\n await this.stopBrowser(name);\n }\n return this.openConnectedBrowser(name, resolvedEndpoint);\n }\n getBrowser(name) {\n const entry = this.browsers.get(name);\n if (!entry?.browser.isConnected()) {\n return;\n }\n return entry;\n }\n async getPage(browserName, pageNameOrId) {\n const entry = this.getBrowserEntry(browserName);\n const existingPage = entry.pages.get(pageNameOrId);\n if (existingPage && !existingPage.isClosed()) {\n return existingPage;\n }\n entry.pages.delete(pageNameOrId);\n if (TARGET_ID_PATTERN.test(pageNameOrId)) {\n const page2 = await this.findPageByTargetId(entry, pageNameOrId);\n if (page2) {\n return page2;\n }\n }\n const page = this.takeInitialBlankPage(entry) ?? await entry.context.newPage();\n this.registerNamedPage(entry, pageNameOrId, page);\n return page;\n }\n newPage(browserName) {\n const entry = this.getBrowserEntry(browserName);\n const initial = this.takeInitialBlankPage(entry);\n return initial ? Promise.resolve(initial) : entry.context.newPage();\n }\n // Scripts dedupe by content (SHA-256). Already-applied scripts are no-ops, so\n // re-issuing the same set across consecutive `execute` requests is safe and\n // does not re-register the script on the context. Hashing is byte-exact:\n // editing a script file (even just whitespace) yields a new hash and a new\n // addInitScript call. Stop the browser to clear all applied scripts.\n async applyInitScripts(browserName, scripts) {\n if (scripts.length === 0) {\n return;\n }\n const entry = this.getBrowserEntry(browserName);\n for (const script of scripts) {\n const hash = createHash("sha256").update(script).digest("hex");\n if (entry.appliedInitScripts.has(hash)) {\n continue;\n }\n await entry.context.addInitScript({ content: script });\n entry.appliedInitScripts.add(hash);\n }\n }\n async listPages(browserName) {\n const entry = this.browsers.get(browserName);\n if (!entry?.browser.isConnected()) {\n return [];\n }\n this.pruneClosedPages(entry);\n const namesByPage = this.getNamedPagesByPage(entry);\n const summaries = [];\n for (const { context, page } of this.getContextPages(entry)) {\n const id = await this.getPageTargetId(context, page);\n if (!id) {\n continue;\n }\n let title = "";\n try {\n title = await this.getPageTitle(page);\n } catch (error) {\n if (page.isClosed()) {\n continue;\n }\n throw error;\n }\n summaries.push({\n id,\n url: page.url(),\n title,\n name: namesByPage.get(page) ?? null\n });\n }\n return summaries;\n }\n async closePage(browserName, pageName) {\n const entry = this.getBrowserEntry(browserName);\n const page = entry.pages.get(pageName);\n if (!page || page.isClosed()) {\n entry.pages.delete(pageName);\n throw new Error(`Page "${browserName}/${pageName}" not found`);\n }\n entry.pages.delete(pageName);\n if (!page.isClosed()) {\n await page.close();\n }\n }\n listBrowsers() {\n return Array.from(this.browsers.values()).filter((entry) => !entry.isSession).map((entry) => {\n this.pruneClosedPages(entry);\n const connected = entry.browser.isConnected();\n let status;\n if (entry.type === "connected") {\n status = connected ? "connected" : "disconnected";\n } else {\n status = connected ? "running" : "disconnected";\n }\n return {\n name: entry.name,\n type: entry.type,\n status,\n pages: this.listNamedPages(entry)\n };\n }).sort((left, right) => left.name.localeCompare(right.name));\n }\n async stopBrowser(name) {\n const entry = this.browsers.get(name);\n if (!entry) {\n return;\n }\n this.browsers.delete(name);\n entry.pages.clear();\n try {\n if (entry.type === "launched") {\n await this.closeLaunchedBrowser(entry);\n } else {\n await entry.browser.close();\n }\n } catch {\n }\n }\n async stopAll() {\n const names = Array.from(this.browsers.keys());\n await Promise.allSettled(names.map(async (name) => this.stopBrowser(name)));\n }\n browserCount() {\n let count = 0;\n for (const entry of this.browsers.values()) {\n if (!entry.isSession) {\n count += 1;\n }\n }\n return count;\n }\n async ensureBaseDir() {\n await this.dependencies.mkdir(this.baseDir, { recursive: true });\n }\n getBrowserEntry(name) {\n const entry = this.browsers.get(name);\n if (!entry?.browser.isConnected()) {\n throw new Error(`Browser "${name}" is not running`);\n }\n return entry;\n }\n // Launch a session-scoped capture context: a dedicated persistent context\n // (isolated profile) configured at launch time with recordVideo / recordHar.\n // The caller (SessionManager) then starts tracing and attaches listeners on\n // the returned entry\'s context.\n launchSessionBrowser(name, options) {\n return this.launchBrowser(name, { ...options, isSession: true });\n }\n // Best-effort screenshot of the most-recently-active page in a browser, used\n // to populate the report\'s per-step timeline. Silent if no page is open; the\n // caller must never let a screenshot failure fail the underlying step.\n async screenshotActivePage(browserName, outPath) {\n const entry = this.browsers.get(browserName);\n if (!entry?.browser.isConnected()) {\n return;\n }\n const pages = this.getContextPages(entry);\n const last = pages.at(-1);\n if (!last) {\n return;\n }\n await this.dependencies.mkdir(path.dirname(outPath), { recursive: true });\n await last.page.screenshot({ path: outPath });\n }\n async launchBrowser(name, options) {\n const profileDir = options.profileDirOverride ?? path.join(this.baseDir, name, "chromium-profile");\n await this.dependencies.mkdir(profileDir, { recursive: true });\n if (options.record?.videoDir) {\n await this.dependencies.mkdir(options.record.videoDir, {\n recursive: true\n });\n }\n const context = await this.dependencies.launchPersistentContext(\n profileDir,\n {\n headless: options.headless,\n viewport: options.headless ? void 0 : null,\n ignoreHTTPSErrors: options.ignoreHTTPSErrors,\n handleSIGINT: false,\n handleSIGTERM: false,\n handleSIGHUP: false,\n ...options.record?.videoDir ? { recordVideo: { dir: options.record.videoDir } } : {},\n ...options.record?.har ? {\n recordHar: {\n path: options.record.har.path,\n content: options.record.har.content\n }\n } : {}\n }\n );\n const browser = context.browser();\n if (!browser) {\n await context.close();\n throw new Error(\n `Playwright did not expose a browser handle for "${name}"`\n );\n }\n const entry = {\n name,\n type: "launched",\n browser,\n context,\n // A persistent context comes up with one about:blank page; reuse it for\n // the first page acquisition rather than orphaning it (see getPage).\n initialBlankPage: context.pages()[0],\n pages: /* @__PURE__ */ new Map(),\n profileDir,\n headless: options.headless,\n ignoreHTTPSErrors: options.ignoreHTTPSErrors,\n isSession: options.isSession ?? false,\n appliedInitScripts: /* @__PURE__ */ new Set()\n };\n this.attachBrowserLifecycle(entry);\n this.browsers.set(name, entry);\n return entry;\n }\n async openConnectedBrowser(name, endpoint) {\n const browser = await this.dependencies.connectOverCDP(endpoint);\n const contexts = browser.contexts();\n for (const browserContext of contexts) {\n browserContext.pages();\n }\n const context = contexts[0] ?? await browser.newContext();\n const entry = {\n name,\n type: "connected",\n browser,\n context,\n pages: /* @__PURE__ */ new Map(),\n endpoint,\n headless: false,\n ignoreHTTPSErrors: false,\n isSession: false,\n appliedInitScripts: /* @__PURE__ */ new Set()\n };\n this.attachBrowserLifecycle(entry);\n this.browsers.set(name, entry);\n return entry;\n }\n attachBrowserLifecycle(entry) {\n entry.browser.on("disconnected", () => {\n const current = this.browsers.get(entry.name);\n if (current !== entry) {\n return;\n }\n entry.pages.clear();\n if (entry.type === "launched") {\n this.browsers.delete(entry.name);\n }\n for (const handler of this.disconnectHandlers) {\n try {\n handler(entry.name);\n } catch {\n }\n }\n });\n }\n async closeLaunchedBrowser(entry) {\n const contexts = this.getBrowserContexts(entry);\n await Promise.allSettled(contexts.map(async (context) => context.close()));\n if (entry.browser.isConnected()) {\n await entry.browser.close().catch(() => void 0);\n }\n }\n async discoverChrome() {\n const devToolsEndpoint = await this.readDevToolsActivePort();\n if (devToolsEndpoint) {\n return devToolsEndpoint;\n }\n for (const port of DISCOVERY_PORTS) {\n const endpoint = await this.probePort(port);\n if (endpoint) {\n return endpoint;\n }\n }\n return null;\n }\n async readDevToolsActivePort(expectedPort) {\n for (const candidate of this.getDevToolsActivePortCandidates()) {\n let contents;\n try {\n contents = await this.dependencies.readFile(candidate, "utf8");\n } catch (error) {\n if (isIgnorableFileError(error)) {\n continue;\n }\n throw error;\n }\n const endpoint = this.parseDevToolsActivePort(contents, expectedPort);\n if (endpoint) {\n return endpoint;\n }\n }\n return null;\n }\n async probePort(port) {\n const endpoint = `http://127.0.0.1:${port}`;\n const result = await this.fetchDebuggerWebSocketUrl(\n endpoint,\n PROBE_TIMEOUT_MS\n );\n if (result.status === "ok") {\n return result.webSocketDebuggerUrl;\n }\n if (result.status === "not-found") {\n return this.readDevToolsActivePort(port);\n }\n return null;\n }\n getDevToolsActivePortCandidates() {\n const homeDir = this.dependencies.homedir();\n switch (this.dependencies.platform) {\n case "darwin":\n return [\n path.join(\n homeDir,\n "Library",\n "Application Support",\n "Google",\n "Chrome",\n "DevToolsActivePort"\n ),\n path.join(\n homeDir,\n "Library",\n "Application Support",\n "Google",\n "Chrome Canary",\n "DevToolsActivePort"\n ),\n path.join(\n homeDir,\n "Library",\n "Application Support",\n "Chromium",\n "DevToolsActivePort"\n ),\n path.join(\n homeDir,\n "Library",\n "Application Support",\n "BraveSoftware",\n "Brave-Browser",\n "DevToolsActivePort"\n )\n ];\n case "linux":\n return [\n path.join(homeDir, ".config", "google-chrome", "DevToolsActivePort"),\n path.join(homeDir, ".config", "chromium", "DevToolsActivePort"),\n path.join(\n homeDir,\n ".config",\n "google-chrome-beta",\n "DevToolsActivePort"\n ),\n path.join(\n homeDir,\n ".config",\n "google-chrome-unstable",\n "DevToolsActivePort"\n ),\n path.join(\n homeDir,\n ".config",\n "BraveSoftware",\n "Brave-Browser",\n "DevToolsActivePort"\n )\n ];\n case "win32":\n return [\n path.join(\n homeDir,\n "AppData",\n "Local",\n "Google",\n "Chrome",\n "User Data",\n "DevToolsActivePort"\n ),\n path.join(\n homeDir,\n "AppData",\n "Local",\n "Google",\n "Chrome Beta",\n "User Data",\n "DevToolsActivePort"\n ),\n path.join(\n homeDir,\n "AppData",\n "Local",\n "Google",\n "Chrome SxS",\n "User Data",\n "DevToolsActivePort"\n ),\n path.join(\n homeDir,\n "AppData",\n "Local",\n "Chromium",\n "User Data",\n "DevToolsActivePort"\n ),\n path.join(\n homeDir,\n "AppData",\n "Local",\n "BraveSoftware",\n "Brave-Browser",\n "User Data",\n "DevToolsActivePort"\n )\n ];\n default:\n return [];\n }\n }\n async resolveEndpoint(endpoint) {\n if (endpoint === "auto") {\n const discoveredEndpoint = await this.discoverChrome();\n if (discoveredEndpoint) {\n return discoveredEndpoint;\n }\n throw new Error(this.buildAutoConnectError());\n }\n if (isHttpEndpoint(endpoint)) {\n const discoveredEndpoint = await this.resolveHttpEndpoint(\n endpoint,\n MANUAL_CONNECT_TIMEOUT_MS\n );\n if (!discoveredEndpoint) {\n throw new Error(this.buildManualConnectError(endpoint));\n }\n return discoveredEndpoint;\n }\n return endpoint;\n }\n async fetchDebuggerWebSocketUrl(endpoint, timeoutMs) {\n let response;\n try {\n response = await this.dependencies.fetch(\n this.toJsonVersionUrl(endpoint),\n {\n headers: {\n accept: "application/json"\n },\n signal: AbortSignal.timeout(timeoutMs)\n }\n );\n } catch {\n return { status: "unavailable" };\n }\n if (response.status === 404) {\n return { status: "not-found" };\n }\n if (!response.ok) {\n return { status: "unavailable" };\n }\n let payload;\n try {\n payload = await response.json();\n } catch {\n return { status: "unavailable" };\n }\n const webSocketDebuggerUrl = typeof payload === "object" && payload !== null ? payload.webSocketDebuggerUrl : void 0;\n return typeof webSocketDebuggerUrl === "string" && webSocketDebuggerUrl.length > 0 ? {\n status: "ok",\n webSocketDebuggerUrl\n } : { status: "unavailable" };\n }\n toJsonVersionUrl(endpoint) {\n const url = new URL(endpoint);\n if (url.pathname !== "/json/version") {\n url.pathname = "/json/version";\n url.search = "";\n url.hash = "";\n }\n return url;\n }\n buildAutoConnectError(lastError) {\n let launchCommand = "google-chrome --remote-debugging-port=9222";\n if (this.dependencies.platform === "darwin") {\n launchCommand = "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome --remote-debugging-port=9222";\n } else if (this.dependencies.platform === "win32") {\n launchCommand = "chrome.exe --remote-debugging-port=9222";\n }\n const details = [\n "Could not auto-discover a running Chrome instance with remote debugging enabled.",\n "Enable Chrome remote debugging at chrome://inspect/#remote-debugging",\n `or launch Chrome with: ${launchCommand}`\n ];\n let lastErrorMessage = null;\n if (lastError instanceof Error) {\n lastErrorMessage = lastError.message;\n } else if (typeof lastError === "string" && lastError.length > 0) {\n lastErrorMessage = lastError;\n }\n if (lastErrorMessage) {\n details.push(`Last connection error: ${lastErrorMessage}`);\n }\n return details.join("\\n");\n }\n async resolveHttpEndpoint(endpoint, timeoutMs) {\n const result = await this.fetchDebuggerWebSocketUrl(endpoint, timeoutMs);\n if (result.status === "ok") {\n return result.webSocketDebuggerUrl;\n }\n if (result.status === "not-found") {\n const port = this.getEndpointPort(endpoint);\n if (port !== null) {\n return this.readDevToolsActivePort(port);\n }\n }\n return null;\n }\n parseDevToolsActivePort(contents, expectedPort) {\n const lines = contents.split(/\\r?\\n/).map((line) => line.trim()).filter((line) => line.length > 0);\n const port = Number.parseInt(lines[0] ?? "", 10);\n const webSocketPath = lines[1] ?? "";\n if (!Number.isInteger(port) || port < 1 || port > 65535) {\n return null;\n }\n if (expectedPort !== void 0 && port !== expectedPort) {\n return null;\n }\n if (!webSocketPath.startsWith("/devtools/browser/")) {\n return null;\n }\n return `ws://127.0.0.1:${port}${webSocketPath}`;\n }\n getEndpointPort(endpoint) {\n let url;\n try {\n url = new URL(endpoint);\n } catch {\n return null;\n }\n let defaultPort = "";\n if (url.protocol === "https:") {\n defaultPort = "443";\n } else if (url.protocol === "http:") {\n defaultPort = "80";\n }\n const rawPort = url.port || defaultPort;\n const port = Number.parseInt(rawPort, 10);\n return Number.isInteger(port) && port > 0 && port <= 65535 ? port : null;\n }\n buildManualConnectError(endpoint) {\n return [\n `Could not resolve a CDP WebSocket endpoint from ${endpoint}.`,\n "If Chrome is using built-in remote debugging, run `canary-browser --connect` without a URL so DevToolsActivePort can be auto-discovered.",\n "Or connect with the exact ws://127.0.0.1:<port>/devtools/browser/... URL from DevToolsActivePort, or launch Chrome with --remote-debugging-port=9222."\n ].join("\\n");\n }\n // Hand out the persistent context\'s initial about:blank page for the first\n // page acquisition, so a session reuses it instead of leaving an idle blank\n // tab that Playwright records as an empty video. Consumed at most once;\n // returns undefined once it has been taken, closed, or navigated away (e.g. a\n // prior target-id lookup), so callers fall back to opening a fresh tab.\n takeInitialBlankPage(entry) {\n const page = entry.initialBlankPage;\n entry.initialBlankPage = void 0;\n if (page && !page.isClosed() && page.url() === "about:blank") {\n return page;\n }\n return;\n }\n registerNamedPage(entry, pageName, page) {\n entry.pages.set(pageName, page);\n page.on("close", () => {\n const current = entry.pages.get(pageName);\n if (current === page) {\n entry.pages.delete(pageName);\n }\n });\n }\n pruneClosedPages(entry) {\n for (const [pageName, page] of entry.pages.entries()) {\n if (page.isClosed()) {\n entry.pages.delete(pageName);\n }\n }\n }\n listNamedPages(entry) {\n this.pruneClosedPages(entry);\n return Array.from(entry.pages.entries()).filter(([, page]) => !page.isClosed()).map(([name]) => name).sort((left, right) => left.localeCompare(right));\n }\n getNamedPagesByPage(entry) {\n const namesByPage = /* @__PURE__ */ new Map();\n for (const [name, page] of entry.pages.entries()) {\n if (!(page.isClosed() || namesByPage.has(page))) {\n namesByPage.set(page, name);\n }\n }\n return namesByPage;\n }\n getBrowserContexts(entry) {\n return [.../* @__PURE__ */ new Set([entry.context, ...entry.browser.contexts()])];\n }\n getContextPages(entry) {\n const pages = [];\n for (const context of this.getBrowserContexts(entry)) {\n for (const page of context.pages()) {\n if (!page.isClosed()) {\n pages.push({ context, page });\n }\n }\n }\n return pages;\n }\n async getPageTitle(page) {\n let timeoutId;\n try {\n return await Promise.race([\n page.title(),\n new Promise((resolve) => {\n timeoutId = setTimeout(() => resolve(""), PAGE_TITLE_TIMEOUT_MS);\n })\n ]);\n } finally {\n if (timeoutId !== void 0) {\n clearTimeout(timeoutId);\n }\n }\n }\n async findPageByTargetId(entry, targetId) {\n for (const { context, page } of this.getContextPages(entry)) {\n const pageTargetId = await this.getPageTargetId(context, page);\n if (pageTargetId === targetId) {\n return page;\n }\n }\n return null;\n }\n async getPageTargetId(context, page) {\n let session;\n try {\n session = await context.newCDPSession(page);\n const result = await session.send("Target.getTargetInfo");\n const targetId = typeof result === "object" && result !== null && "targetInfo" in result && typeof result.targetInfo === "object" && result.targetInfo !== null && "targetId" in result.targetInfo ? result.targetInfo.targetId : void 0;\n if (typeof targetId !== "string" || targetId.length === 0) {\n throw new Error("CDP target info did not include a targetId");\n }\n return targetId;\n } catch (error) {\n if (page.isClosed()) {\n return null;\n }\n throw error;\n } finally {\n await session?.detach().catch(() => void 0);\n }\n }\n};\n\n// src/local-endpoint.ts\nimport os2 from "node:os";\nimport path2 from "node:path";\nfunction sanitizePipeSegment(value) {\n const sanitized = value.replace(/[^A-Za-z0-9._-]/g, "-").replace(/^-+|-+$/g, "").toLowerCase();\n return sanitized.length > 0 ? sanitized : "user";\n}\nfunction getDefaultUsername(homedir) {\n const fromEnv = process.env.USERNAME || process.env.USER;\n if (typeof fromEnv === "string" && fromEnv.trim().length > 0) {\n return fromEnv;\n }\n try {\n const username = os2.userInfo().username;\n if (username.trim().length > 0) {\n return username;\n }\n } catch {\n }\n return path2.basename(homedir) || "user";\n}\nfunction getCanaryBaseDir(homedir = os2.homedir()) {\n return path2.join(homedir, ".canary");\n}\nfunction getDaemonEndpoint(options = {}) {\n const homedir = options.homedir ?? os2.homedir();\n const platform = options.platform ?? process.platform;\n if (platform === "win32") {\n const username = sanitizePipeSegment(\n options.username ?? getDefaultUsername(homedir)\n );\n return `\\\\\\\\.\\\\pipe\\\\canary-daemon-${username}`;\n }\n return path2.join(getCanaryBaseDir(homedir), "daemon.sock");\n}\nfunction getPidPath(homedir = os2.homedir()) {\n return path2.join(getCanaryBaseDir(homedir), "daemon.pid");\n}\nfunction getBrowsersDir(homedir = os2.homedir()) {\n return path2.join(getCanaryBaseDir(homedir), "browsers");\n}\nfunction getSessionsDir(homedir = os2.homedir()) {\n return path2.join(getCanaryBaseDir(homedir), "sessions");\n}\nfunction getSessionDir(sessionId, homedir = os2.homedir()) {\n return path2.join(getSessionsDir(homedir), sessionId);\n}\nfunction requiresDaemonEndpointCleanup(platform = process.platform) {\n return platform !== "win32";\n}\n\n// src/lock.ts\nfunction createKeyedLock() {\n const locks = /* @__PURE__ */ new Map();\n return async function withLock(key, action) {\n const previous = locks.get(key) ?? Promise.resolve();\n let release;\n const current = new Promise((resolve) => {\n release = resolve;\n });\n const tail = previous.catch(() => void 0).then(() => current);\n locks.set(key, tail);\n await previous.catch(() => void 0);\n try {\n return await action();\n } finally {\n release();\n if (locks.get(key) === tail) {\n locks.delete(key);\n }\n }\n };\n}\nfunction createMutex() {\n const withLock = createKeyedLock();\n const lockKey = /* @__PURE__ */ Symbol("mutex");\n return function withMutex(action) {\n return withLock(lockKey, action);\n };\n}\n\n// src/sandbox/quickjs-sandbox.ts\nimport { readFile as readFile2 } from "node:fs/promises";\nimport util2 from "node:util";\n\n// src/temp-files.ts\nimport { constants } from "node:fs";\nimport { lstat, mkdir as mkdir2, open } from "node:fs/promises";\nimport path3 from "node:path";\nvar SAFE_PATH_SEGMENT_PATTERN = /[^A-Za-z0-9._-]/g;\nvar NOFOLLOW_FLAG = constants.O_NOFOLLOW ?? 0;\nvar CANARY_BASE_DIR = getCanaryBaseDir();\nvar CANARY_TMP_DIR = path3.join(CANARY_BASE_DIR, "tmp");\nfunction requireNonEmptyString(value, label) {\n if (typeof value !== "string" || value.length === 0) {\n throw new TypeError(`${label} must be a non-empty string`);\n }\n return value;\n}\nfunction isWithinDirectory(rootDir, candidatePath) {\n if (candidatePath === rootDir) {\n return true;\n }\n const rootWithSeparator = rootDir.endsWith(path3.sep) ? rootDir : `${rootDir}${path3.sep}`;\n return candidatePath.startsWith(rootWithSeparator);\n}\nfunction sanitizePathSegment(segment) {\n if (segment.length === 0) {\n throw new Error("File paths must not contain empty path segments");\n }\n if (segment === "." || segment === ".." || segment.includes("..")) {\n throw new Error("File paths must not contain \'.\' or \'..\' segments");\n }\n const sanitized = segment.replace(SAFE_PATH_SEGMENT_PATTERN, "_");\n if (sanitized.length === 0 || sanitized === "." || sanitized === "..") {\n throw new Error("File paths must resolve to a valid filename");\n }\n return sanitized;\n}\nfunction sanitizeRelativePath(fileName) {\n const rawPath = requireNonEmptyString(fileName, "File name");\n if (rawPath.includes("\\0")) {\n throw new Error("File names must not contain null bytes");\n }\n if (path3.posix.isAbsolute(rawPath) || path3.win32.isAbsolute(rawPath)) {\n throw new Error("Absolute paths are not allowed");\n }\n const normalized = rawPath.replace(/\\\\/g, "/");\n if (normalized.startsWith("/")) {\n throw new Error("Absolute paths are not allowed");\n }\n return normalized.split("/").map(sanitizePathSegment);\n}\nasync function assertControlledDirectory(directoryPath, label) {\n const stats = await lstat(directoryPath);\n if (stats.isSymbolicLink()) {\n throw new Error(`${label} must not be a symlink`);\n }\n if (!stats.isDirectory()) {\n throw new Error(`${label} must be a directory`);\n }\n}\nasync function assertSafeParentDirectories(rootDir, destinationPath, createParents) {\n const relativeParent = path3.relative(rootDir, path3.dirname(destinationPath));\n if (relativeParent.length === 0) {\n return;\n }\n const segments = relativeParent.split(path3.sep).filter((segment) => segment.length > 0);\n let currentPath = rootDir;\n for (const segment of segments) {\n currentPath = path3.join(currentPath, segment);\n if (createParents) {\n await mkdir2(currentPath, {\n recursive: true\n });\n }\n try {\n const stats = await lstat(currentPath);\n if (stats.isSymbolicLink()) {\n throw new Error(\n `Temp path parent must not be a symlink: ${currentPath}`\n );\n }\n if (!stats.isDirectory()) {\n throw new Error(`Temp path parent must be a directory: ${currentPath}`);\n }\n } catch (error) {\n if (error.code === "ENOENT" && !createParents) {\n return;\n }\n throw error;\n }\n }\n}\nfunction normalizeSymlinkError(error, destinationPath) {\n if (error.code === "ELOOP") {\n return new Error(\n `Refusing to follow symlinked temp file: ${destinationPath}`\n );\n }\n return error instanceof Error ? error : new Error(String(error));\n}\nasync function assertDestinationIsNotSymlink(destinationPath) {\n try {\n const stats = await lstat(destinationPath);\n if (stats.isSymbolicLink()) {\n throw new Error(\n `Refusing to follow symlinked temp file: ${destinationPath}`\n );\n }\n } catch (error) {\n if (error.code === "ENOENT") {\n return;\n }\n throw error;\n }\n}\nasync function ensureCanaryTempDir() {\n await mkdir2(CANARY_BASE_DIR, {\n recursive: true\n });\n await assertControlledDirectory(\n CANARY_BASE_DIR,\n "Dev Browser base directory"\n );\n await mkdir2(CANARY_TMP_DIR, {\n recursive: true\n });\n await assertControlledDirectory(CANARY_TMP_DIR, "Dev Browser temp directory");\n return path3.resolve(CANARY_TMP_DIR);\n}\nasync function resolveCanaryTempPath(fileName, options = {}) {\n const rootDir = await ensureCanaryTempDir();\n const segments = sanitizeRelativePath(fileName);\n const destinationPath = path3.resolve(rootDir, ...segments);\n if (!isWithinDirectory(rootDir, destinationPath)) {\n throw new Error(\n "Resolved temp file path escapes the controlled temp directory"\n );\n }\n await assertSafeParentDirectories(\n rootDir,\n destinationPath,\n options.createParents ?? false\n );\n return destinationPath;\n}\nasync function writeCanaryTempFile(fileName, data) {\n const destinationPath = await resolveCanaryTempPath(fileName, {\n createParents: true\n });\n await assertDestinationIsNotSymlink(destinationPath);\n let handle;\n try {\n handle = await open(\n destinationPath,\n constants.O_WRONLY | constants.O_CREAT | constants.O_TRUNC | NOFOLLOW_FLAG,\n 384\n );\n await handle.writeFile(data);\n } catch (error) {\n throw normalizeSymlinkError(error, destinationPath);\n } finally {\n await handle?.close();\n }\n return destinationPath;\n}\nasync function readCanaryTempFile(fileName) {\n const destinationPath = await resolveCanaryTempPath(fileName);\n await assertDestinationIsNotSymlink(destinationPath);\n let handle;\n try {\n handle = await open(destinationPath, constants.O_RDONLY | NOFOLLOW_FLAG);\n return await handle.readFile({\n encoding: "utf8"\n });\n } catch (error) {\n throw normalizeSymlinkError(error, destinationPath);\n } finally {\n await handle?.close();\n }\n}\n\n// src/sandbox/playwright-internals.ts\nimport { existsSync } from "node:fs";\nimport { createRequire } from "node:module";\nimport path4 from "node:path";\nimport { fileURLToPath } from "node:url";\nvar require2 = createRequire(import.meta.url);\nvar currentDir = path4.dirname(fileURLToPath(import.meta.url));\nfunction resolvePlaywrightInternal(modulePath) {\n const candidates = [\n path4.resolve(currentDir, "../../node_modules/playwright-core", modulePath),\n path4.resolve(currentDir, "node_modules/playwright-core", modulePath),\n path4.resolve(process.cwd(), "node_modules/playwright-core", modulePath)\n ];\n for (const candidate of candidates) {\n if (existsSync(candidate)) {\n return candidate;\n }\n }\n throw new Error(`Could not locate Playwright internals at ${modulePath}`);\n}\nvar serverInternals = require2(\n resolvePlaywrightInternal(path4.join("lib", "server", "index.js"))\n);\nvar clientInternals = require2(\n resolvePlaywrightInternal(path4.join("lib", "client", "connection.js"))\n);\nvar nodePlatformInternals = require2(\n resolvePlaywrightInternal(\n path4.join("lib", "server", "utils", "nodePlatform.js")\n )\n);\nvar {\n createPlaywright,\n DispatcherConnection,\n RootDispatcher,\n PlaywrightDispatcher\n} = serverInternals;\nvar { Connection } = clientInternals;\nvar { nodePlatform } = nodePlatformInternals;\n\n// src/sandbox/host-bridge.ts\nvar WITHHELD_EVENTS = /* @__PURE__ */ new Set(["video"]);\nvar HostBridge = class {\n dispatcherConnection;\n rootDispatcher;\n playwright;\n sendToSandbox;\n options;\n playwrightDispatcher;\n disposed = false;\n constructor(options) {\n this.sendToSandbox = options.sendToSandbox;\n this.options = {\n preLaunchedBrowser: options.preLaunchedBrowser,\n sharedBrowser: options.sharedBrowser,\n denyLaunch: options.denyLaunch,\n sdkLanguage: options.sdkLanguage ?? "javascript"\n };\n this.playwright = createPlaywright({\n sdkLanguage: this.options.sdkLanguage ?? "javascript"\n });\n this.dispatcherConnection = new DispatcherConnection(false);\n this.dispatcherConnection.onmessage = (message) => {\n if (this.shouldWithhold(message)) {\n return;\n }\n this.sendToSandbox(JSON.stringify(message));\n };\n this.rootDispatcher = new RootDispatcher(\n this.dispatcherConnection,\n async (rootScope) => {\n this.playwrightDispatcher = new PlaywrightDispatcher(\n rootScope,\n this.playwright,\n {\n preLaunchedBrowser: this.options.preLaunchedBrowser,\n sharedBrowser: this.options.sharedBrowser,\n denyLaunch: this.options.denyLaunch\n }\n );\n return this.playwrightDispatcher;\n }\n );\n }\n // True when a host\u2192sandbox protocol message must be withheld because the\n // vendored sandbox client has no validator for it. Only the `video` event\n // qualifies; the daemon still records video on its own real context.\n shouldWithhold(message) {\n return message.method ? WITHHELD_EVENTS.has(message.method) : false;\n }\n async receiveFromSandbox(json) {\n await this.dispatcherConnection.dispatch(\n JSON.parse(json)\n );\n }\n async dispose() {\n if (this.disposed) {\n return;\n }\n this.disposed = true;\n this.dispatcherConnection.onmessage = () => {\n };\n try {\n await this.playwrightDispatcher?.cleanup();\n } finally {\n this.rootDispatcher._dispose();\n }\n }\n};\n\n// src/sandbox/quickjs-host.ts\nimport {\n getQuickJS\n} from "quickjs-emscripten";\nvar QuickJSHost = class _QuickJSHost {\n static async create(options = {}) {\n const quickjs = await getQuickJS();\n return new _QuickJSHost(quickjs, options);\n }\n #runtime;\n #context;\n #options;\n #timers = /* @__PURE__ */ new Map();\n #pendingDeferreds = /* @__PURE__ */ new Set();\n #disposed = false;\n #interruptDeadline;\n #nextTimerId = 1;\n constructor(quickjs, options) {\n this.#options = options;\n this.#runtime = quickjs.newRuntime();\n if (options.memoryLimitBytes !== void 0) {\n this.#runtime.setMemoryLimit(options.memoryLimitBytes);\n }\n if (options.maxStackSizeBytes !== void 0) {\n this.#runtime.setMaxStackSize(options.maxStackSizeBytes);\n }\n if (options.cpuTimeoutMs !== void 0) {\n this.#runtime.setInterruptHandler(\n () => this.#interruptDeadline !== void 0 && Date.now() > this.#interruptDeadline\n );\n }\n this.#context = this.#runtime.newContext();\n this.#installConsole();\n this.#installTimers();\n this.#installHostCall();\n this.#installTransportSend();\n for (const [name, value] of Object.entries(options.globals ?? {})) {\n this.setGlobal(name, value);\n }\n }\n get disposed() {\n return this.#disposed;\n }\n setGlobal(name, value) {\n this.#assertAlive();\n const valueHandle = this.#toHandle(value);\n try {\n this.#context.setProp(this.#context.global, name, valueHandle);\n } finally {\n valueHandle.dispose();\n }\n }\n executeScriptSync(code, options = {}) {\n const resultHandle = this.#evalCode(code, options);\n try {\n const promiseState = this.#context.getPromiseState(resultHandle);\n if (!(promiseState.type === "fulfilled" && promiseState.notAPromise)) {\n throw new Error(\n "QuickJS script returned a promise; use executeScript() instead"\n );\n }\n return this.#dumpHandle(resultHandle);\n } finally {\n resultHandle.dispose();\n }\n }\n async executeScript(code, options = {}) {\n const resultHandle = this.#evalCode(code, options);\n return this.#consumeHandle(resultHandle);\n }\n async callFunction(name, ...args) {\n this.#assertAlive();\n const functionHandle = this.#context.getProp(this.#context.global, name);\n const argHandles = args.map((value) => this.#toHandle(value));\n try {\n if (this.#context.typeof(functionHandle) !== "function") {\n throw new Error(`QuickJS global "${name}" is not a function`);\n }\n const result = this.#runWithCpuLimit(\n () => this.#context.callFunction(\n functionHandle,\n this.#context.global,\n ...argHandles\n )\n );\n const resultHandle = this.#unwrapResult(\n result,\n `QuickJS function "${name}" failed`\n );\n return await this.#consumeHandle(resultHandle);\n } finally {\n for (const argHandle of argHandles) {\n argHandle.dispose();\n }\n functionHandle.dispose();\n }\n }\n dispose() {\n if (this.#disposed) {\n return;\n }\n this.#disposed = true;\n for (const timerId of [...this.#timers.keys()]) {\n this.#clearTimer(timerId);\n }\n for (const deferred of [...this.#pendingDeferreds]) {\n deferred.dispose();\n this.#pendingDeferreds.delete(deferred);\n }\n this.#context.dispose();\n this.#runtime.dispose();\n }\n #installConsole() {\n const consoleObject = this.#context.newObject();\n try {\n for (const level of ["log", "warn", "error", "info"]) {\n const fn = this.#context.newFunction(level, (...args) => {\n const nativeArgs = args.map((arg) => this.#context.dump(arg));\n this.#options.onConsole?.(level, nativeArgs);\n });\n this.#context.setProp(consoleObject, level, fn);\n fn.dispose();\n }\n this.#context.setProp(this.#context.global, "console", consoleObject);\n } finally {\n consoleObject.dispose();\n }\n }\n #installHostCall() {\n const hostCall = this.#context.newFunction(\n "__hostCall",\n (nameHandle, argsJsonHandle) => {\n const name = this.#context.getString(nameHandle);\n const argsJson = this.#context.getString(argsJsonHandle);\n const args = this.#parseArgs(name, argsJson);\n const invoke = () => {\n if (this.#options.onHostCall) {\n return this.#options.onHostCall(name, args);\n }\n const handler = this.#options.hostFunctions?.[name];\n if (!handler) {\n throw new Error(`No host function registered for "${name}"`);\n }\n return handler(...args);\n };\n return this.#bridgeHostResult(invoke);\n }\n );\n this.#context.setProp(this.#context.global, "__hostCall", hostCall);\n hostCall.dispose();\n }\n #installTransportSend() {\n const transportSend = this.#context.newFunction(\n "__transport_send",\n (messageHandle) => {\n const message = this.#context.getString(messageHandle);\n return this.#bridgeHostResult(\n () => this.#options.onTransportSend?.(message)\n );\n }\n );\n this.#context.setProp(\n this.#context.global,\n "__transport_send",\n transportSend\n );\n transportSend.dispose();\n }\n #installTimers() {\n const setTimeoutHandle = this.#context.newFunction(\n "setTimeout",\n (callbackHandle, delayHandle, ...argHandles) => {\n if (this.#context.typeof(callbackHandle) !== "function") {\n throw new TypeError("setTimeout callback must be a function");\n }\n const timerId = this.#nextTimerId++;\n const delay = Math.max(0, this.#context.getNumber(delayHandle));\n const callback = callbackHandle.dup();\n const args = argHandles.map((arg) => arg.dup());\n const timeout = globalThis.setTimeout(() => {\n if (this.#disposed) {\n this.#clearTimer(timerId);\n return;\n }\n const record = this.#timers.get(timerId);\n if (!record) {\n return;\n }\n try {\n const result = this.#runWithCpuLimit(\n () => this.#context.callFunction(\n record.callback,\n this.#context.undefined,\n ...record.args\n )\n );\n if (result.error) {\n this.#emitConsoleError(this.#context.dump(result.error));\n result.error.dispose();\n } else {\n result.value.dispose();\n }\n this.#tryDrainPendingJobs();\n } finally {\n this.#clearTimer(timerId);\n }\n }, delay);\n this.#timers.set(timerId, { callback, args, timeout });\n return this.#context.newNumber(timerId);\n }\n );\n const clearTimeoutHandle = this.#context.newFunction(\n "clearTimeout",\n (timerIdHandle) => {\n this.#clearTimer(this.#context.getNumber(timerIdHandle));\n }\n );\n this.#context.setProp(this.#context.global, "setTimeout", setTimeoutHandle);\n this.#context.setProp(\n this.#context.global,\n "clearTimeout",\n clearTimeoutHandle\n );\n setTimeoutHandle.dispose();\n clearTimeoutHandle.dispose();\n }\n #clearTimer(timerId) {\n const record = this.#timers.get(timerId);\n if (!record) {\n return;\n }\n globalThis.clearTimeout(record.timeout);\n record.callback.dispose();\n for (const arg of record.args) {\n arg.dispose();\n }\n this.#timers.delete(timerId);\n }\n #bridgeHostResult(invoker) {\n try {\n const result = invoker();\n if (this.#isPromiseLike(result)) {\n return this.#createDeferredPromise(result);\n }\n if (result === void 0) {\n return;\n }\n return this.#toHandle(result);\n } catch (error) {\n throw this.#normalizeHostError(error);\n }\n }\n #createDeferredPromise(promise) {\n const deferred = this.#context.newPromise();\n this.#pendingDeferreds.add(deferred);\n promise.then((value) => {\n if (this.#disposed || !deferred.alive) {\n return;\n }\n const valueHandle = value === void 0 ? void 0 : this.#toHandle(value);\n try {\n deferred.resolve(valueHandle);\n } finally {\n valueHandle?.dispose();\n }\n }).catch((error) => {\n if (this.#disposed || !deferred.alive) {\n return;\n }\n const errorHandle = this.#newGuestErrorHandle(error);\n try {\n deferred.reject(errorHandle);\n } finally {\n errorHandle.dispose();\n }\n }).finally(() => {\n this.#pendingDeferreds.delete(deferred);\n this.#tryDrainPendingJobs();\n });\n return deferred.handle;\n }\n #evalCode(code, options) {\n this.#assertAlive();\n const result = this.#runWithCpuLimit(\n () => this.#context.evalCode(code, options.filename ?? "sandbox.js", {\n type: options.type\n })\n );\n return this.#unwrapResult(result, "QuickJS evaluation failed");\n }\n async #consumeHandle(handle) {\n try {\n const promiseState = this.#context.getPromiseState(handle);\n if (promiseState.type === "fulfilled" && promiseState.notAPromise) {\n return this.#dumpHandle(handle);\n }\n if (promiseState.type === "fulfilled") {\n try {\n return this.#dumpHandle(promiseState.value);\n } finally {\n promiseState.value.dispose();\n }\n }\n if (promiseState.type === "pending") {\n const resolved2 = await this.#awaitQuickJSPromise(handle);\n try {\n return this.#dumpHandle(resolved2);\n } finally {\n resolved2.dispose();\n }\n }\n if (promiseState.type === "rejected") {\n try {\n throw this.#toError("QuickJS promise rejected", promiseState.error);\n } finally {\n promiseState.error.dispose();\n }\n }\n const resolved = await this.#awaitQuickJSPromise(handle);\n try {\n return this.#dumpHandle(resolved);\n } finally {\n resolved.dispose();\n }\n } finally {\n handle.dispose();\n }\n }\n async #awaitQuickJSPromise(promiseHandle) {\n let settled = false;\n const nativePromise = this.#context.resolvePromise(promiseHandle).finally(() => {\n settled = true;\n });\n while (!settled) {\n this.#drainPendingJobs();\n if (settled) {\n break;\n }\n await this.#options.onDrain?.();\n this.#drainPendingJobs();\n if (settled) {\n break;\n }\n await new Promise((resolve) => {\n globalThis.setTimeout(resolve, 0);\n });\n }\n this.#drainPendingJobs();\n return this.#unwrapResult(await nativePromise, "QuickJS promise rejected");\n }\n #drainPendingJobs() {\n this.#assertAlive();\n while (true) {\n const jobResult = this.#runWithCpuLimit(\n () => this.#runtime.executePendingJobs()\n );\n if (jobResult.error) {\n const error = this.#toError(\n "QuickJS pending job failed",\n jobResult.error\n );\n jobResult.error.dispose();\n throw error;\n }\n if (jobResult.value === 0) {\n return;\n }\n }\n }\n #tryDrainPendingJobs() {\n if (this.#disposed) {\n return;\n }\n try {\n this.#drainPendingJobs();\n } catch (error) {\n this.#emitConsoleError(this.#normalizeHostError(error));\n }\n }\n #unwrapResult(result, prefix) {\n if (result.error) {\n const error = this.#toError(prefix, result.error);\n result.error.dispose();\n throw error;\n }\n return result.value;\n }\n #toHandle(value) {\n if (value === void 0) {\n return this.#context.undefined.dup();\n }\n if (value === null) {\n return this.#context.null.dup();\n }\n if (value === true) {\n return this.#context.true.dup();\n }\n if (value === false) {\n return this.#context.false.dup();\n }\n switch (typeof value) {\n case "number":\n return this.#context.newNumber(value);\n case "string":\n return this.#context.newString(value);\n case "bigint":\n return this.#context.newBigInt(value);\n case "object": {\n if (Array.isArray(value)) {\n const arrayHandle = this.#context.newArray();\n try {\n value.forEach((item, index) => {\n const itemHandle = this.#toHandle(item);\n try {\n this.#context.setProp(arrayHandle, index, itemHandle);\n } finally {\n itemHandle.dispose();\n }\n });\n return arrayHandle;\n } catch (error) {\n arrayHandle.dispose();\n throw error;\n }\n }\n const objectHandle = this.#context.newObject();\n try {\n for (const [key, item] of Object.entries(value)) {\n const itemHandle = this.#toHandle(item);\n try {\n this.#context.setProp(objectHandle, key, itemHandle);\n } finally {\n itemHandle.dispose();\n }\n }\n return objectHandle;\n } catch (error) {\n objectHandle.dispose();\n throw error;\n }\n }\n default:\n throw new TypeError(`Unsupported host value type: ${typeof value}`);\n }\n }\n #dumpHandle(handle) {\n return this.#context.dump(handle);\n }\n #parseArgs(name, argsJson) {\n try {\n const parsed = JSON.parse(argsJson);\n if (!Array.isArray(parsed)) {\n throw new Error("Expected a JSON array");\n }\n return parsed;\n } catch (error) {\n throw new Error(\n `Invalid JSON arguments for host call "${name}": ${this.#normalizeHostError(error).message}`\n );\n }\n }\n #newGuestErrorHandle(error) {\n const normalized = this.#normalizeHostError(error);\n const errorHandle = this.#context.newError({\n name: normalized.name || "Error",\n message: normalized.message\n });\n if (normalized.stack) {\n const stackHandle = this.#context.newString(normalized.stack);\n try {\n this.#context.setProp(errorHandle, "stack", stackHandle);\n } finally {\n stackHandle.dispose();\n }\n }\n return errorHandle;\n }\n #toError(prefix, errorHandle) {\n const dumped = this.#context.dump(errorHandle);\n const normalized = this.#normalizeHostError(dumped);\n normalized.message = `${prefix}: ${normalized.message}`;\n return normalized;\n }\n #emitConsoleError(error) {\n const normalized = this.#normalizeHostError(error);\n this.#options.onConsole?.("error", [\n {\n name: normalized.name,\n message: normalized.message,\n stack: normalized.stack\n }\n ]);\n }\n #normalizeHostError(error) {\n if (error instanceof Error) {\n return error;\n }\n if (typeof error === "object" && error !== null) {\n const name = "name" in error && typeof error.name === "string" ? error.name : "Error";\n const message = "message" in error && typeof error.message === "string" ? error.message : JSON.stringify(error);\n const normalized = new Error(message);\n normalized.name = name;\n if ("stack" in error && typeof error.stack === "string") {\n normalized.stack = error.stack;\n }\n return normalized;\n }\n return new Error(String(error));\n }\n #runWithCpuLimit(callback) {\n if (this.#options.cpuTimeoutMs === void 0) {\n return callback();\n }\n const previousDeadline = this.#interruptDeadline;\n this.#interruptDeadline = Date.now() + this.#options.cpuTimeoutMs;\n try {\n return callback();\n } finally {\n this.#interruptDeadline = previousDeadline;\n }\n }\n #assertAlive() {\n if (this.#disposed) {\n throw new Error("QuickJSHost has been disposed");\n }\n }\n #isPromiseLike(value) {\n return typeof value === "object" && value !== null && "then" in value;\n }\n};\n\n// src/sandbox/quickjs-sandbox.ts\nimport { existsSync as existsSync2 } from "node:fs";\nimport { fileURLToPath as fileURLToPath2 } from "node:url";\nvar DEFAULT_MEMORY_LIMIT_BYTES = 512 * 1024 * 1024;\nvar WAIT_FOR_OBJECT_ATTEMPTS = 1e3;\nfunction findBundlePath() {\n const candidates = [\n fileURLToPath2(new URL("./sandbox-client.js", import.meta.url)),\n fileURLToPath2(new URL("../../dist/sandbox-client.js", import.meta.url))\n ];\n for (const p of candidates) {\n if (existsSync2(p)) {\n return p;\n }\n }\n throw new Error(\n `Failed to find sandbox-client.js. Searched:\n${candidates.map((c) => ` - ${c}`).join("\\n")}`\n );\n}\nvar BUNDLE_PATH = findBundlePath();\nvar TRANSPORT_RECEIVE_GLOBAL = "__transport_receive";\nvar bundleCodePromise;\nfunction formatArgs(args) {\n return args.map(\n (arg) => typeof arg === "string" ? arg : util2.inspect(arg, {\n colors: false,\n depth: 6,\n compact: 3,\n breakLength: Number.POSITIVE_INFINITY\n })\n ).join(" ");\n}\nfunction normalizeError(error) {\n if (error instanceof Error) {\n return error;\n }\n return new Error(String(error));\n}\nfunction getSandboxClientBundleCode() {\n bundleCodePromise ??= readFile2(BUNDLE_PATH, "utf8").catch(\n (error) => {\n bundleCodePromise = void 0;\n const message = error instanceof Error ? error.message : "Sandbox client bundle could not be read";\n throw new Error(\n `Failed to load sandbox client bundle at ${BUNDLE_PATH}: ${message}`\n );\n }\n );\n return bundleCodePromise;\n}\nfunction formatTimeoutDuration(timeoutMs) {\n if (timeoutMs % 1e3 === 0) {\n return `${timeoutMs / 1e3}s`;\n }\n return `${timeoutMs}ms`;\n}\nfunction createScriptTimeoutError(timeoutMs) {\n const error = new Error(\n `Script timed out after ${formatTimeoutDuration(timeoutMs)} and was terminated.`\n );\n error.name = "ScriptTimeoutError";\n return error;\n}\nfunction createGuestScriptTimeoutErrorSource(timeoutMs) {\n const message = JSON.stringify(createScriptTimeoutError(timeoutMs).message);\n return `(() => {\n const error = new Error(${message});\n error.name = "ScriptTimeoutError";\n return error;\n })()`;\n}\nfunction wrapScriptWithWallClockTimeout(script, timeoutMs) {\n if (timeoutMs === void 0) {\n return script;\n }\n return `\n (() => {\n return new Promise((resolve, reject) => {\n const timeoutId = setTimeout(() => {\n reject(${createGuestScriptTimeoutErrorSource(timeoutMs)});\n }, ${timeoutMs});\n\n Promise.resolve()\n .then(() => (${script}))\n .then(resolve, reject)\n .finally(() => {\n clearTimeout(timeoutId);\n });\n });\n })()\n `;\n}\nfunction requireString(value, label) {\n if (typeof value !== "string" || value.length === 0) {\n throw new TypeError(`${label} must be a non-empty string`);\n }\n return value;\n}\nfunction toServerImpl(clientObject, label) {\n const connection = clientObject._connection;\n const toImpl = connection?.toImpl;\n if (typeof toImpl !== "function") {\n throw new Error(`${label} does not expose a server implementation`);\n }\n const impl = toImpl(clientObject);\n if (!impl) {\n throw new Error(`${label} could not be mapped to a server implementation`);\n }\n return impl;\n}\nfunction extractGuid(page) {\n const guid = toServerImpl(page, "Playwright page").guid;\n if (typeof guid !== "string" || guid.length === 0) {\n throw new Error("Playwright page did not expose a guid");\n }\n return guid;\n}\nfunction decodeSandboxFilePayload(value, label) {\n if (typeof value !== "object" || value === null) {\n throw new TypeError(`${label} must be an object`);\n }\n const encoding = "encoding" in value ? value.encoding : void 0;\n const data = "data" in value ? value.data : void 0;\n if (encoding !== "utf8" && encoding !== "base64" || typeof data !== "string") {\n throw new TypeError(\n `${label} must include a valid encoding and string data`\n );\n }\n if (encoding === "utf8") {\n return data;\n }\n return Buffer.from(data, "base64");\n}\nvar QuickJSSandbox = class {\n #options;\n #anonymousPages = /* @__PURE__ */ new Set();\n #pendingHostOperations = /* @__PURE__ */ new Set();\n #transportInbox = [];\n #asyncError;\n #host;\n #hostBridge;\n #flushPromise;\n #disposed = false;\n #initialized = false;\n constructor(options) {\n this.#options = options;\n }\n async initialize() {\n this.#assertAlive();\n if (this.#initialized) {\n return;\n }\n try {\n await ensureCanaryTempDir();\n this.#host = await QuickJSHost.create({\n memoryLimitBytes: this.#options.memoryLimitBytes ?? DEFAULT_MEMORY_LIMIT_BYTES,\n cpuTimeoutMs: this.#options.timeoutMs,\n hostFunctions: {\n getPage: (name) => this.#getPage(name),\n newPage: () => this.#newPage(),\n listPages: () => this.#options.manager.listPages(this.#options.browserName),\n closePage: (name) => this.#closePage(name),\n saveScreenshot: (name, data) => this.#writeTempFile(name, data),\n writeFile: (name, data) => this.#writeTempFile(name, data),\n readFile: (name) => this.#readTempFile(name)\n },\n onConsole: (level, args) => {\n this.#routeConsole(level, args);\n },\n onDrain: () => this.#drainAsyncOps(),\n onTransportSend: (message) => {\n this.#handleTransportSend(message);\n }\n });\n this.#host.executeScriptSync(\n `\n const __performanceOrigin = Date.now();\n const __base64Alphabet =\n "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";\n\n const __encodeBase64 = (bytes) => {\n let result = "";\n for (let index = 0; index < bytes.length; index += 3) {\n const chunk =\n (bytes[index] << 16) |\n ((bytes[index + 1] ?? 0) << 8) |\n (bytes[index + 2] ?? 0);\n result += __base64Alphabet[(chunk >> 18) & 63];\n result += __base64Alphabet[(chunk >> 12) & 63];\n result += index + 1 < bytes.length ? __base64Alphabet[(chunk >> 6) & 63] : "=";\n result += index + 2 < bytes.length ? __base64Alphabet[chunk & 63] : "=";\n }\n return result;\n };\n\n const __decodeBase64 = (base64) => {\n const normalized = String(base64).replace(/\\\\s+/g, "");\n const output = [];\n for (let index = 0; index < normalized.length; index += 4) {\n const a = __base64Alphabet.indexOf(normalized[index] ?? "A");\n const b = __base64Alphabet.indexOf(normalized[index + 1] ?? "A");\n const c =\n normalized[index + 2] === "="\n ? 64\n : __base64Alphabet.indexOf(normalized[index + 2] ?? "A");\n const d =\n normalized[index + 3] === "="\n ? 64\n : __base64Alphabet.indexOf(normalized[index + 3] ?? "A");\n const chunk = (a << 18) | (b << 12) | ((c & 63) << 6) | (d & 63);\n output.push((chunk >> 16) & 255);\n if (c !== 64) {\n output.push((chunk >> 8) & 255);\n }\n if (d !== 64) {\n output.push(chunk & 255);\n }\n }\n return new Uint8Array(output);\n };\n\n globalThis.URL ??= class URL {\n constructor(value, base) {\n this.href = base === undefined ? String(value) : String(base) + String(value);\n }\n\n toJSON() {\n return this.href;\n }\n\n toString() {\n return this.href;\n }\n };\n\n globalThis.Buffer ??= class Buffer extends Uint8Array {\n constructor(value, byteOffset, length) {\n if (typeof value === "number") {\n super(value);\n return;\n }\n if (value instanceof ArrayBuffer) {\n super(value, byteOffset, length);\n return;\n }\n if (ArrayBuffer.isView(value)) {\n super(value.buffer, value.byteOffset, value.byteLength);\n return;\n }\n super(value);\n }\n\n static from(value, encodingOrOffset, length) {\n if (typeof value === "string") {\n if (encodingOrOffset !== undefined && encodingOrOffset !== "base64") {\n throw new Error("QuickJS Buffer only supports base64 string input");\n }\n return new Buffer(__decodeBase64(value));\n }\n if (value instanceof ArrayBuffer) {\n return new Buffer(value, encodingOrOffset, length);\n }\n if (ArrayBuffer.isView(value)) {\n return new Buffer(\n value.buffer.slice(\n value.byteOffset,\n value.byteOffset + value.byteLength,\n ),\n );\n }\n if (Array.isArray(value)) {\n return new Buffer(value);\n }\n throw new TypeError("Unsupported Buffer.from input");\n }\n\n toString(encoding) {\n if (encoding === undefined || encoding === "utf8") {\n return Array.from(this)\n .map((value) => String.fromCharCode(value))\n .join("");\n }\n if (encoding === "base64") {\n return __encodeBase64(this);\n }\n throw new Error("QuickJS Buffer only supports utf8 and base64 output");\n }\n };\n\n globalThis.performance ??= {\n now: () => Date.now() - __performanceOrigin,\n timeOrigin: __performanceOrigin,\n };\n globalThis.global = globalThis;\n `,\n {\n filename: "quickjs-runtime.js"\n }\n );\n const bundleCode = await getSandboxClientBundleCode();\n const bundleFactorySource = JSON.stringify(\n `${bundleCode}\nreturn __PlaywrightClient;`\n );\n this.#host.executeScriptSync(\n `\n globalThis.__createPlaywrightClient = () => {\n return new Function(${bundleFactorySource})();\n };\n `,\n {\n filename: "sandbox-client.js"\n }\n );\n const browserEntry = this.#options.manager.getBrowser(\n this.#options.browserName\n );\n if (!browserEntry) {\n throw new Error(\n `Browser "${this.#options.browserName}" not found. It should have been created before script execution.`\n );\n }\n this.#hostBridge = new HostBridge({\n sendToSandbox: (json) => {\n this.#transportInbox.push(json);\n },\n preLaunchedBrowser: toServerImpl(\n browserEntry.browser,\n "Playwright browser"\n ),\n sharedBrowser: true,\n denyLaunch: true\n });\n await this.#host.executeScript(\n `\n (() => {\n const hostCall = globalThis.__hostCall;\n const transportSend = globalThis.__transport_send;\n const createPlaywrightClient = globalThis.__createPlaywrightClient;\n\n if (typeof hostCall !== "function") {\n throw new Error("Sandbox bridge did not expose a host-call function");\n }\n if (typeof transportSend !== "function") {\n throw new Error("Sandbox bridge did not expose a transport sender");\n }\n if (typeof createPlaywrightClient !== "function") {\n throw new Error("Sandbox client bundle did not expose a Playwright client factory");\n }\n\n if (!delete globalThis.__hostCall) {\n globalThis.__hostCall = undefined;\n }\n if (!delete globalThis.__transport_send) {\n globalThis.__transport_send = undefined;\n }\n if (!delete globalThis.__createPlaywrightClient) {\n globalThis.__createPlaywrightClient = undefined;\n }\n\n const playwrightClient = createPlaywrightClient();\n const connection = new playwrightClient.Connection(playwrightClient.quickjsPlatform);\n connection.onmessage = (message) => {\n transportSend(JSON.stringify(message));\n };\n\n Object.defineProperty(globalThis, "${TRANSPORT_RECEIVE_GLOBAL}", {\n value: (json) => {\n connection.dispatch(JSON.parse(json));\n },\n configurable: false,\n enumerable: false,\n writable: false,\n });\n\n const waitForConnectionObject = async (guid, label) => {\n if (typeof guid !== "string" || guid.length === 0) {\n throw new Error(\\`\\${label} did not return a valid guid\\`);\n }\n\n for (let attempt = 0; attempt < ${WAIT_FOR_OBJECT_ATTEMPTS}; attempt += 1) {\n const object = connection.getObjectWithKnownName(guid);\n if (object) {\n return object;\n }\n await new Promise((resolve) => setTimeout(resolve, 0));\n }\n\n throw new Error(\\`Timed out waiting for \\${label} (\\${guid}) in the sandbox\\`);\n };\n\n const encodeHostFilePayload = (value) => {\n if (typeof value === "string") {\n return { encoding: "utf8", data: value };\n }\n if (value instanceof ArrayBuffer || ArrayBuffer.isView(value)) {\n return { encoding: "base64", data: Buffer.from(value).toString("base64") };\n }\n throw new TypeError(\n "File data must be a string, Buffer, Uint8Array, or ArrayBuffer",\n );\n };\n\n return (async () => {\n await connection.initializePlaywright();\n\n const browserApi = Object.create(null);\n Object.defineProperties(browserApi, {\n getPage: {\n value: async (name) => {\n const guid = await hostCall("getPage", JSON.stringify([name]));\n return await waitForConnectionObject(guid, \\`page "\\${name}"\\`);\n },\n enumerable: true,\n },\n newPage: {\n value: async () => {\n const guid = await hostCall("newPage", JSON.stringify([]));\n return await waitForConnectionObject(guid, "anonymous page");\n },\n enumerable: true,\n },\n listPages: {\n value: async () => {\n return await hostCall("listPages", JSON.stringify([]));\n },\n enumerable: true,\n },\n closePage: {\n value: async (name) => {\n await hostCall("closePage", JSON.stringify([name]));\n },\n enumerable: true,\n },\n });\n Object.freeze(browserApi);\n\n Object.defineProperty(globalThis, "browser", {\n value: browserApi,\n configurable: false,\n enumerable: true,\n writable: false,\n });\n\n Object.defineProperties(globalThis, {\n saveScreenshot: {\n value: async (buffer, name) => {\n return await hostCall(\n "saveScreenshot",\n JSON.stringify([name, encodeHostFilePayload(buffer)]),\n );\n },\n configurable: false,\n enumerable: true,\n writable: false,\n },\n writeFile: {\n value: async (name, data) => {\n return await hostCall(\n "writeFile",\n JSON.stringify([name, encodeHostFilePayload(data)]),\n );\n },\n configurable: false,\n enumerable: true,\n writable: false,\n },\n readFile: {\n value: async (name) => {\n return await hostCall("readFile", JSON.stringify([name]));\n },\n configurable: false,\n enumerable: true,\n writable: false,\n },\n });\n })();\n })()\n `,\n {\n filename: "sandbox-init.js"\n }\n );\n await this.#flushTransportQueue();\n this.#throwIfAsyncError();\n this.#initialized = true;\n } catch (error) {\n await this.dispose();\n throw error;\n }\n }\n async executeScript(script) {\n this.#assertInitialized();\n let executionError;\n try {\n this.#throwIfAsyncError();\n await this.#host?.executeScript(\n wrapScriptWithWallClockTimeout(script, this.#options.timeoutMs),\n {\n filename: "user-script.js"\n }\n );\n await this.#flushTransportQueue();\n this.#throwIfAsyncError();\n } catch (error) {\n executionError = error;\n }\n try {\n await this.#cleanupAnonymousPages();\n } catch (error) {\n executionError ??= error;\n }\n if (executionError) {\n throw executionError;\n }\n }\n async dispose() {\n if (this.#disposed) {\n return;\n }\n this.#disposed = true;\n await this.#cleanupAnonymousPages({\n suppressErrors: true\n });\n this.#transportInbox.length = 0;\n this.#pendingHostOperations.clear();\n try {\n await this.#hostBridge?.dispose();\n } catch {\n } finally {\n this.#hostBridge = void 0;\n this.#host?.dispose();\n this.#host = void 0;\n this.#flushPromise = void 0;\n }\n }\n #routeConsole(level, args) {\n const line = `${formatArgs(args)}\n`;\n if (level === "warn" || level === "error") {\n this.#options.onStderr(line);\n return;\n }\n this.#options.onStdout(line);\n }\n #handleTransportSend(message) {\n if (!this.#hostBridge) {\n this.#asyncError ??= new Error("Sandbox transport is not initialized");\n return;\n }\n const operation = this.#hostBridge.receiveFromSandbox(message).catch((error) => {\n this.#asyncError ??= normalizeError(error);\n }).finally(() => {\n this.#pendingHostOperations.delete(operation);\n });\n this.#pendingHostOperations.add(operation);\n }\n async #drainAsyncOps() {\n this.#throwIfAsyncError();\n await this.#flushTransportQueue();\n this.#throwIfAsyncError();\n if (this.#pendingHostOperations.size === 0) {\n return;\n }\n await Promise.race(this.#pendingHostOperations);\n this.#throwIfAsyncError();\n await this.#flushTransportQueue();\n this.#throwIfAsyncError();\n }\n async #flushTransportQueue() {\n this.#throwIfAsyncError();\n if (!this.#host || this.#transportInbox.length === 0) {\n return;\n }\n if (this.#flushPromise) {\n await this.#flushPromise;\n return;\n }\n const flush = async () => {\n while (this.#transportInbox.length > 0) {\n const message = this.#transportInbox.shift();\n if (message === void 0) {\n continue;\n }\n await this.#host?.callFunction(TRANSPORT_RECEIVE_GLOBAL, message);\n this.#throwIfAsyncError();\n }\n };\n this.#flushPromise = flush().finally(() => {\n this.#flushPromise = void 0;\n });\n await this.#flushPromise;\n }\n async #getPage(name) {\n const page = await this.#options.manager.getPage(\n this.#options.browserName,\n requireString(name, "Page name or targetId")\n );\n return extractGuid(page);\n }\n async #newPage() {\n const page = await this.#options.manager.newPage(this.#options.browserName);\n this.#anonymousPages.add(page);\n page.on("close", () => {\n this.#anonymousPages.delete(page);\n });\n return extractGuid(page);\n }\n async #closePage(name) {\n await this.#options.manager.closePage(\n this.#options.browserName,\n requireString(name, "Page name")\n );\n }\n async #writeTempFile(name, payload) {\n return await writeCanaryTempFile(\n requireString(name, "File name"),\n decodeSandboxFilePayload(payload, "File data")\n );\n }\n async #readTempFile(name) {\n return await readCanaryTempFile(requireString(name, "File name"));\n }\n async #cleanupAnonymousPages(options = {}) {\n const anonymousPages = [...this.#anonymousPages];\n this.#anonymousPages.clear();\n for (const page of anonymousPages) {\n try {\n if (!page.isClosed()) {\n await page.close();\n }\n } catch (error) {\n if (!options.suppressErrors) {\n throw error;\n }\n }\n }\n if (options.suppressErrors) {\n try {\n await this.#flushTransportQueue();\n } catch {\n }\n return;\n }\n await this.#flushTransportQueue();\n this.#throwIfAsyncError();\n }\n #throwIfAsyncError() {\n if (this.#asyncError) {\n throw this.#asyncError;\n }\n }\n #assertAlive() {\n if (this.#disposed) {\n throw new Error("QuickJS sandbox has been disposed");\n }\n }\n #assertInitialized() {\n this.#assertAlive();\n if (!(this.#initialized && this.#host && this.#hostBridge)) {\n throw new Error("QuickJS sandbox has not been initialized");\n }\n }\n};\n\n// src/sandbox/script-runner-quickjs.ts\nasync function runScript(script, manager2, browserName, output, options = {}) {\n const sandbox = new QuickJSSandbox({\n manager: manager2,\n browserName,\n onStdout: output.onStdout,\n onStderr: output.onStderr,\n memoryLimitBytes: options.memoryLimitBytes,\n timeoutMs: options.timeout\n });\n try {\n await sandbox.initialize();\n await sandbox.executeScript(`(async () => {\n${script}\n})()`);\n } finally {\n await sandbox.dispose();\n }\n}\n\n// src/session-manager.ts\nimport { createWriteStream } from "node:fs";\nimport { mkdir as mkdir3, readdir, stat, writeFile } from "node:fs/promises";\nimport path5 from "node:path";\nvar SESSION_PREFIX = "__session__";\nvar TEARDOWN_TIMEOUT_MS = 5e3;\nfunction sessionBrowserName(sessionId) {\n return `${SESSION_PREFIX}${sessionId}`;\n}\nvar SessionManager = class {\n sessions = /* @__PURE__ */ new Map();\n manager;\n log;\n constructor(manager2, log2) {\n this.manager = manager2;\n this.log = log2;\n this.manager.onBrowserDisconnect(\n (name) => this.handleBrowserDisconnect(name)\n );\n }\n handleBrowserDisconnect(name) {\n const sessionId = this.sessionIdForBrowser(name);\n if (!sessionId) {\n return;\n }\n const state = this.sessions.get(sessionId);\n if (state?.phase !== "active") {\n return;\n }\n state.phase = "failed";\n state.endedAt = Date.now();\n this.sessions.delete(sessionId);\n for (const dispose of state.errorDisposers) {\n try {\n dispose();\n } catch {\n }\n }\n state.errorDisposers = [];\n void this.closeStream(state.consoleStream);\n state.consoleStream = void 0;\n this.log.warn({ sessionId }, "session browser disconnected unexpectedly");\n }\n isSessionBrowser(name) {\n return name.startsWith(SESSION_PREFIX);\n }\n sessionIdForBrowser(name) {\n return name.startsWith(SESSION_PREFIX) ? name.slice(SESSION_PREFIX.length) : void 0;\n }\n has(sessionId) {\n return this.sessions.has(sessionId);\n }\n status(sessionId) {\n const state = this.sessions.get(sessionId);\n return state ? this.summarize(state) : void 0;\n }\n list() {\n return Array.from(this.sessions.values()).map(\n (state) => this.summarize(state)\n );\n }\n noteRun(sessionId) {\n const state = this.sessions.get(sessionId);\n if (state) {\n state.runCount += 1;\n }\n }\n async start(req) {\n if (this.sessions.has(req.sessionId)) {\n throw new Error(`Session "${req.sessionId}" already exists`);\n }\n const artifactsDir = getSessionDir(req.sessionId);\n const profileDir = path5.join(artifactsDir, "profile");\n const videoDir = path5.join(artifactsDir, SESSION_VIDEO_DIR);\n const harPath = path5.join(artifactsDir, SESSION_HAR_FILE);\n const consolePath = path5.join(artifactsDir, SESSION_CONSOLE_FILE);\n await mkdir3(profileDir, { recursive: true });\n const entry = await this.manager.launchSessionBrowser(\n sessionBrowserName(req.sessionId),\n {\n headless: req.headless ?? false,\n ignoreHTTPSErrors: req.ignoreHTTPSErrors ?? false,\n profileDirOverride: profileDir,\n record: {\n videoDir: req.capture.video ? videoDir : void 0,\n har: req.capture.har ? { path: harPath, content: "embed" } : void 0\n }\n }\n );\n const state = {\n artifactsDir,\n capture: req.capture,\n consolePath,\n entry,\n errorDisposers: [],\n harPath,\n headless: req.headless ?? false,\n name: req.name,\n pageCount: 0,\n phase: "active",\n runCount: 0,\n sessionId: req.sessionId,\n startedAt: Date.now(),\n videoDir\n };\n try {\n if (req.capture.trace) {\n await entry.context.tracing.start({\n screenshots: true,\n snapshots: true,\n sources: true,\n title: req.name ?? req.sessionId\n });\n }\n if (req.capture.console) {\n this.attachConsole(state);\n }\n } catch (err) {\n await this.swallow(() => this.manager.stopBrowser(entry.name));\n throw err;\n }\n this.sessions.set(req.sessionId, state);\n this.log.info(\n { sessionId: req.sessionId, artifactsDir },\n "session started"\n );\n return this.summarize(state);\n }\n async beginStep(sessionId, step) {\n const state = this.sessions.get(sessionId);\n if (state?.capture.trace) {\n await state.entry.context.tracing.group(step).catch(() => void 0);\n }\n }\n async endStep(sessionId) {\n const state = this.sessions.get(sessionId);\n if (state?.capture.trace) {\n await state.entry.context.tracing.groupEnd().catch(() => void 0);\n }\n }\n // Strict teardown ordering: stop tracing (writes trace.zip) -> close context\n // (flushes *.webm + finalizes HAR) -> detach listeners + flush console stream\n // -> enumerate artifacts + write manifest.json -> drop the session browser.\n async end(sessionId, reason) {\n const state = this.sessions.get(sessionId);\n if (!state) {\n throw new Error(`Session "${sessionId}" not found`);\n }\n if (state.phase !== "active") {\n try {\n return await this.collect(state, reason);\n } finally {\n await this.swallow(() => this.manager.stopBrowser(state.entry.name));\n this.sessions.delete(sessionId);\n }\n }\n state.phase = "ending";\n const ctx = state.entry.context;\n if (state.entry.browser.isConnected()) {\n state.pageCount = ctx.pages().length;\n }\n if (state.capture.trace) {\n await this.swallow(\n () => ctx.tracing.stop({ path: path5.join(state.artifactsDir, "trace.zip") })\n );\n }\n await this.swallow(() => ctx.close());\n for (const dispose of state.errorDisposers) {\n try {\n dispose();\n } catch {\n }\n }\n state.errorDisposers = [];\n await this.closeStream(state.consoleStream);\n state.consoleStream = void 0;\n state.phase = reason === "abort" ? "aborted" : "ended";\n state.endedAt = Date.now();\n try {\n const result = await this.collect(state, reason);\n this.log.info({ sessionId, reason }, "session ended");\n return result;\n } finally {\n await this.swallow(() => this.manager.stopBrowser(state.entry.name));\n this.sessions.delete(sessionId);\n }\n }\n async endAll() {\n for (const sessionId of Array.from(this.sessions.keys())) {\n await this.best(() => this.end(sessionId, "abort"));\n }\n }\n attachConsole(state) {\n const stream = createWriteStream(state.consolePath, { flags: "a" });\n stream.on("error", (err) => {\n this.log.debug(\n { err, sessionId: state.sessionId },\n "console log stream error"\n );\n });\n state.consoleStream = stream;\n const ctx = state.entry.context;\n const write = (record) => {\n if (!stream.destroyed) {\n stream.write(`${JSON.stringify(record)}\n`);\n }\n };\n const onConsole = (msg) => {\n const loc = msg.location();\n write({\n ts: Date.now(),\n kind: "console",\n type: msg.type(),\n text: msg.text(),\n url: loc.url,\n line: loc.lineNumber,\n col: loc.columnNumber,\n page: this.namePage(state, msg.page())\n });\n };\n ctx.on("console", onConsole);\n state.errorDisposers.push(() => ctx.off("console", onConsole));\n const onWebError = (webError) => {\n const err = webError.error();\n write({\n ts: Date.now(),\n kind: "pageerror",\n message: err?.message ?? String(err),\n stack: err?.stack,\n page: this.namePage(state, webError.page())\n });\n };\n ctx.on("weberror", onWebError);\n state.errorDisposers.push(() => ctx.off("weberror", onWebError));\n }\n namePage(state, page) {\n if (!page) {\n return;\n }\n for (const [name, candidate] of state.entry.pages) {\n if (candidate === page) {\n return name;\n }\n }\n return;\n }\n async collect(state, reason) {\n const artifacts = [];\n const add = async (kind, filePath) => {\n try {\n const info = await stat(filePath);\n if (info.isFile()) {\n artifacts.push({ kind, path: filePath, bytes: info.size });\n }\n } catch {\n }\n };\n if (state.capture.trace) {\n await add("trace", path5.join(state.artifactsDir, SESSION_TRACE_FILE));\n }\n if (state.capture.har) {\n await add("har", state.harPath);\n }\n if (state.capture.console) {\n await add("console", state.consolePath);\n }\n if (state.capture.video) {\n const files = await readdir(state.videoDir).catch(() => []);\n for (const file of files) {\n if (file.endsWith(SESSION_VIDEO_EXT)) {\n await add("video", path5.join(state.videoDir, file));\n }\n }\n }\n const screenshotsDir = path5.join(\n state.artifactsDir,\n SESSION_SCREENSHOTS_DIR\n );\n const shots = await readdir(screenshotsDir).catch(() => []);\n for (const file of shots) {\n if (file.endsWith(SESSION_SCREENSHOT_EXT)) {\n await add("screenshot", path5.join(screenshotsDir, file));\n }\n }\n const session = this.summarize(state);\n const manifestPath = path5.join(state.artifactsDir, "manifest.json");\n await writeFile(\n manifestPath,\n JSON.stringify({ session, artifacts, reason }, null, 2)\n );\n return { session, artifacts, manifestPath };\n }\n summarize(state) {\n const pageCount = state.entry.browser.isConnected() ? state.entry.context.pages().length : state.pageCount;\n return {\n artifactsDir: state.artifactsDir,\n browser: state.entry.name,\n capture: state.capture,\n endedAt: state.endedAt,\n headless: state.headless,\n name: state.name,\n pageCount,\n phase: state.phase,\n runCount: state.runCount,\n sessionId: state.sessionId,\n startedAt: state.startedAt\n };\n }\n // Await a teardown step to completion, logging (not throwing) on failure.\n // Used by end() so artifacts are fully flushed before enumeration.\n async swallow(fn) {\n try {\n await fn();\n } catch (err) {\n this.log.debug({ err }, "session teardown step failed");\n }\n }\n // Like swallow(), but bounded by a timeout so a wedged context.close() can\'t\n // stall daemon shutdown. Used only by endAll(); the losing promise\'s eventual\n // rejection is consumed by Promise.race, so it never becomes unhandled.\n async best(fn) {\n try {\n await Promise.race([\n fn(),\n new Promise((resolve) => {\n const timer = setTimeout(resolve, TEARDOWN_TIMEOUT_MS);\n timer.unref();\n })\n ]);\n } catch (err) {\n this.log.debug({ err }, "session teardown step failed");\n }\n }\n closeStream(stream) {\n if (!stream) {\n return Promise.resolve();\n }\n return new Promise((resolve) => {\n stream.end(() => resolve());\n });\n }\n};\n\n// src/daemon.ts\nvar BASE_DIR = getCanaryBaseDir();\nvar SOCKET_PATH = getDaemonEndpoint();\nvar PID_PATH = getPidPath();\nvar BROWSERS_DIR = getBrowsersDir();\nvar DEFAULT_SCRIPT_TIMEOUT_MS = 3e4;\nvar SOCKET_CLOSE_TIMEOUT_MS = 500;\nvar LOG_PATH = path6.join(BASE_DIR, "daemon.log");\nvar log = createLogger({\n name: "daemon",\n destination: LOG_PATH,\n fallbackLevel: "info",\n // Synchronous writes so error/shutdown records flush before process.exit().\n sync: true\n});\nvar manager = new BrowserManager(BROWSERS_DIR);\nvar sessions = new SessionManager(manager, log);\nvar startedAt = Date.now();\nvar withBrowserLock = createKeyedLock();\nvar withInstallLock = createMutex();\nvar clients = /* @__PURE__ */ new Set();\nvar server = null;\nvar shuttingDown = null;\nfunction formatError(error) {\n if (error instanceof Error) {\n if (error.name === "ScriptTimeoutError") {\n return error.message;\n }\n return error.stack ?? error.message;\n }\n return String(error);\n}\nasync function writeMessage(socket, message) {\n if (socket.destroyed) {\n return;\n }\n await new Promise((resolve, reject) => {\n const payload = serialize(message);\n socket.write(payload, (error) => {\n if (error) {\n reject(error);\n return;\n }\n resolve();\n });\n });\n}\nasync function unlinkIfExists(filePath) {\n try {\n await unlink(filePath);\n } catch (error) {\n if (error.code !== "ENOENT") {\n throw error;\n }\n }\n}\nasync function closeServerInstance(serverToClose) {\n await new Promise((resolve) => {\n serverToClose.close(() => {\n resolve();\n });\n });\n}\nasync function closeClientSocket(socket) {\n if (socket.destroyed) {\n return;\n }\n await new Promise((resolve) => {\n const timeout = setTimeout(() => {\n if (!socket.destroyed) {\n socket.destroy();\n }\n }, SOCKET_CLOSE_TIMEOUT_MS);\n timeout.unref();\n const finish = () => {\n clearTimeout(timeout);\n resolve();\n };\n socket.once("close", finish);\n socket.once("error", finish);\n socket.end();\n });\n}\nfunction createMessageQueue(socket) {\n let queue = Promise.resolve();\n return {\n push(message) {\n queue = queue.then(() => writeMessage(socket, message)).catch(() => void 0);\n return queue;\n },\n async drain() {\n await queue;\n }\n };\n}\nasync function captureStepScreenshot(browser, sessionId, step) {\n try {\n const shotPath = path6.join(\n getSessionDir(sessionId),\n "screenshots",\n `${sessionStepSlug(step)}.png`\n );\n await manager.screenshotActivePage(browser, shotPath);\n } catch (error) {\n log.debug({ err: error, sessionId, step }, "step screenshot failed");\n }\n}\nasync function resolveExecuteBrowser(socket, request, targetSession) {\n if (targetSession) {\n if (!sessions.has(targetSession)) {\n await writeMessage(socket, {\n id: request.id,\n type: "error",\n message: `No active session "${targetSession}". Start one with \\`canary session start\\`.`\n });\n return false;\n }\n if (request.connect) {\n await writeMessage(socket, {\n id: request.id,\n type: "error",\n message: `Session "${targetSession}" manages its own browser; \\`connect\\` is not allowed for a session run.`\n });\n return false;\n }\n await manager.ensureBrowser(request.browser, {\n headless: request.headless,\n ignoreHTTPSErrors: request.ignoreHTTPSErrors\n });\n return true;\n }\n if (request.connect === "auto") {\n await manager.autoConnect(request.browser);\n } else if (request.connect) {\n await manager.connectBrowser(request.browser, request.connect);\n } else {\n await manager.ensureBrowser(request.browser, {\n headless: request.headless,\n ignoreHTTPSErrors: request.ignoreHTTPSErrors\n });\n }\n return true;\n}\nasync function handleExecute(socket, request) {\n const targetSession = sessions.sessionIdForBrowser(request.browser);\n if (targetSession && !sessions.has(targetSession)) {\n await writeMessage(socket, {\n id: request.id,\n type: "error",\n message: `No active session "${targetSession}". Start one with \\`canary session start\\`.`\n });\n return;\n }\n await withBrowserLock(request.browser, async () => {\n if (!await resolveExecuteBrowser(socket, request, targetSession)) {\n return;\n }\n const output = createMessageQueue(socket);\n const timeoutMs = request.timeoutMs ?? DEFAULT_SCRIPT_TIMEOUT_MS;\n if (targetSession && request.step) {\n await sessions.beginStep(targetSession, request.step);\n }\n try {\n if (request.initScripts && request.initScripts.length > 0) {\n await manager.applyInitScripts(request.browser, request.initScripts);\n }\n await runScript(\n request.script,\n manager,\n request.browser,\n {\n onStdout: (data) => {\n void output.push({\n id: request.id,\n type: "stdout",\n data\n });\n },\n onStderr: (data) => {\n void output.push({\n id: request.id,\n type: "stderr",\n data\n });\n }\n },\n {\n timeout: timeoutMs\n }\n );\n await output.drain();\n await writeMessage(socket, {\n id: request.id,\n type: "complete",\n success: true\n });\n } catch (error) {\n await output.drain().catch(() => void 0);\n await writeMessage(socket, {\n id: request.id,\n type: "error",\n message: formatError(error)\n });\n } finally {\n if (targetSession && request.step) {\n await captureStepScreenshot(\n request.browser,\n targetSession,\n request.step\n );\n await sessions.endStep(targetSession);\n }\n if (targetSession) {\n sessions.noteRun(targetSession);\n }\n }\n });\n}\nasync function handleInstall(socket, request) {\n await withInstallLock(async () => {\n const output = createMessageQueue(socket);\n try {\n await mkdir4(BASE_DIR, { recursive: true });\n await writeFile2(\n path6.join(BASE_DIR, "package.json"),\n EMBEDDED_PACKAGE_JSON\n );\n const npmProgram = process.platform === "win32" ? "npm.cmd" : "npm";\n await runInstallCommand(\n output,\n request.id,\n npmProgram,\n ["install"],\n BASE_DIR,\n "npm install"\n );\n await runInstallCommand(\n output,\n request.id,\n npmProgram,\n ["exec", "--", "playwright", "install", "chromium"],\n BASE_DIR,\n "Playwright install"\n );\n await writeMessage(socket, {\n id: request.id,\n type: "complete",\n success: true\n });\n } catch (error) {\n await output.drain().catch(() => void 0);\n await writeMessage(socket, {\n id: request.id,\n type: "error",\n message: formatError(error)\n });\n }\n });\n}\nasync function runInstallCommand(output, requestId, program, args, cwd, label) {\n const child = spawn(program, args, {\n cwd,\n env: process.env,\n stdio: ["ignore", "pipe", "pipe"]\n });\n child.stdout?.setEncoding("utf8");\n child.stdout?.on("data", (data) => {\n void output.push({\n id: requestId,\n type: "stdout",\n data\n });\n });\n child.stderr?.setEncoding("utf8");\n child.stderr?.on("data", (data) => {\n void output.push({\n id: requestId,\n type: "stderr",\n data\n });\n });\n const result = await new Promise((resolve, reject) => {\n child.once("error", reject);\n child.once("close", (code, signal) => {\n resolve({ code, signal });\n });\n });\n await output.drain();\n if (result.code === 0) {\n return;\n }\n const reason = result.signal === null ? `${label} failed with exit code ${result.code ?? "unknown"}` : `${label} terminated by signal ${result.signal}`;\n throw new Error(reason);\n}\nasync function handleRequest(socket, line) {\n const parsed = parseRequest(line);\n if (!parsed.success) {\n await writeMessage(socket, {\n id: parsed.id ?? "unknown",\n type: "error",\n message: parsed.error\n });\n return;\n }\n const { request } = parsed;\n log.debug({ id: request.id, type: request.type }, "handling request");\n if (shuttingDown && request.type !== "stop") {\n await writeMessage(socket, {\n id: request.id,\n type: "error",\n message: "Daemon is shutting down"\n });\n return;\n }\n switch (request.type) {\n case "execute":\n await handleExecute(socket, request);\n return;\n case "browsers":\n await writeMessage(socket, {\n id: request.id,\n type: "result",\n data: manager.listBrowsers()\n });\n await writeMessage(socket, {\n id: request.id,\n type: "complete",\n success: true\n });\n return;\n case "browser-stop":\n if (sessions.isSessionBrowser(request.browser)) {\n await writeMessage(socket, {\n id: request.id,\n type: "error",\n message: `"${request.browser}" is a session browser; tear it down with \\`canary session end\\` or \\`canary session abort\\`.`\n });\n return;\n }\n await manager.stopBrowser(request.browser);\n log.info({ browser: request.browser }, "browser stopped");\n await writeMessage(socket, {\n id: request.id,\n type: "result",\n data: { browser: request.browser, stopped: true }\n });\n await writeMessage(socket, {\n id: request.id,\n type: "complete",\n success: true\n });\n return;\n case "status":\n await writeMessage(socket, {\n id: request.id,\n type: "result",\n data: {\n pid: process.pid,\n uptimeMs: Date.now() - startedAt,\n browserCount: manager.browserCount(),\n browsers: manager.listBrowsers(),\n socketPath: SOCKET_PATH\n }\n });\n await writeMessage(socket, {\n id: request.id,\n type: "complete",\n success: true\n });\n return;\n case "install":\n await handleInstall(socket, request);\n return;\n case "stop":\n await writeMessage(socket, {\n id: request.id,\n type: "result",\n data: { stopping: true }\n });\n await writeMessage(socket, {\n id: request.id,\n type: "complete",\n success: true\n });\n void shutdown(0);\n return;\n case "session-start":\n await withBrowserLock(sessionBrowserName(request.sessionId), async () => {\n try {\n const session = await sessions.start(request);\n await writeMessage(socket, {\n id: request.id,\n type: "result",\n data: { session }\n });\n await writeMessage(socket, {\n id: request.id,\n type: "complete",\n success: true\n });\n } catch (error) {\n await writeMessage(socket, {\n id: request.id,\n type: "error",\n message: formatError(error)\n });\n }\n });\n return;\n case "session-end":\n await withBrowserLock(sessionBrowserName(request.sessionId), async () => {\n try {\n const result = await sessions.end(request.sessionId, request.reason);\n await writeMessage(socket, {\n id: request.id,\n type: "result",\n data: result\n });\n await writeMessage(socket, {\n id: request.id,\n type: "complete",\n success: true\n });\n } catch (error) {\n await writeMessage(socket, {\n id: request.id,\n type: "error",\n message: formatError(error)\n });\n }\n });\n return;\n case "session-status": {\n const session = sessions.status(request.sessionId);\n if (session) {\n await writeMessage(socket, {\n id: request.id,\n type: "result",\n data: { session }\n });\n await writeMessage(socket, {\n id: request.id,\n type: "complete",\n success: true\n });\n } else {\n await writeMessage(socket, {\n id: request.id,\n type: "error",\n message: `Session "${request.sessionId}" not found`\n });\n }\n return;\n }\n case "session-list":\n await writeMessage(socket, {\n id: request.id,\n type: "result",\n data: { sessions: sessions.list() }\n });\n await writeMessage(socket, {\n id: request.id,\n type: "complete",\n success: true\n });\n return;\n default:\n return;\n }\n}\nfunction shutdown(exitCode = 0) {\n if (shuttingDown) {\n return shuttingDown;\n }\n shuttingDown = (async () => {\n log.info({ exitCode }, "daemon shutting down");\n const serverToClose = server;\n server = null;\n const serverClosed = serverToClose ? closeServerInstance(serverToClose) : Promise.resolve();\n await sessions.endAll();\n await manager.stopAll();\n await Promise.allSettled(\n Array.from(clients, (socket) => closeClientSocket(socket))\n );\n await serverClosed;\n const cleanup = [unlinkIfExists(PID_PATH)];\n if (requiresDaemonEndpointCleanup()) {\n cleanup.push(unlinkIfExists(SOCKET_PATH));\n }\n await Promise.allSettled(cleanup);\n clients.clear();\n process.exit(exitCode);\n })();\n return shuttingDown;\n}\nasync function start() {\n await mkdir4(BASE_DIR, { recursive: true });\n await ensureCanaryTempDir();\n if (requiresDaemonEndpointCleanup()) {\n await unlinkIfExists(SOCKET_PATH);\n }\n await writeFile2(PID_PATH, `${process.pid}\n`);\n server = net.createServer((socket) => {\n if (shuttingDown) {\n socket.end();\n return;\n }\n clients.add(socket);\n socket.setEncoding("utf8");\n let buffer = "";\n let queue = Promise.resolve();\n socket.on("data", (chunk) => {\n buffer += chunk;\n const lines = buffer.split("\\n");\n buffer = lines.pop() ?? "";\n for (const rawLine of lines) {\n const line = rawLine.trim();\n if (!line) {\n continue;\n }\n queue = queue.then(() => handleRequest(socket, line)).catch(async (error) => {\n log.error({ err: error }, "request handling error");\n if (!socket.destroyed) {\n await writeMessage(socket, {\n id: "unknown",\n type: "error",\n message: formatError(error)\n });\n }\n });\n }\n });\n socket.on("close", () => {\n clients.delete(socket);\n });\n socket.on("error", () => {\n clients.delete(socket);\n });\n });\n server.on("error", (error) => {\n log.error({ err: error }, "daemon server error");\n void shutdown(1);\n });\n await new Promise((resolve, reject) => {\n server?.once("error", reject);\n server?.listen(SOCKET_PATH, () => {\n server?.off("error", reject);\n resolve();\n });\n });\n log.info({ socket: SOCKET_PATH, pid: process.pid }, "daemon ready");\n}\nfunction registerShutdownHandlers() {\n const handleSignal = () => {\n void shutdown(0);\n };\n const handleFatalError = (error) => {\n log.error({ err: error }, "fatal daemon error");\n void shutdown(1);\n };\n process.on("SIGINT", handleSignal);\n process.on("SIGTERM", handleSignal);\n process.on("SIGHUP", handleSignal);\n process.on("uncaughtException", handleFatalError);\n process.on("unhandledRejection", handleFatalError);\n}\nregisterShutdownHandlers();\nstart().catch((error) => {\n log.error({ err: error }, "failed to start daemon");\n void shutdown(1);\n});\n';
14492
+ var DAEMON_BUNDLE2 = 'var __defProp = Object.defineProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\n\n// src/daemon.ts\nimport { spawn } from "node:child_process";\nimport { mkdir as mkdir4, unlink, writeFile as writeFile2 } from "node:fs/promises";\nimport net from "node:net";\nimport path6 from "node:path";\n\n// ../../packages/logger/src/index.ts\nimport pino from "pino";\nvar VALID_LEVELS = /* @__PURE__ */ new Set([\n "trace",\n "debug",\n "info",\n "warn",\n "error",\n "fatal",\n "silent"\n]);\nfunction resolveLevel(opts = {}) {\n if (opts.level) {\n return opts.level;\n }\n const fromEnv = process.env.CANARY_LOG_LEVEL?.trim().toLowerCase();\n if (fromEnv && VALID_LEVELS.has(fromEnv)) {\n return fromEnv;\n }\n return opts.fallbackLevel ?? "info";\n}\nfunction createLogger(opts = {}) {\n const options = {\n level: resolveLevel(opts),\n timestamp: pino.stdTimeFunctions.isoTime,\n // Serialize `err`/`error` bindings into structured { type, message, stack }.\n serializers: { err: pino.stdSerializers.err },\n formatters: {\n // Log the level name ("info") instead of the numeric code (30).\n level: (label) => ({ level: label })\n }\n };\n if (opts.name) {\n options.name = opts.name;\n }\n if (opts.redact) {\n options.redact = opts.redact;\n }\n const stream = opts.stream ?? pino.destination({\n dest: opts.destination ?? 2,\n sync: opts.sync ?? false,\n mkdir: true\n });\n const logger = pino(options, stream);\n return opts.base ? logger.child(opts.base) : logger;\n}\n\n// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/external.js\nvar external_exports = {};\n__export(external_exports, {\n BRAND: () => BRAND,\n DIRTY: () => DIRTY,\n EMPTY_PATH: () => EMPTY_PATH,\n INVALID: () => INVALID,\n NEVER: () => NEVER,\n OK: () => OK,\n ParseStatus: () => ParseStatus,\n Schema: () => ZodType,\n ZodAny: () => ZodAny,\n ZodArray: () => ZodArray,\n ZodBigInt: () => ZodBigInt,\n ZodBoolean: () => ZodBoolean,\n ZodBranded: () => ZodBranded,\n ZodCatch: () => ZodCatch,\n ZodDate: () => ZodDate,\n ZodDefault: () => ZodDefault,\n ZodDiscriminatedUnion: () => ZodDiscriminatedUnion,\n ZodEffects: () => ZodEffects,\n ZodEnum: () => ZodEnum,\n ZodError: () => ZodError,\n ZodFirstPartyTypeKind: () => ZodFirstPartyTypeKind,\n ZodFunction: () => ZodFunction,\n ZodIntersection: () => ZodIntersection,\n ZodIssueCode: () => ZodIssueCode,\n ZodLazy: () => ZodLazy,\n ZodLiteral: () => ZodLiteral,\n ZodMap: () => ZodMap,\n ZodNaN: () => ZodNaN,\n ZodNativeEnum: () => ZodNativeEnum,\n ZodNever: () => ZodNever,\n ZodNull: () => ZodNull,\n ZodNullable: () => ZodNullable,\n ZodNumber: () => ZodNumber,\n ZodObject: () => ZodObject,\n ZodOptional: () => ZodOptional,\n ZodParsedType: () => ZodParsedType,\n ZodPipeline: () => ZodPipeline,\n ZodPromise: () => ZodPromise,\n ZodReadonly: () => ZodReadonly,\n ZodRecord: () => ZodRecord,\n ZodSchema: () => ZodType,\n ZodSet: () => ZodSet,\n ZodString: () => ZodString,\n ZodSymbol: () => ZodSymbol,\n ZodTransformer: () => ZodEffects,\n ZodTuple: () => ZodTuple,\n ZodType: () => ZodType,\n ZodUndefined: () => ZodUndefined,\n ZodUnion: () => ZodUnion,\n ZodUnknown: () => ZodUnknown,\n ZodVoid: () => ZodVoid,\n addIssueToContext: () => addIssueToContext,\n any: () => anyType,\n array: () => arrayType,\n bigint: () => bigIntType,\n boolean: () => booleanType,\n coerce: () => coerce,\n custom: () => custom,\n date: () => dateType,\n datetimeRegex: () => datetimeRegex,\n defaultErrorMap: () => en_default,\n discriminatedUnion: () => discriminatedUnionType,\n effect: () => effectsType,\n enum: () => enumType,\n function: () => functionType,\n getErrorMap: () => getErrorMap,\n getParsedType: () => getParsedType,\n instanceof: () => instanceOfType,\n intersection: () => intersectionType,\n isAborted: () => isAborted,\n isAsync: () => isAsync,\n isDirty: () => isDirty,\n isValid: () => isValid,\n late: () => late,\n lazy: () => lazyType,\n literal: () => literalType,\n makeIssue: () => makeIssue,\n map: () => mapType,\n nan: () => nanType,\n nativeEnum: () => nativeEnumType,\n never: () => neverType,\n null: () => nullType,\n nullable: () => nullableType,\n number: () => numberType,\n object: () => objectType,\n objectUtil: () => objectUtil,\n oboolean: () => oboolean,\n onumber: () => onumber,\n optional: () => optionalType,\n ostring: () => ostring,\n pipeline: () => pipelineType,\n preprocess: () => preprocessType,\n promise: () => promiseType,\n quotelessJson: () => quotelessJson,\n record: () => recordType,\n set: () => setType,\n setErrorMap: () => setErrorMap,\n strictObject: () => strictObjectType,\n string: () => stringType,\n symbol: () => symbolType,\n transformer: () => effectsType,\n tuple: () => tupleType,\n undefined: () => undefinedType,\n union: () => unionType,\n unknown: () => unknownType,\n util: () => util,\n void: () => voidType\n});\n\n// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/helpers/util.js\nvar util;\n(function(util3) {\n util3.assertEqual = (_) => {\n };\n function assertIs(_arg) {\n }\n util3.assertIs = assertIs;\n function assertNever(_x) {\n throw new Error();\n }\n util3.assertNever = assertNever;\n util3.arrayToEnum = (items) => {\n const obj = {};\n for (const item of items) {\n obj[item] = item;\n }\n return obj;\n };\n util3.getValidEnumValues = (obj) => {\n const validKeys = util3.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number");\n const filtered = {};\n for (const k of validKeys) {\n filtered[k] = obj[k];\n }\n return util3.objectValues(filtered);\n };\n util3.objectValues = (obj) => {\n return util3.objectKeys(obj).map(function(e) {\n return obj[e];\n });\n };\n util3.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object) => {\n const keys = [];\n for (const key in object) {\n if (Object.prototype.hasOwnProperty.call(object, key)) {\n keys.push(key);\n }\n }\n return keys;\n };\n util3.find = (arr, checker) => {\n for (const item of arr) {\n if (checker(item))\n return item;\n }\n return void 0;\n };\n util3.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "number" && Number.isFinite(val) && Math.floor(val) === val;\n function joinValues(array, separator = " | ") {\n return array.map((val) => typeof val === "string" ? `\'${val}\'` : val).join(separator);\n }\n util3.joinValues = joinValues;\n util3.jsonStringifyReplacer = (_, value) => {\n if (typeof value === "bigint") {\n return value.toString();\n }\n return value;\n };\n})(util || (util = {}));\nvar objectUtil;\n(function(objectUtil2) {\n objectUtil2.mergeShapes = (first, second) => {\n return {\n ...first,\n ...second\n // second overwrites first\n };\n };\n})(objectUtil || (objectUtil = {}));\nvar ZodParsedType = util.arrayToEnum([\n "string",\n "nan",\n "number",\n "integer",\n "float",\n "boolean",\n "date",\n "bigint",\n "symbol",\n "function",\n "undefined",\n "null",\n "array",\n "object",\n "unknown",\n "promise",\n "void",\n "never",\n "map",\n "set"\n]);\nvar getParsedType = (data) => {\n const t = typeof data;\n switch (t) {\n case "undefined":\n return ZodParsedType.undefined;\n case "string":\n return ZodParsedType.string;\n case "number":\n return Number.isNaN(data) ? ZodParsedType.nan : ZodParsedType.number;\n case "boolean":\n return ZodParsedType.boolean;\n case "function":\n return ZodParsedType.function;\n case "bigint":\n return ZodParsedType.bigint;\n case "symbol":\n return ZodParsedType.symbol;\n case "object":\n if (Array.isArray(data)) {\n return ZodParsedType.array;\n }\n if (data === null) {\n return ZodParsedType.null;\n }\n if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") {\n return ZodParsedType.promise;\n }\n if (typeof Map !== "undefined" && data instanceof Map) {\n return ZodParsedType.map;\n }\n if (typeof Set !== "undefined" && data instanceof Set) {\n return ZodParsedType.set;\n }\n if (typeof Date !== "undefined" && data instanceof Date) {\n return ZodParsedType.date;\n }\n return ZodParsedType.object;\n default:\n return ZodParsedType.unknown;\n }\n};\n\n// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/ZodError.js\nvar ZodIssueCode = util.arrayToEnum([\n "invalid_type",\n "invalid_literal",\n "custom",\n "invalid_union",\n "invalid_union_discriminator",\n "invalid_enum_value",\n "unrecognized_keys",\n "invalid_arguments",\n "invalid_return_type",\n "invalid_date",\n "invalid_string",\n "too_small",\n "too_big",\n "invalid_intersection_types",\n "not_multiple_of",\n "not_finite"\n]);\nvar quotelessJson = (obj) => {\n const json = JSON.stringify(obj, null, 2);\n return json.replace(/"([^"]+)":/g, "$1:");\n};\nvar ZodError = class _ZodError extends Error {\n get errors() {\n return this.issues;\n }\n constructor(issues) {\n super();\n this.issues = [];\n this.addIssue = (sub) => {\n this.issues = [...this.issues, sub];\n };\n this.addIssues = (subs = []) => {\n this.issues = [...this.issues, ...subs];\n };\n const actualProto = new.target.prototype;\n if (Object.setPrototypeOf) {\n Object.setPrototypeOf(this, actualProto);\n } else {\n this.__proto__ = actualProto;\n }\n this.name = "ZodError";\n this.issues = issues;\n }\n format(_mapper) {\n const mapper = _mapper || function(issue) {\n return issue.message;\n };\n const fieldErrors = { _errors: [] };\n const processError = (error) => {\n for (const issue of error.issues) {\n if (issue.code === "invalid_union") {\n issue.unionErrors.map(processError);\n } else if (issue.code === "invalid_return_type") {\n processError(issue.returnTypeError);\n } else if (issue.code === "invalid_arguments") {\n processError(issue.argumentsError);\n } else if (issue.path.length === 0) {\n fieldErrors._errors.push(mapper(issue));\n } else {\n let curr = fieldErrors;\n let i = 0;\n while (i < issue.path.length) {\n const el = issue.path[i];\n const terminal = i === issue.path.length - 1;\n if (!terminal) {\n curr[el] = curr[el] || { _errors: [] };\n } else {\n curr[el] = curr[el] || { _errors: [] };\n curr[el]._errors.push(mapper(issue));\n }\n curr = curr[el];\n i++;\n }\n }\n }\n };\n processError(this);\n return fieldErrors;\n }\n static assert(value) {\n if (!(value instanceof _ZodError)) {\n throw new Error(`Not a ZodError: ${value}`);\n }\n }\n toString() {\n return this.message;\n }\n get message() {\n return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2);\n }\n get isEmpty() {\n return this.issues.length === 0;\n }\n flatten(mapper = (issue) => issue.message) {\n const fieldErrors = {};\n const formErrors = [];\n for (const sub of this.issues) {\n if (sub.path.length > 0) {\n const firstEl = sub.path[0];\n fieldErrors[firstEl] = fieldErrors[firstEl] || [];\n fieldErrors[firstEl].push(mapper(sub));\n } else {\n formErrors.push(mapper(sub));\n }\n }\n return { formErrors, fieldErrors };\n }\n get formErrors() {\n return this.flatten();\n }\n};\nZodError.create = (issues) => {\n const error = new ZodError(issues);\n return error;\n};\n\n// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/locales/en.js\nvar errorMap = (issue, _ctx) => {\n let message;\n switch (issue.code) {\n case ZodIssueCode.invalid_type:\n if (issue.received === ZodParsedType.undefined) {\n message = "Required";\n } else {\n message = `Expected ${issue.expected}, received ${issue.received}`;\n }\n break;\n case ZodIssueCode.invalid_literal:\n message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`;\n break;\n case ZodIssueCode.unrecognized_keys:\n message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, ", ")}`;\n break;\n case ZodIssueCode.invalid_union:\n message = `Invalid input`;\n break;\n case ZodIssueCode.invalid_union_discriminator:\n message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`;\n break;\n case ZodIssueCode.invalid_enum_value:\n message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received \'${issue.received}\'`;\n break;\n case ZodIssueCode.invalid_arguments:\n message = `Invalid function arguments`;\n break;\n case ZodIssueCode.invalid_return_type:\n message = `Invalid function return type`;\n break;\n case ZodIssueCode.invalid_date:\n message = `Invalid date`;\n break;\n case ZodIssueCode.invalid_string:\n if (typeof issue.validation === "object") {\n if ("includes" in issue.validation) {\n message = `Invalid input: must include "${issue.validation.includes}"`;\n if (typeof issue.validation.position === "number") {\n message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`;\n }\n } else if ("startsWith" in issue.validation) {\n message = `Invalid input: must start with "${issue.validation.startsWith}"`;\n } else if ("endsWith" in issue.validation) {\n message = `Invalid input: must end with "${issue.validation.endsWith}"`;\n } else {\n util.assertNever(issue.validation);\n }\n } else if (issue.validation !== "regex") {\n message = `Invalid ${issue.validation}`;\n } else {\n message = "Invalid";\n }\n break;\n case ZodIssueCode.too_small:\n if (issue.type === "array")\n message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`;\n else if (issue.type === "string")\n message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`;\n else if (issue.type === "number")\n message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;\n else if (issue.type === "bigint")\n message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;\n else if (issue.type === "date")\n message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`;\n else\n message = "Invalid input";\n break;\n case ZodIssueCode.too_big:\n if (issue.type === "array")\n message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`;\n else if (issue.type === "string")\n message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`;\n else if (issue.type === "number")\n message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;\n else if (issue.type === "bigint")\n message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;\n else if (issue.type === "date")\n message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`;\n else\n message = "Invalid input";\n break;\n case ZodIssueCode.custom:\n message = `Invalid input`;\n break;\n case ZodIssueCode.invalid_intersection_types:\n message = `Intersection results could not be merged`;\n break;\n case ZodIssueCode.not_multiple_of:\n message = `Number must be a multiple of ${issue.multipleOf}`;\n break;\n case ZodIssueCode.not_finite:\n message = "Number must be finite";\n break;\n default:\n message = _ctx.defaultError;\n util.assertNever(issue);\n }\n return { message };\n};\nvar en_default = errorMap;\n\n// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/errors.js\nvar overrideErrorMap = en_default;\nfunction setErrorMap(map) {\n overrideErrorMap = map;\n}\nfunction getErrorMap() {\n return overrideErrorMap;\n}\n\n// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/helpers/parseUtil.js\nvar makeIssue = (params) => {\n const { data, path: path7, errorMaps, issueData } = params;\n const fullPath = [...path7, ...issueData.path || []];\n const fullIssue = {\n ...issueData,\n path: fullPath\n };\n if (issueData.message !== void 0) {\n return {\n ...issueData,\n path: fullPath,\n message: issueData.message\n };\n }\n let errorMessage = "";\n const maps = errorMaps.filter((m) => !!m).slice().reverse();\n for (const map of maps) {\n errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message;\n }\n return {\n ...issueData,\n path: fullPath,\n message: errorMessage\n };\n};\nvar EMPTY_PATH = [];\nfunction addIssueToContext(ctx, issueData) {\n const overrideMap = getErrorMap();\n const issue = makeIssue({\n issueData,\n data: ctx.data,\n path: ctx.path,\n errorMaps: [\n ctx.common.contextualErrorMap,\n // contextual error map is first priority\n ctx.schemaErrorMap,\n // then schema-bound map if available\n overrideMap,\n // then global override map\n overrideMap === en_default ? void 0 : en_default\n // then global default map\n ].filter((x) => !!x)\n });\n ctx.common.issues.push(issue);\n}\nvar ParseStatus = class _ParseStatus {\n constructor() {\n this.value = "valid";\n }\n dirty() {\n if (this.value === "valid")\n this.value = "dirty";\n }\n abort() {\n if (this.value !== "aborted")\n this.value = "aborted";\n }\n static mergeArray(status, results) {\n const arrayValue = [];\n for (const s of results) {\n if (s.status === "aborted")\n return INVALID;\n if (s.status === "dirty")\n status.dirty();\n arrayValue.push(s.value);\n }\n return { status: status.value, value: arrayValue };\n }\n static async mergeObjectAsync(status, pairs) {\n const syncPairs = [];\n for (const pair of pairs) {\n const key = await pair.key;\n const value = await pair.value;\n syncPairs.push({\n key,\n value\n });\n }\n return _ParseStatus.mergeObjectSync(status, syncPairs);\n }\n static mergeObjectSync(status, pairs) {\n const finalObject = {};\n for (const pair of pairs) {\n const { key, value } = pair;\n if (key.status === "aborted")\n return INVALID;\n if (value.status === "aborted")\n return INVALID;\n if (key.status === "dirty")\n status.dirty();\n if (value.status === "dirty")\n status.dirty();\n if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) {\n finalObject[key.value] = value.value;\n }\n }\n return { status: status.value, value: finalObject };\n }\n};\nvar INVALID = Object.freeze({\n status: "aborted"\n});\nvar DIRTY = (value) => ({ status: "dirty", value });\nvar OK = (value) => ({ status: "valid", value });\nvar isAborted = (x) => x.status === "aborted";\nvar isDirty = (x) => x.status === "dirty";\nvar isValid = (x) => x.status === "valid";\nvar isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise;\n\n// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/helpers/errorUtil.js\nvar errorUtil;\n(function(errorUtil2) {\n errorUtil2.errToObj = (message) => typeof message === "string" ? { message } : message || {};\n errorUtil2.toString = (message) => typeof message === "string" ? message : message?.message;\n})(errorUtil || (errorUtil = {}));\n\n// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/types.js\nvar ParseInputLazyPath = class {\n constructor(parent, value, path7, key) {\n this._cachedPath = [];\n this.parent = parent;\n this.data = value;\n this._path = path7;\n this._key = key;\n }\n get path() {\n if (!this._cachedPath.length) {\n if (Array.isArray(this._key)) {\n this._cachedPath.push(...this._path, ...this._key);\n } else {\n this._cachedPath.push(...this._path, this._key);\n }\n }\n return this._cachedPath;\n }\n};\nvar handleResult = (ctx, result) => {\n if (isValid(result)) {\n return { success: true, data: result.value };\n } else {\n if (!ctx.common.issues.length) {\n throw new Error("Validation failed but no issues detected.");\n }\n return {\n success: false,\n get error() {\n if (this._error)\n return this._error;\n const error = new ZodError(ctx.common.issues);\n this._error = error;\n return this._error;\n }\n };\n }\n};\nfunction processCreateParams(params) {\n if (!params)\n return {};\n const { errorMap: errorMap2, invalid_type_error, required_error, description } = params;\n if (errorMap2 && (invalid_type_error || required_error)) {\n throw new Error(`Can\'t use "invalid_type_error" or "required_error" in conjunction with custom error map.`);\n }\n if (errorMap2)\n return { errorMap: errorMap2, description };\n const customMap = (iss, ctx) => {\n const { message } = params;\n if (iss.code === "invalid_enum_value") {\n return { message: message ?? ctx.defaultError };\n }\n if (typeof ctx.data === "undefined") {\n return { message: message ?? required_error ?? ctx.defaultError };\n }\n if (iss.code !== "invalid_type")\n return { message: ctx.defaultError };\n return { message: message ?? invalid_type_error ?? ctx.defaultError };\n };\n return { errorMap: customMap, description };\n}\nvar ZodType = class {\n get description() {\n return this._def.description;\n }\n _getType(input) {\n return getParsedType(input.data);\n }\n _getOrReturnCtx(input, ctx) {\n return ctx || {\n common: input.parent.common,\n data: input.data,\n parsedType: getParsedType(input.data),\n schemaErrorMap: this._def.errorMap,\n path: input.path,\n parent: input.parent\n };\n }\n _processInputParams(input) {\n return {\n status: new ParseStatus(),\n ctx: {\n common: input.parent.common,\n data: input.data,\n parsedType: getParsedType(input.data),\n schemaErrorMap: this._def.errorMap,\n path: input.path,\n parent: input.parent\n }\n };\n }\n _parseSync(input) {\n const result = this._parse(input);\n if (isAsync(result)) {\n throw new Error("Synchronous parse encountered promise.");\n }\n return result;\n }\n _parseAsync(input) {\n const result = this._parse(input);\n return Promise.resolve(result);\n }\n parse(data, params) {\n const result = this.safeParse(data, params);\n if (result.success)\n return result.data;\n throw result.error;\n }\n safeParse(data, params) {\n const ctx = {\n common: {\n issues: [],\n async: params?.async ?? false,\n contextualErrorMap: params?.errorMap\n },\n path: params?.path || [],\n schemaErrorMap: this._def.errorMap,\n parent: null,\n data,\n parsedType: getParsedType(data)\n };\n const result = this._parseSync({ data, path: ctx.path, parent: ctx });\n return handleResult(ctx, result);\n }\n "~validate"(data) {\n const ctx = {\n common: {\n issues: [],\n async: !!this["~standard"].async\n },\n path: [],\n schemaErrorMap: this._def.errorMap,\n parent: null,\n data,\n parsedType: getParsedType(data)\n };\n if (!this["~standard"].async) {\n try {\n const result = this._parseSync({ data, path: [], parent: ctx });\n return isValid(result) ? {\n value: result.value\n } : {\n issues: ctx.common.issues\n };\n } catch (err) {\n if (err?.message?.toLowerCase()?.includes("encountered")) {\n this["~standard"].async = true;\n }\n ctx.common = {\n issues: [],\n async: true\n };\n }\n }\n return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid(result) ? {\n value: result.value\n } : {\n issues: ctx.common.issues\n });\n }\n async parseAsync(data, params) {\n const result = await this.safeParseAsync(data, params);\n if (result.success)\n return result.data;\n throw result.error;\n }\n async safeParseAsync(data, params) {\n const ctx = {\n common: {\n issues: [],\n contextualErrorMap: params?.errorMap,\n async: true\n },\n path: params?.path || [],\n schemaErrorMap: this._def.errorMap,\n parent: null,\n data,\n parsedType: getParsedType(data)\n };\n const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx });\n const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult));\n return handleResult(ctx, result);\n }\n refine(check, message) {\n const getIssueProperties = (val) => {\n if (typeof message === "string" || typeof message === "undefined") {\n return { message };\n } else if (typeof message === "function") {\n return message(val);\n } else {\n return message;\n }\n };\n return this._refinement((val, ctx) => {\n const result = check(val);\n const setError = () => ctx.addIssue({\n code: ZodIssueCode.custom,\n ...getIssueProperties(val)\n });\n if (typeof Promise !== "undefined" && result instanceof Promise) {\n return result.then((data) => {\n if (!data) {\n setError();\n return false;\n } else {\n return true;\n }\n });\n }\n if (!result) {\n setError();\n return false;\n } else {\n return true;\n }\n });\n }\n refinement(check, refinementData) {\n return this._refinement((val, ctx) => {\n if (!check(val)) {\n ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData);\n return false;\n } else {\n return true;\n }\n });\n }\n _refinement(refinement) {\n return new ZodEffects({\n schema: this,\n typeName: ZodFirstPartyTypeKind.ZodEffects,\n effect: { type: "refinement", refinement }\n });\n }\n superRefine(refinement) {\n return this._refinement(refinement);\n }\n constructor(def) {\n this.spa = this.safeParseAsync;\n this._def = def;\n this.parse = this.parse.bind(this);\n this.safeParse = this.safeParse.bind(this);\n this.parseAsync = this.parseAsync.bind(this);\n this.safeParseAsync = this.safeParseAsync.bind(this);\n this.spa = this.spa.bind(this);\n this.refine = this.refine.bind(this);\n this.refinement = this.refinement.bind(this);\n this.superRefine = this.superRefine.bind(this);\n this.optional = this.optional.bind(this);\n this.nullable = this.nullable.bind(this);\n this.nullish = this.nullish.bind(this);\n this.array = this.array.bind(this);\n this.promise = this.promise.bind(this);\n this.or = this.or.bind(this);\n this.and = this.and.bind(this);\n this.transform = this.transform.bind(this);\n this.brand = this.brand.bind(this);\n this.default = this.default.bind(this);\n this.catch = this.catch.bind(this);\n this.describe = this.describe.bind(this);\n this.pipe = this.pipe.bind(this);\n this.readonly = this.readonly.bind(this);\n this.isNullable = this.isNullable.bind(this);\n this.isOptional = this.isOptional.bind(this);\n this["~standard"] = {\n version: 1,\n vendor: "zod",\n validate: (data) => this["~validate"](data)\n };\n }\n optional() {\n return ZodOptional.create(this, this._def);\n }\n nullable() {\n return ZodNullable.create(this, this._def);\n }\n nullish() {\n return this.nullable().optional();\n }\n array() {\n return ZodArray.create(this);\n }\n promise() {\n return ZodPromise.create(this, this._def);\n }\n or(option) {\n return ZodUnion.create([this, option], this._def);\n }\n and(incoming) {\n return ZodIntersection.create(this, incoming, this._def);\n }\n transform(transform) {\n return new ZodEffects({\n ...processCreateParams(this._def),\n schema: this,\n typeName: ZodFirstPartyTypeKind.ZodEffects,\n effect: { type: "transform", transform }\n });\n }\n default(def) {\n const defaultValueFunc = typeof def === "function" ? def : () => def;\n return new ZodDefault({\n ...processCreateParams(this._def),\n innerType: this,\n defaultValue: defaultValueFunc,\n typeName: ZodFirstPartyTypeKind.ZodDefault\n });\n }\n brand() {\n return new ZodBranded({\n typeName: ZodFirstPartyTypeKind.ZodBranded,\n type: this,\n ...processCreateParams(this._def)\n });\n }\n catch(def) {\n const catchValueFunc = typeof def === "function" ? def : () => def;\n return new ZodCatch({\n ...processCreateParams(this._def),\n innerType: this,\n catchValue: catchValueFunc,\n typeName: ZodFirstPartyTypeKind.ZodCatch\n });\n }\n describe(description) {\n const This = this.constructor;\n return new This({\n ...this._def,\n description\n });\n }\n pipe(target) {\n return ZodPipeline.create(this, target);\n }\n readonly() {\n return ZodReadonly.create(this);\n }\n isOptional() {\n return this.safeParse(void 0).success;\n }\n isNullable() {\n return this.safeParse(null).success;\n }\n};\nvar cuidRegex = /^c[^\\s-]{8,}$/i;\nvar cuid2Regex = /^[0-9a-z]+$/;\nvar ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i;\nvar uuidRegex = /^[0-9a-fA-F]{8}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{12}$/i;\nvar nanoidRegex = /^[a-z0-9_-]{21}$/i;\nvar jwtRegex = /^[A-Za-z0-9-_]+\\.[A-Za-z0-9-_]+\\.[A-Za-z0-9-_]*$/;\nvar durationRegex = /^[-+]?P(?!$)(?:(?:[-+]?\\d+Y)|(?:[-+]?\\d+[.,]\\d+Y$))?(?:(?:[-+]?\\d+M)|(?:[-+]?\\d+[.,]\\d+M$))?(?:(?:[-+]?\\d+W)|(?:[-+]?\\d+[.,]\\d+W$))?(?:(?:[-+]?\\d+D)|(?:[-+]?\\d+[.,]\\d+D$))?(?:T(?=[\\d+-])(?:(?:[-+]?\\d+H)|(?:[-+]?\\d+[.,]\\d+H$))?(?:(?:[-+]?\\d+M)|(?:[-+]?\\d+[.,]\\d+M$))?(?:[-+]?\\d+(?:[.,]\\d+)?S)?)??$/;\nvar emailRegex = /^(?!\\.)(?!.*\\.\\.)([A-Z0-9_\'+\\-\\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\\-]*\\.)+[A-Z]{2,}$/i;\nvar _emojiRegex = `^(\\\\p{Extended_Pictographic}|\\\\p{Emoji_Component})+$`;\nvar emojiRegex;\nvar ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;\nvar ipv4CidrRegex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\/(3[0-2]|[12]?[0-9])$/;\nvar ipv6Regex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/;\nvar ipv6CidrRegex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;\nvar base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;\nvar base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/;\nvar dateRegexSource = `((\\\\d\\\\d[2468][048]|\\\\d\\\\d[13579][26]|\\\\d\\\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\\\d|30)|(02)-(0[1-9]|1\\\\d|2[0-8])))`;\nvar dateRegex = new RegExp(`^${dateRegexSource}$`);\nfunction timeRegexSource(args) {\n let secondsRegexSource = `[0-5]\\\\d`;\n if (args.precision) {\n secondsRegexSource = `${secondsRegexSource}\\\\.\\\\d{${args.precision}}`;\n } else if (args.precision == null) {\n secondsRegexSource = `${secondsRegexSource}(\\\\.\\\\d+)?`;\n }\n const secondsQuantifier = args.precision ? "+" : "?";\n return `([01]\\\\d|2[0-3]):[0-5]\\\\d(:${secondsRegexSource})${secondsQuantifier}`;\n}\nfunction timeRegex(args) {\n return new RegExp(`^${timeRegexSource(args)}$`);\n}\nfunction datetimeRegex(args) {\n let regex = `${dateRegexSource}T${timeRegexSource(args)}`;\n const opts = [];\n opts.push(args.local ? `Z?` : `Z`);\n if (args.offset)\n opts.push(`([+-]\\\\d{2}:?\\\\d{2})`);\n regex = `${regex}(${opts.join("|")})`;\n return new RegExp(`^${regex}$`);\n}\nfunction isValidIP(ip, version) {\n if ((version === "v4" || !version) && ipv4Regex.test(ip)) {\n return true;\n }\n if ((version === "v6" || !version) && ipv6Regex.test(ip)) {\n return true;\n }\n return false;\n}\nfunction isValidJWT(jwt, alg) {\n if (!jwtRegex.test(jwt))\n return false;\n try {\n const [header] = jwt.split(".");\n if (!header)\n return false;\n const base64 = header.replace(/-/g, "+").replace(/_/g, "/").padEnd(header.length + (4 - header.length % 4) % 4, "=");\n const decoded = JSON.parse(atob(base64));\n if (typeof decoded !== "object" || decoded === null)\n return false;\n if ("typ" in decoded && decoded?.typ !== "JWT")\n return false;\n if (!decoded.alg)\n return false;\n if (alg && decoded.alg !== alg)\n return false;\n return true;\n } catch {\n return false;\n }\n}\nfunction isValidCidr(ip, version) {\n if ((version === "v4" || !version) && ipv4CidrRegex.test(ip)) {\n return true;\n }\n if ((version === "v6" || !version) && ipv6CidrRegex.test(ip)) {\n return true;\n }\n return false;\n}\nvar ZodString = class _ZodString extends ZodType {\n _parse(input) {\n if (this._def.coerce) {\n input.data = String(input.data);\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.string) {\n const ctx2 = this._getOrReturnCtx(input);\n addIssueToContext(ctx2, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.string,\n received: ctx2.parsedType\n });\n return INVALID;\n }\n const status = new ParseStatus();\n let ctx = void 0;\n for (const check of this._def.checks) {\n if (check.kind === "min") {\n if (input.data.length < check.value) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: check.value,\n type: "string",\n inclusive: true,\n exact: false,\n message: check.message\n });\n status.dirty();\n }\n } else if (check.kind === "max") {\n if (input.data.length > check.value) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: check.value,\n type: "string",\n inclusive: true,\n exact: false,\n message: check.message\n });\n status.dirty();\n }\n } else if (check.kind === "length") {\n const tooBig = input.data.length > check.value;\n const tooSmall = input.data.length < check.value;\n if (tooBig || tooSmall) {\n ctx = this._getOrReturnCtx(input, ctx);\n if (tooBig) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: check.value,\n type: "string",\n inclusive: true,\n exact: true,\n message: check.message\n });\n } else if (tooSmall) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: check.value,\n type: "string",\n inclusive: true,\n exact: true,\n message: check.message\n });\n }\n status.dirty();\n }\n } else if (check.kind === "email") {\n if (!emailRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: "email",\n code: ZodIssueCode.invalid_string,\n message: check.message\n });\n status.dirty();\n }\n } else if (check.kind === "emoji") {\n if (!emojiRegex) {\n emojiRegex = new RegExp(_emojiRegex, "u");\n }\n if (!emojiRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: "emoji",\n code: ZodIssueCode.invalid_string,\n message: check.message\n });\n status.dirty();\n }\n } else if (check.kind === "uuid") {\n if (!uuidRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: "uuid",\n code: ZodIssueCode.invalid_string,\n message: check.message\n });\n status.dirty();\n }\n } else if (check.kind === "nanoid") {\n if (!nanoidRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: "nanoid",\n code: ZodIssueCode.invalid_string,\n message: check.message\n });\n status.dirty();\n }\n } else if (check.kind === "cuid") {\n if (!cuidRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: "cuid",\n code: ZodIssueCode.invalid_string,\n message: check.message\n });\n status.dirty();\n }\n } else if (check.kind === "cuid2") {\n if (!cuid2Regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: "cuid2",\n code: ZodIssueCode.invalid_string,\n message: check.message\n });\n status.dirty();\n }\n } else if (check.kind === "ulid") {\n if (!ulidRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: "ulid",\n code: ZodIssueCode.invalid_string,\n message: check.message\n });\n status.dirty();\n }\n } else if (check.kind === "url") {\n try {\n new URL(input.data);\n } catch {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: "url",\n code: ZodIssueCode.invalid_string,\n message: check.message\n });\n status.dirty();\n }\n } else if (check.kind === "regex") {\n check.regex.lastIndex = 0;\n const testResult = check.regex.test(input.data);\n if (!testResult) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: "regex",\n code: ZodIssueCode.invalid_string,\n message: check.message\n });\n status.dirty();\n }\n } else if (check.kind === "trim") {\n input.data = input.data.trim();\n } else if (check.kind === "includes") {\n if (!input.data.includes(check.value, check.position)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: { includes: check.value, position: check.position },\n message: check.message\n });\n status.dirty();\n }\n } else if (check.kind === "toLowerCase") {\n input.data = input.data.toLowerCase();\n } else if (check.kind === "toUpperCase") {\n input.data = input.data.toUpperCase();\n } else if (check.kind === "startsWith") {\n if (!input.data.startsWith(check.value)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: { startsWith: check.value },\n message: check.message\n });\n status.dirty();\n }\n } else if (check.kind === "endsWith") {\n if (!input.data.endsWith(check.value)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: { endsWith: check.value },\n message: check.message\n });\n status.dirty();\n }\n } else if (check.kind === "datetime") {\n const regex = datetimeRegex(check);\n if (!regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: "datetime",\n message: check.message\n });\n status.dirty();\n }\n } else if (check.kind === "date") {\n const regex = dateRegex;\n if (!regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: "date",\n message: check.message\n });\n status.dirty();\n }\n } else if (check.kind === "time") {\n const regex = timeRegex(check);\n if (!regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: "time",\n message: check.message\n });\n status.dirty();\n }\n } else if (check.kind === "duration") {\n if (!durationRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: "duration",\n code: ZodIssueCode.invalid_string,\n message: check.message\n });\n status.dirty();\n }\n } else if (check.kind === "ip") {\n if (!isValidIP(input.data, check.version)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: "ip",\n code: ZodIssueCode.invalid_string,\n message: check.message\n });\n status.dirty();\n }\n } else if (check.kind === "jwt") {\n if (!isValidJWT(input.data, check.alg)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: "jwt",\n code: ZodIssueCode.invalid_string,\n message: check.message\n });\n status.dirty();\n }\n } else if (check.kind === "cidr") {\n if (!isValidCidr(input.data, check.version)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: "cidr",\n code: ZodIssueCode.invalid_string,\n message: check.message\n });\n status.dirty();\n }\n } else if (check.kind === "base64") {\n if (!base64Regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: "base64",\n code: ZodIssueCode.invalid_string,\n message: check.message\n });\n status.dirty();\n }\n } else if (check.kind === "base64url") {\n if (!base64urlRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: "base64url",\n code: ZodIssueCode.invalid_string,\n message: check.message\n });\n status.dirty();\n }\n } else {\n util.assertNever(check);\n }\n }\n return { status: status.value, value: input.data };\n }\n _regex(regex, validation, message) {\n return this.refinement((data) => regex.test(data), {\n validation,\n code: ZodIssueCode.invalid_string,\n ...errorUtil.errToObj(message)\n });\n }\n _addCheck(check) {\n return new _ZodString({\n ...this._def,\n checks: [...this._def.checks, check]\n });\n }\n email(message) {\n return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) });\n }\n url(message) {\n return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) });\n }\n emoji(message) {\n return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) });\n }\n uuid(message) {\n return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) });\n }\n nanoid(message) {\n return this._addCheck({ kind: "nanoid", ...errorUtil.errToObj(message) });\n }\n cuid(message) {\n return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) });\n }\n cuid2(message) {\n return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) });\n }\n ulid(message) {\n return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) });\n }\n base64(message) {\n return this._addCheck({ kind: "base64", ...errorUtil.errToObj(message) });\n }\n base64url(message) {\n return this._addCheck({\n kind: "base64url",\n ...errorUtil.errToObj(message)\n });\n }\n jwt(options) {\n return this._addCheck({ kind: "jwt", ...errorUtil.errToObj(options) });\n }\n ip(options) {\n return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) });\n }\n cidr(options) {\n return this._addCheck({ kind: "cidr", ...errorUtil.errToObj(options) });\n }\n datetime(options) {\n if (typeof options === "string") {\n return this._addCheck({\n kind: "datetime",\n precision: null,\n offset: false,\n local: false,\n message: options\n });\n }\n return this._addCheck({\n kind: "datetime",\n precision: typeof options?.precision === "undefined" ? null : options?.precision,\n offset: options?.offset ?? false,\n local: options?.local ?? false,\n ...errorUtil.errToObj(options?.message)\n });\n }\n date(message) {\n return this._addCheck({ kind: "date", message });\n }\n time(options) {\n if (typeof options === "string") {\n return this._addCheck({\n kind: "time",\n precision: null,\n message: options\n });\n }\n return this._addCheck({\n kind: "time",\n precision: typeof options?.precision === "undefined" ? null : options?.precision,\n ...errorUtil.errToObj(options?.message)\n });\n }\n duration(message) {\n return this._addCheck({ kind: "duration", ...errorUtil.errToObj(message) });\n }\n regex(regex, message) {\n return this._addCheck({\n kind: "regex",\n regex,\n ...errorUtil.errToObj(message)\n });\n }\n includes(value, options) {\n return this._addCheck({\n kind: "includes",\n value,\n position: options?.position,\n ...errorUtil.errToObj(options?.message)\n });\n }\n startsWith(value, message) {\n return this._addCheck({\n kind: "startsWith",\n value,\n ...errorUtil.errToObj(message)\n });\n }\n endsWith(value, message) {\n return this._addCheck({\n kind: "endsWith",\n value,\n ...errorUtil.errToObj(message)\n });\n }\n min(minLength, message) {\n return this._addCheck({\n kind: "min",\n value: minLength,\n ...errorUtil.errToObj(message)\n });\n }\n max(maxLength, message) {\n return this._addCheck({\n kind: "max",\n value: maxLength,\n ...errorUtil.errToObj(message)\n });\n }\n length(len, message) {\n return this._addCheck({\n kind: "length",\n value: len,\n ...errorUtil.errToObj(message)\n });\n }\n /**\n * Equivalent to `.min(1)`\n */\n nonempty(message) {\n return this.min(1, errorUtil.errToObj(message));\n }\n trim() {\n return new _ZodString({\n ...this._def,\n checks: [...this._def.checks, { kind: "trim" }]\n });\n }\n toLowerCase() {\n return new _ZodString({\n ...this._def,\n checks: [...this._def.checks, { kind: "toLowerCase" }]\n });\n }\n toUpperCase() {\n return new _ZodString({\n ...this._def,\n checks: [...this._def.checks, { kind: "toUpperCase" }]\n });\n }\n get isDatetime() {\n return !!this._def.checks.find((ch) => ch.kind === "datetime");\n }\n get isDate() {\n return !!this._def.checks.find((ch) => ch.kind === "date");\n }\n get isTime() {\n return !!this._def.checks.find((ch) => ch.kind === "time");\n }\n get isDuration() {\n return !!this._def.checks.find((ch) => ch.kind === "duration");\n }\n get isEmail() {\n return !!this._def.checks.find((ch) => ch.kind === "email");\n }\n get isURL() {\n return !!this._def.checks.find((ch) => ch.kind === "url");\n }\n get isEmoji() {\n return !!this._def.checks.find((ch) => ch.kind === "emoji");\n }\n get isUUID() {\n return !!this._def.checks.find((ch) => ch.kind === "uuid");\n }\n get isNANOID() {\n return !!this._def.checks.find((ch) => ch.kind === "nanoid");\n }\n get isCUID() {\n return !!this._def.checks.find((ch) => ch.kind === "cuid");\n }\n get isCUID2() {\n return !!this._def.checks.find((ch) => ch.kind === "cuid2");\n }\n get isULID() {\n return !!this._def.checks.find((ch) => ch.kind === "ulid");\n }\n get isIP() {\n return !!this._def.checks.find((ch) => ch.kind === "ip");\n }\n get isCIDR() {\n return !!this._def.checks.find((ch) => ch.kind === "cidr");\n }\n get isBase64() {\n return !!this._def.checks.find((ch) => ch.kind === "base64");\n }\n get isBase64url() {\n return !!this._def.checks.find((ch) => ch.kind === "base64url");\n }\n get minLength() {\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === "min") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n }\n return min;\n }\n get maxLength() {\n let max = null;\n for (const ch of this._def.checks) {\n if (ch.kind === "max") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return max;\n }\n};\nZodString.create = (params) => {\n return new ZodString({\n checks: [],\n typeName: ZodFirstPartyTypeKind.ZodString,\n coerce: params?.coerce ?? false,\n ...processCreateParams(params)\n });\n};\nfunction floatSafeRemainder(val, step) {\n const valDecCount = (val.toString().split(".")[1] || "").length;\n const stepDecCount = (step.toString().split(".")[1] || "").length;\n const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;\n const valInt = Number.parseInt(val.toFixed(decCount).replace(".", ""));\n const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", ""));\n return valInt % stepInt / 10 ** decCount;\n}\nvar ZodNumber = class _ZodNumber extends ZodType {\n constructor() {\n super(...arguments);\n this.min = this.gte;\n this.max = this.lte;\n this.step = this.multipleOf;\n }\n _parse(input) {\n if (this._def.coerce) {\n input.data = Number(input.data);\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.number) {\n const ctx2 = this._getOrReturnCtx(input);\n addIssueToContext(ctx2, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.number,\n received: ctx2.parsedType\n });\n return INVALID;\n }\n let ctx = void 0;\n const status = new ParseStatus();\n for (const check of this._def.checks) {\n if (check.kind === "int") {\n if (!util.isInteger(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: "integer",\n received: "float",\n message: check.message\n });\n status.dirty();\n }\n } else if (check.kind === "min") {\n const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;\n if (tooSmall) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: check.value,\n type: "number",\n inclusive: check.inclusive,\n exact: false,\n message: check.message\n });\n status.dirty();\n }\n } else if (check.kind === "max") {\n const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;\n if (tooBig) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: check.value,\n type: "number",\n inclusive: check.inclusive,\n exact: false,\n message: check.message\n });\n status.dirty();\n }\n } else if (check.kind === "multipleOf") {\n if (floatSafeRemainder(input.data, check.value) !== 0) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.not_multiple_of,\n multipleOf: check.value,\n message: check.message\n });\n status.dirty();\n }\n } else if (check.kind === "finite") {\n if (!Number.isFinite(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.not_finite,\n message: check.message\n });\n status.dirty();\n }\n } else {\n util.assertNever(check);\n }\n }\n return { status: status.value, value: input.data };\n }\n gte(value, message) {\n return this.setLimit("min", value, true, errorUtil.toString(message));\n }\n gt(value, message) {\n return this.setLimit("min", value, false, errorUtil.toString(message));\n }\n lte(value, message) {\n return this.setLimit("max", value, true, errorUtil.toString(message));\n }\n lt(value, message) {\n return this.setLimit("max", value, false, errorUtil.toString(message));\n }\n setLimit(kind, value, inclusive, message) {\n return new _ZodNumber({\n ...this._def,\n checks: [\n ...this._def.checks,\n {\n kind,\n value,\n inclusive,\n message: errorUtil.toString(message)\n }\n ]\n });\n }\n _addCheck(check) {\n return new _ZodNumber({\n ...this._def,\n checks: [...this._def.checks, check]\n });\n }\n int(message) {\n return this._addCheck({\n kind: "int",\n message: errorUtil.toString(message)\n });\n }\n positive(message) {\n return this._addCheck({\n kind: "min",\n value: 0,\n inclusive: false,\n message: errorUtil.toString(message)\n });\n }\n negative(message) {\n return this._addCheck({\n kind: "max",\n value: 0,\n inclusive: false,\n message: errorUtil.toString(message)\n });\n }\n nonpositive(message) {\n return this._addCheck({\n kind: "max",\n value: 0,\n inclusive: true,\n message: errorUtil.toString(message)\n });\n }\n nonnegative(message) {\n return this._addCheck({\n kind: "min",\n value: 0,\n inclusive: true,\n message: errorUtil.toString(message)\n });\n }\n multipleOf(value, message) {\n return this._addCheck({\n kind: "multipleOf",\n value,\n message: errorUtil.toString(message)\n });\n }\n finite(message) {\n return this._addCheck({\n kind: "finite",\n message: errorUtil.toString(message)\n });\n }\n safe(message) {\n return this._addCheck({\n kind: "min",\n inclusive: true,\n value: Number.MIN_SAFE_INTEGER,\n message: errorUtil.toString(message)\n })._addCheck({\n kind: "max",\n inclusive: true,\n value: Number.MAX_SAFE_INTEGER,\n message: errorUtil.toString(message)\n });\n }\n get minValue() {\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === "min") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n }\n return min;\n }\n get maxValue() {\n let max = null;\n for (const ch of this._def.checks) {\n if (ch.kind === "max") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return max;\n }\n get isInt() {\n return !!this._def.checks.find((ch) => ch.kind === "int" || ch.kind === "multipleOf" && util.isInteger(ch.value));\n }\n get isFinite() {\n let max = null;\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") {\n return true;\n } else if (ch.kind === "min") {\n if (min === null || ch.value > min)\n min = ch.value;\n } else if (ch.kind === "max") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return Number.isFinite(min) && Number.isFinite(max);\n }\n};\nZodNumber.create = (params) => {\n return new ZodNumber({\n checks: [],\n typeName: ZodFirstPartyTypeKind.ZodNumber,\n coerce: params?.coerce || false,\n ...processCreateParams(params)\n });\n};\nvar ZodBigInt = class _ZodBigInt extends ZodType {\n constructor() {\n super(...arguments);\n this.min = this.gte;\n this.max = this.lte;\n }\n _parse(input) {\n if (this._def.coerce) {\n try {\n input.data = BigInt(input.data);\n } catch {\n return this._getInvalidInput(input);\n }\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.bigint) {\n return this._getInvalidInput(input);\n }\n let ctx = void 0;\n const status = new ParseStatus();\n for (const check of this._def.checks) {\n if (check.kind === "min") {\n const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;\n if (tooSmall) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n type: "bigint",\n minimum: check.value,\n inclusive: check.inclusive,\n message: check.message\n });\n status.dirty();\n }\n } else if (check.kind === "max") {\n const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;\n if (tooBig) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n type: "bigint",\n maximum: check.value,\n inclusive: check.inclusive,\n message: check.message\n });\n status.dirty();\n }\n } else if (check.kind === "multipleOf") {\n if (input.data % check.value !== BigInt(0)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.not_multiple_of,\n multipleOf: check.value,\n message: check.message\n });\n status.dirty();\n }\n } else {\n util.assertNever(check);\n }\n }\n return { status: status.value, value: input.data };\n }\n _getInvalidInput(input) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.bigint,\n received: ctx.parsedType\n });\n return INVALID;\n }\n gte(value, message) {\n return this.setLimit("min", value, true, errorUtil.toString(message));\n }\n gt(value, message) {\n return this.setLimit("min", value, false, errorUtil.toString(message));\n }\n lte(value, message) {\n return this.setLimit("max", value, true, errorUtil.toString(message));\n }\n lt(value, message) {\n return this.setLimit("max", value, false, errorUtil.toString(message));\n }\n setLimit(kind, value, inclusive, message) {\n return new _ZodBigInt({\n ...this._def,\n checks: [\n ...this._def.checks,\n {\n kind,\n value,\n inclusive,\n message: errorUtil.toString(message)\n }\n ]\n });\n }\n _addCheck(check) {\n return new _ZodBigInt({\n ...this._def,\n checks: [...this._def.checks, check]\n });\n }\n positive(message) {\n return this._addCheck({\n kind: "min",\n value: BigInt(0),\n inclusive: false,\n message: errorUtil.toString(message)\n });\n }\n negative(message) {\n return this._addCheck({\n kind: "max",\n value: BigInt(0),\n inclusive: false,\n message: errorUtil.toString(message)\n });\n }\n nonpositive(message) {\n return this._addCheck({\n kind: "max",\n value: BigInt(0),\n inclusive: true,\n message: errorUtil.toString(message)\n });\n }\n nonnegative(message) {\n return this._addCheck({\n kind: "min",\n value: BigInt(0),\n inclusive: true,\n message: errorUtil.toString(message)\n });\n }\n multipleOf(value, message) {\n return this._addCheck({\n kind: "multipleOf",\n value,\n message: errorUtil.toString(message)\n });\n }\n get minValue() {\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === "min") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n }\n return min;\n }\n get maxValue() {\n let max = null;\n for (const ch of this._def.checks) {\n if (ch.kind === "max") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return max;\n }\n};\nZodBigInt.create = (params) => {\n return new ZodBigInt({\n checks: [],\n typeName: ZodFirstPartyTypeKind.ZodBigInt,\n coerce: params?.coerce ?? false,\n ...processCreateParams(params)\n });\n};\nvar ZodBoolean = class extends ZodType {\n _parse(input) {\n if (this._def.coerce) {\n input.data = Boolean(input.data);\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.boolean) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.boolean,\n received: ctx.parsedType\n });\n return INVALID;\n }\n return OK(input.data);\n }\n};\nZodBoolean.create = (params) => {\n return new ZodBoolean({\n typeName: ZodFirstPartyTypeKind.ZodBoolean,\n coerce: params?.coerce || false,\n ...processCreateParams(params)\n });\n};\nvar ZodDate = class _ZodDate extends ZodType {\n _parse(input) {\n if (this._def.coerce) {\n input.data = new Date(input.data);\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.date) {\n const ctx2 = this._getOrReturnCtx(input);\n addIssueToContext(ctx2, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.date,\n received: ctx2.parsedType\n });\n return INVALID;\n }\n if (Number.isNaN(input.data.getTime())) {\n const ctx2 = this._getOrReturnCtx(input);\n addIssueToContext(ctx2, {\n code: ZodIssueCode.invalid_date\n });\n return INVALID;\n }\n const status = new ParseStatus();\n let ctx = void 0;\n for (const check of this._def.checks) {\n if (check.kind === "min") {\n if (input.data.getTime() < check.value) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n message: check.message,\n inclusive: true,\n exact: false,\n minimum: check.value,\n type: "date"\n });\n status.dirty();\n }\n } else if (check.kind === "max") {\n if (input.data.getTime() > check.value) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n message: check.message,\n inclusive: true,\n exact: false,\n maximum: check.value,\n type: "date"\n });\n status.dirty();\n }\n } else {\n util.assertNever(check);\n }\n }\n return {\n status: status.value,\n value: new Date(input.data.getTime())\n };\n }\n _addCheck(check) {\n return new _ZodDate({\n ...this._def,\n checks: [...this._def.checks, check]\n });\n }\n min(minDate, message) {\n return this._addCheck({\n kind: "min",\n value: minDate.getTime(),\n message: errorUtil.toString(message)\n });\n }\n max(maxDate, message) {\n return this._addCheck({\n kind: "max",\n value: maxDate.getTime(),\n message: errorUtil.toString(message)\n });\n }\n get minDate() {\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === "min") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n }\n return min != null ? new Date(min) : null;\n }\n get maxDate() {\n let max = null;\n for (const ch of this._def.checks) {\n if (ch.kind === "max") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return max != null ? new Date(max) : null;\n }\n};\nZodDate.create = (params) => {\n return new ZodDate({\n checks: [],\n coerce: params?.coerce || false,\n typeName: ZodFirstPartyTypeKind.ZodDate,\n ...processCreateParams(params)\n });\n};\nvar ZodSymbol = class extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.symbol) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.symbol,\n received: ctx.parsedType\n });\n return INVALID;\n }\n return OK(input.data);\n }\n};\nZodSymbol.create = (params) => {\n return new ZodSymbol({\n typeName: ZodFirstPartyTypeKind.ZodSymbol,\n ...processCreateParams(params)\n });\n};\nvar ZodUndefined = class extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.undefined) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.undefined,\n received: ctx.parsedType\n });\n return INVALID;\n }\n return OK(input.data);\n }\n};\nZodUndefined.create = (params) => {\n return new ZodUndefined({\n typeName: ZodFirstPartyTypeKind.ZodUndefined,\n ...processCreateParams(params)\n });\n};\nvar ZodNull = class extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.null) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.null,\n received: ctx.parsedType\n });\n return INVALID;\n }\n return OK(input.data);\n }\n};\nZodNull.create = (params) => {\n return new ZodNull({\n typeName: ZodFirstPartyTypeKind.ZodNull,\n ...processCreateParams(params)\n });\n};\nvar ZodAny = class extends ZodType {\n constructor() {\n super(...arguments);\n this._any = true;\n }\n _parse(input) {\n return OK(input.data);\n }\n};\nZodAny.create = (params) => {\n return new ZodAny({\n typeName: ZodFirstPartyTypeKind.ZodAny,\n ...processCreateParams(params)\n });\n};\nvar ZodUnknown = class extends ZodType {\n constructor() {\n super(...arguments);\n this._unknown = true;\n }\n _parse(input) {\n return OK(input.data);\n }\n};\nZodUnknown.create = (params) => {\n return new ZodUnknown({\n typeName: ZodFirstPartyTypeKind.ZodUnknown,\n ...processCreateParams(params)\n });\n};\nvar ZodNever = class extends ZodType {\n _parse(input) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.never,\n received: ctx.parsedType\n });\n return INVALID;\n }\n};\nZodNever.create = (params) => {\n return new ZodNever({\n typeName: ZodFirstPartyTypeKind.ZodNever,\n ...processCreateParams(params)\n });\n};\nvar ZodVoid = class extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.undefined) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.void,\n received: ctx.parsedType\n });\n return INVALID;\n }\n return OK(input.data);\n }\n};\nZodVoid.create = (params) => {\n return new ZodVoid({\n typeName: ZodFirstPartyTypeKind.ZodVoid,\n ...processCreateParams(params)\n });\n};\nvar ZodArray = class _ZodArray extends ZodType {\n _parse(input) {\n const { ctx, status } = this._processInputParams(input);\n const def = this._def;\n if (ctx.parsedType !== ZodParsedType.array) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.array,\n received: ctx.parsedType\n });\n return INVALID;\n }\n if (def.exactLength !== null) {\n const tooBig = ctx.data.length > def.exactLength.value;\n const tooSmall = ctx.data.length < def.exactLength.value;\n if (tooBig || tooSmall) {\n addIssueToContext(ctx, {\n code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small,\n minimum: tooSmall ? def.exactLength.value : void 0,\n maximum: tooBig ? def.exactLength.value : void 0,\n type: "array",\n inclusive: true,\n exact: true,\n message: def.exactLength.message\n });\n status.dirty();\n }\n }\n if (def.minLength !== null) {\n if (ctx.data.length < def.minLength.value) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: def.minLength.value,\n type: "array",\n inclusive: true,\n exact: false,\n message: def.minLength.message\n });\n status.dirty();\n }\n }\n if (def.maxLength !== null) {\n if (ctx.data.length > def.maxLength.value) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: def.maxLength.value,\n type: "array",\n inclusive: true,\n exact: false,\n message: def.maxLength.message\n });\n status.dirty();\n }\n }\n if (ctx.common.async) {\n return Promise.all([...ctx.data].map((item, i) => {\n return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i));\n })).then((result2) => {\n return ParseStatus.mergeArray(status, result2);\n });\n }\n const result = [...ctx.data].map((item, i) => {\n return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i));\n });\n return ParseStatus.mergeArray(status, result);\n }\n get element() {\n return this._def.type;\n }\n min(minLength, message) {\n return new _ZodArray({\n ...this._def,\n minLength: { value: minLength, message: errorUtil.toString(message) }\n });\n }\n max(maxLength, message) {\n return new _ZodArray({\n ...this._def,\n maxLength: { value: maxLength, message: errorUtil.toString(message) }\n });\n }\n length(len, message) {\n return new _ZodArray({\n ...this._def,\n exactLength: { value: len, message: errorUtil.toString(message) }\n });\n }\n nonempty(message) {\n return this.min(1, message);\n }\n};\nZodArray.create = (schema, params) => {\n return new ZodArray({\n type: schema,\n minLength: null,\n maxLength: null,\n exactLength: null,\n typeName: ZodFirstPartyTypeKind.ZodArray,\n ...processCreateParams(params)\n });\n};\nfunction deepPartialify(schema) {\n if (schema instanceof ZodObject) {\n const newShape = {};\n for (const key in schema.shape) {\n const fieldSchema = schema.shape[key];\n newShape[key] = ZodOptional.create(deepPartialify(fieldSchema));\n }\n return new ZodObject({\n ...schema._def,\n shape: () => newShape\n });\n } else if (schema instanceof ZodArray) {\n return new ZodArray({\n ...schema._def,\n type: deepPartialify(schema.element)\n });\n } else if (schema instanceof ZodOptional) {\n return ZodOptional.create(deepPartialify(schema.unwrap()));\n } else if (schema instanceof ZodNullable) {\n return ZodNullable.create(deepPartialify(schema.unwrap()));\n } else if (schema instanceof ZodTuple) {\n return ZodTuple.create(schema.items.map((item) => deepPartialify(item)));\n } else {\n return schema;\n }\n}\nvar ZodObject = class _ZodObject extends ZodType {\n constructor() {\n super(...arguments);\n this._cached = null;\n this.nonstrict = this.passthrough;\n this.augment = this.extend;\n }\n _getCached() {\n if (this._cached !== null)\n return this._cached;\n const shape = this._def.shape();\n const keys = util.objectKeys(shape);\n this._cached = { shape, keys };\n return this._cached;\n }\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.object) {\n const ctx2 = this._getOrReturnCtx(input);\n addIssueToContext(ctx2, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.object,\n received: ctx2.parsedType\n });\n return INVALID;\n }\n const { status, ctx } = this._processInputParams(input);\n const { shape, keys: shapeKeys } = this._getCached();\n const extraKeys = [];\n if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === "strip")) {\n for (const key in ctx.data) {\n if (!shapeKeys.includes(key)) {\n extraKeys.push(key);\n }\n }\n }\n const pairs = [];\n for (const key of shapeKeys) {\n const keyValidator = shape[key];\n const value = ctx.data[key];\n pairs.push({\n key: { status: "valid", value: key },\n value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),\n alwaysSet: key in ctx.data\n });\n }\n if (this._def.catchall instanceof ZodNever) {\n const unknownKeys = this._def.unknownKeys;\n if (unknownKeys === "passthrough") {\n for (const key of extraKeys) {\n pairs.push({\n key: { status: "valid", value: key },\n value: { status: "valid", value: ctx.data[key] }\n });\n }\n } else if (unknownKeys === "strict") {\n if (extraKeys.length > 0) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.unrecognized_keys,\n keys: extraKeys\n });\n status.dirty();\n }\n } else if (unknownKeys === "strip") {\n } else {\n throw new Error(`Internal ZodObject error: invalid unknownKeys value.`);\n }\n } else {\n const catchall = this._def.catchall;\n for (const key of extraKeys) {\n const value = ctx.data[key];\n pairs.push({\n key: { status: "valid", value: key },\n value: catchall._parse(\n new ParseInputLazyPath(ctx, value, ctx.path, key)\n //, ctx.child(key), value, getParsedType(value)\n ),\n alwaysSet: key in ctx.data\n });\n }\n }\n if (ctx.common.async) {\n return Promise.resolve().then(async () => {\n const syncPairs = [];\n for (const pair of pairs) {\n const key = await pair.key;\n const value = await pair.value;\n syncPairs.push({\n key,\n value,\n alwaysSet: pair.alwaysSet\n });\n }\n return syncPairs;\n }).then((syncPairs) => {\n return ParseStatus.mergeObjectSync(status, syncPairs);\n });\n } else {\n return ParseStatus.mergeObjectSync(status, pairs);\n }\n }\n get shape() {\n return this._def.shape();\n }\n strict(message) {\n errorUtil.errToObj;\n return new _ZodObject({\n ...this._def,\n unknownKeys: "strict",\n ...message !== void 0 ? {\n errorMap: (issue, ctx) => {\n const defaultError = this._def.errorMap?.(issue, ctx).message ?? ctx.defaultError;\n if (issue.code === "unrecognized_keys")\n return {\n message: errorUtil.errToObj(message).message ?? defaultError\n };\n return {\n message: defaultError\n };\n }\n } : {}\n });\n }\n strip() {\n return new _ZodObject({\n ...this._def,\n unknownKeys: "strip"\n });\n }\n passthrough() {\n return new _ZodObject({\n ...this._def,\n unknownKeys: "passthrough"\n });\n }\n // const AugmentFactory =\n // <Def extends ZodObjectDef>(def: Def) =>\n // <Augmentation extends ZodRawShape>(\n // augmentation: Augmentation\n // ): ZodObject<\n // extendShape<ReturnType<Def["shape"]>, Augmentation>,\n // Def["unknownKeys"],\n // Def["catchall"]\n // > => {\n // return new ZodObject({\n // ...def,\n // shape: () => ({\n // ...def.shape(),\n // ...augmentation,\n // }),\n // }) as any;\n // };\n extend(augmentation) {\n return new _ZodObject({\n ...this._def,\n shape: () => ({\n ...this._def.shape(),\n ...augmentation\n })\n });\n }\n /**\n * Prior to zod@1.0.12 there was a bug in the\n * inferred type of merged objects. Please\n * upgrade if you are experiencing issues.\n */\n merge(merging) {\n const merged = new _ZodObject({\n unknownKeys: merging._def.unknownKeys,\n catchall: merging._def.catchall,\n shape: () => ({\n ...this._def.shape(),\n ...merging._def.shape()\n }),\n typeName: ZodFirstPartyTypeKind.ZodObject\n });\n return merged;\n }\n // merge<\n // Incoming extends AnyZodObject,\n // Augmentation extends Incoming["shape"],\n // NewOutput extends {\n // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation\n // ? Augmentation[k]["_output"]\n // : k extends keyof Output\n // ? Output[k]\n // : never;\n // },\n // NewInput extends {\n // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation\n // ? Augmentation[k]["_input"]\n // : k extends keyof Input\n // ? Input[k]\n // : never;\n // }\n // >(\n // merging: Incoming\n // ): ZodObject<\n // extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,\n // Incoming["_def"]["unknownKeys"],\n // Incoming["_def"]["catchall"],\n // NewOutput,\n // NewInput\n // > {\n // const merged: any = new ZodObject({\n // unknownKeys: merging._def.unknownKeys,\n // catchall: merging._def.catchall,\n // shape: () =>\n // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),\n // typeName: ZodFirstPartyTypeKind.ZodObject,\n // }) as any;\n // return merged;\n // }\n setKey(key, schema) {\n return this.augment({ [key]: schema });\n }\n // merge<Incoming extends AnyZodObject>(\n // merging: Incoming\n // ): //ZodObject<T & Incoming["_shape"], UnknownKeys, Catchall> = (merging) => {\n // ZodObject<\n // extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,\n // Incoming["_def"]["unknownKeys"],\n // Incoming["_def"]["catchall"]\n // > {\n // // const mergedShape = objectUtil.mergeShapes(\n // // this._def.shape(),\n // // merging._def.shape()\n // // );\n // const merged: any = new ZodObject({\n // unknownKeys: merging._def.unknownKeys,\n // catchall: merging._def.catchall,\n // shape: () =>\n // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),\n // typeName: ZodFirstPartyTypeKind.ZodObject,\n // }) as any;\n // return merged;\n // }\n catchall(index) {\n return new _ZodObject({\n ...this._def,\n catchall: index\n });\n }\n pick(mask) {\n const shape = {};\n for (const key of util.objectKeys(mask)) {\n if (mask[key] && this.shape[key]) {\n shape[key] = this.shape[key];\n }\n }\n return new _ZodObject({\n ...this._def,\n shape: () => shape\n });\n }\n omit(mask) {\n const shape = {};\n for (const key of util.objectKeys(this.shape)) {\n if (!mask[key]) {\n shape[key] = this.shape[key];\n }\n }\n return new _ZodObject({\n ...this._def,\n shape: () => shape\n });\n }\n /**\n * @deprecated\n */\n deepPartial() {\n return deepPartialify(this);\n }\n partial(mask) {\n const newShape = {};\n for (const key of util.objectKeys(this.shape)) {\n const fieldSchema = this.shape[key];\n if (mask && !mask[key]) {\n newShape[key] = fieldSchema;\n } else {\n newShape[key] = fieldSchema.optional();\n }\n }\n return new _ZodObject({\n ...this._def,\n shape: () => newShape\n });\n }\n required(mask) {\n const newShape = {};\n for (const key of util.objectKeys(this.shape)) {\n if (mask && !mask[key]) {\n newShape[key] = this.shape[key];\n } else {\n const fieldSchema = this.shape[key];\n let newField = fieldSchema;\n while (newField instanceof ZodOptional) {\n newField = newField._def.innerType;\n }\n newShape[key] = newField;\n }\n }\n return new _ZodObject({\n ...this._def,\n shape: () => newShape\n });\n }\n keyof() {\n return createZodEnum(util.objectKeys(this.shape));\n }\n};\nZodObject.create = (shape, params) => {\n return new ZodObject({\n shape: () => shape,\n unknownKeys: "strip",\n catchall: ZodNever.create(),\n typeName: ZodFirstPartyTypeKind.ZodObject,\n ...processCreateParams(params)\n });\n};\nZodObject.strictCreate = (shape, params) => {\n return new ZodObject({\n shape: () => shape,\n unknownKeys: "strict",\n catchall: ZodNever.create(),\n typeName: ZodFirstPartyTypeKind.ZodObject,\n ...processCreateParams(params)\n });\n};\nZodObject.lazycreate = (shape, params) => {\n return new ZodObject({\n shape,\n unknownKeys: "strip",\n catchall: ZodNever.create(),\n typeName: ZodFirstPartyTypeKind.ZodObject,\n ...processCreateParams(params)\n });\n};\nvar ZodUnion = class extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n const options = this._def.options;\n function handleResults(results) {\n for (const result of results) {\n if (result.result.status === "valid") {\n return result.result;\n }\n }\n for (const result of results) {\n if (result.result.status === "dirty") {\n ctx.common.issues.push(...result.ctx.common.issues);\n return result.result;\n }\n }\n const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues));\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_union,\n unionErrors\n });\n return INVALID;\n }\n if (ctx.common.async) {\n return Promise.all(options.map(async (option) => {\n const childCtx = {\n ...ctx,\n common: {\n ...ctx.common,\n issues: []\n },\n parent: null\n };\n return {\n result: await option._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: childCtx\n }),\n ctx: childCtx\n };\n })).then(handleResults);\n } else {\n let dirty = void 0;\n const issues = [];\n for (const option of options) {\n const childCtx = {\n ...ctx,\n common: {\n ...ctx.common,\n issues: []\n },\n parent: null\n };\n const result = option._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: childCtx\n });\n if (result.status === "valid") {\n return result;\n } else if (result.status === "dirty" && !dirty) {\n dirty = { result, ctx: childCtx };\n }\n if (childCtx.common.issues.length) {\n issues.push(childCtx.common.issues);\n }\n }\n if (dirty) {\n ctx.common.issues.push(...dirty.ctx.common.issues);\n return dirty.result;\n }\n const unionErrors = issues.map((issues2) => new ZodError(issues2));\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_union,\n unionErrors\n });\n return INVALID;\n }\n }\n get options() {\n return this._def.options;\n }\n};\nZodUnion.create = (types, params) => {\n return new ZodUnion({\n options: types,\n typeName: ZodFirstPartyTypeKind.ZodUnion,\n ...processCreateParams(params)\n });\n};\nvar getDiscriminator = (type) => {\n if (type instanceof ZodLazy) {\n return getDiscriminator(type.schema);\n } else if (type instanceof ZodEffects) {\n return getDiscriminator(type.innerType());\n } else if (type instanceof ZodLiteral) {\n return [type.value];\n } else if (type instanceof ZodEnum) {\n return type.options;\n } else if (type instanceof ZodNativeEnum) {\n return util.objectValues(type.enum);\n } else if (type instanceof ZodDefault) {\n return getDiscriminator(type._def.innerType);\n } else if (type instanceof ZodUndefined) {\n return [void 0];\n } else if (type instanceof ZodNull) {\n return [null];\n } else if (type instanceof ZodOptional) {\n return [void 0, ...getDiscriminator(type.unwrap())];\n } else if (type instanceof ZodNullable) {\n return [null, ...getDiscriminator(type.unwrap())];\n } else if (type instanceof ZodBranded) {\n return getDiscriminator(type.unwrap());\n } else if (type instanceof ZodReadonly) {\n return getDiscriminator(type.unwrap());\n } else if (type instanceof ZodCatch) {\n return getDiscriminator(type._def.innerType);\n } else {\n return [];\n }\n};\nvar ZodDiscriminatedUnion = class _ZodDiscriminatedUnion extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.object) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.object,\n received: ctx.parsedType\n });\n return INVALID;\n }\n const discriminator = this.discriminator;\n const discriminatorValue = ctx.data[discriminator];\n const option = this.optionsMap.get(discriminatorValue);\n if (!option) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_union_discriminator,\n options: Array.from(this.optionsMap.keys()),\n path: [discriminator]\n });\n return INVALID;\n }\n if (ctx.common.async) {\n return option._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx\n });\n } else {\n return option._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx\n });\n }\n }\n get discriminator() {\n return this._def.discriminator;\n }\n get options() {\n return this._def.options;\n }\n get optionsMap() {\n return this._def.optionsMap;\n }\n /**\n * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor.\n * However, it only allows a union of objects, all of which need to share a discriminator property. This property must\n * have a different value for each object in the union.\n * @param discriminator the name of the discriminator property\n * @param types an array of object schemas\n * @param params\n */\n static create(discriminator, options, params) {\n const optionsMap = /* @__PURE__ */ new Map();\n for (const type of options) {\n const discriminatorValues = getDiscriminator(type.shape[discriminator]);\n if (!discriminatorValues.length) {\n throw new Error(`A discriminator value for key \\`${discriminator}\\` could not be extracted from all schema options`);\n }\n for (const value of discriminatorValues) {\n if (optionsMap.has(value)) {\n throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`);\n }\n optionsMap.set(value, type);\n }\n }\n return new _ZodDiscriminatedUnion({\n typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion,\n discriminator,\n options,\n optionsMap,\n ...processCreateParams(params)\n });\n }\n};\nfunction mergeValues(a, b) {\n const aType = getParsedType(a);\n const bType = getParsedType(b);\n if (a === b) {\n return { valid: true, data: a };\n } else if (aType === ZodParsedType.object && bType === ZodParsedType.object) {\n const bKeys = util.objectKeys(b);\n const sharedKeys = util.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1);\n const newObj = { ...a, ...b };\n for (const key of sharedKeys) {\n const sharedValue = mergeValues(a[key], b[key]);\n if (!sharedValue.valid) {\n return { valid: false };\n }\n newObj[key] = sharedValue.data;\n }\n return { valid: true, data: newObj };\n } else if (aType === ZodParsedType.array && bType === ZodParsedType.array) {\n if (a.length !== b.length) {\n return { valid: false };\n }\n const newArray = [];\n for (let index = 0; index < a.length; index++) {\n const itemA = a[index];\n const itemB = b[index];\n const sharedValue = mergeValues(itemA, itemB);\n if (!sharedValue.valid) {\n return { valid: false };\n }\n newArray.push(sharedValue.data);\n }\n return { valid: true, data: newArray };\n } else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a === +b) {\n return { valid: true, data: a };\n } else {\n return { valid: false };\n }\n}\nvar ZodIntersection = class extends ZodType {\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n const handleParsed = (parsedLeft, parsedRight) => {\n if (isAborted(parsedLeft) || isAborted(parsedRight)) {\n return INVALID;\n }\n const merged = mergeValues(parsedLeft.value, parsedRight.value);\n if (!merged.valid) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_intersection_types\n });\n return INVALID;\n }\n if (isDirty(parsedLeft) || isDirty(parsedRight)) {\n status.dirty();\n }\n return { status: status.value, value: merged.data };\n };\n if (ctx.common.async) {\n return Promise.all([\n this._def.left._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx\n }),\n this._def.right._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx\n })\n ]).then(([left, right]) => handleParsed(left, right));\n } else {\n return handleParsed(this._def.left._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx\n }), this._def.right._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx\n }));\n }\n }\n};\nZodIntersection.create = (left, right, params) => {\n return new ZodIntersection({\n left,\n right,\n typeName: ZodFirstPartyTypeKind.ZodIntersection,\n ...processCreateParams(params)\n });\n};\nvar ZodTuple = class _ZodTuple extends ZodType {\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.array) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.array,\n received: ctx.parsedType\n });\n return INVALID;\n }\n if (ctx.data.length < this._def.items.length) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: this._def.items.length,\n inclusive: true,\n exact: false,\n type: "array"\n });\n return INVALID;\n }\n const rest = this._def.rest;\n if (!rest && ctx.data.length > this._def.items.length) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: this._def.items.length,\n inclusive: true,\n exact: false,\n type: "array"\n });\n status.dirty();\n }\n const items = [...ctx.data].map((item, itemIndex) => {\n const schema = this._def.items[itemIndex] || this._def.rest;\n if (!schema)\n return null;\n return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex));\n }).filter((x) => !!x);\n if (ctx.common.async) {\n return Promise.all(items).then((results) => {\n return ParseStatus.mergeArray(status, results);\n });\n } else {\n return ParseStatus.mergeArray(status, items);\n }\n }\n get items() {\n return this._def.items;\n }\n rest(rest) {\n return new _ZodTuple({\n ...this._def,\n rest\n });\n }\n};\nZodTuple.create = (schemas, params) => {\n if (!Array.isArray(schemas)) {\n throw new Error("You must pass an array of schemas to z.tuple([ ... ])");\n }\n return new ZodTuple({\n items: schemas,\n typeName: ZodFirstPartyTypeKind.ZodTuple,\n rest: null,\n ...processCreateParams(params)\n });\n};\nvar ZodRecord = class _ZodRecord extends ZodType {\n get keySchema() {\n return this._def.keyType;\n }\n get valueSchema() {\n return this._def.valueType;\n }\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.object) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.object,\n received: ctx.parsedType\n });\n return INVALID;\n }\n const pairs = [];\n const keyType = this._def.keyType;\n const valueType = this._def.valueType;\n for (const key in ctx.data) {\n pairs.push({\n key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)),\n value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)),\n alwaysSet: key in ctx.data\n });\n }\n if (ctx.common.async) {\n return ParseStatus.mergeObjectAsync(status, pairs);\n } else {\n return ParseStatus.mergeObjectSync(status, pairs);\n }\n }\n get element() {\n return this._def.valueType;\n }\n static create(first, second, third) {\n if (second instanceof ZodType) {\n return new _ZodRecord({\n keyType: first,\n valueType: second,\n typeName: ZodFirstPartyTypeKind.ZodRecord,\n ...processCreateParams(third)\n });\n }\n return new _ZodRecord({\n keyType: ZodString.create(),\n valueType: first,\n typeName: ZodFirstPartyTypeKind.ZodRecord,\n ...processCreateParams(second)\n });\n }\n};\nvar ZodMap = class extends ZodType {\n get keySchema() {\n return this._def.keyType;\n }\n get valueSchema() {\n return this._def.valueType;\n }\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.map) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.map,\n received: ctx.parsedType\n });\n return INVALID;\n }\n const keyType = this._def.keyType;\n const valueType = this._def.valueType;\n const pairs = [...ctx.data.entries()].map(([key, value], index) => {\n return {\n key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])),\n value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"]))\n };\n });\n if (ctx.common.async) {\n const finalMap = /* @__PURE__ */ new Map();\n return Promise.resolve().then(async () => {\n for (const pair of pairs) {\n const key = await pair.key;\n const value = await pair.value;\n if (key.status === "aborted" || value.status === "aborted") {\n return INVALID;\n }\n if (key.status === "dirty" || value.status === "dirty") {\n status.dirty();\n }\n finalMap.set(key.value, value.value);\n }\n return { status: status.value, value: finalMap };\n });\n } else {\n const finalMap = /* @__PURE__ */ new Map();\n for (const pair of pairs) {\n const key = pair.key;\n const value = pair.value;\n if (key.status === "aborted" || value.status === "aborted") {\n return INVALID;\n }\n if (key.status === "dirty" || value.status === "dirty") {\n status.dirty();\n }\n finalMap.set(key.value, value.value);\n }\n return { status: status.value, value: finalMap };\n }\n }\n};\nZodMap.create = (keyType, valueType, params) => {\n return new ZodMap({\n valueType,\n keyType,\n typeName: ZodFirstPartyTypeKind.ZodMap,\n ...processCreateParams(params)\n });\n};\nvar ZodSet = class _ZodSet extends ZodType {\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.set) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.set,\n received: ctx.parsedType\n });\n return INVALID;\n }\n const def = this._def;\n if (def.minSize !== null) {\n if (ctx.data.size < def.minSize.value) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: def.minSize.value,\n type: "set",\n inclusive: true,\n exact: false,\n message: def.minSize.message\n });\n status.dirty();\n }\n }\n if (def.maxSize !== null) {\n if (ctx.data.size > def.maxSize.value) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: def.maxSize.value,\n type: "set",\n inclusive: true,\n exact: false,\n message: def.maxSize.message\n });\n status.dirty();\n }\n }\n const valueType = this._def.valueType;\n function finalizeSet(elements2) {\n const parsedSet = /* @__PURE__ */ new Set();\n for (const element of elements2) {\n if (element.status === "aborted")\n return INVALID;\n if (element.status === "dirty")\n status.dirty();\n parsedSet.add(element.value);\n }\n return { status: status.value, value: parsedSet };\n }\n const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i)));\n if (ctx.common.async) {\n return Promise.all(elements).then((elements2) => finalizeSet(elements2));\n } else {\n return finalizeSet(elements);\n }\n }\n min(minSize, message) {\n return new _ZodSet({\n ...this._def,\n minSize: { value: minSize, message: errorUtil.toString(message) }\n });\n }\n max(maxSize, message) {\n return new _ZodSet({\n ...this._def,\n maxSize: { value: maxSize, message: errorUtil.toString(message) }\n });\n }\n size(size, message) {\n return this.min(size, message).max(size, message);\n }\n nonempty(message) {\n return this.min(1, message);\n }\n};\nZodSet.create = (valueType, params) => {\n return new ZodSet({\n valueType,\n minSize: null,\n maxSize: null,\n typeName: ZodFirstPartyTypeKind.ZodSet,\n ...processCreateParams(params)\n });\n};\nvar ZodFunction = class _ZodFunction extends ZodType {\n constructor() {\n super(...arguments);\n this.validate = this.implement;\n }\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.function) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.function,\n received: ctx.parsedType\n });\n return INVALID;\n }\n function makeArgsIssue(args, error) {\n return makeIssue({\n data: args,\n path: ctx.path,\n errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x) => !!x),\n issueData: {\n code: ZodIssueCode.invalid_arguments,\n argumentsError: error\n }\n });\n }\n function makeReturnsIssue(returns, error) {\n return makeIssue({\n data: returns,\n path: ctx.path,\n errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x) => !!x),\n issueData: {\n code: ZodIssueCode.invalid_return_type,\n returnTypeError: error\n }\n });\n }\n const params = { errorMap: ctx.common.contextualErrorMap };\n const fn = ctx.data;\n if (this._def.returns instanceof ZodPromise) {\n const me = this;\n return OK(async function(...args) {\n const error = new ZodError([]);\n const parsedArgs = await me._def.args.parseAsync(args, params).catch((e) => {\n error.addIssue(makeArgsIssue(args, e));\n throw error;\n });\n const result = await Reflect.apply(fn, this, parsedArgs);\n const parsedReturns = await me._def.returns._def.type.parseAsync(result, params).catch((e) => {\n error.addIssue(makeReturnsIssue(result, e));\n throw error;\n });\n return parsedReturns;\n });\n } else {\n const me = this;\n return OK(function(...args) {\n const parsedArgs = me._def.args.safeParse(args, params);\n if (!parsedArgs.success) {\n throw new ZodError([makeArgsIssue(args, parsedArgs.error)]);\n }\n const result = Reflect.apply(fn, this, parsedArgs.data);\n const parsedReturns = me._def.returns.safeParse(result, params);\n if (!parsedReturns.success) {\n throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]);\n }\n return parsedReturns.data;\n });\n }\n }\n parameters() {\n return this._def.args;\n }\n returnType() {\n return this._def.returns;\n }\n args(...items) {\n return new _ZodFunction({\n ...this._def,\n args: ZodTuple.create(items).rest(ZodUnknown.create())\n });\n }\n returns(returnType) {\n return new _ZodFunction({\n ...this._def,\n returns: returnType\n });\n }\n implement(func) {\n const validatedFunc = this.parse(func);\n return validatedFunc;\n }\n strictImplement(func) {\n const validatedFunc = this.parse(func);\n return validatedFunc;\n }\n static create(args, returns, params) {\n return new _ZodFunction({\n args: args ? args : ZodTuple.create([]).rest(ZodUnknown.create()),\n returns: returns || ZodUnknown.create(),\n typeName: ZodFirstPartyTypeKind.ZodFunction,\n ...processCreateParams(params)\n });\n }\n};\nvar ZodLazy = class extends ZodType {\n get schema() {\n return this._def.getter();\n }\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n const lazySchema = this._def.getter();\n return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx });\n }\n};\nZodLazy.create = (getter, params) => {\n return new ZodLazy({\n getter,\n typeName: ZodFirstPartyTypeKind.ZodLazy,\n ...processCreateParams(params)\n });\n};\nvar ZodLiteral = class extends ZodType {\n _parse(input) {\n if (input.data !== this._def.value) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n received: ctx.data,\n code: ZodIssueCode.invalid_literal,\n expected: this._def.value\n });\n return INVALID;\n }\n return { status: "valid", value: input.data };\n }\n get value() {\n return this._def.value;\n }\n};\nZodLiteral.create = (value, params) => {\n return new ZodLiteral({\n value,\n typeName: ZodFirstPartyTypeKind.ZodLiteral,\n ...processCreateParams(params)\n });\n};\nfunction createZodEnum(values, params) {\n return new ZodEnum({\n values,\n typeName: ZodFirstPartyTypeKind.ZodEnum,\n ...processCreateParams(params)\n });\n}\nvar ZodEnum = class _ZodEnum extends ZodType {\n _parse(input) {\n if (typeof input.data !== "string") {\n const ctx = this._getOrReturnCtx(input);\n const expectedValues = this._def.values;\n addIssueToContext(ctx, {\n expected: util.joinValues(expectedValues),\n received: ctx.parsedType,\n code: ZodIssueCode.invalid_type\n });\n return INVALID;\n }\n if (!this._cache) {\n this._cache = new Set(this._def.values);\n }\n if (!this._cache.has(input.data)) {\n const ctx = this._getOrReturnCtx(input);\n const expectedValues = this._def.values;\n addIssueToContext(ctx, {\n received: ctx.data,\n code: ZodIssueCode.invalid_enum_value,\n options: expectedValues\n });\n return INVALID;\n }\n return OK(input.data);\n }\n get options() {\n return this._def.values;\n }\n get enum() {\n const enumValues = {};\n for (const val of this._def.values) {\n enumValues[val] = val;\n }\n return enumValues;\n }\n get Values() {\n const enumValues = {};\n for (const val of this._def.values) {\n enumValues[val] = val;\n }\n return enumValues;\n }\n get Enum() {\n const enumValues = {};\n for (const val of this._def.values) {\n enumValues[val] = val;\n }\n return enumValues;\n }\n extract(values, newDef = this._def) {\n return _ZodEnum.create(values, {\n ...this._def,\n ...newDef\n });\n }\n exclude(values, newDef = this._def) {\n return _ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), {\n ...this._def,\n ...newDef\n });\n }\n};\nZodEnum.create = createZodEnum;\nvar ZodNativeEnum = class extends ZodType {\n _parse(input) {\n const nativeEnumValues = util.getValidEnumValues(this._def.values);\n const ctx = this._getOrReturnCtx(input);\n if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) {\n const expectedValues = util.objectValues(nativeEnumValues);\n addIssueToContext(ctx, {\n expected: util.joinValues(expectedValues),\n received: ctx.parsedType,\n code: ZodIssueCode.invalid_type\n });\n return INVALID;\n }\n if (!this._cache) {\n this._cache = new Set(util.getValidEnumValues(this._def.values));\n }\n if (!this._cache.has(input.data)) {\n const expectedValues = util.objectValues(nativeEnumValues);\n addIssueToContext(ctx, {\n received: ctx.data,\n code: ZodIssueCode.invalid_enum_value,\n options: expectedValues\n });\n return INVALID;\n }\n return OK(input.data);\n }\n get enum() {\n return this._def.values;\n }\n};\nZodNativeEnum.create = (values, params) => {\n return new ZodNativeEnum({\n values,\n typeName: ZodFirstPartyTypeKind.ZodNativeEnum,\n ...processCreateParams(params)\n });\n};\nvar ZodPromise = class extends ZodType {\n unwrap() {\n return this._def.type;\n }\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.promise,\n received: ctx.parsedType\n });\n return INVALID;\n }\n const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data);\n return OK(promisified.then((data) => {\n return this._def.type.parseAsync(data, {\n path: ctx.path,\n errorMap: ctx.common.contextualErrorMap\n });\n }));\n }\n};\nZodPromise.create = (schema, params) => {\n return new ZodPromise({\n type: schema,\n typeName: ZodFirstPartyTypeKind.ZodPromise,\n ...processCreateParams(params)\n });\n};\nvar ZodEffects = class extends ZodType {\n innerType() {\n return this._def.schema;\n }\n sourceType() {\n return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects ? this._def.schema.sourceType() : this._def.schema;\n }\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n const effect = this._def.effect || null;\n const checkCtx = {\n addIssue: (arg) => {\n addIssueToContext(ctx, arg);\n if (arg.fatal) {\n status.abort();\n } else {\n status.dirty();\n }\n },\n get path() {\n return ctx.path;\n }\n };\n checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx);\n if (effect.type === "preprocess") {\n const processed = effect.transform(ctx.data, checkCtx);\n if (ctx.common.async) {\n return Promise.resolve(processed).then(async (processed2) => {\n if (status.value === "aborted")\n return INVALID;\n const result = await this._def.schema._parseAsync({\n data: processed2,\n path: ctx.path,\n parent: ctx\n });\n if (result.status === "aborted")\n return INVALID;\n if (result.status === "dirty")\n return DIRTY(result.value);\n if (status.value === "dirty")\n return DIRTY(result.value);\n return result;\n });\n } else {\n if (status.value === "aborted")\n return INVALID;\n const result = this._def.schema._parseSync({\n data: processed,\n path: ctx.path,\n parent: ctx\n });\n if (result.status === "aborted")\n return INVALID;\n if (result.status === "dirty")\n return DIRTY(result.value);\n if (status.value === "dirty")\n return DIRTY(result.value);\n return result;\n }\n }\n if (effect.type === "refinement") {\n const executeRefinement = (acc) => {\n const result = effect.refinement(acc, checkCtx);\n if (ctx.common.async) {\n return Promise.resolve(result);\n }\n if (result instanceof Promise) {\n throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");\n }\n return acc;\n };\n if (ctx.common.async === false) {\n const inner = this._def.schema._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx\n });\n if (inner.status === "aborted")\n return INVALID;\n if (inner.status === "dirty")\n status.dirty();\n executeRefinement(inner.value);\n return { status: status.value, value: inner.value };\n } else {\n return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => {\n if (inner.status === "aborted")\n return INVALID;\n if (inner.status === "dirty")\n status.dirty();\n return executeRefinement(inner.value).then(() => {\n return { status: status.value, value: inner.value };\n });\n });\n }\n }\n if (effect.type === "transform") {\n if (ctx.common.async === false) {\n const base = this._def.schema._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx\n });\n if (!isValid(base))\n return INVALID;\n const result = effect.transform(base.value, checkCtx);\n if (result instanceof Promise) {\n throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);\n }\n return { status: status.value, value: result };\n } else {\n return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => {\n if (!isValid(base))\n return INVALID;\n return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({\n status: status.value,\n value: result\n }));\n });\n }\n }\n util.assertNever(effect);\n }\n};\nZodEffects.create = (schema, effect, params) => {\n return new ZodEffects({\n schema,\n typeName: ZodFirstPartyTypeKind.ZodEffects,\n effect,\n ...processCreateParams(params)\n });\n};\nZodEffects.createWithPreprocess = (preprocess, schema, params) => {\n return new ZodEffects({\n schema,\n effect: { type: "preprocess", transform: preprocess },\n typeName: ZodFirstPartyTypeKind.ZodEffects,\n ...processCreateParams(params)\n });\n};\nvar ZodOptional = class extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType === ZodParsedType.undefined) {\n return OK(void 0);\n }\n return this._def.innerType._parse(input);\n }\n unwrap() {\n return this._def.innerType;\n }\n};\nZodOptional.create = (type, params) => {\n return new ZodOptional({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodOptional,\n ...processCreateParams(params)\n });\n};\nvar ZodNullable = class extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType === ZodParsedType.null) {\n return OK(null);\n }\n return this._def.innerType._parse(input);\n }\n unwrap() {\n return this._def.innerType;\n }\n};\nZodNullable.create = (type, params) => {\n return new ZodNullable({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodNullable,\n ...processCreateParams(params)\n });\n};\nvar ZodDefault = class extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n let data = ctx.data;\n if (ctx.parsedType === ZodParsedType.undefined) {\n data = this._def.defaultValue();\n }\n return this._def.innerType._parse({\n data,\n path: ctx.path,\n parent: ctx\n });\n }\n removeDefault() {\n return this._def.innerType;\n }\n};\nZodDefault.create = (type, params) => {\n return new ZodDefault({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodDefault,\n defaultValue: typeof params.default === "function" ? params.default : () => params.default,\n ...processCreateParams(params)\n });\n};\nvar ZodCatch = class extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n const newCtx = {\n ...ctx,\n common: {\n ...ctx.common,\n issues: []\n }\n };\n const result = this._def.innerType._parse({\n data: newCtx.data,\n path: newCtx.path,\n parent: {\n ...newCtx\n }\n });\n if (isAsync(result)) {\n return result.then((result2) => {\n return {\n status: "valid",\n value: result2.status === "valid" ? result2.value : this._def.catchValue({\n get error() {\n return new ZodError(newCtx.common.issues);\n },\n input: newCtx.data\n })\n };\n });\n } else {\n return {\n status: "valid",\n value: result.status === "valid" ? result.value : this._def.catchValue({\n get error() {\n return new ZodError(newCtx.common.issues);\n },\n input: newCtx.data\n })\n };\n }\n }\n removeCatch() {\n return this._def.innerType;\n }\n};\nZodCatch.create = (type, params) => {\n return new ZodCatch({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodCatch,\n catchValue: typeof params.catch === "function" ? params.catch : () => params.catch,\n ...processCreateParams(params)\n });\n};\nvar ZodNaN = class extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.nan) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.nan,\n received: ctx.parsedType\n });\n return INVALID;\n }\n return { status: "valid", value: input.data };\n }\n};\nZodNaN.create = (params) => {\n return new ZodNaN({\n typeName: ZodFirstPartyTypeKind.ZodNaN,\n ...processCreateParams(params)\n });\n};\nvar BRAND = /* @__PURE__ */ Symbol("zod_brand");\nvar ZodBranded = class extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n const data = ctx.data;\n return this._def.type._parse({\n data,\n path: ctx.path,\n parent: ctx\n });\n }\n unwrap() {\n return this._def.type;\n }\n};\nvar ZodPipeline = class _ZodPipeline extends ZodType {\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.common.async) {\n const handleAsync = async () => {\n const inResult = await this._def.in._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx\n });\n if (inResult.status === "aborted")\n return INVALID;\n if (inResult.status === "dirty") {\n status.dirty();\n return DIRTY(inResult.value);\n } else {\n return this._def.out._parseAsync({\n data: inResult.value,\n path: ctx.path,\n parent: ctx\n });\n }\n };\n return handleAsync();\n } else {\n const inResult = this._def.in._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx\n });\n if (inResult.status === "aborted")\n return INVALID;\n if (inResult.status === "dirty") {\n status.dirty();\n return {\n status: "dirty",\n value: inResult.value\n };\n } else {\n return this._def.out._parseSync({\n data: inResult.value,\n path: ctx.path,\n parent: ctx\n });\n }\n }\n }\n static create(a, b) {\n return new _ZodPipeline({\n in: a,\n out: b,\n typeName: ZodFirstPartyTypeKind.ZodPipeline\n });\n }\n};\nvar ZodReadonly = class extends ZodType {\n _parse(input) {\n const result = this._def.innerType._parse(input);\n const freeze = (data) => {\n if (isValid(data)) {\n data.value = Object.freeze(data.value);\n }\n return data;\n };\n return isAsync(result) ? result.then((data) => freeze(data)) : freeze(result);\n }\n unwrap() {\n return this._def.innerType;\n }\n};\nZodReadonly.create = (type, params) => {\n return new ZodReadonly({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodReadonly,\n ...processCreateParams(params)\n });\n};\nfunction cleanParams(params, data) {\n const p = typeof params === "function" ? params(data) : typeof params === "string" ? { message: params } : params;\n const p2 = typeof p === "string" ? { message: p } : p;\n return p2;\n}\nfunction custom(check, _params = {}, fatal) {\n if (check)\n return ZodAny.create().superRefine((data, ctx) => {\n const r = check(data);\n if (r instanceof Promise) {\n return r.then((r2) => {\n if (!r2) {\n const params = cleanParams(_params, data);\n const _fatal = params.fatal ?? fatal ?? true;\n ctx.addIssue({ code: "custom", ...params, fatal: _fatal });\n }\n });\n }\n if (!r) {\n const params = cleanParams(_params, data);\n const _fatal = params.fatal ?? fatal ?? true;\n ctx.addIssue({ code: "custom", ...params, fatal: _fatal });\n }\n return;\n });\n return ZodAny.create();\n}\nvar late = {\n object: ZodObject.lazycreate\n};\nvar ZodFirstPartyTypeKind;\n(function(ZodFirstPartyTypeKind2) {\n ZodFirstPartyTypeKind2["ZodString"] = "ZodString";\n ZodFirstPartyTypeKind2["ZodNumber"] = "ZodNumber";\n ZodFirstPartyTypeKind2["ZodNaN"] = "ZodNaN";\n ZodFirstPartyTypeKind2["ZodBigInt"] = "ZodBigInt";\n ZodFirstPartyTypeKind2["ZodBoolean"] = "ZodBoolean";\n ZodFirstPartyTypeKind2["ZodDate"] = "ZodDate";\n ZodFirstPartyTypeKind2["ZodSymbol"] = "ZodSymbol";\n ZodFirstPartyTypeKind2["ZodUndefined"] = "ZodUndefined";\n ZodFirstPartyTypeKind2["ZodNull"] = "ZodNull";\n ZodFirstPartyTypeKind2["ZodAny"] = "ZodAny";\n ZodFirstPartyTypeKind2["ZodUnknown"] = "ZodUnknown";\n ZodFirstPartyTypeKind2["ZodNever"] = "ZodNever";\n ZodFirstPartyTypeKind2["ZodVoid"] = "ZodVoid";\n ZodFirstPartyTypeKind2["ZodArray"] = "ZodArray";\n ZodFirstPartyTypeKind2["ZodObject"] = "ZodObject";\n ZodFirstPartyTypeKind2["ZodUnion"] = "ZodUnion";\n ZodFirstPartyTypeKind2["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion";\n ZodFirstPartyTypeKind2["ZodIntersection"] = "ZodIntersection";\n ZodFirstPartyTypeKind2["ZodTuple"] = "ZodTuple";\n ZodFirstPartyTypeKind2["ZodRecord"] = "ZodRecord";\n ZodFirstPartyTypeKind2["ZodMap"] = "ZodMap";\n ZodFirstPartyTypeKind2["ZodSet"] = "ZodSet";\n ZodFirstPartyTypeKind2["ZodFunction"] = "ZodFunction";\n ZodFirstPartyTypeKind2["ZodLazy"] = "ZodLazy";\n ZodFirstPartyTypeKind2["ZodLiteral"] = "ZodLiteral";\n ZodFirstPartyTypeKind2["ZodEnum"] = "ZodEnum";\n ZodFirstPartyTypeKind2["ZodEffects"] = "ZodEffects";\n ZodFirstPartyTypeKind2["ZodNativeEnum"] = "ZodNativeEnum";\n ZodFirstPartyTypeKind2["ZodOptional"] = "ZodOptional";\n ZodFirstPartyTypeKind2["ZodNullable"] = "ZodNullable";\n ZodFirstPartyTypeKind2["ZodDefault"] = "ZodDefault";\n ZodFirstPartyTypeKind2["ZodCatch"] = "ZodCatch";\n ZodFirstPartyTypeKind2["ZodPromise"] = "ZodPromise";\n ZodFirstPartyTypeKind2["ZodBranded"] = "ZodBranded";\n ZodFirstPartyTypeKind2["ZodPipeline"] = "ZodPipeline";\n ZodFirstPartyTypeKind2["ZodReadonly"] = "ZodReadonly";\n})(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));\nvar instanceOfType = (cls, params = {\n message: `Input not instance of ${cls.name}`\n}) => custom((data) => data instanceof cls, params);\nvar stringType = ZodString.create;\nvar numberType = ZodNumber.create;\nvar nanType = ZodNaN.create;\nvar bigIntType = ZodBigInt.create;\nvar booleanType = ZodBoolean.create;\nvar dateType = ZodDate.create;\nvar symbolType = ZodSymbol.create;\nvar undefinedType = ZodUndefined.create;\nvar nullType = ZodNull.create;\nvar anyType = ZodAny.create;\nvar unknownType = ZodUnknown.create;\nvar neverType = ZodNever.create;\nvar voidType = ZodVoid.create;\nvar arrayType = ZodArray.create;\nvar objectType = ZodObject.create;\nvar strictObjectType = ZodObject.strictCreate;\nvar unionType = ZodUnion.create;\nvar discriminatedUnionType = ZodDiscriminatedUnion.create;\nvar intersectionType = ZodIntersection.create;\nvar tupleType = ZodTuple.create;\nvar recordType = ZodRecord.create;\nvar mapType = ZodMap.create;\nvar setType = ZodSet.create;\nvar functionType = ZodFunction.create;\nvar lazyType = ZodLazy.create;\nvar literalType = ZodLiteral.create;\nvar enumType = ZodEnum.create;\nvar nativeEnumType = ZodNativeEnum.create;\nvar promiseType = ZodPromise.create;\nvar effectsType = ZodEffects.create;\nvar optionalType = ZodOptional.create;\nvar nullableType = ZodNullable.create;\nvar preprocessType = ZodEffects.createWithPreprocess;\nvar pipelineType = ZodPipeline.create;\nvar ostring = () => stringType().optional();\nvar onumber = () => numberType().optional();\nvar oboolean = () => booleanType().optional();\nvar coerce = {\n string: ((arg) => ZodString.create({ ...arg, coerce: true })),\n number: ((arg) => ZodNumber.create({ ...arg, coerce: true })),\n boolean: ((arg) => ZodBoolean.create({\n ...arg,\n coerce: true\n })),\n bigint: ((arg) => ZodBigInt.create({ ...arg, coerce: true })),\n date: ((arg) => ZodDate.create({ ...arg, coerce: true }))\n};\nvar NEVER = INVALID;\n\n// ../../packages/protocol/src/index.ts\nvar RequestBaseSchema = external_exports.object({\n id: external_exports.string().min(1)\n});\nvar ExecuteRequestSchema = RequestBaseSchema.extend({\n type: external_exports.literal("execute"),\n browser: external_exports.string().min(1).default("default"),\n script: external_exports.string(),\n headless: external_exports.boolean().optional(),\n ignoreHTTPSErrors: external_exports.boolean().optional(),\n connect: external_exports.string().min(1).optional(),\n timeoutMs: external_exports.number().int().positive().optional(),\n initScripts: external_exports.array(external_exports.string()).optional(),\n // Optional step label. When the target browser is a session context, the\n // daemon wraps the run in tracing.group(step)/groupEnd and screenshots the\n // active page to the session\'s screenshots/<step>.png after a successful run.\n step: external_exports.string().min(1).max(200).optional()\n});\nvar BrowsersRequestSchema = RequestBaseSchema.extend({\n type: external_exports.literal("browsers")\n});\nvar BrowserStopRequestSchema = RequestBaseSchema.extend({\n type: external_exports.literal("browser-stop"),\n browser: external_exports.string().min(1)\n});\nvar StatusRequestSchema = RequestBaseSchema.extend({\n type: external_exports.literal("status")\n});\nvar InstallRequestSchema = RequestBaseSchema.extend({\n type: external_exports.literal("install")\n});\nvar StopRequestSchema = RequestBaseSchema.extend({\n type: external_exports.literal("stop")\n});\nvar CaptureOptionsSchema = external_exports.object({\n trace: external_exports.boolean().default(true),\n video: external_exports.boolean().default(true),\n har: external_exports.boolean().default(true),\n console: external_exports.boolean().default(true)\n});\nvar SessionIdSchema = external_exports.string().min(1).max(128).regex(/^(?!.*\\.\\.)[A-Za-z0-9._-]+$/, "invalid session id");\nvar SessionStartRequestSchema = RequestBaseSchema.extend({\n type: external_exports.literal("session-start"),\n sessionId: SessionIdSchema,\n name: external_exports.string().min(1).max(200).optional(),\n headless: external_exports.boolean().optional(),\n ignoreHTTPSErrors: external_exports.boolean().optional(),\n capture: CaptureOptionsSchema.default({})\n});\nvar SessionEndRequestSchema = RequestBaseSchema.extend({\n type: external_exports.literal("session-end"),\n sessionId: SessionIdSchema,\n reason: external_exports.enum(["end", "abort"]).default("end")\n});\nvar SessionStatusRequestSchema = RequestBaseSchema.extend({\n type: external_exports.literal("session-status"),\n sessionId: SessionIdSchema\n});\nvar SessionListRequestSchema = RequestBaseSchema.extend({\n type: external_exports.literal("session-list")\n});\nvar RequestSchema = external_exports.discriminatedUnion("type", [\n ExecuteRequestSchema,\n BrowsersRequestSchema,\n BrowserStopRequestSchema,\n StatusRequestSchema,\n InstallRequestSchema,\n StopRequestSchema,\n SessionStartRequestSchema,\n SessionEndRequestSchema,\n SessionStatusRequestSchema,\n SessionListRequestSchema\n]);\nvar ResponseBaseSchema = external_exports.object({\n id: external_exports.string().min(1)\n});\nvar StdoutMessageSchema = ResponseBaseSchema.extend({\n type: external_exports.literal("stdout"),\n data: external_exports.string()\n});\nvar StderrMessageSchema = ResponseBaseSchema.extend({\n type: external_exports.literal("stderr"),\n data: external_exports.string()\n});\nvar CompleteMessageSchema = ResponseBaseSchema.extend({\n type: external_exports.literal("complete"),\n success: external_exports.literal(true)\n});\nvar ErrorMessageSchema = ResponseBaseSchema.extend({\n type: external_exports.literal("error"),\n message: external_exports.string()\n});\nvar ResultMessageSchema = ResponseBaseSchema.extend({\n type: external_exports.literal("result"),\n data: external_exports.unknown()\n});\nvar ResponseSchema = external_exports.discriminatedUnion("type", [\n StdoutMessageSchema,\n StderrMessageSchema,\n CompleteMessageSchema,\n ErrorMessageSchema,\n ResultMessageSchema\n]);\nfunction slugHash(value) {\n let hash = 5381;\n for (let i = 0; i < value.length; i += 1) {\n hash = (hash * 33 + value.charCodeAt(i)) % 2147483647;\n }\n return hash.toString(36);\n}\nfunction sessionStepSlug(step) {\n const base = step.replace(/[^A-Za-z0-9._-]/g, "-").replace(/^-+|-+$/g, "").slice(0, 200) || "step";\n return `${base}-${slugHash(step)}`;\n}\nvar SESSION_TRACE_FILE = "trace.zip";\nvar SESSION_HAR_FILE = "network.har";\nvar SESSION_CONSOLE_FILE = "console.log";\nvar SESSION_VIDEO_DIR = "video";\nvar SESSION_VIDEO_EXT = ".webm";\nvar SESSION_SCREENSHOTS_DIR = "screenshots";\nvar SESSION_SCREENSHOT_EXT = ".png";\nvar DAEMON_RUNTIME_DEPENDENCIES = {\n pino: "^9.5.0",\n playwright: "1.58.2",\n "playwright-core": "1.58.2",\n "quickjs-emscripten": "^0.32.0"\n};\nvar EMBEDDED_PACKAGE_JSON = JSON.stringify(\n {\n name: "canary-runtime",\n private: true,\n type: "module",\n dependencies: DAEMON_RUNTIME_DEPENDENCIES\n },\n null,\n 2\n);\nfunction describeZodError(error) {\n return error.issues.map((issue) => {\n const path7 = issue.path.length > 0 ? issue.path.join(".") : "request";\n return `${path7}: ${issue.message}`;\n }).join("; ");\n}\nfunction extractId(value) {\n if (!value || typeof value !== "object") {\n return;\n }\n const maybeId = value.id;\n return typeof maybeId === "string" && maybeId.length > 0 ? maybeId : void 0;\n}\nfunction parseRequest(line) {\n let parsed;\n try {\n parsed = JSON.parse(line);\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : "Invalid JSON request"\n };\n }\n const result = RequestSchema.safeParse(parsed);\n if (!result.success) {\n const id = extractId(parsed);\n return {\n success: false,\n error: describeZodError(result.error),\n ...id === void 0 ? {} : { id }\n };\n }\n return {\n success: true,\n request: result.data\n };\n}\nfunction serialize(message) {\n return `${JSON.stringify(ResponseSchema.parse(message))}\n`;\n}\n\n// src/browser-manager.ts\nimport { createHash } from "node:crypto";\nimport { mkdir, readFile } from "node:fs/promises";\nimport os from "node:os";\nimport path from "node:path";\nimport {\n chromium\n} from "playwright";\nvar DISCOVERY_PORTS = [9222, 9223, 9224, 9225, 9226, 9227, 9228, 9229];\nvar PROBE_TIMEOUT_MS = 750;\nvar MANUAL_CONNECT_TIMEOUT_MS = 5e3;\nvar PAGE_TITLE_TIMEOUT_MS = 1500;\nvar TARGET_ID_PATTERN = /^[a-f0-9]{16,}$/i;\nfunction isIgnorableFileError(error) {\n const code = error?.code;\n return code === "ENOENT" || code === "ENOTDIR" || code === "EACCES";\n}\nfunction isHttpEndpoint(endpoint) {\n return endpoint.startsWith("http://") || endpoint.startsWith("https://");\n}\nvar BrowserManager = class {\n browsers = /* @__PURE__ */ new Map();\n baseDir;\n dependencies;\n disconnectHandlers = /* @__PURE__ */ new Set();\n constructor(baseDir = path.join(os.homedir(), ".canary", "browsers"), dependencies = {}) {\n this.baseDir = baseDir;\n this.dependencies = {\n connectOverCDP: chromium.connectOverCDP.bind(\n chromium\n ),\n fetch: globalThis.fetch,\n homedir: os.homedir,\n launchPersistentContext: chromium.launchPersistentContext.bind(\n chromium\n ),\n mkdir,\n platform: process.platform,\n readFile,\n ...dependencies\n };\n }\n // Register a callback fired when a managed browser disconnects (crash or\n // external close). SessionManager uses this to reconcile a session whose\n // capture context died out from under it.\n onBrowserDisconnect(handler) {\n this.disconnectHandlers.add(handler);\n }\n async ensureBrowser(name, options = {}) {\n await this.ensureBaseDir();\n const existing = this.browsers.get(name);\n const requestedHeadless = options.headless ?? existing?.headless ?? false;\n const requestedIgnoreHTTPSErrors = options.ignoreHTTPSErrors ?? existing?.ignoreHTTPSErrors ?? false;\n if (existing) {\n if (existing.isSession) {\n return existing;\n }\n const needsRelaunch = existing.type !== "launched" || !existing.browser.isConnected() || options.headless !== void 0 && existing.headless !== requestedHeadless || options.ignoreHTTPSErrors !== void 0 && existing.ignoreHTTPSErrors !== requestedIgnoreHTTPSErrors;\n if (!needsRelaunch) {\n return existing;\n }\n await this.stopBrowser(name);\n }\n return this.launchBrowser(name, {\n headless: requestedHeadless,\n ignoreHTTPSErrors: requestedIgnoreHTTPSErrors\n });\n }\n async autoConnect(name) {\n await this.ensureBaseDir();\n const existing = this.browsers.get(name);\n if (existing?.type === "connected" && existing.browser.isConnected()) {\n return existing;\n }\n if (existing) {\n await this.stopBrowser(name);\n }\n const attemptedEndpoints = /* @__PURE__ */ new Set();\n let lastError;\n const tryEndpoint = async (endpoint) => {\n if (!endpoint || attemptedEndpoints.has(endpoint)) {\n return null;\n }\n attemptedEndpoints.add(endpoint);\n try {\n return await this.openConnectedBrowser(name, endpoint);\n } catch (error) {\n lastError = error;\n return null;\n }\n };\n const devToolsEndpoint = await this.readDevToolsActivePort();\n const devToolsBrowser = await tryEndpoint(devToolsEndpoint);\n if (devToolsBrowser) {\n return devToolsBrowser;\n }\n for (const port of DISCOVERY_PORTS) {\n const endpoint = await this.probePort(port);\n const connectedBrowser = await tryEndpoint(endpoint);\n if (connectedBrowser) {\n return connectedBrowser;\n }\n }\n throw new Error(this.buildAutoConnectError(lastError));\n }\n async connectBrowser(name, endpoint) {\n if (endpoint === "auto") {\n return this.autoConnect(name);\n }\n await this.ensureBaseDir();\n const resolvedEndpoint = await this.resolveEndpoint(endpoint);\n const existing = this.browsers.get(name);\n if (existing) {\n const isSameConnection = existing.type === "connected" && existing.endpoint === resolvedEndpoint && existing.browser.isConnected();\n if (isSameConnection) {\n return existing;\n }\n await this.stopBrowser(name);\n }\n return this.openConnectedBrowser(name, resolvedEndpoint);\n }\n getBrowser(name) {\n const entry = this.browsers.get(name);\n if (!entry?.browser.isConnected()) {\n return;\n }\n return entry;\n }\n async getPage(browserName, pageNameOrId) {\n const entry = this.getBrowserEntry(browserName);\n const existingPage = entry.pages.get(pageNameOrId);\n if (existingPage && !existingPage.isClosed()) {\n return existingPage;\n }\n entry.pages.delete(pageNameOrId);\n if (TARGET_ID_PATTERN.test(pageNameOrId)) {\n const page2 = await this.findPageByTargetId(entry, pageNameOrId);\n if (page2) {\n return page2;\n }\n }\n const page = this.takeInitialBlankPage(entry) ?? await entry.context.newPage();\n this.registerNamedPage(entry, pageNameOrId, page);\n return page;\n }\n newPage(browserName) {\n const entry = this.getBrowserEntry(browserName);\n const initial = this.takeInitialBlankPage(entry);\n return initial ? Promise.resolve(initial) : entry.context.newPage();\n }\n // Scripts dedupe by content (SHA-256). Already-applied scripts are no-ops, so\n // re-issuing the same set across consecutive `execute` requests is safe and\n // does not re-register the script on the context. Hashing is byte-exact:\n // editing a script file (even just whitespace) yields a new hash and a new\n // addInitScript call. Stop the browser to clear all applied scripts.\n async applyInitScripts(browserName, scripts) {\n if (scripts.length === 0) {\n return;\n }\n const entry = this.getBrowserEntry(browserName);\n for (const script of scripts) {\n const hash = createHash("sha256").update(script).digest("hex");\n if (entry.appliedInitScripts.has(hash)) {\n continue;\n }\n await entry.context.addInitScript({ content: script });\n entry.appliedInitScripts.add(hash);\n }\n }\n async listPages(browserName) {\n const entry = this.browsers.get(browserName);\n if (!entry?.browser.isConnected()) {\n return [];\n }\n this.pruneClosedPages(entry);\n const namesByPage = this.getNamedPagesByPage(entry);\n const summaries = [];\n for (const { context, page } of this.getContextPages(entry)) {\n const id = await this.getPageTargetId(context, page);\n if (!id) {\n continue;\n }\n let title = "";\n try {\n title = await this.getPageTitle(page);\n } catch (error) {\n if (page.isClosed()) {\n continue;\n }\n throw error;\n }\n summaries.push({\n id,\n url: page.url(),\n title,\n name: namesByPage.get(page) ?? null\n });\n }\n return summaries;\n }\n async closePage(browserName, pageName) {\n const entry = this.getBrowserEntry(browserName);\n const page = entry.pages.get(pageName);\n if (!page || page.isClosed()) {\n entry.pages.delete(pageName);\n throw new Error(`Page "${browserName}/${pageName}" not found`);\n }\n entry.pages.delete(pageName);\n if (!page.isClosed()) {\n await page.close();\n }\n }\n listBrowsers() {\n return Array.from(this.browsers.values()).filter((entry) => !entry.isSession).map((entry) => {\n this.pruneClosedPages(entry);\n const connected = entry.browser.isConnected();\n let status;\n if (entry.type === "connected") {\n status = connected ? "connected" : "disconnected";\n } else {\n status = connected ? "running" : "disconnected";\n }\n return {\n name: entry.name,\n type: entry.type,\n status,\n pages: this.listNamedPages(entry)\n };\n }).sort((left, right) => left.name.localeCompare(right.name));\n }\n async stopBrowser(name) {\n const entry = this.browsers.get(name);\n if (!entry) {\n return;\n }\n this.browsers.delete(name);\n entry.pages.clear();\n try {\n if (entry.type === "launched") {\n await this.closeLaunchedBrowser(entry);\n } else {\n await entry.browser.close();\n }\n } catch {\n }\n }\n async stopAll() {\n const names = Array.from(this.browsers.keys());\n await Promise.allSettled(names.map(async (name) => this.stopBrowser(name)));\n }\n browserCount() {\n let count = 0;\n for (const entry of this.browsers.values()) {\n if (!entry.isSession) {\n count += 1;\n }\n }\n return count;\n }\n async ensureBaseDir() {\n await this.dependencies.mkdir(this.baseDir, { recursive: true });\n }\n getBrowserEntry(name) {\n const entry = this.browsers.get(name);\n if (!entry?.browser.isConnected()) {\n throw new Error(`Browser "${name}" is not running`);\n }\n return entry;\n }\n // Launch a session-scoped capture context: a dedicated persistent context\n // (isolated profile) configured at launch time with recordVideo / recordHar.\n // The caller (SessionManager) then starts tracing and attaches listeners on\n // the returned entry\'s context.\n launchSessionBrowser(name, options) {\n return this.launchBrowser(name, { ...options, isSession: true });\n }\n // Best-effort screenshot of the most-recently-active page in a browser, used\n // to populate the report\'s per-step timeline. Silent if no page is open; the\n // caller must never let a screenshot failure fail the underlying step.\n async screenshotActivePage(browserName, outPath) {\n const entry = this.browsers.get(browserName);\n if (!entry?.browser.isConnected()) {\n return;\n }\n const pages = this.getContextPages(entry);\n const last = pages.at(-1);\n if (!last) {\n return;\n }\n await this.dependencies.mkdir(path.dirname(outPath), { recursive: true });\n await last.page.screenshot({ path: outPath });\n }\n async launchBrowser(name, options) {\n const profileDir = options.profileDirOverride ?? path.join(this.baseDir, name, "chromium-profile");\n await this.dependencies.mkdir(profileDir, { recursive: true });\n if (options.record?.videoDir) {\n await this.dependencies.mkdir(options.record.videoDir, {\n recursive: true\n });\n }\n const context = await this.dependencies.launchPersistentContext(\n profileDir,\n {\n headless: options.headless,\n viewport: options.headless ? void 0 : null,\n ignoreHTTPSErrors: options.ignoreHTTPSErrors,\n handleSIGINT: false,\n handleSIGTERM: false,\n handleSIGHUP: false,\n ...options.record?.videoDir ? { recordVideo: { dir: options.record.videoDir } } : {},\n ...options.record?.har ? {\n recordHar: {\n path: options.record.har.path,\n content: options.record.har.content\n }\n } : {}\n }\n );\n const browser = context.browser();\n if (!browser) {\n await context.close();\n throw new Error(\n `Playwright did not expose a browser handle for "${name}"`\n );\n }\n const entry = {\n name,\n type: "launched",\n browser,\n context,\n // A persistent context comes up with one about:blank page; reuse it for\n // the first page acquisition rather than orphaning it (see getPage).\n initialBlankPage: context.pages()[0],\n pages: /* @__PURE__ */ new Map(),\n profileDir,\n headless: options.headless,\n ignoreHTTPSErrors: options.ignoreHTTPSErrors,\n isSession: options.isSession ?? false,\n appliedInitScripts: /* @__PURE__ */ new Set()\n };\n this.attachBrowserLifecycle(entry);\n this.browsers.set(name, entry);\n return entry;\n }\n async openConnectedBrowser(name, endpoint) {\n const browser = await this.dependencies.connectOverCDP(endpoint);\n const contexts = browser.contexts();\n for (const browserContext of contexts) {\n browserContext.pages();\n }\n const context = contexts[0] ?? await browser.newContext();\n const entry = {\n name,\n type: "connected",\n browser,\n context,\n pages: /* @__PURE__ */ new Map(),\n endpoint,\n headless: false,\n ignoreHTTPSErrors: false,\n isSession: false,\n appliedInitScripts: /* @__PURE__ */ new Set()\n };\n this.attachBrowserLifecycle(entry);\n this.browsers.set(name, entry);\n return entry;\n }\n attachBrowserLifecycle(entry) {\n entry.browser.on("disconnected", () => {\n const current = this.browsers.get(entry.name);\n if (current !== entry) {\n return;\n }\n entry.pages.clear();\n if (entry.type === "launched") {\n this.browsers.delete(entry.name);\n }\n for (const handler of this.disconnectHandlers) {\n try {\n handler(entry.name);\n } catch {\n }\n }\n });\n }\n async closeLaunchedBrowser(entry) {\n const contexts = this.getBrowserContexts(entry);\n await Promise.allSettled(contexts.map(async (context) => context.close()));\n if (entry.browser.isConnected()) {\n await entry.browser.close().catch(() => void 0);\n }\n }\n async discoverChrome() {\n const devToolsEndpoint = await this.readDevToolsActivePort();\n if (devToolsEndpoint) {\n return devToolsEndpoint;\n }\n for (const port of DISCOVERY_PORTS) {\n const endpoint = await this.probePort(port);\n if (endpoint) {\n return endpoint;\n }\n }\n return null;\n }\n async readDevToolsActivePort(expectedPort) {\n for (const candidate of this.getDevToolsActivePortCandidates()) {\n let contents;\n try {\n contents = await this.dependencies.readFile(candidate, "utf8");\n } catch (error) {\n if (isIgnorableFileError(error)) {\n continue;\n }\n throw error;\n }\n const endpoint = this.parseDevToolsActivePort(contents, expectedPort);\n if (endpoint) {\n return endpoint;\n }\n }\n return null;\n }\n async probePort(port) {\n const endpoint = `http://127.0.0.1:${port}`;\n const result = await this.fetchDebuggerWebSocketUrl(\n endpoint,\n PROBE_TIMEOUT_MS\n );\n if (result.status === "ok") {\n return result.webSocketDebuggerUrl;\n }\n if (result.status === "not-found") {\n return this.readDevToolsActivePort(port);\n }\n return null;\n }\n getDevToolsActivePortCandidates() {\n const homeDir = this.dependencies.homedir();\n switch (this.dependencies.platform) {\n case "darwin":\n return [\n path.join(\n homeDir,\n "Library",\n "Application Support",\n "Google",\n "Chrome",\n "DevToolsActivePort"\n ),\n path.join(\n homeDir,\n "Library",\n "Application Support",\n "Google",\n "Chrome Canary",\n "DevToolsActivePort"\n ),\n path.join(\n homeDir,\n "Library",\n "Application Support",\n "Chromium",\n "DevToolsActivePort"\n ),\n path.join(\n homeDir,\n "Library",\n "Application Support",\n "BraveSoftware",\n "Brave-Browser",\n "DevToolsActivePort"\n )\n ];\n case "linux":\n return [\n path.join(homeDir, ".config", "google-chrome", "DevToolsActivePort"),\n path.join(homeDir, ".config", "chromium", "DevToolsActivePort"),\n path.join(\n homeDir,\n ".config",\n "google-chrome-beta",\n "DevToolsActivePort"\n ),\n path.join(\n homeDir,\n ".config",\n "google-chrome-unstable",\n "DevToolsActivePort"\n ),\n path.join(\n homeDir,\n ".config",\n "BraveSoftware",\n "Brave-Browser",\n "DevToolsActivePort"\n )\n ];\n case "win32":\n return [\n path.join(\n homeDir,\n "AppData",\n "Local",\n "Google",\n "Chrome",\n "User Data",\n "DevToolsActivePort"\n ),\n path.join(\n homeDir,\n "AppData",\n "Local",\n "Google",\n "Chrome Beta",\n "User Data",\n "DevToolsActivePort"\n ),\n path.join(\n homeDir,\n "AppData",\n "Local",\n "Google",\n "Chrome SxS",\n "User Data",\n "DevToolsActivePort"\n ),\n path.join(\n homeDir,\n "AppData",\n "Local",\n "Chromium",\n "User Data",\n "DevToolsActivePort"\n ),\n path.join(\n homeDir,\n "AppData",\n "Local",\n "BraveSoftware",\n "Brave-Browser",\n "User Data",\n "DevToolsActivePort"\n )\n ];\n default:\n return [];\n }\n }\n async resolveEndpoint(endpoint) {\n if (endpoint === "auto") {\n const discoveredEndpoint = await this.discoverChrome();\n if (discoveredEndpoint) {\n return discoveredEndpoint;\n }\n throw new Error(this.buildAutoConnectError());\n }\n if (isHttpEndpoint(endpoint)) {\n const discoveredEndpoint = await this.resolveHttpEndpoint(\n endpoint,\n MANUAL_CONNECT_TIMEOUT_MS\n );\n if (!discoveredEndpoint) {\n throw new Error(this.buildManualConnectError(endpoint));\n }\n return discoveredEndpoint;\n }\n return endpoint;\n }\n async fetchDebuggerWebSocketUrl(endpoint, timeoutMs) {\n let response;\n try {\n response = await this.dependencies.fetch(\n this.toJsonVersionUrl(endpoint),\n {\n headers: {\n accept: "application/json"\n },\n signal: AbortSignal.timeout(timeoutMs)\n }\n );\n } catch {\n return { status: "unavailable" };\n }\n if (response.status === 404) {\n return { status: "not-found" };\n }\n if (!response.ok) {\n return { status: "unavailable" };\n }\n let payload;\n try {\n payload = await response.json();\n } catch {\n return { status: "unavailable" };\n }\n const webSocketDebuggerUrl = typeof payload === "object" && payload !== null ? payload.webSocketDebuggerUrl : void 0;\n return typeof webSocketDebuggerUrl === "string" && webSocketDebuggerUrl.length > 0 ? {\n status: "ok",\n webSocketDebuggerUrl\n } : { status: "unavailable" };\n }\n toJsonVersionUrl(endpoint) {\n const url = new URL(endpoint);\n if (url.pathname !== "/json/version") {\n url.pathname = "/json/version";\n url.search = "";\n url.hash = "";\n }\n return url;\n }\n buildAutoConnectError(lastError) {\n let launchCommand = "google-chrome --remote-debugging-port=9222";\n if (this.dependencies.platform === "darwin") {\n launchCommand = "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome --remote-debugging-port=9222";\n } else if (this.dependencies.platform === "win32") {\n launchCommand = "chrome.exe --remote-debugging-port=9222";\n }\n const details = [\n "Could not auto-discover a running Chrome instance with remote debugging enabled.",\n "Enable Chrome remote debugging at chrome://inspect/#remote-debugging",\n `or launch Chrome with: ${launchCommand}`\n ];\n let lastErrorMessage = null;\n if (lastError instanceof Error) {\n lastErrorMessage = lastError.message;\n } else if (typeof lastError === "string" && lastError.length > 0) {\n lastErrorMessage = lastError;\n }\n if (lastErrorMessage) {\n details.push(`Last connection error: ${lastErrorMessage}`);\n }\n return details.join("\\n");\n }\n async resolveHttpEndpoint(endpoint, timeoutMs) {\n const result = await this.fetchDebuggerWebSocketUrl(endpoint, timeoutMs);\n if (result.status === "ok") {\n return result.webSocketDebuggerUrl;\n }\n if (result.status === "not-found") {\n const port = this.getEndpointPort(endpoint);\n if (port !== null) {\n return this.readDevToolsActivePort(port);\n }\n }\n return null;\n }\n parseDevToolsActivePort(contents, expectedPort) {\n const lines = contents.split(/\\r?\\n/).map((line) => line.trim()).filter((line) => line.length > 0);\n const port = Number.parseInt(lines[0] ?? "", 10);\n const webSocketPath = lines[1] ?? "";\n if (!Number.isInteger(port) || port < 1 || port > 65535) {\n return null;\n }\n if (expectedPort !== void 0 && port !== expectedPort) {\n return null;\n }\n if (!webSocketPath.startsWith("/devtools/browser/")) {\n return null;\n }\n return `ws://127.0.0.1:${port}${webSocketPath}`;\n }\n getEndpointPort(endpoint) {\n let url;\n try {\n url = new URL(endpoint);\n } catch {\n return null;\n }\n let defaultPort = "";\n if (url.protocol === "https:") {\n defaultPort = "443";\n } else if (url.protocol === "http:") {\n defaultPort = "80";\n }\n const rawPort = url.port || defaultPort;\n const port = Number.parseInt(rawPort, 10);\n return Number.isInteger(port) && port > 0 && port <= 65535 ? port : null;\n }\n buildManualConnectError(endpoint) {\n return [\n `Could not resolve a CDP WebSocket endpoint from ${endpoint}.`,\n "If Chrome is using built-in remote debugging, run `canary-browser --connect` without a URL so DevToolsActivePort can be auto-discovered.",\n "Or connect with the exact ws://127.0.0.1:<port>/devtools/browser/... URL from DevToolsActivePort, or launch Chrome with --remote-debugging-port=9222."\n ].join("\\n");\n }\n // Hand out the persistent context\'s initial about:blank page for the first\n // page acquisition, so a session reuses it instead of leaving an idle blank\n // tab that Playwright records as an empty video. Consumed at most once;\n // returns undefined once it has been taken, closed, or navigated away (e.g. a\n // prior target-id lookup), so callers fall back to opening a fresh tab.\n takeInitialBlankPage(entry) {\n const page = entry.initialBlankPage;\n entry.initialBlankPage = void 0;\n if (page && !page.isClosed() && page.url() === "about:blank") {\n return page;\n }\n return;\n }\n registerNamedPage(entry, pageName, page) {\n entry.pages.set(pageName, page);\n page.on("close", () => {\n const current = entry.pages.get(pageName);\n if (current === page) {\n entry.pages.delete(pageName);\n }\n });\n }\n pruneClosedPages(entry) {\n for (const [pageName, page] of entry.pages.entries()) {\n if (page.isClosed()) {\n entry.pages.delete(pageName);\n }\n }\n }\n listNamedPages(entry) {\n this.pruneClosedPages(entry);\n return Array.from(entry.pages.entries()).filter(([, page]) => !page.isClosed()).map(([name]) => name).sort((left, right) => left.localeCompare(right));\n }\n getNamedPagesByPage(entry) {\n const namesByPage = /* @__PURE__ */ new Map();\n for (const [name, page] of entry.pages.entries()) {\n if (!(page.isClosed() || namesByPage.has(page))) {\n namesByPage.set(page, name);\n }\n }\n return namesByPage;\n }\n getBrowserContexts(entry) {\n return [.../* @__PURE__ */ new Set([entry.context, ...entry.browser.contexts()])];\n }\n getContextPages(entry) {\n const pages = [];\n for (const context of this.getBrowserContexts(entry)) {\n for (const page of context.pages()) {\n if (!page.isClosed()) {\n pages.push({ context, page });\n }\n }\n }\n return pages;\n }\n async getPageTitle(page) {\n let timeoutId;\n try {\n return await Promise.race([\n page.title(),\n new Promise((resolve) => {\n timeoutId = setTimeout(() => resolve(""), PAGE_TITLE_TIMEOUT_MS);\n })\n ]);\n } finally {\n if (timeoutId !== void 0) {\n clearTimeout(timeoutId);\n }\n }\n }\n async findPageByTargetId(entry, targetId) {\n for (const { context, page } of this.getContextPages(entry)) {\n const pageTargetId = await this.getPageTargetId(context, page);\n if (pageTargetId === targetId) {\n return page;\n }\n }\n return null;\n }\n async getPageTargetId(context, page) {\n let session;\n try {\n session = await context.newCDPSession(page);\n const result = await session.send("Target.getTargetInfo");\n const targetId = typeof result === "object" && result !== null && "targetInfo" in result && typeof result.targetInfo === "object" && result.targetInfo !== null && "targetId" in result.targetInfo ? result.targetInfo.targetId : void 0;\n if (typeof targetId !== "string" || targetId.length === 0) {\n throw new Error("CDP target info did not include a targetId");\n }\n return targetId;\n } catch (error) {\n if (page.isClosed()) {\n return null;\n }\n throw error;\n } finally {\n await session?.detach().catch(() => void 0);\n }\n }\n};\n\n// src/local-endpoint.ts\nimport os2 from "node:os";\nimport path2 from "node:path";\nfunction sanitizePipeSegment(value) {\n const sanitized = value.replace(/[^A-Za-z0-9._-]/g, "-").replace(/^-+|-+$/g, "").toLowerCase();\n return sanitized.length > 0 ? sanitized : "user";\n}\nfunction getDefaultUsername(homedir) {\n const fromEnv = process.env.USERNAME || process.env.USER;\n if (typeof fromEnv === "string" && fromEnv.trim().length > 0) {\n return fromEnv;\n }\n try {\n const username = os2.userInfo().username;\n if (username.trim().length > 0) {\n return username;\n }\n } catch {\n }\n return path2.basename(homedir) || "user";\n}\nfunction getCanaryBaseDir(homedir = os2.homedir()) {\n return path2.join(homedir, ".canary");\n}\nfunction getDaemonEndpoint(options = {}) {\n const homedir = options.homedir ?? os2.homedir();\n const platform = options.platform ?? process.platform;\n if (platform === "win32") {\n const username = sanitizePipeSegment(\n options.username ?? getDefaultUsername(homedir)\n );\n return `\\\\\\\\.\\\\pipe\\\\canary-daemon-${username}`;\n }\n return path2.join(getCanaryBaseDir(homedir), "daemon.sock");\n}\nfunction getPidPath(homedir = os2.homedir()) {\n return path2.join(getCanaryBaseDir(homedir), "daemon.pid");\n}\nfunction getBrowsersDir(homedir = os2.homedir()) {\n return path2.join(getCanaryBaseDir(homedir), "browsers");\n}\nfunction getSessionsDir(homedir = os2.homedir()) {\n return path2.join(getCanaryBaseDir(homedir), "sessions");\n}\nfunction getSessionDir(sessionId, homedir = os2.homedir()) {\n return path2.join(getSessionsDir(homedir), sessionId);\n}\nfunction requiresDaemonEndpointCleanup(platform = process.platform) {\n return platform !== "win32";\n}\n\n// src/lock.ts\nfunction createKeyedLock() {\n const locks = /* @__PURE__ */ new Map();\n return async function withLock(key, action) {\n const previous = locks.get(key) ?? Promise.resolve();\n let release;\n const current = new Promise((resolve) => {\n release = resolve;\n });\n const tail = previous.catch(() => void 0).then(() => current);\n locks.set(key, tail);\n await previous.catch(() => void 0);\n try {\n return await action();\n } finally {\n release();\n if (locks.get(key) === tail) {\n locks.delete(key);\n }\n }\n };\n}\nfunction createMutex() {\n const withLock = createKeyedLock();\n const lockKey = /* @__PURE__ */ Symbol("mutex");\n return function withMutex(action) {\n return withLock(lockKey, action);\n };\n}\n\n// src/sandbox/quickjs-sandbox.ts\nimport { readFile as readFile2 } from "node:fs/promises";\nimport util2 from "node:util";\n\n// src/temp-files.ts\nimport { constants } from "node:fs";\nimport { lstat, mkdir as mkdir2, open } from "node:fs/promises";\nimport path3 from "node:path";\nvar SAFE_PATH_SEGMENT_PATTERN = /[^A-Za-z0-9._-]/g;\nvar NOFOLLOW_FLAG = constants.O_NOFOLLOW ?? 0;\nvar CANARY_BASE_DIR = getCanaryBaseDir();\nvar CANARY_TMP_DIR = path3.join(CANARY_BASE_DIR, "tmp");\nfunction requireNonEmptyString(value, label) {\n if (typeof value !== "string" || value.length === 0) {\n throw new TypeError(`${label} must be a non-empty string`);\n }\n return value;\n}\nfunction isWithinDirectory(rootDir, candidatePath) {\n if (candidatePath === rootDir) {\n return true;\n }\n const rootWithSeparator = rootDir.endsWith(path3.sep) ? rootDir : `${rootDir}${path3.sep}`;\n return candidatePath.startsWith(rootWithSeparator);\n}\nfunction sanitizePathSegment(segment) {\n if (segment.length === 0) {\n throw new Error("File paths must not contain empty path segments");\n }\n if (segment === "." || segment === ".." || segment.includes("..")) {\n throw new Error("File paths must not contain \'.\' or \'..\' segments");\n }\n const sanitized = segment.replace(SAFE_PATH_SEGMENT_PATTERN, "_");\n if (sanitized.length === 0 || sanitized === "." || sanitized === "..") {\n throw new Error("File paths must resolve to a valid filename");\n }\n return sanitized;\n}\nfunction sanitizeRelativePath(fileName) {\n const rawPath = requireNonEmptyString(fileName, "File name");\n if (rawPath.includes("\\0")) {\n throw new Error("File names must not contain null bytes");\n }\n if (path3.posix.isAbsolute(rawPath) || path3.win32.isAbsolute(rawPath)) {\n throw new Error("Absolute paths are not allowed");\n }\n const normalized = rawPath.replace(/\\\\/g, "/");\n if (normalized.startsWith("/")) {\n throw new Error("Absolute paths are not allowed");\n }\n return normalized.split("/").map(sanitizePathSegment);\n}\nasync function assertControlledDirectory(directoryPath, label) {\n const stats = await lstat(directoryPath);\n if (stats.isSymbolicLink()) {\n throw new Error(`${label} must not be a symlink`);\n }\n if (!stats.isDirectory()) {\n throw new Error(`${label} must be a directory`);\n }\n}\nasync function assertSafeParentDirectories(rootDir, destinationPath, createParents) {\n const relativeParent = path3.relative(rootDir, path3.dirname(destinationPath));\n if (relativeParent.length === 0) {\n return;\n }\n const segments = relativeParent.split(path3.sep).filter((segment) => segment.length > 0);\n let currentPath = rootDir;\n for (const segment of segments) {\n currentPath = path3.join(currentPath, segment);\n if (createParents) {\n await mkdir2(currentPath, {\n recursive: true\n });\n }\n try {\n const stats = await lstat(currentPath);\n if (stats.isSymbolicLink()) {\n throw new Error(\n `Temp path parent must not be a symlink: ${currentPath}`\n );\n }\n if (!stats.isDirectory()) {\n throw new Error(`Temp path parent must be a directory: ${currentPath}`);\n }\n } catch (error) {\n if (error.code === "ENOENT" && !createParents) {\n return;\n }\n throw error;\n }\n }\n}\nfunction normalizeSymlinkError(error, destinationPath) {\n if (error.code === "ELOOP") {\n return new Error(\n `Refusing to follow symlinked temp file: ${destinationPath}`\n );\n }\n return error instanceof Error ? error : new Error(String(error));\n}\nasync function assertDestinationIsNotSymlink(destinationPath) {\n try {\n const stats = await lstat(destinationPath);\n if (stats.isSymbolicLink()) {\n throw new Error(\n `Refusing to follow symlinked temp file: ${destinationPath}`\n );\n }\n } catch (error) {\n if (error.code === "ENOENT") {\n return;\n }\n throw error;\n }\n}\nasync function ensureCanaryTempDir() {\n await mkdir2(CANARY_BASE_DIR, {\n recursive: true\n });\n await assertControlledDirectory(\n CANARY_BASE_DIR,\n "Canary Browser base directory"\n );\n await mkdir2(CANARY_TMP_DIR, {\n recursive: true\n });\n await assertControlledDirectory(\n CANARY_TMP_DIR,\n "Canary Browser temp directory"\n );\n return path3.resolve(CANARY_TMP_DIR);\n}\nasync function resolveCanaryTempPath(fileName, options = {}) {\n const rootDir = await ensureCanaryTempDir();\n const segments = sanitizeRelativePath(fileName);\n const destinationPath = path3.resolve(rootDir, ...segments);\n if (!isWithinDirectory(rootDir, destinationPath)) {\n throw new Error(\n "Resolved temp file path escapes the controlled temp directory"\n );\n }\n await assertSafeParentDirectories(\n rootDir,\n destinationPath,\n options.createParents ?? false\n );\n return destinationPath;\n}\nasync function writeCanaryTempFile(fileName, data) {\n const destinationPath = await resolveCanaryTempPath(fileName, {\n createParents: true\n });\n await assertDestinationIsNotSymlink(destinationPath);\n let handle;\n try {\n handle = await open(\n destinationPath,\n constants.O_WRONLY | constants.O_CREAT | constants.O_TRUNC | NOFOLLOW_FLAG,\n 384\n );\n await handle.writeFile(data);\n } catch (error) {\n throw normalizeSymlinkError(error, destinationPath);\n } finally {\n await handle?.close();\n }\n return destinationPath;\n}\nasync function readCanaryTempFile(fileName) {\n const destinationPath = await resolveCanaryTempPath(fileName);\n await assertDestinationIsNotSymlink(destinationPath);\n let handle;\n try {\n handle = await open(destinationPath, constants.O_RDONLY | NOFOLLOW_FLAG);\n return await handle.readFile({\n encoding: "utf8"\n });\n } catch (error) {\n throw normalizeSymlinkError(error, destinationPath);\n } finally {\n await handle?.close();\n }\n}\n\n// src/sandbox/playwright-internals.ts\nimport { existsSync } from "node:fs";\nimport { createRequire } from "node:module";\nimport path4 from "node:path";\nimport { fileURLToPath } from "node:url";\nvar require2 = createRequire(import.meta.url);\nvar currentDir = path4.dirname(fileURLToPath(import.meta.url));\nfunction resolvePlaywrightInternal(modulePath) {\n const candidates = [\n path4.resolve(currentDir, "../../node_modules/playwright-core", modulePath),\n path4.resolve(currentDir, "node_modules/playwright-core", modulePath),\n path4.resolve(process.cwd(), "node_modules/playwright-core", modulePath)\n ];\n for (const candidate of candidates) {\n if (existsSync(candidate)) {\n return candidate;\n }\n }\n throw new Error(`Could not locate Playwright internals at ${modulePath}`);\n}\nvar serverInternals = require2(\n resolvePlaywrightInternal(path4.join("lib", "server", "index.js"))\n);\nvar clientInternals = require2(\n resolvePlaywrightInternal(path4.join("lib", "client", "connection.js"))\n);\nvar nodePlatformInternals = require2(\n resolvePlaywrightInternal(\n path4.join("lib", "server", "utils", "nodePlatform.js")\n )\n);\nvar {\n createPlaywright,\n DispatcherConnection,\n RootDispatcher,\n PlaywrightDispatcher\n} = serverInternals;\nvar { Connection } = clientInternals;\nvar { nodePlatform } = nodePlatformInternals;\n\n// src/sandbox/host-bridge.ts\nvar WITHHELD_EVENTS = /* @__PURE__ */ new Set(["video"]);\nvar HostBridge = class {\n dispatcherConnection;\n rootDispatcher;\n playwright;\n sendToSandbox;\n options;\n playwrightDispatcher;\n disposed = false;\n constructor(options) {\n this.sendToSandbox = options.sendToSandbox;\n this.options = {\n preLaunchedBrowser: options.preLaunchedBrowser,\n sharedBrowser: options.sharedBrowser,\n denyLaunch: options.denyLaunch,\n sdkLanguage: options.sdkLanguage ?? "javascript"\n };\n this.playwright = createPlaywright({\n sdkLanguage: this.options.sdkLanguage ?? "javascript"\n });\n this.dispatcherConnection = new DispatcherConnection(false);\n this.dispatcherConnection.onmessage = (message) => {\n if (this.shouldWithhold(message)) {\n return;\n }\n this.sendToSandbox(JSON.stringify(message));\n };\n this.rootDispatcher = new RootDispatcher(\n this.dispatcherConnection,\n async (rootScope) => {\n this.playwrightDispatcher = new PlaywrightDispatcher(\n rootScope,\n this.playwright,\n {\n preLaunchedBrowser: this.options.preLaunchedBrowser,\n sharedBrowser: this.options.sharedBrowser,\n denyLaunch: this.options.denyLaunch\n }\n );\n return this.playwrightDispatcher;\n }\n );\n }\n // True when a host\u2192sandbox protocol message must be withheld because the\n // vendored sandbox client has no validator for it. Only the `video` event\n // qualifies; the daemon still records video on its own real context.\n shouldWithhold(message) {\n return message.method ? WITHHELD_EVENTS.has(message.method) : false;\n }\n async receiveFromSandbox(json) {\n await this.dispatcherConnection.dispatch(\n JSON.parse(json)\n );\n }\n async dispose() {\n if (this.disposed) {\n return;\n }\n this.disposed = true;\n this.dispatcherConnection.onmessage = () => {\n };\n try {\n await this.playwrightDispatcher?.cleanup();\n } finally {\n this.rootDispatcher._dispose();\n }\n }\n};\n\n// src/sandbox/quickjs-host.ts\nimport {\n getQuickJS\n} from "quickjs-emscripten";\nvar QuickJSHost = class _QuickJSHost {\n static async create(options = {}) {\n const quickjs = await getQuickJS();\n return new _QuickJSHost(quickjs, options);\n }\n #runtime;\n #context;\n #options;\n #timers = /* @__PURE__ */ new Map();\n #pendingDeferreds = /* @__PURE__ */ new Set();\n #disposed = false;\n #interruptDeadline;\n #nextTimerId = 1;\n constructor(quickjs, options) {\n this.#options = options;\n this.#runtime = quickjs.newRuntime();\n if (options.memoryLimitBytes !== void 0) {\n this.#runtime.setMemoryLimit(options.memoryLimitBytes);\n }\n if (options.maxStackSizeBytes !== void 0) {\n this.#runtime.setMaxStackSize(options.maxStackSizeBytes);\n }\n if (options.cpuTimeoutMs !== void 0) {\n this.#runtime.setInterruptHandler(\n () => this.#interruptDeadline !== void 0 && Date.now() > this.#interruptDeadline\n );\n }\n this.#context = this.#runtime.newContext();\n this.#installConsole();\n this.#installTimers();\n this.#installHostCall();\n this.#installTransportSend();\n for (const [name, value] of Object.entries(options.globals ?? {})) {\n this.setGlobal(name, value);\n }\n }\n get disposed() {\n return this.#disposed;\n }\n setGlobal(name, value) {\n this.#assertAlive();\n const valueHandle = this.#toHandle(value);\n try {\n this.#context.setProp(this.#context.global, name, valueHandle);\n } finally {\n valueHandle.dispose();\n }\n }\n executeScriptSync(code, options = {}) {\n const resultHandle = this.#evalCode(code, options);\n try {\n const promiseState = this.#context.getPromiseState(resultHandle);\n if (!(promiseState.type === "fulfilled" && promiseState.notAPromise)) {\n throw new Error(\n "QuickJS script returned a promise; use executeScript() instead"\n );\n }\n return this.#dumpHandle(resultHandle);\n } finally {\n resultHandle.dispose();\n }\n }\n async executeScript(code, options = {}) {\n const resultHandle = this.#evalCode(code, options);\n return this.#consumeHandle(resultHandle);\n }\n async callFunction(name, ...args) {\n this.#assertAlive();\n const functionHandle = this.#context.getProp(this.#context.global, name);\n const argHandles = args.map((value) => this.#toHandle(value));\n try {\n if (this.#context.typeof(functionHandle) !== "function") {\n throw new Error(`QuickJS global "${name}" is not a function`);\n }\n const result = this.#runWithCpuLimit(\n () => this.#context.callFunction(\n functionHandle,\n this.#context.global,\n ...argHandles\n )\n );\n const resultHandle = this.#unwrapResult(\n result,\n `QuickJS function "${name}" failed`\n );\n return await this.#consumeHandle(resultHandle);\n } finally {\n for (const argHandle of argHandles) {\n argHandle.dispose();\n }\n functionHandle.dispose();\n }\n }\n dispose() {\n if (this.#disposed) {\n return;\n }\n this.#disposed = true;\n for (const timerId of [...this.#timers.keys()]) {\n this.#clearTimer(timerId);\n }\n for (const deferred of [...this.#pendingDeferreds]) {\n deferred.dispose();\n this.#pendingDeferreds.delete(deferred);\n }\n this.#context.dispose();\n this.#runtime.dispose();\n }\n #installConsole() {\n const consoleObject = this.#context.newObject();\n try {\n for (const level of ["log", "warn", "error", "info"]) {\n const fn = this.#context.newFunction(level, (...args) => {\n const nativeArgs = args.map((arg) => this.#context.dump(arg));\n this.#options.onConsole?.(level, nativeArgs);\n });\n this.#context.setProp(consoleObject, level, fn);\n fn.dispose();\n }\n this.#context.setProp(this.#context.global, "console", consoleObject);\n } finally {\n consoleObject.dispose();\n }\n }\n #installHostCall() {\n const hostCall = this.#context.newFunction(\n "__hostCall",\n (nameHandle, argsJsonHandle) => {\n const name = this.#context.getString(nameHandle);\n const argsJson = this.#context.getString(argsJsonHandle);\n const args = this.#parseArgs(name, argsJson);\n const invoke = () => {\n if (this.#options.onHostCall) {\n return this.#options.onHostCall(name, args);\n }\n const handler = this.#options.hostFunctions?.[name];\n if (!handler) {\n throw new Error(`No host function registered for "${name}"`);\n }\n return handler(...args);\n };\n return this.#bridgeHostResult(invoke);\n }\n );\n this.#context.setProp(this.#context.global, "__hostCall", hostCall);\n hostCall.dispose();\n }\n #installTransportSend() {\n const transportSend = this.#context.newFunction(\n "__transport_send",\n (messageHandle) => {\n const message = this.#context.getString(messageHandle);\n return this.#bridgeHostResult(\n () => this.#options.onTransportSend?.(message)\n );\n }\n );\n this.#context.setProp(\n this.#context.global,\n "__transport_send",\n transportSend\n );\n transportSend.dispose();\n }\n #installTimers() {\n const setTimeoutHandle = this.#context.newFunction(\n "setTimeout",\n (callbackHandle, delayHandle, ...argHandles) => {\n if (this.#context.typeof(callbackHandle) !== "function") {\n throw new TypeError("setTimeout callback must be a function");\n }\n const timerId = this.#nextTimerId++;\n const delay = Math.max(0, this.#context.getNumber(delayHandle));\n const callback = callbackHandle.dup();\n const args = argHandles.map((arg) => arg.dup());\n const timeout = globalThis.setTimeout(() => {\n if (this.#disposed) {\n this.#clearTimer(timerId);\n return;\n }\n const record = this.#timers.get(timerId);\n if (!record) {\n return;\n }\n try {\n const result = this.#runWithCpuLimit(\n () => this.#context.callFunction(\n record.callback,\n this.#context.undefined,\n ...record.args\n )\n );\n if (result.error) {\n this.#emitConsoleError(this.#context.dump(result.error));\n result.error.dispose();\n } else {\n result.value.dispose();\n }\n this.#tryDrainPendingJobs();\n } finally {\n this.#clearTimer(timerId);\n }\n }, delay);\n this.#timers.set(timerId, { callback, args, timeout });\n return this.#context.newNumber(timerId);\n }\n );\n const clearTimeoutHandle = this.#context.newFunction(\n "clearTimeout",\n (timerIdHandle) => {\n this.#clearTimer(this.#context.getNumber(timerIdHandle));\n }\n );\n this.#context.setProp(this.#context.global, "setTimeout", setTimeoutHandle);\n this.#context.setProp(\n this.#context.global,\n "clearTimeout",\n clearTimeoutHandle\n );\n setTimeoutHandle.dispose();\n clearTimeoutHandle.dispose();\n }\n #clearTimer(timerId) {\n const record = this.#timers.get(timerId);\n if (!record) {\n return;\n }\n globalThis.clearTimeout(record.timeout);\n record.callback.dispose();\n for (const arg of record.args) {\n arg.dispose();\n }\n this.#timers.delete(timerId);\n }\n #bridgeHostResult(invoker) {\n try {\n const result = invoker();\n if (this.#isPromiseLike(result)) {\n return this.#createDeferredPromise(result);\n }\n if (result === void 0) {\n return;\n }\n return this.#toHandle(result);\n } catch (error) {\n throw this.#normalizeHostError(error);\n }\n }\n #createDeferredPromise(promise) {\n const deferred = this.#context.newPromise();\n this.#pendingDeferreds.add(deferred);\n promise.then((value) => {\n if (this.#disposed || !deferred.alive) {\n return;\n }\n const valueHandle = value === void 0 ? void 0 : this.#toHandle(value);\n try {\n deferred.resolve(valueHandle);\n } finally {\n valueHandle?.dispose();\n }\n }).catch((error) => {\n if (this.#disposed || !deferred.alive) {\n return;\n }\n const errorHandle = this.#newGuestErrorHandle(error);\n try {\n deferred.reject(errorHandle);\n } finally {\n errorHandle.dispose();\n }\n }).finally(() => {\n this.#pendingDeferreds.delete(deferred);\n this.#tryDrainPendingJobs();\n });\n return deferred.handle;\n }\n #evalCode(code, options) {\n this.#assertAlive();\n const result = this.#runWithCpuLimit(\n () => this.#context.evalCode(code, options.filename ?? "sandbox.js", {\n type: options.type\n })\n );\n return this.#unwrapResult(result, "QuickJS evaluation failed");\n }\n async #consumeHandle(handle) {\n try {\n const promiseState = this.#context.getPromiseState(handle);\n if (promiseState.type === "fulfilled" && promiseState.notAPromise) {\n return this.#dumpHandle(handle);\n }\n if (promiseState.type === "fulfilled") {\n try {\n return this.#dumpHandle(promiseState.value);\n } finally {\n promiseState.value.dispose();\n }\n }\n if (promiseState.type === "pending") {\n const resolved2 = await this.#awaitQuickJSPromise(handle);\n try {\n return this.#dumpHandle(resolved2);\n } finally {\n resolved2.dispose();\n }\n }\n if (promiseState.type === "rejected") {\n try {\n throw this.#toError("QuickJS promise rejected", promiseState.error);\n } finally {\n promiseState.error.dispose();\n }\n }\n const resolved = await this.#awaitQuickJSPromise(handle);\n try {\n return this.#dumpHandle(resolved);\n } finally {\n resolved.dispose();\n }\n } finally {\n handle.dispose();\n }\n }\n async #awaitQuickJSPromise(promiseHandle) {\n let settled = false;\n const nativePromise = this.#context.resolvePromise(promiseHandle).finally(() => {\n settled = true;\n });\n while (!settled) {\n this.#drainPendingJobs();\n if (settled) {\n break;\n }\n await this.#options.onDrain?.();\n this.#drainPendingJobs();\n if (settled) {\n break;\n }\n await new Promise((resolve) => {\n globalThis.setTimeout(resolve, 0);\n });\n }\n this.#drainPendingJobs();\n return this.#unwrapResult(await nativePromise, "QuickJS promise rejected");\n }\n #drainPendingJobs() {\n this.#assertAlive();\n while (true) {\n const jobResult = this.#runWithCpuLimit(\n () => this.#runtime.executePendingJobs()\n );\n if (jobResult.error) {\n const error = this.#toError(\n "QuickJS pending job failed",\n jobResult.error\n );\n jobResult.error.dispose();\n throw error;\n }\n if (jobResult.value === 0) {\n return;\n }\n }\n }\n #tryDrainPendingJobs() {\n if (this.#disposed) {\n return;\n }\n try {\n this.#drainPendingJobs();\n } catch (error) {\n this.#emitConsoleError(this.#normalizeHostError(error));\n }\n }\n #unwrapResult(result, prefix) {\n if (result.error) {\n const error = this.#toError(prefix, result.error);\n result.error.dispose();\n throw error;\n }\n return result.value;\n }\n #toHandle(value) {\n if (value === void 0) {\n return this.#context.undefined.dup();\n }\n if (value === null) {\n return this.#context.null.dup();\n }\n if (value === true) {\n return this.#context.true.dup();\n }\n if (value === false) {\n return this.#context.false.dup();\n }\n switch (typeof value) {\n case "number":\n return this.#context.newNumber(value);\n case "string":\n return this.#context.newString(value);\n case "bigint":\n return this.#context.newBigInt(value);\n case "object": {\n if (Array.isArray(value)) {\n const arrayHandle = this.#context.newArray();\n try {\n value.forEach((item, index) => {\n const itemHandle = this.#toHandle(item);\n try {\n this.#context.setProp(arrayHandle, index, itemHandle);\n } finally {\n itemHandle.dispose();\n }\n });\n return arrayHandle;\n } catch (error) {\n arrayHandle.dispose();\n throw error;\n }\n }\n const objectHandle = this.#context.newObject();\n try {\n for (const [key, item] of Object.entries(value)) {\n const itemHandle = this.#toHandle(item);\n try {\n this.#context.setProp(objectHandle, key, itemHandle);\n } finally {\n itemHandle.dispose();\n }\n }\n return objectHandle;\n } catch (error) {\n objectHandle.dispose();\n throw error;\n }\n }\n default:\n throw new TypeError(`Unsupported host value type: ${typeof value}`);\n }\n }\n #dumpHandle(handle) {\n return this.#context.dump(handle);\n }\n #parseArgs(name, argsJson) {\n try {\n const parsed = JSON.parse(argsJson);\n if (!Array.isArray(parsed)) {\n throw new Error("Expected a JSON array");\n }\n return parsed;\n } catch (error) {\n throw new Error(\n `Invalid JSON arguments for host call "${name}": ${this.#normalizeHostError(error).message}`\n );\n }\n }\n #newGuestErrorHandle(error) {\n const normalized = this.#normalizeHostError(error);\n const errorHandle = this.#context.newError({\n name: normalized.name || "Error",\n message: normalized.message\n });\n if (normalized.stack) {\n const stackHandle = this.#context.newString(normalized.stack);\n try {\n this.#context.setProp(errorHandle, "stack", stackHandle);\n } finally {\n stackHandle.dispose();\n }\n }\n return errorHandle;\n }\n #toError(prefix, errorHandle) {\n const dumped = this.#context.dump(errorHandle);\n const normalized = this.#normalizeHostError(dumped);\n normalized.message = `${prefix}: ${normalized.message}`;\n return normalized;\n }\n #emitConsoleError(error) {\n const normalized = this.#normalizeHostError(error);\n this.#options.onConsole?.("error", [\n {\n name: normalized.name,\n message: normalized.message,\n stack: normalized.stack\n }\n ]);\n }\n #normalizeHostError(error) {\n if (error instanceof Error) {\n return error;\n }\n if (typeof error === "object" && error !== null) {\n const name = "name" in error && typeof error.name === "string" ? error.name : "Error";\n const message = "message" in error && typeof error.message === "string" ? error.message : JSON.stringify(error);\n const normalized = new Error(message);\n normalized.name = name;\n if ("stack" in error && typeof error.stack === "string") {\n normalized.stack = error.stack;\n }\n return normalized;\n }\n return new Error(String(error));\n }\n #runWithCpuLimit(callback) {\n if (this.#options.cpuTimeoutMs === void 0) {\n return callback();\n }\n const previousDeadline = this.#interruptDeadline;\n this.#interruptDeadline = Date.now() + this.#options.cpuTimeoutMs;\n try {\n return callback();\n } finally {\n this.#interruptDeadline = previousDeadline;\n }\n }\n #assertAlive() {\n if (this.#disposed) {\n throw new Error("QuickJSHost has been disposed");\n }\n }\n #isPromiseLike(value) {\n return typeof value === "object" && value !== null && "then" in value;\n }\n};\n\n// src/sandbox/quickjs-sandbox.ts\nimport { existsSync as existsSync2 } from "node:fs";\nimport { fileURLToPath as fileURLToPath2 } from "node:url";\nvar DEFAULT_MEMORY_LIMIT_BYTES = 512 * 1024 * 1024;\nvar WAIT_FOR_OBJECT_ATTEMPTS = 1e3;\nfunction findBundlePath() {\n const candidates = [\n fileURLToPath2(new URL("./sandbox-client.js", import.meta.url)),\n fileURLToPath2(new URL("../../dist/sandbox-client.js", import.meta.url))\n ];\n for (const p of candidates) {\n if (existsSync2(p)) {\n return p;\n }\n }\n throw new Error(\n `Failed to find sandbox-client.js. Searched:\n${candidates.map((c) => ` - ${c}`).join("\\n")}`\n );\n}\nvar BUNDLE_PATH = findBundlePath();\nvar TRANSPORT_RECEIVE_GLOBAL = "__transport_receive";\nvar bundleCodePromise;\nfunction formatArgs(args) {\n return args.map(\n (arg) => typeof arg === "string" ? arg : util2.inspect(arg, {\n colors: false,\n depth: 6,\n compact: 3,\n breakLength: Number.POSITIVE_INFINITY\n })\n ).join(" ");\n}\nfunction normalizeError(error) {\n if (error instanceof Error) {\n return error;\n }\n return new Error(String(error));\n}\nfunction getSandboxClientBundleCode() {\n bundleCodePromise ??= readFile2(BUNDLE_PATH, "utf8").catch(\n (error) => {\n bundleCodePromise = void 0;\n const message = error instanceof Error ? error.message : "Sandbox client bundle could not be read";\n throw new Error(\n `Failed to load sandbox client bundle at ${BUNDLE_PATH}: ${message}`\n );\n }\n );\n return bundleCodePromise;\n}\nfunction formatTimeoutDuration(timeoutMs) {\n if (timeoutMs % 1e3 === 0) {\n return `${timeoutMs / 1e3}s`;\n }\n return `${timeoutMs}ms`;\n}\nfunction createScriptTimeoutError(timeoutMs) {\n const error = new Error(\n `Script timed out after ${formatTimeoutDuration(timeoutMs)} and was terminated.`\n );\n error.name = "ScriptTimeoutError";\n return error;\n}\nfunction createGuestScriptTimeoutErrorSource(timeoutMs) {\n const message = JSON.stringify(createScriptTimeoutError(timeoutMs).message);\n return `(() => {\n const error = new Error(${message});\n error.name = "ScriptTimeoutError";\n return error;\n })()`;\n}\nfunction wrapScriptWithWallClockTimeout(script, timeoutMs) {\n if (timeoutMs === void 0) {\n return script;\n }\n return `\n (() => {\n return new Promise((resolve, reject) => {\n const timeoutId = setTimeout(() => {\n reject(${createGuestScriptTimeoutErrorSource(timeoutMs)});\n }, ${timeoutMs});\n\n Promise.resolve()\n .then(() => (${script}))\n .then(resolve, reject)\n .finally(() => {\n clearTimeout(timeoutId);\n });\n });\n })()\n `;\n}\nfunction requireString(value, label) {\n if (typeof value !== "string" || value.length === 0) {\n throw new TypeError(`${label} must be a non-empty string`);\n }\n return value;\n}\nfunction toServerImpl(clientObject, label) {\n const connection = clientObject._connection;\n const toImpl = connection?.toImpl;\n if (typeof toImpl !== "function") {\n throw new Error(`${label} does not expose a server implementation`);\n }\n const impl = toImpl(clientObject);\n if (!impl) {\n throw new Error(`${label} could not be mapped to a server implementation`);\n }\n return impl;\n}\nfunction extractGuid(page) {\n const guid = toServerImpl(page, "Playwright page").guid;\n if (typeof guid !== "string" || guid.length === 0) {\n throw new Error("Playwright page did not expose a guid");\n }\n return guid;\n}\nfunction decodeSandboxFilePayload(value, label) {\n if (typeof value !== "object" || value === null) {\n throw new TypeError(`${label} must be an object`);\n }\n const encoding = "encoding" in value ? value.encoding : void 0;\n const data = "data" in value ? value.data : void 0;\n if (encoding !== "utf8" && encoding !== "base64" || typeof data !== "string") {\n throw new TypeError(\n `${label} must include a valid encoding and string data`\n );\n }\n if (encoding === "utf8") {\n return data;\n }\n return Buffer.from(data, "base64");\n}\nvar QuickJSSandbox = class {\n #options;\n #anonymousPages = /* @__PURE__ */ new Set();\n #pendingHostOperations = /* @__PURE__ */ new Set();\n #transportInbox = [];\n #asyncError;\n #host;\n #hostBridge;\n #flushPromise;\n #disposed = false;\n #initialized = false;\n constructor(options) {\n this.#options = options;\n }\n async initialize() {\n this.#assertAlive();\n if (this.#initialized) {\n return;\n }\n try {\n await ensureCanaryTempDir();\n this.#host = await QuickJSHost.create({\n memoryLimitBytes: this.#options.memoryLimitBytes ?? DEFAULT_MEMORY_LIMIT_BYTES,\n cpuTimeoutMs: this.#options.timeoutMs,\n hostFunctions: {\n getPage: (name) => this.#getPage(name),\n newPage: () => this.#newPage(),\n listPages: () => this.#options.manager.listPages(this.#options.browserName),\n closePage: (name) => this.#closePage(name),\n saveScreenshot: (name, data) => this.#writeTempFile(name, data),\n writeFile: (name, data) => this.#writeTempFile(name, data),\n readFile: (name) => this.#readTempFile(name)\n },\n onConsole: (level, args) => {\n this.#routeConsole(level, args);\n },\n onDrain: () => this.#drainAsyncOps(),\n onTransportSend: (message) => {\n this.#handleTransportSend(message);\n }\n });\n this.#host.executeScriptSync(\n `\n const __performanceOrigin = Date.now();\n const __base64Alphabet =\n "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";\n\n const __encodeBase64 = (bytes) => {\n let result = "";\n for (let index = 0; index < bytes.length; index += 3) {\n const chunk =\n (bytes[index] << 16) |\n ((bytes[index + 1] ?? 0) << 8) |\n (bytes[index + 2] ?? 0);\n result += __base64Alphabet[(chunk >> 18) & 63];\n result += __base64Alphabet[(chunk >> 12) & 63];\n result += index + 1 < bytes.length ? __base64Alphabet[(chunk >> 6) & 63] : "=";\n result += index + 2 < bytes.length ? __base64Alphabet[chunk & 63] : "=";\n }\n return result;\n };\n\n const __decodeBase64 = (base64) => {\n const normalized = String(base64).replace(/\\\\s+/g, "");\n const output = [];\n for (let index = 0; index < normalized.length; index += 4) {\n const a = __base64Alphabet.indexOf(normalized[index] ?? "A");\n const b = __base64Alphabet.indexOf(normalized[index + 1] ?? "A");\n const c =\n normalized[index + 2] === "="\n ? 64\n : __base64Alphabet.indexOf(normalized[index + 2] ?? "A");\n const d =\n normalized[index + 3] === "="\n ? 64\n : __base64Alphabet.indexOf(normalized[index + 3] ?? "A");\n const chunk = (a << 18) | (b << 12) | ((c & 63) << 6) | (d & 63);\n output.push((chunk >> 16) & 255);\n if (c !== 64) {\n output.push((chunk >> 8) & 255);\n }\n if (d !== 64) {\n output.push(chunk & 255);\n }\n }\n return new Uint8Array(output);\n };\n\n globalThis.URL ??= class URL {\n constructor(value, base) {\n this.href = base === undefined ? String(value) : String(base) + String(value);\n }\n\n toJSON() {\n return this.href;\n }\n\n toString() {\n return this.href;\n }\n };\n\n globalThis.Buffer ??= class Buffer extends Uint8Array {\n constructor(value, byteOffset, length) {\n if (typeof value === "number") {\n super(value);\n return;\n }\n if (value instanceof ArrayBuffer) {\n super(value, byteOffset, length);\n return;\n }\n if (ArrayBuffer.isView(value)) {\n super(value.buffer, value.byteOffset, value.byteLength);\n return;\n }\n super(value);\n }\n\n static from(value, encodingOrOffset, length) {\n if (typeof value === "string") {\n if (encodingOrOffset !== undefined && encodingOrOffset !== "base64") {\n throw new Error("QuickJS Buffer only supports base64 string input");\n }\n return new Buffer(__decodeBase64(value));\n }\n if (value instanceof ArrayBuffer) {\n return new Buffer(value, encodingOrOffset, length);\n }\n if (ArrayBuffer.isView(value)) {\n return new Buffer(\n value.buffer.slice(\n value.byteOffset,\n value.byteOffset + value.byteLength,\n ),\n );\n }\n if (Array.isArray(value)) {\n return new Buffer(value);\n }\n throw new TypeError("Unsupported Buffer.from input");\n }\n\n toString(encoding) {\n if (encoding === undefined || encoding === "utf8") {\n return Array.from(this)\n .map((value) => String.fromCharCode(value))\n .join("");\n }\n if (encoding === "base64") {\n return __encodeBase64(this);\n }\n throw new Error("QuickJS Buffer only supports utf8 and base64 output");\n }\n };\n\n globalThis.performance ??= {\n now: () => Date.now() - __performanceOrigin,\n timeOrigin: __performanceOrigin,\n };\n globalThis.global = globalThis;\n `,\n {\n filename: "quickjs-runtime.js"\n }\n );\n const bundleCode = await getSandboxClientBundleCode();\n const bundleFactorySource = JSON.stringify(\n `${bundleCode}\nreturn __PlaywrightClient;`\n );\n this.#host.executeScriptSync(\n `\n globalThis.__createPlaywrightClient = () => {\n return new Function(${bundleFactorySource})();\n };\n `,\n {\n filename: "sandbox-client.js"\n }\n );\n const browserEntry = this.#options.manager.getBrowser(\n this.#options.browserName\n );\n if (!browserEntry) {\n throw new Error(\n `Browser "${this.#options.browserName}" not found. It should have been created before script execution.`\n );\n }\n this.#hostBridge = new HostBridge({\n sendToSandbox: (json) => {\n this.#transportInbox.push(json);\n },\n preLaunchedBrowser: toServerImpl(\n browserEntry.browser,\n "Playwright browser"\n ),\n sharedBrowser: true,\n denyLaunch: true\n });\n await this.#host.executeScript(\n `\n (() => {\n const hostCall = globalThis.__hostCall;\n const transportSend = globalThis.__transport_send;\n const createPlaywrightClient = globalThis.__createPlaywrightClient;\n\n if (typeof hostCall !== "function") {\n throw new Error("Sandbox bridge did not expose a host-call function");\n }\n if (typeof transportSend !== "function") {\n throw new Error("Sandbox bridge did not expose a transport sender");\n }\n if (typeof createPlaywrightClient !== "function") {\n throw new Error("Sandbox client bundle did not expose a Playwright client factory");\n }\n\n if (!delete globalThis.__hostCall) {\n globalThis.__hostCall = undefined;\n }\n if (!delete globalThis.__transport_send) {\n globalThis.__transport_send = undefined;\n }\n if (!delete globalThis.__createPlaywrightClient) {\n globalThis.__createPlaywrightClient = undefined;\n }\n\n const playwrightClient = createPlaywrightClient();\n const connection = new playwrightClient.Connection(playwrightClient.quickjsPlatform);\n connection.onmessage = (message) => {\n transportSend(JSON.stringify(message));\n };\n\n Object.defineProperty(globalThis, "${TRANSPORT_RECEIVE_GLOBAL}", {\n value: (json) => {\n connection.dispatch(JSON.parse(json));\n },\n configurable: false,\n enumerable: false,\n writable: false,\n });\n\n const waitForConnectionObject = async (guid, label) => {\n if (typeof guid !== "string" || guid.length === 0) {\n throw new Error(\\`\\${label} did not return a valid guid\\`);\n }\n\n for (let attempt = 0; attempt < ${WAIT_FOR_OBJECT_ATTEMPTS}; attempt += 1) {\n const object = connection.getObjectWithKnownName(guid);\n if (object) {\n return object;\n }\n await new Promise((resolve) => setTimeout(resolve, 0));\n }\n\n throw new Error(\\`Timed out waiting for \\${label} (\\${guid}) in the sandbox\\`);\n };\n\n const encodeHostFilePayload = (value) => {\n if (typeof value === "string") {\n return { encoding: "utf8", data: value };\n }\n if (value instanceof ArrayBuffer || ArrayBuffer.isView(value)) {\n return { encoding: "base64", data: Buffer.from(value).toString("base64") };\n }\n throw new TypeError(\n "File data must be a string, Buffer, Uint8Array, or ArrayBuffer",\n );\n };\n\n return (async () => {\n await connection.initializePlaywright();\n\n const browserApi = Object.create(null);\n Object.defineProperties(browserApi, {\n getPage: {\n value: async (name) => {\n const guid = await hostCall("getPage", JSON.stringify([name]));\n return await waitForConnectionObject(guid, \\`page "\\${name}"\\`);\n },\n enumerable: true,\n },\n newPage: {\n value: async () => {\n const guid = await hostCall("newPage", JSON.stringify([]));\n return await waitForConnectionObject(guid, "anonymous page");\n },\n enumerable: true,\n },\n listPages: {\n value: async () => {\n return await hostCall("listPages", JSON.stringify([]));\n },\n enumerable: true,\n },\n closePage: {\n value: async (name) => {\n await hostCall("closePage", JSON.stringify([name]));\n },\n enumerable: true,\n },\n });\n Object.freeze(browserApi);\n\n Object.defineProperty(globalThis, "browser", {\n value: browserApi,\n configurable: false,\n enumerable: true,\n writable: false,\n });\n\n Object.defineProperties(globalThis, {\n saveScreenshot: {\n value: async (buffer, name) => {\n return await hostCall(\n "saveScreenshot",\n JSON.stringify([name, encodeHostFilePayload(buffer)]),\n );\n },\n configurable: false,\n enumerable: true,\n writable: false,\n },\n writeFile: {\n value: async (name, data) => {\n return await hostCall(\n "writeFile",\n JSON.stringify([name, encodeHostFilePayload(data)]),\n );\n },\n configurable: false,\n enumerable: true,\n writable: false,\n },\n readFile: {\n value: async (name) => {\n return await hostCall("readFile", JSON.stringify([name]));\n },\n configurable: false,\n enumerable: true,\n writable: false,\n },\n });\n })();\n })()\n `,\n {\n filename: "sandbox-init.js"\n }\n );\n await this.#flushTransportQueue();\n this.#throwIfAsyncError();\n this.#initialized = true;\n } catch (error) {\n await this.dispose();\n throw error;\n }\n }\n async executeScript(script) {\n this.#assertInitialized();\n let executionError;\n try {\n this.#throwIfAsyncError();\n await this.#host?.executeScript(\n wrapScriptWithWallClockTimeout(script, this.#options.timeoutMs),\n {\n filename: "user-script.js"\n }\n );\n await this.#flushTransportQueue();\n this.#throwIfAsyncError();\n } catch (error) {\n executionError = error;\n }\n try {\n await this.#cleanupAnonymousPages();\n } catch (error) {\n executionError ??= error;\n }\n if (executionError) {\n throw executionError;\n }\n }\n async dispose() {\n if (this.#disposed) {\n return;\n }\n this.#disposed = true;\n await this.#cleanupAnonymousPages({\n suppressErrors: true\n });\n this.#transportInbox.length = 0;\n this.#pendingHostOperations.clear();\n try {\n await this.#hostBridge?.dispose();\n } catch {\n } finally {\n this.#hostBridge = void 0;\n this.#host?.dispose();\n this.#host = void 0;\n this.#flushPromise = void 0;\n }\n }\n #routeConsole(level, args) {\n const line = `${formatArgs(args)}\n`;\n if (level === "warn" || level === "error") {\n this.#options.onStderr(line);\n return;\n }\n this.#options.onStdout(line);\n }\n #handleTransportSend(message) {\n if (!this.#hostBridge) {\n this.#asyncError ??= new Error("Sandbox transport is not initialized");\n return;\n }\n const operation = this.#hostBridge.receiveFromSandbox(message).catch((error) => {\n this.#asyncError ??= normalizeError(error);\n }).finally(() => {\n this.#pendingHostOperations.delete(operation);\n });\n this.#pendingHostOperations.add(operation);\n }\n async #drainAsyncOps() {\n this.#throwIfAsyncError();\n await this.#flushTransportQueue();\n this.#throwIfAsyncError();\n if (this.#pendingHostOperations.size === 0) {\n return;\n }\n await Promise.race(this.#pendingHostOperations);\n this.#throwIfAsyncError();\n await this.#flushTransportQueue();\n this.#throwIfAsyncError();\n }\n async #flushTransportQueue() {\n this.#throwIfAsyncError();\n if (!this.#host || this.#transportInbox.length === 0) {\n return;\n }\n if (this.#flushPromise) {\n await this.#flushPromise;\n return;\n }\n const flush = async () => {\n while (this.#transportInbox.length > 0) {\n const message = this.#transportInbox.shift();\n if (message === void 0) {\n continue;\n }\n await this.#host?.callFunction(TRANSPORT_RECEIVE_GLOBAL, message);\n this.#throwIfAsyncError();\n }\n };\n this.#flushPromise = flush().finally(() => {\n this.#flushPromise = void 0;\n });\n await this.#flushPromise;\n }\n async #getPage(name) {\n const page = await this.#options.manager.getPage(\n this.#options.browserName,\n requireString(name, "Page name or targetId")\n );\n return extractGuid(page);\n }\n async #newPage() {\n const page = await this.#options.manager.newPage(this.#options.browserName);\n this.#anonymousPages.add(page);\n page.on("close", () => {\n this.#anonymousPages.delete(page);\n });\n return extractGuid(page);\n }\n async #closePage(name) {\n await this.#options.manager.closePage(\n this.#options.browserName,\n requireString(name, "Page name")\n );\n }\n async #writeTempFile(name, payload) {\n return await writeCanaryTempFile(\n requireString(name, "File name"),\n decodeSandboxFilePayload(payload, "File data")\n );\n }\n async #readTempFile(name) {\n return await readCanaryTempFile(requireString(name, "File name"));\n }\n async #cleanupAnonymousPages(options = {}) {\n const anonymousPages = [...this.#anonymousPages];\n this.#anonymousPages.clear();\n for (const page of anonymousPages) {\n try {\n if (!page.isClosed()) {\n await page.close();\n }\n } catch (error) {\n if (!options.suppressErrors) {\n throw error;\n }\n }\n }\n if (options.suppressErrors) {\n try {\n await this.#flushTransportQueue();\n } catch {\n }\n return;\n }\n await this.#flushTransportQueue();\n this.#throwIfAsyncError();\n }\n #throwIfAsyncError() {\n if (this.#asyncError) {\n throw this.#asyncError;\n }\n }\n #assertAlive() {\n if (this.#disposed) {\n throw new Error("QuickJS sandbox has been disposed");\n }\n }\n #assertInitialized() {\n this.#assertAlive();\n if (!(this.#initialized && this.#host && this.#hostBridge)) {\n throw new Error("QuickJS sandbox has not been initialized");\n }\n }\n};\n\n// src/sandbox/script-runner-quickjs.ts\nasync function runScript(script, manager2, browserName, output, options = {}) {\n const sandbox = new QuickJSSandbox({\n manager: manager2,\n browserName,\n onStdout: output.onStdout,\n onStderr: output.onStderr,\n memoryLimitBytes: options.memoryLimitBytes,\n timeoutMs: options.timeout\n });\n try {\n await sandbox.initialize();\n await sandbox.executeScript(`(async () => {\n${script}\n})()`);\n } finally {\n await sandbox.dispose();\n }\n}\n\n// src/session-manager.ts\nimport { createWriteStream } from "node:fs";\nimport { mkdir as mkdir3, readdir, stat, writeFile } from "node:fs/promises";\nimport path5 from "node:path";\nvar SESSION_PREFIX = "__session__";\nvar TEARDOWN_TIMEOUT_MS = 5e3;\nfunction sessionBrowserName(sessionId) {\n return `${SESSION_PREFIX}${sessionId}`;\n}\nvar SessionManager = class {\n sessions = /* @__PURE__ */ new Map();\n manager;\n log;\n constructor(manager2, log2) {\n this.manager = manager2;\n this.log = log2;\n this.manager.onBrowserDisconnect(\n (name) => this.handleBrowserDisconnect(name)\n );\n }\n handleBrowserDisconnect(name) {\n const sessionId = this.sessionIdForBrowser(name);\n if (!sessionId) {\n return;\n }\n const state = this.sessions.get(sessionId);\n if (state?.phase !== "active") {\n return;\n }\n state.phase = "failed";\n state.endedAt = Date.now();\n this.sessions.delete(sessionId);\n for (const dispose of state.errorDisposers) {\n try {\n dispose();\n } catch {\n }\n }\n state.errorDisposers = [];\n void this.closeStream(state.consoleStream);\n state.consoleStream = void 0;\n this.log.warn({ sessionId }, "session browser disconnected unexpectedly");\n }\n isSessionBrowser(name) {\n return name.startsWith(SESSION_PREFIX);\n }\n sessionIdForBrowser(name) {\n return name.startsWith(SESSION_PREFIX) ? name.slice(SESSION_PREFIX.length) : void 0;\n }\n has(sessionId) {\n return this.sessions.has(sessionId);\n }\n status(sessionId) {\n const state = this.sessions.get(sessionId);\n return state ? this.summarize(state) : void 0;\n }\n list() {\n return Array.from(this.sessions.values()).map(\n (state) => this.summarize(state)\n );\n }\n noteRun(sessionId) {\n const state = this.sessions.get(sessionId);\n if (state) {\n state.runCount += 1;\n }\n }\n async start(req) {\n if (this.sessions.has(req.sessionId)) {\n throw new Error(`Session "${req.sessionId}" already exists`);\n }\n const artifactsDir = getSessionDir(req.sessionId);\n const profileDir = path5.join(artifactsDir, "profile");\n const videoDir = path5.join(artifactsDir, SESSION_VIDEO_DIR);\n const harPath = path5.join(artifactsDir, SESSION_HAR_FILE);\n const consolePath = path5.join(artifactsDir, SESSION_CONSOLE_FILE);\n await mkdir3(profileDir, { recursive: true });\n const entry = await this.manager.launchSessionBrowser(\n sessionBrowserName(req.sessionId),\n {\n headless: req.headless ?? false,\n ignoreHTTPSErrors: req.ignoreHTTPSErrors ?? false,\n profileDirOverride: profileDir,\n record: {\n videoDir: req.capture.video ? videoDir : void 0,\n har: req.capture.har ? { path: harPath, content: "embed" } : void 0\n }\n }\n );\n const state = {\n artifactsDir,\n capture: req.capture,\n consolePath,\n entry,\n errorDisposers: [],\n harPath,\n headless: req.headless ?? false,\n name: req.name,\n pageCount: 0,\n phase: "active",\n runCount: 0,\n sessionId: req.sessionId,\n startedAt: Date.now(),\n videoDir\n };\n try {\n if (req.capture.trace) {\n await entry.context.tracing.start({\n screenshots: true,\n snapshots: true,\n sources: true,\n title: req.name ?? req.sessionId\n });\n }\n if (req.capture.console) {\n this.attachConsole(state);\n }\n } catch (err) {\n await this.swallow(() => this.manager.stopBrowser(entry.name));\n throw err;\n }\n this.sessions.set(req.sessionId, state);\n this.log.info(\n { sessionId: req.sessionId, artifactsDir },\n "session started"\n );\n return this.summarize(state);\n }\n async beginStep(sessionId, step) {\n const state = this.sessions.get(sessionId);\n if (state?.capture.trace) {\n await state.entry.context.tracing.group(step).catch(() => void 0);\n }\n }\n async endStep(sessionId) {\n const state = this.sessions.get(sessionId);\n if (state?.capture.trace) {\n await state.entry.context.tracing.groupEnd().catch(() => void 0);\n }\n }\n // Strict teardown ordering: stop tracing (writes trace.zip) -> close context\n // (flushes *.webm + finalizes HAR) -> detach listeners + flush console stream\n // -> enumerate artifacts + write manifest.json -> drop the session browser.\n async end(sessionId, reason) {\n const state = this.sessions.get(sessionId);\n if (!state) {\n throw new Error(`Session "${sessionId}" not found`);\n }\n if (state.phase !== "active") {\n try {\n return await this.collect(state, reason);\n } finally {\n await this.swallow(() => this.manager.stopBrowser(state.entry.name));\n this.sessions.delete(sessionId);\n }\n }\n state.phase = "ending";\n const ctx = state.entry.context;\n if (state.entry.browser.isConnected()) {\n state.pageCount = ctx.pages().length;\n }\n if (state.capture.trace) {\n await this.swallow(\n () => ctx.tracing.stop({ path: path5.join(state.artifactsDir, "trace.zip") })\n );\n }\n await this.swallow(() => ctx.close());\n for (const dispose of state.errorDisposers) {\n try {\n dispose();\n } catch {\n }\n }\n state.errorDisposers = [];\n await this.closeStream(state.consoleStream);\n state.consoleStream = void 0;\n state.phase = reason === "abort" ? "aborted" : "ended";\n state.endedAt = Date.now();\n try {\n const result = await this.collect(state, reason);\n this.log.info({ sessionId, reason }, "session ended");\n return result;\n } finally {\n await this.swallow(() => this.manager.stopBrowser(state.entry.name));\n this.sessions.delete(sessionId);\n }\n }\n async endAll() {\n for (const sessionId of Array.from(this.sessions.keys())) {\n await this.best(() => this.end(sessionId, "abort"));\n }\n }\n attachConsole(state) {\n const stream = createWriteStream(state.consolePath, { flags: "a" });\n stream.on("error", (err) => {\n this.log.debug(\n { err, sessionId: state.sessionId },\n "console log stream error"\n );\n });\n state.consoleStream = stream;\n const ctx = state.entry.context;\n const write = (record) => {\n if (!stream.destroyed) {\n stream.write(`${JSON.stringify(record)}\n`);\n }\n };\n const onConsole = (msg) => {\n const loc = msg.location();\n write({\n ts: Date.now(),\n kind: "console",\n type: msg.type(),\n text: msg.text(),\n url: loc.url,\n line: loc.lineNumber,\n col: loc.columnNumber,\n page: this.namePage(state, msg.page())\n });\n };\n ctx.on("console", onConsole);\n state.errorDisposers.push(() => ctx.off("console", onConsole));\n const onWebError = (webError) => {\n const err = webError.error();\n write({\n ts: Date.now(),\n kind: "pageerror",\n message: err?.message ?? String(err),\n stack: err?.stack,\n page: this.namePage(state, webError.page())\n });\n };\n ctx.on("weberror", onWebError);\n state.errorDisposers.push(() => ctx.off("weberror", onWebError));\n }\n namePage(state, page) {\n if (!page) {\n return;\n }\n for (const [name, candidate] of state.entry.pages) {\n if (candidate === page) {\n return name;\n }\n }\n return;\n }\n async collect(state, reason) {\n const artifacts = [];\n const add = async (kind, filePath) => {\n try {\n const info = await stat(filePath);\n if (info.isFile()) {\n artifacts.push({ kind, path: filePath, bytes: info.size });\n }\n } catch {\n }\n };\n if (state.capture.trace) {\n await add("trace", path5.join(state.artifactsDir, SESSION_TRACE_FILE));\n }\n if (state.capture.har) {\n await add("har", state.harPath);\n }\n if (state.capture.console) {\n await add("console", state.consolePath);\n }\n if (state.capture.video) {\n const files = await readdir(state.videoDir).catch(() => []);\n for (const file of files) {\n if (file.endsWith(SESSION_VIDEO_EXT)) {\n await add("video", path5.join(state.videoDir, file));\n }\n }\n }\n const screenshotsDir = path5.join(\n state.artifactsDir,\n SESSION_SCREENSHOTS_DIR\n );\n const shots = await readdir(screenshotsDir).catch(() => []);\n for (const file of shots) {\n if (file.endsWith(SESSION_SCREENSHOT_EXT)) {\n await add("screenshot", path5.join(screenshotsDir, file));\n }\n }\n const session = this.summarize(state);\n const manifestPath = path5.join(state.artifactsDir, "manifest.json");\n await writeFile(\n manifestPath,\n JSON.stringify({ session, artifacts, reason }, null, 2)\n );\n return { session, artifacts, manifestPath };\n }\n summarize(state) {\n const pageCount = state.entry.browser.isConnected() ? state.entry.context.pages().length : state.pageCount;\n return {\n artifactsDir: state.artifactsDir,\n browser: state.entry.name,\n capture: state.capture,\n endedAt: state.endedAt,\n headless: state.headless,\n name: state.name,\n pageCount,\n phase: state.phase,\n runCount: state.runCount,\n sessionId: state.sessionId,\n startedAt: state.startedAt\n };\n }\n // Await a teardown step to completion, logging (not throwing) on failure.\n // Used by end() so artifacts are fully flushed before enumeration.\n async swallow(fn) {\n try {\n await fn();\n } catch (err) {\n this.log.debug({ err }, "session teardown step failed");\n }\n }\n // Like swallow(), but bounded by a timeout so a wedged context.close() can\'t\n // stall daemon shutdown. Used only by endAll(); the losing promise\'s eventual\n // rejection is consumed by Promise.race, so it never becomes unhandled.\n async best(fn) {\n try {\n await Promise.race([\n fn(),\n new Promise((resolve) => {\n const timer = setTimeout(resolve, TEARDOWN_TIMEOUT_MS);\n timer.unref();\n })\n ]);\n } catch (err) {\n this.log.debug({ err }, "session teardown step failed");\n }\n }\n closeStream(stream) {\n if (!stream) {\n return Promise.resolve();\n }\n return new Promise((resolve) => {\n stream.end(() => resolve());\n });\n }\n};\n\n// src/daemon.ts\nvar BASE_DIR = getCanaryBaseDir();\nvar SOCKET_PATH = getDaemonEndpoint();\nvar PID_PATH = getPidPath();\nvar BROWSERS_DIR = getBrowsersDir();\nvar DEFAULT_SCRIPT_TIMEOUT_MS = 3e4;\nvar SOCKET_CLOSE_TIMEOUT_MS = 500;\nvar LOG_PATH = path6.join(BASE_DIR, "daemon.log");\nvar log = createLogger({\n name: "daemon",\n destination: LOG_PATH,\n fallbackLevel: "info",\n // Synchronous writes so error/shutdown records flush before process.exit().\n sync: true\n});\nvar manager = new BrowserManager(BROWSERS_DIR);\nvar sessions = new SessionManager(manager, log);\nvar startedAt = Date.now();\nvar withBrowserLock = createKeyedLock();\nvar withInstallLock = createMutex();\nvar clients = /* @__PURE__ */ new Set();\nvar server = null;\nvar shuttingDown = null;\nfunction formatError(error) {\n if (error instanceof Error) {\n if (error.name === "ScriptTimeoutError") {\n return error.message;\n }\n return error.stack ?? error.message;\n }\n return String(error);\n}\nasync function writeMessage(socket, message) {\n if (socket.destroyed) {\n return;\n }\n await new Promise((resolve, reject) => {\n const payload = serialize(message);\n socket.write(payload, (error) => {\n if (error) {\n reject(error);\n return;\n }\n resolve();\n });\n });\n}\nasync function unlinkIfExists(filePath) {\n try {\n await unlink(filePath);\n } catch (error) {\n if (error.code !== "ENOENT") {\n throw error;\n }\n }\n}\nasync function closeServerInstance(serverToClose) {\n await new Promise((resolve) => {\n serverToClose.close(() => {\n resolve();\n });\n });\n}\nasync function closeClientSocket(socket) {\n if (socket.destroyed) {\n return;\n }\n await new Promise((resolve) => {\n const timeout = setTimeout(() => {\n if (!socket.destroyed) {\n socket.destroy();\n }\n }, SOCKET_CLOSE_TIMEOUT_MS);\n timeout.unref();\n const finish = () => {\n clearTimeout(timeout);\n resolve();\n };\n socket.once("close", finish);\n socket.once("error", finish);\n socket.end();\n });\n}\nfunction createMessageQueue(socket) {\n let queue = Promise.resolve();\n return {\n push(message) {\n queue = queue.then(() => writeMessage(socket, message)).catch(() => void 0);\n return queue;\n },\n async drain() {\n await queue;\n }\n };\n}\nasync function captureStepScreenshot(browser, sessionId, step) {\n try {\n const shotPath = path6.join(\n getSessionDir(sessionId),\n "screenshots",\n `${sessionStepSlug(step)}.png`\n );\n await manager.screenshotActivePage(browser, shotPath);\n } catch (error) {\n log.debug({ err: error, sessionId, step }, "step screenshot failed");\n }\n}\nasync function resolveExecuteBrowser(socket, request, targetSession) {\n if (targetSession) {\n if (!sessions.has(targetSession)) {\n await writeMessage(socket, {\n id: request.id,\n type: "error",\n message: `No active session "${targetSession}". Start one with \\`canary session start\\`.`\n });\n return false;\n }\n if (request.connect) {\n await writeMessage(socket, {\n id: request.id,\n type: "error",\n message: `Session "${targetSession}" manages its own browser; \\`connect\\` is not allowed for a session run.`\n });\n return false;\n }\n await manager.ensureBrowser(request.browser, {\n headless: request.headless,\n ignoreHTTPSErrors: request.ignoreHTTPSErrors\n });\n return true;\n }\n if (request.connect === "auto") {\n await manager.autoConnect(request.browser);\n } else if (request.connect) {\n await manager.connectBrowser(request.browser, request.connect);\n } else {\n await manager.ensureBrowser(request.browser, {\n headless: request.headless,\n ignoreHTTPSErrors: request.ignoreHTTPSErrors\n });\n }\n return true;\n}\nasync function handleExecute(socket, request) {\n const targetSession = sessions.sessionIdForBrowser(request.browser);\n if (targetSession && !sessions.has(targetSession)) {\n await writeMessage(socket, {\n id: request.id,\n type: "error",\n message: `No active session "${targetSession}". Start one with \\`canary session start\\`.`\n });\n return;\n }\n await withBrowserLock(request.browser, async () => {\n if (!await resolveExecuteBrowser(socket, request, targetSession)) {\n return;\n }\n const output = createMessageQueue(socket);\n const timeoutMs = request.timeoutMs ?? DEFAULT_SCRIPT_TIMEOUT_MS;\n if (targetSession && request.step) {\n await sessions.beginStep(targetSession, request.step);\n }\n try {\n if (request.initScripts && request.initScripts.length > 0) {\n await manager.applyInitScripts(request.browser, request.initScripts);\n }\n await runScript(\n request.script,\n manager,\n request.browser,\n {\n onStdout: (data) => {\n void output.push({\n id: request.id,\n type: "stdout",\n data\n });\n },\n onStderr: (data) => {\n void output.push({\n id: request.id,\n type: "stderr",\n data\n });\n }\n },\n {\n timeout: timeoutMs\n }\n );\n await output.drain();\n await writeMessage(socket, {\n id: request.id,\n type: "complete",\n success: true\n });\n } catch (error) {\n await output.drain().catch(() => void 0);\n await writeMessage(socket, {\n id: request.id,\n type: "error",\n message: formatError(error)\n });\n } finally {\n if (targetSession && request.step) {\n await captureStepScreenshot(\n request.browser,\n targetSession,\n request.step\n );\n await sessions.endStep(targetSession);\n }\n if (targetSession) {\n sessions.noteRun(targetSession);\n }\n }\n });\n}\nasync function handleInstall(socket, request) {\n await withInstallLock(async () => {\n const output = createMessageQueue(socket);\n try {\n await mkdir4(BASE_DIR, { recursive: true });\n await writeFile2(\n path6.join(BASE_DIR, "package.json"),\n EMBEDDED_PACKAGE_JSON\n );\n const npmProgram = "npm";\n await runInstallCommand(\n output,\n request.id,\n npmProgram,\n ["install"],\n BASE_DIR,\n "npm install"\n );\n await runInstallCommand(\n output,\n request.id,\n npmProgram,\n ["exec", "--", "playwright", "install", "chromium"],\n BASE_DIR,\n "Playwright install"\n );\n await writeMessage(socket, {\n id: request.id,\n type: "complete",\n success: true\n });\n } catch (error) {\n await output.drain().catch(() => void 0);\n await writeMessage(socket, {\n id: request.id,\n type: "error",\n message: formatError(error)\n });\n }\n });\n}\nasync function runInstallCommand(output, requestId, program, args, cwd, label) {\n const child = spawn(program, args, {\n cwd,\n env: process.env,\n stdio: ["ignore", "pipe", "pipe"],\n windowsHide: true,\n shell: process.platform === "win32"\n });\n child.stdout?.setEncoding("utf8");\n child.stdout?.on("data", (data) => {\n void output.push({\n id: requestId,\n type: "stdout",\n data\n });\n });\n child.stderr?.setEncoding("utf8");\n child.stderr?.on("data", (data) => {\n void output.push({\n id: requestId,\n type: "stderr",\n data\n });\n });\n const result = await new Promise((resolve, reject) => {\n child.once("error", reject);\n child.once("close", (code, signal) => {\n resolve({ code, signal });\n });\n });\n await output.drain();\n if (result.code === 0) {\n return;\n }\n const reason = result.signal === null ? `${label} failed with exit code ${result.code ?? "unknown"}` : `${label} terminated by signal ${result.signal}`;\n throw new Error(reason);\n}\nasync function handleRequest(socket, line) {\n const parsed = parseRequest(line);\n if (!parsed.success) {\n await writeMessage(socket, {\n id: parsed.id ?? "unknown",\n type: "error",\n message: parsed.error\n });\n return;\n }\n const { request } = parsed;\n log.debug({ id: request.id, type: request.type }, "handling request");\n if (shuttingDown && request.type !== "stop") {\n await writeMessage(socket, {\n id: request.id,\n type: "error",\n message: "Daemon is shutting down"\n });\n return;\n }\n switch (request.type) {\n case "execute":\n await handleExecute(socket, request);\n return;\n case "browsers":\n await writeMessage(socket, {\n id: request.id,\n type: "result",\n data: manager.listBrowsers()\n });\n await writeMessage(socket, {\n id: request.id,\n type: "complete",\n success: true\n });\n return;\n case "browser-stop":\n if (sessions.isSessionBrowser(request.browser)) {\n await writeMessage(socket, {\n id: request.id,\n type: "error",\n message: `"${request.browser}" is a session browser; tear it down with \\`canary session end\\` or \\`canary session abort\\`.`\n });\n return;\n }\n await manager.stopBrowser(request.browser);\n log.info({ browser: request.browser }, "browser stopped");\n await writeMessage(socket, {\n id: request.id,\n type: "result",\n data: { browser: request.browser, stopped: true }\n });\n await writeMessage(socket, {\n id: request.id,\n type: "complete",\n success: true\n });\n return;\n case "status":\n await writeMessage(socket, {\n id: request.id,\n type: "result",\n data: {\n pid: process.pid,\n uptimeMs: Date.now() - startedAt,\n browserCount: manager.browserCount(),\n browsers: manager.listBrowsers(),\n socketPath: SOCKET_PATH\n }\n });\n await writeMessage(socket, {\n id: request.id,\n type: "complete",\n success: true\n });\n return;\n case "install":\n await handleInstall(socket, request);\n return;\n case "stop":\n await writeMessage(socket, {\n id: request.id,\n type: "result",\n data: { stopping: true }\n });\n await writeMessage(socket, {\n id: request.id,\n type: "complete",\n success: true\n });\n void shutdown(0);\n return;\n case "session-start":\n await withBrowserLock(sessionBrowserName(request.sessionId), async () => {\n try {\n const session = await sessions.start(request);\n await writeMessage(socket, {\n id: request.id,\n type: "result",\n data: { session }\n });\n await writeMessage(socket, {\n id: request.id,\n type: "complete",\n success: true\n });\n } catch (error) {\n await writeMessage(socket, {\n id: request.id,\n type: "error",\n message: formatError(error)\n });\n }\n });\n return;\n case "session-end":\n await withBrowserLock(sessionBrowserName(request.sessionId), async () => {\n try {\n const result = await sessions.end(request.sessionId, request.reason);\n await writeMessage(socket, {\n id: request.id,\n type: "result",\n data: result\n });\n await writeMessage(socket, {\n id: request.id,\n type: "complete",\n success: true\n });\n } catch (error) {\n await writeMessage(socket, {\n id: request.id,\n type: "error",\n message: formatError(error)\n });\n }\n });\n return;\n case "session-status": {\n const session = sessions.status(request.sessionId);\n if (session) {\n await writeMessage(socket, {\n id: request.id,\n type: "result",\n data: { session }\n });\n await writeMessage(socket, {\n id: request.id,\n type: "complete",\n success: true\n });\n } else {\n await writeMessage(socket, {\n id: request.id,\n type: "error",\n message: `Session "${request.sessionId}" not found`\n });\n }\n return;\n }\n case "session-list":\n await writeMessage(socket, {\n id: request.id,\n type: "result",\n data: { sessions: sessions.list() }\n });\n await writeMessage(socket, {\n id: request.id,\n type: "complete",\n success: true\n });\n return;\n default:\n return;\n }\n}\nfunction shutdown(exitCode = 0) {\n if (shuttingDown) {\n return shuttingDown;\n }\n shuttingDown = (async () => {\n log.info({ exitCode }, "daemon shutting down");\n const serverToClose = server;\n server = null;\n const serverClosed = serverToClose ? closeServerInstance(serverToClose) : Promise.resolve();\n await sessions.endAll();\n await manager.stopAll();\n await Promise.allSettled(\n Array.from(clients, (socket) => closeClientSocket(socket))\n );\n await serverClosed;\n const cleanup = [unlinkIfExists(PID_PATH)];\n if (requiresDaemonEndpointCleanup()) {\n cleanup.push(unlinkIfExists(SOCKET_PATH));\n }\n await Promise.allSettled(cleanup);\n clients.clear();\n process.exit(exitCode);\n })();\n return shuttingDown;\n}\nasync function start() {\n await mkdir4(BASE_DIR, { recursive: true });\n await ensureCanaryTempDir();\n if (requiresDaemonEndpointCleanup()) {\n await unlinkIfExists(SOCKET_PATH);\n }\n await writeFile2(PID_PATH, `${process.pid}\n`);\n server = net.createServer((socket) => {\n if (shuttingDown) {\n socket.end();\n return;\n }\n clients.add(socket);\n socket.setEncoding("utf8");\n let buffer = "";\n let queue = Promise.resolve();\n socket.on("data", (chunk) => {\n buffer += chunk;\n const lines = buffer.split("\\n");\n buffer = lines.pop() ?? "";\n for (const rawLine of lines) {\n const line = rawLine.trim();\n if (!line) {\n continue;\n }\n queue = queue.then(() => handleRequest(socket, line)).catch(async (error) => {\n log.error({ err: error }, "request handling error");\n if (!socket.destroyed) {\n await writeMessage(socket, {\n id: "unknown",\n type: "error",\n message: formatError(error)\n });\n }\n });\n }\n });\n socket.on("close", () => {\n clients.delete(socket);\n });\n socket.on("error", () => {\n clients.delete(socket);\n });\n });\n server.on("error", (error) => {\n log.error({ err: error }, "daemon server error");\n void shutdown(1);\n });\n await new Promise((resolve, reject) => {\n server?.once("error", reject);\n server?.listen(SOCKET_PATH, () => {\n server?.off("error", reject);\n resolve();\n });\n });\n log.info({ socket: SOCKET_PATH, pid: process.pid }, "daemon ready");\n}\nfunction registerShutdownHandlers() {\n const handleSignal = () => {\n void shutdown(0);\n };\n const handleFatalError = (error) => {\n log.error({ err: error }, "fatal daemon error");\n void shutdown(1);\n };\n process.on("SIGINT", handleSignal);\n process.on("SIGTERM", handleSignal);\n process.on("SIGHUP", handleSignal);\n process.on("uncaughtException", handleFatalError);\n process.on("unhandledRejection", handleFatalError);\n}\nregisterShutdownHandlers();\nstart().catch((error) => {\n log.error({ err: error }, "failed to start daemon");\n void shutdown(1);\n});\n';
14493
14493
  var SANDBOX_CLIENT2 = '"use strict";\nvar __PlaywrightClient = (() => {\n var __defProp = Object.defineProperty;\n var __getOwnPropDesc = Object.getOwnPropertyDescriptor;\n var __getOwnPropNames = Object.getOwnPropertyNames;\n var __hasOwnProp = Object.prototype.hasOwnProperty;\n var __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n };\n var __copyProps = (to, from, except, desc) => {\n if (from && typeof from === "object" || typeof from === "function") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n };\n var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);\n\n // src/sandbox/forked-client/bundle-entry.ts\n var bundle_entry_exports = {};\n __export(bundle_entry_exports, {\n Connection: () => Connection,\n quickjsPlatform: () => quickjsPlatform\n });\n\n // src/sandbox/forked-client/src/client/eventEmitter.ts\n var EventEmitter = class {\n _events = void 0;\n _eventsCount = 0;\n _maxListeners = void 0;\n _pendingHandlers = /* @__PURE__ */ new Map();\n _rejectionHandler;\n _platform;\n constructor(platform) {\n this._platform = platform;\n if (this._events === void 0 || this._events === Object.getPrototypeOf(this)._events) {\n this._events = /* @__PURE__ */ Object.create(null);\n this._eventsCount = 0;\n }\n this._maxListeners = this._maxListeners || void 0;\n this.on = this.addListener;\n this.off = this.removeListener;\n }\n setMaxListeners(n) {\n if (typeof n !== "number" || n < 0 || Number.isNaN(n))\n throw new RangeError(\n \'The value of "n" is out of range. It must be a non-negative number. Received \' + n + "."\n );\n this._maxListeners = n;\n return this;\n }\n getMaxListeners() {\n return this._maxListeners === void 0 ? this._platform.defaultMaxListeners() : this._maxListeners;\n }\n emit(type, ...args) {\n const events = this._events;\n if (events === void 0) return false;\n const handler = events?.[type];\n if (handler === void 0) return false;\n if (typeof handler === "function") {\n this._callHandler(type, handler, args);\n } else {\n const len = handler.length;\n const listeners = handler.slice();\n for (let i = 0; i < len; ++i) this._callHandler(type, listeners[i], args);\n }\n return true;\n }\n _callHandler(type, handler, args) {\n const promise = Reflect.apply(handler, this, args);\n if (!(promise instanceof Promise)) return;\n let set = this._pendingHandlers.get(type);\n if (!set) {\n set = /* @__PURE__ */ new Set();\n this._pendingHandlers.set(type, set);\n }\n set.add(promise);\n promise.catch((e) => {\n if (this._rejectionHandler) this._rejectionHandler(e);\n else throw e;\n }).finally(() => set.delete(promise));\n }\n addListener(type, listener) {\n return this._addListener(type, listener, false);\n }\n on(type, listener) {\n return this._addListener(type, listener, false);\n }\n _addListener(type, listener, prepend) {\n checkListener(listener);\n let events = this._events;\n let existing;\n if (events === void 0) {\n events = this._events = /* @__PURE__ */ Object.create(null);\n this._eventsCount = 0;\n } else {\n if (events.newListener !== void 0) {\n this.emit("newListener", type, unwrapListener(listener));\n events = this._events;\n }\n existing = events[type];\n }\n if (existing === void 0) {\n existing = events[type] = listener;\n ++this._eventsCount;\n } else {\n if (typeof existing === "function") {\n existing = events[type] = prepend ? [listener, existing] : [existing, listener];\n } else if (prepend) {\n existing.unshift(listener);\n } else {\n existing.push(listener);\n }\n const m = this.getMaxListeners();\n if (m > 0 && existing.length > m && !existing.warned) {\n existing.warned = true;\n const w = new Error(\n "Possible EventEmitter memory leak detected. " + existing.length + " " + String(type) + " listeners added. Use emitter.setMaxListeners() to increase limit"\n );\n w.name = "MaxListenersExceededWarning";\n w.emitter = this;\n w.type = type;\n w.count = existing.length;\n if (!this._platform.isUnderTest()) {\n console.warn(w);\n }\n }\n }\n return this;\n }\n prependListener(type, listener) {\n return this._addListener(type, listener, true);\n }\n once(type, listener) {\n checkListener(listener);\n this.on(type, new OnceWrapper(this, type, listener).wrapperFunction);\n return this;\n }\n prependOnceListener(type, listener) {\n checkListener(listener);\n this.prependListener(type, new OnceWrapper(this, type, listener).wrapperFunction);\n return this;\n }\n removeListener(type, listener) {\n checkListener(listener);\n const events = this._events;\n if (events === void 0) return this;\n const list = events[type];\n if (list === void 0) return this;\n if (list === listener || list.listener === listener) {\n if (--this._eventsCount === 0) {\n this._events = /* @__PURE__ */ Object.create(null);\n } else {\n delete events[type];\n if (events.removeListener)\n this.emit("removeListener", type, list.listener ?? listener);\n }\n } else if (typeof list !== "function") {\n let position = -1;\n let originalListener;\n for (let i = list.length - 1; i >= 0; i--) {\n if (list[i] === listener || wrappedListener(list[i]) === listener) {\n originalListener = wrappedListener(list[i]);\n position = i;\n break;\n }\n }\n if (position < 0) return this;\n if (position === 0) list.shift();\n else list.splice(position, 1);\n if (list.length === 1) events[type] = list[0];\n if (events.removeListener !== void 0)\n this.emit("removeListener", type, originalListener || listener);\n }\n return this;\n }\n off(type, listener) {\n return this.removeListener(type, listener);\n }\n removeAllListeners(type, options) {\n this._removeAllListeners(type);\n if (!options) return this;\n if (options.behavior === "wait") {\n const errors = [];\n this._rejectionHandler = (error) => errors.push(error);\n return this._waitFor(type).then(() => {\n if (errors.length) throw errors[0];\n });\n }\n if (options.behavior === "ignoreErrors") this._rejectionHandler = () => {\n };\n return Promise.resolve();\n }\n _removeAllListeners(type) {\n const events = this._events;\n if (!events) return;\n if (!events.removeListener) {\n if (type === void 0) {\n this._events = /* @__PURE__ */ Object.create(null);\n this._eventsCount = 0;\n } else if (events[type] !== void 0) {\n if (--this._eventsCount === 0) this._events = /* @__PURE__ */ Object.create(null);\n else delete events[type];\n }\n return;\n }\n if (type === void 0) {\n const keys = Object.keys(events);\n let key;\n for (let i = 0; i < keys.length; ++i) {\n key = keys[i];\n if (key === "removeListener") continue;\n this._removeAllListeners(key);\n }\n this._removeAllListeners("removeListener");\n this._events = /* @__PURE__ */ Object.create(null);\n this._eventsCount = 0;\n return;\n }\n const listeners = events[type];\n if (typeof listeners === "function") {\n this.removeListener(type, listeners);\n } else if (listeners !== void 0) {\n for (let i = listeners.length - 1; i >= 0; i--) this.removeListener(type, listeners[i]);\n }\n }\n listeners(type) {\n return this._listeners(this, type, true);\n }\n rawListeners(type) {\n return this._listeners(this, type, false);\n }\n listenerCount(type) {\n const events = this._events;\n if (events !== void 0) {\n const listener = events[type];\n if (typeof listener === "function") return 1;\n if (listener !== void 0) return listener.length;\n }\n return 0;\n }\n eventNames() {\n return this._eventsCount > 0 && this._events ? Reflect.ownKeys(this._events) : [];\n }\n async _waitFor(type) {\n let promises = [];\n if (type) {\n promises = [...this._pendingHandlers.get(type) || []];\n } else {\n promises = [];\n for (const [, pending] of this._pendingHandlers) promises.push(...pending);\n }\n await Promise.all(promises);\n }\n _listeners(target, type, unwrap) {\n const events = target._events;\n if (events === void 0) return [];\n const listener = events[type];\n if (listener === void 0) return [];\n if (typeof listener === "function") return unwrap ? [unwrapListener(listener)] : [listener];\n return unwrap ? unwrapListeners(listener) : listener.slice();\n }\n };\n function checkListener(listener) {\n if (typeof listener !== "function")\n throw new TypeError(\n \'The "listener" argument must be of type Function. Received type \' + typeof listener\n );\n }\n var OnceWrapper = class {\n _fired = false;\n wrapperFunction;\n _listener;\n _eventEmitter;\n _eventType;\n constructor(eventEmitter, eventType, listener) {\n this._eventEmitter = eventEmitter;\n this._eventType = eventType;\n this._listener = listener;\n this.wrapperFunction = this._handle.bind(this);\n this.wrapperFunction.listener = listener;\n }\n _handle(...args) {\n if (this._fired) return;\n this._fired = true;\n this._eventEmitter.removeListener(this._eventType, this.wrapperFunction);\n return this._listener.apply(this._eventEmitter, args);\n }\n };\n function unwrapListener(l) {\n return wrappedListener(l) ?? l;\n }\n function unwrapListeners(arr) {\n return arr.map((l) => wrappedListener(l) ?? l);\n }\n function wrappedListener(l) {\n return l.listener;\n }\n\n // src/sandbox/forked-client/src/protocol/validatorPrimitives.ts\n var ValidationError = class extends Error {\n };\n var scheme = {};\n function findValidator(type, method, kind) {\n const validator = maybeFindValidator(type, method, kind);\n if (!validator) throw new ValidationError(`Unknown scheme for ${kind}: ${type}.${method}`);\n return validator;\n }\n function maybeFindValidator(type, method, kind) {\n const schemeName = type + (kind === "Initializer" ? "" : method[0].toUpperCase() + method.substring(1)) + kind;\n return scheme[schemeName];\n }\n var tFloat = (arg, path, context) => {\n if (arg instanceof Number) return arg.valueOf();\n if (typeof arg === "number") return arg;\n throw new ValidationError(`${path}: expected float, got ${typeof arg}`);\n };\n var tInt = (arg, path, context) => {\n let value;\n if (arg instanceof Number) value = arg.valueOf();\n else if (typeof arg === "number") value = arg;\n else throw new ValidationError(`${path}: expected integer, got ${typeof arg}`);\n if (!Number.isInteger(value))\n throw new ValidationError(`${path}: expected integer, got float ${value}`);\n return value;\n };\n var tBoolean = (arg, path, context) => {\n if (arg instanceof Boolean) return arg.valueOf();\n if (typeof arg === "boolean") return arg;\n throw new ValidationError(`${path}: expected boolean, got ${typeof arg}`);\n };\n var tString = (arg, path, context) => {\n if (arg instanceof String) return arg.valueOf();\n if (typeof arg === "string") return arg;\n throw new ValidationError(`${path}: expected string, got ${typeof arg}`);\n };\n var tBinary = (arg, path, context) => {\n if (context.binary === "fromBase64") {\n if (arg instanceof String) return Buffer.from(arg.valueOf(), "base64");\n if (typeof arg === "string") return Buffer.from(arg, "base64");\n throw new ValidationError(`${path}: expected base64-encoded buffer, got ${typeof arg}`);\n }\n if (context.binary === "toBase64") {\n if (!(arg instanceof Buffer))\n throw new ValidationError(`${path}: expected Buffer, got ${typeof arg}`);\n return arg.toString("base64");\n }\n if (context.binary === "buffer") {\n if (!(arg instanceof Buffer) && !(arg instanceof Object))\n throw new ValidationError(`${path}: expected Buffer, got ${typeof arg}`);\n return arg;\n }\n throw new ValidationError(`Unsupported binary behavior "${context.binary}"`);\n };\n var tAny = (arg, path, context) => {\n return arg;\n };\n var tOptional = (v) => {\n return (arg, path, context) => {\n if (Object.is(arg, void 0)) return arg;\n return v(arg, path, context);\n };\n };\n var tArray = (v) => {\n return (arg, path, context) => {\n if (!Array.isArray(arg))\n throw new ValidationError(`${path}: expected array, got ${typeof arg}`);\n return arg.map((x, index) => v(x, path + "[" + index + "]", context));\n };\n };\n var tObject = (s) => {\n return (arg, path, context) => {\n if (Object.is(arg, null)) throw new ValidationError(`${path}: expected object, got null`);\n if (typeof arg !== "object")\n throw new ValidationError(`${path}: expected object, got ${typeof arg}`);\n const result = {};\n for (const [key, v] of Object.entries(s)) {\n const value = v(arg[key], path ? path + "." + key : key, context);\n if (!Object.is(value, void 0)) result[key] = value;\n }\n if (context.isUnderTest()) {\n for (const [key, value] of Object.entries(arg)) {\n if (key.startsWith("__testHook")) result[key] = value;\n }\n }\n return result;\n };\n };\n var tEnum = (e) => {\n return (arg, path, context) => {\n if (!e.includes(arg)) throw new ValidationError(`${path}: expected one of (${e.join("|")})`);\n return arg;\n };\n };\n var tChannel = (names) => {\n return (arg, path, context) => {\n return context.tChannelImpl(names, arg, path, context);\n };\n };\n var tType = (name) => {\n return (arg, path, context) => {\n const v = scheme[name];\n if (!v) throw new ValidationError(path + \': unknown type "\' + name + \'"\');\n return v(arg, path, context);\n };\n };\n\n // src/sandbox/forked-client/src/protocol/validator.ts\n scheme.StackFrame = tObject({\n file: tString,\n line: tInt,\n column: tInt,\n function: tOptional(tString)\n });\n scheme.Metadata = tObject({\n location: tOptional(\n tObject({\n file: tString,\n line: tOptional(tInt),\n column: tOptional(tInt)\n })\n ),\n title: tOptional(tString),\n internal: tOptional(tBoolean),\n stepId: tOptional(tString)\n });\n scheme.ClientSideCallMetadata = tObject({\n id: tInt,\n stack: tOptional(tArray(tType("StackFrame")))\n });\n scheme.Point = tObject({\n x: tFloat,\n y: tFloat\n });\n scheme.Rect = tObject({\n x: tFloat,\n y: tFloat,\n width: tFloat,\n height: tFloat\n });\n scheme.SerializedValue = tObject({\n n: tOptional(tFloat),\n b: tOptional(tBoolean),\n s: tOptional(tString),\n v: tOptional(tEnum(["null", "undefined", "NaN", "Infinity", "-Infinity", "-0"])),\n d: tOptional(tString),\n u: tOptional(tString),\n bi: tOptional(tString),\n ta: tOptional(\n tObject({\n b: tBinary,\n k: tEnum(["i8", "ui8", "ui8c", "i16", "ui16", "i32", "ui32", "f32", "f64", "bi64", "bui64"])\n })\n ),\n e: tOptional(\n tObject({\n m: tString,\n n: tString,\n s: tString\n })\n ),\n r: tOptional(\n tObject({\n p: tString,\n f: tString\n })\n ),\n a: tOptional(tArray(tType("SerializedValue"))),\n o: tOptional(\n tArray(\n tObject({\n k: tString,\n v: tType("SerializedValue")\n })\n )\n ),\n h: tOptional(tInt),\n id: tOptional(tInt),\n ref: tOptional(tInt)\n });\n scheme.SerializedArgument = tObject({\n value: tType("SerializedValue"),\n handles: tArray(tChannel("*"))\n });\n scheme.ExpectedTextValue = tObject({\n string: tOptional(tString),\n regexSource: tOptional(tString),\n regexFlags: tOptional(tString),\n matchSubstring: tOptional(tBoolean),\n ignoreCase: tOptional(tBoolean),\n normalizeWhiteSpace: tOptional(tBoolean)\n });\n scheme.SelectorEngine = tObject({\n name: tString,\n source: tString,\n contentScript: tOptional(tBoolean)\n });\n scheme.URLPattern = tObject({\n hash: tString,\n hostname: tString,\n password: tString,\n pathname: tString,\n port: tString,\n protocol: tString,\n search: tString,\n username: tString\n });\n scheme.SetNetworkCookie = tObject({\n name: tString,\n value: tString,\n url: tOptional(tString),\n domain: tOptional(tString),\n path: tOptional(tString),\n expires: tOptional(tFloat),\n httpOnly: tOptional(tBoolean),\n secure: tOptional(tBoolean),\n sameSite: tOptional(tEnum(["Strict", "Lax", "None"])),\n partitionKey: tOptional(tString),\n _crHasCrossSiteAncestor: tOptional(tBoolean)\n });\n scheme.NetworkCookie = tObject({\n name: tString,\n value: tString,\n domain: tString,\n path: tString,\n expires: tFloat,\n httpOnly: tBoolean,\n secure: tBoolean,\n sameSite: tEnum(["Strict", "Lax", "None"]),\n partitionKey: tOptional(tString),\n _crHasCrossSiteAncestor: tOptional(tBoolean)\n });\n scheme.NameValue = tObject({\n name: tString,\n value: tString\n });\n scheme.IndexedDBDatabase = tObject({\n name: tString,\n version: tInt,\n stores: tArray(\n tObject({\n name: tString,\n autoIncrement: tBoolean,\n keyPath: tOptional(tString),\n keyPathArray: tOptional(tArray(tString)),\n records: tArray(\n tObject({\n key: tOptional(tAny),\n keyEncoded: tOptional(tAny),\n value: tOptional(tAny),\n valueEncoded: tOptional(tAny)\n })\n ),\n indexes: tArray(\n tObject({\n name: tString,\n keyPath: tOptional(tString),\n keyPathArray: tOptional(tArray(tString)),\n multiEntry: tBoolean,\n unique: tBoolean\n })\n )\n })\n )\n });\n scheme.SetOriginStorage = tObject({\n origin: tString,\n localStorage: tArray(tType("NameValue")),\n indexedDB: tOptional(tArray(tType("IndexedDBDatabase")))\n });\n scheme.OriginStorage = tObject({\n origin: tString,\n localStorage: tArray(tType("NameValue")),\n indexedDB: tOptional(tArray(tType("IndexedDBDatabase")))\n });\n scheme.SerializedError = tObject({\n error: tOptional(\n tObject({\n message: tString,\n name: tString,\n stack: tOptional(tString)\n })\n ),\n value: tOptional(tType("SerializedValue"))\n });\n scheme.RecordHarOptions = tObject({\n zip: tOptional(tBoolean),\n content: tOptional(tEnum(["embed", "attach", "omit"])),\n mode: tOptional(tEnum(["full", "minimal"])),\n urlGlob: tOptional(tString),\n urlRegexSource: tOptional(tString),\n urlRegexFlags: tOptional(tString)\n });\n scheme.FormField = tObject({\n name: tString,\n value: tOptional(tString),\n file: tOptional(\n tObject({\n name: tString,\n mimeType: tOptional(tString),\n buffer: tBinary\n })\n )\n });\n scheme.SDKLanguage = tEnum(["javascript", "python", "java", "csharp"]);\n scheme.APIRequestContextInitializer = tObject({\n tracing: tChannel(["Tracing"])\n });\n scheme.APIRequestContextFetchParams = tObject({\n url: tString,\n encodedParams: tOptional(tString),\n params: tOptional(tArray(tType("NameValue"))),\n method: tOptional(tString),\n headers: tOptional(tArray(tType("NameValue"))),\n postData: tOptional(tBinary),\n jsonData: tOptional(tString),\n formData: tOptional(tArray(tType("NameValue"))),\n multipartData: tOptional(tArray(tType("FormField"))),\n timeout: tFloat,\n failOnStatusCode: tOptional(tBoolean),\n ignoreHTTPSErrors: tOptional(tBoolean),\n maxRedirects: tOptional(tInt),\n maxRetries: tOptional(tInt)\n });\n scheme.APIRequestContextFetchResult = tObject({\n response: tType("APIResponse")\n });\n scheme.APIRequestContextFetchResponseBodyParams = tObject({\n fetchUid: tString\n });\n scheme.APIRequestContextFetchResponseBodyResult = tObject({\n binary: tOptional(tBinary)\n });\n scheme.APIRequestContextFetchLogParams = tObject({\n fetchUid: tString\n });\n scheme.APIRequestContextFetchLogResult = tObject({\n log: tArray(tString)\n });\n scheme.APIRequestContextStorageStateParams = tObject({\n indexedDB: tOptional(tBoolean)\n });\n scheme.APIRequestContextStorageStateResult = tObject({\n cookies: tArray(tType("NetworkCookie")),\n origins: tArray(tType("OriginStorage"))\n });\n scheme.APIRequestContextDisposeAPIResponseParams = tObject({\n fetchUid: tString\n });\n scheme.APIRequestContextDisposeAPIResponseResult = tOptional(tObject({}));\n scheme.APIRequestContextDisposeParams = tObject({\n reason: tOptional(tString)\n });\n scheme.APIRequestContextDisposeResult = tOptional(tObject({}));\n scheme.APIResponse = tObject({\n fetchUid: tString,\n url: tString,\n status: tInt,\n statusText: tString,\n headers: tArray(tType("NameValue"))\n });\n scheme.LifecycleEvent = tEnum(["load", "domcontentloaded", "networkidle", "commit"]);\n scheme.ConsoleMessagesFilter = tEnum(["all", "sinceNavigation"]);\n scheme.LocalUtilsInitializer = tObject({\n deviceDescriptors: tArray(\n tObject({\n name: tString,\n descriptor: tObject({\n userAgent: tString,\n viewport: tObject({\n width: tInt,\n height: tInt\n }),\n screen: tOptional(\n tObject({\n width: tInt,\n height: tInt\n })\n ),\n deviceScaleFactor: tFloat,\n isMobile: tBoolean,\n hasTouch: tBoolean,\n defaultBrowserType: tEnum(["chromium", "firefox", "webkit"])\n })\n })\n )\n });\n scheme.LocalUtilsZipParams = tObject({\n zipFile: tString,\n entries: tArray(tType("NameValue")),\n stacksId: tOptional(tString),\n mode: tEnum(["write", "append"]),\n includeSources: tBoolean,\n additionalSources: tOptional(tArray(tString))\n });\n scheme.LocalUtilsZipResult = tOptional(tObject({}));\n scheme.LocalUtilsHarOpenParams = tObject({\n file: tString\n });\n scheme.LocalUtilsHarOpenResult = tObject({\n harId: tOptional(tString),\n error: tOptional(tString)\n });\n scheme.LocalUtilsHarLookupParams = tObject({\n harId: tString,\n url: tString,\n method: tString,\n headers: tArray(tType("NameValue")),\n postData: tOptional(tBinary),\n isNavigationRequest: tBoolean\n });\n scheme.LocalUtilsHarLookupResult = tObject({\n action: tEnum(["error", "redirect", "fulfill", "noentry"]),\n message: tOptional(tString),\n redirectURL: tOptional(tString),\n status: tOptional(tInt),\n headers: tOptional(tArray(tType("NameValue"))),\n body: tOptional(tBinary)\n });\n scheme.LocalUtilsHarCloseParams = tObject({\n harId: tString\n });\n scheme.LocalUtilsHarCloseResult = tOptional(tObject({}));\n scheme.LocalUtilsHarUnzipParams = tObject({\n zipFile: tString,\n harFile: tString\n });\n scheme.LocalUtilsHarUnzipResult = tOptional(tObject({}));\n scheme.LocalUtilsConnectParams = tObject({\n endpoint: tString,\n headers: tOptional(tAny),\n exposeNetwork: tOptional(tString),\n slowMo: tOptional(tFloat),\n timeout: tFloat,\n socksProxyRedirectPortForTest: tOptional(tInt)\n });\n scheme.LocalUtilsConnectResult = tObject({\n pipe: tChannel(["JsonPipe"]),\n headers: tArray(tType("NameValue"))\n });\n scheme.LocalUtilsTracingStartedParams = tObject({\n tracesDir: tOptional(tString),\n traceName: tString,\n live: tOptional(tBoolean)\n });\n scheme.LocalUtilsTracingStartedResult = tObject({\n stacksId: tString\n });\n scheme.LocalUtilsAddStackToTracingNoReplyParams = tObject({\n callData: tType("ClientSideCallMetadata")\n });\n scheme.LocalUtilsAddStackToTracingNoReplyResult = tOptional(tObject({}));\n scheme.LocalUtilsTraceDiscardedParams = tObject({\n stacksId: tString\n });\n scheme.LocalUtilsTraceDiscardedResult = tOptional(tObject({}));\n scheme.LocalUtilsGlobToRegexParams = tObject({\n glob: tString,\n baseURL: tOptional(tString),\n webSocketUrl: tOptional(tBoolean)\n });\n scheme.LocalUtilsGlobToRegexResult = tObject({\n regex: tString\n });\n scheme.RootInitializer = tOptional(tObject({}));\n scheme.RootInitializeParams = tObject({\n sdkLanguage: tType("SDKLanguage")\n });\n scheme.RootInitializeResult = tObject({\n playwright: tChannel(["Playwright"])\n });\n scheme.PlaywrightInitializer = tObject({\n chromium: tChannel(["BrowserType"]),\n firefox: tChannel(["BrowserType"]),\n webkit: tChannel(["BrowserType"]),\n android: tChannel(["Android"]),\n electron: tChannel(["Electron"]),\n utils: tOptional(tChannel(["LocalUtils"])),\n preLaunchedBrowser: tOptional(tChannel(["Browser"])),\n preConnectedAndroidDevice: tOptional(tChannel(["AndroidDevice"])),\n socksSupport: tOptional(tChannel(["SocksSupport"]))\n });\n scheme.PlaywrightNewRequestParams = tObject({\n baseURL: tOptional(tString),\n userAgent: tOptional(tString),\n ignoreHTTPSErrors: tOptional(tBoolean),\n extraHTTPHeaders: tOptional(tArray(tType("NameValue"))),\n failOnStatusCode: tOptional(tBoolean),\n clientCertificates: tOptional(\n tArray(\n tObject({\n origin: tString,\n cert: tOptional(tBinary),\n key: tOptional(tBinary),\n passphrase: tOptional(tString),\n pfx: tOptional(tBinary)\n })\n )\n ),\n maxRedirects: tOptional(tInt),\n httpCredentials: tOptional(\n tObject({\n username: tString,\n password: tString,\n origin: tOptional(tString),\n send: tOptional(tEnum(["always", "unauthorized"]))\n })\n ),\n proxy: tOptional(\n tObject({\n server: tString,\n bypass: tOptional(tString),\n username: tOptional(tString),\n password: tOptional(tString)\n })\n ),\n storageState: tOptional(\n tObject({\n cookies: tOptional(tArray(tType("NetworkCookie"))),\n origins: tOptional(tArray(tType("SetOriginStorage")))\n })\n ),\n tracesDir: tOptional(tString)\n });\n scheme.PlaywrightNewRequestResult = tObject({\n request: tChannel(["APIRequestContext"])\n });\n scheme.RecorderSource = tObject({\n isRecorded: tBoolean,\n id: tString,\n label: tString,\n text: tString,\n language: tString,\n highlight: tArray(\n tObject({\n line: tInt,\n type: tString\n })\n ),\n revealLine: tOptional(tInt),\n group: tOptional(tString)\n });\n scheme.DebugControllerInitializer = tOptional(tObject({}));\n scheme.DebugControllerInspectRequestedEvent = tObject({\n selector: tString,\n locator: tString,\n ariaSnapshot: tString\n });\n scheme.DebugControllerSetModeRequestedEvent = tObject({\n mode: tString\n });\n scheme.DebugControllerStateChangedEvent = tObject({\n pageCount: tInt\n });\n scheme.DebugControllerSourceChangedEvent = tObject({\n text: tString,\n header: tOptional(tString),\n footer: tOptional(tString),\n actions: tOptional(tArray(tString))\n });\n scheme.DebugControllerPausedEvent = tObject({\n paused: tBoolean\n });\n scheme.DebugControllerInitializeParams = tObject({\n codegenId: tString,\n sdkLanguage: tType("SDKLanguage")\n });\n scheme.DebugControllerInitializeResult = tOptional(tObject({}));\n scheme.DebugControllerSetReportStateChangedParams = tObject({\n enabled: tBoolean\n });\n scheme.DebugControllerSetReportStateChangedResult = tOptional(tObject({}));\n scheme.DebugControllerSetRecorderModeParams = tObject({\n mode: tEnum(["inspecting", "recording", "none"]),\n testIdAttributeName: tOptional(tString),\n generateAutoExpect: tOptional(tBoolean)\n });\n scheme.DebugControllerSetRecorderModeResult = tOptional(tObject({}));\n scheme.DebugControllerHighlightParams = tObject({\n selector: tOptional(tString),\n ariaTemplate: tOptional(tString)\n });\n scheme.DebugControllerHighlightResult = tOptional(tObject({}));\n scheme.DebugControllerHideHighlightParams = tOptional(tObject({}));\n scheme.DebugControllerHideHighlightResult = tOptional(tObject({}));\n scheme.DebugControllerResumeParams = tOptional(tObject({}));\n scheme.DebugControllerResumeResult = tOptional(tObject({}));\n scheme.DebugControllerKillParams = tOptional(tObject({}));\n scheme.DebugControllerKillResult = tOptional(tObject({}));\n scheme.SocksSupportInitializer = tOptional(tObject({}));\n scheme.SocksSupportSocksRequestedEvent = tObject({\n uid: tString,\n host: tString,\n port: tInt\n });\n scheme.SocksSupportSocksDataEvent = tObject({\n uid: tString,\n data: tBinary\n });\n scheme.SocksSupportSocksClosedEvent = tObject({\n uid: tString\n });\n scheme.SocksSupportSocksConnectedParams = tObject({\n uid: tString,\n host: tString,\n port: tInt\n });\n scheme.SocksSupportSocksConnectedResult = tOptional(tObject({}));\n scheme.SocksSupportSocksFailedParams = tObject({\n uid: tString,\n errorCode: tString\n });\n scheme.SocksSupportSocksFailedResult = tOptional(tObject({}));\n scheme.SocksSupportSocksDataParams = tObject({\n uid: tString,\n data: tBinary\n });\n scheme.SocksSupportSocksDataResult = tOptional(tObject({}));\n scheme.SocksSupportSocksErrorParams = tObject({\n uid: tString,\n error: tString\n });\n scheme.SocksSupportSocksErrorResult = tOptional(tObject({}));\n scheme.SocksSupportSocksEndParams = tObject({\n uid: tString\n });\n scheme.SocksSupportSocksEndResult = tOptional(tObject({}));\n scheme.BrowserTypeInitializer = tObject({\n executablePath: tString,\n name: tString\n });\n scheme.BrowserTypeLaunchParams = tObject({\n channel: tOptional(tString),\n executablePath: tOptional(tString),\n args: tOptional(tArray(tString)),\n ignoreAllDefaultArgs: tOptional(tBoolean),\n ignoreDefaultArgs: tOptional(tArray(tString)),\n assistantMode: tOptional(tBoolean),\n handleSIGINT: tOptional(tBoolean),\n handleSIGTERM: tOptional(tBoolean),\n handleSIGHUP: tOptional(tBoolean),\n timeout: tFloat,\n env: tOptional(tArray(tType("NameValue"))),\n headless: tOptional(tBoolean),\n proxy: tOptional(\n tObject({\n server: tString,\n bypass: tOptional(tString),\n username: tOptional(tString),\n password: tOptional(tString)\n })\n ),\n downloadsPath: tOptional(tString),\n tracesDir: tOptional(tString),\n artifactsDir: tOptional(tString),\n chromiumSandbox: tOptional(tBoolean),\n firefoxUserPrefs: tOptional(tAny),\n cdpPort: tOptional(tInt),\n slowMo: tOptional(tFloat)\n });\n scheme.BrowserTypeLaunchResult = tObject({\n browser: tChannel(["Browser"])\n });\n scheme.BrowserTypeLaunchPersistentContextParams = tObject({\n channel: tOptional(tString),\n executablePath: tOptional(tString),\n args: tOptional(tArray(tString)),\n ignoreAllDefaultArgs: tOptional(tBoolean),\n ignoreDefaultArgs: tOptional(tArray(tString)),\n assistantMode: tOptional(tBoolean),\n handleSIGINT: tOptional(tBoolean),\n handleSIGTERM: tOptional(tBoolean),\n handleSIGHUP: tOptional(tBoolean),\n timeout: tFloat,\n env: tOptional(tArray(tType("NameValue"))),\n headless: tOptional(tBoolean),\n proxy: tOptional(\n tObject({\n server: tString,\n bypass: tOptional(tString),\n username: tOptional(tString),\n password: tOptional(tString)\n })\n ),\n downloadsPath: tOptional(tString),\n tracesDir: tOptional(tString),\n artifactsDir: tOptional(tString),\n chromiumSandbox: tOptional(tBoolean),\n firefoxUserPrefs: tOptional(tAny),\n cdpPort: tOptional(tInt),\n noDefaultViewport: tOptional(tBoolean),\n viewport: tOptional(\n tObject({\n width: tInt,\n height: tInt\n })\n ),\n screen: tOptional(\n tObject({\n width: tInt,\n height: tInt\n })\n ),\n ignoreHTTPSErrors: tOptional(tBoolean),\n clientCertificates: tOptional(\n tArray(\n tObject({\n origin: tString,\n cert: tOptional(tBinary),\n key: tOptional(tBinary),\n passphrase: tOptional(tString),\n pfx: tOptional(tBinary)\n })\n )\n ),\n javaScriptEnabled: tOptional(tBoolean),\n bypassCSP: tOptional(tBoolean),\n userAgent: tOptional(tString),\n locale: tOptional(tString),\n timezoneId: tOptional(tString),\n geolocation: tOptional(\n tObject({\n longitude: tFloat,\n latitude: tFloat,\n accuracy: tOptional(tFloat)\n })\n ),\n permissions: tOptional(tArray(tString)),\n extraHTTPHeaders: tOptional(tArray(tType("NameValue"))),\n offline: tOptional(tBoolean),\n httpCredentials: tOptional(\n tObject({\n username: tString,\n password: tString,\n origin: tOptional(tString),\n send: tOptional(tEnum(["always", "unauthorized"]))\n })\n ),\n deviceScaleFactor: tOptional(tFloat),\n isMobile: tOptional(tBoolean),\n hasTouch: tOptional(tBoolean),\n colorScheme: tOptional(tEnum(["dark", "light", "no-preference", "no-override"])),\n reducedMotion: tOptional(tEnum(["reduce", "no-preference", "no-override"])),\n forcedColors: tOptional(tEnum(["active", "none", "no-override"])),\n acceptDownloads: tOptional(tEnum(["accept", "deny", "internal-browser-default"])),\n contrast: tOptional(tEnum(["no-preference", "more", "no-override"])),\n baseURL: tOptional(tString),\n recordVideo: tOptional(\n tObject({\n dir: tString,\n size: tOptional(\n tObject({\n width: tInt,\n height: tInt\n })\n )\n })\n ),\n strictSelectors: tOptional(tBoolean),\n serviceWorkers: tOptional(tEnum(["allow", "block"])),\n selectorEngines: tOptional(tArray(tType("SelectorEngine"))),\n testIdAttributeName: tOptional(tString),\n userDataDir: tString,\n slowMo: tOptional(tFloat)\n });\n scheme.BrowserTypeLaunchPersistentContextResult = tObject({\n browser: tChannel(["Browser"]),\n context: tChannel(["BrowserContext"])\n });\n scheme.BrowserTypeConnectOverCDPParams = tObject({\n endpointURL: tString,\n headers: tOptional(tArray(tType("NameValue"))),\n slowMo: tOptional(tFloat),\n timeout: tFloat,\n isLocal: tOptional(tBoolean)\n });\n scheme.BrowserTypeConnectOverCDPResult = tObject({\n browser: tChannel(["Browser"]),\n defaultContext: tOptional(tChannel(["BrowserContext"]))\n });\n scheme.BrowserTypeConnectOverCDPTransportParams = tObject({\n transport: tBinary\n });\n scheme.BrowserTypeConnectOverCDPTransportResult = tObject({\n browser: tChannel(["Browser"]),\n defaultContext: tOptional(tChannel(["BrowserContext"]))\n });\n scheme.BrowserInitializer = tObject({\n version: tString,\n name: tString\n });\n scheme.BrowserContextEvent = tObject({\n context: tChannel(["BrowserContext"])\n });\n scheme.BrowserCloseEvent = tOptional(tObject({}));\n scheme.BrowserStartServerParams = tObject({\n title: tString,\n workspaceDir: tOptional(tString),\n metadata: tOptional(tAny)\n });\n scheme.BrowserStartServerResult = tObject({\n pipeName: tString\n });\n scheme.BrowserStopServerParams = tOptional(tObject({}));\n scheme.BrowserStopServerResult = tOptional(tObject({}));\n scheme.BrowserCloseParams = tObject({\n reason: tOptional(tString)\n });\n scheme.BrowserCloseResult = tOptional(tObject({}));\n scheme.BrowserKillForTestsParams = tOptional(tObject({}));\n scheme.BrowserKillForTestsResult = tOptional(tObject({}));\n scheme.BrowserDefaultUserAgentForTestParams = tOptional(tObject({}));\n scheme.BrowserDefaultUserAgentForTestResult = tObject({\n userAgent: tString\n });\n scheme.BrowserNewContextParams = tObject({\n noDefaultViewport: tOptional(tBoolean),\n viewport: tOptional(\n tObject({\n width: tInt,\n height: tInt\n })\n ),\n screen: tOptional(\n tObject({\n width: tInt,\n height: tInt\n })\n ),\n ignoreHTTPSErrors: tOptional(tBoolean),\n clientCertificates: tOptional(\n tArray(\n tObject({\n origin: tString,\n cert: tOptional(tBinary),\n key: tOptional(tBinary),\n passphrase: tOptional(tString),\n pfx: tOptional(tBinary)\n })\n )\n ),\n javaScriptEnabled: tOptional(tBoolean),\n bypassCSP: tOptional(tBoolean),\n userAgent: tOptional(tString),\n locale: tOptional(tString),\n timezoneId: tOptional(tString),\n geolocation: tOptional(\n tObject({\n longitude: tFloat,\n latitude: tFloat,\n accuracy: tOptional(tFloat)\n })\n ),\n permissions: tOptional(tArray(tString)),\n extraHTTPHeaders: tOptional(tArray(tType("NameValue"))),\n offline: tOptional(tBoolean),\n httpCredentials: tOptional(\n tObject({\n username: tString,\n password: tString,\n origin: tOptional(tString),\n send: tOptional(tEnum(["always", "unauthorized"]))\n })\n ),\n deviceScaleFactor: tOptional(tFloat),\n isMobile: tOptional(tBoolean),\n hasTouch: tOptional(tBoolean),\n colorScheme: tOptional(tEnum(["dark", "light", "no-preference", "no-override"])),\n reducedMotion: tOptional(tEnum(["reduce", "no-preference", "no-override"])),\n forcedColors: tOptional(tEnum(["active", "none", "no-override"])),\n acceptDownloads: tOptional(tEnum(["accept", "deny", "internal-browser-default"])),\n contrast: tOptional(tEnum(["no-preference", "more", "no-override"])),\n baseURL: tOptional(tString),\n recordVideo: tOptional(\n tObject({\n dir: tString,\n size: tOptional(\n tObject({\n width: tInt,\n height: tInt\n })\n )\n })\n ),\n strictSelectors: tOptional(tBoolean),\n serviceWorkers: tOptional(tEnum(["allow", "block"])),\n selectorEngines: tOptional(tArray(tType("SelectorEngine"))),\n testIdAttributeName: tOptional(tString),\n proxy: tOptional(\n tObject({\n server: tString,\n bypass: tOptional(tString),\n username: tOptional(tString),\n password: tOptional(tString)\n })\n ),\n storageState: tOptional(\n tObject({\n cookies: tOptional(tArray(tType("SetNetworkCookie"))),\n origins: tOptional(tArray(tType("SetOriginStorage")))\n })\n )\n });\n scheme.BrowserNewContextResult = tObject({\n context: tChannel(["BrowserContext"])\n });\n scheme.BrowserNewContextForReuseParams = tObject({\n noDefaultViewport: tOptional(tBoolean),\n viewport: tOptional(\n tObject({\n width: tInt,\n height: tInt\n })\n ),\n screen: tOptional(\n tObject({\n width: tInt,\n height: tInt\n })\n ),\n ignoreHTTPSErrors: tOptional(tBoolean),\n clientCertificates: tOptional(\n tArray(\n tObject({\n origin: tString,\n cert: tOptional(tBinary),\n key: tOptional(tBinary),\n passphrase: tOptional(tString),\n pfx: tOptional(tBinary)\n })\n )\n ),\n javaScriptEnabled: tOptional(tBoolean),\n bypassCSP: tOptional(tBoolean),\n userAgent: tOptional(tString),\n locale: tOptional(tString),\n timezoneId: tOptional(tString),\n geolocation: tOptional(\n tObject({\n longitude: tFloat,\n latitude: tFloat,\n accuracy: tOptional(tFloat)\n })\n ),\n permissions: tOptional(tArray(tString)),\n extraHTTPHeaders: tOptional(tArray(tType("NameValue"))),\n offline: tOptional(tBoolean),\n httpCredentials: tOptional(\n tObject({\n username: tString,\n password: tString,\n origin: tOptional(tString),\n send: tOptional(tEnum(["always", "unauthorized"]))\n })\n ),\n deviceScaleFactor: tOptional(tFloat),\n isMobile: tOptional(tBoolean),\n hasTouch: tOptional(tBoolean),\n colorScheme: tOptional(tEnum(["dark", "light", "no-preference", "no-override"])),\n reducedMotion: tOptional(tEnum(["reduce", "no-preference", "no-override"])),\n forcedColors: tOptional(tEnum(["active", "none", "no-override"])),\n acceptDownloads: tOptional(tEnum(["accept", "deny", "internal-browser-default"])),\n contrast: tOptional(tEnum(["no-preference", "more", "no-override"])),\n baseURL: tOptional(tString),\n recordVideo: tOptional(\n tObject({\n dir: tString,\n size: tOptional(\n tObject({\n width: tInt,\n height: tInt\n })\n )\n })\n ),\n strictSelectors: tOptional(tBoolean),\n serviceWorkers: tOptional(tEnum(["allow", "block"])),\n selectorEngines: tOptional(tArray(tType("SelectorEngine"))),\n testIdAttributeName: tOptional(tString),\n proxy: tOptional(\n tObject({\n server: tString,\n bypass: tOptional(tString),\n username: tOptional(tString),\n password: tOptional(tString)\n })\n ),\n storageState: tOptional(\n tObject({\n cookies: tOptional(tArray(tType("SetNetworkCookie"))),\n origins: tOptional(tArray(tType("SetOriginStorage")))\n })\n )\n });\n scheme.BrowserNewContextForReuseResult = tObject({\n context: tChannel(["BrowserContext"])\n });\n scheme.BrowserDisconnectFromReusedContextParams = tObject({\n reason: tString\n });\n scheme.BrowserDisconnectFromReusedContextResult = tOptional(tObject({}));\n scheme.BrowserNewBrowserCDPSessionParams = tOptional(tObject({}));\n scheme.BrowserNewBrowserCDPSessionResult = tObject({\n session: tChannel(["CDPSession"])\n });\n scheme.BrowserStartTracingParams = tObject({\n page: tOptional(tChannel(["Page"])),\n screenshots: tOptional(tBoolean),\n categories: tOptional(tArray(tString))\n });\n scheme.BrowserStartTracingResult = tOptional(tObject({}));\n scheme.BrowserStopTracingParams = tOptional(tObject({}));\n scheme.BrowserStopTracingResult = tObject({\n artifact: tChannel(["Artifact"])\n });\n scheme.EventTargetInitializer = tOptional(tObject({}));\n scheme.EventTargetWaitForEventInfoParams = tObject({\n info: tObject({\n waitId: tString,\n phase: tEnum(["before", "after", "log"]),\n event: tOptional(tString),\n message: tOptional(tString),\n error: tOptional(tString)\n })\n });\n scheme.BrowserContextWaitForEventInfoParams = tType("EventTargetWaitForEventInfoParams");\n scheme.PageWaitForEventInfoParams = tType("EventTargetWaitForEventInfoParams");\n scheme.WorkerWaitForEventInfoParams = tType("EventTargetWaitForEventInfoParams");\n scheme.WebSocketWaitForEventInfoParams = tType("EventTargetWaitForEventInfoParams");\n scheme.DebuggerWaitForEventInfoParams = tType("EventTargetWaitForEventInfoParams");\n scheme.ElectronApplicationWaitForEventInfoParams = tType("EventTargetWaitForEventInfoParams");\n scheme.AndroidDeviceWaitForEventInfoParams = tType("EventTargetWaitForEventInfoParams");\n scheme.EventTargetWaitForEventInfoResult = tOptional(tObject({}));\n scheme.BrowserContextWaitForEventInfoResult = tType("EventTargetWaitForEventInfoResult");\n scheme.PageWaitForEventInfoResult = tType("EventTargetWaitForEventInfoResult");\n scheme.WorkerWaitForEventInfoResult = tType("EventTargetWaitForEventInfoResult");\n scheme.WebSocketWaitForEventInfoResult = tType("EventTargetWaitForEventInfoResult");\n scheme.DebuggerWaitForEventInfoResult = tType("EventTargetWaitForEventInfoResult");\n scheme.ElectronApplicationWaitForEventInfoResult = tType("EventTargetWaitForEventInfoResult");\n scheme.AndroidDeviceWaitForEventInfoResult = tType("EventTargetWaitForEventInfoResult");\n scheme.BrowserContextInitializer = tObject({\n requestContext: tChannel(["APIRequestContext"]),\n tracing: tChannel(["Tracing"]),\n options: tObject({\n noDefaultViewport: tOptional(tBoolean),\n viewport: tOptional(\n tObject({\n width: tInt,\n height: tInt\n })\n ),\n screen: tOptional(\n tObject({\n width: tInt,\n height: tInt\n })\n ),\n ignoreHTTPSErrors: tOptional(tBoolean),\n clientCertificates: tOptional(\n tArray(\n tObject({\n origin: tString,\n cert: tOptional(tBinary),\n key: tOptional(tBinary),\n passphrase: tOptional(tString),\n pfx: tOptional(tBinary)\n })\n )\n ),\n javaScriptEnabled: tOptional(tBoolean),\n bypassCSP: tOptional(tBoolean),\n userAgent: tOptional(tString),\n locale: tOptional(tString),\n timezoneId: tOptional(tString),\n geolocation: tOptional(\n tObject({\n longitude: tFloat,\n latitude: tFloat,\n accuracy: tOptional(tFloat)\n })\n ),\n permissions: tOptional(tArray(tString)),\n extraHTTPHeaders: tOptional(tArray(tType("NameValue"))),\n offline: tOptional(tBoolean),\n httpCredentials: tOptional(\n tObject({\n username: tString,\n password: tString,\n origin: tOptional(tString),\n send: tOptional(tEnum(["always", "unauthorized"]))\n })\n ),\n deviceScaleFactor: tOptional(tFloat),\n isMobile: tOptional(tBoolean),\n hasTouch: tOptional(tBoolean),\n colorScheme: tOptional(tEnum(["dark", "light", "no-preference", "no-override"])),\n reducedMotion: tOptional(tEnum(["reduce", "no-preference", "no-override"])),\n forcedColors: tOptional(tEnum(["active", "none", "no-override"])),\n acceptDownloads: tOptional(tEnum(["accept", "deny", "internal-browser-default"])),\n contrast: tOptional(tEnum(["no-preference", "more", "no-override"])),\n baseURL: tOptional(tString),\n recordVideo: tOptional(\n tObject({\n dir: tString,\n size: tOptional(\n tObject({\n width: tInt,\n height: tInt\n })\n )\n })\n ),\n strictSelectors: tOptional(tBoolean),\n serviceWorkers: tOptional(tEnum(["allow", "block"])),\n selectorEngines: tOptional(tArray(tType("SelectorEngine"))),\n testIdAttributeName: tOptional(tString)\n })\n });\n scheme.BrowserContextBindingCallEvent = tObject({\n binding: tChannel(["BindingCall"])\n });\n scheme.BrowserContextConsoleEvent = tObject({\n type: tString,\n text: tString,\n args: tArray(tChannel(["ElementHandle", "JSHandle"])),\n location: tObject({\n url: tString,\n lineNumber: tInt,\n columnNumber: tInt\n }),\n timestamp: tOptional(tFloat),\n page: tOptional(tChannel(["Page"])),\n worker: tOptional(tChannel(["Worker"]))\n });\n scheme.BrowserContextCloseEvent = tOptional(tObject({}));\n scheme.BrowserContextDialogEvent = tObject({\n dialog: tChannel(["Dialog"])\n });\n scheme.BrowserContextPageEvent = tObject({\n page: tChannel(["Page"])\n });\n scheme.BrowserContextPageErrorEvent = tObject({\n error: tType("SerializedError"),\n page: tChannel(["Page"])\n });\n scheme.BrowserContextRouteEvent = tObject({\n route: tChannel(["Route"])\n });\n scheme.BrowserContextWebSocketRouteEvent = tObject({\n webSocketRoute: tChannel(["WebSocketRoute"])\n });\n scheme.BrowserContextServiceWorkerEvent = tObject({\n worker: tChannel(["Worker"])\n });\n scheme.BrowserContextRequestEvent = tObject({\n request: tChannel(["Request"]),\n page: tOptional(tChannel(["Page"]))\n });\n scheme.BrowserContextRequestFailedEvent = tObject({\n request: tChannel(["Request"]),\n failureText: tOptional(tString),\n responseEndTiming: tFloat,\n page: tOptional(tChannel(["Page"]))\n });\n scheme.BrowserContextRequestFinishedEvent = tObject({\n request: tChannel(["Request"]),\n response: tOptional(tChannel(["Response"])),\n responseEndTiming: tFloat,\n page: tOptional(tChannel(["Page"]))\n });\n scheme.BrowserContextResponseEvent = tObject({\n response: tChannel(["Response"]),\n page: tOptional(tChannel(["Page"]))\n });\n scheme.BrowserContextRecorderEventEvent = tObject({\n event: tEnum(["actionAdded", "actionUpdated", "signalAdded"]),\n data: tAny,\n page: tChannel(["Page"]),\n code: tString\n });\n scheme.BrowserContextAddCookiesParams = tObject({\n cookies: tArray(tType("SetNetworkCookie"))\n });\n scheme.BrowserContextAddCookiesResult = tOptional(tObject({}));\n scheme.BrowserContextAddInitScriptParams = tObject({\n source: tString\n });\n scheme.BrowserContextAddInitScriptResult = tObject({\n disposable: tChannel(["Disposable"])\n });\n scheme.BrowserContextClearCookiesParams = tObject({\n name: tOptional(tString),\n nameRegexSource: tOptional(tString),\n nameRegexFlags: tOptional(tString),\n domain: tOptional(tString),\n domainRegexSource: tOptional(tString),\n domainRegexFlags: tOptional(tString),\n path: tOptional(tString),\n pathRegexSource: tOptional(tString),\n pathRegexFlags: tOptional(tString)\n });\n scheme.BrowserContextClearCookiesResult = tOptional(tObject({}));\n scheme.BrowserContextClearPermissionsParams = tOptional(tObject({}));\n scheme.BrowserContextClearPermissionsResult = tOptional(tObject({}));\n scheme.BrowserContextCloseParams = tObject({\n reason: tOptional(tString)\n });\n scheme.BrowserContextCloseResult = tOptional(tObject({}));\n scheme.BrowserContextCookiesParams = tObject({\n urls: tArray(tString)\n });\n scheme.BrowserContextCookiesResult = tObject({\n cookies: tArray(tType("NetworkCookie"))\n });\n scheme.BrowserContextExposeBindingParams = tObject({\n name: tString,\n needsHandle: tOptional(tBoolean)\n });\n scheme.BrowserContextExposeBindingResult = tObject({\n disposable: tChannel(["Disposable"])\n });\n scheme.BrowserContextGrantPermissionsParams = tObject({\n permissions: tArray(tString),\n origin: tOptional(tString)\n });\n scheme.BrowserContextGrantPermissionsResult = tOptional(tObject({}));\n scheme.BrowserContextNewPageParams = tOptional(tObject({}));\n scheme.BrowserContextNewPageResult = tObject({\n page: tChannel(["Page"])\n });\n scheme.BrowserContextRegisterSelectorEngineParams = tObject({\n selectorEngine: tType("SelectorEngine")\n });\n scheme.BrowserContextRegisterSelectorEngineResult = tOptional(tObject({}));\n scheme.BrowserContextSetTestIdAttributeNameParams = tObject({\n testIdAttributeName: tString\n });\n scheme.BrowserContextSetTestIdAttributeNameResult = tOptional(tObject({}));\n scheme.BrowserContextSetExtraHTTPHeadersParams = tObject({\n headers: tArray(tType("NameValue"))\n });\n scheme.BrowserContextSetExtraHTTPHeadersResult = tOptional(tObject({}));\n scheme.BrowserContextSetGeolocationParams = tObject({\n geolocation: tOptional(\n tObject({\n longitude: tFloat,\n latitude: tFloat,\n accuracy: tOptional(tFloat)\n })\n )\n });\n scheme.BrowserContextSetGeolocationResult = tOptional(tObject({}));\n scheme.BrowserContextSetHTTPCredentialsParams = tObject({\n httpCredentials: tOptional(\n tObject({\n username: tString,\n password: tString,\n origin: tOptional(tString)\n })\n )\n });\n scheme.BrowserContextSetHTTPCredentialsResult = tOptional(tObject({}));\n scheme.BrowserContextSetNetworkInterceptionPatternsParams = tObject({\n patterns: tArray(\n tObject({\n glob: tOptional(tString),\n regexSource: tOptional(tString),\n regexFlags: tOptional(tString),\n urlPattern: tOptional(tType("URLPattern"))\n })\n )\n });\n scheme.BrowserContextSetNetworkInterceptionPatternsResult = tOptional(tObject({}));\n scheme.BrowserContextSetWebSocketInterceptionPatternsParams = tObject({\n patterns: tArray(\n tObject({\n glob: tOptional(tString),\n regexSource: tOptional(tString),\n regexFlags: tOptional(tString),\n urlPattern: tOptional(tType("URLPattern"))\n })\n )\n });\n scheme.BrowserContextSetWebSocketInterceptionPatternsResult = tOptional(tObject({}));\n scheme.BrowserContextSetOfflineParams = tObject({\n offline: tBoolean\n });\n scheme.BrowserContextSetOfflineResult = tOptional(tObject({}));\n scheme.BrowserContextStorageStateParams = tObject({\n indexedDB: tOptional(tBoolean)\n });\n scheme.BrowserContextStorageStateResult = tObject({\n cookies: tArray(tType("NetworkCookie")),\n origins: tArray(tType("OriginStorage"))\n });\n scheme.BrowserContextSetStorageStateParams = tObject({\n storageState: tOptional(\n tObject({\n cookies: tOptional(tArray(tType("SetNetworkCookie"))),\n origins: tOptional(tArray(tType("SetOriginStorage")))\n })\n )\n });\n scheme.BrowserContextSetStorageStateResult = tOptional(tObject({}));\n scheme.BrowserContextPauseParams = tOptional(tObject({}));\n scheme.BrowserContextPauseResult = tOptional(tObject({}));\n scheme.BrowserContextEnableRecorderParams = tObject({\n language: tOptional(tString),\n mode: tOptional(tEnum(["inspecting", "recording"])),\n recorderMode: tOptional(tEnum(["default", "api"])),\n pauseOnNextStatement: tOptional(tBoolean),\n testIdAttributeName: tOptional(tString),\n launchOptions: tOptional(tAny),\n contextOptions: tOptional(tAny),\n device: tOptional(tString),\n saveStorage: tOptional(tString),\n outputFile: tOptional(tString),\n handleSIGINT: tOptional(tBoolean),\n omitCallTracking: tOptional(tBoolean)\n });\n scheme.BrowserContextEnableRecorderResult = tOptional(tObject({}));\n scheme.BrowserContextDisableRecorderParams = tOptional(tObject({}));\n scheme.BrowserContextDisableRecorderResult = tOptional(tObject({}));\n scheme.BrowserContextExposeConsoleApiParams = tOptional(tObject({}));\n scheme.BrowserContextExposeConsoleApiResult = tOptional(tObject({}));\n scheme.BrowserContextNewCDPSessionParams = tObject({\n page: tOptional(tChannel(["Page"])),\n frame: tOptional(tChannel(["Frame"]))\n });\n scheme.BrowserContextNewCDPSessionResult = tObject({\n session: tChannel(["CDPSession"])\n });\n scheme.BrowserContextHarStartParams = tObject({\n page: tOptional(tChannel(["Page"])),\n options: tType("RecordHarOptions")\n });\n scheme.BrowserContextHarStartResult = tObject({\n harId: tString\n });\n scheme.BrowserContextHarExportParams = tObject({\n harId: tOptional(tString)\n });\n scheme.BrowserContextHarExportResult = tObject({\n artifact: tChannel(["Artifact"])\n });\n scheme.BrowserContextCreateTempFilesParams = tObject({\n rootDirName: tOptional(tString),\n items: tArray(\n tObject({\n name: tString,\n lastModifiedMs: tOptional(tFloat)\n })\n )\n });\n scheme.BrowserContextCreateTempFilesResult = tObject({\n rootDir: tOptional(tChannel(["WritableStream"])),\n writableStreams: tArray(tChannel(["WritableStream"]))\n });\n scheme.BrowserContextUpdateSubscriptionParams = tObject({\n event: tEnum(["console", "dialog", "request", "response", "requestFinished", "requestFailed"]),\n enabled: tBoolean\n });\n scheme.BrowserContextUpdateSubscriptionResult = tOptional(tObject({}));\n scheme.BrowserContextClockFastForwardParams = tObject({\n ticksNumber: tOptional(tFloat),\n ticksString: tOptional(tString)\n });\n scheme.BrowserContextClockFastForwardResult = tOptional(tObject({}));\n scheme.BrowserContextClockInstallParams = tObject({\n timeNumber: tOptional(tFloat),\n timeString: tOptional(tString)\n });\n scheme.BrowserContextClockInstallResult = tOptional(tObject({}));\n scheme.BrowserContextClockPauseAtParams = tObject({\n timeNumber: tOptional(tFloat),\n timeString: tOptional(tString)\n });\n scheme.BrowserContextClockPauseAtResult = tOptional(tObject({}));\n scheme.BrowserContextClockResumeParams = tOptional(tObject({}));\n scheme.BrowserContextClockResumeResult = tOptional(tObject({}));\n scheme.BrowserContextClockRunForParams = tObject({\n ticksNumber: tOptional(tFloat),\n ticksString: tOptional(tString)\n });\n scheme.BrowserContextClockRunForResult = tOptional(tObject({}));\n scheme.BrowserContextClockSetFixedTimeParams = tObject({\n timeNumber: tOptional(tFloat),\n timeString: tOptional(tString)\n });\n scheme.BrowserContextClockSetFixedTimeResult = tOptional(tObject({}));\n scheme.BrowserContextClockSetSystemTimeParams = tObject({\n timeNumber: tOptional(tFloat),\n timeString: tOptional(tString)\n });\n scheme.BrowserContextClockSetSystemTimeResult = tOptional(tObject({}));\n scheme.PageInitializer = tObject({\n mainFrame: tChannel(["Frame"]),\n viewportSize: tOptional(\n tObject({\n width: tInt,\n height: tInt\n })\n ),\n isClosed: tBoolean,\n opener: tOptional(tChannel(["Page"])),\n video: tOptional(tChannel(["Artifact"]))\n });\n scheme.PageBindingCallEvent = tObject({\n binding: tChannel(["BindingCall"])\n });\n scheme.PageCloseEvent = tOptional(tObject({}));\n scheme.PageCrashEvent = tOptional(tObject({}));\n scheme.PageDownloadEvent = tObject({\n url: tString,\n suggestedFilename: tString,\n artifact: tChannel(["Artifact"])\n });\n scheme.PageViewportSizeChangedEvent = tObject({\n viewportSize: tOptional(\n tObject({\n width: tInt,\n height: tInt\n })\n )\n });\n scheme.PageFileChooserEvent = tObject({\n element: tChannel(["ElementHandle"]),\n isMultiple: tBoolean\n });\n scheme.PageFrameAttachedEvent = tObject({\n frame: tChannel(["Frame"])\n });\n scheme.PageFrameDetachedEvent = tObject({\n frame: tChannel(["Frame"])\n });\n scheme.PageLocatorHandlerTriggeredEvent = tObject({\n uid: tInt\n });\n scheme.PageRouteEvent = tObject({\n route: tChannel(["Route"])\n });\n scheme.PageScreencastFrameEvent = tObject({\n data: tBinary\n });\n scheme.PageWebSocketRouteEvent = tObject({\n webSocketRoute: tChannel(["WebSocketRoute"])\n });\n scheme.PageWebSocketEvent = tObject({\n webSocket: tChannel(["WebSocket"])\n });\n scheme.PageWorkerEvent = tObject({\n worker: tChannel(["Worker"])\n });\n scheme.PageAddInitScriptParams = tObject({\n source: tString\n });\n scheme.PageAddInitScriptResult = tObject({\n disposable: tChannel(["Disposable"])\n });\n scheme.PageCloseParams = tObject({\n runBeforeUnload: tOptional(tBoolean),\n reason: tOptional(tString)\n });\n scheme.PageCloseResult = tOptional(tObject({}));\n scheme.PageClearConsoleMessagesParams = tOptional(tObject({}));\n scheme.PageClearConsoleMessagesResult = tOptional(tObject({}));\n scheme.PageConsoleMessagesParams = tObject({\n filter: tOptional(tType("ConsoleMessagesFilter"))\n });\n scheme.PageConsoleMessagesResult = tObject({\n messages: tArray(\n tObject({\n type: tString,\n text: tString,\n args: tArray(tChannel(["ElementHandle", "JSHandle"])),\n location: tObject({\n url: tString,\n lineNumber: tInt,\n columnNumber: tInt\n }),\n timestamp: tFloat\n })\n )\n });\n scheme.PageEmulateMediaParams = tObject({\n media: tOptional(tEnum(["screen", "print", "no-override"])),\n colorScheme: tOptional(tEnum(["dark", "light", "no-preference", "no-override"])),\n reducedMotion: tOptional(tEnum(["reduce", "no-preference", "no-override"])),\n forcedColors: tOptional(tEnum(["active", "none", "no-override"])),\n contrast: tOptional(tEnum(["no-preference", "more", "no-override"]))\n });\n scheme.PageEmulateMediaResult = tOptional(tObject({}));\n scheme.PageExposeBindingParams = tObject({\n name: tString,\n needsHandle: tOptional(tBoolean)\n });\n scheme.PageExposeBindingResult = tObject({\n disposable: tChannel(["Disposable"])\n });\n scheme.PageGoBackParams = tObject({\n timeout: tFloat,\n waitUntil: tOptional(tType("LifecycleEvent"))\n });\n scheme.PageGoBackResult = tObject({\n response: tOptional(tChannel(["Response"]))\n });\n scheme.PageGoForwardParams = tObject({\n timeout: tFloat,\n waitUntil: tOptional(tType("LifecycleEvent"))\n });\n scheme.PageGoForwardResult = tObject({\n response: tOptional(tChannel(["Response"]))\n });\n scheme.PageRequestGCParams = tOptional(tObject({}));\n scheme.PageRequestGCResult = tOptional(tObject({}));\n scheme.PageRegisterLocatorHandlerParams = tObject({\n selector: tString,\n noWaitAfter: tOptional(tBoolean)\n });\n scheme.PageRegisterLocatorHandlerResult = tObject({\n uid: tInt\n });\n scheme.PageResolveLocatorHandlerNoReplyParams = tObject({\n uid: tInt,\n remove: tOptional(tBoolean)\n });\n scheme.PageResolveLocatorHandlerNoReplyResult = tOptional(tObject({}));\n scheme.PageUnregisterLocatorHandlerParams = tObject({\n uid: tInt\n });\n scheme.PageUnregisterLocatorHandlerResult = tOptional(tObject({}));\n scheme.PageReloadParams = tObject({\n timeout: tFloat,\n waitUntil: tOptional(tType("LifecycleEvent"))\n });\n scheme.PageReloadResult = tObject({\n response: tOptional(tChannel(["Response"]))\n });\n scheme.PageExpectScreenshotParams = tObject({\n expected: tOptional(tBinary),\n timeout: tFloat,\n isNot: tBoolean,\n locator: tOptional(\n tObject({\n frame: tChannel(["Frame"]),\n selector: tString\n })\n ),\n comparator: tOptional(tString),\n maxDiffPixels: tOptional(tInt),\n maxDiffPixelRatio: tOptional(tFloat),\n threshold: tOptional(tFloat),\n fullPage: tOptional(tBoolean),\n clip: tOptional(tType("Rect")),\n omitBackground: tOptional(tBoolean),\n caret: tOptional(tEnum(["hide", "initial"])),\n animations: tOptional(tEnum(["disabled", "allow"])),\n scale: tOptional(tEnum(["css", "device"])),\n mask: tOptional(\n tArray(\n tObject({\n frame: tChannel(["Frame"]),\n selector: tString\n })\n )\n ),\n maskColor: tOptional(tString),\n style: tOptional(tString)\n });\n scheme.PageExpectScreenshotResult = tObject({\n diff: tOptional(tBinary),\n errorMessage: tOptional(tString),\n actual: tOptional(tBinary),\n previous: tOptional(tBinary),\n timedOut: tOptional(tBoolean),\n log: tOptional(tArray(tString))\n });\n scheme.PageScreenshotParams = tObject({\n timeout: tFloat,\n type: tOptional(tEnum(["png", "jpeg"])),\n quality: tOptional(tInt),\n fullPage: tOptional(tBoolean),\n clip: tOptional(tType("Rect")),\n omitBackground: tOptional(tBoolean),\n caret: tOptional(tEnum(["hide", "initial"])),\n animations: tOptional(tEnum(["disabled", "allow"])),\n scale: tOptional(tEnum(["css", "device"])),\n mask: tOptional(\n tArray(\n tObject({\n frame: tChannel(["Frame"]),\n selector: tString\n })\n )\n ),\n maskColor: tOptional(tString),\n style: tOptional(tString)\n });\n scheme.PageScreenshotResult = tObject({\n binary: tBinary\n });\n scheme.PageSetExtraHTTPHeadersParams = tObject({\n headers: tArray(tType("NameValue"))\n });\n scheme.PageSetExtraHTTPHeadersResult = tOptional(tObject({}));\n scheme.PageSetNetworkInterceptionPatternsParams = tObject({\n patterns: tArray(\n tObject({\n glob: tOptional(tString),\n regexSource: tOptional(tString),\n regexFlags: tOptional(tString),\n urlPattern: tOptional(tType("URLPattern"))\n })\n )\n });\n scheme.PageSetNetworkInterceptionPatternsResult = tOptional(tObject({}));\n scheme.PageSetWebSocketInterceptionPatternsParams = tObject({\n patterns: tArray(\n tObject({\n glob: tOptional(tString),\n regexSource: tOptional(tString),\n regexFlags: tOptional(tString),\n urlPattern: tOptional(tType("URLPattern"))\n })\n )\n });\n scheme.PageSetWebSocketInterceptionPatternsResult = tOptional(tObject({}));\n scheme.PageSetViewportSizeParams = tObject({\n viewportSize: tObject({\n width: tInt,\n height: tInt\n })\n });\n scheme.PageSetViewportSizeResult = tOptional(tObject({}));\n scheme.PageKeyboardDownParams = tObject({\n key: tString\n });\n scheme.PageKeyboardDownResult = tOptional(tObject({}));\n scheme.PageKeyboardUpParams = tObject({\n key: tString\n });\n scheme.PageKeyboardUpResult = tOptional(tObject({}));\n scheme.PageKeyboardInsertTextParams = tObject({\n text: tString\n });\n scheme.PageKeyboardInsertTextResult = tOptional(tObject({}));\n scheme.PageKeyboardTypeParams = tObject({\n text: tString,\n delay: tOptional(tFloat)\n });\n scheme.PageKeyboardTypeResult = tOptional(tObject({}));\n scheme.PageKeyboardPressParams = tObject({\n key: tString,\n delay: tOptional(tFloat)\n });\n scheme.PageKeyboardPressResult = tOptional(tObject({}));\n scheme.PageMouseMoveParams = tObject({\n x: tFloat,\n y: tFloat,\n steps: tOptional(tInt)\n });\n scheme.PageMouseMoveResult = tOptional(tObject({}));\n scheme.PageMouseDownParams = tObject({\n button: tOptional(tEnum(["left", "right", "middle"])),\n clickCount: tOptional(tInt)\n });\n scheme.PageMouseDownResult = tOptional(tObject({}));\n scheme.PageMouseUpParams = tObject({\n button: tOptional(tEnum(["left", "right", "middle"])),\n clickCount: tOptional(tInt)\n });\n scheme.PageMouseUpResult = tOptional(tObject({}));\n scheme.PageMouseClickParams = tObject({\n x: tFloat,\n y: tFloat,\n delay: tOptional(tFloat),\n button: tOptional(tEnum(["left", "right", "middle"])),\n clickCount: tOptional(tInt)\n });\n scheme.PageMouseClickResult = tOptional(tObject({}));\n scheme.PageMouseWheelParams = tObject({\n deltaX: tFloat,\n deltaY: tFloat\n });\n scheme.PageMouseWheelResult = tOptional(tObject({}));\n scheme.PageTouchscreenTapParams = tObject({\n x: tFloat,\n y: tFloat\n });\n scheme.PageTouchscreenTapResult = tOptional(tObject({}));\n scheme.PageClearPageErrorsParams = tOptional(tObject({}));\n scheme.PageClearPageErrorsResult = tOptional(tObject({}));\n scheme.PagePageErrorsParams = tObject({\n filter: tOptional(tType("ConsoleMessagesFilter"))\n });\n scheme.PagePageErrorsResult = tObject({\n errors: tArray(tType("SerializedError"))\n });\n scheme.PagePdfParams = tObject({\n scale: tOptional(tFloat),\n displayHeaderFooter: tOptional(tBoolean),\n headerTemplate: tOptional(tString),\n footerTemplate: tOptional(tString),\n printBackground: tOptional(tBoolean),\n landscape: tOptional(tBoolean),\n pageRanges: tOptional(tString),\n format: tOptional(tString),\n width: tOptional(tString),\n height: tOptional(tString),\n preferCSSPageSize: tOptional(tBoolean),\n margin: tOptional(\n tObject({\n top: tOptional(tString),\n bottom: tOptional(tString),\n left: tOptional(tString),\n right: tOptional(tString)\n })\n ),\n tagged: tOptional(tBoolean),\n outline: tOptional(tBoolean)\n });\n scheme.PagePdfResult = tObject({\n pdf: tBinary\n });\n scheme.PageRequestsParams = tOptional(tObject({}));\n scheme.PageRequestsResult = tObject({\n requests: tArray(tChannel(["Request"]))\n });\n scheme.PageSnapshotForAIParams = tObject({\n track: tOptional(tString),\n selector: tOptional(tString),\n depth: tOptional(tInt),\n timeout: tFloat\n });\n scheme.PageSnapshotForAIResult = tObject({\n full: tString,\n incremental: tOptional(tString)\n });\n scheme.PageStartJSCoverageParams = tObject({\n resetOnNavigation: tOptional(tBoolean),\n reportAnonymousScripts: tOptional(tBoolean)\n });\n scheme.PageStartJSCoverageResult = tOptional(tObject({}));\n scheme.PageStopJSCoverageParams = tOptional(tObject({}));\n scheme.PageStopJSCoverageResult = tObject({\n entries: tArray(\n tObject({\n url: tString,\n scriptId: tString,\n source: tOptional(tString),\n functions: tArray(\n tObject({\n functionName: tString,\n isBlockCoverage: tBoolean,\n ranges: tArray(\n tObject({\n startOffset: tInt,\n endOffset: tInt,\n count: tInt\n })\n )\n })\n )\n })\n )\n });\n scheme.PageStartCSSCoverageParams = tObject({\n resetOnNavigation: tOptional(tBoolean)\n });\n scheme.PageStartCSSCoverageResult = tOptional(tObject({}));\n scheme.PageStopCSSCoverageParams = tOptional(tObject({}));\n scheme.PageStopCSSCoverageResult = tObject({\n entries: tArray(\n tObject({\n url: tString,\n text: tOptional(tString),\n ranges: tArray(\n tObject({\n start: tInt,\n end: tInt\n })\n )\n })\n )\n });\n scheme.PageBringToFrontParams = tOptional(tObject({}));\n scheme.PageBringToFrontResult = tOptional(tObject({}));\n scheme.PagePickLocatorParams = tOptional(tObject({}));\n scheme.PagePickLocatorResult = tObject({\n selector: tString\n });\n scheme.PageCancelPickLocatorParams = tOptional(tObject({}));\n scheme.PageCancelPickLocatorResult = tOptional(tObject({}));\n scheme.PageStartScreencastParams = tObject({\n maxSize: tOptional(\n tObject({\n width: tInt,\n height: tInt\n })\n )\n });\n scheme.PageStartScreencastResult = tOptional(tObject({}));\n scheme.PageStopScreencastParams = tOptional(tObject({}));\n scheme.PageStopScreencastResult = tOptional(tObject({}));\n scheme.PageVideoStartParams = tObject({\n size: tOptional(\n tObject({\n width: tInt,\n height: tInt\n })\n )\n });\n scheme.PageVideoStartResult = tObject({\n artifact: tChannel(["Artifact"])\n });\n scheme.PageVideoStopParams = tOptional(tObject({}));\n scheme.PageVideoStopResult = tOptional(tObject({}));\n scheme.PageUpdateSubscriptionParams = tObject({\n event: tEnum([\n "console",\n "dialog",\n "fileChooser",\n "request",\n "response",\n "requestFinished",\n "requestFailed"\n ]),\n enabled: tBoolean\n });\n scheme.PageUpdateSubscriptionResult = tOptional(tObject({}));\n scheme.PageSetDockTileParams = tObject({\n image: tBinary\n });\n scheme.PageSetDockTileResult = tOptional(tObject({}));\n scheme.FrameInitializer = tObject({\n url: tString,\n name: tString,\n parentFrame: tOptional(tChannel(["Frame"])),\n loadStates: tArray(tType("LifecycleEvent"))\n });\n scheme.FrameLoadstateEvent = tObject({\n add: tOptional(tType("LifecycleEvent")),\n remove: tOptional(tType("LifecycleEvent"))\n });\n scheme.FrameNavigatedEvent = tObject({\n url: tString,\n name: tString,\n newDocument: tOptional(\n tObject({\n request: tOptional(tChannel(["Request"]))\n })\n ),\n error: tOptional(tString)\n });\n scheme.FrameEvalOnSelectorParams = tObject({\n selector: tString,\n strict: tOptional(tBoolean),\n expression: tString,\n isFunction: tOptional(tBoolean),\n arg: tType("SerializedArgument")\n });\n scheme.FrameEvalOnSelectorResult = tObject({\n value: tType("SerializedValue")\n });\n scheme.FrameEvalOnSelectorAllParams = tObject({\n selector: tString,\n expression: tString,\n isFunction: tOptional(tBoolean),\n arg: tType("SerializedArgument")\n });\n scheme.FrameEvalOnSelectorAllResult = tObject({\n value: tType("SerializedValue")\n });\n scheme.FrameAddScriptTagParams = tObject({\n url: tOptional(tString),\n content: tOptional(tString),\n type: tOptional(tString)\n });\n scheme.FrameAddScriptTagResult = tObject({\n element: tChannel(["ElementHandle"])\n });\n scheme.FrameAddStyleTagParams = tObject({\n url: tOptional(tString),\n content: tOptional(tString)\n });\n scheme.FrameAddStyleTagResult = tObject({\n element: tChannel(["ElementHandle"])\n });\n scheme.FrameAriaSnapshotParams = tObject({\n selector: tString,\n timeout: tFloat\n });\n scheme.FrameAriaSnapshotResult = tObject({\n snapshot: tString\n });\n scheme.FrameBlurParams = tObject({\n selector: tString,\n strict: tOptional(tBoolean),\n timeout: tFloat\n });\n scheme.FrameBlurResult = tOptional(tObject({}));\n scheme.FrameCheckParams = tObject({\n selector: tString,\n strict: tOptional(tBoolean),\n force: tOptional(tBoolean),\n position: tOptional(tType("Point")),\n timeout: tFloat,\n trial: tOptional(tBoolean)\n });\n scheme.FrameCheckResult = tOptional(tObject({}));\n scheme.FrameClickParams = tObject({\n selector: tString,\n strict: tOptional(tBoolean),\n force: tOptional(tBoolean),\n noWaitAfter: tOptional(tBoolean),\n modifiers: tOptional(tArray(tEnum(["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]))),\n position: tOptional(tType("Point")),\n delay: tOptional(tFloat),\n button: tOptional(tEnum(["left", "right", "middle"])),\n clickCount: tOptional(tInt),\n timeout: tFloat,\n trial: tOptional(tBoolean),\n steps: tOptional(tInt)\n });\n scheme.FrameClickResult = tOptional(tObject({}));\n scheme.FrameContentParams = tOptional(tObject({}));\n scheme.FrameContentResult = tObject({\n value: tString\n });\n scheme.FrameDragAndDropParams = tObject({\n source: tString,\n target: tString,\n force: tOptional(tBoolean),\n timeout: tFloat,\n trial: tOptional(tBoolean),\n sourcePosition: tOptional(tType("Point")),\n targetPosition: tOptional(tType("Point")),\n strict: tOptional(tBoolean),\n steps: tOptional(tInt)\n });\n scheme.FrameDragAndDropResult = tOptional(tObject({}));\n scheme.FrameDblclickParams = tObject({\n selector: tString,\n strict: tOptional(tBoolean),\n force: tOptional(tBoolean),\n modifiers: tOptional(tArray(tEnum(["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]))),\n position: tOptional(tType("Point")),\n delay: tOptional(tFloat),\n button: tOptional(tEnum(["left", "right", "middle"])),\n timeout: tFloat,\n trial: tOptional(tBoolean),\n steps: tOptional(tInt)\n });\n scheme.FrameDblclickResult = tOptional(tObject({}));\n scheme.FrameDispatchEventParams = tObject({\n selector: tString,\n strict: tOptional(tBoolean),\n type: tString,\n eventInit: tType("SerializedArgument"),\n timeout: tFloat\n });\n scheme.FrameDispatchEventResult = tOptional(tObject({}));\n scheme.FrameEvaluateExpressionParams = tObject({\n expression: tString,\n isFunction: tOptional(tBoolean),\n arg: tType("SerializedArgument")\n });\n scheme.FrameEvaluateExpressionResult = tObject({\n value: tType("SerializedValue")\n });\n scheme.FrameEvaluateExpressionHandleParams = tObject({\n expression: tString,\n isFunction: tOptional(tBoolean),\n arg: tType("SerializedArgument")\n });\n scheme.FrameEvaluateExpressionHandleResult = tObject({\n handle: tChannel(["ElementHandle", "JSHandle"])\n });\n scheme.FrameFillParams = tObject({\n selector: tString,\n strict: tOptional(tBoolean),\n value: tString,\n force: tOptional(tBoolean),\n timeout: tFloat\n });\n scheme.FrameFillResult = tOptional(tObject({}));\n scheme.FrameFocusParams = tObject({\n selector: tString,\n strict: tOptional(tBoolean),\n timeout: tFloat\n });\n scheme.FrameFocusResult = tOptional(tObject({}));\n scheme.FrameFrameElementParams = tOptional(tObject({}));\n scheme.FrameFrameElementResult = tObject({\n element: tChannel(["ElementHandle"])\n });\n scheme.FrameResolveSelectorParams = tObject({\n selector: tString\n });\n scheme.FrameResolveSelectorResult = tObject({\n resolvedSelector: tString\n });\n scheme.FrameHighlightParams = tObject({\n selector: tString\n });\n scheme.FrameHighlightResult = tOptional(tObject({}));\n scheme.FrameGetAttributeParams = tObject({\n selector: tString,\n strict: tOptional(tBoolean),\n name: tString,\n timeout: tFloat\n });\n scheme.FrameGetAttributeResult = tObject({\n value: tOptional(tString)\n });\n scheme.FrameGotoParams = tObject({\n url: tString,\n timeout: tFloat,\n waitUntil: tOptional(tType("LifecycleEvent")),\n referer: tOptional(tString)\n });\n scheme.FrameGotoResult = tObject({\n response: tOptional(tChannel(["Response"]))\n });\n scheme.FrameHoverParams = tObject({\n selector: tString,\n strict: tOptional(tBoolean),\n force: tOptional(tBoolean),\n modifiers: tOptional(tArray(tEnum(["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]))),\n position: tOptional(tType("Point")),\n timeout: tFloat,\n trial: tOptional(tBoolean)\n });\n scheme.FrameHoverResult = tOptional(tObject({}));\n scheme.FrameInnerHTMLParams = tObject({\n selector: tString,\n strict: tOptional(tBoolean),\n timeout: tFloat\n });\n scheme.FrameInnerHTMLResult = tObject({\n value: tString\n });\n scheme.FrameInnerTextParams = tObject({\n selector: tString,\n strict: tOptional(tBoolean),\n timeout: tFloat\n });\n scheme.FrameInnerTextResult = tObject({\n value: tString\n });\n scheme.FrameInputValueParams = tObject({\n selector: tString,\n strict: tOptional(tBoolean),\n timeout: tFloat\n });\n scheme.FrameInputValueResult = tObject({\n value: tString\n });\n scheme.FrameIsCheckedParams = tObject({\n selector: tString,\n strict: tOptional(tBoolean),\n timeout: tFloat\n });\n scheme.FrameIsCheckedResult = tObject({\n value: tBoolean\n });\n scheme.FrameIsDisabledParams = tObject({\n selector: tString,\n strict: tOptional(tBoolean),\n timeout: tFloat\n });\n scheme.FrameIsDisabledResult = tObject({\n value: tBoolean\n });\n scheme.FrameIsEnabledParams = tObject({\n selector: tString,\n strict: tOptional(tBoolean),\n timeout: tFloat\n });\n scheme.FrameIsEnabledResult = tObject({\n value: tBoolean\n });\n scheme.FrameIsHiddenParams = tObject({\n selector: tString,\n strict: tOptional(tBoolean)\n });\n scheme.FrameIsHiddenResult = tObject({\n value: tBoolean\n });\n scheme.FrameIsVisibleParams = tObject({\n selector: tString,\n strict: tOptional(tBoolean)\n });\n scheme.FrameIsVisibleResult = tObject({\n value: tBoolean\n });\n scheme.FrameIsEditableParams = tObject({\n selector: tString,\n strict: tOptional(tBoolean),\n timeout: tFloat\n });\n scheme.FrameIsEditableResult = tObject({\n value: tBoolean\n });\n scheme.FramePressParams = tObject({\n selector: tString,\n strict: tOptional(tBoolean),\n key: tString,\n delay: tOptional(tFloat),\n noWaitAfter: tOptional(tBoolean),\n timeout: tFloat\n });\n scheme.FramePressResult = tOptional(tObject({}));\n scheme.FrameQuerySelectorParams = tObject({\n selector: tString,\n strict: tOptional(tBoolean)\n });\n scheme.FrameQuerySelectorResult = tObject({\n element: tOptional(tChannel(["ElementHandle"]))\n });\n scheme.FrameQuerySelectorAllParams = tObject({\n selector: tString\n });\n scheme.FrameQuerySelectorAllResult = tObject({\n elements: tArray(tChannel(["ElementHandle"]))\n });\n scheme.FrameQueryCountParams = tObject({\n selector: tString\n });\n scheme.FrameQueryCountResult = tObject({\n value: tInt\n });\n scheme.FrameSelectOptionParams = tObject({\n selector: tString,\n strict: tOptional(tBoolean),\n elements: tOptional(tArray(tChannel(["ElementHandle"]))),\n options: tOptional(\n tArray(\n tObject({\n valueOrLabel: tOptional(tString),\n value: tOptional(tString),\n label: tOptional(tString),\n index: tOptional(tInt)\n })\n )\n ),\n force: tOptional(tBoolean),\n timeout: tFloat\n });\n scheme.FrameSelectOptionResult = tObject({\n values: tArray(tString)\n });\n scheme.FrameSetContentParams = tObject({\n html: tString,\n timeout: tFloat,\n waitUntil: tOptional(tType("LifecycleEvent"))\n });\n scheme.FrameSetContentResult = tOptional(tObject({}));\n scheme.FrameSetInputFilesParams = tObject({\n selector: tString,\n strict: tOptional(tBoolean),\n payloads: tOptional(\n tArray(\n tObject({\n name: tString,\n mimeType: tOptional(tString),\n buffer: tBinary\n })\n )\n ),\n localDirectory: tOptional(tString),\n directoryStream: tOptional(tChannel(["WritableStream"])),\n localPaths: tOptional(tArray(tString)),\n streams: tOptional(tArray(tChannel(["WritableStream"]))),\n timeout: tFloat\n });\n scheme.FrameSetInputFilesResult = tOptional(tObject({}));\n scheme.FrameTapParams = tObject({\n selector: tString,\n strict: tOptional(tBoolean),\n force: tOptional(tBoolean),\n modifiers: tOptional(tArray(tEnum(["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]))),\n position: tOptional(tType("Point")),\n timeout: tFloat,\n trial: tOptional(tBoolean)\n });\n scheme.FrameTapResult = tOptional(tObject({}));\n scheme.FrameTextContentParams = tObject({\n selector: tString,\n strict: tOptional(tBoolean),\n timeout: tFloat\n });\n scheme.FrameTextContentResult = tObject({\n value: tOptional(tString)\n });\n scheme.FrameTitleParams = tOptional(tObject({}));\n scheme.FrameTitleResult = tObject({\n value: tString\n });\n scheme.FrameTypeParams = tObject({\n selector: tString,\n strict: tOptional(tBoolean),\n text: tString,\n delay: tOptional(tFloat),\n timeout: tFloat\n });\n scheme.FrameTypeResult = tOptional(tObject({}));\n scheme.FrameUncheckParams = tObject({\n selector: tString,\n strict: tOptional(tBoolean),\n force: tOptional(tBoolean),\n position: tOptional(tType("Point")),\n timeout: tFloat,\n trial: tOptional(tBoolean)\n });\n scheme.FrameUncheckResult = tOptional(tObject({}));\n scheme.FrameWaitForTimeoutParams = tObject({\n waitTimeout: tFloat\n });\n scheme.FrameWaitForTimeoutResult = tOptional(tObject({}));\n scheme.FrameWaitForFunctionParams = tObject({\n expression: tString,\n isFunction: tOptional(tBoolean),\n arg: tType("SerializedArgument"),\n timeout: tFloat,\n pollingInterval: tOptional(tFloat)\n });\n scheme.FrameWaitForFunctionResult = tObject({\n handle: tChannel(["ElementHandle", "JSHandle"])\n });\n scheme.FrameWaitForSelectorParams = tObject({\n selector: tString,\n strict: tOptional(tBoolean),\n timeout: tFloat,\n state: tOptional(tEnum(["attached", "detached", "visible", "hidden"])),\n omitReturnValue: tOptional(tBoolean)\n });\n scheme.FrameWaitForSelectorResult = tObject({\n element: tOptional(tChannel(["ElementHandle"]))\n });\n scheme.FrameExpectParams = tObject({\n selector: tOptional(tString),\n expression: tString,\n expressionArg: tOptional(tAny),\n expectedText: tOptional(tArray(tType("ExpectedTextValue"))),\n expectedNumber: tOptional(tFloat),\n expectedValue: tOptional(tType("SerializedArgument")),\n useInnerText: tOptional(tBoolean),\n isNot: tBoolean,\n timeout: tFloat\n });\n scheme.FrameExpectResult = tObject({\n matches: tBoolean,\n received: tOptional(tType("SerializedValue")),\n timedOut: tOptional(tBoolean),\n errorMessage: tOptional(tString),\n log: tOptional(tArray(tString))\n });\n scheme.WorkerInitializer = tObject({\n url: tString\n });\n scheme.WorkerCloseEvent = tOptional(tObject({}));\n scheme.WorkerEvaluateExpressionParams = tObject({\n expression: tString,\n isFunction: tOptional(tBoolean),\n arg: tType("SerializedArgument")\n });\n scheme.WorkerEvaluateExpressionResult = tObject({\n value: tType("SerializedValue")\n });\n scheme.WorkerEvaluateExpressionHandleParams = tObject({\n expression: tString,\n isFunction: tOptional(tBoolean),\n arg: tType("SerializedArgument")\n });\n scheme.WorkerEvaluateExpressionHandleResult = tObject({\n handle: tChannel(["ElementHandle", "JSHandle"])\n });\n scheme.WorkerUpdateSubscriptionParams = tObject({\n event: tEnum(["console"]),\n enabled: tBoolean\n });\n scheme.WorkerUpdateSubscriptionResult = tOptional(tObject({}));\n scheme.DisposableInitializer = tOptional(tObject({}));\n scheme.DisposableDisposeParams = tOptional(tObject({}));\n scheme.DisposableDisposeResult = tOptional(tObject({}));\n scheme.JSHandleInitializer = tObject({\n preview: tString\n });\n scheme.JSHandlePreviewUpdatedEvent = tObject({\n preview: tString\n });\n scheme.ElementHandlePreviewUpdatedEvent = tType("JSHandlePreviewUpdatedEvent");\n scheme.JSHandleDisposeParams = tOptional(tObject({}));\n scheme.ElementHandleDisposeParams = tType("JSHandleDisposeParams");\n scheme.JSHandleDisposeResult = tOptional(tObject({}));\n scheme.ElementHandleDisposeResult = tType("JSHandleDisposeResult");\n scheme.JSHandleEvaluateExpressionParams = tObject({\n expression: tString,\n isFunction: tOptional(tBoolean),\n arg: tType("SerializedArgument")\n });\n scheme.ElementHandleEvaluateExpressionParams = tType("JSHandleEvaluateExpressionParams");\n scheme.JSHandleEvaluateExpressionResult = tObject({\n value: tType("SerializedValue")\n });\n scheme.ElementHandleEvaluateExpressionResult = tType("JSHandleEvaluateExpressionResult");\n scheme.JSHandleEvaluateExpressionHandleParams = tObject({\n expression: tString,\n isFunction: tOptional(tBoolean),\n arg: tType("SerializedArgument")\n });\n scheme.ElementHandleEvaluateExpressionHandleParams = tType(\n "JSHandleEvaluateExpressionHandleParams"\n );\n scheme.JSHandleEvaluateExpressionHandleResult = tObject({\n handle: tChannel(["ElementHandle", "JSHandle"])\n });\n scheme.ElementHandleEvaluateExpressionHandleResult = tType(\n "JSHandleEvaluateExpressionHandleResult"\n );\n scheme.JSHandleGetPropertyListParams = tOptional(tObject({}));\n scheme.ElementHandleGetPropertyListParams = tType("JSHandleGetPropertyListParams");\n scheme.JSHandleGetPropertyListResult = tObject({\n properties: tArray(\n tObject({\n name: tString,\n value: tChannel(["ElementHandle", "JSHandle"])\n })\n )\n });\n scheme.ElementHandleGetPropertyListResult = tType("JSHandleGetPropertyListResult");\n scheme.JSHandleGetPropertyParams = tObject({\n name: tString\n });\n scheme.ElementHandleGetPropertyParams = tType("JSHandleGetPropertyParams");\n scheme.JSHandleGetPropertyResult = tObject({\n handle: tChannel(["ElementHandle", "JSHandle"])\n });\n scheme.ElementHandleGetPropertyResult = tType("JSHandleGetPropertyResult");\n scheme.JSHandleJsonValueParams = tOptional(tObject({}));\n scheme.ElementHandleJsonValueParams = tType("JSHandleJsonValueParams");\n scheme.JSHandleJsonValueResult = tObject({\n value: tType("SerializedValue")\n });\n scheme.ElementHandleJsonValueResult = tType("JSHandleJsonValueResult");\n scheme.ElementHandleInitializer = tObject({\n preview: tString\n });\n scheme.ElementHandleEvalOnSelectorParams = tObject({\n selector: tString,\n strict: tOptional(tBoolean),\n expression: tString,\n isFunction: tOptional(tBoolean),\n arg: tType("SerializedArgument")\n });\n scheme.ElementHandleEvalOnSelectorResult = tObject({\n value: tType("SerializedValue")\n });\n scheme.ElementHandleEvalOnSelectorAllParams = tObject({\n selector: tString,\n expression: tString,\n isFunction: tOptional(tBoolean),\n arg: tType("SerializedArgument")\n });\n scheme.ElementHandleEvalOnSelectorAllResult = tObject({\n value: tType("SerializedValue")\n });\n scheme.ElementHandleBoundingBoxParams = tOptional(tObject({}));\n scheme.ElementHandleBoundingBoxResult = tObject({\n value: tOptional(tType("Rect"))\n });\n scheme.ElementHandleCheckParams = tObject({\n force: tOptional(tBoolean),\n position: tOptional(tType("Point")),\n timeout: tFloat,\n trial: tOptional(tBoolean)\n });\n scheme.ElementHandleCheckResult = tOptional(tObject({}));\n scheme.ElementHandleClickParams = tObject({\n force: tOptional(tBoolean),\n noWaitAfter: tOptional(tBoolean),\n modifiers: tOptional(tArray(tEnum(["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]))),\n position: tOptional(tType("Point")),\n delay: tOptional(tFloat),\n button: tOptional(tEnum(["left", "right", "middle"])),\n clickCount: tOptional(tInt),\n timeout: tFloat,\n trial: tOptional(tBoolean),\n steps: tOptional(tInt)\n });\n scheme.ElementHandleClickResult = tOptional(tObject({}));\n scheme.ElementHandleContentFrameParams = tOptional(tObject({}));\n scheme.ElementHandleContentFrameResult = tObject({\n frame: tOptional(tChannel(["Frame"]))\n });\n scheme.ElementHandleDblclickParams = tObject({\n force: tOptional(tBoolean),\n modifiers: tOptional(tArray(tEnum(["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]))),\n position: tOptional(tType("Point")),\n delay: tOptional(tFloat),\n button: tOptional(tEnum(["left", "right", "middle"])),\n timeout: tFloat,\n trial: tOptional(tBoolean),\n steps: tOptional(tInt)\n });\n scheme.ElementHandleDblclickResult = tOptional(tObject({}));\n scheme.ElementHandleDispatchEventParams = tObject({\n type: tString,\n eventInit: tType("SerializedArgument")\n });\n scheme.ElementHandleDispatchEventResult = tOptional(tObject({}));\n scheme.ElementHandleFillParams = tObject({\n value: tString,\n force: tOptional(tBoolean),\n timeout: tFloat\n });\n scheme.ElementHandleFillResult = tOptional(tObject({}));\n scheme.ElementHandleFocusParams = tOptional(tObject({}));\n scheme.ElementHandleFocusResult = tOptional(tObject({}));\n scheme.ElementHandleGetAttributeParams = tObject({\n name: tString\n });\n scheme.ElementHandleGetAttributeResult = tObject({\n value: tOptional(tString)\n });\n scheme.ElementHandleHoverParams = tObject({\n force: tOptional(tBoolean),\n modifiers: tOptional(tArray(tEnum(["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]))),\n position: tOptional(tType("Point")),\n timeout: tFloat,\n trial: tOptional(tBoolean)\n });\n scheme.ElementHandleHoverResult = tOptional(tObject({}));\n scheme.ElementHandleInnerHTMLParams = tOptional(tObject({}));\n scheme.ElementHandleInnerHTMLResult = tObject({\n value: tString\n });\n scheme.ElementHandleInnerTextParams = tOptional(tObject({}));\n scheme.ElementHandleInnerTextResult = tObject({\n value: tString\n });\n scheme.ElementHandleInputValueParams = tOptional(tObject({}));\n scheme.ElementHandleInputValueResult = tObject({\n value: tString\n });\n scheme.ElementHandleIsCheckedParams = tOptional(tObject({}));\n scheme.ElementHandleIsCheckedResult = tObject({\n value: tBoolean\n });\n scheme.ElementHandleIsDisabledParams = tOptional(tObject({}));\n scheme.ElementHandleIsDisabledResult = tObject({\n value: tBoolean\n });\n scheme.ElementHandleIsEditableParams = tOptional(tObject({}));\n scheme.ElementHandleIsEditableResult = tObject({\n value: tBoolean\n });\n scheme.ElementHandleIsEnabledParams = tOptional(tObject({}));\n scheme.ElementHandleIsEnabledResult = tObject({\n value: tBoolean\n });\n scheme.ElementHandleIsHiddenParams = tOptional(tObject({}));\n scheme.ElementHandleIsHiddenResult = tObject({\n value: tBoolean\n });\n scheme.ElementHandleIsVisibleParams = tOptional(tObject({}));\n scheme.ElementHandleIsVisibleResult = tObject({\n value: tBoolean\n });\n scheme.ElementHandleOwnerFrameParams = tOptional(tObject({}));\n scheme.ElementHandleOwnerFrameResult = tObject({\n frame: tOptional(tChannel(["Frame"]))\n });\n scheme.ElementHandlePressParams = tObject({\n key: tString,\n delay: tOptional(tFloat),\n timeout: tFloat,\n noWaitAfter: tOptional(tBoolean)\n });\n scheme.ElementHandlePressResult = tOptional(tObject({}));\n scheme.ElementHandleQuerySelectorParams = tObject({\n selector: tString,\n strict: tOptional(tBoolean)\n });\n scheme.ElementHandleQuerySelectorResult = tObject({\n element: tOptional(tChannel(["ElementHandle"]))\n });\n scheme.ElementHandleQuerySelectorAllParams = tObject({\n selector: tString\n });\n scheme.ElementHandleQuerySelectorAllResult = tObject({\n elements: tArray(tChannel(["ElementHandle"]))\n });\n scheme.ElementHandleScreenshotParams = tObject({\n timeout: tFloat,\n type: tOptional(tEnum(["png", "jpeg"])),\n quality: tOptional(tInt),\n omitBackground: tOptional(tBoolean),\n caret: tOptional(tEnum(["hide", "initial"])),\n animations: tOptional(tEnum(["disabled", "allow"])),\n scale: tOptional(tEnum(["css", "device"])),\n mask: tOptional(\n tArray(\n tObject({\n frame: tChannel(["Frame"]),\n selector: tString\n })\n )\n ),\n maskColor: tOptional(tString),\n style: tOptional(tString)\n });\n scheme.ElementHandleScreenshotResult = tObject({\n binary: tBinary\n });\n scheme.ElementHandleScrollIntoViewIfNeededParams = tObject({\n timeout: tFloat\n });\n scheme.ElementHandleScrollIntoViewIfNeededResult = tOptional(tObject({}));\n scheme.ElementHandleSelectOptionParams = tObject({\n elements: tOptional(tArray(tChannel(["ElementHandle"]))),\n options: tOptional(\n tArray(\n tObject({\n valueOrLabel: tOptional(tString),\n value: tOptional(tString),\n label: tOptional(tString),\n index: tOptional(tInt)\n })\n )\n ),\n force: tOptional(tBoolean),\n timeout: tFloat\n });\n scheme.ElementHandleSelectOptionResult = tObject({\n values: tArray(tString)\n });\n scheme.ElementHandleSelectTextParams = tObject({\n force: tOptional(tBoolean),\n timeout: tFloat\n });\n scheme.ElementHandleSelectTextResult = tOptional(tObject({}));\n scheme.ElementHandleSetInputFilesParams = tObject({\n payloads: tOptional(\n tArray(\n tObject({\n name: tString,\n mimeType: tOptional(tString),\n buffer: tBinary\n })\n )\n ),\n localDirectory: tOptional(tString),\n directoryStream: tOptional(tChannel(["WritableStream"])),\n localPaths: tOptional(tArray(tString)),\n streams: tOptional(tArray(tChannel(["WritableStream"]))),\n timeout: tFloat\n });\n scheme.ElementHandleSetInputFilesResult = tOptional(tObject({}));\n scheme.ElementHandleTapParams = tObject({\n force: tOptional(tBoolean),\n modifiers: tOptional(tArray(tEnum(["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]))),\n position: tOptional(tType("Point")),\n timeout: tFloat,\n trial: tOptional(tBoolean)\n });\n scheme.ElementHandleTapResult = tOptional(tObject({}));\n scheme.ElementHandleTextContentParams = tOptional(tObject({}));\n scheme.ElementHandleTextContentResult = tObject({\n value: tOptional(tString)\n });\n scheme.ElementHandleTypeParams = tObject({\n text: tString,\n delay: tOptional(tFloat),\n timeout: tFloat\n });\n scheme.ElementHandleTypeResult = tOptional(tObject({}));\n scheme.ElementHandleUncheckParams = tObject({\n force: tOptional(tBoolean),\n position: tOptional(tType("Point")),\n timeout: tFloat,\n trial: tOptional(tBoolean)\n });\n scheme.ElementHandleUncheckResult = tOptional(tObject({}));\n scheme.ElementHandleWaitForElementStateParams = tObject({\n state: tEnum(["visible", "hidden", "stable", "enabled", "disabled", "editable"]),\n timeout: tFloat\n });\n scheme.ElementHandleWaitForElementStateResult = tOptional(tObject({}));\n scheme.ElementHandleWaitForSelectorParams = tObject({\n selector: tString,\n strict: tOptional(tBoolean),\n timeout: tFloat,\n state: tOptional(tEnum(["attached", "detached", "visible", "hidden"]))\n });\n scheme.ElementHandleWaitForSelectorResult = tObject({\n element: tOptional(tChannel(["ElementHandle"]))\n });\n scheme.RequestInitializer = tObject({\n frame: tOptional(tChannel(["Frame"])),\n serviceWorker: tOptional(tChannel(["Worker"])),\n url: tString,\n resourceType: tString,\n method: tString,\n postData: tOptional(tBinary),\n headers: tArray(tType("NameValue")),\n isNavigationRequest: tBoolean,\n redirectedFrom: tOptional(tChannel(["Request"])),\n hasResponse: tBoolean\n });\n scheme.RequestResponseEvent = tOptional(tObject({}));\n scheme.RequestResponseParams = tOptional(tObject({}));\n scheme.RequestResponseResult = tObject({\n response: tOptional(tChannel(["Response"]))\n });\n scheme.RequestRawRequestHeadersParams = tOptional(tObject({}));\n scheme.RequestRawRequestHeadersResult = tObject({\n headers: tArray(tType("NameValue"))\n });\n scheme.RouteInitializer = tObject({\n request: tChannel(["Request"])\n });\n scheme.RouteRedirectNavigationRequestParams = tObject({\n url: tString\n });\n scheme.RouteRedirectNavigationRequestResult = tOptional(tObject({}));\n scheme.RouteAbortParams = tObject({\n errorCode: tOptional(tString)\n });\n scheme.RouteAbortResult = tOptional(tObject({}));\n scheme.RouteContinueParams = tObject({\n url: tOptional(tString),\n method: tOptional(tString),\n headers: tOptional(tArray(tType("NameValue"))),\n postData: tOptional(tBinary),\n isFallback: tBoolean\n });\n scheme.RouteContinueResult = tOptional(tObject({}));\n scheme.RouteFulfillParams = tObject({\n status: tOptional(tInt),\n headers: tOptional(tArray(tType("NameValue"))),\n body: tOptional(tString),\n isBase64: tOptional(tBoolean),\n fetchResponseUid: tOptional(tString)\n });\n scheme.RouteFulfillResult = tOptional(tObject({}));\n scheme.WebSocketRouteInitializer = tObject({\n url: tString\n });\n scheme.WebSocketRouteMessageFromPageEvent = tObject({\n message: tString,\n isBase64: tBoolean\n });\n scheme.WebSocketRouteMessageFromServerEvent = tObject({\n message: tString,\n isBase64: tBoolean\n });\n scheme.WebSocketRouteClosePageEvent = tObject({\n code: tOptional(tInt),\n reason: tOptional(tString),\n wasClean: tBoolean\n });\n scheme.WebSocketRouteCloseServerEvent = tObject({\n code: tOptional(tInt),\n reason: tOptional(tString),\n wasClean: tBoolean\n });\n scheme.WebSocketRouteConnectParams = tOptional(tObject({}));\n scheme.WebSocketRouteConnectResult = tOptional(tObject({}));\n scheme.WebSocketRouteEnsureOpenedParams = tOptional(tObject({}));\n scheme.WebSocketRouteEnsureOpenedResult = tOptional(tObject({}));\n scheme.WebSocketRouteSendToPageParams = tObject({\n message: tString,\n isBase64: tBoolean\n });\n scheme.WebSocketRouteSendToPageResult = tOptional(tObject({}));\n scheme.WebSocketRouteSendToServerParams = tObject({\n message: tString,\n isBase64: tBoolean\n });\n scheme.WebSocketRouteSendToServerResult = tOptional(tObject({}));\n scheme.WebSocketRouteClosePageParams = tObject({\n code: tOptional(tInt),\n reason: tOptional(tString),\n wasClean: tBoolean\n });\n scheme.WebSocketRouteClosePageResult = tOptional(tObject({}));\n scheme.WebSocketRouteCloseServerParams = tObject({\n code: tOptional(tInt),\n reason: tOptional(tString),\n wasClean: tBoolean\n });\n scheme.WebSocketRouteCloseServerResult = tOptional(tObject({}));\n scheme.ResourceTiming = tObject({\n startTime: tFloat,\n domainLookupStart: tFloat,\n domainLookupEnd: tFloat,\n connectStart: tFloat,\n secureConnectionStart: tFloat,\n connectEnd: tFloat,\n requestStart: tFloat,\n responseStart: tFloat\n });\n scheme.ResponseInitializer = tObject({\n request: tChannel(["Request"]),\n url: tString,\n status: tInt,\n statusText: tString,\n headers: tArray(tType("NameValue")),\n timing: tType("ResourceTiming"),\n fromServiceWorker: tBoolean\n });\n scheme.ResponseBodyParams = tOptional(tObject({}));\n scheme.ResponseBodyResult = tObject({\n binary: tBinary\n });\n scheme.ResponseSecurityDetailsParams = tOptional(tObject({}));\n scheme.ResponseSecurityDetailsResult = tObject({\n value: tOptional(tType("SecurityDetails"))\n });\n scheme.ResponseServerAddrParams = tOptional(tObject({}));\n scheme.ResponseServerAddrResult = tObject({\n value: tOptional(tType("RemoteAddr"))\n });\n scheme.ResponseRawResponseHeadersParams = tOptional(tObject({}));\n scheme.ResponseRawResponseHeadersResult = tObject({\n headers: tArray(tType("NameValue"))\n });\n scheme.ResponseHttpVersionParams = tOptional(tObject({}));\n scheme.ResponseHttpVersionResult = tObject({\n value: tString\n });\n scheme.ResponseSizesParams = tOptional(tObject({}));\n scheme.ResponseSizesResult = tObject({\n sizes: tType("RequestSizes")\n });\n scheme.SecurityDetails = tObject({\n issuer: tOptional(tString),\n protocol: tOptional(tString),\n subjectName: tOptional(tString),\n validFrom: tOptional(tFloat),\n validTo: tOptional(tFloat)\n });\n scheme.RequestSizes = tObject({\n requestBodySize: tInt,\n requestHeadersSize: tInt,\n responseBodySize: tInt,\n responseHeadersSize: tInt\n });\n scheme.RemoteAddr = tObject({\n ipAddress: tString,\n port: tInt\n });\n scheme.WebSocketInitializer = tObject({\n url: tString\n });\n scheme.WebSocketOpenEvent = tOptional(tObject({}));\n scheme.WebSocketFrameSentEvent = tObject({\n opcode: tInt,\n data: tString\n });\n scheme.WebSocketFrameReceivedEvent = tObject({\n opcode: tInt,\n data: tString\n });\n scheme.WebSocketSocketErrorEvent = tObject({\n error: tString\n });\n scheme.WebSocketCloseEvent = tOptional(tObject({}));\n scheme.BindingCallInitializer = tObject({\n frame: tChannel(["Frame"]),\n name: tString,\n args: tOptional(tArray(tType("SerializedValue"))),\n handle: tOptional(tChannel(["ElementHandle", "JSHandle"]))\n });\n scheme.BindingCallRejectParams = tObject({\n error: tType("SerializedError")\n });\n scheme.BindingCallRejectResult = tOptional(tObject({}));\n scheme.BindingCallResolveParams = tObject({\n result: tType("SerializedArgument")\n });\n scheme.BindingCallResolveResult = tOptional(tObject({}));\n scheme.DebuggerInitializer = tOptional(tObject({}));\n scheme.DebuggerPausedStateChangedEvent = tObject({\n pausedDetails: tArray(\n tObject({\n location: tObject({\n file: tString,\n line: tOptional(tInt),\n column: tOptional(tInt)\n }),\n title: tString\n })\n )\n });\n scheme.DebuggerPauseParams = tOptional(tObject({}));\n scheme.DebuggerPauseResult = tOptional(tObject({}));\n scheme.DebuggerResumeParams = tOptional(tObject({}));\n scheme.DebuggerResumeResult = tOptional(tObject({}));\n scheme.DebuggerNextParams = tOptional(tObject({}));\n scheme.DebuggerNextResult = tOptional(tObject({}));\n scheme.DebuggerRunToParams = tObject({\n location: tObject({\n file: tString,\n line: tOptional(tInt),\n column: tOptional(tInt)\n })\n });\n scheme.DebuggerRunToResult = tOptional(tObject({}));\n scheme.DialogInitializer = tObject({\n page: tOptional(tChannel(["Page"])),\n type: tString,\n message: tString,\n defaultValue: tString\n });\n scheme.DialogAcceptParams = tObject({\n promptText: tOptional(tString)\n });\n scheme.DialogAcceptResult = tOptional(tObject({}));\n scheme.DialogDismissParams = tOptional(tObject({}));\n scheme.DialogDismissResult = tOptional(tObject({}));\n scheme.TracingInitializer = tOptional(tObject({}));\n scheme.TracingTracingStartParams = tObject({\n name: tOptional(tString),\n snapshots: tOptional(tBoolean),\n screenshots: tOptional(tBoolean),\n live: tOptional(tBoolean)\n });\n scheme.TracingTracingStartResult = tOptional(tObject({}));\n scheme.TracingTracingStartChunkParams = tObject({\n name: tOptional(tString),\n title: tOptional(tString)\n });\n scheme.TracingTracingStartChunkResult = tObject({\n traceName: tString\n });\n scheme.TracingTracingGroupParams = tObject({\n name: tString,\n location: tOptional(\n tObject({\n file: tString,\n line: tOptional(tInt),\n column: tOptional(tInt)\n })\n )\n });\n scheme.TracingTracingGroupResult = tOptional(tObject({}));\n scheme.TracingTracingGroupEndParams = tOptional(tObject({}));\n scheme.TracingTracingGroupEndResult = tOptional(tObject({}));\n scheme.TracingTracingStopChunkParams = tObject({\n mode: tEnum(["archive", "discard", "entries"])\n });\n scheme.TracingTracingStopChunkResult = tObject({\n artifact: tOptional(tChannel(["Artifact"])),\n entries: tOptional(tArray(tType("NameValue")))\n });\n scheme.TracingTracingStopParams = tOptional(tObject({}));\n scheme.TracingTracingStopResult = tOptional(tObject({}));\n scheme.ArtifactInitializer = tObject({\n absolutePath: tString\n });\n scheme.ArtifactPathAfterFinishedParams = tOptional(tObject({}));\n scheme.ArtifactPathAfterFinishedResult = tObject({\n value: tString\n });\n scheme.ArtifactSaveAsParams = tObject({\n path: tString\n });\n scheme.ArtifactSaveAsResult = tOptional(tObject({}));\n scheme.ArtifactSaveAsStreamParams = tOptional(tObject({}));\n scheme.ArtifactSaveAsStreamResult = tObject({\n stream: tChannel(["Stream"])\n });\n scheme.ArtifactFailureParams = tOptional(tObject({}));\n scheme.ArtifactFailureResult = tObject({\n error: tOptional(tString)\n });\n scheme.ArtifactStreamParams = tOptional(tObject({}));\n scheme.ArtifactStreamResult = tObject({\n stream: tChannel(["Stream"])\n });\n scheme.ArtifactCancelParams = tOptional(tObject({}));\n scheme.ArtifactCancelResult = tOptional(tObject({}));\n scheme.ArtifactDeleteParams = tOptional(tObject({}));\n scheme.ArtifactDeleteResult = tOptional(tObject({}));\n scheme.StreamInitializer = tOptional(tObject({}));\n scheme.StreamReadParams = tObject({\n size: tOptional(tInt)\n });\n scheme.StreamReadResult = tObject({\n binary: tBinary\n });\n scheme.StreamCloseParams = tOptional(tObject({}));\n scheme.StreamCloseResult = tOptional(tObject({}));\n scheme.WritableStreamInitializer = tOptional(tObject({}));\n scheme.WritableStreamWriteParams = tObject({\n binary: tBinary\n });\n scheme.WritableStreamWriteResult = tOptional(tObject({}));\n scheme.WritableStreamCloseParams = tOptional(tObject({}));\n scheme.WritableStreamCloseResult = tOptional(tObject({}));\n scheme.CDPSessionInitializer = tOptional(tObject({}));\n scheme.CDPSessionEventEvent = tObject({\n method: tString,\n params: tOptional(tAny)\n });\n scheme.CDPSessionCloseEvent = tOptional(tObject({}));\n scheme.CDPSessionSendParams = tObject({\n method: tString,\n params: tOptional(tAny)\n });\n scheme.CDPSessionSendResult = tObject({\n result: tAny\n });\n scheme.CDPSessionDetachParams = tOptional(tObject({}));\n scheme.CDPSessionDetachResult = tOptional(tObject({}));\n scheme.ElectronInitializer = tOptional(tObject({}));\n scheme.ElectronLaunchParams = tObject({\n executablePath: tOptional(tString),\n args: tOptional(tArray(tString)),\n chromiumSandbox: tOptional(tBoolean),\n cwd: tOptional(tString),\n env: tOptional(tArray(tType("NameValue"))),\n timeout: tFloat,\n acceptDownloads: tOptional(tEnum(["accept", "deny", "internal-browser-default"])),\n bypassCSP: tOptional(tBoolean),\n colorScheme: tOptional(tEnum(["dark", "light", "no-preference", "no-override"])),\n extraHTTPHeaders: tOptional(tArray(tType("NameValue"))),\n geolocation: tOptional(\n tObject({\n longitude: tFloat,\n latitude: tFloat,\n accuracy: tOptional(tFloat)\n })\n ),\n httpCredentials: tOptional(\n tObject({\n username: tString,\n password: tString,\n origin: tOptional(tString)\n })\n ),\n ignoreHTTPSErrors: tOptional(tBoolean),\n locale: tOptional(tString),\n offline: tOptional(tBoolean),\n recordVideo: tOptional(\n tObject({\n dir: tString,\n size: tOptional(\n tObject({\n width: tInt,\n height: tInt\n })\n )\n })\n ),\n strictSelectors: tOptional(tBoolean),\n timezoneId: tOptional(tString),\n tracesDir: tOptional(tString),\n selectorEngines: tOptional(tArray(tType("SelectorEngine"))),\n testIdAttributeName: tOptional(tString)\n });\n scheme.ElectronLaunchResult = tObject({\n electronApplication: tChannel(["ElectronApplication"])\n });\n scheme.ElectronApplicationInitializer = tObject({\n context: tChannel(["BrowserContext"])\n });\n scheme.ElectronApplicationCloseEvent = tOptional(tObject({}));\n scheme.ElectronApplicationConsoleEvent = tObject({\n type: tString,\n text: tString,\n args: tArray(tChannel(["ElementHandle", "JSHandle"])),\n location: tObject({\n url: tString,\n lineNumber: tInt,\n columnNumber: tInt\n }),\n timestamp: tFloat\n });\n scheme.ElectronApplicationBrowserWindowParams = tObject({\n page: tChannel(["Page"])\n });\n scheme.ElectronApplicationBrowserWindowResult = tObject({\n handle: tChannel(["ElementHandle", "JSHandle"])\n });\n scheme.ElectronApplicationEvaluateExpressionParams = tObject({\n expression: tString,\n isFunction: tOptional(tBoolean),\n arg: tType("SerializedArgument")\n });\n scheme.ElectronApplicationEvaluateExpressionResult = tObject({\n value: tType("SerializedValue")\n });\n scheme.ElectronApplicationEvaluateExpressionHandleParams = tObject({\n expression: tString,\n isFunction: tOptional(tBoolean),\n arg: tType("SerializedArgument")\n });\n scheme.ElectronApplicationEvaluateExpressionHandleResult = tObject({\n handle: tChannel(["ElementHandle", "JSHandle"])\n });\n scheme.ElectronApplicationUpdateSubscriptionParams = tObject({\n event: tEnum(["console"]),\n enabled: tBoolean\n });\n scheme.ElectronApplicationUpdateSubscriptionResult = tOptional(tObject({}));\n scheme.AndroidInitializer = tOptional(tObject({}));\n scheme.AndroidDevicesParams = tObject({\n host: tOptional(tString),\n port: tOptional(tInt),\n omitDriverInstall: tOptional(tBoolean)\n });\n scheme.AndroidDevicesResult = tObject({\n devices: tArray(tChannel(["AndroidDevice"]))\n });\n scheme.AndroidSocketInitializer = tOptional(tObject({}));\n scheme.AndroidSocketDataEvent = tObject({\n data: tBinary\n });\n scheme.AndroidSocketCloseEvent = tOptional(tObject({}));\n scheme.AndroidSocketWriteParams = tObject({\n data: tBinary\n });\n scheme.AndroidSocketWriteResult = tOptional(tObject({}));\n scheme.AndroidSocketCloseParams = tOptional(tObject({}));\n scheme.AndroidSocketCloseResult = tOptional(tObject({}));\n scheme.AndroidDeviceInitializer = tObject({\n model: tString,\n serial: tString\n });\n scheme.AndroidDeviceCloseEvent = tOptional(tObject({}));\n scheme.AndroidDeviceWebViewAddedEvent = tObject({\n webView: tType("AndroidWebView")\n });\n scheme.AndroidDeviceWebViewRemovedEvent = tObject({\n socketName: tString\n });\n scheme.AndroidDeviceWaitParams = tObject({\n androidSelector: tType("AndroidSelector"),\n state: tOptional(tEnum(["gone"])),\n timeout: tFloat\n });\n scheme.AndroidDeviceWaitResult = tOptional(tObject({}));\n scheme.AndroidDeviceFillParams = tObject({\n androidSelector: tType("AndroidSelector"),\n text: tString,\n timeout: tFloat\n });\n scheme.AndroidDeviceFillResult = tOptional(tObject({}));\n scheme.AndroidDeviceTapParams = tObject({\n androidSelector: tType("AndroidSelector"),\n duration: tOptional(tFloat),\n timeout: tFloat\n });\n scheme.AndroidDeviceTapResult = tOptional(tObject({}));\n scheme.AndroidDeviceDragParams = tObject({\n androidSelector: tType("AndroidSelector"),\n dest: tType("Point"),\n speed: tOptional(tFloat),\n timeout: tFloat\n });\n scheme.AndroidDeviceDragResult = tOptional(tObject({}));\n scheme.AndroidDeviceFlingParams = tObject({\n androidSelector: tType("AndroidSelector"),\n direction: tEnum(["up", "down", "left", "right"]),\n speed: tOptional(tFloat),\n timeout: tFloat\n });\n scheme.AndroidDeviceFlingResult = tOptional(tObject({}));\n scheme.AndroidDeviceLongTapParams = tObject({\n androidSelector: tType("AndroidSelector"),\n timeout: tFloat\n });\n scheme.AndroidDeviceLongTapResult = tOptional(tObject({}));\n scheme.AndroidDevicePinchCloseParams = tObject({\n androidSelector: tType("AndroidSelector"),\n percent: tFloat,\n speed: tOptional(tFloat),\n timeout: tFloat\n });\n scheme.AndroidDevicePinchCloseResult = tOptional(tObject({}));\n scheme.AndroidDevicePinchOpenParams = tObject({\n androidSelector: tType("AndroidSelector"),\n percent: tFloat,\n speed: tOptional(tFloat),\n timeout: tFloat\n });\n scheme.AndroidDevicePinchOpenResult = tOptional(tObject({}));\n scheme.AndroidDeviceScrollParams = tObject({\n androidSelector: tType("AndroidSelector"),\n direction: tEnum(["up", "down", "left", "right"]),\n percent: tFloat,\n speed: tOptional(tFloat),\n timeout: tFloat\n });\n scheme.AndroidDeviceScrollResult = tOptional(tObject({}));\n scheme.AndroidDeviceSwipeParams = tObject({\n androidSelector: tType("AndroidSelector"),\n direction: tEnum(["up", "down", "left", "right"]),\n percent: tFloat,\n speed: tOptional(tFloat),\n timeout: tFloat\n });\n scheme.AndroidDeviceSwipeResult = tOptional(tObject({}));\n scheme.AndroidDeviceInfoParams = tObject({\n androidSelector: tType("AndroidSelector")\n });\n scheme.AndroidDeviceInfoResult = tObject({\n info: tType("AndroidElementInfo")\n });\n scheme.AndroidDeviceScreenshotParams = tOptional(tObject({}));\n scheme.AndroidDeviceScreenshotResult = tObject({\n binary: tBinary\n });\n scheme.AndroidDeviceInputTypeParams = tObject({\n text: tString\n });\n scheme.AndroidDeviceInputTypeResult = tOptional(tObject({}));\n scheme.AndroidDeviceInputPressParams = tObject({\n key: tString\n });\n scheme.AndroidDeviceInputPressResult = tOptional(tObject({}));\n scheme.AndroidDeviceInputTapParams = tObject({\n point: tType("Point")\n });\n scheme.AndroidDeviceInputTapResult = tOptional(tObject({}));\n scheme.AndroidDeviceInputSwipeParams = tObject({\n segments: tArray(tType("Point")),\n steps: tInt\n });\n scheme.AndroidDeviceInputSwipeResult = tOptional(tObject({}));\n scheme.AndroidDeviceInputDragParams = tObject({\n from: tType("Point"),\n to: tType("Point"),\n steps: tInt\n });\n scheme.AndroidDeviceInputDragResult = tOptional(tObject({}));\n scheme.AndroidDeviceLaunchBrowserParams = tObject({\n noDefaultViewport: tOptional(tBoolean),\n viewport: tOptional(\n tObject({\n width: tInt,\n height: tInt\n })\n ),\n screen: tOptional(\n tObject({\n width: tInt,\n height: tInt\n })\n ),\n ignoreHTTPSErrors: tOptional(tBoolean),\n clientCertificates: tOptional(\n tArray(\n tObject({\n origin: tString,\n cert: tOptional(tBinary),\n key: tOptional(tBinary),\n passphrase: tOptional(tString),\n pfx: tOptional(tBinary)\n })\n )\n ),\n javaScriptEnabled: tOptional(tBoolean),\n bypassCSP: tOptional(tBoolean),\n userAgent: tOptional(tString),\n locale: tOptional(tString),\n timezoneId: tOptional(tString),\n geolocation: tOptional(\n tObject({\n longitude: tFloat,\n latitude: tFloat,\n accuracy: tOptional(tFloat)\n })\n ),\n permissions: tOptional(tArray(tString)),\n extraHTTPHeaders: tOptional(tArray(tType("NameValue"))),\n offline: tOptional(tBoolean),\n httpCredentials: tOptional(\n tObject({\n username: tString,\n password: tString,\n origin: tOptional(tString),\n send: tOptional(tEnum(["always", "unauthorized"]))\n })\n ),\n deviceScaleFactor: tOptional(tFloat),\n isMobile: tOptional(tBoolean),\n hasTouch: tOptional(tBoolean),\n colorScheme: tOptional(tEnum(["dark", "light", "no-preference", "no-override"])),\n reducedMotion: tOptional(tEnum(["reduce", "no-preference", "no-override"])),\n forcedColors: tOptional(tEnum(["active", "none", "no-override"])),\n acceptDownloads: tOptional(tEnum(["accept", "deny", "internal-browser-default"])),\n contrast: tOptional(tEnum(["no-preference", "more", "no-override"])),\n baseURL: tOptional(tString),\n recordVideo: tOptional(\n tObject({\n dir: tString,\n size: tOptional(\n tObject({\n width: tInt,\n height: tInt\n })\n )\n })\n ),\n strictSelectors: tOptional(tBoolean),\n serviceWorkers: tOptional(tEnum(["allow", "block"])),\n selectorEngines: tOptional(tArray(tType("SelectorEngine"))),\n testIdAttributeName: tOptional(tString),\n pkg: tOptional(tString),\n args: tOptional(tArray(tString)),\n proxy: tOptional(\n tObject({\n server: tString,\n bypass: tOptional(tString),\n username: tOptional(tString),\n password: tOptional(tString)\n })\n )\n });\n scheme.AndroidDeviceLaunchBrowserResult = tObject({\n context: tChannel(["BrowserContext"])\n });\n scheme.AndroidDeviceOpenParams = tObject({\n command: tString\n });\n scheme.AndroidDeviceOpenResult = tObject({\n socket: tChannel(["AndroidSocket"])\n });\n scheme.AndroidDeviceShellParams = tObject({\n command: tString\n });\n scheme.AndroidDeviceShellResult = tObject({\n result: tBinary\n });\n scheme.AndroidDeviceInstallApkParams = tObject({\n file: tBinary,\n args: tOptional(tArray(tString))\n });\n scheme.AndroidDeviceInstallApkResult = tOptional(tObject({}));\n scheme.AndroidDevicePushParams = tObject({\n file: tBinary,\n path: tString,\n mode: tOptional(tInt)\n });\n scheme.AndroidDevicePushResult = tOptional(tObject({}));\n scheme.AndroidDeviceConnectToWebViewParams = tObject({\n socketName: tString\n });\n scheme.AndroidDeviceConnectToWebViewResult = tObject({\n context: tChannel(["BrowserContext"])\n });\n scheme.AndroidDeviceCloseParams = tOptional(tObject({}));\n scheme.AndroidDeviceCloseResult = tOptional(tObject({}));\n scheme.AndroidWebView = tObject({\n pid: tInt,\n pkg: tString,\n socketName: tString\n });\n scheme.AndroidSelector = tObject({\n checkable: tOptional(tBoolean),\n checked: tOptional(tBoolean),\n clazz: tOptional(tString),\n clickable: tOptional(tBoolean),\n depth: tOptional(tInt),\n desc: tOptional(tString),\n enabled: tOptional(tBoolean),\n focusable: tOptional(tBoolean),\n focused: tOptional(tBoolean),\n hasChild: tOptional(\n tObject({\n androidSelector: tType("AndroidSelector")\n })\n ),\n hasDescendant: tOptional(\n tObject({\n androidSelector: tType("AndroidSelector"),\n maxDepth: tOptional(tInt)\n })\n ),\n longClickable: tOptional(tBoolean),\n pkg: tOptional(tString),\n res: tOptional(tString),\n scrollable: tOptional(tBoolean),\n selected: tOptional(tBoolean),\n text: tOptional(tString)\n });\n scheme.AndroidElementInfo = tObject({\n children: tOptional(tArray(tType("AndroidElementInfo"))),\n clazz: tString,\n desc: tString,\n res: tString,\n pkg: tString,\n text: tString,\n bounds: tType("Rect"),\n checkable: tBoolean,\n checked: tBoolean,\n clickable: tBoolean,\n enabled: tBoolean,\n focusable: tBoolean,\n focused: tBoolean,\n longClickable: tBoolean,\n scrollable: tBoolean,\n selected: tBoolean\n });\n scheme.JsonPipeInitializer = tOptional(tObject({}));\n scheme.JsonPipeMessageEvent = tObject({\n message: tAny\n });\n scheme.JsonPipeClosedEvent = tObject({\n reason: tOptional(tString)\n });\n scheme.JsonPipeSendParams = tObject({\n message: tAny\n });\n scheme.JsonPipeSendResult = tOptional(tObject({}));\n scheme.JsonPipeCloseParams = tOptional(tObject({}));\n scheme.JsonPipeCloseResult = tOptional(tObject({}));\n\n // src/sandbox/forked-client/src/utils/isomorphic/protocolMetainfo.ts\n var methodMetainfo = /* @__PURE__ */ new Map([\n ["APIRequestContext.fetch", { title: \'{method} "{url}"\' }],\n ["APIRequestContext.fetchResponseBody", { title: "Get response body", group: "getter" }],\n ["APIRequestContext.fetchLog", { internal: true }],\n ["APIRequestContext.storageState", { title: "Get storage state", group: "configuration" }],\n ["APIRequestContext.disposeAPIResponse", { internal: true }],\n ["APIRequestContext.dispose", { internal: true }],\n ["LocalUtils.zip", { internal: true }],\n ["LocalUtils.harOpen", { internal: true }],\n ["LocalUtils.harLookup", { internal: true }],\n ["LocalUtils.harClose", { internal: true }],\n ["LocalUtils.harUnzip", { internal: true }],\n ["LocalUtils.connect", { internal: true }],\n ["LocalUtils.tracingStarted", { internal: true }],\n ["LocalUtils.addStackToTracingNoReply", { internal: true }],\n ["LocalUtils.traceDiscarded", { internal: true }],\n ["LocalUtils.globToRegex", { internal: true }],\n ["Root.initialize", { internal: true }],\n ["Playwright.newRequest", { title: "Create request context" }],\n ["DebugController.initialize", { internal: true }],\n ["DebugController.setReportStateChanged", { internal: true }],\n ["DebugController.setRecorderMode", { internal: true }],\n ["DebugController.highlight", { internal: true }],\n ["DebugController.hideHighlight", { internal: true }],\n ["DebugController.resume", { internal: true }],\n ["DebugController.kill", { internal: true }],\n ["SocksSupport.socksConnected", { internal: true }],\n ["SocksSupport.socksFailed", { internal: true }],\n ["SocksSupport.socksData", { internal: true }],\n ["SocksSupport.socksError", { internal: true }],\n ["SocksSupport.socksEnd", { internal: true }],\n ["BrowserType.launch", { title: "Launch browser" }],\n ["BrowserType.launchPersistentContext", { title: "Launch persistent context" }],\n ["BrowserType.connectOverCDP", { title: "Connect over CDP" }],\n ["BrowserType.connectOverCDPTransport", { title: "Connect over CDP transport" }],\n ["Browser.startServer", { title: "Start server" }],\n ["Browser.stopServer", { title: "Stop server" }],\n ["Browser.close", { title: "Close browser", pausesBeforeAction: true }],\n ["Browser.killForTests", { internal: true }],\n ["Browser.defaultUserAgentForTest", { internal: true }],\n ["Browser.newContext", { title: "Create context" }],\n ["Browser.newContextForReuse", { internal: true }],\n ["Browser.disconnectFromReusedContext", { internal: true }],\n ["Browser.newBrowserCDPSession", { title: "Create CDP session", group: "configuration" }],\n ["Browser.startTracing", { title: "Start browser tracing", group: "configuration" }],\n ["Browser.stopTracing", { title: "Stop browser tracing", group: "configuration" }],\n ["EventTarget.waitForEventInfo", { title: \'Wait for event "{info.event}"\', snapshot: true }],\n ["BrowserContext.waitForEventInfo", { title: \'Wait for event "{info.event}"\', snapshot: true }],\n ["Page.waitForEventInfo", { title: \'Wait for event "{info.event}"\', snapshot: true }],\n ["Worker.waitForEventInfo", { title: \'Wait for event "{info.event}"\', snapshot: true }],\n ["WebSocket.waitForEventInfo", { title: \'Wait for event "{info.event}"\', snapshot: true }],\n ["Debugger.waitForEventInfo", { title: \'Wait for event "{info.event}"\', snapshot: true }],\n [\n "ElectronApplication.waitForEventInfo",\n { title: \'Wait for event "{info.event}"\', snapshot: true }\n ],\n ["AndroidDevice.waitForEventInfo", { title: \'Wait for event "{info.event}"\', snapshot: true }],\n ["BrowserContext.addCookies", { title: "Add cookies", group: "configuration" }],\n ["BrowserContext.addInitScript", { title: "Add init script", group: "configuration" }],\n ["BrowserContext.clearCookies", { title: "Clear cookies", group: "configuration" }],\n ["BrowserContext.clearPermissions", { title: "Clear permissions", group: "configuration" }],\n ["BrowserContext.close", { title: "Close context", pausesBeforeAction: true }],\n ["BrowserContext.cookies", { title: "Get cookies", group: "getter" }],\n ["BrowserContext.exposeBinding", { title: "Expose binding", group: "configuration" }],\n ["BrowserContext.grantPermissions", { title: "Grant permissions", group: "configuration" }],\n ["BrowserContext.newPage", { title: "Create page" }],\n ["BrowserContext.registerSelectorEngine", { internal: true }],\n ["BrowserContext.setTestIdAttributeName", { internal: true }],\n [\n "BrowserContext.setExtraHTTPHeaders",\n { title: "Set extra HTTP headers", group: "configuration" }\n ],\n ["BrowserContext.setGeolocation", { title: "Set geolocation", group: "configuration" }],\n ["BrowserContext.setHTTPCredentials", { title: "Set HTTP credentials", group: "configuration" }],\n ["BrowserContext.setNetworkInterceptionPatterns", { title: "Route requests", group: "route" }],\n [\n "BrowserContext.setWebSocketInterceptionPatterns",\n { title: "Route WebSockets", group: "route" }\n ],\n ["BrowserContext.setOffline", { title: "Set offline mode" }],\n ["BrowserContext.storageState", { title: "Get storage state", group: "configuration" }],\n ["BrowserContext.setStorageState", { title: "Set storage state", group: "configuration" }],\n ["BrowserContext.pause", { title: "Pause" }],\n ["BrowserContext.enableRecorder", { internal: true }],\n ["BrowserContext.disableRecorder", { internal: true }],\n ["BrowserContext.exposeConsoleApi", { internal: true }],\n ["BrowserContext.newCDPSession", { title: "Create CDP session", group: "configuration" }],\n ["BrowserContext.harStart", { internal: true }],\n ["BrowserContext.harExport", { internal: true }],\n ["BrowserContext.createTempFiles", { internal: true }],\n ["BrowserContext.updateSubscription", { internal: true }],\n ["BrowserContext.clockFastForward", { title: \'Fast forward clock "{ticksNumber|ticksString}"\' }],\n ["BrowserContext.clockInstall", { title: \'Install clock "{timeNumber|timeString}"\' }],\n ["BrowserContext.clockPauseAt", { title: \'Pause clock "{timeNumber|timeString}"\' }],\n ["BrowserContext.clockResume", { title: "Resume clock" }],\n ["BrowserContext.clockRunFor", { title: \'Run clock "{ticksNumber|ticksString}"\' }],\n ["BrowserContext.clockSetFixedTime", { title: \'Set fixed time "{timeNumber|timeString}"\' }],\n ["BrowserContext.clockSetSystemTime", { title: \'Set system time "{timeNumber|timeString}"\' }],\n ["Page.addInitScript", { title: "Add init script", group: "configuration" }],\n ["Page.close", { title: "Close page", pausesBeforeAction: true }],\n ["Page.clearConsoleMessages", { title: "Clear console messages" }],\n ["Page.consoleMessages", { title: "Get console messages", group: "getter" }],\n ["Page.emulateMedia", { title: "Emulate media", snapshot: true, pausesBeforeAction: true }],\n ["Page.exposeBinding", { title: "Expose binding", group: "configuration" }],\n ["Page.goBack", { title: "Go back", slowMo: true, snapshot: true, pausesBeforeAction: true }],\n [\n "Page.goForward",\n { title: "Go forward", slowMo: true, snapshot: true, pausesBeforeAction: true }\n ],\n ["Page.requestGC", { title: "Request garbage collection", group: "configuration" }],\n ["Page.registerLocatorHandler", { title: "Register locator handler" }],\n ["Page.resolveLocatorHandlerNoReply", { internal: true }],\n ["Page.unregisterLocatorHandler", { title: "Unregister locator handler" }],\n ["Page.reload", { title: "Reload", slowMo: true, snapshot: true, pausesBeforeAction: true }],\n [\n "Page.expectScreenshot",\n { title: "Expect screenshot", snapshot: true, pausesBeforeAction: true }\n ],\n ["Page.screenshot", { title: "Screenshot", snapshot: true, pausesBeforeAction: true }],\n ["Page.setExtraHTTPHeaders", { title: "Set extra HTTP headers", group: "configuration" }],\n ["Page.setNetworkInterceptionPatterns", { title: "Route requests", group: "route" }],\n ["Page.setWebSocketInterceptionPatterns", { title: "Route WebSockets", group: "route" }],\n [\n "Page.setViewportSize",\n { title: "Set viewport size", snapshot: true, pausesBeforeAction: true }\n ],\n [\n "Page.keyboardDown",\n { title: \'Key down "{key}"\', slowMo: true, snapshot: true, pausesBeforeAction: true }\n ],\n [\n "Page.keyboardUp",\n { title: \'Key up "{key}"\', slowMo: true, snapshot: true, pausesBeforeAction: true }\n ],\n [\n "Page.keyboardInsertText",\n { title: \'Insert "{text}"\', slowMo: true, snapshot: true, pausesBeforeAction: true }\n ],\n [\n "Page.keyboardType",\n { title: \'Type "{text}"\', slowMo: true, snapshot: true, pausesBeforeAction: true }\n ],\n [\n "Page.keyboardPress",\n { title: \'Press "{key}"\', slowMo: true, snapshot: true, pausesBeforeAction: true }\n ],\n [\n "Page.mouseMove",\n { title: "Mouse move", slowMo: true, snapshot: true, pausesBeforeAction: true }\n ],\n [\n "Page.mouseDown",\n { title: "Mouse down", slowMo: true, snapshot: true, pausesBeforeAction: true }\n ],\n ["Page.mouseUp", { title: "Mouse up", slowMo: true, snapshot: true, pausesBeforeAction: true }],\n ["Page.mouseClick", { title: "Click", slowMo: true, snapshot: true, pausesBeforeAction: true }],\n [\n "Page.mouseWheel",\n { title: "Mouse wheel", slowMo: true, snapshot: true, pausesBeforeAction: true }\n ],\n ["Page.touchscreenTap", { title: "Tap", slowMo: true, snapshot: true, pausesBeforeAction: true }],\n ["Page.clearPageErrors", { title: "Clear page errors" }],\n ["Page.pageErrors", { title: "Get page errors", group: "getter" }],\n ["Page.pdf", { title: "PDF" }],\n ["Page.requests", { title: "Get network requests", group: "getter" }],\n ["Page.snapshotForAI", { internal: true }],\n ["Page.startJSCoverage", { title: "Start JS coverage", group: "configuration" }],\n ["Page.stopJSCoverage", { title: "Stop JS coverage", group: "configuration" }],\n ["Page.startCSSCoverage", { title: "Start CSS coverage", group: "configuration" }],\n ["Page.stopCSSCoverage", { title: "Stop CSS coverage", group: "configuration" }],\n ["Page.bringToFront", { title: "Bring to front" }],\n ["Page.pickLocator", { title: "Pick locator", group: "configuration" }],\n ["Page.cancelPickLocator", { title: "Cancel pick locator", group: "configuration" }],\n ["Page.startScreencast", { title: "Start screencast", group: "configuration" }],\n ["Page.stopScreencast", { title: "Stop screencast", group: "configuration" }],\n ["Page.videoStart", { title: "Start video recording", group: "configuration" }],\n ["Page.videoStop", { title: "Stop video recording", group: "configuration" }],\n ["Page.updateSubscription", { internal: true }],\n ["Page.setDockTile", { internal: true }],\n ["Frame.evalOnSelector", { title: "Evaluate", snapshot: true, pausesBeforeAction: true }],\n ["Frame.evalOnSelectorAll", { title: "Evaluate", snapshot: true, pausesBeforeAction: true }],\n ["Frame.addScriptTag", { title: "Add script tag", snapshot: true, pausesBeforeAction: true }],\n ["Frame.addStyleTag", { title: "Add style tag", snapshot: true, pausesBeforeAction: true }],\n ["Frame.ariaSnapshot", { title: "Aria snapshot", snapshot: true, pausesBeforeAction: true }],\n ["Frame.blur", { title: "Blur", slowMo: true, snapshot: true, pausesBeforeAction: true }],\n ["Frame.check", { title: "Check", slowMo: true, snapshot: true, pausesBeforeInput: true }],\n ["Frame.click", { title: "Click", slowMo: true, snapshot: true, pausesBeforeInput: true }],\n ["Frame.content", { title: "Get content", snapshot: true, pausesBeforeAction: true }],\n [\n "Frame.dragAndDrop",\n { title: "Drag and drop", slowMo: true, snapshot: true, pausesBeforeInput: true }\n ],\n [\n "Frame.dblclick",\n { title: "Double click", slowMo: true, snapshot: true, pausesBeforeInput: true }\n ],\n [\n "Frame.dispatchEvent",\n { title: \'Dispatch "{type}"\', slowMo: true, snapshot: true, pausesBeforeAction: true }\n ],\n ["Frame.evaluateExpression", { title: "Evaluate", snapshot: true, pausesBeforeAction: true }],\n [\n "Frame.evaluateExpressionHandle",\n { title: "Evaluate", snapshot: true, pausesBeforeAction: true }\n ],\n [\n "Frame.fill",\n { title: \'Fill "{value}"\', slowMo: true, snapshot: true, pausesBeforeInput: true }\n ],\n ["Frame.focus", { title: "Focus", slowMo: true, snapshot: true, pausesBeforeAction: true }],\n ["Frame.frameElement", { title: "Get frame element", group: "getter" }],\n ["Frame.resolveSelector", { internal: true }],\n ["Frame.highlight", { title: "Highlight element", group: "configuration" }],\n [\n "Frame.getAttribute",\n { title: \'Get attribute "{name}"\', snapshot: true, pausesBeforeAction: true, group: "getter" }\n ],\n [\n "Frame.goto",\n { title: \'Navigate to "{url}"\', slowMo: true, snapshot: true, pausesBeforeAction: true }\n ],\n ["Frame.hover", { title: "Hover", slowMo: true, snapshot: true, pausesBeforeInput: true }],\n [\n "Frame.innerHTML",\n { title: "Get HTML", snapshot: true, pausesBeforeAction: true, group: "getter" }\n ],\n [\n "Frame.innerText",\n { title: "Get inner text", snapshot: true, pausesBeforeAction: true, group: "getter" }\n ],\n [\n "Frame.inputValue",\n { title: "Get input value", snapshot: true, pausesBeforeAction: true, group: "getter" }\n ],\n [\n "Frame.isChecked",\n { title: "Is checked", snapshot: true, pausesBeforeAction: true, group: "getter" }\n ],\n [\n "Frame.isDisabled",\n { title: "Is disabled", snapshot: true, pausesBeforeAction: true, group: "getter" }\n ],\n [\n "Frame.isEnabled",\n { title: "Is enabled", snapshot: true, pausesBeforeAction: true, group: "getter" }\n ],\n [\n "Frame.isHidden",\n { title: "Is hidden", snapshot: true, pausesBeforeAction: true, group: "getter" }\n ],\n [\n "Frame.isVisible",\n { title: "Is visible", snapshot: true, pausesBeforeAction: true, group: "getter" }\n ],\n [\n "Frame.isEditable",\n { title: "Is editable", snapshot: true, pausesBeforeAction: true, group: "getter" }\n ],\n [\n "Frame.press",\n { title: \'Press "{key}"\', slowMo: true, snapshot: true, pausesBeforeInput: true }\n ],\n ["Frame.querySelector", { title: "Query selector", snapshot: true }],\n ["Frame.querySelectorAll", { title: "Query selector all", snapshot: true }],\n ["Frame.queryCount", { title: "Query count", snapshot: true, pausesBeforeAction: true }],\n [\n "Frame.selectOption",\n { title: "Select option", slowMo: true, snapshot: true, pausesBeforeInput: true }\n ],\n ["Frame.setContent", { title: "Set content", snapshot: true, pausesBeforeAction: true }],\n [\n "Frame.setInputFiles",\n { title: "Set input files", slowMo: true, snapshot: true, pausesBeforeInput: true }\n ],\n ["Frame.tap", { title: "Tap", slowMo: true, snapshot: true, pausesBeforeInput: true }],\n [\n "Frame.textContent",\n { title: "Get text content", snapshot: true, pausesBeforeAction: true, group: "getter" }\n ],\n ["Frame.title", { title: "Get page title", group: "getter" }],\n ["Frame.type", { title: \'Type "{text}"\', slowMo: true, snapshot: true, pausesBeforeInput: true }],\n ["Frame.uncheck", { title: "Uncheck", slowMo: true, snapshot: true, pausesBeforeInput: true }],\n ["Frame.waitForTimeout", { title: "Wait for timeout", snapshot: true }],\n [\n "Frame.waitForFunction",\n { title: "Wait for function", snapshot: true, pausesBeforeAction: true }\n ],\n ["Frame.waitForSelector", { title: "Wait for selector", snapshot: true }],\n ["Frame.expect", { title: \'Expect "{expression}"\', snapshot: true, pausesBeforeAction: true }],\n ["Worker.evaluateExpression", { title: "Evaluate" }],\n ["Worker.evaluateExpressionHandle", { title: "Evaluate" }],\n ["Worker.updateSubscription", { internal: true }],\n ["Disposable.dispose", { internal: true }],\n ["JSHandle.dispose", { internal: true }],\n ["ElementHandle.dispose", { internal: true }],\n ["JSHandle.evaluateExpression", { title: "Evaluate", snapshot: true, pausesBeforeAction: true }],\n [\n "ElementHandle.evaluateExpression",\n { title: "Evaluate", snapshot: true, pausesBeforeAction: true }\n ],\n [\n "JSHandle.evaluateExpressionHandle",\n { title: "Evaluate", snapshot: true, pausesBeforeAction: true }\n ],\n [\n "ElementHandle.evaluateExpressionHandle",\n { title: "Evaluate", snapshot: true, pausesBeforeAction: true }\n ],\n ["JSHandle.getPropertyList", { title: "Get property list", group: "getter" }],\n ["ElementHandle.getPropertyList", { title: "Get property list", group: "getter" }],\n ["JSHandle.getProperty", { title: "Get JS property", group: "getter" }],\n ["ElementHandle.getProperty", { title: "Get JS property", group: "getter" }],\n ["JSHandle.jsonValue", { title: "Get JSON value", group: "getter" }],\n ["ElementHandle.jsonValue", { title: "Get JSON value", group: "getter" }],\n ["ElementHandle.evalOnSelector", { title: "Evaluate", snapshot: true, pausesBeforeAction: true }],\n [\n "ElementHandle.evalOnSelectorAll",\n { title: "Evaluate", snapshot: true, pausesBeforeAction: true }\n ],\n [\n "ElementHandle.boundingBox",\n { title: "Get bounding box", snapshot: true, pausesBeforeAction: true }\n ],\n [\n "ElementHandle.check",\n { title: "Check", slowMo: true, snapshot: true, pausesBeforeInput: true }\n ],\n [\n "ElementHandle.click",\n { title: "Click", slowMo: true, snapshot: true, pausesBeforeInput: true }\n ],\n ["ElementHandle.contentFrame", { title: "Get content frame", group: "getter" }],\n [\n "ElementHandle.dblclick",\n { title: "Double click", slowMo: true, snapshot: true, pausesBeforeInput: true }\n ],\n [\n "ElementHandle.dispatchEvent",\n { title: "Dispatch event", slowMo: true, snapshot: true, pausesBeforeAction: true }\n ],\n [\n "ElementHandle.fill",\n { title: \'Fill "{value}"\', slowMo: true, snapshot: true, pausesBeforeInput: true }\n ],\n [\n "ElementHandle.focus",\n { title: "Focus", slowMo: true, snapshot: true, pausesBeforeAction: true }\n ],\n [\n "ElementHandle.getAttribute",\n { title: "Get attribute", snapshot: true, pausesBeforeAction: true, group: "getter" }\n ],\n [\n "ElementHandle.hover",\n { title: "Hover", slowMo: true, snapshot: true, pausesBeforeInput: true }\n ],\n [\n "ElementHandle.innerHTML",\n { title: "Get HTML", snapshot: true, pausesBeforeAction: true, group: "getter" }\n ],\n [\n "ElementHandle.innerText",\n { title: "Get inner text", snapshot: true, pausesBeforeAction: true, group: "getter" }\n ],\n [\n "ElementHandle.inputValue",\n { title: "Get input value", snapshot: true, pausesBeforeAction: true, group: "getter" }\n ],\n [\n "ElementHandle.isChecked",\n { title: "Is checked", snapshot: true, pausesBeforeAction: true, group: "getter" }\n ],\n [\n "ElementHandle.isDisabled",\n { title: "Is disabled", snapshot: true, pausesBeforeAction: true, group: "getter" }\n ],\n [\n "ElementHandle.isEditable",\n { title: "Is editable", snapshot: true, pausesBeforeAction: true, group: "getter" }\n ],\n [\n "ElementHandle.isEnabled",\n { title: "Is enabled", snapshot: true, pausesBeforeAction: true, group: "getter" }\n ],\n [\n "ElementHandle.isHidden",\n { title: "Is hidden", snapshot: true, pausesBeforeAction: true, group: "getter" }\n ],\n [\n "ElementHandle.isVisible",\n { title: "Is visible", snapshot: true, pausesBeforeAction: true, group: "getter" }\n ],\n ["ElementHandle.ownerFrame", { title: "Get owner frame", group: "getter" }],\n [\n "ElementHandle.press",\n { title: \'Press "{key}"\', slowMo: true, snapshot: true, pausesBeforeInput: true }\n ],\n ["ElementHandle.querySelector", { title: "Query selector", snapshot: true }],\n ["ElementHandle.querySelectorAll", { title: "Query selector all", snapshot: true }],\n ["ElementHandle.screenshot", { title: "Screenshot", snapshot: true, pausesBeforeAction: true }],\n [\n "ElementHandle.scrollIntoViewIfNeeded",\n { title: "Scroll into view", slowMo: true, snapshot: true, pausesBeforeAction: true }\n ],\n [\n "ElementHandle.selectOption",\n { title: "Select option", slowMo: true, snapshot: true, pausesBeforeInput: true }\n ],\n [\n "ElementHandle.selectText",\n { title: "Select text", slowMo: true, snapshot: true, pausesBeforeAction: true }\n ],\n [\n "ElementHandle.setInputFiles",\n { title: "Set input files", slowMo: true, snapshot: true, pausesBeforeInput: true }\n ],\n ["ElementHandle.tap", { title: "Tap", slowMo: true, snapshot: true, pausesBeforeInput: true }],\n [\n "ElementHandle.textContent",\n { title: "Get text content", snapshot: true, pausesBeforeAction: true, group: "getter" }\n ],\n ["ElementHandle.type", { title: "Type", slowMo: true, snapshot: true, pausesBeforeInput: true }],\n [\n "ElementHandle.uncheck",\n { title: "Uncheck", slowMo: true, snapshot: true, pausesBeforeInput: true }\n ],\n [\n "ElementHandle.waitForElementState",\n { title: "Wait for state", snapshot: true, pausesBeforeAction: true }\n ],\n ["ElementHandle.waitForSelector", { title: "Wait for selector", snapshot: true }],\n ["Request.response", { internal: true }],\n ["Request.rawRequestHeaders", { internal: true }],\n ["Route.redirectNavigationRequest", { internal: true }],\n ["Route.abort", { title: "Abort request", group: "route" }],\n ["Route.continue", { title: "Continue request", group: "route" }],\n ["Route.fulfill", { title: "Fulfill request", group: "route" }],\n ["WebSocketRoute.connect", { title: "Connect WebSocket to server", group: "route" }],\n ["WebSocketRoute.ensureOpened", { internal: true }],\n ["WebSocketRoute.sendToPage", { title: "Send WebSocket message", group: "route" }],\n ["WebSocketRoute.sendToServer", { title: "Send WebSocket message", group: "route" }],\n ["WebSocketRoute.closePage", { internal: true }],\n ["WebSocketRoute.closeServer", { internal: true }],\n ["Response.body", { title: "Get response body", group: "getter" }],\n ["Response.securityDetails", { internal: true }],\n ["Response.serverAddr", { internal: true }],\n ["Response.rawResponseHeaders", { internal: true }],\n ["Response.httpVersion", { internal: true }],\n ["Response.sizes", { internal: true }],\n ["BindingCall.reject", { internal: true }],\n ["BindingCall.resolve", { internal: true }],\n ["Debugger.pause", { title: "Pause on next call", group: "configuration" }],\n ["Debugger.resume", { title: "Resume", group: "configuration" }],\n ["Debugger.next", { title: "Step to next call", group: "configuration" }],\n ["Debugger.runTo", { title: "Run to location", group: "configuration" }],\n ["Dialog.accept", { title: "Accept dialog" }],\n ["Dialog.dismiss", { title: "Dismiss dialog" }],\n ["Tracing.tracingStart", { title: "Start tracing", group: "configuration" }],\n ["Tracing.tracingStartChunk", { title: "Start tracing", group: "configuration" }],\n ["Tracing.tracingGroup", { title: \'Trace "{name}"\' }],\n ["Tracing.tracingGroupEnd", { title: "Group end" }],\n ["Tracing.tracingStopChunk", { title: "Stop tracing", group: "configuration" }],\n ["Tracing.tracingStop", { title: "Stop tracing", group: "configuration" }],\n ["Artifact.pathAfterFinished", { internal: true }],\n ["Artifact.saveAs", { internal: true }],\n ["Artifact.saveAsStream", { internal: true }],\n ["Artifact.failure", { internal: true }],\n ["Artifact.stream", { internal: true }],\n ["Artifact.cancel", { internal: true }],\n ["Artifact.delete", { internal: true }],\n ["Stream.read", { internal: true }],\n ["Stream.close", { internal: true }],\n ["WritableStream.write", { internal: true }],\n ["WritableStream.close", { internal: true }],\n ["CDPSession.send", { title: "Send CDP command", group: "configuration" }],\n ["CDPSession.detach", { title: "Detach CDP session", group: "configuration" }],\n ["Electron.launch", { title: "Launch electron" }],\n ["ElectronApplication.browserWindow", { internal: true }],\n ["ElectronApplication.evaluateExpression", { title: "Evaluate" }],\n ["ElectronApplication.evaluateExpressionHandle", { title: "Evaluate" }],\n ["ElectronApplication.updateSubscription", { internal: true }],\n ["Android.devices", { internal: true }],\n ["AndroidSocket.write", { internal: true }],\n ["AndroidSocket.close", { internal: true }],\n ["AndroidDevice.wait", { title: "Wait" }],\n ["AndroidDevice.fill", { title: \'Fill "{text}"\' }],\n ["AndroidDevice.tap", { title: "Tap" }],\n ["AndroidDevice.drag", { title: "Drag" }],\n ["AndroidDevice.fling", { title: "Fling" }],\n ["AndroidDevice.longTap", { title: "Long tap" }],\n ["AndroidDevice.pinchClose", { title: "Pinch close" }],\n ["AndroidDevice.pinchOpen", { title: "Pinch open" }],\n ["AndroidDevice.scroll", { title: "Scroll" }],\n ["AndroidDevice.swipe", { title: "Swipe" }],\n ["AndroidDevice.info", { internal: true }],\n ["AndroidDevice.screenshot", { title: "Screenshot" }],\n ["AndroidDevice.inputType", { title: "Type" }],\n ["AndroidDevice.inputPress", { title: "Press" }],\n ["AndroidDevice.inputTap", { title: "Tap" }],\n ["AndroidDevice.inputSwipe", { title: "Swipe" }],\n ["AndroidDevice.inputDrag", { title: "Drag" }],\n ["AndroidDevice.launchBrowser", { title: "Launch browser" }],\n ["AndroidDevice.open", { title: "Open app" }],\n ["AndroidDevice.shell", { title: "Execute shell command", group: "configuration" }],\n ["AndroidDevice.installApk", { title: "Install apk" }],\n ["AndroidDevice.push", { title: "Push" }],\n ["AndroidDevice.connectToWebView", { title: "Connect to Web View" }],\n ["AndroidDevice.close", { internal: true }],\n ["JsonPipe.send", { internal: true }],\n ["JsonPipe.close", { internal: true }]\n ]);\n\n // src/sandbox/forked-client/src/utils/isomorphic/stackTrace.ts\n function captureRawStack() {\n const stackTraceLimit = Error.stackTraceLimit;\n Error.stackTraceLimit = 50;\n const error = new Error();\n const stack = error.stack || "";\n Error.stackTraceLimit = stackTraceLimit;\n return stack.split("\\n");\n }\n function parseStackFrame(text, pathSeparator, showInternalStackFrames) {\n const match = text && text.match(re);\n if (!match) return null;\n let fname = match[2];\n let file = match[7];\n if (!file) return null;\n if (!showInternalStackFrames && (file.startsWith("internal") || file.startsWith("node:")))\n return null;\n const line = match[8];\n const column = match[9];\n const closeParen = match[11] === ")";\n const frame = {\n file: "",\n line: 0,\n column: 0\n };\n if (line) frame.line = Number(line);\n if (column) frame.column = Number(column);\n if (closeParen && file) {\n let closes = 0;\n for (let i = file.length - 1; i > 0; i--) {\n if (file.charAt(i) === ")") {\n closes++;\n } else if (file.charAt(i) === "(" && file.charAt(i - 1) === " ") {\n closes--;\n if (closes === -1 && file.charAt(i - 1) === " ") {\n const before = file.slice(0, i - 1);\n const after = file.slice(i + 1);\n file = after;\n fname += ` (${before}`;\n break;\n }\n }\n }\n }\n if (fname) {\n const methodMatch = fname.match(methodRe);\n if (methodMatch) fname = methodMatch[1];\n }\n if (file) {\n if (file.startsWith("file://")) file = fileURLToPath(file, pathSeparator);\n frame.file = file;\n }\n if (fname) frame.function = fname;\n return frame;\n }\n function rewriteErrorMessage(e, newMessage) {\n const lines = (e.stack?.split("\\n") || []).filter((l) => l.startsWith(" at "));\n e.message = newMessage;\n const errorTitle = `${e.name}: ${e.message}`;\n if (lines.length) e.stack = `${errorTitle}\n${lines.join("\\n")}`;\n return e;\n }\n function stringifyStackFrames(frames) {\n const stackLines = [];\n for (const frame of frames) {\n if (frame.function)\n stackLines.push(` at ${frame.function} (${frame.file}:${frame.line}:${frame.column})`);\n else stackLines.push(` at ${frame.file}:${frame.line}:${frame.column}`);\n }\n return stackLines;\n }\n var re = new RegExp(\n "^(?:\\\\s*at )?(?:(new) )?(?:(.*?) \\\\()?(?:eval at ([^ ]+) \\\\((.+?):(\\\\d+):(\\\\d+)\\\\), )?(?:(.+?):(\\\\d+):(\\\\d+)|(native))(\\\\)?)$"\n );\n var methodRe = /^(.*?) \\[as (.*?)\\]$/;\n function fileURLToPath(fileUrl, pathSeparator) {\n if (!fileUrl.startsWith("file://")) return fileUrl;\n let path = decodeURIComponent(fileUrl.slice(7));\n if (path.startsWith("/") && /^[a-zA-Z]:/.test(path.slice(1))) path = path.slice(1);\n return path.replace(/\\//g, pathSeparator);\n }\n\n // src/sandbox/forked-client/src/client/clientStackTrace.ts\n function captureLibraryStackTrace(platform) {\n const stack = captureRawStack();\n let parsedFrames = stack.map((line) => {\n const frame = parseStackFrame(\n line,\n platform.pathSeparator,\n platform.showInternalStackFrames()\n );\n if (!frame || !frame.file) return null;\n const isPlaywrightLibrary = !!platform.coreDir && frame.file.startsWith(platform.coreDir);\n const parsed = {\n frame,\n frameText: line,\n isPlaywrightLibrary\n };\n return parsed;\n }).filter(Boolean);\n let apiName = "";\n for (let i = 0; i < parsedFrames.length - 1; i++) {\n const parsedFrame = parsedFrames[i];\n if (parsedFrame.isPlaywrightLibrary && !parsedFrames[i + 1].isPlaywrightLibrary) {\n apiName = apiName || normalizeAPIName(parsedFrame.frame.function);\n break;\n }\n }\n function normalizeAPIName(name) {\n if (!name) return "";\n const match = name.match(/(API|JS|CDP|[A-Z])(.*)/);\n if (!match) return name;\n return match[1].toLowerCase() + match[2];\n }\n const filterPrefixes = platform.boxedStackPrefixes();\n parsedFrames = parsedFrames.filter((f) => {\n if (filterPrefixes.some((prefix) => f.frame.file.startsWith(prefix))) return false;\n return true;\n });\n return {\n frames: parsedFrames.map((p) => p.frame),\n apiName\n };\n }\n\n // src/sandbox/forked-client/src/client/channelOwner.ts\n var ChannelOwner = class _ChannelOwner extends EventEmitter {\n _connection;\n _parent;\n _objects = /* @__PURE__ */ new Map();\n _type;\n _guid;\n _channel;\n _initializer;\n _logger;\n _instrumentation;\n _eventToSubscriptionMapping = /* @__PURE__ */ new Map();\n _wasCollected = false;\n constructor(parent, type, guid, initializer) {\n const connection = parent instanceof _ChannelOwner ? parent._connection : parent;\n super(connection._platform);\n this.setMaxListeners(0);\n this._connection = connection;\n this._type = type;\n this._guid = guid;\n this._parent = parent instanceof _ChannelOwner ? parent : void 0;\n this._instrumentation = this._connection._instrumentation;\n this._connection._objects.set(guid, this);\n if (this._parent) {\n this._parent._objects.set(guid, this);\n this._logger = this._parent._logger;\n }\n this._channel = this._createChannel(new EventEmitter(connection._platform));\n this._initializer = initializer;\n }\n _setEventToSubscriptionMapping(mapping) {\n this._eventToSubscriptionMapping = mapping;\n }\n _updateSubscription(event, enabled) {\n const protocolEvent = this._eventToSubscriptionMapping.get(String(event));\n if (protocolEvent)\n this._channel.updateSubscription({ event: protocolEvent, enabled }).catch(() => {\n });\n }\n on(event, listener) {\n if (!this.listenerCount(event)) this._updateSubscription(event, true);\n super.on(event, listener);\n return this;\n }\n addListener(event, listener) {\n if (!this.listenerCount(event)) this._updateSubscription(event, true);\n super.addListener(event, listener);\n return this;\n }\n prependListener(event, listener) {\n if (!this.listenerCount(event)) this._updateSubscription(event, true);\n super.prependListener(event, listener);\n return this;\n }\n off(event, listener) {\n super.off(event, listener);\n if (!this.listenerCount(event)) this._updateSubscription(event, false);\n return this;\n }\n removeListener(event, listener) {\n super.removeListener(event, listener);\n if (!this.listenerCount(event)) this._updateSubscription(event, false);\n return this;\n }\n _adopt(child) {\n child._parent._objects.delete(child._guid);\n this._objects.set(child._guid, child);\n child._parent = this;\n }\n _dispose(reason) {\n if (this._parent) this._parent._objects.delete(this._guid);\n this._connection._objects.delete(this._guid);\n this._wasCollected = reason === "gc";\n for (const object of [...this._objects.values()]) object._dispose(reason);\n this._objects.clear();\n }\n _debugScopeState() {\n return {\n _guid: this._guid,\n objects: Array.from(this._objects.values()).map((o) => o._debugScopeState())\n };\n }\n _validatorToWireContext() {\n return {\n tChannelImpl: tChannelImplToWire,\n binary: this._connection.rawBuffers() ? "buffer" : "toBase64",\n isUnderTest: () => this._platform.isUnderTest()\n };\n }\n _createChannel(base) {\n const channel = new Proxy(base, {\n get: (obj, prop) => {\n if (typeof prop === "string") {\n const validator = maybeFindValidator(this._type, prop, "Params");\n const { internal } = methodMetainfo.get(this._type + "." + prop) || {};\n if (validator) {\n return async (params) => {\n return await this._wrapApiCall(\n async (apiZone) => {\n const validatedParams = validator(params, "", this._validatorToWireContext());\n if (!apiZone.internal && !apiZone.reported) {\n apiZone.reported = true;\n this._instrumentation.onApiCallBegin(apiZone, {\n type: this._type,\n method: prop,\n params\n });\n logApiCall(this._platform, this._logger, `=> ${apiZone.apiName} started`);\n return await this._connection.sendMessageToServer(\n this,\n prop,\n validatedParams,\n apiZone\n );\n }\n return await this._connection.sendMessageToServer(this, prop, validatedParams, {\n internal: true\n });\n },\n { internal }\n );\n };\n }\n }\n return obj[prop];\n }\n });\n channel._object = this;\n return channel;\n }\n async _wrapApiCall(func, options) {\n const logger = this._logger;\n const existingApiZone = this._platform.zones.current().data();\n if (existingApiZone) return await func(existingApiZone);\n const stackTrace = captureLibraryStackTrace(this._platform);\n const apiZone = {\n title: options?.title,\n apiName: stackTrace.apiName,\n frames: stackTrace.frames,\n internal: options?.internal ?? false,\n reported: false,\n userData: void 0,\n stepId: void 0\n };\n try {\n const result = await this._platform.zones.current().push(apiZone).run(async () => await func(apiZone));\n if (!options?.internal) {\n logApiCall(this._platform, logger, `<= ${apiZone.apiName} succeeded`);\n this._instrumentation.onApiCallEnd(apiZone);\n }\n return result;\n } catch (e) {\n const innerError = (this._platform.showInternalStackFrames() || this._platform.isUnderTest()) && e.stack ? "\\n<inner error>\\n" + e.stack : "";\n if (apiZone.apiName && !apiZone.apiName.includes("<anonymous>"))\n e.message = apiZone.apiName + ": " + e.message;\n const stackFrames = "\\n" + stringifyStackFrames(stackTrace.frames).join("\\n") + innerError;\n if (stackFrames.trim()) e.stack = e.message + stackFrames;\n else e.stack = "";\n if (!options?.internal) {\n apiZone.error = e;\n logApiCall(this._platform, logger, `<= ${apiZone.apiName} failed`);\n this._instrumentation.onApiCallEnd(apiZone);\n }\n throw e;\n }\n }\n toJSON() {\n return {\n _type: this._type,\n _guid: this._guid\n };\n }\n };\n function logApiCall(platform, logger, message) {\n if (logger && logger.isEnabled("api", "info"))\n logger.log("api", "info", message, [], { color: "cyan" });\n platform.log("api", message);\n }\n function tChannelImplToWire(names, arg, path, context) {\n if (arg._object instanceof ChannelOwner && (names === "*" || names.includes(arg._object._type)))\n return { guid: arg._object._guid };\n throw new ValidationError(`${path}: expected channel ${names.toString()}`);\n }\n\n // src/sandbox/forked-client/src/client/android.ts\n var Android = class extends ChannelOwner {\n static from(channel) {\n return channel?._object;\n }\n };\n var AndroidDevice = class extends ChannelOwner {\n static from(channel) {\n return channel?._object;\n }\n };\n var AndroidSocket = class extends ChannelOwner {\n static from(channel) {\n return channel?._object;\n }\n };\n\n // src/sandbox/forked-client/src/client/artifact.ts\n var Artifact = class extends ChannelOwner {\n static from(channel) {\n return channel?._object;\n }\n async pathAfterFinished() {\n throw new Error("Artifacts are not available in the QuickJS sandbox");\n }\n async saveAs() {\n throw new Error("Artifacts are not available in the QuickJS sandbox");\n }\n async failure() {\n return null;\n }\n async createReadStream() {\n throw new Error("Artifacts are not available in the QuickJS sandbox");\n }\n async readIntoBuffer() {\n throw new Error("Artifacts are not available in the QuickJS sandbox");\n }\n async cancel() {\n await this._channel.cancel?.();\n }\n async delete() {\n await this._channel.delete?.();\n }\n };\n\n // src/sandbox/forked-client/src/client/cdpSession.ts\n var CDPSession = class extends ChannelOwner {\n static from(cdpSession) {\n return cdpSession._object;\n }\n constructor(parent, type, guid, initializer) {\n super(parent, type, guid, initializer);\n this._channel.on("event", (event) => {\n this.emit(event.method, event.params);\n this.emit("event", event);\n });\n this._channel.on("close", () => {\n this.emit("close");\n });\n this.on = super.on;\n this.addListener = super.addListener;\n this.off = super.removeListener;\n this.removeListener = super.removeListener;\n this.once = super.once;\n }\n async send(method, params) {\n const result = await this._channel.send({ method, params });\n return result.result;\n }\n async detach() {\n return await this._channel.detach();\n }\n };\n\n // src/sandbox/forked-client/src/utils/isomorphic/stringUtils.ts\n function escapeWithQuotes(text, char = "\'") {\n const stringified = JSON.stringify(text);\n const escapedText = stringified.substring(1, stringified.length - 1).replace(/\\\\"/g, \'"\');\n if (char === "\'") return char + escapedText.replace(/[\']/g, "\\\\\'") + char;\n if (char === \'"\') return char + escapedText.replace(/["]/g, \'\\\\"\') + char;\n if (char === "`") return char + escapedText.replace(/[`]/g, "\\\\`") + char;\n throw new Error("Invalid escape char");\n }\n function isString(obj) {\n return typeof obj === "string" || obj instanceof String;\n }\n function toTitleCase(name) {\n return name.charAt(0).toUpperCase() + name.substring(1);\n }\n function toSnakeCase(name) {\n return name.replace(/([a-z0-9])([A-Z])/g, "$1_$2").replace(/([A-Z])([A-Z][a-z])/g, "$1_$2").toLowerCase();\n }\n function normalizeEscapedRegexQuotes(source) {\n return source.replace(/(^|[^\\\\])(\\\\\\\\)*\\\\([\'"`])/g, "$1$2$3");\n }\n function escapeRegexForSelector(re2) {\n if (re2.unicode || re2.unicodeSets) return String(re2);\n return String(re2).replace(/(^|[^\\\\])(\\\\\\\\)*(["\'`])/g, "$1$2\\\\$3").replace(/>>/g, "\\\\>\\\\>");\n }\n function escapeForTextSelector(text, exact) {\n if (typeof text !== "string") return escapeRegexForSelector(text);\n return `${JSON.stringify(text)}${exact ? "s" : "i"}`;\n }\n function escapeForAttributeSelector(value, exact) {\n if (typeof value !== "string") return escapeRegexForSelector(value);\n return `"${value.replace(/\\\\/g, "\\\\\\\\").replace(/["]/g, \'\\\\"\')}"${exact ? "s" : "i"}`;\n }\n function trimString(input, cap, suffix = "") {\n if (input.length <= cap) return input;\n const chars = [...input];\n if (chars.length > cap) return chars.slice(0, cap - suffix.length).join("") + suffix;\n return chars.join("");\n }\n function trimStringWithEllipsis(input, cap) {\n return trimString(input, cap, "\\u2026");\n }\n var ansiRegex = new RegExp(\n "([\\\\u001B\\\\u009B][[\\\\]()#;?]*(?:(?:(?:[a-zA-Z\\\\d]*(?:;[-a-zA-Z\\\\d\\\\/#&.:=?%@~_]*)*)?\\\\u0007)|(?:(?:\\\\d{1,4}(?:;\\\\d{0,4})*)?[\\\\dA-PR-TZcf-ntqry=><~])))",\n "g"\n );\n\n // src/sandbox/forked-client/src/utils/isomorphic/rtti.ts\n function isRegExp(obj) {\n return obj instanceof RegExp || Object.prototype.toString.call(obj) === "[object RegExp]";\n }\n function isObject(obj) {\n return typeof obj === "object" && obj !== null;\n }\n function isError(obj) {\n return obj instanceof Error || obj && Object.getPrototypeOf(obj)?.name === "Error";\n }\n\n // src/sandbox/forked-client/src/client/clientHelper.ts\n function envObjectToArray(env) {\n const result = [];\n for (const name in env) {\n if (!Object.is(env[name], void 0)) result.push({ name, value: String(env[name]) });\n }\n return result;\n }\n async function evaluationScript(platform, fun, arg, addSourceUrl = true) {\n if (typeof fun === "function") {\n const source = fun.toString();\n const argString = Object.is(arg, void 0) ? "undefined" : JSON.stringify(arg);\n return `(${source})(${argString})`;\n }\n if (arg !== void 0) throw new Error("Cannot evaluate a string with arguments");\n if (isString(fun)) return fun;\n if (fun.content !== void 0) return fun.content;\n if (fun.path !== void 0) {\n let source = await platform.fs().promises.readFile(fun.path, "utf8");\n if (addSourceUrl) source = addSourceUrlToScript(source, fun.path);\n return source;\n }\n throw new Error("Either path or content property must be present");\n }\n function addSourceUrlToScript(source, path) {\n return `${source}\n//# sourceURL=${path.replace(/\\n/g, "")}`;\n }\n\n // src/sandbox/forked-client/src/client/clock.ts\n var Clock = class {\n _browserContext;\n constructor(browserContext) {\n this._browserContext = browserContext;\n }\n async install(options = {}) {\n await this._browserContext._channel.clockInstall(\n options.time !== void 0 ? parseTime(options.time) : {}\n );\n }\n async fastForward(ticks) {\n await this._browserContext._channel.clockFastForward(parseTicks(ticks));\n }\n async pauseAt(time) {\n await this._browserContext._channel.clockPauseAt(parseTime(time));\n }\n async resume() {\n await this._browserContext._channel.clockResume({});\n }\n async runFor(ticks) {\n await this._browserContext._channel.clockRunFor(parseTicks(ticks));\n }\n async setFixedTime(time) {\n await this._browserContext._channel.clockSetFixedTime(parseTime(time));\n }\n async setSystemTime(time) {\n await this._browserContext._channel.clockSetSystemTime(parseTime(time));\n }\n };\n function parseTime(time) {\n if (typeof time === "number") return { timeNumber: time };\n if (typeof time === "string") return { timeString: time };\n if (!isFinite(time.getTime())) throw new Error(`Invalid date: ${time}`);\n return { timeNumber: time.getTime() };\n }\n function parseTicks(ticks) {\n return {\n ticksNumber: typeof ticks === "number" ? ticks : void 0,\n ticksString: typeof ticks === "string" ? ticks : void 0\n };\n }\n\n // src/sandbox/forked-client/src/protocol/serializers.ts\n function parseSerializedValue(value, handles) {\n return innerParseSerializedValue(value, handles, /* @__PURE__ */ new Map(), []);\n }\n function innerParseSerializedValue(value, handles, refs, accessChain) {\n if (value.ref !== void 0) return refs.get(value.ref);\n if (value.n !== void 0) return value.n;\n if (value.s !== void 0) return value.s;\n if (value.b !== void 0) return value.b;\n if (value.v !== void 0) {\n if (value.v === "undefined") return void 0;\n if (value.v === "null") return null;\n if (value.v === "NaN") return NaN;\n if (value.v === "Infinity") return Infinity;\n if (value.v === "-Infinity") return -Infinity;\n if (value.v === "-0") return -0;\n }\n if (value.d !== void 0) return new Date(value.d);\n if (value.u !== void 0) return new URL(value.u);\n if (value.bi !== void 0) return BigInt(value.bi);\n if (value.e !== void 0) {\n const error = new Error(value.e.m);\n error.name = value.e.n;\n error.stack = value.e.s;\n return error;\n }\n if (value.r !== void 0) return new RegExp(value.r.p, value.r.f);\n if (value.ta !== void 0) {\n const ctor = typedArrayKindToConstructor[value.ta.k];\n return new ctor(\n value.ta.b.buffer,\n value.ta.b.byteOffset,\n value.ta.b.length / ctor.BYTES_PER_ELEMENT\n );\n }\n if (value.a !== void 0) {\n const result = [];\n refs.set(value.id, result);\n for (let i = 0; i < value.a.length; i++)\n result.push(innerParseSerializedValue(value.a[i], handles, refs, [...accessChain, i]));\n return result;\n }\n if (value.o !== void 0) {\n const result = {};\n refs.set(value.id, result);\n for (const { k, v } of value.o)\n result[k] = innerParseSerializedValue(v, handles, refs, [...accessChain, k]);\n return result;\n }\n if (value.h !== void 0) {\n if (handles === void 0) throw new Error("Unexpected handle");\n return handles[value.h];\n }\n throw new Error(\n `Attempting to deserialize unexpected value${accessChainToDisplayString(accessChain)}: ${value}`\n );\n }\n function serializeValue(value, handleSerializer) {\n return innerSerializeValue(value, handleSerializer, { lastId: 0, visited: /* @__PURE__ */ new Map() }, []);\n }\n function innerSerializeValue(value, handleSerializer, visitorInfo, accessChain) {\n const handle = handleSerializer(value);\n if ("fallThrough" in handle) value = handle.fallThrough;\n else return handle;\n if (typeof value === "symbol") return { v: "undefined" };\n if (Object.is(value, void 0)) return { v: "undefined" };\n if (Object.is(value, null)) return { v: "null" };\n if (Object.is(value, NaN)) return { v: "NaN" };\n if (Object.is(value, Infinity)) return { v: "Infinity" };\n if (Object.is(value, -Infinity)) return { v: "-Infinity" };\n if (Object.is(value, -0)) return { v: "-0" };\n if (typeof value === "boolean") return { b: value };\n if (typeof value === "number") return { n: value };\n if (typeof value === "string") return { s: value };\n if (typeof value === "bigint") return { bi: value.toString() };\n if (isError2(value)) return { e: { n: value.name, m: value.message, s: value.stack || "" } };\n if (isDate(value)) return { d: value.toJSON() };\n if (isURL(value)) return { u: value.toJSON() };\n if (isRegExp2(value)) return { r: { p: value.source, f: value.flags } };\n const typedArrayKind = constructorToTypedArrayKind.get(value.constructor);\n if (typedArrayKind)\n return {\n ta: { b: Buffer.from(value.buffer, value.byteOffset, value.byteLength), k: typedArrayKind }\n };\n const id = visitorInfo.visited.get(value);\n if (id) return { ref: id };\n if (Array.isArray(value)) {\n const a = [];\n const id2 = ++visitorInfo.lastId;\n visitorInfo.visited.set(value, id2);\n for (let i = 0; i < value.length; ++i)\n a.push(innerSerializeValue(value[i], handleSerializer, visitorInfo, [...accessChain, i]));\n return { a, id: id2 };\n }\n if (typeof value === "object") {\n const o = [];\n const id2 = ++visitorInfo.lastId;\n visitorInfo.visited.set(value, id2);\n for (const name of Object.keys(value))\n o.push({\n k: name,\n v: innerSerializeValue(value[name], handleSerializer, visitorInfo, [...accessChain, name])\n });\n return { o, id: id2 };\n }\n throw new Error(\n `Attempting to serialize unexpected value${accessChainToDisplayString(accessChain)}: ${value}`\n );\n }\n function accessChainToDisplayString(accessChain) {\n const chainString = accessChain.map((accessor, i) => {\n if (typeof accessor === "string") return i ? `.${accessor}` : accessor;\n return `[${accessor}]`;\n }).join("");\n return chainString.length > 0 ? ` at position "${chainString}"` : "";\n }\n function isRegExp2(obj) {\n return obj instanceof RegExp || Object.prototype.toString.call(obj) === "[object RegExp]";\n }\n function isDate(obj) {\n return obj instanceof Date || Object.prototype.toString.call(obj) === "[object Date]";\n }\n function isURL(obj) {\n return obj instanceof URL || Object.prototype.toString.call(obj) === "[object URL]";\n }\n function isError2(obj) {\n const proto = obj ? Object.getPrototypeOf(obj) : null;\n return obj instanceof Error || proto?.name === "Error" || proto && isError2(proto);\n }\n var typedArrayKindToConstructor = {\n i8: Int8Array,\n ui8: Uint8Array,\n ui8c: Uint8ClampedArray,\n i16: Int16Array,\n ui16: Uint16Array,\n i32: Int32Array,\n ui32: Uint32Array,\n f32: Float32Array,\n f64: Float64Array,\n bi64: BigInt64Array,\n bui64: BigUint64Array\n };\n var constructorToTypedArrayKind = new Map(\n Object.entries(typedArrayKindToConstructor).map(([k, v]) => [v, k])\n );\n\n // src/sandbox/forked-client/src/client/errors.ts\n var TimeoutError = class extends Error {\n constructor(message) {\n super(message);\n this.name = "TimeoutError";\n }\n };\n var TargetClosedError = class extends Error {\n constructor(cause) {\n super(cause || "Target page, context or browser has been closed");\n }\n };\n function isTargetClosedError(error) {\n return error instanceof TargetClosedError;\n }\n function serializeError(e) {\n if (isError(e)) return { error: { message: e.message, stack: e.stack, name: e.name } };\n return { value: serializeValue(e, (value) => ({ fallThrough: value })) };\n }\n function parseError(error) {\n if (!error.error) {\n if (error.value === void 0)\n throw new Error("Serialized error must have either an error or a value");\n return parseSerializedValue(error.value, void 0);\n }\n if (error.error.name === "TimeoutError") {\n const e2 = new TimeoutError(error.error.message);\n e2.stack = error.error.stack || "";\n return e2;\n }\n if (error.error.name === "TargetClosedError") {\n const e2 = new TargetClosedError(error.error.message);\n e2.stack = error.error.stack || "";\n return e2;\n }\n const e = new Error(error.error.message);\n e.stack = error.error.stack || "";\n e.name = error.error.name;\n return e;\n }\n\n // src/sandbox/forked-client/src/client/jsHandle.ts\n var JSHandle = class _JSHandle extends ChannelOwner {\n _preview;\n static from(handle) {\n return handle._object;\n }\n constructor(parent, type, guid, initializer) {\n super(parent, type, guid, initializer);\n this._preview = this._initializer.preview;\n this._channel.on("previewUpdated", ({ preview }) => this._preview = preview);\n }\n async evaluate(pageFunction, arg) {\n const result = await this._channel.evaluateExpression({\n expression: String(pageFunction),\n isFunction: typeof pageFunction === "function",\n arg: serializeArgument(arg)\n });\n return parseResult(result.value);\n }\n async evaluateHandle(pageFunction, arg) {\n const result = await this._channel.evaluateExpressionHandle({\n expression: String(pageFunction),\n isFunction: typeof pageFunction === "function",\n arg: serializeArgument(arg)\n });\n return _JSHandle.from(result.handle);\n }\n async getProperty(propertyName) {\n const result = await this._channel.getProperty({ name: propertyName });\n return _JSHandle.from(result.handle);\n }\n async getProperties() {\n const map = /* @__PURE__ */ new Map();\n for (const { name, value } of (await this._channel.getPropertyList()).properties)\n map.set(name, _JSHandle.from(value));\n return map;\n }\n async jsonValue() {\n return parseResult((await this._channel.jsonValue()).value);\n }\n asElement() {\n return null;\n }\n async [Symbol.asyncDispose]() {\n await this.dispose();\n }\n async dispose() {\n try {\n await this._channel.dispose();\n } catch (e) {\n if (isTargetClosedError(e)) return;\n throw e;\n }\n }\n toString() {\n return this._preview;\n }\n };\n function serializeArgument(arg) {\n const handles = [];\n const pushHandle = (channel) => {\n handles.push(channel);\n return handles.length - 1;\n };\n const value = serializeValue(arg, (value2) => {\n if (value2 instanceof JSHandle) return { h: pushHandle(value2._channel) };\n return { fallThrough: value2 };\n });\n return { value, handles };\n }\n function parseResult(value) {\n return parseSerializedValue(value, void 0);\n }\n function assertMaxArguments(count, max) {\n if (count > max)\n throw new Error(\n "Too many arguments. If you need to pass more than 1 argument to the function wrap them in an object."\n );\n }\n\n // src/sandbox/forked-client/src/client/consoleMessage.ts\n var ConsoleMessage = class {\n _page;\n _worker;\n _event;\n constructor(platform, event, page, worker) {\n this._page = page;\n this._worker = worker;\n this._event = event;\n if (platform.inspectCustom) this[platform.inspectCustom] = () => this._inspect();\n }\n worker() {\n return this._worker;\n }\n page() {\n return this._page;\n }\n type() {\n return this._event.type;\n }\n text() {\n return this._event.text;\n }\n args() {\n return this._event.args.map(JSHandle.from);\n }\n location() {\n return this._event.location;\n }\n timestamp() {\n return this._event.timestamp;\n }\n _inspect() {\n return this.text();\n }\n };\n\n // src/sandbox/forked-client/src/client/coverage.ts\n var Coverage = class {\n _channel;\n constructor(channel) {\n this._channel = channel;\n }\n async startJSCoverage(options = {}) {\n await this._channel.startJSCoverage(options);\n }\n async stopJSCoverage() {\n return (await this._channel.stopJSCoverage()).entries;\n }\n async startCSSCoverage(options = {}) {\n await this._channel.startCSSCoverage(options);\n }\n async stopCSSCoverage() {\n return (await this._channel.stopCSSCoverage()).entries;\n }\n };\n\n // src/sandbox/forked-client/src/client/disposable.ts\n var DisposableObject = class extends ChannelOwner {\n static from(channel) {\n return channel._object;\n }\n async [Symbol.asyncDispose]() {\n await this.dispose();\n }\n async dispose() {\n try {\n await this._channel.dispose();\n } catch (e) {\n if (isTargetClosedError(e)) return;\n throw e;\n }\n }\n };\n var DisposableStub = class {\n _dispose;\n constructor(dispose) {\n this._dispose = dispose;\n }\n async [Symbol.asyncDispose]() {\n await this.dispose();\n }\n async dispose() {\n if (!this._dispose) return;\n try {\n const dispose = this._dispose;\n this._dispose = void 0;\n await dispose();\n } catch (e) {\n if (isTargetClosedError(e)) return;\n throw e;\n }\n }\n };\n\n // src/sandbox/forked-client/src/client/download.ts\n var Download = class {\n _page;\n _url;\n _suggestedFilename;\n _artifact;\n constructor(page, url, suggestedFilename, artifact) {\n this._page = page;\n this._url = url;\n this._suggestedFilename = suggestedFilename;\n this._artifact = artifact;\n }\n page() {\n return this._page;\n }\n url() {\n return this._url;\n }\n suggestedFilename() {\n return this._suggestedFilename;\n }\n async path() {\n return await this._artifact.pathAfterFinished();\n }\n async saveAs(path) {\n return await this._artifact.saveAs(path);\n }\n async failure() {\n return await this._artifact.failure();\n }\n async createReadStream() {\n return await this._artifact.createReadStream();\n }\n async cancel() {\n return await this._artifact.cancel();\n }\n async delete() {\n return await this._artifact.delete();\n }\n };\n\n // src/sandbox/forked-client/src/client/events.ts\n var Events = {\n AndroidDevice: {\n WebView: "webview",\n Close: "close"\n },\n AndroidSocket: {\n Data: "data",\n Close: "close"\n },\n AndroidWebView: {\n Close: "close"\n },\n Browser: {\n Disconnected: "disconnected"\n },\n Debugger: {\n PausedStateChanged: "pausedstatechanged"\n },\n BrowserContext: {\n Console: "console",\n Close: "close",\n Dialog: "dialog",\n Page: "page",\n // Can\'t use just \'error\' due to node.js special treatment of error events.\n // @see https://nodejs.org/api/events.html#events_error_events\n WebError: "weberror",\n BackgroundPage: "backgroundpage",\n // Deprecated in v1.56, never emitted anymore.\n ServiceWorker: "serviceworker",\n Request: "request",\n Response: "response",\n RequestFailed: "requestfailed",\n RequestFinished: "requestfinished"\n },\n BrowserServer: {\n Close: "close"\n },\n Page: {\n Close: "close",\n Crash: "crash",\n Console: "console",\n Dialog: "dialog",\n Download: "download",\n FileChooser: "filechooser",\n DOMContentLoaded: "domcontentloaded",\n // Can\'t use just \'error\' due to node.js special treatment of error events.\n // @see https://nodejs.org/api/events.html#events_error_events\n PageError: "pageerror",\n Request: "request",\n Response: "response",\n RequestFailed: "requestfailed",\n RequestFinished: "requestfinished",\n FrameAttached: "frameattached",\n FrameDetached: "framedetached",\n FrameNavigated: "framenavigated",\n Load: "load",\n Popup: "popup",\n WebSocket: "websocket",\n Worker: "worker"\n },\n WebSocket: {\n Close: "close",\n Error: "socketerror",\n FrameReceived: "framereceived",\n FrameSent: "framesent"\n },\n Worker: {\n Close: "close",\n Console: "console"\n },\n ElectronApplication: {\n Close: "close",\n Console: "console",\n Window: "window"\n }\n };\n\n // src/sandbox/forked-client/src/utils/isomorphic/cssTokenizer.ts\n var between = function(num, first, last) {\n return num >= first && num <= last;\n };\n function digit(code) {\n return between(code, 48, 57);\n }\n function hexdigit(code) {\n return digit(code) || between(code, 65, 70) || between(code, 97, 102);\n }\n function uppercaseletter(code) {\n return between(code, 65, 90);\n }\n function lowercaseletter(code) {\n return between(code, 97, 122);\n }\n function letter(code) {\n return uppercaseletter(code) || lowercaseletter(code);\n }\n function nonascii(code) {\n return code >= 128;\n }\n function namestartchar(code) {\n return letter(code) || nonascii(code) || code === 95;\n }\n function namechar(code) {\n return namestartchar(code) || digit(code) || code === 45;\n }\n function nonprintable(code) {\n return between(code, 0, 8) || code === 11 || between(code, 14, 31) || code === 127;\n }\n function newline(code) {\n return code === 10;\n }\n function whitespace(code) {\n return newline(code) || code === 9 || code === 32;\n }\n var maximumallowedcodepoint = 1114111;\n var InvalidCharacterError = class extends Error {\n constructor(message) {\n super(message);\n this.name = "InvalidCharacterError";\n }\n };\n function preprocess(str) {\n const codepoints = [];\n for (let i = 0; i < str.length; i++) {\n let code = str.charCodeAt(i);\n if (code === 13 && str.charCodeAt(i + 1) === 10) {\n code = 10;\n i++;\n }\n if (code === 13 || code === 12) code = 10;\n if (code === 0) code = 65533;\n if (between(code, 55296, 56319) && between(str.charCodeAt(i + 1), 56320, 57343)) {\n const lead = code - 55296;\n const trail = str.charCodeAt(i + 1) - 56320;\n code = Math.pow(2, 16) + lead * Math.pow(2, 10) + trail;\n i++;\n }\n codepoints.push(code);\n }\n return codepoints;\n }\n function stringFromCode(code) {\n if (code <= 65535) return String.fromCharCode(code);\n code -= Math.pow(2, 16);\n const lead = Math.floor(code / Math.pow(2, 10)) + 55296;\n const trail = code % Math.pow(2, 10) + 56320;\n return String.fromCharCode(lead) + String.fromCharCode(trail);\n }\n function tokenize(str1) {\n const str = preprocess(str1);\n let i = -1;\n const tokens = [];\n let code;\n let line = 0;\n let column = 0;\n let lastLineLength = 0;\n const incrLineno = function() {\n line += 1;\n lastLineLength = column;\n column = 0;\n };\n const locStart = { line, column };\n const codepoint = function(i2) {\n if (i2 >= str.length) return -1;\n return str[i2];\n };\n const next = function(num) {\n if (num === void 0) num = 1;\n if (num > 3) throw "Spec Error: no more than three codepoints of lookahead.";\n return codepoint(i + num);\n };\n const consume = function(num) {\n if (num === void 0) num = 1;\n i += num;\n code = codepoint(i);\n if (newline(code)) incrLineno();\n else column += num;\n return true;\n };\n const reconsume = function() {\n i -= 1;\n if (newline(code)) {\n line -= 1;\n column = lastLineLength;\n } else {\n column -= 1;\n }\n locStart.line = line;\n locStart.column = column;\n return true;\n };\n const eof = function(codepoint2) {\n if (codepoint2 === void 0) codepoint2 = code;\n return codepoint2 === -1;\n };\n const donothing = function() {\n };\n const parseerror = function() {\n };\n const consumeAToken = function() {\n consumeComments();\n consume();\n if (whitespace(code)) {\n while (whitespace(next())) consume();\n return new WhitespaceToken();\n } else if (code === 34) {\n return consumeAStringToken();\n } else if (code === 35) {\n if (namechar(next()) || areAValidEscape(next(1), next(2))) {\n const token = new HashToken("");\n if (wouldStartAnIdentifier(next(1), next(2), next(3))) token.type = "id";\n token.value = consumeAName();\n return token;\n } else {\n return new DelimToken(code);\n }\n } else if (code === 36) {\n if (next() === 61) {\n consume();\n return new SuffixMatchToken();\n } else {\n return new DelimToken(code);\n }\n } else if (code === 39) {\n return consumeAStringToken();\n } else if (code === 40) {\n return new OpenParenToken();\n } else if (code === 41) {\n return new CloseParenToken();\n } else if (code === 42) {\n if (next() === 61) {\n consume();\n return new SubstringMatchToken();\n } else {\n return new DelimToken(code);\n }\n } else if (code === 43) {\n if (startsWithANumber()) {\n reconsume();\n return consumeANumericToken();\n } else {\n return new DelimToken(code);\n }\n } else if (code === 44) {\n return new CommaToken();\n } else if (code === 45) {\n if (startsWithANumber()) {\n reconsume();\n return consumeANumericToken();\n } else if (next(1) === 45 && next(2) === 62) {\n consume(2);\n return new CDCToken();\n } else if (startsWithAnIdentifier()) {\n reconsume();\n return consumeAnIdentlikeToken();\n } else {\n return new DelimToken(code);\n }\n } else if (code === 46) {\n if (startsWithANumber()) {\n reconsume();\n return consumeANumericToken();\n } else {\n return new DelimToken(code);\n }\n } else if (code === 58) {\n return new ColonToken();\n } else if (code === 59) {\n return new SemicolonToken();\n } else if (code === 60) {\n if (next(1) === 33 && next(2) === 45 && next(3) === 45) {\n consume(3);\n return new CDOToken();\n } else {\n return new DelimToken(code);\n }\n } else if (code === 64) {\n if (wouldStartAnIdentifier(next(1), next(2), next(3)))\n return new AtKeywordToken(consumeAName());\n else return new DelimToken(code);\n } else if (code === 91) {\n return new OpenSquareToken();\n } else if (code === 92) {\n if (startsWithAValidEscape()) {\n reconsume();\n return consumeAnIdentlikeToken();\n } else {\n parseerror();\n return new DelimToken(code);\n }\n } else if (code === 93) {\n return new CloseSquareToken();\n } else if (code === 94) {\n if (next() === 61) {\n consume();\n return new PrefixMatchToken();\n } else {\n return new DelimToken(code);\n }\n } else if (code === 123) {\n return new OpenCurlyToken();\n } else if (code === 124) {\n if (next() === 61) {\n consume();\n return new DashMatchToken();\n } else if (next() === 124) {\n consume();\n return new ColumnToken();\n } else {\n return new DelimToken(code);\n }\n } else if (code === 125) {\n return new CloseCurlyToken();\n } else if (code === 126) {\n if (next() === 61) {\n consume();\n return new IncludeMatchToken();\n } else {\n return new DelimToken(code);\n }\n } else if (digit(code)) {\n reconsume();\n return consumeANumericToken();\n } else if (namestartchar(code)) {\n reconsume();\n return consumeAnIdentlikeToken();\n } else if (eof()) {\n return new EOFToken();\n } else {\n return new DelimToken(code);\n }\n };\n const consumeComments = function() {\n while (next(1) === 47 && next(2) === 42) {\n consume(2);\n while (true) {\n consume();\n if (code === 42 && next() === 47) {\n consume();\n break;\n } else if (eof()) {\n parseerror();\n return;\n }\n }\n }\n };\n const consumeANumericToken = function() {\n const num = consumeANumber();\n if (wouldStartAnIdentifier(next(1), next(2), next(3))) {\n const token = new DimensionToken();\n token.value = num.value;\n token.repr = num.repr;\n token.type = num.type;\n token.unit = consumeAName();\n return token;\n } else if (next() === 37) {\n consume();\n const token = new PercentageToken();\n token.value = num.value;\n token.repr = num.repr;\n return token;\n } else {\n const token = new NumberToken();\n token.value = num.value;\n token.repr = num.repr;\n token.type = num.type;\n return token;\n }\n };\n const consumeAnIdentlikeToken = function() {\n const str2 = consumeAName();\n if (str2.toLowerCase() === "url" && next() === 40) {\n consume();\n while (whitespace(next(1)) && whitespace(next(2))) consume();\n if (next() === 34 || next() === 39) return new FunctionToken(str2);\n else if (whitespace(next()) && (next(2) === 34 || next(2) === 39))\n return new FunctionToken(str2);\n else return consumeAURLToken();\n } else if (next() === 40) {\n consume();\n return new FunctionToken(str2);\n } else {\n return new IdentToken(str2);\n }\n };\n const consumeAStringToken = function(endingCodePoint) {\n if (endingCodePoint === void 0) endingCodePoint = code;\n let string = "";\n while (consume()) {\n if (code === endingCodePoint || eof()) {\n return new StringToken(string);\n } else if (newline(code)) {\n parseerror();\n reconsume();\n return new BadStringToken();\n } else if (code === 92) {\n if (eof(next())) donothing();\n else if (newline(next())) consume();\n else string += stringFromCode(consumeEscape());\n } else {\n string += stringFromCode(code);\n }\n }\n throw new Error("Internal error");\n };\n const consumeAURLToken = function() {\n const token = new URLToken("");\n while (whitespace(next())) consume();\n if (eof(next())) return token;\n while (consume()) {\n if (code === 41 || eof()) {\n return token;\n } else if (whitespace(code)) {\n while (whitespace(next())) consume();\n if (next() === 41 || eof(next())) {\n consume();\n return token;\n } else {\n consumeTheRemnantsOfABadURL();\n return new BadURLToken();\n }\n } else if (code === 34 || code === 39 || code === 40 || nonprintable(code)) {\n parseerror();\n consumeTheRemnantsOfABadURL();\n return new BadURLToken();\n } else if (code === 92) {\n if (startsWithAValidEscape()) {\n token.value += stringFromCode(consumeEscape());\n } else {\n parseerror();\n consumeTheRemnantsOfABadURL();\n return new BadURLToken();\n }\n } else {\n token.value += stringFromCode(code);\n }\n }\n throw new Error("Internal error");\n };\n const consumeEscape = function() {\n consume();\n if (hexdigit(code)) {\n const digits = [code];\n for (let total = 0; total < 5; total++) {\n if (hexdigit(next())) {\n consume();\n digits.push(code);\n } else {\n break;\n }\n }\n if (whitespace(next())) consume();\n let value = parseInt(\n digits.map(function(x) {\n return String.fromCharCode(x);\n }).join(""),\n 16\n );\n if (value > maximumallowedcodepoint) value = 65533;\n return value;\n } else if (eof()) {\n return 65533;\n } else {\n return code;\n }\n };\n const areAValidEscape = function(c1, c2) {\n if (c1 !== 92) return false;\n if (newline(c2)) return false;\n return true;\n };\n const startsWithAValidEscape = function() {\n return areAValidEscape(code, next());\n };\n const wouldStartAnIdentifier = function(c1, c2, c3) {\n if (c1 === 45) return namestartchar(c2) || c2 === 45 || areAValidEscape(c2, c3);\n else if (namestartchar(c1)) return true;\n else if (c1 === 92) return areAValidEscape(c1, c2);\n else return false;\n };\n const startsWithAnIdentifier = function() {\n return wouldStartAnIdentifier(code, next(1), next(2));\n };\n const wouldStartANumber = function(c1, c2, c3) {\n if (c1 === 43 || c1 === 45) {\n if (digit(c2)) return true;\n if (c2 === 46 && digit(c3)) return true;\n return false;\n } else if (c1 === 46) {\n if (digit(c2)) return true;\n return false;\n } else if (digit(c1)) {\n return true;\n } else {\n return false;\n }\n };\n const startsWithANumber = function() {\n return wouldStartANumber(code, next(1), next(2));\n };\n const consumeAName = function() {\n let result = "";\n while (consume()) {\n if (namechar(code)) {\n result += stringFromCode(code);\n } else if (startsWithAValidEscape()) {\n result += stringFromCode(consumeEscape());\n } else {\n reconsume();\n return result;\n }\n }\n throw new Error("Internal parse error");\n };\n const consumeANumber = function() {\n let repr = "";\n let type = "integer";\n if (next() === 43 || next() === 45) {\n consume();\n repr += stringFromCode(code);\n }\n while (digit(next())) {\n consume();\n repr += stringFromCode(code);\n }\n if (next(1) === 46 && digit(next(2))) {\n consume();\n repr += stringFromCode(code);\n consume();\n repr += stringFromCode(code);\n type = "number";\n while (digit(next())) {\n consume();\n repr += stringFromCode(code);\n }\n }\n const c1 = next(1), c2 = next(2), c3 = next(3);\n if ((c1 === 69 || c1 === 101) && digit(c2)) {\n consume();\n repr += stringFromCode(code);\n consume();\n repr += stringFromCode(code);\n type = "number";\n while (digit(next())) {\n consume();\n repr += stringFromCode(code);\n }\n } else if ((c1 === 69 || c1 === 101) && (c2 === 43 || c2 === 45) && digit(c3)) {\n consume();\n repr += stringFromCode(code);\n consume();\n repr += stringFromCode(code);\n consume();\n repr += stringFromCode(code);\n type = "number";\n while (digit(next())) {\n consume();\n repr += stringFromCode(code);\n }\n }\n const value = convertAStringToANumber(repr);\n return { type, value, repr };\n };\n const convertAStringToANumber = function(string) {\n return +string;\n };\n const consumeTheRemnantsOfABadURL = function() {\n while (consume()) {\n if (code === 41 || eof()) {\n return;\n } else if (startsWithAValidEscape()) {\n consumeEscape();\n donothing();\n } else {\n donothing();\n }\n }\n };\n let iterationCount = 0;\n while (!eof(next())) {\n tokens.push(consumeAToken());\n iterationCount++;\n if (iterationCount > str.length * 2) throw new Error("I\'m infinite-looping!");\n }\n return tokens;\n }\n var CSSParserToken = class {\n tokenType = "";\n value;\n toJSON() {\n return { token: this.tokenType };\n }\n toString() {\n return this.tokenType;\n }\n toSource() {\n return "" + this;\n }\n };\n var BadStringToken = class extends CSSParserToken {\n tokenType = "BADSTRING";\n };\n var BadURLToken = class extends CSSParserToken {\n tokenType = "BADURL";\n };\n var WhitespaceToken = class extends CSSParserToken {\n tokenType = "WHITESPACE";\n toString() {\n return "WS";\n }\n toSource() {\n return " ";\n }\n };\n var CDOToken = class extends CSSParserToken {\n tokenType = "CDO";\n toSource() {\n return "<!--";\n }\n };\n var CDCToken = class extends CSSParserToken {\n tokenType = "CDC";\n toSource() {\n return "-->";\n }\n };\n var ColonToken = class extends CSSParserToken {\n tokenType = ":";\n };\n var SemicolonToken = class extends CSSParserToken {\n tokenType = ";";\n };\n var CommaToken = class extends CSSParserToken {\n tokenType = ",";\n };\n var GroupingToken = class extends CSSParserToken {\n value = "";\n mirror = "";\n };\n var OpenCurlyToken = class extends GroupingToken {\n tokenType = "{";\n constructor() {\n super();\n this.value = "{";\n this.mirror = "}";\n }\n };\n var CloseCurlyToken = class extends GroupingToken {\n tokenType = "}";\n constructor() {\n super();\n this.value = "}";\n this.mirror = "{";\n }\n };\n var OpenSquareToken = class extends GroupingToken {\n tokenType = "[";\n constructor() {\n super();\n this.value = "[";\n this.mirror = "]";\n }\n };\n var CloseSquareToken = class extends GroupingToken {\n tokenType = "]";\n constructor() {\n super();\n this.value = "]";\n this.mirror = "[";\n }\n };\n var OpenParenToken = class extends GroupingToken {\n tokenType = "(";\n constructor() {\n super();\n this.value = "(";\n this.mirror = ")";\n }\n };\n var CloseParenToken = class extends GroupingToken {\n tokenType = ")";\n constructor() {\n super();\n this.value = ")";\n this.mirror = "(";\n }\n };\n var IncludeMatchToken = class extends CSSParserToken {\n tokenType = "~=";\n };\n var DashMatchToken = class extends CSSParserToken {\n tokenType = "|=";\n };\n var PrefixMatchToken = class extends CSSParserToken {\n tokenType = "^=";\n };\n var SuffixMatchToken = class extends CSSParserToken {\n tokenType = "$=";\n };\n var SubstringMatchToken = class extends CSSParserToken {\n tokenType = "*=";\n };\n var ColumnToken = class extends CSSParserToken {\n tokenType = "||";\n };\n var EOFToken = class extends CSSParserToken {\n tokenType = "EOF";\n toSource() {\n return "";\n }\n };\n var DelimToken = class extends CSSParserToken {\n tokenType = "DELIM";\n value = "";\n constructor(code) {\n super();\n this.value = stringFromCode(code);\n }\n toString() {\n return "DELIM(" + this.value + ")";\n }\n toJSON() {\n const json = this.constructor.prototype.constructor.prototype.toJSON.call(this);\n json.value = this.value;\n return json;\n }\n toSource() {\n if (this.value === "\\\\") return "\\\\\\n";\n else return this.value;\n }\n };\n var StringValuedToken = class extends CSSParserToken {\n value = "";\n ASCIIMatch(str) {\n return this.value.toLowerCase() === str.toLowerCase();\n }\n toJSON() {\n const json = this.constructor.prototype.constructor.prototype.toJSON.call(this);\n json.value = this.value;\n return json;\n }\n };\n var IdentToken = class extends StringValuedToken {\n constructor(val) {\n super();\n this.value = val;\n }\n tokenType = "IDENT";\n toString() {\n return "IDENT(" + this.value + ")";\n }\n toSource() {\n return escapeIdent(this.value);\n }\n };\n var FunctionToken = class extends StringValuedToken {\n tokenType = "FUNCTION";\n mirror;\n constructor(val) {\n super();\n this.value = val;\n this.mirror = ")";\n }\n toString() {\n return "FUNCTION(" + this.value + ")";\n }\n toSource() {\n return escapeIdent(this.value) + "(";\n }\n };\n var AtKeywordToken = class extends StringValuedToken {\n tokenType = "AT-KEYWORD";\n constructor(val) {\n super();\n this.value = val;\n }\n toString() {\n return "AT(" + this.value + ")";\n }\n toSource() {\n return "@" + escapeIdent(this.value);\n }\n };\n var HashToken = class extends StringValuedToken {\n tokenType = "HASH";\n type;\n constructor(val) {\n super();\n this.value = val;\n this.type = "unrestricted";\n }\n toString() {\n return "HASH(" + this.value + ")";\n }\n toJSON() {\n const json = this.constructor.prototype.constructor.prototype.toJSON.call(this);\n json.value = this.value;\n json.type = this.type;\n return json;\n }\n toSource() {\n if (this.type === "id") return "#" + escapeIdent(this.value);\n else return "#" + escapeHash(this.value);\n }\n };\n var StringToken = class extends StringValuedToken {\n tokenType = "STRING";\n constructor(val) {\n super();\n this.value = val;\n }\n toString() {\n return \'"\' + escapeString(this.value) + \'"\';\n }\n };\n var URLToken = class extends StringValuedToken {\n tokenType = "URL";\n constructor(val) {\n super();\n this.value = val;\n }\n toString() {\n return "URL(" + this.value + ")";\n }\n toSource() {\n return \'url("\' + escapeString(this.value) + \'")\';\n }\n };\n var NumberToken = class extends CSSParserToken {\n tokenType = "NUMBER";\n type;\n repr;\n constructor() {\n super();\n this.type = "integer";\n this.repr = "";\n }\n toString() {\n if (this.type === "integer") return "INT(" + this.value + ")";\n return "NUMBER(" + this.value + ")";\n }\n toJSON() {\n const json = super.toJSON();\n json.value = this.value;\n json.type = this.type;\n json.repr = this.repr;\n return json;\n }\n toSource() {\n return this.repr;\n }\n };\n var PercentageToken = class extends CSSParserToken {\n tokenType = "PERCENTAGE";\n repr;\n constructor() {\n super();\n this.repr = "";\n }\n toString() {\n return "PERCENTAGE(" + this.value + ")";\n }\n toJSON() {\n const json = this.constructor.prototype.constructor.prototype.toJSON.call(this);\n json.value = this.value;\n json.repr = this.repr;\n return json;\n }\n toSource() {\n return this.repr + "%";\n }\n };\n var DimensionToken = class extends CSSParserToken {\n tokenType = "DIMENSION";\n type;\n repr;\n unit;\n constructor() {\n super();\n this.type = "integer";\n this.repr = "";\n this.unit = "";\n }\n toString() {\n return "DIM(" + this.value + "," + this.unit + ")";\n }\n toJSON() {\n const json = this.constructor.prototype.constructor.prototype.toJSON.call(this);\n json.value = this.value;\n json.type = this.type;\n json.repr = this.repr;\n json.unit = this.unit;\n return json;\n }\n toSource() {\n const source = this.repr;\n let unit = escapeIdent(this.unit);\n if (unit[0].toLowerCase() === "e" && (unit[1] === "-" || between(unit.charCodeAt(1), 48, 57))) {\n unit = "\\\\65 " + unit.slice(1, unit.length);\n }\n return source + unit;\n }\n };\n function escapeIdent(string) {\n string = "" + string;\n let result = "";\n const firstcode = string.charCodeAt(0);\n for (let i = 0; i < string.length; i++) {\n const code = string.charCodeAt(i);\n if (code === 0)\n throw new InvalidCharacterError("Invalid character: the input contains U+0000.");\n if (between(code, 1, 31) || code === 127 || i === 0 && between(code, 48, 57) || i === 1 && between(code, 48, 57) && firstcode === 45)\n result += "\\\\" + code.toString(16) + " ";\n else if (code >= 128 || code === 45 || code === 95 || between(code, 48, 57) || between(code, 65, 90) || between(code, 97, 122))\n result += string[i];\n else result += "\\\\" + string[i];\n }\n return result;\n }\n function escapeHash(string) {\n string = "" + string;\n let result = "";\n for (let i = 0; i < string.length; i++) {\n const code = string.charCodeAt(i);\n if (code === 0)\n throw new InvalidCharacterError("Invalid character: the input contains U+0000.");\n if (code >= 128 || code === 45 || code === 95 || between(code, 48, 57) || between(code, 65, 90) || between(code, 97, 122))\n result += string[i];\n else result += "\\\\" + code.toString(16) + " ";\n }\n return result;\n }\n function escapeString(string) {\n string = "" + string;\n let result = "";\n for (let i = 0; i < string.length; i++) {\n const code = string.charCodeAt(i);\n if (code === 0)\n throw new InvalidCharacterError("Invalid character: the input contains U+0000.");\n if (between(code, 1, 31) || code === 127) result += "\\\\" + code.toString(16) + " ";\n else if (code === 34 || code === 92) result += "\\\\" + string[i];\n else result += string[i];\n }\n return result;\n }\n\n // src/sandbox/forked-client/src/utils/isomorphic/cssParser.ts\n var InvalidSelectorError = class extends Error {\n };\n function parseCSS(selector, customNames) {\n let tokens;\n try {\n tokens = tokenize(selector);\n if (!(tokens[tokens.length - 1] instanceof EOFToken)) tokens.push(new EOFToken());\n } catch (e) {\n const newMessage = e.message + ` while parsing css selector "${selector}". Did you mean to CSS.escape it?`;\n const index = (e.stack || "").indexOf(e.message);\n if (index !== -1)\n e.stack = e.stack.substring(0, index) + newMessage + e.stack.substring(index + e.message.length);\n e.message = newMessage;\n throw e;\n }\n const unsupportedToken = tokens.find((token) => {\n return token instanceof AtKeywordToken || token instanceof BadStringToken || token instanceof BadURLToken || token instanceof ColumnToken || token instanceof CDOToken || token instanceof CDCToken || token instanceof SemicolonToken || // TODO: Consider using these for something, e.g. to escape complex strings.\n // For example :xpath{ (//div/bar[@attr="foo"])[2]/baz }\n // Or this way :xpath( {complex-xpath-goes-here("hello")} )\n token instanceof OpenCurlyToken || token instanceof CloseCurlyToken || // TODO: Consider treating these as strings?\n token instanceof URLToken || token instanceof PercentageToken;\n });\n if (unsupportedToken)\n throw new InvalidSelectorError(\n `Unsupported token "${unsupportedToken.toSource()}" while parsing css selector "${selector}". Did you mean to CSS.escape it?`\n );\n let pos = 0;\n const names = /* @__PURE__ */ new Set();\n function unexpected() {\n return new InvalidSelectorError(\n `Unexpected token "${tokens[pos].toSource()}" while parsing css selector "${selector}". Did you mean to CSS.escape it?`\n );\n }\n function skipWhitespace() {\n while (tokens[pos] instanceof WhitespaceToken) pos++;\n }\n function isIdent(p = pos) {\n return tokens[p] instanceof IdentToken;\n }\n function isString2(p = pos) {\n return tokens[p] instanceof StringToken;\n }\n function isNumber(p = pos) {\n return tokens[p] instanceof NumberToken;\n }\n function isComma(p = pos) {\n return tokens[p] instanceof CommaToken;\n }\n function isOpenParen(p = pos) {\n return tokens[p] instanceof OpenParenToken;\n }\n function isCloseParen(p = pos) {\n return tokens[p] instanceof CloseParenToken;\n }\n function isFunction(p = pos) {\n return tokens[p] instanceof FunctionToken;\n }\n function isStar(p = pos) {\n return tokens[p] instanceof DelimToken && tokens[p].value === "*";\n }\n function isEOF(p = pos) {\n return tokens[p] instanceof EOFToken;\n }\n function isClauseCombinator(p = pos) {\n return tokens[p] instanceof DelimToken && [">", "+", "~"].includes(tokens[p].value);\n }\n function isSelectorClauseEnd(p = pos) {\n return isComma(p) || isCloseParen(p) || isEOF(p) || isClauseCombinator(p) || tokens[p] instanceof WhitespaceToken;\n }\n function consumeFunctionArguments() {\n const result2 = [consumeArgument()];\n while (true) {\n skipWhitespace();\n if (!isComma()) break;\n pos++;\n result2.push(consumeArgument());\n }\n return result2;\n }\n function consumeArgument() {\n skipWhitespace();\n if (isNumber()) return tokens[pos++].value;\n if (isString2()) return tokens[pos++].value;\n return consumeComplexSelector();\n }\n function consumeComplexSelector() {\n const result2 = { simples: [] };\n skipWhitespace();\n if (isClauseCombinator()) {\n result2.simples.push({\n selector: { functions: [{ name: "scope", args: [] }] },\n combinator: ""\n });\n } else {\n result2.simples.push({ selector: consumeSimpleSelector(), combinator: "" });\n }\n while (true) {\n skipWhitespace();\n if (isClauseCombinator()) {\n result2.simples[result2.simples.length - 1].combinator = tokens[pos++].value;\n skipWhitespace();\n } else if (isSelectorClauseEnd()) {\n break;\n }\n result2.simples.push({ combinator: "", selector: consumeSimpleSelector() });\n }\n return result2;\n }\n function consumeSimpleSelector() {\n let rawCSSString = "";\n const functions = [];\n while (!isSelectorClauseEnd()) {\n if (isIdent() || isStar()) {\n rawCSSString += tokens[pos++].toSource();\n } else if (tokens[pos] instanceof HashToken) {\n rawCSSString += tokens[pos++].toSource();\n } else if (tokens[pos] instanceof DelimToken && tokens[pos].value === ".") {\n pos++;\n if (isIdent()) rawCSSString += "." + tokens[pos++].toSource();\n else throw unexpected();\n } else if (tokens[pos] instanceof ColonToken) {\n pos++;\n if (isIdent()) {\n if (!customNames.has(tokens[pos].value.toLowerCase())) {\n rawCSSString += ":" + tokens[pos++].toSource();\n } else {\n const name = tokens[pos++].value.toLowerCase();\n functions.push({ name, args: [] });\n names.add(name);\n }\n } else if (isFunction()) {\n const name = tokens[pos++].value.toLowerCase();\n if (!customNames.has(name)) {\n rawCSSString += `:${name}(${consumeBuiltinFunctionArguments()})`;\n } else {\n functions.push({ name, args: consumeFunctionArguments() });\n names.add(name);\n }\n skipWhitespace();\n if (!isCloseParen()) throw unexpected();\n pos++;\n } else {\n throw unexpected();\n }\n } else if (tokens[pos] instanceof OpenSquareToken) {\n rawCSSString += "[";\n pos++;\n while (!(tokens[pos] instanceof CloseSquareToken) && !isEOF())\n rawCSSString += tokens[pos++].toSource();\n if (!(tokens[pos] instanceof CloseSquareToken)) throw unexpected();\n rawCSSString += "]";\n pos++;\n } else {\n throw unexpected();\n }\n }\n if (!rawCSSString && !functions.length) throw unexpected();\n return { css: rawCSSString || void 0, functions };\n }\n function consumeBuiltinFunctionArguments() {\n let s = "";\n let balance = 1;\n while (!isEOF()) {\n if (isOpenParen() || isFunction()) balance++;\n if (isCloseParen()) balance--;\n if (!balance) break;\n s += tokens[pos++].toSource();\n }\n return s;\n }\n const result = consumeFunctionArguments();\n if (!isEOF()) throw unexpected();\n if (result.some((arg) => typeof arg !== "object" || !("simples" in arg)))\n throw new InvalidSelectorError(\n `Error while parsing css selector "${selector}". Did you mean to CSS.escape it?`\n );\n return { selector: result, names: Array.from(names) };\n }\n\n // src/sandbox/forked-client/src/utils/isomorphic/selectorParser.ts\n var kNestedSelectorNames = /* @__PURE__ */ new Set([\n "internal:has",\n "internal:has-not",\n "internal:and",\n "internal:or",\n "internal:chain",\n "left-of",\n "right-of",\n "above",\n "below",\n "near"\n ]);\n var kNestedSelectorNamesWithDistance = /* @__PURE__ */ new Set(["left-of", "right-of", "above", "below", "near"]);\n var customCSSNames = /* @__PURE__ */ new Set([\n "not",\n "is",\n "where",\n "has",\n "scope",\n "light",\n "visible",\n "text",\n "text-matches",\n "text-is",\n "has-text",\n "above",\n "below",\n "right-of",\n "left-of",\n "near",\n "nth-match"\n ]);\n function parseSelector(selector) {\n const parsedStrings = parseSelectorString(selector);\n const parts = [];\n for (const part of parsedStrings.parts) {\n if (part.name === "css" || part.name === "css:light") {\n if (part.name === "css:light") part.body = ":light(" + part.body + ")";\n const parsedCSS = parseCSS(part.body, customCSSNames);\n parts.push({\n name: "css",\n body: parsedCSS.selector,\n source: part.body\n });\n continue;\n }\n if (kNestedSelectorNames.has(part.name)) {\n let innerSelector;\n let distance;\n try {\n const unescaped = JSON.parse("[" + part.body + "]");\n if (!Array.isArray(unescaped) || unescaped.length < 1 || unescaped.length > 2 || typeof unescaped[0] !== "string")\n throw new InvalidSelectorError(`Malformed selector: ${part.name}=` + part.body);\n innerSelector = unescaped[0];\n if (unescaped.length === 2) {\n if (typeof unescaped[1] !== "number" || !kNestedSelectorNamesWithDistance.has(part.name))\n throw new InvalidSelectorError(`Malformed selector: ${part.name}=` + part.body);\n distance = unescaped[1];\n }\n } catch (e) {\n throw new InvalidSelectorError(`Malformed selector: ${part.name}=` + part.body);\n }\n const nested = {\n name: part.name,\n source: part.body,\n body: { parsed: parseSelector(innerSelector), distance }\n };\n const lastFrame = [...nested.body.parsed.parts].reverse().find((part2) => part2.name === "internal:control" && part2.body === "enter-frame");\n const lastFrameIndex = lastFrame ? nested.body.parsed.parts.indexOf(lastFrame) : -1;\n if (lastFrameIndex !== -1 && selectorPartsEqual(\n nested.body.parsed.parts.slice(0, lastFrameIndex + 1),\n parts.slice(0, lastFrameIndex + 1)\n ))\n nested.body.parsed.parts.splice(0, lastFrameIndex + 1);\n parts.push(nested);\n continue;\n }\n parts.push({ ...part, source: part.body });\n }\n if (kNestedSelectorNames.has(parts[0].name))\n throw new InvalidSelectorError(`"${parts[0].name}" selector cannot be first`);\n return {\n capture: parsedStrings.capture,\n parts\n };\n }\n function selectorPartsEqual(list1, list2) {\n return stringifySelector({ parts: list1 }) === stringifySelector({ parts: list2 });\n }\n function stringifySelector(selector, forceEngineName) {\n if (typeof selector === "string") return selector;\n return selector.parts.map((p, i) => {\n let includeEngine = true;\n if (!forceEngineName && i !== selector.capture) {\n if (p.name === "css") includeEngine = false;\n else if (p.name === "xpath" && p.source.startsWith("//") || p.source.startsWith(".."))\n includeEngine = false;\n }\n const prefix = includeEngine ? p.name + "=" : "";\n return `${i === selector.capture ? "*" : ""}${prefix}${p.source}`;\n }).join(" >> ");\n }\n function parseSelectorString(selector) {\n let index = 0;\n let quote;\n let start = 0;\n const result = { parts: [] };\n const append = () => {\n const part = selector.substring(start, index).trim();\n const eqIndex = part.indexOf("=");\n let name;\n let body;\n if (eqIndex !== -1 && part.substring(0, eqIndex).trim().match(/^[a-zA-Z_0-9-+:*]+$/)) {\n name = part.substring(0, eqIndex).trim();\n body = part.substring(eqIndex + 1);\n } else if (part.length > 1 && part[0] === \'"\' && part[part.length - 1] === \'"\') {\n name = "text";\n body = part;\n } else if (part.length > 1 && part[0] === "\'" && part[part.length - 1] === "\'") {\n name = "text";\n body = part;\n } else if (/^\\(*\\/\\//.test(part) || part.startsWith("..")) {\n name = "xpath";\n body = part;\n } else {\n name = "css";\n body = part;\n }\n let capture = false;\n if (name[0] === "*") {\n capture = true;\n name = name.substring(1);\n }\n result.parts.push({ name, body });\n if (capture) {\n if (result.capture !== void 0)\n throw new InvalidSelectorError(`Only one of the selectors can capture using * modifier`);\n result.capture = result.parts.length - 1;\n }\n };\n if (!selector.includes(">>")) {\n index = selector.length;\n append();\n return result;\n }\n const shouldIgnoreTextSelectorQuote = () => {\n const prefix = selector.substring(start, index);\n const match = prefix.match(/^\\s*text\\s*=(.*)$/);\n return !!match && !!match[1];\n };\n while (index < selector.length) {\n const c = selector[index];\n if (c === "\\\\" && index + 1 < selector.length) {\n index += 2;\n } else if (c === quote) {\n quote = void 0;\n index++;\n } else if (!quote && (c === \'"\' || c === "\'" || c === "`") && !shouldIgnoreTextSelectorQuote()) {\n quote = c;\n index++;\n } else if (!quote && c === ">" && selector[index + 1] === ">") {\n append();\n index += 2;\n start = index;\n } else {\n index++;\n }\n }\n append();\n return result;\n }\n function parseAttributeSelector(selector, allowUnquotedStrings) {\n let wp = 0;\n let EOL = selector.length === 0;\n const next = () => selector[wp] || "";\n const eat1 = () => {\n const result2 = next();\n ++wp;\n EOL = wp >= selector.length;\n return result2;\n };\n const syntaxError = (stage) => {\n if (EOL)\n throw new InvalidSelectorError(\n `Unexpected end of selector while parsing selector \\`${selector}\\``\n );\n throw new InvalidSelectorError(\n `Error while parsing selector \\`${selector}\\` - unexpected symbol "${next()}" at position ${wp}` + (stage ? " during " + stage : "")\n );\n };\n function skipSpaces() {\n while (!EOL && /\\s/.test(next())) eat1();\n }\n function isCSSNameChar(char) {\n return char >= "\\x80" || // non-ascii\n char >= "0" && char <= "9" || // digit\n char >= "A" && char <= "Z" || // uppercase letter\n char >= "a" && char <= "z" || // lowercase letter\n char >= "0" && char <= "9" || // digit\n char === "_" || // "_"\n char === "-";\n }\n function readIdentifier() {\n let result2 = "";\n skipSpaces();\n while (!EOL && isCSSNameChar(next())) result2 += eat1();\n return result2;\n }\n function readQuotedString(quote) {\n let result2 = eat1();\n if (result2 !== quote) syntaxError("parsing quoted string");\n while (!EOL && next() !== quote) {\n if (next() === "\\\\") eat1();\n result2 += eat1();\n }\n if (next() !== quote) syntaxError("parsing quoted string");\n result2 += eat1();\n return result2;\n }\n function readRegularExpression() {\n if (eat1() !== "/") syntaxError("parsing regular expression");\n let source = "";\n let inClass = false;\n while (!EOL) {\n if (next() === "\\\\") {\n source += eat1();\n if (EOL) syntaxError("parsing regular expression");\n } else if (inClass && next() === "]") {\n inClass = false;\n } else if (!inClass && next() === "[") {\n inClass = true;\n } else if (!inClass && next() === "/") {\n break;\n }\n source += eat1();\n }\n if (eat1() !== "/") syntaxError("parsing regular expression");\n let flags = "";\n while (!EOL && next().match(/[dgimsuy]/)) flags += eat1();\n try {\n return new RegExp(source, flags);\n } catch (e) {\n throw new InvalidSelectorError(`Error while parsing selector \\`${selector}\\`: ${e.message}`);\n }\n }\n function readAttributeToken() {\n let token = "";\n skipSpaces();\n if (next() === `\'` || next() === `"`) token = readQuotedString(next()).slice(1, -1);\n else token = readIdentifier();\n if (!token) syntaxError("parsing property path");\n return token;\n }\n function readOperator() {\n skipSpaces();\n let op = "";\n if (!EOL) op += eat1();\n if (!EOL && op !== "=") op += eat1();\n if (!["=", "*=", "^=", "$=", "|=", "~="].includes(op)) syntaxError("parsing operator");\n return op;\n }\n function readAttribute() {\n eat1();\n const jsonPath = [];\n jsonPath.push(readAttributeToken());\n skipSpaces();\n while (next() === ".") {\n eat1();\n jsonPath.push(readAttributeToken());\n skipSpaces();\n }\n if (next() === "]") {\n eat1();\n return {\n name: jsonPath.join("."),\n jsonPath,\n op: "<truthy>",\n value: null,\n caseSensitive: false\n };\n }\n const operator = readOperator();\n let value = void 0;\n let caseSensitive = true;\n skipSpaces();\n if (next() === "/") {\n if (operator !== "=")\n throw new InvalidSelectorError(\n `Error while parsing selector \\`${selector}\\` - cannot use ${operator} in attribute with regular expression`\n );\n value = readRegularExpression();\n } else if (next() === `\'` || next() === `"`) {\n value = readQuotedString(next()).slice(1, -1);\n skipSpaces();\n if (next() === "i" || next() === "I") {\n caseSensitive = false;\n eat1();\n } else if (next() === "s" || next() === "S") {\n caseSensitive = true;\n eat1();\n }\n } else {\n value = "";\n while (!EOL && (isCSSNameChar(next()) || next() === "+" || next() === ".")) value += eat1();\n if (value === "true") {\n value = true;\n } else if (value === "false") {\n value = false;\n } else {\n if (!allowUnquotedStrings) {\n value = +value;\n if (Number.isNaN(value)) syntaxError("parsing attribute value");\n }\n }\n }\n skipSpaces();\n if (next() !== "]") syntaxError("parsing attribute value");\n eat1();\n if (operator !== "=" && typeof value !== "string")\n throw new InvalidSelectorError(\n `Error while parsing selector \\`${selector}\\` - cannot use ${operator} in attribute with non-string matching value - ${value}`\n );\n return { name: jsonPath.join("."), jsonPath, op: operator, value, caseSensitive };\n }\n const result = {\n name: "",\n attributes: []\n };\n result.name = readIdentifier();\n skipSpaces();\n while (next() === "[") {\n result.attributes.push(readAttribute());\n skipSpaces();\n }\n if (!EOL) syntaxError(void 0);\n if (!result.name && !result.attributes.length)\n throw new InvalidSelectorError(\n `Error while parsing selector \\`${selector}\\` - selector cannot be empty`\n );\n return result;\n }\n\n // src/sandbox/forked-client/src/utils/isomorphic/locatorGenerators.ts\n function asLocatorDescription(lang, selector) {\n try {\n const parsed = parseSelector(selector);\n const customDescription = parseCustomDescription(parsed);\n if (customDescription) return customDescription;\n return innerAsLocators(new generators[lang](), parsed, false, 1)[0];\n } catch (e) {\n return selector;\n }\n }\n function locatorCustomDescription(selector) {\n try {\n const parsed = parseSelector(selector);\n return parseCustomDescription(parsed);\n } catch (e) {\n return void 0;\n }\n }\n function parseCustomDescription(parsed) {\n const lastPart = parsed.parts[parsed.parts.length - 1];\n if (lastPart?.name === "internal:describe") {\n const description = JSON.parse(lastPart.body);\n if (typeof description === "string") return description;\n }\n return void 0;\n }\n function innerAsLocators(factory, parsed, isFrameLocator = false, maxOutputSize = 20) {\n const parts = [...parsed.parts];\n const tokens = [];\n let nextBase = isFrameLocator ? "frame-locator" : "page";\n for (let index = 0; index < parts.length; index++) {\n const part = parts[index];\n const base = nextBase;\n nextBase = "locator";\n if (part.name === "internal:describe") continue;\n if (part.name === "nth") {\n if (part.body === "0")\n tokens.push([\n factory.generateLocator(base, "first", ""),\n factory.generateLocator(base, "nth", "0")\n ]);\n else if (part.body === "-1")\n tokens.push([\n factory.generateLocator(base, "last", ""),\n factory.generateLocator(base, "nth", "-1")\n ]);\n else tokens.push([factory.generateLocator(base, "nth", part.body)]);\n continue;\n }\n if (part.name === "visible") {\n tokens.push([\n factory.generateLocator(base, "visible", part.body),\n factory.generateLocator(base, "default", `visible=${part.body}`)\n ]);\n continue;\n }\n if (part.name === "internal:text") {\n const { exact, text } = detectExact(part.body);\n tokens.push([factory.generateLocator(base, "text", text, { exact })]);\n continue;\n }\n if (part.name === "internal:has-text") {\n const { exact, text } = detectExact(part.body);\n if (!exact) {\n tokens.push([factory.generateLocator(base, "has-text", text, { exact })]);\n continue;\n }\n }\n if (part.name === "internal:has-not-text") {\n const { exact, text } = detectExact(part.body);\n if (!exact) {\n tokens.push([factory.generateLocator(base, "has-not-text", text, { exact })]);\n continue;\n }\n }\n if (part.name === "internal:has") {\n const inners = innerAsLocators(\n factory,\n part.body.parsed,\n false,\n maxOutputSize\n );\n tokens.push(inners.map((inner) => factory.generateLocator(base, "has", inner)));\n continue;\n }\n if (part.name === "internal:has-not") {\n const inners = innerAsLocators(\n factory,\n part.body.parsed,\n false,\n maxOutputSize\n );\n tokens.push(inners.map((inner) => factory.generateLocator(base, "hasNot", inner)));\n continue;\n }\n if (part.name === "internal:and") {\n const inners = innerAsLocators(\n factory,\n part.body.parsed,\n false,\n maxOutputSize\n );\n tokens.push(inners.map((inner) => factory.generateLocator(base, "and", inner)));\n continue;\n }\n if (part.name === "internal:or") {\n const inners = innerAsLocators(\n factory,\n part.body.parsed,\n false,\n maxOutputSize\n );\n tokens.push(inners.map((inner) => factory.generateLocator(base, "or", inner)));\n continue;\n }\n if (part.name === "internal:chain") {\n const inners = innerAsLocators(\n factory,\n part.body.parsed,\n false,\n maxOutputSize\n );\n tokens.push(inners.map((inner) => factory.generateLocator(base, "chain", inner)));\n continue;\n }\n if (part.name === "internal:label") {\n const { exact, text } = detectExact(part.body);\n tokens.push([factory.generateLocator(base, "label", text, { exact })]);\n continue;\n }\n if (part.name === "internal:role") {\n const attrSelector = parseAttributeSelector(part.body, true);\n const options = { attrs: [] };\n for (const attr of attrSelector.attributes) {\n if (attr.name === "name") {\n options.exact = attr.caseSensitive;\n options.name = attr.value;\n } else {\n if (attr.name === "level" && typeof attr.value === "string") attr.value = +attr.value;\n options.attrs.push({\n name: attr.name === "include-hidden" ? "includeHidden" : attr.name,\n value: attr.value\n });\n }\n }\n tokens.push([factory.generateLocator(base, "role", attrSelector.name, options)]);\n continue;\n }\n if (part.name === "internal:testid") {\n const attrSelector = parseAttributeSelector(part.body, true);\n const { value } = attrSelector.attributes[0];\n tokens.push([factory.generateLocator(base, "test-id", value)]);\n continue;\n }\n if (part.name === "internal:attr") {\n const attrSelector = parseAttributeSelector(part.body, true);\n const { name, value, caseSensitive } = attrSelector.attributes[0];\n const text = value;\n const exact = !!caseSensitive;\n if (name === "placeholder") {\n tokens.push([factory.generateLocator(base, "placeholder", text, { exact })]);\n continue;\n }\n if (name === "alt") {\n tokens.push([factory.generateLocator(base, "alt", text, { exact })]);\n continue;\n }\n if (name === "title") {\n tokens.push([factory.generateLocator(base, "title", text, { exact })]);\n continue;\n }\n }\n if (part.name === "internal:control" && part.body === "enter-frame") {\n const lastTokens = tokens[tokens.length - 1];\n const lastPart = parts[index - 1];\n const transformed = lastTokens.map(\n (token) => factory.chainLocators([token, factory.generateLocator(base, "frame", "")])\n );\n if (["xpath", "css"].includes(lastPart.name)) {\n transformed.push(\n factory.generateLocator(base, "frame-locator", stringifySelector({ parts: [lastPart] })),\n factory.generateLocator(\n base,\n "frame-locator",\n stringifySelector({ parts: [lastPart] }, true)\n )\n );\n }\n lastTokens.splice(0, lastTokens.length, ...transformed);\n nextBase = "frame-locator";\n continue;\n }\n const nextPart = parts[index + 1];\n const selectorPart = stringifySelector({ parts: [part] });\n const locatorPart = factory.generateLocator(base, "default", selectorPart);\n if (nextPart && ["internal:has-text", "internal:has-not-text"].includes(nextPart.name)) {\n const { exact, text } = detectExact(nextPart.body);\n if (!exact) {\n const nextLocatorPart = factory.generateLocator(\n "locator",\n nextPart.name === "internal:has-text" ? "has-text" : "has-not-text",\n text,\n { exact }\n );\n const options = {};\n if (nextPart.name === "internal:has-text") options.hasText = text;\n else options.hasNotText = text;\n const combinedPart = factory.generateLocator(base, "default", selectorPart, options);\n tokens.push([factory.chainLocators([locatorPart, nextLocatorPart]), combinedPart]);\n index++;\n continue;\n }\n }\n let locatorPartWithEngine;\n if (["xpath", "css"].includes(part.name)) {\n const selectorPart2 = stringifySelector(\n { parts: [part] },\n /* forceEngineName */\n true\n );\n locatorPartWithEngine = factory.generateLocator(base, "default", selectorPart2);\n }\n tokens.push([locatorPart, locatorPartWithEngine].filter(Boolean));\n }\n return combineTokens(factory, tokens, maxOutputSize);\n }\n function combineTokens(factory, tokens, maxOutputSize) {\n const currentTokens = tokens.map(() => "");\n const result = [];\n const visit = (index) => {\n if (index === tokens.length) {\n result.push(factory.chainLocators(currentTokens));\n return result.length < maxOutputSize;\n }\n for (const taken of tokens[index]) {\n currentTokens[index] = taken;\n if (!visit(index + 1)) return false;\n }\n return true;\n };\n visit(0);\n return result;\n }\n function detectExact(text) {\n let exact = false;\n const match = text.match(/^\\/(.*)\\/([igm]*)$/);\n if (match) return { text: new RegExp(match[1], match[2]) };\n if (text.endsWith(\'"\')) {\n text = JSON.parse(text);\n exact = true;\n } else if (text.endsWith(\'"s\')) {\n text = JSON.parse(text.substring(0, text.length - 1));\n exact = true;\n } else if (text.endsWith(\'"i\')) {\n text = JSON.parse(text.substring(0, text.length - 1));\n exact = false;\n }\n return { exact, text };\n }\n var JavaScriptLocatorFactory = class {\n constructor(preferredQuote) {\n this.preferredQuote = preferredQuote;\n }\n preferredQuote;\n generateLocator(base, kind, body, options = {}) {\n switch (kind) {\n case "default":\n if (options.hasText !== void 0)\n return `locator(${this.quote(body)}, { hasText: ${this.toHasText(options.hasText)} })`;\n if (options.hasNotText !== void 0)\n return `locator(${this.quote(body)}, { hasNotText: ${this.toHasText(options.hasNotText)} })`;\n return `locator(${this.quote(body)})`;\n case "frame-locator":\n return `frameLocator(${this.quote(body)})`;\n case "frame":\n return `contentFrame()`;\n case "nth":\n return `nth(${body})`;\n case "first":\n return `first()`;\n case "last":\n return `last()`;\n case "visible":\n return `filter({ visible: ${body === "true" ? "true" : "false"} })`;\n case "role":\n const attrs = [];\n if (isRegExp3(options.name)) {\n attrs.push(`name: ${this.regexToSourceString(options.name)}`);\n } else if (typeof options.name === "string") {\n attrs.push(`name: ${this.quote(options.name)}`);\n if (options.exact) attrs.push(`exact: true`);\n }\n for (const { name, value } of options.attrs)\n attrs.push(`${name}: ${typeof value === "string" ? this.quote(value) : value}`);\n const attrString = attrs.length ? `, { ${attrs.join(", ")} }` : "";\n return `getByRole(${this.quote(body)}${attrString})`;\n case "has-text":\n return `filter({ hasText: ${this.toHasText(body)} })`;\n case "has-not-text":\n return `filter({ hasNotText: ${this.toHasText(body)} })`;\n case "has":\n return `filter({ has: ${body} })`;\n case "hasNot":\n return `filter({ hasNot: ${body} })`;\n case "and":\n return `and(${body})`;\n case "or":\n return `or(${body})`;\n case "chain":\n return `locator(${body})`;\n case "test-id":\n return `getByTestId(${this.toTestIdValue(body)})`;\n case "text":\n return this.toCallWithExact("getByText", body, !!options.exact);\n case "alt":\n return this.toCallWithExact("getByAltText", body, !!options.exact);\n case "placeholder":\n return this.toCallWithExact("getByPlaceholder", body, !!options.exact);\n case "label":\n return this.toCallWithExact("getByLabel", body, !!options.exact);\n case "title":\n return this.toCallWithExact("getByTitle", body, !!options.exact);\n default:\n throw new Error("Unknown selector kind " + kind);\n }\n }\n chainLocators(locators) {\n return locators.join(".");\n }\n regexToSourceString(re2) {\n return normalizeEscapedRegexQuotes(String(re2));\n }\n toCallWithExact(method, body, exact) {\n if (isRegExp3(body)) return `${method}(${this.regexToSourceString(body)})`;\n return exact ? `${method}(${this.quote(body)}, { exact: true })` : `${method}(${this.quote(body)})`;\n }\n toHasText(body) {\n if (isRegExp3(body)) return this.regexToSourceString(body);\n return this.quote(body);\n }\n toTestIdValue(value) {\n if (isRegExp3(value)) return this.regexToSourceString(value);\n return this.quote(value);\n }\n quote(text) {\n return escapeWithQuotes(text, this.preferredQuote ?? "\'");\n }\n };\n var PythonLocatorFactory = class {\n generateLocator(base, kind, body, options = {}) {\n switch (kind) {\n case "default":\n if (options.hasText !== void 0)\n return `locator(${this.quote(body)}, has_text=${this.toHasText(options.hasText)})`;\n if (options.hasNotText !== void 0)\n return `locator(${this.quote(body)}, has_not_text=${this.toHasText(options.hasNotText)})`;\n return `locator(${this.quote(body)})`;\n case "frame-locator":\n return `frame_locator(${this.quote(body)})`;\n case "frame":\n return `content_frame`;\n case "nth":\n return `nth(${body})`;\n case "first":\n return `first`;\n case "last":\n return `last`;\n case "visible":\n return `filter(visible=${body === "true" ? "True" : "False"})`;\n case "role":\n const attrs = [];\n if (isRegExp3(options.name)) {\n attrs.push(`name=${this.regexToString(options.name)}`);\n } else if (typeof options.name === "string") {\n attrs.push(`name=${this.quote(options.name)}`);\n if (options.exact) attrs.push(`exact=True`);\n }\n for (const { name, value } of options.attrs) {\n let valueString = typeof value === "string" ? this.quote(value) : value;\n if (typeof value === "boolean") valueString = value ? "True" : "False";\n attrs.push(`${toSnakeCase(name)}=${valueString}`);\n }\n const attrString = attrs.length ? `, ${attrs.join(", ")}` : "";\n return `get_by_role(${this.quote(body)}${attrString})`;\n case "has-text":\n return `filter(has_text=${this.toHasText(body)})`;\n case "has-not-text":\n return `filter(has_not_text=${this.toHasText(body)})`;\n case "has":\n return `filter(has=${body})`;\n case "hasNot":\n return `filter(has_not=${body})`;\n case "and":\n return `and_(${body})`;\n case "or":\n return `or_(${body})`;\n case "chain":\n return `locator(${body})`;\n case "test-id":\n return `get_by_test_id(${this.toTestIdValue(body)})`;\n case "text":\n return this.toCallWithExact("get_by_text", body, !!options.exact);\n case "alt":\n return this.toCallWithExact("get_by_alt_text", body, !!options.exact);\n case "placeholder":\n return this.toCallWithExact("get_by_placeholder", body, !!options.exact);\n case "label":\n return this.toCallWithExact("get_by_label", body, !!options.exact);\n case "title":\n return this.toCallWithExact("get_by_title", body, !!options.exact);\n default:\n throw new Error("Unknown selector kind " + kind);\n }\n }\n chainLocators(locators) {\n return locators.join(".");\n }\n regexToString(body) {\n const suffix = body.flags.includes("i") ? ", re.IGNORECASE" : "";\n return `re.compile(r"${normalizeEscapedRegexQuotes(body.source).replace(/\\\\\\//, "/").replace(/"/g, \'\\\\"\')}"${suffix})`;\n }\n toCallWithExact(method, body, exact) {\n if (isRegExp3(body)) return `${method}(${this.regexToString(body)})`;\n if (exact) return `${method}(${this.quote(body)}, exact=True)`;\n return `${method}(${this.quote(body)})`;\n }\n toHasText(body) {\n if (isRegExp3(body)) return this.regexToString(body);\n return `${this.quote(body)}`;\n }\n toTestIdValue(value) {\n if (isRegExp3(value)) return this.regexToString(value);\n return this.quote(value);\n }\n quote(text) {\n return escapeWithQuotes(text, \'"\');\n }\n };\n var JavaLocatorFactory = class {\n generateLocator(base, kind, body, options = {}) {\n let clazz;\n switch (base) {\n case "page":\n clazz = "Page";\n break;\n case "frame-locator":\n clazz = "FrameLocator";\n break;\n case "locator":\n clazz = "Locator";\n break;\n }\n switch (kind) {\n case "default":\n if (options.hasText !== void 0)\n return `locator(${this.quote(body)}, new ${clazz}.LocatorOptions().setHasText(${this.toHasText(options.hasText)}))`;\n if (options.hasNotText !== void 0)\n return `locator(${this.quote(body)}, new ${clazz}.LocatorOptions().setHasNotText(${this.toHasText(options.hasNotText)}))`;\n return `locator(${this.quote(body)})`;\n case "frame-locator":\n return `frameLocator(${this.quote(body)})`;\n case "frame":\n return `contentFrame()`;\n case "nth":\n return `nth(${body})`;\n case "first":\n return `first()`;\n case "last":\n return `last()`;\n case "visible":\n return `filter(new ${clazz}.FilterOptions().setVisible(${body === "true" ? "true" : "false"}))`;\n case "role":\n const attrs = [];\n if (isRegExp3(options.name)) {\n attrs.push(`.setName(${this.regexToString(options.name)})`);\n } else if (typeof options.name === "string") {\n attrs.push(`.setName(${this.quote(options.name)})`);\n if (options.exact) attrs.push(`.setExact(true)`);\n }\n for (const { name, value } of options.attrs)\n attrs.push(\n `.set${toTitleCase(name)}(${typeof value === "string" ? this.quote(value) : value})`\n );\n const attrString = attrs.length ? `, new ${clazz}.GetByRoleOptions()${attrs.join("")}` : "";\n return `getByRole(AriaRole.${toSnakeCase(body).toUpperCase()}${attrString})`;\n case "has-text":\n return `filter(new ${clazz}.FilterOptions().setHasText(${this.toHasText(body)}))`;\n case "has-not-text":\n return `filter(new ${clazz}.FilterOptions().setHasNotText(${this.toHasText(body)}))`;\n case "has":\n return `filter(new ${clazz}.FilterOptions().setHas(${body}))`;\n case "hasNot":\n return `filter(new ${clazz}.FilterOptions().setHasNot(${body}))`;\n case "and":\n return `and(${body})`;\n case "or":\n return `or(${body})`;\n case "chain":\n return `locator(${body})`;\n case "test-id":\n return `getByTestId(${this.toTestIdValue(body)})`;\n case "text":\n return this.toCallWithExact(clazz, "getByText", body, !!options.exact);\n case "alt":\n return this.toCallWithExact(clazz, "getByAltText", body, !!options.exact);\n case "placeholder":\n return this.toCallWithExact(clazz, "getByPlaceholder", body, !!options.exact);\n case "label":\n return this.toCallWithExact(clazz, "getByLabel", body, !!options.exact);\n case "title":\n return this.toCallWithExact(clazz, "getByTitle", body, !!options.exact);\n default:\n throw new Error("Unknown selector kind " + kind);\n }\n }\n chainLocators(locators) {\n return locators.join(".");\n }\n regexToString(body) {\n const suffix = body.flags.includes("i") ? ", Pattern.CASE_INSENSITIVE" : "";\n return `Pattern.compile(${this.quote(normalizeEscapedRegexQuotes(body.source))}${suffix})`;\n }\n toCallWithExact(clazz, method, body, exact) {\n if (isRegExp3(body)) return `${method}(${this.regexToString(body)})`;\n if (exact)\n return `${method}(${this.quote(body)}, new ${clazz}.${toTitleCase(method)}Options().setExact(true))`;\n return `${method}(${this.quote(body)})`;\n }\n toHasText(body) {\n if (isRegExp3(body)) return this.regexToString(body);\n return this.quote(body);\n }\n toTestIdValue(value) {\n if (isRegExp3(value)) return this.regexToString(value);\n return this.quote(value);\n }\n quote(text) {\n return escapeWithQuotes(text, \'"\');\n }\n };\n var CSharpLocatorFactory = class {\n generateLocator(base, kind, body, options = {}) {\n switch (kind) {\n case "default":\n if (options.hasText !== void 0)\n return `Locator(${this.quote(body)}, new() { ${this.toHasText(options.hasText)} })`;\n if (options.hasNotText !== void 0)\n return `Locator(${this.quote(body)}, new() { ${this.toHasNotText(options.hasNotText)} })`;\n return `Locator(${this.quote(body)})`;\n case "frame-locator":\n return `FrameLocator(${this.quote(body)})`;\n case "frame":\n return `ContentFrame`;\n case "nth":\n return `Nth(${body})`;\n case "first":\n return `First`;\n case "last":\n return `Last`;\n case "visible":\n return `Filter(new() { Visible = ${body === "true" ? "true" : "false"} })`;\n case "role":\n const attrs = [];\n if (isRegExp3(options.name)) {\n attrs.push(`NameRegex = ${this.regexToString(options.name)}`);\n } else if (typeof options.name === "string") {\n attrs.push(`Name = ${this.quote(options.name)}`);\n if (options.exact) attrs.push(`Exact = true`);\n }\n for (const { name, value } of options.attrs)\n attrs.push(\n `${toTitleCase(name)} = ${typeof value === "string" ? this.quote(value) : value}`\n );\n const attrString = attrs.length ? `, new() { ${attrs.join(", ")} }` : "";\n return `GetByRole(AriaRole.${toTitleCase(body)}${attrString})`;\n case "has-text":\n return `Filter(new() { ${this.toHasText(body)} })`;\n case "has-not-text":\n return `Filter(new() { ${this.toHasNotText(body)} })`;\n case "has":\n return `Filter(new() { Has = ${body} })`;\n case "hasNot":\n return `Filter(new() { HasNot = ${body} })`;\n case "and":\n return `And(${body})`;\n case "or":\n return `Or(${body})`;\n case "chain":\n return `Locator(${body})`;\n case "test-id":\n return `GetByTestId(${this.toTestIdValue(body)})`;\n case "text":\n return this.toCallWithExact("GetByText", body, !!options.exact);\n case "alt":\n return this.toCallWithExact("GetByAltText", body, !!options.exact);\n case "placeholder":\n return this.toCallWithExact("GetByPlaceholder", body, !!options.exact);\n case "label":\n return this.toCallWithExact("GetByLabel", body, !!options.exact);\n case "title":\n return this.toCallWithExact("GetByTitle", body, !!options.exact);\n default:\n throw new Error("Unknown selector kind " + kind);\n }\n }\n chainLocators(locators) {\n return locators.join(".");\n }\n regexToString(body) {\n const suffix = body.flags.includes("i") ? ", RegexOptions.IgnoreCase" : "";\n return `new Regex(${this.quote(normalizeEscapedRegexQuotes(body.source))}${suffix})`;\n }\n toCallWithExact(method, body, exact) {\n if (isRegExp3(body)) return `${method}(${this.regexToString(body)})`;\n if (exact) return `${method}(${this.quote(body)}, new() { Exact = true })`;\n return `${method}(${this.quote(body)})`;\n }\n toHasText(body) {\n if (isRegExp3(body)) return `HasTextRegex = ${this.regexToString(body)}`;\n return `HasText = ${this.quote(body)}`;\n }\n toTestIdValue(value) {\n if (isRegExp3(value)) return this.regexToString(value);\n return this.quote(value);\n }\n toHasNotText(body) {\n if (isRegExp3(body)) return `HasNotTextRegex = ${this.regexToString(body)}`;\n return `HasNotText = ${this.quote(body)}`;\n }\n quote(text) {\n return escapeWithQuotes(text, \'"\');\n }\n };\n var JsonlLocatorFactory = class {\n generateLocator(base, kind, body, options = {}) {\n return JSON.stringify({\n kind,\n body,\n options\n });\n }\n chainLocators(locators) {\n const objects = locators.map((l) => JSON.parse(l));\n for (let i = 0; i < objects.length - 1; ++i) objects[i].next = objects[i + 1];\n return JSON.stringify(objects[0]);\n }\n };\n var generators = {\n javascript: JavaScriptLocatorFactory,\n python: PythonLocatorFactory,\n java: JavaLocatorFactory,\n csharp: CSharpLocatorFactory,\n jsonl: JsonlLocatorFactory\n };\n function isRegExp3(obj) {\n return obj instanceof RegExp;\n }\n\n // src/sandbox/forked-client/src/utils/isomorphic/locatorUtils.ts\n function getByAttributeTextSelector(attrName, text, options) {\n return `internal:attr=[${attrName}=${escapeForAttributeSelector(text, options?.exact || false)}]`;\n }\n function getByTestIdSelector(testIdAttributeName2, testId) {\n return `internal:testid=[${testIdAttributeName2}=${escapeForAttributeSelector(testId, true)}]`;\n }\n function getByLabelSelector(text, options) {\n return "internal:label=" + escapeForTextSelector(text, !!options?.exact);\n }\n function getByAltTextSelector(text, options) {\n return getByAttributeTextSelector("alt", text, options);\n }\n function getByTitleSelector(text, options) {\n return getByAttributeTextSelector("title", text, options);\n }\n function getByPlaceholderSelector(text, options) {\n return getByAttributeTextSelector("placeholder", text, options);\n }\n function getByTextSelector(text, options) {\n return "internal:text=" + escapeForTextSelector(text, !!options?.exact);\n }\n function getByRoleSelector(role, options = {}) {\n const props = [];\n if (options.checked !== void 0) props.push(["checked", String(options.checked)]);\n if (options.disabled !== void 0) props.push(["disabled", String(options.disabled)]);\n if (options.selected !== void 0) props.push(["selected", String(options.selected)]);\n if (options.expanded !== void 0) props.push(["expanded", String(options.expanded)]);\n if (options.includeHidden !== void 0)\n props.push(["include-hidden", String(options.includeHidden)]);\n if (options.level !== void 0) props.push(["level", String(options.level)]);\n if (options.name !== void 0)\n props.push(["name", escapeForAttributeSelector(options.name, !!options.exact)]);\n if (options.pressed !== void 0) props.push(["pressed", String(options.pressed)]);\n return `internal:role=${role}${props.map(([n, v]) => `[${n}=${v}]`).join("")}`;\n }\n\n // src/sandbox/forked-client/src/utils/isomorphic/time.ts\n var fallbackTimeOrigin = Date.now();\n var performanceApi = globalThis.performance ?? {\n timeOrigin: fallbackTimeOrigin,\n now: () => Date.now() - fallbackTimeOrigin\n };\n var _timeOrigin = performanceApi.timeOrigin;\n var _timeShift = 0;\n function monotonicTime() {\n return Math.floor((performanceApi.now() + _timeShift) * 1e3) / 1e3;\n }\n var DEFAULT_PLAYWRIGHT_TIMEOUT = 3e4;\n var DEFAULT_PLAYWRIGHT_LAUNCH_TIMEOUT = 3 * 60 * 1e3;\n\n // src/sandbox/forked-client/src/client/locator.ts\n var Locator = class _Locator {\n _frame;\n _selector;\n constructor(frame, selector, options) {\n this._frame = frame;\n this._selector = selector;\n if (options?.hasText)\n this._selector += ` >> internal:has-text=${escapeForTextSelector(options.hasText, false)}`;\n if (options?.hasNotText)\n this._selector += ` >> internal:has-not-text=${escapeForTextSelector(options.hasNotText, false)}`;\n if (options?.has) {\n const locator = options.has;\n if (locator._frame !== frame)\n throw new Error(`Inner "has" locator must belong to the same frame.`);\n this._selector += ` >> internal:has=` + JSON.stringify(locator._selector);\n }\n if (options?.hasNot) {\n const locator = options.hasNot;\n if (locator._frame !== frame)\n throw new Error(`Inner "hasNot" locator must belong to the same frame.`);\n this._selector += ` >> internal:has-not=` + JSON.stringify(locator._selector);\n }\n if (options?.visible !== void 0)\n this._selector += ` >> visible=${options.visible ? "true" : "false"}`;\n if (this._frame._platform.inspectCustom)\n this[this._frame._platform.inspectCustom] = () => this._inspect();\n }\n async _withElement(task, options) {\n const timeout = this._frame._timeout({ timeout: options.timeout });\n const deadline = timeout ? monotonicTime() + timeout : 0;\n return await this._frame._wrapApiCall(\n async () => {\n const result = await this._frame._channel.waitForSelector({\n selector: this._selector,\n strict: true,\n state: "attached",\n timeout\n });\n const handle = ElementHandle.fromNullable(result.element);\n if (!handle) throw new Error(`Could not resolve ${this._selector} to DOM Element`);\n try {\n return await task(handle, deadline ? deadline - monotonicTime() : 0);\n } finally {\n await handle.dispose();\n }\n },\n { title: options.title, internal: options.internal }\n );\n }\n _equals(locator) {\n return this._frame === locator._frame && this._selector === locator._selector;\n }\n page() {\n return this._frame.page();\n }\n async boundingBox(options) {\n return await this._withElement((h) => h.boundingBox(), {\n title: "Bounding box",\n timeout: options?.timeout\n });\n }\n async check(options = {}) {\n return await this._frame.check(this._selector, { strict: true, ...options });\n }\n async click(options = {}) {\n return await this._frame.click(this._selector, { strict: true, ...options });\n }\n async dblclick(options = {}) {\n await this._frame.dblclick(this._selector, { strict: true, ...options });\n }\n async dispatchEvent(type, eventInit = {}, options) {\n return await this._frame.dispatchEvent(this._selector, type, eventInit, {\n strict: true,\n ...options\n });\n }\n async dragTo(target, options = {}) {\n return await this._frame.dragAndDrop(this._selector, target._selector, {\n strict: true,\n ...options\n });\n }\n async evaluate(pageFunction, arg, options) {\n return await this._withElement((h) => h.evaluate(pageFunction, arg), {\n title: "Evaluate",\n timeout: options?.timeout\n });\n }\n async evaluateAll(pageFunction, arg) {\n return await this._frame.$$eval(this._selector, pageFunction, arg);\n }\n async evaluateHandle(pageFunction, arg, options) {\n return await this._withElement((h) => h.evaluateHandle(pageFunction, arg), {\n title: "Evaluate",\n timeout: options?.timeout\n });\n }\n async fill(value, options = {}) {\n return await this._frame.fill(this._selector, value, { strict: true, ...options });\n }\n async clear(options = {}) {\n await this._frame._wrapApiCall(() => this.fill("", options), { title: "Clear" });\n }\n async _highlight() {\n return await this._frame._highlight(this._selector);\n }\n async highlight() {\n return await this._frame._highlight(this._selector);\n }\n locator(selectorOrLocator, options) {\n if (isString(selectorOrLocator))\n return new _Locator(this._frame, this._selector + " >> " + selectorOrLocator, options);\n if (selectorOrLocator._frame !== this._frame)\n throw new Error(`Locators must belong to the same frame.`);\n return new _Locator(\n this._frame,\n this._selector + " >> internal:chain=" + JSON.stringify(selectorOrLocator._selector),\n options\n );\n }\n getByTestId(testId) {\n return this.locator(getByTestIdSelector(testIdAttributeName(), testId));\n }\n getByAltText(text, options) {\n return this.locator(getByAltTextSelector(text, options));\n }\n getByLabel(text, options) {\n return this.locator(getByLabelSelector(text, options));\n }\n getByPlaceholder(text, options) {\n return this.locator(getByPlaceholderSelector(text, options));\n }\n getByText(text, options) {\n return this.locator(getByTextSelector(text, options));\n }\n getByTitle(text, options) {\n return this.locator(getByTitleSelector(text, options));\n }\n getByRole(role, options = {}) {\n return this.locator(getByRoleSelector(role, options));\n }\n frameLocator(selector) {\n return new FrameLocator(this._frame, this._selector + " >> " + selector);\n }\n filter(options) {\n return new _Locator(this._frame, this._selector, options);\n }\n async elementHandle(options) {\n return await this._frame.waitForSelector(this._selector, {\n strict: true,\n state: "attached",\n ...options\n });\n }\n async elementHandles() {\n return await this._frame.$$(this._selector);\n }\n contentFrame() {\n return new FrameLocator(this._frame, this._selector);\n }\n describe(description) {\n return new _Locator(\n this._frame,\n this._selector + " >> internal:describe=" + JSON.stringify(description)\n );\n }\n description() {\n return locatorCustomDescription(this._selector) || null;\n }\n first() {\n return new _Locator(this._frame, this._selector + " >> nth=0");\n }\n last() {\n return new _Locator(this._frame, this._selector + ` >> nth=-1`);\n }\n nth(index) {\n return new _Locator(this._frame, this._selector + ` >> nth=${index}`);\n }\n and(locator) {\n if (locator._frame !== this._frame) throw new Error(`Locators must belong to the same frame.`);\n return new _Locator(\n this._frame,\n this._selector + ` >> internal:and=` + JSON.stringify(locator._selector)\n );\n }\n or(locator) {\n if (locator._frame !== this._frame) throw new Error(`Locators must belong to the same frame.`);\n return new _Locator(\n this._frame,\n this._selector + ` >> internal:or=` + JSON.stringify(locator._selector)\n );\n }\n async focus(options) {\n return await this._frame.focus(this._selector, { strict: true, ...options });\n }\n async blur(options) {\n await this._frame._channel.blur({\n selector: this._selector,\n strict: true,\n ...options,\n timeout: this._frame._timeout(options)\n });\n }\n // options are only here for testing\n async count(_options) {\n return await this._frame._queryCount(this._selector, _options);\n }\n async toCode() {\n const { resolvedSelector } = await this._frame._channel.resolveSelector({\n selector: this._selector\n });\n return new _Locator(this._frame, resolvedSelector).toString();\n }\n async getAttribute(name, options) {\n return await this._frame.getAttribute(this._selector, name, { strict: true, ...options });\n }\n async hover(options = {}) {\n return await this._frame.hover(this._selector, { strict: true, ...options });\n }\n async innerHTML(options) {\n return await this._frame.innerHTML(this._selector, { strict: true, ...options });\n }\n async innerText(options) {\n return await this._frame.innerText(this._selector, { strict: true, ...options });\n }\n async inputValue(options) {\n return await this._frame.inputValue(this._selector, { strict: true, ...options });\n }\n async isChecked(options) {\n return await this._frame.isChecked(this._selector, { strict: true, ...options });\n }\n async isDisabled(options) {\n return await this._frame.isDisabled(this._selector, { strict: true, ...options });\n }\n async isEditable(options) {\n return await this._frame.isEditable(this._selector, { strict: true, ...options });\n }\n async isEnabled(options) {\n return await this._frame.isEnabled(this._selector, { strict: true, ...options });\n }\n async isHidden(options) {\n return await this._frame.isHidden(this._selector, { strict: true, ...options });\n }\n async isVisible(options) {\n return await this._frame.isVisible(this._selector, { strict: true, ...options });\n }\n async press(key, options = {}) {\n return await this._frame.press(this._selector, key, { strict: true, ...options });\n }\n async screenshot(options = {}) {\n const mask = options.mask;\n return await this._withElement((h, timeout) => h.screenshot({ ...options, mask, timeout }), {\n title: "Screenshot",\n timeout: options.timeout\n });\n }\n async ariaSnapshot(options) {\n const result = await this._frame._channel.ariaSnapshot({\n ...options,\n selector: this._selector,\n timeout: this._frame._timeout(options)\n });\n return result.snapshot;\n }\n async scrollIntoViewIfNeeded(options = {}) {\n return await this._withElement(\n (h, timeout) => h.scrollIntoViewIfNeeded({ ...options, timeout }),\n { title: "Scroll into view", timeout: options.timeout }\n );\n }\n async selectOption(values, options = {}) {\n return await this._frame.selectOption(this._selector, values, { strict: true, ...options });\n }\n async selectText(options = {}) {\n return await this._withElement((h, timeout) => h.selectText({ ...options, timeout }), {\n title: "Select text",\n timeout: options.timeout\n });\n }\n async setChecked(checked, options) {\n if (checked) await this.check(options);\n else await this.uncheck(options);\n }\n async setInputFiles(files, options = {}) {\n return await this._frame.setInputFiles(this._selector, files, { strict: true, ...options });\n }\n async tap(options = {}) {\n return await this._frame.tap(this._selector, { strict: true, ...options });\n }\n async textContent(options) {\n return await this._frame.textContent(this._selector, { strict: true, ...options });\n }\n async type(text, options = {}) {\n return await this._frame.type(this._selector, text, { strict: true, ...options });\n }\n async pressSequentially(text, options = {}) {\n return await this.type(text, options);\n }\n async uncheck(options = {}) {\n return await this._frame.uncheck(this._selector, { strict: true, ...options });\n }\n async all() {\n return new Array(await this.count()).fill(0).map((e, i) => this.nth(i));\n }\n async allInnerTexts() {\n return await this._frame.$$eval(\n this._selector,\n (ee) => ee.map((e) => e.innerText)\n );\n }\n async allTextContents() {\n return await this._frame.$$eval(this._selector, (ee) => ee.map((e) => e.textContent || ""));\n }\n async waitFor(options) {\n await this._frame._channel.waitForSelector({\n selector: this._selector,\n strict: true,\n omitReturnValue: true,\n ...options,\n timeout: this._frame._timeout(options)\n });\n }\n async snapshotForAI(options = {}) {\n return await this._frame._page._channel.snapshotForAI({\n timeout: this._frame._timeout(options),\n selector: this._selector,\n depth: options.depth\n });\n }\n async _expect(expression, options) {\n return this._frame._expect(expression, {\n ...options,\n selector: this._selector\n });\n }\n _inspect() {\n return this.toString();\n }\n toString() {\n return asLocatorDescription("javascript", this._selector);\n }\n };\n var FrameLocator = class _FrameLocator {\n _frame;\n _frameSelector;\n constructor(frame, selector) {\n this._frame = frame;\n this._frameSelector = selector;\n }\n locator(selectorOrLocator, options) {\n if (isString(selectorOrLocator))\n return new Locator(\n this._frame,\n this._frameSelector + " >> internal:control=enter-frame >> " + selectorOrLocator,\n options\n );\n if (selectorOrLocator._frame !== this._frame)\n throw new Error(`Locators must belong to the same frame.`);\n return new Locator(\n this._frame,\n this._frameSelector + " >> internal:control=enter-frame >> " + selectorOrLocator._selector,\n options\n );\n }\n getByTestId(testId) {\n return this.locator(getByTestIdSelector(testIdAttributeName(), testId));\n }\n getByAltText(text, options) {\n return this.locator(getByAltTextSelector(text, options));\n }\n getByLabel(text, options) {\n return this.locator(getByLabelSelector(text, options));\n }\n getByPlaceholder(text, options) {\n return this.locator(getByPlaceholderSelector(text, options));\n }\n getByText(text, options) {\n return this.locator(getByTextSelector(text, options));\n }\n getByTitle(text, options) {\n return this.locator(getByTitleSelector(text, options));\n }\n getByRole(role, options = {}) {\n return this.locator(getByRoleSelector(role, options));\n }\n owner() {\n return new Locator(this._frame, this._frameSelector);\n }\n frameLocator(selector) {\n return new _FrameLocator(\n this._frame,\n this._frameSelector + " >> internal:control=enter-frame >> " + selector\n );\n }\n first() {\n return new _FrameLocator(this._frame, this._frameSelector + " >> nth=0");\n }\n last() {\n return new _FrameLocator(this._frame, this._frameSelector + ` >> nth=-1`);\n }\n nth(index) {\n return new _FrameLocator(this._frame, this._frameSelector + ` >> nth=${index}`);\n }\n };\n var _testIdAttributeName = "data-testid";\n function testIdAttributeName() {\n return _testIdAttributeName;\n }\n function setTestIdAttribute(attributeName) {\n _testIdAttributeName = attributeName;\n }\n\n // src/sandbox/forked-client/src/client/fetch.ts\n function unsupported() {\n throw new Error("APIRequest is not available in the QuickJS sandbox");\n }\n var APIRequestContext = class extends ChannelOwner {\n static from(channel) {\n return channel?._object;\n }\n async storageState() {\n return { cookies: [], origins: [] };\n }\n async dispose() {\n await this._channel.dispose?.({});\n }\n };\n var APIRequest = class {\n constructor(playwright) {\n this._playwright = playwright;\n }\n async newContext() {\n unsupported();\n }\n };\n var APIResponse = class {\n async body() {\n unsupported();\n }\n };\n\n // src/sandbox/forked-client/src/client/waiter.ts\n var Waiter = class _Waiter {\n _dispose;\n _failures = [];\n _immediateError;\n _logs = [];\n _channelOwner;\n _waitId;\n _error;\n _savedZone;\n constructor(channelOwner, event) {\n this._waitId = channelOwner._platform.createGuid();\n this._channelOwner = channelOwner;\n this._savedZone = channelOwner._platform.zones.current().pop();\n this._channelOwner._channel.waitForEventInfo({ info: { waitId: this._waitId, phase: "before", event } }).catch(() => {\n });\n this._dispose = [\n () => this._channelOwner._wrapApiCall(\n async () => {\n await this._channelOwner._channel.waitForEventInfo({\n info: { waitId: this._waitId, phase: "after", error: this._error }\n });\n },\n { internal: true }\n ).catch(() => {\n })\n ];\n }\n static createForEvent(channelOwner, event) {\n return new _Waiter(channelOwner, event);\n }\n async waitForEvent(emitter, event, predicate) {\n const { promise, dispose } = waitForEvent(emitter, event, this._savedZone, predicate);\n return await this.waitForPromise(promise, dispose);\n }\n rejectOnEvent(emitter, event, error, predicate) {\n const { promise, dispose } = waitForEvent(emitter, event, this._savedZone, predicate);\n this._rejectOn(\n promise.then(() => {\n throw typeof error === "function" ? error() : error;\n }),\n dispose\n );\n }\n rejectOnTimeout(timeout, message) {\n if (!timeout) return;\n const { promise, dispose } = waitForTimeout(timeout);\n this._rejectOn(\n promise.then(() => {\n throw new TimeoutError(message);\n }),\n dispose\n );\n }\n rejectImmediately(error) {\n this._immediateError = error;\n }\n dispose() {\n for (const dispose of this._dispose) dispose();\n }\n async waitForPromise(promise, dispose) {\n try {\n if (this._immediateError) throw this._immediateError;\n const result = await Promise.race([promise, ...this._failures]);\n if (dispose) dispose();\n return result;\n } catch (e) {\n if (dispose) dispose();\n this._error = e.message;\n this.dispose();\n rewriteErrorMessage(e, e.message + formatLogRecording(this._logs));\n throw e;\n }\n }\n log(s) {\n this._logs.push(s);\n this._channelOwner._wrapApiCall(\n async () => {\n await this._channelOwner._channel.waitForEventInfo({\n info: { waitId: this._waitId, phase: "log", message: s }\n });\n },\n { internal: true }\n ).catch(() => {\n });\n }\n _rejectOn(promise, dispose) {\n this._failures.push(promise);\n if (dispose) this._dispose.push(dispose);\n }\n };\n function waitForEvent(emitter, event, savedZone, predicate) {\n let listener;\n const promise = new Promise((resolve, reject) => {\n listener = async (eventArg) => {\n await savedZone.run(async () => {\n try {\n if (predicate && !await predicate(eventArg)) return;\n emitter.removeListener(event, listener);\n resolve(eventArg);\n } catch (e) {\n emitter.removeListener(event, listener);\n reject(e);\n }\n });\n };\n emitter.addListener(event, listener);\n });\n const dispose = () => emitter.removeListener(event, listener);\n return { promise, dispose };\n }\n function waitForTimeout(timeout) {\n let timeoutId;\n const promise = new Promise((resolve) => timeoutId = setTimeout(resolve, timeout));\n const dispose = () => clearTimeout(timeoutId);\n return { promise, dispose };\n }\n function formatLogRecording(log) {\n if (!log.length) return "";\n const header = ` logs `;\n const headerLength = 60;\n const leftLength = (headerLength - header.length) / 2;\n const rightLength = headerLength - header.length - leftLength;\n return `\n${"=".repeat(leftLength)}${header}${"=".repeat(rightLength)}\n${log.join("\\n")}\n${"=".repeat(headerLength)}`;\n }\n\n // src/sandbox/forked-client/src/utils/isomorphic/manualPromise.ts\n var ManualPromise = class extends Promise {\n _resolve;\n _reject;\n _isDone;\n constructor() {\n let resolve;\n let reject;\n super((f, r) => {\n resolve = f;\n reject = r;\n });\n this._isDone = false;\n this._resolve = resolve;\n this._reject = reject;\n }\n isDone() {\n return this._isDone;\n }\n resolve(t) {\n this._isDone = true;\n this._resolve(t);\n }\n reject(e) {\n this._isDone = true;\n this._reject(e);\n }\n static get [Symbol.species]() {\n return Promise;\n }\n get [Symbol.toStringTag]() {\n return "ManualPromise";\n }\n };\n var LongStandingScope = class {\n _terminateError;\n _closeError;\n _terminatePromises = /* @__PURE__ */ new Map();\n _isClosed = false;\n reject(error) {\n this._isClosed = true;\n this._terminateError = error;\n for (const p of this._terminatePromises.keys()) p.resolve(error);\n }\n close(error) {\n this._isClosed = true;\n this._closeError = error;\n for (const [p, frames] of this._terminatePromises) p.resolve(cloneError(error, frames));\n }\n isClosed() {\n return this._isClosed;\n }\n static async raceMultiple(scopes, promise) {\n return Promise.race(scopes.map((s) => s.race(promise)));\n }\n async race(promise) {\n return this._race(Array.isArray(promise) ? promise : [promise], false);\n }\n async safeRace(promise, defaultValue) {\n return this._race([promise], true, defaultValue);\n }\n async _race(promises, safe, defaultValue) {\n const terminatePromise = new ManualPromise();\n const frames = captureRawStack();\n if (this._terminateError) terminatePromise.resolve(this._terminateError);\n if (this._closeError) terminatePromise.resolve(cloneError(this._closeError, frames));\n this._terminatePromises.set(terminatePromise, frames);\n try {\n return await Promise.race([\n terminatePromise.then((e) => safe ? defaultValue : Promise.reject(e)),\n ...promises\n ]);\n } finally {\n this._terminatePromises.delete(terminatePromise);\n }\n }\n };\n function cloneError(error, frames) {\n const clone = new Error();\n clone.name = error.name;\n clone.message = error.message;\n clone.stack = [error.name + ":" + error.message, ...frames].join("\\n");\n return clone;\n }\n\n // src/sandbox/forked-client/src/client/timeoutSettings.ts\n var TimeoutSettings = class {\n _parent;\n _defaultTimeout;\n _defaultNavigationTimeout;\n _platform;\n constructor(platform, parent) {\n this._parent = parent;\n this._platform = platform;\n }\n setDefaultTimeout(timeout) {\n this._defaultTimeout = timeout;\n }\n setDefaultNavigationTimeout(timeout) {\n this._defaultNavigationTimeout = timeout;\n }\n defaultNavigationTimeout() {\n return this._defaultNavigationTimeout;\n }\n defaultTimeout() {\n return this._defaultTimeout;\n }\n navigationTimeout(options) {\n if (typeof options.timeout === "number") return options.timeout;\n if (this._defaultNavigationTimeout !== void 0) return this._defaultNavigationTimeout;\n if (this._platform.isDebugMode()) return 0;\n if (this._defaultTimeout !== void 0) return this._defaultTimeout;\n if (this._parent) return this._parent.navigationTimeout(options);\n return DEFAULT_PLAYWRIGHT_TIMEOUT;\n }\n timeout(options) {\n if (typeof options.timeout === "number") return options.timeout;\n if (this._platform.isDebugMode()) return 0;\n if (this._defaultTimeout !== void 0) return this._defaultTimeout;\n if (this._parent) return this._parent.timeout(options);\n return DEFAULT_PLAYWRIGHT_TIMEOUT;\n }\n launchTimeout(options) {\n if (typeof options.timeout === "number") return options.timeout;\n if (this._platform.isDebugMode()) return 0;\n if (this._parent) return this._parent.launchTimeout(options);\n return DEFAULT_PLAYWRIGHT_LAUNCH_TIMEOUT;\n }\n };\n\n // src/sandbox/forked-client/src/client/worker.ts\n var Worker = class _Worker extends ChannelOwner {\n _page;\n // Set for web workers.\n _context;\n // Set for service workers.\n _closedScope = new LongStandingScope();\n static fromNullable(worker) {\n return worker ? _Worker.from(worker) : null;\n }\n static from(worker) {\n return worker._object;\n }\n constructor(parent, type, guid, initializer) {\n super(parent, type, guid, initializer);\n this._setEventToSubscriptionMapping(\n /* @__PURE__ */ new Map([\n [Events.Worker.Console, "console"]\n ])\n );\n this._channel.on("close", () => {\n if (this._page) this._page._workers.delete(this);\n if (this._context) this._context._serviceWorkers.delete(this);\n this.emit(Events.Worker.Close, this);\n });\n this.once(\n Events.Worker.Close,\n () => this._closedScope.close(this._page?._closeErrorWithReason() || new TargetClosedError())\n );\n }\n url() {\n return this._initializer.url;\n }\n async evaluate(pageFunction, arg) {\n assertMaxArguments(arguments.length, 2);\n const result = await this._channel.evaluateExpression({\n expression: String(pageFunction),\n isFunction: typeof pageFunction === "function",\n arg: serializeArgument(arg)\n });\n return parseResult(result.value);\n }\n async evaluateHandle(pageFunction, arg) {\n assertMaxArguments(arguments.length, 2);\n const result = await this._channel.evaluateExpressionHandle({\n expression: String(pageFunction),\n isFunction: typeof pageFunction === "function",\n arg: serializeArgument(arg)\n });\n return JSHandle.from(result.handle);\n }\n async waitForEvent(event, optionsOrPredicate = {}) {\n return await this._wrapApiCall(async () => {\n const timeoutSettings = this._page?._timeoutSettings ?? this._context?._timeoutSettings ?? new TimeoutSettings(this._platform);\n const timeout = timeoutSettings.timeout(\n typeof optionsOrPredicate === "function" ? {} : optionsOrPredicate\n );\n const predicate = typeof optionsOrPredicate === "function" ? optionsOrPredicate : optionsOrPredicate.predicate;\n const waiter = Waiter.createForEvent(this, event);\n waiter.rejectOnTimeout(\n timeout,\n `Timeout ${timeout}ms exceeded while waiting for event "${event}"`\n );\n if (event !== Events.Worker.Close)\n waiter.rejectOnEvent(this, Events.Worker.Close, () => new TargetClosedError());\n const result = await waiter.waitForEvent(this, event, predicate);\n waiter.dispose();\n return result;\n });\n }\n };\n\n // src/sandbox/forked-client/src/utils/isomorphic/assert.ts\n function assert(value, message) {\n if (!value) throw new Error(message || "Assertion error");\n }\n\n // src/sandbox/forked-client/src/utils/isomorphic/headers.ts\n function headersObjectToArray(headers, separator, setCookieSeparator) {\n if (!setCookieSeparator) setCookieSeparator = separator;\n const result = [];\n for (const name in headers) {\n const values = headers[name];\n if (values === void 0) continue;\n if (separator) {\n const sep = name.toLowerCase() === "set-cookie" ? setCookieSeparator : separator;\n for (const value of values.split(sep)) result.push({ name, value: value.trim() });\n } else {\n result.push({ name, value: values });\n }\n }\n return result;\n }\n function headersArrayToObject(headers, lowerCase) {\n const result = {};\n for (const { name, value } of headers) result[lowerCase ? name.toLowerCase() : name] = value;\n return result;\n }\n\n // src/sandbox/forked-client/src/utils/isomorphic/urlMatch.ts\n var escapedChars = /* @__PURE__ */ new Set([\n "$",\n "^",\n "+",\n ".",\n "*",\n "(",\n ")",\n "|",\n "\\\\",\n "?",\n "{",\n "}",\n "[",\n "]"\n ]);\n function globToRegexPattern(glob) {\n const tokens = ["^"];\n let inGroup = false;\n for (let i = 0; i < glob.length; ++i) {\n const c = glob[i];\n if (c === "\\\\" && i + 1 < glob.length) {\n const char = glob[++i];\n tokens.push(escapedChars.has(char) ? "\\\\" + char : char);\n continue;\n }\n if (c === "*") {\n const charBefore = glob[i - 1];\n let starCount = 1;\n while (glob[i + 1] === "*") {\n starCount++;\n i++;\n }\n if (starCount > 1) {\n const charAfter = glob[i + 1];\n if (charAfter === "/") {\n if (charBefore === "/") tokens.push("((.+/)|)");\n else tokens.push("(.*/)");\n ++i;\n } else {\n tokens.push("(.*)");\n }\n } else {\n tokens.push("([^/]*)");\n }\n continue;\n }\n switch (c) {\n case "{":\n inGroup = true;\n tokens.push("(");\n break;\n case "}":\n inGroup = false;\n tokens.push(")");\n break;\n case ",":\n if (inGroup) {\n tokens.push("|");\n break;\n }\n tokens.push("\\\\" + c);\n break;\n default:\n tokens.push(escapedChars.has(c) ? "\\\\" + c : c);\n }\n }\n tokens.push("$");\n return tokens.join("");\n }\n function isRegExp4(obj) {\n return obj instanceof RegExp || Object.prototype.toString.call(obj) === "[object RegExp]";\n }\n var isURLPattern = (v) => typeof globalThis.URLPattern === "function" && v instanceof globalThis.URLPattern;\n function serializeURLPattern(v) {\n return {\n hash: v.hash,\n hostname: v.hostname,\n password: v.password,\n pathname: v.pathname,\n port: v.port,\n protocol: v.protocol,\n search: v.search,\n username: v.username\n };\n }\n function serializeURLMatch(match) {\n if (isString(match)) return { glob: match };\n if (isRegExp4(match)) return { regexSource: match.source, regexFlags: match.flags };\n if (isURLPattern(match)) return { urlPattern: serializeURLPattern(match) };\n return void 0;\n }\n function urlMatchesEqual(match1, match2) {\n if (isRegExp4(match1) && isRegExp4(match2))\n return match1.source === match2.source && match1.flags === match2.flags;\n return match1 === match2;\n }\n function urlMatches(baseURL, urlString, match, webSocketUrl) {\n if (match === void 0 || match === "") return true;\n if (isString(match)) match = new RegExp(resolveGlobToRegexPattern(baseURL, match, webSocketUrl));\n if (isRegExp4(match)) {\n const r = match.test(urlString);\n return r;\n }\n const url = parseURL(urlString);\n if (!url) return false;\n if (isURLPattern(match)) return match.test(url.href);\n if (typeof match !== "function")\n throw new Error("url parameter should be string, RegExp, URLPattern or function");\n return match(url);\n }\n function resolveGlobToRegexPattern(baseURL, glob, webSocketUrl) {\n if (webSocketUrl) baseURL = toWebSocketBaseUrl(baseURL);\n glob = resolveGlobBase(baseURL, glob);\n return globToRegexPattern(glob);\n }\n function toWebSocketBaseUrl(baseURL) {\n if (baseURL && /^https?:\\/\\//.test(baseURL)) baseURL = baseURL.replace(/^http/, "ws");\n return baseURL;\n }\n function resolveGlobBase(baseURL, match) {\n if (!match.startsWith("*")) {\n let mapToken2 = function(original, replacement) {\n if (original.length === 0) return "";\n tokenMap.set(replacement, original);\n return replacement;\n };\n var mapToken = mapToken2;\n const tokenMap = /* @__PURE__ */ new Map();\n match = match.replaceAll(/\\\\\\\\\\?/g, "?");\n if (match.startsWith("about:") || match.startsWith("data:") || match.startsWith("chrome:") || match.startsWith("edge:") || match.startsWith("file:"))\n return match;\n const relativePath = match.split("/").map((token, index) => {\n if (token === "." || token === ".." || token === "") return token;\n if (index === 0 && token.endsWith(":")) {\n if (token.indexOf("*") !== -1 || token.indexOf("{") !== -1)\n return mapToken2(token, "http:");\n return token;\n }\n const questionIndex = token.indexOf("?");\n if (questionIndex === -1) return mapToken2(token, `$_${index}_$`);\n const newPrefix = mapToken2(token.substring(0, questionIndex), `$_${index}_$`);\n const newSuffix = mapToken2(token.substring(questionIndex), `?$_${index}_$`);\n return newPrefix + newSuffix;\n }).join("/");\n const result = resolveBaseURL(baseURL, relativePath);\n let resolved = result.resolved;\n for (const [token, original] of tokenMap) {\n const normalize = result.caseInsensitivePart?.includes(token);\n resolved = resolved.replace(token, normalize ? original.toLowerCase() : original);\n }\n match = resolved;\n }\n return match;\n }\n function parseURL(url) {\n try {\n return new URL(url);\n } catch (e) {\n return null;\n }\n }\n function resolveBaseURL(baseURL, givenURL) {\n try {\n const url = new URL(givenURL, baseURL);\n const resolved = url.toString();\n const caseInsensitivePrefix = url.origin;\n return { resolved, caseInsensitivePart: caseInsensitivePrefix };\n } catch (e) {\n return { resolved: givenURL };\n }\n }\n\n // src/sandbox/forked-client/src/utils/isomorphic/multimap.ts\n var MultiMap = class {\n _map;\n constructor() {\n this._map = /* @__PURE__ */ new Map();\n }\n set(key, value) {\n let values = this._map.get(key);\n if (!values) {\n values = [];\n this._map.set(key, values);\n }\n values.push(value);\n }\n get(key) {\n return this._map.get(key) || [];\n }\n has(key) {\n return this._map.has(key);\n }\n delete(key, value) {\n const values = this._map.get(key);\n if (!values) return;\n if (values.includes(value))\n this._map.set(\n key,\n values.filter((v) => value !== v)\n );\n }\n deleteAll(key) {\n this._map.delete(key);\n }\n hasValue(key, value) {\n const values = this._map.get(key);\n if (!values) return false;\n return values.includes(value);\n }\n get size() {\n return this._map.size;\n }\n [Symbol.iterator]() {\n return this._map[Symbol.iterator]();\n }\n keys() {\n return this._map.keys();\n }\n values() {\n const result = [];\n for (const key of this.keys()) result.push(...this.get(key));\n return result;\n }\n clear() {\n this._map.clear();\n }\n };\n\n // src/sandbox/forked-client/src/utils/isomorphic/mimeType.ts\n function getMimeTypeForPath(path) {\n const dotIndex = path.lastIndexOf(".");\n if (dotIndex === -1) return null;\n const extension = path.substring(dotIndex + 1);\n return types.get(extension) || null;\n }\n var types = /* @__PURE__ */ new Map([\n ["ez", "application/andrew-inset"],\n ["aw", "application/applixware"],\n ["atom", "application/atom+xml"],\n ["atomcat", "application/atomcat+xml"],\n ["atomdeleted", "application/atomdeleted+xml"],\n ["atomsvc", "application/atomsvc+xml"],\n ["dwd", "application/atsc-dwd+xml"],\n ["held", "application/atsc-held+xml"],\n ["rsat", "application/atsc-rsat+xml"],\n ["bdoc", "application/bdoc"],\n ["xcs", "application/calendar+xml"],\n ["ccxml", "application/ccxml+xml"],\n ["cdfx", "application/cdfx+xml"],\n ["cdmia", "application/cdmi-capability"],\n ["cdmic", "application/cdmi-container"],\n ["cdmid", "application/cdmi-domain"],\n ["cdmio", "application/cdmi-object"],\n ["cdmiq", "application/cdmi-queue"],\n ["cu", "application/cu-seeme"],\n ["mpd", "application/dash+xml"],\n ["davmount", "application/davmount+xml"],\n ["dbk", "application/docbook+xml"],\n ["dssc", "application/dssc+der"],\n ["xdssc", "application/dssc+xml"],\n ["ecma", "application/ecmascript"],\n ["es", "application/ecmascript"],\n ["emma", "application/emma+xml"],\n ["emotionml", "application/emotionml+xml"],\n ["epub", "application/epub+zip"],\n ["exi", "application/exi"],\n ["exp", "application/express"],\n ["fdt", "application/fdt+xml"],\n ["pfr", "application/font-tdpfr"],\n ["geojson", "application/geo+json"],\n ["gml", "application/gml+xml"],\n ["gpx", "application/gpx+xml"],\n ["gxf", "application/gxf"],\n ["gz", "application/gzip"],\n ["hjson", "application/hjson"],\n ["stk", "application/hyperstudio"],\n ["ink", "application/inkml+xml"],\n ["inkml", "application/inkml+xml"],\n ["ipfix", "application/ipfix"],\n ["its", "application/its+xml"],\n ["ear", "application/java-archive"],\n ["jar", "application/java-archive"],\n ["war", "application/java-archive"],\n ["ser", "application/java-serialized-object"],\n ["class", "application/java-vm"],\n ["js", "application/javascript"],\n ["mjs", "application/javascript"],\n ["json", "application/json"],\n ["map", "application/json"],\n ["json5", "application/json5"],\n ["jsonml", "application/jsonml+json"],\n ["jsonld", "application/ld+json"],\n ["lgr", "application/lgr+xml"],\n ["lostxml", "application/lost+xml"],\n ["hqx", "application/mac-binhex40"],\n ["cpt", "application/mac-compactpro"],\n ["mads", "application/mads+xml"],\n ["webmanifest", "application/manifest+json"],\n ["mrc", "application/marc"],\n ["mrcx", "application/marcxml+xml"],\n ["ma", "application/mathematica"],\n ["mb", "application/mathematica"],\n ["nb", "application/mathematica"],\n ["mathml", "application/mathml+xml"],\n ["mbox", "application/mbox"],\n ["mscml", "application/mediaservercontrol+xml"],\n ["metalink", "application/metalink+xml"],\n ["meta4", "application/metalink4+xml"],\n ["mets", "application/mets+xml"],\n ["maei", "application/mmt-aei+xml"],\n ["musd", "application/mmt-usd+xml"],\n ["mods", "application/mods+xml"],\n ["m21", "application/mp21"],\n ["mp21", "application/mp21"],\n ["m4p", "application/mp4"],\n ["mp4s", "application/mp4"],\n ["doc", "application/msword"],\n ["dot", "application/msword"],\n ["mxf", "application/mxf"],\n ["nq", "application/n-quads"],\n ["nt", "application/n-triples"],\n ["cjs", "application/node"],\n ["bin", "application/octet-stream"],\n ["bpk", "application/octet-stream"],\n ["buffer", "application/octet-stream"],\n ["deb", "application/octet-stream"],\n ["deploy", "application/octet-stream"],\n ["dist", "application/octet-stream"],\n ["distz", "application/octet-stream"],\n ["dll", "application/octet-stream"],\n ["dmg", "application/octet-stream"],\n ["dms", "application/octet-stream"],\n ["dump", "application/octet-stream"],\n ["elc", "application/octet-stream"],\n ["exe", "application/octet-stream"],\n ["img", "application/octet-stream"],\n ["iso", "application/octet-stream"],\n ["lrf", "application/octet-stream"],\n ["mar", "application/octet-stream"],\n ["msi", "application/octet-stream"],\n ["msm", "application/octet-stream"],\n ["msp", "application/octet-stream"],\n ["pkg", "application/octet-stream"],\n ["so", "application/octet-stream"],\n ["oda", "application/oda"],\n ["opf", "application/oebps-package+xml"],\n ["ogx", "application/ogg"],\n ["omdoc", "application/omdoc+xml"],\n ["onepkg", "application/onenote"],\n ["onetmp", "application/onenote"],\n ["onetoc", "application/onenote"],\n ["onetoc2", "application/onenote"],\n ["oxps", "application/oxps"],\n ["relo", "application/p2p-overlay+xml"],\n ["xer", "application/patch-ops-error+xml"],\n ["pdf", "application/pdf"],\n ["pgp", "application/pgp-encrypted"],\n ["asc", "application/pgp-signature"],\n ["sig", "application/pgp-signature"],\n ["prf", "application/pics-rules"],\n ["p10", "application/pkcs10"],\n ["p7c", "application/pkcs7-mime"],\n ["p7m", "application/pkcs7-mime"],\n ["p7s", "application/pkcs7-signature"],\n ["p8", "application/pkcs8"],\n ["ac", "application/pkix-attr-cert"],\n ["cer", "application/pkix-cert"],\n ["crl", "application/pkix-crl"],\n ["pkipath", "application/pkix-pkipath"],\n ["pki", "application/pkixcmp"],\n ["pls", "application/pls+xml"],\n ["ai", "application/postscript"],\n ["eps", "application/postscript"],\n ["ps", "application/postscript"],\n ["provx", "application/provenance+xml"],\n ["pskcxml", "application/pskc+xml"],\n ["raml", "application/raml+yaml"],\n ["owl", "application/rdf+xml"],\n ["rdf", "application/rdf+xml"],\n ["rif", "application/reginfo+xml"],\n ["rnc", "application/relax-ng-compact-syntax"],\n ["rl", "application/resource-lists+xml"],\n ["rld", "application/resource-lists-diff+xml"],\n ["rs", "application/rls-services+xml"],\n ["rapd", "application/route-apd+xml"],\n ["sls", "application/route-s-tsid+xml"],\n ["rusd", "application/route-usd+xml"],\n ["gbr", "application/rpki-ghostbusters"],\n ["mft", "application/rpki-manifest"],\n ["roa", "application/rpki-roa"],\n ["rsd", "application/rsd+xml"],\n ["rss", "application/rss+xml"],\n ["rtf", "application/rtf"],\n ["sbml", "application/sbml+xml"],\n ["scq", "application/scvp-cv-request"],\n ["scs", "application/scvp-cv-response"],\n ["spq", "application/scvp-vp-request"],\n ["spp", "application/scvp-vp-response"],\n ["sdp", "application/sdp"],\n ["senmlx", "application/senml+xml"],\n ["sensmlx", "application/sensml+xml"],\n ["setpay", "application/set-payment-initiation"],\n ["setreg", "application/set-registration-initiation"],\n ["shf", "application/shf+xml"],\n ["sieve", "application/sieve"],\n ["siv", "application/sieve"],\n ["smi", "application/smil+xml"],\n ["smil", "application/smil+xml"],\n ["rq", "application/sparql-query"],\n ["srx", "application/sparql-results+xml"],\n ["gram", "application/srgs"],\n ["grxml", "application/srgs+xml"],\n ["sru", "application/sru+xml"],\n ["ssdl", "application/ssdl+xml"],\n ["ssml", "application/ssml+xml"],\n ["swidtag", "application/swid+xml"],\n ["tei", "application/tei+xml"],\n ["teicorpus", "application/tei+xml"],\n ["tfi", "application/thraud+xml"],\n ["tsd", "application/timestamped-data"],\n ["toml", "application/toml"],\n ["trig", "application/trig"],\n ["ttml", "application/ttml+xml"],\n ["ubj", "application/ubjson"],\n ["rsheet", "application/urc-ressheet+xml"],\n ["td", "application/urc-targetdesc+xml"],\n ["vxml", "application/voicexml+xml"],\n ["wasm", "application/wasm"],\n ["wgt", "application/widget"],\n ["hlp", "application/winhlp"],\n ["wsdl", "application/wsdl+xml"],\n ["wspolicy", "application/wspolicy+xml"],\n ["xaml", "application/xaml+xml"],\n ["xav", "application/xcap-att+xml"],\n ["xca", "application/xcap-caps+xml"],\n ["xdf", "application/xcap-diff+xml"],\n ["xel", "application/xcap-el+xml"],\n ["xns", "application/xcap-ns+xml"],\n ["xenc", "application/xenc+xml"],\n ["xht", "application/xhtml+xml"],\n ["xhtml", "application/xhtml+xml"],\n ["xlf", "application/xliff+xml"],\n ["rng", "application/xml"],\n ["xml", "application/xml"],\n ["xsd", "application/xml"],\n ["xsl", "application/xml"],\n ["dtd", "application/xml-dtd"],\n ["xop", "application/xop+xml"],\n ["xpl", "application/xproc+xml"],\n ["*xsl", "application/xslt+xml"],\n ["xslt", "application/xslt+xml"],\n ["xspf", "application/xspf+xml"],\n ["mxml", "application/xv+xml"],\n ["xhvml", "application/xv+xml"],\n ["xvm", "application/xv+xml"],\n ["xvml", "application/xv+xml"],\n ["yang", "application/yang"],\n ["yin", "application/yin+xml"],\n ["zip", "application/zip"],\n ["*3gpp", "audio/3gpp"],\n ["adp", "audio/adpcm"],\n ["amr", "audio/amr"],\n ["au", "audio/basic"],\n ["snd", "audio/basic"],\n ["kar", "audio/midi"],\n ["mid", "audio/midi"],\n ["midi", "audio/midi"],\n ["rmi", "audio/midi"],\n ["mxmf", "audio/mobile-xmf"],\n ["*mp3", "audio/mp3"],\n ["m4a", "audio/mp4"],\n ["mp4a", "audio/mp4"],\n ["m2a", "audio/mpeg"],\n ["m3a", "audio/mpeg"],\n ["mp2", "audio/mpeg"],\n ["mp2a", "audio/mpeg"],\n ["mp3", "audio/mpeg"],\n ["mpga", "audio/mpeg"],\n ["oga", "audio/ogg"],\n ["ogg", "audio/ogg"],\n ["opus", "audio/ogg"],\n ["spx", "audio/ogg"],\n ["s3m", "audio/s3m"],\n ["sil", "audio/silk"],\n ["wav", "audio/wav"],\n ["*wav", "audio/wave"],\n ["weba", "audio/webm"],\n ["xm", "audio/xm"],\n ["ttc", "font/collection"],\n ["otf", "font/otf"],\n ["ttf", "font/ttf"],\n ["woff", "font/woff"],\n ["woff2", "font/woff2"],\n ["exr", "image/aces"],\n ["apng", "image/apng"],\n ["avif", "image/avif"],\n ["bmp", "image/bmp"],\n ["cgm", "image/cgm"],\n ["drle", "image/dicom-rle"],\n ["emf", "image/emf"],\n ["fits", "image/fits"],\n ["g3", "image/g3fax"],\n ["gif", "image/gif"],\n ["heic", "image/heic"],\n ["heics", "image/heic-sequence"],\n ["heif", "image/heif"],\n ["heifs", "image/heif-sequence"],\n ["hej2", "image/hej2k"],\n ["hsj2", "image/hsj2"],\n ["ief", "image/ief"],\n ["jls", "image/jls"],\n ["jp2", "image/jp2"],\n ["jpg2", "image/jp2"],\n ["jpe", "image/jpeg"],\n ["jpeg", "image/jpeg"],\n ["jpg", "image/jpeg"],\n ["jph", "image/jph"],\n ["jhc", "image/jphc"],\n ["jpm", "image/jpm"],\n ["jpf", "image/jpx"],\n ["jpx", "image/jpx"],\n ["jxr", "image/jxr"],\n ["jxra", "image/jxra"],\n ["jxrs", "image/jxrs"],\n ["jxs", "image/jxs"],\n ["jxsc", "image/jxsc"],\n ["jxsi", "image/jxsi"],\n ["jxss", "image/jxss"],\n ["ktx", "image/ktx"],\n ["ktx2", "image/ktx2"],\n ["png", "image/png"],\n ["sgi", "image/sgi"],\n ["svg", "image/svg+xml"],\n ["svgz", "image/svg+xml"],\n ["t38", "image/t38"],\n ["tif", "image/tiff"],\n ["tiff", "image/tiff"],\n ["tfx", "image/tiff-fx"],\n ["webp", "image/webp"],\n ["wmf", "image/wmf"],\n ["disposition-notification", "message/disposition-notification"],\n ["u8msg", "message/global"],\n ["u8dsn", "message/global-delivery-status"],\n ["u8mdn", "message/global-disposition-notification"],\n ["u8hdr", "message/global-headers"],\n ["eml", "message/rfc822"],\n ["mime", "message/rfc822"],\n ["3mf", "model/3mf"],\n ["gltf", "model/gltf+json"],\n ["glb", "model/gltf-binary"],\n ["iges", "model/iges"],\n ["igs", "model/iges"],\n ["mesh", "model/mesh"],\n ["msh", "model/mesh"],\n ["silo", "model/mesh"],\n ["mtl", "model/mtl"],\n ["obj", "model/obj"],\n ["stpx", "model/step+xml"],\n ["stpz", "model/step+zip"],\n ["stpxz", "model/step-xml+zip"],\n ["stl", "model/stl"],\n ["vrml", "model/vrml"],\n ["wrl", "model/vrml"],\n ["*x3db", "model/x3d+binary"],\n ["x3dbz", "model/x3d+binary"],\n ["x3db", "model/x3d+fastinfoset"],\n ["*x3dv", "model/x3d+vrml"],\n ["x3dvz", "model/x3d+vrml"],\n ["x3d", "model/x3d+xml"],\n ["x3dz", "model/x3d+xml"],\n ["x3dv", "model/x3d-vrml"],\n ["appcache", "text/cache-manifest"],\n ["manifest", "text/cache-manifest"],\n ["ics", "text/calendar"],\n ["ifb", "text/calendar"],\n ["coffee", "text/coffeescript"],\n ["litcoffee", "text/coffeescript"],\n ["css", "text/css"],\n ["csv", "text/csv"],\n ["htm", "text/html"],\n ["html", "text/html"],\n ["shtml", "text/html"],\n ["jade", "text/jade"],\n ["jsx", "text/jsx"],\n ["less", "text/less"],\n ["markdown", "text/markdown"],\n ["md", "text/markdown"],\n ["mml", "text/mathml"],\n ["mdx", "text/mdx"],\n ["n3", "text/n3"],\n ["conf", "text/plain"],\n ["def", "text/plain"],\n ["in", "text/plain"],\n ["ini", "text/plain"],\n ["list", "text/plain"],\n ["log", "text/plain"],\n ["text", "text/plain"],\n ["txt", "text/plain"],\n ["rtx", "text/richtext"],\n ["*rtf", "text/rtf"],\n ["sgm", "text/sgml"],\n ["sgml", "text/sgml"],\n ["shex", "text/shex"],\n ["slim", "text/slim"],\n ["slm", "text/slim"],\n ["spdx", "text/spdx"],\n ["styl", "text/stylus"],\n ["stylus", "text/stylus"],\n ["tsv", "text/tab-separated-values"],\n ["man", "text/troff"],\n ["me", "text/troff"],\n ["ms", "text/troff"],\n ["roff", "text/troff"],\n ["t", "text/troff"],\n ["tr", "text/troff"],\n ["ttl", "text/turtle"],\n ["uri", "text/uri-list"],\n ["uris", "text/uri-list"],\n ["urls", "text/uri-list"],\n ["vcard", "text/vcard"],\n ["vtt", "text/vtt"],\n ["*xml", "text/xml"],\n ["yaml", "text/yaml"],\n ["yml", "text/yaml"],\n ["3gp", "video/3gpp"],\n ["3gpp", "video/3gpp"],\n ["3g2", "video/3gpp2"],\n ["h261", "video/h261"],\n ["h263", "video/h263"],\n ["h264", "video/h264"],\n ["m4s", "video/iso.segment"],\n ["jpgv", "video/jpeg"],\n ["jpm", "video/jpm"],\n ["jpgm", "video/jpm"],\n ["mj2", "video/mj2"],\n ["mjp2", "video/mj2"],\n ["ts", "application/typescript"],\n ["mp4", "video/mp4"],\n ["mp4v", "video/mp4"],\n ["mpg4", "video/mp4"],\n ["m1v", "video/mpeg"],\n ["m2v", "video/mpeg"],\n ["mpe", "video/mpeg"],\n ["mpeg", "video/mpeg"],\n ["mpg", "video/mpeg"],\n ["ogv", "video/ogg"],\n ["mov", "video/quicktime"],\n ["qt", "video/quicktime"],\n ["webm", "video/webm"]\n ]);\n\n // src/sandbox/forked-client/src/client/network.ts\n var Request = class _Request extends ChannelOwner {\n _redirectedFrom = null;\n _redirectedTo = null;\n _failureText = null;\n _response = null;\n _hasResponse = false;\n _provisionalHeaders;\n _actualHeadersPromise;\n _timing;\n _fallbackOverrides = {};\n static from(request) {\n return request._object;\n }\n static fromNullable(request) {\n return request ? _Request.from(request) : null;\n }\n constructor(parent, type, guid, initializer) {\n super(parent, type, guid, initializer);\n this._redirectedFrom = _Request.fromNullable(initializer.redirectedFrom);\n if (this._redirectedFrom) this._redirectedFrom._redirectedTo = this;\n this._provisionalHeaders = new RawHeaders(initializer.headers);\n this._timing = {\n startTime: 0,\n domainLookupStart: -1,\n domainLookupEnd: -1,\n connectStart: -1,\n secureConnectionStart: -1,\n connectEnd: -1,\n requestStart: -1,\n responseStart: -1,\n responseEnd: -1\n };\n this._hasResponse = this._initializer.hasResponse;\n this._channel.on("response", () => this._hasResponse = true);\n }\n url() {\n return this._fallbackOverrides.url || this._initializer.url;\n }\n resourceType() {\n return this._initializer.resourceType;\n }\n method() {\n return this._fallbackOverrides.method || this._initializer.method;\n }\n postData() {\n return (this._fallbackOverrides.postDataBuffer || this._initializer.postData)?.toString("utf-8") || null;\n }\n postDataBuffer() {\n return this._fallbackOverrides.postDataBuffer || this._initializer.postData || null;\n }\n postDataJSON() {\n const postData = this.postData();\n if (!postData) return null;\n const contentType = this.headers()["content-type"];\n if (contentType?.includes("application/x-www-form-urlencoded")) {\n const entries = {};\n const parsed = new URLSearchParams(postData);\n for (const [k, v] of parsed.entries()) entries[k] = v;\n return entries;\n }\n try {\n return JSON.parse(postData);\n } catch (e) {\n throw new Error("POST data is not a valid JSON object: " + postData);\n }\n }\n /**\n * @deprecated\n */\n headers() {\n if (this._fallbackOverrides.headers)\n return RawHeaders._fromHeadersObjectLossy(this._fallbackOverrides.headers).headers();\n return this._provisionalHeaders.headers();\n }\n async _actualHeaders() {\n if (this._fallbackOverrides.headers)\n return RawHeaders._fromHeadersObjectLossy(this._fallbackOverrides.headers);\n if (!this._actualHeadersPromise) {\n this._actualHeadersPromise = this._wrapApiCall(\n async () => {\n return new RawHeaders((await this._channel.rawRequestHeaders()).headers);\n },\n { internal: true }\n );\n }\n return await this._actualHeadersPromise;\n }\n async allHeaders() {\n return (await this._actualHeaders()).headers();\n }\n async headersArray() {\n return (await this._actualHeaders()).headersArray();\n }\n async headerValue(name) {\n return (await this._actualHeaders()).get(name);\n }\n async response() {\n return Response.fromNullable((await this._channel.response()).response);\n }\n async _internalResponse() {\n return Response.fromNullable((await this._channel.response()).response);\n }\n existingResponse() {\n return this._response;\n }\n frame() {\n if (!this._initializer.frame) {\n assert(this.serviceWorker());\n throw new Error("Service Worker requests do not have an associated frame.");\n }\n const frame = Frame.from(this._initializer.frame);\n if (!frame._page) {\n throw new Error(\n [\n "Frame for this navigation request is not available, because the request",\n "was issued before the frame is created. You can check whether the request",\n "is a navigation request by calling isNavigationRequest() method."\n ].join("\\n")\n );\n }\n return frame;\n }\n _safePage() {\n return Frame.fromNullable(this._initializer.frame)?._page || null;\n }\n serviceWorker() {\n return this._initializer.serviceWorker ? Worker.from(this._initializer.serviceWorker) : null;\n }\n isNavigationRequest() {\n return this._initializer.isNavigationRequest;\n }\n redirectedFrom() {\n return this._redirectedFrom;\n }\n redirectedTo() {\n return this._redirectedTo;\n }\n failure() {\n if (this._failureText === null) return null;\n return {\n errorText: this._failureText\n };\n }\n timing() {\n return this._timing;\n }\n async sizes() {\n const response = await this.response();\n if (!response) throw new Error("Unable to fetch sizes for failed request");\n return (await response._channel.sizes()).sizes;\n }\n _setResponseEndTiming(responseEndTiming) {\n this._timing.responseEnd = responseEndTiming;\n if (this._timing.responseStart === -1) this._timing.responseStart = responseEndTiming;\n }\n _finalRequest() {\n return this._redirectedTo ? this._redirectedTo._finalRequest() : this;\n }\n _applyFallbackOverrides(overrides) {\n if (overrides.url) this._fallbackOverrides.url = overrides.url;\n if (overrides.method) this._fallbackOverrides.method = overrides.method;\n if (overrides.headers) this._fallbackOverrides.headers = overrides.headers;\n if (isString(overrides.postData))\n this._fallbackOverrides.postDataBuffer = Buffer.from(overrides.postData, "utf-8");\n else if (overrides.postData instanceof Buffer)\n this._fallbackOverrides.postDataBuffer = overrides.postData;\n else if (overrides.postData)\n this._fallbackOverrides.postDataBuffer = Buffer.from(\n JSON.stringify(overrides.postData),\n "utf-8"\n );\n }\n _fallbackOverridesForContinue() {\n return this._fallbackOverrides;\n }\n _targetClosedScope() {\n return this.serviceWorker()?._closedScope || this._safePage()?._closedOrCrashedScope || new LongStandingScope();\n }\n };\n var Route = class extends ChannelOwner {\n _handlingPromise = null;\n _context;\n _didThrow = false;\n static from(route) {\n return route._object;\n }\n constructor(parent, type, guid, initializer) {\n super(parent, type, guid, initializer);\n }\n request() {\n return Request.from(this._initializer.request);\n }\n async _raceWithTargetClose(promise) {\n return await this.request()._targetClosedScope().safeRace(promise);\n }\n async _startHandling() {\n this._handlingPromise = new ManualPromise();\n return await this._handlingPromise;\n }\n async fallback(options = {}) {\n this._checkNotHandled();\n this.request()._applyFallbackOverrides(options);\n this._reportHandled(false);\n }\n async abort(errorCode) {\n await this._handleRoute(async () => {\n await this._raceWithTargetClose(this._channel.abort({ errorCode }));\n });\n }\n async _redirectNavigationRequest(url) {\n await this._handleRoute(async () => {\n await this._raceWithTargetClose(this._channel.redirectNavigationRequest({ url }));\n });\n }\n async fetch(options = {}) {\n return await this._wrapApiCall(async () => {\n return await this._context.request._innerFetch({\n request: this.request(),\n data: options.postData,\n ...options\n });\n });\n }\n async fulfill(options = {}) {\n await this._handleRoute(async () => {\n await this._innerFulfill(options);\n });\n }\n async _handleRoute(callback) {\n this._checkNotHandled();\n try {\n await callback();\n this._reportHandled(true);\n } catch (e) {\n this._didThrow = true;\n throw e;\n }\n }\n async _innerFulfill(options = {}) {\n let fetchResponseUid;\n let { status: statusOption, headers: headersOption, body } = options;\n if (options.json !== void 0) {\n assert(options.body === void 0, "Can specify either body or json parameters");\n body = JSON.stringify(options.json);\n }\n if (options.response instanceof APIResponse) {\n statusOption ??= options.response.status();\n headersOption ??= options.response.headers();\n if (body === void 0 && options.path === void 0) {\n if (options.response._request._connection === this._connection)\n fetchResponseUid = options.response._fetchUid();\n else body = await options.response.body();\n }\n }\n let isBase64 = false;\n let length = 0;\n if (options.path) {\n const buffer = await this._platform.fs().promises.readFile(options.path);\n body = buffer.toString("base64");\n isBase64 = true;\n length = buffer.length;\n } else if (isString(body)) {\n isBase64 = false;\n length = Buffer.byteLength(body);\n } else if (body) {\n length = body.length;\n body = body.toString("base64");\n isBase64 = true;\n }\n const headers = {};\n for (const header of Object.keys(headersOption || {}))\n headers[header.toLowerCase()] = String(headersOption[header]);\n if (options.contentType) headers["content-type"] = String(options.contentType);\n else if (options.json) headers["content-type"] = "application/json";\n else if (options.path)\n headers["content-type"] = getMimeTypeForPath(options.path) || "application/octet-stream";\n if (length && !("content-length" in headers)) headers["content-length"] = String(length);\n await this._raceWithTargetClose(\n this._channel.fulfill({\n status: statusOption || 200,\n headers: headersObjectToArray(headers),\n body,\n isBase64,\n fetchResponseUid\n })\n );\n }\n async continue(options = {}) {\n await this._handleRoute(async () => {\n this.request()._applyFallbackOverrides(options);\n await this._innerContinue(\n false\n /* isFallback */\n );\n });\n }\n _checkNotHandled() {\n if (!this._handlingPromise) throw new Error("Route is already handled!");\n }\n _reportHandled(done) {\n const chain = this._handlingPromise;\n this._handlingPromise = null;\n chain.resolve(done);\n }\n async _innerContinue(isFallback) {\n const options = this.request()._fallbackOverridesForContinue();\n return await this._raceWithTargetClose(\n this._channel.continue({\n url: options.url,\n method: options.method,\n headers: options.headers ? headersObjectToArray(options.headers) : void 0,\n postData: options.postDataBuffer,\n isFallback\n })\n );\n }\n };\n var WebSocketRoute = class extends ChannelOwner {\n static from(route) {\n return route._object;\n }\n _onPageMessage;\n _onPageClose;\n _onServerMessage;\n _onServerClose;\n _server;\n _connected = false;\n constructor(parent, type, guid, initializer) {\n super(parent, type, guid, initializer);\n this._server = {\n onMessage: (handler) => {\n this._onServerMessage = handler;\n },\n onClose: (handler) => {\n this._onServerClose = handler;\n },\n connectToServer: () => {\n throw new Error(`connectToServer must be called on the page-side WebSocketRoute`);\n },\n url: () => {\n return this._initializer.url;\n },\n close: async (options = {}) => {\n await this._channel.closeServer({ ...options, wasClean: true }).catch(() => {\n });\n },\n send: (message) => {\n if (isString(message))\n this._channel.sendToServer({ message, isBase64: false }).catch(() => {\n });\n else\n this._channel.sendToServer({ message: message.toString("base64"), isBase64: true }).catch(() => {\n });\n },\n async [Symbol.asyncDispose]() {\n await this.close();\n }\n };\n this._channel.on("messageFromPage", ({ message, isBase64 }) => {\n if (this._onPageMessage)\n this._onPageMessage(isBase64 ? Buffer.from(message, "base64") : message);\n else if (this._connected) this._channel.sendToServer({ message, isBase64 }).catch(() => {\n });\n });\n this._channel.on("messageFromServer", ({ message, isBase64 }) => {\n if (this._onServerMessage)\n this._onServerMessage(isBase64 ? Buffer.from(message, "base64") : message);\n else this._channel.sendToPage({ message, isBase64 }).catch(() => {\n });\n });\n this._channel.on("closePage", ({ code, reason, wasClean }) => {\n if (this._onPageClose) this._onPageClose(code, reason);\n else this._channel.closeServer({ code, reason, wasClean }).catch(() => {\n });\n });\n this._channel.on("closeServer", ({ code, reason, wasClean }) => {\n if (this._onServerClose) this._onServerClose(code, reason);\n else this._channel.closePage({ code, reason, wasClean }).catch(() => {\n });\n });\n }\n url() {\n return this._initializer.url;\n }\n async close(options = {}) {\n await this._channel.closePage({ ...options, wasClean: true }).catch(() => {\n });\n }\n connectToServer() {\n if (this._connected) throw new Error("Already connected to the server");\n this._connected = true;\n this._channel.connect().catch(() => {\n });\n return this._server;\n }\n send(message) {\n if (isString(message)) this._channel.sendToPage({ message, isBase64: false }).catch(() => {\n });\n else\n this._channel.sendToPage({ message: message.toString("base64"), isBase64: true }).catch(() => {\n });\n }\n onMessage(handler) {\n this._onPageMessage = handler;\n }\n onClose(handler) {\n this._onPageClose = handler;\n }\n async [Symbol.asyncDispose]() {\n await this.close();\n }\n async _afterHandle() {\n if (this._connected) return;\n await this._channel.ensureOpened().catch(() => {\n });\n }\n };\n var WebSocketRouteHandler = class {\n _baseURL;\n url;\n handler;\n constructor(baseURL, url, handler) {\n this._baseURL = baseURL;\n this.url = url;\n this.handler = handler;\n }\n static prepareInterceptionPatterns(handlers) {\n const patterns = [];\n let all = false;\n for (const handler of handlers) {\n const serialized = serializeURLMatch(handler.url);\n if (serialized) patterns.push(serialized);\n else all = true;\n }\n if (all) return [{ glob: "**/*" }];\n return patterns;\n }\n matches(wsURL) {\n return urlMatches(this._baseURL, wsURL, this.url, true);\n }\n async handle(webSocketRoute) {\n const handler = this.handler;\n await handler(webSocketRoute);\n await webSocketRoute._afterHandle();\n }\n };\n var Response = class _Response extends ChannelOwner {\n _provisionalHeaders;\n _actualHeadersPromise;\n _request;\n _finishedPromise = new ManualPromise();\n static from(response) {\n return response._object;\n }\n static fromNullable(response) {\n return response ? _Response.from(response) : null;\n }\n constructor(parent, type, guid, initializer) {\n super(parent, type, guid, initializer);\n this._provisionalHeaders = new RawHeaders(initializer.headers);\n this._request = Request.from(this._initializer.request);\n this._request._response = this;\n Object.assign(this._request._timing, this._initializer.timing);\n }\n url() {\n return this._initializer.url;\n }\n ok() {\n return this._initializer.status === 0 || this._initializer.status >= 200 && this._initializer.status <= 299;\n }\n status() {\n return this._initializer.status;\n }\n statusText() {\n return this._initializer.statusText;\n }\n fromServiceWorker() {\n return this._initializer.fromServiceWorker;\n }\n /**\n * @deprecated\n */\n headers() {\n return this._provisionalHeaders.headers();\n }\n async _actualHeaders() {\n if (!this._actualHeadersPromise) {\n this._actualHeadersPromise = (async () => {\n return new RawHeaders((await this._channel.rawResponseHeaders()).headers);\n })();\n }\n return await this._actualHeadersPromise;\n }\n async allHeaders() {\n return (await this._actualHeaders()).headers();\n }\n async headersArray() {\n return (await this._actualHeaders()).headersArray().slice();\n }\n async headerValue(name) {\n return (await this._actualHeaders()).get(name);\n }\n async headerValues(name) {\n return (await this._actualHeaders()).getAll(name);\n }\n async finished() {\n return await this.request()._targetClosedScope().race(this._finishedPromise);\n }\n async body() {\n return (await this._channel.body()).binary;\n }\n async text() {\n const content = await this.body();\n return content.toString("utf8");\n }\n async json() {\n const content = await this.text();\n return JSON.parse(content);\n }\n request() {\n return this._request;\n }\n frame() {\n return this._request.frame();\n }\n async serverAddr() {\n return (await this._channel.serverAddr()).value || null;\n }\n async securityDetails() {\n return (await this._channel.securityDetails()).value || null;\n }\n async httpVersion() {\n return (await this._channel.httpVersion()).value;\n }\n };\n var WebSocket = class extends ChannelOwner {\n _page;\n _isClosed;\n static from(webSocket) {\n return webSocket._object;\n }\n constructor(parent, type, guid, initializer) {\n super(parent, type, guid, initializer);\n this._isClosed = false;\n this._page = parent;\n this._channel.on("frameSent", (event) => {\n if (event.opcode === 1) this.emit(Events.WebSocket.FrameSent, { payload: event.data });\n else if (event.opcode === 2)\n this.emit(Events.WebSocket.FrameSent, { payload: Buffer.from(event.data, "base64") });\n });\n this._channel.on("frameReceived", (event) => {\n if (event.opcode === 1) this.emit(Events.WebSocket.FrameReceived, { payload: event.data });\n else if (event.opcode === 2)\n this.emit(Events.WebSocket.FrameReceived, { payload: Buffer.from(event.data, "base64") });\n });\n this._channel.on("socketError", ({ error }) => this.emit(Events.WebSocket.Error, error));\n this._channel.on("close", () => {\n this._isClosed = true;\n this.emit(Events.WebSocket.Close, this);\n });\n }\n url() {\n return this._initializer.url;\n }\n isClosed() {\n return this._isClosed;\n }\n async waitForEvent(event, optionsOrPredicate = {}) {\n return await this._wrapApiCall(async () => {\n const timeout = this._page._timeoutSettings.timeout(\n typeof optionsOrPredicate === "function" ? {} : optionsOrPredicate\n );\n const predicate = typeof optionsOrPredicate === "function" ? optionsOrPredicate : optionsOrPredicate.predicate;\n const waiter = Waiter.createForEvent(this, event);\n waiter.rejectOnTimeout(\n timeout,\n `Timeout ${timeout}ms exceeded while waiting for event "${event}"`\n );\n if (event !== Events.WebSocket.Error)\n waiter.rejectOnEvent(this, Events.WebSocket.Error, new Error("Socket error"));\n if (event !== Events.WebSocket.Close)\n waiter.rejectOnEvent(this, Events.WebSocket.Close, new Error("Socket closed"));\n waiter.rejectOnEvent(this._page, Events.Page.Close, () => this._page._closeErrorWithReason());\n const result = await waiter.waitForEvent(this, event, predicate);\n waiter.dispose();\n return result;\n });\n }\n };\n function validateHeaders(headers) {\n for (const key of Object.keys(headers)) {\n const value = headers[key];\n if (!Object.is(value, void 0) && !isString(value))\n throw new Error(\n `Expected value of header "${key}" to be String, but "${typeof value}" is found.`\n );\n }\n }\n var RouteHandler = class {\n handledCount = 0;\n _baseURL;\n _times;\n url;\n handler;\n _ignoreException = false;\n _activeInvocations = /* @__PURE__ */ new Set();\n _savedZone;\n constructor(platform, baseURL, url, handler, times = Number.MAX_SAFE_INTEGER) {\n this._baseURL = baseURL;\n this._times = times;\n this.url = url;\n this.handler = handler;\n this._savedZone = platform.zones.current().pop();\n }\n static prepareInterceptionPatterns(handlers) {\n const patterns = [];\n let all = false;\n for (const handler of handlers) {\n const serialized = serializeURLMatch(handler.url);\n if (serialized) patterns.push(serialized);\n else all = true;\n }\n if (all) return [{ glob: "**/*" }];\n return patterns;\n }\n matches(requestURL) {\n return urlMatches(this._baseURL, requestURL, this.url);\n }\n async handle(route) {\n return await this._savedZone.run(async () => this._handleImpl(route));\n }\n async _handleImpl(route) {\n const handlerInvocation = { complete: new ManualPromise(), route };\n this._activeInvocations.add(handlerInvocation);\n try {\n return await this._handleInternal(route);\n } catch (e) {\n if (this._ignoreException) return false;\n if (isTargetClosedError(e)) {\n rewriteErrorMessage(\n e,\n `"${e.message}" while running route callback.\nConsider awaiting \\`await page.unrouteAll({ behavior: \'ignoreErrors\' })\\`\nbefore the end of the test to ignore remaining routes in flight.`\n );\n }\n throw e;\n } finally {\n handlerInvocation.complete.resolve();\n this._activeInvocations.delete(handlerInvocation);\n }\n }\n async stop(behavior) {\n if (behavior === "ignoreErrors") {\n this._ignoreException = true;\n } else {\n const promises = [];\n for (const activation of this._activeInvocations) {\n if (!activation.route._didThrow) promises.push(activation.complete);\n }\n await Promise.all(promises);\n }\n }\n async _handleInternal(route) {\n ++this.handledCount;\n const handledPromise = route._startHandling();\n const handler = this.handler;\n const [handled] = await Promise.all([handledPromise, handler(route, route.request())]);\n return handled;\n }\n willExpire() {\n return this.handledCount + 1 >= this._times;\n }\n };\n var RawHeaders = class _RawHeaders {\n _headersArray;\n _headersMap = new MultiMap();\n static _fromHeadersObjectLossy(headers) {\n const headersArray = Object.entries(headers).map(([name, value]) => ({\n name,\n value\n })).filter((header) => header.value !== void 0);\n return new _RawHeaders(headersArray);\n }\n constructor(headers) {\n this._headersArray = headers;\n for (const header of headers) this._headersMap.set(header.name.toLowerCase(), header.value);\n }\n get(name) {\n const values = this.getAll(name);\n if (!values || !values.length) return null;\n return values.join(name.toLowerCase() === "set-cookie" ? "\\n" : ", ");\n }\n getAll(name) {\n return [...this._headersMap.get(name.toLowerCase())];\n }\n headers() {\n const result = {};\n for (const name of this._headersMap.keys()) result[name] = this.get(name);\n return result;\n }\n headersArray() {\n return this._headersArray;\n }\n };\n\n // src/sandbox/forked-client/src/client/types.ts\n var kLifecycleEvents = /* @__PURE__ */ new Set([\n "load",\n "domcontentloaded",\n "networkidle",\n "commit"\n ]);\n\n // src/sandbox/forked-client/src/client/frame.ts\n var Frame = class _Frame extends ChannelOwner {\n _eventEmitter;\n _loadStates;\n _parentFrame = null;\n _url = "";\n _name = "";\n _detached = false;\n _childFrames = /* @__PURE__ */ new Set();\n _page;\n static from(frame) {\n return frame._object;\n }\n static fromNullable(frame) {\n return frame ? _Frame.from(frame) : null;\n }\n constructor(parent, type, guid, initializer) {\n super(parent, type, guid, initializer);\n this._eventEmitter = new EventEmitter(parent._platform);\n this._eventEmitter.setMaxListeners(0);\n this._parentFrame = _Frame.fromNullable(initializer.parentFrame);\n if (this._parentFrame) this._parentFrame._childFrames.add(this);\n this._name = initializer.name;\n this._url = initializer.url;\n this._loadStates = new Set(initializer.loadStates);\n this._channel.on("loadstate", (event) => {\n if (event.add) {\n this._loadStates.add(event.add);\n this._eventEmitter.emit("loadstate", event.add);\n }\n if (event.remove) this._loadStates.delete(event.remove);\n if (!this._parentFrame && event.add === "load" && this._page)\n this._page.emit(Events.Page.Load, this._page);\n if (!this._parentFrame && event.add === "domcontentloaded" && this._page)\n this._page.emit(Events.Page.DOMContentLoaded, this._page);\n });\n this._channel.on("navigated", (event) => {\n this._url = event.url;\n this._name = event.name;\n this._eventEmitter.emit("navigated", event);\n if (!event.error && this._page) this._page.emit(Events.Page.FrameNavigated, this);\n });\n }\n page() {\n return this._page;\n }\n _timeout(options) {\n const timeoutSettings = this._page?._timeoutSettings || new TimeoutSettings(this._platform);\n return timeoutSettings.timeout(options || {});\n }\n _navigationTimeout(options) {\n const timeoutSettings = this._page?._timeoutSettings || new TimeoutSettings(this._platform);\n return timeoutSettings.navigationTimeout(options || {});\n }\n async goto(url, options = {}) {\n const waitUntil = verifyLoadState(\n "waitUntil",\n options.waitUntil === void 0 ? "load" : options.waitUntil\n );\n return Response.fromNullable(\n (await this._channel.goto({\n url,\n ...options,\n waitUntil,\n timeout: this._navigationTimeout(options)\n })).response\n );\n }\n _setupNavigationWaiter(options) {\n const waiter = new Waiter(this._page, "");\n if (this._page.isClosed()) waiter.rejectImmediately(this._page._closeErrorWithReason());\n waiter.rejectOnEvent(this._page, Events.Page.Close, () => this._page._closeErrorWithReason());\n waiter.rejectOnEvent(\n this._page,\n Events.Page.Crash,\n new Error("Navigation failed because page crashed!")\n );\n waiter.rejectOnEvent(\n this._page,\n Events.Page.FrameDetached,\n new Error("Navigating frame was detached!"),\n (frame) => frame === this\n );\n const timeout = this._page._timeoutSettings.navigationTimeout(options);\n waiter.rejectOnTimeout(timeout, `Timeout ${timeout}ms exceeded.`);\n return waiter;\n }\n async waitForNavigation(options = {}) {\n return await this._page._wrapApiCall(\n async () => {\n const waitUntil = verifyLoadState(\n "waitUntil",\n options.waitUntil === void 0 ? "load" : options.waitUntil\n );\n const waiter = this._setupNavigationWaiter(options);\n const toUrl = typeof options.url === "string" ? ` to "${options.url}"` : "";\n waiter.log(`waiting for navigation${toUrl} until "${waitUntil}"`);\n const navigatedEvent = await waiter.waitForEvent(\n this._eventEmitter,\n "navigated",\n (event) => {\n if (event.error) return true;\n waiter.log(` navigated to "${event.url}"`);\n return urlMatches(this._page?.context()._options.baseURL, event.url, options.url);\n }\n );\n if (navigatedEvent.error) {\n const e = new Error(navigatedEvent.error);\n e.stack = "";\n await waiter.waitForPromise(Promise.reject(e));\n }\n if (!this._loadStates.has(waitUntil)) {\n await waiter.waitForEvent(this._eventEmitter, "loadstate", (s) => {\n waiter.log(` "${s}" event fired`);\n return s === waitUntil;\n });\n }\n const request = navigatedEvent.newDocument ? Request.fromNullable(navigatedEvent.newDocument.request) : null;\n const response = request ? await waiter.waitForPromise(request._finalRequest()._internalResponse()) : null;\n waiter.dispose();\n return response;\n },\n { title: "Wait for navigation" }\n );\n }\n async waitForLoadState(state = "load", options = {}) {\n state = verifyLoadState("state", state);\n return await this._page._wrapApiCall(\n async () => {\n const waiter = this._setupNavigationWaiter(options);\n if (this._loadStates.has(state)) {\n waiter.log(` not waiting, "${state}" event already fired`);\n } else {\n await waiter.waitForEvent(this._eventEmitter, "loadstate", (s) => {\n waiter.log(` "${s}" event fired`);\n return s === state;\n });\n }\n waiter.dispose();\n },\n { title: `Wait for load state "${state}"` }\n );\n }\n async waitForURL(url, options = {}) {\n if (urlMatches(this._page?.context()._options.baseURL, this.url(), url))\n return await this.waitForLoadState(options.waitUntil, options);\n await this.waitForNavigation({ url, ...options });\n }\n async frameElement() {\n return ElementHandle.from((await this._channel.frameElement()).element);\n }\n async evaluateHandle(pageFunction, arg) {\n assertMaxArguments(arguments.length, 2);\n const result = await this._channel.evaluateExpressionHandle({\n expression: String(pageFunction),\n isFunction: typeof pageFunction === "function",\n arg: serializeArgument(arg)\n });\n return JSHandle.from(result.handle);\n }\n async evaluate(pageFunction, arg) {\n assertMaxArguments(arguments.length, 2);\n const result = await this._channel.evaluateExpression({\n expression: String(pageFunction),\n isFunction: typeof pageFunction === "function",\n arg: serializeArgument(arg)\n });\n return parseResult(result.value);\n }\n async _evaluateExposeUtilityScript(pageFunction, arg) {\n assertMaxArguments(arguments.length, 2);\n const result = await this._channel.evaluateExpression({\n expression: String(pageFunction),\n isFunction: typeof pageFunction === "function",\n arg: serializeArgument(arg)\n });\n return parseResult(result.value);\n }\n async $(selector, options) {\n const result = await this._channel.querySelector({ selector, ...options });\n return ElementHandle.fromNullable(result.element);\n }\n async waitForSelector(selector, options = {}) {\n if (options.visibility)\n throw new Error("options.visibility is not supported, did you mean options.state?");\n if (options.waitFor && options.waitFor !== "visible")\n throw new Error("options.waitFor is not supported, did you mean options.state?");\n const result = await this._channel.waitForSelector({\n selector,\n ...options,\n timeout: this._timeout(options)\n });\n return ElementHandle.fromNullable(result.element);\n }\n async dispatchEvent(selector, type, eventInit, options = {}) {\n await this._channel.dispatchEvent({\n selector,\n type,\n eventInit: serializeArgument(eventInit),\n ...options,\n timeout: this._timeout(options)\n });\n }\n async $eval(selector, pageFunction, arg) {\n assertMaxArguments(arguments.length, 3);\n const result = await this._channel.evalOnSelector({\n selector,\n expression: String(pageFunction),\n isFunction: typeof pageFunction === "function",\n arg: serializeArgument(arg)\n });\n return parseResult(result.value);\n }\n async $$eval(selector, pageFunction, arg) {\n assertMaxArguments(arguments.length, 3);\n const result = await this._channel.evalOnSelectorAll({\n selector,\n expression: String(pageFunction),\n isFunction: typeof pageFunction === "function",\n arg: serializeArgument(arg)\n });\n return parseResult(result.value);\n }\n async $$(selector) {\n const result = await this._channel.querySelectorAll({ selector });\n return result.elements.map(\n (e) => ElementHandle.from(e)\n );\n }\n async _queryCount(selector, options) {\n return (await this._channel.queryCount({ selector, ...options })).value;\n }\n async content() {\n return (await this._channel.content()).value;\n }\n async setContent(html, options = {}) {\n const waitUntil = verifyLoadState(\n "waitUntil",\n options.waitUntil === void 0 ? "load" : options.waitUntil\n );\n await this._channel.setContent({\n html,\n ...options,\n waitUntil,\n timeout: this._navigationTimeout(options)\n });\n }\n name() {\n return this._name || "";\n }\n url() {\n return this._url;\n }\n parentFrame() {\n return this._parentFrame;\n }\n childFrames() {\n return Array.from(this._childFrames);\n }\n isDetached() {\n return this._detached;\n }\n async addScriptTag(options = {}) {\n const copy = { ...options };\n if (copy.path) {\n copy.content = (await this._platform.fs().promises.readFile(copy.path)).toString();\n copy.content = addSourceUrlToScript(copy.content, copy.path);\n }\n return ElementHandle.from((await this._channel.addScriptTag({ ...copy })).element);\n }\n async addStyleTag(options = {}) {\n const copy = { ...options };\n if (copy.path) {\n copy.content = (await this._platform.fs().promises.readFile(copy.path)).toString();\n copy.content += "/*# sourceURL=" + copy.path.replace(/\\n/g, "") + "*/";\n }\n return ElementHandle.from((await this._channel.addStyleTag({ ...copy })).element);\n }\n async click(selector, options = {}) {\n return await this._channel.click({ selector, ...options, timeout: this._timeout(options) });\n }\n async dblclick(selector, options = {}) {\n return await this._channel.dblclick({ selector, ...options, timeout: this._timeout(options) });\n }\n async dragAndDrop(source, target, options = {}) {\n return await this._channel.dragAndDrop({\n source,\n target,\n ...options,\n timeout: this._timeout(options)\n });\n }\n async tap(selector, options = {}) {\n return await this._channel.tap({ selector, ...options, timeout: this._timeout(options) });\n }\n async fill(selector, value, options = {}) {\n return await this._channel.fill({\n selector,\n value,\n ...options,\n timeout: this._timeout(options)\n });\n }\n async _highlight(selector) {\n return await this._channel.highlight({ selector });\n }\n locator(selector, options) {\n return new Locator(this, selector, options);\n }\n getByTestId(testId) {\n return this.locator(getByTestIdSelector(testIdAttributeName(), testId));\n }\n getByAltText(text, options) {\n return this.locator(getByAltTextSelector(text, options));\n }\n getByLabel(text, options) {\n return this.locator(getByLabelSelector(text, options));\n }\n getByPlaceholder(text, options) {\n return this.locator(getByPlaceholderSelector(text, options));\n }\n getByText(text, options) {\n return this.locator(getByTextSelector(text, options));\n }\n getByTitle(text, options) {\n return this.locator(getByTitleSelector(text, options));\n }\n getByRole(role, options = {}) {\n return this.locator(getByRoleSelector(role, options));\n }\n frameLocator(selector) {\n return new FrameLocator(this, selector);\n }\n async focus(selector, options = {}) {\n await this._channel.focus({ selector, ...options, timeout: this._timeout(options) });\n }\n async textContent(selector, options = {}) {\n const value = (await this._channel.textContent({ selector, ...options, timeout: this._timeout(options) })).value;\n return value === void 0 ? null : value;\n }\n async innerText(selector, options = {}) {\n return (await this._channel.innerText({ selector, ...options, timeout: this._timeout(options) })).value;\n }\n async innerHTML(selector, options = {}) {\n return (await this._channel.innerHTML({ selector, ...options, timeout: this._timeout(options) })).value;\n }\n async getAttribute(selector, name, options = {}) {\n const value = (await this._channel.getAttribute({\n selector,\n name,\n ...options,\n timeout: this._timeout(options)\n })).value;\n return value === void 0 ? null : value;\n }\n async inputValue(selector, options = {}) {\n return (await this._channel.inputValue({ selector, ...options, timeout: this._timeout(options) })).value;\n }\n async isChecked(selector, options = {}) {\n return (await this._channel.isChecked({ selector, ...options, timeout: this._timeout(options) })).value;\n }\n async isDisabled(selector, options = {}) {\n return (await this._channel.isDisabled({ selector, ...options, timeout: this._timeout(options) })).value;\n }\n async isEditable(selector, options = {}) {\n return (await this._channel.isEditable({ selector, ...options, timeout: this._timeout(options) })).value;\n }\n async isEnabled(selector, options = {}) {\n return (await this._channel.isEnabled({ selector, ...options, timeout: this._timeout(options) })).value;\n }\n async isHidden(selector, options = {}) {\n return (await this._channel.isHidden({ selector, ...options })).value;\n }\n async isVisible(selector, options = {}) {\n return (await this._channel.isVisible({ selector, ...options })).value;\n }\n async hover(selector, options = {}) {\n await this._channel.hover({ selector, ...options, timeout: this._timeout(options) });\n }\n async selectOption(selector, values, options = {}) {\n return (await this._channel.selectOption({\n selector,\n ...convertSelectOptionValues(values),\n ...options,\n timeout: this._timeout(options)\n })).values;\n }\n async setInputFiles(selector, files, options = {}) {\n const converted = await convertInputFiles(this._platform, files, this.page().context());\n await this._channel.setInputFiles({\n selector,\n ...converted,\n ...options,\n timeout: this._timeout(options)\n });\n }\n async type(selector, text, options = {}) {\n await this._channel.type({ selector, text, ...options, timeout: this._timeout(options) });\n }\n async press(selector, key, options = {}) {\n await this._channel.press({ selector, key, ...options, timeout: this._timeout(options) });\n }\n async check(selector, options = {}) {\n await this._channel.check({ selector, ...options, timeout: this._timeout(options) });\n }\n async uncheck(selector, options = {}) {\n await this._channel.uncheck({ selector, ...options, timeout: this._timeout(options) });\n }\n async setChecked(selector, checked, options) {\n if (checked) await this.check(selector, options);\n else await this.uncheck(selector, options);\n }\n async waitForTimeout(timeout) {\n await this._channel.waitForTimeout({ waitTimeout: timeout });\n }\n async waitForFunction(pageFunction, arg, options = {}) {\n if (typeof options.polling === "string")\n assert(options.polling === "raf", "Unknown polling option: " + options.polling);\n const result = await this._channel.waitForFunction({\n ...options,\n pollingInterval: options.polling === "raf" ? void 0 : options.polling,\n expression: String(pageFunction),\n isFunction: typeof pageFunction === "function",\n arg: serializeArgument(arg),\n timeout: this._timeout(options)\n });\n return JSHandle.from(result.handle);\n }\n async title() {\n return (await this._channel.title()).value;\n }\n async _expect(expression, options) {\n const params = { expression, ...options, isNot: !!options.isNot };\n params.expectedValue = serializeArgument(options.expectedValue);\n const result = await this._channel.expect(params);\n if (result.received !== void 0) result.received = parseResult(result.received);\n return result;\n }\n };\n function verifyLoadState(name, waitUntil) {\n if (waitUntil === "networkidle0") waitUntil = "networkidle";\n if (!kLifecycleEvents.has(waitUntil))\n throw new Error(`${name}: expected one of (load|domcontentloaded|networkidle|commit)`);\n return waitUntil;\n }\n\n // src/sandbox/forked-client/src/client/fileUtils.ts\n var fileUploadSizeLimit = 50 * 1024 * 1024;\n async function mkdirIfNeeded() {\n }\n async function writeTempFile(path, data) {\n const writer = globalThis.writeFile;\n if (typeof writer !== "function")\n throw new Error("writeFile() is not available in the QuickJS sandbox");\n return await writer(path, data);\n }\n\n // src/sandbox/forked-client/src/client/writableStream.ts\n var WritableStream = class extends ChannelOwner {\n static from(channel) {\n return channel?._object;\n }\n stream() {\n throw new Error("Writable streams are not available in the QuickJS sandbox");\n }\n };\n\n // src/sandbox/forked-client/src/client/elementHandle.ts\n var ElementHandle = class _ElementHandle extends JSHandle {\n _frame;\n _elementChannel;\n static from(handle) {\n return handle._object;\n }\n static fromNullable(handle) {\n return handle ? _ElementHandle.from(handle) : null;\n }\n constructor(parent, type, guid, initializer) {\n super(parent, type, guid, initializer);\n this._frame = parent;\n this._elementChannel = this._channel;\n }\n asElement() {\n return this;\n }\n async ownerFrame() {\n return Frame.fromNullable((await this._elementChannel.ownerFrame()).frame);\n }\n async contentFrame() {\n return Frame.fromNullable((await this._elementChannel.contentFrame()).frame);\n }\n async getAttribute(name) {\n const value = (await this._elementChannel.getAttribute({ name })).value;\n return value === void 0 ? null : value;\n }\n async inputValue() {\n return (await this._elementChannel.inputValue()).value;\n }\n async textContent() {\n const value = (await this._elementChannel.textContent()).value;\n return value === void 0 ? null : value;\n }\n async innerText() {\n return (await this._elementChannel.innerText()).value;\n }\n async innerHTML() {\n return (await this._elementChannel.innerHTML()).value;\n }\n async isChecked() {\n return (await this._elementChannel.isChecked()).value;\n }\n async isDisabled() {\n return (await this._elementChannel.isDisabled()).value;\n }\n async isEditable() {\n return (await this._elementChannel.isEditable()).value;\n }\n async isEnabled() {\n return (await this._elementChannel.isEnabled()).value;\n }\n async isHidden() {\n return (await this._elementChannel.isHidden()).value;\n }\n async isVisible() {\n return (await this._elementChannel.isVisible()).value;\n }\n async dispatchEvent(type, eventInit = {}) {\n await this._elementChannel.dispatchEvent({ type, eventInit: serializeArgument(eventInit) });\n }\n async scrollIntoViewIfNeeded(options = {}) {\n await this._elementChannel.scrollIntoViewIfNeeded({\n ...options,\n timeout: this._frame._timeout(options)\n });\n }\n async hover(options = {}) {\n await this._elementChannel.hover({ ...options, timeout: this._frame._timeout(options) });\n }\n async click(options = {}) {\n return await this._elementChannel.click({ ...options, timeout: this._frame._timeout(options) });\n }\n async dblclick(options = {}) {\n return await this._elementChannel.dblclick({\n ...options,\n timeout: this._frame._timeout(options)\n });\n }\n async tap(options = {}) {\n return await this._elementChannel.tap({ ...options, timeout: this._frame._timeout(options) });\n }\n async selectOption(values, options = {}) {\n const result = await this._elementChannel.selectOption({\n ...convertSelectOptionValues(values),\n ...options,\n timeout: this._frame._timeout(options)\n });\n return result.values;\n }\n async fill(value, options = {}) {\n return await this._elementChannel.fill({\n value,\n ...options,\n timeout: this._frame._timeout(options)\n });\n }\n async selectText(options = {}) {\n await this._elementChannel.selectText({ ...options, timeout: this._frame._timeout(options) });\n }\n async setInputFiles(files, options = {}) {\n const frame = await this.ownerFrame();\n if (!frame) throw new Error("Cannot set input files to detached element");\n const converted = await convertInputFiles(this._platform, files, frame.page().context());\n await this._elementChannel.setInputFiles({\n ...converted,\n ...options,\n timeout: this._frame._timeout(options)\n });\n }\n async focus() {\n await this._elementChannel.focus();\n }\n async type(text, options = {}) {\n await this._elementChannel.type({ text, ...options, timeout: this._frame._timeout(options) });\n }\n async press(key, options = {}) {\n await this._elementChannel.press({ key, ...options, timeout: this._frame._timeout(options) });\n }\n async check(options = {}) {\n return await this._elementChannel.check({ ...options, timeout: this._frame._timeout(options) });\n }\n async uncheck(options = {}) {\n return await this._elementChannel.uncheck({\n ...options,\n timeout: this._frame._timeout(options)\n });\n }\n async setChecked(checked, options) {\n if (checked) await this.check(options);\n else await this.uncheck(options);\n }\n async boundingBox() {\n const value = (await this._elementChannel.boundingBox()).value;\n return value === void 0 ? null : value;\n }\n async screenshot(options = {}) {\n const mask = options.mask;\n const copy = {\n ...options,\n path: void 0,\n mask: void 0,\n timeout: this._frame._timeout(options)\n };\n if (!copy.type) copy.type = determineScreenshotType(options);\n if (mask) {\n copy.mask = mask.map((locator) => ({\n frame: locator._frame._channel,\n selector: locator._selector\n }));\n }\n const result = await this._elementChannel.screenshot(copy);\n if (options.path) {\n options.path = await writeTempFile(options.path, result.binary);\n }\n return result.binary;\n }\n async $(selector) {\n return _ElementHandle.fromNullable(\n (await this._elementChannel.querySelector({ selector })).element\n );\n }\n async $$(selector) {\n const result = await this._elementChannel.querySelectorAll({ selector });\n return result.elements.map(\n (h) => _ElementHandle.from(h)\n );\n }\n async $eval(selector, pageFunction, arg) {\n const result = await this._elementChannel.evalOnSelector({\n selector,\n expression: String(pageFunction),\n isFunction: typeof pageFunction === "function",\n arg: serializeArgument(arg)\n });\n return parseResult(result.value);\n }\n async $$eval(selector, pageFunction, arg) {\n const result = await this._elementChannel.evalOnSelectorAll({\n selector,\n expression: String(pageFunction),\n isFunction: typeof pageFunction === "function",\n arg: serializeArgument(arg)\n });\n return parseResult(result.value);\n }\n async waitForElementState(state, options = {}) {\n return await this._elementChannel.waitForElementState({\n state,\n ...options,\n timeout: this._frame._timeout(options)\n });\n }\n async waitForSelector(selector, options = {}) {\n const result = await this._elementChannel.waitForSelector({\n selector,\n ...options,\n timeout: this._frame._timeout(options)\n });\n return _ElementHandle.fromNullable(result.element);\n }\n };\n function convertSelectOptionValues(values) {\n if (values === null) return {};\n if (!Array.isArray(values)) values = [values];\n if (!values.length) return {};\n for (let i = 0; i < values.length; i++)\n assert(values[i] !== null, `options[${i}]: expected object, got null`);\n if (values[0] instanceof ElementHandle)\n return { elements: values.map((v) => v._elementChannel) };\n if (isString(values[0]))\n return { options: values.map((valueOrLabel) => ({ valueOrLabel })) };\n return { options: values };\n }\n function filePayloadExceedsSizeLimit(payloads) {\n return payloads.reduce((size, item) => size + (item.buffer ? item.buffer.byteLength : 0), 0) >= fileUploadSizeLimit;\n }\n async function resolvePathsAndDirectoryForInputFiles(platform, items) {\n let localPaths;\n let localDirectory;\n for (const item of items) {\n const stat = await platform.fs().promises.stat(item);\n if (stat.isDirectory()) {\n if (localDirectory) throw new Error("Multiple directories are not supported");\n localDirectory = platform.path().resolve(item);\n } else {\n localPaths ??= [];\n localPaths.push(platform.path().resolve(item));\n }\n }\n if (localPaths?.length && localDirectory)\n throw new Error("File paths must be all files or a single directory");\n return [localPaths, localDirectory];\n }\n async function convertInputFiles(platform, files, context) {\n const items = Array.isArray(files) ? files.slice() : [files];\n if (items.some((item) => typeof item === "string")) {\n if (!items.every((item) => typeof item === "string"))\n throw new Error("File paths cannot be mixed with buffers");\n const [localPaths, localDirectory] = await resolvePathsAndDirectoryForInputFiles(\n platform,\n items\n );\n if (context._connection.isRemote()) {\n const files2 = localDirectory ? (await platform.fs().promises.readdir(localDirectory, { withFileTypes: true, recursive: true })).filter((f) => f.isFile()).map((f) => platform.path().join(f.parentPath, f.name)) : localPaths;\n const { writableStreams, rootDir } = await context._wrapApiCall(\n async () => context._channel.createTempFiles({\n rootDirName: localDirectory ? platform.path().basename(localDirectory) : void 0,\n items: await Promise.all(\n files2.map(async (file) => {\n const lastModifiedMs = (await platform.fs().promises.stat(file)).mtimeMs;\n return {\n name: localDirectory ? platform.path().relative(localDirectory, file) : platform.path().basename(file),\n lastModifiedMs\n };\n })\n )\n }),\n { internal: true }\n );\n for (let i = 0; i < files2.length; i++) {\n const writable = WritableStream.from(writableStreams[i]);\n await platform.streamFile(files2[i], writable.stream());\n }\n return {\n directoryStream: rootDir,\n streams: localDirectory ? void 0 : writableStreams\n };\n }\n return {\n localPaths,\n localDirectory\n };\n }\n const payloads = items;\n if (filePayloadExceedsSizeLimit(payloads))\n throw new Error(\n "Cannot set buffer larger than 50Mb, please write it to a file and pass its path instead."\n );\n return { payloads };\n }\n function determineScreenshotType(options) {\n if (options.path) {\n const mimeType = getMimeTypeForPath(options.path);\n if (mimeType === "image/png") return "png";\n else if (mimeType === "image/jpeg") return "jpeg";\n throw new Error(`path: unsupported mime type "${mimeType}"`);\n }\n return options.type;\n }\n\n // src/sandbox/forked-client/src/client/fileChooser.ts\n var FileChooser = class {\n _page;\n _elementHandle;\n _isMultiple;\n constructor(page, elementHandle, isMultiple) {\n this._page = page;\n this._elementHandle = elementHandle;\n this._isMultiple = isMultiple;\n }\n element() {\n return this._elementHandle;\n }\n isMultiple() {\n return this._isMultiple;\n }\n page() {\n return this._page;\n }\n async setFiles(files, options) {\n return await this._elementHandle.setInputFiles(files, options);\n }\n };\n\n // src/sandbox/forked-client/src/client/harRouter.ts\n function unsupported2() {\n throw new Error("HAR routing is not available in the QuickJS sandbox");\n }\n var HarRouter = class _HarRouter {\n static async create() {\n return new _HarRouter();\n }\n async addContextRoute() {\n unsupported2();\n }\n async addPageRoute() {\n unsupported2();\n }\n async dispose() {\n }\n };\n\n // src/sandbox/forked-client/src/client/input.ts\n var Keyboard = class {\n _page;\n constructor(page) {\n this._page = page;\n }\n async down(key) {\n await this._page._channel.keyboardDown({ key });\n }\n async up(key) {\n await this._page._channel.keyboardUp({ key });\n }\n async insertText(text) {\n await this._page._channel.keyboardInsertText({ text });\n }\n async type(text, options = {}) {\n await this._page._channel.keyboardType({ text, ...options });\n }\n async press(key, options = {}) {\n await this._page._channel.keyboardPress({ key, ...options });\n }\n };\n var Mouse = class {\n _page;\n constructor(page) {\n this._page = page;\n }\n async move(x, y, options = {}) {\n await this._page._channel.mouseMove({ x, y, ...options });\n }\n async down(options = {}) {\n await this._page._channel.mouseDown({ ...options });\n }\n async up(options = {}) {\n await this._page._channel.mouseUp(options);\n }\n async click(x, y, options = {}) {\n await this._page._channel.mouseClick({ x, y, ...options });\n }\n async dblclick(x, y, options = {}) {\n await this._page._wrapApiCall(\n async () => {\n await this.click(x, y, { ...options, clickCount: 2 });\n },\n { title: "Double click" }\n );\n }\n async wheel(deltaX, deltaY) {\n await this._page._channel.mouseWheel({ deltaX, deltaY });\n }\n };\n var Touchscreen = class {\n _page;\n constructor(page) {\n this._page = page;\n }\n async tap(x, y) {\n await this._page._channel.touchscreenTap({ x, y });\n }\n };\n\n // src/sandbox/forked-client/src/client/video.ts\n var Video = class extends EventEmitter {\n constructor(page, connection, artifact) {\n super(page._platform);\n this._page = page;\n this._connection = connection;\n this._artifact = artifact;\n }\n async start() {\n throw new Error("Video capture is not available in the QuickJS sandbox");\n }\n async stop() {\n }\n async path() {\n throw new Error("Video capture is not available in the QuickJS sandbox");\n }\n async saveAs() {\n throw new Error("Video capture is not available in the QuickJS sandbox");\n }\n async delete() {\n await this._artifact?.delete?.();\n }\n };\n\n // src/sandbox/forked-client/src/client/screencast.ts\n var Screencast = class {\n constructor(page) {\n this._page = page;\n }\n async start() {\n throw new Error("Screencast is not available in the QuickJS sandbox");\n }\n async stop() {\n }\n };\n\n // src/sandbox/forked-client/src/client/page.ts\n var Page = class _Page extends ChannelOwner {\n _browserContext;\n _ownedContext;\n _mainFrame;\n _frames = /* @__PURE__ */ new Set();\n _workers = /* @__PURE__ */ new Set();\n _closed = false;\n _closedOrCrashedScope = new LongStandingScope();\n _viewportSize;\n _routes = [];\n _webSocketRoutes = [];\n coverage;\n keyboard;\n mouse;\n request;\n touchscreen;\n clock;\n screencast;\n _bindings = /* @__PURE__ */ new Map();\n _timeoutSettings;\n _video;\n _opener;\n _closeReason;\n _closeWasCalled = false;\n _harRouters = [];\n _locatorHandlers = /* @__PURE__ */ new Map();\n static from(page) {\n return page._object;\n }\n static fromNullable(page) {\n return page ? _Page.from(page) : null;\n }\n constructor(parent, type, guid, initializer) {\n super(parent, type, guid, initializer);\n this._instrumentation.onPage(this);\n this._browserContext = parent;\n this._timeoutSettings = new TimeoutSettings(\n this._platform,\n this._browserContext._timeoutSettings\n );\n this.keyboard = new Keyboard(this);\n this.mouse = new Mouse(this);\n this.request = this._browserContext.request;\n this.touchscreen = new Touchscreen(this);\n this.clock = this._browserContext.clock;\n this._mainFrame = Frame.from(initializer.mainFrame);\n this._mainFrame._page = this;\n this._frames.add(this._mainFrame);\n this._viewportSize = initializer.viewportSize;\n this._closed = initializer.isClosed;\n this._opener = _Page.fromNullable(initializer.opener);\n this._video = new Video(\n this,\n this._connection,\n initializer.video ? Artifact.from(initializer.video) : void 0\n );\n this.screencast = new Screencast(this);\n this._channel.on("bindingCall", ({ binding }) => this._onBinding(BindingCall.from(binding)));\n this._channel.on("close", () => this._onClose());\n this._channel.on("crash", () => this._onCrash());\n this._channel.on("download", ({ url, suggestedFilename, artifact }) => {\n const artifactObject = Artifact.from(artifact);\n this.emit(Events.Page.Download, new Download(this, url, suggestedFilename, artifactObject));\n });\n this._channel.on(\n "fileChooser",\n ({ element, isMultiple }) => this.emit(\n Events.Page.FileChooser,\n new FileChooser(this, ElementHandle.from(element), isMultiple)\n )\n );\n this._channel.on("frameAttached", ({ frame }) => this._onFrameAttached(Frame.from(frame)));\n this._channel.on("frameDetached", ({ frame }) => this._onFrameDetached(Frame.from(frame)));\n this._channel.on("locatorHandlerTriggered", ({ uid }) => this._onLocatorHandlerTriggered(uid));\n this._channel.on("route", ({ route }) => this._onRoute(Route.from(route)));\n this._channel.on(\n "webSocketRoute",\n ({ webSocketRoute }) => this._onWebSocketRoute(WebSocketRoute.from(webSocketRoute))\n );\n this._channel.on(\n "viewportSizeChanged",\n ({ viewportSize }) => this._viewportSize = viewportSize\n );\n this._channel.on(\n "webSocket",\n ({ webSocket }) => this.emit(Events.Page.WebSocket, WebSocket.from(webSocket))\n );\n this._channel.on("worker", ({ worker }) => this._onWorker(Worker.from(worker)));\n this.coverage = new Coverage(this._channel);\n this.once(\n Events.Page.Close,\n () => this._closedOrCrashedScope.close(this._closeErrorWithReason())\n );\n this.once(Events.Page.Crash, () => this._closedOrCrashedScope.close(new TargetClosedError()));\n this._setEventToSubscriptionMapping(\n /* @__PURE__ */ new Map([\n [Events.Page.Console, "console"],\n [Events.Page.Dialog, "dialog"],\n [Events.Page.Request, "request"],\n [Events.Page.Response, "response"],\n [Events.Page.RequestFinished, "requestFinished"],\n [Events.Page.RequestFailed, "requestFailed"],\n [Events.Page.FileChooser, "fileChooser"]\n ])\n );\n }\n _onFrameAttached(frame) {\n frame._page = this;\n this._frames.add(frame);\n if (frame._parentFrame) frame._parentFrame._childFrames.add(frame);\n this.emit(Events.Page.FrameAttached, frame);\n }\n _onFrameDetached(frame) {\n this._frames.delete(frame);\n frame._detached = true;\n if (frame._parentFrame) frame._parentFrame._childFrames.delete(frame);\n this.emit(Events.Page.FrameDetached, frame);\n }\n async _onRoute(route) {\n route._context = this.context();\n const routeHandlers = this._routes.slice();\n for (const routeHandler of routeHandlers) {\n if (this._closeWasCalled || this._browserContext.isClosedOrClosing()) return;\n if (!routeHandler.matches(route.request().url())) continue;\n const index = this._routes.indexOf(routeHandler);\n if (index === -1) continue;\n if (routeHandler.willExpire()) this._routes.splice(index, 1);\n const handled = await routeHandler.handle(route);\n if (!this._routes.length)\n this._updateInterceptionPatterns({ internal: true }).catch(() => {\n });\n if (handled) return;\n }\n await this._browserContext._onRoute(route);\n }\n async _onWebSocketRoute(webSocketRoute) {\n const routeHandler = this._webSocketRoutes.find((route) => route.matches(webSocketRoute.url()));\n if (routeHandler) await routeHandler.handle(webSocketRoute);\n else await this._browserContext._onWebSocketRoute(webSocketRoute);\n }\n async _onBinding(bindingCall) {\n const func = this._bindings.get(bindingCall._initializer.name);\n if (func) {\n await bindingCall.call(func);\n return;\n }\n await this._browserContext._onBinding(bindingCall);\n }\n _onWorker(worker) {\n this._workers.add(worker);\n worker._page = this;\n this.emit(Events.Page.Worker, worker);\n }\n _onClose() {\n this._closed = true;\n this._browserContext._pages.delete(this);\n this._disposeHarRouters();\n this.emit(Events.Page.Close, this);\n }\n _onCrash() {\n this.emit(Events.Page.Crash, this);\n }\n context() {\n return this._browserContext;\n }\n async opener() {\n if (!this._opener || this._opener.isClosed()) return null;\n return this._opener;\n }\n mainFrame() {\n return this._mainFrame;\n }\n frame(frameSelector) {\n const name = isString(frameSelector) ? frameSelector : frameSelector.name;\n const url = isObject(frameSelector) ? frameSelector.url : void 0;\n assert(name || url, "Either name or url matcher should be specified");\n return this.frames().find((f) => {\n if (name) return f.name() === name;\n return urlMatches(this._browserContext._options.baseURL, f.url(), url);\n }) || null;\n }\n frames() {\n return [...this._frames];\n }\n setDefaultNavigationTimeout(timeout) {\n this._timeoutSettings.setDefaultNavigationTimeout(timeout);\n }\n setDefaultTimeout(timeout) {\n this._timeoutSettings.setDefaultTimeout(timeout);\n }\n video() {\n return this._video;\n }\n async pickLocator() {\n const { selector } = await this._channel.pickLocator({});\n return this.locator(selector);\n }\n async cancelPickLocator() {\n await this._channel.cancelPickLocator({});\n }\n async $(selector, options) {\n return await this._mainFrame.$(selector, options);\n }\n async waitForSelector(selector, options) {\n return await this._mainFrame.waitForSelector(selector, options);\n }\n async dispatchEvent(selector, type, eventInit, options) {\n return await this._mainFrame.dispatchEvent(selector, type, eventInit, options);\n }\n async evaluateHandle(pageFunction, arg) {\n assertMaxArguments(arguments.length, 2);\n return await this._mainFrame.evaluateHandle(pageFunction, arg);\n }\n async $eval(selector, pageFunction, arg) {\n assertMaxArguments(arguments.length, 3);\n return await this._mainFrame.$eval(selector, pageFunction, arg);\n }\n async $$eval(selector, pageFunction, arg) {\n assertMaxArguments(arguments.length, 3);\n return await this._mainFrame.$$eval(selector, pageFunction, arg);\n }\n async $$(selector) {\n return await this._mainFrame.$$(selector);\n }\n async addScriptTag(options = {}) {\n return await this._mainFrame.addScriptTag(options);\n }\n async addStyleTag(options = {}) {\n return await this._mainFrame.addStyleTag(options);\n }\n async exposeFunction(name, callback) {\n const result = await this._channel.exposeBinding({ name });\n const binding = (source, ...args) => callback(...args);\n this._bindings.set(name, binding);\n return DisposableObject.from(result.disposable);\n }\n async exposeBinding(name, callback, options = {}) {\n const result = await this._channel.exposeBinding({ name, needsHandle: options.handle });\n this._bindings.set(name, callback);\n return DisposableObject.from(result.disposable);\n }\n async setExtraHTTPHeaders(headers) {\n validateHeaders(headers);\n await this._channel.setExtraHTTPHeaders({ headers: headersObjectToArray(headers) });\n }\n url() {\n return this._mainFrame.url();\n }\n async content() {\n return await this._mainFrame.content();\n }\n async setContent(html, options) {\n return await this._mainFrame.setContent(html, options);\n }\n async goto(url, options) {\n return await this._mainFrame.goto(url, options);\n }\n async reload(options = {}) {\n const waitUntil = verifyLoadState(\n "waitUntil",\n options.waitUntil === void 0 ? "load" : options.waitUntil\n );\n return Response.fromNullable(\n (await this._channel.reload({\n ...options,\n waitUntil,\n timeout: this._timeoutSettings.navigationTimeout(options)\n })).response\n );\n }\n async addLocatorHandler(locator, handler, options = {}) {\n if (locator._frame !== this._mainFrame)\n throw new Error(`Locator must belong to the main frame of this page`);\n if (options.times === 0) return;\n const { uid } = await this._channel.registerLocatorHandler({\n selector: locator._selector,\n noWaitAfter: options.noWaitAfter\n });\n this._locatorHandlers.set(uid, { locator, handler, times: options.times });\n }\n async _onLocatorHandlerTriggered(uid) {\n let remove = false;\n try {\n const handler = this._locatorHandlers.get(uid);\n if (handler && handler.times !== 0) {\n if (handler.times !== void 0) handler.times--;\n await handler.handler(handler.locator);\n }\n remove = handler?.times === 0;\n } finally {\n if (remove) this._locatorHandlers.delete(uid);\n this._channel.resolveLocatorHandlerNoReply({ uid, remove }).catch(() => {\n });\n }\n }\n async removeLocatorHandler(locator) {\n for (const [uid, data] of this._locatorHandlers) {\n if (data.locator._equals(locator)) {\n this._locatorHandlers.delete(uid);\n await this._channel.unregisterLocatorHandler({ uid }).catch(() => {\n });\n }\n }\n }\n async waitForLoadState(state, options) {\n return await this._mainFrame.waitForLoadState(state, options);\n }\n async waitForNavigation(options) {\n return await this._mainFrame.waitForNavigation(options);\n }\n async waitForURL(url, options) {\n return await this._mainFrame.waitForURL(url, options);\n }\n async waitForRequest(urlOrPredicate, options = {}) {\n const predicate = async (request) => {\n if (isString(urlOrPredicate) || isRegExp(urlOrPredicate))\n return urlMatches(this._browserContext._options.baseURL, request.url(), urlOrPredicate);\n return await urlOrPredicate(request);\n };\n const trimmedUrl = trimUrl(urlOrPredicate);\n const logLine = trimmedUrl ? `waiting for request ${trimmedUrl}` : void 0;\n return await this._waitForEvent(\n Events.Page.Request,\n { predicate, timeout: options.timeout },\n logLine\n );\n }\n async waitForResponse(urlOrPredicate, options = {}) {\n const predicate = async (response) => {\n if (isString(urlOrPredicate) || isRegExp(urlOrPredicate))\n return urlMatches(this._browserContext._options.baseURL, response.url(), urlOrPredicate);\n return await urlOrPredicate(response);\n };\n const trimmedUrl = trimUrl(urlOrPredicate);\n const logLine = trimmedUrl ? `waiting for response ${trimmedUrl}` : void 0;\n return await this._waitForEvent(\n Events.Page.Response,\n { predicate, timeout: options.timeout },\n logLine\n );\n }\n async waitForEvent(event, optionsOrPredicate = {}) {\n return await this._waitForEvent(event, optionsOrPredicate, `waiting for event "${event}"`);\n }\n _closeErrorWithReason() {\n return new TargetClosedError(this._closeReason || this._browserContext._effectiveCloseReason());\n }\n async _waitForEvent(event, optionsOrPredicate, logLine) {\n return await this._wrapApiCall(async () => {\n const timeout = this._timeoutSettings.timeout(\n typeof optionsOrPredicate === "function" ? {} : optionsOrPredicate\n );\n const predicate = typeof optionsOrPredicate === "function" ? optionsOrPredicate : optionsOrPredicate.predicate;\n const waiter = Waiter.createForEvent(this, event);\n if (logLine) waiter.log(logLine);\n waiter.rejectOnTimeout(\n timeout,\n `Timeout ${timeout}ms exceeded while waiting for event "${event}"`\n );\n if (event !== Events.Page.Crash)\n waiter.rejectOnEvent(this, Events.Page.Crash, new Error("Page crashed"));\n if (event !== Events.Page.Close)\n waiter.rejectOnEvent(this, Events.Page.Close, () => this._closeErrorWithReason());\n const result = await waiter.waitForEvent(this, event, predicate);\n waiter.dispose();\n return result;\n });\n }\n async goBack(options = {}) {\n const waitUntil = verifyLoadState(\n "waitUntil",\n options.waitUntil === void 0 ? "load" : options.waitUntil\n );\n return Response.fromNullable(\n (await this._channel.goBack({\n ...options,\n waitUntil,\n timeout: this._timeoutSettings.navigationTimeout(options)\n })).response\n );\n }\n async goForward(options = {}) {\n const waitUntil = verifyLoadState(\n "waitUntil",\n options.waitUntil === void 0 ? "load" : options.waitUntil\n );\n return Response.fromNullable(\n (await this._channel.goForward({\n ...options,\n waitUntil,\n timeout: this._timeoutSettings.navigationTimeout(options)\n })).response\n );\n }\n async requestGC() {\n await this._channel.requestGC();\n }\n async emulateMedia(options = {}) {\n await this._channel.emulateMedia({\n media: options.media === null ? "no-override" : options.media,\n colorScheme: options.colorScheme === null ? "no-override" : options.colorScheme,\n reducedMotion: options.reducedMotion === null ? "no-override" : options.reducedMotion,\n forcedColors: options.forcedColors === null ? "no-override" : options.forcedColors,\n contrast: options.contrast === null ? "no-override" : options.contrast\n });\n }\n async setViewportSize(viewportSize) {\n this._viewportSize = viewportSize;\n await this._channel.setViewportSize({ viewportSize });\n }\n viewportSize() {\n return this._viewportSize || null;\n }\n async evaluate(pageFunction, arg) {\n assertMaxArguments(arguments.length, 2);\n return await this._mainFrame.evaluate(pageFunction, arg);\n }\n async addInitScript(script, arg) {\n const source = await evaluationScript(this._platform, script, arg);\n return DisposableObject.from((await this._channel.addInitScript({ source })).disposable);\n }\n async route(url, handler, options = {}) {\n this._routes.unshift(\n new RouteHandler(\n this._platform,\n this._browserContext._options.baseURL,\n url,\n handler,\n options.times\n )\n );\n await this._updateInterceptionPatterns({ title: "Route requests" });\n return new DisposableStub(() => this.unroute(url, handler));\n }\n async routeFromHAR(har, options = {}) {\n const localUtils = this._connection.localUtils();\n if (!localUtils) throw new Error("Route from har is not supported in thin clients");\n if (options.update) {\n await this._browserContext._recordIntoHAR(har, this, options);\n return;\n }\n const harRouter = await HarRouter.create(localUtils, har, options.notFound || "abort", {\n urlMatch: options.url\n });\n this._harRouters.push(harRouter);\n await harRouter.addPageRoute(this);\n }\n async routeWebSocket(url, handler) {\n this._webSocketRoutes.unshift(\n new WebSocketRouteHandler(this._browserContext._options.baseURL, url, handler)\n );\n await this._updateWebSocketInterceptionPatterns({ title: "Route WebSockets" });\n }\n _disposeHarRouters() {\n this._harRouters.forEach((router) => router.dispose());\n this._harRouters = [];\n }\n async unrouteAll(options) {\n await this._unrouteInternal(this._routes, [], options?.behavior);\n this._disposeHarRouters();\n }\n async unroute(url, handler) {\n const removed = [];\n const remaining = [];\n for (const route of this._routes) {\n if (urlMatchesEqual(route.url, url) && (!handler || route.handler === handler))\n removed.push(route);\n else remaining.push(route);\n }\n await this._unrouteInternal(removed, remaining, "default");\n }\n async _unrouteInternal(removed, remaining, behavior) {\n this._routes = remaining;\n if (behavior && behavior !== "default") {\n const promises = removed.map((routeHandler) => routeHandler.stop(behavior));\n await Promise.all(promises);\n }\n await this._updateInterceptionPatterns({ title: "Unroute requests" });\n }\n async _updateInterceptionPatterns(options) {\n const patterns = RouteHandler.prepareInterceptionPatterns(this._routes);\n await this._wrapApiCall(\n () => this._channel.setNetworkInterceptionPatterns({ patterns }),\n options\n );\n }\n async _updateWebSocketInterceptionPatterns(options) {\n const patterns = WebSocketRouteHandler.prepareInterceptionPatterns(this._webSocketRoutes);\n await this._wrapApiCall(\n () => this._channel.setWebSocketInterceptionPatterns({ patterns }),\n options\n );\n }\n async screenshot(options = {}) {\n const mask = options.mask;\n const copy = {\n ...options,\n path: void 0,\n mask: void 0,\n timeout: this._timeoutSettings.timeout(options)\n };\n if (!copy.type) copy.type = determineScreenshotType(options);\n if (mask) {\n copy.mask = mask.map((locator) => ({\n frame: locator._frame._channel,\n selector: locator._selector\n }));\n }\n const result = await this._channel.screenshot(copy);\n if (options.path) {\n options.path = await writeTempFile(options.path, result.binary);\n }\n return result.binary;\n }\n async _expectScreenshot(options) {\n const mask = options?.mask ? options?.mask.map((locator2) => ({\n frame: locator2._frame._channel,\n selector: locator2._selector\n })) : void 0;\n const locator = options.locator ? {\n frame: options.locator._frame._channel,\n selector: options.locator._selector\n } : void 0;\n return await this._channel.expectScreenshot({\n ...options,\n isNot: !!options.isNot,\n locator,\n mask\n });\n }\n async title() {\n return await this._mainFrame.title();\n }\n async bringToFront() {\n await this._channel.bringToFront();\n }\n async [Symbol.asyncDispose]() {\n await this.close();\n }\n async close(options = {}) {\n this._closeReason = options.reason;\n if (!options.runBeforeUnload) this._closeWasCalled = true;\n try {\n if (this._ownedContext) await this._ownedContext.close();\n else await this._channel.close(options);\n } catch (e) {\n if (isTargetClosedError(e) && !options.runBeforeUnload) return;\n throw e;\n }\n }\n isClosed() {\n return this._closed;\n }\n async click(selector, options) {\n return await this._mainFrame.click(selector, options);\n }\n async dragAndDrop(source, target, options) {\n return await this._mainFrame.dragAndDrop(source, target, options);\n }\n async dblclick(selector, options) {\n await this._mainFrame.dblclick(selector, options);\n }\n async tap(selector, options) {\n return await this._mainFrame.tap(selector, options);\n }\n async fill(selector, value, options) {\n return await this._mainFrame.fill(selector, value, options);\n }\n async clearConsoleMessages() {\n await this._channel.clearConsoleMessages();\n }\n async consoleMessages(options) {\n const { messages } = await this._channel.consoleMessages({ filter: options?.filter });\n return messages.map((message) => new ConsoleMessage(this._platform, message, this, null));\n }\n async clearPageErrors() {\n await this._channel.clearPageErrors();\n }\n async pageErrors(options) {\n const { errors } = await this._channel.pageErrors({ filter: options?.filter });\n return errors.map((error) => parseError(error));\n }\n locator(selector, options) {\n return this.mainFrame().locator(selector, options);\n }\n getByTestId(testId) {\n return this.mainFrame().getByTestId(testId);\n }\n getByAltText(text, options) {\n return this.mainFrame().getByAltText(text, options);\n }\n getByLabel(text, options) {\n return this.mainFrame().getByLabel(text, options);\n }\n getByPlaceholder(text, options) {\n return this.mainFrame().getByPlaceholder(text, options);\n }\n getByText(text, options) {\n return this.mainFrame().getByText(text, options);\n }\n getByTitle(text, options) {\n return this.mainFrame().getByTitle(text, options);\n }\n getByRole(role, options = {}) {\n return this.mainFrame().getByRole(role, options);\n }\n frameLocator(selector) {\n return this.mainFrame().frameLocator(selector);\n }\n async focus(selector, options) {\n return await this._mainFrame.focus(selector, options);\n }\n async textContent(selector, options) {\n return await this._mainFrame.textContent(selector, options);\n }\n async innerText(selector, options) {\n return await this._mainFrame.innerText(selector, options);\n }\n async innerHTML(selector, options) {\n return await this._mainFrame.innerHTML(selector, options);\n }\n async getAttribute(selector, name, options) {\n return await this._mainFrame.getAttribute(selector, name, options);\n }\n async inputValue(selector, options) {\n return await this._mainFrame.inputValue(selector, options);\n }\n async isChecked(selector, options) {\n return await this._mainFrame.isChecked(selector, options);\n }\n async isDisabled(selector, options) {\n return await this._mainFrame.isDisabled(selector, options);\n }\n async isEditable(selector, options) {\n return await this._mainFrame.isEditable(selector, options);\n }\n async isEnabled(selector, options) {\n return await this._mainFrame.isEnabled(selector, options);\n }\n async isHidden(selector, options) {\n return await this._mainFrame.isHidden(selector, options);\n }\n async isVisible(selector, options) {\n return await this._mainFrame.isVisible(selector, options);\n }\n async hover(selector, options) {\n return await this._mainFrame.hover(selector, options);\n }\n async selectOption(selector, values, options) {\n return await this._mainFrame.selectOption(selector, values, options);\n }\n async setInputFiles(selector, files, options) {\n return await this._mainFrame.setInputFiles(selector, files, options);\n }\n async type(selector, text, options) {\n return await this._mainFrame.type(selector, text, options);\n }\n async press(selector, key, options) {\n return await this._mainFrame.press(selector, key, options);\n }\n async check(selector, options) {\n return await this._mainFrame.check(selector, options);\n }\n async uncheck(selector, options) {\n return await this._mainFrame.uncheck(selector, options);\n }\n async setChecked(selector, checked, options) {\n return await this._mainFrame.setChecked(selector, checked, options);\n }\n async waitForTimeout(timeout) {\n return await this._mainFrame.waitForTimeout(timeout);\n }\n async waitForFunction(pageFunction, arg, options) {\n return await this._mainFrame.waitForFunction(pageFunction, arg, options);\n }\n async requests() {\n const { requests } = await this._channel.requests();\n return requests.map((request) => Request.from(request));\n }\n workers() {\n return [...this._workers];\n }\n async pause(_options) {\n if (this._platform.isJSDebuggerAttached()) return;\n const defaultNavigationTimeout = this._browserContext._timeoutSettings.defaultNavigationTimeout();\n const defaultTimeout = this._browserContext._timeoutSettings.defaultTimeout();\n this._browserContext.setDefaultNavigationTimeout(0);\n this._browserContext.setDefaultTimeout(0);\n this._instrumentation?.onWillPause({ keepTestTimeout: !!_options?.__testHookKeepTestTimeout });\n await this._closedOrCrashedScope.safeRace(this.context()._channel.pause());\n this._browserContext.setDefaultNavigationTimeout(defaultNavigationTimeout);\n this._browserContext.setDefaultTimeout(defaultTimeout);\n }\n async pdf(options = {}) {\n const transportOptions = { ...options };\n if (transportOptions.margin) transportOptions.margin = { ...transportOptions.margin };\n if (typeof options.width === "number") transportOptions.width = options.width + "px";\n if (typeof options.height === "number") transportOptions.height = options.height + "px";\n for (const margin of ["top", "right", "bottom", "left"]) {\n const index = margin;\n if (options.margin && typeof options.margin[index] === "number")\n transportOptions.margin[index] = transportOptions.margin[index] + "px";\n }\n const result = await this._channel.pdf(transportOptions);\n if (options.path) {\n const platform = this._platform;\n await platform.fs().promises.mkdir(platform.path().dirname(options.path), { recursive: true });\n await platform.fs().promises.writeFile(options.path, result.pdf);\n }\n return result.pdf;\n }\n async snapshotForAI(options = {}) {\n return await this._channel.snapshotForAI({\n timeout: this._timeoutSettings.timeout(options),\n track: options.track,\n depth: options.depth\n });\n }\n async _setDockTile(image) {\n await this._channel.setDockTile({ image });\n }\n };\n var BindingCall = class extends ChannelOwner {\n static from(channel) {\n return channel._object;\n }\n constructor(parent, type, guid, initializer) {\n super(parent, type, guid, initializer);\n }\n async call(func) {\n try {\n const frame = Frame.from(this._initializer.frame);\n const source = {\n context: frame._page.context(),\n page: frame._page,\n frame\n };\n let result;\n if (this._initializer.handle)\n result = await func(source, JSHandle.from(this._initializer.handle));\n else result = await func(source, ...this._initializer.args.map(parseResult));\n this._channel.resolve({ result: serializeArgument(result) }).catch(() => {\n });\n } catch (e) {\n this._channel.reject({ error: serializeError(e) }).catch(() => {\n });\n }\n }\n };\n function trimUrl(param) {\n if (isRegExp(param)) return `/${trimStringWithEllipsis(param.source, 50)}/${param.flags}`;\n if (isString(param)) return `"${trimStringWithEllipsis(param, 50)}"`;\n }\n\n // src/sandbox/forked-client/src/client/dialog.ts\n var Dialog = class extends ChannelOwner {\n static from(dialog) {\n return dialog._object;\n }\n _page;\n constructor(parent, type, guid, initializer) {\n super(parent, type, guid, initializer);\n this._page = Page.fromNullable(initializer.page);\n }\n page() {\n return this._page;\n }\n type() {\n return this._initializer.type;\n }\n message() {\n return this._initializer.message;\n }\n defaultValue() {\n return this._initializer.defaultValue;\n }\n async accept(promptText) {\n await this._channel.accept({ promptText });\n }\n async dismiss() {\n await this._channel.dismiss();\n }\n };\n\n // src/sandbox/forked-client/src/client/tracing.ts\n var Tracing = class extends ChannelOwner {\n _tracesDir;\n static from(channel) {\n return channel?._object;\n }\n async start() {\n }\n async startChunk() {\n }\n async stop() {\n }\n async stopChunk() {\n }\n async group() {\n }\n async groupEnd() {\n }\n };\n\n // src/sandbox/forked-client/src/client/webError.ts\n var WebError = class {\n _page;\n _error;\n constructor(page, error) {\n this._page = page;\n this._error = error;\n }\n page() {\n return this._page;\n }\n error() {\n return this._error;\n }\n };\n\n // src/sandbox/forked-client/src/client/browserContext.ts\n var BrowserContext = class _BrowserContext extends ChannelOwner {\n _pages = /* @__PURE__ */ new Set();\n _routes = [];\n _webSocketRoutes = [];\n // Browser is null for browser contexts created outside of normal browser, e.g. android or electron.\n _browser = null;\n _bindings = /* @__PURE__ */ new Map();\n _timeoutSettings;\n _ownerPage;\n _forReuse = false;\n _closedPromise;\n _options;\n request;\n tracing;\n clock;\n _serviceWorkers = /* @__PURE__ */ new Set();\n _harRecorders = /* @__PURE__ */ new Map();\n _closingStatus = "none";\n _closeReason;\n _harRouters = [];\n _onRecorderEventSink;\n static from(context) {\n return context._object;\n }\n static fromNullable(context) {\n return context ? _BrowserContext.from(context) : null;\n }\n constructor(parent, type, guid, initializer) {\n super(parent, type, guid, initializer);\n this._options = initializer.options;\n this._timeoutSettings = new TimeoutSettings(this._platform);\n this.tracing = Tracing.from(initializer.tracing);\n this.request = APIRequestContext.from(initializer.requestContext);\n this.request._timeoutSettings = this._timeoutSettings;\n this.clock = new Clock(this);\n this._channel.on("bindingCall", ({ binding }) => this._onBinding(BindingCall.from(binding)));\n this._channel.on("close", () => this._onClose());\n this._channel.on("page", ({ page }) => this._onPage(Page.from(page)));\n this._channel.on("route", ({ route }) => this._onRoute(Route.from(route)));\n this._channel.on(\n "webSocketRoute",\n ({ webSocketRoute }) => this._onWebSocketRoute(WebSocketRoute.from(webSocketRoute))\n );\n this._channel.on("serviceWorker", ({ worker }) => {\n const serviceWorker = Worker.from(worker);\n serviceWorker._context = this;\n this._serviceWorkers.add(serviceWorker);\n this.emit(Events.BrowserContext.ServiceWorker, serviceWorker);\n });\n this._channel.on("console", (event) => {\n const worker = Worker.fromNullable(event.worker);\n const page = Page.fromNullable(event.page);\n const consoleMessage = new ConsoleMessage(this._platform, event, page, worker);\n worker?.emit(Events.Worker.Console, consoleMessage);\n page?.emit(Events.Page.Console, consoleMessage);\n if (worker && this._serviceWorkers.has(worker)) {\n const scope = this._serviceWorkerScope(worker);\n for (const page2 of this._pages) {\n if (scope && page2.url().startsWith(scope)) page2.emit(Events.Page.Console, consoleMessage);\n }\n }\n this.emit(Events.BrowserContext.Console, consoleMessage);\n });\n this._channel.on("pageError", ({ error, page }) => {\n const pageObject = Page.from(page);\n const parsedError = parseError(error);\n this.emit(Events.BrowserContext.WebError, new WebError(pageObject, parsedError));\n if (pageObject) pageObject.emit(Events.Page.PageError, parsedError);\n });\n this._channel.on("dialog", ({ dialog }) => {\n const dialogObject = Dialog.from(dialog);\n let hasListeners = this.emit(Events.BrowserContext.Dialog, dialogObject);\n const page = dialogObject.page();\n if (page) hasListeners = page.emit(Events.Page.Dialog, dialogObject) || hasListeners;\n if (!hasListeners) {\n if (dialogObject.type() === "beforeunload") dialog.accept({}).catch(() => {\n });\n else dialog.dismiss().catch(() => {\n });\n }\n });\n this._channel.on(\n "request",\n ({ request, page }) => this._onRequest(Request.from(request), Page.fromNullable(page))\n );\n this._channel.on(\n "requestFailed",\n ({ request, failureText, responseEndTiming, page }) => this._onRequestFailed(\n Request.from(request),\n responseEndTiming,\n failureText,\n Page.fromNullable(page)\n )\n );\n this._channel.on("requestFinished", (params) => this._onRequestFinished(params));\n this._channel.on(\n "response",\n ({ response, page }) => this._onResponse(Response.from(response), Page.fromNullable(page))\n );\n this._channel.on("recorderEvent", ({ event, data, page, code }) => {\n if (event === "actionAdded")\n this._onRecorderEventSink?.actionAdded?.(\n Page.from(page),\n data,\n code\n );\n else if (event === "actionUpdated")\n this._onRecorderEventSink?.actionUpdated?.(\n Page.from(page),\n data,\n code\n );\n else if (event === "signalAdded")\n this._onRecorderEventSink?.signalAdded?.(Page.from(page), data);\n });\n this._closedPromise = new Promise((f) => this.once(Events.BrowserContext.Close, f));\n this._setEventToSubscriptionMapping(\n /* @__PURE__ */ new Map([\n [Events.BrowserContext.Console, "console"],\n [Events.BrowserContext.Dialog, "dialog"],\n [Events.BrowserContext.Request, "request"],\n [Events.BrowserContext.Response, "response"],\n [Events.BrowserContext.RequestFinished, "requestFinished"],\n [Events.BrowserContext.RequestFailed, "requestFailed"]\n ])\n );\n }\n async _initializeHarFromOptions(recordHar) {\n if (!recordHar) return;\n const defaultContent = recordHar.path.endsWith(".zip") ? "attach" : "embed";\n await this._recordIntoHAR(recordHar.path, null, {\n url: recordHar.urlFilter,\n updateContent: recordHar.content ?? (recordHar.omitContent ? "omit" : defaultContent),\n updateMode: recordHar.mode ?? "full"\n });\n }\n _onPage(page) {\n this._pages.add(page);\n this.emit(Events.BrowserContext.Page, page);\n if (page._opener && !page._opener.isClosed()) page._opener.emit(Events.Page.Popup, page);\n }\n _onRequest(request, page) {\n this.emit(Events.BrowserContext.Request, request);\n if (page) page.emit(Events.Page.Request, request);\n }\n _onResponse(response, page) {\n this.emit(Events.BrowserContext.Response, response);\n if (page) page.emit(Events.Page.Response, response);\n }\n _onRequestFailed(request, responseEndTiming, failureText, page) {\n request._failureText = failureText || null;\n request._setResponseEndTiming(responseEndTiming);\n this.emit(Events.BrowserContext.RequestFailed, request);\n if (page) page.emit(Events.Page.RequestFailed, request);\n }\n _onRequestFinished(params) {\n const { responseEndTiming } = params;\n const request = Request.from(params.request);\n const response = Response.fromNullable(params.response);\n const page = Page.fromNullable(params.page);\n request._setResponseEndTiming(responseEndTiming);\n this.emit(Events.BrowserContext.RequestFinished, request);\n if (page) page.emit(Events.Page.RequestFinished, request);\n if (response) response._finishedPromise.resolve(null);\n }\n async _onRoute(route) {\n route._context = this;\n const page = route.request()._safePage();\n const routeHandlers = this._routes.slice();\n for (const routeHandler of routeHandlers) {\n if (page?._closeWasCalled || this.isClosedOrClosing()) return;\n if (!routeHandler.matches(route.request().url())) continue;\n const index = this._routes.indexOf(routeHandler);\n if (index === -1) continue;\n if (routeHandler.willExpire()) this._routes.splice(index, 1);\n const handled = await routeHandler.handle(route);\n if (!this._routes.length)\n this._updateInterceptionPatterns({ internal: true }).catch(() => {\n });\n if (handled) return;\n }\n await route._innerContinue(\n true\n /* isFallback */\n ).catch(() => {\n });\n }\n async _onWebSocketRoute(webSocketRoute) {\n const routeHandler = this._webSocketRoutes.find((route) => route.matches(webSocketRoute.url()));\n if (routeHandler) await routeHandler.handle(webSocketRoute);\n else webSocketRoute.connectToServer();\n }\n async _onBinding(bindingCall) {\n const func = this._bindings.get(bindingCall._initializer.name);\n if (!func) return;\n await bindingCall.call(func);\n }\n _serviceWorkerScope(serviceWorker) {\n try {\n let url = new URL(".", serviceWorker.url()).href;\n if (!url.endsWith("/")) url += "/";\n return url;\n } catch {\n return null;\n }\n }\n setDefaultNavigationTimeout(timeout) {\n this._timeoutSettings.setDefaultNavigationTimeout(timeout);\n }\n setDefaultTimeout(timeout) {\n this._timeoutSettings.setDefaultTimeout(timeout);\n }\n browser() {\n return this._browser;\n }\n contextOptions() {\n return contextParamsToPublicOptions(this._options);\n }\n pages() {\n return [...this._pages];\n }\n isClosedOrClosing() {\n return this._closingStatus !== "none";\n }\n async newPage() {\n if (this._ownerPage) throw new Error("Please use browser.newContext()");\n return Page.from((await this._channel.newPage()).page);\n }\n async cookies(urls) {\n if (!urls) urls = [];\n if (urls && typeof urls === "string") urls = [urls];\n return (await this._channel.cookies({ urls })).cookies;\n }\n async addCookies(cookies) {\n await this._channel.addCookies({ cookies });\n }\n async clearCookies(options = {}) {\n await this._channel.clearCookies({\n name: isString(options.name) ? options.name : void 0,\n nameRegexSource: isRegExp(options.name) ? options.name.source : void 0,\n nameRegexFlags: isRegExp(options.name) ? options.name.flags : void 0,\n domain: isString(options.domain) ? options.domain : void 0,\n domainRegexSource: isRegExp(options.domain) ? options.domain.source : void 0,\n domainRegexFlags: isRegExp(options.domain) ? options.domain.flags : void 0,\n path: isString(options.path) ? options.path : void 0,\n pathRegexSource: isRegExp(options.path) ? options.path.source : void 0,\n pathRegexFlags: isRegExp(options.path) ? options.path.flags : void 0\n });\n }\n async grantPermissions(permissions, options) {\n await this._channel.grantPermissions({ permissions, ...options });\n }\n async clearPermissions() {\n await this._channel.clearPermissions();\n }\n async setGeolocation(geolocation) {\n await this._channel.setGeolocation({ geolocation: geolocation || void 0 });\n }\n async setExtraHTTPHeaders(headers) {\n validateHeaders(headers);\n await this._channel.setExtraHTTPHeaders({ headers: headersObjectToArray(headers) });\n }\n async setOffline(offline) {\n await this._channel.setOffline({ offline });\n }\n async setHTTPCredentials(httpCredentials) {\n await this._channel.setHTTPCredentials({ httpCredentials: httpCredentials || void 0 });\n }\n async addInitScript(script, arg) {\n const source = await evaluationScript(this._platform, script, arg);\n return DisposableObject.from((await this._channel.addInitScript({ source })).disposable);\n }\n async exposeBinding(name, callback, options = {}) {\n const result = await this._channel.exposeBinding({ name, needsHandle: options.handle });\n this._bindings.set(name, callback);\n return DisposableObject.from(result.disposable);\n }\n async exposeFunction(name, callback) {\n const result = await this._channel.exposeBinding({ name });\n const binding = (source, ...args) => callback(...args);\n this._bindings.set(name, binding);\n return DisposableObject.from(result.disposable);\n }\n async route(url, handler, options = {}) {\n this._routes.unshift(\n new RouteHandler(this._platform, this._options.baseURL, url, handler, options.times)\n );\n await this._updateInterceptionPatterns({ title: "Route requests" });\n return new DisposableStub(() => this.unroute(url, handler));\n }\n async routeWebSocket(url, handler) {\n this._webSocketRoutes.unshift(\n new WebSocketRouteHandler(this._options.baseURL, url, handler)\n );\n await this._updateWebSocketInterceptionPatterns({ title: "Route WebSockets" });\n }\n async _recordIntoHAR(har, page, options = {}) {\n const { harId } = await this._channel.harStart({\n page: page?._channel,\n options: {\n zip: har.endsWith(".zip"),\n content: options.updateContent ?? "attach",\n urlGlob: isString(options.url) ? options.url : void 0,\n urlRegexSource: isRegExp(options.url) ? options.url.source : void 0,\n urlRegexFlags: isRegExp(options.url) ? options.url.flags : void 0,\n mode: options.updateMode ?? "minimal"\n }\n });\n this._harRecorders.set(harId, { path: har, content: options.updateContent ?? "attach" });\n }\n async routeFromHAR(har, options = {}) {\n const localUtils = this._connection.localUtils();\n if (!localUtils) throw new Error("Route from har is not supported in thin clients");\n if (options.update) {\n await this._recordIntoHAR(har, null, options);\n return;\n }\n const harRouter = await HarRouter.create(localUtils, har, options.notFound || "abort", {\n urlMatch: options.url\n });\n this._harRouters.push(harRouter);\n await harRouter.addContextRoute(this);\n }\n _disposeHarRouters() {\n this._harRouters.forEach((router) => router.dispose());\n this._harRouters = [];\n }\n async unrouteAll(options) {\n await this._unrouteInternal(this._routes, [], options?.behavior);\n this._disposeHarRouters();\n }\n async unroute(url, handler) {\n const removed = [];\n const remaining = [];\n for (const route of this._routes) {\n if (urlMatchesEqual(route.url, url) && (!handler || route.handler === handler))\n removed.push(route);\n else remaining.push(route);\n }\n await this._unrouteInternal(removed, remaining, "default");\n }\n async _unrouteInternal(removed, remaining, behavior) {\n this._routes = remaining;\n if (behavior && behavior !== "default") {\n const promises = removed.map((routeHandler) => routeHandler.stop(behavior));\n await Promise.all(promises);\n }\n await this._updateInterceptionPatterns({ title: "Unroute requests" });\n }\n async _updateInterceptionPatterns(options) {\n const patterns = RouteHandler.prepareInterceptionPatterns(this._routes);\n await this._wrapApiCall(\n () => this._channel.setNetworkInterceptionPatterns({ patterns }),\n options\n );\n }\n async _updateWebSocketInterceptionPatterns(options) {\n const patterns = WebSocketRouteHandler.prepareInterceptionPatterns(\n this._webSocketRoutes\n );\n await this._wrapApiCall(\n () => this._channel.setWebSocketInterceptionPatterns({ patterns }),\n options\n );\n }\n _effectiveCloseReason() {\n return this._closeReason || this._browser?._closeReason;\n }\n async waitForEvent(event, optionsOrPredicate = {}) {\n return await this._wrapApiCall(async () => {\n const timeout = this._timeoutSettings.timeout(\n typeof optionsOrPredicate === "function" ? {} : optionsOrPredicate\n );\n const predicate = typeof optionsOrPredicate === "function" ? optionsOrPredicate : optionsOrPredicate.predicate;\n const waiter = Waiter.createForEvent(this, event);\n waiter.rejectOnTimeout(\n timeout,\n `Timeout ${timeout}ms exceeded while waiting for event "${event}"`\n );\n if (event !== Events.BrowserContext.Close)\n waiter.rejectOnEvent(\n this,\n Events.BrowserContext.Close,\n () => new TargetClosedError(this._effectiveCloseReason())\n );\n const result = await waiter.waitForEvent(this, event, predicate);\n waiter.dispose();\n return result;\n });\n }\n async storageState(options = {}) {\n const state = await this._channel.storageState({ indexedDB: options.indexedDB });\n if (options.path) {\n await mkdirIfNeeded(this._platform, options.path);\n await this._platform.fs().promises.writeFile(options.path, JSON.stringify(state, void 0, 2), "utf8");\n }\n return state;\n }\n async setStorageState(storageState) {\n const state = await prepareStorageState(this._platform, storageState);\n await this._channel.setStorageState({ storageState: state });\n }\n backgroundPages() {\n return [];\n }\n serviceWorkers() {\n return [...this._serviceWorkers];\n }\n async newCDPSession(page) {\n if (!(page instanceof Page) && !(page instanceof Frame))\n throw new Error("page: expected Page or Frame");\n const result = await this._channel.newCDPSession(\n page instanceof Page ? { page: page._channel } : { frame: page._channel }\n );\n return CDPSession.from(result.session);\n }\n _onClose() {\n this._closingStatus = "closed";\n this._browser?._contexts.delete(this);\n this._browser?._browserType._contexts.delete(this);\n this._browser?._browserType._playwright.selectors._contextsForSelectors.delete(this);\n this._disposeHarRouters();\n this.tracing._resetStackCounter();\n this.emit(Events.BrowserContext.Close, this);\n }\n async [Symbol.asyncDispose]() {\n await this.close();\n }\n async close(options = {}) {\n if (this.isClosedOrClosing()) return;\n this._closeReason = options.reason;\n this._closingStatus = "closing";\n await this.request.dispose(options);\n await this._instrumentation.runBeforeCloseBrowserContext(this);\n await this._wrapApiCall(\n async () => {\n for (const [harId, harParams] of this._harRecorders) {\n const har = await this._channel.harExport({ harId });\n const artifact = Artifact.from(har.artifact);\n const isCompressed = harParams.content === "attach" || harParams.path.endsWith(".zip");\n const needCompressed = harParams.path.endsWith(".zip");\n if (isCompressed && !needCompressed) {\n const localUtils = this._connection.localUtils();\n if (!localUtils) throw new Error("Uncompressed har is not supported in thin clients");\n await artifact.saveAs(harParams.path + ".tmp");\n await localUtils.harUnzip({\n zipFile: harParams.path + ".tmp",\n harFile: harParams.path\n });\n } else {\n await artifact.saveAs(harParams.path);\n }\n await artifact.delete();\n }\n },\n { internal: true }\n );\n await this._channel.close(options);\n await this._closedPromise;\n }\n async _enableRecorder(params, eventSink) {\n if (eventSink) this._onRecorderEventSink = eventSink;\n await this._channel.enableRecorder(params);\n }\n async _disableRecorder() {\n this._onRecorderEventSink = void 0;\n await this._channel.disableRecorder();\n }\n async _exposeConsoleApi() {\n await this._channel.exposeConsoleApi();\n }\n };\n async function prepareStorageState(platform, storageState) {\n if (typeof storageState !== "string") return storageState;\n try {\n return JSON.parse(await platform.fs().promises.readFile(storageState, "utf8"));\n } catch (e) {\n rewriteErrorMessage(e, `Error reading storage state from ${storageState}:\n` + e.message);\n throw e;\n }\n }\n async function prepareBrowserContextParams(platform, options) {\n if (options.videoSize && !options.videosPath)\n throw new Error(`"videoSize" option requires "videosPath" to be specified`);\n if (options.extraHTTPHeaders) validateHeaders(options.extraHTTPHeaders);\n const contextParams = {\n ...options,\n viewport: options.viewport === null ? void 0 : options.viewport,\n noDefaultViewport: options.viewport === null,\n extraHTTPHeaders: options.extraHTTPHeaders ? headersObjectToArray(options.extraHTTPHeaders) : void 0,\n storageState: options.storageState ? await prepareStorageState(platform, options.storageState) : void 0,\n serviceWorkers: options.serviceWorkers,\n colorScheme: options.colorScheme === null ? "no-override" : options.colorScheme,\n reducedMotion: options.reducedMotion === null ? "no-override" : options.reducedMotion,\n forcedColors: options.forcedColors === null ? "no-override" : options.forcedColors,\n contrast: options.contrast === null ? "no-override" : options.contrast,\n acceptDownloads: toAcceptDownloadsProtocol(options.acceptDownloads),\n clientCertificates: await toClientCertificatesProtocol(platform, options.clientCertificates)\n };\n if (!contextParams.recordVideo && options.videosPath) {\n contextParams.recordVideo = {\n dir: options.videosPath,\n size: options.videoSize\n };\n }\n if (contextParams.recordVideo && contextParams.recordVideo.dir)\n contextParams.recordVideo.dir = platform.path().resolve(contextParams.recordVideo.dir);\n return contextParams;\n }\n function contextParamsToPublicOptions(params) {\n const result = {\n ...params,\n viewport: params.noDefaultViewport ? null : params.viewport,\n extraHTTPHeaders: params.extraHTTPHeaders ? headersArrayToObject(params.extraHTTPHeaders, false) : void 0,\n colorScheme: params.colorScheme === "no-override" ? null : params.colorScheme,\n reducedMotion: params.reducedMotion === "no-override" ? null : params.reducedMotion,\n forcedColors: params.forcedColors === "no-override" ? null : params.forcedColors,\n contrast: params.contrast === "no-override" ? null : params.contrast,\n acceptDownloads: params.acceptDownloads === "accept" ? true : params.acceptDownloads === "deny" ? false : void 0,\n storageState: void 0\n };\n delete result.clientCertificates;\n delete result.noDefaultViewport;\n delete result.selectorEngines;\n return result;\n }\n function toAcceptDownloadsProtocol(acceptDownloads) {\n if (acceptDownloads === void 0) return void 0;\n if (acceptDownloads) return "accept";\n return "deny";\n }\n async function toClientCertificatesProtocol(platform, certs) {\n if (!certs) return void 0;\n const bufferizeContent = async (value, path) => {\n if (value) return value;\n if (path) return await platform.fs().promises.readFile(path);\n };\n return await Promise.all(\n certs.map(async (cert) => ({\n origin: cert.origin,\n cert: await bufferizeContent(cert.cert, cert.certPath),\n key: await bufferizeContent(cert.key, cert.keyPath),\n pfx: await bufferizeContent(cert.pfx, cert.pfxPath),\n passphrase: cert.passphrase\n }))\n );\n }\n\n // src/sandbox/forked-client/src/client/browser.ts\n var Browser = class extends ChannelOwner {\n _contexts = /* @__PURE__ */ new Set();\n _isConnected = true;\n _closedPromise;\n _shouldCloseConnectionOnClose = false;\n _browserType;\n _options = {};\n _userDataDir;\n _name;\n _path;\n _closeReason;\n static from(browser) {\n return browser._object;\n }\n constructor(parent, type, guid, initializer) {\n super(parent, type, guid, initializer);\n this._name = initializer.name;\n this._channel.on(\n "context",\n ({ context }) => this._didCreateContext(BrowserContext.from(context))\n );\n this._channel.on("close", () => this._didClose());\n this._closedPromise = new Promise((f) => this.once(Events.Browser.Disconnected, f));\n }\n browserType() {\n return this._browserType;\n }\n async newContext(options = {}) {\n return await this._innerNewContext(options, false);\n }\n async _newContextForReuse(options = {}) {\n return await this._innerNewContext(options, true);\n }\n async _disconnectFromReusedContext(reason) {\n const context = [...this._contexts].find((context2) => context2._forReuse);\n if (!context) return;\n await this._instrumentation.runBeforeCloseBrowserContext(context);\n for (const page of context.pages()) page._onClose();\n context._onClose();\n await this._channel.disconnectFromReusedContext({ reason });\n }\n async _innerNewContext(userOptions = {}, forReuse) {\n const options = this._browserType._playwright.selectors._withSelectorOptions(userOptions);\n await this._instrumentation.runBeforeCreateBrowserContext(options);\n const contextOptions = await prepareBrowserContextParams(this._platform, options);\n const response = forReuse ? await this._channel.newContextForReuse(contextOptions) : await this._channel.newContext(contextOptions);\n const context = BrowserContext.from(response.context);\n if (forReuse) context._forReuse = true;\n if (options.logger) context._logger = options.logger;\n await context._initializeHarFromOptions(options.recordHar);\n await this._instrumentation.runAfterCreateBrowserContext(context);\n return context;\n }\n _connectToBrowserType(browserType, browserOptions, logger, userDataDir) {\n this._browserType = browserType;\n this._options = browserOptions;\n this._userDataDir = userDataDir;\n this._logger = logger;\n for (const context of this._contexts) this._setupBrowserContext(context);\n }\n _didCreateContext(context) {\n context._browser = this;\n this._contexts.add(context);\n if (this._browserType) this._setupBrowserContext(context);\n }\n _setupBrowserContext(context) {\n context._logger = this._logger;\n context.tracing._tracesDir = this._options.tracesDir;\n this._browserType._contexts.add(context);\n this._browserType._playwright.selectors._contextsForSelectors.add(context);\n context.setDefaultTimeout(this._browserType._playwright._defaultContextTimeout);\n context.setDefaultNavigationTimeout(\n this._browserType._playwright._defaultContextNavigationTimeout\n );\n }\n contexts() {\n return [...this._contexts];\n }\n version() {\n return this._initializer.version;\n }\n async _register(title, options = {}) {\n const { pipeName } = await this._channel.startServer({ title, ...options });\n return { pipeName };\n }\n async _unregister() {\n await this._channel.stopServer();\n }\n async newPage(options = {}) {\n return await this._wrapApiCall(\n async () => {\n const context = await this.newContext(options);\n const page = await context.newPage();\n page._ownedContext = context;\n context._ownerPage = page;\n return page;\n },\n { title: "Create page" }\n );\n }\n isConnected() {\n return this._isConnected;\n }\n launchOptions() {\n return this._options;\n }\n userDataDir() {\n return this._userDataDir ?? null;\n }\n async newBrowserCDPSession() {\n return CDPSession.from((await this._channel.newBrowserCDPSession()).session);\n }\n async startTracing(page, options = {}) {\n this._path = options.path;\n await this._channel.startTracing({ ...options, page: page ? page._channel : void 0 });\n }\n async stopTracing() {\n const artifact = Artifact.from((await this._channel.stopTracing()).artifact);\n const buffer = await artifact.readIntoBuffer();\n await artifact.delete();\n if (this._path) {\n await mkdirIfNeeded(this._platform, this._path);\n await this._platform.fs().promises.writeFile(this._path, buffer);\n this._path = void 0;\n }\n return buffer;\n }\n async [Symbol.asyncDispose]() {\n await this.close();\n }\n async close(options = {}) {\n this._closeReason = options.reason;\n try {\n if (this._shouldCloseConnectionOnClose) this._connection.close();\n else await this._channel.close(options);\n await this._closedPromise;\n } catch (e) {\n if (isTargetClosedError(e)) return;\n throw e;\n }\n }\n _didClose() {\n this._isConnected = false;\n this.emit(Events.Browser.Disconnected, this);\n }\n };\n\n // src/sandbox/forked-client/src/client/browserType.ts\n var BrowserType = class extends ChannelOwner {\n _serverLauncher;\n _contexts = /* @__PURE__ */ new Set();\n _playwright;\n static from(browserType) {\n return browserType._object;\n }\n executablePath() {\n if (!this._initializer.executablePath)\n throw new Error("Browser is not supported on current platform");\n return this._initializer.executablePath;\n }\n name() {\n return this._initializer.name;\n }\n async launch(options = {}) {\n assert(\n !options.userDataDir,\n "userDataDir option is not supported in `browserType.launch`. Use `browserType.launchPersistentContext` instead"\n );\n assert(!options.port, "Cannot specify a port without launching as a server.");\n const logger = options.logger || this._playwright._defaultLaunchOptions?.logger;\n options = { ...this._playwright._defaultLaunchOptions, ...options };\n const launchOptions = {\n ...options,\n ignoreDefaultArgs: Array.isArray(options.ignoreDefaultArgs) ? options.ignoreDefaultArgs : void 0,\n ignoreAllDefaultArgs: !!options.ignoreDefaultArgs && !Array.isArray(options.ignoreDefaultArgs),\n env: options.env ? envObjectToArray(options.env) : void 0,\n timeout: new TimeoutSettings(this._platform).launchTimeout(options)\n };\n return await this._wrapApiCall(async () => {\n const browser = Browser.from((await this._channel.launch(launchOptions)).browser);\n browser._connectToBrowserType(this, options, logger);\n return browser;\n });\n }\n async launchServer(options = {}) {\n if (!this._serverLauncher) throw new Error("Launching server is not supported");\n options = { ...this._playwright._defaultLaunchOptions, ...options };\n return await this._serverLauncher.launchServer(options);\n }\n async launchPersistentContext(userDataDir, options = {}) {\n void userDataDir;\n void options;\n throw new Error(\n "browserType.launchPersistentContext() is not available in the QuickJS sandbox"\n );\n }\n async connect(optionsOrEndpoint, options) {\n if (typeof optionsOrEndpoint === "string")\n return await this._connect({ ...options, endpoint: optionsOrEndpoint });\n assert(optionsOrEndpoint.wsEndpoint, "options.wsEndpoint is required");\n return await this._connect({ ...options, endpoint: optionsOrEndpoint.wsEndpoint });\n }\n async _connect(params) {\n void params;\n throw new Error("browserType.connect() is not available in the QuickJS sandbox");\n }\n async connectOverCDP(endpointURLOrOptions, options) {\n if (typeof endpointURLOrOptions === "string")\n return await this._connectOverCDP(endpointURLOrOptions, options);\n const endpointURL = "endpointURL" in endpointURLOrOptions ? endpointURLOrOptions.endpointURL : endpointURLOrOptions.wsEndpoint;\n assert(endpointURL, "Cannot connect over CDP without wsEndpoint.");\n return await this.connectOverCDP(endpointURL, endpointURLOrOptions);\n }\n async _connectOverCDP(endpointURL, params = {}) {\n if (this.name() !== "chromium")\n throw new Error("Connecting over CDP is only supported in Chromium.");\n const headers = params.headers ? headersObjectToArray(params.headers) : void 0;\n const result = await this._channel.connectOverCDP({\n endpointURL,\n headers,\n slowMo: params.slowMo,\n timeout: new TimeoutSettings(this._platform).timeout(params),\n isLocal: params.isLocal\n });\n const browser = Browser.from(result.browser);\n browser._connectToBrowserType(this, {}, params.logger);\n if (result.defaultContext)\n await this._instrumentation.runAfterCreateBrowserContext(\n BrowserContext.from(result.defaultContext)\n );\n return browser;\n }\n async _connectOverCDPTransport(transport) {\n if (this.name() !== "chromium")\n throw new Error("Connecting over CDP is only supported in Chromium.");\n const result = await this._channel.connectOverCDPTransport({ transport });\n const browser = Browser.from(result.browser);\n browser._connectToBrowserType(this, {}, void 0);\n if (result.defaultContext)\n await this._instrumentation.runAfterCreateBrowserContext(\n BrowserContext.from(result.defaultContext)\n );\n return browser;\n }\n };\n\n // src/sandbox/forked-client/src/client/clientInstrumentation.ts\n function createInstrumentation() {\n const listeners = [];\n return new Proxy(\n {},\n {\n get: (obj, prop) => {\n if (typeof prop !== "string") return obj[prop];\n if (prop === "addListener")\n return (listener) => listeners.push(listener);\n if (prop === "removeListener")\n return (listener) => listeners.splice(listeners.indexOf(listener), 1);\n if (prop === "removeAllListeners") return () => listeners.splice(0, listeners.length);\n if (prop.startsWith("run")) {\n return async (...params) => {\n for (const listener of listeners) await listener[prop]?.(...params);\n };\n }\n if (prop.startsWith("on")) {\n return (...params) => {\n for (const listener of listeners) listener[prop]?.(...params);\n };\n }\n return obj[prop];\n }\n }\n );\n }\n\n // src/sandbox/forked-client/src/client/debugger.ts\n var Debugger = class extends ChannelOwner {\n _pausedDetails = [];\n static from(channel) {\n return channel._object;\n }\n constructor(parent, type, guid, initializer) {\n super(parent, type, guid, initializer);\n this._channel.on("pausedStateChanged", ({ pausedDetails }) => {\n this._pausedDetails = pausedDetails;\n this.emit(Events.Debugger.PausedStateChanged);\n });\n }\n async pause() {\n await this._channel.pause();\n }\n async resume() {\n await this._channel.resume();\n }\n async next() {\n await this._channel.next();\n }\n async runTo(location) {\n await this._channel.runTo({ location });\n }\n pausedDetails() {\n return this._pausedDetails;\n }\n };\n\n // src/sandbox/forked-client/src/client/electron.ts\n var Electron = class extends ChannelOwner {\n static from(channel) {\n return channel?._object;\n }\n };\n var ElectronApplication = class extends ChannelOwner {\n static from(channel) {\n return channel?._object;\n }\n };\n\n // src/sandbox/forked-client/src/client/jsonPipe.ts\n var JsonPipe = class extends ChannelOwner {\n static from(channel) {\n return channel?._object;\n }\n };\n\n // src/sandbox/forked-client/src/client/localUtils.ts\n function unsupported3() {\n throw new Error("LocalUtils is not available in the QuickJS sandbox");\n }\n var LocalUtils = class extends ChannelOwner {\n devices = {};\n static from(channel) {\n return channel?._object;\n }\n async connect() {\n unsupported3();\n }\n async addStackToTracingNoReply() {\n }\n async zip() {\n unsupported3();\n }\n async harOpen() {\n unsupported3();\n }\n async harLookup() {\n unsupported3();\n }\n async harClose() {\n unsupported3();\n }\n async harUnzip() {\n unsupported3();\n }\n };\n\n // src/sandbox/forked-client/src/client/selectors.ts\n var Selectors = class {\n _platform;\n _selectorEngines = [];\n _testIdAttributeName;\n _contextsForSelectors = /* @__PURE__ */ new Set();\n constructor(platform) {\n this._platform = platform;\n }\n async register(name, script, options = {}) {\n if (this._selectorEngines.some((engine) => engine.name === name))\n throw new Error(`selectors.register: "${name}" selector engine has been already registered`);\n const source = await evaluationScript(this._platform, script, void 0, false);\n const selectorEngine = { ...options, name, source };\n for (const context of this._contextsForSelectors)\n await context._channel.registerSelectorEngine({ selectorEngine });\n this._selectorEngines.push(selectorEngine);\n }\n setTestIdAttribute(attributeName) {\n this._testIdAttributeName = attributeName;\n setTestIdAttribute(attributeName);\n for (const context of this._contextsForSelectors) {\n context._options.testIdAttributeName = attributeName;\n context._channel.setTestIdAttributeName({ testIdAttributeName: attributeName }).catch(() => {\n });\n }\n }\n _withSelectorOptions(options) {\n return {\n ...options,\n selectorEngines: this._selectorEngines,\n testIdAttributeName: this._testIdAttributeName\n };\n }\n };\n\n // src/sandbox/forked-client/src/client/playwright.ts\n var Playwright = class extends ChannelOwner {\n _android;\n _electron;\n chromium;\n firefox;\n webkit;\n devices;\n selectors;\n request;\n errors;\n // Instrumentation.\n _defaultLaunchOptions;\n _defaultContextTimeout;\n _defaultContextNavigationTimeout;\n constructor(parent, type, guid, initializer) {\n super(parent, type, guid, initializer);\n this.request = new APIRequest(this);\n this.chromium = BrowserType.from(initializer.chromium);\n this.chromium._playwright = this;\n this.firefox = BrowserType.from(initializer.firefox);\n this.firefox._playwright = this;\n this.webkit = BrowserType.from(initializer.webkit);\n this.webkit._playwright = this;\n this._android = Android.from(initializer.android);\n this._android._playwright = this;\n this._electron = Electron.from(initializer.electron);\n this._electron._playwright = this;\n this.devices = this._connection.localUtils()?.devices ?? {};\n this.selectors = new Selectors(this._connection._platform);\n this.errors = { TimeoutError };\n }\n static from(channel) {\n return channel._object;\n }\n _browserTypes() {\n return [this.chromium, this.firefox, this.webkit];\n }\n _preLaunchedBrowser() {\n const browser = Browser.from(this._initializer.preLaunchedBrowser);\n browser._connectToBrowserType(\n this[browser._name],\n {},\n void 0\n );\n return browser;\n }\n _allContexts() {\n return this._browserTypes().flatMap((type) => [...type._contexts]);\n }\n _allPages() {\n return this._allContexts().flatMap((context) => context.pages());\n }\n };\n\n // src/sandbox/forked-client/src/client/stream.ts\n var Stream = class extends ChannelOwner {\n static from(channel) {\n return channel?._object;\n }\n stream() {\n throw new Error("Readable streams are not available in the QuickJS sandbox");\n }\n };\n\n // src/sandbox/forked-client/src/utils/isomorphic/colors.ts\n var webColors = {\n enabled: true,\n reset: (text) => applyStyle(0, 0, text),\n bold: (text) => applyStyle(1, 22, text),\n dim: (text) => applyStyle(2, 22, text),\n italic: (text) => applyStyle(3, 23, text),\n underline: (text) => applyStyle(4, 24, text),\n inverse: (text) => applyStyle(7, 27, text),\n hidden: (text) => applyStyle(8, 28, text),\n strikethrough: (text) => applyStyle(9, 29, text),\n black: (text) => applyStyle(30, 39, text),\n red: (text) => applyStyle(31, 39, text),\n green: (text) => applyStyle(32, 39, text),\n yellow: (text) => applyStyle(33, 39, text),\n blue: (text) => applyStyle(34, 39, text),\n magenta: (text) => applyStyle(35, 39, text),\n cyan: (text) => applyStyle(36, 39, text),\n white: (text) => applyStyle(37, 39, text),\n gray: (text) => applyStyle(90, 39, text),\n grey: (text) => applyStyle(90, 39, text)\n };\n var applyStyle = (open, close, text) => `\\x1B[${open}m${text}\\x1B[${close}m`;\n\n // src/sandbox/forked-client/quickjs-platform.ts\n var noopZone = {\n push: () => noopZone,\n pop: () => noopZone,\n run: (callback) => callback(),\n data: () => void 0\n };\n function unsupported4(apiName) {\n throw new Error(`${apiName} is not available in the QuickJS sandbox`);\n }\n function pseudoSha1(text) {\n let hash = 2166136261;\n for (let index = 0; index < text.length; index += 1) {\n hash ^= text.charCodeAt(index);\n hash = Math.imul(hash, 16777619);\n }\n return (hash >>> 0).toString(16).padStart(8, "0");\n }\n var quickjsPlatform = {\n name: "empty",\n boxedStackPrefixes: () => [],\n calculateSha1: async (text) => pseudoSha1(text),\n colors: webColors,\n createGuid: () => "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (token) => {\n const value = Math.floor(Math.random() * 16);\n const nibble = token === "x" ? value : value & 3 | 8;\n return nibble.toString(16);\n }),\n defaultMaxListeners: () => 10,\n env: {},\n fs: () => unsupported4("fs"),\n inspectCustom: void 0,\n isDebugMode: () => false,\n isJSDebuggerAttached: () => false,\n isLogEnabled: () => false,\n isUnderTest: () => false,\n log: () => {\n },\n path: () => unsupported4("path"),\n pathSeparator: "/",\n showInternalStackFrames: () => false,\n streamFile: () => unsupported4("streamFile"),\n streamReadable: () => unsupported4("streamReadable"),\n streamWritable: () => unsupported4("streamWritable"),\n zodToJsonSchema: () => unsupported4("zodToJsonSchema"),\n zones: {\n empty: noopZone,\n current: () => noopZone\n }\n };\n\n // src/sandbox/forked-client/src/client/connection.ts\n var Root = class extends ChannelOwner {\n constructor(connection) {\n super(connection, "Root", "", {});\n }\n async initialize() {\n return Playwright.from(\n (await this._channel.initialize({\n sdkLanguage: "javascript"\n })).playwright\n );\n }\n };\n var DummyChannelOwner = class extends ChannelOwner {\n };\n var Connection = class extends EventEmitter {\n _objects = /* @__PURE__ */ new Map();\n onmessage = (message) => {\n };\n _lastId = 0;\n _callbacks = /* @__PURE__ */ new Map();\n _rootObject;\n _closedError;\n _isRemote = false;\n _localUtils;\n _rawBuffers = false;\n // Some connections allow resolving in-process dispatchers.\n toImpl;\n _tracingCount = 0;\n _instrumentation;\n // Used from @playwright/test fixtures -> TODO remove?\n headers;\n constructor(platform = quickjsPlatform, localUtils, instrumentation, headers = []) {\n super(platform);\n this._instrumentation = instrumentation || createInstrumentation();\n this._localUtils = localUtils;\n this._rootObject = new Root(this);\n this.headers = headers;\n }\n markAsRemote() {\n this._isRemote = true;\n }\n isRemote() {\n return this._isRemote;\n }\n useRawBuffers() {\n this._rawBuffers = true;\n }\n rawBuffers() {\n return this._rawBuffers;\n }\n localUtils() {\n return this._localUtils;\n }\n async initializePlaywright() {\n return await this._rootObject.initialize();\n }\n getObjectWithKnownName(guid) {\n return this._objects.get(guid);\n }\n setIsTracing(isTracing) {\n if (isTracing) this._tracingCount++;\n else this._tracingCount--;\n }\n async sendMessageToServer(object, method, params, options) {\n if (this._closedError) throw this._closedError;\n if (object._wasCollected)\n throw new Error("The object has been collected to prevent unbounded heap growth.");\n const guid = object._guid;\n const type = object._type;\n const id = ++this._lastId;\n const message = { id, guid, method, params };\n if (this._platform.isLogEnabled("channel")) {\n this._platform.log("channel", "SEND> " + JSON.stringify(message));\n }\n const location = options.frames?.[0] ? {\n file: options.frames[0].file,\n line: options.frames[0].line,\n column: options.frames[0].column\n } : void 0;\n const metadata = {\n title: options.title,\n location,\n internal: options.internal,\n stepId: options.stepId\n };\n if (this._tracingCount && options.frames && type !== "LocalUtils")\n this._localUtils?.addStackToTracingNoReply({ callData: { stack: options.frames ?? [], id } }).catch(() => {\n });\n this._platform.zones.empty.run(() => this.onmessage({ ...message, metadata }));\n return await new Promise(\n (resolve, reject) => this._callbacks.set(id, { resolve, reject, title: options.title, type, method })\n );\n }\n _validatorFromWireContext() {\n return {\n tChannelImpl: this._tChannelImplFromWire.bind(this),\n binary: this._rawBuffers ? "buffer" : "fromBase64",\n isUnderTest: () => this._platform.isUnderTest()\n };\n }\n dispatch(message) {\n if (this._closedError) return;\n const { id, guid, method, params, result, error, log } = message;\n if (id) {\n if (this._platform.isLogEnabled("channel"))\n this._platform.log("channel", "<RECV " + JSON.stringify(message));\n const callback = this._callbacks.get(id);\n if (!callback) throw new Error(`Cannot find command to respond: ${id}`);\n this._callbacks.delete(id);\n if (error && !result) {\n const parsedError = parseError(error);\n rewriteErrorMessage(parsedError, parsedError.message + formatCallLog(this._platform, log));\n callback.reject(parsedError);\n } else {\n const validator2 = findValidator(callback.type, callback.method, "Result");\n callback.resolve(validator2(result, "", this._validatorFromWireContext()));\n }\n return;\n }\n if (this._platform.isLogEnabled("channel"))\n this._platform.log("channel", "<EVENT " + JSON.stringify(message));\n if (method === "__create__") {\n this._createRemoteObject(guid, params.type, params.guid, params.initializer);\n return;\n }\n const object = this._objects.get(guid);\n if (!object) throw new Error(`Cannot find object to "${method}": ${guid}`);\n if (method === "__adopt__") {\n const child = this._objects.get(params.guid);\n if (!child) throw new Error(`Unknown new child: ${params.guid}`);\n object._adopt(child);\n return;\n }\n if (method === "__dispose__") {\n object._dispose(params.reason);\n return;\n }\n const validator = findValidator(object._type, method, "Event");\n object._channel.emit(method, validator(params, "", this._validatorFromWireContext()));\n }\n close(cause) {\n if (this._closedError) return;\n this._closedError = new TargetClosedError(cause);\n for (const callback of this._callbacks.values()) callback.reject(this._closedError);\n this._callbacks.clear();\n this.emit("close");\n }\n _tChannelImplFromWire(names, arg, path, context) {\n if (arg && typeof arg === "object" && typeof arg.guid === "string") {\n const object = this._objects.get(arg.guid);\n if (!object) throw new Error(`Object with guid ${arg.guid} was not bound in the connection`);\n if (names !== "*" && !names.includes(object._type))\n throw new ValidationError(`${path}: expected channel ${names.toString()}`);\n return object._channel;\n }\n throw new ValidationError(`${path}: expected channel ${names.toString()}`);\n }\n _createRemoteObject(parentGuid, type, guid, initializer) {\n const parent = this._objects.get(parentGuid);\n if (!parent) throw new Error(`Cannot find parent object ${parentGuid} to create ${guid}`);\n let result;\n const validator = findValidator(type, "", "Initializer");\n initializer = validator(initializer, "", this._validatorFromWireContext());\n switch (type) {\n case "Android":\n result = new Android(parent, type, guid, initializer);\n break;\n case "AndroidSocket":\n result = new AndroidSocket(parent, type, guid, initializer);\n break;\n case "AndroidDevice":\n result = new AndroidDevice(parent, type, guid, initializer);\n break;\n case "APIRequestContext":\n result = new APIRequestContext(parent, type, guid, initializer);\n break;\n case "Artifact":\n result = new Artifact(parent, type, guid, initializer);\n break;\n case "BindingCall":\n result = new BindingCall(parent, type, guid, initializer);\n break;\n case "Browser":\n result = new Browser(parent, type, guid, initializer);\n break;\n case "BrowserContext":\n result = new BrowserContext(parent, type, guid, initializer);\n break;\n case "BrowserType":\n result = new BrowserType(parent, type, guid, initializer);\n break;\n case "CDPSession":\n result = new CDPSession(parent, type, guid, initializer);\n break;\n case "Debugger":\n result = new Debugger(parent, type, guid, initializer);\n break;\n case "Dialog":\n result = new Dialog(parent, type, guid, initializer);\n break;\n case "Disposable":\n result = new DisposableObject(parent, type, guid, initializer);\n break;\n case "Electron":\n result = new Electron(parent, type, guid, initializer);\n break;\n case "ElectronApplication":\n result = new ElectronApplication(parent, type, guid, initializer);\n break;\n case "ElementHandle":\n result = new ElementHandle(parent, type, guid, initializer);\n break;\n case "Frame":\n result = new Frame(parent, type, guid, initializer);\n break;\n case "JSHandle":\n result = new JSHandle(parent, type, guid, initializer);\n break;\n case "JsonPipe":\n result = new JsonPipe(parent, type, guid, initializer);\n break;\n case "LocalUtils":\n result = new LocalUtils(parent, type, guid, initializer);\n if (!this._localUtils) this._localUtils = result;\n break;\n case "Page":\n result = new Page(parent, type, guid, initializer);\n break;\n case "Playwright":\n result = new Playwright(parent, type, guid, initializer);\n break;\n case "Request":\n result = new Request(parent, type, guid, initializer);\n break;\n case "Response":\n result = new Response(parent, type, guid, initializer);\n break;\n case "Route":\n result = new Route(parent, type, guid, initializer);\n break;\n case "Stream":\n result = new Stream(parent, type, guid, initializer);\n break;\n case "SocksSupport":\n result = new DummyChannelOwner(parent, type, guid, initializer);\n break;\n case "Tracing":\n result = new Tracing(parent, type, guid, initializer);\n break;\n case "WebSocket":\n result = new WebSocket(parent, type, guid, initializer);\n break;\n case "WebSocketRoute":\n result = new WebSocketRoute(parent, type, guid, initializer);\n break;\n case "Worker":\n result = new Worker(parent, type, guid, initializer);\n break;\n case "WritableStream":\n result = new WritableStream(parent, type, guid, initializer);\n break;\n default:\n throw new Error("Missing type " + type);\n }\n return result;\n }\n };\n function formatCallLog(platform, log) {\n if (!log || !log.some((l) => !!l)) return "";\n return `\nCall log:\n${platform.colors.dim(log.join("\\n"))}\n`;\n }\n return __toCommonJS(bundle_entry_exports);\n})();\n';
14494
14494
 
14495
14495
  // ../../packages/daemon-client/src/daemon/extract.ts
@@ -14624,28 +14624,8 @@ async function findTsxCli(entry) {
14624
14624
  import { spawn } from "node:child_process";
14625
14625
 
14626
14626
  // ../../packages/daemon-client/src/daemon/npm.ts
14627
- import { accessSync, constants } from "node:fs";
14628
- import { delimiter, join as join3 } from "node:path";
14629
14627
  function npmCommand() {
14630
- if (process.platform === "win32") {
14631
- return findInPath("npm.cmd") ?? findInPath("npm") ?? "npm.cmd";
14632
- }
14633
- return findInPath("npm") ?? "npm";
14634
- }
14635
- function findInPath(name) {
14636
- const pathEnv = process.env.PATH ?? "";
14637
- for (const entry of pathEnv.split(delimiter)) {
14638
- if (!entry) {
14639
- continue;
14640
- }
14641
- const candidate = join3(entry, name);
14642
- try {
14643
- accessSync(candidate, constants.F_OK | constants.X_OK);
14644
- return candidate;
14645
- } catch {
14646
- }
14647
- }
14648
- return null;
14628
+ return "npm";
14649
14629
  }
14650
14630
 
14651
14631
  // ../../packages/daemon-client/src/daemon/install.ts
@@ -14666,7 +14646,8 @@ function runInstall(program2, args, cwd) {
14666
14646
  const child = spawn(program2, args, {
14667
14647
  cwd,
14668
14648
  stdio: "inherit",
14669
- windowsHide: true
14649
+ windowsHide: true,
14650
+ shell: process.platform === "win32"
14670
14651
  });
14671
14652
  child.on("error", (err) => {
14672
14653
  const nodeErr = err;
@@ -15001,7 +14982,7 @@ var INVOCATION_STYLES = `Primary invocation styles:
15001
14982
  const page = await browser.getPage("main");
15002
14983
  console.log(await page.title());
15003
14984
  EOF`;
15004
- var CLI_LONG_ABOUT = `Dev Browser is a CLI for controlling local or external browsers with JavaScript scripts.
14985
+ var CLI_LONG_ABOUT = `Canary Browser is a CLI for controlling local or external browsers with JavaScript scripts.
15005
14986
  Scripts run in a sandboxed QuickJS runtime (not Node.js). Top-level \`await\` is
15006
14987
  available, along with a preconnected \`browser\` global and standard \`console\` output.
15007
14988
  A background daemon starts automatically when needed and manages browser instances,