@sqlitecloud/drivers 1.0.178 → 1.0.193

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -32,6 +32,34 @@ We aim for full compatibility with the established [sqlite3 API](https://www.npm
32
32
 
33
33
  The package is developed entirely in TypeScript and is fully compatible with JavaScript. It doesn't require any native libraries. This makes it a straightforward and effective tool for managing cloud-based databases in a familiar SQLite environment.
34
34
 
35
+ ## Publish / Subscribe (Pub/Sub)
36
+
37
+ ```ts
38
+ import { Database } from '@sqlitecloud/drivers'
39
+ import { PubSub, PUBSUB_ENTITY_TYPE } from '@sqlitecloud/drivers/lib/drivers/pubsub'
40
+
41
+ let database = new Database('sqlitecloud://user:password@xxx.sqlite.cloud:8860/chinook.sqlite')
42
+ // or use sqlitecloud://xxx.sqlite.cloud:8860?apikey=xxxxxxx
43
+
44
+ const pubSub: PubSub = await database.getPubSub()
45
+
46
+ await pubSub.listen(PUBSUB_ENTITY_TYPE.TABLE, 'albums', (error, results, data) => {
47
+ if (results) {
48
+ // Changes on albums table will be received here as JSON object
49
+ console.log('Received message:', results)
50
+ }
51
+ })
52
+
53
+ await database.sql`INSERT INTO albums (Title, ArtistId) values ('Brand new song', 1)`
54
+
55
+ // Stop listening changes on the table
56
+ await pubSub.unlisten(PUBSUB_ENTITY_TYPE.TABLE, 'albums')
57
+ ```
58
+
59
+ Pub/Sub is a messaging pattern that allows multiple applications to communicate with each other asynchronously. In the context of SQLiteCloud, Pub/Sub can be used to provide real-time updates and notifications to subscribed applications whenever data changes in the database or it can be used to send payloads (messages) to anyone subscribed to a channel.
60
+
61
+ Pub/Sub Documentation: [https://docs.sqlitecloud.io/docs/pub-sub](https://docs.sqlitecloud.io/docs/pub-sub)
62
+
35
63
  ## More
36
64
 
37
65
  How do I deploy SQLite in the cloud?
@@ -202,8 +202,8 @@ class SQLiteCloudTlsConnection extends connection_1.SQLiteCloudConnection {
202
202
  }
203
203
  if (this.processCallback) {
204
204
  this.processCallback(error, result);
205
- // this.processCallback = undefined
206
205
  }
206
+ this.buffer = Buffer.alloc(0);
207
207
  }
208
208
  /** Disconnect immediately, release connection, no events. */
209
209
  close() {
@@ -2,6 +2,7 @@ import { SQLiteCloudConfig, RowCountCallback } from './types';
2
2
  import { Statement } from './statement';
3
3
  import { ErrorCallback, ResultsCallback, RowCallback, RowsCallback } from './types';
4
4
  import EventEmitter from 'eventemitter3';
5
+ import { PubSub } from './pubsub';
5
6
  /**
6
7
  * Creating a Database object automatically opens a connection to the SQLite database.
7
8
  * When the connection is established the Database object emits an open event and calls
@@ -151,4 +152,13 @@ export declare class Database extends EventEmitter {
151
152
  * metadata in case of insert, update, delete.
152
153
  */
153
154
  sql(sql: TemplateStringsArray | string, ...values: any[]): Promise<any>;
155
+ /**
156
+ * PubSub class provides a Pub/Sub real-time updates and notifications system to
157
+ * allow multiple applications to communicate with each other asynchronously.
158
+ * It allows applications to subscribe to tables and receive notifications whenever
159
+ * data changes in the database table. It also enables sending messages to anyone
160
+ * subscribed to a specific channel.
161
+ * @returns {PubSub} A PubSub object
162
+ */
163
+ getPubSub(): Promise<PubSub>;
154
164
  }
@@ -45,6 +45,7 @@ const utilities_1 = require("./utilities");
45
45
  const statement_1 = require("./statement");
46
46
  const eventemitter3_1 = __importDefault(require("eventemitter3"));
47
47
  const utilities_2 = require("./utilities");
48
+ const pubsub_1 = require("./pubsub");
48
49
  // Uses eventemitter3 instead of node events for browser compatibility
49
50
  // https://github.com/primus/eventemitter3
50
51
  /**
@@ -443,5 +444,27 @@ class Database extends eventemitter3_1.default {
443
444
  });
444
445
  });
445
446
  }
447
+ /**
448
+ * PubSub class provides a Pub/Sub real-time updates and notifications system to
449
+ * allow multiple applications to communicate with each other asynchronously.
450
+ * It allows applications to subscribe to tables and receive notifications whenever
451
+ * data changes in the database table. It also enables sending messages to anyone
452
+ * subscribed to a specific channel.
453
+ * @returns {PubSub} A PubSub object
454
+ */
455
+ getPubSub() {
456
+ return __awaiter(this, void 0, void 0, function* () {
457
+ return new Promise((resolve, reject) => {
458
+ this.getConnection((error, connection) => {
459
+ if (error || !connection) {
460
+ reject(error);
461
+ }
462
+ else {
463
+ resolve(new pubsub_1.PubSub(connection));
464
+ }
465
+ });
466
+ });
467
+ });
468
+ }
446
469
  }
447
470
  exports.Database = Database;
@@ -14,6 +14,7 @@ export declare const CMD_BLOB = "$";
14
14
  export declare const CMD_COMPRESSED = "%";
15
15
  export declare const CMD_COMMAND = "^";
16
16
  export declare const CMD_ARRAY = "=";
17
+ export declare const CMD_PUBSUB = "|";
17
18
  export declare const ROWSET_CHUNKS_END = "/6 0 0 0 ";
18
19
  /** Analyze first character to check if corresponding data type has LEN */
19
20
  export declare function hasCommandLength(firstCharacter: string): boolean;
@@ -3,7 +3,7 @@
3
3
  // protocol.ts - low level protocol handling for SQLiteCloud transport
4
4
  //
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.formatCommand = exports.popData = exports.parseRowsetChunks = exports.bufferEndsWith = exports.bufferStartsWith = exports.parseRowsetHeader = exports.parseArray = exports.parseError = exports.decompressBuffer = exports.parseCommandLength = exports.hasCommandLength = exports.ROWSET_CHUNKS_END = exports.CMD_ARRAY = exports.CMD_COMMAND = exports.CMD_COMPRESSED = exports.CMD_BLOB = exports.CMD_NULL = exports.CMD_JSON = exports.CMD_ROWSET_CHUNK = exports.CMD_ROWSET = exports.CMD_FLOAT = exports.CMD_INT = exports.CMD_ERROR = exports.CMD_ZEROSTRING = exports.CMD_STRING = void 0;
6
+ exports.formatCommand = exports.popData = exports.parseRowsetChunks = exports.bufferEndsWith = exports.bufferStartsWith = exports.parseRowsetHeader = exports.parseArray = exports.parseError = exports.decompressBuffer = exports.parseCommandLength = exports.hasCommandLength = exports.ROWSET_CHUNKS_END = exports.CMD_PUBSUB = exports.CMD_ARRAY = exports.CMD_COMMAND = exports.CMD_COMPRESSED = exports.CMD_BLOB = exports.CMD_NULL = exports.CMD_JSON = exports.CMD_ROWSET_CHUNK = exports.CMD_ROWSET = exports.CMD_FLOAT = exports.CMD_INT = exports.CMD_ERROR = exports.CMD_ZEROSTRING = exports.CMD_STRING = void 0;
7
7
  const types_1 = require("./types");
8
8
  const rowset_1 = require("./rowset");
9
9
  const lz4 = require('lz4js');
@@ -24,7 +24,7 @@ exports.CMD_COMPRESSED = '%';
24
24
  exports.CMD_COMMAND = '^';
25
25
  exports.CMD_ARRAY = '=';
26
26
  // const CMD_RAWJSON = '{'
27
- // const CMD_PUBSUB = '|'
27
+ exports.CMD_PUBSUB = '|';
28
28
  // const CMD_RECONNECT = '@'
29
29
  // To mark the end of the Rowset, the special string /LEN 0 0 0 is sent (LEN is always 6 in this case)
30
30
  // https://github.com/sqlitecloud/sdk/blob/master/PROTOCOL.md#scsp-rowset-chunk
