{"version":3,"file":"util.mjs","sources":["../../../../lib/web/websocket/util.js"],"sourcesContent":["'use strict'\n\nconst { states, opcodes } = require('./constants')\nconst { isUtf8 } = require('node:buffer')\nconst { removeHTTPWhitespace } = require('../fetch/data-url')\nconst { collectASequenceOfCodePointsFast } = require('../infra')\n\n/**\n * @param {number} readyState\n * @returns {boolean}\n */\nfunction isConnecting (readyState) {\n  // If the WebSocket connection is not yet established, and the connection\n  // is not yet closed, then the WebSocket connection is in the CONNECTING state.\n  return readyState === states.CONNECTING\n}\n\n/**\n * @param {number} readyState\n * @returns {boolean}\n */\nfunction isEstablished (readyState) {\n  // If the server's response is validated as provided for above, it is\n  // said that _The WebSocket Connection is Established_ and that the\n  // WebSocket Connection is in the OPEN state.\n  return readyState === states.OPEN\n}\n\n/**\n * @param {number} readyState\n * @returns {boolean}\n */\nfunction isClosing (readyState) {\n  // Upon either sending or receiving a Close control frame, it is said\n  // that _The WebSocket Closing Handshake is Started_ and that the\n  // WebSocket connection is in the CLOSING state.\n  return readyState === states.CLOSING\n}\n\n/**\n * @param {number} readyState\n * @returns {boolean}\n */\nfunction isClosed (readyState) {\n  return readyState === states.CLOSED\n}\n\n/**\n * @see https://dom.spec.whatwg.org/#concept-event-fire\n * @param {string} e\n * @param {EventTarget} target\n * @param {(...args: ConstructorParameters<typeof Event>) => Event} eventFactory\n * @param {EventInit | undefined} eventInitDict\n * @returns {void}\n */\nfunction fireEvent (e, target, eventFactory = (type, init) => new Event(type, init), eventInitDict = {}) {\n  // 1. If eventConstructor is not given, then let eventConstructor be Event.\n\n  // 2. Let event be the result of creating an event given eventConstructor,\n  //    in the relevant realm of target.\n  // 3. Initialize event’s type attribute to e.\n  const event = eventFactory(e, eventInitDict)\n\n  // 4. Initialize any other IDL attributes of event as described in the\n  //    invocation of this algorithm.\n\n  // 5. Return the result of dispatching event at target, with legacy target\n  //    override flag set if set.\n  target.dispatchEvent(event)\n}\n\n/**\n * @see https://websockets.spec.whatwg.org/#feedback-from-the-protocol\n * @param {import('./websocket').Handler} handler\n * @param {number} type Opcode\n * @param {Buffer} data application data\n * @returns {void}\n */\nfunction websocketMessageReceived (handler, type, data) {\n  handler.onMessage(type, data)\n}\n\n/**\n * @param {Buffer} buffer\n * @returns {ArrayBuffer}\n */\nfunction toArrayBuffer (buffer) {\n  if (buffer.byteLength === buffer.buffer.byteLength) {\n    return buffer.buffer\n  }\n  return new Uint8Array(buffer).buffer\n}\n\n/**\n * @see https://datatracker.ietf.org/doc/html/rfc6455\n * @see https://datatracker.ietf.org/doc/html/rfc2616\n * @see https://bugs.chromium.org/p/chromium/issues/detail?id=398407\n * @param {string} protocol\n * @returns {boolean}\n */\nfunction isValidSubprotocol (protocol) {\n  // If present, this value indicates one\n  // or more comma-separated subprotocol the client wishes to speak,\n  // ordered by preference.  The elements that comprise this value\n  // MUST be non-empty strings with characters in the range U+0021 to\n  // U+007E not including separator characters as defined in\n  // [RFC2616] and MUST all be unique strings.\n  if (protocol.length === 0) {\n    return false\n  }\n\n  for (let i = 0; i < protocol.length; ++i) {\n    const code = protocol.charCodeAt(i)\n\n    if (\n      code < 0x21 || // CTL, contains SP (0x20) and HT (0x09)\n      code > 0x7E ||\n      code === 0x22 || // \"\n      code === 0x28 || // (\n      code === 0x29 || // )\n      code === 0x2C || // ,\n      code === 0x2F || // /\n      code === 0x3A || // :\n      code === 0x3B || // ;\n      code === 0x3C || // <\n      code === 0x3D || // =\n      code === 0x3E || // >\n      code === 0x3F || // ?\n      code === 0x40 || // @\n      code === 0x5B || // [\n      code === 0x5C || // \\\n      code === 0x5D || // ]\n      code === 0x7B || // {\n      code === 0x7D // }\n    ) {\n      return false\n    }\n  }\n\n  return true\n}\n\n/**\n * @see https://datatracker.ietf.org/doc/html/rfc6455#section-7-4\n * @param {number} code\n * @returns {boolean}\n */\nfunction isValidStatusCode (code) {\n  if (code >= 1000 && code < 1015) {\n    return (\n      code !== 1004 && // reserved\n      code !== 1005 && // \"MUST NOT be set as a status code\"\n      code !== 1006 // \"MUST NOT be set as a status code\"\n    )\n  }\n\n  return code >= 3000 && code <= 4999\n}\n\n/**\n * @see https://datatracker.ietf.org/doc/html/rfc6455#section-5.5\n * @param {number} opcode\n * @returns {boolean}\n */\nfunction isControlFrame (opcode) {\n  return (\n    opcode === opcodes.CLOSE ||\n    opcode === opcodes.PING ||\n    opcode === opcodes.PONG\n  )\n}\n\n/**\n * @param {number} opcode\n * @returns {boolean}\n */\nfunction isContinuationFrame (opcode) {\n  return opcode === opcodes.CONTINUATION\n}\n\n/**\n * @param {number} opcode\n * @returns {boolean}\n */\nfunction isTextBinaryFrame (opcode) {\n  return opcode === opcodes.TEXT || opcode === opcodes.BINARY\n}\n\n/**\n *\n * @param {number} opcode\n * @returns {boolean}\n */\nfunction isValidOpcode (opcode) {\n  return isTextBinaryFrame(opcode) || isContinuationFrame(opcode) || isControlFrame(opcode)\n}\n\n/**\n * Parses a Sec-WebSocket-Extensions header value.\n * @param {string} extensions\n * @returns {Map<string, string>}\n */\n// TODO(@Uzlopak, @KhafraDev): make compliant https://datatracker.ietf.org/doc/html/rfc6455#section-9.1\nfunction parseExtensions (extensions) {\n  const position = { position: 0 }\n  const extensionList = new Map()\n\n  while (position.position < extensions.length) {\n    const pair = collectASequenceOfCodePointsFast(';', extensions, position)\n    const [name, value = ''] = pair.split('=', 2)\n\n    extensionList.set(\n      removeHTTPWhitespace(name, true, false),\n      removeHTTPWhitespace(value, false, true)\n    )\n\n    position.position++\n  }\n\n  return extensionList\n}\n\n/**\n * @see https://www.rfc-editor.org/rfc/rfc7692#section-7.1.2.2\n * @description \"client-max-window-bits = 1*DIGIT\"\n * @param {string} value\n * @returns {boolean}\n */\nfunction isValidClientWindowBits (value) {\n  // Must have at least one character\n  if (value.length === 0) {\n    return false\n  }\n\n  // Check all characters are ASCII digits\n  for (let i = 0; i < value.length; i++) {\n    const byte = value.charCodeAt(i)\n\n    if (byte < 0x30 || byte > 0x39) {\n      return false\n    }\n  }\n\n  // Check numeric range: zlib requires windowBits in range 8-15\n  const num = Number.parseInt(value, 10)\n  return num >= 8 && num <= 15\n}\n\n/**\n * @see https://whatpr.org/websockets/48/7b748d3...d5570f3.html#get-a-url-record\n * @param {string} url\n * @param {string} [baseURL]\n */\nfunction getURLRecord (url, baseURL) {\n  // 1. Let urlRecord be the result of applying the URL parser to url with baseURL .\n  // 2. If urlRecord is failure, then throw a \" SyntaxError \" DOMException .\n  let urlRecord\n\n  try {\n    urlRecord = new URL(url, baseURL)\n  } catch (e) {\n    throw new DOMException(e, 'SyntaxError')\n  }\n\n  // 3. If urlRecord ’s scheme is \" http \", then set urlRecord ’s scheme to \" ws \".\n  // 4. Otherwise, if urlRecord ’s scheme is \" https \", set urlRecord ’s scheme to \" wss \".\n  if (urlRecord.protocol === 'http:') {\n    urlRecord.protocol = 'ws:'\n  } else if (urlRecord.protocol === 'https:') {\n    urlRecord.protocol = 'wss:'\n  }\n\n  // 5. If urlRecord ’s scheme is not \" ws \" or \" wss \", then throw a \" SyntaxError \" DOMException .\n  if (urlRecord.protocol !== 'ws:' && urlRecord.protocol !== 'wss:') {\n    throw new DOMException('expected a ws: or wss: url', 'SyntaxError')\n  }\n\n  // If urlRecord ’s fragment is non-null, then throw a \" SyntaxError \" DOMException .\n  if (urlRecord.hash.length || urlRecord.href.endsWith('#')) {\n    throw new DOMException('hash', 'SyntaxError')\n  }\n\n  // Return urlRecord .\n  return urlRecord\n}\n\n// https://whatpr.org/websockets/48.html#validate-close-code-and-reason\nfunction validateCloseCodeAndReason (code, reason) {\n  // 1. If code is not null, but is neither an integer equal to\n  //    1000 nor an integer in the range 3000 to 4999, inclusive,\n  //    throw an \"InvalidAccessError\" DOMException.\n  if (code !== null) {\n    if (code !== 1000 && (code < 3000 || code > 4999)) {\n      throw new DOMException('invalid code', 'InvalidAccessError')\n    }\n  }\n\n  // 2. If reason is not null, then:\n  if (reason !== null) {\n    // 2.1. Let reasonBytes be the result of UTF-8 encoding reason.\n    // 2.2. If reasonBytes is longer than 123 bytes, then throw a\n    //      \"SyntaxError\" DOMException.\n    const reasonBytesLength = Buffer.byteLength(reason)\n\n    if (reasonBytesLength > 123) {\n      throw new DOMException(`Reason must be less than 123 bytes; received ${reasonBytesLength}`, 'SyntaxError')\n    }\n  }\n}\n\n/**\n * Converts a Buffer to utf-8, even on platforms without icu.\n * @type {(buffer: Buffer) => string}\n */\nconst utf8Decode = (() => {\n  if (typeof process.versions.icu === 'string') {\n    const fatalDecoder = new TextDecoder('utf-8', { fatal: true })\n    return fatalDecoder.decode.bind(fatalDecoder)\n  }\n  return function (buffer) {\n    if (isUtf8(buffer)) {\n      return buffer.toString('utf-8')\n    }\n    throw new TypeError('Invalid utf-8 received.')\n  }\n})()\n\nmodule.exports = {\n  isConnecting,\n  isEstablished,\n  isClosing,\n  isClosed,\n  fireEvent,\n  isValidSubprotocol,\n  isValidStatusCode,\n  websocketMessageReceived,\n  utf8Decode,\n  isControlFrame,\n  isContinuationFrame,\n  isTextBinaryFrame,\n  isValidOpcode,\n  parseExtensions,\n  isValidClientWindowBits,\n  toArrayBuffer,\n  getURLRecord,\n  validateCloseCodeAndReason\n}\n"],"names":["states","opcodes","require$$0","removeHTTPWhitespace","require$$2","collectASequenceOfCodePointsFast","require$$3","isControlFrame","opcode","CLOSE","PING","PONG","isContinuationFrame","CONTINUATION","isTextBinaryFrame","TEXT","BINARY","utf8Decode","fatalDecoder","TextDecoder","fatal","decode","bind","util","isConnecting","readyState","CONNECTING","isEstablished","OPEN","isClosing","CLOSING","isClosed","CLOSED","fireEvent","e","target","eventFactory","type","init","Event","eventInitDict","event","dispatchEvent","isValidSubprotocol","protocol","length","i","code","charCodeAt","isValidStatusCode","websocketMessageReceived","handler","data","onMessage","isValidOpcode","parseExtensions","extensions","position","extensionList","Map","pair","name","value","split","set","isValidClientWindowBits","byte","num","Number","parseInt","toArrayBuffer","buffer","byteLength","Uint8Array","getURLRecord","url","baseURL","urlRecord","URL","DOMException","hash","href","endsWith","validateCloseCodeAndReason","reason","reasonBytesLength","Bu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