freddyaboulton HF staff commited on
Commit
5ac6ee4
1 Parent(s): 384c1a4

Upload folder using huggingface_hub

Browse files
Dockerfile CHANGED
@@ -1,3 +1,4 @@
 
1
  FROM python:3.9
2
 
3
  WORKDIR /code
@@ -6,13 +7,6 @@ COPY --link --chown=1000 . .
6
 
7
  RUN pip install --no-cache-dir -r requirements.txt
8
 
9
- RUN mkdir -p /tmp/cache/
10
- RUN chmod a+rwx -R /tmp/cache/
11
-
12
- RUN apt-get update && apt-get install -y poppler-utils tesseract-ocr chromium
13
-
14
- ENV TRANSFORMERS_CACHE=/tmp/cache/
15
  ENV PYTHONUNBUFFERED=1 GRADIO_ALLOW_FLAGGING=never GRADIO_NUM_PORTS=1 GRADIO_SERVER_NAME=0.0.0.0 GRADIO_SERVER_PORT=7860 SYSTEM=spaces
16
 
17
  CMD ["python", "app.py"]
18
-
 
1
+
2
  FROM python:3.9
3
 
4
  WORKDIR /code
 
7
 
8
  RUN pip install --no-cache-dir -r requirements.txt
9
 
 
 
 
 
 
 
10
  ENV PYTHONUNBUFFERED=1 GRADIO_ALLOW_FLAGGING=never GRADIO_NUM_PORTS=1 GRADIO_SERVER_NAME=0.0.0.0 GRADIO_SERVER_PORT=7860 SYSTEM=spaces
11
 
12
  CMD ["python", "app.py"]
 
README.md CHANGED
@@ -1,9 +1,9 @@
1
 
2
  ---
3
  tags: [gradio-custom-component, gradio-template-Fallback]
4
- title: gradio_pdf V0.0.2
5
- colorFrom: pink
6
- colorTo: blue
7
  sdk: docker
8
  pinned: false
9
  license: apache-2.0
 
1
 
2
  ---
3
  tags: [gradio-custom-component, gradio-template-Fallback]
4
+ title: gradio_pdf V0.0.3
5
+ colorFrom: indigo
6
+ colorTo: gray
7
  sdk: docker
8
  pinned: false
9
  license: apache-2.0
requirements.txt CHANGED
@@ -1,5 +1,5 @@
1
  torch
2
  transformers
3
  pdf2image
4
- gradio_pdf-0.0.2-py3-none-any.whl
5
- pytesseract
 
1
  torch
2
  transformers
3
  pdf2image
4
+ pytesseract
5
+ gradio_pdf-0.0.3-py3-none-any.whl
src/backend/gradio_pdf/pdf.py CHANGED
@@ -7,10 +7,30 @@ from gradio import processing_utils
7
 
8
  class PDF(Component):
9
 
 
 
10
  data_model = FileData
11
 
12
- def __init__(self, value: Any = None, *, height: int | None = None, label: str | None = None, info: str | None = None, show_label: bool | None = None, container: bool = True, scale: int | None = None, min_width: int | None = None, interactive: bool | None = None, visible: bool = True, elem_id: str | None = None, elem_classes: list[str] | str | None = None, render: bool = True, load_fn: Callable[..., Any] | None = None, every: float | None = None):
13
- super().__init__(value, label=label, info=info, show_label=show_label, container=container, scale=scale, min_width=min_width, interactive=interactive, visible=visible, elem_id=elem_id, elem_classes=elem_classes, render=render, load_fn=load_fn, every=every)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
  self.height = height
15
 
16
  def preprocess(self, payload: FileData) -> str:
@@ -22,12 +42,9 @@ class PDF(Component):
22
  return FileData(path=value)
23
 
24
  def example_inputs(self):
25
- return {"foo": "bar"}
26
-
27
- def api_info(self):
28
- return {"type": {}, "description": "any valid json"}
29
 
30
  def as_example(self, input_data: str | None) -> str | None:
31
  if input_data is None:
32
  return None
33
- return processing_utils.move_resource_to_block_cache(input_data, self)
 
7
 
8
  class PDF(Component):
9
 
10
+ EVENTS = ["change", "upload"]
11
+
12
  data_model = FileData
13
 
14
+ def __init__(self, value: Any = None, *,
15
+ height: int | None = None,
16
+ label: str | None = None, info: str | None = None,
17
+ show_label: bool | None = None,
18
+ container: bool = True,
19
+ scale: int | None = None,
20
+ min_width: int | None = None,
21
+ interactive: bool | None = None,
22
+ visible: bool = True,
23
+ elem_id: str | None = None,
24
+ elem_classes: list[str] | str | None = None,
25
+ render: bool = True,
26
+ load_fn: Callable[..., Any] | None = None,
27
+ every: float | None = None):
28
+ super().__init__(value, label=label, info=info,
29
+ show_label=show_label, container=container,
30
+ scale=scale, min_width=min_width,
31
+ interactive=interactive, visible=visible,
32
+ elem_id=elem_id, elem_classes=elem_classes,
33
+ render=render, load_fn=load_fn, every=every)
34
  self.height = height
35
 
36
  def preprocess(self, payload: FileData) -> str:
 
42
  return FileData(path=value)
43
 
44
  def example_inputs(self):
45
+ return "https://gradio-builds.s3.amazonaws.com/assets/pdf-guide/fw9.pdf"
 
 
 
46
 
47
  def as_example(self, input_data: str | None) -> str | None:
48
  if input_data is None:
49
  return None
50
+ return processing_utils.move_resource_to_block_cache(input_data, self)
src/backend/gradio_pdf/pdf.pyi CHANGED
@@ -4,10 +4,30 @@ from gradio.events import Dependency
4
 
5
  class PDF(Component):
6
 
 
 
7
  data_model = FileData
8
 
9
- def __init__(self, value: Any = None, *, height: int | None = None, label: str | None = None, info: str | None = None, show_label: bool | None = None, container: bool = True, scale: int | None = None, min_width: int | None = None, interactive: bool | None = None, visible: bool = True, elem_id: str | None = None, elem_classes: list[str] | str | None = None, render: bool = True, load_fn: Callable[..., Any] | None = None, every: float | None = None):
10
- super().__init__(value, label=label, info=info, show_label=show_label, container=container, scale=scale, min_width=min_width, interactive=interactive, visible=visible, elem_id=elem_id, elem_classes=elem_classes, render=render, load_fn=load_fn, every=every)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
  self.height = height
12
 
13
  def preprocess(self, payload: FileData) -> str:
@@ -19,12 +39,84 @@ class PDF(Component):
19
  return FileData(path=value)
20
 
21
  def example_inputs(self):
22
- return {"foo": "bar"}
23
-
24
- def api_info(self):
25
- return {"type": {}, "description": "any valid json"}
26
 
27
  def as_example(self, input_data: str | None) -> str | None:
28
  if input_data is None:
29
  return None
30
- return processing_utils.move_resource_to_block_cache(input_data, self)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4
 
5
  class PDF(Component):
6
 
7
+ EVENTS = ["change", "upload"]
8
+
9
  data_model = FileData
10
 
11
+ def __init__(self, value: Any = None, *,
12
+ height: int | None = None,
13
+ label: str | None = None, info: str | None = None,
14
+ show_label: bool | None = None,
15
+ container: bool = True,
16
+ scale: int | None = None,
17
+ min_width: int | None = None,
18
+ interactive: bool | None = None,
19
+ visible: bool = True,
20
+ elem_id: str | None = None,
21
+ elem_classes: list[str] | str | None = None,
22
+ render: bool = True,
23
+ load_fn: Callable[..., Any] | None = None,
24
+ every: float | None = None):
25
+ super().__init__(value, label=label, info=info,
26
+ show_label=show_label, container=container,
27
+ scale=scale, min_width=min_width,
28
+ interactive=interactive, visible=visible,
29
+ elem_id=elem_id, elem_classes=elem_classes,
30
+ render=render, load_fn=load_fn, every=every)
31
  self.height = height
32
 
33
  def preprocess(self, payload: FileData) -> str:
 
39
  return FileData(path=value)
40
 
41
  def example_inputs(self):
42
+ return "https://gradio-builds.s3.amazonaws.com/assets/pdf-guide/fw9.pdf"
 
 
 
43
 
44
  def as_example(self, input_data: str | None) -> str | None:
45
  if input_data is None:
46
  return None
47
+ return processing_utils.move_resource_to_block_cache(input_data, self)
48
+
49
+
50
+ def change(self,
51
+ fn: Callable | None,
52
+ inputs: Component | Sequence[Component] | set[Component] | None = None,
53
+ outputs: Component | Sequence[Component] | None = None,
54
+ api_name: str | None | Literal[False] = None,
55
+ status_tracker: None = None,
56
+ scroll_to_output: bool = False,
57
+ show_progress: Literal["full", "minimal", "hidden"] = "full",
58
+ queue: bool | None = None,
59
+ batch: bool = False,
60
+ max_batch_size: int = 4,
61
+ preprocess: bool = True,
62
+ postprocess: bool = True,
63
+ cancels: dict[str, Any] | list[dict[str, Any]] | None = None,
64
+ every: float | None = None,
65
+ trigger_mode: Literal["once", "multiple", "always_last"] | None = None,
66
+ js: str | None = None,) -> Dependency:
67
+ """
68
+ Parameters:
69
+ fn: the function to call when this event is triggered. Often a machine learning model's prediction function. Each parameter of the function corresponds to one input component, and the function should return a single value or a tuple of values, with each element in the tuple corresponding to one output component.
70
+ inputs: List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.
71
+ outputs: List of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list.
72
+ api_name: Defines how the endpoint appears in the API docs. Can be a string, None, or False. If False, the endpoint will not be exposed in the api docs. If set to None, the endpoint will be exposed in the api docs as an unnamed endpoint, although this behavior will be changed in Gradio 4.0. If set to a string, the endpoint will be exposed in the api docs with the given name.
73
+ scroll_to_output: If True, will scroll to output component on completion
74
+ show_progress: If True, will show progress animation while pending
75
+ queue: If True, will place the request on the queue, if the queue has been enabled. If False, will not put this event on the queue, even if the queue has been enabled. If None, will use the queue setting of the gradio app.
76
+ batch: If True, then the function should process a batch of inputs, meaning that it should accept a list of input values for each parameter. The lists should be of equal length (and be up to length `max_batch_size`). The function is then *required* to return a tuple of lists (even if there is only 1 output component), with each list in the tuple corresponding to one output component.
77
+ max_batch_size: Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)
78
+ preprocess: If False, will not run preprocessing of component data before running 'fn' (e.g. leaving it as a base64 string if this method is called with the `Image` component).
79
+ postprocess: If False, will not run postprocessing of component data before returning 'fn' output to the browser.
80
+ cancels: A list of other events to cancel when this listener is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method. Functions that have not yet run (or generators that are iterating) will be cancelled, but functions that are currently running will be allowed to finish.
81
+ every: Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled.
82
+ trigger_mode: If "once" (default for all events except `.change()`) would not allow any submissions while an event is pending. If set to "multiple", unlimited submissions are allowed while pending, and "always_last" (default for `.change()` event) would allow a second submission after the pending event is complete.
83
+ js: Optional frontend js method to run before running 'fn'. Input arguments for js method are values of 'inputs' and 'outputs', return should be a list of values for output components.
84
+ """
85
+ ...
86
+
87
+ def upload(self,
88
+ fn: Callable | None,
89
+ inputs: Component | Sequence[Component] | set[Component] | None = None,
90
+ outputs: Component | Sequence[Component] | None = None,
91
+ api_name: str | None | Literal[False] = None,
92
+ status_tracker: None = None,
93
+ scroll_to_output: bool = False,
94
+ show_progress: Literal["full", "minimal", "hidden"] = "full",
95
+ queue: bool | None = None,
96
+ batch: bool = False,
97
+ max_batch_size: int = 4,
98
+ preprocess: bool = True,
99
+ postprocess: bool = True,
100
+ cancels: dict[str, Any] | list[dict[str, Any]] | None = None,
101
+ every: float | None = None,
102
+ trigger_mode: Literal["once", "multiple", "always_last"] | None = None,
103
+ js: str | None = None,) -> Dependency:
104
+ """
105
+ Parameters:
106
+ fn: the function to call when this event is triggered. Often a machine learning model's prediction function. Each parameter of the function corresponds to one input component, and the function should return a single value or a tuple of values, with each element in the tuple corresponding to one output component.
107
+ inputs: List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.
108
+ outputs: List of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list.
109
+ api_name: Defines how the endpoint appears in the API docs. Can be a string, None, or False. If False, the endpoint will not be exposed in the api docs. If set to None, the endpoint will be exposed in the api docs as an unnamed endpoint, although this behavior will be changed in Gradio 4.0. If set to a string, the endpoint will be exposed in the api docs with the given name.
110
+ scroll_to_output: If True, will scroll to output component on completion
111
+ show_progress: If True, will show progress animation while pending
112
+ queue: If True, will place the request on the queue, if the queue has been enabled. If False, will not put this event on the queue, even if the queue has been enabled. If None, will use the queue setting of the gradio app.
113
+ batch: If True, then the function should process a batch of inputs, meaning that it should accept a list of input values for each parameter. The lists should be of equal length (and be up to length `max_batch_size`). The function is then *required* to return a tuple of lists (even if there is only 1 output component), with each list in the tuple corresponding to one output component.
114
+ max_batch_size: Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)
115
+ preprocess: If False, will not run preprocessing of component data before running 'fn' (e.g. leaving it as a base64 string if this method is called with the `Image` component).
116
+ postprocess: If False, will not run postprocessing of component data before returning 'fn' output to the browser.
117
+ cancels: A list of other events to cancel when this listener is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method. Functions that have not yet run (or generators that are iterating) will be cancelled, but functions that are currently running will be allowed to finish.
118
+ every: Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled.
119
+ trigger_mode: If "once" (default for all events except `.change()`) would not allow any submissions while an event is pending. If set to "multiple", unlimited submissions are allowed while pending, and "always_last" (default for `.change()` event) would allow a second submission after the pending event is complete.
120
+ js: Optional frontend js method to run before running 'fn'. Input arguments for js method are values of 'inputs' and 'outputs', return should be a list of values for output components.
121
+ """
122
+ ...
src/backend/gradio_pdf/templates/component/Index-f4230f0b.js ADDED
The diff for this file is too large to render. See raw diff
 
src/backend/gradio_pdf/templates/component/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { I as f } from "./Index-f36f7747.js";
2
  export {
3
  f as default
4
  };
 
1
+ import { I as f } from "./Index-f4230f0b.js";
2
  export {
3
  f as default
4
  };
