"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var storageScriptSource_exports = {};
__export(storageScriptSource_exports, {
  source: () => source
});
module.exports = __toCommonJS(storageScriptSource_exports);
const source = '\nvar __commonJS = obj => {\n  let required = false;\n  let result;\n  return function __require() {\n    if (!required) {\n      required = true;\n      let fn;\n      for (const name in obj) { fn = obj[name]; break; }\n      const module = { exports: {} };\n      fn(module.exports, module);\n      result = module.exports;\n    }\n    return result;\n  }\n};\nvar __export = (target, all) => {for (var name in all) target[name] = all[name];};\nvar __toESM = mod => ({ ...mod, \'default\': mod });\nvar __toCommonJS = mod => ({ ...mod, __esModule: true });\n\n\n// packages/injected/src/storageScript.ts\nvar storageScript_exports = {};\n__export(storageScript_exports, {\n  StorageScript: () => StorageScript\n});\nmodule.exports = __toCommonJS(storageScript_exports);\n\n// packages/playwright-core/src/utils/isomorphic/utilityScriptSerializers.ts\nfunction isRegExp(obj) {\n  try {\n    return obj instanceof RegExp || Object.prototype.toString.call(obj) === "[object RegExp]";\n  } catch (error) {\n    return false;\n  }\n}\nfunction isDate(obj) {\n  try {\n    return obj instanceof Date || Object.prototype.toString.call(obj) === "[object Date]";\n  } catch (error) {\n    return false;\n  }\n}\nfunction isURL(obj) {\n  try {\n    return obj instanceof URL || Object.prototype.toString.call(obj) === "[object URL]";\n  } catch (error) {\n    return false;\n  }\n}\nfunction isError(obj) {\n  var _a;\n  try {\n    return obj instanceof Error || obj && ((_a = Object.getPrototypeOf(obj)) == null ? void 0 : _a.name) === "Error";\n  } catch (error) {\n    return false;\n  }\n}\nfunction isTypedArray(obj, constructor) {\n  try {\n    return obj instanceof constructor || Object.prototype.toString.call(obj) === `[object ${constructor.name}]`;\n  } catch (error) {\n    return false;\n  }\n}\nvar typedArrayConstructors = {\n  i8: Int8Array,\n  ui8: Uint8Array,\n  ui8c: Uint8ClampedArray,\n  i16: Int16Array,\n  ui16: Uint16Array,\n  i32: Int32Array,\n  ui32: Uint32Array,\n  // TODO: add Float16Array once it\'s in baseline\n  f32: Float32Array,\n  f64: Float64Array,\n  bi64: BigInt64Array,\n  bui64: BigUint64Array\n};\nfunction typedArrayToBase64(array) {\n  if ("toBase64" in array)\n    return array.toBase64();\n  const binary = Array.from(new Uint8Array(array.buffer, array.byteOffset, array.byteLength)).map((b) => String.fromCharCode(b)).join("");\n  return btoa(binary);\n}\nfunction base64ToTypedArray(base64, TypedArrayConstructor) {\n  const binary = atob(base64);\n  const bytes = new Uint8Array(binary.length);\n  for (let i = 0; i < binary.length; i++)\n    bytes[i] = binary.charCodeAt(i);\n  return new TypedArrayConstructor(bytes.buffer);\n}\nfunction parseEvaluationResultValue(value, handles = [], refs = /* @__PURE__ */ new Map()) {\n  if (Object.is(value, void 0))\n    return void 0;\n  if (typeof value === "object" && value) {\n    if ("ref" in value)\n      return refs.get(value.ref);\n    if ("v" in value) {\n      if (value.v === "undefined")\n        return void 0;\n      if (value.v === "null")\n        return null;\n      if (value.v === "NaN")\n        return NaN;\n      if (value.v === "Infinity")\n        return Infinity;\n      if (value.v === "-Infinity")\n        return -Infinity;\n      if (value.v === "-0")\n        return -0;\n      return void 0;\n    }\n    if ("d" in value) {\n      return new Date(value.d);\n    }\n    if ("u" in value)\n      return new URL(value.u);\n    if ("bi" in value)\n      return BigInt(value.bi);\n    if ("e" in value) {\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 ("r" in value)\n      return new RegExp(value.r.p, value.r.f);\n    if ("a" in value) {\n      const result = [];\n      refs.set(value.id, result);\n      for (const a of value.a)\n        result.push(parseEvaluationResultValue(a, handles, refs));\n      return result;\n    }\n    if ("o" in value) {\n      const result = {};\n      refs.set(value.id, result);\n      for (const { k, v } of value.o) {\n        if (k === "__proto__")\n          continue;\n        result[k] = parseEvaluationResultValue(v, handles, refs);\n      }\n      return result;\n    }\n    if ("h" in value)\n      return handles[value.h];\n    if ("ta" in value)\n      return base64ToTypedArray(value.ta.b, typedArrayConstructors[value.ta.k]);\n  }\n  return value;\n}\nfunction serializeAsCallArgument(value, handleSerializer) {\n  return serialize(value, handleSerializer, { visited: /* @__PURE__ */ new Map(), lastId: 0 });\n}\nfunction serialize(value, handleSerializer, visitorInfo) {\n  if (value && typeof value === "object") {\n    if (typeof globalThis.Window === "function" && value instanceof globalThis.Window)\n      return "ref: <Window>";\n    if (typeof globalThis.Document === "function" && value instanceof globalThis.Document)\n      return "ref: <Document>";\n    if (typeof globalThis.Node === "function" && value instanceof globalThis.Node)\n      return "ref: <Node>";\n  }\n  return innerSerialize(value, handleSerializer, visitorInfo);\n}\nfunction innerSerialize(value, handleSerializer, visitorInfo) {\n  var _a;\n  const result = handleSerializer(value);\n  if ("fallThrough" in result)\n    value = result.fallThrough;\n  else\n    return result;\n  if (typeof value === "symbol")\n    return { v: "undefined" };\n  if (Object.is(value, void 0))\n    return { v: "undefined" };\n  if (Object.is(value, null))\n    return { v: "null" };\n  if (Object.is(value, NaN))\n    return { v: "NaN" };\n  if (Object.is(value, Infinity))\n    return { v: "Infinity" };\n  if (Object.is(value, -Infinity))\n    return { v: "-Infinity" };\n  if (Object.is(value, -0))\n    return { v: "-0" };\n  if (typeof value === "boolean")\n    return value;\n  if (typeof value === "number")\n    return value;\n  if (typeof value === "string")\n    return value;\n  if (typeof value === "bigint")\n    return { bi: value.toString() };\n  if (isError(value)) {\n    let stack;\n    if ((_a = value.stack) == null ? void 0 : _a.startsWith(value.name + ": " + value.message)) {\n      stack = value.stack;\n    } else {\n      stack = `${value.name}: ${value.message}\n${value.stack}`;\n    }\n    return { e: { n: value.name, m: value.message, s: stack } };\n  }\n  if (isDate(value))\n    return { d: value.toJSON() };\n  if (isURL(value))\n    return { u: value.toJSON() };\n  if (isRegExp(value))\n    return { r: { p: value.source, f: value.flags } };\n  for (const [k, ctor] of Object.entries(typedArrayConstructors)) {\n    if (isTypedArray(value, ctor))\n      return { ta: { b: typedArrayToBase64(value), k } };\n  }\n  const id = visitorInfo.visited.get(value);\n  if (id)\n    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(serialize(value[i], handleSerializer, visitorInfo));\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      let item;\n      try {\n        item = value[name];\n      } catch (e) {\n        continue;\n      }\n      if (name === "toJSON" && typeof item === "function")\n        o.push({ k: name, v: { o: [], id: 0 } });\n      else\n        o.push({ k: name, v: serialize(item, handleSerializer, visitorInfo) });\n    }\n    let jsonWrapper;\n    try {\n      if (o.length === 0 && value.toJSON && typeof value.toJSON === "function")\n        jsonWrapper = { value: value.toJSON() };\n    } catch (e) {\n    }\n    if (jsonWrapper)\n      return innerSerialize(jsonWrapper.value, handleSerializer, visitorInfo);\n    return { o, id: id2 };\n  }\n}\n\n// packages/injected/src/storageScript.ts\nvar StorageScript = class {\n  constructor(isFirefox) {\n    this._isFirefox = isFirefox;\n    this._global = globalThis;\n  }\n  _idbRequestToPromise(request) {\n    return new Promise((resolve, reject) => {\n      request.addEventListener("success", () => resolve(request.result));\n      request.addEventListener("error", () => reject(request.error));\n    });\n  }\n  _isPlainObject(v) {\n    const ctor = v == null ? void 0 : v.constructor;\n    if (this._isFirefox) {\n      const constructorImpl = ctor == null ? void 0 : ctor.toString();\n      if ((constructorImpl == null ? void 0 : constructorImpl.startsWith("function Object() {")) && (constructorImpl == null ? void 0 : constructorImpl.includes("[native code]")))\n        return true;\n    }\n    return ctor === Object;\n  }\n  _trySerialize(value) {\n    let trivial = true;\n    const encoded = serializeAsCallArgument(value, (v) => {\n      const isTrivial = this._isPlainObject(v) || Array.isArray(v) || typeof v === "string" || typeof v === "number" || typeof v === "boolean" || Object.is(v, null);\n      if (!isTrivial)\n        trivial = false;\n      return { fallThrough: v };\n    });\n    if (trivial)\n      return { trivial: value };\n    return { encoded };\n  }\n  async _collectDB(dbInfo) {\n    if (!dbInfo.name)\n      throw new Error("Database name is empty");\n    if (!dbInfo.version)\n      throw new Error("Database version is unset");\n    const db = await this._idbRequestToPromise(indexedDB.open(dbInfo.name));\n    if (db.objectStoreNames.length === 0)\n      return { name: dbInfo.name, version: dbInfo.version, stores: [] };\n    const transaction = db.transaction(db.objectStoreNames, "readonly");\n    const stores = await Promise.all([...db.objectStoreNames].map(async (storeName) => {\n      const objectStore = transaction.objectStore(storeName);\n      const keys = await this._idbRequestToPromise(objectStore.getAllKeys());\n      const records = await Promise.all(keys.map(async (key) => {\n        const record = {};\n        if (objectStore.keyPath === null) {\n          const { encoded: encoded2, trivial: trivial2 } = this._trySerialize(key);\n          if (trivial2)\n            record.key = trivial2;\n          else\n            record.keyEncoded = encoded2;\n        }\n        const value = await this._idbRequestToPromise(objectStore.get(key));\n        const { encoded, trivial } = this._trySerialize(value);\n        if (trivial)\n          record.value = trivial;\n        else\n          record.valueEncoded = encoded;\n        return record;\n      }));\n      const indexes = [...objectStore.indexNames].map((indexName) => {\n        const index = objectStore.index(indexName);\n        return {\n          name: index.name,\n          keyPath: typeof index.keyPath === "string" ? index.keyPath : void 0,\n          keyPathArray: Array.isArray(index.keyPath) ? index.keyPath : void 0,\n          multiEntry: index.multiEntry,\n          unique: index.unique\n        };\n      });\n      return {\n        name: storeName,\n        records,\n        indexes,\n        autoIncrement: objectStore.autoIncrement,\n        keyPath: typeof objectStore.keyPath === "string" ? objectStore.keyPath : void 0,\n        keyPathArray: Array.isArray(objectStore.keyPath) ? objectStore.keyPath : void 0\n      };\n    }));\n    return {\n      name: dbInfo.name,\n      version: dbInfo.version,\n      stores\n    };\n  }\n  async collect(recordIndexedDB) {\n    const localStorage = Object.keys(this._global.localStorage).map((name) => ({ name, value: this._global.localStorage.getItem(name) }));\n    if (!recordIndexedDB)\n      return { localStorage };\n    try {\n      const databases = await this._global.indexedDB.databases();\n      const indexedDB2 = await Promise.all(databases.map((db) => this._collectDB(db)));\n      return { localStorage, indexedDB: indexedDB2 };\n    } catch (e) {\n      throw new Error("Unable to serialize IndexedDB: " + e.message);\n    }\n  }\n  async _restoreDB(dbInfo) {\n    const openRequest = this._global.indexedDB.open(dbInfo.name, dbInfo.version);\n    openRequest.addEventListener("upgradeneeded", () => {\n      var _a, _b;\n      const db2 = openRequest.result;\n      for (const store of dbInfo.stores) {\n        const objectStore = db2.createObjectStore(store.name, { autoIncrement: store.autoIncrement, keyPath: (_a = store.keyPathArray) != null ? _a : store.keyPath });\n        for (const index of store.indexes)\n          objectStore.createIndex(index.name, (_b = index.keyPathArray) != null ? _b : index.keyPath, { unique: index.unique, multiEntry: index.multiEntry });\n      }\n    });\n    const db = await this._idbRequestToPromise(openRequest);\n    if (db.objectStoreNames.length === 0)\n      return;\n    const transaction = db.transaction(db.objectStoreNames, "readwrite");\n    await Promise.all(dbInfo.stores.map(async (store) => {\n      const objectStore = transaction.objectStore(store.name);\n      await Promise.all(store.records.map(async (record) => {\n        var _a, _b;\n        await this._idbRequestToPromise(\n          objectStore.add(\n            (_a = record.value) != null ? _a : parseEvaluationResultValue(record.valueEncoded),\n            (_b = record.key) != null ? _b : parseEvaluationResultValue(record.keyEncoded)\n          )\n        );\n      }));\n    }));\n  }\n  async restore(originState) {\n    var _a;\n    try {\n      await Promise.all(((_a = originState.indexedDB) != null ? _a : []).map((dbInfo) => this._restoreDB(dbInfo)));\n    } catch (e) {\n      throw new Error("Unable to restore IndexedDB: " + e.message);\n    }\n    for (const { name, value } of originState.localStorage || [])\n      this._global.localStorage.setItem(name, value);\n  }\n};\n';
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  source
});
