{
  "version": 3,
  "sources": ["../node_modules/@msgpack/msgpack/src/utils/int.ts", "../node_modules/@msgpack/msgpack/src/utils/utf8.ts", "../node_modules/@msgpack/msgpack/src/ExtData.ts", "../node_modules/@msgpack/msgpack/src/DecodeError.ts", "../node_modules/@msgpack/msgpack/src/timestamp.ts", "../node_modules/@msgpack/msgpack/src/ExtensionCodec.ts", "../node_modules/@msgpack/msgpack/src/utils/typedArrays.ts", "../node_modules/@msgpack/msgpack/src/Encoder.ts", "../node_modules/@msgpack/msgpack/src/encode.ts", "../node_modules/@msgpack/msgpack/src/utils/prettyByte.ts", "../node_modules/@msgpack/msgpack/src/CachedKeyDecoder.ts", "../node_modules/@msgpack/msgpack/src/Decoder.ts", "../node_modules/@msgpack/msgpack/src/decode.ts", "../node_modules/@msgpack/msgpack/src/utils/stream.ts", "../node_modules/@msgpack/msgpack/src/decodeAsync.ts", "../node_modules/@msgpack/msgpack/src/index.ts", "../webR/webr-main.ts", "../webR/error.ts", "../webR/compat.ts", "../webR/robj.ts", "../webR/emscripten.ts", "../webR/utils-r.ts", "../webR/chan/task-common.ts", "../webR/robj-worker.ts", "../webR/utils.ts", "../webR/chan/task-main.ts", "../webR/chan/queue.ts", "../webR/chan/message.ts", "../webR/payload.ts", "../webR/chan/channel.ts", "../webR/chan/task-worker.ts", "../webR/chan/proxy-websocket.ts", "../webR/chan/proxy-worker.ts", "../webR/chan/channel-shared.ts", "../webR/chan/channel-postmessage.ts", "../webR/chan/channel-common.ts", "../webR/config.ts", "../webR/robj-main.ts", "../webR/proxy.ts", "../webR/console.ts"],
  "sourcesContent": ["// Integer Utility\n\nexport const UINT32_MAX = 0xffff_ffff;\n\n// DataView extension to handle int64 / uint64,\n// where the actual range is 53-bits integer (a.k.a. safe integer)\n\nexport function setUint64(view: DataView, offset: number, value: number): void {\n  const high = value / 0x1_0000_0000;\n  const low = value; // high bits are truncated by DataView\n  view.setUint32(offset, high);\n  view.setUint32(offset + 4, low);\n}\n\nexport function setInt64(view: DataView, offset: number, value: number): void {\n  const high = Math.floor(value / 0x1_0000_0000);\n  const low = value; // high bits are truncated by DataView\n  view.setUint32(offset, high);\n  view.setUint32(offset + 4, low);\n}\n\nexport function getInt64(view: DataView, offset: number): number {\n  const high = view.getInt32(offset);\n  const low = view.getUint32(offset + 4);\n  return high * 0x1_0000_0000 + low;\n}\n\nexport function getUint64(view: DataView, offset: number): number {\n  const high = view.getUint32(offset);\n  const low = view.getUint32(offset + 4);\n  return high * 0x1_0000_0000 + low;\n}\n", "/* eslint-disable @typescript-eslint/no-unnecessary-condition */\nimport { UINT32_MAX } from \"./int\";\n\nconst TEXT_ENCODING_AVAILABLE =\n  (typeof process === \"undefined\" || process?.env?.[\"TEXT_ENCODING\"] !== \"never\") &&\n  typeof TextEncoder !== \"undefined\" &&\n  typeof TextDecoder !== \"undefined\";\n\nexport function utf8Count(str: string): number {\n  const strLength = str.length;\n\n  let byteLength = 0;\n  let pos = 0;\n  while (pos < strLength) {\n    let value = str.charCodeAt(pos++);\n\n    if ((value & 0xffffff80) === 0) {\n      // 1-byte\n      byteLength++;\n      continue;\n    } else if ((value & 0xfffff800) === 0) {\n      // 2-bytes\n      byteLength += 2;\n    } else {\n      // handle surrogate pair\n      if (value >= 0xd800 && value <= 0xdbff) {\n        // high surrogate\n        if (pos < strLength) {\n          const extra = str.charCodeAt(pos);\n          if ((extra & 0xfc00) === 0xdc00) {\n            ++pos;\n            value = ((value & 0x3ff) << 10) + (extra & 0x3ff) + 0x10000;\n          }\n        }\n      }\n\n      if ((value & 0xffff0000) === 0) {\n        // 3-byte\n        byteLength += 3;\n      } else {\n        // 4-byte\n        byteLength += 4;\n      }\n    }\n  }\n  return byteLength;\n}\n\nexport function utf8EncodeJs(str: string, output: Uint8Array, outputOffset: number): void {\n  const strLength = str.length;\n  let offset = outputOffset;\n  let pos = 0;\n  while (pos < strLength) {\n    let value = str.charCodeAt(pos++);\n\n    if ((value & 0xffffff80) === 0) {\n      // 1-byte\n      output[offset++] = value;\n      continue;\n    } else if ((value & 0xfffff800) === 0) {\n      // 2-bytes\n      output[offset++] = ((value >> 6) & 0x1f) | 0xc0;\n    } else {\n      // handle surrogate pair\n      if (value >= 0xd800 && value <= 0xdbff) {\n        // high surrogate\n        if (pos < strLength) {\n          const extra = str.charCodeAt(pos);\n          if ((extra & 0xfc00) === 0xdc00) {\n            ++pos;\n            value = ((value & 0x3ff) << 10) + (extra & 0x3ff) + 0x10000;\n          }\n        }\n      }\n\n      if ((value & 0xffff0000) === 0) {\n        // 3-byte\n        output[offset++] = ((value >> 12) & 0x0f) | 0xe0;\n        output[offset++] = ((value >> 6) & 0x3f) | 0x80;\n      } else {\n        // 4-byte\n        output[offset++] = ((value >> 18) & 0x07) | 0xf0;\n        output[offset++] = ((value >> 12) & 0x3f) | 0x80;\n        output[offset++] = ((value >> 6) & 0x3f) | 0x80;\n      }\n    }\n\n    output[offset++] = (value & 0x3f) | 0x80;\n  }\n}\n\nconst sharedTextEncoder = TEXT_ENCODING_AVAILABLE ? new TextEncoder() : undefined;\nexport const TEXT_ENCODER_THRESHOLD = !TEXT_ENCODING_AVAILABLE\n  ? UINT32_MAX\n  : typeof process !== \"undefined\" && process?.env?.[\"TEXT_ENCODING\"] !== \"force\"\n  ? 200\n  : 0;\n\nfunction utf8EncodeTEencode(str: string, output: Uint8Array, outputOffset: number): void {\n  output.set(sharedTextEncoder!.encode(str), outputOffset);\n}\n\nfunction utf8EncodeTEencodeInto(str: string, output: Uint8Array, outputOffset: number): void {\n  sharedTextEncoder!.encodeInto(str, output.subarray(outputOffset));\n}\n\nexport const utf8EncodeTE = sharedTextEncoder?.encodeInto ? utf8EncodeTEencodeInto : utf8EncodeTEencode;\n\nconst CHUNK_SIZE = 0x1_000;\n\nexport function utf8DecodeJs(bytes: Uint8Array, inputOffset: number, byteLength: number): string {\n  let offset = inputOffset;\n  const end = offset + byteLength;\n\n  const units: Array<number> = [];\n  let result = \"\";\n  while (offset < end) {\n    const byte1 = bytes[offset++]!;\n    if ((byte1 & 0x80) === 0) {\n      // 1 byte\n      units.push(byte1);\n    } else if ((byte1 & 0xe0) === 0xc0) {\n      // 2 bytes\n      const byte2 = bytes[offset++]! & 0x3f;\n      units.push(((byte1 & 0x1f) << 6) | byte2);\n    } else if ((byte1 & 0xf0) === 0xe0) {\n      // 3 bytes\n      const byte2 = bytes[offset++]! & 0x3f;\n      const byte3 = bytes[offset++]! & 0x3f;\n      units.push(((byte1 & 0x1f) << 12) | (byte2 << 6) | byte3);\n    } else if ((byte1 & 0xf8) === 0xf0) {\n      // 4 bytes\n      const byte2 = bytes[offset++]! & 0x3f;\n      const byte3 = bytes[offset++]! & 0x3f;\n      const byte4 = bytes[offset++]! & 0x3f;\n      let unit = ((byte1 & 0x07) << 0x12) | (byte2 << 0x0c) | (byte3 << 0x06) | byte4;\n      if (unit > 0xffff) {\n        unit -= 0x10000;\n        units.push(((unit >>> 10) & 0x3ff) | 0xd800);\n        unit = 0xdc00 | (unit & 0x3ff);\n      }\n      units.push(unit);\n    } else {\n      units.push(byte1);\n    }\n\n    if (units.length >= CHUNK_SIZE) {\n      result += String.fromCharCode(...units);\n      units.length = 0;\n    }\n  }\n\n  if (units.length > 0) {\n    result += String.fromCharCode(...units);\n  }\n\n  return result;\n}\n\nconst sharedTextDecoder = TEXT_ENCODING_AVAILABLE ? new TextDecoder() : null;\nexport const TEXT_DECODER_THRESHOLD = !TEXT_ENCODING_AVAILABLE\n  ? UINT32_MAX\n  : typeof process !== \"undefined\" && process?.env?.[\"TEXT_DECODER\"] !== \"force\"\n  ? 200\n  : 0;\n\nexport function utf8DecodeTD(bytes: Uint8Array, inputOffset: number, byteLength: number): string {\n  const stringBytes = bytes.subarray(inputOffset, inputOffset + byteLength);\n  return sharedTextDecoder!.decode(stringBytes);\n}\n", "/**\n * ExtData is used to handle Extension Types that are not registered to ExtensionCodec.\n */\nexport class ExtData {\n  constructor(readonly type: number, readonly data: Uint8Array) {}\n}\n", "export class DecodeError extends Error {\n  constructor(message: string) {\n    super(message);\n\n    // fix the prototype chain in a cross-platform way\n    const proto: typeof DecodeError.prototype = Object.create(DecodeError.prototype);\n    Object.setPrototypeOf(this, proto);\n\n    Object.defineProperty(this, \"name\", {\n      configurable: true,\n      enumerable: false,\n      value: DecodeError.name,\n    });\n  }\n}\n", "// https://github.com/msgpack/msgpack/blob/master/spec.md#timestamp-extension-type\nimport { DecodeError } from \"./DecodeError\";\nimport { getInt64, setInt64 } from \"./utils/int\";\n\nexport const EXT_TIMESTAMP = -1;\n\nexport type TimeSpec = {\n  sec: number;\n  nsec: number;\n};\n\nconst TIMESTAMP32_MAX_SEC = 0x100000000 - 1; // 32-bit unsigned int\nconst TIMESTAMP64_MAX_SEC = 0x400000000 - 1; // 34-bit unsigned int\n\nexport function encodeTimeSpecToTimestamp({ sec, nsec }: TimeSpec): Uint8Array {\n  if (sec >= 0 && nsec >= 0 && sec <= TIMESTAMP64_MAX_SEC) {\n    // Here sec >= 0 && nsec >= 0\n    if (nsec === 0 && sec <= TIMESTAMP32_MAX_SEC) {\n      // timestamp 32 = { sec32 (unsigned) }\n      const rv = new Uint8Array(4);\n      const view = new DataView(rv.buffer);\n      view.setUint32(0, sec);\n      return rv;\n    } else {\n      // timestamp 64 = { nsec30 (unsigned), sec34 (unsigned) }\n      const secHigh = sec / 0x100000000;\n      const secLow = sec & 0xffffffff;\n      const rv = new Uint8Array(8);\n      const view = new DataView(rv.buffer);\n      // nsec30 | secHigh2\n      view.setUint32(0, (nsec << 2) | (secHigh & 0x3));\n      // secLow32\n      view.setUint32(4, secLow);\n      return rv;\n    }\n  } else {\n    // timestamp 96 = { nsec32 (unsigned), sec64 (signed) }\n    const rv = new Uint8Array(12);\n    const view = new DataView(rv.buffer);\n    view.setUint32(0, nsec);\n    setInt64(view, 4, sec);\n    return rv;\n  }\n}\n\nexport function encodeDateToTimeSpec(date: Date): TimeSpec {\n  const msec = date.getTime();\n  const sec = Math.floor(msec / 1e3);\n  const nsec = (msec - sec * 1e3) * 1e6;\n\n  // Normalizes { sec, nsec } to ensure nsec is unsigned.\n  const nsecInSec = Math.floor(nsec / 1e9);\n  return {\n    sec: sec + nsecInSec,\n    nsec: nsec - nsecInSec * 1e9,\n  };\n}\n\nexport function encodeTimestampExtension(object: unknown): Uint8Array | null {\n  if (object instanceof Date) {\n    const timeSpec = encodeDateToTimeSpec(object);\n    return encodeTimeSpecToTimestamp(timeSpec);\n  } else {\n    return null;\n  }\n}\n\nexport function decodeTimestampToTimeSpec(data: Uint8Array): TimeSpec {\n  const view = new DataView(data.buffer, data.byteOffset, data.byteLength);\n\n  // data may be 32, 64, or 96 bits\n  switch (data.byteLength) {\n    case 4: {\n      // timestamp 32 = { sec32 }\n      const sec = view.getUint32(0);\n      const nsec = 0;\n      return { sec, nsec };\n    }\n    case 8: {\n      // timestamp 64 = { nsec30, sec34 }\n      const nsec30AndSecHigh2 = view.getUint32(0);\n      const secLow32 = view.getUint32(4);\n      const sec = (nsec30AndSecHigh2 & 0x3) * 0x100000000 + secLow32;\n      const nsec = nsec30AndSecHigh2 >>> 2;\n      return { sec, nsec };\n    }\n    case 12: {\n      // timestamp 96 = { nsec32 (unsigned), sec64 (signed) }\n\n      const sec = getInt64(view, 4);\n      const nsec = view.getUint32(0);\n      return { sec, nsec };\n    }\n    default:\n      throw new DecodeError(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${data.length}`);\n  }\n}\n\nexport function decodeTimestampExtension(data: Uint8Array): Date {\n  const timeSpec = decodeTimestampToTimeSpec(data);\n  return new Date(timeSpec.sec * 1e3 + timeSpec.nsec / 1e6);\n}\n\nexport const timestampExtension = {\n  type: EXT_TIMESTAMP,\n  encode: encodeTimestampExtension,\n  decode: decodeTimestampExtension,\n};\n", "// ExtensionCodec to handle MessagePack extensions\n\nimport { ExtData } from \"./ExtData\";\nimport { timestampExtension } from \"./timestamp\";\n\nexport type ExtensionDecoderType<ContextType> = (\n  data: Uint8Array,\n  extensionType: number,\n  context: ContextType,\n) => unknown;\n\nexport type ExtensionEncoderType<ContextType> = (input: unknown, context: ContextType) => Uint8Array | null;\n\n// immutable interface to ExtensionCodec\nexport type ExtensionCodecType<ContextType> = {\n  // eslint-disable-next-line @typescript-eslint/naming-convention\n  __brand?: ContextType;\n  tryToEncode(object: unknown, context: ContextType): ExtData | null;\n  decode(data: Uint8Array, extType: number, context: ContextType): unknown;\n};\n\nexport class ExtensionCodec<ContextType = undefined> implements ExtensionCodecType<ContextType> {\n  public static readonly defaultCodec: ExtensionCodecType<undefined> = new ExtensionCodec();\n\n  // ensures ExtensionCodecType<X> matches ExtensionCodec<X>\n  // this will make type errors a lot more clear\n  // eslint-disable-next-line @typescript-eslint/naming-convention\n  __brand?: ContextType;\n\n  // built-in extensions\n  private readonly builtInEncoders: Array<ExtensionEncoderType<ContextType> | undefined | null> = [];\n  private readonly builtInDecoders: Array<ExtensionDecoderType<ContextType> | undefined | null> = [];\n\n  // custom extensions\n  private readonly encoders: Array<ExtensionEncoderType<ContextType> | undefined | null> = [];\n  private readonly decoders: Array<ExtensionDecoderType<ContextType> | undefined | null> = [];\n\n  public constructor() {\n    this.register(timestampExtension);\n  }\n\n  public register({\n    type,\n    encode,\n    decode,\n  }: {\n    type: number;\n    encode: ExtensionEncoderType<ContextType>;\n    decode: ExtensionDecoderType<ContextType>;\n  }): void {\n    if (type >= 0) {\n      // custom extensions\n      this.encoders[type] = encode;\n      this.decoders[type] = decode;\n    } else {\n      // built-in extensions\n      const index = 1 + type;\n      this.builtInEncoders[index] = encode;\n      this.builtInDecoders[index] = decode;\n    }\n  }\n\n  public tryToEncode(object: unknown, context: ContextType): ExtData | null {\n    // built-in extensions\n    for (let i = 0; i < this.builtInEncoders.length; i++) {\n      const encodeExt = this.builtInEncoders[i];\n      if (encodeExt != null) {\n        const data = encodeExt(object, context);\n        if (data != null) {\n          const type = -1 - i;\n          return new ExtData(type, data);\n        }\n      }\n    }\n\n    // custom extensions\n    for (let i = 0; i < this.encoders.length; i++) {\n      const encodeExt = this.encoders[i];\n      if (encodeExt != null) {\n        const data = encodeExt(object, context);\n        if (data != null) {\n          const type = i;\n          return new ExtData(type, data);\n        }\n      }\n    }\n\n    if (object instanceof ExtData) {\n      // to keep ExtData as is\n      return object;\n    }\n    return null;\n  }\n\n  public decode(data: Uint8Array, type: number, context: ContextType): unknown {\n    const decodeExt = type < 0 ? this.builtInDecoders[-1 - type] : this.decoders[type];\n    if (decodeExt) {\n      return decodeExt(data, type, context);\n    } else {\n      // decode() does not fail, returns ExtData instead.\n      return new ExtData(type, data);\n    }\n  }\n}\n", "export function ensureUint8Array(buffer: ArrayLike<number> | Uint8Array | ArrayBufferView | ArrayBuffer): Uint8Array {\n  if (buffer instanceof Uint8Array) {\n    return buffer;\n  } else if (ArrayBuffer.isView(buffer)) {\n    return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);\n  } else if (buffer instanceof ArrayBuffer) {\n    return new Uint8Array(buffer);\n  } else {\n    // ArrayLike<number>\n    return Uint8Array.from(buffer);\n  }\n}\n\nexport function createDataView(buffer: ArrayLike<number> | ArrayBufferView | ArrayBuffer): DataView {\n  if (buffer instanceof ArrayBuffer) {\n    return new DataView(buffer);\n  }\n\n  const bufferView = ensureUint8Array(buffer);\n  return new DataView(bufferView.buffer, bufferView.byteOffset, bufferView.byteLength);\n}\n", "import { utf8EncodeJs, utf8Count, TEXT_ENCODER_THRESHOLD, utf8EncodeTE } from \"./utils/utf8\";\nimport { ExtensionCodec, ExtensionCodecType } from \"./ExtensionCodec\";\nimport { setInt64, setUint64 } from \"./utils/int\";\nimport { ensureUint8Array } from \"./utils/typedArrays\";\nimport type { ExtData } from \"./ExtData\";\n\nexport const DEFAULT_MAX_DEPTH = 100;\nexport const DEFAULT_INITIAL_BUFFER_SIZE = 2048;\n\nexport class Encoder<ContextType = undefined> {\n  private pos = 0;\n  private view = new DataView(new ArrayBuffer(this.initialBufferSize));\n  private bytes = new Uint8Array(this.view.buffer);\n\n  public constructor(\n    private readonly extensionCodec: ExtensionCodecType<ContextType> = ExtensionCodec.defaultCodec as any,\n    private readonly context: ContextType = undefined as any,\n    private readonly maxDepth = DEFAULT_MAX_DEPTH,\n    private readonly initialBufferSize = DEFAULT_INITIAL_BUFFER_SIZE,\n    private readonly sortKeys = false,\n    private readonly forceFloat32 = false,\n    private readonly ignoreUndefined = false,\n    private readonly forceIntegerToFloat = false,\n  ) {}\n\n  private reinitializeState() {\n    this.pos = 0;\n  }\n\n  /**\n   * This is almost equivalent to {@link Encoder#encode}, but it returns an reference of the encoder's internal buffer and thus much faster than {@link Encoder#encode}.\n   *\n   * @returns Encodes the object and returns a shared reference the encoder's internal buffer.\n   */\n  public encodeSharedRef(object: unknown): Uint8Array {\n    this.reinitializeState();\n    this.doEncode(object, 1);\n    return this.bytes.subarray(0, this.pos);\n  }\n\n  /**\n   * @returns Encodes the object and returns a copy of the encoder's internal buffer.\n   */\n  public encode(object: unknown): Uint8Array {\n    this.reinitializeState();\n    this.doEncode(object, 1);\n    return this.bytes.slice(0, this.pos);\n  }\n\n  private doEncode(object: unknown, depth: number): void {\n    if (depth > this.maxDepth) {\n      throw new Error(`Too deep objects in depth ${depth}`);\n    }\n\n    if (object == null) {\n      this.encodeNil();\n    } else if (typeof object === \"boolean\") {\n      this.encodeBoolean(object);\n    } else if (typeof object === \"number\") {\n      this.encodeNumber(object);\n    } else if (typeof object === \"string\") {\n      this.encodeString(object);\n    } else {\n      this.encodeObject(object, depth);\n    }\n  }\n\n  private ensureBufferSizeToWrite(sizeToWrite: number) {\n    const requiredSize = this.pos + sizeToWrite;\n\n    if (this.view.byteLength < requiredSize) {\n      this.resizeBuffer(requiredSize * 2);\n    }\n  }\n\n  private resizeBuffer(newSize: number) {\n    const newBuffer = new ArrayBuffer(newSize);\n    const newBytes = new Uint8Array(newBuffer);\n    const newView = new DataView(newBuffer);\n\n    newBytes.set(this.bytes);\n\n    this.view = newView;\n    this.bytes = newBytes;\n  }\n\n  private encodeNil() {\n    this.writeU8(0xc0);\n  }\n\n  private encodeBoolean(object: boolean) {\n    if (object === false) {\n      this.writeU8(0xc2);\n    } else {\n      this.writeU8(0xc3);\n    }\n  }\n  private encodeNumber(object: number) {\n    if (Number.isSafeInteger(object) && !this.forceIntegerToFloat) {\n      if (object >= 0) {\n        if (object < 0x80) {\n          // positive fixint\n          this.writeU8(object);\n        } else if (object < 0x100) {\n          // uint 8\n          this.writeU8(0xcc);\n          this.writeU8(object);\n        } else if (object < 0x10000) {\n          // uint 16\n          this.writeU8(0xcd);\n          this.writeU16(object);\n        } else if (object < 0x100000000) {\n          // uint 32\n          this.writeU8(0xce);\n          this.writeU32(object);\n        } else {\n          // uint 64\n          this.writeU8(0xcf);\n          this.writeU64(object);\n        }\n      } else {\n        if (object >= -0x20) {\n          // negative fixint\n          this.writeU8(0xe0 | (object + 0x20));\n        } else if (object >= -0x80) {\n          // int 8\n          this.writeU8(0xd0);\n          this.writeI8(object);\n        } else if (object >= -0x8000) {\n          // int 16\n          this.writeU8(0xd1);\n          this.writeI16(object);\n        } else if (object >= -0x80000000) {\n          // int 32\n          this.writeU8(0xd2);\n          this.writeI32(object);\n        } else {\n          // int 64\n          this.writeU8(0xd3);\n          this.writeI64(object);\n        }\n      }\n    } else {\n      // non-integer numbers\n      if (this.forceFloat32) {\n        // float 32\n        this.writeU8(0xca);\n        this.writeF32(object);\n      } else {\n        // float 64\n        this.writeU8(0xcb);\n        this.writeF64(object);\n      }\n    }\n  }\n\n  private writeStringHeader(byteLength: number) {\n    if (byteLength < 32) {\n      // fixstr\n      this.writeU8(0xa0 + byteLength);\n    } else if (byteLength < 0x100) {\n      // str 8\n      this.writeU8(0xd9);\n      this.writeU8(byteLength);\n    } else if (byteLength < 0x10000) {\n      // str 16\n      this.writeU8(0xda);\n      this.writeU16(byteLength);\n    } else if (byteLength < 0x100000000) {\n      // str 32\n      this.writeU8(0xdb);\n      this.writeU32(byteLength);\n    } else {\n      throw new Error(`Too long string: ${byteLength} bytes in UTF-8`);\n    }\n  }\n\n  private encodeString(object: string) {\n    const maxHeaderSize = 1 + 4;\n    const strLength = object.length;\n\n    if (strLength > TEXT_ENCODER_THRESHOLD) {\n      const byteLength = utf8Count(object);\n      this.ensureBufferSizeToWrite(maxHeaderSize + byteLength);\n      this.writeStringHeader(byteLength);\n      utf8EncodeTE(object, this.bytes, this.pos);\n      this.pos += byteLength;\n    } else {\n      const byteLength = utf8Count(object);\n      this.ensureBufferSizeToWrite(maxHeaderSize + byteLength);\n      this.writeStringHeader(byteLength);\n      utf8EncodeJs(object, this.bytes, this.pos);\n      this.pos += byteLength;\n    }\n  }\n\n  private encodeObject(object: unknown, depth: number) {\n    // try to encode objects with custom codec first of non-primitives\n    const ext = this.extensionCodec.tryToEncode(object, this.context);\n    if (ext != null) {\n      this.encodeExtension(ext);\n    } else if (Array.isArray(object)) {\n      this.encodeArray(object, depth);\n    } else if (ArrayBuffer.isView(object)) {\n      this.encodeBinary(object);\n    } else if (typeof object === \"object\") {\n      this.encodeMap(object as Record<string, unknown>, depth);\n    } else {\n      // symbol, function and other special object come here unless extensionCodec handles them.\n      throw new Error(`Unrecognized object: ${Object.prototype.toString.apply(object)}`);\n    }\n  }\n\n  private encodeBinary(object: ArrayBufferView) {\n    const size = object.byteLength;\n    if (size < 0x100) {\n      // bin 8\n      this.writeU8(0xc4);\n      this.writeU8(size);\n    } else if (size < 0x10000) {\n      // bin 16\n      this.writeU8(0xc5);\n      this.writeU16(size);\n    } else if (size < 0x100000000) {\n      // bin 32\n      this.writeU8(0xc6);\n      this.writeU32(size);\n    } else {\n      throw new Error(`Too large binary: ${size}`);\n    }\n    const bytes = ensureUint8Array(object);\n    this.writeU8a(bytes);\n  }\n\n  private encodeArray(object: Array<unknown>, depth: number) {\n    const size = object.length;\n    if (size < 16) {\n      // fixarray\n      this.writeU8(0x90 + size);\n    } else if (size < 0x10000) {\n      // array 16\n      this.writeU8(0xdc);\n      this.writeU16(size);\n    } else if (size < 0x100000000) {\n      // array 32\n      this.writeU8(0xdd);\n      this.writeU32(size);\n    } else {\n      throw new Error(`Too large array: ${size}`);\n    }\n    for (const item of object) {\n      this.doEncode(item, depth + 1);\n    }\n  }\n\n  private countWithoutUndefined(object: Record<string, unknown>, keys: ReadonlyArray<string>): number {\n    let count = 0;\n\n    for (const key of keys) {\n      if (object[key] !== undefined) {\n        count++;\n      }\n    }\n\n    return count;\n  }\n\n  private encodeMap(object: Record<string, unknown>, depth: number) {\n    const keys = Object.keys(object);\n    if (this.sortKeys) {\n      keys.sort();\n    }\n\n    const size = this.ignoreUndefined ? this.countWithoutUndefined(object, keys) : keys.length;\n\n    if (size < 16) {\n      // fixmap\n      this.writeU8(0x80 + size);\n    } else if (size < 0x10000) {\n      // map 16\n      this.writeU8(0xde);\n      this.writeU16(size);\n    } else if (size < 0x100000000) {\n      // map 32\n      this.writeU8(0xdf);\n      this.writeU32(size);\n    } else {\n      throw new Error(`Too large map object: ${size}`);\n    }\n\n    for (const key of keys) {\n      const value = object[key];\n\n      if (!(this.ignoreUndefined && value === undefined)) {\n        this.encodeString(key);\n        this.doEncode(value, depth + 1);\n      }\n    }\n  }\n\n  private encodeExtension(ext: ExtData) {\n    const size = ext.data.length;\n    if (size === 1) {\n      // fixext 1\n      this.writeU8(0xd4);\n    } else if (size === 2) {\n      // fixext 2\n      this.writeU8(0xd5);\n    } else if (size === 4) {\n      // fixext 4\n      this.writeU8(0xd6);\n    } else if (size === 8) {\n      // fixext 8\n      this.writeU8(0xd7);\n    } else if (size === 16) {\n      // fixext 16\n      this.writeU8(0xd8);\n    } else if (size < 0x100) {\n      // ext 8\n      this.writeU8(0xc7);\n      this.writeU8(size);\n    } else if (size < 0x10000) {\n      // ext 16\n      this.writeU8(0xc8);\n      this.writeU16(size);\n    } else if (size < 0x100000000) {\n      // ext 32\n      this.writeU8(0xc9);\n      this.writeU32(size);\n    } else {\n      throw new Error(`Too large extension object: ${size}`);\n    }\n    this.writeI8(ext.type);\n    this.writeU8a(ext.data);\n  }\n\n  private writeU8(value: number) {\n    this.ensureBufferSizeToWrite(1);\n\n    this.view.setUint8(this.pos, value);\n    this.pos++;\n  }\n\n  private writeU8a(values: ArrayLike<number>) {\n    const size = values.length;\n    this.ensureBufferSizeToWrite(size);\n\n    this.bytes.set(values, this.pos);\n    this.pos += size;\n  }\n\n  private writeI8(value: number) {\n    this.ensureBufferSizeToWrite(1);\n\n    this.view.setInt8(this.pos, value);\n    this.pos++;\n  }\n\n  private writeU16(value: number) {\n    this.ensureBufferSizeToWrite(2);\n\n    this.view.setUint16(this.pos, value);\n    this.pos += 2;\n  }\n\n  private writeI16(value: number) {\n    this.ensureBufferSizeToWrite(2);\n\n    this.view.setInt16(this.pos, value);\n    this.pos += 2;\n  }\n\n  private writeU32(value: number) {\n    this.ensureBufferSizeToWrite(4);\n\n    this.view.setUint32(this.pos, value);\n    this.pos += 4;\n  }\n\n  private writeI32(value: number) {\n    this.ensureBufferSizeToWrite(4);\n\n    this.view.setInt32(this.pos, value);\n    this.pos += 4;\n  }\n\n  private writeF32(value: number) {\n    this.ensureBufferSizeToWrite(4);\n    this.view.setFloat32(this.pos, value);\n    this.pos += 4;\n  }\n\n  private writeF64(value: number) {\n    this.ensureBufferSizeToWrite(8);\n    this.view.setFloat64(this.pos, value);\n    this.pos += 8;\n  }\n\n  private writeU64(value: number) {\n    this.ensureBufferSizeToWrite(8);\n\n    setUint64(this.view, this.pos, value);\n    this.pos += 8;\n  }\n\n  private writeI64(value: number) {\n    this.ensureBufferSizeToWrite(8);\n\n    setInt64(this.view, this.pos, value);\n    this.pos += 8;\n  }\n}\n", "import { Encoder } from \"./Encoder\";\nimport type { ExtensionCodecType } from \"./ExtensionCodec\";\nimport type { ContextOf, SplitUndefined } from \"./context\";\n\nexport type EncodeOptions<ContextType = undefined> = Partial<\n  Readonly<{\n    extensionCodec: ExtensionCodecType<ContextType>;\n\n    /**\n     * The maximum depth in nested objects and arrays.\n     *\n     * Defaults to 100.\n     */\n    maxDepth: number;\n\n    /**\n     * The initial size of the internal buffer.\n     *\n     * Defaults to 2048.\n     */\n    initialBufferSize: number;\n\n    /**\n     * If `true`, the keys of an object is sorted. In other words, the encoded\n     * binary is canonical and thus comparable to another encoded binary.\n     *\n     * Defaults to `false`. If enabled, it spends more time in encoding objects.\n     */\n    sortKeys: boolean;\n    /**\n     * If `true`, non-integer numbers are encoded in float32, not in float64 (the default).\n     *\n     * Only use it if precisions don't matter.\n     *\n     * Defaults to `false`.\n     */\n    forceFloat32: boolean;\n\n    /**\n     * If `true`, an object property with `undefined` value are ignored.\n     * e.g. `{ foo: undefined }` will be encoded as `{}`, as `JSON.stringify()` does.\n     *\n     * Defaults to `false`. If enabled, it spends more time in encoding objects.\n     */\n    ignoreUndefined: boolean;\n\n    /**\n     * If `true`, integer numbers are encoded as floating point numbers,\n     * with the `forceFloat32` option taken into account.\n     *\n     * Defaults to `false`.\n     */\n    forceIntegerToFloat: boolean;\n  }>\n> &\n  ContextOf<ContextType>;\n\nconst defaultEncodeOptions: EncodeOptions = {};\n\n/**\n * It encodes `value` in the MessagePack format and\n * returns a byte buffer.\n *\n * The returned buffer is a slice of a larger `ArrayBuffer`, so you have to use its `#byteOffset` and `#byteLength` in order to convert it to another typed arrays including NodeJS `Buffer`.\n */\nexport function encode<ContextType = undefined>(\n  value: unknown,\n  options: EncodeOptions<SplitUndefined<ContextType>> = defaultEncodeOptions as any,\n): Uint8Array {\n  const encoder = new Encoder(\n    options.extensionCodec,\n    (options as typeof options & { context: any }).context,\n    options.maxDepth,\n    options.initialBufferSize,\n    options.sortKeys,\n    options.forceFloat32,\n    options.ignoreUndefined,\n    options.forceIntegerToFloat,\n  );\n  return encoder.encodeSharedRef(value);\n}\n", "export function prettyByte(byte: number): string {\n  return `${byte < 0 ? \"-\" : \"\"}0x${Math.abs(byte).toString(16).padStart(2, \"0\")}`;\n}\n", "import { utf8DecodeJs } from \"./utils/utf8\";\n\nconst DEFAULT_MAX_KEY_LENGTH = 16;\nconst DEFAULT_MAX_LENGTH_PER_KEY = 16;\n\nexport interface KeyDecoder {\n  canBeCached(byteLength: number): boolean;\n  decode(bytes: Uint8Array, inputOffset: number, byteLength: number): string;\n}\ninterface KeyCacheRecord {\n  readonly bytes: Uint8Array;\n  readonly str: string;\n}\n\nexport class CachedKeyDecoder implements KeyDecoder {\n  hit = 0;\n  miss = 0;\n  private readonly caches: Array<Array<KeyCacheRecord>>;\n\n  constructor(readonly maxKeyLength = DEFAULT_MAX_KEY_LENGTH, readonly maxLengthPerKey = DEFAULT_MAX_LENGTH_PER_KEY) {\n    // avoid `new Array(N)`, which makes a sparse array,\n    // because a sparse array is typically slower than a non-sparse array.\n    this.caches = [];\n    for (let i = 0; i < this.maxKeyLength; i++) {\n      this.caches.push([]);\n    }\n  }\n\n  public canBeCached(byteLength: number): boolean {\n    return byteLength > 0 && byteLength <= this.maxKeyLength;\n  }\n\n  private find(bytes: Uint8Array, inputOffset: number, byteLength: number): string | null {\n    const records = this.caches[byteLength - 1]!;\n\n    FIND_CHUNK: for (const record of records) {\n      const recordBytes = record.bytes;\n\n      for (let j = 0; j < byteLength; j++) {\n        if (recordBytes[j] !== bytes[inputOffset + j]) {\n          continue FIND_CHUNK;\n        }\n      }\n      return record.str;\n    }\n    return null;\n  }\n\n  private store(bytes: Uint8Array, value: string) {\n    const records = this.caches[bytes.length - 1]!;\n    const record: KeyCacheRecord = { bytes, str: value };\n\n    if (records.length >= this.maxLengthPerKey) {\n      // `records` are full!\n      // Set `record` to an arbitrary position.\n      records[(Math.random() * records.length) | 0] = record;\n    } else {\n      records.push(record);\n    }\n  }\n\n  public decode(bytes: Uint8Array, inputOffset: number, byteLength: number): string {\n    const cachedValue = this.find(bytes, inputOffset, byteLength);\n    if (cachedValue != null) {\n      this.hit++;\n      return cachedValue;\n    }\n    this.miss++;\n\n    const str = utf8DecodeJs(bytes, inputOffset, byteLength);\n    // Ensure to copy a slice of bytes because the byte may be NodeJS Buffer and Buffer#slice() returns a reference to its internal ArrayBuffer.\n    const slicedCopyOfBytes = Uint8Array.prototype.slice.call(bytes, inputOffset, inputOffset + byteLength);\n    this.store(slicedCopyOfBytes, str);\n    return str;\n  }\n}\n", "import { prettyByte } from \"./utils/prettyByte\";\nimport { ExtensionCodec, ExtensionCodecType } from \"./ExtensionCodec\";\nimport { getInt64, getUint64, UINT32_MAX } from \"./utils/int\";\nimport { utf8DecodeJs, TEXT_DECODER_THRESHOLD, utf8DecodeTD } from \"./utils/utf8\";\nimport { createDataView, ensureUint8Array } from \"./utils/typedArrays\";\nimport { CachedKeyDecoder, KeyDecoder } from \"./CachedKeyDecoder\";\nimport { DecodeError } from \"./DecodeError\";\n\nconst enum State {\n  ARRAY,\n  MAP_KEY,\n  MAP_VALUE,\n}\n\ntype MapKeyType = string | number;\n\nconst isValidMapKeyType = (key: unknown): key is MapKeyType => {\n  const keyType = typeof key;\n\n  return keyType === \"string\" || keyType === \"number\";\n};\n\ntype StackMapState = {\n  type: State.MAP_KEY | State.MAP_VALUE;\n  size: number;\n  key: MapKeyType | null;\n  readCount: number;\n  map: Record<string, unknown>;\n};\n\ntype StackArrayState = {\n  type: State.ARRAY;\n  size: number;\n  array: Array<unknown>;\n  position: number;\n};\n\ntype StackState = StackArrayState | StackMapState;\n\nconst HEAD_BYTE_REQUIRED = -1;\n\nconst EMPTY_VIEW = new DataView(new ArrayBuffer(0));\nconst EMPTY_BYTES = new Uint8Array(EMPTY_VIEW.buffer);\n\n// IE11: Hack to support IE11.\n// IE11: Drop this hack and just use RangeError when IE11 is obsolete.\nexport const DataViewIndexOutOfBoundsError: typeof Error = (() => {\n  try {\n    // IE11: The spec says it should throw RangeError,\n    // IE11: but in IE11 it throws TypeError.\n    EMPTY_VIEW.getInt8(0);\n  } catch (e: any) {\n    return e.constructor;\n  }\n  throw new Error(\"never reached\");\n})();\n\nconst MORE_DATA = new DataViewIndexOutOfBoundsError(\"Insufficient data\");\n\nconst sharedCachedKeyDecoder = new CachedKeyDecoder();\n\nexport class Decoder<ContextType = undefined> {\n  private totalPos = 0;\n  private pos = 0;\n\n  private view = EMPTY_VIEW;\n  private bytes = EMPTY_BYTES;\n  private headByte = HEAD_BYTE_REQUIRED;\n  private readonly stack: Array<StackState> = [];\n\n  public constructor(\n    private readonly extensionCodec: ExtensionCodecType<ContextType> = ExtensionCodec.defaultCodec as any,\n    private readonly context: ContextType = undefined as any,\n    private readonly maxStrLength = UINT32_MAX,\n    private readonly maxBinLength = UINT32_MAX,\n    private readonly maxArrayLength = UINT32_MAX,\n    private readonly maxMapLength = UINT32_MAX,\n    private readonly maxExtLength = UINT32_MAX,\n    private readonly keyDecoder: KeyDecoder | null = sharedCachedKeyDecoder,\n  ) {}\n\n  private reinitializeState() {\n    this.totalPos = 0;\n    this.headByte = HEAD_BYTE_REQUIRED;\n    this.stack.length = 0;\n\n    // view, bytes, and pos will be re-initialized in setBuffer()\n  }\n\n  private setBuffer(buffer: ArrayLike<number> | BufferSource): void {\n    this.bytes = ensureUint8Array(buffer);\n    this.view = createDataView(this.bytes);\n    this.pos = 0;\n  }\n\n  private appendBuffer(buffer: ArrayLike<number> | BufferSource) {\n    if (this.headByte === HEAD_BYTE_REQUIRED && !this.hasRemaining(1)) {\n      this.setBuffer(buffer);\n    } else {\n      const remainingData = this.bytes.subarray(this.pos);\n      const newData = ensureUint8Array(buffer);\n\n      // concat remainingData + newData\n      const newBuffer = new Uint8Array(remainingData.length + newData.length);\n      newBuffer.set(remainingData);\n      newBuffer.set(newData, remainingData.length);\n      this.setBuffer(newBuffer);\n    }\n  }\n\n  private hasRemaining(size: number) {\n    return this.view.byteLength - this.pos >= size;\n  }\n\n  private createExtraByteError(posToShow: number): Error {\n    const { view, pos } = this;\n    return new RangeError(`Extra ${view.byteLength - pos} of ${view.byteLength} byte(s) found at buffer[${posToShow}]`);\n  }\n\n  /**\n   * @throws {@link DecodeError}\n   * @throws {@link RangeError}\n   */\n  public decode(buffer: ArrayLike<number> | BufferSource): unknown {\n    this.reinitializeState();\n    this.setBuffer(buffer);\n\n    const object = this.doDecodeSync();\n    if (this.hasRemaining(1)) {\n      throw this.createExtraByteError(this.pos);\n    }\n    return object;\n  }\n\n  public *decodeMulti(buffer: ArrayLike<number> | BufferSource): Generator<unknown, void, unknown> {\n    this.reinitializeState();\n    this.setBuffer(buffer);\n\n    while (this.hasRemaining(1)) {\n      yield this.doDecodeSync();\n    }\n  }\n\n  public async decodeAsync(stream: AsyncIterable<ArrayLike<number> | BufferSource>): Promise<unknown> {\n    let decoded = false;\n    let object: unknown;\n    for await (const buffer of stream) {\n      if (decoded) {\n        throw this.createExtraByteError(this.totalPos);\n      }\n\n      this.appendBuffer(buffer);\n\n      try {\n        object = this.doDecodeSync();\n        decoded = true;\n      } catch (e) {\n        if (!(e instanceof DataViewIndexOutOfBoundsError)) {\n          throw e; // rethrow\n        }\n        // fallthrough\n      }\n      this.totalPos += this.pos;\n    }\n\n    if (decoded) {\n      if (this.hasRemaining(1)) {\n        throw this.createExtraByteError(this.totalPos);\n      }\n      return object;\n    }\n\n    const { headByte, pos, totalPos } = this;\n    throw new RangeError(\n      `Insufficient data in parsing ${prettyByte(headByte)} at ${totalPos} (${pos} in the current buffer)`,\n    );\n  }\n\n  public decodeArrayStream(\n    stream: AsyncIterable<ArrayLike<number> | BufferSource>,\n  ): AsyncGenerator<unknown, void, unknown> {\n    return this.decodeMultiAsync(stream, true);\n  }\n\n  public decodeStream(stream: AsyncIterable<ArrayLike<number> | BufferSource>): AsyncGenerator<unknown, void, unknown> {\n    return this.decodeMultiAsync(stream, false);\n  }\n\n  private async *decodeMultiAsync(stream: AsyncIterable<ArrayLike<number> | BufferSource>, isArray: boolean) {\n    let isArrayHeaderRequired = isArray;\n    let arrayItemsLeft = -1;\n\n    for await (const buffer of stream) {\n      if (isArray && arrayItemsLeft === 0) {\n        throw this.createExtraByteError(this.totalPos);\n      }\n\n      this.appendBuffer(buffer);\n\n      if (isArrayHeaderRequired) {\n        arrayItemsLeft = this.readArraySize();\n        isArrayHeaderRequired = false;\n        this.complete();\n      }\n\n      try {\n        while (true) {\n          yield this.doDecodeSync();\n          if (--arrayItemsLeft === 0) {\n            break;\n          }\n        }\n      } catch (e) {\n        if (!(e instanceof DataViewIndexOutOfBoundsError)) {\n          throw e; // rethrow\n        }\n        // fallthrough\n      }\n      this.totalPos += this.pos;\n    }\n  }\n\n  private doDecodeSync(): unknown {\n    DECODE: while (true) {\n      const headByte = this.readHeadByte();\n      let object: unknown;\n\n      if (headByte >= 0xe0) {\n        // negative fixint (111x xxxx) 0xe0 - 0xff\n        object = headByte - 0x100;\n      } else if (headByte < 0xc0) {\n        if (headByte < 0x80) {\n          // positive fixint (0xxx xxxx) 0x00 - 0x7f\n          object = headByte;\n        } else if (headByte < 0x90) {\n          // fixmap (1000 xxxx) 0x80 - 0x8f\n          const size = headByte - 0x80;\n          if (size !== 0) {\n            this.pushMapState(size);\n            this.complete();\n            continue DECODE;\n          } else {\n            object = {};\n          }\n        } else if (headByte < 0xa0) {\n          // fixarray (1001 xxxx) 0x90 - 0x9f\n          const size = headByte - 0x90;\n          if (size !== 0) {\n            this.pushArrayState(size);\n            this.complete();\n            continue DECODE;\n          } else {\n            object = [];\n          }\n        } else {\n          // fixstr (101x xxxx) 0xa0 - 0xbf\n          const byteLength = headByte - 0xa0;\n          object = this.decodeUtf8String(byteLength, 0);\n        }\n      } else if (headByte === 0xc0) {\n        // nil\n        object = null;\n      } else if (headByte === 0xc2) {\n        // false\n        object = false;\n      } else if (headByte === 0xc3) {\n        // true\n        object = true;\n      } else if (headByte === 0xca) {\n        // float 32\n        object = this.readF32();\n      } else if (headByte === 0xcb) {\n        // float 64\n        object = this.readF64();\n      } else if (headByte === 0xcc) {\n        // uint 8\n        object = this.readU8();\n      } else if (headByte === 0xcd) {\n        // uint 16\n        object = this.readU16();\n      } else if (headByte === 0xce) {\n        // uint 32\n        object = this.readU32();\n      } else if (headByte === 0xcf) {\n        // uint 64\n        object = this.readU64();\n      } else if (headByte === 0xd0) {\n        // int 8\n        object = this.readI8();\n      } else if (headByte === 0xd1) {\n        // int 16\n        object = this.readI16();\n      } else if (headByte === 0xd2) {\n        // int 32\n        object = this.readI32();\n      } else if (headByte === 0xd3) {\n        // int 64\n        object = this.readI64();\n      } else if (headByte === 0xd9) {\n        // str 8\n        const byteLength = this.lookU8();\n        object = this.decodeUtf8String(byteLength, 1);\n      } else if (headByte === 0xda) {\n        // str 16\n        const byteLength = this.lookU16();\n        object = this.decodeUtf8String(byteLength, 2);\n      } else if (headByte === 0xdb) {\n        // str 32\n        const byteLength = this.lookU32();\n        object = this.decodeUtf8String(byteLength, 4);\n      } else if (headByte === 0xdc) {\n        // array 16\n        const size = this.readU16();\n        if (size !== 0) {\n          this.pushArrayState(size);\n          this.complete();\n          continue DECODE;\n        } else {\n          object = [];\n        }\n      } else if (headByte === 0xdd) {\n        // array 32\n        const size = this.readU32();\n        if (size !== 0) {\n          this.pushArrayState(size);\n          this.complete();\n          continue DECODE;\n        } else {\n          object = [];\n        }\n      } else if (headByte === 0xde) {\n        // map 16\n        const size = this.readU16();\n        if (size !== 0) {\n          this.pushMapState(size);\n          this.complete();\n          continue DECODE;\n        } else {\n          object = {};\n        }\n      } else if (headByte === 0xdf) {\n        // map 32\n        const size = this.readU32();\n        if (size !== 0) {\n          this.pushMapState(size);\n          this.complete();\n          continue DECODE;\n        } else {\n          object = {};\n        }\n      } else if (headByte === 0xc4) {\n        // bin 8\n        const size = this.lookU8();\n        object = this.decodeBinary(size, 1);\n      } else if (headByte === 0xc5) {\n        // bin 16\n        const size = this.lookU16();\n        object = this.decodeBinary(size, 2);\n      } else if (headByte === 0xc6) {\n        // bin 32\n        const size = this.lookU32();\n        object = this.decodeBinary(size, 4);\n      } else if (headByte === 0xd4) {\n        // fixext 1\n        object = this.decodeExtension(1, 0);\n      } else if (headByte === 0xd5) {\n        // fixext 2\n        object = this.decodeExtension(2, 0);\n      } else if (headByte === 0xd6) {\n        // fixext 4\n        object = this.decodeExtension(4, 0);\n      } else if (headByte === 0xd7) {\n        // fixext 8\n        object = this.decodeExtension(8, 0);\n      } else if (headByte === 0xd8) {\n        // fixext 16\n        object = this.decodeExtension(16, 0);\n      } else if (headByte === 0xc7) {\n        // ext 8\n        const size = this.lookU8();\n        object = this.decodeExtension(size, 1);\n      } else if (headByte === 0xc8) {\n        // ext 16\n        const size = this.lookU16();\n        object = this.decodeExtension(size, 2);\n      } else if (headByte === 0xc9) {\n        // ext 32\n        const size = this.lookU32();\n        object = this.decodeExtension(size, 4);\n      } else {\n        throw new DecodeError(`Unrecognized type byte: ${prettyByte(headByte)}`);\n      }\n\n      this.complete();\n\n      const stack = this.stack;\n      while (stack.length > 0) {\n        // arrays and maps\n        const state = stack[stack.length - 1]!;\n        if (state.type === State.ARRAY) {\n          state.array[state.position] = object;\n          state.position++;\n          if (state.position === state.size) {\n            stack.pop();\n            object = state.array;\n          } else {\n            continue DECODE;\n          }\n        } else if (state.type === State.MAP_KEY) {\n          if (!isValidMapKeyType(object)) {\n            throw new DecodeError(\"The type of key must be string or number but \" + typeof object);\n          }\n          if (object === \"__proto__\") {\n            throw new DecodeError(\"The key __proto__ is not allowed\");\n          }\n\n          state.key = object;\n          state.type = State.MAP_VALUE;\n          continue DECODE;\n        } else {\n          // it must be `state.type === State.MAP_VALUE` here\n\n          state.map[state.key!] = object;\n          state.readCount++;\n\n          if (state.readCount === state.size) {\n            stack.pop();\n            object = state.map;\n          } else {\n            state.key = null;\n            state.type = State.MAP_KEY;\n            continue DECODE;\n          }\n        }\n      }\n\n      return object;\n    }\n  }\n\n  private readHeadByte(): number {\n    if (this.headByte === HEAD_BYTE_REQUIRED) {\n      this.headByte = this.readU8();\n      // console.log(\"headByte\", prettyByte(this.headByte));\n    }\n\n    return this.headByte;\n  }\n\n  private complete(): void {\n    this.headByte = HEAD_BYTE_REQUIRED;\n  }\n\n  private readArraySize(): number {\n    const headByte = this.readHeadByte();\n\n    switch (headByte) {\n      case 0xdc:\n        return this.readU16();\n      case 0xdd:\n        return this.readU32();\n      default: {\n        if (headByte < 0xa0) {\n          return headByte - 0x90;\n        } else {\n          throw new DecodeError(`Unrecognized array type byte: ${prettyByte(headByte)}`);\n        }\n      }\n    }\n  }\n\n  private pushMapState(size: number) {\n    if (size > this.maxMapLength) {\n      throw new DecodeError(`Max length exceeded: map length (${size}) > maxMapLengthLength (${this.maxMapLength})`);\n    }\n\n    this.stack.push({\n      type: State.MAP_KEY,\n      size,\n      key: null,\n      readCount: 0,\n      map: {},\n    });\n  }\n\n  private pushArrayState(size: number) {\n    if (size > this.maxArrayLength) {\n      throw new DecodeError(`Max length exceeded: array length (${size}) > maxArrayLength (${this.maxArrayLength})`);\n    }\n\n    this.stack.push({\n      type: State.ARRAY,\n      size,\n      array: new Array<unknown>(size),\n      position: 0,\n    });\n  }\n\n  private decodeUtf8String(byteLength: number, headerOffset: number): string {\n    if (byteLength > this.maxStrLength) {\n      throw new DecodeError(\n        `Max length exceeded: UTF-8 byte length (${byteLength}) > maxStrLength (${this.maxStrLength})`,\n      );\n    }\n\n    if (this.bytes.byteLength < this.pos + headerOffset + byteLength) {\n      throw MORE_DATA;\n    }\n\n    const offset = this.pos + headerOffset;\n    let object: string;\n    if (this.stateIsMapKey() && this.keyDecoder?.canBeCached(byteLength)) {\n      object = this.keyDecoder.decode(this.bytes, offset, byteLength);\n    } else if (byteLength > TEXT_DECODER_THRESHOLD) {\n      object = utf8DecodeTD(this.bytes, offset, byteLength);\n    } else {\n      object = utf8DecodeJs(this.bytes, offset, byteLength);\n    }\n    this.pos += headerOffset + byteLength;\n    return object;\n  }\n\n  private stateIsMapKey(): boolean {\n    if (this.stack.length > 0) {\n      const state = this.stack[this.stack.length - 1]!;\n      return state.type === State.MAP_KEY;\n    }\n    return false;\n  }\n\n  private decodeBinary(byteLength: number, headOffset: number): Uint8Array {\n    if (byteLength > this.maxBinLength) {\n      throw new DecodeError(`Max length exceeded: bin length (${byteLength}) > maxBinLength (${this.maxBinLength})`);\n    }\n\n    if (!this.hasRemaining(byteLength + headOffset)) {\n      throw MORE_DATA;\n    }\n\n    const offset = this.pos + headOffset;\n    const object = this.bytes.subarray(offset, offset + byteLength);\n    this.pos += headOffset + byteLength;\n    return object;\n  }\n\n  private decodeExtension(size: number, headOffset: number): unknown {\n    if (size > this.maxExtLength) {\n      throw new DecodeError(`Max length exceeded: ext length (${size}) > maxExtLength (${this.maxExtLength})`);\n    }\n\n    const extType = this.view.getInt8(this.pos + headOffset);\n    const data = this.decodeBinary(size, headOffset + 1 /* extType */);\n    return this.extensionCodec.decode(data, extType, this.context);\n  }\n\n  private lookU8() {\n    return this.view.getUint8(this.pos);\n  }\n\n  private lookU16() {\n    return this.view.getUint16(this.pos);\n  }\n\n  private lookU32() {\n    return this.view.getUint32(this.pos);\n  }\n\n  private readU8(): number {\n    const value = this.view.getUint8(this.pos);\n    this.pos++;\n    return value;\n  }\n\n  private readI8(): number {\n    const value = this.view.getInt8(this.pos);\n    this.pos++;\n    return value;\n  }\n\n  private readU16(): number {\n    const value = this.view.getUint16(this.pos);\n    this.pos += 2;\n    return value;\n  }\n\n  private readI16(): number {\n    const value = this.view.getInt16(this.pos);\n    this.pos += 2;\n    return value;\n  }\n\n  private readU32(): number {\n    const value = this.view.getUint32(this.pos);\n    this.pos += 4;\n    return value;\n  }\n\n  private readI32(): number {\n    const value = this.view.getInt32(this.pos);\n    this.pos += 4;\n    return value;\n  }\n\n  private readU64(): number {\n    const value = getUint64(this.view, this.pos);\n    this.pos += 8;\n    return value;\n  }\n\n  private readI64(): number {\n    const value = getInt64(this.view, this.pos);\n    this.pos += 8;\n    return value;\n  }\n\n  private readF32() {\n    const value = this.view.getFloat32(this.pos);\n    this.pos += 4;\n    return value;\n  }\n\n  private readF64() {\n    const value = this.view.getFloat64(this.pos);\n    this.pos += 8;\n    return value;\n  }\n}\n", "import { Decoder } from \"./Decoder\";\nimport type { ExtensionCodecType } from \"./ExtensionCodec\";\nimport type { ContextOf, SplitUndefined } from \"./context\";\n\nexport type DecodeOptions<ContextType = undefined> = Readonly<\n  Partial<{\n    extensionCodec: ExtensionCodecType<ContextType>;\n\n    /**\n     * Maximum string length.\n     *\n     * Defaults to 4_294_967_295 (UINT32_MAX).\n     */\n    maxStrLength: number;\n    /**\n     * Maximum binary length.\n     *\n     * Defaults to 4_294_967_295 (UINT32_MAX).\n     */\n    maxBinLength: number;\n    /**\n     * Maximum array length.\n     *\n     * Defaults to 4_294_967_295 (UINT32_MAX).\n     */\n    maxArrayLength: number;\n    /**\n     * Maximum map length.\n     *\n     * Defaults to 4_294_967_295 (UINT32_MAX).\n     */\n    maxMapLength: number;\n    /**\n     * Maximum extension length.\n     *\n     * Defaults to 4_294_967_295 (UINT32_MAX).\n     */\n    maxExtLength: number;\n  }>\n> &\n  ContextOf<ContextType>;\n\nexport const defaultDecodeOptions: DecodeOptions = {};\n\n/**\n * It decodes a single MessagePack object in a buffer.\n *\n * This is a synchronous decoding function.\n * See other variants for asynchronous decoding: {@link decodeAsync()}, {@link decodeStream()}, or {@link decodeArrayStream()}.\n *\n * @throws {@link RangeError} if the buffer is incomplete, including the case where the buffer is empty.\n * @throws {@link DecodeError} if the buffer contains invalid data.\n */\nexport function decode<ContextType = undefined>(\n  buffer: ArrayLike<number> | BufferSource,\n  options: DecodeOptions<SplitUndefined<ContextType>> = defaultDecodeOptions as any,\n): unknown {\n  const decoder = new Decoder(\n    options.extensionCodec,\n    (options as typeof options & { context: any }).context,\n    options.maxStrLength,\n    options.maxBinLength,\n    options.maxArrayLength,\n    options.maxMapLength,\n    options.maxExtLength,\n  );\n  return decoder.decode(buffer);\n}\n\n/**\n * It decodes multiple MessagePack objects in a buffer.\n * This is corresponding to {@link decodeMultiStream()}.\n *\n * @throws {@link RangeError} if the buffer is incomplete, including the case where the buffer is empty.\n * @throws {@link DecodeError} if the buffer contains invalid data.\n */\nexport function decodeMulti<ContextType = undefined>(\n  buffer: ArrayLike<number> | BufferSource,\n  options: DecodeOptions<SplitUndefined<ContextType>> = defaultDecodeOptions as any,\n): Generator<unknown, void, unknown> {\n  const decoder = new Decoder(\n    options.extensionCodec,\n    (options as typeof options & { context: any }).context,\n    options.maxStrLength,\n    options.maxBinLength,\n    options.maxArrayLength,\n    options.maxMapLength,\n    options.maxExtLength,\n  );\n  return decoder.decodeMulti(buffer);\n}\n", "// utility for whatwg streams\n\n// The living standard of whatwg streams says\n// ReadableStream is also AsyncIterable, but\n// as of June 2019, no browser implements it.\n// See https://streams.spec.whatwg.org/ for details\nexport type ReadableStreamLike<T> = AsyncIterable<T> | ReadableStream<T>;\n\nexport function isAsyncIterable<T>(object: ReadableStreamLike<T>): object is AsyncIterable<T> {\n  return (object as any)[Symbol.asyncIterator] != null;\n}\n\nfunction assertNonNull<T>(value: T | null | undefined): asserts value is T {\n  if (value == null) {\n    throw new Error(\"Assertion Failure: value must not be null nor undefined\");\n  }\n}\n\nexport async function* asyncIterableFromStream<T>(stream: ReadableStream<T>): AsyncIterable<T> {\n  const reader = stream.getReader();\n\n  try {\n    while (true) {\n      const { done, value } = await reader.read();\n      if (done) {\n        return;\n      }\n      assertNonNull(value);\n      yield value;\n    }\n  } finally {\n    reader.releaseLock();\n  }\n}\n\nexport function ensureAsyncIterable<T>(streamLike: ReadableStreamLike<T>): AsyncIterable<T> {\n  if (isAsyncIterable(streamLike)) {\n    return streamLike;\n  } else {\n    return asyncIterableFromStream(streamLike);\n  }\n}\n", "import { Decoder } from \"./Decoder\";\nimport { ensureAsyncIterable } from \"./utils/stream\";\nimport { defaultDecodeOptions } from \"./decode\";\nimport type { ReadableStreamLike } from \"./utils/stream\";\nimport type { DecodeOptions } from \"./decode\";\nimport type { SplitUndefined } from \"./context\";\n\n/**\n * @throws {@link RangeError} if the buffer is incomplete, including the case where the buffer is empty.\n * @throws {@link DecodeError} if the buffer contains invalid data.\n */\n export async function decodeAsync<ContextType>(\n  streamLike: ReadableStreamLike<ArrayLike<number> | BufferSource>,\n  options: DecodeOptions<SplitUndefined<ContextType>> = defaultDecodeOptions as any,\n): Promise<unknown> {\n  const stream = ensureAsyncIterable(streamLike);\n\n  const decoder = new Decoder(\n    options.extensionCodec,\n    (options as typeof options & { context: any }).context,\n    options.maxStrLength,\n    options.maxBinLength,\n    options.maxArrayLength,\n    options.maxMapLength,\n    options.maxExtLength,\n  );\n  return decoder.decodeAsync(stream);\n}\n\n/**\n * @throws {@link RangeError} if the buffer is incomplete, including the case where the buffer is empty.\n * @throws {@link DecodeError} if the buffer contains invalid data.\n */\n export function decodeArrayStream<ContextType>(\n  streamLike: ReadableStreamLike<ArrayLike<number> | BufferSource>,\n  options: DecodeOptions<SplitUndefined<ContextType>> = defaultDecodeOptions as any,\n): AsyncGenerator<unknown, void, unknown> {\n  const stream = ensureAsyncIterable(streamLike);\n\n  const decoder = new Decoder(\n    options.extensionCodec,\n    (options as typeof options & { context: any }).context,\n    options.maxStrLength,\n    options.maxBinLength,\n    options.maxArrayLength,\n    options.maxMapLength,\n    options.maxExtLength,\n  );\n\n  return decoder.decodeArrayStream(stream);\n}\n\n/**\n * @throws {@link RangeError} if the buffer is incomplete, including the case where the buffer is empty.\n * @throws {@link DecodeError} if the buffer contains invalid data.\n */\nexport function decodeMultiStream<ContextType>(\n  streamLike: ReadableStreamLike<ArrayLike<number> | BufferSource>,\n  options: DecodeOptions<SplitUndefined<ContextType>> = defaultDecodeOptions as any,\n): AsyncGenerator<unknown, void, unknown> {\n  const stream = ensureAsyncIterable(streamLike);\n\n  const decoder = new Decoder(\n    options.extensionCodec,\n    (options as typeof options & { context: any }).context,\n    options.maxStrLength,\n    options.maxBinLength,\n    options.maxArrayLength,\n    options.maxMapLength,\n    options.maxExtLength,\n  );\n\n  return decoder.decodeStream(stream);\n}\n\n/**\n * @deprecated Use {@link decodeMultiStream()} instead.\n */\nexport function decodeStream<ContextType>(\n  streamLike: ReadableStreamLike<ArrayLike<number> | BufferSource>,\n  options: DecodeOptions<SplitUndefined<ContextType>> = defaultDecodeOptions as any,\n): AsyncGenerator<unknown, void, unknown> {\n  return decodeMultiStream(streamLike, options);\n}\n", "// Main Functions:\n\nimport { encode } from \"./encode\";\nexport { encode };\nimport type { EncodeOptions } from \"./encode\";\nexport type { EncodeOptions };\n\nimport { decode, decodeMulti } from \"./decode\";\nexport { decode, decodeMulti };\nimport type { DecodeOptions } from \"./decode\";\nexport { DecodeOptions };\n\nimport { decodeAsync, decodeArrayStream, decodeMultiStream, decodeStream } from \"./decodeAsync\";\nexport { decodeAsync, decodeArrayStream, decodeMultiStream, decodeStream };\n\nimport { Decoder, DataViewIndexOutOfBoundsError } from \"./Decoder\";\nimport { DecodeError } from \"./DecodeError\";\nexport { Decoder, DecodeError, DataViewIndexOutOfBoundsError };\n\nimport { Encoder } from \"./Encoder\";\nexport { Encoder };\n\n// Utilitiies for Extension Types:\n\nimport { ExtensionCodec } from \"./ExtensionCodec\";\nexport { ExtensionCodec };\nimport type { ExtensionCodecType, ExtensionDecoderType, ExtensionEncoderType } from \"./ExtensionCodec\";\nexport type { ExtensionCodecType, ExtensionDecoderType, ExtensionEncoderType };\nimport { ExtData } from \"./ExtData\";\nexport { ExtData };\n\nimport {\n  EXT_TIMESTAMP,\n  encodeDateToTimeSpec,\n  encodeTimeSpecToTimestamp,\n  decodeTimestampToTimeSpec,\n  encodeTimestampExtension,\n  decodeTimestampExtension,\n} from \"./timestamp\";\nexport {\n  EXT_TIMESTAMP,\n  encodeDateToTimeSpec,\n  encodeTimeSpecToTimestamp,\n  decodeTimestampToTimeSpec,\n  encodeTimestampExtension,\n  decodeTimestampExtension,\n};\n", "/**\n * The webR JavaScript API.\n * @module WebR\n */\n\nimport { ChannelMain } from './chan/channel';\nimport { newChannelMain, ChannelType } from './chan/channel-common';\nimport { CloseWebSocketMessage, Message, PostMessageWorkerMessage, ProxyWebSocketMessage, ProxyWorkerMessage, SendWebSocketMessage, TerminateWorkerMessage } from './chan/message';\nimport { BASE_URL, PKG_BASE_URL, WEBR_VERSION, R_VERSION } from './config';\nimport { EmPtr } from './emscripten';\nimport { WebRPayloadPtr } from './payload';\nimport { newRProxy, newRClassProxy } from './proxy';\nimport { isRObject, RCharacter, RComplex, RDouble } from './robj-main';\nimport { REnvironment, RSymbol, RInteger, RList, RDataFrame } from './robj-main';\nimport { RLogical, RNull, RObject, RPairlist, RRaw, RString, RCall } from './robj-main';\nimport { replaceInObject } from './utils';\nimport * as RWorker from './robj-worker';\nimport { WebRError, WebRPayloadError } from './error';\n\nimport {\n  CaptureRMessage,\n  EvalRMessage,\n  EvalRMessageOutputType,\n  EvalRMessageRaw,\n  EvalROptions,\n  FSMessage,\n  FSMountMessage,\n  FSSyncfsMessage,\n  FSReadFileMessage,\n  FSWriteFileMessage,\n  InstallPackagesOptions,\n  InvokeWasmFunctionMessage,\n  NewShelterMessage,\n  ShelterDestroyMessage,\n  ShelterMessage,\n  FSRenameMessage,\n  FSAnalyzePathMessage,\n} from './webr-chan';\nimport { WebSocketMap } from './chan/proxy-websocket';\nimport { WorkerMap } from './chan/proxy-worker';\n\nexport { Console, ConsoleCallbacks } from './console';\nexport * from './robj-main';\nexport * from './error';\nexport * from './webr-chan';\nexport { ChannelType } from './chan/channel-common';\n\n/**\n * The webR FS API for interacting with the Emscripten Virtual File System.\n */\nexport interface WebRFS {\n  /**\n   * Lookup information about a file or directory node in the Emscripten\n   * virtual file system.\n   * @param {string} path Path to the requested node.\n   * @returns {Promise<FSNode>} The requested node.\n   */\n  lookupPath: (path: string) => Promise<FSNode>;\n  /**\n   * Create a directory on the Emscripten virtual file system.\n   * @param {string} path Path of the directory to create.\n   * @returns {Promise<FSNode>} The newly created directory node.\n   */\n  mkdir: (path: string) => Promise<FSNode>;\n  /**\n   * Get the content of a file on the Emscripten virtual file system.\n   * @param {string} path Path of the file to read.\n   * @param {string} [flags] Open the file with the specified flags.\n   * @returns {Promise<Uint8Array>} The content of the requested file.\n   */\n  readFile: (path: string, flags?: string) => Promise<Uint8Array>;\n  /**\n   * Remove a directory on the Emscripten virtual file system.\n   * @param {string} path Path of the directory to remove.\n   */\n  rmdir: (path: string) => Promise<void>;\n  /**\n   * Write a new file to the Emscripten virtual file system.\n   * @param {string} path Path of the new file.\n   * @param {Uint8Array} data The content of the new file.\n   * @param {string} [flags] Open the file with the specified flags.\n   */\n  writeFile: (path: string, data: ArrayBufferView, flags?: string) => Promise<void>;\n  /**\n   * Unlink a node on the Emscripten virtual file system. If that node was the\n   * last link to a file it is is deleted.\n   * @param {string} path Path of the target node.\n   */\n  unlink: (path: string) => Promise<void>;\n}\n\n/** A filesystem entry in the Emscripten Virtual File System */\nexport type FSNode = {\n  id: number;\n  name: string;\n  mode: number;\n  isFolder: boolean;\n  contents?: { [key: string]: FSNode };\n  mounted: null | {\n    mountpoint: string;\n    root: FSNode;\n  }\n};\n\n/** An Emscripten Filesystem type */\nexport type FSType = 'NODEFS' | 'WORKERFS' | 'IDBFS' | 'DRIVEFS';\n\n/**\n * Configuration settings to be used when mounting Filesystem objects with\n * Emscripten\n */\nexport type FSMountOptions<T extends FSType = FSType> =\n  T extends 'DRIVEFS' ? { driveName?: string; browsingContextId?: string } :\n  T extends 'NODEFS' ? { root: string } : {\n    blobs?: Array<{ name: string, data: Blob | Buffer | ArrayBufferLike | Uint8Array }>;\n    files?: Array<File | FileList>;\n    packages?: Array<{ metadata: FSMetaData, blob: Blob | Buffer | ArrayBufferLike | Uint8Array }>;\n  };\n\n/**\n * Emscripten filesystem image metadata\n */\nexport type FSMetaData = {\n  files: {\n    filename: string;\n    start: number;\n    end: number;\n  }[],\n  gzip?: boolean;\n};\n\n/** Emscripten filesystem entry information, as given by `FS.analyzePath()` */\nexport type FSAnalyzeInfo = {\n  isRoot: boolean,\n  exists: boolean,\n  error: Error,\n  name: string,\n  path: string,\n  object?: FSNode,\n  parentExists: boolean,\n  parentPath: string,\n  parentObject?: FSNode,\n};\n\n/**\n * The configuration settings to be used when starting webR.\n */\nexport interface WebROptions {\n  /**\n   * Command line arguments to be passed to R.\n   * Default: `[]`.\n   */\n  RArgs?: string[];\n\n  /**\n   * Environment variables to be made available for the R process.\n   * Default: `{ R_HOME: '/usr/lib/R', R_ENABLE_JIT: 0 }`.\n   */\n  REnv?: { [key: string]: string };\n\n  /**\n   * The base URL used for downloading R WebAssembly binaries.\n   *  Default: `'https://webr.r-wasm.org/[version]/'`\n   */\n  baseUrl?: string;\n\n  /**\n   * The repo URL to use when downloading R WebAssembly packages.\n   * Default: `'https://repo.r-wasm.org/`\n   */\n  repoUrl?: string;\n\n  /**\n   * The base URL from where to load JavaScript worker scripts when loading\n   * webR with the ServiceWorker communication channel mode.\n   * Default: `''`\n   */\n  serviceWorkerUrl?: string;\n\n  /**\n   * The WebAssembly user's home directory and initial working directory.\n   * Default: `'/home/web_user'`\n   */\n  homedir?: string;\n\n  /**\n   * Start R in interactive mode?\n   * Default: `true`.\n   */\n  interactive?: boolean;\n\n  /**\n   * Set the communication channel type to be used.\n   * Default: `channelType.Automatic`\n   */\n  channelType?: (typeof ChannelType)[keyof typeof ChannelType];\n\n  /**\n   * Create the lazy virtual filesystem entries before starting R?\n   * Default: `true`.\n   */\n  createLazyFilesystem?: boolean;\n}\n\nconst defaultEnv = {\n  FONTCONFIG_PATH: '/etc/fonts',\n  R_HOME: '/usr/lib/R',\n  R_ENABLE_JIT: '0',\n  ALL_PROXY: 'socks5h://localhost:8580',\n  WEBR: '1',\n  WEBR_VERSION: WEBR_VERSION,\n  R_VERSION: R_VERSION,\n};\n\nconst defaultOptions = {\n  RArgs: [],\n  REnv: defaultEnv,\n  baseUrl: BASE_URL,\n  serviceWorkerUrl: '',\n  repoUrl: PKG_BASE_URL,\n  homedir: '/home/web_user',\n  interactive: true,\n  channelType: ChannelType.Automatic,\n  createLazyFilesystem: true,\n};\n\n/**\n * The webR class is used to initialize and interact with the webR system.\n *\n * Start webR by constructing an instance of the WebR class, optionally passing\n * an options argument of type {@link WebROptions}. WebR will begin to download\n * and start a version of R built for WebAssembly in a worker thread.\n */\nexport class WebR {\n  #chan: ChannelMain;\n  #ws: WebSocketMap;\n  #workers: WorkerMap;\n  #initialised: Promise<unknown>;\n  globalShelter!: Shelter;\n  version: string = WEBR_VERSION;\n  versionR: string = R_VERSION;\n\n  RObject!: ReturnType<typeof newRClassProxy<typeof RWorker.RObject, RObject>>;\n  RLogical!: ReturnType<typeof newRClassProxy<typeof RWorker.RLogical, RLogical>>;\n  RInteger!: ReturnType<typeof newRClassProxy<typeof RWorker.RInteger, RInteger>>;\n  RDouble!: ReturnType<typeof newRClassProxy<typeof RWorker.RDouble, RDouble>>;\n  RCharacter!: ReturnType<typeof newRClassProxy<typeof RWorker.RCharacter, RCharacter>>;\n  RComplex!: ReturnType<typeof newRClassProxy<typeof RWorker.RComplex, RComplex>>;\n  RRaw!: ReturnType<typeof newRClassProxy<typeof RWorker.RRaw, RRaw>>;\n  RList!: ReturnType<typeof newRClassProxy<typeof RWorker.RList, RList>>;\n  RDataFrame!: ReturnType<typeof newRClassProxy<typeof RWorker.RDataFrame, RDataFrame>>;\n  RPairlist!: ReturnType<typeof newRClassProxy<typeof RWorker.RPairlist, RPairlist>>;\n  REnvironment!: ReturnType<typeof newRClassProxy<typeof RWorker.REnvironment, REnvironment>>;\n  RSymbol!: ReturnType<typeof newRClassProxy<typeof RWorker.RSymbol, RSymbol>>;\n  RString!: ReturnType<typeof newRClassProxy<typeof RWorker.RString, RString>>;\n  RCall!: ReturnType<typeof newRClassProxy<typeof RWorker.RCall, RCall>>;\n\n  objs: {\n    baseEnv: REnvironment;\n    globalEnv: REnvironment;\n    null: RNull;\n    true: RLogical;\n    false: RLogical;\n    na: RLogical;\n  };\n\n  Shelter;\n\n  constructor(options: WebROptions = {}) {\n    const config: Required<WebROptions> = {\n      ...defaultOptions,\n      ...options,\n      REnv: {\n        ...defaultOptions.REnv,\n        ...options.REnv,\n      }\n    };\n    this.#chan = newChannelMain(config);\n    this.#ws = new WebSocketMap(this.#chan);\n    this.#workers = new WorkerMap(this.#chan);\n\n    this.objs = {} as typeof this.objs;\n    this.Shelter = newShelterProxy(this.#chan);\n\n    this.#initialised = this.#chan.initialised.then(async () => {\n      this.globalShelter = await new this.Shelter();\n\n      this.RObject = this.globalShelter.RObject;\n      this.RLogical = this.globalShelter.RLogical;\n      this.RInteger = this.globalShelter.RInteger;\n      this.RDouble = this.globalShelter.RDouble;\n      this.RComplex = this.globalShelter.RComplex;\n      this.RCharacter = this.globalShelter.RCharacter;\n      this.RRaw = this.globalShelter.RRaw;\n      this.RList = this.globalShelter.RList;\n      this.RDataFrame = this.globalShelter.RDataFrame;\n      this.RPairlist = this.globalShelter.RPairlist;\n      this.REnvironment = this.globalShelter.REnvironment;\n      this.RSymbol = this.globalShelter.RSymbol;\n      this.RString = this.globalShelter.RString;\n      this.RCall = this.globalShelter.RCall;\n\n      this.objs = {\n        baseEnv: (await this.RObject.getPersistentObject('baseEnv')) as REnvironment,\n        globalEnv: (await this.RObject.getPersistentObject('globalEnv')) as REnvironment,\n        null: (await this.RObject.getPersistentObject('null')) as RNull,\n        true: (await this.RObject.getPersistentObject('true')) as RLogical,\n        false: (await this.RObject.getPersistentObject('false')) as RLogical,\n        na: (await this.RObject.getPersistentObject('na')) as RLogical,\n      };\n\n      void this.#handleSystemMessages();\n    });\n  }\n\n  /**\n   * @returns {Promise<void>} A promise that resolves once webR has been\n   * initialised.\n   */\n  async init() {\n    return this.#initialised;\n  }\n\n  async #handleSystemMessages() {\n    for (; ;) {\n      const msg = await this.#chan.readSystem();\n      switch (msg.type) {\n        case 'setTimeoutWasm':\n          /* Handle messages requesting a delayed invocation of a wasm function.\n          * TODO: Reimplement without using the main thread once it is possible\n          *       to yield in the worker thread.\n          */\n          setTimeout(\n            (ptr: EmPtr, args: number[]) => {\n              void this.invokeWasmFunction(ptr, ...args);\n            },\n            msg.data.delay as number,\n            msg.data.ptr,\n            msg.data.args\n          );\n          break;\n        case 'proxyWebSocket': {\n          const message = msg as ProxyWebSocketMessage;\n          this.#ws.new(message.data.uuid, message.data.url, message.data.protocol);\n          break;\n        }\n        case 'sendWebSocket': {\n          const message = msg as SendWebSocketMessage;\n          this.#ws.send(message.data.uuid, message.data.data);\n          break;\n        }\n        case 'closeWebSocket': {\n          const message = msg as CloseWebSocketMessage;\n          this.#ws.close(message.data.uuid, message.data.code, message.data.reason);\n          break;\n        }\n        case 'proxyWorker': {\n          const message = msg as ProxyWorkerMessage;\n          this.#workers.new(message.data.uuid, message.data.url, message.data.options);\n          break;\n        }\n        case 'postMessageWorker': {\n          const message = msg as PostMessageWorkerMessage;\n          this.#workers.postMessage(message);\n          break;\n        }\n        case 'terminateWorker': {\n          const message = msg as TerminateWorkerMessage;\n          this.#workers.terminate(message.data.uuid);\n          break;\n        }\n        case 'console.log':\n          console.log(msg.data);\n          break;\n        case 'console.warn':\n          console.warn(msg.data);\n          break;\n        case 'console.error':\n          console.error(msg.data);\n          break;\n        case 'close':\n          this.#chan.close();\n          break;\n        default:\n          throw new WebRError('Unknown system message type `' + msg.type + '`');\n      }\n    }\n  }\n\n  /**\n   * Close the communication channel between the main thread and the worker\n   * thread cleanly. Once this has been executed, webR will be unable to\n   * continue.\n   */\n  close() {\n    this.#chan.close();\n  }\n\n  /**\n   * Read from the communication channel and return an output message.\n   * @returns {Promise<Message>} The output message\n   */\n  async read(): Promise<Message> {\n    return await this.#chan.read();\n  }\n\n  /**\n   * Stream output messages from the communication channel via an async generator.\n   * @yields {Promise<Message>} Output messages from the communication channel.\n   */\n  async *stream(): AsyncGenerator<Message, void> {\n    for (; ;) {\n      const output = await this.#chan.read();\n      if (output.type === 'closed') {\n        return;\n      }\n      yield output;\n    }\n  }\n\n  /**\n   * Flush the output queue in the communication channel and return all output\n   * messages.\n   * @returns {Promise<Message[]>} The output messages\n   */\n  async flush(): Promise<Message[]> {\n    return await this.#chan.flush();\n  }\n\n  /**\n   * Send a message to the communication channel input queue.\n   * @param {Message} msg Message to be added to the input queue.\n   */\n  write(msg: Message) {\n    this.#chan.write(msg);\n  }\n\n  /**\n   * Send a line of standard input to the communication channel input queue.\n   * @param {string} input Message to be added to the input queue.\n   */\n  writeConsole(input: string) {\n    this.write({ type: 'stdin', data: input + '\\n' });\n  }\n\n  /** Attempt to interrupt a running R computation. */\n  interrupt() {\n    this.#chan.interrupt();\n  }\n\n  /**\n   * Install a list of R packages from Wasm binary package repositories.\n   * @param {string | string[]} packages An string or array of strings\n   *   containing R package names.\n   * @param {InstallPackagesOptions} [options] Options to be used when\n   *   installing webR packages.\n   */\n  async installPackages(packages: string | string[], options?: InstallPackagesOptions) {\n    const op = Object.assign({\n      quiet: false,\n      mount: true\n    }, options);\n\n    const msg = { type: 'installPackages', data: { name: packages, options: op } };\n    await this.#chan.request(msg);\n  }\n\n  /**\n   * Destroy an R object reference.\n   * @param {RObject} x An R object reference.\n   */\n  async destroy(x: RObject) {\n    await this.globalShelter.destroy(x);\n  }\n\n  /**\n   * Evaluate the given R code.\n   *\n   * Stream outputs and any conditions raised during execution are written to\n   * the JavaScript console.\n   * @param {string} code The R code to evaluate.\n   * @param {EvalROptions} [options] Options for the execution environment.\n   * @returns {Promise<RObject>} The result of the computation.\n   */\n  async evalR(code: string, options?: EvalROptions): Promise<RObject> {\n    return this.globalShelter.evalR(code, options);\n  }\n\n  /**\n   * Evaluate the given R code, returning a promise for no return data.\n   * @param {string} code The R code to evaluate.\n   * @param {EvalROptions} [options] Options for the execution environment.\n   * @returns {Promise<void>} A promise which fires when the R code completes, but returns no data.\n   */\n  async evalRVoid(code: string, options?: EvalROptions) {\n    return this.evalRRaw(code, 'void', options);\n  }\n\n  /**\n   * Evaluate the given R code, returning a promise for a boolean value. If the returned R value is not a boolean, an error will be thrown.\n   * @param {string} code The R code to evaluate.\n   * @param {EvalROptions} [options] Options for the execution environment.\n   * @returns {Promise<boolean>} The result of the computation.\n   */\n  async evalRBoolean(code: string, options?: EvalROptions) {\n    return this.evalRRaw(code, 'boolean', options);\n  }\n\n  /**\n   * Evaluate the given R code, returning a promise for a number. If the returned R value is not a number, an error will be thrown.\n   * @param {string} code The R code to evaluate.\n   * @param {EvalROptions} [options] Options for the execution environment.\n   * @returns {Promise<number>} The result of the computation.\n   */\n  async evalRNumber(code: string, options?: EvalROptions) {\n    return this.evalRRaw(code, 'number', options);\n  }\n\n  /**\n   * Evaluate the given R code, returning a promise for a string. If the returned R value is not a string, an error will be thrown.\n   * @param {string} code The R code to evaluate.\n   * @param {EvalROptions} [options] Options for the execution environment.\n   * @returns {Promise<string>} The result of the computation.\n   */\n  async evalRString(code: string, options?: EvalROptions) {\n    return this.evalRRaw(code, 'string', options);\n  }\n\n  /**\n   * Evaluate the given R code, returning the result as a raw JavaScript object.\n   * @param {string} code The R code to evaluate.\n   * @param {EvalRMessageOutputType} outputType JavaScript type to return the result as.\n   * @param {EvalROptions} [options] Options for the execution environment.\n   * @returns {Promise<unknown>} The result of the computation.\n   */\n  async evalRRaw(code: string, outputType: 'void', options?: EvalROptions): Promise<void>;\n  async evalRRaw(code: string, outputType: 'boolean', options?: EvalROptions): Promise<boolean>;\n  async evalRRaw(code: string, outputType: 'boolean[]', options?: EvalROptions): Promise<boolean[]>;\n  async evalRRaw(code: string, outputType: 'number', options?: EvalROptions): Promise<number>;\n  async evalRRaw(code: string, outputType: 'number[]', options?: EvalROptions): Promise<number[]>;\n  async evalRRaw(code: string, outputType: 'string', options?: EvalROptions): Promise<string>;\n  async evalRRaw(code: string, outputType: 'string[]', options?: EvalROptions): Promise<string[]>;\n  async evalRRaw(code: string, outputType: EvalRMessageOutputType, options: EvalROptions = {}) {\n    const opts = replaceInObject(options, isRObject, (obj: RObject) => obj._payload);\n    const msg: EvalRMessageRaw = {\n      type: 'evalRRaw',\n      data: { code: code, options: opts as EvalROptions, outputType: outputType },\n    };\n    const payload = await this.#chan.request(msg);\n\n    switch (payload.payloadType) {\n      case 'raw':\n        return payload.obj;\n      case 'ptr':\n        throw new WebRPayloadError('Unexpected ptr payload type returned from evalRVoid');\n    }\n  }\n\n  async invokeWasmFunction(ptr: EmPtr, ...args: number[]): Promise<EmPtr> {\n    const msg = {\n      type: 'invokeWasmFunction',\n      data: { ptr, args },\n    } as InvokeWasmFunctionMessage;\n    const resp = await this.#chan.request(msg);\n    return resp.obj as EmPtr;\n  }\n\n  FS = {\n    analyzePath: async (path: string, dontResolveLastLink?: boolean): Promise<FSAnalyzeInfo> => {\n      const msg: FSAnalyzePathMessage = { type: 'analyzePath', data: { path, dontResolveLastLink } };\n      const payload = await this.#chan.request(msg);\n      return payload.obj as FSAnalyzeInfo;\n    },\n    lookupPath: async (path: string): Promise<FSNode> => {\n      const msg: FSMessage = { type: 'lookupPath', data: { path } };\n      const payload = await this.#chan.request(msg);\n      return payload.obj as FSNode;\n    },\n    mkdir: async (path: string): Promise<FSNode> => {\n      const msg: FSMessage = { type: 'mkdir', data: { path } };\n      const payload = await this.#chan.request(msg);\n      return payload.obj as FSNode;\n    },\n    mount: async <T extends FSType>(\n      type: T,\n      options: FSMountOptions<T>,\n      mountpoint: string\n    ): Promise<void> => {\n      // Convert blobs to ArrayBuffer for transfer over the communication channel\n      // FIXME: Use a replacer + reviver to transfer `Blob`s\n      let promises: Promise<void>[] = [];\n      if ('blobs' in options && options.blobs) {\n        promises = [...promises, ...options.blobs.map((item) => {\n          if (item.data instanceof Blob) {\n            return item.data.arrayBuffer().then((data) => {\n              item.data = new Uint8Array(data);\n            });\n          } else {\n            return Promise.resolve();\n          }\n        })];\n      }\n      if ('packages' in options && options.packages) {\n        promises = [...promises, ...options.packages.map((pkg) => {\n          if (pkg.blob instanceof Blob) {\n            return pkg.blob.arrayBuffer().then((data) => {\n              pkg.blob = new Uint8Array(data);\n            });\n          } else {\n            return Promise.resolve();\n          }\n        })];\n      }\n      await Promise.all(promises);\n\n      const msg: FSMountMessage = { type: 'mount', data: { type, options, mountpoint } };\n      await this.#chan.request(msg);\n    },\n    syncfs: async (populate: boolean): Promise<void> => {\n      const msg: FSSyncfsMessage = { type: 'syncfs', data: { populate } };\n      await this.#chan.request(msg);\n    },\n    readFile: async (path: string, flags?: string): Promise<Uint8Array> => {\n      const msg: FSReadFileMessage = { type: 'readFile', data: { path, flags } };\n      const payload = await this.#chan.request(msg);\n      return payload.obj as Uint8Array;\n    },\n    rename: async (oldpath: string, newpath: string): Promise<void> => {\n      const msg: FSRenameMessage = { type: 'rename', data: { oldpath, newpath } };\n      await this.#chan.request(msg);\n    },\n    rmdir: async (path: string): Promise<void> => {\n      const msg: FSMessage = { type: 'rmdir', data: { path } };\n      await this.#chan.request(msg);\n    },\n    writeFile: async (path: string, data: ArrayBufferView, flags?: string): Promise<void> => {\n      const msg: FSWriteFileMessage = { type: 'writeFile', data: { path, data, flags } };\n      await this.#chan.request(msg);\n    },\n    unlink: async (path: string): Promise<void> => {\n      const msg: FSMessage = { type: 'unlink', data: { path } };\n      await this.#chan.request(msg);\n    },\n    unmount: async (mountpoint: string): Promise<void> => {\n      const msg: FSMessage = { type: 'unmount', data: { path: mountpoint } };\n      await this.#chan.request(msg);\n    },\n  };\n}\n\n/** WebR shelters provide fine-grained control over the lifetime of R objects. */\nexport class Shelter {\n  #id = '';\n  #chan: ChannelMain;\n  #initialised = false;\n\n  RObject!: ReturnType<typeof newRClassProxy<typeof RWorker.RObject, RObject>>;\n  RLogical!: ReturnType<typeof newRClassProxy<typeof RWorker.RLogical, RLogical>>;\n  RInteger!: ReturnType<typeof newRClassProxy<typeof RWorker.RInteger, RInteger>>;\n  RDouble!: ReturnType<typeof newRClassProxy<typeof RWorker.RDouble, RDouble>>;\n  RCharacter!: ReturnType<typeof newRClassProxy<typeof RWorker.RCharacter, RCharacter>>;\n  RComplex!: ReturnType<typeof newRClassProxy<typeof RWorker.RComplex, RComplex>>;\n  RRaw!: ReturnType<typeof newRClassProxy<typeof RWorker.RRaw, RRaw>>;\n  RList!: ReturnType<typeof newRClassProxy<typeof RWorker.RList, RList>>;\n  RDataFrame!: ReturnType<typeof newRClassProxy<typeof RWorker.RDataFrame, RDataFrame>>;\n  RPairlist!: ReturnType<typeof newRClassProxy<typeof RWorker.RPairlist, RPairlist>>;\n  REnvironment!: ReturnType<typeof newRClassProxy<typeof RWorker.REnvironment, REnvironment>>;\n  RSymbol!: ReturnType<typeof newRClassProxy<typeof RWorker.RSymbol, RSymbol>>;\n  RString!: ReturnType<typeof newRClassProxy<typeof RWorker.RString, RString>>;\n  RCall!: ReturnType<typeof newRClassProxy<typeof RWorker.RCall, RCall>>;\n\n  /** @internal */\n  constructor(chan: ChannelMain) {\n    this.#chan = chan;\n  }\n\n  /** @internal */\n  async init() {\n    if (this.#initialised) {\n      return;\n    }\n\n    const msg = { type: 'newShelter' } as NewShelterMessage;\n    const payload = await this.#chan.request(msg);\n    this.#id = payload.obj as string;\n\n    this.RObject = newRClassProxy<typeof RWorker.RObject, RObject>(this.#chan, this.#id, 'object');\n    this.RLogical = newRClassProxy<typeof RWorker.RLogical, RLogical>(this.#chan, this.#id, 'logical');\n    this.RInteger = newRClassProxy<typeof RWorker.RInteger, RInteger>(this.#chan, this.#id, 'integer');\n    this.RDouble = newRClassProxy<typeof RWorker.RDouble, RDouble>(this.#chan, this.#id, 'double');\n    this.RComplex = newRClassProxy<typeof RWorker.RComplex, RComplex>(this.#chan, this.#id, 'complex');\n    this.RCharacter = newRClassProxy<typeof RWorker.RCharacter, RCharacter>(this.#chan, this.#id, 'character');\n    this.RRaw = newRClassProxy<typeof RWorker.RRaw, RRaw>(this.#chan, this.#id, 'raw');\n    this.RList = newRClassProxy<typeof RWorker.RList, RList>(this.#chan, this.#id, 'list');\n    this.RDataFrame = newRClassProxy<typeof RWorker.RDataFrame, RDataFrame>(this.#chan, this.#id, 'dataframe');\n    this.RPairlist = newRClassProxy<typeof RWorker.RPairlist, RPairlist>(this.#chan, this.#id, 'pairlist');\n    this.REnvironment = newRClassProxy<typeof RWorker.REnvironment, REnvironment>(this.#chan, this.#id, 'environment');\n    this.RSymbol = newRClassProxy<typeof RWorker.RSymbol, RSymbol>(this.#chan, this.#id, 'symbol');\n    this.RString = newRClassProxy<typeof RWorker.RString, RString>(this.#chan, this.#id, 'string');\n    this.RCall = newRClassProxy<typeof RWorker.RCall, RCall>(this.#chan, this.#id, 'call');\n\n    this.#initialised = true;\n  }\n\n  async purge() {\n    const msg: ShelterMessage = {\n      type: 'shelterPurge',\n      data: this.#id,\n    };\n    await this.#chan.request(msg);\n  }\n\n  async destroy(x: RObject) {\n    const msg: ShelterDestroyMessage = {\n      type: 'shelterDestroy',\n      data: { id: this.#id, obj: x._payload },\n    };\n    await this.#chan.request(msg);\n  }\n\n  async size(): Promise<number> {\n    const msg: ShelterMessage = {\n      type: 'shelterSize',\n      data: this.#id,\n    };\n    const payload = await this.#chan.request(msg);\n    return payload.obj as number;\n  }\n\n  /**\n   * Evaluate the given R code.\n   *\n   * Stream outputs and any conditions raised during execution are written to\n   * the JavaScript console. The returned R object is protected by the shelter.\n   * @param {string} code The R code to evaluate.\n   * @param {EvalROptions} [options] Options for the execution environment.\n   * @returns {Promise<RObject>} The result of the computation.\n   */\n  async evalR(code: string, options: EvalROptions = {}): Promise<RObject> {\n    const opts = replaceInObject(options, isRObject, (obj: RObject) => obj._payload);\n    const msg: EvalRMessage = {\n      type: 'evalR',\n      data: { code: code, options: opts as EvalROptions, shelter: this.#id },\n    };\n    const payload = await this.#chan.request(msg);\n\n    switch (payload.payloadType) {\n      case 'raw':\n        throw new WebRPayloadError('Unexpected payload type returned from evalR');\n      default:\n        return newRProxy(this.#chan, payload);\n    }\n  }\n\n  /**\n   * Evaluate the given R code, capturing output.\n   *\n   * Stream outputs and conditions raised during execution are captured and\n   * returned as part of the output of this function. Returned R objects are\n   * protected by the shelter.\n   * @param {string} code The R code to evaluate.\n   * @param {EvalROptions} [options] Options for the execution environment.\n   * @returns {Promise<{\n   *   result: RObject,\n   *   output: { type: string; data: any }[],\n   *   images: ImageBitmap[]\n   * }>} An object containing the result of the computation, an array of output,\n   *   and an array of captured plots.\n   */\n  async captureR(code: string, options: EvalROptions = {}): Promise<{\n    result: RObject;\n    output: { type: string; data: any }[];\n    images: ImageBitmap[];\n  }> {\n    const opts = replaceInObject(options, isRObject, (obj: RObject) => obj._payload);\n    const msg: CaptureRMessage = {\n      type: 'captureR',\n      data: {\n        code: code,\n        options: opts as EvalROptions,\n        shelter: this.#id,\n      },\n    };\n    const payload = await this.#chan.request(msg);\n\n    switch (payload.payloadType) {\n      case 'ptr':\n        throw new WebRPayloadError('Unexpected payload type returned from evalR');\n\n      case 'raw': {\n        const data = payload.obj as {\n          result: WebRPayloadPtr;\n          output: { type: string; data: any }[];\n          images: ImageBitmap[];\n        };\n        const result = newRProxy(this.#chan, data.result);\n        const output = data.output;\n        const images = data.images;\n\n        for (let i = 0; i < output.length; ++i) {\n          if (output[i].type !== 'stdout' && output[i].type !== 'stderr') {\n            output[i].data = newRProxy(this.#chan, output[i].data as WebRPayloadPtr);\n          }\n        }\n\n        return { result, output, images };\n      }\n    }\n  }\n}\n\nfunction newShelterProxy(chan: ChannelMain) {\n  return new Proxy(Shelter, {\n    construct: async () => {\n      const out = new Shelter(chan);\n      await out.init();\n      return out;\n    },\n  }) as unknown as {\n    new(): Promise<Shelter>;\n  };\n}\n", "/**\n * Custom Error classes that shall be raised by webR.\n * @module Error\n */\n\n/**\n * A general error raised by webR.\n */\nexport class WebRError extends Error {\n  constructor(msg: string) {\n    super(msg);\n    this.name = this.constructor.name;\n    Object.setPrototypeOf(this, new.target.prototype);\n  }\n}\n\n/**\n * Exceptions raised on the webR worker thread that have been forwarded to the\n * main thread through the communication channel.\n */\nexport class WebRWorkerError extends WebRError { }\n\n/**\n * Exceptions related to issues with the webR communication channel.\n */\nexport class WebRChannelError extends WebRError { }\n\n/**\n * Exceptions related to issues with webR object payloads.\n */\nexport class WebRPayloadError extends WebRError { }\n", "import { WebRError } from './error';\n\ninterface Process {\n  browser: string | undefined;\n  release: { [key: string]: string };\n}\ndeclare let process: Process;\n\nexport const IN_NODE =\n  typeof process !== 'undefined' &&\n  process.release &&\n  process.release.name === 'node';\n\n// Adapted from https://github.com/pyodide/pyodide/blob/main/src/js/compat.ts\nexport let loadScript: (url: string) => Promise<void>;\nif (globalThis.document) {\n  loadScript = (url) =>\n    new Promise((resolve, reject) => {\n      const script = document.createElement('script');\n      script.src = url;\n      script.onload = () => resolve();\n      script.onerror = reject;\n      document.head.appendChild(script);\n    });\n} else if (globalThis.importScripts) {\n  loadScript = async (url) => {\n    try {\n      globalThis.importScripts(url);\n    } catch (e) {\n      if (e instanceof TypeError) {\n        await import(url);\n      } else {\n        throw e;\n      }\n    }\n  };\n} else if (IN_NODE) {\n  loadScript = async (url: string) => {\n    const nodePathMod = (await import('path')).default;\n    await import(nodePathMod.resolve(url));\n  };\n} else {\n  throw new WebRError('Cannot determine runtime environment');\n}\n", "/**\n * Common module for working with R objects.\n * @module RObject\n */\nimport * as RMain from './robj-main';\nimport * as RWorker from './robj-worker';\n\nexport type RPtr = number;\n\nexport const RTypeMap = {\n  null: 0,\n  symbol: 1,\n  pairlist: 2,\n  closure: 3,\n  environment: 4,\n  promise: 5,\n  call: 6,\n  special: 7,\n  builtin: 8,\n  string: 9,\n  logical: 10,\n  integer: 13,\n  double: 14,\n  complex: 15,\n  character: 16,\n  dots: 17,\n  any: 18,\n  list: 19,\n  expression: 20,\n  bytecode: 21,\n  pointer: 22,\n  weakref: 23,\n  raw: 24,\n  s4: 25,\n  new: 30,\n  free: 31,\n  function: 99,\n} as const;\nexport type RType = keyof typeof RTypeMap;\nexport type RTypeNumber = typeof RTypeMap[RType];\n\n/** @internal */\nexport type RCtor = 'object' | 'dataframe';\n\nexport type Complex = {\n  re: number;\n  im: number;\n};\n\nexport type WebRDataRaw =\n  | number\n  | string\n  | boolean\n  | undefined\n  | null\n  | void\n  | Complex\n  | Error\n  | ArrayBuffer\n  | ArrayBufferView\n  | ImageBitmap\n  | Array<WebRDataRaw>\n  | Map<WebRDataRaw, WebRDataRaw>\n  | Set<WebRDataRaw>\n  | { [key: string]: WebRDataRaw };\n\nexport type NamedEntries<T> = [string | null, T][];\nexport type NamedObject<T> = { [key: string]: T };\n\n/**\n * A union of JavaScript types that are able to be converted into an R object.\n *\n * `WebRData` is used both as a general input argument for R object construction\n * and also as a general return type when converting R objects into JavaScript.\n *\n */\nexport type WebRData =\n  | RMain.RObject\n  | RWorker.RObjectBase\n  | RWorker.RObject\n  | WebRDataRaw\n  | WebRDataJs\n  | WebRData[]\n  | ArrayBuffer\n  | ArrayBufferView\n  | { [key: string]: WebRData };\n\n/**\n * A subset of {@link WebRData} for JavaScript objects that can be converted\n * into R atomic vectors.\n * @typeParam T The JavaScript scalar type associated with the atomic vector.\n */\nexport type WebRDataAtomic<T> =\n  | WebRDataScalar<T>\n  | WebRDataJsAtomic<T>\n  | NamedObject<T | null>\n  | ([T] extends [number] ? ArrayBuffer | ArrayBufferView | (number | null)[] : (T | null)[]);\n\n/**\n * `WebRDataJs` objects form a tree structure, used when serialising R objects\n * into a JavaScript representation.\n *\n * Nested R objects are serialised using the {@link WebRDataJsNode} type,\n * forming branches in the resulting tree structure, with leaves formed by the\n * remaining types.\n */\nexport type WebRDataJs =\n  | WebRDataJsNull\n  | WebRDataJsString\n  | WebRDataJsSymbol\n  | WebRDataJsNode\n  | WebRDataJsAtomic<RWorker.atomicType>;\n\nexport type WebRDataJsNull = {\n  type: 'null';\n};\n\nexport type WebRDataJsString = {\n  type: 'string';\n  value: string;\n};\n\nexport type WebRDataJsSymbol = {\n  type: 'symbol';\n  printname: string | null;\n  symvalue: RPtr | null;\n  internal: RPtr | null;\n};\n\nexport type WebRDataJsNode = {\n  type: 'list' | 'pairlist' | 'environment';\n  names: (string | null)[] | null;\n  values: (WebRDataRaw | RWorker.RObject | RMain.RObject | WebRDataJs)[];\n};\n\nexport type WebRDataJsAtomic<T> = {\n  type: 'logical' | 'integer' | 'double' | 'complex' | 'character' | 'raw';\n  names: (string | null)[] | null;\n  values: (T | null)[];\n};\n\n/**\n * Test for a {@link WebRDataJs} instance.\n * @param {any} value The object to test.\n * @returns {boolean} True if the object is an instance of a {@link WebRDataJs}.\n */\nexport function isWebRDataJs(value: any): value is WebRDataJs {\n  return !!value && typeof value === 'object'\n    && Object.keys(RTypeMap).includes(value.type as string);\n}\n\n/**\n * A subset of WebRData for scalar JavaScript objects.\n */\nexport type WebRDataScalar<T> = T | RMain.RObject | RWorker.RObjectBase;\n\n/**\n * Test if an object is of type {@link Complex}.\n * @param {any} value The object to test.\n * @returns {boolean} True if the object is of type {@link Complex}.\n */\nexport function isComplex(value: any): value is Complex {\n  return !!value && typeof value === 'object' && 're' in value && 'im' in value;\n}\n", "import type { RPtr, RTypeNumber } from './robj';\nimport type { RObject, RList } from './robj-worker';\nimport type { EvalROptions } from './webr-chan';\nimport type { UnwindProtectException } from './utils-r';\nimport type { ChannelWorker } from './chan/channel';\nimport type { FSMountOptions } from './webr-main';\n\nexport interface Module extends EmscriptenModule {\n  /* Add mkdirTree to FS namespace, missing from @types/emscripten at the\n   * time of writing.\n   */\n  FS: typeof FS & {\n    _mount: typeof FS.mount;\n    mkdirTree(path: string): void;\n    filesystems: {\n      [key: string]: Emscripten.FileSystemType;\n    }\n  };\n  ENV: { [key: string]: string };\n  GOT: {\n    [key: string]: { required: boolean; value: number };\n  }\n  createLazyFilesystem: () => void;\n  monitorRunDependencies: (n: number) => void;\n  websocket?: {\n    url?: string;\n    WebSocket?: typeof WebSocket;\n    subprotocol?: string;\n  };\n  noImageDecoding: boolean;\n  noAudioDecoding: boolean;\n  noWasmDecoding: boolean;\n  downloadFileContent: (\n    URL: string,\n    headers?: Array<string>\n  ) => {\n    status: number;\n    response: string | ArrayBuffer;\n  };\n  mountImageUrl: (url: string, mountpoint: string) => void;\n  mountImagePath: (path: string, mountpoint: string) => void;\n  mountDriveFS: (mountpoint: string, options: FSMountOptions<'DRIVEFS'>) => void;\n  // Exported Emscripten JS API\n  allocateUTF8: typeof allocateUTF8;\n  allocateUTF8OnStack: typeof allocateUTF8OnStack;\n  getValue: typeof getValue;\n  setValue: typeof setValue;\n  UTF8ToString: typeof UTF8ToString;\n  callMain: (args: string[]) => void;\n  getWasmTableEntry: (entry: number) => (...args: any[]) => RPtr;\n  // R symbols from Rinternals.h\n  _ATTRIB: (ptr: RPtr) => RPtr;\n  _CAR: (ptr: RPtr) => RPtr;\n  _CDR: (ptr: RPtr) => RPtr;\n  _CLOENV: (ptr: RPtr) => RPtr;\n  _COMPLEX: (ptr: RPtr) => RPtr;\n  _FRAME: (ptr: RPtr) => RPtr;\n  _INTEGER: (ptr: RPtr) => RPtr;\n  _INTERNAL: (ptr: RPtr) => RPtr;\n  _LENGTH: (ptr: RPtr) => number;\n  _LOGICAL: (ptr: RPtr) => RPtr;\n  _PRINTNAME: (ptr: RPtr) => RPtr;\n  _R_CHAR: (ptr: RPtr) => RPtr;\n  _RAW: (ptr: RPtr) => RPtr;\n  _REAL: (ptr: RPtr) => RPtr;\n  _SETCAR: (x: RPtr, y: RPtr) => void;\n  _STRING_ELT: (ptr: RPtr, idx: number) => RPtr;\n  _STRING_PTR: (ptr: RPtr) => RPtr;\n  _SYMVALUE: (ptr: RPtr) => RPtr;\n  _TAG: (ptr: RPtr) => RPtr;\n  _TYPEOF: (ptr: RPtr) => RPtr;\n  _VECTOR_ELT: (ptr: RPtr, idx: number) => RPtr;\n  _R_lsInternal3: (env: RPtr, all: number, sorted: number) => RPtr;\n  _R_MakeExternalPtr: (p: number, tag: RPtr, prot: RPtr) => RPtr;\n  _R_NewEnv: (enclos: RPtr, hash: number, size: number) => RPtr;\n  _R_ParseEvalString: (code: number, env: RPtr) => RPtr;\n  _R_PreserveObject: (ptr: RPtr) => void;\n  _R_ReleaseObject: (ptr: RPtr) => void;\n  _R_ReplDLLinit: () => void;\n  _R_ReplDLLdo1: () => number;\n  _Rf_ScalarReal: (n: number) => RPtr;\n  _Rf_ScalarLogical: (l: number) => RPtr;\n  _Rf_ScalarInteger: (n: number) => RPtr;\n  _Rf_ScalarString: (s: string) => RPtr;\n  _Rf_allocList: (len: number) => RPtr;\n  _Rf_allocVector: (type: RTypeNumber, len: number) => RPtr;\n  _Rf_defineVar: (symbol: RPtr, value: RPtr, env: RPtr) => void;\n  _Rf_error: (msg: EmPtr) => void;\n  _Rf_eval: (call: RPtr, env: RPtr) => RPtr;\n  _Rf_findVarInFrame: (rho: RPtr, symbol: RPtr) => RPtr;\n  _Rf_listAppend: (source: RPtr, target: RPtr) => RPtr;\n  _Rf_getAttrib: (ptr1: RPtr, ptr2: RPtr) => RPtr;\n  _Rf_initialize_R: (argc: number, argv: RPtr) => void;\n  _Rf_install: (ptr: number) => RPtr;\n  _Rf_installTrChar: (name: RPtr) => RPtr;\n  _Rf_lang1: (ptr1: RPtr) => RPtr;\n  _Rf_lang2: (ptr1: RPtr, ptr2: RPtr) => RPtr;\n  _Rf_lang3: (ptr1: RPtr, ptr2: RPtr, ptr3: RPtr) => RPtr;\n  _Rf_lang4: (ptr1: RPtr, ptr2: RPtr, ptr3: RPtr, ptr4: RPtr) => RPtr;\n  _Rf_lang5: (ptr1: RPtr, ptr2: RPtr, ptr3: RPtr, ptr4: RPtr, ptr5: RPtr) => RPtr;\n  _Rf_lang6: (ptr1: RPtr, ptr2: RPtr, ptr3: RPtr, ptr4: RPtr, ptr5: RPtr, ptr6: RPtr) => RPtr;\n  _Rf_mkChar: (string: number) => RPtr;\n  _Rf_mkCharCE: (string: number, encoding: number) => RPtr;\n  _Rf_mkString: (ptr: number) => RPtr;\n  _Rf_onintr: () => void;\n  _Rf_protect: (ptr: RPtr) => RPtr;\n  _Rf_translateCharUTF8: (ptr: RPtr) => RPtr;\n  _R_ContinueUnwind: (cont: RPtr) => never;\n  _R_ProtectWithIndex: (ptr1: RPtr, ptr2: RPtr) => void;\n  _R_Reprotect: (ptr1: RPtr, ptr2: RPtr) => void;\n  _Rf_setAttrib: (ptr1: RPtr, ptr2: RPtr, ptr3: RPtr) => RPtr;\n  _Rf_unprotect: (n: number) => void;\n  _Rf_unprotect_ptr: (ptr: RPtr) => void;\n  _DLLbuf: RPtr;\n  _DLLbufp: RPtr;\n  _R_BaseEnv: RPtr;\n  _R_BracketSymbol: RPtr;\n  _R_Bracket2Symbol: RPtr;\n  _R_DollarSymbol: RPtr;\n  _R_EmptyEnv: RPtr;\n  _R_FalseValue: RPtr;\n  _R_GlobalEnv: RPtr;\n  _R_Interactive: RPtr;\n  _R_NaInt: RPtr;\n  _R_NaReal: RPtr;\n  _R_NaString: RPtr;\n  _R_LogicalNAValue: RPtr;\n  _R_NilValue: RPtr;\n  _R_TrueValue: RPtr;\n  _R_NamesSymbol: RPtr;\n  _R_UnboundValue: RPtr;\n  _SET_STRING_ELT: (ptr: RPtr, idx: number, val: RPtr) => void;\n  _SET_VECTOR_ELT: (ptr: RPtr, idx: number, val: RPtr) => void;\n  _setup_Rmainloop: () => void;\n  _strcpy: (dest: RPtr, src: RPtr) => number;\n  _vmaxget: () => number;\n  _vmaxset: (ptr: number) => void;\n  // TODO: Namespace all webR properties\n  webr: {\n    UnwindProtectException: typeof UnwindProtectException;\n    channel: ChannelWorker | undefined,\n    canvas: {\n      [key: number]: {\n        ctx: OffscreenCanvasRenderingContext2D;\n        offscreen: OffscreenCanvas;\n        transmit: boolean;\n      };\n    };\n    readConsole: () => number;\n    setPrompt: (prompt: string) => void;\n    resolveInit: () => void;\n    handleEvents: () => void;\n    dataViewer: (data: RPtr, title: string) => void;\n    evalJs: (code: RPtr) => unknown;\n    evalR: (expr: string | RObject, options?: EvalROptions) => RObject;\n    captureR: (expr: string | RObject, options: EvalROptions) => {\n      result: RObject,\n      output: RList,\n      images: ImageBitmap[],\n    };\n    setTimeoutWasm: (ptr: EmPtr, data: EmPtr, delay: number) => void;\n  };\n}\n\nexport const Module = {} as Module;\n\nexport type EmPtr = ReturnType<typeof Module.allocateUTF8>;\n\nexport interface DictEmPtrs {\n  [key: string]: EmPtr;\n}\n\nexport function dictEmFree(dict: { [key: string | number]: EmPtr }) {\n  Object.keys(dict).forEach((key) => Module._free(dict[key]));\n}\n", "import { Module, DictEmPtrs, dictEmFree } from './emscripten';\nimport { WebRData, RPtr } from './robj';\nimport { RObject, REnvironment, RHandle, handlePtr } from './robj-worker';\n\nexport function protect<T extends RHandle>(x: T): T {\n  Module._Rf_protect(handlePtr(x));\n  return x;\n}\n\nexport function protectInc<T extends RHandle>(x: T, prot: { n: number }): T {\n  Module._Rf_protect(handlePtr(x));\n  ++prot.n;\n  return x;\n}\n\nexport function protectWithIndex(x: RHandle): { loc: number; ptr: RPtr } {\n  // Integer size hardcoded to 4 bytes. This is fine but is there a\n  // way to call sizeof?\n  const pLoc = Module._malloc(4);\n\n  Module._R_ProtectWithIndex(handlePtr(x), pLoc);\n  const loc = Module.getValue(pLoc, 'i32');\n\n  return { loc: loc, ptr: pLoc };\n}\n\nexport function unprotectIndex(index: { ptr: RPtr }): void {\n  Module._Rf_unprotect(1);\n  Module._free(index.ptr);\n}\n\nexport function reprotect<T extends RHandle>(x: T, index: { loc: number; ptr: RPtr }): T {\n  Module._R_Reprotect(handlePtr(x), index.loc);\n  return x;\n}\n\nexport function unprotect(n: number) {\n  Module._Rf_unprotect(n);\n}\n\n// rlang convention: `env`-prefixed functions consistently take `env`\n// as first argument\nexport function envPoke(env: RHandle, sym: RHandle, value: RHandle) {\n  Module._Rf_defineVar(handlePtr(sym), handlePtr(value), handlePtr(env));\n}\n\nexport function parseEvalBare(code: string, env: WebRData): RObject {\n  const strings: DictEmPtrs = {};\n  const prot = { n: 0 };\n\n  try {\n    const envObj = new REnvironment(env);\n    protectInc(envObj, prot);\n\n    strings.code = Module.allocateUTF8(code);\n\n    const out = Module._R_ParseEvalString(strings.code, envObj.ptr);\n    return RObject.wrap(out);\n  } finally {\n    dictEmFree(strings);\n    unprotect(prot.n);\n  }\n}\n\nexport class UnwindProtectException extends Error {\n  cont: RPtr;\n  constructor(message: string, cont: RPtr) {\n    super(message);\n    this.name = 'UnwindProtectException';\n    this.cont = cont;\n  }\n}\n\nexport function safeEval(call: RHandle, env: RHandle): RPtr {\n  return Module.getWasmTableEntry(Module.GOT.ffi_safe_eval.value)(\n    handlePtr(call),\n    handlePtr(env)\n  );\n}\n", "// Original code from Synclink and Comlink. Released under Apache 2.0.\n\nexport const SZ_BUF_DOESNT_FIT = 0;\nexport const SZ_BUF_FITS_IDX = 1;\nexport const SZ_BUF_SIZE_IDX = 0;\n\nexport interface Endpoint extends EventSource {\n  postMessage(message: any, transfer?: Transferable[]): void;\n  start?: () => void;\n}\n\nexport interface EventSource {\n  addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: object): void;\n\n  removeEventListener(\n    type: string,\n    listener: EventListenerOrEventListenerObject,\n    options?: object,\n  ): void;\n}\n\nexport function toWireValue(value: any): [any, Transferable[]] {\n  return [value, transferCache.get(value) || []];\n}\n\nconst transferCache = new WeakMap<any, Transferable[]>();\nexport function transfer<T>(obj: T, transfers: Transferable[]): T {\n  transferCache.set(obj, transfers);\n  return obj;\n}\n\nexport type UUID = string;\n\nexport function isUUID(x: any): x is UUID {\n  return typeof x === 'string' && x.length === UUID_LENGTH;\n}\n\nexport const UUID_LENGTH = 63;\n\nexport function generateUUID(): UUID {\n  const result = Array.from({ length: 4 }, randomSegment).join('-');\n  if (result.length !== UUID_LENGTH) {\n    throw new Error('comlink internal error: UUID has the wrong length');\n  }\n  return result;\n}\n\nfunction randomSegment() {\n  let result = Math.floor(Math.random() * Number.MAX_SAFE_INTEGER).toString(16);\n  const pad = 15 - result.length;\n  if (pad > 0) {\n    result = Array.from({ length: pad }, () => 0).join('') + result;\n  }\n  return result;\n}\n", "/**\n * Module for working with R objects on the worker thead.\n * @module RWorker\n */\nimport { Module } from './emscripten';\nimport { Complex, isComplex, NamedEntries, NamedObject, WebRDataRaw, WebRDataScalar } from './robj';\nimport { WebRData, WebRDataAtomic, RPtr, RType, RTypeMap, RTypeNumber, RCtor } from './robj';\nimport { isWebRDataJs, WebRDataJs, WebRDataJsAtomic, WebRDataJsNode } from './robj';\nimport { WebRDataJsNull, WebRDataJsString, WebRDataJsSymbol } from './robj';\nimport { isSimpleObject } from './utils';\nimport { envPoke, parseEvalBare, protect, protectInc, unprotect } from './utils-r';\nimport { protectWithIndex, reprotect, unprotectIndex, safeEval } from './utils-r';\nimport { EvalROptions, ShelterID, isShelterID } from './webr-chan';\n\nexport type RHandle = RObject | RPtr;\n\nexport function handlePtr(x: RHandle): RPtr {\n  if (isRObject(x)) {\n    return x.ptr;\n  } else {\n    return x;\n  }\n}\n\n// Throw if an R object does not match a certain R type\nfunction assertRType(obj: RObjectBase, type: RType) {\n  if (Module._TYPEOF(obj.ptr) !== RTypeMap[type]) {\n    throw new Error(`Unexpected object type \"${obj.type()}\" when expecting type \"${type}\"`);\n  }\n}\n\n// TODO: Shelter should be a dictionary not an array\nexport const shelters = new Map<ShelterID, RPtr[]>();\n\n// Use this for implicit protection of objects sent to the main\n// thread. Currently uses the precious list but could use a different\n// mechanism in the future. Unprotection is explicit through\n// `Shelter.destroy()`.\nexport function keep(shelter: ShelterID, x: RHandle) {\n  const ptr = handlePtr(x);\n  Module._R_PreserveObject(ptr);\n\n  // TODO: Remove when shelter transition is complete\n  if (shelter === undefined) {\n    return;\n  }\n\n  if (isShelterID(shelter)) {\n    shelters.get(shelter)!.push(ptr);\n    return;\n  }\n\n  throw new Error('Unexpected shelter type ' + typeof shelter);\n}\n\n// Frees objects preserved with `keep()`. This method is called by\n// users in the main thread to release objects that were automatically\n// protected before being sent away.\nexport function destroy(shelter: ShelterID, x: RHandle) {\n  const ptr = handlePtr(x);\n  Module._R_ReleaseObject(ptr);\n\n  const objs: RPtr[] = shelters.get(shelter)!;\n  const loc = objs.indexOf(ptr);\n\n  if (loc < 0) {\n    throw new Error(\"Can't find object in shelter.\");\n  }\n\n  objs.splice(loc, 1);\n}\n\nexport function purge(shelter: ShelterID) {\n  const ptrs: RPtr[] = shelters.get(shelter)!;\n\n  for (const ptr of ptrs) {\n    try {\n      Module._R_ReleaseObject(ptr);\n    } catch (e) {\n      console.error(e);\n    }\n  }\n\n  shelters.set(shelter, []);\n}\n\nexport interface ToJsOptions {\n  depth: number;\n}\n\nexport type Nullable<T> = T | RNull;\n\nfunction newObjectFromData(obj: WebRData): RObject {\n  // Conversion of WebRDataJs type JS objects\n  if (isWebRDataJs(obj)) {\n    return new (getRWorkerClass(obj.type))(obj);\n  }\n\n  // Map JS's 'undefined' type to R's NULL object\n  if (typeof obj == 'undefined') {\n    return new RNull();\n  }\n\n  // Conversion of explicit R NULL value\n  if (obj && typeof obj === 'object' && 'type' in obj && obj.type === 'null') {\n    return new RNull();\n  }\n\n  // Direct conversion of scalar JS values\n  if (obj === null) {\n    return new RLogical({ type: 'logical', names: null, values: [null] });\n  }\n  if (typeof obj === 'boolean') {\n    return new RLogical(obj);\n  }\n  if (typeof obj === 'number') {\n    return new RDouble(obj);\n  }\n  if (typeof obj === 'string') {\n    return new RCharacter(obj);\n  }\n  if (isComplex(obj)) {\n    return new RComplex(obj);\n  }\n\n  // Conversion of composite JS objects\n  if (ArrayBuffer.isView(obj) || obj instanceof ArrayBuffer) {\n    return new RRaw(obj);\n  }\n  if (Array.isArray(obj)) {\n    return newObjectFromArray(obj);\n  }\n  // Any other JS object shape is reserved for creating an R `data.frame`\n  if (typeof obj === 'object') {\n    return RDataFrame.fromObject(obj);\n  }\n\n  throw new Error('R object construction for this JS object is not yet supported.');\n}\n\nfunction newObjectFromArray(arr: WebRData[]): RObject {\n  const prot = { n: 0 };\n\n  // Is this a D3 formatted data frame?\n  const hasObjects = arr.every((v) => v && typeof v === 'object' && !isRObject(v) && !isComplex(v));\n  if (hasObjects) {\n    const _arr = arr as { [key: string]: WebRData }[];\n    const isConsistent = _arr.every((a) => {\n      return Object.keys(a).filter((k) => !Object.keys(_arr[0]).includes(k)).length === 0 &&\n        Object.keys(_arr[0]).filter((k) => !Object.keys(a).includes(k)).length === 0;\n    });\n    const isAtomic = _arr.every((a) => Object.values(a).every((v) => {\n      return isAtomicType(v) || isRVectorAtomic(v);\n    }));\n    if (isConsistent && isAtomic) {\n      return RDataFrame.fromD3(_arr);\n    }\n  }\n\n  // Not D3 formatted - Can we shortcut and convert directly?\n  if (arr.every((v) => typeof v === 'boolean' || v === null)) {\n    return new RLogical(arr as (boolean | null)[]);\n  }\n  if (arr.every((v) => typeof v === 'number' || v === null)) {\n    return new RDouble(arr as (number | null)[]);\n  }\n  if (arr.every((v) => typeof v === 'string' || v === null)) {\n    return new RCharacter(arr as (string | null)[]);\n  }\n\n  // Not D3 & mixed types: use R's built in object coercion with c() so as to\n  // match R's built in coercion rules\n  try {\n    const call = new RCall([new RSymbol('c'), ...arr]);\n    protectInc(call, prot);\n    return call.eval();\n  } finally {\n    unprotect(prot.n);\n  }\n}\n\nexport class RObjectBase {\n  ptr: RPtr;\n  constructor(ptr: RPtr) {\n    this.ptr = ptr;\n  }\n\n  type(): RType {\n    const typeNumber = Module._TYPEOF(this.ptr) as RTypeNumber;\n    const type = Object.keys(RTypeMap).find(\n      (typeName) => RTypeMap[typeName as RType] === typeNumber\n    );\n    return type as RType;\n  }\n}\n\nexport class RObject extends RObjectBase {\n  constructor(data: WebRData) {\n    if (!(data instanceof RObjectBase)) {\n      return newObjectFromData(data);\n    }\n\n    super(data.ptr);\n  }\n\n  static wrap<T extends typeof RObject>(this: T, ptr: RPtr): InstanceType<T> {\n    const typeNumber = Module._TYPEOF(ptr) as RTypeNumber;\n    const type = Object.keys(RTypeMap)[Object.values(RTypeMap).indexOf(typeNumber)];\n    return new (getRWorkerClass(type as RType))(new RObjectBase(ptr)) as InstanceType<T>;\n  }\n\n  get [Symbol.toStringTag](): string {\n    return `RObject:${this.type()}`;\n  }\n\n  /** @internal */\n  static getPersistentObject(prop: keyof typeof objs): unknown {\n    return objs[prop];\n  }\n\n  /** @internal */\n  getPropertyValue(prop: keyof this): unknown {\n    return this[prop];\n  }\n\n  inspect(): void {\n    parseEvalBare('.Internal(inspect(x))', { x: this });\n  }\n\n  isNull(): this is RNull {\n    return Module._TYPEOF(this.ptr) === RTypeMap.null;\n  }\n\n  isNa(): boolean {\n    try {\n      const result = parseEvalBare('is.na(x)', { x: this }) as RLogical;\n      protect(result);\n      return result.toBoolean();\n    } finally {\n      unprotect(1);\n    }\n  }\n\n  isUnbound(): boolean {\n    return this.ptr === objs.unboundValue.ptr;\n  }\n\n  attrs(): Nullable<RPairlist> {\n    return RPairlist.wrap(Module._ATTRIB(this.ptr));\n  }\n\n  class(): RCharacter {\n    const prot = { n: 0 };\n    const classCall = new RCall([new RSymbol('class'), this]);\n    protectInc(classCall, prot);\n    try {\n      return classCall.eval() as RCharacter;\n    } finally {\n      unprotect(prot.n);\n    }\n  }\n\n  setNames(values: (string | null)[] | null): this {\n    let namesObj: RObject;\n\n    if (values === null) {\n      namesObj = objs.null;\n    } else if (Array.isArray(values) && values.every((v) => typeof v === 'string' || v === null)) {\n      namesObj = new RCharacter(values);\n    } else {\n      throw new Error('Argument to setNames must be null or an Array of strings or null');\n    }\n\n    // `setAttrib()` protects its inputs\n    Module._Rf_setAttrib(this.ptr, objs.namesSymbol.ptr, namesObj.ptr);\n    return this;\n  }\n\n  names(): (string | null)[] | null {\n    const names = RCharacter.wrap(Module._Rf_getAttrib(this.ptr, objs.namesSymbol.ptr));\n    if (names.isNull()) {\n      return null;\n    } else {\n      return names.toArray();\n    }\n  }\n\n  includes(name: string) {\n    const names = this.names();\n    return names && names.includes(name);\n  }\n\n  // eslint-disable-next-line @typescript-eslint/no-unused-vars\n  toJs(options: ToJsOptions = { depth: 0 }, depth = 1): WebRDataJs {\n    throw new Error('This R object cannot be converted to JS');\n  }\n\n  subset(prop: number | string): RObject {\n    return this.#slice(prop, objs.bracketSymbol.ptr);\n  }\n\n  get(prop: number | string): RObject {\n    return this.#slice(prop, objs.bracket2Symbol.ptr);\n  }\n\n  getDollar(prop: string): RObject {\n    return this.#slice(prop, objs.dollarSymbol.ptr);\n  }\n\n  #slice(prop: number | string, op: RPtr): RObject {\n    const prot = { n: 0 };\n\n    try {\n      const idx = new RObject(prop);\n      protectInc(idx, prot);\n\n      const call = Module._Rf_lang3(op, this.ptr, idx.ptr);\n      protectInc(call, prot);\n\n      return RObject.wrap(safeEval(call, objs.baseEnv));\n    } finally {\n      unprotect(prot.n);\n    }\n  }\n\n  pluck(...path: (string | number)[]): RObject | undefined {\n    const index = protectWithIndex(objs.null);\n\n    try {\n      const getter = (obj: RObject, prop: string | number): RObject => {\n        const out = obj.get(prop);\n        return reprotect(out, index);\n      };\n      const result = path.reduce(getter, this);\n\n      return result.isNull() ? undefined : result;\n    } finally {\n      unprotectIndex(index);\n    }\n  }\n\n  set(prop: string | number, value: RObject | WebRDataRaw): RObject {\n    const prot = { n: 0 };\n\n    try {\n      const idx = new RObject(prop);\n      protectInc(idx, prot);\n\n      const valueObj = new RObject(value);\n      protectInc(valueObj, prot);\n\n      const assign = new RSymbol('[[<-');\n      const call = Module._Rf_lang4(assign.ptr, this.ptr, idx.ptr, valueObj.ptr);\n      protectInc(call, prot);\n\n      return RObject.wrap(safeEval(call, objs.baseEnv));\n    } finally {\n      unprotect(prot.n);\n    }\n  }\n\n  /** @internal */\n  static getMethods(obj: RObject) {\n    const props = new Set<string>();\n    let cur: unknown = obj;\n    do {\n      Object.getOwnPropertyNames(cur).map((p) => props.add(p));\n    } while ((cur = Object.getPrototypeOf(cur)));\n    return [...props.keys()].filter((i) => typeof obj[i as keyof typeof obj] === 'function');\n  }\n}\n\nexport class RNull extends RObject {\n  constructor() {\n    super(new RObjectBase(Module.getValue(Module._R_NilValue, '*')));\n    return this;\n  }\n\n  toJs(): WebRDataJsNull {\n    return { type: 'null' };\n  }\n}\n\nexport class RSymbol extends RObject {\n  // Note that symbols don't need to be protected. This also means\n  // that allocating symbols in loops with random data is probably a\n  // bad idea because this leaks memory.\n  constructor(x: WebRDataScalar<string>) {\n    if (x instanceof RObjectBase) {\n      assertRType(x, 'symbol');\n      super(x);\n      return;\n    }\n    const name = Module.allocateUTF8(x as string);\n    try {\n      super(new RObjectBase(Module._Rf_install(name)));\n    } finally {\n      Module._free(name);\n    }\n  }\n\n  toJs(): WebRDataJsSymbol {\n    const obj = this.toObject();\n    return {\n      type: 'symbol',\n      printname: obj.printname,\n      symvalue: obj.symvalue,\n      internal: obj.internal,\n    };\n  }\n\n  toObject(): {\n    printname: string | null;\n    symvalue: RPtr | null;\n    internal: RPtr | null;\n  } {\n    return {\n      printname: this.printname().isUnbound() ? null : this.printname().toString(),\n      symvalue: this.symvalue().isUnbound() ? null : this.symvalue().ptr,\n      internal: this.internal().isNull() ? null : this.internal().ptr,\n    };\n  }\n\n  toString(): string {\n    return this.printname().toString();\n  }\n\n  printname(): RString {\n    return RString.wrap(Module._PRINTNAME(this.ptr));\n  }\n  symvalue(): RObject {\n    return RObject.wrap(Module._SYMVALUE(this.ptr));\n  }\n  internal(): RObject {\n    return RObject.wrap(Module._INTERNAL(this.ptr));\n  }\n}\n\nexport class RPairlist extends RObject {\n  constructor(val: WebRData) {\n    if (val instanceof RObjectBase) {\n      assertRType(val, 'pairlist');\n      super(val);\n      return this;\n    }\n\n    const prot = { n: 0 };\n\n    try {\n      const { names, values } = toWebRData(val);\n\n      const list = RPairlist.wrap(Module._Rf_allocList(values.length));\n      protectInc(list, prot);\n\n      for (\n        let [i, next] = [0, list as Nullable<RPairlist>];\n        !next.isNull();\n        [i, next] = [i + 1, next.cdr()]\n      ) {\n        next.setcar(new RObject(values[i]));\n      }\n\n      list.setNames(names);\n      super(list);\n    } finally {\n      unprotect(prot.n);\n    }\n  }\n\n  get length(): number {\n    return this.toArray().length;\n  }\n\n  toArray(options: ToJsOptions = { depth: 1 }): WebRData[] {\n    return this.toJs(options).values;\n  }\n\n  toObject({\n    allowDuplicateKey = true,\n    allowEmptyKey = false,\n    depth = -1,\n  } = {}): NamedObject<WebRData> {\n    const entries = this.entries({ depth });\n    const keys = entries.map(([k,]) => k);\n    if (!allowDuplicateKey && new Set(keys).size !== keys.length) {\n      throw new Error('Duplicate key when converting pairlist without allowDuplicateKey enabled');\n    }\n    if (!allowEmptyKey && keys.some((k) => !k)) {\n      throw new Error('Empty or null key when converting pairlist without allowEmptyKey enabled');\n    }\n    return Object.fromEntries(\n      entries.filter((u, idx) => entries.findIndex((v) => v[0] === u[0]) === idx)\n    ) as NamedObject<WebRData>;\n  }\n\n  entries(options: ToJsOptions = { depth: 1 }): NamedEntries<WebRData> {\n    const obj = this.toJs(options);\n    return obj.values.map((v, i) => [obj.names ? obj.names[i] : null, v]);\n  }\n\n  toJs(options: ToJsOptions = { depth: 0 }, depth = 1): WebRDataJsNode {\n    const namesArray: string[] = [];\n    let hasNames = false;\n    const values: WebRDataJsNode['values'] = [];\n\n    for (let next = this as Nullable<RPairlist>; !next.isNull(); next = next.cdr()) {\n      const symbol = next.tag();\n      if (symbol.isNull()) {\n        namesArray.push('');\n      } else {\n        hasNames = true;\n        namesArray.push(symbol.toString());\n      }\n      if (options.depth && depth >= options.depth) {\n        values.push(next.car());\n      } else {\n        values.push(next.car().toJs(options, depth + 1));\n      }\n    }\n    const names = hasNames ? namesArray : null;\n    return { type: 'pairlist', names, values };\n  }\n\n  includes(name: string): boolean {\n    return name in this.toObject();\n  }\n\n  setcar(obj: RObject): void {\n    Module._SETCAR(this.ptr, obj.ptr);\n  }\n\n  car(): RObject {\n    return RObject.wrap(Module._CAR(this.ptr));\n  }\n\n  cdr(): Nullable<RPairlist> {\n    return RObject.wrap(Module._CDR(this.ptr)) as Nullable<RPairlist>;\n  }\n\n  tag(): Nullable<RSymbol> {\n    return RObject.wrap(Module._TAG(this.ptr)) as Nullable<RSymbol>;\n  }\n}\n\nexport class RCall extends RObject {\n  constructor(val: WebRData) {\n    if (val instanceof RObjectBase) {\n      assertRType(val, 'call');\n      super(val);\n      return this;\n    }\n    const prot = { n: 0 };\n\n    try {\n      const { values } = toWebRData(val);\n      const objs = values.map((value) => protectInc(new RObject(value), prot));\n      const call = RCall.wrap(Module._Rf_allocVector(RTypeMap.call, values.length));\n      protectInc(call, prot);\n\n      for (\n        let [i, next] = [0, call as Nullable<RPairlist>];\n        !next.isNull();\n        [i, next] = [i + 1, next.cdr()]\n      ) {\n        next.setcar(objs[i]);\n      }\n      super(call);\n    } finally {\n      unprotect(prot.n);\n    }\n  }\n\n  setcar(obj: RObject): void {\n    Module._SETCAR(this.ptr, obj.ptr);\n  }\n\n  car(): RObject {\n    return RObject.wrap(Module._CAR(this.ptr));\n  }\n\n  cdr(): Nullable<RPairlist> {\n    return RObject.wrap(Module._CDR(this.ptr)) as Nullable<RPairlist>;\n  }\n\n  eval(): RObject {\n    return Module.webr.evalR(this, { env: objs.baseEnv });\n  }\n\n  capture(options: EvalROptions = {}) {\n    return Module.webr.captureR(this, options);\n  }\n\n  deparse(): string {\n    const prot = { n: 0 };\n    try {\n      const call = Module._Rf_lang2(\n        new RSymbol('deparse1').ptr,\n        Module._Rf_lang2(new RSymbol('quote').ptr, this.ptr)\n      );\n      protectInc(call, prot);\n\n      const val = RCharacter.wrap(safeEval(call, objs.baseEnv));\n      protectInc(val, prot);\n\n      return val.toString();\n    } finally {\n      unprotect(prot.n);\n    }\n  }\n}\n\nexport class RList extends RObject {\n  constructor(val: WebRData, names: (string | null)[] | null = null) {\n    if (val instanceof RObjectBase) {\n      assertRType(val, 'list');\n      super(val);\n      if (names) {\n        if (names.length !== this.length) {\n          throw new Error(\n            \"Can't construct named `RList`. Supplied `names` must be the same length as the list.\"\n          );\n        }\n        this.setNames(names);\n      }\n      return this;\n    }\n\n    const prot = { n: 0 };\n\n    try {\n      const data = toWebRData(val);\n      const ptr = Module._Rf_allocVector(RTypeMap.list, data.values.length);\n      protectInc(ptr, prot);\n\n      data.values.forEach((v, i) => {\n        // When we specifically use the `RList` constructor, deeply convert R objects to R lists\n        if (isSimpleObject(v)) {\n          Module._SET_VECTOR_ELT(ptr, i, new RList(v).ptr);\n        } else {\n          Module._SET_VECTOR_ELT(ptr, i, new RObject(v).ptr);\n        }\n      });\n\n      const _names = names ? names : data.names;\n      if (_names && _names.length !== data.values.length) {\n        throw new Error(\n          \"Can't construct named `RList`. Supplied `names` must be the same length as the list.\"\n        );\n      }\n      RObject.wrap(ptr).setNames(_names);\n\n      super(new RObjectBase(ptr));\n    } finally {\n      unprotect(prot.n);\n    }\n  }\n\n  get length(): number {\n    return Module._LENGTH(this.ptr);\n  }\n\n  isDataFrame(): boolean {\n    const classes = RPairlist.wrap(Module._ATTRIB(this.ptr)).get('class') as RNull | RCharacter;\n    return !classes.isNull() && classes.toArray().includes('data.frame');\n  }\n\n  toArray(options: { depth: number } = { depth: 1 }): WebRData[] {\n    return this.toJs(options).values;\n  }\n\n  toObject({\n    allowDuplicateKey = true,\n    allowEmptyKey = false,\n    depth = -1,\n  } = {}): NamedObject<WebRData> {\n    const entries = this.entries({ depth });\n    const keys = entries.map(([k,]) => k);\n    if (!allowDuplicateKey && new Set(keys).size !== keys.length) {\n      throw new Error('Duplicate key when converting list without allowDuplicateKey enabled');\n    }\n    if (!allowEmptyKey && keys.some((k) => !k)) {\n      throw new Error('Empty or null key when converting list without allowEmptyKey enabled');\n    }\n    return Object.fromEntries(\n      entries.filter((u, idx) => entries.findIndex((v) => v[0] === u[0]) === idx)\n    ) as NamedObject<WebRData>;\n  }\n\n  toD3(): NamedObject<WebRData>[] {\n    if (!this.isDataFrame()) {\n      throw new Error(\n        \"Can't convert R list object to D3 format. Object must be of class 'data.frame'.\"\n      );\n    }\n    const entries = this.entries() as Array<[string, atomicType[]]>;\n    return entries.reduce((a, entry) => {\n      entry[1].forEach((v, j) => a[j] = Object.assign(a[j] || {}, { [entry[0]!]: v }));\n      return a;\n    }, []);\n  }\n\n  entries(options: { depth: number } = { depth: -1 }): NamedEntries<WebRData> {\n    const obj = this.toJs(options);\n\n    // If this is a data frame, assume we have atomic vector columns and can\n    // convert directly to array values by default.\n    if (this.isDataFrame() && options.depth < 0) {\n      obj.values = (obj.values as RVectorAtomic<atomicType>[]).map((v) => v.toArray());\n    }\n    return obj.values.map((v, i) => [obj.names ? obj.names[i] : null, v]);\n  }\n\n  toJs(options: { depth: number } = { depth: 0 }, depth = 1): WebRDataJsNode {\n    return {\n      type: 'list',\n      names: this.names(),\n      values: [...Array(this.length).keys()].map((i) => {\n        if (options.depth && depth >= options.depth) {\n          return this.get(i + 1);\n        } else {\n          return this.get(i + 1).toJs(options, depth + 1);\n        }\n      }),\n    };\n  }\n}\n\nexport class RDataFrame extends RList {\n  constructor(val: WebRData) {\n    if (val instanceof RObjectBase) {\n      super(val);\n      if (!this.isDataFrame()) {\n        throw new Error(\"Can't construct `RDataFrame`. Supplied R object is not a `data.frame`.\");\n      }\n      return this;\n    }\n    return RDataFrame.fromObject(val);\n  }\n\n  static fromObject(obj: WebRData) {\n    const { names, values } = toWebRData(obj);\n    const prot = { n: 0 };\n\n    // Do we have consistent columns of atomic type? If so, make a `data.frame`.\n    try {\n      const hasNames = !!names && names.length > 0 && names.every((v) => v);\n      const hasArrays = values.length > 0 && values.every((v) => {\n        return Array.isArray(v) || ArrayBuffer.isView(v) || v instanceof ArrayBuffer;\n      });\n\n      if (hasNames && hasArrays) {\n        const _values = values as WebRData[][];\n        const isConsistentLength = _values.every((a) => a.length === _values[0].length);\n        const isAtomic = _values.every((a) => {\n          return isAtomicType(a[0]) || isRVectorAtomic(a[0]);\n        });\n\n        if (isConsistentLength && isAtomic) {\n          const listObj = new RList({\n            type: 'list',\n            names: names,\n            values: _values.map((a) => newObjectFromData(a))\n          });\n          protectInc(listObj, prot);\n\n          const asDataFrame = new RCall([new RSymbol('as.data.frame'), listObj]);\n          protectInc(asDataFrame, prot);\n\n          return new RDataFrame(asDataFrame.eval());\n        }\n      }\n    } finally {\n      unprotect(prot.n);\n    }\n\n    // Not eligible as a `data.frame`, throw an error.\n    throw new Error(\"Can't construct `data.frame`. Source object is not eligible.\");\n  }\n\n  static fromD3(arr: { [key: string]: WebRData }[]) {\n    return this.fromObject(\n      Object.fromEntries(Object.keys(arr[0]).map((k) => [k, arr.map((v) => v[k])]))\n    );\n  }\n}\n\nexport class RFunction extends RObject {\n  exec(...args: (WebRDataRaw | RObject)[]): RObject {\n    const prot = { n: 0 };\n\n    try {\n      const call = new RCall([this, ...args]);\n      protectInc(call, prot);\n      return call.eval();\n    } finally {\n      unprotect(prot.n);\n    }\n  }\n\n  capture(options: EvalROptions = {}, ...args: (WebRDataRaw | RObject)[]) {\n    const prot = { n: 0 };\n\n    try {\n      const call = new RCall([this, ...args]);\n      protectInc(call, prot);\n      return call.capture(options);\n    } finally {\n      unprotect(prot.n);\n    }\n  }\n}\n\nexport class RString extends RObject {\n  static CEType = {\n    CE_NATIVE: 0,\n    CE_UTF8: 1,\n    CE_LATIN1: 2,\n    CE_BYTES: 3,\n    CE_SYMBOL: 5,\n    CE_ANY: 99\n  } as const;\n\n  // Unlike symbols, strings are not cached and must thus be protected\n  constructor(x: WebRDataScalar<string>) {\n    if (x instanceof RObjectBase) {\n      assertRType(x, 'string');\n      super(x);\n      return;\n    }\n\n    const name = Module.allocateUTF8(x as string);\n\n    try {\n      super(new RObjectBase(Module._Rf_mkCharCE(name, RString.CEType.CE_UTF8)));\n    } finally {\n      Module._free(name);\n    }\n  }\n\n  toString(): string {\n    const vmax = Module._vmaxget();\n    try {\n      return Module.UTF8ToString(Module._Rf_translateCharUTF8(this.ptr));\n    } finally {\n      Module._vmaxset(vmax);\n    }\n  }\n\n  toJs(): WebRDataJsString {\n    return {\n      type: 'string',\n      value: this.toString(),\n    };\n  }\n}\n\nexport class REnvironment extends RObject {\n  constructor(val: WebRData = {}) {\n    if (val instanceof RObjectBase) {\n      assertRType(val, 'environment');\n      super(val);\n      return this;\n    }\n    let nProt = 0;\n\n    try {\n      const { names, values } = toWebRData(val);\n\n      const ptr = protect(Module._R_NewEnv(objs.globalEnv.ptr, 0, 0));\n      ++nProt;\n\n      values.forEach((v, i) => {\n        const name = names ? names[i] : null;\n        if (!name) {\n          throw new Error(\"Can't create object in new environment with empty symbol name\");\n        }\n\n        const sym = new RSymbol(name);\n        const vObj = protect(new RObject(v));\n        try {\n          envPoke(ptr, sym, vObj);\n        } finally {\n          unprotect(1);\n        }\n      });\n\n      super(new RObjectBase(ptr));\n    } finally {\n      unprotect(nProt);\n    }\n  }\n\n  ls(all = false, sorted = true): string[] {\n    const ls = RCharacter.wrap(Module._R_lsInternal3(this.ptr, Number(all), Number(sorted)));\n    return ls.toArray() as string[];\n  }\n\n  bind(name: string, value: WebRData): void {\n    const sym = new RSymbol(name);\n    const valueObj = protect(new RObject(value));\n\n    try {\n      envPoke(this, sym, valueObj);\n    } finally {\n      unprotect(1);\n    }\n  }\n\n  names(): string[] {\n    return this.ls(true, true);\n  }\n\n  frame(): RObject {\n    return RObject.wrap(Module._FRAME(this.ptr));\n  }\n\n  subset(prop: number | string): RObject {\n    if (typeof prop === 'number') {\n      throw new Error('Object of type environment is not subsettable');\n    }\n    return this.getDollar(prop);\n  }\n\n  toObject({ depth = -1 } = {}): NamedObject<WebRData> {\n    const symbols = this.names();\n    return Object.fromEntries(\n      [...Array(symbols.length).keys()].map((i) => {\n        const value = this.getDollar(symbols[i]);\n        return [symbols[i], depth < 0 ? value : value.toJs({ depth })];\n      })\n    );\n  }\n\n  toJs(options: { depth: number } = { depth: 0 }, depth = 1): WebRDataJsNode {\n    const names = this.names();\n    const values = [...Array(names.length).keys()].map((i) => {\n      if (options.depth && depth >= options.depth) {\n        return this.getDollar(names[i]);\n      } else {\n        return this.getDollar(names[i]).toJs(options, depth + 1);\n      }\n    });\n\n    return {\n      type: 'environment',\n      names,\n      values,\n    };\n  }\n}\n\ntype TypedArray =\n  | Int8Array\n  | Uint8Array\n  | Int16Array\n  | Uint16Array\n  | Int32Array\n  | Uint32Array\n  | Float32Array\n  | Float64Array;\n\nexport type atomicType = number | boolean | Complex | string;\n\nabstract class RVectorAtomic<T extends atomicType> extends RObject {\n  constructor(\n    val: WebRDataAtomic<T>,\n    kind: RType,\n    newSetter: (ptr: RPtr) => (v: any, i: number) => void\n  ) {\n    if (val instanceof RObjectBase) {\n      assertRType(val, kind);\n      super(val);\n      return this;\n    }\n\n    const prot = { n: 0 };\n\n    try {\n      const { names, values } = toWebRData(val);\n\n      const ptr = Module._Rf_allocVector(RTypeMap[kind], values.length);\n      protectInc(ptr, prot);\n\n      values.forEach(newSetter(ptr));\n      RObject.wrap(ptr).setNames(names);\n\n      super(new RObjectBase(ptr));\n    } finally {\n      unprotect(prot.n);\n    }\n  }\n\n  get length(): number {\n    return Module._LENGTH(this.ptr);\n  }\n\n  get(prop: number | string): this {\n    return super.get(prop) as this;\n  }\n\n  subset(prop: number | string): this {\n    return super.subset(prop) as this;\n  }\n\n  getDollar(): RObject {\n    throw new Error('$ operator is invalid for atomic vectors');\n  }\n\n  detectMissing(): boolean[] {\n    const prot = { n: 0 };\n\n    try {\n      const call = Module._Rf_lang2(new RSymbol('is.na').ptr, this.ptr);\n      protectInc(call, prot);\n\n      const val = RLogical.wrap(safeEval(call, objs.baseEnv));\n      protectInc(val, prot);\n\n      const ret = val.toTypedArray();\n      return Array.from(ret).map((elt) => Boolean(elt));\n    } finally {\n      unprotect(prot.n);\n    }\n  }\n\n  abstract toTypedArray(): TypedArray;\n\n  toArray(): (T | null)[] {\n    const arr = this.toTypedArray();\n    return this.detectMissing().map((m, idx) => (m ? null : (arr[idx] as T)));\n  }\n\n  toObject({ allowDuplicateKey = true, allowEmptyKey = false } = {}): NamedObject<T | null> {\n    const entries = this.entries();\n    const keys = entries.map(([k,]) => k);\n    if (!allowDuplicateKey && new Set(keys).size !== keys.length) {\n      throw new Error(\n        'Duplicate key when converting atomic vector without allowDuplicateKey enabled'\n      );\n    }\n    if (!allowEmptyKey && keys.some((k) => !k)) {\n      throw new Error(\n        'Empty or null key when converting atomic vector without allowEmptyKey enabled'\n      );\n    }\n    return Object.fromEntries(\n      entries.filter((u, idx) => entries.findIndex((v) => v[0] === u[0]) === idx)\n    ) as NamedObject<T | null>;\n  }\n\n  entries(): NamedEntries<T | null> {\n    const values = this.toArray();\n    const names = this.names();\n    return values.map((v, i) => [names ? names[i] : null, v]);\n  }\n\n  toJs(): WebRDataJsAtomic<T> {\n    return {\n      type: this.type() as 'logical' | 'integer' | 'double' | 'complex' | 'character' | 'raw',\n      names: this.names(),\n      values: this.toArray(),\n    };\n  }\n}\n\nexport class RLogical extends RVectorAtomic<boolean> {\n  constructor(val: WebRDataAtomic<boolean>) {\n    super(val, 'logical', RLogical.#newSetter);\n  }\n\n  static #newSetter = (ptr: RPtr) => {\n    const data = Module._LOGICAL(ptr);\n    const naLogical = Module.getValue(Module._R_NaInt, 'i32');\n    return (v: null | boolean, i: number) => {\n      Module.setValue(data + 4 * i, v === null ? naLogical : Boolean(v), 'i32');\n    };\n  };\n\n  getBoolean(idx: number): boolean | null {\n    return this.get(idx).toArray()[0];\n  }\n\n  toBoolean(): boolean {\n    if (this.length !== 1) {\n      throw new Error(\"Can't convert atomic vector of length > 1 to a scalar JS value\");\n    }\n    const val = this.getBoolean(1);\n    if (val === null) {\n      throw new Error(\"Can't convert missing value `NA` to a JS boolean\");\n    }\n    return val;\n  }\n\n  toTypedArray(): Int32Array {\n    return new Int32Array(\n      Module.HEAP32.subarray(\n        Module._LOGICAL(this.ptr) / 4,\n        Module._LOGICAL(this.ptr) / 4 + this.length\n      )\n    );\n  }\n\n  toArray(): (boolean | null)[] {\n    const arr = this.toTypedArray();\n    return this.detectMissing().map((m, idx) => (m ? null : Boolean(arr[idx])));\n  }\n}\n\nexport class RInteger extends RVectorAtomic<number> {\n  constructor(val: WebRDataAtomic<number>) {\n    super(val, 'integer', RInteger.#newSetter);\n  }\n\n  static #newSetter = (ptr: RPtr) => {\n    const data = Module._INTEGER(ptr);\n    const naInteger = Module.getValue(Module._R_NaInt, 'i32');\n\n    return (v: null | number, i: number) => {\n      Module.setValue(data + 4 * i, v === null ? naInteger : Math.round(Number(v)), 'i32');\n    };\n  };\n\n  getNumber(idx: number): number | null {\n    return this.get(idx).toArray()[0];\n  }\n\n  toNumber(): number {\n    if (this.length !== 1) {\n      throw new Error(\"Can't convert atomic vector of length > 1 to a scalar JS value\");\n    }\n    const val = this.getNumber(1);\n    if (val === null) {\n      throw new Error(\"Can't convert missing value `NA` to a JS number\");\n    }\n    return val;\n  }\n\n  toTypedArray(): Int32Array {\n    return new Int32Array(\n      Module.HEAP32.subarray(\n        Module._INTEGER(this.ptr) / 4,\n        Module._INTEGER(this.ptr) / 4 + this.length\n      )\n    );\n  }\n}\n\nexport class RDouble extends RVectorAtomic<number> {\n  constructor(val: WebRDataAtomic<number>) {\n    super(val, 'double', RDouble.#newSetter);\n  }\n\n  static #newSetter = (ptr: RPtr) => {\n    const data = Module._REAL(ptr);\n    const naDouble = Module.getValue(Module._R_NaReal, 'double');\n\n    return (v: null | number, i: number) => {\n      Module.setValue(data + 8 * i, v === null ? naDouble : v, 'double');\n    };\n  };\n\n  getNumber(idx: number): number | null {\n    return this.get(idx).toArray()[0];\n  }\n\n  toNumber(): number {\n    if (this.length !== 1) {\n      throw new Error(\"Can't convert atomic vector of length > 1 to a scalar JS value\");\n    }\n    const val = this.getNumber(1);\n    if (val === null) {\n      throw new Error(\"Can't convert missing value `NA` to a JS number\");\n    }\n    return val;\n  }\n\n  toTypedArray(): Float64Array {\n    return new Float64Array(\n      Module.HEAPF64.subarray(Module._REAL(this.ptr) / 8, Module._REAL(this.ptr) / 8 + this.length)\n    );\n  }\n}\n\nexport class RComplex extends RVectorAtomic<Complex> {\n  constructor(val: WebRDataAtomic<Complex>) {\n    super(val, 'complex', RComplex.#newSetter);\n  }\n\n  static #newSetter = (ptr: RPtr) => {\n    const data = Module._COMPLEX(ptr);\n    const naDouble = Module.getValue(Module._R_NaReal, 'double');\n\n    return (v: null | Complex, i: number) => {\n      Module.setValue(data + 8 * (2 * i), v === null ? naDouble : v.re, 'double');\n      Module.setValue(data + 8 * (2 * i + 1), v === null ? naDouble : v.im, 'double');\n    };\n  };\n\n  getComplex(idx: number): Complex | null {\n    return this.get(idx).toArray()[0];\n  }\n\n  toComplex(): Complex {\n    if (this.length !== 1) {\n      throw new Error(\"Can't convert atomic vector of length > 1 to a scalar JS value\");\n    }\n    const val = this.getComplex(1);\n    if (val === null) {\n      throw new Error(\"Can't convert missing value `NA` to a JS object\");\n    }\n    return val;\n  }\n\n  toTypedArray(): Float64Array {\n    return new Float64Array(\n      Module.HEAPF64.subarray(\n        Module._COMPLEX(this.ptr) / 8,\n        Module._COMPLEX(this.ptr) / 8 + 2 * this.length\n      )\n    );\n  }\n\n  toArray(): (Complex | null)[] {\n    const arr = this.toTypedArray();\n    return this.detectMissing().map((m, idx) =>\n      m ? null : { re: arr[2 * idx], im: arr[2 * idx + 1] }\n    );\n  }\n}\n\nexport class RCharacter extends RVectorAtomic<string> {\n  constructor(val: WebRDataAtomic<string>) {\n    super(val, 'character', RCharacter.#newSetter);\n  }\n\n  static #newSetter = (ptr: RPtr) => {\n    return (v: null | string, i: number) => {\n      if (v === null) {\n        Module._SET_STRING_ELT(ptr, i, objs.naString.ptr);\n      } else {\n        Module._SET_STRING_ELT(ptr, i, new RString(v).ptr);\n      }\n    };\n  };\n\n  getString(idx: number): string | null {\n    return this.get(idx).toArray()[0];\n  }\n\n  toString(): string {\n    if (this.length !== 1) {\n      throw new Error(\"Can't convert atomic vector of length > 1 to a scalar JS value\");\n    }\n    const val = this.getString(1);\n    if (val === null) {\n      throw new Error(\"Can't convert missing value `NA` to a JS string\");\n    }\n    return val;\n  }\n\n  toTypedArray(): Uint32Array {\n    return new Uint32Array(\n      Module.HEAPU32.subarray(\n        Module._STRING_PTR(this.ptr) / 4,\n        Module._STRING_PTR(this.ptr) / 4 + this.length\n      )\n    );\n  }\n\n  toArray(): (string | null)[] {\n    const vmax = Module._vmaxget();\n    try {\n      return this.detectMissing().map((m, idx) =>\n        m ? null : Module.UTF8ToString(\n          Module._Rf_translateCharUTF8(Module._STRING_ELT(this.ptr, idx))\n        )\n      );\n    } finally {\n      Module._vmaxset(vmax);\n    }\n  }\n}\n\nexport class RRaw extends RVectorAtomic<number> {\n  constructor(val: WebRDataAtomic<number>) {\n    if (val instanceof ArrayBuffer) {\n      val = new Uint8Array(val);\n    }\n    super(val, 'raw', RRaw.#newSetter);\n  }\n\n  static #newSetter = (ptr: RPtr) => {\n    const data = Module._RAW(ptr);\n\n    return (v: number, i: number) => {\n      Module.setValue(data + i, Number(v), 'i8');\n    };\n  };\n\n  getNumber(idx: number): number | null {\n    return this.get(idx).toArray()[0];\n  }\n\n  toNumber(): number {\n    if (this.length !== 1) {\n      throw new Error(\"Can't convert atomic vector of length > 1 to a scalar JS value\");\n    }\n    const val = this.getNumber(1);\n    if (val === null) {\n      throw new Error(\"Can't convert missing value `NA` to a JS number\");\n    }\n    return val;\n  }\n\n  toTypedArray(): Uint8Array {\n    return new Uint8Array(\n      Module.HEAPU8.subarray(Module._RAW(this.ptr), Module._RAW(this.ptr) + this.length)\n    );\n  }\n}\n\n/*\n * Convert the various types possible in the type union WebRData into\n * consistently typed arrays of names and values.\n */\nfunction toWebRData<T>(jsObj: WebRDataAtomic<T>): {\n  names: (string | null)[] | null;\n  values: (T | null)[];\n};\nfunction toWebRData(jsObj: WebRData): WebRData;\nfunction toWebRData(jsObj: WebRData): WebRData {\n  if (isWebRDataJs(jsObj)) {\n    return jsObj;\n  } else if (Array.isArray(jsObj) || ArrayBuffer.isView(jsObj)) {\n    return { names: null, values: jsObj };\n  } else if (jsObj && typeof jsObj === 'object' && !isComplex(jsObj)) {\n    return {\n      names: Object.keys(jsObj),\n      values: Object.values(jsObj),\n    };\n  }\n  return { names: null, values: [jsObj] };\n}\n\nexport function getRWorkerClass(type: RType | RCtor): typeof RObject {\n  const typeClasses: { [key: string]: typeof RObject } = {\n    object: RObject,\n    null: RNull,\n    symbol: RSymbol,\n    pairlist: RPairlist,\n    closure: RFunction,\n    environment: REnvironment,\n    call: RCall,\n    special: RFunction,\n    builtin: RFunction,\n    string: RString,\n    logical: RLogical,\n    integer: RInteger,\n    double: RDouble,\n    complex: RComplex,\n    character: RCharacter,\n    list: RList,\n    raw: RRaw,\n    function: RFunction,\n    dataframe: RDataFrame,\n  };\n  if (type in typeClasses) {\n    return typeClasses[type];\n  }\n  return RObject;\n}\n\n/**\n * Test for an RWorker.RObject instance.\n *\n * RWorker.RObject is the internal interface to R objects, intended to be used\n * on the worker thread.\n *\n * @private\n * @param {any} value The object to test.\n * @return {boolean} True if the object is an instance of an RObject.\n */\nexport function isRObject(value: any): value is RObject {\n  return value instanceof RObject;\n}\n\n/**\n * Test for an RWorker.RVectorAtomic instance.\n *\n * @private\n * @param {any} value The object to test.\n * @return {boolean} True if the object is an instance of an RVectorAtomic.\n */\nexport function isRVectorAtomic(value: any): value is RVectorAtomic<atomicType> {\n  const atomicRTypes = ['logical', 'integer', 'double', 'complex', 'character'];\n\n  return (\n    (isRObject(value) && atomicRTypes.includes(value.type()))\n    || (isRObject(value) && value.isNa())\n  );\n}\n\n/**\n * Test for an atomicType, including missing `null` values.\n *\n * @private\n * @param {any} value The object to test.\n * @return {boolean} True if the object is of type atomicType.\n */\nexport function isAtomicType(value: any): value is atomicType | null {\n  return (\n    value === null\n    || typeof value === 'number'\n    || typeof value === 'boolean'\n    || typeof value === 'string'\n    || isComplex(value)\n  );\n}\n\n/**\n * A store for persistent R objects, initialised at R startup.\n */\nexport let objs: {\n  baseEnv: REnvironment,\n  bracket2Symbol: RSymbol,\n  bracketSymbol: RSymbol,\n  dollarSymbol: RSymbol,\n  emptyEnv: REnvironment,\n  false: RLogical,\n  globalEnv: REnvironment,\n  na: RLogical,\n  namesSymbol: RSymbol,\n  naString: RObject,\n  null: RNull,\n  true: RLogical,\n  unboundValue: RObject,\n};\n\n/**\n * Populate the persistent R object store.\n * @internal\n */\nexport function initPersistentObjects() {\n  objs = {\n    baseEnv: REnvironment.wrap(Module.getValue(Module._R_BaseEnv, '*')),\n    bracket2Symbol: RSymbol.wrap(Module.getValue(Module._R_Bracket2Symbol, '*')),\n    bracketSymbol: RSymbol.wrap(Module.getValue(Module._R_BracketSymbol, '*')),\n    dollarSymbol: RSymbol.wrap(Module.getValue(Module._R_DollarSymbol, '*')),\n    emptyEnv: REnvironment.wrap(Module.getValue(Module._R_EmptyEnv, '*')),\n    false: RLogical.wrap(Module.getValue(Module._R_FalseValue, '*')),\n    globalEnv: REnvironment.wrap(Module.getValue(Module._R_GlobalEnv, '*')),\n    na: RLogical.wrap(Module.getValue(Module._R_LogicalNAValue, '*')),\n    namesSymbol: RSymbol.wrap(Module.getValue(Module._R_NamesSymbol, '*')),\n    naString: RObject.wrap(Module.getValue(Module._R_NaString, '*')),\n    null: RNull.wrap(Module.getValue(Module._R_NilValue, '*')),\n    true: RLogical.wrap(Module.getValue(Module._R_TrueValue, '*')),\n    unboundValue: RObject.wrap(Module.getValue(Module._R_UnboundValue, '*')),\n  };\n}\n", "import { IN_NODE } from './compat';\nimport { WebRError } from './error';\nimport { isComplex, isWebRDataJs } from './robj';\nimport { RObjectBase } from './robj-worker';\n\nexport type PromiseHandles<T = void> = {\n  resolve: ResolveFn<T>;\n  reject: RejectFn;\n  promise: Promise<T>;\n};\nexport type ResolveFn<T = unknown> = (value: T | PromiseLike<T>) => void;\nexport type RejectFn = (_reason?: any) => void;\n\nexport function promiseHandles<T = void>(): PromiseHandles<T> {\n  const out = {\n    resolve: (() => { return; }) as ResolveFn<T>,\n    reject: (() => { return; }) as RejectFn,\n    promise: Promise.resolve() as Promise<T>,\n  };\n\n  const promise = new Promise<T>((resolve, reject) => {\n    out.resolve = resolve;\n    out.reject = reject;\n  });\n  out.promise = promise;\n\n  return out;\n}\n\nexport function sleep(ms: number) {\n  return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nexport function replaceInObject<T>(\n  obj: T | T[],\n  test: (obj: any) => boolean,\n  replacer: (obj: any, ...replacerArgs: any[]) => unknown,\n  ...replacerArgs: unknown[]\n): T | T[] {\n  if (obj === null || obj === undefined || isImageBitmap(obj)) {\n    return obj;\n  }\n  if (obj instanceof ArrayBuffer) {\n    return new Uint8Array(obj) as T;\n  }\n  if (test(obj)) {\n    return replacer(obj, ...replacerArgs) as T;\n  }\n  if (Array.isArray(obj) || ArrayBuffer.isView(obj)) {\n    return (obj as unknown[]).map((v) =>\n      replaceInObject(v, test, replacer, ...replacerArgs)\n    ) as T[];\n  }\n  if (obj instanceof RObjectBase) {\n    return obj;\n  }\n  if (typeof obj === 'object') {\n    return Object.fromEntries(\n      Object.entries(obj).map(([k, v]) => [k, replaceInObject(v, test, replacer, ...replacerArgs)])\n    ) as T;\n  }\n  return obj;\n}\n\n/* Workaround for loading a cross-origin script.\n *\n * When fetching a worker script, the fetch is required by the spec to\n * use \"same-origin\" mode. This is to avoid loading a worker with a\n * cross-origin global scope, which can allow for a cross-origin\n * restriction bypass.\n *\n * When the fetch URL begins with 'http', we assume the request is\n * cross-origin. We download the content of the URL using a XHR first,\n * create a blob URL containing the requested content, then load the\n * blob URL as a script.\n *\n * The origin of a blob URL is the same as that of the environment that\n * created the URL, and so the global scope of the resulting worker is\n * no longer cross-origin. In that case, the cross-origin restriction\n * bypass is not possible, and the script is permitted to be loaded.\n */\nexport function newCrossOriginWorker(\n  url: string,\n  cb: (worker: Worker) => void,\n  onError?: (error: Error) => void,\n  options?: WorkerOptions,\n  async = true,\n): void {\n  const req = new XMLHttpRequest();\n  req.open('get', url, async);\n  req.onload = () => {\n    if (req.status >= 200 && req.status < 300) {\n      try {\n        const worker = new Worker(URL.createObjectURL(new Blob([req.responseText])), options);\n        cb(worker);\n      } catch (error) {\n        if (onError) {\n          onError(error instanceof Error ? error : new Error(String(error)));\n        } else {\n          throw error;\n        }\n      }\n    } else {\n      if (onError) {\n        onError(new Error(`Worker loading error: HTTP ${req.status}`));\n      } else {\n        console.error(`HTTP Error: ${req.status}`);\n      }\n    }\n  };\n\n  req.onerror = () => {\n    if (onError) {\n      onError(new Error(`Network error loading ${url}`));\n    } else {\n      console.error(`Network error loading ${url}`);\n    }\n  };\n  req.send();\n}\n\nexport function isCrossOrigin(urlString: string) {\n  if (IN_NODE) return false;\n  const url1 = new URL(location.href);\n  const url2 = new URL(urlString, location.origin);\n  if (url1.host === url2.host && url1.port === url2.port && url1.protocol === url2.protocol) {\n    return false;\n  }\n  return true;\n}\n\nexport function isImageBitmap(value: any): value is ImageBitmap {\n  return (typeof ImageBitmap !== 'undefined' && value instanceof ImageBitmap);\n}\n\nexport function throwUnreachable(context?: string) {\n  let msg = 'Reached the unreachable';\n  msg = msg + (context ? ': ' + context : '.');\n\n  throw new WebRError(msg);\n}\n\nexport function isSimpleObject(value: any): value is { [key: string | number | symbol]: any } {\n  return (\n    typeof value === 'object' &&\n    value !== null &&\n    !Array.isArray(value) &&\n    !(ArrayBuffer.isView(value)) &&\n    !isComplex(value) &&\n    !isWebRDataJs(value) &&\n    !(value instanceof Date) &&\n    !(value instanceof RegExp) &&\n    !(value instanceof Error) &&\n    !(value instanceof RObjectBase) &&\n    Object.getPrototypeOf(value) === Object.prototype\n  );\n}\n\n// From https://stackoverflow.com/a/9458996\nexport function bufferToBase64(buffer: ArrayBufferLike): string {\n  let binary = '';\n  const bytes = new Uint8Array(buffer);\n  const len = bytes.byteLength;\n  for (let i = 0; i < len; i++) {\n    binary += String.fromCharCode(bytes[i]);\n  }\n  return window.btoa(binary);\n}\n\n// From https://stackoverflow.com/a/21797381\nexport function base64ToBuffer(base64: string): ArrayBuffer {\n  const binaryString = window.atob(base64);\n  const bytes = new Uint8Array(binaryString.length);\n  for (let i = 0; i < binaryString.length; i++) {\n    bytes[i] = binaryString.charCodeAt(i);\n  }\n  return bytes.buffer;\n}\n", "// Original code from Synclink and Comlink. Released under Apache 2.0.\n\nimport { Endpoint, SZ_BUF_FITS_IDX, SZ_BUF_SIZE_IDX, generateUUID } from './task-common';\n\nimport { sleep } from '../utils';\nimport { SyncRequestData } from './message';\nimport { encode } from '@msgpack/msgpack';\n\nimport { IN_NODE } from '../compat';\nimport type { Worker as NodeWorker } from 'worker_threads';\n\nconst encoder = new TextEncoder();\n\n/**\n * Respond to a blocking request. Most of the work has already been done in\n * asynclink, we are just responsible here for getting the return value back to\n * the requester through this slightly convoluted Atomics protocol.\n * @param {Endpoint} endpoint  A message port to receive messages from. Other\n *        thread is blocked, so we can't send messages back.\n * @param {SyncRequestData} data The message that was recieved. We will use it\n *        to read out the buffers to write the answer into. NOTE: requester\n *        owns buffers.\n * @param {any} response The value we want to send back to the requester. We\n *        have to encode it into data_buffer.\n */\nexport async function syncResponse(endpoint: Endpoint, data: SyncRequestData, response: any) {\n  try {\n    // eslint-disable-next-line prefer-const\n    let { taskId, sizeBuffer, dataBuffer, signalBuffer } = data;\n    // console.warn(msg);\n\n    const bytes = encode(response);\n    const fits = bytes.length <= dataBuffer.length;\n\n    Atomics.store(sizeBuffer, SZ_BUF_SIZE_IDX, bytes.length);\n    Atomics.store(sizeBuffer, SZ_BUF_FITS_IDX, +fits);\n    if (!fits) {\n      // console.log(\"      need larger buffer\", taskId)\n      // Request larger buffer\n      const [uuid, dataPromise] = requestResponseMessage(endpoint);\n\n      // Write UUID into dataBuffer so syncRequest knows where to respond to.\n      dataBuffer.set(encoder.encode(uuid));\n      await signalRequester(signalBuffer, taskId!);\n\n      // Wait for response with new bigger dataBuffer\n      dataBuffer = (await dataPromise).dataBuffer as Uint8Array;\n    }\n\n    // Encode result into dataBuffer\n    dataBuffer.set(bytes);\n    Atomics.store(sizeBuffer, SZ_BUF_FITS_IDX, +true);\n\n    // console.log(\"       signaling completion\", taskId)\n    await signalRequester(signalBuffer, taskId as number);\n  } catch (e) {\n    console.warn(e);\n  }\n}\n\nfunction requestResponseMessage(ep: Endpoint): [string, Promise<any>] {\n  const id = generateUUID();\n  return [\n    id,\n    new Promise((resolve) => {\n      if (IN_NODE) {\n        (ep as unknown as NodeWorker).once('message', (message: any) => {\n          if (!message.id || message.id !== id) {\n            return;\n          }\n          resolve(message);\n        });\n      } else {\n        ep.addEventListener('message', function l(ev: MessageEvent) {\n          if (!ev.data || !ev.data.id || ev.data.id !== id) {\n            return;\n          }\n          ep.removeEventListener('message', l as EventListenerOrEventListenerObject);\n          resolve(ev.data);\n        } as EventListenerOrEventListenerObject);\n      }\n      if (ep.start) {\n        ep.start();\n      }\n    }),\n  ];\n}\n\nasync function signalRequester(signalBuffer: Int32Array, taskId: number) {\n  const index = (taskId >> 1) % 32;\n  let sleepTime = 1;\n  while (Atomics.compareExchange(signalBuffer, index + 1, 0, taskId) !== 0) {\n    // No Atomics.asyncWait except on Chrome =(\n    await sleep(sleepTime);\n    if (sleepTime < 32) {\n      // exponential backoff\n      sleepTime *= 2;\n    }\n  }\n  Atomics.or(signalBuffer, 0, 1 << index);\n  Atomics.notify(signalBuffer, 0);\n}\n", "// From https://stackoverflow.com/questions/47157428/how-to-implement-a-pseudo-blocking-async-queue-in-js-ts\n/**\n * @module Queue\n */\n\n/**\n * Asynchronous queue mechanism to be used by the communication channels.\n * @typeParam T The type of item to be stored in the queue.\n */\nexport class AsyncQueue<T> {\n  #promises: Promise<T>[];\n  #resolvers: ((t: T) => void)[];\n\n  constructor() {\n    this.#resolvers = [];\n    this.#promises = [];\n  }\n\n  reset() {\n    this.#resolvers = [];\n    this.#promises = [];\n  }\n\n  put(t: T) {\n    if (!this.#resolvers.length) {\n      this.#add();\n    }\n    const resolve = this.#resolvers.shift()!;\n    resolve(t);\n  }\n\n  async get() {\n    if (!this.#promises.length) {\n      this.#add();\n    }\n    const promise = this.#promises.shift()!;\n    return promise;\n  }\n\n  isEmpty() {\n    return !this.#promises.length;\n  }\n\n  isBlocked() {\n    return !!this.#resolvers.length;\n  }\n\n  get length() {\n    return this.#promises.length - this.#resolvers.length;\n  }\n\n  #add() {\n    this.#promises.push(\n      new Promise((resolve) => {\n        this.#resolvers.push(resolve);\n      })\n    );\n  }\n}\n", "/**\n * WebR communication channel messaging and request types.\n * @module Message\n */\nimport { PromiseHandles } from '../utils';\nimport { generateUUID, transfer, UUID } from './task-common';\n\n/** A webR communication channel message. */\nexport interface Message {\n  type: string;\n  data?: any;\n}\n\n/** A webR communication channel request. */\nexport interface Request {\n  type: 'request';\n  data: {\n    uuid: UUID;\n    msg: Message;\n  };\n}\n\n/** A webR communication channel event message. */\nexport interface EventMessage {\n  type: 'event';\n  data: {\n    msg: Message;\n  };\n}\n\n/** A webR communication channel response. */\nexport interface Response {\n  type: 'response';\n  data: {\n    uuid: UUID;\n    resp: Message;\n  };\n}\n\n/** @internal */\nexport function newRequest(msg: Message, transferables?: [Transferable]): Request {\n  return newRequestResponseMessage(\n    {\n      type: 'request',\n      data: {\n        uuid: generateUUID(),\n        msg: msg,\n      },\n    },\n    transferables\n  );\n}\n\n/** @internal */\nexport function newResponse(uuid: UUID, resp: Message, transferables?: [Transferable]): Response {\n  return newRequestResponseMessage(\n    {\n      type: 'response',\n      data: {\n        uuid,\n        resp,\n      },\n    },\n    transferables\n  );\n}\n\n/** @internal */\nfunction newRequestResponseMessage<T>(msg: T, transferables?: [Transferable]): T {\n  // Signal to Synclink that the data contains objects we wish to\n  // transfer, as in `postMessage()`\n  if (transferables) {\n    transfer(msg, transferables);\n  }\n  return msg;\n}\n\n/** A webR communication channel `eval-response` message.\n * @internal\n */\nexport interface EvalResponse {\n  type: 'eval-response';\n  data: {\n    result?: unknown;\n    error?: string;\n  };\n}\n\n/** A webR communication channel `proxyWebSocket` message.\n * @internal\n */\nexport interface ProxyWebSocketMessage {\n  type: 'proxyWebSocket';\n  data: {\n    uuid: string;\n    url: string;\n    protocol?: string;\n  };\n}\n\n/** A webR communication channel `sendWebSocket` message.\n * @internal\n */\nexport interface SendWebSocketMessage {\n  type: 'sendWebSocket';\n  data: {\n    uuid: string;\n    data: string | ArrayBufferLike | Blob | ArrayBufferView;\n  };\n}\n\n/** A webR communication channel `closeWebSocket` message.\n * @internal\n */\nexport interface CloseWebSocketMessage {\n  type: 'closeWebSocket';\n  data: {\n    uuid: string;\n    code?: number;\n    reason?: string;\n  };\n}\n\n/** A webR communication channel `websocket-message` message.\n * @internal\n */\nexport interface WebSocketMessage {\n  type: 'websocket-message';\n  data: {\n    uuid: string;\n    data: string | ArrayBufferLike | Blob | ArrayBufferView;\n  };\n}\n\n/** A webR communication channel `websocket-open` message.\n * @internal\n */\nexport interface WebSocketOpenMessage {\n  type: 'websocket-open';\n  data: {\n    uuid: string;\n  };\n}\n\n/** A webR communication channel `websocket-close` message.\n * @internal\n */\nexport interface WebSocketCloseMessage {\n  type: 'websocket-close';\n  data: {\n    uuid: string;\n    code?: number;\n    reason?: string;\n  };\n}\n\n/** A webR communication channel `proxyWorker` message.\n * @internal\n */\nexport interface ProxyWorkerMessage {\n  type: 'proxyWorker';\n  data: {\n    uuid: string;\n    url: string;\n    options?: WorkerOptions;\n  };\n}\n\n/** A webR communication channel `postMessageWorker` message.\n * @internal\n */\nexport interface PostMessageWorkerMessage {\n  type: 'postMessageWorker';\n  data: {\n    uuid: string;\n    data: unknown;\n    async: boolean;\n    transfer?: Transferable[];\n    handles?: PromiseHandles<unknown>;\n  };\n}\n\n/** A webR communication channel `terminateWorker` message.\n * @internal\n */\nexport interface TerminateWorkerMessage {\n  type: 'terminateWorker';\n  data: {\n    uuid: string;\n  };\n}\n\n/** A webR communication channel `worker-message` message.\n * @internal\n */\nexport interface WorkerMessage {\n  type: 'worker-message';\n  data: {\n    uuid: string;\n    data: any;\n  };\n}\n\n/** A webR communication channel `worker-messageerror` message.\n * @internal\n */\nexport interface WorkerMessageErrorMessage {\n  type: 'worker-messageerror';\n  data: {\n    uuid: string;\n    data: any;\n  };\n}\n\n/** A webR communication channel `worker-error` message.\n * @internal\n */\nexport interface WorkerErrorMessage {\n  type: 'worker-error';\n  data: {\n    uuid: string;\n  };\n}\n\n/** A webR communication channel sync-request.\n * @internal\n */\nexport interface SyncRequest {\n  type: 'sync-request';\n  data: {\n    msg: Message;\n    reqData: SyncRequestData;\n  };\n}\n\n/** Transfer data required when using sync-request with SharedArrayBuffer.\n * @internal */\nexport interface SyncRequestData {\n  taskId?: number;\n  sizeBuffer: Int32Array;\n  signalBuffer: Int32Array;\n  dataBuffer: Uint8Array;\n}\n\n/** @internal */\nexport function newSyncRequest(msg: Message, data: SyncRequestData): SyncRequest {\n  return {\n    type: 'sync-request',\n    data: { msg, reqData: data },\n  };\n}\n", "/**\n * Types containing references to R objects, raw data or errors over the webR\n * communication channel.\n * @module Payload\n */\nimport { WebRDataRaw, RPtr, RType } from './robj';\nimport { WebRWorkerError } from './error';\n\nexport type WebRPayloadRaw = {\n  obj: WebRDataRaw;\n  payloadType: 'raw';\n};\n\nexport type WebRPayloadPtr = {\n  obj: {\n    type?: RType;\n    ptr: RPtr;\n    methods?: string[];\n  };\n  payloadType: 'ptr';\n};\n\nexport type WebRPayloadErr = {\n  obj: {\n    message: string;\n    name: string;\n    errno?: number;\n    stack?: string;\n  };\n  payloadType: 'err';\n};\n\n// On the main side we shouldn't see any error payload as these are\n// rethrown as JS exceptions\nexport type WebRPayload = WebRPayloadRaw | WebRPayloadPtr;\nexport type WebRPayloadWorker = WebRPayloadRaw | WebRPayloadPtr | WebRPayloadErr;\n\n/* @internal */\nexport function webRPayloadAsError(payload: WebRPayloadErr): Error {\n  const e = new WebRWorkerError(payload.obj.message);\n  // Forward the error name to the main thread, if more specific than a general `Error`\n  if (payload.obj.name == 'ErrnoError') {\n    e.message = `ErrnoError: ${String(payload.obj.errno)}`;\n  } else if (payload.obj.name !== 'Error') {\n    e.name = payload.obj.name;\n  }\n  e.stack = payload.obj.stack;\n  return e;\n}\n\n/**\n * Test for an WebRPayload instance.\n * @param {any} value The object to test.\n * @returns {boolean} True if the object is an instance of an WebRPayload.\n */\nexport function isWebRPayload(value: any): value is WebRPayload {\n  return !!value && typeof value === 'object' && 'payloadType' in value && 'obj' in value;\n}\n\n/**\n * Test for an WebRPayloadPtr instance.\n * @param {any} value The object to test.\n * @returns {boolean} True if the object is an instance of an WebRPayloadPtr.\n */\nexport function isWebRPayloadPtr(value: any): value is WebRPayloadPtr {\n  return isWebRPayload(value) && value.payloadType === 'ptr';\n}\n\n/**\n * Test for an WebRPayloadRaw instance.\n * @param {any} value The object to test.\n * @returns {boolean} True if the object is an instance of an WebRPayloadRaw.\n */\nexport function isWebRPayloadRaw(value: any): value is WebRPayloadRaw {\n  return isWebRPayload(value) && value.payloadType === 'raw';\n}\n", "/**\n * Interfaces for the webR main and worker thread communication channels.\n * @module Channel\n */\n\nimport { promiseHandles, ResolveFn, RejectFn } from '../utils';\nimport { AsyncQueue } from './queue';\nimport { EventMessage, Message, newRequest, Response } from './message';\nimport { WebRPayload, WebRPayloadWorker, webRPayloadAsError } from '../payload';\nimport { WebRChannelError } from '../error';\n\n// The channel structure is asymmetric:\n//\n// - The main thread maintains the input and output queues. All\n//   messages sent from main are stored in the input queue. The input\n//   queue is pull-based, it's the worker that initiates a transfer\n//   via a sync-request.\n//\n//   The output queue is filled at the initiative of the worker. The\n//   main thread asynchronously reads from this queue, typically in an\n//   async infloop.\n//\n// - The worker synchronously reads from the input queue. Reading a\n//   message blocks until an input is available. Writing a message to\n//   the output queue is equivalent to calling `postMessage()` and\n//   returns immediately.\n//\n//   Note that the messages sent from main to worker need to be\n//   serialised. There is no structured cloning involved, and\n//   ArrayBuffers can't be transferred, only copied.\n\nexport abstract class ChannelMain {\n  inputQueue = new AsyncQueue<Message>();\n  outputQueue = new AsyncQueue<Message>();\n  systemQueue = new AsyncQueue<Message>();\n  eventQueue = new Array<EventMessage>;\n\n  #parked = new Map<string, { resolve: ResolveFn<any>; reject: RejectFn }>();\n  #closed = false;\n\n  abstract initialised: Promise<unknown>;\n  abstract close(): void;\n  abstract emit(msg: Message): void;\n  abstract interrupt(): void;\n\n  async read(): Promise<Message> {\n    return await this.outputQueue.get();\n  }\n\n  async flush(): Promise<Message[]> {\n    const msg: Message[] = [];\n    while (!this.outputQueue.isEmpty()) {\n      msg.push(await this.read());\n    }\n    return msg;\n  }\n\n  async readSystem(): Promise<Message> {\n    return await this.systemQueue.get();\n  }\n\n  write(msg: Message): void {\n    if (this.#closed) {\n      throw new WebRChannelError(\"The webR communication channel has been closed.\");\n    }\n    this.inputQueue.put(msg);\n  }\n\n  async request(msg: Message, transferables?: [Transferable]): Promise<WebRPayload> {\n    const req = newRequest(msg, transferables);\n\n    const { resolve, reject, promise } = promiseHandles<WebRPayload>();\n    this.#parked.set(req.data.uuid, { resolve, reject });\n\n    this.write(req);\n    return promise;\n  }\n\n  protected putClosedMessage(): void {\n    this.#closed = true;\n    this.outputQueue.put({ type: 'closed' });\n  }\n\n  protected resolveResponse(msg: Response) {\n    const uuid = msg.data.uuid;\n    const handles = this.#parked.get(uuid);\n\n    if (handles) {\n      const payload = msg.data.resp.data as WebRPayloadWorker;\n      this.#parked.delete(uuid);\n\n      if (payload.payloadType === 'err') {\n        handles.reject(webRPayloadAsError(payload));\n      } else {\n        handles.resolve(payload);\n      }\n    } else {\n      console.warn(\"Can't find request.\");\n    }\n  }\n}\n\nexport interface ChannelWorker {\n  WebSocketProxy: typeof WebSocket | undefined;\n  WorkerProxy: typeof Worker | undefined;\n  resolve(): void;\n  write(msg: Message, transfer?: [Transferable]): void;\n  writeSystem(msg: Message, transfer?: [Transferable]): void;\n  syncRequest(msg: Message, transfer?: [Transferable]): Message;\n  read(): Message;\n  handleEvents(): void;\n  setInterrupt(interrupt: () => void): void;\n  run(args: string[]): void;\n  inputOrDispatch: () => number;\n  setDispatchHandler: (dispatch: (msg: Message) => void) => void;\n  resolveRequest: (msg: Message) => void;\n}\n\n/**\n * Handler functions dealing with setup and communication over a Service Worker.\n */\nexport interface ServiceWorkerHandlers {\n  handleActivate: (this: ServiceWorkerGlobalScope, ev: ExtendableEvent) => any;\n  handleFetch: (this: ServiceWorkerGlobalScope, ev: FetchEvent) => any;\n  handleInstall: (this: ServiceWorkerGlobalScope, ev: ExtendableEvent) => any;\n  handleMessage: (this: ServiceWorkerGlobalScope, ev: ExtendableMessageEvent) => any;\n}\n", "// Original code from Synclink and Comlink. Released under Apache 2.0.\n\nimport {\n  Endpoint,\n  SZ_BUF_DOESNT_FIT,\n  SZ_BUF_FITS_IDX,\n  SZ_BUF_SIZE_IDX,\n  UUID_LENGTH,\n} from './task-common';\n\nimport { newSyncRequest, Message } from './message';\nimport { decode } from '@msgpack/msgpack';\n\nconst decoder = new TextDecoder('utf-8');\n\nexport class SyncTask {\n  endpoint: Endpoint;\n  msg: Message;\n  transfers: Transferable[];\n\n  #scheduled = false;\n  #resolved: boolean;\n  #result?: any;\n  #exception?: any;\n\n  // sync only\n  taskId?: number;\n  #syncGen?: Generator<void, unknown, void>;\n  sizeBuffer?: Int32Array;\n  signalBuffer?: Int32Array;\n  syncifier = new _Syncifier();\n\n  constructor(endpoint: Endpoint, msg: Message, transfers: Transferable[] = []) {\n    this.endpoint = endpoint;\n    this.msg = msg;\n    this.transfers = transfers;\n    this.#resolved = false;\n  }\n\n  scheduleSync() {\n    if (this.#scheduled) {\n      return;\n    }\n    this.#scheduled = true;\n\n    this.syncifier.scheduleTask(this);\n    this.#syncGen = this.doSync();\n    this.#syncGen.next();\n    return this;\n  }\n\n  poll() {\n    if (!this.#scheduled) {\n      throw new Error('Task not synchronously scheduled');\n    }\n\n    const { done, value } = this.#syncGen!.next();\n    if (!done) {\n      return false;\n    }\n\n    this.#resolved = true;\n    this.#result = value;\n\n    return true;\n  }\n\n  *doSync() {\n    // just use syncRequest.\n    const { endpoint, msg, transfers } = this;\n    const sizeBuffer = new Int32Array(new SharedArrayBuffer(8));\n    const signalBuffer = this.signalBuffer!;\n    const taskId = this.taskId;\n\n    // Ensure status is cleared. We will notify\n    let dataBuffer = acquireDataBuffer(UUID_LENGTH);\n    // console.log(\"===requesting\", taskId);\n\n    const syncMsg = newSyncRequest(msg, {\n      sizeBuffer,\n      dataBuffer,\n      signalBuffer,\n      taskId,\n    });\n\n    endpoint.postMessage(syncMsg, transfers);\n    yield;\n\n    if (Atomics.load(sizeBuffer, SZ_BUF_FITS_IDX) === SZ_BUF_DOESNT_FIT) {\n      // There wasn't enough space, make a bigger dataBuffer.\n      // First read uuid for response out of current dataBuffer\n      const id = decoder.decode(dataBuffer.slice(0, UUID_LENGTH));\n      releaseDataBuffer(dataBuffer);\n      const size = Atomics.load(sizeBuffer, SZ_BUF_SIZE_IDX);\n      dataBuffer = acquireDataBuffer(size);\n      // console.log(\"===bigger data buffer\", taskId);\n      endpoint.postMessage({ id, dataBuffer });\n      yield;\n    }\n\n    const size = Atomics.load(sizeBuffer, SZ_BUF_SIZE_IDX);\n    // console.log(\"===completing\", taskId);\n    return decode(dataBuffer.slice(0, size));\n  }\n\n  get result() {\n    if (this.#exception) {\n      throw this.#exception;\n    }\n    // console.log(this.#resolved);\n    if (this.#resolved) {\n      return this.#result as unknown;\n    }\n    throw new Error('Not ready.');\n  }\n\n  syncify(): any {\n    this.scheduleSync();\n    this.syncifier.syncifyTask(this);\n    return this.result;\n  }\n}\n\nclass _Syncifier {\n  nextTaskId: Int32Array;\n  signalBuffer: Int32Array;\n  tasks: Map<number, SyncTask>;\n\n  constructor() {\n    this.nextTaskId = new Int32Array([1]);\n    this.signalBuffer = new Int32Array(new SharedArrayBuffer(32 * 4 + 4));\n    this.tasks = new Map();\n  }\n\n  scheduleTask(task: SyncTask) {\n    task.taskId = this.nextTaskId[0];\n    this.nextTaskId[0] += 2;\n    task.signalBuffer = this.signalBuffer;\n    this.tasks.set(task.taskId, task);\n  }\n\n  waitOnSignalBuffer() {\n    const timeout = 50;\n    for (; ;) {\n      const status = Atomics.wait(this.signalBuffer, 0, 0, timeout);\n      switch (status) {\n        case 'ok':\n        case 'not-equal':\n          return;\n        case 'timed-out':\n          if (eventBuffer[0] !== 0) {\n            handleEvents();\n          }\n          break;\n        default:\n          throw new Error('Unreachable');\n      }\n    }\n  }\n\n  *tasksIdsToWakeup() {\n    const flag = Atomics.load(this.signalBuffer, 0);\n    for (let i = 0; i < 32; i++) {\n      const bit = 1 << i;\n      if (flag & bit) {\n        Atomics.and(this.signalBuffer, 0, ~bit);\n        const wokenTask = Atomics.exchange(this.signalBuffer, i + 1, 0);\n        yield wokenTask;\n      }\n    }\n  }\n\n  pollTasks(task?: SyncTask) {\n    let result = false;\n    for (const wokenTaskId of this.tasksIdsToWakeup()) {\n      // console.log(\"poll task\", wokenTaskId, \"looking for\",task);\n      const wokenTask = this.tasks.get(wokenTaskId);\n      if (!wokenTask) {\n        throw new Error(`Assertion error: unknown taskId ${wokenTaskId}.`);\n      }\n      if (wokenTask.poll()) {\n        // console.log(\"completed task \", wokenTaskId, wokenTask, wokenTask._result);\n        this.tasks.delete(wokenTaskId);\n        if (wokenTask === task) {\n          result = true;\n        }\n      }\n    }\n    return result;\n  }\n\n  syncifyTask(task: SyncTask) {\n    for (; ;) {\n      this.waitOnSignalBuffer();\n      // console.log(\"syncifyTask:: woke\");\n      if (this.pollTasks(task)) {\n        return;\n      }\n    }\n  }\n}\n\nconst dataBuffers: Uint8Array[][] = [];\n\nfunction acquireDataBuffer(size: number): Uint8Array {\n  const powerof2 = Math.ceil(Math.log2(size));\n  if (!dataBuffers[powerof2]) {\n    dataBuffers[powerof2] = [];\n  }\n  const result = dataBuffers[powerof2].pop();\n  if (result) {\n    result.fill(0);\n    return result;\n  }\n  return new Uint8Array(new SharedArrayBuffer(2 ** powerof2));\n}\n\nfunction releaseDataBuffer(buffer: Uint8Array) {\n  const powerof2 = Math.ceil(Math.log2(buffer.byteLength));\n  dataBuffers[powerof2].push(buffer);\n}\n\nlet eventBuffer: Int32Array = new Int32Array(new ArrayBuffer(4));\n\nlet handleEvents = (): void => {\n  eventBuffer[0] = 0;\n  throw new Error('No event handler.');\n};\n\n/**\n * Sets the events handler. This is called when the computation is\n * interrupted by an event. Should zero the event buffer.\n * @internal\n */\nexport function setEventsHandler(handler: () => void) {\n  handleEvents = handler;\n}\n\n/**\n * Sets the events buffer. Should be a shared array buffer. When element 0\n * is set non-zero it signals an event has been emitted.\n * @internal\n */\nexport function setEventBuffer(buffer: ArrayBufferLike) {\n  eventBuffer = new Int32Array(buffer);\n}\n", "import { ChannelMain } from \"./channel\";\nimport { SharedBufferChannelWorker } from \"./channel-shared\";\nimport { generateUUID } from \"./task-common\";\nimport { IN_NODE } from '../compat';\n\nexport interface WebSocketProxy extends WebSocket {\n  uuid: string;\n  _accept(): void;\n  _recieve(data: string | ArrayBufferLike | Blob | ArrayBufferView): void;\n  _close(code?: number, reason?: string): void;\n  _error(): void;\n}\n\nexport class WebSocketMap {\n  WebSocket: typeof WebSocket;\n  #map = new Map<string, WebSocket>();\n\n  constructor(readonly chan: ChannelMain) {\n    if (IN_NODE) {\n      // Use the built-in WebSocket if available (Node.js >= 21), otherwise\n      // fall back to the 'ws' npm package which must be installed separately.\n      this.WebSocket = ('WebSocket' in globalThis)\n        ? globalThis.WebSocket\n        : require('ws') as typeof WebSocket;\n    } else {\n      this.WebSocket = WebSocket;\n    }\n  }\n\n  new(uuid: string, url: string | URL, protocols?: string | string[]) {\n    const ws = new this.WebSocket(url, protocols || []);\n    ws.binaryType = 'arraybuffer';\n    \n    ws.addEventListener('open', () => {\n      this.chan.emit({ type: 'websocket-open', data: { uuid } });\n    });\n\n    ws.addEventListener('message', (ev: MessageEvent) => {\n      const data = new Uint8Array(ev.data as ArrayBufferLike);\n      this.chan.emit({ type: 'websocket-message', data: { uuid, data } });\n    });\n\n    ws.addEventListener('close', (ev: CloseEvent) => {\n      this.chan.emit({ type: 'websocket-close', data: { uuid, code: ev.code, reason: ev.reason } });\n    });\n\n    ws.addEventListener('error', () => {\n      this.chan.emit({ type: 'websocket-error', data: { uuid } });\n    });\n\n    this.#map.set(uuid, ws);\n  }\n\n  send(uuid: string, data: string | ArrayBufferLike | Blob | ArrayBufferView): void {\n    const ws = this.#map.get(uuid);\n    ws?.send(data);\n  }\n\n  close(uuid: string, code?: number, reason?: string): void {\n    const ws = this.#map.get(uuid);\n    ws?.close(code, reason);\n    this.#map.delete(uuid);\n  }\n}\n\nexport class WebSocketProxyFactory {\n  static proxy(chan: SharedBufferChannelWorker): typeof WebSocket {\n    return class WebSocket extends EventTarget implements WebSocketProxy {\n      static readonly CONNECTING = 0;\n      static readonly OPEN = 1;\n      static readonly CLOSING = 2;\n      static readonly CLOSED = 3;\n\n      readonly CONNECTING = WebSocket.CONNECTING;\n      readonly OPEN = WebSocket.OPEN;\n      readonly CLOSING = WebSocket.CLOSING;\n      readonly CLOSED = WebSocket.CLOSED;\n\n      uuid: string;\n      url: string;\n      protocol: string;\n      readyState: number = WebSocket.CONNECTING;\n      bufferedAmount = 0;\n      binaryType: BinaryType;\n      extensions = \"\";\n      onopen: ((ev: Event) => any) | null;\n      onmessage: ((ev: MessageEvent) => any) | null;\n      onclose: ((ev: CloseEvent) => any) | null;\n      onerror: ((ev: Event) => any) | null;\n\n      constructor(url: string | URL, protocols?: string | string[]) {\n        super();\n        this.url = String(url);\n        this.protocol = Array.isArray(protocols) ? protocols[0] : protocols || '';\n        this.binaryType = 'arraybuffer';\n\n        this.onopen = null;\n        this.onmessage = null;\n        this.onclose = null;\n        this.onerror = null;\n\n        this.uuid = generateUUID();\n\n        chan.writeSystem({\n          type: 'proxyWebSocket',\n          data: { uuid: this.uuid, url: this.url, protocol: this.protocol }\n        });\n        chan.ws.set(this.uuid, this);\n      }\n\n      send(data: string | ArrayBufferLike | Blob | ArrayBufferView): void {\n        chan.writeSystem({ type: 'sendWebSocket', data: { uuid: this.uuid, data } });\n      }\n\n      close(code?: number, reason?: string): void {\n        chan.writeSystem({ type: 'closeWebSocket', data: { uuid: this.uuid, code, reason } });\n      }\n\n      _accept() {\n        if (this.readyState !== 0) {\n          return;\n        }\n\n        this.readyState = 1;\n        const ev = new Event('open');\n        this.dispatchEvent(ev);\n        this.onopen?.(ev);\n      }\n\n      _recieve(data: string | ArrayBufferLike | Blob | ArrayBufferView): void {\n        const ev = new MessageEvent('message', { data });\n        this.dispatchEvent(ev);\n        this.onmessage?.(ev);\n      }\n\n      _close(code?: number, reason?: string): void {\n        const ev = new CloseEvent('close', { code, reason });\n        this.dispatchEvent(ev);\n        this.onclose?.(ev);\n        chan.ws.delete(this.uuid);\n      }\n\n      _error(): void {\n        const ev = new Event(\"error\");\n        this.dispatchEvent(ev);\n        this.onerror?.(ev);\n      }\n\n      // Node.js EventEmitter-style .on() for Emscripten SOCKFS compatibility.\n      // In Node.js, SOCKFS registers socket events via .on() rather than\n      // .onopen/.onmessage etc., so we must support both APIs.\n      on(event: string, handler: (...args: unknown[]) => void): this {\n        if (event === 'message') {\n          // SOCKFS expects handler(data, isBinary) like the 'ws' npm package\n          this.addEventListener('message', (ev: Event) => {\n            const data = (ev as MessageEvent<unknown>).data;\n            const isBinary = !(typeof data === 'string');\n            handler(data, isBinary);\n          });\n        } else {\n          this.addEventListener(event, () => handler());\n        }\n        return this;\n      }\n    };\n  }\n}\n\n// TODO: Remove this once we have nodejs/node#53355\nif (IN_NODE) {\n  globalThis.CloseEvent = class CloseEvent extends Event {\n    wasClean: boolean;\n    code: number;\n    reason: string;\n    constructor(type: string, eventInitDict: CloseEventInit = {}) {\n      super(type, eventInitDict as EventInit);\n\n      this.wasClean = eventInitDict.wasClean || false;\n      this.code = eventInitDict.code || 0;\n      this.reason = eventInitDict.reason || '';\n    }\n  };\n}\n", "import { IN_NODE } from \"../compat\";\nimport { newCrossOriginWorker } from \"../utils\";\nimport { ChannelMain } from \"./channel\";\nimport { SharedBufferChannelWorker } from \"./channel-shared\";\nimport { PostMessageWorkerMessage } from \"./message\";\nimport { generateUUID } from \"./task-common\";\nimport type { Worker as NodeWorker } from 'worker_threads';\n\nexport interface WorkerProxy extends Worker {\n  uuid: string;\n  _message(data: any): void;\n  _messageerror(data: any): void;\n  _error(): void;\n}\n\n// Main --------------------------------------------------------------\n\nexport class WorkerMap {\n  #map = new Map<string, Worker>();\n\n  constructor(readonly chan: ChannelMain) { }\n\n  new(uuid: string, url: string, options?: WorkerOptions) {\n    if (IN_NODE) {\n      const worker = new Worker(url, options);\n      const nodeWorker = worker as unknown as NodeWorker;\n      nodeWorker.on('message', (ev: MessageEvent<unknown>) => {\n        this.chan.emit({ type: 'worker-message', data: { uuid, data: ev } });\n      });\n\n      nodeWorker.on('messageerror', (ev: MessageEvent<unknown>) => {\n        this.chan.emit({ type: 'worker-messageerror', data: { uuid, data: ev } });\n      });\n\n      nodeWorker.on('error', () => {\n        this.chan.emit({ type: 'worker-error', data: { uuid } });\n      });\n\n      this.#map.set(uuid, worker);\n    } else {\n      newCrossOriginWorker(\n        url,\n        (worker: Worker) => {\n          worker.addEventListener('message', (ev: MessageEvent<unknown>) => {\n            this.chan.emit({ type: 'worker-message', data: { uuid, data: ev.data } });\n          });\n\n          worker.addEventListener('messageerror', (ev: MessageEvent<unknown>) => {\n            this.chan.emit({ type: 'worker-messageerror', data: { uuid, data: ev.data } });\n          });\n\n          worker.addEventListener('error', () => {\n            this.chan.emit({ type: 'worker-error', data: { uuid } });\n          });\n\n          this.#map.set(uuid, worker);\n        },\n        (error: Error) => { throw error; },\n        options,\n        false\n      );\n    }\n  }\n\n  postMessage(message: PostMessageWorkerMessage): void {\n    const { uuid, async, handles, data, transfer } = message.data;\n    const worker = this.#map.get(uuid);\n    if (!worker) {\n      throw new Error(`Worker with uuid ${uuid} not found`);\n    }\n\n    if (!async && handles) {\n      const handler = (ev: MessageEvent) => {\n        const _uuid = ev.data.uuid as string;\n        const result = ev.data.result as unknown;\n        const error = ev.data.error as string | undefined;\n        if (_uuid === uuid) {\n          if (error) {\n            handles.reject(new Error(error));\n          } else {\n            handles.resolve(result);\n          }\n          worker.removeEventListener('message', handler);\n        }\n      };\n      worker.addEventListener('message', handler);\n    }\n\n    worker.postMessage({ uuid, data }, { transfer: transfer });\n  }\n\n  terminate(uuid: string): void {\n    const worker = this.#map.get(uuid);\n    worker?.terminate();\n    this.#map.delete(uuid);\n  }\n}\n\n\n// Worker --------------------------------------------------------------\n\ntype WorkerProxyOptions = StructuredSerializeOptions & {\n  async?: boolean;\n};\n\nexport class WorkerProxyFactory {\n  static proxy(chan: SharedBufferChannelWorker): typeof Worker {\n    return class Worker extends EventTarget implements WorkerProxy {\n      uuid: string;\n      url: string;\n      options: WorkerOptions;\n      onmessage: ((ev: MessageEvent) => any) | null;\n      onmessageerror: ((ev: MessageEvent) => any) | null;\n      onerror: ((ev: Event) => any) | null;\n\n      constructor(url: string | URL, options: WorkerOptions = {}) {\n        super();\n        this.url = String(url);\n        this.options = options;\n        this.onmessage = null;\n        this.onmessageerror = null;\n        this.onerror = null;\n\n        this.uuid = generateUUID();\n\n        chan.writeSystem({\n          type: 'proxyWorker',\n          data: { uuid: this.uuid, url: this.url, options: this.options }\n        });\n        chan.workers.set(this.uuid, this);\n      }\n\n      postMessage(data: unknown, options: Transferable[] | WorkerProxyOptions = { async: true }): any {\n        const async = Array.isArray(options) ? true : options.async ?? true;\n        const transfer = Array.isArray(options) ? options : options.transfer ?? [];\n        const response = chan.syncRequest({\n          type: 'post-message-worker', data: {\n            uuid: this.uuid,\n            data,\n            async,\n            transfer\n          }\n        });\n        return response.data;\n      }\n\n      terminate(): void {\n        chan.writeSystem({ type: 'terminateWorker', data: { uuid: this.uuid } });\n      }\n\n      _message(data: unknown): void {\n        const ev = new MessageEvent('message', { data });\n        this.dispatchEvent(ev);\n        this.onmessage?.(ev);\n      }\n\n      _messageerror(data: unknown): void {\n        const ev = new MessageEvent('message', { data });\n        this.dispatchEvent(ev);\n        this.onmessageerror?.(ev);\n      }\n\n      _error(): void {\n        const ev = new Event(\"error\");\n        this.dispatchEvent(ev);\n        this.onerror?.(ev);\n      }\n    };\n  }\n}\n", "import { promiseHandles, newCrossOriginWorker, isCrossOrigin } from '../utils';\nimport { EventMessage, Message, PostMessageWorkerMessage, Response, SyncRequest, WebSocketCloseMessage, WebSocketMessage, WebSocketOpenMessage, WorkerErrorMessage, WorkerMessage, WorkerMessageErrorMessage } from './message';\nimport { Endpoint } from './task-common';\nimport { syncResponse } from './task-main';\nimport { ChannelMain, ChannelWorker } from './channel';\nimport { ChannelType } from './channel-common';\nimport { WebROptions } from '../webr-main';\nimport { WebRChannelError, WebRWorkerError } from '../error';\n\nimport { IN_NODE } from '../compat';\nimport type { Worker as NodeWorker } from 'worker_threads';\nif (IN_NODE) {\n  (globalThis as any).Worker = require('worker_threads').Worker as NodeWorker;\n}\n\n// Main ----------------------------------------------------------------\n\nexport class SharedBufferChannelMain extends ChannelMain {\n  #eventBuffer?: Int32Array;\n\n  initialised: Promise<unknown>;\n  resolve: (_?: unknown) => void;\n  reject: (message: string | Error) => void;\n  close = () => { return; };\n\n  constructor(config: Required<WebROptions>) {\n    super();\n    ({ resolve: this.resolve, reject: this.reject, promise: this.initialised } = promiseHandles());\n\n    const initWorker = (worker: Worker) => {\n      this.#handleEventsFromWorker(worker);\n      this.close = () => {\n        worker.terminate();\n        this.putClosedMessage();\n      };\n      const msg = {\n        type: 'init',\n        data: { config, channelType: ChannelType.SharedArrayBuffer },\n      } as Message;\n      worker.postMessage(msg);\n    };\n\n    if (isCrossOrigin(config.baseUrl)) {\n      newCrossOriginWorker(\n        `${config.baseUrl}webr-worker.js`,\n        (worker: Worker) => initWorker(worker),\n        (error: Error) => {\n          this.reject(new WebRWorkerError(`Worker loading error: ${error.message}`));\n        }\n      );\n    } else {\n      const worker = new Worker(`${config.baseUrl}webr-worker.js`);\n      initWorker(worker);\n    }\n  }\n\n  emit(msg: Message): void {\n    if (!this.#eventBuffer) {\n      throw new WebRChannelError('Failed attempt to interrupt before initialising interruptBuffer');\n    }\n    this.eventQueue.push({ type: 'event', data: { msg } });\n    this.#eventBuffer[0] = 1;\n  }\n\n  interrupt() {\n    this.inputQueue.reset();\n    this.emit({ type: 'interrupt' });\n  }\n\n  #handleEventsFromWorker(worker: Worker) {\n    if (IN_NODE) {\n      (worker as unknown as NodeWorker).on('message', (message: Message) => {\n        void this.#onMessageFromWorker(worker, message);\n      });\n      (worker as unknown as NodeWorker).on('error', (ev: Event) => {\n        const message = ev instanceof Error ? ev.message : String(ev);\n        console.error(message);\n        this.reject(new WebRWorkerError(\n          `An error occurred initialising the webR SharedBufferChannel worker: ${message}.`\n        ));\n      });\n    } else {\n      worker.onmessage = (ev: MessageEvent) =>\n        this.#onMessageFromWorker(worker, ev.data as Message);\n      worker.onerror = (ev) => {\n        const message = ev instanceof Error ? ev.message : String(ev);\n        console.error(message);\n        this.reject(new WebRWorkerError(\n          `An error occurred initialising the webR SharedBufferChannel worker: ${message}.`\n        ));\n      };\n    }\n  }\n\n  #onMessageFromWorker = async (worker: Worker, message: Message) => {\n    if (!message || !message.type) {\n      return;\n    }\n\n    switch (message.type) {\n      case 'resolve':\n        this.#eventBuffer = new Int32Array(message.data as SharedArrayBuffer);\n        this.resolve();\n        return;\n\n      case 'response':\n        this.resolveResponse(message as Response);\n        return;\n\n      case 'system':\n        this.systemQueue.put(message.data as Message);\n        return;\n\n      default:\n        this.outputQueue.put(message);\n        return;\n\n      case 'sync-request': {\n        const msg = message as SyncRequest;\n        const payload = msg.data.msg;\n        const reqData = msg.data.reqData;\n\n        switch (payload.type) {\n          case 'read': {\n            const response = await this.inputQueue.get();\n            await syncResponse(worker, reqData, response);\n            break;\n          }\n          case 'event': {\n            const response = this.eventQueue.shift();\n            await syncResponse(worker, reqData, response);\n            break;\n          }\n          case 'eval-await': {\n            const src = payload.data as string;\n            const data = {} as { result?: any; error?: string };\n            try {\n              data.result = await (0, eval)(src) as unknown;\n              if (typeof data.result === 'function') {\n                // Don't try to transfer a function back to the worker thread\n                data.result = String(data.result);\n              }\n            } catch (_error) {\n              const error = _error as Error;\n              data.error = error.message;\n            }\n            await syncResponse(worker, reqData, { type: 'eval-response', data });\n            break;\n          }\n          case 'post-message-worker': {\n            const message = payload.data as PostMessageWorkerMessage['data'];\n            message.handles = promiseHandles();\n            this.systemQueue.put({ type: 'postMessageWorker', data: message });\n\n            if (message.async) {\n              await syncResponse(worker, reqData, { type: 'post-message-response' });\n            } else {\n              message.handles.promise.then(\n                (value) => {\n                  void syncResponse(worker, reqData, { type: 'post-message-response', data: { result: value } });\n                },\n                (error) => {\n                  void syncResponse(worker, reqData, { type: 'post-message-response', data: { error: String(error) } });\n                }\n              );\n            }\n            break;\n          }\n          default:\n            throw new WebRChannelError(`Unsupported request type '${payload.type}'.`);\n        }\n        return;\n      }\n      case 'request':\n        throw new WebRChannelError(\n          \"Can't send messages of type 'request' from a worker. Please Use 'sync-request' instead.\"\n        );\n    }\n  };\n}\n\n// Worker --------------------------------------------------------------\n\nimport { setEventBuffer, setEventsHandler, SyncTask } from './task-worker';\nimport { Module } from '../emscripten';\nimport { WebSocketProxy, WebSocketProxyFactory } from './proxy-websocket';\nimport { WorkerProxy, WorkerProxyFactory } from './proxy-worker';\n\nexport class SharedBufferChannelWorker implements ChannelWorker {\n  WebSocketProxy: typeof WebSocket;\n  WorkerProxy: typeof Worker;\n  ws: Map<string, WebSocketProxy>;\n  workers: Map<string, WorkerProxy>;\n  #ep: Endpoint;\n  #dispatch: (msg: Message) => void = () => 0;\n  #eventBuffer = new Int32Array(new SharedArrayBuffer(4));\n  #interrupt = () => { return; };\n  resolveRequest: (msg: Message) => void = () => { return; };\n\n  constructor() {\n    this.#ep = (IN_NODE ? require('worker_threads').parentPort : globalThis) as Endpoint;\n    setEventBuffer(this.#eventBuffer.buffer);\n    setEventsHandler(() => this.handleEvents());\n\n    // Event functionality to be handled via proxy to main thread\n    this.WebSocketProxy = WebSocketProxyFactory.proxy(this);\n    this.ws = new Map();\n    this.WorkerProxy = WorkerProxyFactory.proxy(this);\n    this.workers = new Map();\n  }\n\n  resolve() {\n    this.write({ type: 'resolve', data: this.#eventBuffer.buffer });\n  }\n\n  write(msg: Message, transfer?: Transferable[]) {\n    this.#ep.postMessage(msg, transfer);\n  }\n\n  writeSystem(msg: Message, transfer?: Transferable[]) {\n    this.#ep.postMessage({ type: 'system', data: msg }, transfer);\n  }\n\n  syncRequest(msg: Message, transfer?: Transferable[]): Message {\n    const task = new SyncTask(this.#ep, msg, transfer);\n    return task.syncify() as Message;\n  }\n\n  read(): Message {\n    return this.syncRequest({ type: 'read' });\n  }\n\n  inputOrDispatch(): number {\n    for (; ;) {\n      const msg = this.read();\n      if (msg.type === 'stdin') {\n        return Module.allocateUTF8(msg.data as string);\n      }\n      this.#dispatch(msg);\n    }\n  }\n\n  run(args: string[]) {\n    try {\n      Module.callMain(args);\n    } catch (e) {\n      if (e instanceof WebAssembly.RuntimeError) {\n        this.writeSystem({ type: 'console.error', data: e.message });\n        this.writeSystem({\n          type: 'console.error',\n          data: \"An unrecoverable WebAssembly error has occurred, the webR worker will be closed.\",\n        });\n        this.writeSystem({ type: 'close' });\n      }\n      throw e;\n    }\n  }\n\n  handleEvents() {\n    if (this.#eventBuffer[0] !== 0) {\n      for (; ;) {\n        const response = this.syncRequest({ type: 'event' }) as EventMessage | undefined;\n        if (!response) break;\n        switch (response.data.msg.type) {\n          case 'interrupt':\n            this.#interrupt();\n            break;\n          case 'websocket-open': {\n            const message = response.data.msg as WebSocketOpenMessage;\n            this.ws.get(message.data.uuid)?._accept();\n            break;\n          }\n          case 'websocket-message': {\n            const message = response.data.msg as WebSocketMessage;\n            this.ws.get(message.data.uuid)?._recieve(message.data.data);\n            break;\n          }\n          case 'websocket-close': {\n            const message = response.data.msg as WebSocketCloseMessage;\n            this.ws.get(message.data.uuid)?._close(message.data.code, message.data.reason);\n            break;\n          }\n          case 'websocket-error': {\n            const message = response.data.msg as WebSocketMessage;\n            this.ws.get(message.data.uuid)?._error();\n            break;\n          }\n          case 'worker-message': {\n            const message = response.data.msg as WorkerMessage;\n            this.workers.get(message.data.uuid)?._message(message.data.data);\n            break;\n          }\n          case 'worker-messageerror': {\n            const message = response.data.msg as WorkerMessageErrorMessage;\n            this.workers.get(message.data.uuid)?._messageerror(message.data.data);\n            break;\n          }\n          case 'worker-error': {\n            const message = response.data.msg as WorkerErrorMessage;\n            this.workers.get(message.data.uuid)?._error();\n            break;\n          }\n          default:\n            throw new Error(`Unsupported event type '${response.data.msg.type}'.`);\n        }\n      }\n      this.#eventBuffer[0] = 0;\n    }\n  }\n\n  setInterrupt(interrupt: () => void) {\n    this.#interrupt = interrupt;\n  }\n\n  setDispatchHandler(dispatch: (msg: Message) => void) {\n    this.#dispatch = dispatch;\n  }\n}\n", "import { promiseHandles, ResolveFn, newCrossOriginWorker, isCrossOrigin } from '../utils';\nimport { Message, newRequest, Response, Request, newResponse } from './message';\nimport { Endpoint } from './task-common';\nimport { ChannelType } from './channel-common';\nimport { WebROptions } from '../webr-main';\nimport { ChannelMain } from './channel';\nimport { WebRChannelError, WebRWorkerError } from '../error';\n\nimport { IN_NODE } from '../compat';\nimport type { Worker as NodeWorker } from 'worker_threads';\nif (IN_NODE) {\n  (globalThis as any).Worker = require('worker_threads').Worker as NodeWorker;\n}\n\n// Main ----------------------------------------------------------------\n\nexport class PostMessageChannelMain extends ChannelMain {\n\n  initialised: Promise<unknown>;\n  resolve: (_?: unknown) => void;\n  reject: (message: string | Error) => void;\n  close: ChannelMain['close'] = () => { return; };\n  emit: ChannelMain['emit'] = () => { return; };\n  #worker?: Worker;\n\n  constructor(config: Required<WebROptions>) {\n    super();\n    ({ resolve: this.resolve, reject: this.reject, promise: this.initialised } = promiseHandles());\n\n    const initWorker = (worker: Worker) => {\n      this.#worker = worker;\n      this.#handleEventsFromWorker(worker);\n      this.close = () => {\n        worker.terminate();\n        this.putClosedMessage();\n      };\n      const msg = {\n        type: 'init',\n        data: { config, channelType: ChannelType.PostMessage },\n      } as Message;\n      worker.postMessage(msg);\n    };\n\n    if (isCrossOrigin(config.baseUrl)) {\n      newCrossOriginWorker(\n        `${config.baseUrl}webr-worker.js`,\n        (worker: Worker) => initWorker(worker),\n        (error: Error) => {\n          this.reject(new WebRWorkerError(`Worker loading error: ${error.message}`));\n        }\n      );\n    } else {\n      const worker = new Worker(`${config.baseUrl}webr-worker.js`);\n      initWorker(worker);\n    }\n  }\n\n  interrupt() {\n    console.error('Interrupting R execution is not available when using the PostMessage channel');\n  }\n\n  #handleEventsFromWorker(worker: Worker) {\n    if (IN_NODE) {\n      (worker as unknown as NodeWorker).on('message', (message: Message) => {\n        void this.#onMessageFromWorker(worker, message);\n      });\n      (worker as unknown as NodeWorker).on('error', (ev: Event) => {\n        console.error(ev);\n        this.reject(new WebRWorkerError(\n          \"An error occurred initialising the webR PostMessageChannel worker.\"\n        ));\n      });\n    } else {\n      worker.onmessage = (ev: MessageEvent) =>\n        this.#onMessageFromWorker(worker, ev.data as Message);\n      worker.onerror = (ev) => {\n        console.error(ev);\n        this.reject(new WebRWorkerError(\n          \"An error occurred initialising the webR PostMessageChannel worker.\"\n        ));\n      };\n    }\n  }\n\n  #onMessageFromWorker = async (worker: Worker, message: Message) => {\n    if (!message || !message.type) {\n      return;\n    }\n\n    switch (message.type) {\n      case 'resolve':\n        this.resolve();\n        return;\n\n      case 'response':\n        this.resolveResponse(message as Response);\n        return;\n\n      case 'system':\n        this.systemQueue.put(message.data as Message);\n        return;\n\n      default:\n        this.outputQueue.put(message);\n        return;\n\n      case 'request': {\n        const msg = message as Request;\n        const payload = msg.data.msg;\n\n        switch (payload.type) {\n          case 'read': {\n            const input = await this.inputQueue.get();\n            if (this.#worker) {\n              const response = newResponse(msg.data.uuid, input);\n              this.#worker.postMessage(response);\n            }\n            break;\n          }\n          default:\n            throw new WebRChannelError(`Unsupported request type '${payload.type}'.`);\n        }\n        return;\n      }\n\n      case 'sync-request':\n        throw new WebRChannelError(\n          \"Can't send messages of type 'sync-request' in PostMessage mode. Use 'request' instead.\"\n        );\n    }\n  };\n}\n\n// Worker --------------------------------------------------------------\n\nimport { Module as _Module } from '../emscripten';\n\ndeclare let Module: _Module;\n\nexport class PostMessageChannelWorker {\n  #ep: Endpoint;\n  #parked = new Map<string, ResolveFn<Message>>();\n  #dispatch: (msg: Message) => void = () => 0;\n  #promptDepth = 0;\n  \n  // Main thread proxies only work with SharedBufferChannelWorker for now\n  WebSocketProxy = IN_NODE ? undefined : WebSocket;\n  WorkerProxy = IN_NODE ? undefined : Worker;\n\n  constructor() {\n    this.#ep = (IN_NODE ? require('worker_threads').parentPort : globalThis) as Endpoint;\n  }\n\n  resolve() {\n    this.write({ type: 'resolve' });\n  }\n\n  write(msg: Message, transfer?: [Transferable]) {\n    this.#ep.postMessage(msg, transfer);\n  }\n\n  writeSystem(msg: Message, transfer?: [Transferable]) {\n    this.#ep.postMessage({ type: 'system', data: msg }, transfer);\n  }\n\n  read(): Message {\n    throw new WebRChannelError(\n      'Unable to synchronously read when using the `PostMessage` channel.'\n    );\n  }\n\n  inputOrDispatch(): number {\n    if (this.#promptDepth > 0) {\n      this.#promptDepth = 0;\n      const msg = Module.allocateUTF8OnStack(\n        \"Can't block for input when using the PostMessage communication channel.\"\n      );\n      Module._Rf_error(msg);\n    }\n    this.#promptDepth++;\n    // Unable to block, so just return a NULL\n    return 0;\n  }\n\n  run(_args: string[]) {\n    const args: string[] = _args || [];\n    args.unshift('R');\n    const argc = args.length;\n    const argv = Module._malloc(4 * (argc + 1));\n    args.forEach((arg, idx) => {\n      const argvPtr = argv + 4 * idx;\n      const argPtr = Module.allocateUTF8(arg);\n      Module.setValue(argvPtr, argPtr, '*');\n    });\n\n    this.writeSystem({\n      type: 'console.warn',\n      data: 'WebR is using `PostMessage` communication channel, nested R REPLs are not available.',\n    });\n\n    Module._Rf_initialize_R(argc, argv);\n    Module._setup_Rmainloop();\n    Module._R_ReplDLLinit();\n    Module._R_ReplDLLdo1();\n    void this.#asyncREPL();\n  }\n\n  setDispatchHandler(dispatch: (msg: Message) => void) {\n    this.#dispatch = dispatch;\n  }\n\n  protected async request(msg: Message, transferables?: [Transferable]): Promise<Message> {\n    const req = newRequest(msg, transferables);\n\n    const { resolve: resolve, promise: prom } = promiseHandles<Message>();\n    this.#parked.set(req.data.uuid, resolve);\n\n    this.write(req, transferables);\n    return prom;\n  }\n\n  syncRequest(): Message {\n    throw new Error('Unable to sync-request when using the `PostMessage` channel.');\n  }\n\n  setInterrupt() { return; }\n  handleEvents() { return; }\n\n  resolveRequest(message: Message) {\n    const msg = message as Response;\n    const uuid = msg.data.uuid;\n    const resolve = this.#parked.get(uuid);\n\n    if (resolve) {\n      this.#parked.delete(uuid);\n      resolve(msg.data.resp);\n    } else {\n      console.warn(\"Can't find request.\");\n    }\n  }\n\n  /*\n   * This is a fallback REPL for webR running in PostMessage mode. The prompt\n   * section of R's R_ReplDLLdo1 returns empty with -1, which allows this\n   * fallback REPL to yield to the event loop with await.\n   *\n   * The drawback of this approach is that nested REPLs do not work, such as\n   * readline, browser or menu. Attempting to use a nested REPL prints an error\n   * to the JS console.\n   *\n   * R/Wasm errors during execution are caught and the REPL is restarted at the\n   * top level. Any other JS errors are re-thrown.\n   */\n  #asyncREPL = async () => {\n    for (; ;) {\n      try {\n        this.#promptDepth = 0;\n        const msg = await this.request({ type: 'read' });\n        if (msg.type === 'stdin') {\n          // Copy the new input into WASM memory\n          const str = Module.allocateUTF8(msg.data as string);\n          Module._strcpy(Module._DLLbuf, str);\n          Module.setValue(Module._DLLbufp, Module._DLLbuf, '*');\n          Module._free(str);\n\n          // Execute the R code using a single step of R's built in REPL\n          try {\n            while (Module._R_ReplDLLdo1() > 0);\n          } catch (e: any) {\n            if (e instanceof (WebAssembly as any).Exception) {\n              // R error: clear command buffer and reproduce prompt\n              Module._R_ReplDLLinit();\n              Module._R_ReplDLLdo1();\n            } else {\n              throw e;\n            }\n          }\n        } else {\n          this.#dispatch(msg);\n        }\n      } catch (e) {\n        // Close on unrecoverable error\n        if (e instanceof WebAssembly.RuntimeError) {\n          this.writeSystem({ type: 'console.error', data: e.message });\n          this.writeSystem({\n            type: 'console.error',\n            data: \"An unrecoverable WebAssembly error has occurred, the webR worker will be closed.\",\n          });\n          this.writeSystem({ type: 'close' });\n        }\n        // Don't break the REPL loop on other Wasm `Exception` errors\n        if (!(e instanceof (WebAssembly as any).Exception)) {\n          throw e;\n        }\n      }\n    }\n  };\n}\n", "import { SharedBufferChannelMain, SharedBufferChannelWorker } from './channel-shared';\nimport { PostMessageChannelMain, PostMessageChannelWorker } from './channel-postmessage';\nimport { WebROptions } from '../webr-main';\nimport { WebRChannelError } from '../error';\n\n// This file refers to objects imported from `./channel-shared` and\n// `./channel-service.` These can't be included in `./channel` as this\n// causes a circular dependency issue.\n\nexport const ChannelType = {\n  Automatic: 0,\n  SharedArrayBuffer: 1,\n  PostMessage: 3,\n} as const;\n\nexport type ChannelInitMessage = {\n  type: string;\n  data: {\n    config: Required<WebROptions>;\n    channelType: Exclude<\n      (typeof ChannelType)[keyof typeof ChannelType],\n      typeof ChannelType.Automatic\n    >;\n    clientId?: string;\n    location?: string;\n  };\n};\n\nexport function newChannelMain(data: Required<WebROptions>) {\n  switch (data.channelType) {\n    case ChannelType.SharedArrayBuffer:\n      return new SharedBufferChannelMain(data);\n    case ChannelType.PostMessage:\n      return new PostMessageChannelMain(data);\n    case ChannelType.Automatic:\n    default:\n      if (typeof SharedArrayBuffer !== 'undefined') {\n        return new SharedBufferChannelMain(data);\n      } else {\n        return new PostMessageChannelMain(data);\n      }\n  }\n}\n\nexport function newChannelWorker(msg: ChannelInitMessage) {\n  switch (msg.data.channelType) {\n    case ChannelType.SharedArrayBuffer:\n      return new SharedBufferChannelWorker();\n    case ChannelType.PostMessage:\n      return new PostMessageChannelWorker();\n    default:\n      throw new WebRChannelError('Unknown worker channel type received');\n  }\n}\n", "import { IN_NODE } from './compat';\n\nexport const BASE_URL = IN_NODE ? __dirname + '/' : './';\nexport const PKG_BASE_URL = 'https://repo.r-wasm.org';\nexport const WEBR_VERSION = '2026.04.14';\nexport const R_VERSION = '4.5.1';\n", "/**\n * Module for working with R objects on the main thead through\n * JavaScript proxies. The `RObject` types in `RMain` are aliases for\n * proxies to the corresponding types in `RWorker`. For instance,\n * `RMain.RCharacter` is an alias for `RMain.RProxy<RWorker.RCharacter>`.\n * The proxies automatically and asynchronously forward method and\n * getter calls to the implementations on the R worker side.\n * @module RMain\n */\nimport type { RProxy } from './proxy';\nimport { isWebRPayloadPtr } from './payload';\nimport * as RWorker from './robj-worker';\n\n// RProxy<RWorker.RObject> type aliases\nexport type RObject = RProxy<RWorker.RObject>;\nexport type RNull = RProxy<RWorker.RNull>;\nexport type RSymbol = RProxy<RWorker.RSymbol>;\nexport type RPairlist = RProxy<RWorker.RPairlist>;\nexport type REnvironment = RProxy<RWorker.REnvironment>;\nexport type RString = RProxy<RWorker.RString>;\nexport type RLogical = RProxy<RWorker.RLogical>;\nexport type RInteger = RProxy<RWorker.RInteger>;\nexport type RDouble = RProxy<RWorker.RDouble>;\nexport type RComplex = RProxy<RWorker.RComplex>;\nexport type RCharacter = RProxy<RWorker.RCharacter>;\nexport type RList = RProxy<RWorker.RList>;\nexport type RDataFrame = RProxy<RWorker.RDataFrame>;\nexport type RRaw = RProxy<RWorker.RRaw>;\nexport type RCall = RProxy<RWorker.RCall>;\n// RFunction proxies are callable\nexport type RFunction = RProxy<RWorker.RFunction> & ((...args: unknown[]) => Promise<unknown>);\n\n/**\n * Test for an RObject instance\n *\n * RObject is the user facing interface to R objects.\n * @param {any} value The object to test.\n * @returns {boolean} True if the object is an instance of an RObject.\n */\nexport function isRObject(value: any): value is RObject {\n  return (\n    !!value &&\n    (typeof value === 'object' || typeof value === 'function') &&\n    'payloadType' in value &&\n    isWebRPayloadPtr(value._payload)\n  );\n}\n\n/**\n * Test for an RNull instance\n * @param {any} value The object to test.\n * @returns {boolean} True if the object is an instance of an RNull.\n */\nexport function isRNull(value: any): value is RNull {\n  return isRObject(value) && value._payload.obj.type === 'null';\n}\n\n/**\n * Test for an RSymbol instance\n * @param {any} value The object to test.\n * @returns {boolean} True if the object is an instance of an RSymbol.\n */\nexport function isRSymbol(value: any): value is RSymbol {\n  return isRObject(value) && value._payload.obj.type === 'symbol';\n}\n\n/**\n * Test for an RPairlist instance\n * @param {any} value The object to test.\n * @returns {boolean} True if the object is an instance of an RPairlist.\n */\nexport function isRPairlist(value: any): value is RPairlist {\n  return isRObject(value) && value._payload.obj.type === 'pairlist';\n}\n\n/**\n * Test for an REnvironment instance\n * @param {any} value The object to test.\n * @returns {boolean} True if the object is an instance of an REnvironment.\n */\nexport function isREnvironment(value: any): value is REnvironment {\n  return isRObject(value) && value._payload.obj.type === 'environment';\n}\n\n/**\n * Test for an RLogical instance\n * @param {any} value The object to test.\n * @returns {boolean} True if the object is an instance of an RLogical.\n */\nexport function isRLogical(value: any): value is RLogical {\n  return isRObject(value) && value._payload.obj.type === 'logical';\n}\n\n/**\n * Test for an RInteger instance\n * @param {any} value The object to test.\n * @returns {boolean} True if the object is an instance of an RInteger.\n */\nexport function isRInteger(value: any): value is RInteger {\n  return isRObject(value) && value._payload.obj.type === 'integer';\n}\n\n/**\n * Test for an RDouble instance\n * @param {any} value The object to test.\n * @returns {boolean} True if the object is an instance of an RDouble.\n */\nexport function isRDouble(value: any): value is RDouble {\n  return isRObject(value) && value._payload.obj.type === 'double';\n}\n\n/**\n * Test for an RComplex instance\n * @param {any} value The object to test.\n * @returns {boolean} True if the object is an instance of an RComplex.\n */\nexport function isRComplex(value: any): value is RComplex {\n  return isRObject(value) && value._payload.obj.type === 'complex';\n}\n\n/**\n * Test for an RCharacter instance\n * @param {any} value The object to test.\n * @returns {boolean} True if the object is an instance of an RCharacter.\n */\nexport function isRCharacter(value: any): value is RCharacter {\n  return isRObject(value) && value._payload.obj.type === 'character';\n}\n\n/**\n * Test for an RList instance\n * @param {any} value The object to test.\n * @returns {boolean} True if the object is an instance of an RList.\n */\nexport function isRList(value: any): value is RList {\n  return isRObject(value) && value._payload.obj.type === 'list';\n}\n\n/**\n * Test for an RRaw instance\n * @param {any} value The object to test.\n * @returns {boolean} True if the object is an instance of an RRaw.\n */\nexport function isRRaw(value: any): value is RRaw {\n  return isRObject(value) && value._payload.obj.type === 'raw';\n}\n\n/**\n * Test for an RCall instance\n * @param {any} value The object to test.\n * @returns {boolean} True if the object is an instance of an RCall.\n */\nexport function isRCall(value: any): value is RCall {\n  return isRObject(value) && value._payload.obj.type === 'call';\n}\n\n/**\n * Test for an RFunction instance\n * @param {any} value The object to test.\n * @returns {boolean} True if the object is an instance of an RFunction.\n */\nexport function isRFunction(value: any): value is RFunction {\n  return Boolean(isRObject(value) && value._payload.obj.methods?.includes('exec'));\n}\n", "/**\n * Proxy R objects on the webR worker thread so that they can be accessed from\n * the main thread.\n * @module Proxy\n */\nimport { ChannelMain } from './chan/channel';\nimport { replaceInObject } from './utils';\nimport { isWebRPayloadPtr, WebRPayloadPtr, WebRPayload } from './payload';\nimport { RType, RCtor, WebRData, WebRDataRaw } from './robj';\nimport { isRObject, RObject, isRFunction } from './robj-main';\nimport * as RWorker from './robj-worker';\nimport { ShelterID, CallRObjectMethodMessage, NewRObjectMessage } from './webr-chan';\nimport type * as Payload from './payload';\nimport { WebRError, WebRPayloadError } from './error';\n\n/**\n * Obtain a union of the keys corresponding to methods of a given class `T`.\n * @typeParam T The type to provide the methods for.\n */\nexport type Methods<T> = {\n  [P in keyof T]: T[P] extends (...args: any) => any ? P : never;\n}[keyof T];\n\n/**\n * Distributive conditional type for {@link RProxy}.\n *\n * Distributes {@link RProxy} over any {@link RWorker.RObject} in the given\n * union type U.\n * @typeParam U The type union to distribute {@link RProxy} over.\n */\nexport type DistProxy<U> = U extends RWorker.RObject ? RProxy<U> : U;\n\n/**\n * Convert {@link RWorker.RObject} properties for use with an {@link RProxy}.\n *\n * Properties in the type parameter `T` are mapped so that {@link RProxy} is\n * distributed over any {@link RWorker.RObject} types, then wrapped in a\n * Promise.\n *\n * Function signatures are mapped so that arguments with {@link RWorker.RObject}\n * type instead take {@link RProxy}<{@link RWorker.RObject}> type. Other\n * function arguments remain as they are. The function return type is also\n * converted to a corresponding type using `RProxify` recursively.\n * @typeParam T The type to convert.\n */\nexport type RProxify<T> = T extends Array<any> // [RObject, RObject, ...]\n  ? Promise<DistProxy<T[0]>[]>\n  : T extends (...args: infer U) => any // (...args) => <RObject>\n  ? (\n    ...args: {\n      [V in keyof U]: DistProxy<U[V]>;\n    }\n  ) => RProxify<ReturnType<T>>\n  : T extends { result: RWorker.RObject, output: RWorker.RObject } // Return type of .capture()\n  ? Promise<{\n    [U in keyof T]: DistProxy<T[U]>\n  }>\n  : Promise<DistProxy<T>>; // RObject, any other types\n\n/**\n * Create an {@link RProxy} based on an {@link RWorker.RObject} type parameter.\n *\n * R objects created via an {@link RProxy} are intended to be used in place of\n * {@link RWorker.RObject} on the main thread. An {@link RProxy} object has the\n * same instance methods as the given {@link RWorker.RObject} parameter, with\n * the following differences:\n * - Method arguments take `RProxy` in place of {@link RWorker.RObject}.\n *\n * - Where an {@link RWorker.RObject} would be returned, an `RProxy` is\n *   returned instead.\n *\n * - All return types are wrapped in a Promise.\n *\n * If required, the {@link Payload.WebRPayloadPtr} object associated with the\n * proxy can be accessed directly through the `_payload` property.\n * @typeParam T The {@link RWorker.RObject} type to convert into `RProxy` type.\n */\nexport type RProxy<T extends RWorker.RObject> = { [P in Methods<T>]: RProxify<T[P]> } & {\n  _payload: WebRPayloadPtr;\n  [Symbol.asyncIterator](): AsyncGenerator<RProxy<RWorker.RObject>, void, unknown>;\n};\n\n/**\n * Create a proxy constructor based on a {@link RWorker.RObject} class.\n *\n * The class constructors and static methods of the given subclass of\n * {@link RWorker.RObject} are proxied, and the proxied constructor returns a\n * promise to an R object of a given {@link RProxy} type.\n * @typeParam T The type of the {@link RWorker.RObject} class to be proxied.\n * @typeParam R The type to be returned from the proxied class constructor.\n */\nexport type ProxyConstructor<T, R> = (T extends abstract new (...args: infer U) => any\n  ? {\n    new(\n      ...args: {\n        [V in keyof U]: U[V];\n      }\n    ): Promise<R>;\n  }\n  : never) & {\n    [P in Methods<typeof RWorker.RObject>]: RProxify<(typeof RWorker.RObject)[P]>;\n  };\n\n/* The empty function is used as base when we are proxying RFunction objects.\n * This enables function call semantics on the proxy using the apply hook.\n */\nfunction empty() { return; }\n\n/* Proxy the asyncIterator property for R objects with a length. This allows us\n * to use the `for await (i of obj){}` JavaScript syntax.\n */\nfunction targetAsyncIterator(chan: ChannelMain, proxy: RProxy<RWorker.RObject>) {\n  return async function* () {\n    // Get the R object's length\n    const msg: CallRObjectMethodMessage = {\n      type: 'callRObjectMethod',\n      data: {\n        payload: proxy._payload,\n        prop: 'getPropertyValue',\n        args: [{ payloadType: 'raw', obj: 'length' }],\n        shelter: undefined, // TODO\n      },\n    };\n    const reply = await chan.request(msg);\n\n    // Throw an error if there was some problem accessing the object length\n    if (typeof reply.obj !== 'number') {\n      throw new WebRError('Cannot iterate over object, unexpected type for length property.');\n    }\n\n    // Loop through the object and yield values\n    for (let i = 1; i <= reply.obj; i++) {\n      yield proxy.get(i);\n    }\n  };\n}\n\n/**\n * Proxy an R object method by providing an async function that requests that\n * the worker thread calls the method and then returns the result.\n *\n * When the optional payload argument has not been provided, an\n * {@link RWorker.RObject} static method is called.\n * @internal\n */\nexport function targetMethod(chan: ChannelMain, prop: string): unknown;\nexport function targetMethod(chan: ChannelMain, prop: string, payload: WebRPayloadPtr): unknown;\nexport function targetMethod(chan: ChannelMain, prop: string, payload?: WebRPayloadPtr): unknown {\n  return async (..._args: WebRData[]) => {\n    const args = _args.map((arg) => {\n      if (isRObject(arg)) {\n        return arg._payload;\n      }\n      return {\n        obj: replaceInObject(arg, isRObject, (obj: RObject) => obj._payload),\n        payloadType: 'raw',\n      } as WebRPayload;\n    });\n\n    const msg: CallRObjectMethodMessage = {\n      type: 'callRObjectMethod',\n      data: { payload, prop, args: args },\n    };\n    const reply = await chan.request(msg);\n\n    switch (reply.payloadType) {\n      case 'ptr':\n        return newRProxy(chan, reply);\n      case 'raw': {\n        const proxyReply = replaceInObject(\n          reply,\n          isWebRPayloadPtr,\n          (obj: WebRPayloadPtr, chan: ChannelMain) => newRProxy(chan, obj),\n          chan\n        ) as WebRPayload;\n        return proxyReply.obj;\n      }\n    }\n  };\n}\n\n/* Proxy the `RWorker` class constructors. This allows us to create a new R\n * object on the worker thread from a given JS object.\n */\nasync function newRObject(\n  chan: ChannelMain,\n  objType: RType | RCtor,\n  shelter: ShelterID,\n  ...args: WebRData[]\n) {\n  const msg: NewRObjectMessage = {\n    type: 'newRObject',\n    data: {\n      objType,\n      args: replaceInObject<WebRData[]>(args, isRObject, (obj: RObject) => obj._payload),\n      shelter: shelter,\n    },\n  };\n  const payload = await chan.request(msg);\n  switch (payload.payloadType) {\n    case 'raw':\n      throw new WebRPayloadError('Unexpected raw payload type returned from newRObject');\n    case 'ptr':\n      return newRProxy(chan, payload);\n  }\n}\n\n/**\n * Proxy an R object.\n *\n * The proxy targets a particular R object in WebAssembly memory. Methods of the\n * relevant subclass of {@link RWorker.RObject} are proxied, enabling\n * structured manipulation of R objects from the main thread.\n * @param {ChannelMain} chan The current main thread communication channel.\n * @param {WebRPayloadPtr} payload A webR payload referencing an R object.\n * @returns {RProxy<RWorker.RObject>} An {@link RObject} corresponding to the\n * referenced R object.\n */\nexport function newRProxy(chan: ChannelMain, payload: WebRPayloadPtr): RProxy<RWorker.RObject> {\n  const proxy = new Proxy(\n    // Assume we are proxying an RFunction if the methods list contains 'exec'.\n    payload.obj.methods?.includes('exec') ? Object.assign(empty, { ...payload }) : payload,\n    {\n      get: (_: WebRPayload, prop: string | number | symbol) => {\n        if (prop === '_payload') {\n          return payload;\n        } else if (prop === Symbol.asyncIterator) {\n          return targetAsyncIterator(chan, proxy);\n        } else if (payload.obj.methods?.includes(prop.toString())) {\n          return targetMethod(chan, prop.toString(), payload);\n        }\n      },\n      apply: async (_: WebRPayload, _thisArg, args: (WebRDataRaw | RProxy<RWorker.RObject>)[]) => {\n        const res = await (newRProxy(chan, payload) as RProxy<RWorker.RFunction>).exec(...args);\n        return isRFunction(res) ? res : res.toJs();\n      },\n    }\n  ) as unknown as RProxy<RWorker.RObject>;\n  return proxy;\n}\n\n/**\n * Proxy an {@link RWorker.RObject} class.s\n * @param {ChannelMain} chan The current main thread communication channel.\n * @param {ShelterID} shelter The shelter ID to protect returned objects with.\n * @param {(RType | RCtor)} objType The R object type or class, `'object'` for\n * the generic {@link RWorker.RObject} class.\n * @returns {ProxyConstructor} A proxy to the R object subclass corresponding to\n * the given value of the `objType` argument.\n * @typeParam T The type of the {@link RWorker.RObject} class to be proxied.\n * @typeParam R The type to be returned from the proxied class constructor.\n */\nexport function newRClassProxy<T, R>(\n  chan: ChannelMain,\n  shelter: ShelterID,\n  objType: RType | RCtor\n) {\n  return new Proxy(RWorker.RObject, {\n    construct: (_, args: WebRData[]) => newRObject(chan, objType, shelter, ...args),\n    get: (_, prop: string | number | symbol) => {\n      return targetMethod(chan, prop.toString());\n    },\n  }) as unknown as ProxyConstructor<T, R>;\n}\n", "import { IN_NODE } from './compat';\nimport { WebR, WebROptions } from './webr-main';\n\nexport interface ConsoleCallbacks {\n  stdout?: (line: string) => void;\n  stderr?: (line: string) => void;\n  prompt?: (line: string) => void;\n  canvasImage?: (image: ImageBitmap) => void;\n  canvasNewPage?: () => void;\n}\n\n/**\n * Text-based Interactive Console for WebR\n *\n * A helper application to assist in creating an interactive R REPL based on\n * JavaScript callbacks.\n *\n * Callback functions ``stdout`` and ``stderr`` are called with a single line\n * of output as the first argument. The default implementation of `stdout` and\n * `stderr` writes to the console using `console.log` and `console.error`.\n *\n * R code can be sent as input by calling the ``stdin`` method with a single\n * line of textual input.\n *\n * A long running R computation can be interrupted by calling the `interrupt`\n * method.\n *\n * The ``prompt`` callback function is called when webR produces a prompt at\n * the REPL console and is therefore awaiting user input. The prompt character\n * (usually ``>`` or ``+``) is given as the first argument to the callback\n * function. The default implementation of `prompt` shows a JavaScript prompt\n * asking the user for input, and then sends the user input to `stdin`.\n *\n * The ``canvasImage`` callback function is called when webR writes plots to\n * the built-in HTML canvas graphics device.\n *\n * The ``canvasNewPage`` callback function is called when webR creates a new\n * plot.\n *\n * Once constructed, start the Console using the ``run`` method. The `run`\n * method starts an asynchronous infinite loop that waits for output from the\n * webR worker and then calls the relevant callbacks.\n */\nexport class Console {\n  /** The supporting instance of webR */\n  webR: WebR;\n  /**\n   * A HTML canvas element\n   *\n   * The canvas graphics device writes to this element by default. Undefined\n   * when HTML canvas is unsupported.\n   */\n  canvas: HTMLCanvasElement | undefined;\n  /** Called when webR outputs to ``stdout`` */\n  #stdout: (line: string) => void;\n  /** Called when webR outputs to ``stderr`` */\n  #stderr: (line: string) => void;\n  /** Called when webR prompts for input */\n  #prompt: (line: string) => void;\n  /** Called when webR writes to the HTML canvas element */\n  #canvasImage: (image: ImageBitmap) => void;\n  /** Called when webR creates a new plot */\n  #canvasNewPage: () => void;\n\n  /**\n   * @param {ConsoleCallbacks} callbacks A list of webR Console callbacks to\n   * be used for this console.\n   * @param {WebROptions} options The options to use for the new instance of\n   * webR started to support this console.\n   */\n  constructor(\n    callbacks: ConsoleCallbacks = {},\n    options: WebROptions = {\n      REnv: {\n        R_HOME: '/usr/lib/R',\n        FONTCONFIG_PATH: '/etc/fonts',\n        R_ENABLE_JIT: '0',\n      },\n    }\n  ) {\n    this.webR = new WebR(options);\n    if (!IN_NODE) {\n      this.canvas = document.createElement('canvas');\n      this.canvas.setAttribute('width', '1008');\n      this.canvas.setAttribute('height', '1008');\n    }\n    this.#stdout = callbacks.stdout || this.#defaultStdout;\n    this.#stderr = callbacks.stderr || this.#defaultStderr;\n    this.#prompt = callbacks.prompt || this.#defaultPrompt;\n    this.#canvasImage = callbacks.canvasImage || this.#defaultCanvasImage;\n    this.#canvasNewPage = callbacks.canvasNewPage || this.#defaultCanvasNewPage;\n    void this.webR.evalRVoid('options(device=webr::canvas)');\n  }\n\n  /**\n   * Write a line of input to webR's REPL through ``stdin``\n   * @param {string} input A line of input text.\n   */\n  stdin(input: string) {\n    this.webR.writeConsole(input);\n  }\n\n  /**\n   * Interrupt a long running R computation and return to the prompt\n   */\n  interrupt() {\n    this.webR.interrupt();\n  }\n\n  /**\n   * The default function called when webR outputs to ``stdout``\n   * @param {string} text The line sent to stdout by webR.\n   */\n  #defaultStdout = (text: string) => {\n    console.log(text);\n  };\n\n  /**\n   * The default function called when webR outputs to ``stderr``\n   * @param {string} text The line sent to stderr by webR.\n   */\n  #defaultStderr = (text: string) => {\n    console.error(text);\n  };\n\n  /**\n   * The default function called when webR writes out a prompt\n   * @param {string} text The text content of the prompt.\n   */\n  #defaultPrompt = (text: string) => {\n    const input = prompt(text);\n    if (input) this.stdin(`${input}\\n`);\n  };\n\n  /**\n   * The default function called when webR writes to HTML canvas\n   * @param {ImageBitmap} image An ImageBitmap containing the image data.\n   */\n  #defaultCanvasImage = (image: ImageBitmap) => {\n    if (IN_NODE) {\n      throw new Error('Plotting with HTML canvas is not yet supported under Node');\n    }\n    this.canvas!.getContext('2d')!.drawImage(image, 0, 0);\n  };\n\n  /**\n   * The default function called when webR creates a new plot\n   */\n  #defaultCanvasNewPage = () => {\n    if (IN_NODE) {\n      throw new Error('Plotting with HTML canvas is not yet supported under Node');\n    }\n    this.canvas!.getContext('2d')!.clearRect(0, 0, this.canvas!.width, this.canvas!.height);\n  };\n\n  /**\n   * Start the webR console\n   */\n  run() {\n    void this.#run();\n  }\n\n  /*\n   * Start the asynchronous infinite loop\n   *\n   * This loop waits for output from webR and dispatches callbacks based on the\n   * message received.\n   *\n   * The promise returned by this asynchronous function resolves only once the\n   * webR communication channel has closed.\n   */\n  async #run() {\n    for (; ;) {\n      const output = await this.webR.read();\n      switch (output.type) {\n        case 'stdout':\n          this.#stdout(output.data as string);\n          break;\n        case 'stderr':\n          this.#stderr(output.data as string);\n          break;\n        case 'prompt':\n          this.#prompt(output.data as string);\n          break;\n        case 'canvas':\n          if (output.data.event === 'canvasImage') {\n            this.#canvasImage(output.data.image as ImageBitmap);\n          } else if (output.data.event === 'canvasNewPage') {\n            this.#canvasNewPage();\n          }\n          break;\n        case 'closed':\n          return;\n        default:\n          console.warn(`Unhandled output type for webR Console: ${output.type}.`);\n      }\n    }\n  }\n}\n"],
  "mappings": "sxBAEaA,EAAA,WAAa,WAK1B,SAAgBC,GAAUC,EAAgBC,EAAgBC,EAAa,CACrE,IAAMC,EAAOD,EAAQ,WACfE,EAAMF,EACZF,EAAK,UAAUC,EAAQE,CAAI,EAC3BH,EAAK,UAAUC,EAAS,EAAGG,CAAG,CAChC,CALAN,EAAA,UAAAC,GAOA,SAAgBM,GAASL,EAAgBC,EAAgBC,EAAa,CACpE,IAAMC,EAAO,KAAK,MAAMD,EAAQ,UAAa,EACvCE,EAAMF,EACZF,EAAK,UAAUC,EAAQE,CAAI,EAC3BH,EAAK,UAAUC,EAAS,EAAGG,CAAG,CAChC,CALAN,EAAA,SAAAO,GAOA,SAAgBC,GAASN,EAAgBC,EAAc,CACrD,IAAME,EAAOH,EAAK,SAASC,CAAM,EAC3BG,EAAMJ,EAAK,UAAUC,EAAS,CAAC,EACrC,OAAOE,EAAO,WAAgBC,CAChC,CAJAN,EAAA,SAAAQ,GAMA,SAAgBC,GAAUP,EAAgBC,EAAc,CACtD,IAAME,EAAOH,EAAK,UAAUC,CAAM,EAC5BG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QACE,OAAOK,EAAU,KAAKzC,GAAOmC,CAAO,CACxC,CACF,CAiBA,MAAM,SAASN,EAAcjC,EAAwB,CAAC,EAInD,CACD,IAAMmC,EAAOC,EAAgBpC,EAASqC,EAAYC,GAAiBA,EAAI,QAAQ,EACzEnC,EAAuB,CAC3B,KAAM,WACN,KAAM,CACJ,KAAM8B,EACN,QAASE,EACT,QAAS,KAAKO,EAChB,CACF,EACMH,EAAU,MAAM,KAAKnC,GAAM,QAAQD,CAAG,EAE5C,OAAQoC,EAAQ,YAAa,CAC3B,IAAK,MACH,MAAM,IAAIC,EAAiB,6CAA6C,EAE1E,IAAK,MAAO,CACV,IAAM/B,EAAO8B,EAAQ,IAKfO,EAASD,EAAU,KAAKzC,GAAOK,EAAK,MAAM,EAC1CmB,EAASnB,EAAK,OACdsC,EAAStC,EAAK,OAEpB,QAASuC,EAAI,EAAGA,EAAIpB,EAAO,OAAQ,EAAEoB,EAC/BpB,EAAOoB,CAAC,EAAE,OAAS,UAAYpB,EAAOoB,CAAC,EAAE,OAAS,WACpDpB,EAAOoB,CAAC,EAAE,KAAOH,EAAU,KAAKzC,GAAOwB,EAAOoB,CAAC,EAAE,IAAsB,GAI3E,MAAO,CAAE,OAAAF,EAAQ,OAAAlB,EAAQ,OAAAmB,CAAO,CAClC,CACF,CACF,CACF,EAEA,SAAS1B,GAAgBsB,EAAmB,CAC1C,OAAO,IAAI,MAAMF,GAAS,CACxB,UAAW,SAAY,CACrB,IAAMQ,EAAM,IAAIR,GAAQE,CAAI,EAC5B,aAAMM,EAAI,KAAK,EACRA,CACT,CACF,CAAC,CAGH",
  "names": ["exports", "setUint64", "view", "offset", "value", "high", "low", "setInt64", "getInt64", "getUint64", "int_1", "TEXT_ENCODING_AVAILABLE", "_a", "utf8Count", "str", "strLength", "byteLength", "pos", "value", "extra", "exports", "utf8EncodeJs", "output", "outputOffset", "offset", "sharedTextEncoder", "_b", "utf8EncodeTEencode", "utf8EncodeTEencodeInto", "CHUNK_SIZE", "utf8DecodeJs", "bytes", "inputOffset", "end", "units", "result", "byte1", "byte2", "byte3", "byte4", "unit", "sharedTextDecoder", "_c", "utf8DecodeTD", "stringBytes", "ExtData", "type", "data", "exports", "DecodeError", "_DecodeError", "message", "proto", "exports", "DecodeError_1", "int_1", "exports", "TIMESTAMP32_MAX_SEC", "TIMESTAMP64_MAX_SEC", "encodeTimeSpecToTimestamp", "sec", "nsec", "rv", "secHigh", "secLow", "view", "encodeDateToTimeSpec", "date", "msec", "nsecInSec", "encodeTimestampExtension", "object", "timeSpec", "decodeTimestampToTimeSpec", "data", "nsec30AndSecHigh2", "secLow32", "decodeTimestampExtension", "ExtData_1", "timestamp_1", "ExtensionCodec", "type", "encode", "decode", "index", "object", "context", "i", "encodeExt", "data", "decodeExt", "exports", "ensureUint8Array", "buffer", "exports", "createDataView", "bufferView", "utf8_1", "ExtensionCodec_1", "int_1", "typedArrays_1", "exports", "Encoder", "extensionCodec", "context", "maxDepth", "initialBufferSize", "sortKeys", "forceFloat32", "ignoreUndefined", "forceIntegerToFloat", "object", "depth", "sizeToWrite", "requiredSize", "newSize", "newBuffer", "newBytes", "newView", "byteLength", "ext", "size", "bytes", "item", "keys", "count", "key", "value", "values", "Encoder_1", "defaultEncodeOptions", "encode", "value", "options", "exports", "prettyByte", "byte", "exports", "utf8_1", "DEFAULT_MAX_KEY_LENGTH", "DEFAULT_MAX_LENGTH_PER_KEY", "CachedKeyDecoder", "maxKeyLength", "maxLengthPerKey", "i", "byteLength", "bytes", "inputOffset", "records", "FIND_CHUNK", "record", "recordBytes", "j", "value", "cachedValue", "str", "slicedCopyOfBytes", "exports", "prettyByte_1", "ExtensionCodec_1", "int_1", "utf8_1", "typedArrays_1", "CachedKeyDecoder_1", "DecodeError_1", "isValidMapKeyType", "key", "keyType", "HEAD_BYTE_REQUIRED", "EMPTY_VIEW", "EMPTY_BYTES", "exports", "e", "MORE_DATA", "sharedCachedKeyDecoder", "Decoder", "extensionCodec", "context", "maxStrLength", "maxBinLength", "maxArrayLength", "maxMapLength", "maxExtLength", "keyDecoder", "buffer", "remainingData", "newData", "newBuffer", "size", "posToShow", "view", "pos", "object", "stream", "decoded", "headByte", "totalPos", "isArray", "isArrayHeaderRequired", "arrayItemsLeft", "DECODE", "byteLength", "stack", "state", "headerOffset", "offset", "_a", "headOffset", "extType", "data", "value", "Decoder_1", "exports", "decode", "buffer", "options", "decodeMulti", "isAsyncIterable", "object", "exports", "assertNonNull", "value", "asyncIterableFromStream", "stream", "reader", "done", "ensureAsyncIterable", "streamLike", "Decoder_1", "stream_1", "decode_1", "decodeAsync", "streamLike", "options", "stream", "exports", "decodeArrayStream", "decodeMultiStream", "decodeStream", "encode_1", "exports", "decode_1", "decodeAsync_1", "Decoder_1", "DecodeError_1", "Encoder_1", "ExtensionCodec_1", "ExtData_1", "timestamp_1", "webr_main_exports", "__export", "ChannelType", "Console", "Shelter", "WebR", "WebRChannelError", "WebRError", "WebRPayloadError", "WebRWorkerError", "isRCall", "isRCharacter", "isRComplex", "isRDouble", "isREnvironment", "isRFunction", "isRInteger", "isRList", "isRLogical", "isRNull", "isRObject", "isRPairlist", "isRRaw", "isRSymbol", "isUUID", "__toCommonJS", "WebRError", "msg", "WebRWorkerError", "WebRChannelError", "WebRPayloadError", "IN_NODE", "loadScript", "url", "resolve", "reject", "script", "WebRError", "RTypeMap", "isWebRDataJs", "value", "isComplex", "Module", "dictEmFree", "dict", "key", "protect", "x", "Module", "handlePtr", "protectInc", "prot", "protectWithIndex", "pLoc", "unprotectIndex", "index", "reprotect", "unprotect", "n", "envPoke", "env", "sym", "value", "parseEvalBare", "code", "strings", "envObj", "REnvironment", "out", "RObject", "dictEmFree", "safeEval", "call", "env", "Module", "handlePtr", "transferCache", "transfer", "obj", "transfers", "isUUID", "x", "UUID_LENGTH", "generateUUID", "result", "randomSegment", "pad", "handlePtr", "x", "isRObject", "assertRType", "obj", "type", "Module", "RTypeMap", "newObjectFromData", "obj", "isWebRDataJs", "getRWorkerClass", "RNull", "RLogical", "RDouble", "RCharacter", "isComplex", "RComplex", "RRaw", "newObjectFromArray", "RDataFrame", "arr", "prot", "v", "isRObject", "_arr", "isConsistent", "k", "isAtomic", "isAtomicType", "isRVectorAtomic", "call", "RCall", "RSymbol", "protectInc", "unprotect", "RObjectBase", "ptr", "typeNumber", "Module", "RTypeMap", "typeName", "RObject", "_RObject", "data", "type", "prop", "objs", "parseEvalBare", "result", "protect", "RPairlist", "classCall", "values", "namesObj", "names", "name", "options", "depth", "#slice", "op", "idx", "safeEval", "path", "index", "protectWithIndex", "getter", "out", "reprotect", "unprotectIndex", "value", "valueObj", "assign", "props", "cur", "p", "i", "x", "assertRType", "RString", "_RPairlist", "val", "toWebRData", "list", "next", "allowDuplicateKey", "allowEmptyKey", "entries", "keys", "u", "namesArray", "hasNames", "symbol", "_RCall", "RList", "_RList", "isSimpleObject", "_names", "classes", "a", "entry", "j", "_RDataFrame", "hasArrays", "_values", "isConsistentLength", "listObj", "asDataFrame", "RFunction", "args", "_RString", "vmax", "REnvironment", "nProt", "sym", "vObj", "envPoke", "all", "sorted", "symbols", "RVectorAtomic", "kind", "newSetter", "ret", "elt", "m", "_RLogical", "#newSetter", "naLogical", "RInteger", "_RInteger", "naInteger", "_RDouble", "naDouble", "_RComplex", "_RCharacter", "_RRaw", "jsObj", "typeClasses", "atomicRTypes", "promiseHandles", "out", "promise", "resolve", "reject", "sleep", "ms", "replaceInObject", "obj", "test", "replacer", "replacerArgs", "isImageBitmap", "v", "RObjectBase", "k", "newCrossOriginWorker", "url", "cb", "onError", "options", "async", "req", "worker", "error", "isCrossOrigin", "urlString", "IN_NODE", "url1", "url2", "value", "isSimpleObject", "value", "isComplex", "isWebRDataJs", "RObjectBase", "import_msgpack", "encoder", "syncResponse", "endpoint", "data", "response", "taskId", "sizeBuffer", "dataBuffer", "signalBuffer", "bytes", "fits", "uuid", "dataPromise", "requestResponseMessage", "signalRequester", "e", "ep", "id", "generateUUID", "resolve", "IN_NODE", "message", "l", "ev", "index", "sleepTime", "sleep", "AsyncQueue", "#promises", "#resolvers", "t", "#add", "resolve", "newRequest", "msg", "transferables", "newRequestResponseMessage", "generateUUID", "newResponse", "uuid", "resp", "transfer", "webRPayloadAsError", "payload", "WebRWorkerError", "isWebRPayload", "value", "isWebRPayloadPtr", "ChannelMain", "AsyncQueue", "#parked", "#closed", "msg", "WebRChannelError", "transferables", "req", "newRequest", "resolve", "reject", "promise", "promiseHandles", "uuid", "handles", "payload", "webRPayloadAsError", "decoder", "eventBuffer", "WebSocketMap", "chan", "IN_NODE", "#map", "uuid", "url", "protocols", "ws", "ev", "data", "code", "reason", "IN_NODE", "type", "eventInitDict", "WorkerMap", "chan", "#map", "uuid", "url", "options", "IN_NODE", "worker", "nodeWorker", "ev", "newCrossOriginWorker", "error", "message", "async", "handles", "data", "transfer", "handler", "_uuid", "result", "IN_NODE", "SharedBufferChannelMain", "ChannelMain", "config", "#onMessageFromWorker", "worker", "message", "#eventBuffer", "msg", "payload", "reqData", "response", "syncResponse", "src", "data", "_error", "error", "promiseHandles", "value", "WebRChannelError", "initWorker", "#handleEventsFromWorker", "ChannelType", "isCrossOrigin", "newCrossOriginWorker", "WebRWorkerError", "ev", "IN_NODE", "PostMessageChannelMain", "ChannelMain", "config", "#onMessageFromWorker", "worker", "message", "msg", "payload", "input", "#worker", "response", "newResponse", "WebRChannelError", "promiseHandles", "initWorker", "#handleEventsFromWorker", "ChannelType", "isCrossOrigin", "newCrossOriginWorker", "error", "WebRWorkerError", "ev", "ChannelType", "newChannelMain", "data", "SharedBufferChannelMain", "PostMessageChannelMain", "BASE_URL", "IN_NODE", "PKG_BASE_URL", "WEBR_VERSION", "R_VERSION", "isRObject", "value", "isWebRPayloadPtr", "isRNull", "isRSymbol", "isRPairlist", "isREnvironment", "isRLogical", "isRInteger", "isRDouble", "isRComplex", "isRCharacter", "isRList", "isRRaw", "isRCall", "isRFunction", "empty", "targetAsyncIterator", "chan", "proxy", "msg", "reply", "WebRError", "i", "targetMethod", "prop", "payload", "_args", "args", "arg", "isRObject", "replaceInObject", "obj", "newRProxy", "isWebRPayloadPtr", "newRObject", "objType", "shelter", "WebRPayloadError", "_", "_thisArg", "res", "isRFunction", "newRClassProxy", "RObject", "Console", "#stdout", "#stderr", "#prompt", "#canvasImage", "#canvasNewPage", "callbacks", "options", "WebR", "IN_NODE", "#defaultStdout", "#defaultStderr", "#defaultPrompt", "#defaultCanvasImage", "#defaultCanvasNewPage", "input", "text", "image", "#run", "output", "defaultEnv", "WEBR_VERSION", "R_VERSION", "defaultOptions", "BASE_URL", "PKG_BASE_URL", "ChannelType", "WebR", "options", "path", "dontResolveLastLink", "msg", "#chan", "type", "mountpoint", "promises", "item", "data", "pkg", "populate", "flags", "oldpath", "newpath", "config", "newChannelMain", "#ws", "WebSocketMap", "#workers", "WorkerMap", "newShelterProxy", "#initialised", "#handleSystemMessages", "ptr", "args", "message", "WebRError", "output", "input", "packages", "op", "x", "code", "outputType", "opts", "replaceInObject", "isRObject", "obj", "payload", "WebRPayloadError", "Shelter", "#id", "chan", "newRClassProxy", "newRProxy", "result", "images", "i", "out"]
}