src/backend/gradio_pdf/templates/component/wrapper-98f94c21-523a3923.js ADDED
@@ -0,0 +1,2449 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { r as S } from "./Index-f4230f0b.js";
2
+ function z(s) {
3
+ return s && s.__esModule && Object.prototype.hasOwnProperty.call(s, "default") ? s.default : s;
4
+ }
5
+ function gt(s) {
6
+ if (s.__esModule)
7
+ return s;
8
+ var e = s.default;
9
+ if (typeof e == "function") {
10
+ var t = function r() {
11
+ return this instanceof r ? Reflect.construct(e, arguments, this.constructor) : e.apply(this, arguments);
12
+ };
13
+ t.prototype = e.prototype;
14
+ } else
15
+ t = {};
16
+ return Object.defineProperty(t, "__esModule", { value: !0 }), Object.keys(s).forEach(function(r) {
17
+ var i = Object.getOwnPropertyDescriptor(s, r);
18
+ Object.defineProperty(t, r, i.get ? i : {
19
+ enumerable: !0,
20
+ get: function() {
21
+ return s[r];
22
+ }
23
+ });
24
+ }), t;
25
+ }
26
+ const { Duplex: yt } = S;
27
+ function Oe(s) {
28
+ s.emit("close");
29
+ }
30
+ function vt() {
31
+ !this.destroyed && this._writableState.finished && this.destroy();
32
+ }
33
+ function Qe(s) {
34
+ this.removeListener("error", Qe), this.destroy(), this.listenerCount("error") === 0 && this.emit("error", s);
35
+ }
36
+ function St(s, e) {
37
+ let t = !0;
38
+ const r = new yt({
39
+ ...e,
40
+ autoDestroy: !1,
41
+ emitClose: !1,
42
+ objectMode: !1,
43
+ writableObjectMode: !1
44
+ });
45
+ return s.on("message", function(n, o) {
46
+ const l = !o && r._readableState.objectMode ? n.toString() : n;
47
+ r.push(l) || s.pause();
48
+ }), s.once("error", function(n) {
49
+ r.destroyed || (t = !1, r.destroy(n));
50
+ }), s.once("close", function() {
51
+ r.destroyed || r.push(null);
52
+ }), r._destroy = function(i, n) {
53
+ if (s.readyState === s.CLOSED) {
54
+ n(i), process.nextTick(Oe, r);
55
+ return;
56
+ }
57
+ let o = !1;
58
+ s.once("error", function(f) {
59
+ o = !0, n(f);
60
+ }), s.once("close", function() {
61
+ o || n(i), process.nextTick(Oe, r);
62
+ }), t && s.terminate();
63
+ }, r._final = function(i) {
64
+ if (s.readyState === s.CONNECTING) {
65
+ s.once("open", function() {
66
+ r._final(i);
67
+ });
68
+ return;
69
+ }
70
+ s._socket !== null && (s._socket._writableState.finished ? (i(), r._readableState.endEmitted && r.destroy()) : (s._socket.once("finish", function() {
71
+ i();
72
+ }), s.close()));
73
+ }, r._read = function() {
74
+ s.isPaused && s.resume();
75
+ }, r._write = function(i, n, o) {
76
+ if (s.readyState === s.CONNECTING) {
77
+ s.once("open", function() {
78
+ r._write(i, n, o);
79
+ });
80
+ return;
81
+ }
82
+ s.send(i, o);
83
+ }, r.on("end", vt), r.on("error", Qe), r;
84
+ }
85
+ var Et = St;
86
+ const Vs = /* @__PURE__ */ z(Et);
87
+ var te = { exports: {} }, U = {
88
+ BINARY_TYPES: ["nodebuffer", "arraybuffer", "fragments"],
89
+ EMPTY_BUFFER: Buffer.alloc(0),
90
+ GUID: "258EAFA5-E914-47DA-95CA-C5AB0DC85B11",
91
+ kForOnEventAttribute: Symbol("kIsForOnEventAttribute"),
92
+ kListener: Symbol("kListener"),
93
+ kStatusCode: Symbol("status-code"),
94
+ kWebSocket: Symbol("websocket"),
95
+ NOOP: () => {
96
+ }
97
+ }, bt, xt;
98
+ const { EMPTY_BUFFER: kt } = U, Se = Buffer[Symbol.species];
99
+ function wt(s, e) {
100
+ if (s.length === 0)
101
+ return kt;
102
+ if (s.length === 1)
103
+ return s[0];
104
+ const t = Buffer.allocUnsafe(e);
105
+ let r = 0;
106
+ for (let i = 0; i < s.length; i++) {
107
+ const n = s[i];
108
+ t.set(n, r), r += n.length;
109
+ }
110
+ return r < e ? new Se(t.buffer, t.byteOffset, r) : t;
111
+ }
112
+ function Je(s, e, t, r, i) {
113
+ for (let n = 0; n < i; n++)
114
+ t[r + n] = s[n] ^ e[n & 3];
115
+ }
116
+ function et(s, e) {
117
+ for (let t = 0; t < s.length; t++)
118
+ s[t] ^= e[t & 3];
119
+ }
120
+ function Ot(s) {
121
+ return s.length === s.buffer.byteLength ? s.buffer : s.buffer.slice(s.byteOffset, s.byteOffset + s.length);
122
+ }
123
+ function Ee(s) {
124
+ if (Ee.readOnly = !0, Buffer.isBuffer(s))
125
+ return s;
126
+ let e;
127
+ return s instanceof ArrayBuffer ? e = new Se(s) : ArrayBuffer.isView(s) ? e = new Se(s.buffer, s.byteOffset, s.byteLength) : (e = Buffer.from(s), Ee.readOnly = !1), e;
128
+ }
129
+ te.exports = {
130
+ concat: wt,
131
+ mask: Je,
132
+ toArrayBuffer: Ot,
133
+ toBuffer: Ee,
134
+ unmask: et
135
+ };
136
+ if (!process.env.WS_NO_BUFFER_UTIL)
137
+ try {
138
+ const s = require("bufferutil");
139
+ xt = te.exports.mask = function(e, t, r, i, n) {
140
+ n < 48 ? Je(e, t, r, i, n) : s.mask(e, t, r, i, n);
141
+ }, bt = te.exports.unmask = function(e, t) {
142
+ e.length < 32 ? et(e, t) : s.unmask(e, t);
143
+ };
144
+ } catch {
145
+ }
146
+ var ne = te.exports;
147
+ const Ce = Symbol("kDone"), ue = Symbol("kRun");
148
+ let Ct = class {
149
+ /**
150
+ * Creates a new `Limiter`.
151
+ *
152
+ * @param {Number} [concurrency=Infinity] The maximum number of jobs allowed
153
+ * to run concurrently
154
+ */
155
+ constructor(e) {
156
+ this[Ce] = () => {
157
+ this.pending--, this[ue]();
158
+ }, this.concurrency = e || 1 / 0, this.jobs = [], this.pending = 0;
159
+ }
160
+ /**
161
+ * Adds a job to the queue.
162
+ *
163
+ * @param {Function} job The job to run
164
+ * @public
165
+ */
166
+ add(e) {
167
+ this.jobs.push(e), this[ue]();
168
+ }
169
+ /**
170
+ * Removes a job from the queue and runs it if possible.
171
+ *
172
+ * @private
173
+ */
174
+ [ue]() {
175
+ if (this.pending !== this.concurrency && this.jobs.length) {
176
+ const e = this.jobs.shift();
177
+ this.pending++, e(this[Ce]);
178
+ }
179
+ }
180
+ };
181
+ var Tt = Ct;
182
+ const W = S, Te = ne, Lt = Tt, { kStatusCode: tt } = U, Nt = Buffer[Symbol.species], Pt = Buffer.from([0, 0, 255, 255]), se = Symbol("permessage-deflate"), w = Symbol("total-length"), V = Symbol("callback"), C = Symbol("buffers"), J = Symbol("error");
183
+ let K, Rt = class {
184
+ /**
185
+ * Creates a PerMessageDeflate instance.
186
+ *
187
+ * @param {Object} [options] Configuration options
188
+ * @param {(Boolean|Number)} [options.clientMaxWindowBits] Advertise support
189
+ * for, or request, a custom client window size
190
+ * @param {Boolean} [options.clientNoContextTakeover=false] Advertise/
191
+ * acknowledge disabling of client context takeover
192
+ * @param {Number} [options.concurrencyLimit=10] The number of concurrent
193
+ * calls to zlib
194
+ * @param {(Boolean|Number)} [options.serverMaxWindowBits] Request/confirm the
195
+ * use of a custom server window size
196
+ * @param {Boolean} [options.serverNoContextTakeover=false] Request/accept
197
+ * disabling of server context takeover
198
+ * @param {Number} [options.threshold=1024] Size (in bytes) below which
199
+ * messages should not be compressed if context takeover is disabled
200
+ * @param {Object} [options.zlibDeflateOptions] Options to pass to zlib on
201
+ * deflate
202
+ * @param {Object} [options.zlibInflateOptions] Options to pass to zlib on
203
+ * inflate
204
+ * @param {Boolean} [isServer=false] Create the instance in either server or
205
+ * client mode
206
+ * @param {Number} [maxPayload=0] The maximum allowed message length
207
+ */
208
+ constructor(e, t, r) {
209
+ if (this._maxPayload = r | 0, this._options = e || {}, this._threshold = this._options.threshold !== void 0 ? this._options.threshold : 1024, this._isServer = !!t, this._deflate = null, this._inflate = null, this.params = null, !K) {
210
+ const i = this._options.concurrencyLimit !== void 0 ? this._options.concurrencyLimit : 10;
211
+ K = new Lt(i);
212
+ }
213
+ }
214
+ /**
215
+ * @type {String}
216
+ */
217
+ static get extensionName() {
218
+ return "permessage-deflate";
219
+ }
220
+ /**
221
+ * Create an extension negotiation offer.
222
+ *
223
+ * @return {Object} Extension parameters
224
+ * @public
225
+ */
226
+ offer() {
227
+ const e = {};
228
+ return this._options.serverNoContextTakeover && (e.server_no_context_takeover = !0), this._options.clientNoContextTakeover && (e.client_no_context_takeover = !0), this._options.serverMaxWindowBits && (e.server_max_window_bits = this._options.serverMaxWindowBits), this._options.clientMaxWindowBits ? e.client_max_window_bits = this._options.clientMaxWindowBits : this._options.clientMaxWindowBits == null && (e.client_max_window_bits = !0), e;
229
+ }
230
+ /**
231
+ * Accept an extension negotiation offer/response.
232
+ *
233
+ * @param {Array} configurations The extension negotiation offers/reponse
234
+ * @return {Object} Accepted configuration
235
+ * @public
236
+ */
237
+ accept(e) {
238
+ return e = this.normalizeParams(e), this.params = this._isServer ? this.acceptAsServer(e) : this.acceptAsClient(e), this.params;
239
+ }
240
+ /**
241
+ * Releases all resources used by the extension.
242
+ *
243
+ * @public
244
+ */
245
+ cleanup() {
246
+ if (this._inflate && (this._inflate.close(), this._inflate = null), this._deflate) {
247
+ const e = this._deflate[V];
248
+ this._deflate.close(), this._deflate = null, e && e(
249
+ new Error(
250
+ "The deflate stream was closed while data was being processed"
251
+ )
252
+ );
253
+ }
254
+ }
255
+ /**
256
+ * Accept an extension negotiation offer.
257
+ *
258
+ * @param {Array} offers The extension negotiation offers
259
+ * @return {Object} Accepted configuration
260
+ * @private
261
+ */
262
+ acceptAsServer(e) {
263
+ const t = this._options, r = e.find((i) => !(t.serverNoContextTakeover === !1 && i.server_no_context_takeover || i.server_max_window_bits && (t.serverMaxWindowBits === !1 || typeof t.serverMaxWindowBits == "number" && t.serverMaxWindowBits > i.server_max_window_bits) || typeof t.clientMaxWindowBits == "number" && !i.client_max_window_bits));
264
+ if (!r)
265
+ throw new Error("None of the extension offers can be accepted");
266
+ return t.serverNoContextTakeover && (r.server_no_context_takeover = !0), t.clientNoContextTakeover && (r.client_no_context_takeover = !0), typeof t.serverMaxWindowBits == "number" && (r.server_max_window_bits = t.serverMaxWindowBits), typeof t.clientMaxWindowBits == "number" ? r.client_max_window_bits = t.clientMaxWindowBits : (r.client_max_window_bits === !0 || t.clientMaxWindowBits === !1) && delete r.client_max_window_bits, r;
267
+ }
268
+ /**
269
+ * Accept the extension negotiation response.
270
+ *
271
+ * @param {Array} response The extension negotiation response
272
+ * @return {Object} Accepted configuration
273
+ * @private
274
+ */
275
+ acceptAsClient(e) {
276
+ const t = e[0];
277
+ if (this._options.clientNoContextTakeover === !1 && t.client_no_context_takeover)
278
+ throw new Error('Unexpected parameter "client_no_context_takeover"');
279
+ if (!t.client_max_window_bits)
280
+ typeof this._options.clientMaxWindowBits == "number" && (t.client_max_window_bits = this._options.clientMaxWindowBits);
281
+ else if (this._options.clientMaxWindowBits === !1 || typeof this._options.clientMaxWindowBits == "number" && t.client_max_window_bits > this._options.clientMaxWindowBits)
282
+ throw new Error(
283
+ 'Unexpected or invalid parameter "client_max_window_bits"'
284
+ );
285
+ return t;
286
+ }
287
+ /**
288
+ * Normalize parameters.
289
+ *
290
+ * @param {Array} configurations The extension negotiation offers/reponse
291
+ * @return {Array} The offers/response with normalized parameters
292
+ * @private
293
+ */
294
+ normalizeParams(e) {
295
+ return e.forEach((t) => {
296
+ Object.keys(t).forEach((r) => {
297
+ let i = t[r];
298
+ if (i.length > 1)
299
+ throw new Error(`Parameter "${r}" must have only a single value`);
300
+ if (i = i[0], r === "client_max_window_bits") {
301
+ if (i !== !0) {
302
+ const n = +i;
303
+ if (!Number.isInteger(n) || n < 8 || n > 15)
304
+ throw new TypeError(
305
+ `Invalid value for parameter "${r}": ${i}`
306
+ );
307
+ i = n;
308
+ } else if (!this._isServer)
309
+ throw new TypeError(
310
+ `Invalid value for parameter "${r}": ${i}`
311
+ );
312
+ } else if (r === "server_max_window_bits") {
313
+ const n = +i;
314
+ if (!Number.isInteger(n) || n < 8 || n > 15)
315
+ throw new TypeError(
316
+ `Invalid value for parameter "${r}": ${i}`
317
+ );
318
+ i = n;
319
+ } else if (r === "client_no_context_takeover" || r === "server_no_context_takeover") {
320
+ if (i !== !0)
321
+ throw new TypeError(
322
+ `Invalid value for parameter "${r}": ${i}`
323
+ );
324
+ } else
325
+ throw new Error(`Unknown parameter "${r}"`);
326
+ t[r] = i;
327
+ });
328
+ }), e;
329
+ }
330
+ /**
331
+ * Decompress data. Concurrency limited.
332
+ *
333
+ * @param {Buffer} data Compressed data
334
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
335
+ * @param {Function} callback Callback
336
+ * @public
337
+ */
338
+ decompress(e, t, r) {
339
+ K.add((i) => {
340
+ this._decompress(e, t, (n, o) => {
341
+ i(), r(n, o);
342
+ });
343
+ });
344
+ }
345
+ /**
346
+ * Compress data. Concurrency limited.
347
+ *
348
+ * @param {(Buffer|String)} data Data to compress
349
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
350
+ * @param {Function} callback Callback
351
+ * @public
352
+ */
353
+ compress(e, t, r) {
354
+ K.add((i) => {
355
+ this._compress(e, t, (n, o) => {
356
+ i(), r(n, o);
357
+ });
358
+ });
359
+ }
360
+ /**
361
+ * Decompress data.
362
+ *
363
+ * @param {Buffer} data Compressed data
364
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
365
+ * @param {Function} callback Callback
366
+ * @private
367
+ */
368
+ _decompress(e, t, r) {
369
+ const i = this._isServer ? "client" : "server";
370
+ if (!this._inflate) {
371
+ const n = `${i}_max_window_bits`, o = typeof this.params[n] != "number" ? W.Z_DEFAULT_WINDOWBITS : this.params[n];
372
+ this._inflate = W.createInflateRaw({
373
+ ...this._options.zlibInflateOptions,
374
+ windowBits: o
375
+ }), this._inflate[se] = this, this._inflate[w] = 0, this._inflate[C] = [], this._inflate.on("error", Bt), this._inflate.on("data", st);
376
+ }
377
+ this._inflate[V] = r, this._inflate.write(e), t && this._inflate.write(Pt), this._inflate.flush(() => {
378
+ const n = this._inflate[J];
379
+ if (n) {
380
+ this._inflate.close(), this._inflate = null, r(n);
381
+ return;
382
+ }
383
+ const o = Te.concat(
384
+ this._inflate[C],
385
+ this._inflate[w]
386
+ );
387
+ this._inflate._readableState.endEmitted ? (this._inflate.close(), this._inflate = null) : (this._inflate[w] = 0, this._inflate[C] = [], t && this.params[`${i}_no_context_takeover`] && this._inflate.reset()), r(null, o);
388
+ });
389
+ }
390
+ /**
391
+ * Compress data.
392
+ *
393
+ * @param {(Buffer|String)} data Data to compress
394
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
395
+ * @param {Function} callback Callback
396
+ * @private
397
+ */
398
+ _compress(e, t, r) {
399
+ const i = this._isServer ? "server" : "client";
400
+ if (!this._deflate) {
401
+ const n = `${i}_max_window_bits`, o = typeof this.params[n] != "number" ? W.Z_DEFAULT_WINDOWBITS : this.params[n];
402
+ this._deflate = W.createDeflateRaw({
403
+ ...this._options.zlibDeflateOptions,
404
+ windowBits: o
405
+ }), this._deflate[w] = 0, this._deflate[C] = [], this._deflate.on("data", Ut);
406
+ }
407
+ this._deflate[V] = r, this._deflate.write(e), this._deflate.flush(W.Z_SYNC_FLUSH, () => {
408
+ if (!this._deflate)
409
+ return;
410
+ let n = Te.concat(
411
+ this._deflate[C],
412
+ this._deflate[w]
413
+ );
414
+ t && (n = new Nt(n.buffer, n.byteOffset, n.length - 4)), this._deflate[V] = null, this._deflate[w] = 0, this._deflate[C] = [], t && this.params[`${i}_no_context_takeover`] && this._deflate.reset(), r(null, n);
415
+ });
416
+ }
417
+ };
418
+ var oe = Rt;
419
+ function Ut(s) {
420
+ this[C].push(s), this[w] += s.length;
421
+ }
422
+ function st(s) {
423
+ if (this[w] += s.length, this[se]._maxPayload < 1 || this[w] <= this[se]._maxPayload) {
424
+ this[C].push(s);
425
+ return;
426
+ }
427
+ this[J] = new RangeError("Max payload size exceeded"), this[J].code = "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH", this[J][tt] = 1009, this.removeListener("data", st), this.reset();
428
+ }
429
+ function Bt(s) {
430
+ this[se]._inflate = null, s[tt] = 1007, this[V](s);
431
+ }
432
+ var re = { exports: {} };
433
+ const $t = {}, Mt = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
434
+ __proto__: null,
435
+ default: $t
436
+ }, Symbol.toStringTag, { value: "Module" })), It = /* @__PURE__ */ gt(Mt);
437
+ var Le;
438
+ const { isUtf8: Ne } = S, Dt = [
439
+ 0,
440
+ 0,
441
+ 0,
442
+ 0,
443
+ 0,
444
+ 0,
445
+ 0,
446
+ 0,
447
+ 0,
448
+ 0,
449
+ 0,
450
+ 0,
451
+ 0,
452
+ 0,
453
+ 0,
454
+ 0,
455
+ // 0 - 15
456
+ 0,
457
+ 0,
458
+ 0,
459
+ 0,
460
+ 0,
461
+ 0,
462
+ 0,
463
+ 0,
464
+ 0,
465
+ 0,
466
+ 0,
467
+ 0,
468
+ 0,
469
+ 0,
470
+ 0,
471
+ 0,
472
+ // 16 - 31
473
+ 0,
474
+ 1,
475
+ 0,
476
+ 1,
477
+ 1,
478
+ 1,
479
+ 1,
480
+ 1,
481
+ 0,
482
+ 0,
483
+ 1,
484
+ 1,
485
+ 0,
486
+ 1,
487
+ 1,
488
+ 0,
489
+ // 32 - 47
490
+ 1,
491
+ 1,
492
+ 1,
493
+ 1,
494
+ 1,
495
+ 1,
496
+ 1,
497
+ 1,
498
+ 1,
499
+ 1,
500
+ 0,
501
+ 0,
502
+ 0,
503
+ 0,
504
+ 0,
505
+ 0,
506
+ // 48 - 63
507
+ 0,
508
+ 1,
509
+ 1,
510
+ 1,
511
+ 1,
512
+ 1,
513
+ 1,
514
+ 1,
515
+ 1,
516
+ 1,
517
+ 1,
518
+ 1,
519
+ 1,
520
+ 1,
521
+ 1,
522
+ 1,
523
+ // 64 - 79
524
+ 1,
525
+ 1,
526
+ 1,
527
+ 1,
528
+ 1,
529
+ 1,
530
+ 1,
531
+ 1,
532
+ 1,
533
+ 1,
534
+ 1,
535
+ 0,
536
+ 0,
537
+ 0,
538
+ 1,
539
+ 1,
540
+ // 80 - 95
541
+ 1,
542
+ 1,
543
+ 1,
544
+ 1,
545
+ 1,
546
+ 1,
547
+ 1,
548
+ 1,
549
+ 1,
550
+ 1,
551
+ 1,
552
+ 1,
553
+ 1,
554
+ 1,
555
+ 1,
556
+ 1,
557
+ // 96 - 111
558
+ 1,
559
+ 1,
560
+ 1,
561
+ 1,
562
+ 1,
563
+ 1,
564
+ 1,
565
+ 1,
566
+ 1,
567
+ 1,
568
+ 1,
569
+ 0,
570
+ 1,
571
+ 0,
572
+ 1,
573
+ 0
574
+ // 112 - 127
575
+ ];
576
+ function Wt(s) {
577
+ return s >= 1e3 && s <= 1014 && s !== 1004 && s !== 1005 && s !== 1006 || s >= 3e3 && s <= 4999;
578
+ }
579
+ function be(s) {
580
+ const e = s.length;
581
+ let t = 0;
582
+ for (; t < e; )
583
+ if (!(s[t] & 128))
584
+ t++;
585
+ else if ((s[t] & 224) === 192) {
586
+ if (t + 1 === e || (s[t + 1] & 192) !== 128 || (s[t] & 254) === 192)
587
+ return !1;
588
+ t += 2;
589
+ } else if ((s[t] & 240) === 224) {
590
+ if (t + 2 >= e || (s[t + 1] & 192) !== 128 || (s[t + 2] & 192) !== 128 || s[t] === 224 && (s[t + 1] & 224) === 128 || // Overlong
591
+ s[t] === 237 && (s[t + 1] & 224) === 160)
592
+ return !1;
593
+ t += 3;
594
+ } else if ((s[t] & 248) === 240) {
595
+ if (t + 3 >= e || (s[t + 1] & 192) !== 128 || (s[t + 2] & 192) !== 128 || (s[t + 3] & 192) !== 128 || s[t] === 240 && (s[t + 1] & 240) === 128 || // Overlong
596
+ s[t] === 244 && s[t + 1] > 143 || s[t] > 244)
597
+ return !1;
598
+ t += 4;
599
+ } else
600
+ return !1;
601
+ return !0;
602
+ }
603
+ re.exports = {
604
+ isValidStatusCode: Wt,
605
+ isValidUTF8: be,
606
+ tokenChars: Dt
607
+ };
608
+ if (Ne)
609
+ Le = re.exports.isValidUTF8 = function(s) {
610
+ return s.length < 24 ? be(s) : Ne(s);
611
+ };
612
+ else if (!process.env.WS_NO_UTF_8_VALIDATE)
613
+ try {
614
+ const s = It;
615
+ Le = re.exports.isValidUTF8 = function(e) {
616
+ return e.length < 32 ? be(e) : s(e);
617
+ };
618
+ } catch {
619
+ }
620
+ var ae = re.exports;
621
+ const { Writable: At } = S, Pe = oe, {
622
+ BINARY_TYPES: Ft,
623
+ EMPTY_BUFFER: Re,
624
+ kStatusCode: jt,
625
+ kWebSocket: Gt
626
+ } = U, { concat: de, toArrayBuffer: Vt, unmask: Ht } = ne, { isValidStatusCode: zt, isValidUTF8: Ue } = ae, X = Buffer[Symbol.species], A = 0, Be = 1, $e = 2, Me = 3, _e = 4, Yt = 5;
627
+ let qt = class extends At {
628
+ /**
629
+ * Creates a Receiver instance.
630
+ *
631
+ * @param {Object} [options] Options object
632
+ * @param {String} [options.binaryType=nodebuffer] The type for binary data
633
+ * @param {Object} [options.extensions] An object containing the negotiated
634
+ * extensions
635
+ * @param {Boolean} [options.isServer=false] Specifies whether to operate in
636
+ * client or server mode
637
+ * @param {Number} [options.maxPayload=0] The maximum allowed message length
638
+ * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
639
+ * not to skip UTF-8 validation for text and close messages
640
+ */
641
+ constructor(e = {}) {
642
+ super(), this._binaryType = e.binaryType || Ft[0], this._extensions = e.extensions || {}, this._isServer = !!e.isServer, this._maxPayload = e.maxPayload | 0, this._skipUTF8Validation = !!e.skipUTF8Validation, this[Gt] = void 0, this._bufferedBytes = 0, this._buffers = [], this._compressed = !1, this._payloadLength = 0, this._mask = void 0, this._fragmented = 0, this._masked = !1, this._fin = !1, this._opcode = 0, this._totalPayloadLength = 0, this._messageLength = 0, this._fragments = [], this._state = A, this._loop = !1;
643
+ }
644
+ /**
645
+ * Implements `Writable.prototype._write()`.
646
+ *
647
+ * @param {Buffer} chunk The chunk of data to write
648
+ * @param {String} encoding The character encoding of `chunk`
649
+ * @param {Function} cb Callback
650
+ * @private
651
+ */
652
+ _write(e, t, r) {
653
+ if (this._opcode === 8 && this._state == A)
654
+ return r();
655
+ this._bufferedBytes += e.length, this._buffers.push(e), this.startLoop(r);
656
+ }
657
+ /**
658
+ * Consumes `n` bytes from the buffered data.
659
+ *
660
+ * @param {Number} n The number of bytes to consume
661
+ * @return {Buffer} The consumed bytes
662
+ * @private
663
+ */
664
+ consume(e) {
665
+ if (this._bufferedBytes -= e, e === this._buffers[0].length)
666
+ return this._buffers.shift();
667
+ if (e < this._buffers[0].length) {
668
+ const r = this._buffers[0];
669
+ return this._buffers[0] = new X(
670
+ r.buffer,
671
+ r.byteOffset + e,
672
+ r.length - e
673
+ ), new X(r.buffer, r.byteOffset, e);
674
+ }
675
+ const t = Buffer.allocUnsafe(e);
676
+ do {
677
+ const r = this._buffers[0], i = t.length - e;
678
+ e >= r.length ? t.set(this._buffers.shift(), i) : (t.set(new Uint8Array(r.buffer, r.byteOffset, e), i), this._buffers[0] = new X(
679
+ r.buffer,
680
+ r.byteOffset + e,
681
+ r.length - e
682
+ )), e -= r.length;
683
+ } while (e > 0);
684
+ return t;
685
+ }
686
+ /**
687
+ * Starts the parsing loop.
688
+ *
689
+ * @param {Function} cb Callback
690
+ * @private
691
+ */
692
+ startLoop(e) {
693
+ let t;
694
+ this._loop = !0;
695
+ do
696
+ switch (this._state) {
697
+ case A:
698
+ t = this.getInfo();
699
+ break;
700
+ case Be:
701
+ t = this.getPayloadLength16();
702
+ break;
703
+ case $e:
704
+ t = this.getPayloadLength64();
705
+ break;
706
+ case Me:
707
+ this.getMask();
708
+ break;
709
+ case _e:
710
+ t = this.getData(e);
711
+ break;
712
+ default:
713
+ this._loop = !1;
714
+ return;
715
+ }
716
+ while (this._loop);
717
+ e(t);
718
+ }
719
+ /**
720
+ * Reads the first two bytes of a frame.
721
+ *
722
+ * @return {(RangeError|undefined)} A possible error
723
+ * @private
724
+ */
725
+ getInfo() {
726
+ if (this._bufferedBytes < 2) {
727
+ this._loop = !1;
728
+ return;
729
+ }
730
+ const e = this.consume(2);
731
+ if (e[0] & 48)
732
+ return this._loop = !1, g(
733
+ RangeError,
734
+ "RSV2 and RSV3 must be clear",
735
+ !0,
736
+ 1002,
737
+ "WS_ERR_UNEXPECTED_RSV_2_3"
738
+ );
739
+ const t = (e[0] & 64) === 64;
740
+ if (t && !this._extensions[Pe.extensionName])
741
+ return this._loop = !1, g(
742
+ RangeError,
743
+ "RSV1 must be clear",
744
+ !0,
745
+ 1002,
746
+ "WS_ERR_UNEXPECTED_RSV_1"
747
+ );
748
+ if (this._fin = (e[0] & 128) === 128, this._opcode = e[0] & 15, this._payloadLength = e[1] & 127, this._opcode === 0) {
749
+ if (t)
750
+ return this._loop = !1, g(
751
+ RangeError,
752
+ "RSV1 must be clear",
753
+ !0,
754
+ 1002,
755
+ "WS_ERR_UNEXPECTED_RSV_1"
756
+ );
757
+ if (!this._fragmented)
758
+ return this._loop = !1, g(
759
+ RangeError,
760
+ "invalid opcode 0",
761
+ !0,
762
+ 1002,
763
+ "WS_ERR_INVALID_OPCODE"
764
+ );
765
+ this._opcode = this._fragmented;
766
+ } else if (this._opcode === 1 || this._opcode === 2) {
767
+ if (this._fragmented)
768
+ return this._loop = !1, g(
769
+ RangeError,
770
+ `invalid opcode ${this._opcode}`,
771
+ !0,
772
+ 1002,
773
+ "WS_ERR_INVALID_OPCODE"
774
+ );
775
+ this._compressed = t;
776
+ } else if (this._opcode > 7 && this._opcode < 11) {
777
+ if (!this._fin)
778
+ return this._loop = !1, g(
779
+ RangeError,
780
+ "FIN must be set",
781
+ !0,
782
+ 1002,
783
+ "WS_ERR_EXPECTED_FIN"
784
+ );
785
+ if (t)
786
+ return this._loop = !1, g(
787
+ RangeError,
788
+ "RSV1 must be clear",
789
+ !0,
790
+ 1002,
791
+ "WS_ERR_UNEXPECTED_RSV_1"
792
+ );
793
+ if (this._payloadLength > 125 || this._opcode === 8 && this._payloadLength === 1)
794
+ return this._loop = !1, g(
795
+ RangeError,
796
+ `invalid payload length ${this._payloadLength}`,
797
+ !0,
798
+ 1002,
799
+ "WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH"
800
+ );
801
+ } else
802
+ return this._loop = !1, g(
803
+ RangeError,
804
+ `invalid opcode ${this._opcode}`,
805
+ !0,
806
+ 1002,
807
+ "WS_ERR_INVALID_OPCODE"
808
+ );
809
+ if (!this._fin && !this._fragmented && (this._fragmented = this._opcode), this._masked = (e[1] & 128) === 128, this._isServer) {
810
+ if (!this._masked)
811
+ return this._loop = !1, g(
812
+ RangeError,
813
+ "MASK must be set",
814
+ !0,
815
+ 1002,
816
+ "WS_ERR_EXPECTED_MASK"
817
+ );
818
+ } else if (this._masked)
819
+ return this._loop = !1, g(
820
+ RangeError,
821
+ "MASK must be clear",
822
+ !0,
823
+ 1002,
824
+ "WS_ERR_UNEXPECTED_MASK"
825
+ );
826
+ if (this._payloadLength === 126)
827
+ this._state = Be;
828
+ else if (this._payloadLength === 127)
829
+ this._state = $e;
830
+ else
831
+ return this.haveLength();
832
+ }
833
+ /**
834
+ * Gets extended payload length (7+16).
835
+ *
836
+ * @return {(RangeError|undefined)} A possible error
837
+ * @private
838
+ */
839
+ getPayloadLength16() {
840
+ if (this._bufferedBytes < 2) {
841
+ this._loop = !1;
842
+ return;
843
+ }
844
+ return this._payloadLength = this.consume(2).readUInt16BE(0), this.haveLength();
845
+ }
846
+ /**
847
+ * Gets extended payload length (7+64).
848
+ *
849
+ * @return {(RangeError|undefined)} A possible error
850
+ * @private
851
+ */
852
+ getPayloadLength64() {
853
+ if (this._bufferedBytes < 8) {
854
+ this._loop = !1;
855
+ return;
856
+ }
857
+ const e = this.consume(8), t = e.readUInt32BE(0);
858
+ return t > Math.pow(2, 53 - 32) - 1 ? (this._loop = !1, g(
859
+ RangeError,
860
+ "Unsupported WebSocket frame: payload length > 2^53 - 1",
861
+ !1,
862
+ 1009,
863
+ "WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH"
864
+ )) : (this._payloadLength = t * Math.pow(2, 32) + e.readUInt32BE(4), this.haveLength());
865
+ }
866
+ /**
867
+ * Payload length has been read.
868
+ *
869
+ * @return {(RangeError|undefined)} A possible error
870
+ * @private
871
+ */
872
+ haveLength() {
873
+ if (this._payloadLength && this._opcode < 8 && (this._totalPayloadLength += this._payloadLength, this._totalPayloadLength > this._maxPayload && this._maxPayload > 0))
874
+ return this._loop = !1, g(
875
+ RangeError,
876
+ "Max payload size exceeded",
877
+ !1,
878
+ 1009,
879
+ "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"
880
+ );
881
+ this._masked ? this._state = Me : this._state = _e;
882
+ }
883
+ /**
884
+ * Reads mask bytes.
885
+ *
886
+ * @private
887
+ */
888
+ getMask() {
889
+ if (this._bufferedBytes < 4) {
890
+ this._loop = !1;
891
+ return;
892
+ }
893
+ this._mask = this.consume(4), this._state = _e;
894
+ }
895
+ /**
896
+ * Reads data bytes.
897
+ *
898
+ * @param {Function} cb Callback
899
+ * @return {(Error|RangeError|undefined)} A possible error
900
+ * @private
901
+ */
902
+ getData(e) {
903
+ let t = Re;
904
+ if (this._payloadLength) {
905
+ if (this._bufferedBytes < this._payloadLength) {
906
+ this._loop = !1;
907
+ return;
908
+ }
909
+ t = this.consume(this._payloadLength), this._masked && this._mask[0] | this._mask[1] | this._mask[2] | this._mask[3] && Ht(t, this._mask);
910
+ }
911
+ if (this._opcode > 7)
912
+ return this.controlMessage(t);
913
+ if (this._compressed) {
914
+ this._state = Yt, this.decompress(t, e);
915
+ return;
916
+ }
917
+ return t.length && (this._messageLength = this._totalPayloadLength, this._fragments.push(t)), this.dataMessage();
918
+ }
919
+ /**
920
+ * Decompresses data.
921
+ *
922
+ * @param {Buffer} data Compressed data
923
+ * @param {Function} cb Callback
924
+ * @private
925
+ */
926
+ decompress(e, t) {
927
+ this._extensions[Pe.extensionName].decompress(e, this._fin, (i, n) => {
928
+ if (i)
929
+ return t(i);
930
+ if (n.length) {
931
+ if (this._messageLength += n.length, this._messageLength > this._maxPayload && this._maxPayload > 0)
932
+ return t(
933
+ g(
934
+ RangeError,
935
+ "Max payload size exceeded",
936
+ !1,
937
+ 1009,
938
+ "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"
939
+ )
940
+ );
941
+ this._fragments.push(n);
942
+ }
943
+ const o = this.dataMessage();
944
+ if (o)
945
+ return t(o);
946
+ this.startLoop(t);
947
+ });
948
+ }
949
+ /**
950
+ * Handles a data message.
951
+ *
952
+ * @return {(Error|undefined)} A possible error
953
+ * @private
954
+ */
955
+ dataMessage() {
956
+ if (this._fin) {
957
+ const e = this._messageLength, t = this._fragments;
958
+ if (this._totalPayloadLength = 0, this._messageLength = 0, this._fragmented = 0, this._fragments = [], this._opcode === 2) {
959
+ let r;
960
+ this._binaryType === "nodebuffer" ? r = de(t, e) : this._binaryType === "arraybuffer" ? r = Vt(de(t, e)) : r = t, this.emit("message", r, !0);
961
+ } else {
962
+ const r = de(t, e);
963
+ if (!this._skipUTF8Validation && !Ue(r))
964
+ return this._loop = !1, g(
965
+ Error,
966
+ "invalid UTF-8 sequence",
967
+ !0,
968
+ 1007,
969
+ "WS_ERR_INVALID_UTF8"
970
+ );
971
+ this.emit("message", r, !1);
972
+ }
973
+ }
974
+ this._state = A;
975
+ }
976
+ /**
977
+ * Handles a control message.
978
+ *
979
+ * @param {Buffer} data Data to handle
980
+ * @return {(Error|RangeError|undefined)} A possible error
981
+ * @private
982
+ */
983
+ controlMessage(e) {
984
+ if (this._opcode === 8)
985
+ if (this._loop = !1, e.length === 0)
986
+ this.emit("conclude", 1005, Re), this.end();
987
+ else {
988
+ const t = e.readUInt16BE(0);
989
+ if (!zt(t))
990
+ return g(
991
+ RangeError,
992
+ `invalid status code ${t}`,
993
+ !0,
994
+ 1002,
995
+ "WS_ERR_INVALID_CLOSE_CODE"
996
+ );
997
+ const r = new X(
998
+ e.buffer,
999
+ e.byteOffset + 2,
1000
+ e.length - 2
1001
+ );
1002
+ if (!this._skipUTF8Validation && !Ue(r))
1003
+ return g(
1004
+ Error,
1005
+ "invalid UTF-8 sequence",
1006
+ !0,
1007
+ 1007,
1008
+ "WS_ERR_INVALID_UTF8"
1009
+ );
1010
+ this.emit("conclude", t, r), this.end();
1011
+ }
1012
+ else
1013
+ this._opcode === 9 ? this.emit("ping", e) : this.emit("pong", e);
1014
+ this._state = A;
1015
+ }
1016
+ };
1017
+ var rt = qt;
1018
+ function g(s, e, t, r, i) {
1019
+ const n = new s(
1020
+ t ? `Invalid WebSocket frame: ${e}` : e
1021
+ );
1022
+ return Error.captureStackTrace(n, g), n.code = i, n[jt] = r, n;
1023
+ }
1024
+ const qs = /* @__PURE__ */ z(rt), { randomFillSync: Kt } = S, Ie = oe, { EMPTY_BUFFER: Xt } = U, { isValidStatusCode: Zt } = ae, { mask: De, toBuffer: M } = ne, x = Symbol("kByteLength"), Qt = Buffer.alloc(4);
1025
+ let Jt = class P {
1026
+ /**
1027
+ * Creates a Sender instance.
1028
+ *
1029
+ * @param {(net.Socket|tls.Socket)} socket The connection socket
1030
+ * @param {Object} [extensions] An object containing the negotiated extensions
1031
+ * @param {Function} [generateMask] The function used to generate the masking
1032
+ * key
1033
+ */
1034
+ constructor(e, t, r) {
1035
+ this._extensions = t || {}, r && (this._generateMask = r, this._maskBuffer = Buffer.alloc(4)), this._socket = e, this._firstFragment = !0, this._compress = !1, this._bufferedBytes = 0, this._deflating = !1, this._queue = [];
1036
+ }
1037
+ /**
1038
+ * Frames a piece of data according to the HyBi WebSocket protocol.
1039
+ *
1040
+ * @param {(Buffer|String)} data The data to frame
1041
+ * @param {Object} options Options object
1042
+ * @param {Boolean} [options.fin=false] Specifies whether or not to set the
1043
+ * FIN bit
1044
+ * @param {Function} [options.generateMask] The function used to generate the
1045
+ * masking key
1046
+ * @param {Boolean} [options.mask=false] Specifies whether or not to mask
1047
+ * `data`
1048
+ * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
1049
+ * key
1050
+ * @param {Number} options.opcode The opcode
1051
+ * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
1052
+ * modified
1053
+ * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
1054
+ * RSV1 bit
1055
+ * @return {(Buffer|String)[]} The framed data
1056
+ * @public
1057
+ */
1058
+ static frame(e, t) {
1059
+ let r, i = !1, n = 2, o = !1;
1060
+ t.mask && (r = t.maskBuffer || Qt, t.generateMask ? t.generateMask(r) : Kt(r, 0, 4), o = (r[0] | r[1] | r[2] | r[3]) === 0, n = 6);
1061
+ let l;
1062
+ typeof e == "string" ? (!t.mask || o) && t[x] !== void 0 ? l = t[x] : (e = Buffer.from(e), l = e.length) : (l = e.length, i = t.mask && t.readOnly && !o);
1063
+ let f = l;
1064
+ l >= 65536 ? (n += 8, f = 127) : l > 125 && (n += 2, f = 126);
1065
+ const a = Buffer.allocUnsafe(i ? l + n : n);
1066
+ return a[0] = t.fin ? t.opcode | 128 : t.opcode, t.rsv1 && (a[0] |= 64), a[1] = f, f === 126 ? a.writeUInt16BE(l, 2) : f === 127 && (a[2] = a[3] = 0, a.writeUIntBE(l, 4, 6)), t.mask ? (a[1] |= 128, a[n - 4] = r[0], a[n - 3] = r[1], a[n - 2] = r[2], a[n - 1] = r[3], o ? [a, e] : i ? (De(e, r, a, n, l), [a]) : (De(e, r, e, 0, l), [a, e])) : [a, e];
1067
+ }
1068
+ /**
1069
+ * Sends a close message to the other peer.
1070
+ *
1071
+ * @param {Number} [code] The status code component of the body
1072
+ * @param {(String|Buffer)} [data] The message component of the body
1073
+ * @param {Boolean} [mask=false] Specifies whether or not to mask the message
1074
+ * @param {Function} [cb] Callback
1075
+ * @public
1076
+ */
1077
+ close(e, t, r, i) {
1078
+ let n;
1079
+ if (e === void 0)
1080
+ n = Xt;
1081
+ else {
1082
+ if (typeof e != "number" || !Zt(e))
1083
+ throw new TypeError("First argument must be a valid error code number");
1084
+ if (t === void 0 || !t.length)
1085
+ n = Buffer.allocUnsafe(2), n.writeUInt16BE(e, 0);
1086
+ else {
1087
+ const l = Buffer.byteLength(t);
1088
+ if (l > 123)
1089
+ throw new RangeError("The message must not be greater than 123 bytes");
1090
+ n = Buffer.allocUnsafe(2 + l), n.writeUInt16BE(e, 0), typeof t == "string" ? n.write(t, 2) : n.set(t, 2);
1091
+ }
1092
+ }
1093
+ const o = {
1094
+ [x]: n.length,
1095
+ fin: !0,
1096
+ generateMask: this._generateMask,
1097
+ mask: r,
1098
+ maskBuffer: this._maskBuffer,
1099
+ opcode: 8,
1100
+ readOnly: !1,
1101
+ rsv1: !1
1102
+ };
1103
+ this._deflating ? this.enqueue([this.dispatch, n, !1, o, i]) : this.sendFrame(P.frame(n, o), i);
1104
+ }
1105
+ /**
1106
+ * Sends a ping message to the other peer.
1107
+ *
1108
+ * @param {*} data The message to send
1109
+ * @param {Boolean} [mask=false] Specifies whether or not to mask `data`
1110
+ * @param {Function} [cb] Callback
1111
+ * @public
1112
+ */
1113
+ ping(e, t, r) {
1114
+ let i, n;
1115
+ if (typeof e == "string" ? (i = Buffer.byteLength(e), n = !1) : (e = M(e), i = e.length, n = M.readOnly), i > 125)
1116
+ throw new RangeError("The data size must not be greater than 125 bytes");
1117
+ const o = {
1118
+ [x]: i,
1119
+ fin: !0,
1120
+ generateMask: this._generateMask,
1121
+ mask: t,
1122
+ maskBuffer: this._maskBuffer,
1123
+ opcode: 9,
1124
+ readOnly: n,
1125
+ rsv1: !1
1126
+ };
1127
+ this._deflating ? this.enqueue([this.dispatch, e, !1, o, r]) : this.sendFrame(P.frame(e, o), r);
1128
+ }
1129
+ /**
1130
+ * Sends a pong message to the other peer.
1131
+ *
1132
+ * @param {*} data The message to send
1133
+ * @param {Boolean} [mask=false] Specifies whether or not to mask `data`
1134
+ * @param {Function} [cb] Callback
1135
+ * @public
1136
+ */
1137
+ pong(e, t, r) {
1138
+ let i, n;
1139
+ if (typeof e == "string" ? (i = Buffer.byteLength(e), n = !1) : (e = M(e), i = e.length, n = M.readOnly), i > 125)
1140
+ throw new RangeError("The data size must not be greater than 125 bytes");
1141
+ const o = {
1142
+ [x]: i,
1143
+ fin: !0,
1144
+ generateMask: this._generateMask,
1145
+ mask: t,
1146
+ maskBuffer: this._maskBuffer,
1147
+ opcode: 10,
1148
+ readOnly: n,
1149
+ rsv1: !1
1150
+ };
1151
+ this._deflating ? this.enqueue([this.dispatch, e, !1, o, r]) : this.sendFrame(P.frame(e, o), r);
1152
+ }
1153
+ /**
1154
+ * Sends a data message to the other peer.
1155
+ *
1156
+ * @param {*} data The message to send
1157
+ * @param {Object} options Options object
1158
+ * @param {Boolean} [options.binary=false] Specifies whether `data` is binary
1159
+ * or text
1160
+ * @param {Boolean} [options.compress=false] Specifies whether or not to
1161
+ * compress `data`
1162
+ * @param {Boolean} [options.fin=false] Specifies whether the fragment is the
1163
+ * last one
1164
+ * @param {Boolean} [options.mask=false] Specifies whether or not to mask
1165
+ * `data`
1166
+ * @param {Function} [cb] Callback
1167
+ * @public
1168
+ */
1169
+ send(e, t, r) {
1170
+ const i = this._extensions[Ie.extensionName];
1171
+ let n = t.binary ? 2 : 1, o = t.compress, l, f;
1172
+ if (typeof e == "string" ? (l = Buffer.byteLength(e), f = !1) : (e = M(e), l = e.length, f = M.readOnly), this._firstFragment ? (this._firstFragment = !1, o && i && i.params[i._isServer ? "server_no_context_takeover" : "client_no_context_takeover"] && (o = l >= i._threshold), this._compress = o) : (o = !1, n = 0), t.fin && (this._firstFragment = !0), i) {
1173
+ const a = {
1174
+ [x]: l,
1175
+ fin: t.fin,
1176
+ generateMask: this._generateMask,
1177
+ mask: t.mask,
1178
+ maskBuffer: this._maskBuffer,
1179
+ opcode: n,
1180
+ readOnly: f,
1181
+ rsv1: o
1182
+ };
1183
+ this._deflating ? this.enqueue([this.dispatch, e, this._compress, a, r]) : this.dispatch(e, this._compress, a, r);
1184
+ } else
1185
+ this.sendFrame(
1186
+ P.frame(e, {
1187
+ [x]: l,
1188
+ fin: t.fin,
1189
+ generateMask: this._generateMask,
1190
+ mask: t.mask,
1191
+ maskBuffer: this._maskBuffer,
1192
+ opcode: n,
1193
+ readOnly: f,
1194
+ rsv1: !1
1195
+ }),
1196
+ r
1197
+ );
1198
+ }
1199
+ /**
1200
+ * Dispatches a message.
1201
+ *
1202
+ * @param {(Buffer|String)} data The message to send
1203
+ * @param {Boolean} [compress=false] Specifies whether or not to compress
1204
+ * `data`
1205
+ * @param {Object} options Options object
1206
+ * @param {Boolean} [options.fin=false] Specifies whether or not to set the
1207
+ * FIN bit
1208
+ * @param {Function} [options.generateMask] The function used to generate the
1209
+ * masking key
1210
+ * @param {Boolean} [options.mask=false] Specifies whether or not to mask
1211
+ * `data`
1212
+ * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
1213
+ * key
1214
+ * @param {Number} options.opcode The opcode
1215
+ * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
1216
+ * modified
1217
+ * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
1218
+ * RSV1 bit
1219
+ * @param {Function} [cb] Callback
1220
+ * @private
1221
+ */
1222
+ dispatch(e, t, r, i) {
1223
+ if (!t) {
1224
+ this.sendFrame(P.frame(e, r), i);
1225
+ return;
1226
+ }
1227
+ const n = this._extensions[Ie.extensionName];
1228
+ this._bufferedBytes += r[x], this._deflating = !0, n.compress(e, r.fin, (o, l) => {
1229
+ if (this._socket.destroyed) {
1230
+ const f = new Error(
1231
+ "The socket was closed while data was being compressed"
1232
+ );
1233
+ typeof i == "function" && i(f);
1234
+ for (let a = 0; a < this._queue.length; a++) {
1235
+ const c = this._queue[a], h = c[c.length - 1];
1236
+ typeof h == "function" && h(f);
1237
+ }
1238
+ return;
1239
+ }
1240
+ this._bufferedBytes -= r[x], this._deflating = !1, r.readOnly = !1, this.sendFrame(P.frame(l, r), i), this.dequeue();
1241
+ });
1242
+ }
1243
+ /**
1244
+ * Executes queued send operations.
1245
+ *
1246
+ * @private
1247
+ */
1248
+ dequeue() {
1249
+ for (; !this._deflating && this._queue.length; ) {
1250
+ const e = this._queue.shift();
1251
+ this._bufferedBytes -= e[3][x], Reflect.apply(e[0], this, e.slice(1));
1252
+ }
1253
+ }
1254
+ /**
1255
+ * Enqueues a send operation.
1256
+ *
1257
+ * @param {Array} params Send operation parameters.
1258
+ * @private
1259
+ */
1260
+ enqueue(e) {
1261
+ this._bufferedBytes += e[3][x], this._queue.push(e);
1262
+ }
1263
+ /**
1264
+ * Sends a frame.
1265
+ *
1266
+ * @param {Buffer[]} list The frame to send
1267
+ * @param {Function} [cb] Callback
1268
+ * @private
1269
+ */
1270
+ sendFrame(e, t) {
1271
+ e.length === 2 ? (this._socket.cork(), this._socket.write(e[0]), this._socket.write(e[1], t), this._socket.uncork()) : this._socket.write(e[0], t);
1272
+ }
1273
+ };
1274
+ var it = Jt;
1275
+ const Ks = /* @__PURE__ */ z(it), { kForOnEventAttribute: F, kListener: pe } = U, We = Symbol("kCode"), Ae = Symbol("kData"), Fe = Symbol("kError"), je = Symbol("kMessage"), Ge = Symbol("kReason"), I = Symbol("kTarget"), Ve = Symbol("kType"), He = Symbol("kWasClean");
1276
+ class B {
1277
+ /**
1278
+ * Create a new `Event`.
1279
+ *
1280
+ * @param {String} type The name of the event
1281
+ * @throws {TypeError} If the `type` argument is not specified
1282
+ */
1283
+ constructor(e) {
1284
+ this[I] = null, this[Ve] = e;
1285
+ }
1286
+ /**
1287
+ * @type {*}
1288
+ */
1289
+ get target() {
1290
+ return this[I];
1291
+ }
1292
+ /**
1293
+ * @type {String}
1294
+ */
1295
+ get type() {
1296
+ return this[Ve];
1297
+ }
1298
+ }
1299
+ Object.defineProperty(B.prototype, "target", { enumerable: !0 });
1300
+ Object.defineProperty(B.prototype, "type", { enumerable: !0 });
1301
+ class Y extends B {
1302
+ /**
1303
+ * Create a new `CloseEvent`.
1304
+ *
1305
+ * @param {String} type The name of the event
1306
+ * @param {Object} [options] A dictionary object that allows for setting
1307
+ * attributes via object members of the same name
1308
+ * @param {Number} [options.code=0] The status code explaining why the
1309
+ * connection was closed
1310
+ * @param {String} [options.reason=''] A human-readable string explaining why
1311
+ * the connection was closed
1312
+ * @param {Boolean} [options.wasClean=false] Indicates whether or not the
1313
+ * connection was cleanly closed
1314
+ */
1315
+ constructor(e, t = {}) {
1316
+ super(e), this[We] = t.code === void 0 ? 0 : t.code, this[Ge] = t.reason === void 0 ? "" : t.reason, this[He] = t.wasClean === void 0 ? !1 : t.wasClean;
1317
+ }
1318
+ /**
1319
+ * @type {Number}
1320
+ */
1321
+ get code() {
1322
+ return this[We];
1323
+ }
1324
+ /**
1325
+ * @type {String}
1326
+ */
1327
+ get reason() {
1328
+ return this[Ge];
1329
+ }
1330
+ /**
1331
+ * @type {Boolean}
1332
+ */
1333
+ get wasClean() {
1334
+ return this[He];
1335
+ }
1336
+ }
1337
+ Object.defineProperty(Y.prototype, "code", { enumerable: !0 });
1338
+ Object.defineProperty(Y.prototype, "reason", { enumerable: !0 });
1339
+ Object.defineProperty(Y.prototype, "wasClean", { enumerable: !0 });
1340
+ class le extends B {
1341
+ /**
1342
+ * Create a new `ErrorEvent`.
1343
+ *
1344
+ * @param {String} type The name of the event
1345
+ * @param {Object} [options] A dictionary object that allows for setting
1346
+ * attributes via object members of the same name
1347
+ * @param {*} [options.error=null] The error that generated this event
1348
+ * @param {String} [options.message=''] The error message
1349
+ */
1350
+ constructor(e, t = {}) {
1351
+ super(e), this[Fe] = t.error === void 0 ? null : t.error, this[je] = t.message === void 0 ? "" : t.message;
1352
+ }
1353
+ /**
1354
+ * @type {*}
1355
+ */
1356
+ get error() {
1357
+ return this[Fe];
1358
+ }
1359
+ /**
1360
+ * @type {String}
1361
+ */
1362
+ get message() {
1363
+ return this[je];
1364
+ }
1365
+ }
1366
+ Object.defineProperty(le.prototype, "error", { enumerable: !0 });
1367
+ Object.defineProperty(le.prototype, "message", { enumerable: !0 });
1368
+ class xe extends B {
1369
+ /**
1370
+ * Create a new `MessageEvent`.
1371
+ *
1372
+ * @param {String} type The name of the event
1373
+ * @param {Object} [options] A dictionary object that allows for setting
1374
+ * attributes via object members of the same name
1375
+ * @param {*} [options.data=null] The message content
1376
+ */
1377
+ constructor(e, t = {}) {
1378
+ super(e), this[Ae] = t.data === void 0 ? null : t.data;
1379
+ }
1380
+ /**
1381
+ * @type {*}
1382
+ */
1383
+ get data() {
1384
+ return this[Ae];
1385
+ }
1386
+ }
1387
+ Object.defineProperty(xe.prototype, "data", { enumerable: !0 });
1388
+ const es = {
1389
+ /**
1390
+ * Register an event listener.
1391
+ *
1392
+ * @param {String} type A string representing the event type to listen for
1393
+ * @param {(Function|Object)} handler The listener to add
1394
+ * @param {Object} [options] An options object specifies characteristics about
1395
+ * the event listener
1396
+ * @param {Boolean} [options.once=false] A `Boolean` indicating that the
1397
+ * listener should be invoked at most once after being added. If `true`,
1398
+ * the listener would be automatically removed when invoked.
1399
+ * @public
1400
+ */
1401
+ addEventListener(s, e, t = {}) {
1402
+ for (const i of this.listeners(s))
1403
+ if (!t[F] && i[pe] === e && !i[F])
1404
+ return;
1405
+ let r;
1406
+ if (s === "message")
1407
+ r = function(n, o) {
1408
+ const l = new xe("message", {
1409
+ data: o ? n : n.toString()
1410
+ });
1411
+ l[I] = this, Z(e, this, l);
1412
+ };
1413
+ else if (s === "close")
1414
+ r = function(n, o) {
1415
+ const l = new Y("close", {
1416
+ code: n,
1417
+ reason: o.toString(),
1418
+ wasClean: this._closeFrameReceived && this._closeFrameSent
1419
+ });
1420
+ l[I] = this, Z(e, this, l);
1421
+ };
1422
+ else if (s === "error")
1423
+ r = function(n) {
1424
+ const o = new le("error", {
1425
+ error: n,
1426
+ message: n.message
1427
+ });
1428
+ o[I] = this, Z(e, this, o);
1429
+ };
1430
+ else if (s === "open")
1431
+ r = function() {
1432
+ const n = new B("open");
1433
+ n[I] = this, Z(e, this, n);
1434
+ };
1435
+ else
1436
+ return;
1437
+ r[F] = !!t[F], r[pe] = e, t.once ? this.once(s, r) : this.on(s, r);
1438
+ },
1439
+ /**
1440
+ * Remove an event listener.
1441
+ *
1442
+ * @param {String} type A string representing the event type to remove
1443
+ * @param {(Function|Object)} handler The listener to remove
1444
+ * @public
1445
+ */
1446
+ removeEventListener(s, e) {
1447
+ for (const t of this.listeners(s))
1448
+ if (t[pe] === e && !t[F]) {
1449
+ this.removeListener(s, t);
1450
+ break;
1451
+ }
1452
+ }
1453
+ };
1454
+ var ts = {
1455
+ CloseEvent: Y,
1456
+ ErrorEvent: le,
1457
+ Event: B,
1458
+ EventTarget: es,
1459
+ MessageEvent: xe
1460
+ };
1461
+ function Z(s, e, t) {
1462
+ typeof s == "object" && s.handleEvent ? s.handleEvent.call(s, t) : s.call(e, t);
1463
+ }
1464
+ const { tokenChars: j } = ae;
1465
+ function k(s, e, t) {
1466
+ s[e] === void 0 ? s[e] = [t] : s[e].push(t);
1467
+ }
1468
+ function ss(s) {
1469
+ const e = /* @__PURE__ */ Object.create(null);
1470
+ let t = /* @__PURE__ */ Object.create(null), r = !1, i = !1, n = !1, o, l, f = -1, a = -1, c = -1, h = 0;
1471
+ for (; h < s.length; h++)
1472
+ if (a = s.charCodeAt(h), o === void 0)
1473
+ if (c === -1 && j[a] === 1)
1474
+ f === -1 && (f = h);
1475
+ else if (h !== 0 && (a === 32 || a === 9))
1476
+ c === -1 && f !== -1 && (c = h);
1477
+ else if (a === 59 || a === 44) {
1478
+ if (f === -1)
1479
+ throw new SyntaxError(`Unexpected character at index ${h}`);
1480
+ c === -1 && (c = h);
1481
+ const v = s.slice(f, c);
1482
+ a === 44 ? (k(e, v, t), t = /* @__PURE__ */ Object.create(null)) : o = v, f = c = -1;
1483
+ } else
1484
+ throw new SyntaxError(`Unexpected character at index ${h}`);
1485
+ else if (l === void 0)
1486
+ if (c === -1 && j[a] === 1)
1487
+ f === -1 && (f = h);
1488
+ else if (a === 32 || a === 9)
1489
+ c === -1 && f !== -1 && (c = h);
1490
+ else if (a === 59 || a === 44) {
1491
+ if (f === -1)
1492
+ throw new SyntaxError(`Unexpected character at index ${h}`);
1493
+ c === -1 && (c = h), k(t, s.slice(f, c), !0), a === 44 && (k(e, o, t), t = /* @__PURE__ */ Object.create(null), o = void 0), f = c = -1;
1494
+ } else if (a === 61 && f !== -1 && c === -1)
1495
+ l = s.slice(f, h), f = c = -1;
1496
+ else
1497
+ throw new SyntaxError(`Unexpected character at index ${h}`);
1498
+ else if (i) {
1499
+ if (j[a] !== 1)
1500
+ throw new SyntaxError(`Unexpected character at index ${h}`);
1501
+ f === -1 ? f = h : r || (r = !0), i = !1;
1502
+ } else if (n)
1503
+ if (j[a] === 1)
1504
+ f === -1 && (f = h);
1505
+ else if (a === 34 && f !== -1)
1506
+ n = !1, c = h;
1507
+ else if (a === 92)
1508
+ i = !0;
1509
+ else
1510
+ throw new SyntaxError(`Unexpected character at index ${h}`);
1511
+ else if (a === 34 && s.charCodeAt(h - 1) === 61)
1512
+ n = !0;
1513
+ else if (c === -1 && j[a] === 1)
1514
+ f === -1 && (f = h);
1515
+ else if (f !== -1 && (a === 32 || a === 9))
1516
+ c === -1 && (c = h);
1517
+ else if (a === 59 || a === 44) {
1518
+ if (f === -1)
1519
+ throw new SyntaxError(`Unexpected character at index ${h}`);
1520
+ c === -1 && (c = h);
1521
+ let v = s.slice(f, c);
1522
+ r && (v = v.replace(/\\/g, ""), r = !1), k(t, l, v), a === 44 && (k(e, o, t), t = /* @__PURE__ */ Object.create(null), o = void 0), l = void 0, f = c = -1;
1523
+ } else
1524
+ throw new SyntaxError(`Unexpected character at index ${h}`);
1525
+ if (f === -1 || n || a === 32 || a === 9)
1526
+ throw new SyntaxError("Unexpected end of input");
1527
+ c === -1 && (c = h);
1528
+ const p = s.slice(f, c);
1529
+ return o === void 0 ? k(e, p, t) : (l === void 0 ? k(t, p, !0) : r ? k(t, l, p.replace(/\\/g, "")) : k(t, l, p), k(e, o, t)), e;
1530
+ }
1531
+ function rs(s) {
1532
+ return Object.keys(s).map((e) => {
1533
+ let t = s[e];
1534
+ return Array.isArray(t) || (t = [t]), t.map((r) => [e].concat(
1535
+ Object.keys(r).map((i) => {
1536
+ let n = r[i];
1537
+ return Array.isArray(n) || (n = [n]), n.map((o) => o === !0 ? i : `${i}=${o}`).join("; ");
1538
+ })
1539
+ ).join("; ")).join(", ");
1540
+ }).join(", ");
1541
+ }
1542
+ var nt = { format: rs, parse: ss };
1543
+ const is = S, ns = S, os = S, ot = S, as = S, { randomBytes: ls, createHash: fs } = S, { URL: me } = S, T = oe, hs = rt, cs = it, {
1544
+ BINARY_TYPES: ze,
1545
+ EMPTY_BUFFER: Q,
1546
+ GUID: us,
1547
+ kForOnEventAttribute: ge,
1548
+ kListener: ds,
1549
+ kStatusCode: _s,
1550
+ kWebSocket: y,
1551
+ NOOP: at
1552
+ } = U, {
1553
+ EventTarget: { addEventListener: ps, removeEventListener: ms }
1554
+ } = ts, { format: gs, parse: ys } = nt, { toBuffer: vs } = ne, Ss = 30 * 1e3, lt = Symbol("kAborted"), ye = [8, 13], O = ["CONNECTING", "OPEN", "CLOSING", "CLOSED"], Es = /^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;
1555
+ let m = class d extends is {
1556
+ /**
1557
+ * Create a new `WebSocket`.
1558
+ *
1559
+ * @param {(String|URL)} address The URL to which to connect
1560
+ * @param {(String|String[])} [protocols] The subprotocols
1561
+ * @param {Object} [options] Connection options
1562
+ */
1563
+ constructor(e, t, r) {
1564
+ super(), this._binaryType = ze[0], this._closeCode = 1006, this._closeFrameReceived = !1, this._closeFrameSent = !1, this._closeMessage = Q, this._closeTimer = null, this._extensions = {}, this._paused = !1, this._protocol = "", this._readyState = d.CONNECTING, this._receiver = null, this._sender = null, this._socket = null, e !== null ? (this._bufferedAmount = 0, this._isServer = !1, this._redirects = 0, t === void 0 ? t = [] : Array.isArray(t) || (typeof t == "object" && t !== null ? (r = t, t = []) : t = [t]), ht(this, e, t, r)) : this._isServer = !0;
1565
+ }
1566
+ /**
1567
+ * This deviates from the WHATWG interface since ws doesn't support the
1568
+ * required default "blob" type (instead we define a custom "nodebuffer"
1569
+ * type).
1570
+ *
1571
+ * @type {String}
1572
+ */
1573
+ get binaryType() {
1574
+ return this._binaryType;
1575
+ }
1576
+ set binaryType(e) {
1577
+ ze.includes(e) && (this._binaryType = e, this._receiver && (this._receiver._binaryType = e));
1578
+ }
1579
+ /**
1580
+ * @type {Number}
1581
+ */
1582
+ get bufferedAmount() {
1583
+ return this._socket ? this._socket._writableState.length + this._sender._bufferedBytes : this._bufferedAmount;
1584
+ }
1585
+ /**
1586
+ * @type {String}
1587
+ */
1588
+ get extensions() {
1589
+ return Object.keys(this._extensions).join();
1590
+ }
1591
+ /**
1592
+ * @type {Boolean}
1593
+ */
1594
+ get isPaused() {
1595
+ return this._paused;
1596
+ }
1597
+ /**
1598
+ * @type {Function}
1599
+ */
1600
+ /* istanbul ignore next */
1601
+ get onclose() {
1602
+ return null;
1603
+ }
1604
+ /**
1605
+ * @type {Function}
1606
+ */
1607
+ /* istanbul ignore next */
1608
+ get onerror() {
1609
+ return null;
1610
+ }
1611
+ /**
1612
+ * @type {Function}
1613
+ */
1614
+ /* istanbul ignore next */
1615
+ get onopen() {
1616
+ return null;
1617
+ }
1618
+ /**
1619
+ * @type {Function}
1620
+ */
1621
+ /* istanbul ignore next */
1622
+ get onmessage() {
1623
+ return null;
1624
+ }
1625
+ /**
1626
+ * @type {String}
1627
+ */
1628
+ get protocol() {
1629
+ return this._protocol;
1630
+ }
1631
+ /**
1632
+ * @type {Number}
1633
+ */
1634
+ get readyState() {
1635
+ return this._readyState;
1636
+ }
1637
+ /**
1638
+ * @type {String}
1639
+ */
1640
+ get url() {
1641
+ return this._url;
1642
+ }
1643
+ /**
1644
+ * Set up the socket and the internal resources.
1645
+ *
1646
+ * @param {(net.Socket|tls.Socket)} socket The network socket between the
1647
+ * server and client
1648
+ * @param {Buffer} head The first packet of the upgraded stream
1649
+ * @param {Object} options Options object
1650
+ * @param {Function} [options.generateMask] The function used to generate the
1651
+ * masking key
1652
+ * @param {Number} [options.maxPayload=0] The maximum allowed message size
1653
+ * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
1654
+ * not to skip UTF-8 validation for text and close messages
1655
+ * @private
1656
+ */
1657
+ setSocket(e, t, r) {
1658
+ const i = new hs({
1659
+ binaryType: this.binaryType,
1660
+ extensions: this._extensions,
1661
+ isServer: this._isServer,
1662
+ maxPayload: r.maxPayload,
1663
+ skipUTF8Validation: r.skipUTF8Validation
1664
+ });
1665
+ this._sender = new cs(e, this._extensions, r.generateMask), this._receiver = i, this._socket = e, i[y] = this, e[y] = this, i.on("conclude", ks), i.on("drain", ws), i.on("error", Os), i.on("message", Cs), i.on("ping", Ts), i.on("pong", Ls), e.setTimeout(0), e.setNoDelay(), t.length > 0 && e.unshift(t), e.on("close", ut), e.on("data", fe), e.on("end", dt), e.on("error", _t), this._readyState = d.OPEN, this.emit("open");
1666
+ }
1667
+ /**
1668
+ * Emit the `'close'` event.
1669
+ *
1670
+ * @private
1671
+ */
1672
+ emitClose() {
1673
+ if (!this._socket) {
1674
+ this._readyState = d.CLOSED, this.emit("close", this._closeCode, this._closeMessage);
1675
+ return;
1676
+ }
1677
+ this._extensions[T.extensionName] && this._extensions[T.extensionName].cleanup(), this._receiver.removeAllListeners(), this._readyState = d.CLOSED, this.emit("close", this._closeCode, this._closeMessage);
1678
+ }
1679
+ /**
1680
+ * Start a closing handshake.
1681
+ *
1682
+ * +----------+ +-----------+ +----------+
1683
+ * - - -|ws.close()|-->|close frame|-->|ws.close()|- - -
1684
+ * | +----------+ +-----------+ +----------+ |
1685
+ * +----------+ +-----------+ |
1686
+ * CLOSING |ws.close()|<--|close frame|<--+-----+ CLOSING
1687
+ * +----------+ +-----------+ |
1688
+ * | | | +---+ |
1689
+ * +------------------------+-->|fin| - - - -
1690
+ * | +---+ | +---+
1691
+ * - - - - -|fin|<---------------------+
1692
+ * +---+
1693
+ *
1694
+ * @param {Number} [code] Status code explaining why the connection is closing
1695
+ * @param {(String|Buffer)} [data] The reason why the connection is
1696
+ * closing
1697
+ * @public
1698
+ */
1699
+ close(e, t) {
1700
+ if (this.readyState !== d.CLOSED) {
1701
+ if (this.readyState === d.CONNECTING) {
1702
+ const r = "WebSocket was closed before the connection was established";
1703
+ b(this, this._req, r);
1704
+ return;
1705
+ }
1706
+ if (this.readyState === d.CLOSING) {
1707
+ this._closeFrameSent && (this._closeFrameReceived || this._receiver._writableState.errorEmitted) && this._socket.end();
1708
+ return;
1709
+ }
1710
+ this._readyState = d.CLOSING, this._sender.close(e, t, !this._isServer, (r) => {
1711
+ r || (this._closeFrameSent = !0, (this._closeFrameReceived || this._receiver._writableState.errorEmitted) && this._socket.end());
1712
+ }), this._closeTimer = setTimeout(
1713
+ this._socket.destroy.bind(this._socket),
1714
+ Ss
1715
+ );
1716
+ }
1717
+ }
1718
+ /**
1719
+ * Pause the socket.
1720
+ *
1721
+ * @public
1722
+ */
1723
+ pause() {
1724
+ this.readyState === d.CONNECTING || this.readyState === d.CLOSED || (this._paused = !0, this._socket.pause());
1725
+ }
1726
+ /**
1727
+ * Send a ping.
1728
+ *
1729
+ * @param {*} [data] The data to send
1730
+ * @param {Boolean} [mask] Indicates whether or not to mask `data`
1731
+ * @param {Function} [cb] Callback which is executed when the ping is sent
1732
+ * @public
1733
+ */
1734
+ ping(e, t, r) {
1735
+ if (this.readyState === d.CONNECTING)
1736
+ throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
1737
+ if (typeof e == "function" ? (r = e, e = t = void 0) : typeof t == "function" && (r = t, t = void 0), typeof e == "number" && (e = e.toString()), this.readyState !== d.OPEN) {
1738
+ ve(this, e, r);
1739
+ return;
1740
+ }
1741
+ t === void 0 && (t = !this._isServer), this._sender.ping(e || Q, t, r);
1742
+ }
1743
+ /**
1744
+ * Send a pong.
1745
+ *
1746
+ * @param {*} [data] The data to send
1747
+ * @param {Boolean} [mask] Indicates whether or not to mask `data`
1748
+ * @param {Function} [cb] Callback which is executed when the pong is sent
1749
+ * @public
1750
+ */
1751
+ pong(e, t, r) {
1752
+ if (this.readyState === d.CONNECTING)
1753
+ throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
1754
+ if (typeof e == "function" ? (r = e, e = t = void 0) : typeof t == "function" && (r = t, t = void 0), typeof e == "number" && (e = e.toString()), this.readyState !== d.OPEN) {
1755
+ ve(this, e, r);
1756
+ return;
1757
+ }
1758
+ t === void 0 && (t = !this._isServer), this._sender.pong(e || Q, t, r);
1759
+ }
1760
+ /**
1761
+ * Resume the socket.
1762
+ *
1763
+ * @public
1764
+ */
1765
+ resume() {
1766
+ this.readyState === d.CONNECTING || this.readyState === d.CLOSED || (this._paused = !1, this._receiver._writableState.needDrain || this._socket.resume());
1767
+ }
1768
+ /**
1769
+ * Send a data message.
1770
+ *
1771
+ * @param {*} data The message to send
1772
+ * @param {Object} [options] Options object
1773
+ * @param {Boolean} [options.binary] Specifies whether `data` is binary or
1774
+ * text
1775
+ * @param {Boolean} [options.compress] Specifies whether or not to compress
1776
+ * `data`
1777
+ * @param {Boolean} [options.fin=true] Specifies whether the fragment is the
1778
+ * last one
1779
+ * @param {Boolean} [options.mask] Specifies whether or not to mask `data`
1780
+ * @param {Function} [cb] Callback which is executed when data is written out
1781
+ * @public
1782
+ */
1783
+ send(e, t, r) {
1784
+ if (this.readyState === d.CONNECTING)
1785
+ throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
1786
+ if (typeof t == "function" && (r = t, t = {}), typeof e == "number" && (e = e.toString()), this.readyState !== d.OPEN) {
1787
+ ve(this, e, r);
1788
+ return;
1789
+ }
1790
+ const i = {
1791
+ binary: typeof e != "string",
1792
+ mask: !this._isServer,
1793
+ compress: !0,
1794
+ fin: !0,
1795
+ ...t
1796
+ };
1797
+ this._extensions[T.extensionName] || (i.compress = !1), this._sender.send(e || Q, i, r);
1798
+ }
1799
+ /**
1800
+ * Forcibly close the connection.
1801
+ *
1802
+ * @public
1803
+ */
1804
+ terminate() {
1805
+ if (this.readyState !== d.CLOSED) {
1806
+ if (this.readyState === d.CONNECTING) {
1807
+ const e = "WebSocket was closed before the connection was established";
1808
+ b(this, this._req, e);
1809
+ return;
1810
+ }
1811
+ this._socket && (this._readyState = d.CLOSING, this._socket.destroy());
1812
+ }
1813
+ }
1814
+ };
1815
+ Object.defineProperty(m, "CONNECTING", {
1816
+ enumerable: !0,
1817
+ value: O.indexOf("CONNECTING")
1818
+ });
1819
+ Object.defineProperty(m.prototype, "CONNECTING", {
1820
+ enumerable: !0,
1821
+ value: O.indexOf("CONNECTING")
1822
+ });
1823
+ Object.defineProperty(m, "OPEN", {
1824
+ enumerable: !0,
1825
+ value: O.indexOf("OPEN")
1826
+ });
1827
+ Object.defineProperty(m.prototype, "OPEN", {
1828
+ enumerable: !0,
1829
+ value: O.indexOf("OPEN")
1830
+ });
1831
+ Object.defineProperty(m, "CLOSING", {
1832
+ enumerable: !0,
1833
+ value: O.indexOf("CLOSING")
1834
+ });
1835
+ Object.defineProperty(m.prototype, "CLOSING", {
1836
+ enumerable: !0,
1837
+ value: O.indexOf("CLOSING")
1838
+ });
1839
+ Object.defineProperty(m, "CLOSED", {
1840
+ enumerable: !0,
1841
+ value: O.indexOf("CLOSED")
1842
+ });
1843
+ Object.defineProperty(m.prototype, "CLOSED", {
1844
+ enumerable: !0,
1845
+ value: O.indexOf("CLOSED")
1846
+ });
1847
+ [
1848
+ "binaryType",
1849
+ "bufferedAmount",
1850
+ "extensions",
1851
+ "isPaused",
1852
+ "protocol",
1853
+ "readyState",
1854
+ "url"
1855
+ ].forEach((s) => {
1856
+ Object.defineProperty(m.prototype, s, { enumerable: !0 });
1857
+ });
1858
+ ["open", "error", "close", "message"].forEach((s) => {
1859
+ Object.defineProperty(m.prototype, `on${s}`, {
1860
+ enumerable: !0,
1861
+ get() {
1862
+ for (const e of this.listeners(s))
1863
+ if (e[ge])
1864
+ return e[ds];
1865
+ return null;
1866
+ },
1867
+ set(e) {
1868
+ for (const t of this.listeners(s))
1869
+ if (t[ge]) {
1870
+ this.removeListener(s, t);
1871
+ break;
1872
+ }
1873
+ typeof e == "function" && this.addEventListener(s, e, {
1874
+ [ge]: !0
1875
+ });
1876
+ }
1877
+ });
1878
+ });
1879
+ m.prototype.addEventListener = ps;
1880
+ m.prototype.removeEventListener = ms;
1881
+ var ft = m;
1882
+ function ht(s, e, t, r) {
1883
+ const i = {
1884
+ protocolVersion: ye[1],
1885
+ maxPayload: 104857600,
1886
+ skipUTF8Validation: !1,
1887
+ perMessageDeflate: !0,
1888
+ followRedirects: !1,
1889
+ maxRedirects: 10,
1890
+ ...r,
1891
+ createConnection: void 0,
1892
+ socketPath: void 0,
1893
+ hostname: void 0,
1894
+ protocol: void 0,
1895
+ timeout: void 0,
1896
+ method: "GET",
1897
+ host: void 0,
1898
+ path: void 0,
1899
+ port: void 0
1900
+ };
1901
+ if (!ye.includes(i.protocolVersion))
1902
+ throw new RangeError(
1903
+ `Unsupported protocol version: ${i.protocolVersion} (supported versions: ${ye.join(", ")})`
1904
+ );
1905
+ let n;
1906
+ if (e instanceof me)
1907
+ n = e, s._url = e.href;
1908
+ else {
1909
+ try {
1910
+ n = new me(e);
1911
+ } catch {
1912
+ throw new SyntaxError(`Invalid URL: ${e}`);
1913
+ }
1914
+ s._url = e;
1915
+ }
1916
+ const o = n.protocol === "wss:", l = n.protocol === "ws+unix:";
1917
+ let f;
1918
+ if (n.protocol !== "ws:" && !o && !l ? f = `The URL's protocol must be one of "ws:", "wss:", or "ws+unix:"` : l && !n.pathname ? f = "The URL's pathname is empty" : n.hash && (f = "The URL contains a fragment identifier"), f) {
1919
+ const u = new SyntaxError(f);
1920
+ if (s._redirects === 0)
1921
+ throw u;
1922
+ ee(s, u);
1923
+ return;
1924
+ }
1925
+ const a = o ? 443 : 80, c = ls(16).toString("base64"), h = o ? ns.request : os.request, p = /* @__PURE__ */ new Set();
1926
+ let v;
1927
+ if (i.createConnection = o ? xs : bs, i.defaultPort = i.defaultPort || a, i.port = n.port || a, i.host = n.hostname.startsWith("[") ? n.hostname.slice(1, -1) : n.hostname, i.headers = {
1928
+ ...i.headers,
1929
+ "Sec-WebSocket-Version": i.protocolVersion,
1930
+ "Sec-WebSocket-Key": c,
1931
+ Connection: "Upgrade",
1932
+ Upgrade: "websocket"
1933
+ }, i.path = n.pathname + n.search, i.timeout = i.handshakeTimeout, i.perMessageDeflate && (v = new T(
1934
+ i.perMessageDeflate !== !0 ? i.perMessageDeflate : {},
1935
+ !1,
1936
+ i.maxPayload
1937
+ ), i.headers["Sec-WebSocket-Extensions"] = gs({
1938
+ [T.extensionName]: v.offer()
1939
+ })), t.length) {
1940
+ for (const u of t) {
1941
+ if (typeof u != "string" || !Es.test(u) || p.has(u))
1942
+ throw new SyntaxError(
1943
+ "An invalid or duplicated subprotocol was specified"
1944
+ );
1945
+ p.add(u);
1946
+ }
1947
+ i.headers["Sec-WebSocket-Protocol"] = t.join(",");
1948
+ }
1949
+ if (i.origin && (i.protocolVersion < 13 ? i.headers["Sec-WebSocket-Origin"] = i.origin : i.headers.Origin = i.origin), (n.username || n.password) && (i.auth = `${n.username}:${n.password}`), l) {
1950
+ const u = i.path.split(":");
1951
+ i.socketPath = u[0], i.path = u[1];
1952
+ }
1953
+ let _;
1954
+ if (i.followRedirects) {
1955
+ if (s._redirects === 0) {
1956
+ s._originalIpc = l, s._originalSecure = o, s._originalHostOrSocketPath = l ? i.socketPath : n.host;
1957
+ const u = r && r.headers;
1958
+ if (r = { ...r, headers: {} }, u)
1959
+ for (const [E, $] of Object.entries(u))
1960
+ r.headers[E.toLowerCase()] = $;
1961
+ } else if (s.listenerCount("redirect") === 0) {
1962
+ const u = l ? s._originalIpc ? i.socketPath === s._originalHostOrSocketPath : !1 : s._originalIpc ? !1 : n.host === s._originalHostOrSocketPath;
1963
+ (!u || s._originalSecure && !o) && (delete i.headers.authorization, delete i.headers.cookie, u || delete i.headers.host, i.auth = void 0);
1964
+ }
1965
+ i.auth && !r.headers.authorization && (r.headers.authorization = "Basic " + Buffer.from(i.auth).toString("base64")), _ = s._req = h(i), s._redirects && s.emit("redirect", s.url, _);
1966
+ } else
1967
+ _ = s._req = h(i);
1968
+ i.timeout && _.on("timeout", () => {
1969
+ b(s, _, "Opening handshake has timed out");
1970
+ }), _.on("error", (u) => {
1971
+ _ === null || _[lt] || (_ = s._req = null, ee(s, u));
1972
+ }), _.on("response", (u) => {
1973
+ const E = u.headers.location, $ = u.statusCode;
1974
+ if (E && i.followRedirects && $ >= 300 && $ < 400) {
1975
+ if (++s._redirects > i.maxRedirects) {
1976
+ b(s, _, "Maximum redirects exceeded");
1977
+ return;
1978
+ }
1979
+ _.abort();
1980
+ let q;
1981
+ try {
1982
+ q = new me(E, e);
1983
+ } catch {
1984
+ const L = new SyntaxError(`Invalid URL: ${E}`);
1985
+ ee(s, L);
1986
+ return;
1987
+ }
1988
+ ht(s, q, t, r);
1989
+ } else
1990
+ s.emit("unexpected-response", _, u) || b(
1991
+ s,
1992
+ _,
1993
+ `Unexpected server response: ${u.statusCode}`
1994
+ );
1995
+ }), _.on("upgrade", (u, E, $) => {
1996
+ if (s.emit("upgrade", u), s.readyState !== m.CONNECTING)
1997
+ return;
1998
+ if (_ = s._req = null, u.headers.upgrade.toLowerCase() !== "websocket") {
1999
+ b(s, E, "Invalid Upgrade header");
2000
+ return;
2001
+ }
2002
+ const q = fs("sha1").update(c + us).digest("base64");
2003
+ if (u.headers["sec-websocket-accept"] !== q) {
2004
+ b(s, E, "Invalid Sec-WebSocket-Accept header");
2005
+ return;
2006
+ }
2007
+ const D = u.headers["sec-websocket-protocol"];
2008
+ let L;
2009
+ if (D !== void 0 ? p.size ? p.has(D) || (L = "Server sent an invalid subprotocol") : L = "Server sent a subprotocol but none was requested" : p.size && (L = "Server sent no subprotocol"), L) {
2010
+ b(s, E, L);
2011
+ return;
2012
+ }
2013
+ D && (s._protocol = D);
2014
+ const ke = u.headers["sec-websocket-extensions"];
2015
+ if (ke !== void 0) {
2016
+ if (!v) {
2017
+ b(s, E, "Server sent a Sec-WebSocket-Extensions header but no extension was requested");
2018
+ return;
2019
+ }
2020
+ let he;
2021
+ try {
2022
+ he = ys(ke);
2023
+ } catch {
2024
+ b(s, E, "Invalid Sec-WebSocket-Extensions header");
2025
+ return;
2026
+ }
2027
+ const we = Object.keys(he);
2028
+ if (we.length !== 1 || we[0] !== T.extensionName) {
2029
+ b(s, E, "Server indicated an extension that was not requested");
2030
+ return;
2031
+ }
2032
+ try {
2033
+ v.accept(he[T.extensionName]);
2034
+ } catch {
2035
+ b(s, E, "Invalid Sec-WebSocket-Extensions header");
2036
+ return;
2037
+ }
2038
+ s._extensions[T.extensionName] = v;
2039
+ }
2040
+ s.setSocket(E, $, {
2041
+ generateMask: i.generateMask,
2042
+ maxPayload: i.maxPayload,
2043
+ skipUTF8Validation: i.skipUTF8Validation
2044
+ });
2045
+ }), i.finishRequest ? i.finishRequest(_, s) : _.end();
2046
+ }
2047
+ function ee(s, e) {
2048
+ s._readyState = m.CLOSING, s.emit("error", e), s.emitClose();
2049
+ }
2050
+ function bs(s) {
2051
+ return s.path = s.socketPath, ot.connect(s);
2052
+ }
2053
+ function xs(s) {
2054
+ return s.path = void 0, !s.servername && s.servername !== "" && (s.servername = ot.isIP(s.host) ? "" : s.host), as.connect(s);
2055
+ }
2056
+ function b(s, e, t) {
2057
+ s._readyState = m.CLOSING;
2058
+ const r = new Error(t);
2059
+ Error.captureStackTrace(r, b), e.setHeader ? (e[lt] = !0, e.abort(), e.socket && !e.socket.destroyed && e.socket.destroy(), process.nextTick(ee, s, r)) : (e.destroy(r), e.once("error", s.emit.bind(s, "error")), e.once("close", s.emitClose.bind(s)));
2060
+ }
2061
+ function ve(s, e, t) {
2062
+ if (e) {
2063
+ const r = vs(e).length;
2064
+ s._socket ? s._sender._bufferedBytes += r : s._bufferedAmount += r;
2065
+ }
2066
+ if (t) {
2067
+ const r = new Error(
2068
+ `WebSocket is not open: readyState ${s.readyState} (${O[s.readyState]})`
2069
+ );
2070
+ process.nextTick(t, r);
2071
+ }
2072
+ }
2073
+ function ks(s, e) {
2074
+ const t = this[y];
2075
+ t._closeFrameReceived = !0, t._closeMessage = e, t._closeCode = s, t._socket[y] !== void 0 && (t._socket.removeListener("data", fe), process.nextTick(ct, t._socket), s === 1005 ? t.close() : t.close(s, e));
2076
+ }
2077
+ function ws() {
2078
+ const s = this[y];
2079
+ s.isPaused || s._socket.resume();
2080
+ }
2081
+ function Os(s) {
2082
+ const e = this[y];
2083
+ e._socket[y] !== void 0 && (e._socket.removeListener("data", fe), process.nextTick(ct, e._socket), e.close(s[_s])), e.emit("error", s);
2084
+ }
2085
+ function Ye() {
2086
+ this[y].emitClose();
2087
+ }
2088
+ function Cs(s, e) {
2089
+ this[y].emit("message", s, e);
2090
+ }
2091
+ function Ts(s) {
2092
+ const e = this[y];
2093
+ e.pong(s, !e._isServer, at), e.emit("ping", s);
2094
+ }
2095
+ function Ls(s) {
2096
+ this[y].emit("pong", s);
2097
+ }
2098
+ function ct(s) {
2099
+ s.resume();
2100
+ }
2101
+ function ut() {
2102
+ const s = this[y];
2103
+ this.removeListener("close", ut), this.removeListener("data", fe), this.removeListener("end", dt), s._readyState = m.CLOSING;
2104
+ let e;
2105
+ !this._readableState.endEmitted && !s._closeFrameReceived && !s._receiver._writableState.errorEmitted && (e = s._socket.read()) !== null && s._receiver.write(e), s._receiver.end(), this[y] = void 0, clearTimeout(s._closeTimer), s._receiver._writableState.finished || s._receiver._writableState.errorEmitted ? s.emitClose() : (s._receiver.on("error", Ye), s._receiver.on("finish", Ye));
2106
+ }
2107
+ function fe(s) {
2108
+ this[y]._receiver.write(s) || this.pause();
2109
+ }
2110
+ function dt() {
2111
+ const s = this[y];
2112
+ s._readyState = m.CLOSING, s._receiver.end(), this.end();
2113
+ }
2114
+ function _t() {
2115
+ const s = this[y];
2116
+ this.removeListener("error", _t), this.on("error", at), s && (s._readyState = m.CLOSING, this.destroy());
2117
+ }
2118
+ const Xs = /* @__PURE__ */ z(ft), { tokenChars: Ns } = ae;
2119
+ function Ps(s) {
2120
+ const e = /* @__PURE__ */ new Set();
2121
+ let t = -1, r = -1, i = 0;
2122
+ for (i; i < s.length; i++) {
2123
+ const o = s.charCodeAt(i);
2124
+ if (r === -1 && Ns[o] === 1)
2125
+ t === -1 && (t = i);
2126
+ else if (i !== 0 && (o === 32 || o === 9))
2127
+ r === -1 && t !== -1 && (r = i);
2128
+ else if (o === 44) {
2129
+ if (t === -1)
2130
+ throw new SyntaxError(`Unexpected character at index ${i}`);
2131
+ r === -1 && (r = i);
2132
+ const l = s.slice(t, r);
2133
+ if (e.has(l))
2134
+ throw new SyntaxError(`The "${l}" subprotocol is duplicated`);
2135
+ e.add(l), t = r = -1;
2136
+ } else
2137
+ throw new SyntaxError(`Unexpected character at index ${i}`);
2138
+ }
2139
+ if (t === -1 || r !== -1)
2140
+ throw new SyntaxError("Unexpected end of input");
2141
+ const n = s.slice(t, i);
2142
+ if (e.has(n))
2143
+ throw new SyntaxError(`The "${n}" subprotocol is duplicated`);
2144
+ return e.add(n), e;
2145
+ }
2146
+ var Rs = { parse: Ps };
2147
+ const Us = S, ie = S, { createHash: Bs } = S, qe = nt, N = oe, $s = Rs, Ms = ft, { GUID: Is, kWebSocket: Ds } = U, Ws = /^[+/0-9A-Za-z]{22}==$/, Ke = 0, Xe = 1, pt = 2;
2148
+ class As extends Us {
2149
+ /**
2150
+ * Create a `WebSocketServer` instance.
2151
+ *
2152
+ * @param {Object} options Configuration options
2153
+ * @param {Number} [options.backlog=511] The maximum length of the queue of
2154
+ * pending connections
2155
+ * @param {Boolean} [options.clientTracking=true] Specifies whether or not to
2156
+ * track clients
2157
+ * @param {Function} [options.handleProtocols] A hook to handle protocols
2158
+ * @param {String} [options.host] The hostname where to bind the server
2159
+ * @param {Number} [options.maxPayload=104857600] The maximum allowed message
2160
+ * size
2161
+ * @param {Boolean} [options.noServer=false] Enable no server mode
2162
+ * @param {String} [options.path] Accept only connections matching this path
2163
+ * @param {(Boolean|Object)} [options.perMessageDeflate=false] Enable/disable
2164
+ * permessage-deflate
2165
+ * @param {Number} [options.port] The port where to bind the server
2166
+ * @param {(http.Server|https.Server)} [options.server] A pre-created HTTP/S
2167
+ * server to use
2168
+ * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
2169
+ * not to skip UTF-8 validation for text and close messages
2170
+ * @param {Function} [options.verifyClient] A hook to reject connections
2171
+ * @param {Function} [options.WebSocket=WebSocket] Specifies the `WebSocket`
2172
+ * class to use. It must be the `WebSocket` class or class that extends it
2173
+ * @param {Function} [callback] A listener for the `listening` event
2174
+ */
2175
+ constructor(e, t) {
2176
+ if (super(), e = {
2177
+ maxPayload: 100 * 1024 * 1024,
2178
+ skipUTF8Validation: !1,
2179
+ perMessageDeflate: !1,
2180
+ handleProtocols: null,
2181
+ clientTracking: !0,
2182
+ verifyClient: null,
2183
+ noServer: !1,
2184
+ backlog: null,
2185
+ // use default (511 as implemented in net.js)
2186
+ server: null,
2187
+ host: null,
2188
+ path: null,
2189
+ port: null,
2190
+ WebSocket: Ms,
2191
+ ...e
2192
+ }, e.port == null && !e.server && !e.noServer || e.port != null && (e.server || e.noServer) || e.server && e.noServer)
2193
+ throw new TypeError(
2194
+ 'One and only one of the "port", "server", or "noServer" options must be specified'
2195
+ );
2196
+ if (e.port != null ? (this._server = ie.createServer((r, i) => {
2197
+ const n = ie.STATUS_CODES[426];
2198
+ i.writeHead(426, {
2199
+ "Content-Length": n.length,
2200
+ "Content-Type": "text/plain"
2201
+ }), i.end(n);
2202
+ }), this._server.listen(
2203
+ e.port,
2204
+ e.host,
2205
+ e.backlog,
2206
+ t
2207
+ )) : e.server && (this._server = e.server), this._server) {
2208
+ const r = this.emit.bind(this, "connection");
2209
+ this._removeListeners = js(this._server, {
2210
+ listening: this.emit.bind(this, "listening"),
2211
+ error: this.emit.bind(this, "error"),
2212
+ upgrade: (i, n, o) => {
2213
+ this.handleUpgrade(i, n, o, r);
2214
+ }
2215
+ });
2216
+ }
2217
+ e.perMessageDeflate === !0 && (e.perMessageDeflate = {}), e.clientTracking && (this.clients = /* @__PURE__ */ new Set(), this._shouldEmitClose = !1), this.options = e, this._state = Ke;
2218
+ }
2219
+ /**
2220
+ * Returns the bound address, the address family name, and port of the server
2221
+ * as reported by the operating system if listening on an IP socket.
2222
+ * If the server is listening on a pipe or UNIX domain socket, the name is
2223
+ * returned as a string.
2224
+ *
2225
+ * @return {(Object|String|null)} The address of the server
2226
+ * @public
2227
+ */
2228
+ address() {
2229
+ if (this.options.noServer)
2230
+ throw new Error('The server is operating in "noServer" mode');
2231
+ return this._server ? this._server.address() : null;
2232
+ }
2233
+ /**
2234
+ * Stop the server from accepting new connections and emit the `'close'` event
2235
+ * when all existing connections are closed.
2236
+ *
2237
+ * @param {Function} [cb] A one-time listener for the `'close'` event
2238
+ * @public
2239
+ */
2240
+ close(e) {
2241
+ if (this._state === pt) {
2242
+ e && this.once("close", () => {
2243
+ e(new Error("The server is not running"));
2244
+ }), process.nextTick(G, this);
2245
+ return;
2246
+ }
2247
+ if (e && this.once("close", e), this._state !== Xe)
2248
+ if (this._state = Xe, this.options.noServer || this.options.server)
2249
+ this._server && (this._removeListeners(), this._removeListeners = this._server = null), this.clients ? this.clients.size ? this._shouldEmitClose = !0 : process.nextTick(G, this) : process.nextTick(G, this);
2250
+ else {
2251
+ const t = this._server;
2252
+ this._removeListeners(), this._removeListeners = this._server = null, t.close(() => {
2253
+ G(this);
2254
+ });
2255
+ }
2256
+ }
2257
+ /**
2258
+ * See if a given request should be handled by this server instance.
2259
+ *
2260
+ * @param {http.IncomingMessage} req Request object to inspect
2261
+ * @return {Boolean} `true` if the request is valid, else `false`
2262
+ * @public
2263
+ */
2264
+ shouldHandle(e) {
2265
+ if (this.options.path) {
2266
+ const t = e.url.indexOf("?");
2267
+ if ((t !== -1 ? e.url.slice(0, t) : e.url) !== this.options.path)
2268
+ return !1;
2269
+ }
2270
+ return !0;
2271
+ }
2272
+ /**
2273
+ * Handle a HTTP Upgrade request.
2274
+ *
2275
+ * @param {http.IncomingMessage} req The request object
2276
+ * @param {(net.Socket|tls.Socket)} socket The network socket between the
2277
+ * server and client
2278
+ * @param {Buffer} head The first packet of the upgraded stream
2279
+ * @param {Function} cb Callback
2280
+ * @public
2281
+ */
2282
+ handleUpgrade(e, t, r, i) {
2283
+ t.on("error", Ze);
2284
+ const n = e.headers["sec-websocket-key"], o = +e.headers["sec-websocket-version"];
2285
+ if (e.method !== "GET") {
2286
+ R(this, e, t, 405, "Invalid HTTP method");
2287
+ return;
2288
+ }
2289
+ if (e.headers.upgrade.toLowerCase() !== "websocket") {
2290
+ R(this, e, t, 400, "Invalid Upgrade header");
2291
+ return;
2292
+ }
2293
+ if (!n || !Ws.test(n)) {
2294
+ R(this, e, t, 400, "Missing or invalid Sec-WebSocket-Key header");
2295
+ return;
2296
+ }
2297
+ if (o !== 8 && o !== 13) {
2298
+ R(this, e, t, 400, "Missing or invalid Sec-WebSocket-Version header");
2299
+ return;
2300
+ }
2301
+ if (!this.shouldHandle(e)) {
2302
+ H(t, 400);
2303
+ return;
2304
+ }
2305
+ const l = e.headers["sec-websocket-protocol"];
2306
+ let f = /* @__PURE__ */ new Set();
2307
+ if (l !== void 0)
2308
+ try {
2309
+ f = $s.parse(l);
2310
+ } catch {
2311
+ R(this, e, t, 400, "Invalid Sec-WebSocket-Protocol header");
2312
+ return;
2313
+ }
2314
+ const a = e.headers["sec-websocket-extensions"], c = {};
2315
+ if (this.options.perMessageDeflate && a !== void 0) {
2316
+ const h = new N(
2317
+ this.options.perMessageDeflate,
2318
+ !0,
2319
+ this.options.maxPayload
2320
+ );
2321
+ try {
2322
+ const p = qe.parse(a);
2323
+ p[N.extensionName] && (h.accept(p[N.extensionName]), c[N.extensionName] = h);
2324
+ } catch {
2325
+ R(this, e, t, 400, "Invalid or unacceptable Sec-WebSocket-Extensions header");
2326
+ return;
2327
+ }
2328
+ }
2329
+ if (this.options.verifyClient) {
2330
+ const h = {
2331
+ origin: e.headers[`${o === 8 ? "sec-websocket-origin" : "origin"}`],
2332
+ secure: !!(e.socket.authorized || e.socket.encrypted),
2333
+ req: e
2334
+ };
2335
+ if (this.options.verifyClient.length === 2) {
2336
+ this.options.verifyClient(h, (p, v, _, u) => {
2337
+ if (!p)
2338
+ return H(t, v || 401, _, u);
2339
+ this.completeUpgrade(
2340
+ c,
2341
+ n,
2342
+ f,
2343
+ e,
2344
+ t,
2345
+ r,
2346
+ i
2347
+ );
2348
+ });
2349
+ return;
2350
+ }
2351
+ if (!this.options.verifyClient(h))
2352
+ return H(t, 401);
2353
+ }
2354
+ this.completeUpgrade(c, n, f, e, t, r, i);
2355
+ }
2356
+ /**
2357
+ * Upgrade the connection to WebSocket.
2358
+ *
2359
+ * @param {Object} extensions The accepted extensions
2360
+ * @param {String} key The value of the `Sec-WebSocket-Key` header
2361
+ * @param {Set} protocols The subprotocols
2362
+ * @param {http.IncomingMessage} req The request object
2363
+ * @param {(net.Socket|tls.Socket)} socket The network socket between the
2364
+ * server and client
2365
+ * @param {Buffer} head The first packet of the upgraded stream
2366
+ * @param {Function} cb Callback
2367
+ * @throws {Error} If called more than once with the same socket
2368
+ * @private
2369
+ */
2370
+ completeUpgrade(e, t, r, i, n, o, l) {
2371
+ if (!n.readable || !n.writable)
2372
+ return n.destroy();
2373
+ if (n[Ds])
2374
+ throw new Error(
2375
+ "server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration"
2376
+ );
2377
+ if (this._state > Ke)
2378
+ return H(n, 503);
2379
+ const a = [
2380
+ "HTTP/1.1 101 Switching Protocols",
2381
+ "Upgrade: websocket",
2382
+ "Connection: Upgrade",
2383
+ `Sec-WebSocket-Accept: ${Bs("sha1").update(t + Is).digest("base64")}`
2384
+ ], c = new this.options.WebSocket(null);
2385
+ if (r.size) {
2386
+ const h = this.options.handleProtocols ? this.options.handleProtocols(r, i) : r.values().next().value;
2387
+ h && (a.push(`Sec-WebSocket-Protocol: ${h}`), c._protocol = h);
2388
+ }
2389
+ if (e[N.extensionName]) {
2390
+ const h = e[N.extensionName].params, p = qe.format({
2391
+ [N.extensionName]: [h]
2392
+ });
2393
+ a.push(`Sec-WebSocket-Extensions: ${p}`), c._extensions = e;
2394
+ }
2395
+ this.emit("headers", a, i), n.write(a.concat(`\r
2396
+ `).join(`\r
2397
+ `)), n.removeListener("error", Ze), c.setSocket(n, o, {
2398
+ maxPayload: this.options.maxPayload,
2399
+ skipUTF8Validation: this.options.skipUTF8Validation
2400
+ }), this.clients && (this.clients.add(c), c.on("close", () => {
2401
+ this.clients.delete(c), this._shouldEmitClose && !this.clients.size && process.nextTick(G, this);
2402
+ })), l(c, i);
2403
+ }
2404
+ }
2405
+ var Fs = As;
2406
+ function js(s, e) {
2407
+ for (const t of Object.keys(e))
2408
+ s.on(t, e[t]);
2409
+ return function() {
2410
+ for (const r of Object.keys(e))
2411
+ s.removeListener(r, e[r]);
2412
+ };
2413
+ }
2414
+ function G(s) {
2415
+ s._state = pt, s.emit("close");
2416
+ }
2417
+ function Ze() {
2418
+ this.destroy();
2419
+ }
2420
+ function H(s, e, t, r) {
2421
+ t = t || ie.STATUS_CODES[e], r = {
2422
+ Connection: "close",
2423
+ "Content-Type": "text/html",
2424
+ "Content-Length": Buffer.byteLength(t),
2425
+ ...r
2426
+ }, s.once("finish", s.destroy), s.end(
2427
+ `HTTP/1.1 ${e} ${ie.STATUS_CODES[e]}\r
2428
+ ` + Object.keys(r).map((i) => `${i}: ${r[i]}`).join(`\r
2429
+ `) + `\r
2430
+ \r
2431
+ ` + t
2432
+ );
2433
+ }
2434
+ function R(s, e, t, r, i) {
2435
+ if (s.listenerCount("wsClientError")) {
2436
+ const n = new Error(i);
2437
+ Error.captureStackTrace(n, R), s.emit("wsClientError", n, t, e);
2438
+ } else
2439
+ H(t, r, i);
2440
+ }
2441
+ const Zs = /* @__PURE__ */ z(Fs);
2442
+ export {
2443
+ qs as Receiver,
2444
+ Ks as Sender,
2445
+ Xs as WebSocket,
2446
+ Zs as WebSocketServer,
2447
+ Vs as createWebSocketStream,
2448
+ Xs as default
2449
+ };
src/demo/requirements.txt CHANGED
@@ -1,3 +1,4 @@
1
  torch