@@ -268,6 +268,8 @@ function popData(buffer) {
268
268
  return popResults(buffer.subarray(spaceIndex + 1, commandEnd - 1).toString('utf8'));
269
269
  case exports.CMD_COMMAND:
270
270
  return popResults(buffer.subarray(spaceIndex + 1, commandEnd).toString('utf8'));
271
+ case exports.CMD_PUBSUB:
272
+ return popResults(buffer.subarray(spaceIndex + 1, commandEnd).toString('utf8'));
271
273
  case exports.CMD_JSON:
272
274
  return popResults(JSON.parse(buffer.subarray(spaceIndex + 1, commandEnd).toString('utf8')));
273
275
  case exports.CMD_BLOB:
@@ -0,0 +1,48 @@
1
+ import { SQLiteCloudConnection } from './connection';
2
+ import { PubSubCallback } from './types';
3
+ export declare enum PUBSUB_ENTITY_TYPE {
4
+ TABLE = "TABLE",
5
+ CHANNEL = "CHANNEL"
6
+ }
7
+ /**
8
+ * Pub/Sub class to receive changes on database tables or to send messages to channels.
9
+ */
10
+ export declare class PubSub {
11
+ constructor(connection: SQLiteCloudConnection);
12
+ private connection;
13
+ private connectionPubSub;
14
+ /**
15
+ * Listen for a table or channel and start to receive messages to the provided callback.
16
+ * @param entityType One of TABLE or CHANNEL'
17
+ * @param entityName Name of the table or the channel
18
+ * @param callback Callback to be called when a message is received
19
+ * @param data Extra data to be passed to the callback
20
+ */
21
+ listen(entityType: PUBSUB_ENTITY_TYPE, entityName: string, callback: PubSubCallback, data?: any): Promise<any>;
22
+ /**
23
+ * Stop receive messages from a table or channel.
24
+ * @param entityType One of TABLE or CHANNEL
25
+ * @param entityName Name of the table or the channel
26
+ */
27
+ unlisten(entityType: string, entityName: string): Promise<any>;
28
+ /**
29
+ * Create a channel to send messages to.
30
+ * @param name Channel name
31
+ * @param failIfExists Raise an error if the channel already exists
32
+ */
33
+ createChannel(name: string, failIfExists?: boolean): Promise<any>;
34
+ /**
35
+ * Send a message to the channel.
36
+ */
37
+ notifyChannel(channelName: string, message: string): Promise<any>;
38
+ /**
39
+ * Ask the server to close the connection to the database and
40
+ * to keep only open the Pub/Sub connection.
41
+ * Only interaction with Pub/Sub commands will be allowed.
42
+ */
43
+ setPubSubOnly(): Promise<any>;
44
+ /** True if Pub/Sub connection is open. */
45
+ connected(): boolean;
46
+ /** Close Pub/Sub connection. */
47
+ close(): void;
48
+ }
@@ -0,0 +1,116 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.PubSub = exports.PUBSUB_ENTITY_TYPE = void 0;
16
+ const connection_tls_1 = __importDefault(require("./connection-tls"));
17
+ var PUBSUB_ENTITY_TYPE;
18
+ (function (PUBSUB_ENTITY_TYPE) {
19
+ PUBSUB_ENTITY_TYPE["TABLE"] = "TABLE";
20
+ PUBSUB_ENTITY_TYPE["CHANNEL"] = "CHANNEL";
21
+ })(PUBSUB_ENTITY_TYPE = exports.PUBSUB_ENTITY_TYPE || (exports.PUBSUB_ENTITY_TYPE = {}));
22
+ /**
23
+ * Pub/Sub class to receive changes on database tables or to send messages to channels.
24
+ */
25
+ class PubSub {
26
+ constructor(connection) {
27
+ this.connection = connection;
28
+ this.connectionPubSub = new connection_tls_1.default(connection.getConfig());
29
+ }
30
+ /**
31
+ * Listen for a table or channel and start to receive messages to the provided callback.
32
+ * @param entityType One of TABLE or CHANNEL'
33
+ * @param entityName Name of the table or the channel
34
+ * @param callback Callback to be called when a message is received
35
+ * @param data Extra data to be passed to the callback
36
+ */
37
+ listen(entityType, entityName, callback, data) {
38
+ return __awaiter(this, void 0, void 0, function* () {
39
+ const entity = entityType === 'TABLE' ? 'TABLE ' : '';
40
+ const authCommand = yield this.connection.sql(`LISTEN ${entity}${entityName};`);
41
+ return new Promise((resolve, reject) => {
42
+ this.connectionPubSub.sendCommands(authCommand, (error, results) => {
43
+ if (error) {
44
+ callback.call(this, error, null, data);
45
+ reject(error);
46
+ }
47
+ else {
48
+ // skip results from pubSub auth command
49
+ if (results !== 'OK') {
50
+ callback.call(this, null, results, data);
51
+ }
52
+ resolve(results);
53
+ }
54
+ });
55
+ });
56
+ });
57
+ }
58
+ /**
59
+ * Stop receive messages from a table or channel.
60
+ * @param entityType One of TABLE or CHANNEL
61
+ * @param entityName Name of the table or the channel
62
+ */
63
+ unlisten(entityType, entityName) {
64
+ return __awaiter(this, void 0, void 0, function* () {
65
+ const subject = entityType === 'TABLE' ? 'TABLE ' : '';
66
+ return this.connection.sql(`UNLISTEN ${subject}?;`, entityName);
67
+ });
68
+ }
69
+ /**
70
+ * Create a channel to send messages to.
71
+ * @param name Channel name
72
+ * @param failIfExists Raise an error if the channel already exists
73
+ */
74
+ createChannel(name, failIfExists = true) {
75
+ return __awaiter(this, void 0, void 0, function* () {
76
+ let notExistsCommand = '';
77
+ if (!failIfExists) {
78
+ notExistsCommand = 'IF NOT EXISTS;';
79
+ }
80
+ return this.connection.sql(`CREATE CHANNEL ? ${notExistsCommand}`, name);
81
+ });
82
+ }
83
+ /**
84
+ * Send a message to the channel.
85
+ */
86
+ notifyChannel(channelName, message) {
87
+ return this.connection.sql `NOTIFY ${channelName} ${message};`;
88
+ }
89
+ /**
90
+ * Ask the server to close the connection to the database and
91
+ * to keep only open the Pub/Sub connection.
92
+ * Only interaction with Pub/Sub commands will be allowed.
93
+ */
94
+ setPubSubOnly() {
95
+ return new Promise((resolve, reject) => {
96
+ this.connection.sendCommands('PUBSUB ONLY;', (error, results) => {
97
+ if (error) {
98
+ reject(error);
99
+ }
100
+ else {
101
+ this.connection.close();
102
+ resolve(results);
103
+ }
104
+ });
105
+ });
106
+ }
107
+ /** True if Pub/Sub connection is open. */
108
+ connected() {
109
+ return this.connectionPubSub.connected;
110
+ }
111
+ /** Close Pub/Sub connection. */
112
+ close() {
113
+ this.connectionPubSub.close();
114
+ }
115
+ }
116
+ exports.PubSub = PubSub;
@@ -108,6 +108,7 @@ export type ResultsCallback<T = any> = (error: Error | null, results?: T) => voi
108
108
  export type RowsCallback<T = Record<string, any>> = (error: Error | null, rows?: T[]) => void;
109
109
  export type RowCallback<T = Record<string, any>> = (error: Error | null, row?: T) => void;
110
110
  export type RowCountCallback = (error: Error | null, rowCount?: number) => void;
111
+ export type PubSubCallback<T = any> = (error: Error | null, results?: T, extraData?: T) => void;
111
112
  /**
112
113
  * Certain responses include arrays with various types of metadata.
113
114
  * The first entry is always an array type from this list. This enum
@@ -26,7 +26,7 @@ return /******/ (() => { // webpackBootstrap
26
26
  /***/ (function(__unused_webpack_module, exports, __webpack_require__) {
27
27
 
28
28
  "use strict";
29
- eval("\n/**\n * connection-tls.ts - connection via tls socket and sqlitecloud protocol\n */\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n});\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n};\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nexports.SQLiteCloudTlsConnection = void 0;\nconst types_1 = __webpack_require__(/*! ./types */ \"./lib/drivers/types.js\");\nconst connection_1 = __webpack_require__(/*! ./connection */ \"./lib/drivers/connection.js\");\nconst utilities_1 = __webpack_require__(/*! ./utilities */ \"./lib/drivers/utilities.js\");\nconst protocol_1 = __webpack_require__(/*! ./protocol */ \"./lib/drivers/protocol.js\");\nconst tls = __importStar(__webpack_require__(/*! tls */ \"?4235\"));\n/**\n * Implementation of SQLiteCloudConnection that connects to the database using specific tls APIs\n * that connect to native sockets or tls sockets and communicates via raw, binary protocol.\n */\nclass SQLiteCloudTlsConnection extends connection_1.SQLiteCloudConnection {\n constructor() {\n super(...arguments);\n // processCommands sets up empty buffers, results callback then send the command to the server via socket.write\n // onData is called when data is received, it will process the data until all data is retrieved for a response\n // when response is complete or there's an error, finish is called to call the results callback set by processCommands...\n // buffer to accumulate incoming data until an whole command is received and can be parsed\n this.buffer = Buffer.alloc(0);\n this.startedOn = new Date();\n }\n /** True if connection is open */\n get connected() {\n return !!this.socket;\n }\n /* Opens a connection with the server and sends the initialization commands. Will throw in case of errors. */\n /* eslint-disable @typescript-eslint/no-unused-vars */\n connectTransport(config, callback) {\n console.assert(!this.connected, 'SQLiteCloudTlsConnection.connect - connection already established');\n if (this.config.verbose) {\n console.debug(`-> connecting ${config === null || config === void 0 ? void 0 : config.host}:${config === null || config === void 0 ? void 0 : config.port}`);\n }\n this.config = config;\n const initializationCommands = (0, utilities_1.getInitializationCommands)(config);\n // connect to plain socket, without encryption, only if insecure parameter specified\n // this option is mainly for testing purposes and is not available on production nodes\n // which would need to connect using tls and proper certificates as per code below\n const connectionOptions = {\n host: config.host,\n port: config.port,\n rejectUnauthorized: config.host != 'localhost',\n // Server name for the SNI (Server Name Indication) TLS extension.\n // https://r2.nodejs.org/docs/v6.11.4/api/tls.html#tls_class_tls_tlssocket\n servername: config.host\n };\n this.socket = tls.connect(connectionOptions, () => {\n var _a;\n if (this.config.verbose) {\n console.debug(`SQLiteCloudTlsConnection - connected to ${this.config.host}, authorized: ${(_a = this.socket) === null || _a === void 0 ? void 0 : _a.authorized}`);\n }\n this.transportCommands(initializationCommands, error => {\n if (this.config.verbose) {\n console.debug(`SQLiteCloudTlsConnection - initialized connection`);\n }\n callback === null || callback === void 0 ? void 0 : callback.call(this, error);\n });\n });\n this.socket.on('data', data => {\n this.processCommandsData(data);\n });\n this.socket.on('error', error => {\n this.close();\n this.processCommandsFinish(new types_1.SQLiteCloudError('Connection error', { errorCode: 'ERR_CONNECTION_ERROR', cause: error }));\n });\n this.socket.on('end', () => {\n this.close();\n if (this.processCallback)\n this.processCommandsFinish(new types_1.SQLiteCloudError('Server ended the connection', { errorCode: 'ERR_CONNECTION_ENDED' }));\n });\n this.socket.on('close', () => {\n this.close();\n this.processCommandsFinish(new types_1.SQLiteCloudError('Connection closed', { errorCode: 'ERR_CONNECTION_CLOSED' }));\n });\n return this;\n }\n /** Will send a command immediately (no queueing), return the rowset/result or throw an error */\n transportCommands(commands, callback) {\n var _a, _b, _c, _d, _e;\n // connection needs to be established?\n if (!this.socket) {\n callback === null || callback === void 0 ? void 0 : callback.call(this, new types_1.SQLiteCloudError('Connection not established', { errorCode: 'ERR_CONNECTION_NOT_ESTABLISHED' }));\n return this;\n }\n // reset buffer and rowset chunks, define response callback\n this.buffer = Buffer.alloc(0);\n this.startedOn = new Date();\n this.processCallback = callback;\n this.executingCommands = commands;\n // compose commands following SCPC protocol\n const formattedCommands = (0, protocol_1.formatCommand)(commands);\n if ((_a = this.config) === null || _a === void 0 ? void 0 : _a.verbose) {\n console.debug(`-> ${formattedCommands}`);\n }\n const timeoutMs = (_c = (_b = this.config) === null || _b === void 0 ? void 0 : _b.timeout) !== null && _c !== void 0 ? _c : 0;\n if (timeoutMs > 0) {\n const timeout = setTimeout(() => {\n var _a;\n callback === null || callback === void 0 ? void 0 : callback.call(this, new types_1.SQLiteCloudError('Connection timeout out', { errorCode: 'ERR_CONNECTION_TIMEOUT' }));\n (_a = this.socket) === null || _a === void 0 ? void 0 : _a.destroy();\n this.socket = undefined;\n }, timeoutMs);\n (_d = this.socket) === null || _d === void 0 ? void 0 : _d.write(formattedCommands, 'utf-8', () => {\n clearTimeout(timeout); // Clear the timeout on successful write\n });\n }\n else {\n (_e = this.socket) === null || _e === void 0 ? void 0 : _e.write(formattedCommands, 'utf-8');\n }\n return this;\n }\n /** Handles data received in response to an outbound command sent by processCommands */\n processCommandsData(data) {\n var _a, _b, _c, _d, _e, _f;\n try {\n // append data to buffer as it arrives\n if (data.length && data.length > 0) {\n this.buffer = Buffer.concat([this.buffer, data]);\n }\n let dataType = (_a = this.buffer) === null || _a === void 0 ? void 0 : _a.subarray(0, 1).toString();\n if ((0, protocol_1.hasCommandLength)(dataType)) {\n const commandLength = (0, protocol_1.parseCommandLength)(this.buffer);\n const hasReceivedEntireCommand = this.buffer.length - this.buffer.indexOf(' ') - 1 >= commandLength ? true : false;\n if (hasReceivedEntireCommand) {\n if ((_b = this.config) === null || _b === void 0 ? void 0 : _b.verbose) {\n let bufferString = this.buffer.toString('utf8');\n if (bufferString.length > 1000) {\n bufferString = bufferString.substring(0, 100) + '...' + bufferString.substring(bufferString.length - 40);\n }\n const elapsedMs = new Date().getTime() - this.startedOn.getTime();\n console.debug(`<- ${bufferString} (${elapsedMs}ms)`);\n }\n // need to decompress this buffer before decoding?\n if (dataType === protocol_1.CMD_COMPRESSED) {\n ;\n ({ buffer: this.buffer, dataType } = (0, protocol_1.decompressBuffer)(this.buffer));\n }\n if (dataType !== protocol_1.CMD_ROWSET_CHUNK) {\n const { data } = (0, protocol_1.popData)(this.buffer);\n (_c = this.processCommandsFinish) === null || _c === void 0 ? void 0 : _c.call(this, null, data);\n }\n else {\n // check if rowset received the ending chunk in which case it can be unpacked\n if ((0, protocol_1.bufferEndsWith)(this.buffer, protocol_1.ROWSET_CHUNKS_END)) {\n const parsedData = (0, protocol_1.parseRowsetChunks)([this.buffer]);\n (_d = this.processCommandsFinish) === null || _d === void 0 ? void 0 : _d.call(this, null, parsedData);\n }\n }\n }\n }\n else {\n // command with no explicit len so make sure that the final character is a space\n const lastChar = this.buffer.subarray(this.buffer.length - 1, this.buffer.length).toString('utf8');\n if (lastChar == ' ') {\n const { data } = (0, protocol_1.popData)(this.buffer);\n (_e = this.processCommandsFinish) === null || _e === void 0 ? void 0 : _e.call(this, null, data);\n }\n }\n }\n catch (error) {\n console.assert(error instanceof Error);\n if (error instanceof Error) {\n (_f = this.processCommandsFinish) === null || _f === void 0 ? void 0 : _f.call(this, error);\n }\n }\n }\n /** Completes a transaction initiated by processCommands */\n processCommandsFinish(error, result) {\n if (error) {\n if (this.processCallback) {\n console.error('processCommandsFinish - error', error);\n }\n else {\n console.warn('processCommandsFinish - error with no registered callback', error);\n }\n }\n if (this.processCallback) {\n this.processCallback(error, result);\n // this.processCallback = undefined\n }\n }\n /** Disconnect immediately, release connection, no events. */\n close() {\n if (this.socket) {\n this.socket.removeAllListeners();\n this.socket.destroy();\n this.socket = undefined;\n }\n this.operations.clear();\n return this;\n }\n}\nexports.SQLiteCloudTlsConnection = SQLiteCloudTlsConnection;\nexports[\"default\"] = SQLiteCloudTlsConnection;\n\n\n//# sourceURL=webpack://sqlitecloud/./lib/drivers/connection-tls.js?");
29
+ eval("\n/**\n * connection-tls.ts - connection via tls socket and sqlitecloud protocol\n */\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n});\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n};\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nexports.SQLiteCloudTlsConnection = void 0;\nconst types_1 = __webpack_require__(/*! ./types */ \"./lib/drivers/types.js\");\nconst connection_1 = __webpack_require__(/*! ./connection */ \"./lib/drivers/connection.js\");\nconst utilities_1 = __webpack_require__(/*! ./utilities */ \"./lib/drivers/utilities.js\");\nconst protocol_1 = __webpack_require__(/*! ./protocol */ \"./lib/drivers/protocol.js\");\nconst tls = __importStar(__webpack_require__(/*! tls */ \"?4235\"));\n/**\n * Implementation of SQLiteCloudConnection that connects to the database using specific tls APIs\n * that connect to native sockets or tls sockets and communicates via raw, binary protocol.\n */\nclass SQLiteCloudTlsConnection extends connection_1.SQLiteCloudConnection {\n constructor() {\n super(...arguments);\n // processCommands sets up empty buffers, results callback then send the command to the server via socket.write\n // onData is called when data is received, it will process the data until all data is retrieved for a response\n // when response is complete or there's an error, finish is called to call the results callback set by processCommands...\n // buffer to accumulate incoming data until an whole command is received and can be parsed\n this.buffer = Buffer.alloc(0);\n this.startedOn = new Date();\n }\n /** True if connection is open */\n get connected() {\n return !!this.socket;\n }\n /* Opens a connection with the server and sends the initialization commands. Will throw in case of errors. */\n /* eslint-disable @typescript-eslint/no-unused-vars */\n connectTransport(config, callback) {\n console.assert(!this.connected, 'SQLiteCloudTlsConnection.connect - connection already established');\n if (this.config.verbose) {\n console.debug(`-> connecting ${config === null || config === void 0 ? void 0 : config.host}:${config === null || config === void 0 ? void 0 : config.port}`);\n }\n this.config = config;\n const initializationCommands = (0, utilities_1.getInitializationCommands)(config);\n // connect to plain socket, without encryption, only if insecure parameter specified\n // this option is mainly for testing purposes and is not available on production nodes\n // which would need to connect using tls and proper certificates as per code below\n const connectionOptions = {\n host: config.host,\n port: config.port,\n rejectUnauthorized: config.host != 'localhost',\n // Server name for the SNI (Server Name Indication) TLS extension.\n // https://r2.nodejs.org/docs/v6.11.4/api/tls.html#tls_class_tls_tlssocket\n servername: config.host\n };\n this.socket = tls.connect(connectionOptions, () => {\n var _a;\n if (this.config.verbose) {\n console.debug(`SQLiteCloudTlsConnection - connected to ${this.config.host}, authorized: ${(_a = this.socket) === null || _a === void 0 ? void 0 : _a.authorized}`);\n }\n this.transportCommands(initializationCommands, error => {\n if (this.config.verbose) {\n console.debug(`SQLiteCloudTlsConnection - initialized connection`);\n }\n callback === null || callback === void 0 ? void 0 : callback.call(this, error);\n });\n });\n this.socket.on('data', data => {\n this.processCommandsData(data);\n });\n this.socket.on('error', error => {\n this.close();\n this.processCommandsFinish(new types_1.SQLiteCloudError('Connection error', { errorCode: 'ERR_CONNECTION_ERROR', cause: error }));\n });\n this.socket.on('end', () => {\n this.close();\n if (this.processCallback)\n this.processCommandsFinish(new types_1.SQLiteCloudError('Server ended the connection', { errorCode: 'ERR_CONNECTION_ENDED' }));\n });\n this.socket.on('close', () => {\n this.close();\n this.processCommandsFinish(new types_1.SQLiteCloudError('Connection closed', { errorCode: 'ERR_CONNECTION_CLOSED' }));\n });\n return this;\n }\n /** Will send a command immediately (no queueing), return the rowset/result or throw an error */\n transportCommands(commands, callback) {\n var _a, _b, _c, _d, _e;\n // connection needs to be established?\n if (!this.socket) {\n callback === null || callback === void 0 ? void 0 : callback.call(this, new types_1.SQLiteCloudError('Connection not established', { errorCode: 'ERR_CONNECTION_NOT_ESTABLISHED' }));\n return this;\n }\n // reset buffer and rowset chunks, define response callback\n this.buffer = Buffer.alloc(0);\n this.startedOn = new Date();\n this.processCallback = callback;\n this.executingCommands = commands;\n // compose commands following SCPC protocol\n const formattedCommands = (0, protocol_1.formatCommand)(commands);\n if ((_a = this.config) === null || _a === void 0 ? void 0 : _a.verbose) {\n console.debug(`-> ${formattedCommands}`);\n }\n const timeoutMs = (_c = (_b = this.config) === null || _b === void 0 ? void 0 : _b.timeout) !== null && _c !== void 0 ? _c : 0;\n if (timeoutMs > 0) {\n const timeout = setTimeout(() => {\n var _a;\n callback === null || callback === void 0 ? void 0 : callback.call(this, new types_1.SQLiteCloudError('Connection timeout out', { errorCode: 'ERR_CONNECTION_TIMEOUT' }));\n (_a = this.socket) === null || _a === void 0 ? void 0 : _a.destroy();\n this.socket = undefined;\n }, timeoutMs);\n (_d = this.socket) === null || _d === void 0 ? void 0 : _d.write(formattedCommands, 'utf-8', () => {\n clearTimeout(timeout); // Clear the timeout on successful write\n });\n }\n else {\n (_e = this.socket) === null || _e === void 0 ? void 0 : _e.write(formattedCommands, 'utf-8');\n }\n return this;\n }\n /** Handles data received in response to an outbound command sent by processCommands */\n processCommandsData(data) {\n var _a, _b, _c, _d, _e, _f;\n try {\n // append data to buffer as it arrives\n if (data.length && data.length > 0) {\n this.buffer = Buffer.concat([this.buffer, data]);\n }\n let dataType = (_a = this.buffer) === null || _a === void 0 ? void 0 : _a.subarray(0, 1).toString();\n if ((0, protocol_1.hasCommandLength)(dataType)) {\n const commandLength = (0, protocol_1.parseCommandLength)(this.buffer);\n const hasReceivedEntireCommand = this.buffer.length - this.buffer.indexOf(' ') - 1 >= commandLength ? true : false;\n if (hasReceivedEntireCommand) {\n if ((_b = this.config) === null || _b === void 0 ? void 0 : _b.verbose) {\n let bufferString = this.buffer.toString('utf8');\n if (bufferString.length > 1000) {\n bufferString = bufferString.substring(0, 100) + '...' + bufferString.substring(bufferString.length - 40);\n }\n const elapsedMs = new Date().getTime() - this.startedOn.getTime();\n console.debug(`<- ${bufferString} (${elapsedMs}ms)`);\n }\n // need to decompress this buffer before decoding?\n if (dataType === protocol_1.CMD_COMPRESSED) {\n ;\n ({ buffer: this.buffer, dataType } = (0, protocol_1.decompressBuffer)(this.buffer));\n }\n if (dataType !== protocol_1.CMD_ROWSET_CHUNK) {\n const { data } = (0, protocol_1.popData)(this.buffer);\n (_c = this.processCommandsFinish) === null || _c === void 0 ? void 0 : _c.call(this, null, data);\n }\n else {\n // check if rowset received the ending chunk in which case it can be unpacked\n if ((0, protocol_1.bufferEndsWith)(this.buffer, protocol_1.ROWSET_CHUNKS_END)) {\n const parsedData = (0, protocol_1.parseRowsetChunks)([this.buffer]);\n (_d = this.processCommandsFinish) === null || _d === void 0 ? void 0 : _d.call(this, null, parsedData);\n }\n }\n }\n }\n else {\n // command with no explicit len so make sure that the final character is a space\n const lastChar = this.buffer.subarray(this.buffer.length - 1, this.buffer.length).toString('utf8');\n if (lastChar == ' ') {\n const { data } = (0, protocol_1.popData)(this.buffer);\n (_e = this.processCommandsFinish) === null || _e === void 0 ? void 0 : _e.call(this, null, data);\n }\n }\n }\n catch (error) {\n console.assert(error instanceof Error);\n if (error instanceof Error) {\n (_f = this.processCommandsFinish) === null || _f === void 0 ? void 0 : _f.call(this, error);\n }\n }\n }\n /** Completes a transaction initiated by processCommands */\n processCommandsFinish(error, result) {\n if (error) {\n if (this.processCallback) {\n console.error('processCommandsFinish - error', error);\n }\n else {\n console.warn('processCommandsFinish - error with no registered callback', error);\n }\n }\n if (this.processCallback) {\n this.processCallback(error, result);\n }\n this.buffer = Buffer.alloc(0);\n }\n /** Disconnect immediately, release connection, no events. */\n close() {\n if (this.socket) {\n this.socket.removeAllListeners();\n this.socket.destroy();\n this.socket = undefined;\n }\n this.operations.clear();\n return this;\n }\n}\nexports.SQLiteCloudTlsConnection = SQLiteCloudTlsConnection;\nexports[\"default\"] = SQLiteCloudTlsConnection;\n\n\n//# sourceURL=webpack://sqlitecloud/./lib/drivers/connection-tls.js?");
30
30
 
31
31
  /***/ }),
32
32
 
@@ -59,7 +59,7 @@ eval("\n/**\n * connection.ts - base abstract class for sqlitecloud server conne
59
59
  /***/ (function(__unused_webpack_module, exports, __webpack_require__) {
60
60
 
61
61
  "use strict";
62
- eval("\n//\n// database.ts - database driver api, implements and extends sqlite3\n//\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n});\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n};\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nexports.Database = void 0;\nconst rowset_1 = __webpack_require__(/*! ./rowset */ \"./lib/drivers/rowset.js\");\nconst types_1 = __webpack_require__(/*! ./types */ \"./lib/drivers/types.js\");\nconst utilities_1 = __webpack_require__(/*! ./utilities */ \"./lib/drivers/utilities.js\");\nconst statement_1 = __webpack_require__(/*! ./statement */ \"./lib/drivers/statement.js\");\nconst eventemitter3_1 = __importDefault(__webpack_require__(/*! eventemitter3 */ \"./node_modules/eventemitter3/index.js\"));\nconst utilities_2 = __webpack_require__(/*! ./utilities */ \"./lib/drivers/utilities.js\");\n// Uses eventemitter3 instead of node events for browser compatibility\n// https://github.com/primus/eventemitter3\n/**\n * Creating a Database object automatically opens a connection to the SQLite database.\n * When the connection is established the Database object emits an open event and calls\n * the optional provided callback. If the connection cannot be established an error event\n * will be emitted and the optional callback is called with the error information.\n */\nclass Database extends eventemitter3_1.default {\n constructor(config, mode, callback) {\n super();\n /** Database connections */\n this.connections = [];\n this.config = typeof config === 'string' ? { connectionstring: config } : config;\n // mode is optional and so is callback\n // https://github.com/TryGhost/node-sqlite3/wiki/API#new-sqlite3databasefilename--mode--callback\n if (typeof mode === 'function') {\n callback = mode;\n mode = undefined;\n }\n // mode is ignored for now\n // opens first connection to the database automatically\n this.getConnection((error, _connection) => {\n if (callback) {\n callback.call(this, error);\n }\n });\n }\n //\n // private methods\n //\n /** Returns first available connection from connection pool */\n getConnection(callback) {\n var _a, _b, _c;\n // TODO sqlitecloud-js / implement database connection pool #10\n if (((_a = this.connections) === null || _a === void 0 ? void 0 : _a.length) > 0) {\n callback === null || callback === void 0 ? void 0 : callback.call(this, null, this.connections[0]);\n }\n else {\n // connect using websocket if tls is not supported or if explicitly requested\n const useWebsocket = utilities_2.isBrowser || ((_b = this.config) === null || _b === void 0 ? void 0 : _b.usewebsocket) || ((_c = this.config) === null || _c === void 0 ? void 0 : _c.gatewayurl);\n if (useWebsocket) {\n // socket.io transport works in both node.js and browser environments and connects via SQLite Cloud Gateway\n Promise.resolve().then(() => __importStar(__webpack_require__(/*! ./connection-ws */ \"./lib/drivers/connection-ws.js\"))).then(module => {\n this.connections.push(new module.default(this.config, error => {\n if (error) {\n this.handleError(this.connections[0], error, callback);\n }\n else {\n console.assert;\n callback === null || callback === void 0 ? void 0 : callback.call(this, null, this.connections[0]);\n this.emitEvent('open');\n }\n }));\n })\n .catch(error => {\n this.handleError(null, error, callback);\n });\n }\n else {\n // tls sockets work only in node.js environments\n Promise.resolve().then(() => __importStar(__webpack_require__(/*! ./connection-tls */ \"./lib/drivers/connection-tls.js\"))).then(module => {\n this.connections.push(new module.default(this.config, error => {\n if (error) {\n this.handleError(this.connections[0], error, callback);\n }\n else {\n console.assert;\n callback === null || callback === void 0 ? void 0 : callback.call(this, null, this.connections[0]);\n this.emitEvent('open');\n }\n }));\n })\n .catch(error => {\n this.handleError(null, error, callback);\n });\n }\n }\n }\n /** Handles an error by closing the connection, calling the callback and/or emitting an error event */\n handleError(connection, error, callback) {\n // an errored connection is thrown out\n if (connection) {\n this.connections = this.connections.filter(c => c !== connection);\n connection.close();\n }\n if (callback) {\n callback.call(this, error);\n }\n else {\n this.emitEvent('error', error);\n }\n }\n /**\n * Some queries like inserts or updates processed via run or exec may generate\n * an empty result (eg. no data was selected), but still have some metadata.\n * For example the server may pass the id of the last row that was modified.\n * In this case the callback results should be empty but the context may contain\n * additional information like lastID, etc.\n * @see https://github.com/TryGhost/node-sqlite3/wiki/API#runsql--param---callback\n * @param results Results received from the server\n * @returns A context object if one makes sense, otherwise undefined\n */\n processContext(results) {\n if (results) {\n if (Array.isArray(results) && results.length > 0) {\n switch (results[0]) {\n case types_1.SQLiteCloudArrayType.ARRAY_TYPE_SQLITE_EXEC:\n return {\n lastID: results[2],\n changes: results[3],\n totalChanges: results[4],\n finalized: results[5] // FINALIZED\n };\n }\n }\n }\n return undefined;\n }\n /** Emits given event with optional arguments on the next tick so callbacks can complete first */\n emitEvent(event, ...args) {\n setTimeout(() => {\n this.emit(event, ...args);\n }, 0);\n }\n //\n // public methods\n //\n /**\n * Returns the configuration with which this database was opened.\n * The configuration is readonly and cannot be changed as there may\n * be multiple connections using the same configuration.\n * @returns {SQLiteCloudConfig} A configuration object\n */\n getConfiguration() {\n return JSON.parse(JSON.stringify(this.config));\n }\n /** Enable verbose mode */\n verbose() {\n this.config.verbose = true;\n for (const connection of this.connections) {\n connection.verbose();\n }\n return this;\n }\n /** Set a configuration option for the database */\n configure(_option, _value) {\n // https://github.com/TryGhost/node-sqlite3/wiki/API#configureoption-value\n return this;\n }\n run(sql, ...params) {\n const { args, callback } = (0, utilities_1.popCallback)(params);\n const preparedSql = (args === null || args === void 0 ? void 0 : args.length) > 0 ? (0, utilities_1.prepareSql)(sql, ...args) : sql;\n this.getConnection((error, connection) => {\n if (error || !connection) {\n this.handleError(null, error, callback);\n }\n else {\n connection.sendCommands(preparedSql, (error, results) => {\n if (error) {\n this.handleError(connection, error, callback);\n }\n else {\n // context may include id of last row inserted, total changes, etc...\n const context = this.processContext(results);\n callback === null || callback === void 0 ? void 0 : callback.call(context || this, null, context ? context : results);\n }\n });\n }\n });\n return this;\n }\n get(sql, ...params) {\n const { args, callback } = (0, utilities_1.popCallback)(params);\n const preparedSql = (args === null || args === void 0 ? void 0 : args.length) > 0 ? (0, utilities_1.prepareSql)(sql, ...args) : sql;\n this.getConnection((error, connection) => {\n if (error || !connection) {\n this.handleError(null, error, callback);\n }\n else {\n connection.sendCommands(preparedSql, (error, results) => {\n if (error) {\n this.handleError(connection, error, callback);\n }\n else {\n if (results && results instanceof rowset_1.SQLiteCloudRowset && results.length > 0) {\n callback === null || callback === void 0 ? void 0 : callback.call(this, null, results[0]);\n }\n else {\n callback === null || callback === void 0 ? void 0 : callback.call(this, null);\n }\n }\n });\n }\n });\n return this;\n }\n all(sql, ...params) {\n const { args, callback } = (0, utilities_1.popCallback)(params);\n const preparedSql = (args === null || args === void 0 ? void 0 : args.length) > 0 ? (0, utilities_1.prepareSql)(sql, ...args) : sql;\n this.getConnection((error, connection) => {\n if (error || !connection) {\n this.handleError(null, error, callback);\n }\n else {\n connection.sendCommands(preparedSql, (error, results) => {\n if (error) {\n this.handleError(connection, error, callback);\n }\n else {\n if (results && results instanceof rowset_1.SQLiteCloudRowset) {\n callback === null || callback === void 0 ? void 0 : callback.call(this, null, results);\n }\n else {\n callback === null || callback === void 0 ? void 0 : callback.call(this, null);\n }\n }\n });\n }\n });\n return this;\n }\n each(sql, ...params) {\n // extract optional parameters and one or two callbacks\n const { args, callback, complete } = (0, utilities_1.popCallback)(params);\n const preparedSql = (args === null || args === void 0 ? void 0 : args.length) > 0 ? (0, utilities_1.prepareSql)(sql, ...args) : sql;\n this.getConnection((error, connection) => {\n if (error || !connection) {\n this.handleError(null, error, callback);\n }\n else {\n connection.sendCommands(preparedSql, (error, rowset) => {\n if (error) {\n this.handleError(connection, error, callback);\n }\n else {\n if (rowset && rowset instanceof rowset_1.SQLiteCloudRowset) {\n if (callback) {\n for (const row of rowset) {\n callback.call(this, null, row);\n }\n }\n if (complete) {\n ;\n complete.call(this, null, rowset.numberOfRows);\n }\n }\n else {\n callback === null || callback === void 0 ? void 0 : callback.call(this, new types_1.SQLiteCloudError('Invalid rowset'));\n }\n }\n });\n }\n });\n return this;\n }\n /**\n * Prepares the SQL statement and optionally binds the specified parameters and\n * calls the callback when done. The function returns a Statement object.\n * When preparing was successful, the first and only argument to the callback\n * is null, otherwise it is the error object. When bind parameters are supplied,\n * they are bound to the prepared statement before calling the callback.\n */\n prepare(sql, ...params) {\n const { args, callback } = (0, utilities_1.popCallback)(params);\n return new statement_1.Statement(this, sql, ...args, callback);\n }\n /**\n * Runs all SQL queries in the supplied string. No result rows are retrieved.\n * The function returns the Database object to allow for function chaining.\n * If a query fails, no subsequent statements will be executed (wrap it in a\n * transaction if you want all or none to be executed). When all statements\n * have been executed successfully, or when an error occurs, the callback\n * function is called, with the first parameter being either null or an error\n * object. When no callback is provided and an error occurs, an error event\n * will be emitted on the database object.\n */\n exec(sql, callback) {\n this.getConnection((error, connection) => {\n if (error || !connection) {\n this.handleError(null, error, callback);\n }\n else {\n connection.sendCommands(sql, (error, results) => {\n if (error) {\n this.handleError(connection, error, callback);\n }\n else {\n const context = this.processContext(results);\n callback === null || callback === void 0 ? void 0 : callback.call(context ? context : this, null);\n }\n });\n }\n });\n return this;\n }\n /**\n * If the optional callback is provided, this function will be called when the\n * database was closed successfully or when an error occurred. The first argument\n * is an error object. When it is null, closing succeeded. If no callback is provided\n * and an error occurred, an error event with the error object as the only parameter\n * will be emitted on the database object. If closing succeeded, a close event with no\n * parameters is emitted, regardless of whether a callback was provided or not.\n */\n close(callback) {\n var _a;\n if (((_a = this.connections) === null || _a === void 0 ? void 0 : _a.length) > 0) {\n for (const connection of this.connections) {\n connection.close();\n }\n }\n callback === null || callback === void 0 ? void 0 : callback.call(this, null);\n this.emitEvent('close');\n }\n /**\n * Loads a compiled SQLite extension into the database connection object.\n * @param path Filename of the extension to load.\n * @param callback If provided, this function will be called when the extension\n * was loaded successfully or when an error occurred. The first argument is an\n * error object. When it is null, loading succeeded. If no callback is provided\n * and an error occurred, an error event with the error object as the only parameter\n * will be emitted on the database object.\n */\n loadExtension(_path, callback) {\n // TODO sqlitecloud-js / implement database loadExtension #17\n if (callback) {\n callback.call(this, new Error('Database.loadExtension - Not implemented'));\n }\n else {\n this.emitEvent('error', new Error('Database.loadExtension - Not implemented'));\n }\n return this;\n }\n /**\n * Allows the user to interrupt long-running queries. Wrapper around\n * sqlite3_interrupt and causes other data-fetching functions to be\n * passed an err with code = sqlite3.INTERRUPT. The database must be\n * open to use this function.\n */\n interrupt() {\n // TODO sqlitecloud-js / implement database interrupt #13\n }\n //\n // extended APIs\n //\n /**\n * Sql is a promise based API for executing SQL statements. You can\n * pass a simple string with a SQL statement or a template string\n * using backticks and parameters in ${parameter} format. These parameters\n * will be properly escaped and quoted like when using a prepared statement.\n * @param sql A sql string or a template string in `backticks` format\n * @returns An array of rows in case of selections or an object with\n * metadata in case of insert, update, delete.\n */\n sql(sql, ...values) {\n return __awaiter(this, void 0, void 0, function* () {\n let preparedSql = '';\n // sql is a TemplateStringsArray, the 'raw' property is specific to TemplateStringsArray\n if (Array.isArray(sql) && 'raw' in sql) {\n sql.forEach((string, i) => {\n preparedSql += string + (i < values.length ? '?' : '');\n });\n preparedSql = (0, utilities_1.prepareSql)(preparedSql, ...values);\n }\n else {\n if (typeof sql === 'string') {\n if ((values === null || values === void 0 ? void 0 : values.length) > 0) {\n preparedSql = (0, utilities_1.prepareSql)(sql, ...values);\n }\n else {\n preparedSql = sql;\n }\n }\n else {\n throw new Error('Invalid sql');\n }\n }\n return new Promise((resolve, reject) => {\n this.getConnection((error, connection) => {\n if (error || !connection) {\n reject(error);\n }\n else {\n connection.sendCommands(preparedSql, (error, results) => {\n if (error) {\n reject(error);\n }\n else {\n // metadata for operations like insert, update, delete?\n const context = this.processContext(results);\n resolve(context ? context : results);\n }\n });\n }\n });\n });\n });\n }\n}\nexports.Database = Database;\n\n\n//# sourceURL=webpack://sqlitecloud/./lib/drivers/database.js?");
62
+ eval("\n//\n// database.ts - database driver api, implements and extends sqlite3\n//\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n});\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n};\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nexports.Database = void 0;\nconst rowset_1 = __webpack_require__(/*! ./rowset */ \"./lib/drivers/rowset.js\");\nconst types_1 = __webpack_require__(/*! ./types */ \"./lib/drivers/types.js\");\nconst utilities_1 = __webpack_require__(/*! ./utilities */ \"./lib/drivers/utilities.js\");\nconst statement_1 = __webpack_require__(/*! ./statement */ \"./lib/drivers/statement.js\");\nconst eventemitter3_1 = __importDefault(__webpack_require__(/*! eventemitter3 */ \"./node_modules/eventemitter3/index.js\"));\nconst utilities_2 = __webpack_require__(/*! ./utilities */ \"./lib/drivers/utilities.js\");\nconst pubsub_1 = __webpack_require__(/*! ./pubsub */ \"./lib/drivers/pubsub.js\");\n// Uses eventemitter3 instead of node events for browser compatibility\n// https://github.com/primus/eventemitter3\n/**\n * Creating a Database object automatically opens a connection to the SQLite database.\n * When the connection is established the Database object emits an open event and calls\n * the optional provided callback. If the connection cannot be established an error event\n * will be emitted and the optional callback is called with the error information.\n */\nclass Database extends eventemitter3_1.default {\n constructor(config, mode, callback) {\n super();\n /** Database connections */\n this.connections = [];\n this.config = typeof config === 'string' ? { connectionstring: config } : config;\n // mode is optional and so is callback\n // https://github.com/TryGhost/node-sqlite3/wiki/API#new-sqlite3databasefilename--mode--callback\n if (typeof mode === 'function') {\n callback = mode;\n mode = undefined;\n }\n // mode is ignored for now\n // opens first connection to the database automatically\n this.getConnection((error, _connection) => {\n if (callback) {\n callback.call(this, error);\n }\n });\n }\n //\n // private methods\n //\n /** Returns first available connection from connection pool */\n getConnection(callback) {\n var _a, _b, _c;\n // TODO sqlitecloud-js / implement database connection pool #10\n if (((_a = this.connections) === null || _a === void 0 ? void 0 : _a.length) > 0) {\n callback === null || callback === void 0 ? void 0 : callback.call(this, null, this.connections[0]);\n }\n else {\n // connect using websocket if tls is not supported or if explicitly requested\n const useWebsocket = utilities_2.isBrowser || ((_b = this.config) === null || _b === void 0 ? void 0 : _b.usewebsocket) || ((_c = this.config) === null || _c === void 0 ? void 0 : _c.gatewayurl);\n if (useWebsocket) {\n // socket.io transport works in both node.js and browser environments and connects via SQLite Cloud Gateway\n Promise.resolve().then(() => __importStar(__webpack_require__(/*! ./connection-ws */ \"./lib/drivers/connection-ws.js\"))).then(module => {\n this.connections.push(new module.default(this.config, error => {\n if (error) {\n this.handleError(this.connections[0], error, callback);\n }\n else {\n console.assert;\n callback === null || callback === void 0 ? void 0 : callback.call(this, null, this.connections[0]);\n this.emitEvent('open');\n }\n }));\n })\n .catch(error => {\n this.handleError(null, error, callback);\n });\n }\n else {\n // tls sockets work only in node.js environments\n Promise.resolve().then(() => __importStar(__webpack_require__(/*! ./connection-tls */ \"./lib/drivers/connection-tls.js\"))).then(module => {\n this.connections.push(new module.default(this.config, error => {\n if (error) {\n this.handleError(this.connections[0], error, callback);\n }\n else {\n console.assert;\n callback === null || callback === void 0 ? void 0 : callback.call(this, null, this.connections[0]);\n this.emitEvent('open');\n }\n }));\n })\n .catch(error => {\n this.handleError(null, error, callback);\n });\n }\n }\n }\n /** Handles an error by closing the connection, calling the callback and/or emitting an error event */\n handleError(connection, error, callback) {\n // an errored connection is thrown out\n if (connection) {\n this.connections = this.connections.filter(c => c !== connection);\n connection.close();\n }\n if (callback) {\n callback.call(this, error);\n }\n else {\n this.emitEvent('error', error);\n }\n }\n /**\n * Some queries like inserts or updates processed via run or exec may generate\n * an empty result (eg. no data was selected), but still have some metadata.\n * For example the server may pass the id of the last row that was modified.\n * In this case the callback results should be empty but the context may contain\n * additional information like lastID, etc.\n * @see https://github.com/TryGhost/node-sqlite3/wiki/API#runsql--param---callback\n * @param results Results received from the server\n * @returns A context object if one makes sense, otherwise undefined\n */\n processContext(results) {\n if (results) {\n if (Array.isArray(results) && results.length > 0) {\n switch (results[0]) {\n case types_1.SQLiteCloudArrayType.ARRAY_TYPE_SQLITE_EXEC:\n return {\n lastID: results[2],\n changes: results[3],\n totalChanges: results[4],\n finalized: results[5] // FINALIZED\n };\n }\n }\n }\n return undefined;\n }\n /** Emits given event with optional arguments on the next tick so callbacks can complete first */\n emitEvent(event, ...args) {\n setTimeout(() => {\n this.emit(event, ...args);\n }, 0);\n }\n //\n // public methods\n //\n /**\n * Returns the configuration with which this database was opened.\n * The configuration is readonly and cannot be changed as there may\n * be multiple connections using the same configuration.\n * @returns {SQLiteCloudConfig} A configuration object\n */\n getConfiguration() {\n return JSON.parse(JSON.stringify(this.config));\n }\n /** Enable verbose mode */\n verbose() {\n this.config.verbose = true;\n for (const connection of this.connections) {\n connection.verbose();\n }\n return this;\n }\n /** Set a configuration option for the database */\n configure(_option, _value) {\n // https://github.com/TryGhost/node-sqlite3/wiki/API#configureoption-value\n return this;\n }\n run(sql, ...params) {\n const { args, callback } = (0, utilities_1.popCallback)(params);\n const preparedSql = (args === null || args === void 0 ? void 0 : args.length) > 0 ? (0, utilities_1.prepareSql)(sql, ...args) : sql;\n this.getConnection((error, connection) => {\n if (error || !connection) {\n this.handleError(null, error, callback);\n }\n else {\n connection.sendCommands(preparedSql, (error, results) => {\n if (error) {\n this.handleError(connection, error, callback);\n }\n else {\n // context may include id of last row inserted, total changes, etc...\n const context = this.processContext(results);\n callback === null || callback === void 0 ? void 0 : callback.call(context || this, null, context ? context : results);\n }\n });\n }\n });\n return this;\n }\n get(sql, ...params) {\n const { args, callback } = (0, utilities_1.popCallback)(params);\n const preparedSql = (args === null || args === void 0 ? void 0 : args.length) > 0 ? (0, utilities_1.prepareSql)(sql, ...args) : sql;\n this.getConnection((error, connection) => {\n if (error || !connection) {\n this.handleError(null, error, callback);\n }\n else {\n connection.sendCommands(preparedSql, (error, results) => {\n if (error) {\n this.handleError(connection, error, callback);\n }\n else {\n if (results && results instanceof rowset_1.SQLiteCloudRowset && results.length > 0) {\n callback === null || callback === void 0 ? void 0 : callback.call(this, null, results[0]);\n }\n else {\n callback === null || callback === void 0 ? void 0 : callback.call(this, null);\n }\n }\n });\n }\n });\n return this;\n }\n all(sql, ...params) {\n const { args, callback } = (0, utilities_1.popCallback)(params);\n const preparedSql = (args === null || args === void 0 ? void 0 : args.length) > 0 ? (0, utilities_1.prepareSql)(sql, ...args) : sql;\n this.getConnection((error, connection) => {\n if (error || !connection) {\n this.handleError(null, error, callback);\n }\n else {\n connection.sendCommands(preparedSql, (error, results) => {\n if (error) {\n this.handleError(connection, error, callback);\n }\n else {\n if (results && results instanceof rowset_1.SQLiteCloudRowset) {\n callback === null || callback === void 0 ? void 0 : callback.call(this, null, results);\n }\n else {\n callback === null || callback === void 0 ? void 0 : callback.call(this, null);\n }\n }\n });\n }\n });\n return this;\n }\n each(sql, ...params) {\n // extract optional parameters and one or two callbacks\n const { args, callback, complete } = (0, utilities_1.popCallback)(params);\n const preparedSql = (args === null || args === void 0 ? void 0 : args.length) > 0 ? (0, utilities_1.prepareSql)(sql, ...args) : sql;\n this.getConnection((error, connection) => {\n if (error || !connection) {\n this.handleError(null, error, callback);\n }\n else {\n connection.sendCommands(preparedSql, (error, rowset) => {\n if (error) {\n this.handleError(connection, error, callback);\n }\n else {\n if (rowset && rowset instanceof rowset_1.SQLiteCloudRowset) {\n if (callback) {\n for (const row of rowset) {\n callback.call(this, null, row);\n }\n }\n if (complete) {\n ;\n complete.call(this, null, rowset.numberOfRows);\n }\n }\n else {\n callback === null || callback === void 0 ? void 0 : callback.call(this, new types_1.SQLiteCloudError('Invalid rowset'));\n }\n }\n });\n }\n });\n return this;\n }\n /**\n * Prepares the SQL statement and optionally binds the specified parameters and\n * calls the callback when done. The function returns a Statement object.\n * When preparing was successful, the first and only argument to the callback\n * is null, otherwise it is the error object. When bind parameters are supplied,\n * they are bound to the prepared statement before calling the callback.\n */\n prepare(sql, ...params) {\n const { args, callback } = (0, utilities_1.popCallback)(params);\n return new statement_1.Statement(this, sql, ...args, callback);\n }\n /**\n * Runs all SQL queries in the supplied string. No result rows are retrieved.\n * The function returns the Database object to allow for function chaining.\n * If a query fails, no subsequent statements will be executed (wrap it in a\n * transaction if you want all or none to be executed). When all statements\n * have been executed successfully, or when an error occurs, the callback\n * function is called, with the first parameter being either null or an error\n * object. When no callback is provided and an error occurs, an error event\n * will be emitted on the database object.\n */\n exec(sql, callback) {\n this.getConnection((error, connection) => {\n if (error || !connection) {\n this.handleError(null, error, callback);\n }\n else {\n connection.sendCommands(sql, (error, results) => {\n if (error) {\n this.handleError(connection, error, callback);\n }\n else {\n const context = this.processContext(results);\n callback === null || callback === void 0 ? void 0 : callback.call(context ? context : this, null);\n }\n });\n }\n });\n return this;\n }\n /**\n * If the optional callback is provided, this function will be called when the\n * database was closed successfully or when an error occurred. The first argument\n * is an error object. When it is null, closing succeeded. If no callback is provided\n * and an error occurred, an error event with the error object as the only parameter\n * will be emitted on the database object. If closing succeeded, a close event with no\n * parameters is emitted, regardless of whether a callback was provided or not.\n */\n close(callback) {\n var _a;\n if (((_a = this.connections) === null || _a === void 0 ? void 0 : _a.length) > 0) {\n for (const connection of this.connections) {\n connection.close();\n }\n }\n callback === null || callback === void 0 ? void 0 : callback.call(this, null);\n this.emitEvent('close');\n }\n /**\n * Loads a compiled SQLite extension into the database connection object.\n * @param path Filename of the extension to load.\n * @param callback If provided, this function will be called when the extension\n * was loaded successfully or when an error occurred. The first argument is an\n * error object. When it is null, loading succeeded. If no callback is provided\n * and an error occurred, an error event with the error object as the only parameter\n * will be emitted on the database object.\n */\n loadExtension(_path, callback) {\n // TODO sqlitecloud-js / implement database loadExtension #17\n if (callback) {\n callback.call(this, new Error('Database.loadExtension - Not implemented'));\n }\n else {\n this.emitEvent('error', new Error('Database.loadExtension - Not implemented'));\n }\n return this;\n }\n /**\n * Allows the user to interrupt long-running queries. Wrapper around\n * sqlite3_interrupt and causes other data-fetching functions to be\n * passed an err with code = sqlite3.INTERRUPT. The database must be\n * open to use this function.\n */\n interrupt() {\n // TODO sqlitecloud-js / implement database interrupt #13\n }\n //\n // extended APIs\n //\n /**\n * Sql is a promise based API for executing SQL statements. You can\n * pass a simple string with a SQL statement or a template string\n * using backticks and parameters in ${parameter} format. These parameters\n * will be properly escaped and quoted like when using a prepared statement.\n * @param sql A sql string or a template string in `backticks` format\n * @returns An array of rows in case of selections or an object with\n * metadata in case of insert, update, delete.\n */\n sql(sql, ...values) {\n return __awaiter(this, void 0, void 0, function* () {\n let preparedSql = '';\n // sql is a TemplateStringsArray, the 'raw' property is specific to TemplateStringsArray\n if (Array.isArray(sql) && 'raw' in sql) {\n sql.forEach((string, i) => {\n preparedSql += string + (i < values.length ? '?' : '');\n });\n preparedSql = (0, utilities_1.prepareSql)(preparedSql, ...values);\n }\n else {\n if (typeof sql === 'string') {\n if ((values === null || values === void 0 ? void 0 : values.length) > 0) {\n preparedSql = (0, utilities_1.prepareSql)(sql, ...values);\n }\n else {\n preparedSql = sql;\n }\n }\n else {\n throw new Error('Invalid sql');\n }\n }\n return new Promise((resolve, reject) => {\n this.getConnection((error, connection) => {\n if (error || !connection) {\n reject(error);\n }\n else {\n connection.sendCommands(preparedSql, (error, results) => {\n if (error) {\n reject(error);\n }\n else {\n // metadata for operations like insert, update, delete?\n const context = this.processContext(results);\n resolve(context ? context : results);\n }\n });\n }\n });\n });\n });\n }\n /**\n * PubSub class provides a Pub/Sub real-time updates and notifications system to\n * allow multiple applications to communicate with each other asynchronously.\n * It allows applications to subscribe to tables and receive notifications whenever\n * data changes in the database table. It also enables sending messages to anyone\n * subscribed to a specific channel.\n * @returns {PubSub} A PubSub object\n */\n getPubSub() {\n return __awaiter(this, void 0, void 0, function* () {\n return new Promise((resolve, reject) => {\n this.getConnection((error, connection) => {\n if (error || !connection) {\n reject(error);\n }\n else {\n resolve(new pubsub_1.PubSub(connection));\n }\n });\n });\n });\n }\n}\nexports.Database = Database;\n\n\n//# sourceURL=webpack://sqlitecloud/./lib/drivers/database.js?");
63
63
 
64
64
  /***/ }),
65
65
 
@@ -70,7 +70,18 @@ eval("\n//\n// database.ts - database driver api, implements and extends sqlite3
70
70
  /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
71
71
 
72
72
  "use strict";
73
- eval("\n//\n// protocol.ts - low level protocol handling for SQLiteCloud transport\n//\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nexports.formatCommand = exports.popData = exports.parseRowsetChunks = exports.bufferEndsWith = exports.bufferStartsWith = exports.parseRowsetHeader = exports.parseArray = exports.parseError = exports.decompressBuffer = exports.parseCommandLength = exports.hasCommandLength = exports.ROWSET_CHUNKS_END = exports.CMD_ARRAY = exports.CMD_COMMAND = exports.CMD_COMPRESSED = exports.CMD_BLOB = exports.CMD_NULL = exports.CMD_JSON = exports.CMD_ROWSET_CHUNK = exports.CMD_ROWSET = exports.CMD_FLOAT = exports.CMD_INT = exports.CMD_ERROR = exports.CMD_ZEROSTRING = exports.CMD_STRING = void 0;\nconst types_1 = __webpack_require__(/*! ./types */ \"./lib/drivers/types.js\");\nconst rowset_1 = __webpack_require__(/*! ./rowset */ \"./lib/drivers/rowset.js\");\nconst lz4 = __webpack_require__(/*! lz4js */ \"./node_modules/lz4js/lz4.js\");\n// The server communicates with clients via commands defined in\n// SQLiteCloud Server Protocol (SCSP), see more at:\n// https://github.com/sqlitecloud/sdk/blob/master/PROTOCOL.md\nexports.CMD_STRING = '+';\nexports.CMD_ZEROSTRING = '!';\nexports.CMD_ERROR = '-';\nexports.CMD_INT = ':';\nexports.CMD_FLOAT = ',';\nexports.CMD_ROWSET = '*';\nexports.CMD_ROWSET_CHUNK = '/';\nexports.CMD_JSON = '#';\nexports.CMD_NULL = '_';\nexports.CMD_BLOB = '$';\nexports.CMD_COMPRESSED = '%';\nexports.CMD_COMMAND = '^';\nexports.CMD_ARRAY = '=';\n// const CMD_RAWJSON = '{'\n// const CMD_PUBSUB = '|'\n// const CMD_RECONNECT = '@'\n// To mark the end of the Rowset, the special string /LEN 0 0 0 is sent (LEN is always 6 in this case)\n// https://github.com/sqlitecloud/sdk/blob/master/PROTOCOL.md#scsp-rowset-chunk\nexports.ROWSET_CHUNKS_END = '/6 0 0 0 ';\n//\n// utility functions\n//\n/** Analyze first character to check if corresponding data type has LEN */\nfunction hasCommandLength(firstCharacter) {\n return firstCharacter == exports.CMD_INT || firstCharacter == exports.CMD_FLOAT || firstCharacter == exports.CMD_NULL ? false : true;\n}\nexports.hasCommandLength = hasCommandLength;\n/** Analyze a command with explict LEN and extract it */\nfunction parseCommandLength(data) {\n return parseInt(data.subarray(1, data.indexOf(' ')).toString('utf8'));\n}\nexports.parseCommandLength = parseCommandLength;\n/** Receive a compressed buffer, decompress with lz4, return buffer and datatype */\nfunction decompressBuffer(buffer) {\n const spaceIndex = buffer.indexOf(' ');\n buffer = buffer.subarray(spaceIndex + 1);\n // extract compressed size\n const compressedSize = parseInt(buffer.subarray(0, buffer.indexOf(' ') + 1).toString('utf8'));\n buffer = buffer.subarray(buffer.indexOf(' ') + 1);\n // extract decompressed size\n const decompressedSize = parseInt(buffer.subarray(0, buffer.indexOf(' ') + 1).toString('utf8'));\n buffer = buffer.subarray(buffer.indexOf(' ') + 1);\n // extract compressed dataType\n const dataType = buffer.subarray(0, 1).toString('utf8');\n const decompressedBuffer = Buffer.alloc(decompressedSize);\n const compressedBuffer = buffer.subarray(buffer.length - compressedSize);\n // lz4js library is javascript and doesn't have types so we silence the type check\n // eslint-disable-next-line\n const decompressionResult = lz4.decompressBlock(compressedBuffer, decompressedBuffer, 0, compressedSize, 0);\n buffer = Buffer.concat([buffer.subarray(0, buffer.length - compressedSize), decompressedBuffer]);\n if (decompressionResult <= 0 || decompressionResult !== decompressedSize) {\n throw new Error(`lz4 decompression error at offset ${decompressionResult}`);\n }\n return { buffer, dataType };\n}\nexports.decompressBuffer = decompressBuffer;\n/** Parse error message or extended error message */\nfunction parseError(buffer, spaceIndex) {\n const errorBuffer = buffer.subarray(spaceIndex + 1);\n const errorString = errorBuffer.toString('utf8');\n const parts = errorString.split(' ');\n let errorCodeStr = parts.shift() || '0'; // Default errorCode is '0' if not present\n let extErrCodeStr = '0'; // Default extended error code\n let offsetCodeStr = '-1'; // Default offset code\n // Split the errorCode by ':' to check for extended error codes\n const errorCodeParts = errorCodeStr.split(':');\n errorCodeStr = errorCodeParts[0];\n if (errorCodeParts.length > 1) {\n extErrCodeStr = errorCodeParts[1];\n if (errorCodeParts.length > 2) {\n offsetCodeStr = errorCodeParts[2];\n }\n }\n // Rest of the error string is the error message\n const errorMessage = parts.join(' ');\n // Parse error codes to integers safely, defaulting to 0 if NaN\n const errorCode = parseInt(errorCodeStr);\n const extErrCode = parseInt(extErrCodeStr);\n const offsetCode = parseInt(offsetCodeStr);\n // create an Error object and add the custom properties\n throw new types_1.SQLiteCloudError(errorMessage, {\n errorCode: errorCode.toString(),\n externalErrorCode: extErrCode.toString(),\n offsetCode\n });\n}\nexports.parseError = parseError;\n/** Parse an array of items (each of which will be parsed by type separately) */\nfunction parseArray(buffer, spaceIndex) {\n const parsedData = [];\n const array = buffer.subarray(spaceIndex + 1, buffer.length);\n const numberOfItems = parseInt(array.subarray(0, spaceIndex - 2).toString('utf8'));\n let arrayItems = array.subarray(array.indexOf(' ') + 1, array.length);\n for (let i = 0; i < numberOfItems; i++) {\n const { data, fwdBuffer: buffer } = popData(arrayItems);\n parsedData.push(data);\n arrayItems = buffer;\n }\n return parsedData;\n}\nexports.parseArray = parseArray;\n/** Parse header in a rowset or chunk of a chunked rowset */\nfunction parseRowsetHeader(buffer) {\n const index = parseInt(buffer.subarray(0, buffer.indexOf(':') + 1).toString());\n buffer = buffer.subarray(buffer.indexOf(':') + 1);\n // extract rowset header\n const { data, fwdBuffer } = popIntegers(buffer, 3);\n return {\n index,\n metadata: {\n version: data[0],\n numberOfRows: data[1],\n numberOfColumns: data[2],\n columns: []\n },\n fwdBuffer\n };\n}\nexports.parseRowsetHeader = parseRowsetHeader;\n/** Extract column names and, optionally, more metadata out of a rowset's header */\nfunction parseRowsetColumnsMetadata(buffer, metadata) {\n function popForward() {\n const { data, fwdBuffer: fwdBuffer } = popData(buffer); // buffer in parent scope\n buffer = fwdBuffer;\n return data;\n }\n for (let i = 0; i < metadata.numberOfColumns; i++) {\n metadata.columns.push({ name: popForward() });\n }\n // extract additional metadata if rowset has version 2\n if (metadata.version == 2) {\n for (let i = 0; i < metadata.numberOfColumns; i++)\n metadata.columns[i].type = popForward();\n for (let i = 0; i < metadata.numberOfColumns; i++)\n metadata.columns[i].database = popForward();\n for (let i = 0; i < metadata.numberOfColumns; i++)\n metadata.columns[i].table = popForward();\n for (let i = 0; i < metadata.numberOfColumns; i++)\n metadata.columns[i].column = popForward(); // original column name\n for (let i = 0; i < metadata.numberOfColumns; i++)\n metadata.columns[i].notNull = popForward();\n for (let i = 0; i < metadata.numberOfColumns; i++)\n metadata.columns[i].primaryKey = popForward();\n for (let i = 0; i < metadata.numberOfColumns; i++)\n metadata.columns[i].autoIncrement = popForward();\n }\n return buffer;\n}\n/** Parse a regular rowset (no chunks) */\nfunction parseRowset(buffer, spaceIndex) {\n buffer = buffer.subarray(spaceIndex + 1, buffer.length);\n const { metadata, fwdBuffer } = parseRowsetHeader(buffer);\n buffer = parseRowsetColumnsMetadata(fwdBuffer, metadata);\n // decode each rowset item\n const data = [];\n for (let j = 0; j < metadata.numberOfRows * metadata.numberOfColumns; j++) {\n const { data: rowData, fwdBuffer } = popData(buffer);\n data.push(rowData);\n buffer = fwdBuffer;\n }\n console.assert(data && data.length === metadata.numberOfRows * metadata.numberOfColumns, 'SQLiteCloudConnection.parseRowset - invalid rowset data');\n return new rowset_1.SQLiteCloudRowset(metadata, data);\n}\nfunction bufferStartsWith(buffer, prefix) {\n return buffer.length >= prefix.length && buffer.subarray(0, prefix.length).toString('utf8') === prefix;\n}\nexports.bufferStartsWith = bufferStartsWith;\nfunction bufferEndsWith(buffer, suffix) {\n return buffer.length >= suffix.length && buffer.subarray(buffer.length - suffix.length, buffer.length).toString('utf8') === suffix;\n}\nexports.bufferEndsWith = bufferEndsWith;\n/**\n * Parse a chunk of a chunked rowset command, eg:\n * *LEN 0:VERS NROWS NCOLS DATA\n * @see https://github.com/sqlitecloud/sdk/blob/master/PROTOCOL.md#scsp-rowset-chunk\n */\nfunction parseRowsetChunks(buffers) {\n let buffer = Buffer.concat(buffers);\n if (!bufferStartsWith(buffer, exports.CMD_ROWSET_CHUNK) || !bufferEndsWith(buffer, exports.ROWSET_CHUNKS_END)) {\n throw new Error('SQLiteCloudConnection.parseRowsetChunks - invalid chunks buffer');\n }\n let metadata = { version: 1, numberOfColumns: 0, numberOfRows: 0, columns: [] };\n const data = [];\n // validate and skip data type\n const dataType = buffer.subarray(0, 1).toString();\n console.assert(dataType === exports.CMD_ROWSET_CHUNK);\n buffer = buffer.subarray(buffer.indexOf(' ') + 1);\n while (buffer.length > 0 && !bufferStartsWith(buffer, exports.ROWSET_CHUNKS_END)) {\n // chunk header, eg: 0:VERS NROWS NCOLS\n const { index: chunkIndex, metadata: chunkMetadata, fwdBuffer } = parseRowsetHeader(buffer);\n buffer = fwdBuffer;\n // first chunk? extract columns metadata\n if (chunkIndex === 1) {\n metadata = chunkMetadata;\n buffer = parseRowsetColumnsMetadata(buffer, metadata);\n }\n else {\n metadata.numberOfRows += chunkMetadata.numberOfRows;\n }\n // extract single rowset row\n for (let k = 0; k < chunkMetadata.numberOfRows * metadata.numberOfColumns; k++) {\n const { data: itemData, fwdBuffer } = popData(buffer);\n data.push(itemData);\n buffer = fwdBuffer;\n }\n }\n console.assert(data && data.length === metadata.numberOfRows * metadata.numberOfColumns, 'parseRowsetChunks - invalid rowset data');\n const rowset = new rowset_1.SQLiteCloudRowset(metadata, data);\n // console.debug(`parseRowsetChunks - ${rowset.numberOfRows} rows, ${rowset.numberOfColumns} columns`)\n return rowset;\n}\nexports.parseRowsetChunks = parseRowsetChunks;\n/** Pop one or more space separated integers from beginning of buffer, move buffer forward */\nfunction popIntegers(buffer, numberOfIntegers = 1) {\n const data = [];\n for (let i = 0; i < numberOfIntegers; i++) {\n const spaceIndex = buffer.indexOf(' ');\n data[i] = parseInt(buffer.subarray(0, spaceIndex).toString());\n buffer = buffer.subarray(spaceIndex + 1);\n }\n return { data, fwdBuffer: buffer };\n}\n/** Parse command, extract its data, return the data and the buffer moved to the first byte after the command */\nfunction popData(buffer) {\n function popResults(data) {\n const fwdBuffer = buffer.subarray(commandEnd);\n return { data, fwdBuffer };\n }\n // first character is the data type\n console.assert(buffer && buffer instanceof Buffer);\n const dataType = buffer.subarray(0, 1).toString('utf8');\n console.assert(dataType !== exports.CMD_COMPRESSED, \"Compressed data shouldn't be decompressed before parsing\");\n console.assert(dataType !== exports.CMD_ROWSET_CHUNK, 'Chunked data should be parsed by parseRowsetChunks');\n let spaceIndex = buffer.indexOf(' ');\n if (spaceIndex === -1) {\n spaceIndex = buffer.length - 1;\n }\n let commandEnd = -1;\n if (dataType === exports.CMD_INT || dataType === exports.CMD_FLOAT || dataType === exports.CMD_NULL) {\n commandEnd = spaceIndex + 1;\n }\n else {\n const commandLength = parseInt(buffer.subarray(1, spaceIndex).toString());\n commandEnd = spaceIndex + 1 + commandLength;\n }\n switch (dataType) {\n case exports.CMD_INT:\n return popResults(parseInt(buffer.subarray(1, spaceIndex).toString()));\n case exports.CMD_FLOAT:\n return popResults(parseFloat(buffer.subarray(1, spaceIndex).toString()));\n case exports.CMD_NULL:\n return popResults(null);\n case exports.CMD_STRING:\n return popResults(buffer.subarray(spaceIndex + 1, commandEnd).toString('utf8'));\n case exports.CMD_ZEROSTRING:\n return popResults(buffer.subarray(spaceIndex + 1, commandEnd - 1).toString('utf8'));\n case exports.CMD_COMMAND:\n return popResults(buffer.subarray(spaceIndex + 1, commandEnd).toString('utf8'));\n case exports.CMD_JSON:\n return popResults(JSON.parse(buffer.subarray(spaceIndex + 1, commandEnd).toString('utf8')));\n case exports.CMD_BLOB:\n return popResults(buffer.subarray(spaceIndex + 1, commandEnd));\n case exports.CMD_ARRAY:\n return popResults(parseArray(buffer, spaceIndex));\n case exports.CMD_ROWSET:\n return popResults(parseRowset(buffer, spaceIndex));\n case exports.CMD_ERROR:\n parseError(buffer, spaceIndex); // throws custom error\n break;\n }\n throw new TypeError(`Data type: ${dataType} is not defined in SCSP`);\n}\nexports.popData = popData;\n/** Format a command to be sent via SCSP protocol */\nfunction formatCommand(command) {\n const commandLength = Buffer.byteLength(command, 'utf-8');\n return `+${commandLength} ${command}`;\n}\nexports.formatCommand = formatCommand;\n\n\n//# sourceURL=webpack://sqlitecloud/./lib/drivers/protocol.js?");
73
+ eval("\n//\n// protocol.ts - low level protocol handling for SQLiteCloud transport\n//\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nexports.formatCommand = exports.popData = exports.parseRowsetChunks = exports.bufferEndsWith = exports.bufferStartsWith = exports.parseRowsetHeader = exports.parseArray = exports.parseError = exports.decompressBuffer = exports.parseCommandLength = exports.hasCommandLength = exports.ROWSET_CHUNKS_END = exports.CMD_PUBSUB = exports.CMD_ARRAY = exports.CMD_COMMAND = exports.CMD_COMPRESSED = exports.CMD_BLOB = exports.CMD_NULL = exports.CMD_JSON = exports.CMD_ROWSET_CHUNK = exports.CMD_ROWSET = exports.CMD_FLOAT = exports.CMD_INT = exports.CMD_ERROR = exports.CMD_ZEROSTRING = exports.CMD_STRING = void 0;\nconst types_1 = __webpack_require__(/*! ./types */ \"./lib/drivers/types.js\");\nconst rowset_1 = __webpack_require__(/*! ./rowset */ \"./lib/drivers/rowset.js\");\nconst lz4 = __webpack_require__(/*! lz4js */ \"./node_modules/lz4js/lz4.js\");\n// The server communicates with clients via commands defined in\n// SQLiteCloud Server Protocol (SCSP), see more at:\n// https://github.com/sqlitecloud/sdk/blob/master/PROTOCOL.md\nexports.CMD_STRING = '+';\nexports.CMD_ZEROSTRING = '!';\nexports.CMD_ERROR = '-';\nexports.CMD_INT = ':';\nexports.CMD_FLOAT = ',';\nexports.CMD_ROWSET = '*';\nexports.CMD_ROWSET_CHUNK = '/';\nexports.CMD_JSON = '#';\nexports.CMD_NULL = '_';\nexports.CMD_BLOB = '$';\nexports.CMD_COMPRESSED = '%';\nexports.CMD_COMMAND = '^';\nexports.CMD_ARRAY = '=';\n// const CMD_RAWJSON = '{'\nexports.CMD_PUBSUB = '|';\n// const CMD_RECONNECT = '@'\n// To mark the end of the Rowset, the special string /LEN 0 0 0 is sent (LEN is always 6 in this case)\n// https://github.com/sqlitecloud/sdk/blob/master/PROTOCOL.md#scsp-rowset-chunk\nexports.ROWSET_CHUNKS_END = '/6 0 0 0 ';\n//\n// utility functions\n//\n/** Analyze first character to check if corresponding data type has LEN */\nfunction hasCommandLength(firstCharacter) {\n return firstCharacter == exports.CMD_INT || firstCharacter == exports.CMD_FLOAT || firstCharacter == exports.CMD_NULL ? false : true;\n}\nexports.hasCommandLength = hasCommandLength;\n/** Analyze a command with explict LEN and extract it */\nfunction parseCommandLength(data) {\n return parseInt(data.subarray(1, data.indexOf(' ')).toString('utf8'));\n}\nexports.parseCommandLength = parseCommandLength;\n/** Receive a compressed buffer, decompress with lz4, return buffer and datatype */\nfunction decompressBuffer(buffer) {\n const spaceIndex = buffer.indexOf(' ');\n buffer = buffer.subarray(spaceIndex + 1);\n // extract compressed size\n const compressedSize = parseInt(buffer.subarray(0, buffer.indexOf(' ') + 1).toString('utf8'));\n buffer = buffer.subarray(buffer.indexOf(' ') + 1);\n // extract decompressed size\n const decompressedSize = parseInt(buffer.subarray(0, buffer.indexOf(' ') + 1).toString('utf8'));\n buffer = buffer.subarray(buffer.indexOf(' ') + 1);\n // extract compressed dataType\n const dataType = buffer.subarray(0, 1).toString('utf8');\n const decompressedBuffer = Buffer.alloc(decompressedSize);\n const compressedBuffer = buffer.subarray(buffer.length - compressedSize);\n // lz4js library is javascript and doesn't have types so we silence the type check\n // eslint-disable-next-line\n const decompressionResult = lz4.decompressBlock(compressedBuffer, decompressedBuffer, 0, compressedSize, 0);\n buffer = Buffer.concat([buffer.subarray(0, buffer.length - compressedSize), decompressedBuffer]);\n if (decompressionResult <= 0 || decompressionResult !== decompressedSize) {\n throw new Error(`lz4 decompression error at offset ${decompressionResult}`);\n }\n return { buffer, dataType };\n}\nexports.decompressBuffer = decompressBuffer;\n/** Parse error message or extended error message */\nfunction parseError(buffer, spaceIndex) {\n const errorBuffer = buffer.subarray(spaceIndex + 1);\n const errorString = errorBuffer.toString('utf8');\n const parts = errorString.split(' ');\n let errorCodeStr = parts.shift() || '0'; // Default errorCode is '0' if not present\n let extErrCodeStr = '0'; // Default extended error code\n let offsetCodeStr = '-1'; // Default offset code\n // Split the errorCode by ':' to check for extended error codes\n const errorCodeParts = errorCodeStr.split(':');\n errorCodeStr = errorCodeParts[0];\n if (errorCodeParts.length > 1) {\n extErrCodeStr = errorCodeParts[1];\n if (errorCodeParts.length > 2) {\n offsetCodeStr = errorCodeParts[2];\n }\n }\n // Rest of the error string is the error message\n const errorMessage = parts.join(' ');\n // Parse error codes to integers safely, defaulting to 0 if NaN\n const errorCode = parseInt(errorCodeStr);\n const extErrCode = parseInt(extErrCodeStr);\n const offsetCode = parseInt(offsetCodeStr);\n // create an Error object and add the custom properties\n throw new types_1.SQLiteCloudError(errorMessage, {\n errorCode: errorCode.toString(),\n externalErrorCode: extErrCode.toString(),\n offsetCode\n });\n}\nexports.parseError = parseError;\n/** Parse an array of items (each of which will be parsed by type separately) */\nfunction parseArray(buffer, spaceIndex) {\n const parsedData = [];\n const array = buffer.subarray(spaceIndex + 1, buffer.length);\n const numberOfItems = parseInt(array.subarray(0, spaceIndex - 2).toString('utf8'));\n let arrayItems = array.subarray(array.indexOf(' ') + 1, array.length);\n for (let i = 0; i < numberOfItems; i++) {\n const { data, fwdBuffer: buffer } = popData(arrayItems);\n parsedData.push(data);\n arrayItems = buffer;\n }\n return parsedData;\n}\nexports.parseArray = parseArray;\n/** Parse header in a rowset or chunk of a chunked rowset */\nfunction parseRowsetHeader(buffer) {\n const index = parseInt(buffer.subarray(0, buffer.indexOf(':') + 1).toString());\n buffer = buffer.subarray(buffer.indexOf(':') + 1);\n // extract rowset header\n const { data, fwdBuffer } = popIntegers(buffer, 3);\n return {\n index,\n metadata: {\n version: data[0],\n numberOfRows: data[1],\n numberOfColumns: data[2],\n columns: []\n },\n fwdBuffer\n };\n}\nexports.parseRowsetHeader = parseRowsetHeader;\n/** Extract column names and, optionally, more metadata out of a rowset's header */\nfunction parseRowsetColumnsMetadata(buffer, metadata) {\n function popForward() {\n const { data, fwdBuffer: fwdBuffer } = popData(buffer); // buffer in parent scope\n buffer = fwdBuffer;\n return data;\n }\n for (let i = 0; i < metadata.numberOfColumns; i++) {\n metadata.columns.push({ name: popForward() });\n }\n // extract additional metadata if rowset has version 2\n if (metadata.version == 2) {\n for (let i = 0; i < metadata.numberOfColumns; i++)\n metadata.columns[i].type = popForward();\n for (let i = 0; i < metadata.numberOfColumns; i++)\n metadata.columns[i].database = popForward();\n for (let i = 0; i < metadata.numberOfColumns; i++)\n metadata.columns[i].table = popForward();\n for (let i = 0; i < metadata.numberOfColumns; i++)\n metadata.columns[i].column = popForward(); // original column name\n for (let i = 0; i < metadata.numberOfColumns; i++)\n metadata.columns[i].notNull = popForward();\n for (let i = 0; i < metadata.numberOfColumns; i++)\n metadata.columns[i].primaryKey = popForward();\n for (let i = 0; i < metadata.numberOfColumns; i++)\n metadata.columns[i].autoIncrement = popForward();\n }\n return buffer;\n}\n/** Parse a regular rowset (no chunks) */\nfunction parseRowset(buffer, spaceIndex) {\n buffer = buffer.subarray(spaceIndex + 1, buffer.length);\n const { metadata, fwdBuffer } = parseRowsetHeader(buffer);\n buffer = parseRowsetColumnsMetadata(fwdBuffer, metadata);\n // decode each rowset item\n const data = [];\n for (let j = 0; j < metadata.numberOfRows * metadata.numberOfColumns; j++) {\n const { data: rowData, fwdBuffer } = popData(buffer);\n data.push(rowData);\n buffer = fwdBuffer;\n }\n console.assert(data && data.length === metadata.numberOfRows * metadata.numberOfColumns, 'SQLiteCloudConnection.parseRowset - invalid rowset data');\n return new rowset_1.SQLiteCloudRowset(metadata, data);\n}\nfunction bufferStartsWith(buffer, prefix) {\n return buffer.length >= prefix.length && buffer.subarray(0, prefix.length).toString('utf8') === prefix;\n}\nexports.bufferStartsWith = bufferStartsWith;\nfunction bufferEndsWith(buffer, suffix) {\n return buffer.length >= suffix.length && buffer.subarray(buffer.length - suffix.length, buffer.length).toString('utf8') === suffix;\n}\nexports.bufferEndsWith = bufferEndsWith;\n/**\n * Parse a chunk of a chunked rowset command, eg:\n * *LEN 0:VERS NROWS NCOLS DATA\n * @see https://github.com/sqlitecloud/sdk/blob/master/PROTOCOL.md#scsp-rowset-chunk\n */\nfunction parseRowsetChunks(buffers) {\n let buffer = Buffer.concat(buffers);\n if (!bufferStartsWith(buffer, exports.CMD_ROWSET_CHUNK) || !bufferEndsWith(buffer, exports.ROWSET_CHUNKS_END)) {\n throw new Error('SQLiteCloudConnection.parseRowsetChunks - invalid chunks buffer');\n }\n let metadata = { version: 1, numberOfColumns: 0, numberOfRows: 0, columns: [] };\n const data = [];\n // validate and skip data type\n const dataType = buffer.subarray(0, 1).toString();\n console.assert(dataType === exports.CMD_ROWSET_CHUNK);\n buffer = buffer.subarray(buffer.indexOf(' ') + 1);\n while (buffer.length > 0 && !bufferStartsWith(buffer, exports.ROWSET_CHUNKS_END)) {\n // chunk header, eg: 0:VERS NROWS NCOLS\n const { index: chunkIndex, metadata: chunkMetadata, fwdBuffer } = parseRowsetHeader(buffer);\n buffer = fwdBuffer;\n // first chunk? extract columns metadata\n if (chunkIndex === 1) {\n metadata = chunkMetadata;\n buffer = parseRowsetColumnsMetadata(buffer, metadata);\n }\n else {\n metadata.numberOfRows += chunkMetadata.numberOfRows;\n }\n // extract single rowset row\n for (let k = 0; k < chunkMetadata.numberOfRows * metadata.numberOfColumns; k++) {\n const { data: itemData, fwdBuffer } = popData(buffer);\n data.push(itemData);\n buffer = fwdBuffer;\n }\n }\n console.assert(data && data.length === metadata.numberOfRows * metadata.numberOfColumns, 'parseRowsetChunks - invalid rowset data');\n const rowset = new rowset_1.SQLiteCloudRowset(metadata, data);\n // console.debug(`parseRowsetChunks - ${rowset.numberOfRows} rows, ${rowset.numberOfColumns} columns`)\n return rowset;\n}\nexports.parseRowsetChunks = parseRowsetChunks;\n/** Pop one or more space separated integers from beginning of buffer, move buffer forward */\nfunction popIntegers(buffer, numberOfIntegers = 1) {\n const data = [];\n for (let i = 0; i < numberOfIntegers; i++) {\n const spaceIndex = buffer.indexOf(' ');\n data[i] = parseInt(buffer.subarray(0, spaceIndex).toString());\n buffer = buffer.subarray(spaceIndex + 1);\n }\n return { data, fwdBuffer: buffer };\n}\n/** Parse command, extract its data, return the data and the buffer moved to the first byte after the command */\nfunction popData(buffer) {\n function popResults(data) {\n const fwdBuffer = buffer.subarray(commandEnd);\n return { data, fwdBuffer };\n }\n // first character is the data type\n console.assert(buffer && buffer instanceof Buffer);\n const dataType = buffer.subarray(0, 1).toString('utf8');\n console.assert(dataType !== exports.CMD_COMPRESSED, \"Compressed data shouldn't be decompressed before parsing\");\n console.assert(dataType !== exports.CMD_ROWSET_CHUNK, 'Chunked data should be parsed by parseRowsetChunks');\n let spaceIndex = buffer.indexOf(' ');\n if (spaceIndex === -1) {\n spaceIndex = buffer.length - 1;\n }\n let commandEnd = -1;\n if (dataType === exports.CMD_INT || dataType === exports.CMD_FLOAT || dataType === exports.CMD_NULL) {\n commandEnd = spaceIndex + 1;\n }\n else {\n const commandLength = parseInt(buffer.subarray(1, spaceIndex).toString());\n commandEnd = spaceIndex + 1 + commandLength;\n }\n switch (dataType) {\n case exports.CMD_INT:\n return popResults(parseInt(buffer.subarray(1, spaceIndex).toString()));\n case exports.CMD_FLOAT:\n return popResults(parseFloat(buffer.subarray(1, spaceIndex).toString()));\n case exports.CMD_NULL:\n return popResults(null);\n case exports.CMD_STRING:\n return popResults(buffer.subarray(spaceIndex + 1, commandEnd).toString('utf8'));\n case exports.CMD_ZEROSTRING:\n return popResults(buffer.subarray(spaceIndex + 1, commandEnd - 1).toString('utf8'));\n case exports.CMD_COMMAND:\n return popResults(buffer.subarray(spaceIndex + 1, commandEnd).toString('utf8'));\n case exports.CMD_PUBSUB:\n return popResults(buffer.subarray(spaceIndex + 1, commandEnd).toString('utf8'));\n case exports.CMD_JSON:\n return popResults(JSON.parse(buffer.subarray(spaceIndex + 1, commandEnd).toString('utf8')));\n case exports.CMD_BLOB:\n return popResults(buffer.subarray(spaceIndex + 1, commandEnd));\n case exports.CMD_ARRAY:\n return popResults(parseArray(buffer, spaceIndex));\n case exports.CMD_ROWSET:\n return popResults(parseRowset(buffer, spaceIndex));\n case exports.CMD_ERROR:\n parseError(buffer, spaceIndex); // throws custom error\n break;\n }\n throw new TypeError(`Data type: ${dataType} is not defined in SCSP`);\n}\nexports.popData = popData;\n/** Format a command to be sent via SCSP protocol */\nfunction formatCommand(command) {\n const commandLength = Buffer.byteLength(command, 'utf-8');\n return `+${commandLength} ${command}`;\n}\nexports.formatCommand = formatCommand;\n\n\n//# sourceURL=webpack://sqlitecloud/./lib/drivers/protocol.js?");
74
+
75
+ /***/ }),
76
+
77
+ /***/ "./lib/drivers/pubsub.js":
78
+ /*!*******************************!*\
79
+ !*** ./lib/drivers/pubsub.js ***!
80
+ \*******************************/
81
+ /***/ (function(__unused_webpack_module, exports, __webpack_require__) {
82
+
83
+ "use strict";
84
+ eval("\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nexports.PubSub = exports.PUBSUB_ENTITY_TYPE = void 0;\nconst connection_tls_1 = __importDefault(__webpack_require__(/*! ./connection-tls */ \"./lib/drivers/connection-tls.js\"));\nvar PUBSUB_ENTITY_TYPE;\n(function (PUBSUB_ENTITY_TYPE) {\n PUBSUB_ENTITY_TYPE[\"TABLE\"] = \"TABLE\";\n PUBSUB_ENTITY_TYPE[\"CHANNEL\"] = \"CHANNEL\";\n})(PUBSUB_ENTITY_TYPE = exports.PUBSUB_ENTITY_TYPE || (exports.PUBSUB_ENTITY_TYPE = {}));\n/**\n * Pub/Sub class to receive changes on database tables or to send messages to channels.\n */\nclass PubSub {\n constructor(connection) {\n this.connection = connection;\n this.connectionPubSub = new connection_tls_1.default(connection.getConfig());\n }\n /**\n * Listen for a table or channel and start to receive messages to the provided callback.\n * @param entityType One of TABLE or CHANNEL'\n * @param entityName Name of the table or the channel\n * @param callback Callback to be called when a message is received\n * @param data Extra data to be passed to the callback\n */\n listen(entityType, entityName, callback, data) {\n return __awaiter(this, void 0, void 0, function* () {\n const entity = entityType === 'TABLE' ? 'TABLE ' : '';\n const authCommand = yield this.connection.sql(`LISTEN ${entity}${entityName};`);\n return new Promise((resolve, reject) => {\n this.connectionPubSub.sendCommands(authCommand, (error, results) => {\n if (error) {\n callback.call(this, error, null, data);\n reject(error);\n }\n else {\n // skip results from pubSub auth command\n if (results !== 'OK') {\n callback.call(this, null, results, data);\n }\n resolve(results);\n }\n });\n });\n });\n }\n /**\n * Stop receive messages from a table or channel.\n * @param entityType One of TABLE or CHANNEL\n * @param entityName Name of the table or the channel\n */\n unlisten(entityType, entityName) {\n return __awaiter(this, void 0, void 0, function* () {\n const subject = entityType === 'TABLE' ? 'TABLE ' : '';\n return this.connection.sql(`UNLISTEN ${subject}?;`, entityName);\n });\n }\n /**\n * Create a channel to send messages to.\n * @param name Channel name\n * @param failIfExists Raise an error if the channel already exists\n */\n createChannel(name, failIfExists = true) {\n return __awaiter(this, void 0, void 0, function* () {\n let notExistsCommand = '';\n if (!failIfExists) {\n notExistsCommand = 'IF NOT EXISTS;';\n }\n return this.connection.sql(`CREATE CHANNEL ? ${notExistsCommand}`, name);\n });\n }\n /**\n * Send a message to the channel.\n */\n notifyChannel(channelName, message) {\n return this.connection.sql `NOTIFY ${channelName} ${message};`;\n }\n /**\n * Ask the server to close the connection to the database and\n * to keep only open the Pub/Sub connection.\n * Only interaction with Pub/Sub commands will be allowed.\n */\n setPubSubOnly() {\n return new Promise((resolve, reject) => {\n this.connection.sendCommands('PUBSUB ONLY;', (error, results) => {\n if (error) {\n reject(error);\n }\n else {\n this.connection.close();\n resolve(results);\n }\n });\n });\n }\n /** True if Pub/Sub connection is open. */\n connected() {\n return this.connectionPubSub.connected;\n }\n /** Close Pub/Sub connection. */\n close() {\n this.connectionPubSub.close();\n }\n}\nexports.PubSub = PubSub;\n\n\n//# sourceURL=webpack://sqlitecloud/./lib/drivers/pubsub.js?");
74
85
 
75
86
  /***/ }),
76
87
 
@@ -1 +1 @@
1
- !function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.sqlitecloud=t():e.sqlitecloud=t()}(this,(()=>(()=>{var e={945:function(e,t,n){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,n,r){void 0===r&&(r=n);var s=Object.getOwnPropertyDescriptor(t,n);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,s)}:function(e,t,n,r){void 0===r&&(r=n),e[r]=t[n]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&r(t,e,n);return s(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.SQLiteCloudTlsConnection=void 0;const i=n(80),a=n(361),c=n(193),u=n(773),l=o(n(498));class h extends a.SQLiteCloudConnection{constructor(){super(...arguments),this.buffer=Buffer.alloc(0),this.startedOn=new Date}get connected(){return!!this.socket}connectTransport(e,t){console.assert(!this.connected,"SQLiteCloudTlsConnection.connect - connection already established"),this.config.verbose&&console.debug(`-> connecting ${null==e?void 0:e.host}:${null==e?void 0:e.port}`),this.config=e;const n=(0,c.getInitializationCommands)(e),r={host:e.host,port:e.port,rejectUnauthorized:"localhost"!=e.host,servername:e.host};return this.socket=l.connect(r,(()=>{var e;this.config.verbose&&console.debug(`SQLiteCloudTlsConnection - connected to ${this.config.host}, authorized: ${null===(e=this.socket)||void 0===e?void 0:e.authorized}`),this.transportCommands(n,(e=>{this.config.verbose&&console.debug("SQLiteCloudTlsConnection - initialized connection"),null==t||t.call(this,e)}))})),this.socket.on("data",(e=>{this.processCommandsData(e)})),this.socket.on("error",(e=>{this.close(),this.processCommandsFinish(new i.SQLiteCloudError("Connection error",{errorCode:"ERR_CONNECTION_ERROR",cause:e}))})),this.socket.on("end",(()=>{this.close(),this.processCallback&&this.processCommandsFinish(new i.SQLiteCloudError("Server ended the connection",{errorCode:"ERR_CONNECTION_ENDED"}))})),this.socket.on("close",(()=>{this.close(),this.processCommandsFinish(new i.SQLiteCloudError("Connection closed",{errorCode:"ERR_CONNECTION_CLOSED"}))})),this}transportCommands(e,t){var n,r,s,o,a;if(!this.socket)return null==t||t.call(this,new i.SQLiteCloudError("Connection not established",{errorCode:"ERR_CONNECTION_NOT_ESTABLISHED"})),this;this.buffer=Buffer.alloc(0),this.startedOn=new Date,this.processCallback=t,this.executingCommands=e;const c=(0,u.formatCommand)(e);(null===(n=this.config)||void 0===n?void 0:n.verbose)&&console.debug(`-> ${c}`);const l=null!==(s=null===(r=this.config)||void 0===r?void 0:r.timeout)&&void 0!==s?s:0;if(l>0){const e=setTimeout((()=>{var e;null==t||t.call(this,new i.SQLiteCloudError("Connection timeout out",{errorCode:"ERR_CONNECTION_TIMEOUT"})),null===(e=this.socket)||void 0===e||e.destroy(),this.socket=void 0}),l);null===(o=this.socket)||void 0===o||o.write(c,"utf-8",(()=>{clearTimeout(e)}))}else null===(a=this.socket)||void 0===a||a.write(c,"utf-8");return this}processCommandsData(e){var t,n,r,s,o,i;try{e.length&&e.length>0&&(this.buffer=Buffer.concat([this.buffer,e]));let i=null===(t=this.buffer)||void 0===t?void 0:t.subarray(0,1).toString();if((0,u.hasCommandLength)(i)){const e=(0,u.parseCommandLength)(this.buffer);if(this.buffer.length-this.buffer.indexOf(" ")-1>=e){if(null===(n=this.config)||void 0===n?void 0:n.verbose){let e=this.buffer.toString("utf8");e.length>1e3&&(e=e.substring(0,100)+"..."+e.substring(e.length-40));const t=(new Date).getTime()-this.startedOn.getTime();console.debug(`<- ${e} (${t}ms)`)}if(i===u.CMD_COMPRESSED&&({buffer:this.buffer,dataType:i}=(0,u.decompressBuffer)(this.buffer)),i!==u.CMD_ROWSET_CHUNK){const{data:e}=(0,u.popData)(this.buffer);null===(r=this.processCommandsFinish)||void 0===r||r.call(this,null,e)}else if((0,u.bufferEndsWith)(this.buffer,u.ROWSET_CHUNKS_END)){const e=(0,u.parseRowsetChunks)([this.buffer]);null===(s=this.processCommandsFinish)||void 0===s||s.call(this,null,e)}}}else if(" "==this.buffer.subarray(this.buffer.length-1,this.buffer.length).toString("utf8")){const{data:e}=(0,u.popData)(this.buffer);null===(o=this.processCommandsFinish)||void 0===o||o.call(this,null,e)}}catch(e){console.assert(e instanceof Error),e instanceof Error&&(null===(i=this.processCommandsFinish)||void 0===i||i.call(this,e))}}processCommandsFinish(e,t){e&&(this.processCallback?console.error("processCommandsFinish - error",e):console.warn("processCommandsFinish - error with no registered callback",e)),this.processCallback&&this.processCallback(e,t)}close(){return this.socket&&(this.socket.removeAllListeners(),this.socket.destroy(),this.socket=void 0),this.operations.clear(),this}}t.SQLiteCloudTlsConnection=h,t.default=h},392:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SQLiteCloudWebsocketConnection=void 0;const r=n(80),s=n(121),o=n(361),i=n(7);class a extends o.SQLiteCloudConnection{get connected(){return!!this.socket}connectTransport(e,t){var n;try{if(console.assert(!this.connected,"Connection already established"),!this.socket){this.config=e;const t=this.config.connectionstring,r=(null===(n=this.config)||void 0===n?void 0:n.gatewayurl)||`${"localhost"===this.config.host?"ws":"wss"}://${this.config.host}:4000`;this.socket=(0,i.io)(r,{auth:{token:t}})}null==t||t.call(this,null)}catch(e){null==t||t.call(this,e)}return this}transportCommands(e,t){return this.socket?(this.socket.emit("v1/sql",{sql:e,row:"array"},(e=>{if(null==e?void 0:e.error){const n=new r.SQLiteCloudError(e.error.detail,Object.assign({},e.error));null==t||t.call(this,n)}else{const{data:n,metadata:r}=e;if(n&&r&&void 0!==r.numberOfRows&&void 0!==r.numberOfColumns&&void 0!==r.columns){console.assert(Array.isArray(n),"SQLiteCloudWebsocketConnection.transportCommands - data is not an array");const e=new s.SQLiteCloudRowset(r,n.flat());return void(null==t||t.call(this,null,e))}null==t||t.call(this,null,null==e?void 0:e.data)}})),this):(null==t||t.call(this,new r.SQLiteCloudError("Connection not established",{errorCode:"ERR_CONNECTION_NOT_ESTABLISHED"})),this)}close(){var e;return console.assert(null!==this.socket,"SQLiteCloudWebsocketConnection.close - connection already closed"),this.socket&&(null===(e=this.socket)||void 0===e||e.close(),this.socket=void 0),this.operations.clear(),this.socket=void 0,this}}t.SQLiteCloudWebsocketConnection=a,t.default=a},361:function(e,t,n){"use strict";var r=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(s,o){function i(e){try{c(r.next(e))}catch(e){o(e)}}function a(e){try{c(r.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?s(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}c((r=r.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.SQLiteCloudConnection=void 0;const s=n(80),o=n(193),i=n(774),a=n(193);t.SQLiteCloudConnection=class{constructor(e,t){this.operations=new i.OperationsQueue,this.config="string"==typeof e?(0,o.validateConfiguration)({connectionstring:e}):(0,o.validateConfiguration)(e),this.connect(t)}getConfig(){return Object.assign({},this.config)}connect(e){return this.operations.enqueue((t=>{this.connectTransport(this.config,(n=>{n&&(console.error(`SQLiteCloudConnection.connect - error connecting ${this.config.host}:${this.config.port} ${n.toString()}`,n),this.close()),e&&e.call(this,n||null),t(n)}))})),this}log(e,...t){this.config.verbose&&(e=(0,a.anonimizeCommand)(e),console.log(`${(new Date).toISOString()} ${this.config.clientid}: ${e}`,...t))}verbose(){this.config.verbose=!0}sendCommands(e,t){return this.operations.enqueue((n=>{if(this.connected)this.transportCommands(e,((e,r)=>{null==t||t.call(this,e,r),n(e)}));else{const e=new s.SQLiteCloudError("Connection not established",{errorCode:"ERR_CONNECTION_NOT_ESTABLISHED"});null==t||t.call(this,e),n(e)}})),this}sql(e,...t){return r(this,void 0,void 0,(function*(){let n="";if(Array.isArray(e)&&"raw"in e)e.forEach(((e,r)=>{n+=e+(r<t.length?"?":"")})),n=(0,o.prepareSql)(n,...t);else{if("string"!=typeof e)throw new Error("Invalid sql");n=(null==t?void 0:t.length)>0?(0,o.prepareSql)(e,...t):e}return new Promise(((e,t)=>{this.sendCommands(n,((n,r)=>{if(n)t(n);else{const t=(0,a.getUpdateResults)(r);e(t||r)}}))}))}))}}},500:function(e,t,n){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,n,r){void 0===r&&(r=n);var s=Object.getOwnPropertyDescriptor(t,n);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,s)}:function(e,t,n,r){void 0===r&&(r=n),e[r]=t[n]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&r(t,e,n);return s(t,e),t},i=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(s,o){function i(e){try{c(r.next(e))}catch(e){o(e)}}function a(e){try{c(r.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?s(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}c((r=r.apply(e,t||[])).next())}))},a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.Database=void 0;const c=n(121),u=n(80),l=n(193),h=n(96),d=a(n(228)),f=n(193);class p extends d.default{constructor(e,t,n){super(),this.connections=[],this.config="string"==typeof e?{connectionstring:e}:e,"function"==typeof t&&(n=t,t=void 0),this.getConnection(((e,t)=>{n&&n.call(this,e)}))}getConnection(e){var t,r,s;(null===(t=this.connections)||void 0===t?void 0:t.length)>0?null==e||e.call(this,null,this.connections[0]):f.isBrowser||(null===(r=this.config)||void 0===r?void 0:r.usewebsocket)||(null===(s=this.config)||void 0===s?void 0:s.gatewayurl)?Promise.resolve().then((()=>o(n(392)))).then((t=>{this.connections.push(new t.default(this.config,(t=>{t?this.handleError(this.connections[0],t,e):(console.assert,null==e||e.call(this,null,this.connections[0]),this.emitEvent("open"))})))})).catch((t=>{this.handleError(null,t,e)})):Promise.resolve().then((()=>o(n(945)))).then((t=>{this.connections.push(new t.default(this.config,(t=>{t?this.handleError(this.connections[0],t,e):(console.assert,null==e||e.call(this,null,this.connections[0]),this.emitEvent("open"))})))})).catch((t=>{this.handleError(null,t,e)}))}handleError(e,t,n){e&&(this.connections=this.connections.filter((t=>t!==e)),e.close()),n?n.call(this,t):this.emitEvent("error",t)}processContext(e){if(e&&Array.isArray(e)&&e.length>0&&e[0]===u.SQLiteCloudArrayType.ARRAY_TYPE_SQLITE_EXEC)return{lastID:e[2],changes:e[3],totalChanges:e[4],finalized:e[5]}}emitEvent(e,...t){setTimeout((()=>{this.emit(e,...t)}),0)}getConfiguration(){return JSON.parse(JSON.stringify(this.config))}verbose(){this.config.verbose=!0;for(const e of this.connections)e.verbose();return this}configure(e,t){return this}run(e,...t){const{args:n,callback:r}=(0,l.popCallback)(t),s=(null==n?void 0:n.length)>0?(0,l.prepareSql)(e,...n):e;return this.getConnection(((e,t)=>{e||!t?this.handleError(null,e,r):t.sendCommands(s,((e,n)=>{if(e)this.handleError(t,e,r);else{const e=this.processContext(n);null==r||r.call(e||this,null,e||n)}}))})),this}get(e,...t){const{args:n,callback:r}=(0,l.popCallback)(t),s=(null==n?void 0:n.length)>0?(0,l.prepareSql)(e,...n):e;return this.getConnection(((e,t)=>{e||!t?this.handleError(null,e,r):t.sendCommands(s,((e,n)=>{e?this.handleError(t,e,r):n&&n instanceof c.SQLiteCloudRowset&&n.length>0?null==r||r.call(this,null,n[0]):null==r||r.call(this,null)}))})),this}all(e,...t){const{args:n,callback:r}=(0,l.popCallback)(t),s=(null==n?void 0:n.length)>0?(0,l.prepareSql)(e,...n):e;return this.getConnection(((e,t)=>{e||!t?this.handleError(null,e,r):t.sendCommands(s,((e,n)=>{e?this.handleError(t,e,r):n&&n instanceof c.SQLiteCloudRowset?null==r||r.call(this,null,n):null==r||r.call(this,null)}))})),this}each(e,...t){const{args:n,callback:r,complete:s}=(0,l.popCallback)(t),o=(null==n?void 0:n.length)>0?(0,l.prepareSql)(e,...n):e;return this.getConnection(((e,t)=>{e||!t?this.handleError(null,e,r):t.sendCommands(o,((e,n)=>{if(e)this.handleError(t,e,r);else if(n&&n instanceof c.SQLiteCloudRowset){if(r)for(const e of n)r.call(this,null,e);s&&s.call(this,null,n.numberOfRows)}else null==r||r.call(this,new u.SQLiteCloudError("Invalid rowset"))}))})),this}prepare(e,...t){const{args:n,callback:r}=(0,l.popCallback)(t);return new h.Statement(this,e,...n,r)}exec(e,t){return this.getConnection(((n,r)=>{n||!r?this.handleError(null,n,t):r.sendCommands(e,((e,n)=>{if(e)this.handleError(r,e,t);else{const e=this.processContext(n);null==t||t.call(e||this,null)}}))})),this}close(e){var t;if((null===(t=this.connections)||void 0===t?void 0:t.length)>0)for(const e of this.connections)e.close();null==e||e.call(this,null),this.emitEvent("close")}loadExtension(e,t){return t?t.call(this,new Error("Database.loadExtension - Not implemented")):this.emitEvent("error",new Error("Database.loadExtension - Not implemented")),this}interrupt(){}sql(e,...t){return i(this,void 0,void 0,(function*(){let n="";if(Array.isArray(e)&&"raw"in e)e.forEach(((e,r)=>{n+=e+(r<t.length?"?":"")})),n=(0,l.prepareSql)(n,...t);else{if("string"!=typeof e)throw new Error("Invalid sql");n=(null==t?void 0:t.length)>0?(0,l.prepareSql)(e,...t):e}return new Promise(((e,t)=>{this.getConnection(((r,s)=>{r||!s?t(r):s.sendCommands(n,((n,r)=>{if(n)t(n);else{const t=this.processContext(r);e(t||r)}}))}))}))}))}}t.Database=p},773:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.formatCommand=t.popData=t.parseRowsetChunks=t.bufferEndsWith=t.bufferStartsWith=t.parseRowsetHeader=t.parseArray=t.parseError=t.decompressBuffer=t.parseCommandLength=t.hasCommandLength=t.ROWSET_CHUNKS_END=t.CMD_ARRAY=t.CMD_COMMAND=t.CMD_COMPRESSED=t.CMD_BLOB=t.CMD_NULL=t.CMD_JSON=t.CMD_ROWSET_CHUNK=t.CMD_ROWSET=t.CMD_FLOAT=t.CMD_INT=t.CMD_ERROR=t.CMD_ZEROSTRING=t.CMD_STRING=void 0;const r=n(80),s=n(121),o=n(404);function i(e,t){const n=e.subarray(t+1).toString("utf8").split(" ");let s=n.shift()||"0",o="0",i="-1";const a=s.split(":");s=a[0],a.length>1&&(o=a[1],a.length>2&&(i=a[2]));const c=n.join(" "),u=parseInt(s),l=parseInt(o),h=parseInt(i);throw new r.SQLiteCloudError(c,{errorCode:u.toString(),externalErrorCode:l.toString(),offsetCode:h})}function a(e,t){const n=[],r=e.subarray(t+1,e.length),s=parseInt(r.subarray(0,t-2).toString("utf8"));let o=r.subarray(r.indexOf(" ")+1,r.length);for(let e=0;e<s;e++){const{data:e,fwdBuffer:t}=d(o);n.push(e),o=t}return n}function c(e){const t=parseInt(e.subarray(0,e.indexOf(":")+1).toString());e=e.subarray(e.indexOf(":")+1);const{data:n,fwdBuffer:r}=function(e,t=1){const n=[];for(let r=0;r<t;r++){const t=e.indexOf(" ");n[r]=parseInt(e.subarray(0,t).toString()),e=e.subarray(t+1)}return{data:n,fwdBuffer:e}}(e,3);return{index:t,metadata:{version:n[0],numberOfRows:n[1],numberOfColumns:n[2],columns:[]},fwdBuffer:r}}function u(e,t){function n(){const{data:t,fwdBuffer:n}=d(e);return e=n,t}for(let e=0;e<t.numberOfColumns;e++)t.columns.push({name:n()});if(2==t.version){for(let e=0;e<t.numberOfColumns;e++)t.columns[e].type=n();for(let e=0;e<t.numberOfColumns;e++)t.columns[e].database=n();for(let e=0;e<t.numberOfColumns;e++)t.columns[e].table=n();for(let e=0;e<t.numberOfColumns;e++)t.columns[e].column=n();for(let e=0;e<t.numberOfColumns;e++)t.columns[e].notNull=n();for(let e=0;e<t.numberOfColumns;e++)t.columns[e].primaryKey=n();for(let e=0;e<t.numberOfColumns;e++)t.columns[e].autoIncrement=n()}return e}function l(e,t){return e.length>=t.length&&e.subarray(0,t.length).toString("utf8")===t}function h(e,t){return e.length>=t.length&&e.subarray(e.length-t.length,e.length).toString("utf8")===t}function d(e){function n(t){return{data:t,fwdBuffer:e.subarray(l)}}console.assert(e&&e instanceof Buffer);const r=e.subarray(0,1).toString("utf8");console.assert(r!==t.CMD_COMPRESSED,"Compressed data shouldn't be decompressed before parsing"),console.assert(r!==t.CMD_ROWSET_CHUNK,"Chunked data should be parsed by parseRowsetChunks");let o=e.indexOf(" ");-1===o&&(o=e.length-1);let l=-1;if(r===t.CMD_INT||r===t.CMD_FLOAT||r===t.CMD_NULL)l=o+1;else{const t=parseInt(e.subarray(1,o).toString());l=o+1+t}switch(r){case t.CMD_INT:return n(parseInt(e.subarray(1,o).toString()));case t.CMD_FLOAT:return n(parseFloat(e.subarray(1,o).toString()));case t.CMD_NULL:return n(null);case t.CMD_STRING:return n(e.subarray(o+1,l).toString("utf8"));case t.CMD_ZEROSTRING:return n(e.subarray(o+1,l-1).toString("utf8"));case t.CMD_COMMAND:return n(e.subarray(o+1,l).toString("utf8"));case t.CMD_JSON:return n(JSON.parse(e.subarray(o+1,l).toString("utf8")));case t.CMD_BLOB:return n(e.subarray(o+1,l));case t.CMD_ARRAY:return n(a(e,o));case t.CMD_ROWSET:return n(function(e,t){e=e.subarray(t+1,e.length);const{metadata:n,fwdBuffer:r}=c(e);e=u(r,n);const o=[];for(let t=0;t<n.numberOfRows*n.numberOfColumns;t++){const{data:t,fwdBuffer:n}=d(e);o.push(t),e=n}return console.assert(o&&o.length===n.numberOfRows*n.numberOfColumns,"SQLiteCloudConnection.parseRowset - invalid rowset data"),new s.SQLiteCloudRowset(n,o)}(e,o));case t.CMD_ERROR:i(e,o)}throw new TypeError(`Data type: ${r} is not defined in SCSP`)}t.CMD_STRING="+",t.CMD_ZEROSTRING="!",t.CMD_ERROR="-",t.CMD_INT=":",t.CMD_FLOAT=",",t.CMD_ROWSET="*",t.CMD_ROWSET_CHUNK="/",t.CMD_JSON="#",t.CMD_NULL="_",t.CMD_BLOB="$",t.CMD_COMPRESSED="%",t.CMD_COMMAND="^",t.CMD_ARRAY="=",t.ROWSET_CHUNKS_END="/6 0 0 0 ",t.hasCommandLength=function(e){return e!=t.CMD_INT&&e!=t.CMD_FLOAT&&e!=t.CMD_NULL},t.parseCommandLength=function(e){return parseInt(e.subarray(1,e.indexOf(" ")).toString("utf8"))},t.decompressBuffer=function(e){const t=e.indexOf(" ");e=e.subarray(t+1);const n=parseInt(e.subarray(0,e.indexOf(" ")+1).toString("utf8"));e=e.subarray(e.indexOf(" ")+1);const r=parseInt(e.subarray(0,e.indexOf(" ")+1).toString("utf8")),s=(e=e.subarray(e.indexOf(" ")+1)).subarray(0,1).toString("utf8"),i=Buffer.alloc(r),a=e.subarray(e.length-n),c=o.decompressBlock(a,i,0,n,0);if(e=Buffer.concat([e.subarray(0,e.length-n),i]),c<=0||c!==r)throw new Error(`lz4 decompression error at offset ${c}`);return{buffer:e,dataType:s}},t.parseError=i,t.parseArray=a,t.parseRowsetHeader=c,t.bufferStartsWith=l,t.bufferEndsWith=h,t.parseRowsetChunks=function(e){let n=Buffer.concat(e);if(!l(n,t.CMD_ROWSET_CHUNK)||!h(n,t.ROWSET_CHUNKS_END))throw new Error("SQLiteCloudConnection.parseRowsetChunks - invalid chunks buffer");let r={version:1,numberOfColumns:0,numberOfRows:0,columns:[]};const o=[],i=n.subarray(0,1).toString();for(console.assert(i===t.CMD_ROWSET_CHUNK),n=n.subarray(n.indexOf(" ")+1);n.length>0&&!l(n,t.ROWSET_CHUNKS_END);){const{index:e,metadata:t,fwdBuffer:s}=c(n);n=s,1===e?(r=t,n=u(n,r)):r.numberOfRows+=t.numberOfRows;for(let e=0;e<t.numberOfRows*r.numberOfColumns;e++){const{data:e,fwdBuffer:t}=d(n);o.push(e),n=t}}return console.assert(o&&o.length===r.numberOfRows*r.numberOfColumns,"parseRowsetChunks - invalid rowset data"),new s.SQLiteCloudRowset(r,o)},t.popData=d,t.formatCommand=function(e){return`+${Buffer.byteLength(e,"utf-8")} ${e}`}},774:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OperationsQueue=void 0,t.OperationsQueue=class{constructor(){this.queue=[],this.isProcessing=!1}enqueue(e){this.queue.push(e),this.isProcessing||this.processNext()}clear(){this.queue=[],this.isProcessing=!1}processNext(){if(0===this.queue.length)return void(this.isProcessing=!1);this.isProcessing=!0;const e=this.queue.shift();null==e||e((()=>{this.processNext()}))}}},121:function(e,t,n){"use strict";var r,s,o,i,a=this&&this.__classPrivateFieldSet||function(e,t,n,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,n):s?s.value=n:t.set(e,n),n},c=this&&this.__classPrivateFieldGet||function(e,t,n,r){if("a"===n&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?r:"a"===n?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.SQLiteCloudRowset=t.SQLiteCloudRow=void 0;const u=n(80);class l{constructor(e,t,n){r.set(this,void 0),s.set(this,void 0),a(this,r,e,"f"),a(this,s,n,"f");for(let e=0;e<t.length;e++)this[t[e]]=n[e]}getRowset(){return c(this,r,"f")}getData(){return c(this,s,"f")}}t.SQLiteCloudRow=l,r=new WeakMap,s=new WeakMap;class h extends Array{constructor(e,t){super(e.numberOfRows),o.set(this,void 0),i.set(this,void 0),a(this,o,e,"f"),a(this,i,t,"f");const n=this.columnsNames;for(let t=0;t<e.numberOfColumns;t++){n[t]||(n[t]=`column_${t}`);let e=0;for(;n.findIndex(((e,r)=>r!==t&&e===n[t]))>=0;)n[t]=`${n[t]}_${e}`,e++}for(let r=0,s=0;r<e.numberOfRows;r++,s+=e.numberOfColumns)this[r]=new l(this,n,t.slice(s,s+e.numberOfColumns))}get version(){return c(this,o,"f").version}get numberOfRows(){return c(this,o,"f").numberOfRows}get numberOfColumns(){return c(this,o,"f").numberOfColumns}get columnsNames(){return c(this,o,"f").columns.map((e=>e.name))}get metadata(){return c(this,o,"f")}getItem(e,t){if(e<0||e>=this.numberOfRows||t<0||t>=this.numberOfColumns)throw new u.SQLiteCloudError(`This rowset has ${this.numberOfColumns} columns by ${this.numberOfRows} rows, requested column ${t} and row ${e} is invalid.`);return c(this,i,"f")[e*this.numberOfColumns+t]}slice(e,t){e=void 0===e?0:e<0?this.numberOfRows+e:e,e=Math.min(Math.max(e,0),this.numberOfRows),t=void 0===t?this.numberOfRows:t<0?this.numberOfRows+t:t,t=Math.min(Math.max(e,t),this.numberOfRows);const n=Object.assign(Object.assign({},c(this,o,"f")),{numberOfRows:t-e}),r=c(this,i,"f").slice(e*this.numberOfColumns,t*this.numberOfColumns);return console.assert(r&&r.length===n.numberOfRows*n.numberOfColumns,"SQLiteCloudRowset.slice - invalid rowset data"),new h(n,r)}map(e){const t=[];for(let n=0;n<this.numberOfRows;n++){const r=this[n];t.push(e(r,n,this))}return t}filter(e){const t=[];for(let n=0;n<this.numberOfRows;n++)e(this[n],n,this)&&t.push(...c(this,i,"f").slice(n*this.numberOfColumns,(n+1)*this.numberOfColumns));return new h(Object.assign(Object.assign({},c(this,o,"f")),{numberOfRows:t.length/this.numberOfColumns}),t)}}t.SQLiteCloudRowset=h,o=new WeakMap,i=new WeakMap},96:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Statement=void 0;const r=n(193);t.Statement=class{constructor(e,t,...n){const{args:s,callback:o}=(0,r.popCallback)(n);this._database=e,this._sql=t,(null==s?void 0:s.length)>0?this.bind(...s,o):null==o||o.call(this,null)}bind(...e){const{args:t,callback:n}=(0,r.popCallback)(e);try{this._preparedSql=(0,r.prepareSql)(this._sql,...t),n&&n.call(this,null)}catch(e){this._preparedSql=void 0,n&&n.call(this,e)}return this}run(...e){const{args:t,callback:n}=(0,r.popCallback)(e||[]);return(null==t?void 0:t.length)>0?this.bind(...t,(e=>{e?null==n||n.call(this,e):this._database.run(this._preparedSql||"",n)})):this._database.run(this._preparedSql||"",n),this}get(...e){const{args:t,callback:n}=(0,r.popCallback)(e||[]);return(null==t?void 0:t.length)>0?this.bind(...t,(e=>{e?null==n||n.call(this,e):this._database.get(this._preparedSql||"",n)})):this._database.get(this._preparedSql||"",n),this}all(...e){const{args:t,callback:n}=(0,r.popCallback)(e||[]);return(null==t?void 0:t.length)>0?this.bind(...t,(e=>{e?null==n||n.call(this,e):this._database.all(this._preparedSql||"",n)})):this._database.all(this._preparedSql||"",n),this}each(...e){const{args:t,callback:n,complete:s}=(0,r.popCallback)(e);return(null==t?void 0:t.length)>0?this.bind(...t,(e=>{e?null==n||n.call(this,e):this._database.each(this._preparedSql||"",n,s)})):this._database.each(this._preparedSql||"",n,s),this}}},80:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SQLiteCloudArrayType=t.SQLiteCloudError=t.DEFAULT_PORT=t.DEFAULT_TIMEOUT=void 0,t.DEFAULT_TIMEOUT=3e5,t.DEFAULT_PORT=9960;class n extends Error{constructor(e,t){super(e),this.name="SQLiteCloudError",t&&Object.assign(this,t)}}var r;t.SQLiteCloudError=n,(r=t.SQLiteCloudArrayType||(t.SQLiteCloudArrayType={}))[r.ARRAY_TYPE_SQLITE_EXEC=10]="ARRAY_TYPE_SQLITE_EXEC",r[r.ARRAY_TYPE_DB_STATUS=11]="ARRAY_TYPE_DB_STATUS",r[r.ARRAY_TYPE_METADATA=12]="ARRAY_TYPE_METADATA",r[r.ARRAY_TYPE_VM_STEP=20]="ARRAY_TYPE_VM_STEP",r[r.ARRAY_TYPE_VM_COMPILE=21]="ARRAY_TYPE_VM_COMPILE",r[r.ARRAY_TYPE_VM_STEP_ONE=22]="ARRAY_TYPE_VM_STEP_ONE",r[r.ARRAY_TYPE_VM_SQL=23]="ARRAY_TYPE_VM_SQL",r[r.ARRAY_TYPE_VM_STATUS=24]="ARRAY_TYPE_VM_STATUS",r[r.ARRAY_TYPE_VM_LIST=25]="ARRAY_TYPE_VM_LIST",r[r.ARRAY_TYPE_BACKUP_INIT=40]="ARRAY_TYPE_BACKUP_INIT",r[r.ARRAY_TYPE_BACKUP_STEP=41]="ARRAY_TYPE_BACKUP_STEP",r[r.ARRAY_TYPE_BACKUP_END=42]="ARRAY_TYPE_BACKUP_END",r[r.ARRAY_TYPE_SQLITE_STATUS=50]="ARRAY_TYPE_SQLITE_STATUS"},193:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseBooleanToZeroOne=t.parseBoolean=t.parseconnectionstring=t.validateConfiguration=t.popCallback=t.getUpdateResults=t.prepareSql=t.escapeSqlParameter=t.getInitializationCommands=t.anonimizeError=t.anonimizeCommand=t.isNode=t.isBrowser=void 0;const r=n(80),s=n(80);function o(e){return(e=(e=e.replace(/USER \S+/,"USER ******")).replace(/PASSWORD \S+?(?=;)/,"PASSWORD ******")).replace(/HASH \S+?(?=;)/,"HASH ******")}function i(e){if(null==e)return"NULL";if("string"==typeof e)return`'${e=e.replace(/'/g,"''")}'`;if("number"==typeof e||"bigint"==typeof e)return e.toString();if("boolean"==typeof e)return e?"1":"0";if(Buffer.isBuffer(e))return`X'${e.toString("hex")}'`;if("object"==typeof e){let t=JSON.stringify(e);return t=t.replace(/'/g,"''"),`'${t}'`}throw new r.SQLiteCloudError("Unsupported parameter type: "+typeof e)}function a(e){try{const t=e.replace("sqlitecloud:","https:"),n=new URL(t),r={};n.searchParams.forEach(((e,t)=>{r[t.toLowerCase().replaceAll("-","_")]=e}));const s=Object.assign({username:decodeURIComponent(n.username),password:decodeURIComponent(n.password),host:n.hostname,port:n.port?parseInt(n.port):void 0},r);s.apikey&&((s.username||s.password)&&console.warn("SQLiteCloudConnection.parseconnectionstring - apikey and username/password are both specified, using apikey"),delete s.username,delete s.password);const o=n.pathname.replace("/","");return o&&(s.database=o),s}catch(t){throw new r.SQLiteCloudError(`Invalid connection string: ${e}`)}}function c(e){return"string"==typeof e?"true"===e.toLowerCase()||"1"===e:!!e}t.isBrowser="undefined"!=typeof window&&void 0!==window.document,t.isNode="undefined"!=typeof process&&null!=process.versions&&null!=process.versions.node,t.anonimizeCommand=o,t.anonimizeError=function(e){return(null==e?void 0:e.message)&&(e.message=o(e.message)),e},t.getInitializationCommands=function(e){let t="SET CLIENT KEY NONLINEARIZABLE TO 1; ";return e.apikey?t+=`AUTH APIKEY ${e.apikey}; `:t+=`AUTH USER ${e.username||""} ${e.password_hashed?"HASH":"PASSWORD"} ${e.password||""}; `,e.compression&&(t+="SET CLIENT KEY COMPRESSION TO 1; "),e.zerotext&&(t+="SET CLIENT KEY ZEROTEXT TO 1; "),e.noblob&&(t+="SET CLIENT KEY NOBLOB TO 1; "),e.maxdata&&(t+=`SET CLIENT KEY MAXDATA TO ${e.maxdata}; `),e.maxrows&&(t+=`SET CLIENT KEY MAXROWS TO ${e.maxrows}; `),e.maxrowset&&(t+=`SET CLIENT KEY MAXROWSET TO ${e.maxrowset}; `),e.non_linearizable||(t+="SET CLIENT KEY NONLINEARIZABLE TO 0; "),e.database&&(e.create&&!e.memory&&(t+=`CREATE DATABASE ${e.database} IF NOT EXISTS; `),t+=`USE DATABASE ${e.database}; `),t},t.escapeSqlParameter=i,t.prepareSql=function(e,...t){1===(null==t?void 0:t.length)&&Array.isArray(t[0])&&(t=t[0]);let n=1,s=e.replace(/\?(\d+)?/g,((e,s)=>{const o=s?parseInt(s):n;let a;if(n++,!t[0]||"object"!=typeof t[0]||t[0]instanceof Buffer||(a=t[0][o]),!a){if(o>t.length)throw new r.SQLiteCloudError("Not enough parameters");a=t[o-1]}return null!=a?i(a):"NULL"}));if(1===(null==t?void 0:t.length)&&t[0]&&"object"==typeof t[0]){const e=t[0];for(const[t,n]of Object.entries(e)){const e=t.charAt(0);if("$"==e||":"==e||"@"==e){const e=i(n);s=s.replace(new RegExp(`\\${t}`,"g"),e)}}}return s},t.getUpdateResults=function(e){if(e&&Array.isArray(e)&&e.length>0&&e[0]===s.SQLiteCloudArrayType.ARRAY_TYPE_SQLITE_EXEC)return{type:e[0],index:e[1],lastID:e[2],changes:e[3],totalChanges:e[4],finalized:e[5],rowId:e[2]}},t.popCallback=function(e){const t=e;return e&&e.length>0&&"function"==typeof e[e.length-1]?e.length>1&&"function"==typeof e[e.length-2]?{args:t.slice(0,-2),callback:e[e.length-2],complete:e[e.length-1]}:{args:t.slice(0,-1),callback:e[e.length-1]}:{args:t}},t.validateConfiguration=function(e){console.assert(e,"SQLiteCloudConnection.validateConfiguration - missing config"),e.connectionstring&&(e=Object.assign(Object.assign(Object.assign({},e),a(e.connectionstring)),{connectionstring:e.connectionstring})),e.port||(e.port=r.DEFAULT_PORT),e.timeout=e.timeout&&e.timeout>0?e.timeout:r.DEFAULT_TIMEOUT,e.clientid||(e.clientid="SQLiteCloud"),e.verbose=c(e.verbose),e.noblob=c(e.noblob),e.compression=c(e.compression),e.create=c(e.create),e.non_linearizable=c(e.non_linearizable),e.insecure=c(e.insecure);const t=e.username&&e.password||e.apikey;if(!e.host||!t)throw console.error("SQLiteCloudConnection.validateConfiguration - missing arguments",e),new r.SQLiteCloudError("The user, password and host arguments or the ?apikey= must be specified.",{errorCode:"ERR_MISSING_ARGS"});return e.connectionstring||(e.apikey?e.connectionstring=`sqlitecloud://${e.host}:${e.port}/${e.database||""}?apikey=${e.apikey}`:e.connectionstring=`sqlitecloud://${encodeURIComponent(e.username||"")}:${encodeURIComponent(e.password||"")}@${e.host}:${e.port}/${e.database}`),e},t.parseconnectionstring=a,t.parseBoolean=c,t.parseBooleanToZeroOne=function(e){return"string"==typeof e?"true"===e.toLowerCase()||"1"===e?1:0:e?1:0}},833:(e,t,n)=>{t.formatArgs=function(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+e.exports.humanize(this.diff),!this.useColors)return;const n="color: "+this.color;t.splice(1,0,n,"color: inherit");let r=0,s=0;t[0].replace(/%[a-zA-Z%]/g,(e=>{"%%"!==e&&(r++,"%c"===e&&(s=r))})),t.splice(s,0,n)},t.save=function(e){try{e?t.storage.setItem("debug",e):t.storage.removeItem("debug")}catch(e){}},t.load=function(){let e;try{e=t.storage.getItem("debug")}catch(e){}return!e&&"undefined"!=typeof process&&"env"in process&&(e=process.env.DEBUG),e},t.useColors=function(){return!("undefined"==typeof window||!window.process||"renderer"!==window.process.type&&!window.process.__nwjs)||("undefined"==typeof navigator||!navigator.userAgent||!navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))&&("undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/))},t.storage=function(){try{return localStorage}catch(e){}}(),t.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),t.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],t.log=console.debug||console.log||(()=>{}),e.exports=n(736)(t);const{formatters:r}=e.exports;r.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}},736:(e,t,n)=>{e.exports=function(e){function t(e){let n,s,o,i=null;function a(...e){if(!a.enabled)return;const r=a,s=Number(new Date),o=s-(n||s);r.diff=o,r.prev=n,r.curr=s,n=s,e[0]=t.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let i=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,((n,s)=>{if("%%"===n)return"%";i++;const o=t.formatters[s];if("function"==typeof o){const t=e[i];n=o.call(r,t),e.splice(i,1),i--}return n})),t.formatArgs.call(r,e),(r.log||t.log).apply(r,e)}return a.namespace=e,a.useColors=t.useColors(),a.color=t.selectColor(e),a.extend=r,a.destroy=t.destroy,Object.defineProperty(a,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==i?i:(s!==t.namespaces&&(s=t.namespaces,o=t.enabled(e)),o),set:e=>{i=e}}),"function"==typeof t.init&&t.init(a),a}function r(e,n){const r=t(this.namespace+(void 0===n?":":n)+e);return r.log=this.log,r}function s(e){return e.toString().substring(2,e.toString().length-2).replace(/\.\*\?$/,"*")}return t.debug=t,t.default=t,t.coerce=function(e){return e instanceof Error?e.stack||e.message:e},t.disable=function(){const e=[...t.names.map(s),...t.skips.map(s).map((e=>"-"+e))].join(",");return t.enable(""),e},t.enable=function(e){let n;t.save(e),t.namespaces=e,t.names=[],t.skips=[];const r=("string"==typeof e?e:"").split(/[\s,]+/),s=r.length;for(n=0;n<s;n++)r[n]&&("-"===(e=r[n].replace(/\*/g,".*?"))[0]?t.skips.push(new RegExp("^"+e.slice(1)+"$")):t.names.push(new RegExp("^"+e+"$")))},t.enabled=function(e){if("*"===e[e.length-1])return!0;let n,r;for(n=0,r=t.skips.length;n<r;n++)if(t.skips[n].test(e))return!1;for(n=0,r=t.names.length;n<r;n++)if(t.names[n].test(e))return!0;return!1},t.humanize=n(585),t.destroy=function(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")},Object.keys(e).forEach((n=>{t[n]=e[n]})),t.names=[],t.skips=[],t.formatters={},t.selectColor=function(e){let n=0;for(let t=0;t<e.length;t++)n=(n<<5)-n+e.charCodeAt(t),n|=0;return t.colors[Math.abs(n)%t.colors.length]},t.enable(t.load()),t}},228:e=>{"use strict";var t=Object.prototype.hasOwnProperty,n="~";function r(){}function s(e,t,n){this.fn=e,this.context=t,this.once=n||!1}function o(e,t,r,o,i){if("function"!=typeof r)throw new TypeError("The listener must be a function");var a=new s(r,o||e,i),c=n?n+t:t;return e._events[c]?e._events[c].fn?e._events[c]=[e._events[c],a]:e._events[c].push(a):(e._events[c]=a,e._eventsCount++),e}function i(e,t){0==--e._eventsCount?e._events=new r:delete e._events[t]}function a(){this._events=new r,this._eventsCount=0}Object.create&&(r.prototype=Object.create(null),(new r).__proto__||(n=!1)),a.prototype.eventNames=function(){var e,r,s=[];if(0===this._eventsCount)return s;for(r in e=this._events)t.call(e,r)&&s.push(n?r.slice(1):r);return Object.getOwnPropertySymbols?s.concat(Object.getOwnPropertySymbols(e)):s},a.prototype.listeners=function(e){var t=n?n+e:e,r=this._events[t];if(!r)return[];if(r.fn)return[r.fn];for(var s=0,o=r.length,i=new Array(o);s<o;s++)i[s]=r[s].fn;return i},a.prototype.listenerCount=function(e){var t=n?n+e:e,r=this._events[t];return r?r.fn?1:r.length:0},a.prototype.emit=function(e,t,r,s,o,i){var a=n?n+e:e;if(!this._events[a])return!1;var c,u,l=this._events[a],h=arguments.length;if(l.fn){switch(l.once&&this.removeListener(e,l.fn,void 0,!0),h){case 1:return l.fn.call(l.context),!0;case 2:return l.fn.call(l.context,t),!0;case 3:return l.fn.call(l.context,t,r),!0;case 4:return l.fn.call(l.context,t,r,s),!0;case 5:return l.fn.call(l.context,t,r,s,o),!0;case 6:return l.fn.call(l.context,t,r,s,o,i),!0}for(u=1,c=new Array(h-1);u<h;u++)c[u-1]=arguments[u];l.fn.apply(l.context,c)}else{var d,f=l.length;for(u=0;u<f;u++)switch(l[u].once&&this.removeListener(e,l[u].fn,void 0,!0),h){case 1:l[u].fn.call(l[u].context);break;case 2:l[u].fn.call(l[u].context,t);break;case 3:l[u].fn.call(l[u].context,t,r);break;case 4:l[u].fn.call(l[u].context,t,r,s);break;default:if(!c)for(d=1,c=new Array(h-1);d<h;d++)c[d-1]=arguments[d];l[u].fn.apply(l[u].context,c)}}return!0},a.prototype.on=function(e,t,n){return o(this,e,t,n,!1)},a.prototype.once=function(e,t,n){return o(this,e,t,n,!0)},a.prototype.removeListener=function(e,t,r,s){var o=n?n+e:e;if(!this._events[o])return this;if(!t)return i(this,o),this;var a=this._events[o];if(a.fn)a.fn!==t||s&&!a.once||r&&a.context!==r||i(this,o);else{for(var c=0,u=[],l=a.length;c<l;c++)(a[c].fn!==t||s&&!a[c].once||r&&a[c].context!==r)&&u.push(a[c]);u.length?this._events[o]=1===u.length?u[0]:u:i(this,o)}return this},a.prototype.removeAllListeners=function(e){var t;return e?(t=n?n+e:e,this._events[t]&&i(this,t)):(this._events=new r,this._eventsCount=0),this},a.prototype.off=a.prototype.removeListener,a.prototype.addListener=a.prototype.on,a.prefixed=n,a.EventEmitter=a,e.exports=a},404:(e,t,n)=>{var r=n(255),s=n(144),o=65536,i=h(5<<20),a=function(){try{return new Uint32Array(o)}catch(n){for(var e=new Array(o),t=0;t<o;t++)e[t]=0;return e}}(),c=407708164,u=2147483648,l={4:65536,5:262144,6:1048576,7:4194304};function h(e){try{return new Uint8Array(e)}catch(r){for(var t=new Array(e),n=0;n<e;n++)t[n]=0;return t}}function d(e,t,n){if(void 0!==typeof e.buffer){if(Uint8Array.prototype.slice)return e.slice(t,n);var r=e.length;t=(t|=0)<0?Math.max(r+t,0):Math.min(t,r),n=(n=void 0===n?r:0|n)<0?Math.max(r+n,0):Math.min(n,r);for(var s=new Uint8Array(n-t),o=t,i=0;o<n;)s[i++]=e[o++];return s}return e.slice(t,n)}t.compressBound=function(e){return e+e/255+16|0},t.decompressBound=function(e){var t=0;if(s.readU32(e,t)!==c)throw new Error("invalid magic number");t+=4;var n=e[t++];if(64!=(192&n))throw new Error("incompatible descriptor version "+(192&n));var r=0!=(16&n),o=0!=(8&n),i=e[t++]>>4&7;if(void 0===l[i])throw new Error("invalid block size "+i);var a=l[i];if(o)return s.readU64(e,t);t++;for(var h=0;;){var d=s.readU32(e,t);if(t+=4,h+=d&u?d&=2147483647:a,0===d)return h;r&&(t+=4),t+=d}},t.makeBuffer=h,t.decompressBlock=function(e,t,n,r,s){var o,i,a,c,u;for(a=n+r;n<a;){var l=e[n++],h=l>>4;if(h>0){if(15===h)for(;h+=e[n],255===e[n++];);for(c=n+h;n<c;)t[s++]=e[n++]}if(n>=a)break;if(o=15&l,i=e[n++]|e[n++]<<8,15===o)for(;o+=e[n],255===e[n++];);for(c=(u=s-i)+(o+=4);u<c;)t[s++]=0|t[u++]}return s},t.compressBlock=function(e,t,n,r,o){var i,a,c,u,l,h,d,f;if(h=0,d=r+n,a=n,r>=13)for(var p=67;n+4<d-5;){var m=s.readU32(e,n),g=s.hashU32(m)>>>0;if(i=o[g=(g>>16^g)>>>0&65535]-1,o[g]=n+1,i<0||n-i>>>16>0||s.readU32(e,i)!==m)n+=p++>>6;else{for(p=67,l=n-a,u=n-i,i+=4,c=n+=4;n<d-5&&e[n]===e[i];)n++,i++;var y=(c=n-c)<15?c:15;if(l>=15){for(t[h++]=240+y,f=l-15;f>=255;f-=255)t[h++]=255;t[h++]=f}else t[h++]=(l<<4)+y;for(var b=0;b<l;b++)t[h++]=e[a+b];if(t[h++]=u,t[h++]=u>>8,c>=15){for(f=c-15;f>=255;f-=255)t[h++]=255;t[h++]=f}a=n}}if(0===a)return 0;if((l=d-a)>=15){for(t[h++]=240,f=l-15;f>=255;f-=255)t[h++]=255;t[h++]=f}else t[h++]=l<<4;for(n=a;n<d;)t[h++]=e[n++];return h},t.decompressFrame=function(e,n){var r,o,i,a,h=0,d=0;if(s.readU32(e,h)!==c)throw new Error("invalid magic number");if(h+=4,64!=(192&(a=e[h++])))throw new Error("incompatible descriptor version");r=0!=(16&a),o=0!=(4&a),i=0!=(8&a);var f=e[h++]>>4&7;if(void 0===l[f])throw new Error("invalid block size");for(i&&(h+=8),h++;;){var p;if(p=s.readU32(e,h),h+=4,0===p)break;if(r&&(h+=4),0!=(p&u)){p&=2147483647;for(var m=0;m<p;m++)n[d++]=e[h++]}else d=t.decompressBlock(e,n,h,p,d),h+=p}return o&&(h+=4),d},t.compressFrame=function(e,n){var u=0;s.writeU32(n,u,c),u+=4,n[u++]=64,n[u++]=112,n[u]=r.hash(0,n,4,u-4)>>8,u++;var h=l[7],d=e.length,f=0;for(function(e){for(var t=0;t<o;t++)a[t]=0}();d>0;){var p,m=d>h?h:d;if((p=t.compressBlock(e,i,f,m,a))>m||0===p){s.writeU32(n,u,2147483648|m),u+=4;for(var g=f+m;f<g;)n[u++]=e[f++];d-=m}else{s.writeU32(n,u,p),u+=4;for(var y=0;y<p;)n[u++]=i[y++];f+=m,d-=m}}return s.writeU32(n,u,0),u+4},t.decompress=function(e,n){var r,s;return void 0===n&&(n=t.decompressBound(e)),r=t.makeBuffer(n),(s=t.decompressFrame(e,r))!==n&&(r=d(r,0,s)),r},t.compress=function(e,n){var r,s;return void 0===n&&(n=t.compressBound(e.length)),r=t.makeBuffer(n),(s=t.compressFrame(e,r))!==n&&(r=d(r,0,s)),r}},144:(e,t)=>{t.hashU32=function(e){return-1252372727^(e=(e=(e=374761393+(e=-949894596^(e=2127912214+(e|=0)+(e<<12)|0)^e>>>19)+(e<<5)|0)-744332180^e<<9)-42973499+(e<<3)|0)^e>>>16|0},t.readU64=function(e,t){var n=0;return n|=e[t++]<<0,n|=e[t++]<<8,n|=e[t++]<<16,n|=e[t++]<<24,n|=e[t++]<<32,n|=e[t++]<<40,(n|=e[t++]<<48)|e[t++]<<56},t.readU32=function(e,t){var n=0;return n|=e[t++]<<0,n|=e[t++]<<8,(n|=e[t++]<<16)|e[t++]<<24},t.writeU32=function(e,t,n){e[t++]=n>>0&255,e[t++]=n>>8&255,e[t++]=n>>16&255,e[t++]=n>>24&255},t.imul=function(e,t){var n=65535&e,r=65535&t;return n*r+((e>>>16)*r+n*(t>>>16)<<16)|0}},255:(e,t,n)=>{var r=n(144),s=2654435761,o=2246822519,i=3266489917,a=374761393;function c(e,t){return(e|=0)>>>(32-(t|=0)|0)|e<<t|0}function u(e,t,n){return e|=0,t|=0,n|=0,0|r.imul(e>>>(32-t|0)|e<<t,n)}function l(e,t){return(e|=0)>>>(t|=0)^e|0}function h(e,t,n,s,o){return u(r.imul(t,n)+e,s,o)}function d(e,t,n){return u(e+r.imul(t[n],a),11,s)}function f(e,t,n){return h(e,r.readU32(t,n),i,17,668265263)}function p(e,t,n){return[h(e[0],r.readU32(t,n+0),o,13,s),h(e[1],r.readU32(t,n+4),o,13,s),h(e[2],r.readU32(t,n+8),o,13,s),h(e[3],r.readU32(t,n+12),o,13,s)]}t.hash=function(e,t,n,u){var h,m;if(m=u,u>=16){for(h=[e+s+o,e+o,e,e-s];u>=16;)h=p(h,t,n),n+=16,u-=16;h=c(h[0],1)+c(h[1],7)+c(h[2],12)+c(h[3],18)+m}else h=e+a+u>>>0;for(;u>=4;)h=f(h,t,n),n+=4,u-=4;for(;u>0;)h=d(h,t,n),n++,u--;return(h=l(r.imul(l(r.imul(l(h,15),o),13),i),16))>>>0}},585:e=>{var t=1e3,n=60*t,r=60*n,s=24*r;function o(e,t,n,r){var s=t>=1.5*n;return Math.round(e/n)+" "+r+(s?"s":"")}e.exports=function(e,i){i=i||{};var a,c,u=typeof e;if("string"===u&&e.length>0)return function(e){if(!((e=String(e)).length>100)){var o=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(o){var i=parseFloat(o[1]);switch((o[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return 315576e5*i;case"weeks":case"week":case"w":return 6048e5*i;case"days":case"day":case"d":return i*s;case"hours":case"hour":case"hrs":case"hr":case"h":return i*r;case"minutes":case"minute":case"mins":case"min":case"m":return i*n;case"seconds":case"second":case"secs":case"sec":case"s":return i*t;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return i;default:return}}}}(e);if("number"===u&&isFinite(e))return i.long?(a=e,(c=Math.abs(a))>=s?o(a,c,s,"day"):c>=r?o(a,c,r,"hour"):c>=n?o(a,c,n,"minute"):c>=t?o(a,c,t,"second"):a+" ms"):function(e){var o=Math.abs(e);return o>=s?Math.round(e/s)+"d":o>=r?Math.round(e/r)+"h":o>=n?Math.round(e/n)+"m":o>=t?Math.round(e/t)+"s":e+"ms"}(e);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))}},498:()=>{},110:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.hasCORS=void 0;let n=!1;try{n="undefined"!=typeof XMLHttpRequest&&"withCredentials"in new XMLHttpRequest}catch(e){}t.hasCORS=n},661:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.decode=t.encode=void 0,t.encode=function(e){let t="";for(let n in e)e.hasOwnProperty(n)&&(t.length&&(t+="&"),t+=encodeURIComponent(n)+"="+encodeURIComponent(e[n]));return t},t.decode=function(e){let t={},n=e.split("&");for(let e=0,r=n.length;e<r;e++){let r=n[e].split("=");t[decodeURIComponent(r[0])]=decodeURIComponent(r[1])}return t}},15:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parse=void 0;const n=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,r=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];t.parse=function(e){if(e.length>2e3)throw"URI too long";const t=e,s=e.indexOf("["),o=e.indexOf("]");-1!=s&&-1!=o&&(e=e.substring(0,s)+e.substring(s,o).replace(/:/g,";")+e.substring(o,e.length));let i=n.exec(e||""),a={},c=14;for(;c--;)a[r[c]]=i[c]||"";return-1!=s&&-1!=o&&(a.source=t,a.host=a.host.substring(1,a.host.length-1).replace(/;/g,":"),a.authority=a.authority.replace("[","").replace("]","").replace(/;/g,":"),a.ipv6uri=!0),a.pathNames=function(e,t){const n=t.replace(/\/{2,9}/g,"/").split("/");return"/"!=t.slice(0,1)&&0!==t.length||n.splice(0,1),"/"==t.slice(-1)&&n.splice(n.length-1,1),n}(0,a.path),a.queryKey=function(e,t){const n={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,(function(e,t,r){t&&(n[t]=r)})),n}(0,a.query),a}},732:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.yeast=t.decode=t.encode=void 0;const n="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_".split(""),r={};let s,o=0,i=0;function a(e){let t="";do{t=n[e%64]+t,e=Math.floor(e/64)}while(e>0);return t}for(t.encode=a,t.decode=function(e){let t=0;for(i=0;i<e.length;i++)t=64*t+r[e.charAt(i)];return t},t.yeast=function(){const e=a(+new Date);return e!==s?(o=0,s=e):e+"."+a(o++)};i<64;i++)r[n[i]]=i},235:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.globalThisShim=void 0,t.globalThisShim="undefined"!=typeof self?self:"undefined"!=typeof window?window:Function("return this")()},956:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.nextTick=t.parse=t.installTimerFunctions=t.transports=t.TransportError=t.Transport=t.protocol=t.Socket=void 0;const r=n(223);Object.defineProperty(t,"Socket",{enumerable:!0,get:function(){return r.Socket}}),t.protocol=r.Socket.protocol;var s=n(689);Object.defineProperty(t,"Transport",{enumerable:!0,get:function(){return s.Transport}}),Object.defineProperty(t,"TransportError",{enumerable:!0,get:function(){return s.TransportError}});var o=n(419);Object.defineProperty(t,"transports",{enumerable:!0,get:function(){return o.transports}});var i=n(374);Object.defineProperty(t,"installTimerFunctions",{enumerable:!0,get:function(){return i.installTimerFunctions}});var a=n(15);Object.defineProperty(t,"parse",{enumerable:!0,get:function(){return a.parse}});var c=n(87);Object.defineProperty(t,"nextTick",{enumerable:!0,get:function(){return c.nextTick}})},223:function(e,t,n){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.Socket=void 0;const s=n(419),o=n(374),i=n(661),a=n(15),c=r(n(833)),u=n(285),l=n(376),h=n(87),d=(0,c.default)("engine.io-client:socket");class f extends u.Emitter{constructor(e,t={}){super(),this.binaryType=h.defaultBinaryType,this.writeBuffer=[],e&&"object"==typeof e&&(t=e,e=null),e?(e=(0,a.parse)(e),t.hostname=e.host,t.secure="https"===e.protocol||"wss"===e.protocol,t.port=e.port,e.query&&(t.query=e.query)):t.host&&(t.hostname=(0,a.parse)(t.host).host),(0,o.installTimerFunctions)(this,t),this.secure=null!=t.secure?t.secure:"undefined"!=typeof location&&"https:"===location.protocol,t.hostname&&!t.port&&(t.port=this.secure?"443":"80"),this.hostname=t.hostname||("undefined"!=typeof location?location.hostname:"localhost"),this.port=t.port||("undefined"!=typeof location&&location.port?location.port:this.secure?"443":"80"),this.transports=t.transports||["polling","websocket","webtransport"],this.writeBuffer=[],this.prevBufferLen=0,this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},t),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),"string"==typeof this.opts.query&&(this.opts.query=(0,i.decode)(this.opts.query)),this.id=null,this.upgrades=null,this.pingInterval=null,this.pingTimeout=null,this.pingTimeoutTimer=null,"function"==typeof addEventListener&&(this.opts.closeOnBeforeunload&&(this.beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this.beforeunloadEventListener,!1)),"localhost"!==this.hostname&&(this.offlineEventListener=()=>{this.onClose("transport close",{description:"network connection lost"})},addEventListener("offline",this.offlineEventListener,!1))),this.open()}createTransport(e){d('creating transport "%s"',e);const t=Object.assign({},this.opts.query);t.EIO=l.protocol,t.transport=e,this.id&&(t.sid=this.id);const n=Object.assign({},this.opts,{query:t,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[e]);return d("options: %j",n),new s.transports[e](n)}open(){let e;if(this.opts.rememberUpgrade&&f.priorWebsocketSuccess&&-1!==this.transports.indexOf("websocket"))e="websocket";else{if(0===this.transports.length)return void this.setTimeoutFn((()=>{this.emitReserved("error","No transports available")}),0);e=this.transports[0]}this.readyState="opening";try{e=this.createTransport(e)}catch(e){return d("error while creating transport: %s",e),this.transports.shift(),void this.open()}e.open(),this.setTransport(e)}setTransport(e){d("setting transport %s",e.name),this.transport&&(d("clearing existing transport %s",this.transport.name),this.transport.removeAllListeners()),this.transport=e,e.on("drain",this.onDrain.bind(this)).on("packet",this.onPacket.bind(this)).on("error",this.onError.bind(this)).on("close",(e=>this.onClose("transport close",e)))}probe(e){d('probing transport "%s"',e);let t=this.createTransport(e),n=!1;f.priorWebsocketSuccess=!1;const r=()=>{n||(d('probe transport "%s" opened',e),t.send([{type:"ping",data:"probe"}]),t.once("packet",(r=>{if(!n)if("pong"===r.type&&"probe"===r.data){if(d('probe transport "%s" pong',e),this.upgrading=!0,this.emitReserved("upgrading",t),!t)return;f.priorWebsocketSuccess="websocket"===t.name,d('pausing current transport "%s"',this.transport.name),this.transport.pause((()=>{n||"closed"!==this.readyState&&(d("changing transport and sending upgrade packet"),u(),this.setTransport(t),t.send([{type:"upgrade"}]),this.emitReserved("upgrade",t),t=null,this.upgrading=!1,this.flush())}))}else{d('probe transport "%s" failed',e);const n=new Error("probe error");n.transport=t.name,this.emitReserved("upgradeError",n)}})))};function s(){n||(n=!0,u(),t.close(),t=null)}const o=n=>{const r=new Error("probe error: "+n);r.transport=t.name,s(),d('probe transport "%s" failed because of error: %s',e,n),this.emitReserved("upgradeError",r)};function i(){o("transport closed")}function a(){o("socket closed")}function c(e){t&&e.name!==t.name&&(d('"%s" works - aborting "%s"',e.name,t.name),s())}const u=()=>{t.removeListener("open",r),t.removeListener("error",o),t.removeListener("close",i),this.off("close",a),this.off("upgrading",c)};t.once("open",r),t.once("error",o),t.once("close",i),this.once("close",a),this.once("upgrading",c),-1!==this.upgrades.indexOf("webtransport")&&"webtransport"!==e?this.setTimeoutFn((()=>{n||t.open()}),200):t.open()}onOpen(){if(d("socket open"),this.readyState="open",f.priorWebsocketSuccess="websocket"===this.transport.name,this.emitReserved("open"),this.flush(),"open"===this.readyState&&this.opts.upgrade){d("starting upgrade probes");let e=0;const t=this.upgrades.length;for(;e<t;e++)this.probe(this.upgrades[e])}}onPacket(e){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState)switch(d('socket receive: type "%s", data "%s"',e.type,e.data),this.emitReserved("packet",e),this.emitReserved("heartbeat"),this.resetPingTimeout(),e.type){case"open":this.onHandshake(JSON.parse(e.data));break;case"ping":this.sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong");break;case"error":const t=new Error("server error");t.code=e.data,this.onError(t);break;case"message":this.emitReserved("data",e.data),this.emitReserved("message",e.data)}else d('packet received with socket readyState "%s"',this.readyState)}onHandshake(e){this.emitReserved("handshake",e),this.id=e.sid,this.transport.query.sid=e.sid,this.upgrades=this.filterUpgrades(e.upgrades),this.pingInterval=e.pingInterval,this.pingTimeout=e.pingTimeout,this.maxPayload=e.maxPayload,this.onOpen(),"closed"!==this.readyState&&this.resetPingTimeout()}resetPingTimeout(){this.clearTimeoutFn(this.pingTimeoutTimer),this.pingTimeoutTimer=this.setTimeoutFn((()=>{this.onClose("ping timeout")}),this.pingInterval+this.pingTimeout),this.opts.autoUnref&&this.pingTimeoutTimer.unref()}onDrain(){this.writeBuffer.splice(0,this.prevBufferLen),this.prevBufferLen=0,0===this.writeBuffer.length?this.emitReserved("drain"):this.flush()}flush(){if("closed"!==this.readyState&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const e=this.getWritablePackets();d("flushing %d packets in socket",e.length),this.transport.send(e),this.prevBufferLen=e.length,this.emitReserved("flush")}}getWritablePackets(){if(!(this.maxPayload&&"polling"===this.transport.name&&this.writeBuffer.length>1))return this.writeBuffer;let e=1;for(let t=0;t<this.writeBuffer.length;t++){const n=this.writeBuffer[t].data;if(n&&(e+=(0,o.byteLength)(n)),t>0&&e>this.maxPayload)return d("only send %d out of %d packets",t,this.writeBuffer.length),this.writeBuffer.slice(0,t);e+=2}return d("payload size is %d (max: %d)",e,this.maxPayload),this.writeBuffer}write(e,t,n){return this.sendPacket("message",e,t,n),this}send(e,t,n){return this.sendPacket("message",e,t,n),this}sendPacket(e,t,n,r){if("function"==typeof t&&(r=t,t=void 0),"function"==typeof n&&(r=n,n=null),"closing"===this.readyState||"closed"===this.readyState)return;(n=n||{}).compress=!1!==n.compress;const s={type:e,data:t,options:n};this.emitReserved("packetCreate",s),this.writeBuffer.push(s),r&&this.once("flush",r),this.flush()}close(){const e=()=>{this.onClose("forced close"),d("socket closing - telling transport to close"),this.transport.close()},t=()=>{this.off("upgrade",t),this.off("upgradeError",t),e()},n=()=>{this.once("upgrade",t),this.once("upgradeError",t)};return"opening"!==this.readyState&&"open"!==this.readyState||(this.readyState="closing",this.writeBuffer.length?this.once("drain",(()=>{this.upgrading?n():e()})):this.upgrading?n():e()),this}onError(e){d("socket error %j",e),f.priorWebsocketSuccess=!1,this.emitReserved("error",e),this.onClose("transport error",e)}onClose(e,t){"opening"!==this.readyState&&"open"!==this.readyState&&"closing"!==this.readyState||(d('socket close with reason: "%s"',e),this.clearTimeoutFn(this.pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),"function"==typeof removeEventListener&&(removeEventListener("beforeunload",this.beforeunloadEventListener,!1),removeEventListener("offline",this.offlineEventListener,!1)),this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this.prevBufferLen=0)}filterUpgrades(e){const t=[];let n=0;const r=e.length;for(;n<r;n++)~this.transports.indexOf(e[n])&&t.push(e[n]);return t}}t.Socket=f,f.protocol=l.protocol},689:function(e,t,n){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.Transport=t.TransportError=void 0;const s=n(376),o=n(285),i=n(374),a=r(n(833)),c=n(661),u=(0,a.default)("engine.io-client:transport");class l extends Error{constructor(e,t,n){super(e),this.description=t,this.context=n,this.type="TransportError"}}t.TransportError=l;class h extends o.Emitter{constructor(e){super(),this.writable=!1,(0,i.installTimerFunctions)(this,e),this.opts=e,this.query=e.query,this.socket=e.socket}onError(e,t,n){return super.emitReserved("error",new l(e,t,n)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return"opening"!==this.readyState&&"open"!==this.readyState||(this.doClose(),this.onClose()),this}send(e){"open"===this.readyState?this.write(e):u("transport is not open, discarding packets")}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(e){const t=(0,s.decodePacket)(e,this.socket.binaryType);this.onPacket(t)}onPacket(e){super.emitReserved("packet",e)}onClose(e){this.readyState="closed",super.emitReserved("close",e)}pause(e){}createUri(e,t={}){return e+"://"+this._hostname()+this._port()+this.opts.path+this._query(t)}_hostname(){const e=this.opts.hostname;return-1===e.indexOf(":")?e:"["+e+"]"}_port(){return this.opts.port&&(this.opts.secure&&Number(443!==this.opts.port)||!this.opts.secure&&80!==Number(this.opts.port))?":"+this.opts.port:""}_query(e){const t=(0,c.encode)(e);return t.length?"?"+t:""}}t.Transport=h},419:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.transports=void 0;const r=n(528),s=n(716),o=n(480);t.transports={websocket:s.WS,webtransport:o.WT,polling:r.Polling}},528:function(e,t,n){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.Request=t.Polling=void 0;const s=n(689),o=r(n(833)),i=n(732),a=n(376),c=n(519),u=n(285),l=n(374),h=n(235),d=(0,o.default)("engine.io-client:polling");function f(){}const p=null!=new c.XHR({xdomain:!1}).responseType;class m extends s.Transport{constructor(e){if(super(e),this.polling=!1,"undefined"!=typeof location){const t="https:"===location.protocol;let n=location.port;n||(n=t?"443":"80"),this.xd="undefined"!=typeof location&&e.hostname!==location.hostname||n!==e.port}const t=e&&e.forceBase64;this.supportsBinary=p&&!t,this.opts.withCredentials&&(this.cookieJar=(0,c.createCookieJar)())}get name(){return"polling"}doOpen(){this.poll()}pause(e){this.readyState="pausing";const t=()=>{d("paused"),this.readyState="paused",e()};if(this.polling||!this.writable){let e=0;this.polling&&(d("we are currently polling - waiting to pause"),e++,this.once("pollComplete",(function(){d("pre-pause polling complete"),--e||t()}))),this.writable||(d("we are currently writing - waiting to pause"),e++,this.once("drain",(function(){d("pre-pause writing complete"),--e||t()})))}else t()}poll(){d("polling"),this.polling=!0,this.doPoll(),this.emitReserved("poll")}onData(e){d("polling got data %s",e),(0,a.decodePayload)(e,this.socket.binaryType).forEach((e=>{if("opening"===this.readyState&&"open"===e.type&&this.onOpen(),"close"===e.type)return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(e)})),"closed"!==this.readyState&&(this.polling=!1,this.emitReserved("pollComplete"),"open"===this.readyState?this.poll():d('ignoring poll - transport state "%s"',this.readyState))}doClose(){const e=()=>{d("writing close packet"),this.write([{type:"close"}])};"open"===this.readyState?(d("transport open - closing"),e()):(d("transport not open - deferring close"),this.once("open",e))}write(e){this.writable=!1,(0,a.encodePayload)(e,(e=>{this.doWrite(e,(()=>{this.writable=!0,this.emitReserved("drain")}))}))}uri(){const e=this.opts.secure?"https":"http",t=this.query||{};return!1!==this.opts.timestampRequests&&(t[this.opts.timestampParam]=(0,i.yeast)()),this.supportsBinary||t.sid||(t.b64=1),this.createUri(e,t)}request(e={}){return Object.assign(e,{xd:this.xd,cookieJar:this.cookieJar},this.opts),new g(this.uri(),e)}doWrite(e,t){const n=this.request({method:"POST",data:e});n.on("success",t),n.on("error",((e,t)=>{this.onError("xhr post error",e,t)}))}doPoll(){d("xhr poll");const e=this.request();e.on("data",this.onData.bind(this)),e.on("error",((e,t)=>{this.onError("xhr poll error",e,t)})),this.pollXhr=e}}t.Polling=m;class g extends u.Emitter{constructor(e,t){super(),(0,l.installTimerFunctions)(this,t),this.opts=t,this.method=t.method||"GET",this.uri=e,this.data=void 0!==t.data?t.data:null,this.create()}create(){var e;const t=(0,l.pick)(this.opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");t.xdomain=!!this.opts.xd;const n=this.xhr=new c.XHR(t);try{d("xhr open %s: %s",this.method,this.uri),n.open(this.method,this.uri,!0);try{if(this.opts.extraHeaders){n.setDisableHeaderCheck&&n.setDisableHeaderCheck(!0);for(let e in this.opts.extraHeaders)this.opts.extraHeaders.hasOwnProperty(e)&&n.setRequestHeader(e,this.opts.extraHeaders[e])}}catch(e){}if("POST"===this.method)try{n.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch(e){}try{n.setRequestHeader("Accept","*/*")}catch(e){}null===(e=this.opts.cookieJar)||void 0===e||e.addCookies(n),"withCredentials"in n&&(n.withCredentials=this.opts.withCredentials),this.opts.requestTimeout&&(n.timeout=this.opts.requestTimeout),n.onreadystatechange=()=>{var e;3===n.readyState&&(null===(e=this.opts.cookieJar)||void 0===e||e.parseCookies(n)),4===n.readyState&&(200===n.status||1223===n.status?this.onLoad():this.setTimeoutFn((()=>{this.onError("number"==typeof n.status?n.status:0)}),0))},d("xhr data %s",this.data),n.send(this.data)}catch(e){return void this.setTimeoutFn((()=>{this.onError(e)}),0)}"undefined"!=typeof document&&(this.index=g.requestsCount++,g.requests[this.index]=this)}onError(e){this.emitReserved("error",e,this.xhr),this.cleanup(!0)}cleanup(e){if(void 0!==this.xhr&&null!==this.xhr){if(this.xhr.onreadystatechange=f,e)try{this.xhr.abort()}catch(e){}"undefined"!=typeof document&&delete g.requests[this.index],this.xhr=null}}onLoad(){const e=this.xhr.responseText;null!==e&&(this.emitReserved("data",e),this.emitReserved("success"),this.cleanup())}abort(){this.cleanup()}}if(t.Request=g,g.requestsCount=0,g.requests={},"undefined"!=typeof document)if("function"==typeof attachEvent)attachEvent("onunload",y);else if("function"==typeof addEventListener){const e="onpagehide"in h.globalThisShim?"pagehide":"unload";addEventListener(e,y,!1)}function y(){for(let e in g.requests)g.requests.hasOwnProperty(e)&&g.requests[e].abort()}},87:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.defaultBinaryType=t.usingBrowserWebSocket=t.WebSocket=t.nextTick=void 0;const r=n(235);t.nextTick="function"==typeof Promise&&"function"==typeof Promise.resolve?e=>Promise.resolve().then(e):(e,t)=>t(e,0),t.WebSocket=r.globalThisShim.WebSocket||r.globalThisShim.MozWebSocket,t.usingBrowserWebSocket=!0,t.defaultBinaryType="arraybuffer"},716:function(e,t,n){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.WS=void 0;const s=n(689),o=n(732),i=n(374),a=n(87),c=r(n(833)),u=n(376),l=(0,c.default)("engine.io-client:websocket"),h="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase();class d extends s.Transport{constructor(e){super(e),this.supportsBinary=!e.forceBase64}get name(){return"websocket"}doOpen(){if(!this.check())return;const e=this.uri(),t=this.opts.protocols,n=h?{}:(0,i.pick)(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(n.headers=this.opts.extraHeaders);try{this.ws=a.usingBrowserWebSocket&&!h?t?new a.WebSocket(e,t):new a.WebSocket(e):new a.WebSocket(e,t,n)}catch(e){return this.emitReserved("error",e)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=e=>this.onClose({description:"websocket connection closed",context:e}),this.ws.onmessage=e=>this.onData(e.data),this.ws.onerror=e=>this.onError("websocket error",e)}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const n=e[t],r=t===e.length-1;(0,u.encodePacket)(n,this.supportsBinary,(e=>{const t={};!a.usingBrowserWebSocket&&(n.options&&(t.compress=n.options.compress),this.opts.perMessageDeflate)&&("string"==typeof e?Buffer.byteLength(e):e.length)<this.opts.perMessageDeflate.threshold&&(t.compress=!1);try{a.usingBrowserWebSocket?this.ws.send(e):this.ws.send(e,t)}catch(e){l("websocket closed before onclose event")}r&&(0,a.nextTick)((()=>{this.writable=!0,this.emitReserved("drain")}),this.setTimeoutFn)}))}}doClose(){void 0!==this.ws&&(this.ws.close(),this.ws=null)}uri(){const e=this.opts.secure?"wss":"ws",t=this.query||{};return this.opts.timestampRequests&&(t[this.opts.timestampParam]=(0,o.yeast)()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}check(){return!!a.WebSocket}}t.WS=d},480:function(e,t,n){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.WT=void 0;const s=n(689),o=n(87),i=n(376),a=(0,r(n(833)).default)("engine.io-client:webtransport");class c extends s.Transport{get name(){return"webtransport"}doOpen(){"function"==typeof WebTransport&&(this.transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name]),this.transport.closed.then((()=>{a("transport closed gracefully"),this.onClose()})).catch((e=>{a("transport closed due to %s",e),this.onError("webtransport error",e)})),this.transport.ready.then((()=>{this.transport.createBidirectionalStream().then((e=>{const t=(0,i.createPacketDecoderStream)(Number.MAX_SAFE_INTEGER,this.socket.binaryType),n=e.readable.pipeThrough(t).getReader(),r=(0,i.createPacketEncoderStream)();r.readable.pipeTo(e.writable),this.writer=r.writable.getWriter();const s=()=>{n.read().then((({done:e,value:t})=>{e?a("session is closed"):(a("received chunk: %o",t),this.onPacket(t),s())})).catch((e=>{a("an error occurred while reading: %s",e)}))};s();const o={type:"open"};this.query.sid&&(o.data=`{"sid":"${this.query.sid}"}`),this.writer.write(o).then((()=>this.onOpen()))}))})))}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const n=e[t],r=t===e.length-1;this.writer.write(n).then((()=>{r&&(0,o.nextTick)((()=>{this.writable=!0,this.emitReserved("drain")}),this.setTimeoutFn)}))}}doClose(){var e;null===(e=this.transport)||void 0===e||e.close()}}t.WT=c},519:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.createCookieJar=t.XHR=void 0;const r=n(110),s=n(235);t.XHR=function(e){const t=e.xdomain;try{if("undefined"!=typeof XMLHttpRequest&&(!t||r.hasCORS))return new XMLHttpRequest}catch(e){}if(!t)try{return new(s.globalThisShim[["Active"].concat("Object").join("X")])("Microsoft.XMLHTTP")}catch(e){}},t.createCookieJar=function(){}},374:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.byteLength=t.installTimerFunctions=t.pick=void 0;const r=n(235);t.pick=function(e,...t){return t.reduce(((t,n)=>(e.hasOwnProperty(n)&&(t[n]=e[n]),t)),{})};const s=r.globalThisShim.setTimeout,o=r.globalThisShim.clearTimeout;t.installTimerFunctions=function(e,t){t.useNativeTimers?(e.setTimeoutFn=s.bind(r.globalThisShim),e.clearTimeoutFn=o.bind(r.globalThisShim)):(e.setTimeoutFn=r.globalThisShim.setTimeout.bind(r.globalThisShim),e.clearTimeoutFn=r.globalThisShim.clearTimeout.bind(r.globalThisShim))},t.byteLength=function(e){return"string"==typeof e?function(e){let t=0,n=0;for(let r=0,s=e.length;r<s;r++)t=e.charCodeAt(r),t<128?n+=1:t<2048?n+=2:t<55296||t>=57344?n+=3:(r++,n+=4);return n}(e):Math.ceil(1.33*(e.byteLength||e.size))}},46:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ERROR_PACKET=t.PACKET_TYPES_REVERSE=t.PACKET_TYPES=void 0;const n=Object.create(null);t.PACKET_TYPES=n,n.open="0",n.close="1",n.ping="2",n.pong="3",n.message="4",n.upgrade="5",n.noop="6";const r=Object.create(null);t.PACKET_TYPES_REVERSE=r,Object.keys(n).forEach((e=>{r[n[e]]=e})),t.ERROR_PACKET={type:"error",data:"parser error"}},745:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.decode=t.encode=void 0;const n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",r="undefined"==typeof Uint8Array?[]:new Uint8Array(256);for(let e=0;e<64;e++)r[n.charCodeAt(e)]=e;t.encode=e=>{let t,r=new Uint8Array(e),s=r.length,o="";for(t=0;t<s;t+=3)o+=n[r[t]>>2],o+=n[(3&r[t])<<4|r[t+1]>>4],o+=n[(15&r[t+1])<<2|r[t+2]>>6],o+=n[63&r[t+2]];return s%3==2?o=o.substring(0,o.length-1)+"=":s%3==1&&(o=o.substring(0,o.length-2)+"=="),o},t.decode=e=>{let t,n,s,o,i,a=.75*e.length,c=e.length,u=0;"="===e[e.length-1]&&(a--,"="===e[e.length-2]&&a--);const l=new ArrayBuffer(a),h=new Uint8Array(l);for(t=0;t<c;t+=4)n=r[e.charCodeAt(t)],s=r[e.charCodeAt(t+1)],o=r[e.charCodeAt(t+2)],i=r[e.charCodeAt(t+3)],h[u++]=n<<2|s>>4,h[u++]=(15&s)<<4|o>>2,h[u++]=(3&o)<<6|63&i;return l}},662:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.decodePacket=void 0;const r=n(46),s=n(745),o="function"==typeof ArrayBuffer;t.decodePacket=(e,t)=>{if("string"!=typeof e)return{type:"message",data:a(e,t)};const n=e.charAt(0);return"b"===n?{type:"message",data:i(e.substring(1),t)}:r.PACKET_TYPES_REVERSE[n]?e.length>1?{type:r.PACKET_TYPES_REVERSE[n],data:e.substring(1)}:{type:r.PACKET_TYPES_REVERSE[n]}:r.ERROR_PACKET};const i=(e,t)=>{if(o){const n=(0,s.decode)(e);return a(n,t)}return{base64:!0,data:e}},a=(e,t)=>"blob"===t?e instanceof Blob?e:new Blob([e]):e instanceof ArrayBuffer?e:e.buffer},686:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.encodePacket=t.encodePacketToBinary=void 0;const r=n(46),s="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Object.prototype.toString.call(Blob),o="function"==typeof ArrayBuffer,i=e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,a=({type:e,data:t},n,a)=>s&&t instanceof Blob?n?a(t):c(t,a):o&&(t instanceof ArrayBuffer||i(t))?n?a(t):c(new Blob([t]),a):a(r.PACKET_TYPES[e]+(t||""));t.encodePacket=a;const c=(e,t)=>{const n=new FileReader;return n.onload=function(){const e=n.result.split(",")[1];t("b"+(e||""))},n.readAsDataURL(e)};function u(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}let l;t.encodePacketToBinary=function(e,t){return s&&e.data instanceof Blob?e.data.arrayBuffer().then(u).then(t):o&&(e.data instanceof ArrayBuffer||i(e.data))?t(u(e.data)):void a(e,!1,(e=>{l||(l=new TextEncoder),t(l.encode(e))}))}},376:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.decodePayload=t.decodePacket=t.encodePayload=t.encodePacket=t.protocol=t.createPacketDecoderStream=t.createPacketEncoderStream=void 0;const r=n(686);Object.defineProperty(t,"encodePacket",{enumerable:!0,get:function(){return r.encodePacket}});const s=n(662);Object.defineProperty(t,"decodePacket",{enumerable:!0,get:function(){return s.decodePacket}});const o=n(46),i=String.fromCharCode(30);let a;function c(e){return e.reduce(((e,t)=>e+t.length),0)}function u(e,t){if(e[0].length===t)return e.shift();const n=new Uint8Array(t);let r=0;for(let s=0;s<t;s++)n[s]=e[0][r++],r===e[0].length&&(e.shift(),r=0);return e.length&&r<e[0].length&&(e[0]=e[0].slice(r)),n}t.encodePayload=(e,t)=>{const n=e.length,s=new Array(n);let o=0;e.forEach(((e,a)=>{(0,r.encodePacket)(e,!1,(e=>{s[a]=e,++o===n&&t(s.join(i))}))}))},t.decodePayload=(e,t)=>{const n=e.split(i),r=[];for(let e=0;e<n.length;e++){const o=(0,s.decodePacket)(n[e],t);if(r.push(o),"error"===o.type)break}return r},t.createPacketEncoderStream=function(){return new TransformStream({transform(e,t){(0,r.encodePacketToBinary)(e,(n=>{const r=n.length;let s;if(r<126)s=new Uint8Array(1),new DataView(s.buffer).setUint8(0,r);else if(r<65536){s=new Uint8Array(3);const e=new DataView(s.buffer);e.setUint8(0,126),e.setUint16(1,r)}else{s=new Uint8Array(9);const e=new DataView(s.buffer);e.setUint8(0,127),e.setBigUint64(1,BigInt(r))}e.data&&"string"!=typeof e.data&&(s[0]|=128),t.enqueue(s),t.enqueue(n)}))}})},t.createPacketDecoderStream=function(e,t){a||(a=new TextDecoder);const n=[];let r=0,i=-1,l=!1;return new TransformStream({transform(h,d){for(n.push(h);;){if(0===r){if(c(n)<1)break;const e=u(n,1);l=128==(128&e[0]),i=127&e[0],r=i<126?3:126===i?1:2}else if(1===r){if(c(n)<2)break;const e=u(n,2);i=new DataView(e.buffer,e.byteOffset,e.length).getUint16(0),r=3}else if(2===r){if(c(n)<8)break;const e=u(n,8),t=new DataView(e.buffer,e.byteOffset,e.length),s=t.getUint32(0);if(s>Math.pow(2,21)-1){d.enqueue(o.ERROR_PACKET);break}i=s*Math.pow(2,32)+t.getUint32(4),r=3}else{if(c(n)<i)break;const e=u(n,i);d.enqueue((0,s.decodePacket)(l?e:a.decode(e),t)),r=0}if(0===i||i>e){d.enqueue(o.ERROR_PACKET);break}}}})},t.protocol=4},743:(e,t)=>{"use strict";function n(e){e=e||{},this.ms=e.min||100,this.max=e.max||1e4,this.factor=e.factor||2,this.jitter=e.jitter>0&&e.jitter<=1?e.jitter:0,this.attempts=0}Object.defineProperty(t,"__esModule",{value:!0}),t.Backoff=void 0,t.Backoff=n,n.prototype.duration=function(){var e=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var t=Math.random(),n=Math.floor(t*this.jitter*e);e=0==(1&Math.floor(10*t))?e-n:e+n}return 0|Math.min(e,this.max)},n.prototype.reset=function(){this.attempts=0},n.prototype.setMin=function(e){this.ms=e},n.prototype.setMax=function(e){this.max=e},n.prototype.setJitter=function(e){this.jitter=e}},7:function(e,t,n){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.default=t.connect=t.io=t.Socket=t.Manager=t.protocol=void 0;const s=n(894),o=n(776);Object.defineProperty(t,"Manager",{enumerable:!0,get:function(){return o.Manager}});const i=n(214);Object.defineProperty(t,"Socket",{enumerable:!0,get:function(){return i.Socket}});const a=r(n(833)).default("socket.io-client"),c={};function u(e,t){"object"==typeof e&&(t=e,e=void 0),t=t||{};const n=s.url(e,t.path||"/socket.io"),r=n.source,i=n.id,u=n.path,l=c[i]&&u in c[i].nsps;let h;return t.forceNew||t["force new connection"]||!1===t.multiplex||l?(a("ignoring socket cache for %s",r),h=new o.Manager(r,t)):(c[i]||(a("new io instance for %s",r),c[i]=new o.Manager(r,t)),h=c[i]),n.query&&!t.query&&(t.query=n.queryKey),h.socket(n.path,t)}t.io=u,t.connect=u,t.default=u,Object.assign(u,{Manager:o.Manager,Socket:i.Socket,io:u,connect:u});var l=n(627);Object.defineProperty(t,"protocol",{enumerable:!0,get:function(){return l.protocol}}),e.exports=u},776:function(e,t,n){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,n,r){void 0===r&&(r=n),Object.defineProperty(e,r,{enumerable:!0,get:function(){return t[n]}})}:function(e,t,n,r){void 0===r&&(r=n),e[r]=t[n]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&r(t,e,n);return s(t,e),t},i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.Manager=void 0;const a=n(956),c=n(214),u=o(n(627)),l=n(942),h=n(743),d=n(285),f=i(n(833)).default("socket.io-client:manager");class p extends d.Emitter{constructor(e,t){var n;super(),this.nsps={},this.subs=[],e&&"object"==typeof e&&(t=e,e=void 0),(t=t||{}).path=t.path||"/socket.io",this.opts=t,a.installTimerFunctions(this,t),this.reconnection(!1!==t.reconnection),this.reconnectionAttempts(t.reconnectionAttempts||1/0),this.reconnectionDelay(t.reconnectionDelay||1e3),this.reconnectionDelayMax(t.reconnectionDelayMax||5e3),this.randomizationFactor(null!==(n=t.randomizationFactor)&&void 0!==n?n:.5),this.backoff=new h.Backoff({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(null==t.timeout?2e4:t.timeout),this._readyState="closed",this.uri=e;const r=t.parser||u;this.encoder=new r.Encoder,this.decoder=new r.Decoder,this._autoConnect=!1!==t.autoConnect,this._autoConnect&&this.open()}reconnection(e){return arguments.length?(this._reconnection=!!e,this):this._reconnection}reconnectionAttempts(e){return void 0===e?this._reconnectionAttempts:(this._reconnectionAttempts=e,this)}reconnectionDelay(e){var t;return void 0===e?this._reconnectionDelay:(this._reconnectionDelay=e,null===(t=this.backoff)||void 0===t||t.setMin(e),this)}randomizationFactor(e){var t;return void 0===e?this._randomizationFactor:(this._randomizationFactor=e,null===(t=this.backoff)||void 0===t||t.setJitter(e),this)}reconnectionDelayMax(e){var t;return void 0===e?this._reconnectionDelayMax:(this._reconnectionDelayMax=e,null===(t=this.backoff)||void 0===t||t.setMax(e),this)}timeout(e){return arguments.length?(this._timeout=e,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&0===this.backoff.attempts&&this.reconnect()}open(e){if(f("readyState %s",this._readyState),~this._readyState.indexOf("open"))return this;f("opening %s",this.uri),this.engine=new a.Socket(this.uri,this.opts);const t=this.engine,n=this;this._readyState="opening",this.skipReconnect=!1;const r=l.on(t,"open",(function(){n.onopen(),e&&e()})),s=t=>{f("error"),this.cleanup(),this._readyState="closed",this.emitReserved("error",t),e?e(t):this.maybeReconnectOnOpen()},o=l.on(t,"error",s);if(!1!==this._timeout){const e=this._timeout;f("connect attempt will timeout after %d",e);const n=this.setTimeoutFn((()=>{f("connect attempt timed out after %d",e),r(),s(new Error("timeout")),t.close()}),e);this.opts.autoUnref&&n.unref(),this.subs.push((()=>{this.clearTimeoutFn(n)}))}return this.subs.push(r),this.subs.push(o),this}connect(e){return this.open(e)}onopen(){f("open"),this.cleanup(),this._readyState="open",this.emitReserved("open");const e=this.engine;this.subs.push(l.on(e,"ping",this.onping.bind(this)),l.on(e,"data",this.ondata.bind(this)),l.on(e,"error",this.onerror.bind(this)),l.on(e,"close",this.onclose.bind(this)),l.on(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(e){try{this.decoder.add(e)}catch(e){this.onclose("parse error",e)}}ondecoded(e){a.nextTick((()=>{this.emitReserved("packet",e)}),this.setTimeoutFn)}onerror(e){f("error",e),this.emitReserved("error",e)}socket(e,t){let n=this.nsps[e];return n?this._autoConnect&&!n.active&&n.connect():(n=new c.Socket(this,e,t),this.nsps[e]=n),n}_destroy(e){const t=Object.keys(this.nsps);for(const e of t)if(this.nsps[e].active)return void f("socket %s is still active, skipping close",e);this._close()}_packet(e){f("writing packet %j",e);const t=this.encoder.encode(e);for(let n=0;n<t.length;n++)this.engine.write(t[n],e.options)}cleanup(){f("cleanup"),this.subs.forEach((e=>e())),this.subs.length=0,this.decoder.destroy()}_close(){f("disconnect"),this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close"),this.engine&&this.engine.close()}disconnect(){return this._close()}onclose(e,t){f("closed due to %s",e),this.cleanup(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",e,t),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const e=this;if(this.backoff.attempts>=this._reconnectionAttempts)f("reconnect failed"),this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const t=this.backoff.duration();f("will wait %dms before reconnect attempt",t),this._reconnecting=!0;const n=this.setTimeoutFn((()=>{e.skipReconnect||(f("attempting reconnect"),this.emitReserved("reconnect_attempt",e.backoff.attempts),e.skipReconnect||e.open((t=>{t?(f("reconnect attempt error"),e._reconnecting=!1,e.reconnect(),this.emitReserved("reconnect_error",t)):(f("reconnect success"),e.onreconnect())})))}),t);this.opts.autoUnref&&n.unref(),this.subs.push((()=>{this.clearTimeoutFn(n)}))}}onreconnect(){const e=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",e)}}t.Manager=p},942:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.on=void 0,t.on=function(e,t,n){return e.on(t,n),function(){e.off(t,n)}}},214:function(e,t,n){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.Socket=void 0;const s=n(627),o=n(942),i=n(285),a=r(n(833)).default("socket.io-client:socket"),c=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class u extends i.Emitter{constructor(e,t,n){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=e,this.nsp=t,n&&n.auth&&(this.auth=n.auth),this._opts=Object.assign({},n),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const e=this.io;this.subs=[o.on(e,"open",this.onopen.bind(this)),o.on(e,"packet",this.onpacket.bind(this)),o.on(e,"error",this.onerror.bind(this)),o.on(e,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected||(this.subEvents(),this.io._reconnecting||this.io.open(),"open"===this.io._readyState&&this.onopen()),this}open(){return this.connect()}send(...e){return e.unshift("message"),this.emit.apply(this,e),this}emit(e,...t){if(c.hasOwnProperty(e))throw new Error('"'+e.toString()+'" is a reserved event name');if(t.unshift(e),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(t),this;const n={type:s.PacketType.EVENT,data:t,options:{}};if(n.options.compress=!1!==this.flags.compress,"function"==typeof t[t.length-1]){const e=this.ids++;a("emitting packet with ack id %d",e);const r=t.pop();this._registerAckCallback(e,r),n.id=e}const r=this.io.engine&&this.io.engine.transport&&this.io.engine.transport.writable;return!this.flags.volatile||r&&this.connected?this.connected?(this.notifyOutgoingListeners(n),this.packet(n)):this.sendBuffer.push(n):a("discard packet as the transport is not currently writable"),this.flags={},this}_registerAckCallback(e,t){var n;const r=null!==(n=this.flags.timeout)&&void 0!==n?n:this._opts.ackTimeout;if(void 0===r)return void(this.acks[e]=t);const s=this.io.setTimeoutFn((()=>{delete this.acks[e];for(let t=0;t<this.sendBuffer.length;t++)this.sendBuffer[t].id===e&&(a("removing packet with ack id %d from the buffer",e),this.sendBuffer.splice(t,1));a("event with ack id %d has timed out after %d ms",e,r),t.call(this,new Error("operation has timed out"))}),r),o=(...e)=>{this.io.clearTimeoutFn(s),t.apply(this,e)};o.withError=!0,this.acks[e]=o}emitWithAck(e,...t){return new Promise(((n,r)=>{const s=(e,t)=>e?r(e):n(t);s.withError=!0,t.push(s),this.emit(e,...t)}))}_addToQueue(e){let t;"function"==typeof e[e.length-1]&&(t=e.pop());const n={id:this._queueSeq++,tryCount:0,pending:!1,args:e,flags:Object.assign({fromQueue:!0},this.flags)};e.push(((e,...r)=>{if(n===this._queue[0])return null!==e?n.tryCount>this._opts.retries&&(a("packet [%d] is discarded after %d tries",n.id,n.tryCount),this._queue.shift(),t&&t(e)):(a("packet [%d] was successfully sent",n.id),this._queue.shift(),t&&t(null,...r)),n.pending=!1,this._drainQueue()})),this._queue.push(n),this._drainQueue()}_drainQueue(e=!1){if(a("draining queue"),!this.connected||0===this._queue.length)return;const t=this._queue[0];!t.pending||e?(t.pending=!0,t.tryCount++,a("sending packet [%d] (try n°%d)",t.id,t.tryCount),this.flags=t.flags,this.emit.apply(this,t.args)):a("packet [%d] has already been sent and is waiting for an ack",t.id)}packet(e){e.nsp=this.nsp,this.io._packet(e)}onopen(){a("transport is open - connecting"),"function"==typeof this.auth?this.auth((e=>{this._sendConnectPacket(e)})):this._sendConnectPacket(this.auth)}_sendConnectPacket(e){this.packet({type:s.PacketType.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},e):e})}onerror(e){this.connected||this.emitReserved("connect_error",e)}onclose(e,t){a("close (%s)",e),this.connected=!1,delete this.id,this.emitReserved("disconnect",e,t),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach((e=>{if(!this.sendBuffer.some((t=>String(t.id)===e))){const t=this.acks[e];delete this.acks[e],t.withError&&t.call(this,new Error("socket has been disconnected"))}}))}onpacket(e){if(e.nsp===this.nsp)switch(e.type){case s.PacketType.CONNECT:e.data&&e.data.sid?this.onconnect(e.data.sid,e.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case s.PacketType.EVENT:case s.PacketType.BINARY_EVENT:this.onevent(e);break;case s.PacketType.ACK:case s.PacketType.BINARY_ACK:this.onack(e);break;case s.PacketType.DISCONNECT:this.ondisconnect();break;case s.PacketType.CONNECT_ERROR:this.destroy();const t=new Error(e.data.message);t.data=e.data.data,this.emitReserved("connect_error",t)}}onevent(e){const t=e.data||[];a("emitting event %j",t),null!=e.id&&(a("attaching ack callback to event"),t.push(this.ack(e.id))),this.connected?this.emitEvent(t):this.receiveBuffer.push(Object.freeze(t))}emitEvent(e){if(this._anyListeners&&this._anyListeners.length){const t=this._anyListeners.slice();for(const n of t)n.apply(this,e)}super.emit.apply(this,e),this._pid&&e.length&&"string"==typeof e[e.length-1]&&(this._lastOffset=e[e.length-1])}ack(e){const t=this;let n=!1;return function(...r){n||(n=!0,a("sending ack %j",r),t.packet({type:s.PacketType.ACK,id:e,data:r}))}}onack(e){const t=this.acks[e.id];"function"==typeof t?(delete this.acks[e.id],a("calling ack %s with %j",e.id,e.data),t.withError&&e.data.unshift(null),t.apply(this,e.data)):a("bad ack %s",e.id)}onconnect(e,t){a("socket connected with id %s",e),this.id=e,this.recovered=t&&this._pid===t,this._pid=t,this.connected=!0,this.emitBuffered(),this.emitReserved("connect"),this._drainQueue(!0)}emitBuffered(){this.receiveBuffer.forEach((e=>this.emitEvent(e))),this.receiveBuffer=[],this.sendBuffer.forEach((e=>{this.notifyOutgoingListeners(e),this.packet(e)})),this.sendBuffer=[]}ondisconnect(){a("server disconnect (%s)",this.nsp),this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach((e=>e())),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&(a("performing disconnect (%s)",this.nsp),this.packet({type:s.PacketType.DISCONNECT})),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(e){return this.flags.compress=e,this}get volatile(){return this.flags.volatile=!0,this}timeout(e){return this.flags.timeout=e,this}onAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(e),this}prependAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(e),this}offAny(e){if(!this._anyListeners)return this;if(e){const t=this._anyListeners;for(let n=0;n<t.length;n++)if(e===t[n])return t.splice(n,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(e),this}prependAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(e),this}offAnyOutgoing(e){if(!this._anyOutgoingListeners)return this;if(e){const t=this._anyOutgoingListeners;for(let n=0;n<t.length;n++)if(e===t[n])return t.splice(n,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(e){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const t=this._anyOutgoingListeners.slice();for(const n of t)n.apply(this,e.data)}}}t.Socket=u},894:function(e,t,n){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.url=void 0;const s=n(956),o=r(n(833)).default("socket.io-client:url");t.url=function(e,t="",n){let r=e;n=n||"undefined"!=typeof location&&location,null==e&&(e=n.protocol+"//"+n.host),"string"==typeof e&&("/"===e.charAt(0)&&(e="/"===e.charAt(1)?n.protocol+e:n.host+e),/^(https?|wss?):\/\//.test(e)||(o("protocol-less url %s",e),e=void 0!==n?n.protocol+"//"+e:"https://"+e),o("parse %s",e),r=s.parse(e)),r.port||(/^(http|ws)$/.test(r.protocol)?r.port="80":/^(http|ws)s$/.test(r.protocol)&&(r.port="443")),r.path=r.path||"/";const i=-1!==r.host.indexOf(":")?"["+r.host+"]":r.host;return r.id=r.protocol+"://"+i+":"+r.port+t,r.href=r.protocol+"://"+i+(n&&n.port===r.port?"":":"+r.port),r}},926:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.reconstructPacket=t.deconstructPacket=void 0;const r=n(133);function s(e,t){if(!e)return e;if((0,r.isBinary)(e)){const n={_placeholder:!0,num:t.length};return t.push(e),n}if(Array.isArray(e)){const n=new Array(e.length);for(let r=0;r<e.length;r++)n[r]=s(e[r],t);return n}if("object"==typeof e&&!(e instanceof Date)){const n={};for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=s(e[r],t));return n}return e}function o(e,t){if(!e)return e;if(e&&!0===e._placeholder){if("number"==typeof e.num&&e.num>=0&&e.num<t.length)return t[e.num];throw new Error("illegal attachments")}if(Array.isArray(e))for(let n=0;n<e.length;n++)e[n]=o(e[n],t);else if("object"==typeof e)for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&(e[n]=o(e[n],t));return e}t.deconstructPacket=function(e){const t=[],n=e.data,r=e;return r.data=s(n,t),r.attachments=t.length,{packet:r,buffers:t}},t.reconstructPacket=function(e,t){return e.data=o(e.data,t),delete e.attachments,e}},627:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Decoder=t.Encoder=t.PacketType=t.protocol=void 0;const r=n(285),s=n(926),o=n(133),i=(0,n(833).default)("socket.io-parser"),a=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var c;function u(e){return"[object Object]"===Object.prototype.toString.call(e)}t.protocol=5,function(e){e[e.CONNECT=0]="CONNECT",e[e.DISCONNECT=1]="DISCONNECT",e[e.EVENT=2]="EVENT",e[e.ACK=3]="ACK",e[e.CONNECT_ERROR=4]="CONNECT_ERROR",e[e.BINARY_EVENT=5]="BINARY_EVENT",e[e.BINARY_ACK=6]="BINARY_ACK"}(c=t.PacketType||(t.PacketType={})),t.Encoder=class{constructor(e){this.replacer=e}encode(e){return i("encoding packet %j",e),e.type!==c.EVENT&&e.type!==c.ACK||!(0,o.hasBinary)(e)?[this.encodeAsString(e)]:this.encodeAsBinary({type:e.type===c.EVENT?c.BINARY_EVENT:c.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id})}encodeAsString(e){let t=""+e.type;return e.type!==c.BINARY_EVENT&&e.type!==c.BINARY_ACK||(t+=e.attachments+"-"),e.nsp&&"/"!==e.nsp&&(t+=e.nsp+","),null!=e.id&&(t+=e.id),null!=e.data&&(t+=JSON.stringify(e.data,this.replacer)),i("encoded %j as %s",e,t),t}encodeAsBinary(e){const t=(0,s.deconstructPacket)(e),n=this.encodeAsString(t.packet),r=t.buffers;return r.unshift(n),r}};class l extends r.Emitter{constructor(e){super(),this.reviver=e}add(e){let t;if("string"==typeof e){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");t=this.decodeString(e);const n=t.type===c.BINARY_EVENT;n||t.type===c.BINARY_ACK?(t.type=n?c.EVENT:c.ACK,this.reconstructor=new h(t),0===t.attachments&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t)}else{if(!(0,o.isBinary)(e)&&!e.base64)throw new Error("Unknown type: "+e);if(!this.reconstructor)throw new Error("got binary data when not reconstructing a packet");t=this.reconstructor.takeBinaryData(e),t&&(this.reconstructor=null,super.emitReserved("decoded",t))}}decodeString(e){let t=0;const n={type:Number(e.charAt(0))};if(void 0===c[n.type])throw new Error("unknown packet type "+n.type);if(n.type===c.BINARY_EVENT||n.type===c.BINARY_ACK){const r=t+1;for(;"-"!==e.charAt(++t)&&t!=e.length;);const s=e.substring(r,t);if(s!=Number(s)||"-"!==e.charAt(t))throw new Error("Illegal attachments");n.attachments=Number(s)}if("/"===e.charAt(t+1)){const r=t+1;for(;++t&&","!==e.charAt(t)&&t!==e.length;);n.nsp=e.substring(r,t)}else n.nsp="/";const r=e.charAt(t+1);if(""!==r&&Number(r)==r){const r=t+1;for(;++t;){const n=e.charAt(t);if(null==n||Number(n)!=n){--t;break}if(t===e.length)break}n.id=Number(e.substring(r,t+1))}if(e.charAt(++t)){const r=this.tryParse(e.substr(t));if(!l.isPayloadValid(n.type,r))throw new Error("invalid payload");n.data=r}return i("decoded %s as %j",e,n),n}tryParse(e){try{return JSON.parse(e,this.reviver)}catch(e){return!1}}static isPayloadValid(e,t){switch(e){case c.CONNECT:return u(t);case c.DISCONNECT:return void 0===t;case c.CONNECT_ERROR:return"string"==typeof t||u(t);case c.EVENT:case c.BINARY_EVENT:return Array.isArray(t)&&("number"==typeof t[0]||"string"==typeof t[0]&&-1===a.indexOf(t[0]));case c.ACK:case c.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}t.Decoder=l;class h{constructor(e){this.packet=e,this.buffers=[],this.reconPack=e}takeBinaryData(e){if(this.buffers.push(e),this.buffers.length===this.reconPack.attachments){const e=(0,s.reconstructPacket)(this.reconPack,this.buffers);return this.finishedReconstruction(),e}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}},133:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.hasBinary=t.isBinary=void 0;const n="function"==typeof ArrayBuffer,r=Object.prototype.toString,s="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===r.call(Blob),o="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===r.call(File);function i(e){return n&&(e instanceof ArrayBuffer||(e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer)(e))||s&&e instanceof Blob||o&&e instanceof File}t.isBinary=i,t.hasBinary=function e(t,n){if(!t||"object"!=typeof t)return!1;if(Array.isArray(t)){for(let n=0,r=t.length;n<r;n++)if(e(t[n]))return!0;return!1}if(i(t))return!0;if(t.toJSON&&"function"==typeof t.toJSON&&1===arguments.length)return e(t.toJSON(),!0);for(const n in t)if(Object.prototype.hasOwnProperty.call(t,n)&&e(t[n]))return!0;return!1}},285:(e,t,n)=>{"use strict";function r(e){if(e)return function(e){for(var t in r.prototype)e[t]=r.prototype[t];return e}(e)}n.r(t),n.d(t,{Emitter:()=>r}),r.prototype.on=r.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this},r.prototype.once=function(e,t){function n(){this.off(e,n),t.apply(this,arguments)}return n.fn=t,this.on(e,n),this},r.prototype.off=r.prototype.removeListener=r.prototype.removeAllListeners=r.prototype.removeEventListener=function(e,t){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var n,r=this._callbacks["$"+e];if(!r)return this;if(1==arguments.length)return delete this._callbacks["$"+e],this;for(var s=0;s<r.length;s++)if((n=r[s])===t||n.fn===t){r.splice(s,1);break}return 0===r.length&&delete this._callbacks["$"+e],this},r.prototype.emit=function(e){this._callbacks=this._callbacks||{};for(var t=new Array(arguments.length-1),n=this._callbacks["$"+e],r=1;r<arguments.length;r++)t[r-1]=arguments[r];if(n){r=0;for(var s=(n=n.slice(0)).length;r<s;++r)n[r].apply(this,t)}return this},r.prototype.emitReserved=r.prototype.emit,r.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks["$"+e]||[]},r.prototype.hasListeners=function(e){return!!this.listeners(e).length}}},t={};function n(r){var s=t[r];if(void 0!==s)return s.exports;var o=t[r]={exports:{}};return e[r].call(o.exports,o,o.exports,n),o.exports}n.d=(e,t)=>{for(var r in t)n.o(t,r)&&!n.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},n.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),n.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var r={};return(()=>{"use strict";var e=r;Object.defineProperty(e,"__esModule",{value:!0}),e.validateConfiguration=e.parseconnectionstring=e.prepareSql=e.escapeSqlParameter=e.SQLiteCloudRow=e.SQLiteCloudRowset=e.SQLiteCloudError=e.SQLiteCloudConnection=e.Statement=e.Database=void 0;var t=n(500);Object.defineProperty(e,"Database",{enumerable:!0,get:function(){return t.Database}});var s=n(96);Object.defineProperty(e,"Statement",{enumerable:!0,get:function(){return s.Statement}});var o=n(361);Object.defineProperty(e,"SQLiteCloudConnection",{enumerable:!0,get:function(){return o.SQLiteCloudConnection}});var i=n(80);Object.defineProperty(e,"SQLiteCloudError",{enumerable:!0,get:function(){return i.SQLiteCloudError}});var a=n(121);Object.defineProperty(e,"SQLiteCloudRowset",{enumerable:!0,get:function(){return a.SQLiteCloudRowset}}),Object.defineProperty(e,"SQLiteCloudRow",{enumerable:!0,get:function(){return a.SQLiteCloudRow}});var c=n(193);Object.defineProperty(e,"escapeSqlParameter",{enumerable:!0,get:function(){return c.escapeSqlParameter}}),Object.defineProperty(e,"prepareSql",{enumerable:!0,get:function(){return c.prepareSql}}),Object.defineProperty(e,"parseconnectionstring",{enumerable:!0,get:function(){return c.parseconnectionstring}}),Object.defineProperty(e,"validateConfiguration",{enumerable:!0,get:function(){return c.validateConfiguration}})})(),r})()));
1
+ !function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.sqlitecloud=t():e.sqlitecloud=t()}(this,(()=>(()=>{var e={945:function(e,t,n){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,n,r){void 0===r&&(r=n);var s=Object.getOwnPropertyDescriptor(t,n);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,s)}:function(e,t,n,r){void 0===r&&(r=n),e[r]=t[n]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&r(t,e,n);return s(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.SQLiteCloudTlsConnection=void 0;const i=n(80),a=n(361),c=n(193),u=n(773),l=o(n(498));class h extends a.SQLiteCloudConnection{constructor(){super(...arguments),this.buffer=Buffer.alloc(0),this.startedOn=new Date}get connected(){return!!this.socket}connectTransport(e,t){console.assert(!this.connected,"SQLiteCloudTlsConnection.connect - connection already established"),this.config.verbose&&console.debug(`-> connecting ${null==e?void 0:e.host}:${null==e?void 0:e.port}`),this.config=e;const n=(0,c.getInitializationCommands)(e),r={host:e.host,port:e.port,rejectUnauthorized:"localhost"!=e.host,servername:e.host};return this.socket=l.connect(r,(()=>{var e;this.config.verbose&&console.debug(`SQLiteCloudTlsConnection - connected to ${this.config.host}, authorized: ${null===(e=this.socket)||void 0===e?void 0:e.authorized}`),this.transportCommands(n,(e=>{this.config.verbose&&console.debug("SQLiteCloudTlsConnection - initialized connection"),null==t||t.call(this,e)}))})),this.socket.on("data",(e=>{this.processCommandsData(e)})),this.socket.on("error",(e=>{this.close(),this.processCommandsFinish(new i.SQLiteCloudError("Connection error",{errorCode:"ERR_CONNECTION_ERROR",cause:e}))})),this.socket.on("end",(()=>{this.close(),this.processCallback&&this.processCommandsFinish(new i.SQLiteCloudError("Server ended the connection",{errorCode:"ERR_CONNECTION_ENDED"}))})),this.socket.on("close",(()=>{this.close(),this.processCommandsFinish(new i.SQLiteCloudError("Connection closed",{errorCode:"ERR_CONNECTION_CLOSED"}))})),this}transportCommands(e,t){var n,r,s,o,a;if(!this.socket)return null==t||t.call(this,new i.SQLiteCloudError("Connection not established",{errorCode:"ERR_CONNECTION_NOT_ESTABLISHED"})),this;this.buffer=Buffer.alloc(0),this.startedOn=new Date,this.processCallback=t,this.executingCommands=e;const c=(0,u.formatCommand)(e);(null===(n=this.config)||void 0===n?void 0:n.verbose)&&console.debug(`-> ${c}`);const l=null!==(s=null===(r=this.config)||void 0===r?void 0:r.timeout)&&void 0!==s?s:0;if(l>0){const e=setTimeout((()=>{var e;null==t||t.call(this,new i.SQLiteCloudError("Connection timeout out",{errorCode:"ERR_CONNECTION_TIMEOUT"})),null===(e=this.socket)||void 0===e||e.destroy(),this.socket=void 0}),l);null===(o=this.socket)||void 0===o||o.write(c,"utf-8",(()=>{clearTimeout(e)}))}else null===(a=this.socket)||void 0===a||a.write(c,"utf-8");return this}processCommandsData(e){var t,n,r,s,o,i;try{e.length&&e.length>0&&(this.buffer=Buffer.concat([this.buffer,e]));let i=null===(t=this.buffer)||void 0===t?void 0:t.subarray(0,1).toString();if((0,u.hasCommandLength)(i)){const e=(0,u.parseCommandLength)(this.buffer);if(this.buffer.length-this.buffer.indexOf(" ")-1>=e){if(null===(n=this.config)||void 0===n?void 0:n.verbose){let e=this.buffer.toString("utf8");e.length>1e3&&(e=e.substring(0,100)+"..."+e.substring(e.length-40));const t=(new Date).getTime()-this.startedOn.getTime();console.debug(`<- ${e} (${t}ms)`)}if(i===u.CMD_COMPRESSED&&({buffer:this.buffer,dataType:i}=(0,u.decompressBuffer)(this.buffer)),i!==u.CMD_ROWSET_CHUNK){const{data:e}=(0,u.popData)(this.buffer);null===(r=this.processCommandsFinish)||void 0===r||r.call(this,null,e)}else if((0,u.bufferEndsWith)(this.buffer,u.ROWSET_CHUNKS_END)){const e=(0,u.parseRowsetChunks)([this.buffer]);null===(s=this.processCommandsFinish)||void 0===s||s.call(this,null,e)}}}else if(" "==this.buffer.subarray(this.buffer.length-1,this.buffer.length).toString("utf8")){const{data:e}=(0,u.popData)(this.buffer);null===(o=this.processCommandsFinish)||void 0===o||o.call(this,null,e)}}catch(e){console.assert(e instanceof Error),e instanceof Error&&(null===(i=this.processCommandsFinish)||void 0===i||i.call(this,e))}}processCommandsFinish(e,t){e&&(this.processCallback?console.error("processCommandsFinish - error",e):console.warn("processCommandsFinish - error with no registered callback",e)),this.processCallback&&this.processCallback(e,t),this.buffer=Buffer.alloc(0)}close(){return this.socket&&(this.socket.removeAllListeners(),this.socket.destroy(),this.socket=void 0),this.operations.clear(),this}}t.SQLiteCloudTlsConnection=h,t.default=h},392:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SQLiteCloudWebsocketConnection=void 0;const r=n(80),s=n(121),o=n(361),i=n(7);class a extends o.SQLiteCloudConnection{get connected(){return!!this.socket}connectTransport(e,t){var n;try{if(console.assert(!this.connected,"Connection already established"),!this.socket){this.config=e;const t=this.config.connectionstring,r=(null===(n=this.config)||void 0===n?void 0:n.gatewayurl)||`${"localhost"===this.config.host?"ws":"wss"}://${this.config.host}:4000`;this.socket=(0,i.io)(r,{auth:{token:t}})}null==t||t.call(this,null)}catch(e){null==t||t.call(this,e)}return this}transportCommands(e,t){return this.socket?(this.socket.emit("v1/sql",{sql:e,row:"array"},(e=>{if(null==e?void 0:e.error){const n=new r.SQLiteCloudError(e.error.detail,Object.assign({},e.error));null==t||t.call(this,n)}else{const{data:n,metadata:r}=e;if(n&&r&&void 0!==r.numberOfRows&&void 0!==r.numberOfColumns&&void 0!==r.columns){console.assert(Array.isArray(n),"SQLiteCloudWebsocketConnection.transportCommands - data is not an array");const e=new s.SQLiteCloudRowset(r,n.flat());return void(null==t||t.call(this,null,e))}null==t||t.call(this,null,null==e?void 0:e.data)}})),this):(null==t||t.call(this,new r.SQLiteCloudError("Connection not established",{errorCode:"ERR_CONNECTION_NOT_ESTABLISHED"})),this)}close(){var e;return console.assert(null!==this.socket,"SQLiteCloudWebsocketConnection.close - connection already closed"),this.socket&&(null===(e=this.socket)||void 0===e||e.close(),this.socket=void 0),this.operations.clear(),this.socket=void 0,this}}t.SQLiteCloudWebsocketConnection=a,t.default=a},361:function(e,t,n){"use strict";var r=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(s,o){function i(e){try{c(r.next(e))}catch(e){o(e)}}function a(e){try{c(r.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?s(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}c((r=r.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.SQLiteCloudConnection=void 0;const s=n(80),o=n(193),i=n(774),a=n(193);t.SQLiteCloudConnection=class{constructor(e,t){this.operations=new i.OperationsQueue,this.config="string"==typeof e?(0,o.validateConfiguration)({connectionstring:e}):(0,o.validateConfiguration)(e),this.connect(t)}getConfig(){return Object.assign({},this.config)}connect(e){return this.operations.enqueue((t=>{this.connectTransport(this.config,(n=>{n&&(console.error(`SQLiteCloudConnection.connect - error connecting ${this.config.host}:${this.config.port} ${n.toString()}`,n),this.close()),e&&e.call(this,n||null),t(n)}))})),this}log(e,...t){this.config.verbose&&(e=(0,a.anonimizeCommand)(e),console.log(`${(new Date).toISOString()} ${this.config.clientid}: ${e}`,...t))}verbose(){this.config.verbose=!0}sendCommands(e,t){return this.operations.enqueue((n=>{if(this.connected)this.transportCommands(e,((e,r)=>{null==t||t.call(this,e,r),n(e)}));else{const e=new s.SQLiteCloudError("Connection not established",{errorCode:"ERR_CONNECTION_NOT_ESTABLISHED"});null==t||t.call(this,e),n(e)}})),this}sql(e,...t){return r(this,void 0,void 0,(function*(){let n="";if(Array.isArray(e)&&"raw"in e)e.forEach(((e,r)=>{n+=e+(r<t.length?"?":"")})),n=(0,o.prepareSql)(n,...t);else{if("string"!=typeof e)throw new Error("Invalid sql");n=(null==t?void 0:t.length)>0?(0,o.prepareSql)(e,...t):e}return new Promise(((e,t)=>{this.sendCommands(n,((n,r)=>{if(n)t(n);else{const t=(0,a.getUpdateResults)(r);e(t||r)}}))}))}))}}},500:function(e,t,n){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,n,r){void 0===r&&(r=n);var s=Object.getOwnPropertyDescriptor(t,n);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,s)}:function(e,t,n,r){void 0===r&&(r=n),e[r]=t[n]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&r(t,e,n);return s(t,e),t},i=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(s,o){function i(e){try{c(r.next(e))}catch(e){o(e)}}function a(e){try{c(r.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?s(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}c((r=r.apply(e,t||[])).next())}))},a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.Database=void 0;const c=n(121),u=n(80),l=n(193),h=n(96),d=a(n(228)),f=n(193),p=n(842);class m extends d.default{constructor(e,t,n){super(),this.connections=[],this.config="string"==typeof e?{connectionstring:e}:e,"function"==typeof t&&(n=t,t=void 0),this.getConnection(((e,t)=>{n&&n.call(this,e)}))}getConnection(e){var t,r,s;(null===(t=this.connections)||void 0===t?void 0:t.length)>0?null==e||e.call(this,null,this.connections[0]):f.isBrowser||(null===(r=this.config)||void 0===r?void 0:r.usewebsocket)||(null===(s=this.config)||void 0===s?void 0:s.gatewayurl)?Promise.resolve().then((()=>o(n(392)))).then((t=>{this.connections.push(new t.default(this.config,(t=>{t?this.handleError(this.connections[0],t,e):(console.assert,null==e||e.call(this,null,this.connections[0]),this.emitEvent("open"))})))})).catch((t=>{this.handleError(null,t,e)})):Promise.resolve().then((()=>o(n(945)))).then((t=>{this.connections.push(new t.default(this.config,(t=>{t?this.handleError(this.connections[0],t,e):(console.assert,null==e||e.call(this,null,this.connections[0]),this.emitEvent("open"))})))})).catch((t=>{this.handleError(null,t,e)}))}handleError(e,t,n){e&&(this.connections=this.connections.filter((t=>t!==e)),e.close()),n?n.call(this,t):this.emitEvent("error",t)}processContext(e){if(e&&Array.isArray(e)&&e.length>0&&e[0]===u.SQLiteCloudArrayType.ARRAY_TYPE_SQLITE_EXEC)return{lastID:e[2],changes:e[3],totalChanges:e[4],finalized:e[5]}}emitEvent(e,...t){setTimeout((()=>{this.emit(e,...t)}),0)}getConfiguration(){return JSON.parse(JSON.stringify(this.config))}verbose(){this.config.verbose=!0;for(const e of this.connections)e.verbose();return this}configure(e,t){return this}run(e,...t){const{args:n,callback:r}=(0,l.popCallback)(t),s=(null==n?void 0:n.length)>0?(0,l.prepareSql)(e,...n):e;return this.getConnection(((e,t)=>{e||!t?this.handleError(null,e,r):t.sendCommands(s,((e,n)=>{if(e)this.handleError(t,e,r);else{const e=this.processContext(n);null==r||r.call(e||this,null,e||n)}}))})),this}get(e,...t){const{args:n,callback:r}=(0,l.popCallback)(t),s=(null==n?void 0:n.length)>0?(0,l.prepareSql)(e,...n):e;return this.getConnection(((e,t)=>{e||!t?this.handleError(null,e,r):t.sendCommands(s,((e,n)=>{e?this.handleError(t,e,r):n&&n instanceof c.SQLiteCloudRowset&&n.length>0?null==r||r.call(this,null,n[0]):null==r||r.call(this,null)}))})),this}all(e,...t){const{args:n,callback:r}=(0,l.popCallback)(t),s=(null==n?void 0:n.length)>0?(0,l.prepareSql)(e,...n):e;return this.getConnection(((e,t)=>{e||!t?this.handleError(null,e,r):t.sendCommands(s,((e,n)=>{e?this.handleError(t,e,r):n&&n instanceof c.SQLiteCloudRowset?null==r||r.call(this,null,n):null==r||r.call(this,null)}))})),this}each(e,...t){const{args:n,callback:r,complete:s}=(0,l.popCallback)(t),o=(null==n?void 0:n.length)>0?(0,l.prepareSql)(e,...n):e;return this.getConnection(((e,t)=>{e||!t?this.handleError(null,e,r):t.sendCommands(o,((e,n)=>{if(e)this.handleError(t,e,r);else if(n&&n instanceof c.SQLiteCloudRowset){if(r)for(const e of n)r.call(this,null,e);s&&s.call(this,null,n.numberOfRows)}else null==r||r.call(this,new u.SQLiteCloudError("Invalid rowset"))}))})),this}prepare(e,...t){const{args:n,callback:r}=(0,l.popCallback)(t);return new h.Statement(this,e,...n,r)}exec(e,t){return this.getConnection(((n,r)=>{n||!r?this.handleError(null,n,t):r.sendCommands(e,((e,n)=>{if(e)this.handleError(r,e,t);else{const e=this.processContext(n);null==t||t.call(e||this,null)}}))})),this}close(e){var t;if((null===(t=this.connections)||void 0===t?void 0:t.length)>0)for(const e of this.connections)e.close();null==e||e.call(this,null),this.emitEvent("close")}loadExtension(e,t){return t?t.call(this,new Error("Database.loadExtension - Not implemented")):this.emitEvent("error",new Error("Database.loadExtension - Not implemented")),this}interrupt(){}sql(e,...t){return i(this,void 0,void 0,(function*(){let n="";if(Array.isArray(e)&&"raw"in e)e.forEach(((e,r)=>{n+=e+(r<t.length?"?":"")})),n=(0,l.prepareSql)(n,...t);else{if("string"!=typeof e)throw new Error("Invalid sql");n=(null==t?void 0:t.length)>0?(0,l.prepareSql)(e,...t):e}return new Promise(((e,t)=>{this.getConnection(((r,s)=>{r||!s?t(r):s.sendCommands(n,((n,r)=>{if(n)t(n);else{const t=this.processContext(r);e(t||r)}}))}))}))}))}getPubSub(){return i(this,void 0,void 0,(function*(){return new Promise(((e,t)=>{this.getConnection(((n,r)=>{n||!r?t(n):e(new p.PubSub(r))}))}))}))}}t.Database=m},773:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.formatCommand=t.popData=t.parseRowsetChunks=t.bufferEndsWith=t.bufferStartsWith=t.parseRowsetHeader=t.parseArray=t.parseError=t.decompressBuffer=t.parseCommandLength=t.hasCommandLength=t.ROWSET_CHUNKS_END=t.CMD_PUBSUB=t.CMD_ARRAY=t.CMD_COMMAND=t.CMD_COMPRESSED=t.CMD_BLOB=t.CMD_NULL=t.CMD_JSON=t.CMD_ROWSET_CHUNK=t.CMD_ROWSET=t.CMD_FLOAT=t.CMD_INT=t.CMD_ERROR=t.CMD_ZEROSTRING=t.CMD_STRING=void 0;const r=n(80),s=n(121),o=n(404);function i(e,t){const n=e.subarray(t+1).toString("utf8").split(" ");let s=n.shift()||"0",o="0",i="-1";const a=s.split(":");s=a[0],a.length>1&&(o=a[1],a.length>2&&(i=a[2]));const c=n.join(" "),u=parseInt(s),l=parseInt(o),h=parseInt(i);throw new r.SQLiteCloudError(c,{errorCode:u.toString(),externalErrorCode:l.toString(),offsetCode:h})}function a(e,t){const n=[],r=e.subarray(t+1,e.length),s=parseInt(r.subarray(0,t-2).toString("utf8"));let o=r.subarray(r.indexOf(" ")+1,r.length);for(let e=0;e<s;e++){const{data:e,fwdBuffer:t}=d(o);n.push(e),o=t}return n}function c(e){const t=parseInt(e.subarray(0,e.indexOf(":")+1).toString());e=e.subarray(e.indexOf(":")+1);const{data:n,fwdBuffer:r}=function(e,t=1){const n=[];for(let r=0;r<t;r++){const t=e.indexOf(" ");n[r]=parseInt(e.subarray(0,t).toString()),e=e.subarray(t+1)}return{data:n,fwdBuffer:e}}(e,3);return{index:t,metadata:{version:n[0],numberOfRows:n[1],numberOfColumns:n[2],columns:[]},fwdBuffer:r}}function u(e,t){function n(){const{data:t,fwdBuffer:n}=d(e);return e=n,t}for(let e=0;e<t.numberOfColumns;e++)t.columns.push({name:n()});if(2==t.version){for(let e=0;e<t.numberOfColumns;e++)t.columns[e].type=n();for(let e=0;e<t.numberOfColumns;e++)t.columns[e].database=n();for(let e=0;e<t.numberOfColumns;e++)t.columns[e].table=n();for(let e=0;e<t.numberOfColumns;e++)t.columns[e].column=n();for(let e=0;e<t.numberOfColumns;e++)t.columns[e].notNull=n();for(let e=0;e<t.numberOfColumns;e++)t.columns[e].primaryKey=n();for(let e=0;e<t.numberOfColumns;e++)t.columns[e].autoIncrement=n()}return e}function l(e,t){return e.length>=t.length&&e.subarray(0,t.length).toString("utf8")===t}function h(e,t){return e.length>=t.length&&e.subarray(e.length-t.length,e.length).toString("utf8")===t}function d(e){function n(t){return{data:t,fwdBuffer:e.subarray(l)}}console.assert(e&&e instanceof Buffer);const r=e.subarray(0,1).toString("utf8");console.assert(r!==t.CMD_COMPRESSED,"Compressed data shouldn't be decompressed before parsing"),console.assert(r!==t.CMD_ROWSET_CHUNK,"Chunked data should be parsed by parseRowsetChunks");let o=e.indexOf(" ");-1===o&&(o=e.length-1);let l=-1;if(r===t.CMD_INT||r===t.CMD_FLOAT||r===t.CMD_NULL)l=o+1;else{const t=parseInt(e.subarray(1,o).toString());l=o+1+t}switch(r){case t.CMD_INT:return n(parseInt(e.subarray(1,o).toString()));case t.CMD_FLOAT:return n(parseFloat(e.subarray(1,o).toString()));case t.CMD_NULL:return n(null);case t.CMD_STRING:return n(e.subarray(o+1,l).toString("utf8"));case t.CMD_ZEROSTRING:return n(e.subarray(o+1,l-1).toString("utf8"));case t.CMD_COMMAND:case t.CMD_PUBSUB:return n(e.subarray(o+1,l).toString("utf8"));case t.CMD_JSON:return n(JSON.parse(e.subarray(o+1,l).toString("utf8")));case t.CMD_BLOB:return n(e.subarray(o+1,l));case t.CMD_ARRAY:return n(a(e,o));case t.CMD_ROWSET:return n(function(e,t){e=e.subarray(t+1,e.length);const{metadata:n,fwdBuffer:r}=c(e);e=u(r,n);const o=[];for(let t=0;t<n.numberOfRows*n.numberOfColumns;t++){const{data:t,fwdBuffer:n}=d(e);o.push(t),e=n}return console.assert(o&&o.length===n.numberOfRows*n.numberOfColumns,"SQLiteCloudConnection.parseRowset - invalid rowset data"),new s.SQLiteCloudRowset(n,o)}(e,o));case t.CMD_ERROR:i(e,o)}throw new TypeError(`Data type: ${r} is not defined in SCSP`)}t.CMD_STRING="+",t.CMD_ZEROSTRING="!",t.CMD_ERROR="-",t.CMD_INT=":",t.CMD_FLOAT=",",t.CMD_ROWSET="*",t.CMD_ROWSET_CHUNK="/",t.CMD_JSON="#",t.CMD_NULL="_",t.CMD_BLOB="$",t.CMD_COMPRESSED="%",t.CMD_COMMAND="^",t.CMD_ARRAY="=",t.CMD_PUBSUB="|",t.ROWSET_CHUNKS_END="/6 0 0 0 ",t.hasCommandLength=function(e){return e!=t.CMD_INT&&e!=t.CMD_FLOAT&&e!=t.CMD_NULL},t.parseCommandLength=function(e){return parseInt(e.subarray(1,e.indexOf(" ")).toString("utf8"))},t.decompressBuffer=function(e){const t=e.indexOf(" ");e=e.subarray(t+1);const n=parseInt(e.subarray(0,e.indexOf(" ")+1).toString("utf8"));e=e.subarray(e.indexOf(" ")+1);const r=parseInt(e.subarray(0,e.indexOf(" ")+1).toString("utf8")),s=(e=e.subarray(e.indexOf(" ")+1)).subarray(0,1).toString("utf8"),i=Buffer.alloc(r),a=e.subarray(e.length-n),c=o.decompressBlock(a,i,0,n,0);if(e=Buffer.concat([e.subarray(0,e.length-n),i]),c<=0||c!==r)throw new Error(`lz4 decompression error at offset ${c}`);return{buffer:e,dataType:s}},t.parseError=i,t.parseArray=a,t.parseRowsetHeader=c,t.bufferStartsWith=l,t.bufferEndsWith=h,t.parseRowsetChunks=function(e){let n=Buffer.concat(e);if(!l(n,t.CMD_ROWSET_CHUNK)||!h(n,t.ROWSET_CHUNKS_END))throw new Error("SQLiteCloudConnection.parseRowsetChunks - invalid chunks buffer");let r={version:1,numberOfColumns:0,numberOfRows:0,columns:[]};const o=[],i=n.subarray(0,1).toString();for(console.assert(i===t.CMD_ROWSET_CHUNK),n=n.subarray(n.indexOf(" ")+1);n.length>0&&!l(n,t.ROWSET_CHUNKS_END);){const{index:e,metadata:t,fwdBuffer:s}=c(n);n=s,1===e?(r=t,n=u(n,r)):r.numberOfRows+=t.numberOfRows;for(let e=0;e<t.numberOfRows*r.numberOfColumns;e++){const{data:e,fwdBuffer:t}=d(n);o.push(e),n=t}}return console.assert(o&&o.length===r.numberOfRows*r.numberOfColumns,"parseRowsetChunks - invalid rowset data"),new s.SQLiteCloudRowset(r,o)},t.popData=d,t.formatCommand=function(e){return`+${Buffer.byteLength(e,"utf-8")} ${e}`}},842:function(e,t,n){"use strict";var r=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(s,o){function i(e){try{c(r.next(e))}catch(e){o(e)}}function a(e){try{c(r.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?s(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}c((r=r.apply(e,t||[])).next())}))},s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.PubSub=t.PUBSUB_ENTITY_TYPE=void 0;const o=s(n(945));var i;(i=t.PUBSUB_ENTITY_TYPE||(t.PUBSUB_ENTITY_TYPE={})).TABLE="TABLE",i.CHANNEL="CHANNEL",t.PubSub=class{constructor(e){this.connection=e,this.connectionPubSub=new o.default(e.getConfig())}listen(e,t,n,s){return r(this,void 0,void 0,(function*(){const r="TABLE"===e?"TABLE ":"",o=yield this.connection.sql(`LISTEN ${r}${t};`);return new Promise(((e,t)=>{this.connectionPubSub.sendCommands(o,((r,o)=>{r?(n.call(this,r,null,s),t(r)):("OK"!==o&&n.call(this,null,o,s),e(o))}))}))}))}unlisten(e,t){return r(this,void 0,void 0,(function*(){const n="TABLE"===e?"TABLE ":"";return this.connection.sql(`UNLISTEN ${n}?;`,t)}))}createChannel(e,t=!0){return r(this,void 0,void 0,(function*(){let n="";return t||(n="IF NOT EXISTS;"),this.connection.sql(`CREATE CHANNEL ? ${n}`,e)}))}notifyChannel(e,t){return this.connection.sql`NOTIFY ${e} ${t};`}setPubSubOnly(){return new Promise(((e,t)=>{this.connection.sendCommands("PUBSUB ONLY;",((n,r)=>{n?t(n):(this.connection.close(),e(r))}))}))}connected(){return this.connectionPubSub.connected}close(){this.connectionPubSub.close()}}},774:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OperationsQueue=void 0,t.OperationsQueue=class{constructor(){this.queue=[],this.isProcessing=!1}enqueue(e){this.queue.push(e),this.isProcessing||this.processNext()}clear(){this.queue=[],this.isProcessing=!1}processNext(){if(0===this.queue.length)return void(this.isProcessing=!1);this.isProcessing=!0;const e=this.queue.shift();null==e||e((()=>{this.processNext()}))}}},121:function(e,t,n){"use strict";var r,s,o,i,a=this&&this.__classPrivateFieldSet||function(e,t,n,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,n):s?s.value=n:t.set(e,n),n},c=this&&this.__classPrivateFieldGet||function(e,t,n,r){if("a"===n&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?r:"a"===n?r.call(e):r?r.value:t.get(e)};Object.defineProperty(t,"__esModule",{value:!0}),t.SQLiteCloudRowset=t.SQLiteCloudRow=void 0;const u=n(80);class l{constructor(e,t,n){r.set(this,void 0),s.set(this,void 0),a(this,r,e,"f"),a(this,s,n,"f");for(let e=0;e<t.length;e++)this[t[e]]=n[e]}getRowset(){return c(this,r,"f")}getData(){return c(this,s,"f")}}t.SQLiteCloudRow=l,r=new WeakMap,s=new WeakMap;class h extends Array{constructor(e,t){super(e.numberOfRows),o.set(this,void 0),i.set(this,void 0),a(this,o,e,"f"),a(this,i,t,"f");const n=this.columnsNames;for(let t=0;t<e.numberOfColumns;t++){n[t]||(n[t]=`column_${t}`);let e=0;for(;n.findIndex(((e,r)=>r!==t&&e===n[t]))>=0;)n[t]=`${n[t]}_${e}`,e++}for(let r=0,s=0;r<e.numberOfRows;r++,s+=e.numberOfColumns)this[r]=new l(this,n,t.slice(s,s+e.numberOfColumns))}get version(){return c(this,o,"f").version}get numberOfRows(){return c(this,o,"f").numberOfRows}get numberOfColumns(){return c(this,o,"f").numberOfColumns}get columnsNames(){return c(this,o,"f").columns.map((e=>e.name))}get metadata(){return c(this,o,"f")}getItem(e,t){if(e<0||e>=this.numberOfRows||t<0||t>=this.numberOfColumns)throw new u.SQLiteCloudError(`This rowset has ${this.numberOfColumns} columns by ${this.numberOfRows} rows, requested column ${t} and row ${e} is invalid.`);return c(this,i,"f")[e*this.numberOfColumns+t]}slice(e,t){e=void 0===e?0:e<0?this.numberOfRows+e:e,e=Math.min(Math.max(e,0),this.numberOfRows),t=void 0===t?this.numberOfRows:t<0?this.numberOfRows+t:t,t=Math.min(Math.max(e,t),this.numberOfRows);const n=Object.assign(Object.assign({},c(this,o,"f")),{numberOfRows:t-e}),r=c(this,i,"f").slice(e*this.numberOfColumns,t*this.numberOfColumns);return console.assert(r&&r.length===n.numberOfRows*n.numberOfColumns,"SQLiteCloudRowset.slice - invalid rowset data"),new h(n,r)}map(e){const t=[];for(let n=0;n<this.numberOfRows;n++){const r=this[n];t.push(e(r,n,this))}return t}filter(e){const t=[];for(let n=0;n<this.numberOfRows;n++)e(this[n],n,this)&&t.push(...c(this,i,"f").slice(n*this.numberOfColumns,(n+1)*this.numberOfColumns));return new h(Object.assign(Object.assign({},c(this,o,"f")),{numberOfRows:t.length/this.numberOfColumns}),t)}}t.SQLiteCloudRowset=h,o=new WeakMap,i=new WeakMap},96:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Statement=void 0;const r=n(193);t.Statement=class{constructor(e,t,...n){const{args:s,callback:o}=(0,r.popCallback)(n);this._database=e,this._sql=t,(null==s?void 0:s.length)>0?this.bind(...s,o):null==o||o.call(this,null)}bind(...e){const{args:t,callback:n}=(0,r.popCallback)(e);try{this._preparedSql=(0,r.prepareSql)(this._sql,...t),n&&n.call(this,null)}catch(e){this._preparedSql=void 0,n&&n.call(this,e)}return this}run(...e){const{args:t,callback:n}=(0,r.popCallback)(e||[]);return(null==t?void 0:t.length)>0?this.bind(...t,(e=>{e?null==n||n.call(this,e):this._database.run(this._preparedSql||"",n)})):this._database.run(this._preparedSql||"",n),this}get(...e){const{args:t,callback:n}=(0,r.popCallback)(e||[]);return(null==t?void 0:t.length)>0?this.bind(...t,(e=>{e?null==n||n.call(this,e):this._database.get(this._preparedSql||"",n)})):this._database.get(this._preparedSql||"",n),this}all(...e){const{args:t,callback:n}=(0,r.popCallback)(e||[]);return(null==t?void 0:t.length)>0?this.bind(...t,(e=>{e?null==n||n.call(this,e):this._database.all(this._preparedSql||"",n)})):this._database.all(this._preparedSql||"",n),this}each(...e){const{args:t,callback:n,complete:s}=(0,r.popCallback)(e);return(null==t?void 0:t.length)>0?this.bind(...t,(e=>{e?null==n||n.call(this,e):this._database.each(this._preparedSql||"",n,s)})):this._database.each(this._preparedSql||"",n,s),this}}},80:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SQLiteCloudArrayType=t.SQLiteCloudError=t.DEFAULT_PORT=t.DEFAULT_TIMEOUT=void 0,t.DEFAULT_TIMEOUT=3e5,t.DEFAULT_PORT=9960;class n extends Error{constructor(e,t){super(e),this.name="SQLiteCloudError",t&&Object.assign(this,t)}}var r;t.SQLiteCloudError=n,(r=t.SQLiteCloudArrayType||(t.SQLiteCloudArrayType={}))[r.ARRAY_TYPE_SQLITE_EXEC=10]="ARRAY_TYPE_SQLITE_EXEC",r[r.ARRAY_TYPE_DB_STATUS=11]="ARRAY_TYPE_DB_STATUS",r[r.ARRAY_TYPE_METADATA=12]="ARRAY_TYPE_METADATA",r[r.ARRAY_TYPE_VM_STEP=20]="ARRAY_TYPE_VM_STEP",r[r.ARRAY_TYPE_VM_COMPILE=21]="ARRAY_TYPE_VM_COMPILE",r[r.ARRAY_TYPE_VM_STEP_ONE=22]="ARRAY_TYPE_VM_STEP_ONE",r[r.ARRAY_TYPE_VM_SQL=23]="ARRAY_TYPE_VM_SQL",r[r.ARRAY_TYPE_VM_STATUS=24]="ARRAY_TYPE_VM_STATUS",r[r.ARRAY_TYPE_VM_LIST=25]="ARRAY_TYPE_VM_LIST",r[r.ARRAY_TYPE_BACKUP_INIT=40]="ARRAY_TYPE_BACKUP_INIT",r[r.ARRAY_TYPE_BACKUP_STEP=41]="ARRAY_TYPE_BACKUP_STEP",r[r.ARRAY_TYPE_BACKUP_END=42]="ARRAY_TYPE_BACKUP_END",r[r.ARRAY_TYPE_SQLITE_STATUS=50]="ARRAY_TYPE_SQLITE_STATUS"},193:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseBooleanToZeroOne=t.parseBoolean=t.parseconnectionstring=t.validateConfiguration=t.popCallback=t.getUpdateResults=t.prepareSql=t.escapeSqlParameter=t.getInitializationCommands=t.anonimizeError=t.anonimizeCommand=t.isNode=t.isBrowser=void 0;const r=n(80),s=n(80);function o(e){return(e=(e=e.replace(/USER \S+/,"USER ******")).replace(/PASSWORD \S+?(?=;)/,"PASSWORD ******")).replace(/HASH \S+?(?=;)/,"HASH ******")}function i(e){if(null==e)return"NULL";if("string"==typeof e)return`'${e=e.replace(/'/g,"''")}'`;if("number"==typeof e||"bigint"==typeof e)return e.toString();if("boolean"==typeof e)return e?"1":"0";if(Buffer.isBuffer(e))return`X'${e.toString("hex")}'`;if("object"==typeof e){let t=JSON.stringify(e);return t=t.replace(/'/g,"''"),`'${t}'`}throw new r.SQLiteCloudError("Unsupported parameter type: "+typeof e)}function a(e){try{const t=e.replace("sqlitecloud:","https:"),n=new URL(t),r={};n.searchParams.forEach(((e,t)=>{r[t.toLowerCase().replaceAll("-","_")]=e}));const s=Object.assign({username:decodeURIComponent(n.username),password:decodeURIComponent(n.password),host:n.hostname,port:n.port?parseInt(n.port):void 0},r);s.apikey&&((s.username||s.password)&&console.warn("SQLiteCloudConnection.parseconnectionstring - apikey and username/password are both specified, using apikey"),delete s.username,delete s.password);const o=n.pathname.replace("/","");return o&&(s.database=o),s}catch(t){throw new r.SQLiteCloudError(`Invalid connection string: ${e}`)}}function c(e){return"string"==typeof e?"true"===e.toLowerCase()||"1"===e:!!e}t.isBrowser="undefined"!=typeof window&&void 0!==window.document,t.isNode="undefined"!=typeof process&&null!=process.versions&&null!=process.versions.node,t.anonimizeCommand=o,t.anonimizeError=function(e){return(null==e?void 0:e.message)&&(e.message=o(e.message)),e},t.getInitializationCommands=function(e){let t="SET CLIENT KEY NONLINEARIZABLE TO 1; ";return e.apikey?t+=`AUTH APIKEY ${e.apikey}; `:t+=`AUTH USER ${e.username||""} ${e.password_hashed?"HASH":"PASSWORD"} ${e.password||""}; `,e.compression&&(t+="SET CLIENT KEY COMPRESSION TO 1; "),e.zerotext&&(t+="SET CLIENT KEY ZEROTEXT TO 1; "),e.noblob&&(t+="SET CLIENT KEY NOBLOB TO 1; "),e.maxdata&&(t+=`SET CLIENT KEY MAXDATA TO ${e.maxdata}; `),e.maxrows&&(t+=`SET CLIENT KEY MAXROWS TO ${e.maxrows}; `),e.maxrowset&&(t+=`SET CLIENT KEY MAXROWSET TO ${e.maxrowset}; `),e.non_linearizable||(t+="SET CLIENT KEY NONLINEARIZABLE TO 0; "),e.database&&(e.create&&!e.memory&&(t+=`CREATE DATABASE ${e.database} IF NOT EXISTS; `),t+=`USE DATABASE ${e.database}; `),t},t.escapeSqlParameter=i,t.prepareSql=function(e,...t){1===(null==t?void 0:t.length)&&Array.isArray(t[0])&&(t=t[0]);let n=1,s=e.replace(/\?(\d+)?/g,((e,s)=>{const o=s?parseInt(s):n;let a;if(n++,!t[0]||"object"!=typeof t[0]||t[0]instanceof Buffer||(a=t[0][o]),!a){if(o>t.length)throw new r.SQLiteCloudError("Not enough parameters");a=t[o-1]}return null!=a?i(a):"NULL"}));if(1===(null==t?void 0:t.length)&&t[0]&&"object"==typeof t[0]){const e=t[0];for(const[t,n]of Object.entries(e)){const e=t.charAt(0);if("$"==e||":"==e||"@"==e){const e=i(n);s=s.replace(new RegExp(`\\${t}`,"g"),e)}}}return s},t.getUpdateResults=function(e){if(e&&Array.isArray(e)&&e.length>0&&e[0]===s.SQLiteCloudArrayType.ARRAY_TYPE_SQLITE_EXEC)return{type:e[0],index:e[1],lastID:e[2],changes:e[3],totalChanges:e[4],finalized:e[5],rowId:e[2]}},t.popCallback=function(e){const t=e;return e&&e.length>0&&"function"==typeof e[e.length-1]?e.length>1&&"function"==typeof e[e.length-2]?{args:t.slice(0,-2),callback:e[e.length-2],complete:e[e.length-1]}:{args:t.slice(0,-1),callback:e[e.length-1]}:{args:t}},t.validateConfiguration=function(e){console.assert(e,"SQLiteCloudConnection.validateConfiguration - missing config"),e.connectionstring&&(e=Object.assign(Object.assign(Object.assign({},e),a(e.connectionstring)),{connectionstring:e.connectionstring})),e.port||(e.port=r.DEFAULT_PORT),e.timeout=e.timeout&&e.timeout>0?e.timeout:r.DEFAULT_TIMEOUT,e.clientid||(e.clientid="SQLiteCloud"),e.verbose=c(e.verbose),e.noblob=c(e.noblob),e.compression=c(e.compression),e.create=c(e.create),e.non_linearizable=c(e.non_linearizable),e.insecure=c(e.insecure);const t=e.username&&e.password||e.apikey;if(!e.host||!t)throw console.error("SQLiteCloudConnection.validateConfiguration - missing arguments",e),new r.SQLiteCloudError("The user, password and host arguments or the ?apikey= must be specified.",{errorCode:"ERR_MISSING_ARGS"});return e.connectionstring||(e.apikey?e.connectionstring=`sqlitecloud://${e.host}:${e.port}/${e.database||""}?apikey=${e.apikey}`:e.connectionstring=`sqlitecloud://${encodeURIComponent(e.username||"")}:${encodeURIComponent(e.password||"")}@${e.host}:${e.port}/${e.database}`),e},t.parseconnectionstring=a,t.parseBoolean=c,t.parseBooleanToZeroOne=function(e){return"string"==typeof e?"true"===e.toLowerCase()||"1"===e?1:0:e?1:0}},833:(e,t,n)=>{t.formatArgs=function(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+e.exports.humanize(this.diff),!this.useColors)return;const n="color: "+this.color;t.splice(1,0,n,"color: inherit");let r=0,s=0;t[0].replace(/%[a-zA-Z%]/g,(e=>{"%%"!==e&&(r++,"%c"===e&&(s=r))})),t.splice(s,0,n)},t.save=function(e){try{e?t.storage.setItem("debug",e):t.storage.removeItem("debug")}catch(e){}},t.load=function(){let e;try{e=t.storage.getItem("debug")}catch(e){}return!e&&"undefined"!=typeof process&&"env"in process&&(e=process.env.DEBUG),e},t.useColors=function(){return!("undefined"==typeof window||!window.process||"renderer"!==window.process.type&&!window.process.__nwjs)||("undefined"==typeof navigator||!navigator.userAgent||!navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))&&("undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/))},t.storage=function(){try{return localStorage}catch(e){}}(),t.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),t.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],t.log=console.debug||console.log||(()=>{}),e.exports=n(736)(t);const{formatters:r}=e.exports;r.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}},736:(e,t,n)=>{e.exports=function(e){function t(e){let n,s,o,i=null;function a(...e){if(!a.enabled)return;const r=a,s=Number(new Date),o=s-(n||s);r.diff=o,r.prev=n,r.curr=s,n=s,e[0]=t.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let i=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,((n,s)=>{if("%%"===n)return"%";i++;const o=t.formatters[s];if("function"==typeof o){const t=e[i];n=o.call(r,t),e.splice(i,1),i--}return n})),t.formatArgs.call(r,e),(r.log||t.log).apply(r,e)}return a.namespace=e,a.useColors=t.useColors(),a.color=t.selectColor(e),a.extend=r,a.destroy=t.destroy,Object.defineProperty(a,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==i?i:(s!==t.namespaces&&(s=t.namespaces,o=t.enabled(e)),o),set:e=>{i=e}}),"function"==typeof t.init&&t.init(a),a}function r(e,n){const r=t(this.namespace+(void 0===n?":":n)+e);return r.log=this.log,r}function s(e){return e.toString().substring(2,e.toString().length-2).replace(/\.\*\?$/,"*")}return t.debug=t,t.default=t,t.coerce=function(e){return e instanceof Error?e.stack||e.message:e},t.disable=function(){const e=[...t.names.map(s),...t.skips.map(s).map((e=>"-"+e))].join(",");return t.enable(""),e},t.enable=function(e){let n;t.save(e),t.namespaces=e,t.names=[],t.skips=[];const r=("string"==typeof e?e:"").split(/[\s,]+/),s=r.length;for(n=0;n<s;n++)r[n]&&("-"===(e=r[n].replace(/\*/g,".*?"))[0]?t.skips.push(new RegExp("^"+e.slice(1)+"$")):t.names.push(new RegExp("^"+e+"$")))},t.enabled=function(e){if("*"===e[e.length-1])return!0;let n,r;for(n=0,r=t.skips.length;n<r;n++)if(t.skips[n].test(e))return!1;for(n=0,r=t.names.length;n<r;n++)if(t.names[n].test(e))return!0;return!1},t.humanize=n(585),t.destroy=function(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")},Object.keys(e).forEach((n=>{t[n]=e[n]})),t.names=[],t.skips=[],t.formatters={},t.selectColor=function(e){let n=0;for(let t=0;t<e.length;t++)n=(n<<5)-n+e.charCodeAt(t),n|=0;return t.colors[Math.abs(n)%t.colors.length]},t.enable(t.load()),t}},228:e=>{"use strict";var t=Object.prototype.hasOwnProperty,n="~";function r(){}function s(e,t,n){this.fn=e,this.context=t,this.once=n||!1}function o(e,t,r,o,i){if("function"!=typeof r)throw new TypeError("The listener must be a function");var a=new s(r,o||e,i),c=n?n+t:t;return e._events[c]?e._events[c].fn?e._events[c]=[e._events[c],a]:e._events[c].push(a):(e._events[c]=a,e._eventsCount++),e}function i(e,t){0==--e._eventsCount?e._events=new r:delete e._events[t]}function a(){this._events=new r,this._eventsCount=0}Object.create&&(r.prototype=Object.create(null),(new r).__proto__||(n=!1)),a.prototype.eventNames=function(){var e,r,s=[];if(0===this._eventsCount)return s;for(r in e=this._events)t.call(e,r)&&s.push(n?r.slice(1):r);return Object.getOwnPropertySymbols?s.concat(Object.getOwnPropertySymbols(e)):s},a.prototype.listeners=function(e){var t=n?n+e:e,r=this._events[t];if(!r)return[];if(r.fn)return[r.fn];for(var s=0,o=r.length,i=new Array(o);s<o;s++)i[s]=r[s].fn;return i},a.prototype.listenerCount=function(e){var t=n?n+e:e,r=this._events[t];return r?r.fn?1:r.length:0},a.prototype.emit=function(e,t,r,s,o,i){var a=n?n+e:e;if(!this._events[a])return!1;var c,u,l=this._events[a],h=arguments.length;if(l.fn){switch(l.once&&this.removeListener(e,l.fn,void 0,!0),h){case 1:return l.fn.call(l.context),!0;case 2:return l.fn.call(l.context,t),!0;case 3:return l.fn.call(l.context,t,r),!0;case 4:return l.fn.call(l.context,t,r,s),!0;case 5:return l.fn.call(l.context,t,r,s,o),!0;case 6:return l.fn.call(l.context,t,r,s,o,i),!0}for(u=1,c=new Array(h-1);u<h;u++)c[u-1]=arguments[u];l.fn.apply(l.context,c)}else{var d,f=l.length;for(u=0;u<f;u++)switch(l[u].once&&this.removeListener(e,l[u].fn,void 0,!0),h){case 1:l[u].fn.call(l[u].context);break;case 2:l[u].fn.call(l[u].context,t);break;case 3:l[u].fn.call(l[u].context,t,r);break;case 4:l[u].fn.call(l[u].context,t,r,s);break;default:if(!c)for(d=1,c=new Array(h-1);d<h;d++)c[d-1]=arguments[d];l[u].fn.apply(l[u].context,c)}}return!0},a.prototype.on=function(e,t,n){return o(this,e,t,n,!1)},a.prototype.once=function(e,t,n){return o(this,e,t,n,!0)},a.prototype.removeListener=function(e,t,r,s){var o=n?n+e:e;if(!this._events[o])return this;if(!t)return i(this,o),this;var a=this._events[o];if(a.fn)a.fn!==t||s&&!a.once||r&&a.context!==r||i(this,o);else{for(var c=0,u=[],l=a.length;c<l;c++)(a[c].fn!==t||s&&!a[c].once||r&&a[c].context!==r)&&u.push(a[c]);u.length?this._events[o]=1===u.length?u[0]:u:i(this,o)}return this},a.prototype.removeAllListeners=function(e){var t;return e?(t=n?n+e:e,this._events[t]&&i(this,t)):(this._events=new r,this._eventsCount=0),this},a.prototype.off=a.prototype.removeListener,a.prototype.addListener=a.prototype.on,a.prefixed=n,a.EventEmitter=a,e.exports=a},404:(e,t,n)=>{var r=n(255),s=n(144),o=65536,i=h(5<<20),a=function(){try{return new Uint32Array(o)}catch(n){for(var e=new Array(o),t=0;t<o;t++)e[t]=0;return e}}(),c=407708164,u=2147483648,l={4:65536,5:262144,6:1048576,7:4194304};function h(e){try{return new Uint8Array(e)}catch(r){for(var t=new Array(e),n=0;n<e;n++)t[n]=0;return t}}function d(e,t,n){if(void 0!==typeof e.buffer){if(Uint8Array.prototype.slice)return e.slice(t,n);var r=e.length;t=(t|=0)<0?Math.max(r+t,0):Math.min(t,r),n=(n=void 0===n?r:0|n)<0?Math.max(r+n,0):Math.min(n,r);for(var s=new Uint8Array(n-t),o=t,i=0;o<n;)s[i++]=e[o++];return s}return e.slice(t,n)}t.compressBound=function(e){return e+e/255+16|0},t.decompressBound=function(e){var t=0;if(s.readU32(e,t)!==c)throw new Error("invalid magic number");t+=4;var n=e[t++];if(64!=(192&n))throw new Error("incompatible descriptor version "+(192&n));var r=0!=(16&n),o=0!=(8&n),i=e[t++]>>4&7;if(void 0===l[i])throw new Error("invalid block size "+i);var a=l[i];if(o)return s.readU64(e,t);t++;for(var h=0;;){var d=s.readU32(e,t);if(t+=4,h+=d&u?d&=2147483647:a,0===d)return h;r&&(t+=4),t+=d}},t.makeBuffer=h,t.decompressBlock=function(e,t,n,r,s){var o,i,a,c,u;for(a=n+r;n<a;){var l=e[n++],h=l>>4;if(h>0){if(15===h)for(;h+=e[n],255===e[n++];);for(c=n+h;n<c;)t[s++]=e[n++]}if(n>=a)break;if(o=15&l,i=e[n++]|e[n++]<<8,15===o)for(;o+=e[n],255===e[n++];);for(c=(u=s-i)+(o+=4);u<c;)t[s++]=0|t[u++]}return s},t.compressBlock=function(e,t,n,r,o){var i,a,c,u,l,h,d,f;if(h=0,d=r+n,a=n,r>=13)for(var p=67;n+4<d-5;){var m=s.readU32(e,n),g=s.hashU32(m)>>>0;if(i=o[g=(g>>16^g)>>>0&65535]-1,o[g]=n+1,i<0||n-i>>>16>0||s.readU32(e,i)!==m)n+=p++>>6;else{for(p=67,l=n-a,u=n-i,i+=4,c=n+=4;n<d-5&&e[n]===e[i];)n++,i++;var y=(c=n-c)<15?c:15;if(l>=15){for(t[h++]=240+y,f=l-15;f>=255;f-=255)t[h++]=255;t[h++]=f}else t[h++]=(l<<4)+y;for(var b=0;b<l;b++)t[h++]=e[a+b];if(t[h++]=u,t[h++]=u>>8,c>=15){for(f=c-15;f>=255;f-=255)t[h++]=255;t[h++]=f}a=n}}if(0===a)return 0;if((l=d-a)>=15){for(t[h++]=240,f=l-15;f>=255;f-=255)t[h++]=255;t[h++]=f}else t[h++]=l<<4;for(n=a;n<d;)t[h++]=e[n++];return h},t.decompressFrame=function(e,n){var r,o,i,a,h=0,d=0;if(s.readU32(e,h)!==c)throw new Error("invalid magic number");if(h+=4,64!=(192&(a=e[h++])))throw new Error("incompatible descriptor version");r=0!=(16&a),o=0!=(4&a),i=0!=(8&a);var f=e[h++]>>4&7;if(void 0===l[f])throw new Error("invalid block size");for(i&&(h+=8),h++;;){var p;if(p=s.readU32(e,h),h+=4,0===p)break;if(r&&(h+=4),0!=(p&u)){p&=2147483647;for(var m=0;m<p;m++)n[d++]=e[h++]}else d=t.decompressBlock(e,n,h,p,d),h+=p}return o&&(h+=4),d},t.compressFrame=function(e,n){var u=0;s.writeU32(n,u,c),u+=4,n[u++]=64,n[u++]=112,n[u]=r.hash(0,n,4,u-4)>>8,u++;var h=l[7],d=e.length,f=0;for(function(e){for(var t=0;t<o;t++)a[t]=0}();d>0;){var p,m=d>h?h:d;if((p=t.compressBlock(e,i,f,m,a))>m||0===p){s.writeU32(n,u,2147483648|m),u+=4;for(var g=f+m;f<g;)n[u++]=e[f++];d-=m}else{s.writeU32(n,u,p),u+=4;for(var y=0;y<p;)n[u++]=i[y++];f+=m,d-=m}}return s.writeU32(n,u,0),u+4},t.decompress=function(e,n){var r,s;return void 0===n&&(n=t.decompressBound(e)),r=t.makeBuffer(n),(s=t.decompressFrame(e,r))!==n&&(r=d(r,0,s)),r},t.compress=function(e,n){var r,s;return void 0===n&&(n=t.compressBound(e.length)),r=t.makeBuffer(n),(s=t.compressFrame(e,r))!==n&&(r=d(r,0,s)),r}},144:(e,t)=>{t.hashU32=function(e){return-1252372727^(e=(e=(e=374761393+(e=-949894596^(e=2127912214+(e|=0)+(e<<12)|0)^e>>>19)+(e<<5)|0)-744332180^e<<9)-42973499+(e<<3)|0)^e>>>16|0},t.readU64=function(e,t){var n=0;return n|=e[t++]<<0,n|=e[t++]<<8,n|=e[t++]<<16,n|=e[t++]<<24,n|=e[t++]<<32,n|=e[t++]<<40,(n|=e[t++]<<48)|e[t++]<<56},t.readU32=function(e,t){var n=0;return n|=e[t++]<<0,n|=e[t++]<<8,(n|=e[t++]<<16)|e[t++]<<24},t.writeU32=function(e,t,n){e[t++]=n>>0&255,e[t++]=n>>8&255,e[t++]=n>>16&255,e[t++]=n>>24&255},t.imul=function(e,t){var n=65535&e,r=65535&t;return n*r+((e>>>16)*r+n*(t>>>16)<<16)|0}},255:(e,t,n)=>{var r=n(144),s=2654435761,o=2246822519,i=3266489917,a=374761393;function c(e,t){return(e|=0)>>>(32-(t|=0)|0)|e<<t|0}function u(e,t,n){return e|=0,t|=0,n|=0,0|r.imul(e>>>(32-t|0)|e<<t,n)}function l(e,t){return(e|=0)>>>(t|=0)^e|0}function h(e,t,n,s,o){return u(r.imul(t,n)+e,s,o)}function d(e,t,n){return u(e+r.imul(t[n],a),11,s)}function f(e,t,n){return h(e,r.readU32(t,n),i,17,668265263)}function p(e,t,n){return[h(e[0],r.readU32(t,n+0),o,13,s),h(e[1],r.readU32(t,n+4),o,13,s),h(e[2],r.readU32(t,n+8),o,13,s),h(e[3],r.readU32(t,n+12),o,13,s)]}t.hash=function(e,t,n,u){var h,m;if(m=u,u>=16){for(h=[e+s+o,e+o,e,e-s];u>=16;)h=p(h,t,n),n+=16,u-=16;h=c(h[0],1)+c(h[1],7)+c(h[2],12)+c(h[3],18)+m}else h=e+a+u>>>0;for(;u>=4;)h=f(h,t,n),n+=4,u-=4;for(;u>0;)h=d(h,t,n),n++,u--;return(h=l(r.imul(l(r.imul(l(h,15),o),13),i),16))>>>0}},585:e=>{var t=1e3,n=60*t,r=60*n,s=24*r;function o(e,t,n,r){var s=t>=1.5*n;return Math.round(e/n)+" "+r+(s?"s":"")}e.exports=function(e,i){i=i||{};var a,c,u=typeof e;if("string"===u&&e.length>0)return function(e){if(!((e=String(e)).length>100)){var o=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(o){var i=parseFloat(o[1]);switch((o[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return 315576e5*i;case"weeks":case"week":case"w":return 6048e5*i;case"days":case"day":case"d":return i*s;case"hours":case"hour":case"hrs":case"hr":case"h":return i*r;case"minutes":case"minute":case"mins":case"min":case"m":return i*n;case"seconds":case"second":case"secs":case"sec":case"s":return i*t;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return i;default:return}}}}(e);if("number"===u&&isFinite(e))return i.long?(a=e,(c=Math.abs(a))>=s?o(a,c,s,"day"):c>=r?o(a,c,r,"hour"):c>=n?o(a,c,n,"minute"):c>=t?o(a,c,t,"second"):a+" ms"):function(e){var o=Math.abs(e);return o>=s?Math.round(e/s)+"d":o>=r?Math.round(e/r)+"h":o>=n?Math.round(e/n)+"m":o>=t?Math.round(e/t)+"s":e+"ms"}(e);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))}},498:()=>{},110:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.hasCORS=void 0;let n=!1;try{n="undefined"!=typeof XMLHttpRequest&&"withCredentials"in new XMLHttpRequest}catch(e){}t.hasCORS=n},661:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.decode=t.encode=void 0,t.encode=function(e){let t="";for(let n in e)e.hasOwnProperty(n)&&(t.length&&(t+="&"),t+=encodeURIComponent(n)+"="+encodeURIComponent(e[n]));return t},t.decode=function(e){let t={},n=e.split("&");for(let e=0,r=n.length;e<r;e++){let r=n[e].split("=");t[decodeURIComponent(r[0])]=decodeURIComponent(r[1])}return t}},15:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parse=void 0;const n=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,r=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];t.parse=function(e){if(e.length>2e3)throw"URI too long";const t=e,s=e.indexOf("["),o=e.indexOf("]");-1!=s&&-1!=o&&(e=e.substring(0,s)+e.substring(s,o).replace(/:/g,";")+e.substring(o,e.length));let i=n.exec(e||""),a={},c=14;for(;c--;)a[r[c]]=i[c]||"";return-1!=s&&-1!=o&&(a.source=t,a.host=a.host.substring(1,a.host.length-1).replace(/;/g,":"),a.authority=a.authority.replace("[","").replace("]","").replace(/;/g,":"),a.ipv6uri=!0),a.pathNames=function(e,t){const n=t.replace(/\/{2,9}/g,"/").split("/");return"/"!=t.slice(0,1)&&0!==t.length||n.splice(0,1),"/"==t.slice(-1)&&n.splice(n.length-1,1),n}(0,a.path),a.queryKey=function(e,t){const n={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,(function(e,t,r){t&&(n[t]=r)})),n}(0,a.query),a}},732:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.yeast=t.decode=t.encode=void 0;const n="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_".split(""),r={};let s,o=0,i=0;function a(e){let t="";do{t=n[e%64]+t,e=Math.floor(e/64)}while(e>0);return t}for(t.encode=a,t.decode=function(e){let t=0;for(i=0;i<e.length;i++)t=64*t+r[e.charAt(i)];return t},t.yeast=function(){const e=a(+new Date);return e!==s?(o=0,s=e):e+"."+a(o++)};i<64;i++)r[n[i]]=i},235:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.globalThisShim=void 0,t.globalThisShim="undefined"!=typeof self?self:"undefined"!=typeof window?window:Function("return this")()},956:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.nextTick=t.parse=t.installTimerFunctions=t.transports=t.TransportError=t.Transport=t.protocol=t.Socket=void 0;const r=n(223);Object.defineProperty(t,"Socket",{enumerable:!0,get:function(){return r.Socket}}),t.protocol=r.Socket.protocol;var s=n(689);Object.defineProperty(t,"Transport",{enumerable:!0,get:function(){return s.Transport}}),Object.defineProperty(t,"TransportError",{enumerable:!0,get:function(){return s.TransportError}});var o=n(419);Object.defineProperty(t,"transports",{enumerable:!0,get:function(){return o.transports}});var i=n(374);Object.defineProperty(t,"installTimerFunctions",{enumerable:!0,get:function(){return i.installTimerFunctions}});var a=n(15);Object.defineProperty(t,"parse",{enumerable:!0,get:function(){return a.parse}});var c=n(87);Object.defineProperty(t,"nextTick",{enumerable:!0,get:function(){return c.nextTick}})},223:function(e,t,n){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.Socket=void 0;const s=n(419),o=n(374),i=n(661),a=n(15),c=r(n(833)),u=n(285),l=n(376),h=n(87),d=(0,c.default)("engine.io-client:socket");class f extends u.Emitter{constructor(e,t={}){super(),this.binaryType=h.defaultBinaryType,this.writeBuffer=[],e&&"object"==typeof e&&(t=e,e=null),e?(e=(0,a.parse)(e),t.hostname=e.host,t.secure="https"===e.protocol||"wss"===e.protocol,t.port=e.port,e.query&&(t.query=e.query)):t.host&&(t.hostname=(0,a.parse)(t.host).host),(0,o.installTimerFunctions)(this,t),this.secure=null!=t.secure?t.secure:"undefined"!=typeof location&&"https:"===location.protocol,t.hostname&&!t.port&&(t.port=this.secure?"443":"80"),this.hostname=t.hostname||("undefined"!=typeof location?location.hostname:"localhost"),this.port=t.port||("undefined"!=typeof location&&location.port?location.port:this.secure?"443":"80"),this.transports=t.transports||["polling","websocket","webtransport"],this.writeBuffer=[],this.prevBufferLen=0,this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},t),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),"string"==typeof this.opts.query&&(this.opts.query=(0,i.decode)(this.opts.query)),this.id=null,this.upgrades=null,this.pingInterval=null,this.pingTimeout=null,this.pingTimeoutTimer=null,"function"==typeof addEventListener&&(this.opts.closeOnBeforeunload&&(this.beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this.beforeunloadEventListener,!1)),"localhost"!==this.hostname&&(this.offlineEventListener=()=>{this.onClose("transport close",{description:"network connection lost"})},addEventListener("offline",this.offlineEventListener,!1))),this.open()}createTransport(e){d('creating transport "%s"',e);const t=Object.assign({},this.opts.query);t.EIO=l.protocol,t.transport=e,this.id&&(t.sid=this.id);const n=Object.assign({},this.opts,{query:t,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[e]);return d("options: %j",n),new s.transports[e](n)}open(){let e;if(this.opts.rememberUpgrade&&f.priorWebsocketSuccess&&-1!==this.transports.indexOf("websocket"))e="websocket";else{if(0===this.transports.length)return void this.setTimeoutFn((()=>{this.emitReserved("error","No transports available")}),0);e=this.transports[0]}this.readyState="opening";try{e=this.createTransport(e)}catch(e){return d("error while creating transport: %s",e),this.transports.shift(),void this.open()}e.open(),this.setTransport(e)}setTransport(e){d("setting transport %s",e.name),this.transport&&(d("clearing existing transport %s",this.transport.name),this.transport.removeAllListeners()),this.transport=e,e.on("drain",this.onDrain.bind(this)).on("packet",this.onPacket.bind(this)).on("error",this.onError.bind(this)).on("close",(e=>this.onClose("transport close",e)))}probe(e){d('probing transport "%s"',e);let t=this.createTransport(e),n=!1;f.priorWebsocketSuccess=!1;const r=()=>{n||(d('probe transport "%s" opened',e),t.send([{type:"ping",data:"probe"}]),t.once("packet",(r=>{if(!n)if("pong"===r.type&&"probe"===r.data){if(d('probe transport "%s" pong',e),this.upgrading=!0,this.emitReserved("upgrading",t),!t)return;f.priorWebsocketSuccess="websocket"===t.name,d('pausing current transport "%s"',this.transport.name),this.transport.pause((()=>{n||"closed"!==this.readyState&&(d("changing transport and sending upgrade packet"),u(),this.setTransport(t),t.send([{type:"upgrade"}]),this.emitReserved("upgrade",t),t=null,this.upgrading=!1,this.flush())}))}else{d('probe transport "%s" failed',e);const n=new Error("probe error");n.transport=t.name,this.emitReserved("upgradeError",n)}})))};function s(){n||(n=!0,u(),t.close(),t=null)}const o=n=>{const r=new Error("probe error: "+n);r.transport=t.name,s(),d('probe transport "%s" failed because of error: %s',e,n),this.emitReserved("upgradeError",r)};function i(){o("transport closed")}function a(){o("socket closed")}function c(e){t&&e.name!==t.name&&(d('"%s" works - aborting "%s"',e.name,t.name),s())}const u=()=>{t.removeListener("open",r),t.removeListener("error",o),t.removeListener("close",i),this.off("close",a),this.off("upgrading",c)};t.once("open",r),t.once("error",o),t.once("close",i),this.once("close",a),this.once("upgrading",c),-1!==this.upgrades.indexOf("webtransport")&&"webtransport"!==e?this.setTimeoutFn((()=>{n||t.open()}),200):t.open()}onOpen(){if(d("socket open"),this.readyState="open",f.priorWebsocketSuccess="websocket"===this.transport.name,this.emitReserved("open"),this.flush(),"open"===this.readyState&&this.opts.upgrade){d("starting upgrade probes");let e=0;const t=this.upgrades.length;for(;e<t;e++)this.probe(this.upgrades[e])}}onPacket(e){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState)switch(d('socket receive: type "%s", data "%s"',e.type,e.data),this.emitReserved("packet",e),this.emitReserved("heartbeat"),this.resetPingTimeout(),e.type){case"open":this.onHandshake(JSON.parse(e.data));break;case"ping":this.sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong");break;case"error":const t=new Error("server error");t.code=e.data,this.onError(t);break;case"message":this.emitReserved("data",e.data),this.emitReserved("message",e.data)}else d('packet received with socket readyState "%s"',this.readyState)}onHandshake(e){this.emitReserved("handshake",e),this.id=e.sid,this.transport.query.sid=e.sid,this.upgrades=this.filterUpgrades(e.upgrades),this.pingInterval=e.pingInterval,this.pingTimeout=e.pingTimeout,this.maxPayload=e.maxPayload,this.onOpen(),"closed"!==this.readyState&&this.resetPingTimeout()}resetPingTimeout(){this.clearTimeoutFn(this.pingTimeoutTimer),this.pingTimeoutTimer=this.setTimeoutFn((()=>{this.onClose("ping timeout")}),this.pingInterval+this.pingTimeout),this.opts.autoUnref&&this.pingTimeoutTimer.unref()}onDrain(){this.writeBuffer.splice(0,this.prevBufferLen),this.prevBufferLen=0,0===this.writeBuffer.length?this.emitReserved("drain"):this.flush()}flush(){if("closed"!==this.readyState&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const e=this.getWritablePackets();d("flushing %d packets in socket",e.length),this.transport.send(e),this.prevBufferLen=e.length,this.emitReserved("flush")}}getWritablePackets(){if(!(this.maxPayload&&"polling"===this.transport.name&&this.writeBuffer.length>1))return this.writeBuffer;let e=1;for(let t=0;t<this.writeBuffer.length;t++){const n=this.writeBuffer[t].data;if(n&&(e+=(0,o.byteLength)(n)),t>0&&e>this.maxPayload)return d("only send %d out of %d packets",t,this.writeBuffer.length),this.writeBuffer.slice(0,t);e+=2}return d("payload size is %d (max: %d)",e,this.maxPayload),this.writeBuffer}write(e,t,n){return this.sendPacket("message",e,t,n),this}send(e,t,n){return this.sendPacket("message",e,t,n),this}sendPacket(e,t,n,r){if("function"==typeof t&&(r=t,t=void 0),"function"==typeof n&&(r=n,n=null),"closing"===this.readyState||"closed"===this.readyState)return;(n=n||{}).compress=!1!==n.compress;const s={type:e,data:t,options:n};this.emitReserved("packetCreate",s),this.writeBuffer.push(s),r&&this.once("flush",r),this.flush()}close(){const e=()=>{this.onClose("forced close"),d("socket closing - telling transport to close"),this.transport.close()},t=()=>{this.off("upgrade",t),this.off("upgradeError",t),e()},n=()=>{this.once("upgrade",t),this.once("upgradeError",t)};return"opening"!==this.readyState&&"open"!==this.readyState||(this.readyState="closing",this.writeBuffer.length?this.once("drain",(()=>{this.upgrading?n():e()})):this.upgrading?n():e()),this}onError(e){d("socket error %j",e),f.priorWebsocketSuccess=!1,this.emitReserved("error",e),this.onClose("transport error",e)}onClose(e,t){"opening"!==this.readyState&&"open"!==this.readyState&&"closing"!==this.readyState||(d('socket close with reason: "%s"',e),this.clearTimeoutFn(this.pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),"function"==typeof removeEventListener&&(removeEventListener("beforeunload",this.beforeunloadEventListener,!1),removeEventListener("offline",this.offlineEventListener,!1)),this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this.prevBufferLen=0)}filterUpgrades(e){const t=[];let n=0;const r=e.length;for(;n<r;n++)~this.transports.indexOf(e[n])&&t.push(e[n]);return t}}t.Socket=f,f.protocol=l.protocol},689:function(e,t,n){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.Transport=t.TransportError=void 0;const s=n(376),o=n(285),i=n(374),a=r(n(833)),c=n(661),u=(0,a.default)("engine.io-client:transport");class l extends Error{constructor(e,t,n){super(e),this.description=t,this.context=n,this.type="TransportError"}}t.TransportError=l;class h extends o.Emitter{constructor(e){super(),this.writable=!1,(0,i.installTimerFunctions)(this,e),this.opts=e,this.query=e.query,this.socket=e.socket}onError(e,t,n){return super.emitReserved("error",new l(e,t,n)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return"opening"!==this.readyState&&"open"!==this.readyState||(this.doClose(),this.onClose()),this}send(e){"open"===this.readyState?this.write(e):u("transport is not open, discarding packets")}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(e){const t=(0,s.decodePacket)(e,this.socket.binaryType);this.onPacket(t)}onPacket(e){super.emitReserved("packet",e)}onClose(e){this.readyState="closed",super.emitReserved("close",e)}pause(e){}createUri(e,t={}){return e+"://"+this._hostname()+this._port()+this.opts.path+this._query(t)}_hostname(){const e=this.opts.hostname;return-1===e.indexOf(":")?e:"["+e+"]"}_port(){return this.opts.port&&(this.opts.secure&&Number(443!==this.opts.port)||!this.opts.secure&&80!==Number(this.opts.port))?":"+this.opts.port:""}_query(e){const t=(0,c.encode)(e);return t.length?"?"+t:""}}t.Transport=h},419:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.transports=void 0;const r=n(528),s=n(716),o=n(480);t.transports={websocket:s.WS,webtransport:o.WT,polling:r.Polling}},528:function(e,t,n){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.Request=t.Polling=void 0;const s=n(689),o=r(n(833)),i=n(732),a=n(376),c=n(519),u=n(285),l=n(374),h=n(235),d=(0,o.default)("engine.io-client:polling");function f(){}const p=null!=new c.XHR({xdomain:!1}).responseType;class m extends s.Transport{constructor(e){if(super(e),this.polling=!1,"undefined"!=typeof location){const t="https:"===location.protocol;let n=location.port;n||(n=t?"443":"80"),this.xd="undefined"!=typeof location&&e.hostname!==location.hostname||n!==e.port}const t=e&&e.forceBase64;this.supportsBinary=p&&!t,this.opts.withCredentials&&(this.cookieJar=(0,c.createCookieJar)())}get name(){return"polling"}doOpen(){this.poll()}pause(e){this.readyState="pausing";const t=()=>{d("paused"),this.readyState="paused",e()};if(this.polling||!this.writable){let e=0;this.polling&&(d("we are currently polling - waiting to pause"),e++,this.once("pollComplete",(function(){d("pre-pause polling complete"),--e||t()}))),this.writable||(d("we are currently writing - waiting to pause"),e++,this.once("drain",(function(){d("pre-pause writing complete"),--e||t()})))}else t()}poll(){d("polling"),this.polling=!0,this.doPoll(),this.emitReserved("poll")}onData(e){d("polling got data %s",e),(0,a.decodePayload)(e,this.socket.binaryType).forEach((e=>{if("opening"===this.readyState&&"open"===e.type&&this.onOpen(),"close"===e.type)return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(e)})),"closed"!==this.readyState&&(this.polling=!1,this.emitReserved("pollComplete"),"open"===this.readyState?this.poll():d('ignoring poll - transport state "%s"',this.readyState))}doClose(){const e=()=>{d("writing close packet"),this.write([{type:"close"}])};"open"===this.readyState?(d("transport open - closing"),e()):(d("transport not open - deferring close"),this.once("open",e))}write(e){this.writable=!1,(0,a.encodePayload)(e,(e=>{this.doWrite(e,(()=>{this.writable=!0,this.emitReserved("drain")}))}))}uri(){const e=this.opts.secure?"https":"http",t=this.query||{};return!1!==this.opts.timestampRequests&&(t[this.opts.timestampParam]=(0,i.yeast)()),this.supportsBinary||t.sid||(t.b64=1),this.createUri(e,t)}request(e={}){return Object.assign(e,{xd:this.xd,cookieJar:this.cookieJar},this.opts),new g(this.uri(),e)}doWrite(e,t){const n=this.request({method:"POST",data:e});n.on("success",t),n.on("error",((e,t)=>{this.onError("xhr post error",e,t)}))}doPoll(){d("xhr poll");const e=this.request();e.on("data",this.onData.bind(this)),e.on("error",((e,t)=>{this.onError("xhr poll error",e,t)})),this.pollXhr=e}}t.Polling=m;class g extends u.Emitter{constructor(e,t){super(),(0,l.installTimerFunctions)(this,t),this.opts=t,this.method=t.method||"GET",this.uri=e,this.data=void 0!==t.data?t.data:null,this.create()}create(){var e;const t=(0,l.pick)(this.opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");t.xdomain=!!this.opts.xd;const n=this.xhr=new c.XHR(t);try{d("xhr open %s: %s",this.method,this.uri),n.open(this.method,this.uri,!0);try{if(this.opts.extraHeaders){n.setDisableHeaderCheck&&n.setDisableHeaderCheck(!0);for(let e in this.opts.extraHeaders)this.opts.extraHeaders.hasOwnProperty(e)&&n.setRequestHeader(e,this.opts.extraHeaders[e])}}catch(e){}if("POST"===this.method)try{n.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch(e){}try{n.setRequestHeader("Accept","*/*")}catch(e){}null===(e=this.opts.cookieJar)||void 0===e||e.addCookies(n),"withCredentials"in n&&(n.withCredentials=this.opts.withCredentials),this.opts.requestTimeout&&(n.timeout=this.opts.requestTimeout),n.onreadystatechange=()=>{var e;3===n.readyState&&(null===(e=this.opts.cookieJar)||void 0===e||e.parseCookies(n)),4===n.readyState&&(200===n.status||1223===n.status?this.onLoad():this.setTimeoutFn((()=>{this.onError("number"==typeof n.status?n.status:0)}),0))},d("xhr data %s",this.data),n.send(this.data)}catch(e){return void this.setTimeoutFn((()=>{this.onError(e)}),0)}"undefined"!=typeof document&&(this.index=g.requestsCount++,g.requests[this.index]=this)}onError(e){this.emitReserved("error",e,this.xhr),this.cleanup(!0)}cleanup(e){if(void 0!==this.xhr&&null!==this.xhr){if(this.xhr.onreadystatechange=f,e)try{this.xhr.abort()}catch(e){}"undefined"!=typeof document&&delete g.requests[this.index],this.xhr=null}}onLoad(){const e=this.xhr.responseText;null!==e&&(this.emitReserved("data",e),this.emitReserved("success"),this.cleanup())}abort(){this.cleanup()}}if(t.Request=g,g.requestsCount=0,g.requests={},"undefined"!=typeof document)if("function"==typeof attachEvent)attachEvent("onunload",y);else if("function"==typeof addEventListener){const e="onpagehide"in h.globalThisShim?"pagehide":"unload";addEventListener(e,y,!1)}function y(){for(let e in g.requests)g.requests.hasOwnProperty(e)&&g.requests[e].abort()}},87:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.defaultBinaryType=t.usingBrowserWebSocket=t.WebSocket=t.nextTick=void 0;const r=n(235);t.nextTick="function"==typeof Promise&&"function"==typeof Promise.resolve?e=>Promise.resolve().then(e):(e,t)=>t(e,0),t.WebSocket=r.globalThisShim.WebSocket||r.globalThisShim.MozWebSocket,t.usingBrowserWebSocket=!0,t.defaultBinaryType="arraybuffer"},716:function(e,t,n){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.WS=void 0;const s=n(689),o=n(732),i=n(374),a=n(87),c=r(n(833)),u=n(376),l=(0,c.default)("engine.io-client:websocket"),h="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase();class d extends s.Transport{constructor(e){super(e),this.supportsBinary=!e.forceBase64}get name(){return"websocket"}doOpen(){if(!this.check())return;const e=this.uri(),t=this.opts.protocols,n=h?{}:(0,i.pick)(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(n.headers=this.opts.extraHeaders);try{this.ws=a.usingBrowserWebSocket&&!h?t?new a.WebSocket(e,t):new a.WebSocket(e):new a.WebSocket(e,t,n)}catch(e){return this.emitReserved("error",e)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=e=>this.onClose({description:"websocket connection closed",context:e}),this.ws.onmessage=e=>this.onData(e.data),this.ws.onerror=e=>this.onError("websocket error",e)}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const n=e[t],r=t===e.length-1;(0,u.encodePacket)(n,this.supportsBinary,(e=>{const t={};!a.usingBrowserWebSocket&&(n.options&&(t.compress=n.options.compress),this.opts.perMessageDeflate)&&("string"==typeof e?Buffer.byteLength(e):e.length)<this.opts.perMessageDeflate.threshold&&(t.compress=!1);try{a.usingBrowserWebSocket?this.ws.send(e):this.ws.send(e,t)}catch(e){l("websocket closed before onclose event")}r&&(0,a.nextTick)((()=>{this.writable=!0,this.emitReserved("drain")}),this.setTimeoutFn)}))}}doClose(){void 0!==this.ws&&(this.ws.close(),this.ws=null)}uri(){const e=this.opts.secure?"wss":"ws",t=this.query||{};return this.opts.timestampRequests&&(t[this.opts.timestampParam]=(0,o.yeast)()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}check(){return!!a.WebSocket}}t.WS=d},480:function(e,t,n){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.WT=void 0;const s=n(689),o=n(87),i=n(376),a=(0,r(n(833)).default)("engine.io-client:webtransport");class c extends s.Transport{get name(){return"webtransport"}doOpen(){"function"==typeof WebTransport&&(this.transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name]),this.transport.closed.then((()=>{a("transport closed gracefully"),this.onClose()})).catch((e=>{a("transport closed due to %s",e),this.onError("webtransport error",e)})),this.transport.ready.then((()=>{this.transport.createBidirectionalStream().then((e=>{const t=(0,i.createPacketDecoderStream)(Number.MAX_SAFE_INTEGER,this.socket.binaryType),n=e.readable.pipeThrough(t).getReader(),r=(0,i.createPacketEncoderStream)();r.readable.pipeTo(e.writable),this.writer=r.writable.getWriter();const s=()=>{n.read().then((({done:e,value:t})=>{e?a("session is closed"):(a("received chunk: %o",t),this.onPacket(t),s())})).catch((e=>{a("an error occurred while reading: %s",e)}))};s();const o={type:"open"};this.query.sid&&(o.data=`{"sid":"${this.query.sid}"}`),this.writer.write(o).then((()=>this.onOpen()))}))})))}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const n=e[t],r=t===e.length-1;this.writer.write(n).then((()=>{r&&(0,o.nextTick)((()=>{this.writable=!0,this.emitReserved("drain")}),this.setTimeoutFn)}))}}doClose(){var e;null===(e=this.transport)||void 0===e||e.close()}}t.WT=c},519:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.createCookieJar=t.XHR=void 0;const r=n(110),s=n(235);t.XHR=function(e){const t=e.xdomain;try{if("undefined"!=typeof XMLHttpRequest&&(!t||r.hasCORS))return new XMLHttpRequest}catch(e){}if(!t)try{return new(s.globalThisShim[["Active"].concat("Object").join("X")])("Microsoft.XMLHTTP")}catch(e){}},t.createCookieJar=function(){}},374:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.byteLength=t.installTimerFunctions=t.pick=void 0;const r=n(235);t.pick=function(e,...t){return t.reduce(((t,n)=>(e.hasOwnProperty(n)&&(t[n]=e[n]),t)),{})};const s=r.globalThisShim.setTimeout,o=r.globalThisShim.clearTimeout;t.installTimerFunctions=function(e,t){t.useNativeTimers?(e.setTimeoutFn=s.bind(r.globalThisShim),e.clearTimeoutFn=o.bind(r.globalThisShim)):(e.setTimeoutFn=r.globalThisShim.setTimeout.bind(r.globalThisShim),e.clearTimeoutFn=r.globalThisShim.clearTimeout.bind(r.globalThisShim))},t.byteLength=function(e){return"string"==typeof e?function(e){let t=0,n=0;for(let r=0,s=e.length;r<s;r++)t=e.charCodeAt(r),t<128?n+=1:t<2048?n+=2:t<55296||t>=57344?n+=3:(r++,n+=4);return n}(e):Math.ceil(1.33*(e.byteLength||e.size))}},46:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ERROR_PACKET=t.PACKET_TYPES_REVERSE=t.PACKET_TYPES=void 0;const n=Object.create(null);t.PACKET_TYPES=n,n.open="0",n.close="1",n.ping="2",n.pong="3",n.message="4",n.upgrade="5",n.noop="6";const r=Object.create(null);t.PACKET_TYPES_REVERSE=r,Object.keys(n).forEach((e=>{r[n[e]]=e})),t.ERROR_PACKET={type:"error",data:"parser error"}},745:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.decode=t.encode=void 0;const n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",r="undefined"==typeof Uint8Array?[]:new Uint8Array(256);for(let e=0;e<64;e++)r[n.charCodeAt(e)]=e;t.encode=e=>{let t,r=new Uint8Array(e),s=r.length,o="";for(t=0;t<s;t+=3)o+=n[r[t]>>2],o+=n[(3&r[t])<<4|r[t+1]>>4],o+=n[(15&r[t+1])<<2|r[t+2]>>6],o+=n[63&r[t+2]];return s%3==2?o=o.substring(0,o.length-1)+"=":s%3==1&&(o=o.substring(0,o.length-2)+"=="),o},t.decode=e=>{let t,n,s,o,i,a=.75*e.length,c=e.length,u=0;"="===e[e.length-1]&&(a--,"="===e[e.length-2]&&a--);const l=new ArrayBuffer(a),h=new Uint8Array(l);for(t=0;t<c;t+=4)n=r[e.charCodeAt(t)],s=r[e.charCodeAt(t+1)],o=r[e.charCodeAt(t+2)],i=r[e.charCodeAt(t+3)],h[u++]=n<<2|s>>4,h[u++]=(15&s)<<4|o>>2,h[u++]=(3&o)<<6|63&i;return l}},662:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.decodePacket=void 0;const r=n(46),s=n(745),o="function"==typeof ArrayBuffer;t.decodePacket=(e,t)=>{if("string"!=typeof e)return{type:"message",data:a(e,t)};const n=e.charAt(0);return"b"===n?{type:"message",data:i(e.substring(1),t)}:r.PACKET_TYPES_REVERSE[n]?e.length>1?{type:r.PACKET_TYPES_REVERSE[n],data:e.substring(1)}:{type:r.PACKET_TYPES_REVERSE[n]}:r.ERROR_PACKET};const i=(e,t)=>{if(o){const n=(0,s.decode)(e);return a(n,t)}return{base64:!0,data:e}},a=(e,t)=>"blob"===t?e instanceof Blob?e:new Blob([e]):e instanceof ArrayBuffer?e:e.buffer},686:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.encodePacket=t.encodePacketToBinary=void 0;const r=n(46),s="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Object.prototype.toString.call(Blob),o="function"==typeof ArrayBuffer,i=e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,a=({type:e,data:t},n,a)=>s&&t instanceof Blob?n?a(t):c(t,a):o&&(t instanceof ArrayBuffer||i(t))?n?a(t):c(new Blob([t]),a):a(r.PACKET_TYPES[e]+(t||""));t.encodePacket=a;const c=(e,t)=>{const n=new FileReader;return n.onload=function(){const e=n.result.split(",")[1];t("b"+(e||""))},n.readAsDataURL(e)};function u(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}let l;t.encodePacketToBinary=function(e,t){return s&&e.data instanceof Blob?e.data.arrayBuffer().then(u).then(t):o&&(e.data instanceof ArrayBuffer||i(e.data))?t(u(e.data)):void a(e,!1,(e=>{l||(l=new TextEncoder),t(l.encode(e))}))}},376:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.decodePayload=t.decodePacket=t.encodePayload=t.encodePacket=t.protocol=t.createPacketDecoderStream=t.createPacketEncoderStream=void 0;const r=n(686);Object.defineProperty(t,"encodePacket",{enumerable:!0,get:function(){return r.encodePacket}});const s=n(662);Object.defineProperty(t,"decodePacket",{enumerable:!0,get:function(){return s.decodePacket}});const o=n(46),i=String.fromCharCode(30);let a;function c(e){return e.reduce(((e,t)=>e+t.length),0)}function u(e,t){if(e[0].length===t)return e.shift();const n=new Uint8Array(t);let r=0;for(let s=0;s<t;s++)n[s]=e[0][r++],r===e[0].length&&(e.shift(),r=0);return e.length&&r<e[0].length&&(e[0]=e[0].slice(r)),n}t.encodePayload=(e,t)=>{const n=e.length,s=new Array(n);let o=0;e.forEach(((e,a)=>{(0,r.encodePacket)(e,!1,(e=>{s[a]=e,++o===n&&t(s.join(i))}))}))},t.decodePayload=(e,t)=>{const n=e.split(i),r=[];for(let e=0;e<n.length;e++){const o=(0,s.decodePacket)(n[e],t);if(r.push(o),"error"===o.type)break}return r},t.createPacketEncoderStream=function(){return new TransformStream({transform(e,t){(0,r.encodePacketToBinary)(e,(n=>{const r=n.length;let s;if(r<126)s=new Uint8Array(1),new DataView(s.buffer).setUint8(0,r);else if(r<65536){s=new Uint8Array(3);const e=new DataView(s.buffer);e.setUint8(0,126),e.setUint16(1,r)}else{s=new Uint8Array(9);const e=new DataView(s.buffer);e.setUint8(0,127),e.setBigUint64(1,BigInt(r))}e.data&&"string"!=typeof e.data&&(s[0]|=128),t.enqueue(s),t.enqueue(n)}))}})},t.createPacketDecoderStream=function(e,t){a||(a=new TextDecoder);const n=[];let r=0,i=-1,l=!1;return new TransformStream({transform(h,d){for(n.push(h);;){if(0===r){if(c(n)<1)break;const e=u(n,1);l=128==(128&e[0]),i=127&e[0],r=i<126?3:126===i?1:2}else if(1===r){if(c(n)<2)break;const e=u(n,2);i=new DataView(e.buffer,e.byteOffset,e.length).getUint16(0),r=3}else if(2===r){if(c(n)<8)break;const e=u(n,8),t=new DataView(e.buffer,e.byteOffset,e.length),s=t.getUint32(0);if(s>Math.pow(2,21)-1){d.enqueue(o.ERROR_PACKET);break}i=s*Math.pow(2,32)+t.getUint32(4),r=3}else{if(c(n)<i)break;const e=u(n,i);d.enqueue((0,s.decodePacket)(l?e:a.decode(e),t)),r=0}if(0===i||i>e){d.enqueue(o.ERROR_PACKET);break}}}})},t.protocol=4},743:(e,t)=>{"use strict";function n(e){e=e||{},this.ms=e.min||100,this.max=e.max||1e4,this.factor=e.factor||2,this.jitter=e.jitter>0&&e.jitter<=1?e.jitter:0,this.attempts=0}Object.defineProperty(t,"__esModule",{value:!0}),t.Backoff=void 0,t.Backoff=n,n.prototype.duration=function(){var e=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var t=Math.random(),n=Math.floor(t*this.jitter*e);e=0==(1&Math.floor(10*t))?e-n:e+n}return 0|Math.min(e,this.max)},n.prototype.reset=function(){this.attempts=0},n.prototype.setMin=function(e){this.ms=e},n.prototype.setMax=function(e){this.max=e},n.prototype.setJitter=function(e){this.jitter=e}},7:function(e,t,n){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.default=t.connect=t.io=t.Socket=t.Manager=t.protocol=void 0;const s=n(894),o=n(776);Object.defineProperty(t,"Manager",{enumerable:!0,get:function(){return o.Manager}});const i=n(214);Object.defineProperty(t,"Socket",{enumerable:!0,get:function(){return i.Socket}});const a=r(n(833)).default("socket.io-client"),c={};function u(e,t){"object"==typeof e&&(t=e,e=void 0),t=t||{};const n=s.url(e,t.path||"/socket.io"),r=n.source,i=n.id,u=n.path,l=c[i]&&u in c[i].nsps;let h;return t.forceNew||t["force new connection"]||!1===t.multiplex||l?(a("ignoring socket cache for %s",r),h=new o.Manager(r,t)):(c[i]||(a("new io instance for %s",r),c[i]=new o.Manager(r,t)),h=c[i]),n.query&&!t.query&&(t.query=n.queryKey),h.socket(n.path,t)}t.io=u,t.connect=u,t.default=u,Object.assign(u,{Manager:o.Manager,Socket:i.Socket,io:u,connect:u});var l=n(627);Object.defineProperty(t,"protocol",{enumerable:!0,get:function(){return l.protocol}}),e.exports=u},776:function(e,t,n){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,n,r){void 0===r&&(r=n),Object.defineProperty(e,r,{enumerable:!0,get:function(){return t[n]}})}:function(e,t,n,r){void 0===r&&(r=n),e[r]=t[n]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&r(t,e,n);return s(t,e),t},i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.Manager=void 0;const a=n(956),c=n(214),u=o(n(627)),l=n(942),h=n(743),d=n(285),f=i(n(833)).default("socket.io-client:manager");class p extends d.Emitter{constructor(e,t){var n;super(),this.nsps={},this.subs=[],e&&"object"==typeof e&&(t=e,e=void 0),(t=t||{}).path=t.path||"/socket.io",this.opts=t,a.installTimerFunctions(this,t),this.reconnection(!1!==t.reconnection),this.reconnectionAttempts(t.reconnectionAttempts||1/0),this.reconnectionDelay(t.reconnectionDelay||1e3),this.reconnectionDelayMax(t.reconnectionDelayMax||5e3),this.randomizationFactor(null!==(n=t.randomizationFactor)&&void 0!==n?n:.5),this.backoff=new h.Backoff({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(null==t.timeout?2e4:t.timeout),this._readyState="closed",this.uri=e;const r=t.parser||u;this.encoder=new r.Encoder,this.decoder=new r.Decoder,this._autoConnect=!1!==t.autoConnect,this._autoConnect&&this.open()}reconnection(e){return arguments.length?(this._reconnection=!!e,this):this._reconnection}reconnectionAttempts(e){return void 0===e?this._reconnectionAttempts:(this._reconnectionAttempts=e,this)}reconnectionDelay(e){var t;return void 0===e?this._reconnectionDelay:(this._reconnectionDelay=e,null===(t=this.backoff)||void 0===t||t.setMin(e),this)}randomizationFactor(e){var t;return void 0===e?this._randomizationFactor:(this._randomizationFactor=e,null===(t=this.backoff)||void 0===t||t.setJitter(e),this)}reconnectionDelayMax(e){var t;return void 0===e?this._reconnectionDelayMax:(this._reconnectionDelayMax=e,null===(t=this.backoff)||void 0===t||t.setMax(e),this)}timeout(e){return arguments.length?(this._timeout=e,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&0===this.backoff.attempts&&this.reconnect()}open(e){if(f("readyState %s",this._readyState),~this._readyState.indexOf("open"))return this;f("opening %s",this.uri),this.engine=new a.Socket(this.uri,this.opts);const t=this.engine,n=this;this._readyState="opening",this.skipReconnect=!1;const r=l.on(t,"open",(function(){n.onopen(),e&&e()})),s=t=>{f("error"),this.cleanup(),this._readyState="closed",this.emitReserved("error",t),e?e(t):this.maybeReconnectOnOpen()},o=l.on(t,"error",s);if(!1!==this._timeout){const e=this._timeout;f("connect attempt will timeout after %d",e);const n=this.setTimeoutFn((()=>{f("connect attempt timed out after %d",e),r(),s(new Error("timeout")),t.close()}),e);this.opts.autoUnref&&n.unref(),this.subs.push((()=>{this.clearTimeoutFn(n)}))}return this.subs.push(r),this.subs.push(o),this}connect(e){return this.open(e)}onopen(){f("open"),this.cleanup(),this._readyState="open",this.emitReserved("open");const e=this.engine;this.subs.push(l.on(e,"ping",this.onping.bind(this)),l.on(e,"data",this.ondata.bind(this)),l.on(e,"error",this.onerror.bind(this)),l.on(e,"close",this.onclose.bind(this)),l.on(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(e){try{this.decoder.add(e)}catch(e){this.onclose("parse error",e)}}ondecoded(e){a.nextTick((()=>{this.emitReserved("packet",e)}),this.setTimeoutFn)}onerror(e){f("error",e),this.emitReserved("error",e)}socket(e,t){let n=this.nsps[e];return n?this._autoConnect&&!n.active&&n.connect():(n=new c.Socket(this,e,t),this.nsps[e]=n),n}_destroy(e){const t=Object.keys(this.nsps);for(const e of t)if(this.nsps[e].active)return void f("socket %s is still active, skipping close",e);this._close()}_packet(e){f("writing packet %j",e);const t=this.encoder.encode(e);for(let n=0;n<t.length;n++)this.engine.write(t[n],e.options)}cleanup(){f("cleanup"),this.subs.forEach((e=>e())),this.subs.length=0,this.decoder.destroy()}_close(){f("disconnect"),this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close"),this.engine&&this.engine.close()}disconnect(){return this._close()}onclose(e,t){f("closed due to %s",e),this.cleanup(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",e,t),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const e=this;if(this.backoff.attempts>=this._reconnectionAttempts)f("reconnect failed"),this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const t=this.backoff.duration();f("will wait %dms before reconnect attempt",t),this._reconnecting=!0;const n=this.setTimeoutFn((()=>{e.skipReconnect||(f("attempting reconnect"),this.emitReserved("reconnect_attempt",e.backoff.attempts),e.skipReconnect||e.open((t=>{t?(f("reconnect attempt error"),e._reconnecting=!1,e.reconnect(),this.emitReserved("reconnect_error",t)):(f("reconnect success"),e.onreconnect())})))}),t);this.opts.autoUnref&&n.unref(),this.subs.push((()=>{this.clearTimeoutFn(n)}))}}onreconnect(){const e=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",e)}}t.Manager=p},942:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.on=void 0,t.on=function(e,t,n){return e.on(t,n),function(){e.off(t,n)}}},214:function(e,t,n){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.Socket=void 0;const s=n(627),o=n(942),i=n(285),a=r(n(833)).default("socket.io-client:socket"),c=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class u extends i.Emitter{constructor(e,t,n){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=e,this.nsp=t,n&&n.auth&&(this.auth=n.auth),this._opts=Object.assign({},n),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const e=this.io;this.subs=[o.on(e,"open",this.onopen.bind(this)),o.on(e,"packet",this.onpacket.bind(this)),o.on(e,"error",this.onerror.bind(this)),o.on(e,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected||(this.subEvents(),this.io._reconnecting||this.io.open(),"open"===this.io._readyState&&this.onopen()),this}open(){return this.connect()}send(...e){return e.unshift("message"),this.emit.apply(this,e),this}emit(e,...t){if(c.hasOwnProperty(e))throw new Error('"'+e.toString()+'" is a reserved event name');if(t.unshift(e),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(t),this;const n={type:s.PacketType.EVENT,data:t,options:{}};if(n.options.compress=!1!==this.flags.compress,"function"==typeof t[t.length-1]){const e=this.ids++;a("emitting packet with ack id %d",e);const r=t.pop();this._registerAckCallback(e,r),n.id=e}const r=this.io.engine&&this.io.engine.transport&&this.io.engine.transport.writable;return!this.flags.volatile||r&&this.connected?this.connected?(this.notifyOutgoingListeners(n),this.packet(n)):this.sendBuffer.push(n):a("discard packet as the transport is not currently writable"),this.flags={},this}_registerAckCallback(e,t){var n;const r=null!==(n=this.flags.timeout)&&void 0!==n?n:this._opts.ackTimeout;if(void 0===r)return void(this.acks[e]=t);const s=this.io.setTimeoutFn((()=>{delete this.acks[e];for(let t=0;t<this.sendBuffer.length;t++)this.sendBuffer[t].id===e&&(a("removing packet with ack id %d from the buffer",e),this.sendBuffer.splice(t,1));a("event with ack id %d has timed out after %d ms",e,r),t.call(this,new Error("operation has timed out"))}),r),o=(...e)=>{this.io.clearTimeoutFn(s),t.apply(this,e)};o.withError=!0,this.acks[e]=o}emitWithAck(e,...t){return new Promise(((n,r)=>{const s=(e,t)=>e?r(e):n(t);s.withError=!0,t.push(s),this.emit(e,...t)}))}_addToQueue(e){let t;"function"==typeof e[e.length-1]&&(t=e.pop());const n={id:this._queueSeq++,tryCount:0,pending:!1,args:e,flags:Object.assign({fromQueue:!0},this.flags)};e.push(((e,...r)=>{if(n===this._queue[0])return null!==e?n.tryCount>this._opts.retries&&(a("packet [%d] is discarded after %d tries",n.id,n.tryCount),this._queue.shift(),t&&t(e)):(a("packet [%d] was successfully sent",n.id),this._queue.shift(),t&&t(null,...r)),n.pending=!1,this._drainQueue()})),this._queue.push(n),this._drainQueue()}_drainQueue(e=!1){if(a("draining queue"),!this.connected||0===this._queue.length)return;const t=this._queue[0];!t.pending||e?(t.pending=!0,t.tryCount++,a("sending packet [%d] (try n°%d)",t.id,t.tryCount),this.flags=t.flags,this.emit.apply(this,t.args)):a("packet [%d] has already been sent and is waiting for an ack",t.id)}packet(e){e.nsp=this.nsp,this.io._packet(e)}onopen(){a("transport is open - connecting"),"function"==typeof this.auth?this.auth((e=>{this._sendConnectPacket(e)})):this._sendConnectPacket(this.auth)}_sendConnectPacket(e){this.packet({type:s.PacketType.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},e):e})}onerror(e){this.connected||this.emitReserved("connect_error",e)}onclose(e,t){a("close (%s)",e),this.connected=!1,delete this.id,this.emitReserved("disconnect",e,t),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach((e=>{if(!this.sendBuffer.some((t=>String(t.id)===e))){const t=this.acks[e];delete this.acks[e],t.withError&&t.call(this,new Error("socket has been disconnected"))}}))}onpacket(e){if(e.nsp===this.nsp)switch(e.type){case s.PacketType.CONNECT:e.data&&e.data.sid?this.onconnect(e.data.sid,e.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case s.PacketType.EVENT:case s.PacketType.BINARY_EVENT:this.onevent(e);break;case s.PacketType.ACK:case s.PacketType.BINARY_ACK:this.onack(e);break;case s.PacketType.DISCONNECT:this.ondisconnect();break;case s.PacketType.CONNECT_ERROR:this.destroy();const t=new Error(e.data.message);t.data=e.data.data,this.emitReserved("connect_error",t)}}onevent(e){const t=e.data||[];a("emitting event %j",t),null!=e.id&&(a("attaching ack callback to event"),t.push(this.ack(e.id))),this.connected?this.emitEvent(t):this.receiveBuffer.push(Object.freeze(t))}emitEvent(e){if(this._anyListeners&&this._anyListeners.length){const t=this._anyListeners.slice();for(const n of t)n.apply(this,e)}super.emit.apply(this,e),this._pid&&e.length&&"string"==typeof e[e.length-1]&&(this._lastOffset=e[e.length-1])}ack(e){const t=this;let n=!1;return function(...r){n||(n=!0,a("sending ack %j",r),t.packet({type:s.PacketType.ACK,id:e,data:r}))}}onack(e){const t=this.acks[e.id];"function"==typeof t?(delete this.acks[e.id],a("calling ack %s with %j",e.id,e.data),t.withError&&e.data.unshift(null),t.apply(this,e.data)):a("bad ack %s",e.id)}onconnect(e,t){a("socket connected with id %s",e),this.id=e,this.recovered=t&&this._pid===t,this._pid=t,this.connected=!0,this.emitBuffered(),this.emitReserved("connect"),this._drainQueue(!0)}emitBuffered(){this.receiveBuffer.forEach((e=>this.emitEvent(e))),this.receiveBuffer=[],this.sendBuffer.forEach((e=>{this.notifyOutgoingListeners(e),this.packet(e)})),this.sendBuffer=[]}ondisconnect(){a("server disconnect (%s)",this.nsp),this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach((e=>e())),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&(a("performing disconnect (%s)",this.nsp),this.packet({type:s.PacketType.DISCONNECT})),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(e){return this.flags.compress=e,this}get volatile(){return this.flags.volatile=!0,this}timeout(e){return this.flags.timeout=e,this}onAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(e),this}prependAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(e),this}offAny(e){if(!this._anyListeners)return this;if(e){const t=this._anyListeners;for(let n=0;n<t.length;n++)if(e===t[n])return t.splice(n,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(e),this}prependAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(e),this}offAnyOutgoing(e){if(!this._anyOutgoingListeners)return this;if(e){const t=this._anyOutgoingListeners;for(let n=0;n<t.length;n++)if(e===t[n])return t.splice(n,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(e){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const t=this._anyOutgoingListeners.slice();for(const n of t)n.apply(this,e.data)}}}t.Socket=u},894:function(e,t,n){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.url=void 0;const s=n(956),o=r(n(833)).default("socket.io-client:url");t.url=function(e,t="",n){let r=e;n=n||"undefined"!=typeof location&&location,null==e&&(e=n.protocol+"//"+n.host),"string"==typeof e&&("/"===e.charAt(0)&&(e="/"===e.charAt(1)?n.protocol+e:n.host+e),/^(https?|wss?):\/\//.test(e)||(o("protocol-less url %s",e),e=void 0!==n?n.protocol+"//"+e:"https://"+e),o("parse %s",e),r=s.parse(e)),r.port||(/^(http|ws)$/.test(r.protocol)?r.port="80":/^(http|ws)s$/.test(r.protocol)&&(r.port="443")),r.path=r.path||"/";const i=-1!==r.host.indexOf(":")?"["+r.host+"]":r.host;return r.id=r.protocol+"://"+i+":"+r.port+t,r.href=r.protocol+"://"+i+(n&&n.port===r.port?"":":"+r.port),r}},926:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.reconstructPacket=t.deconstructPacket=void 0;const r=n(133);function s(e,t){if(!e)return e;if((0,r.isBinary)(e)){const n={_placeholder:!0,num:t.length};return t.push(e),n}if(Array.isArray(e)){const n=new Array(e.length);for(let r=0;r<e.length;r++)n[r]=s(e[r],t);return n}if("object"==typeof e&&!(e instanceof Date)){const n={};for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=s(e[r],t));return n}return e}function o(e,t){if(!e)return e;if(e&&!0===e._placeholder){if("number"==typeof e.num&&e.num>=0&&e.num<t.length)return t[e.num];throw new Error("illegal attachments")}if(Array.isArray(e))for(let n=0;n<e.length;n++)e[n]=o(e[n],t);else if("object"==typeof e)for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&(e[n]=o(e[n],t));return e}t.deconstructPacket=function(e){const t=[],n=e.data,r=e;return r.data=s(n,t),r.attachments=t.length,{packet:r,buffers:t}},t.reconstructPacket=function(e,t){return e.data=o(e.data,t),delete e.attachments,e}},627:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Decoder=t.Encoder=t.PacketType=t.protocol=void 0;const r=n(285),s=n(926),o=n(133),i=(0,n(833).default)("socket.io-parser"),a=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var c;function u(e){return"[object Object]"===Object.prototype.toString.call(e)}t.protocol=5,function(e){e[e.CONNECT=0]="CONNECT",e[e.DISCONNECT=1]="DISCONNECT",e[e.EVENT=2]="EVENT",e[e.ACK=3]="ACK",e[e.CONNECT_ERROR=4]="CONNECT_ERROR",e[e.BINARY_EVENT=5]="BINARY_EVENT",e[e.BINARY_ACK=6]="BINARY_ACK"}(c=t.PacketType||(t.PacketType={})),t.Encoder=class{constructor(e){this.replacer=e}encode(e){return i("encoding packet %j",e),e.type!==c.EVENT&&e.type!==c.ACK||!(0,o.hasBinary)(e)?[this.encodeAsString(e)]:this.encodeAsBinary({type:e.type===c.EVENT?c.BINARY_EVENT:c.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id})}encodeAsString(e){let t=""+e.type;return e.type!==c.BINARY_EVENT&&e.type!==c.BINARY_ACK||(t+=e.attachments+"-"),e.nsp&&"/"!==e.nsp&&(t+=e.nsp+","),null!=e.id&&(t+=e.id),null!=e.data&&(t+=JSON.stringify(e.data,this.replacer)),i("encoded %j as %s",e,t),t}encodeAsBinary(e){const t=(0,s.deconstructPacket)(e),n=this.encodeAsString(t.packet),r=t.buffers;return r.unshift(n),r}};class l extends r.Emitter{constructor(e){super(),this.reviver=e}add(e){let t;if("string"==typeof e){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");t=this.decodeString(e);const n=t.type===c.BINARY_EVENT;n||t.type===c.BINARY_ACK?(t.type=n?c.EVENT:c.ACK,this.reconstructor=new h(t),0===t.attachments&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t)}else{if(!(0,o.isBinary)(e)&&!e.base64)throw new Error("Unknown type: "+e);if(!this.reconstructor)throw new Error("got binary data when not reconstructing a packet");t=this.reconstructor.takeBinaryData(e),t&&(this.reconstructor=null,super.emitReserved("decoded",t))}}decodeString(e){let t=0;const n={type:Number(e.charAt(0))};if(void 0===c[n.type])throw new Error("unknown packet type "+n.type);if(n.type===c.BINARY_EVENT||n.type===c.BINARY_ACK){const r=t+1;for(;"-"!==e.charAt(++t)&&t!=e.length;);const s=e.substring(r,t);if(s!=Number(s)||"-"!==e.charAt(t))throw new Error("Illegal attachments");n.attachments=Number(s)}if("/"===e.charAt(t+1)){const r=t+1;for(;++t&&","!==e.charAt(t)&&t!==e.length;);n.nsp=e.substring(r,t)}else n.nsp="/";const r=e.charAt(t+1);if(""!==r&&Number(r)==r){const r=t+1;for(;++t;){const n=e.charAt(t);if(null==n||Number(n)!=n){--t;break}if(t===e.length)break}n.id=Number(e.substring(r,t+1))}if(e.charAt(++t)){const r=this.tryParse(e.substr(t));if(!l.isPayloadValid(n.type,r))throw new Error("invalid payload");n.data=r}return i("decoded %s as %j",e,n),n}tryParse(e){try{return JSON.parse(e,this.reviver)}catch(e){return!1}}static isPayloadValid(e,t){switch(e){case c.CONNECT:return u(t);case c.DISCONNECT:return void 0===t;case c.CONNECT_ERROR:return"string"==typeof t||u(t);case c.EVENT:case c.BINARY_EVENT:return Array.isArray(t)&&("number"==typeof t[0]||"string"==typeof t[0]&&-1===a.indexOf(t[0]));case c.ACK:case c.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}t.Decoder=l;class h{constructor(e){this.packet=e,this.buffers=[],this.reconPack=e}takeBinaryData(e){if(this.buffers.push(e),this.buffers.length===this.reconPack.attachments){const e=(0,s.reconstructPacket)(this.reconPack,this.buffers);return this.finishedReconstruction(),e}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}},133:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.hasBinary=t.isBinary=void 0;const n="function"==typeof ArrayBuffer,r=Object.prototype.toString,s="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===r.call(Blob),o="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===r.call(File);function i(e){return n&&(e instanceof ArrayBuffer||(e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer)(e))||s&&e instanceof Blob||o&&e instanceof File}t.isBinary=i,t.hasBinary=function e(t,n){if(!t||"object"!=typeof t)return!1;if(Array.isArray(t)){for(let n=0,r=t.length;n<r;n++)if(e(t[n]))return!0;return!1}if(i(t))return!0;if(t.toJSON&&"function"==typeof t.toJSON&&1===arguments.length)return e(t.toJSON(),!0);for(const n in t)if(Object.prototype.hasOwnProperty.call(t,n)&&e(t[n]))return!0;return!1}},285:(e,t,n)=>{"use strict";function r(e){if(e)return function(e){for(var t in r.prototype)e[t]=r.prototype[t];return e}(e)}n.r(t),n.d(t,{Emitter:()=>r}),r.prototype.on=r.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this},r.prototype.once=function(e,t){function n(){this.off(e,n),t.apply(this,arguments)}return n.fn=t,this.on(e,n),this},r.prototype.off=r.prototype.removeListener=r.prototype.removeAllListeners=r.prototype.removeEventListener=function(e,t){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var n,r=this._callbacks["$"+e];if(!r)return this;if(1==arguments.length)return delete this._callbacks["$"+e],this;for(var s=0;s<r.length;s++)if((n=r[s])===t||n.fn===t){r.splice(s,1);break}return 0===r.length&&delete this._callbacks["$"+e],this},r.prototype.emit=function(e){this._callbacks=this._callbacks||{};for(var t=new Array(arguments.length-1),n=this._callbacks["$"+e],r=1;r<arguments.length;r++)t[r-1]=arguments[r];if(n){r=0;for(var s=(n=n.slice(0)).length;r<s;++r)n[r].apply(this,t)}return this},r.prototype.emitReserved=r.prototype.emit,r.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks["$"+e]||[]},r.prototype.hasListeners=function(e){return!!this.listeners(e).length}}},t={};function n(r){var s=t[r];if(void 0!==s)return s.exports;var o=t[r]={exports:{}};return e[r].call(o.exports,o,o.exports,n),o.exports}n.d=(e,t)=>{for(var r in t)n.o(t,r)&&!n.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},n.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),n.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var r={};return(()=>{"use strict";var e=r;Object.defineProperty(e,"__esModule",{value:!0}),e.validateConfiguration=e.parseconnectionstring=e.prepareSql=e.escapeSqlParameter=e.SQLiteCloudRow=e.SQLiteCloudRowset=e.SQLiteCloudError=e.SQLiteCloudConnection=e.Statement=e.Database=void 0;var t=n(500);Object.defineProperty(e,"Database",{enumerable:!0,get:function(){return t.Database}});var s=n(96);Object.defineProperty(e,"Statement",{enumerable:!0,get:function(){return s.Statement}});var o=n(361);Object.defineProperty(e,"SQLiteCloudConnection",{enumerable:!0,get:function(){return o.SQLiteCloudConnection}});var i=n(80);Object.defineProperty(e,"SQLiteCloudError",{enumerable:!0,get:function(){return i.SQLiteCloudError}});var a=n(121);Object.defineProperty(e,"SQLiteCloudRowset",{enumerable:!0,get:function(){return a.SQLiteCloudRowset}}),Object.defineProperty(e,"SQLiteCloudRow",{enumerable:!0,get:function(){return a.SQLiteCloudRow}});var c=n(193);Object.defineProperty(e,"escapeSqlParameter",{enumerable:!0,get:function(){return c.escapeSqlParameter}}),Object.defineProperty(e,"prepareSql",{enumerable:!0,get:function(){return c.prepareSql}}),Object.defineProperty(e,"parseconnectionstring",{enumerable:!0,get:function(){return c.parseconnectionstring}}),Object.defineProperty(e,"validateConfiguration",{enumerable:!0,get:function(){return c.validateConfiguration}})})(),r})()));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sqlitecloud/drivers",
3
- "version": "1.0.178",
3
+ "version": "1.0.193",
4
4
  "description": "SQLiteCloud drivers for Typescript/Javascript in edge, web and node clients",
5
5
  "main": "./lib/index.js",
6
6
  "types": "./lib/index.d.ts",