2
  transformers
3
- pdf2image
 
 
1
  torch
2
  transformers
3
+ pdf2image
4
+ pytesseract
src/frontend/Index.svelte CHANGED
@@ -1,5 +1,5 @@
1
  <script lang="ts">
2
- import {tick, onMount} from "svelte";
3
  import PdfUploadText from "./PdfUploadText.svelte";
4
  import type { Gradio } from "@gradio/utils";
5
  import { Block, BlockLabel } from "@gradio/atoms";
@@ -96,8 +96,11 @@
96
 
97
  $: height = height || 500;
98
 
 
 
99
  $: _value = normalise_file(value, root, proxy_url);
100
 
 
101
  $: if(JSON.stringify(old_value) != JSON.stringify(_value)) {
102
  if (_value){
103
  get_doc(_value);
@@ -105,8 +108,6 @@
105
  old_value = _value;
106
  gradio.dispatch("change");
107
  }
108
-
109
-
110
  </script>
111
 
112
  <Block {visible} {elem_id} {elem_classes} {container} {scale} {min_width}>
 
1
  <script lang="ts">
2
+ import { tick } from "svelte";
3
  import PdfUploadText from "./PdfUploadText.svelte";
4
  import type { Gradio } from "@gradio/utils";
5
  import { Block, BlockLabel } from "@gradio/atoms";
 
96
 
97
  $: height = height || 500;
98
 
99
+ // Compute the url to fetch the file from the backend\
100
+ // whenever a new value is passed in.
101
  $: _value = normalise_file(value, root, proxy_url);
102
 
103
+ // If the value changes, render the PDF of the currentPage
104
  $: if(JSON.stringify(old_value) != JSON.stringify(_value)) {
105
  if (_value){
106
  get_doc(_value);
 
108
  old_value = _value;
109
  gradio.dispatch("change");
110
  }
 
 
111
  </script>
112
 
113
  <Block {visible} {elem_id} {elem_classes} {container} {scale} {min_width}>
src/pyproject.toml CHANGED
@@ -8,7 +8,7 @@ build-backend = "hatchling.build"
8
 
9
  [project]
10
  name = "gradio_pdf"
11
- version = "0.0.2"
12
  description = "Python library for easily interacting with trained machine learning models"
13
  readme = "README.md"
14
  license = "Apache-2.0"
@@ -43,7 +43,7 @@ classifiers = [
43
  dev = ["build", "twine"]
44
 
45
  [tool.hatch.build]
46
- artifacts = ["/backend/gradio_pdf/templates", "*.pyi", "backend/gradio_pdf/templates", "backend/gradio_pdf/templates", "backend/gradio_pdf/templates", "backend/gradio_pdf/templates", "backend/gradio_pdf/templates", "backend/gradio_pdf/templates", "backend/gradio_pdf/templates", "backend/gradio_pdf/templates", "backend/gradio_pdf/templates", "backend/gradio_pdf/templates", "backend/gradio_pdf/templates", "backend/gradio_pdf/templates", "backend/gradio_pdf/templates", "backend/gradio_pdf/templates", "backend/gradio_pdf/templates", "backend/gradio_pdf/templates", "backend/gradio_pdf/templates", "backend/gradio_pdf/templates", "backend/gradio_pdf/templates", "backend/gradio_pdf/templates", "backend/gradio_pdf/templates", "backend/gradio_pdf/templates", "backend/gradio_pdf/templates", "backend/gradio_pdf/templates", "backend/gradio_pdf/templates", "backend/gradio_pdf/templates", "backend/gradio_pdf/templates", "backend/gradio_pdf/templates", "backend/gradio_pdf/templates", "backend/gradio_pdf/templates", "backend/gradio_pdf/templates", "backend/gradio_pdf/templates", "backend/gradio_pdf/templates", "backend/gradio_pdf/templates", "backend/gradio_pdf/templates", "backend/gradio_pdf/templates", "backend/gradio_pdf/templates", "backend/gradio_pdf/templates", "backend/gradio_pdf/templates", "backend/gradio_pdf/templates", "backend/gradio_pdf/templates"]
47
 
48
  [tool.hatch.build.targets.wheel]
49
  packages = ["/backend/gradio_pdf"]
 
8
 
9
  [project]
10
  name = "gradio_pdf"
11
+ version = "0.0.3"
12
  description = "Python library for easily interacting with trained machine learning models"
13
  readme = "README.md"
14
  license = "Apache-2.0"
 
43
  dev = ["build", "twine"]
44
 
45
  [tool.hatch.build]
46
+ artifacts = ["/backend/gradio_pdf/templates", "*.pyi", "backend/gradio_pdf/templates", "backend/gradio_pdf/templates", "backend/gradio_pdf/templates", "backend/gradio_pdf/templates", "backend/gradio_pdf/templates", "backend/gradio_pdf/templates", "backend/gradio_pdf/templates", "backend/gradio_pdf/templates", "backend/gradio_pdf/templates", "backend/gradio_pdf/templates", "backend/gradio_pdf/templates", "backend/gradio_pdf/templates", "backend/gradio_pdf/templates", "backend/gradio_pdf/templates", "backend/gradio_pdf/templates", "backend/gradio_pdf/templates", "backend/gradio_pdf/templates", "backend/gradio_pdf/templates", "backend/gradio_pdf/templates", "backend/gradio_pdf/templates", "backend/gradio_pdf/templates", "backend/gradio_pdf/templates", "backend/gradio_pdf/templates", "backend/gradio_pdf/templates", "backend/gradio_pdf/templates", "backend/gradio_pdf/templates", "backend/gradio_pdf/templates", "backend/gradio_pdf/templates", "backend/gradio_pdf/templates", "backend/gradio_pdf/templates", "backend/gradio_pdf/templates", "backend/gradio_pdf/templates", "backend/gradio_pdf/templates", "backend/gradio_pdf/templates", "backend/gradio_pdf/templates", "backend/gradio_pdf/templates", "backend/gradio_pdf/templates", "backend/gradio_pdf/templates", "backend/gradio_pdf/templates", "backend/gradio_pdf/templates", "backend/gradio_pdf/templates", "backend/gradio_pdf/templates"]
47
 
48
  [tool.hatch.build.targets.wheel]
49
  packages = ["/backend/gradio_pdf"]