blaizejs 0.3.2 → 0.3.3
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/dist/chunk-337RPHG5.js +11 -0
- package/dist/{chunk-HB6MRTGD.js.map → chunk-337RPHG5.js.map} +1 -1
- package/dist/{unsupported-media-type-error-VVHRDTUH.js → chunk-HX7XLEO3.js} +3 -9
- package/dist/{chunk-7IM52S7P.js.map → chunk-HX7XLEO3.js.map} +1 -1
- package/dist/chunk-KE2IOPV4.js +11 -0
- package/dist/{chunk-IFP53BNM.js.map → chunk-KE2IOPV4.js.map} +1 -1
- package/dist/chunk-LY65OJH4.js +11 -0
- package/dist/{chunk-3VK325MM.js.map → chunk-LY65OJH4.js.map} +1 -1
- package/dist/chunk-VM3QGHVO.js +11 -0
- package/dist/{chunk-CQKM74J4.js.map → chunk-VM3QGHVO.js.map} +1 -1
- package/dist/index.cjs +38 -3486
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +38 -3153
- package/dist/index.js.map +1 -1
- package/dist/{validation-error-TXMSFWZL.js → internal-server-error-JHHSKW5B.js} +3 -9
- package/dist/{internal-server-error-PVME2DGN.js → payload-too-large-error-SOQINKUL.js} +3 -9
- package/dist/{payload-too-large-error-QQG7MKGT.js → unsupported-media-type-error-KJMHH5CY.js} +3 -9
- package/dist/validation-error-Q6IOTN4C.js +11 -0
- package/package.json +6 -6
- package/dist/chunk-3VK325MM.js +0 -31
- package/dist/chunk-7IM52S7P.js +0 -31
- package/dist/chunk-CQKM74J4.js +0 -39
- package/dist/chunk-HB6MRTGD.js +0 -39
- package/dist/chunk-IFP53BNM.js +0 -149
- /package/dist/{internal-server-error-PVME2DGN.js.map → internal-server-error-JHHSKW5B.js.map} +0 -0
- /package/dist/{payload-too-large-error-QQG7MKGT.js.map → payload-too-large-error-SOQINKUL.js.map} +0 -0
- /package/dist/{unsupported-media-type-error-VVHRDTUH.js.map → unsupported-media-type-error-KJMHH5CY.js.map} +0 -0
- /package/dist/{validation-error-TXMSFWZL.js.map → validation-error-Q6IOTN4C.js.map} +0 -0
package/dist/index.cjs
CHANGED
|
@@ -1,3505 +1,57 @@
|
|
|
1
1
|
|
|
2
2
|
/**
|
|
3
|
-
* blaizejs v0.3.
|
|
3
|
+
* blaizejs v0.3.3
|
|
4
4
|
* A blazing-fast, TypeScript-first Node.js framework with HTTP/2 support, file-based routing, powerful middleware system, and end-to-end type safety for building modern APIs.
|
|
5
5
|
*
|
|
6
6
|
* Copyright (c) 2025 BlaizeJS Contributors
|
|
7
7
|
* @license MIT
|
|
8
8
|
*/
|
|
9
9
|
|
|
10
|
-
"use strict";
|
|
11
|
-
var __create = Object.create;
|
|
12
|
-
var
|
|
13
|
-
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
14
|
-
var
|
|
15
|
-
|
|
16
|
-
var
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
var
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
};
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
};
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
37
|
-
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
38
|
-
mod
|
|
39
|
-
));
|
|
40
|
-
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
41
|
-
|
|
42
|
-
// ../blaize-types/src/errors.ts
|
|
43
|
-
function isBodyParseError(error) {
|
|
44
|
-
return typeof error === "object" && error !== null && "type" in error && "message" in error && "error" in error && typeof error.type === "string" && typeof error.message === "string";
|
|
45
|
-
}
|
|
46
|
-
var ErrorType, ErrorSeverity, BlaizeError;
|
|
47
|
-
var init_errors = __esm({
|
|
48
|
-
"../blaize-types/src/errors.ts"() {
|
|
49
|
-
"use strict";
|
|
50
|
-
ErrorType = /* @__PURE__ */ ((ErrorType2) => {
|
|
51
|
-
ErrorType2["VALIDATION_ERROR"] = "VALIDATION_ERROR";
|
|
52
|
-
ErrorType2["NOT_FOUND"] = "NOT_FOUND";
|
|
53
|
-
ErrorType2["UNAUTHORIZED"] = "UNAUTHORIZED";
|
|
54
|
-
ErrorType2["FORBIDDEN"] = "FORBIDDEN";
|
|
55
|
-
ErrorType2["CONFLICT"] = "CONFLICT";
|
|
56
|
-
ErrorType2["RATE_LIMITED"] = "RATE_LIMITED";
|
|
57
|
-
ErrorType2["INTERNAL_SERVER_ERROR"] = "INTERNAL_SERVER_ERROR";
|
|
58
|
-
ErrorType2["PAYLOAD_TOO_LARGE"] = "PAYLOAD_TOO_LARGE";
|
|
59
|
-
ErrorType2["UNSUPPORTED_MEDIA_TYPE"] = "UNSUPPORTED_MEDIA_TYPE";
|
|
60
|
-
ErrorType2["UPLOAD_TIMEOUT"] = "UPLOAD_TIMEOUT";
|
|
61
|
-
ErrorType2["UNPROCESSABLE_ENTITY"] = "UNPROCESSABLE_ENTITY";
|
|
62
|
-
ErrorType2["NETWORK_ERROR"] = "NETWORK_ERROR";
|
|
63
|
-
ErrorType2["TIMEOUT_ERROR"] = "TIMEOUT_ERROR";
|
|
64
|
-
ErrorType2["PARSE_ERROR"] = "PARSE_ERROR";
|
|
65
|
-
ErrorType2["HTTP_ERROR"] = "HTTP_ERROR";
|
|
66
|
-
return ErrorType2;
|
|
67
|
-
})(ErrorType || {});
|
|
68
|
-
ErrorSeverity = /* @__PURE__ */ ((ErrorSeverity2) => {
|
|
69
|
-
ErrorSeverity2["LOW"] = "low";
|
|
70
|
-
ErrorSeverity2["MEDIUM"] = "medium";
|
|
71
|
-
ErrorSeverity2["HIGH"] = "high";
|
|
72
|
-
ErrorSeverity2["CRITICAL"] = "critical";
|
|
73
|
-
return ErrorSeverity2;
|
|
74
|
-
})(ErrorSeverity || {});
|
|
75
|
-
BlaizeError = class extends Error {
|
|
76
|
-
/**
|
|
77
|
-
* Error type identifier from the ErrorType enum
|
|
78
|
-
* Used for programmatic error handling and client-side error routing
|
|
79
|
-
*/
|
|
80
|
-
type;
|
|
81
|
-
/**
|
|
82
|
-
* Human-readable error title/message
|
|
83
|
-
* Should be descriptive enough for debugging but safe for end users
|
|
84
|
-
*/
|
|
85
|
-
title;
|
|
86
|
-
/**
|
|
87
|
-
* HTTP status code associated with this error
|
|
88
|
-
* Used by the error boundary to set appropriate response status
|
|
89
|
-
*/
|
|
90
|
-
status;
|
|
91
|
-
/**
|
|
92
|
-
* Correlation ID for request tracing
|
|
93
|
-
* Links this error to the specific request that generated it
|
|
94
|
-
*/
|
|
95
|
-
correlationId;
|
|
96
|
-
/**
|
|
97
|
-
* Timestamp when the error occurred
|
|
98
|
-
* Useful for debugging and log correlation
|
|
99
|
-
*/
|
|
100
|
-
timestamp;
|
|
101
|
-
/**
|
|
102
|
-
* Additional error-specific details
|
|
103
|
-
* Type-safe error context that varies by error type
|
|
104
|
-
*/
|
|
105
|
-
details;
|
|
106
|
-
/**
|
|
107
|
-
* Creates a new BlaizeError instance
|
|
108
|
-
*
|
|
109
|
-
* @param type - Error type from the ErrorType enum
|
|
110
|
-
* @param title - Human-readable error message
|
|
111
|
-
* @param status - HTTP status code
|
|
112
|
-
* @param correlationId - Request correlation ID for tracing
|
|
113
|
-
* @param details - Optional error-specific details
|
|
114
|
-
*/
|
|
115
|
-
constructor(type, title, status, correlationId, details) {
|
|
116
|
-
super(title);
|
|
117
|
-
this.name = this.constructor.name;
|
|
118
|
-
this.type = type;
|
|
119
|
-
this.title = title;
|
|
120
|
-
this.status = status;
|
|
121
|
-
this.correlationId = correlationId;
|
|
122
|
-
this.timestamp = /* @__PURE__ */ new Date();
|
|
123
|
-
this.details = details;
|
|
124
|
-
Object.setPrototypeOf(this, new.target.prototype);
|
|
125
|
-
if (Error.captureStackTrace) {
|
|
126
|
-
Error.captureStackTrace(this, this.constructor);
|
|
127
|
-
}
|
|
128
|
-
}
|
|
129
|
-
/**
|
|
130
|
-
* Serializes the error to a plain object suitable for HTTP responses
|
|
131
|
-
*
|
|
132
|
-
* @returns Object representation of the error
|
|
133
|
-
*/
|
|
134
|
-
toJSON() {
|
|
135
|
-
const base = {
|
|
136
|
-
type: this.type,
|
|
137
|
-
title: this.title,
|
|
138
|
-
status: this.status,
|
|
139
|
-
correlationId: this.correlationId,
|
|
140
|
-
timestamp: this.timestamp.toISOString()
|
|
141
|
-
};
|
|
142
|
-
if (this.details !== void 0) {
|
|
143
|
-
return { ...base, details: this.details };
|
|
144
|
-
}
|
|
145
|
-
return base;
|
|
146
|
-
}
|
|
147
|
-
/**
|
|
148
|
-
* Returns a string representation of the error
|
|
149
|
-
* Includes correlation ID for easier debugging
|
|
150
|
-
*/
|
|
151
|
-
toString() {
|
|
152
|
-
return `${this.name}: ${this.title} [${this.correlationId}]`;
|
|
153
|
-
}
|
|
154
|
-
};
|
|
155
|
-
}
|
|
156
|
-
});
|
|
157
|
-
|
|
158
|
-
// src/errors/correlation.ts
|
|
159
|
-
function generateCorrelationId() {
|
|
160
|
-
const timestamp = Date.now().toString(36);
|
|
161
|
-
const random = Math.random().toString(36).substr(2, 9);
|
|
162
|
-
return `req_${timestamp}_${random}`;
|
|
163
|
-
}
|
|
164
|
-
function getCurrentCorrelationId() {
|
|
165
|
-
const stored = correlationStorage.getStore();
|
|
166
|
-
return stored && stored.trim() ? stored : "unknown";
|
|
167
|
-
}
|
|
168
|
-
var import_node_async_hooks2, correlationStorage;
|
|
169
|
-
var init_correlation = __esm({
|
|
170
|
-
"src/errors/correlation.ts"() {
|
|
171
|
-
"use strict";
|
|
172
|
-
import_node_async_hooks2 = require("async_hooks");
|
|
173
|
-
correlationStorage = new import_node_async_hooks2.AsyncLocalStorage();
|
|
174
|
-
}
|
|
175
|
-
});
|
|
176
|
-
|
|
177
|
-
// src/errors/internal-server-error.ts
|
|
178
|
-
var internal_server_error_exports = {};
|
|
179
|
-
__export(internal_server_error_exports, {
|
|
180
|
-
InternalServerError: () => InternalServerError
|
|
181
|
-
});
|
|
182
|
-
var InternalServerError;
|
|
183
|
-
var init_internal_server_error = __esm({
|
|
184
|
-
"src/errors/internal-server-error.ts"() {
|
|
185
|
-
"use strict";
|
|
186
|
-
init_errors();
|
|
187
|
-
init_correlation();
|
|
188
|
-
InternalServerError = class extends BlaizeError {
|
|
189
|
-
/**
|
|
190
|
-
* Creates a new InternalServerError instance
|
|
191
|
-
*
|
|
192
|
-
* @param title - Human-readable error message
|
|
193
|
-
* @param details - Optional debugging context
|
|
194
|
-
* @param correlationId - Optional correlation ID (uses current context if not provided)
|
|
195
|
-
*/
|
|
196
|
-
constructor(title, details = void 0, correlationId = void 0) {
|
|
197
|
-
super(
|
|
198
|
-
"INTERNAL_SERVER_ERROR" /* INTERNAL_SERVER_ERROR */,
|
|
199
|
-
title,
|
|
200
|
-
500,
|
|
201
|
-
// HTTP 500 Internal Server Error
|
|
202
|
-
correlationId ?? getCurrentCorrelationId(),
|
|
203
|
-
details
|
|
204
|
-
);
|
|
205
|
-
}
|
|
206
|
-
};
|
|
207
|
-
}
|
|
208
|
-
});
|
|
209
|
-
|
|
210
|
-
// src/errors/validation-error.ts
|
|
211
|
-
var validation_error_exports = {};
|
|
212
|
-
__export(validation_error_exports, {
|
|
213
|
-
ValidationError: () => ValidationError
|
|
214
|
-
});
|
|
215
|
-
var ValidationError;
|
|
216
|
-
var init_validation_error = __esm({
|
|
217
|
-
"src/errors/validation-error.ts"() {
|
|
218
|
-
"use strict";
|
|
219
|
-
init_errors();
|
|
220
|
-
init_correlation();
|
|
221
|
-
ValidationError = class extends BlaizeError {
|
|
222
|
-
/**
|
|
223
|
-
* Creates a new ValidationError instance
|
|
224
|
-
*
|
|
225
|
-
* @param title - Human-readable error message
|
|
226
|
-
* @param details - Optional structured validation details
|
|
227
|
-
* @param correlationId - Optional correlation ID (uses current context if not provided)
|
|
228
|
-
*/
|
|
229
|
-
constructor(title, details = void 0, correlationId = void 0) {
|
|
230
|
-
super(
|
|
231
|
-
"VALIDATION_ERROR" /* VALIDATION_ERROR */,
|
|
232
|
-
title,
|
|
233
|
-
400,
|
|
234
|
-
// HTTP 400 Bad Request
|
|
235
|
-
correlationId ?? getCurrentCorrelationId(),
|
|
236
|
-
details
|
|
237
|
-
);
|
|
238
|
-
}
|
|
239
|
-
};
|
|
240
|
-
}
|
|
241
|
-
});
|
|
242
|
-
|
|
243
|
-
// src/errors/payload-too-large-error.ts
|
|
244
|
-
var payload_too_large_error_exports = {};
|
|
245
|
-
__export(payload_too_large_error_exports, {
|
|
246
|
-
PayloadTooLargeError: () => PayloadTooLargeError
|
|
247
|
-
});
|
|
248
|
-
var PayloadTooLargeError;
|
|
249
|
-
var init_payload_too_large_error = __esm({
|
|
250
|
-
"src/errors/payload-too-large-error.ts"() {
|
|
251
|
-
"use strict";
|
|
252
|
-
init_correlation();
|
|
253
|
-
init_errors();
|
|
254
|
-
PayloadTooLargeError = class extends BlaizeError {
|
|
255
|
-
constructor(title, details, correlationId) {
|
|
256
|
-
super(
|
|
257
|
-
"PAYLOAD_TOO_LARGE" /* PAYLOAD_TOO_LARGE */,
|
|
258
|
-
title,
|
|
259
|
-
413,
|
|
260
|
-
correlationId ?? getCurrentCorrelationId(),
|
|
261
|
-
details
|
|
262
|
-
);
|
|
263
|
-
}
|
|
264
|
-
};
|
|
265
|
-
}
|
|
266
|
-
});
|
|
267
|
-
|
|
268
|
-
// src/errors/unsupported-media-type-error.ts
|
|
269
|
-
var unsupported_media_type_error_exports = {};
|
|
270
|
-
__export(unsupported_media_type_error_exports, {
|
|
271
|
-
UnsupportedMediaTypeError: () => UnsupportedMediaTypeError
|
|
272
|
-
});
|
|
273
|
-
var UnsupportedMediaTypeError;
|
|
274
|
-
var init_unsupported_media_type_error = __esm({
|
|
275
|
-
"src/errors/unsupported-media-type-error.ts"() {
|
|
276
|
-
"use strict";
|
|
277
|
-
init_correlation();
|
|
278
|
-
init_errors();
|
|
279
|
-
UnsupportedMediaTypeError = class extends BlaizeError {
|
|
280
|
-
constructor(title, details, correlationId) {
|
|
281
|
-
super(
|
|
282
|
-
"UNSUPPORTED_MEDIA_TYPE" /* UNSUPPORTED_MEDIA_TYPE */,
|
|
283
|
-
title,
|
|
284
|
-
415,
|
|
285
|
-
correlationId ?? getCurrentCorrelationId(),
|
|
286
|
-
details
|
|
287
|
-
);
|
|
288
|
-
}
|
|
289
|
-
};
|
|
290
|
-
}
|
|
291
|
-
});
|
|
292
|
-
|
|
293
|
-
// src/index.ts
|
|
294
|
-
var index_exports = {};
|
|
295
|
-
__export(index_exports, {
|
|
296
|
-
Blaize: () => Blaize,
|
|
297
|
-
BlaizeError: () => BlaizeError,
|
|
298
|
-
ConflictError: () => ConflictError,
|
|
299
|
-
ErrorSeverity: () => ErrorSeverity,
|
|
300
|
-
ErrorType: () => ErrorType,
|
|
301
|
-
ForbiddenError: () => ForbiddenError,
|
|
302
|
-
InternalServerError: () => InternalServerError,
|
|
303
|
-
MiddlewareAPI: () => MiddlewareAPI,
|
|
304
|
-
NotFoundError: () => NotFoundError,
|
|
305
|
-
PayloadTooLargeError: () => PayloadTooLargeError,
|
|
306
|
-
PluginsAPI: () => PluginsAPI,
|
|
307
|
-
RateLimitError: () => RateLimitError,
|
|
308
|
-
RequestTimeoutError: () => RequestTimeoutError,
|
|
309
|
-
RouterAPI: () => RouterAPI,
|
|
310
|
-
ServerAPI: () => ServerAPI,
|
|
311
|
-
UnauthorizedError: () => UnauthorizedError,
|
|
312
|
-
UnprocessableEntityError: () => UnprocessableEntityError,
|
|
313
|
-
UnsupportedMediaTypeError: () => UnsupportedMediaTypeError,
|
|
314
|
-
VERSION: () => VERSION,
|
|
315
|
-
ValidationError: () => ValidationError,
|
|
316
|
-
compose: () => compose,
|
|
317
|
-
createDeleteRoute: () => createDeleteRoute,
|
|
318
|
-
createGetRoute: () => createGetRoute,
|
|
319
|
-
createHeadRoute: () => createHeadRoute,
|
|
320
|
-
createMiddleware: () => create,
|
|
321
|
-
createOptionsRoute: () => createOptionsRoute,
|
|
322
|
-
createPatchRoute: () => createPatchRoute,
|
|
323
|
-
createPlugin: () => create2,
|
|
324
|
-
createPostRoute: () => createPostRoute,
|
|
325
|
-
createPutRoute: () => createPutRoute,
|
|
326
|
-
createServer: () => create3,
|
|
327
|
-
default: () => index_default,
|
|
328
|
-
isBodyParseError: () => isBodyParseError
|
|
329
|
-
});
|
|
330
|
-
module.exports = __toCommonJS(index_exports);
|
|
331
|
-
|
|
332
|
-
// src/middleware/execute.ts
|
|
333
|
-
function execute(middleware, ctx, next) {
|
|
334
|
-
if (!middleware) {
|
|
335
|
-
return Promise.resolve(next());
|
|
336
|
-
}
|
|
337
|
-
if (middleware.skip && middleware.skip(ctx)) {
|
|
338
|
-
return Promise.resolve(next());
|
|
339
|
-
}
|
|
340
|
-
try {
|
|
341
|
-
const result = middleware.execute(ctx, next);
|
|
342
|
-
if (result instanceof Promise) {
|
|
343
|
-
return result;
|
|
344
|
-
} else {
|
|
345
|
-
return Promise.resolve(result);
|
|
346
|
-
}
|
|
347
|
-
} catch (error) {
|
|
348
|
-
return Promise.reject(error);
|
|
349
|
-
}
|
|
350
|
-
}
|
|
351
|
-
|
|
352
|
-
// src/middleware/compose.ts
|
|
353
|
-
function compose(middlewareStack) {
|
|
354
|
-
if (middlewareStack.length === 0) {
|
|
355
|
-
return async (_, next) => {
|
|
356
|
-
await Promise.resolve(next());
|
|
357
|
-
};
|
|
358
|
-
}
|
|
359
|
-
return async function(ctx, finalHandler) {
|
|
360
|
-
const called = /* @__PURE__ */ new Set();
|
|
361
|
-
const dispatch = async (i) => {
|
|
362
|
-
if (i >= middlewareStack.length) {
|
|
363
|
-
return Promise.resolve(finalHandler());
|
|
364
|
-
}
|
|
365
|
-
const middleware = middlewareStack[i];
|
|
366
|
-
const nextDispatch = () => {
|
|
367
|
-
if (called.has(i)) {
|
|
368
|
-
throw new Error("next() called multiple times");
|
|
369
|
-
}
|
|
370
|
-
called.add(i);
|
|
371
|
-
return dispatch(i + 1);
|
|
372
|
-
};
|
|
373
|
-
return execute(middleware, ctx, nextDispatch);
|
|
374
|
-
};
|
|
375
|
-
return dispatch(0);
|
|
376
|
-
};
|
|
377
|
-
}
|
|
378
|
-
|
|
379
|
-
// src/middleware/create.ts
|
|
380
|
-
function create(handlerOrOptions) {
|
|
381
|
-
if (typeof handlerOrOptions === "function") {
|
|
382
|
-
return {
|
|
383
|
-
name: "anonymous",
|
|
384
|
-
// Default name for function middleware
|
|
385
|
-
execute: handlerOrOptions,
|
|
386
|
-
debug: false
|
|
387
|
-
};
|
|
388
|
-
}
|
|
389
|
-
const { name = "anonymous", handler, skip, debug = false } = handlerOrOptions;
|
|
390
|
-
const middleware = {
|
|
391
|
-
name,
|
|
392
|
-
execute: handler,
|
|
393
|
-
debug
|
|
394
|
-
};
|
|
395
|
-
if (skip !== void 0) {
|
|
396
|
-
return {
|
|
397
|
-
...middleware,
|
|
398
|
-
skip
|
|
399
|
-
};
|
|
400
|
-
}
|
|
401
|
-
return middleware;
|
|
402
|
-
}
|
|
403
|
-
|
|
404
|
-
// src/plugins/create.ts
|
|
405
|
-
function create2(name, version, setup, defaultOptions = {}) {
|
|
406
|
-
if (!name || typeof name !== "string") {
|
|
407
|
-
throw new Error("Plugin name must be a non-empty string");
|
|
408
|
-
}
|
|
409
|
-
if (!version || typeof version !== "string") {
|
|
410
|
-
throw new Error("Plugin version must be a non-empty string");
|
|
411
|
-
}
|
|
412
|
-
if (typeof setup !== "function") {
|
|
413
|
-
throw new Error("Plugin setup must be a function");
|
|
414
|
-
}
|
|
415
|
-
return function pluginFactory(userOptions) {
|
|
416
|
-
const mergedOptions = { ...defaultOptions, ...userOptions };
|
|
417
|
-
const plugin = {
|
|
418
|
-
name,
|
|
419
|
-
version,
|
|
420
|
-
// The register hook calls the user's setup function
|
|
421
|
-
register: async (app) => {
|
|
422
|
-
const result = await setup(app, mergedOptions);
|
|
423
|
-
if (result && typeof result === "object") {
|
|
424
|
-
Object.assign(plugin, result);
|
|
425
|
-
}
|
|
426
|
-
}
|
|
427
|
-
};
|
|
428
|
-
return plugin;
|
|
429
|
-
};
|
|
430
|
-
}
|
|
431
|
-
|
|
432
|
-
// src/router/create.ts
|
|
433
|
-
var import_node_url = require("url");
|
|
434
|
-
|
|
435
|
-
// src/config.ts
|
|
436
|
-
var config = {};
|
|
437
|
-
function setRuntimeConfig(newConfig) {
|
|
438
|
-
config = { ...config, ...newConfig };
|
|
439
|
-
}
|
|
440
|
-
function getRoutesDir() {
|
|
441
|
-
if (!config.routesDir) {
|
|
442
|
-
throw new Error("Routes directory not configured. Make sure server is properly initialized.");
|
|
443
|
-
}
|
|
444
|
-
return config.routesDir;
|
|
445
|
-
}
|
|
446
|
-
|
|
447
|
-
// src/router/discovery/parser.ts
|
|
448
|
-
var path = __toESM(require("path"), 1);
|
|
449
|
-
function parseRoutePath(filePath, basePath) {
|
|
450
|
-
if (filePath.startsWith("file://")) {
|
|
451
|
-
filePath = filePath.replace("file://", "");
|
|
452
|
-
}
|
|
453
|
-
if (basePath.startsWith("file://")) {
|
|
454
|
-
basePath = basePath.replace("file://", "");
|
|
455
|
-
}
|
|
456
|
-
const forwardSlashFilePath = filePath.replace(/\\/g, "/");
|
|
457
|
-
const forwardSlashBasePath = basePath.replace(/\\/g, "/");
|
|
458
|
-
const normalizedBasePath = forwardSlashBasePath.endsWith("/") ? forwardSlashBasePath : `${forwardSlashBasePath}/`;
|
|
459
|
-
let relativePath = forwardSlashFilePath;
|
|
460
|
-
if (forwardSlashFilePath.startsWith(normalizedBasePath)) {
|
|
461
|
-
relativePath = forwardSlashFilePath.substring(normalizedBasePath.length);
|
|
462
|
-
} else if (forwardSlashFilePath.startsWith(forwardSlashBasePath)) {
|
|
463
|
-
relativePath = forwardSlashFilePath.substring(forwardSlashBasePath.length);
|
|
464
|
-
if (relativePath.startsWith("/")) {
|
|
465
|
-
relativePath = relativePath.substring(1);
|
|
466
|
-
}
|
|
467
|
-
} else {
|
|
468
|
-
relativePath = path.relative(forwardSlashBasePath, forwardSlashFilePath).replace(/\\/g, "/");
|
|
469
|
-
}
|
|
470
|
-
relativePath = relativePath.replace(/\.[^.]+$/, "");
|
|
471
|
-
const segments = relativePath.split("/").filter(Boolean);
|
|
472
|
-
const params = [];
|
|
473
|
-
const routeSegments = segments.map((segment) => {
|
|
474
|
-
if (segment.startsWith("[") && segment.endsWith("]")) {
|
|
475
|
-
const paramName = segment.slice(1, -1);
|
|
476
|
-
params.push(paramName);
|
|
477
|
-
return `:${paramName}`;
|
|
478
|
-
}
|
|
479
|
-
return segment;
|
|
480
|
-
});
|
|
481
|
-
let routePath = routeSegments.length > 0 ? `/${routeSegments.join("/")}` : "/";
|
|
482
|
-
if (routePath.endsWith("/index")) {
|
|
483
|
-
routePath = routePath.slice(0, -6) || "/";
|
|
484
|
-
}
|
|
485
|
-
return {
|
|
486
|
-
filePath,
|
|
487
|
-
routePath,
|
|
488
|
-
params
|
|
489
|
-
};
|
|
490
|
-
}
|
|
491
|
-
|
|
492
|
-
// src/router/create.ts
|
|
493
|
-
function getCallerFilePath() {
|
|
494
|
-
const originalPrepareStackTrace = Error.prepareStackTrace;
|
|
495
|
-
try {
|
|
496
|
-
Error.prepareStackTrace = (_, stack2) => stack2;
|
|
497
|
-
const stack = new Error().stack;
|
|
498
|
-
const callerFrame = stack[3];
|
|
499
|
-
if (!callerFrame || typeof callerFrame.getFileName !== "function") {
|
|
500
|
-
throw new Error("Unable to determine caller file frame");
|
|
501
|
-
}
|
|
502
|
-
const fileName = callerFrame.getFileName();
|
|
503
|
-
if (!fileName) {
|
|
504
|
-
throw new Error("Unable to determine caller file name");
|
|
505
|
-
}
|
|
506
|
-
if (fileName.startsWith("file://")) {
|
|
507
|
-
return (0, import_node_url.fileURLToPath)(fileName);
|
|
508
|
-
}
|
|
509
|
-
return fileName;
|
|
510
|
-
} finally {
|
|
511
|
-
Error.prepareStackTrace = originalPrepareStackTrace;
|
|
512
|
-
}
|
|
513
|
-
}
|
|
514
|
-
function getRoutePath() {
|
|
515
|
-
const callerPath = getCallerFilePath();
|
|
516
|
-
const routesDir = getRoutesDir();
|
|
517
|
-
const parsedRoute = parseRoutePath(callerPath, routesDir);
|
|
518
|
-
console.log(`\u{1F50E} Parsed route path: ${parsedRoute.routePath} from file: ${callerPath}`);
|
|
519
|
-
return parsedRoute.routePath;
|
|
520
|
-
}
|
|
521
|
-
var createGetRoute = (config2) => {
|
|
522
|
-
validateMethodConfig("GET", config2);
|
|
523
|
-
const path6 = getRoutePath();
|
|
524
|
-
return {
|
|
525
|
-
GET: config2,
|
|
526
|
-
// Let TypeScript infer the proper types
|
|
527
|
-
path: path6
|
|
528
|
-
};
|
|
529
|
-
};
|
|
530
|
-
var createPostRoute = (config2) => {
|
|
531
|
-
validateMethodConfig("POST", config2);
|
|
532
|
-
const path6 = getRoutePath();
|
|
533
|
-
return {
|
|
534
|
-
POST: config2,
|
|
535
|
-
// Let TypeScript infer the proper types
|
|
536
|
-
path: path6
|
|
537
|
-
};
|
|
538
|
-
};
|
|
539
|
-
var createPutRoute = (config2) => {
|
|
540
|
-
validateMethodConfig("PUT", config2);
|
|
541
|
-
const path6 = getRoutePath();
|
|
542
|
-
return {
|
|
543
|
-
PUT: config2,
|
|
544
|
-
// Let TypeScript infer the proper types
|
|
545
|
-
path: path6
|
|
546
|
-
};
|
|
547
|
-
};
|
|
548
|
-
var createDeleteRoute = (config2) => {
|
|
549
|
-
validateMethodConfig("DELETE", config2);
|
|
550
|
-
const path6 = getRoutePath();
|
|
551
|
-
return {
|
|
552
|
-
DELETE: config2,
|
|
553
|
-
// Let TypeScript infer the proper types
|
|
554
|
-
path: path6
|
|
555
|
-
};
|
|
556
|
-
};
|
|
557
|
-
var createPatchRoute = (config2) => {
|
|
558
|
-
validateMethodConfig("PATCH", config2);
|
|
559
|
-
const path6 = getRoutePath();
|
|
560
|
-
return {
|
|
561
|
-
PATCH: config2,
|
|
562
|
-
// Let TypeScript infer the proper types
|
|
563
|
-
path: path6
|
|
564
|
-
};
|
|
565
|
-
};
|
|
566
|
-
var createHeadRoute = (config2) => {
|
|
567
|
-
validateMethodConfig("HEAD", config2);
|
|
568
|
-
const path6 = getRoutePath();
|
|
569
|
-
return {
|
|
570
|
-
HEAD: config2,
|
|
571
|
-
// Let TypeScript infer the proper types
|
|
572
|
-
path: path6
|
|
573
|
-
};
|
|
574
|
-
};
|
|
575
|
-
var createOptionsRoute = (config2) => {
|
|
576
|
-
validateMethodConfig("OPTIONS", config2);
|
|
577
|
-
const path6 = getRoutePath();
|
|
578
|
-
return {
|
|
579
|
-
OPTIONS: config2,
|
|
580
|
-
// Let TypeScript infer the proper types
|
|
581
|
-
path: path6
|
|
582
|
-
};
|
|
583
|
-
};
|
|
584
|
-
function validateMethodConfig(method, config2) {
|
|
585
|
-
if (!config2.handler || typeof config2.handler !== "function") {
|
|
586
|
-
throw new Error(`Handler for method ${method} must be a function`);
|
|
587
|
-
}
|
|
588
|
-
if (config2.middleware && !Array.isArray(config2.middleware)) {
|
|
589
|
-
throw new Error(`Middleware for method ${method} must be an array`);
|
|
590
|
-
}
|
|
591
|
-
if (config2.schema) {
|
|
592
|
-
validateSchema(method, config2.schema);
|
|
593
|
-
}
|
|
594
|
-
switch (method) {
|
|
595
|
-
case "GET":
|
|
596
|
-
case "HEAD":
|
|
597
|
-
case "DELETE":
|
|
598
|
-
if (config2.schema?.body) {
|
|
599
|
-
console.warn(`Warning: ${method} requests typically don't have request bodies`);
|
|
600
|
-
}
|
|
601
|
-
break;
|
|
602
|
-
}
|
|
603
|
-
}
|
|
604
|
-
function validateSchema(method, schema) {
|
|
605
|
-
const { params, query, body, response } = schema;
|
|
606
|
-
if (params && (!params._def || typeof params.parse !== "function")) {
|
|
607
|
-
throw new Error(`Params schema for ${method} must be a valid Zod schema`);
|
|
608
|
-
}
|
|
609
|
-
if (query && (!query._def || typeof query.parse !== "function")) {
|
|
610
|
-
throw new Error(`Query schema for ${method} must be a valid Zod schema`);
|
|
611
|
-
}
|
|
612
|
-
if (body && (!body._def || typeof body.parse !== "function")) {
|
|
613
|
-
throw new Error(`Body schema for ${method} must be a valid Zod schema`);
|
|
614
|
-
}
|
|
615
|
-
if (response && (!response._def || typeof response.parse !== "function")) {
|
|
616
|
-
throw new Error(`Response schema for ${method} must be a valid Zod schema`);
|
|
617
|
-
}
|
|
618
|
-
}
|
|
619
|
-
|
|
620
|
-
// src/server/create.ts
|
|
621
|
-
var import_node_async_hooks3 = require("async_hooks");
|
|
622
|
-
var import_node_events = __toESM(require("events"), 1);
|
|
623
|
-
|
|
624
|
-
// src/server/start.ts
|
|
625
|
-
var fs2 = __toESM(require("fs"), 1);
|
|
626
|
-
var http = __toESM(require("http"), 1);
|
|
627
|
-
var http2 = __toESM(require("http2"), 1);
|
|
628
|
-
|
|
629
|
-
// src/server/dev-certificate.ts
|
|
630
|
-
var fs = __toESM(require("fs"), 1);
|
|
631
|
-
var path2 = __toESM(require("path"), 1);
|
|
632
|
-
var selfsigned = __toESM(require("selfsigned"), 1);
|
|
633
|
-
async function generateDevCertificates() {
|
|
634
|
-
const certDir = path2.join(process.cwd(), ".blaizejs", "certs");
|
|
635
|
-
const keyPath = path2.join(certDir, "dev.key");
|
|
636
|
-
const certPath = path2.join(certDir, "dev.cert");
|
|
637
|
-
if (fs.existsSync(keyPath) && fs.existsSync(certPath)) {
|
|
638
|
-
return {
|
|
639
|
-
keyFile: keyPath,
|
|
640
|
-
certFile: certPath
|
|
641
|
-
};
|
|
642
|
-
}
|
|
643
|
-
if (!fs.existsSync(certDir)) {
|
|
644
|
-
fs.mkdirSync(certDir, { recursive: true });
|
|
645
|
-
}
|
|
646
|
-
const attrs = [{ name: "commonName", value: "localhost" }];
|
|
647
|
-
const options = {
|
|
648
|
-
days: 365,
|
|
649
|
-
algorithm: "sha256",
|
|
650
|
-
keySize: 2048,
|
|
651
|
-
extensions: [
|
|
652
|
-
{ name: "basicConstraints", cA: true },
|
|
653
|
-
{
|
|
654
|
-
name: "keyUsage",
|
|
655
|
-
keyCertSign: true,
|
|
656
|
-
digitalSignature: true,
|
|
657
|
-
nonRepudiation: true,
|
|
658
|
-
keyEncipherment: true,
|
|
659
|
-
dataEncipherment: true
|
|
660
|
-
},
|
|
661
|
-
{
|
|
662
|
-
name: "extKeyUsage",
|
|
663
|
-
serverAuth: true,
|
|
664
|
-
clientAuth: true
|
|
665
|
-
},
|
|
666
|
-
{
|
|
667
|
-
name: "subjectAltName",
|
|
668
|
-
altNames: [
|
|
669
|
-
{ type: 2, value: "localhost" },
|
|
670
|
-
{ type: 7, ip: "127.0.0.1" }
|
|
671
|
-
]
|
|
672
|
-
}
|
|
673
|
-
]
|
|
674
|
-
};
|
|
675
|
-
const pems = selfsigned.generate(attrs, options);
|
|
676
|
-
fs.writeFileSync(keyPath, Buffer.from(pems.private, "utf-8"));
|
|
677
|
-
fs.writeFileSync(certPath, Buffer.from(pems.cert, "utf-8"));
|
|
678
|
-
console.log(`
|
|
679
|
-
\u{1F512} Generated self-signed certificates for development at ${certDir}
|
|
680
|
-
`);
|
|
681
|
-
return {
|
|
682
|
-
keyFile: keyPath,
|
|
683
|
-
certFile: certPath
|
|
684
|
-
};
|
|
685
|
-
}
|
|
686
|
-
|
|
687
|
-
// src/context/errors.ts
|
|
688
|
-
var ResponseSentError = class extends Error {
|
|
689
|
-
constructor(message = "\u274C Response has already been sent") {
|
|
690
|
-
super(message);
|
|
691
|
-
this.name = "ResponseSentError";
|
|
692
|
-
}
|
|
693
|
-
};
|
|
694
|
-
var ResponseSentHeaderError = class extends ResponseSentError {
|
|
695
|
-
constructor(message = "Cannot set header after response has been sent") {
|
|
696
|
-
super(message);
|
|
697
|
-
}
|
|
698
|
-
};
|
|
699
|
-
var ResponseSentContentError = class extends ResponseSentError {
|
|
700
|
-
constructor(message = "Cannot set content type after response has been sent") {
|
|
701
|
-
super(message);
|
|
702
|
-
}
|
|
703
|
-
};
|
|
704
|
-
var ParseUrlError = class extends ResponseSentError {
|
|
705
|
-
constructor(message = "Invalide URL") {
|
|
706
|
-
super(message);
|
|
707
|
-
}
|
|
708
|
-
};
|
|
709
|
-
|
|
710
|
-
// src/context/store.ts
|
|
711
|
-
var import_node_async_hooks = require("async_hooks");
|
|
712
|
-
var contextStorage = new import_node_async_hooks.AsyncLocalStorage();
|
|
713
|
-
function runWithContext(context, callback) {
|
|
714
|
-
return contextStorage.run(context, callback);
|
|
715
|
-
}
|
|
716
|
-
|
|
717
|
-
// src/upload/multipart-parser.ts
|
|
718
|
-
var import_node_crypto = require("crypto");
|
|
719
|
-
var import_node_fs = require("fs");
|
|
720
|
-
var import_node_os = require("os");
|
|
721
|
-
var import_node_path = require("path");
|
|
722
|
-
var import_node_stream = require("stream");
|
|
723
|
-
|
|
724
|
-
// src/upload/utils.ts
|
|
725
|
-
var BOUNDARY_REGEX = /boundary=([^;]+)/i;
|
|
726
|
-
var CONTENT_DISPOSITION_REGEX = /Content-Disposition:\s*form-data;\s*name="([^"]+)"(?:;[\s\r\n]*filename="([^"]*)")?/i;
|
|
727
|
-
var CONTENT_TYPE_REGEX = /Content-Type:\s*([^\r\n]+)/i;
|
|
728
|
-
var MULTIPART_REGEX = /multipart\/form-data/i;
|
|
729
|
-
function extractBoundary(contentType) {
|
|
730
|
-
const match = contentType.match(BOUNDARY_REGEX);
|
|
731
|
-
if (!match || !match[1]) return null;
|
|
732
|
-
let boundary = match[1].trim();
|
|
733
|
-
if (boundary.startsWith('"') && boundary.endsWith('"')) {
|
|
734
|
-
boundary = boundary.slice(1, -1);
|
|
735
|
-
}
|
|
736
|
-
return boundary || null;
|
|
737
|
-
}
|
|
738
|
-
function parseContentDisposition(headers) {
|
|
739
|
-
const match = headers.match(CONTENT_DISPOSITION_REGEX);
|
|
740
|
-
if (!match || !match[1]) return null;
|
|
741
|
-
return {
|
|
742
|
-
name: match[1],
|
|
743
|
-
filename: match[2] !== void 0 ? match[2] : void 0
|
|
744
|
-
};
|
|
745
|
-
}
|
|
746
|
-
function parseContentType(headers) {
|
|
747
|
-
const match = headers.match(CONTENT_TYPE_REGEX);
|
|
748
|
-
return match && match[1]?.trim() ? match[1].trim() : "application/octet-stream";
|
|
749
|
-
}
|
|
750
|
-
function isMultipartContent(contentType) {
|
|
751
|
-
return MULTIPART_REGEX.test(contentType);
|
|
752
|
-
}
|
|
753
|
-
|
|
754
|
-
// src/upload/multipart-parser.ts
|
|
755
|
-
var DEFAULT_OPTIONS = {
|
|
756
|
-
maxFileSize: 10 * 1024 * 1024,
|
|
757
|
-
// 10MB
|
|
758
|
-
maxFiles: 10,
|
|
759
|
-
maxFieldSize: 1 * 1024 * 1024,
|
|
760
|
-
// 1MB
|
|
761
|
-
allowedMimeTypes: [],
|
|
762
|
-
allowedExtensions: [],
|
|
763
|
-
strategy: "stream",
|
|
764
|
-
tempDir: (0, import_node_os.tmpdir)(),
|
|
765
|
-
computeHash: false
|
|
766
|
-
};
|
|
767
|
-
function createParserState(boundary, options = {}) {
|
|
768
|
-
return {
|
|
769
|
-
boundary: Buffer.from(`--${boundary}`),
|
|
770
|
-
options: { ...DEFAULT_OPTIONS, ...options },
|
|
771
|
-
fields: /* @__PURE__ */ new Map(),
|
|
772
|
-
files: /* @__PURE__ */ new Map(),
|
|
773
|
-
buffer: Buffer.alloc(0),
|
|
774
|
-
stage: "boundary",
|
|
775
|
-
currentHeaders: "",
|
|
776
|
-
currentField: null,
|
|
777
|
-
currentFilename: void 0,
|
|
778
|
-
currentMimetype: "application/octet-stream",
|
|
779
|
-
currentContentLength: 0,
|
|
780
|
-
fileCount: 0,
|
|
781
|
-
fieldCount: 0,
|
|
782
|
-
currentBufferChunks: [],
|
|
783
|
-
currentStream: null,
|
|
784
|
-
currentTempPath: null,
|
|
785
|
-
currentWriteStream: null,
|
|
786
|
-
streamController: null,
|
|
787
|
-
cleanupTasks: [],
|
|
788
|
-
// Track validation state
|
|
789
|
-
hasFoundValidBoundary: false,
|
|
790
|
-
hasProcessedAnyPart: false,
|
|
791
|
-
isFinished: false
|
|
792
|
-
};
|
|
793
|
-
}
|
|
794
|
-
async function processChunk(state, chunk) {
|
|
795
|
-
const newBuffer = Buffer.concat([state.buffer, chunk]);
|
|
796
|
-
let currentState = { ...state, buffer: newBuffer };
|
|
797
|
-
while (currentState.buffer.length > 0 && !currentState.isFinished) {
|
|
798
|
-
const nextState = await processCurrentStage(currentState);
|
|
799
|
-
if (nextState === currentState) break;
|
|
800
|
-
currentState = nextState;
|
|
801
|
-
}
|
|
802
|
-
return currentState;
|
|
803
|
-
}
|
|
804
|
-
async function processCurrentStage(state) {
|
|
805
|
-
switch (state.stage) {
|
|
806
|
-
case "boundary":
|
|
807
|
-
return processBoundary(state);
|
|
808
|
-
case "headers":
|
|
809
|
-
return processHeaders(state);
|
|
810
|
-
case "content":
|
|
811
|
-
return processContent(state);
|
|
812
|
-
default: {
|
|
813
|
-
const { InternalServerError: InternalServerError2 } = await Promise.resolve().then(() => (init_internal_server_error(), internal_server_error_exports));
|
|
814
|
-
throw new InternalServerError2(`Invalid parser stage`, {
|
|
815
|
-
operation: state.stage
|
|
816
|
-
});
|
|
817
|
-
}
|
|
818
|
-
}
|
|
819
|
-
}
|
|
820
|
-
function processBoundary(state) {
|
|
821
|
-
const boundaryIndex = state.buffer.indexOf(state.boundary);
|
|
822
|
-
if (boundaryIndex === -1) return state;
|
|
823
|
-
const hasFoundValidBoundary = true;
|
|
824
|
-
let buffer = state.buffer.subarray(boundaryIndex + state.boundary.length);
|
|
825
|
-
if (buffer.length >= 2 && buffer.subarray(0, 2).equals(Buffer.from("--"))) {
|
|
826
|
-
return {
|
|
827
|
-
...state,
|
|
828
|
-
buffer,
|
|
829
|
-
hasFoundValidBoundary,
|
|
830
|
-
isFinished: true,
|
|
831
|
-
stage: "boundary"
|
|
832
|
-
};
|
|
833
|
-
}
|
|
834
|
-
if (buffer.length >= 2 && buffer.subarray(0, 2).equals(Buffer.from("\r\n"))) {
|
|
835
|
-
buffer = buffer.subarray(2);
|
|
836
|
-
}
|
|
837
|
-
return {
|
|
838
|
-
...state,
|
|
839
|
-
buffer,
|
|
840
|
-
hasFoundValidBoundary,
|
|
841
|
-
stage: "headers",
|
|
842
|
-
currentHeaders: ""
|
|
843
|
-
};
|
|
844
|
-
}
|
|
845
|
-
async function processHeaders(state) {
|
|
846
|
-
const headerEnd = state.buffer.indexOf("\r\n\r\n");
|
|
847
|
-
if (headerEnd === -1) return state;
|
|
848
|
-
const headers = state.buffer.subarray(0, headerEnd).toString("utf8");
|
|
849
|
-
const buffer = state.buffer.subarray(headerEnd + 4);
|
|
850
|
-
const disposition = parseContentDisposition(headers);
|
|
851
|
-
if (!disposition) {
|
|
852
|
-
const { ValidationError: ValidationError2 } = await Promise.resolve().then(() => (init_validation_error(), validation_error_exports));
|
|
853
|
-
throw new ValidationError2("Missing or invalid Content-Disposition header");
|
|
854
|
-
}
|
|
855
|
-
const mimetype = parseContentType(headers);
|
|
856
|
-
const isFile = disposition.filename !== void 0;
|
|
857
|
-
if (isFile && state.fileCount >= state.options.maxFiles) {
|
|
858
|
-
const { PayloadTooLargeError: PayloadTooLargeError2 } = await Promise.resolve().then(() => (init_payload_too_large_error(), payload_too_large_error_exports));
|
|
859
|
-
throw new PayloadTooLargeError2("Too many files in upload", {
|
|
860
|
-
fileCount: state.fileCount + 1,
|
|
861
|
-
maxFiles: state.options.maxFiles,
|
|
862
|
-
filename: disposition.filename
|
|
863
|
-
});
|
|
864
|
-
}
|
|
865
|
-
if (isFile && state.options.allowedMimeTypes.length > 0 && !state.options.allowedMimeTypes.includes(mimetype)) {
|
|
866
|
-
const { UnsupportedMediaTypeError: UnsupportedMediaTypeError2 } = await Promise.resolve().then(() => (init_unsupported_media_type_error(), unsupported_media_type_error_exports));
|
|
867
|
-
throw new UnsupportedMediaTypeError2("File type not allowed", {
|
|
868
|
-
receivedMimeType: mimetype,
|
|
869
|
-
allowedMimeTypes: state.options.allowedMimeTypes,
|
|
870
|
-
filename: disposition.filename
|
|
871
|
-
});
|
|
872
|
-
}
|
|
873
|
-
return {
|
|
874
|
-
...state,
|
|
875
|
-
buffer,
|
|
876
|
-
stage: "content",
|
|
877
|
-
currentHeaders: headers,
|
|
878
|
-
currentField: disposition.name,
|
|
879
|
-
currentFilename: disposition.filename,
|
|
880
|
-
currentMimetype: mimetype,
|
|
881
|
-
currentContentLength: 0,
|
|
882
|
-
fileCount: isFile ? state.fileCount + 1 : state.fileCount,
|
|
883
|
-
fieldCount: isFile ? state.fieldCount : state.fieldCount + 1,
|
|
884
|
-
currentBufferChunks: []
|
|
885
|
-
};
|
|
886
|
-
}
|
|
887
|
-
async function processContent(state) {
|
|
888
|
-
const nextBoundaryIndex = state.buffer.indexOf(state.boundary);
|
|
889
|
-
let contentChunk;
|
|
890
|
-
let isComplete = false;
|
|
891
|
-
let buffer = state.buffer;
|
|
892
|
-
if (nextBoundaryIndex === -1) {
|
|
893
|
-
const safeLength = Math.max(0, state.buffer.length - state.boundary.length);
|
|
894
|
-
if (safeLength === 0) return state;
|
|
895
|
-
contentChunk = state.buffer.subarray(0, safeLength);
|
|
896
|
-
buffer = state.buffer.subarray(safeLength);
|
|
897
|
-
} else {
|
|
898
|
-
const contentEnd = Math.max(0, nextBoundaryIndex - 2);
|
|
899
|
-
contentChunk = state.buffer.subarray(0, contentEnd);
|
|
900
|
-
buffer = state.buffer.subarray(nextBoundaryIndex);
|
|
901
|
-
isComplete = true;
|
|
902
|
-
}
|
|
903
|
-
let updatedState = { ...state, buffer };
|
|
904
|
-
if (contentChunk.length > 0) {
|
|
905
|
-
updatedState = await processContentChunk(updatedState, contentChunk);
|
|
906
|
-
}
|
|
907
|
-
if (isComplete) {
|
|
908
|
-
updatedState = await finalizeCurrentPart(updatedState);
|
|
909
|
-
updatedState = {
|
|
910
|
-
...updatedState,
|
|
911
|
-
stage: "boundary",
|
|
912
|
-
hasProcessedAnyPart: true
|
|
913
|
-
// Mark that we've processed at least one part
|
|
914
|
-
};
|
|
915
|
-
}
|
|
916
|
-
return updatedState;
|
|
917
|
-
}
|
|
918
|
-
async function processContentChunk(state, chunk) {
|
|
919
|
-
const newContentLength = state.currentContentLength + chunk.length;
|
|
920
|
-
const maxSize = state.currentFilename !== void 0 ? state.options.maxFileSize : state.options.maxFieldSize;
|
|
921
|
-
if (newContentLength > maxSize) {
|
|
922
|
-
const isFile = state.currentFilename !== void 0;
|
|
923
|
-
const { PayloadTooLargeError: PayloadTooLargeError2 } = await Promise.resolve().then(() => (init_payload_too_large_error(), payload_too_large_error_exports));
|
|
924
|
-
const payloadErrorDetals = state.currentField ? {
|
|
925
|
-
contentType: isFile ? "file" : "field",
|
|
926
|
-
currentSize: newContentLength,
|
|
927
|
-
maxSize,
|
|
928
|
-
field: state.currentField,
|
|
929
|
-
filename: state.currentFilename
|
|
930
|
-
} : {
|
|
931
|
-
contentType: isFile ? "file" : "field",
|
|
932
|
-
currentSize: newContentLength,
|
|
933
|
-
maxSize,
|
|
934
|
-
filename: state.currentFilename
|
|
935
|
-
};
|
|
936
|
-
throw new PayloadTooLargeError2(
|
|
937
|
-
`${isFile ? "File" : "Field"} size exceeds limit`,
|
|
938
|
-
payloadErrorDetals
|
|
939
|
-
);
|
|
940
|
-
}
|
|
941
|
-
if (state.currentFilename !== void 0) {
|
|
942
|
-
return processFileChunk(state, chunk, newContentLength);
|
|
943
|
-
} else {
|
|
944
|
-
return {
|
|
945
|
-
...state,
|
|
946
|
-
currentContentLength: newContentLength,
|
|
947
|
-
currentBufferChunks: [...state.currentBufferChunks, chunk]
|
|
948
|
-
};
|
|
949
|
-
}
|
|
950
|
-
}
|
|
951
|
-
async function processFileChunk(state, chunk, newContentLength) {
|
|
952
|
-
switch (state.options.strategy) {
|
|
953
|
-
case "memory":
|
|
954
|
-
return {
|
|
955
|
-
...state,
|
|
956
|
-
currentContentLength: newContentLength,
|
|
957
|
-
currentBufferChunks: [...state.currentBufferChunks, chunk]
|
|
958
|
-
};
|
|
959
|
-
case "stream":
|
|
960
|
-
if (state.streamController) {
|
|
961
|
-
state.streamController.enqueue(chunk);
|
|
962
|
-
}
|
|
963
|
-
return { ...state, currentContentLength: newContentLength };
|
|
964
|
-
case "temp":
|
|
965
|
-
if (state.currentWriteStream) {
|
|
966
|
-
await writeToStream(state.currentWriteStream, chunk);
|
|
967
|
-
}
|
|
968
|
-
return { ...state, currentContentLength: newContentLength };
|
|
969
|
-
default: {
|
|
970
|
-
const { ValidationError: ValidationError2 } = await Promise.resolve().then(() => (init_validation_error(), validation_error_exports));
|
|
971
|
-
throw new ValidationError2(`Invalid parsing strategy`);
|
|
972
|
-
}
|
|
973
|
-
}
|
|
974
|
-
}
|
|
975
|
-
async function initializeFileProcessing(state) {
|
|
976
|
-
if (state.currentFilename === void 0) return state;
|
|
977
|
-
switch (state.options.strategy) {
|
|
978
|
-
case "memory":
|
|
979
|
-
return { ...state, currentBufferChunks: [] };
|
|
980
|
-
case "stream": {
|
|
981
|
-
let streamController = null;
|
|
982
|
-
const stream = new ReadableStream({
|
|
983
|
-
start: (controller) => {
|
|
984
|
-
streamController = controller;
|
|
985
|
-
}
|
|
986
|
-
});
|
|
987
|
-
return {
|
|
988
|
-
...state,
|
|
989
|
-
currentStream: stream,
|
|
990
|
-
// Type cast for Node.js compatibility
|
|
991
|
-
streamController
|
|
992
|
-
};
|
|
993
|
-
}
|
|
994
|
-
case "temp": {
|
|
995
|
-
const tempPath = (0, import_node_path.join)(state.options.tempDir, `upload-${(0, import_node_crypto.randomUUID)()}`);
|
|
996
|
-
const writeStream = (0, import_node_fs.createWriteStream)(tempPath);
|
|
997
|
-
const cleanupTask = async () => {
|
|
998
|
-
try {
|
|
999
|
-
const { unlink } = await import("fs/promises");
|
|
1000
|
-
await unlink(tempPath);
|
|
1001
|
-
} catch (error) {
|
|
1002
|
-
console.warn(`Failed to cleanup temp file: ${tempPath}`, error);
|
|
1003
|
-
}
|
|
1004
|
-
};
|
|
1005
|
-
return {
|
|
1006
|
-
...state,
|
|
1007
|
-
currentTempPath: tempPath,
|
|
1008
|
-
currentWriteStream: writeStream,
|
|
1009
|
-
cleanupTasks: [...state.cleanupTasks, cleanupTask]
|
|
1010
|
-
};
|
|
1011
|
-
}
|
|
1012
|
-
default: {
|
|
1013
|
-
const { ValidationError: ValidationError2 } = await Promise.resolve().then(() => (init_validation_error(), validation_error_exports));
|
|
1014
|
-
throw new ValidationError2(`Invalid file processing strategy`);
|
|
1015
|
-
}
|
|
1016
|
-
}
|
|
1017
|
-
}
|
|
1018
|
-
async function finalizeCurrentPart(state) {
|
|
1019
|
-
if (!state.currentField) return resetCurrentPart(state);
|
|
1020
|
-
if (state.currentFilename !== void 0) {
|
|
1021
|
-
return finalizeFile(state);
|
|
1022
|
-
} else {
|
|
1023
|
-
return finalizeField(state);
|
|
1024
|
-
}
|
|
1025
|
-
}
|
|
1026
|
-
async function finalizeFile(state) {
|
|
1027
|
-
if (!state.currentField || state.currentFilename === void 0) {
|
|
1028
|
-
return resetCurrentPart(state);
|
|
1029
|
-
}
|
|
1030
|
-
let stream;
|
|
1031
|
-
let buffer;
|
|
1032
|
-
let tempPath;
|
|
1033
|
-
switch (state.options.strategy) {
|
|
1034
|
-
case "memory":
|
|
1035
|
-
buffer = Buffer.concat(state.currentBufferChunks);
|
|
1036
|
-
stream = import_node_stream.Readable.from(buffer);
|
|
1037
|
-
break;
|
|
1038
|
-
case "stream":
|
|
1039
|
-
if (state.streamController) {
|
|
1040
|
-
state.streamController.close();
|
|
1041
|
-
}
|
|
1042
|
-
stream = state.currentStream;
|
|
1043
|
-
break;
|
|
1044
|
-
case "temp":
|
|
1045
|
-
if (state.currentWriteStream) {
|
|
1046
|
-
await closeStream(state.currentWriteStream);
|
|
1047
|
-
}
|
|
1048
|
-
tempPath = state.currentTempPath;
|
|
1049
|
-
stream = import_node_stream.Readable.from(Buffer.alloc(0));
|
|
1050
|
-
break;
|
|
1051
|
-
default: {
|
|
1052
|
-
const { ValidationError: ValidationError2 } = await Promise.resolve().then(() => (init_validation_error(), validation_error_exports));
|
|
1053
|
-
throw new ValidationError2(`Invalid file finalization strategy`);
|
|
1054
|
-
}
|
|
1055
|
-
}
|
|
1056
|
-
const file = {
|
|
1057
|
-
filename: state.currentFilename,
|
|
1058
|
-
fieldname: state.currentField,
|
|
1059
|
-
mimetype: state.currentMimetype,
|
|
1060
|
-
size: state.currentContentLength,
|
|
1061
|
-
stream,
|
|
1062
|
-
buffer,
|
|
1063
|
-
tempPath
|
|
1064
|
-
};
|
|
1065
|
-
const updatedFiles = addToCollection(state.files, state.currentField, file);
|
|
1066
|
-
return {
|
|
1067
|
-
...resetCurrentPart(state),
|
|
1068
|
-
files: updatedFiles
|
|
1069
|
-
};
|
|
1070
|
-
}
|
|
1071
|
-
function finalizeField(state) {
|
|
1072
|
-
if (!state.currentField) return resetCurrentPart(state);
|
|
1073
|
-
const value = Buffer.concat(state.currentBufferChunks).toString("utf8");
|
|
1074
|
-
const updatedFields = addToCollection(state.fields, state.currentField, value);
|
|
1075
|
-
return {
|
|
1076
|
-
...resetCurrentPart(state),
|
|
1077
|
-
fields: updatedFields
|
|
1078
|
-
};
|
|
1079
|
-
}
|
|
1080
|
-
function resetCurrentPart(state) {
|
|
1081
|
-
return {
|
|
1082
|
-
...state,
|
|
1083
|
-
currentField: null,
|
|
1084
|
-
currentFilename: void 0,
|
|
1085
|
-
currentContentLength: 0,
|
|
1086
|
-
currentBufferChunks: [],
|
|
1087
|
-
currentStream: null,
|
|
1088
|
-
streamController: null,
|
|
1089
|
-
currentTempPath: null,
|
|
1090
|
-
currentWriteStream: null
|
|
1091
|
-
};
|
|
1092
|
-
}
|
|
1093
|
-
function addToCollection(collection, key, value) {
|
|
1094
|
-
const newCollection = new Map(collection);
|
|
1095
|
-
const existing = newCollection.get(key) || [];
|
|
1096
|
-
newCollection.set(key, [...existing, value]);
|
|
1097
|
-
return newCollection;
|
|
1098
|
-
}
|
|
1099
|
-
async function finalize(state) {
|
|
1100
|
-
if (!state.hasFoundValidBoundary) {
|
|
1101
|
-
const { ValidationError: ValidationError2 } = await Promise.resolve().then(() => (init_validation_error(), validation_error_exports));
|
|
1102
|
-
throw new ValidationError2("No valid multipart boundary found");
|
|
1103
|
-
}
|
|
1104
|
-
if (state.hasFoundValidBoundary && !state.hasProcessedAnyPart) {
|
|
1105
|
-
const { ValidationError: ValidationError2 } = await Promise.resolve().then(() => (init_validation_error(), validation_error_exports));
|
|
1106
|
-
throw new ValidationError2("Empty multipart request");
|
|
1107
|
-
}
|
|
1108
|
-
const fields = {};
|
|
1109
|
-
for (const [key, values] of state.fields.entries()) {
|
|
1110
|
-
fields[key] = values.length === 1 ? values[0] : values;
|
|
1111
|
-
}
|
|
1112
|
-
const files = {};
|
|
1113
|
-
for (const [key, fileList] of state.files.entries()) {
|
|
1114
|
-
files[key] = fileList.length === 1 ? fileList[0] : fileList;
|
|
1115
|
-
}
|
|
1116
|
-
return { fields, files };
|
|
1117
|
-
}
|
|
1118
|
-
async function cleanup(state) {
|
|
1119
|
-
await Promise.allSettled(state.cleanupTasks.map((task) => task()));
|
|
1120
|
-
if (state.streamController) {
|
|
1121
|
-
state.streamController.close();
|
|
1122
|
-
}
|
|
1123
|
-
if (state.currentWriteStream) {
|
|
1124
|
-
await closeStream(state.currentWriteStream);
|
|
1125
|
-
}
|
|
1126
|
-
}
|
|
1127
|
-
async function writeToStream(stream, chunk) {
|
|
1128
|
-
return new Promise((resolve3, reject) => {
|
|
1129
|
-
stream.write(chunk, (error) => {
|
|
1130
|
-
if (error) reject(error);
|
|
1131
|
-
else resolve3();
|
|
1132
|
-
});
|
|
1133
|
-
});
|
|
1134
|
-
}
|
|
1135
|
-
async function closeStream(stream) {
|
|
1136
|
-
return new Promise((resolve3) => {
|
|
1137
|
-
stream.end(() => resolve3());
|
|
1138
|
-
});
|
|
1139
|
-
}
|
|
1140
|
-
async function parseMultipartRequest(request, options = {}) {
|
|
1141
|
-
const contentType = request.headers["content-type"] || "";
|
|
1142
|
-
const boundary = extractBoundary(contentType);
|
|
1143
|
-
if (!boundary) {
|
|
1144
|
-
const { UnsupportedMediaTypeError: UnsupportedMediaTypeError2 } = await Promise.resolve().then(() => (init_unsupported_media_type_error(), unsupported_media_type_error_exports));
|
|
1145
|
-
throw new UnsupportedMediaTypeError2("Missing boundary in multipart content-type", {
|
|
1146
|
-
receivedContentType: contentType,
|
|
1147
|
-
expectedFormat: "multipart/form-data; boundary=..."
|
|
1148
|
-
});
|
|
1149
|
-
}
|
|
1150
|
-
let state = createParserState(boundary, options);
|
|
1151
|
-
if (state.currentFilename !== void 0) {
|
|
1152
|
-
state = await initializeFileProcessing(state);
|
|
1153
|
-
}
|
|
1154
|
-
try {
|
|
1155
|
-
for await (const chunk of request) {
|
|
1156
|
-
state = await processChunk(state, chunk);
|
|
1157
|
-
}
|
|
1158
|
-
return finalize(state);
|
|
1159
|
-
} finally {
|
|
1160
|
-
await cleanup(state);
|
|
1161
|
-
}
|
|
1162
|
-
}
|
|
1163
|
-
|
|
1164
|
-
// src/context/create.ts
|
|
1165
|
-
var CONTENT_TYPE_HEADER = "Content-Type";
|
|
1166
|
-
var DEFAULT_BODY_LIMITS = {
|
|
1167
|
-
json: 512 * 1024,
|
|
1168
|
-
// 512KB - Most APIs should be much smaller
|
|
1169
|
-
form: 1024 * 1024,
|
|
1170
|
-
// 1MB - Reasonable for form submissions
|
|
1171
|
-
text: 5 * 1024 * 1024,
|
|
1172
|
-
// 5MB - Documents, logs, code files
|
|
1173
|
-
multipart: {
|
|
1174
|
-
maxFileSize: 50 * 1024 * 1024,
|
|
1175
|
-
// 50MB per file
|
|
1176
|
-
maxTotalSize: 100 * 1024 * 1024,
|
|
1177
|
-
// 100MB total request
|
|
1178
|
-
maxFiles: 10,
|
|
1179
|
-
maxFieldSize: 1024 * 1024
|
|
1180
|
-
// 1MB for form fields
|
|
1181
|
-
},
|
|
1182
|
-
raw: 10 * 1024 * 1024
|
|
1183
|
-
// 10MB for unknown content types
|
|
1184
|
-
};
|
|
1185
|
-
function parseRequestUrl(req) {
|
|
1186
|
-
const originalUrl = req.url || "/";
|
|
1187
|
-
const host = req.headers.host || "localhost";
|
|
1188
|
-
const protocol = req.socket && req.socket.encrypted ? "https" : "http";
|
|
1189
|
-
const fullUrl = `${protocol}://${host}${originalUrl.startsWith("/") ? "" : "/"}${originalUrl}`;
|
|
1190
|
-
try {
|
|
1191
|
-
const url = new URL(fullUrl);
|
|
1192
|
-
const path6 = url.pathname;
|
|
1193
|
-
const query = {};
|
|
1194
|
-
url.searchParams.forEach((value, key) => {
|
|
1195
|
-
if (query[key] !== void 0) {
|
|
1196
|
-
if (Array.isArray(query[key])) {
|
|
1197
|
-
query[key].push(value);
|
|
1198
|
-
} else {
|
|
1199
|
-
query[key] = [query[key], value];
|
|
1200
|
-
}
|
|
1201
|
-
} else {
|
|
1202
|
-
query[key] = value;
|
|
1203
|
-
}
|
|
1204
|
-
});
|
|
1205
|
-
return { path: path6, url, query };
|
|
1206
|
-
} catch (error) {
|
|
1207
|
-
console.warn(`Invalid URL: ${fullUrl}`, error);
|
|
1208
|
-
throw new ParseUrlError(`Invalid URL: ${fullUrl}`);
|
|
1209
|
-
}
|
|
1210
|
-
}
|
|
1211
|
-
function isHttp2Request(req) {
|
|
1212
|
-
return "stream" in req || "httpVersionMajor" in req && req.httpVersionMajor === 2;
|
|
1213
|
-
}
|
|
1214
|
-
function getProtocol(req) {
|
|
1215
|
-
const encrypted = req.socket && req.socket.encrypted;
|
|
1216
|
-
const forwardedProto = req.headers["x-forwarded-proto"];
|
|
1217
|
-
if (forwardedProto) {
|
|
1218
|
-
if (Array.isArray(forwardedProto)) {
|
|
1219
|
-
return forwardedProto[0]?.split(",")[0]?.trim() || "http";
|
|
1220
|
-
} else {
|
|
1221
|
-
return forwardedProto.split(",")[0]?.trim() || "http";
|
|
1222
|
-
}
|
|
1223
|
-
}
|
|
1224
|
-
return encrypted ? "https" : "http";
|
|
1225
|
-
}
|
|
1226
|
-
async function createContext(req, res, options = {}) {
|
|
1227
|
-
const { path: path6, url, query } = parseRequestUrl(req);
|
|
1228
|
-
const method = req.method || "GET";
|
|
1229
|
-
const isHttp2 = isHttp2Request(req);
|
|
1230
|
-
const protocol = getProtocol(req);
|
|
1231
|
-
const params = {};
|
|
1232
|
-
const state = { ...options.initialState || {} };
|
|
1233
|
-
const responseState = { sent: false };
|
|
1234
|
-
const ctx = {
|
|
1235
|
-
request: createRequestObject(req, {
|
|
1236
|
-
path: path6,
|
|
1237
|
-
url,
|
|
1238
|
-
query,
|
|
1239
|
-
params,
|
|
1240
|
-
method,
|
|
1241
|
-
isHttp2,
|
|
1242
|
-
protocol
|
|
1243
|
-
}),
|
|
1244
|
-
response: {},
|
|
1245
|
-
state
|
|
1246
|
-
};
|
|
1247
|
-
ctx.response = createResponseObject(res, responseState, ctx);
|
|
1248
|
-
if (options.parseBody) {
|
|
1249
|
-
await parseBodyIfNeeded(req, ctx, options);
|
|
1250
|
-
}
|
|
1251
|
-
return ctx;
|
|
1252
|
-
}
|
|
1253
|
-
function createRequestObject(req, info) {
|
|
1254
|
-
return {
|
|
1255
|
-
raw: req,
|
|
1256
|
-
...info,
|
|
1257
|
-
header: createRequestHeaderGetter(req),
|
|
1258
|
-
headers: createRequestHeadersGetter(req),
|
|
1259
|
-
body: void 0
|
|
1260
|
-
};
|
|
1261
|
-
}
|
|
1262
|
-
function createRequestHeaderGetter(req) {
|
|
1263
|
-
return (name) => {
|
|
1264
|
-
const value = req.headers[name.toLowerCase()];
|
|
1265
|
-
if (Array.isArray(value)) {
|
|
1266
|
-
return value.join(", ");
|
|
1267
|
-
}
|
|
1268
|
-
return value || void 0;
|
|
1269
|
-
};
|
|
1270
|
-
}
|
|
1271
|
-
function createRequestHeadersGetter(req) {
|
|
1272
|
-
const headerGetter = createRequestHeaderGetter(req);
|
|
1273
|
-
return (names) => {
|
|
1274
|
-
if (names && Array.isArray(names) && names.length > 0) {
|
|
1275
|
-
return names.reduce((acc, name) => {
|
|
1276
|
-
acc[name] = headerGetter(name);
|
|
1277
|
-
return acc;
|
|
1278
|
-
}, {});
|
|
1279
|
-
} else {
|
|
1280
|
-
return Object.entries(req.headers).reduce(
|
|
1281
|
-
(acc, [key, value]) => {
|
|
1282
|
-
acc[key] = Array.isArray(value) ? value.join(", ") : value || void 0;
|
|
1283
|
-
return acc;
|
|
1284
|
-
},
|
|
1285
|
-
{}
|
|
1286
|
-
);
|
|
1287
|
-
}
|
|
1288
|
-
};
|
|
1289
|
-
}
|
|
1290
|
-
function createResponseObject(res, responseState, ctx) {
|
|
1291
|
-
return {
|
|
1292
|
-
raw: res,
|
|
1293
|
-
get sent() {
|
|
1294
|
-
return responseState.sent;
|
|
1295
|
-
},
|
|
1296
|
-
status: createStatusSetter(res, responseState, ctx),
|
|
1297
|
-
header: createHeaderSetter(res, responseState, ctx),
|
|
1298
|
-
headers: createHeadersSetter(res, responseState, ctx),
|
|
1299
|
-
type: createContentTypeSetter(res, responseState, ctx),
|
|
1300
|
-
json: createJsonResponder(res, responseState),
|
|
1301
|
-
text: createTextResponder(res, responseState),
|
|
1302
|
-
html: createHtmlResponder(res, responseState),
|
|
1303
|
-
redirect: createRedirectResponder(res, responseState),
|
|
1304
|
-
stream: createStreamResponder(res, responseState)
|
|
1305
|
-
};
|
|
1306
|
-
}
|
|
1307
|
-
function createStatusSetter(res, responseState, ctx) {
|
|
1308
|
-
return function statusSetter(code) {
|
|
1309
|
-
if (responseState.sent) {
|
|
1310
|
-
throw new ResponseSentError();
|
|
1311
|
-
}
|
|
1312
|
-
res.statusCode = code;
|
|
1313
|
-
return ctx.response;
|
|
1314
|
-
};
|
|
1315
|
-
}
|
|
1316
|
-
function createHeaderSetter(res, responseState, ctx) {
|
|
1317
|
-
return function headerSetter(name, value) {
|
|
1318
|
-
if (responseState.sent) {
|
|
1319
|
-
throw new ResponseSentHeaderError();
|
|
1320
|
-
}
|
|
1321
|
-
res.setHeader(name, value);
|
|
1322
|
-
return ctx.response;
|
|
1323
|
-
};
|
|
1324
|
-
}
|
|
1325
|
-
function createHeadersSetter(res, responseState, ctx) {
|
|
1326
|
-
return function headersSetter(headers) {
|
|
1327
|
-
if (responseState.sent) {
|
|
1328
|
-
throw new ResponseSentHeaderError();
|
|
1329
|
-
}
|
|
1330
|
-
for (const [name, value] of Object.entries(headers)) {
|
|
1331
|
-
res.setHeader(name, value);
|
|
1332
|
-
}
|
|
1333
|
-
return ctx.response;
|
|
1334
|
-
};
|
|
1335
|
-
}
|
|
1336
|
-
function createContentTypeSetter(res, responseState, ctx) {
|
|
1337
|
-
return function typeSetter(type) {
|
|
1338
|
-
if (responseState.sent) {
|
|
1339
|
-
throw new ResponseSentContentError();
|
|
1340
|
-
}
|
|
1341
|
-
res.setHeader(CONTENT_TYPE_HEADER, type);
|
|
1342
|
-
return ctx.response;
|
|
1343
|
-
};
|
|
1344
|
-
}
|
|
1345
|
-
function createJsonResponder(res, responseState) {
|
|
1346
|
-
return function jsonResponder(body, status) {
|
|
1347
|
-
if (responseState.sent) {
|
|
1348
|
-
throw new ResponseSentError();
|
|
1349
|
-
}
|
|
1350
|
-
if (status !== void 0) {
|
|
1351
|
-
res.statusCode = status;
|
|
1352
|
-
}
|
|
1353
|
-
res.setHeader(CONTENT_TYPE_HEADER, "application/json");
|
|
1354
|
-
res.end(JSON.stringify(body));
|
|
1355
|
-
responseState.sent = true;
|
|
1356
|
-
};
|
|
1357
|
-
}
|
|
1358
|
-
function createTextResponder(res, responseState) {
|
|
1359
|
-
return function textResponder(body, status) {
|
|
1360
|
-
if (responseState.sent) {
|
|
1361
|
-
throw new ResponseSentError();
|
|
1362
|
-
}
|
|
1363
|
-
if (status !== void 0) {
|
|
1364
|
-
res.statusCode = status;
|
|
1365
|
-
}
|
|
1366
|
-
res.setHeader(CONTENT_TYPE_HEADER, "text/plain");
|
|
1367
|
-
res.end(body);
|
|
1368
|
-
responseState.sent = true;
|
|
1369
|
-
};
|
|
1370
|
-
}
|
|
1371
|
-
function createHtmlResponder(res, responseState) {
|
|
1372
|
-
return function htmlResponder(body, status) {
|
|
1373
|
-
if (responseState.sent) {
|
|
1374
|
-
throw new ResponseSentError();
|
|
1375
|
-
}
|
|
1376
|
-
if (status !== void 0) {
|
|
1377
|
-
res.statusCode = status;
|
|
1378
|
-
}
|
|
1379
|
-
res.setHeader(CONTENT_TYPE_HEADER, "text/html");
|
|
1380
|
-
res.end(body);
|
|
1381
|
-
responseState.sent = true;
|
|
1382
|
-
};
|
|
1383
|
-
}
|
|
1384
|
-
function createRedirectResponder(res, responseState) {
|
|
1385
|
-
return function redirectResponder(url, status = 302) {
|
|
1386
|
-
if (responseState.sent) {
|
|
1387
|
-
throw new ResponseSentError();
|
|
1388
|
-
}
|
|
1389
|
-
res.statusCode = status;
|
|
1390
|
-
res.setHeader("Location", url);
|
|
1391
|
-
res.end();
|
|
1392
|
-
responseState.sent = true;
|
|
1393
|
-
};
|
|
1394
|
-
}
|
|
1395
|
-
function createStreamResponder(res, responseState) {
|
|
1396
|
-
return function streamResponder(readable, options = {}) {
|
|
1397
|
-
if (responseState.sent) {
|
|
1398
|
-
throw new ResponseSentError();
|
|
1399
|
-
}
|
|
1400
|
-
if (options.status !== void 0) {
|
|
1401
|
-
res.statusCode = options.status;
|
|
1402
|
-
}
|
|
1403
|
-
if (options.contentType) {
|
|
1404
|
-
res.setHeader(CONTENT_TYPE_HEADER, options.contentType);
|
|
1405
|
-
}
|
|
1406
|
-
if (options.headers) {
|
|
1407
|
-
for (const [name, value] of Object.entries(options.headers)) {
|
|
1408
|
-
res.setHeader(name, value);
|
|
1409
|
-
}
|
|
1410
|
-
}
|
|
1411
|
-
readable.pipe(res);
|
|
1412
|
-
readable.on("end", () => {
|
|
1413
|
-
responseState.sent = true;
|
|
1414
|
-
});
|
|
1415
|
-
readable.on("error", (err) => {
|
|
1416
|
-
console.error("Stream error:", err);
|
|
1417
|
-
if (!responseState.sent) {
|
|
1418
|
-
res.statusCode = 500;
|
|
1419
|
-
res.end("Stream error");
|
|
1420
|
-
responseState.sent = true;
|
|
1421
|
-
}
|
|
1422
|
-
});
|
|
1423
|
-
};
|
|
1424
|
-
}
|
|
1425
|
-
async function parseBodyIfNeeded(req, ctx, options = {}) {
|
|
1426
|
-
if (shouldSkipParsing(req.method)) {
|
|
1427
|
-
return;
|
|
1428
|
-
}
|
|
1429
|
-
const contentType = req.headers["content-type"] || "";
|
|
1430
|
-
const contentLength = parseInt(req.headers["content-length"] || "0", 10);
|
|
1431
|
-
if (contentLength === 0) {
|
|
1432
|
-
return;
|
|
1433
|
-
}
|
|
1434
|
-
const limits = {
|
|
1435
|
-
json: options.bodyLimits?.json ?? DEFAULT_BODY_LIMITS.json,
|
|
1436
|
-
form: options.bodyLimits?.form ?? DEFAULT_BODY_LIMITS.form,
|
|
1437
|
-
text: options.bodyLimits?.text ?? DEFAULT_BODY_LIMITS.text,
|
|
1438
|
-
raw: options.bodyLimits?.raw ?? DEFAULT_BODY_LIMITS.raw,
|
|
1439
|
-
multipart: {
|
|
1440
|
-
maxFileSize: options.bodyLimits?.multipart?.maxFileSize ?? DEFAULT_BODY_LIMITS.multipart.maxFileSize,
|
|
1441
|
-
maxFiles: options.bodyLimits?.multipart?.maxFiles ?? DEFAULT_BODY_LIMITS.multipart.maxFiles,
|
|
1442
|
-
maxFieldSize: options.bodyLimits?.multipart?.maxFieldSize ?? DEFAULT_BODY_LIMITS.multipart.maxFieldSize,
|
|
1443
|
-
maxTotalSize: options.bodyLimits?.multipart?.maxTotalSize ?? DEFAULT_BODY_LIMITS.multipart.maxTotalSize
|
|
1444
|
-
}
|
|
1445
|
-
};
|
|
1446
|
-
try {
|
|
1447
|
-
if (contentType.includes("application/json")) {
|
|
1448
|
-
if (contentLength > limits.json) {
|
|
1449
|
-
throw new Error(`JSON body too large: ${contentLength} > ${limits.json} bytes`);
|
|
1450
|
-
}
|
|
1451
|
-
await parseJsonBody(req, ctx);
|
|
1452
|
-
} else if (contentType.includes("application/x-www-form-urlencoded")) {
|
|
1453
|
-
if (contentLength > limits.form) {
|
|
1454
|
-
throw new Error(`Form body too large: ${contentLength} > ${limits.form} bytes`);
|
|
1455
|
-
}
|
|
1456
|
-
await parseFormUrlEncodedBody(req, ctx);
|
|
1457
|
-
} else if (contentType.includes("text/")) {
|
|
1458
|
-
if (contentLength > limits.text) {
|
|
1459
|
-
throw new Error(`Text body too large: ${contentLength} > ${limits.text} bytes`);
|
|
1460
|
-
}
|
|
1461
|
-
await parseTextBody(req, ctx);
|
|
1462
|
-
} else if (isMultipartContent(contentType)) {
|
|
1463
|
-
await parseMultipartBody(req, ctx, limits.multipart);
|
|
1464
|
-
} else {
|
|
1465
|
-
if (contentLength > limits.raw) {
|
|
1466
|
-
throw new Error(`Request body too large: ${contentLength} > ${limits.raw} bytes`);
|
|
1467
|
-
}
|
|
1468
|
-
return;
|
|
1469
|
-
}
|
|
1470
|
-
} catch (error) {
|
|
1471
|
-
const errorType = contentType.includes("multipart") ? "multipart_parse_error" : "body_read_error";
|
|
1472
|
-
setBodyError(ctx, errorType, "Error reading request body", error);
|
|
1473
|
-
}
|
|
1474
|
-
}
|
|
1475
|
-
function shouldSkipParsing(method) {
|
|
1476
|
-
const skipMethods = ["GET", "HEAD", "OPTIONS"];
|
|
1477
|
-
return skipMethods.includes(method || "GET");
|
|
1478
|
-
}
|
|
1479
|
-
async function parseJsonBody(req, ctx) {
|
|
1480
|
-
const body = await readRequestBody(req);
|
|
1481
|
-
if (!body) {
|
|
1482
|
-
console.warn("Empty body, skipping JSON parsing");
|
|
1483
|
-
return;
|
|
1484
|
-
}
|
|
1485
|
-
if (body.trim() === "null") {
|
|
1486
|
-
console.warn('Body is the string "null"');
|
|
1487
|
-
ctx.request.body = null;
|
|
1488
|
-
return;
|
|
1489
|
-
}
|
|
1490
|
-
try {
|
|
1491
|
-
const json = JSON.parse(body);
|
|
1492
|
-
ctx.request.body = json;
|
|
1493
|
-
} catch (error) {
|
|
1494
|
-
ctx.request.body = null;
|
|
1495
|
-
setBodyError(ctx, "json_parse_error", "Invalid JSON in request body", error);
|
|
1496
|
-
}
|
|
1497
|
-
}
|
|
1498
|
-
async function parseFormUrlEncodedBody(req, ctx) {
|
|
1499
|
-
const body = await readRequestBody(req);
|
|
1500
|
-
if (!body) return;
|
|
1501
|
-
try {
|
|
1502
|
-
ctx.request.body = parseUrlEncodedData(body);
|
|
1503
|
-
} catch (error) {
|
|
1504
|
-
ctx.request.body = null;
|
|
1505
|
-
setBodyError(ctx, "form_parse_error", "Invalid form data in request body", error);
|
|
1506
|
-
}
|
|
1507
|
-
}
|
|
1508
|
-
function parseUrlEncodedData(body) {
|
|
1509
|
-
const params = new URLSearchParams(body);
|
|
1510
|
-
const formData = {};
|
|
1511
|
-
params.forEach((value, key) => {
|
|
1512
|
-
if (formData[key] !== void 0) {
|
|
1513
|
-
if (Array.isArray(formData[key])) {
|
|
1514
|
-
formData[key].push(value);
|
|
1515
|
-
} else {
|
|
1516
|
-
formData[key] = [formData[key], value];
|
|
1517
|
-
}
|
|
1518
|
-
} else {
|
|
1519
|
-
formData[key] = value;
|
|
1520
|
-
}
|
|
1521
|
-
});
|
|
1522
|
-
return formData;
|
|
1523
|
-
}
|
|
1524
|
-
async function parseTextBody(req, ctx) {
|
|
1525
|
-
const body = await readRequestBody(req);
|
|
1526
|
-
if (body) {
|
|
1527
|
-
ctx.request.body = body;
|
|
1528
|
-
}
|
|
1529
|
-
}
|
|
1530
|
-
async function parseMultipartBody(req, ctx, multipartLimits) {
|
|
1531
|
-
try {
|
|
1532
|
-
const limits = multipartLimits || DEFAULT_BODY_LIMITS.multipart;
|
|
1533
|
-
const multipartData = await parseMultipartRequest(req, {
|
|
1534
|
-
strategy: "stream",
|
|
1535
|
-
maxFileSize: limits.maxFileSize,
|
|
1536
|
-
maxFiles: limits.maxFiles,
|
|
1537
|
-
maxFieldSize: limits.maxFieldSize
|
|
1538
|
-
// Could add total size validation here
|
|
1539
|
-
});
|
|
1540
|
-
ctx.request.multipart = multipartData;
|
|
1541
|
-
ctx.request.files = multipartData.files;
|
|
1542
|
-
ctx.request.body = multipartData.fields;
|
|
1543
|
-
} catch (error) {
|
|
1544
|
-
ctx.request.body = null;
|
|
1545
|
-
setBodyError(ctx, "multipart_parse_error", "Failed to parse multipart data", error);
|
|
1546
|
-
}
|
|
1547
|
-
}
|
|
1548
|
-
function setBodyError(ctx, type, message, error) {
|
|
1549
|
-
const bodyError = { type, message, error };
|
|
1550
|
-
ctx.state._bodyError = bodyError;
|
|
1551
|
-
}
|
|
1552
|
-
async function readRequestBody(req) {
|
|
1553
|
-
return new Promise((resolve3, reject) => {
|
|
1554
|
-
const chunks = [];
|
|
1555
|
-
req.on("data", (chunk) => {
|
|
1556
|
-
chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
|
|
1557
|
-
});
|
|
1558
|
-
req.on("end", () => {
|
|
1559
|
-
resolve3(Buffer.concat(chunks).toString("utf8"));
|
|
1560
|
-
});
|
|
1561
|
-
req.on("error", (err) => {
|
|
1562
|
-
reject(err);
|
|
1563
|
-
});
|
|
1564
|
-
});
|
|
1565
|
-
}
|
|
1566
|
-
|
|
1567
|
-
// src/errors/not-found-error.ts
|
|
1568
|
-
init_errors();
|
|
1569
|
-
init_correlation();
|
|
1570
|
-
var NotFoundError = class extends BlaizeError {
|
|
1571
|
-
/**
|
|
1572
|
-
* Creates a new NotFoundError instance
|
|
1573
|
-
*
|
|
1574
|
-
* @param title - Human-readable error message
|
|
1575
|
-
* @param details - Optional context about the missing resource
|
|
1576
|
-
* @param correlationId - Optional correlation ID (uses current context if not provided)
|
|
1577
|
-
*/
|
|
1578
|
-
constructor(title, details = void 0, correlationId = void 0) {
|
|
1579
|
-
super(
|
|
1580
|
-
"NOT_FOUND" /* NOT_FOUND */,
|
|
1581
|
-
title,
|
|
1582
|
-
404,
|
|
1583
|
-
// HTTP 404 Not Found
|
|
1584
|
-
correlationId ?? getCurrentCorrelationId(),
|
|
1585
|
-
details
|
|
1586
|
-
);
|
|
1587
|
-
}
|
|
1588
|
-
};
|
|
1589
|
-
|
|
1590
|
-
// src/errors/boundary.ts
|
|
1591
|
-
init_errors();
|
|
1592
|
-
init_correlation();
|
|
1593
|
-
init_internal_server_error();
|
|
1594
|
-
function isHandledError(error) {
|
|
1595
|
-
return error instanceof BlaizeError;
|
|
1596
|
-
}
|
|
1597
|
-
function formatErrorResponse(error) {
|
|
1598
|
-
if (isHandledError(error)) {
|
|
1599
|
-
return {
|
|
1600
|
-
type: error.type,
|
|
1601
|
-
title: error.title,
|
|
1602
|
-
status: error.status,
|
|
1603
|
-
correlationId: error.correlationId,
|
|
1604
|
-
timestamp: error.timestamp.toISOString(),
|
|
1605
|
-
details: error.details
|
|
1606
|
-
};
|
|
1607
|
-
}
|
|
1608
|
-
const correlationId = generateCorrelationId();
|
|
1609
|
-
let originalMessage;
|
|
1610
|
-
if (error instanceof Error) {
|
|
1611
|
-
originalMessage = error.message;
|
|
1612
|
-
} else if (error === null || error === void 0) {
|
|
1613
|
-
originalMessage = "Unknown error occurred";
|
|
1614
|
-
} else {
|
|
1615
|
-
originalMessage = String(error);
|
|
1616
|
-
}
|
|
1617
|
-
const wrappedError = new InternalServerError(
|
|
1618
|
-
"Internal Server Error",
|
|
1619
|
-
{ originalMessage },
|
|
1620
|
-
correlationId
|
|
1621
|
-
);
|
|
1622
|
-
return {
|
|
1623
|
-
type: wrappedError.type,
|
|
1624
|
-
title: wrappedError.title,
|
|
1625
|
-
status: wrappedError.status,
|
|
1626
|
-
correlationId: wrappedError.correlationId,
|
|
1627
|
-
timestamp: wrappedError.timestamp.toISOString(),
|
|
1628
|
-
details: wrappedError.details
|
|
1629
|
-
};
|
|
1630
|
-
}
|
|
1631
|
-
function extractOrGenerateCorrelationId(headerGetter) {
|
|
1632
|
-
return headerGetter("x-correlation-id") ?? generateCorrelationId();
|
|
1633
|
-
}
|
|
1634
|
-
function setErrorResponseHeaders(headerSetter, correlationId) {
|
|
1635
|
-
headerSetter("x-correlation-id", correlationId);
|
|
1636
|
-
}
|
|
1637
|
-
|
|
1638
|
-
// src/middleware/error-boundary.ts
|
|
1639
|
-
function createErrorBoundary(options = {}) {
|
|
1640
|
-
const { debug = false } = options;
|
|
1641
|
-
const middlewareFn = async (ctx, next) => {
|
|
1642
|
-
try {
|
|
1643
|
-
await next();
|
|
1644
|
-
} catch (error) {
|
|
1645
|
-
if (ctx.response.sent) {
|
|
1646
|
-
if (debug) {
|
|
1647
|
-
console.error("Error occurred after response was sent:", error);
|
|
1648
|
-
}
|
|
1649
|
-
return;
|
|
1650
|
-
}
|
|
1651
|
-
if (debug) {
|
|
1652
|
-
console.error("Error boundary caught error:", error);
|
|
1653
|
-
}
|
|
1654
|
-
const correlationId = extractOrGenerateCorrelationId(ctx.request.header);
|
|
1655
|
-
const errorResponse = formatErrorResponse(error);
|
|
1656
|
-
errorResponse.correlationId = correlationId;
|
|
1657
|
-
setErrorResponseHeaders(ctx.response.header, correlationId);
|
|
1658
|
-
ctx.response.status(errorResponse.status).json(errorResponse);
|
|
1659
|
-
}
|
|
1660
|
-
};
|
|
1661
|
-
return {
|
|
1662
|
-
name: "ErrorBoundary",
|
|
1663
|
-
execute: middlewareFn,
|
|
1664
|
-
debug
|
|
1665
|
-
};
|
|
1666
|
-
}
|
|
1667
|
-
|
|
1668
|
-
// src/server/request-handler.ts
|
|
1669
|
-
function createRequestHandler(serverInstance) {
|
|
1670
|
-
return async (req, res) => {
|
|
1671
|
-
try {
|
|
1672
|
-
const context = await createContext(req, res, {
|
|
1673
|
-
parseBody: true
|
|
1674
|
-
// Enable automatic body parsing
|
|
1675
|
-
});
|
|
1676
|
-
const errorBoundary = createErrorBoundary();
|
|
1677
|
-
const allMiddleware = [errorBoundary, ...serverInstance.middleware];
|
|
1678
|
-
const handler = compose(allMiddleware);
|
|
1679
|
-
await runWithContext(context, async () => {
|
|
1680
|
-
await handler(context, async () => {
|
|
1681
|
-
if (!context.response.sent) {
|
|
1682
|
-
await serverInstance.router.handleRequest(context);
|
|
1683
|
-
if (!context.response.sent) {
|
|
1684
|
-
throw new NotFoundError(
|
|
1685
|
-
`Route not found: ${context.request.method} ${context.request.path}`
|
|
1686
|
-
);
|
|
1687
|
-
}
|
|
1688
|
-
}
|
|
1689
|
-
});
|
|
1690
|
-
});
|
|
1691
|
-
} catch (error) {
|
|
1692
|
-
console.error("Error creating context:", error);
|
|
1693
|
-
res.writeHead(500, { "Content-Type": "application/json" });
|
|
1694
|
-
res.end(
|
|
1695
|
-
JSON.stringify({
|
|
1696
|
-
error: "Internal Server Error",
|
|
1697
|
-
message: "Failed to process request"
|
|
1698
|
-
})
|
|
1699
|
-
);
|
|
1700
|
-
}
|
|
1701
|
-
};
|
|
1702
|
-
}
|
|
1703
|
-
|
|
1704
|
-
// src/server/start.ts
|
|
1705
|
-
async function prepareCertificates(http2Options) {
|
|
1706
|
-
if (!http2Options.enabled) {
|
|
1707
|
-
return {};
|
|
1708
|
-
}
|
|
1709
|
-
const { keyFile, certFile } = http2Options;
|
|
1710
|
-
const isDevMode = process.env.NODE_ENV === "development";
|
|
1711
|
-
const certificatesMissing = !keyFile || !certFile;
|
|
1712
|
-
if (certificatesMissing && isDevMode) {
|
|
1713
|
-
const devCerts = await generateDevCertificates();
|
|
1714
|
-
return devCerts;
|
|
1715
|
-
}
|
|
1716
|
-
if (certificatesMissing) {
|
|
1717
|
-
throw new Error(
|
|
1718
|
-
"HTTP/2 requires SSL certificates. Provide keyFile and certFile in http2 options. In development, set NODE_ENV=development to generate them automatically."
|
|
1719
|
-
);
|
|
1720
|
-
}
|
|
1721
|
-
return { keyFile, certFile };
|
|
1722
|
-
}
|
|
1723
|
-
function createServerInstance(isHttp2, certOptions) {
|
|
1724
|
-
if (!isHttp2) {
|
|
1725
|
-
return http.createServer();
|
|
1726
|
-
}
|
|
1727
|
-
const http2ServerOptions = {
|
|
1728
|
-
allowHTTP1: true
|
|
1729
|
-
// Allow fallback to HTTP/1.1
|
|
1730
|
-
};
|
|
1731
|
-
try {
|
|
1732
|
-
if (certOptions.keyFile) {
|
|
1733
|
-
http2ServerOptions.key = fs2.readFileSync(certOptions.keyFile);
|
|
1734
|
-
}
|
|
1735
|
-
if (certOptions.certFile) {
|
|
1736
|
-
http2ServerOptions.cert = fs2.readFileSync(certOptions.certFile);
|
|
1737
|
-
}
|
|
1738
|
-
} catch (err) {
|
|
1739
|
-
throw new Error(
|
|
1740
|
-
`Failed to read certificate files: ${err instanceof Error ? err.message : String(err)}`
|
|
1741
|
-
);
|
|
1742
|
-
}
|
|
1743
|
-
return http2.createSecureServer(http2ServerOptions);
|
|
1744
|
-
}
|
|
1745
|
-
function listenOnPort(server, port, host, isHttp2) {
|
|
1746
|
-
return new Promise((resolve3, reject) => {
|
|
1747
|
-
server.listen(port, host, () => {
|
|
1748
|
-
const protocol = isHttp2 ? "https" : "http";
|
|
1749
|
-
const url = `${protocol}://${host}:${port}`;
|
|
1750
|
-
console.log(`
|
|
10
|
+
"use strict";var of=Object.create;var ca=Object.defineProperty;var uf=Object.getOwnPropertyDescriptor;var lf=Object.getOwnPropertyNames;var ff=Object.getPrototypeOf,cf=Object.prototype.hasOwnProperty;var Cr=(e,t)=>()=>(e&&(t=e(e=0)),t);var H=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Or=(e,t)=>{for(var a in t)ca(e,a,{get:t[a],enumerable:!0})},us=(e,t,a,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of lf(t))!cf.call(e,n)&&n!==a&&ca(e,n,{get:()=>t[n],enumerable:!(r=uf(t,n))||r.enumerable});return e};var Ae=(e,t,a)=>(a=e!=null?of(ff(e)):{},us(t||!e||!e.__esModule?ca(a,"default",{value:e,enumerable:!0}):a,e)),df=e=>us(ca({},"__esModule",{value:!0}),e);var W=H((ug,hs)=>{"use strict";hs.exports={options:{usePureJavaScript:!1}}});var ms=H((lg,ys)=>{"use strict";var Bn={};ys.exports=Bn;var gs={};Bn.encode=function(e,t,a){if(typeof t!="string")throw new TypeError('"alphabet" must be a string.');if(a!==void 0&&typeof a!="number")throw new TypeError('"maxline" must be a number.');var r="";if(!(e instanceof Uint8Array))r=gf(e,t);else{var n=0,i=t.length,s=t.charAt(0),o=[0];for(n=0;n<e.length;++n){for(var u=0,l=e[n];u<o.length;++u)l+=o[u]<<8,o[u]=l%i,l=l/i|0;for(;l>0;)o.push(l%i),l=l/i|0}for(n=0;e[n]===0&&n<e.length-1;++n)r+=s;for(n=o.length-1;n>=0;--n)r+=t[o[n]]}if(a){var f=new RegExp(".{1,"+a+"}","g");r=r.match(f).join(`\r
|
|
11
|
+
`)}return r};Bn.decode=function(e,t){if(typeof e!="string")throw new TypeError('"input" must be a string.');if(typeof t!="string")throw new TypeError('"alphabet" must be a string.');var a=gs[t];if(!a){a=gs[t]=[];for(var r=0;r<t.length;++r)a[t.charCodeAt(r)]=r}e=e.replace(/\s/g,"");for(var n=t.length,i=t.charAt(0),s=[0],r=0;r<e.length;r++){var o=a[e.charCodeAt(r)];if(o===void 0)return;for(var u=0,l=o;u<s.length;++u)l+=s[u]*n,s[u]=l&255,l>>=8;for(;l>0;)s.push(l&255),l>>=8}for(var f=0;e[f]===i&&f<e.length-1;++f)s.push(0);return typeof Buffer<"u"?Buffer.from(s.reverse()):new Uint8Array(s.reverse())};function gf(e,t){var a=0,r=t.length,n=t.charAt(0),i=[0];for(a=0;a<e.length();++a){for(var s=0,o=e.at(a);s<i.length;++s)o+=i[s]<<8,i[s]=o%r,o=o/r|0;for(;o>0;)i.push(o%r),o=o/r|0}var u="";for(a=0;e.at(a)===0&&a<e.length()-1;++a)u+=n;for(a=i.length-1;a>=0;--a)u+=t[i[a]];return u}});var re=H((fg,xs)=>{"use strict";var vs=W(),Es=ms(),S=xs.exports=vs.util=vs.util||{};(function(){if(typeof process<"u"&&process.nextTick&&!process.browser){S.nextTick=process.nextTick,typeof setImmediate=="function"?S.setImmediate=setImmediate:S.setImmediate=S.nextTick;return}if(typeof setImmediate=="function"){S.setImmediate=function(){return setImmediate.apply(void 0,arguments)},S.nextTick=function(o){return setImmediate(o)};return}if(S.setImmediate=function(o){setTimeout(o,0)},typeof window<"u"&&typeof window.postMessage=="function"){let o=function(u){if(u.source===window&&u.data===e){u.stopPropagation();var l=t.slice();t.length=0,l.forEach(function(f){f()})}};var s=o,e="forge.setImmediate",t=[];S.setImmediate=function(u){t.push(u),t.length===1&&window.postMessage(e,"*")},window.addEventListener("message",o,!0)}if(typeof MutationObserver<"u"){var a=Date.now(),r=!0,n=document.createElement("div"),t=[];new MutationObserver(function(){var u=t.slice();t.length=0,u.forEach(function(l){l()})}).observe(n,{attributes:!0});var i=S.setImmediate;S.setImmediate=function(u){Date.now()-a>15?(a=Date.now(),i(u)):(t.push(u),t.length===1&&n.setAttribute("a",r=!r))}}S.nextTick=S.setImmediate})();S.isNodejs=typeof process<"u"&&process.versions&&process.versions.node;S.globalScope=function(){return S.isNodejs?global:typeof self>"u"?window:self}();S.isArray=Array.isArray||function(e){return Object.prototype.toString.call(e)==="[object Array]"};S.isArrayBuffer=function(e){return typeof ArrayBuffer<"u"&&e instanceof ArrayBuffer};S.isArrayBufferView=function(e){return e&&S.isArrayBuffer(e.buffer)&&e.byteLength!==void 0};function Vr(e){if(!(e===8||e===16||e===24||e===32))throw new Error("Only 8, 16, 24, or 32 bits supported: "+e)}S.ByteBuffer=Rn;function Rn(e){if(this.data="",this.read=0,typeof e=="string")this.data=e;else if(S.isArrayBuffer(e)||S.isArrayBufferView(e))if(typeof Buffer<"u"&&e instanceof Buffer)this.data=e.toString("binary");else{var t=new Uint8Array(e);try{this.data=String.fromCharCode.apply(null,t)}catch{for(var a=0;a<t.length;++a)this.putByte(t[a])}}else(e instanceof Rn||typeof e=="object"&&typeof e.data=="string"&&typeof e.read=="number")&&(this.data=e.data,this.read=e.read);this._constructedStringLength=0}S.ByteStringBuffer=Rn;var yf=4096;S.ByteStringBuffer.prototype._optimizeConstructedString=function(e){this._constructedStringLength+=e,this._constructedStringLength>yf&&(this.data.substr(0,1),this._constructedStringLength=0)};S.ByteStringBuffer.prototype.length=function(){return this.data.length-this.read};S.ByteStringBuffer.prototype.isEmpty=function(){return this.length()<=0};S.ByteStringBuffer.prototype.putByte=function(e){return this.putBytes(String.fromCharCode(e))};S.ByteStringBuffer.prototype.fillWithByte=function(e,t){e=String.fromCharCode(e);for(var a=this.data;t>0;)t&1&&(a+=e),t>>>=1,t>0&&(e+=e);return this.data=a,this._optimizeConstructedString(t),this};S.ByteStringBuffer.prototype.putBytes=function(e){return this.data+=e,this._optimizeConstructedString(e.length),this};S.ByteStringBuffer.prototype.putString=function(e){return this.putBytes(S.encodeUtf8(e))};S.ByteStringBuffer.prototype.putInt16=function(e){return this.putBytes(String.fromCharCode(e>>8&255)+String.fromCharCode(e&255))};S.ByteStringBuffer.prototype.putInt24=function(e){return this.putBytes(String.fromCharCode(e>>16&255)+String.fromCharCode(e>>8&255)+String.fromCharCode(e&255))};S.ByteStringBuffer.prototype.putInt32=function(e){return this.putBytes(String.fromCharCode(e>>24&255)+String.fromCharCode(e>>16&255)+String.fromCharCode(e>>8&255)+String.fromCharCode(e&255))};S.ByteStringBuffer.prototype.putInt16Le=function(e){return this.putBytes(String.fromCharCode(e&255)+String.fromCharCode(e>>8&255))};S.ByteStringBuffer.prototype.putInt24Le=function(e){return this.putBytes(String.fromCharCode(e&255)+String.fromCharCode(e>>8&255)+String.fromCharCode(e>>16&255))};S.ByteStringBuffer.prototype.putInt32Le=function(e){return this.putBytes(String.fromCharCode(e&255)+String.fromCharCode(e>>8&255)+String.fromCharCode(e>>16&255)+String.fromCharCode(e>>24&255))};S.ByteStringBuffer.prototype.putInt=function(e,t){Vr(t);var a="";do t-=8,a+=String.fromCharCode(e>>t&255);while(t>0);return this.putBytes(a)};S.ByteStringBuffer.prototype.putSignedInt=function(e,t){return e<0&&(e+=2<<t-1),this.putInt(e,t)};S.ByteStringBuffer.prototype.putBuffer=function(e){return this.putBytes(e.getBytes())};S.ByteStringBuffer.prototype.getByte=function(){return this.data.charCodeAt(this.read++)};S.ByteStringBuffer.prototype.getInt16=function(){var e=this.data.charCodeAt(this.read)<<8^this.data.charCodeAt(this.read+1);return this.read+=2,e};S.ByteStringBuffer.prototype.getInt24=function(){var e=this.data.charCodeAt(this.read)<<16^this.data.charCodeAt(this.read+1)<<8^this.data.charCodeAt(this.read+2);return this.read+=3,e};S.ByteStringBuffer.prototype.getInt32=function(){var e=this.data.charCodeAt(this.read)<<24^this.data.charCodeAt(this.read+1)<<16^this.data.charCodeAt(this.read+2)<<8^this.data.charCodeAt(this.read+3);return this.read+=4,e};S.ByteStringBuffer.prototype.getInt16Le=function(){var e=this.data.charCodeAt(this.read)^this.data.charCodeAt(this.read+1)<<8;return this.read+=2,e};S.ByteStringBuffer.prototype.getInt24Le=function(){var e=this.data.charCodeAt(this.read)^this.data.charCodeAt(this.read+1)<<8^this.data.charCodeAt(this.read+2)<<16;return this.read+=3,e};S.ByteStringBuffer.prototype.getInt32Le=function(){var e=this.data.charCodeAt(this.read)^this.data.charCodeAt(this.read+1)<<8^this.data.charCodeAt(this.read+2)<<16^this.data.charCodeAt(this.read+3)<<24;return this.read+=4,e};S.ByteStringBuffer.prototype.getInt=function(e){Vr(e);var t=0;do t=(t<<8)+this.data.charCodeAt(this.read++),e-=8;while(e>0);return t};S.ByteStringBuffer.prototype.getSignedInt=function(e){var t=this.getInt(e),a=2<<e-2;return t>=a&&(t-=a<<1),t};S.ByteStringBuffer.prototype.getBytes=function(e){var t;return e?(e=Math.min(this.length(),e),t=this.data.slice(this.read,this.read+e),this.read+=e):e===0?t="":(t=this.read===0?this.data:this.data.slice(this.read),this.clear()),t};S.ByteStringBuffer.prototype.bytes=function(e){return typeof e>"u"?this.data.slice(this.read):this.data.slice(this.read,this.read+e)};S.ByteStringBuffer.prototype.at=function(e){return this.data.charCodeAt(this.read+e)};S.ByteStringBuffer.prototype.setAt=function(e,t){return this.data=this.data.substr(0,this.read+e)+String.fromCharCode(t)+this.data.substr(this.read+e+1),this};S.ByteStringBuffer.prototype.last=function(){return this.data.charCodeAt(this.data.length-1)};S.ByteStringBuffer.prototype.copy=function(){var e=S.createBuffer(this.data);return e.read=this.read,e};S.ByteStringBuffer.prototype.compact=function(){return this.read>0&&(this.data=this.data.slice(this.read),this.read=0),this};S.ByteStringBuffer.prototype.clear=function(){return this.data="",this.read=0,this};S.ByteStringBuffer.prototype.truncate=function(e){var t=Math.max(0,this.length()-e);return this.data=this.data.substr(this.read,t),this.read=0,this};S.ByteStringBuffer.prototype.toHex=function(){for(var e="",t=this.read;t<this.data.length;++t){var a=this.data.charCodeAt(t);a<16&&(e+="0"),e+=a.toString(16)}return e};S.ByteStringBuffer.prototype.toString=function(){return S.decodeUtf8(this.bytes())};function mf(e,t){t=t||{},this.read=t.readOffset||0,this.growSize=t.growSize||1024;var a=S.isArrayBuffer(e),r=S.isArrayBufferView(e);if(a||r){a?this.data=new DataView(e):this.data=new DataView(e.buffer,e.byteOffset,e.byteLength),this.write="writeOffset"in t?t.writeOffset:this.data.byteLength;return}this.data=new DataView(new ArrayBuffer(0)),this.write=0,e!=null&&this.putBytes(e),"writeOffset"in t&&(this.write=t.writeOffset)}S.DataBuffer=mf;S.DataBuffer.prototype.length=function(){return this.write-this.read};S.DataBuffer.prototype.isEmpty=function(){return this.length()<=0};S.DataBuffer.prototype.accommodate=function(e,t){if(this.length()>=e)return this;t=Math.max(t||this.growSize,e);var a=new Uint8Array(this.data.buffer,this.data.byteOffset,this.data.byteLength),r=new Uint8Array(this.length()+t);return r.set(a),this.data=new DataView(r.buffer),this};S.DataBuffer.prototype.putByte=function(e){return this.accommodate(1),this.data.setUint8(this.write++,e),this};S.DataBuffer.prototype.fillWithByte=function(e,t){this.accommodate(t);for(var a=0;a<t;++a)this.data.setUint8(e);return this};S.DataBuffer.prototype.putBytes=function(e,t){if(S.isArrayBufferView(e)){var a=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),r=a.byteLength-a.byteOffset;this.accommodate(r);var n=new Uint8Array(this.data.buffer,this.write);return n.set(a),this.write+=r,this}if(S.isArrayBuffer(e)){var a=new Uint8Array(e);this.accommodate(a.byteLength);var n=new Uint8Array(this.data.buffer);return n.set(a,this.write),this.write+=a.byteLength,this}if(e instanceof S.DataBuffer||typeof e=="object"&&typeof e.read=="number"&&typeof e.write=="number"&&S.isArrayBufferView(e.data)){var a=new Uint8Array(e.data.byteLength,e.read,e.length());this.accommodate(a.byteLength);var n=new Uint8Array(e.data.byteLength,this.write);return n.set(a),this.write+=a.byteLength,this}if(e instanceof S.ByteStringBuffer&&(e=e.data,t="binary"),t=t||"binary",typeof e=="string"){var i;if(t==="hex")return this.accommodate(Math.ceil(e.length/2)),i=new Uint8Array(this.data.buffer,this.write),this.write+=S.binary.hex.decode(e,i,this.write),this;if(t==="base64")return this.accommodate(Math.ceil(e.length/4)*3),i=new Uint8Array(this.data.buffer,this.write),this.write+=S.binary.base64.decode(e,i,this.write),this;if(t==="utf8"&&(e=S.encodeUtf8(e),t="binary"),t==="binary"||t==="raw")return this.accommodate(e.length),i=new Uint8Array(this.data.buffer,this.write),this.write+=S.binary.raw.decode(i),this;if(t==="utf16")return this.accommodate(e.length*2),i=new Uint16Array(this.data.buffer,this.write),this.write+=S.text.utf16.encode(i),this;throw new Error("Invalid encoding: "+t)}throw Error("Invalid parameter: "+e)};S.DataBuffer.prototype.putBuffer=function(e){return this.putBytes(e),e.clear(),this};S.DataBuffer.prototype.putString=function(e){return this.putBytes(e,"utf16")};S.DataBuffer.prototype.putInt16=function(e){return this.accommodate(2),this.data.setInt16(this.write,e),this.write+=2,this};S.DataBuffer.prototype.putInt24=function(e){return this.accommodate(3),this.data.setInt16(this.write,e>>8&65535),this.data.setInt8(this.write,e>>16&255),this.write+=3,this};S.DataBuffer.prototype.putInt32=function(e){return this.accommodate(4),this.data.setInt32(this.write,e),this.write+=4,this};S.DataBuffer.prototype.putInt16Le=function(e){return this.accommodate(2),this.data.setInt16(this.write,e,!0),this.write+=2,this};S.DataBuffer.prototype.putInt24Le=function(e){return this.accommodate(3),this.data.setInt8(this.write,e>>16&255),this.data.setInt16(this.write,e>>8&65535,!0),this.write+=3,this};S.DataBuffer.prototype.putInt32Le=function(e){return this.accommodate(4),this.data.setInt32(this.write,e,!0),this.write+=4,this};S.DataBuffer.prototype.putInt=function(e,t){Vr(t),this.accommodate(t/8);do t-=8,this.data.setInt8(this.write++,e>>t&255);while(t>0);return this};S.DataBuffer.prototype.putSignedInt=function(e,t){return Vr(t),this.accommodate(t/8),e<0&&(e+=2<<t-1),this.putInt(e,t)};S.DataBuffer.prototype.getByte=function(){return this.data.getInt8(this.read++)};S.DataBuffer.prototype.getInt16=function(){var e=this.data.getInt16(this.read);return this.read+=2,e};S.DataBuffer.prototype.getInt24=function(){var e=this.data.getInt16(this.read)<<8^this.data.getInt8(this.read+2);return this.read+=3,e};S.DataBuffer.prototype.getInt32=function(){var e=this.data.getInt32(this.read);return this.read+=4,e};S.DataBuffer.prototype.getInt16Le=function(){var e=this.data.getInt16(this.read,!0);return this.read+=2,e};S.DataBuffer.prototype.getInt24Le=function(){var e=this.data.getInt8(this.read)^this.data.getInt16(this.read+1,!0)<<8;return this.read+=3,e};S.DataBuffer.prototype.getInt32Le=function(){var e=this.data.getInt32(this.read,!0);return this.read+=4,e};S.DataBuffer.prototype.getInt=function(e){Vr(e);var t=0;do t=(t<<8)+this.data.getInt8(this.read++),e-=8;while(e>0);return t};S.DataBuffer.prototype.getSignedInt=function(e){var t=this.getInt(e),a=2<<e-2;return t>=a&&(t-=a<<1),t};S.DataBuffer.prototype.getBytes=function(e){var t;return e?(e=Math.min(this.length(),e),t=this.data.slice(this.read,this.read+e),this.read+=e):e===0?t="":(t=this.read===0?this.data:this.data.slice(this.read),this.clear()),t};S.DataBuffer.prototype.bytes=function(e){return typeof e>"u"?this.data.slice(this.read):this.data.slice(this.read,this.read+e)};S.DataBuffer.prototype.at=function(e){return this.data.getUint8(this.read+e)};S.DataBuffer.prototype.setAt=function(e,t){return this.data.setUint8(e,t),this};S.DataBuffer.prototype.last=function(){return this.data.getUint8(this.write-1)};S.DataBuffer.prototype.copy=function(){return new S.DataBuffer(this)};S.DataBuffer.prototype.compact=function(){if(this.read>0){var e=new Uint8Array(this.data.buffer,this.read),t=new Uint8Array(e.byteLength);t.set(e),this.data=new DataView(t),this.write-=this.read,this.read=0}return this};S.DataBuffer.prototype.clear=function(){return this.data=new DataView(new ArrayBuffer(0)),this.read=this.write=0,this};S.DataBuffer.prototype.truncate=function(e){return this.write=Math.max(0,this.length()-e),this.read=Math.min(this.read,this.write),this};S.DataBuffer.prototype.toHex=function(){for(var e="",t=this.read;t<this.data.byteLength;++t){var a=this.data.getUint8(t);a<16&&(e+="0"),e+=a.toString(16)}return e};S.DataBuffer.prototype.toString=function(e){var t=new Uint8Array(this.data,this.read,this.length());if(e=e||"utf8",e==="binary"||e==="raw")return S.binary.raw.encode(t);if(e==="hex")return S.binary.hex.encode(t);if(e==="base64")return S.binary.base64.encode(t);if(e==="utf8")return S.text.utf8.decode(t);if(e==="utf16")return S.text.utf16.decode(t);throw new Error("Invalid encoding: "+e)};S.createBuffer=function(e,t){return t=t||"raw",e!==void 0&&t==="utf8"&&(e=S.encodeUtf8(e)),new S.ByteBuffer(e)};S.fillString=function(e,t){for(var a="";t>0;)t&1&&(a+=e),t>>>=1,t>0&&(e+=e);return a};S.xorBytes=function(e,t,a){for(var r="",n="",i="",s=0,o=0;a>0;--a,++s)n=e.charCodeAt(s)^t.charCodeAt(s),o>=10&&(r+=i,i="",o=0),i+=String.fromCharCode(n),++o;return r+=i,r};S.hexToBytes=function(e){var t="",a=0;for(e.length&!0&&(a=1,t+=String.fromCharCode(parseInt(e[0],16)));a<e.length;a+=2)t+=String.fromCharCode(parseInt(e.substr(a,2),16));return t};S.bytesToHex=function(e){return S.createBuffer(e).toHex()};S.int32ToBytes=function(e){return String.fromCharCode(e>>24&255)+String.fromCharCode(e>>16&255)+String.fromCharCode(e>>8&255)+String.fromCharCode(e&255)};var Ht="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",zt=[62,-1,-1,-1,63,52,53,54,55,56,57,58,59,60,61,-1,-1,-1,64,-1,-1,-1,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,-1,-1,-1,-1,-1,-1,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51],Cs="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";S.encode64=function(e,t){for(var a="",r="",n,i,s,o=0;o<e.length;)n=e.charCodeAt(o++),i=e.charCodeAt(o++),s=e.charCodeAt(o++),a+=Ht.charAt(n>>2),a+=Ht.charAt((n&3)<<4|i>>4),isNaN(i)?a+="==":(a+=Ht.charAt((i&15)<<2|s>>6),a+=isNaN(s)?"=":Ht.charAt(s&63)),t&&a.length>t&&(r+=a.substr(0,t)+`\r
|
|
12
|
+
`,a=a.substr(t));return r+=a,r};S.decode64=function(e){e=e.replace(/[^A-Za-z0-9\+\/\=]/g,"");for(var t="",a,r,n,i,s=0;s<e.length;)a=zt[e.charCodeAt(s++)-43],r=zt[e.charCodeAt(s++)-43],n=zt[e.charCodeAt(s++)-43],i=zt[e.charCodeAt(s++)-43],t+=String.fromCharCode(a<<2|r>>4),n!==64&&(t+=String.fromCharCode((r&15)<<4|n>>2),i!==64&&(t+=String.fromCharCode((n&3)<<6|i)));return t};S.encodeUtf8=function(e){return unescape(encodeURIComponent(e))};S.decodeUtf8=function(e){return decodeURIComponent(escape(e))};S.binary={raw:{},hex:{},base64:{},base58:{},baseN:{encode:Es.encode,decode:Es.decode}};S.binary.raw.encode=function(e){return String.fromCharCode.apply(null,e)};S.binary.raw.decode=function(e,t,a){var r=t;r||(r=new Uint8Array(e.length)),a=a||0;for(var n=a,i=0;i<e.length;++i)r[n++]=e.charCodeAt(i);return t?n-a:r};S.binary.hex.encode=S.bytesToHex;S.binary.hex.decode=function(e,t,a){var r=t;r||(r=new Uint8Array(Math.ceil(e.length/2))),a=a||0;var n=0,i=a;for(e.length&1&&(n=1,r[i++]=parseInt(e[0],16));n<e.length;n+=2)r[i++]=parseInt(e.substr(n,2),16);return t?i-a:r};S.binary.base64.encode=function(e,t){for(var a="",r="",n,i,s,o=0;o<e.byteLength;)n=e[o++],i=e[o++],s=e[o++],a+=Ht.charAt(n>>2),a+=Ht.charAt((n&3)<<4|i>>4),isNaN(i)?a+="==":(a+=Ht.charAt((i&15)<<2|s>>6),a+=isNaN(s)?"=":Ht.charAt(s&63)),t&&a.length>t&&(r+=a.substr(0,t)+`\r
|
|
13
|
+
`,a=a.substr(t));return r+=a,r};S.binary.base64.decode=function(e,t,a){var r=t;r||(r=new Uint8Array(Math.ceil(e.length/4)*3)),e=e.replace(/[^A-Za-z0-9\+\/\=]/g,""),a=a||0;for(var n,i,s,o,u=0,l=a;u<e.length;)n=zt[e.charCodeAt(u++)-43],i=zt[e.charCodeAt(u++)-43],s=zt[e.charCodeAt(u++)-43],o=zt[e.charCodeAt(u++)-43],r[l++]=n<<2|i>>4,s!==64&&(r[l++]=(i&15)<<4|s>>2,o!==64&&(r[l++]=(s&3)<<6|o));return t?l-a:r.subarray(0,l)};S.binary.base58.encode=function(e,t){return S.binary.baseN.encode(e,Cs,t)};S.binary.base58.decode=function(e,t){return S.binary.baseN.decode(e,Cs,t)};S.text={utf8:{},utf16:{}};S.text.utf8.encode=function(e,t,a){e=S.encodeUtf8(e);var r=t;r||(r=new Uint8Array(e.length)),a=a||0;for(var n=a,i=0;i<e.length;++i)r[n++]=e.charCodeAt(i);return t?n-a:r};S.text.utf8.decode=function(e){return S.decodeUtf8(String.fromCharCode.apply(null,e))};S.text.utf16.encode=function(e,t,a){var r=t;r||(r=new Uint8Array(e.length*2));var n=new Uint16Array(r.buffer);a=a||0;for(var i=a,s=a,o=0;o<e.length;++o)n[s++]=e.charCodeAt(o),i+=2;return t?i-a:r};S.text.utf16.decode=function(e){return String.fromCharCode.apply(null,new Uint16Array(e.buffer))};S.deflate=function(e,t,a){if(t=S.decode64(e.deflate(S.encode64(t)).rval),a){var r=2,n=t.charCodeAt(1);n&32&&(r=6),t=t.substring(r,t.length-4)}return t};S.inflate=function(e,t,a){var r=e.inflate(S.encode64(t)).rval;return r===null?null:S.decode64(r)};var _n=function(e,t,a){if(!e)throw new Error("WebStorage not available.");var r;if(a===null?r=e.removeItem(t):(a=S.encode64(JSON.stringify(a)),r=e.setItem(t,a)),typeof r<"u"&&r.rval!==!0){var n=new Error(r.error.message);throw n.id=r.error.id,n.name=r.error.name,n}},Nn=function(e,t){if(!e)throw new Error("WebStorage not available.");var a=e.getItem(t);if(e.init)if(a.rval===null){if(a.error){var r=new Error(a.error.message);throw r.id=a.error.id,r.name=a.error.name,r}a=null}else a=a.rval;return a!==null&&(a=JSON.parse(S.decode64(a))),a},vf=function(e,t,a,r){var n=Nn(e,t);n===null&&(n={}),n[a]=r,_n(e,t,n)},Ef=function(e,t,a){var r=Nn(e,t);return r!==null&&(r=a in r?r[a]:null),r},Cf=function(e,t,a){var r=Nn(e,t);if(r!==null&&a in r){delete r[a];var n=!0;for(var i in r){n=!1;break}n&&(r=null),_n(e,t,r)}},xf=function(e,t){_n(e,t,null)},ya=function(e,t,a){var r=null;typeof a>"u"&&(a=["web","flash"]);var n,i=!1,s=null;for(var o in a){n=a[o];try{if(n==="flash"||n==="both"){if(t[0]===null)throw new Error("Flash local storage not available.");r=e.apply(this,t),i=n==="flash"}(n==="web"||n==="both")&&(t[0]=localStorage,r=e.apply(this,t),i=!0)}catch(u){s=u}if(i)break}if(!i)throw s;return r};S.setItem=function(e,t,a,r,n){ya(vf,arguments,n)};S.getItem=function(e,t,a,r){return ya(Ef,arguments,r)};S.removeItem=function(e,t,a,r){ya(Cf,arguments,r)};S.clearItems=function(e,t,a){ya(xf,arguments,a)};S.isEmpty=function(e){for(var t in e)if(e.hasOwnProperty(t))return!1;return!0};S.format=function(e){for(var t=/%./g,a,r,n=0,i=[],s=0;a=t.exec(e);){r=e.substring(s,t.lastIndex-2),r.length>0&&i.push(r),s=t.lastIndex;var o=a[0][1];switch(o){case"s":case"o":n<arguments.length?i.push(arguments[n+++1]):i.push("<?>");break;case"%":i.push("%");break;default:i.push("<%"+o+"?>")}}return i.push(e.substring(s)),i.join("")};S.formatNumber=function(e,t,a,r){var n=e,i=isNaN(t=Math.abs(t))?2:t,s=a===void 0?",":a,o=r===void 0?".":r,u=n<0?"-":"",l=parseInt(n=Math.abs(+n||0).toFixed(i),10)+"",f=l.length>3?l.length%3:0;return u+(f?l.substr(0,f)+o:"")+l.substr(f).replace(/(\d{3})(?=\d)/g,"$1"+o)+(i?s+Math.abs(n-l).toFixed(i).slice(2):"")};S.formatSize=function(e){return e>=1073741824?e=S.formatNumber(e/1073741824,2,".","")+" GiB":e>=1048576?e=S.formatNumber(e/1048576,2,".","")+" MiB":e>=1024?e=S.formatNumber(e/1024,0)+" KiB":e=S.formatNumber(e,0)+" bytes",e};S.bytesFromIP=function(e){return e.indexOf(".")!==-1?S.bytesFromIPv4(e):e.indexOf(":")!==-1?S.bytesFromIPv6(e):null};S.bytesFromIPv4=function(e){if(e=e.split("."),e.length!==4)return null;for(var t=S.createBuffer(),a=0;a<e.length;++a){var r=parseInt(e[a],10);if(isNaN(r))return null;t.putByte(r)}return t.getBytes()};S.bytesFromIPv6=function(e){var t=0;e=e.split(":").filter(function(s){return s.length===0&&++t,!0});for(var a=(8-e.length+t)*2,r=S.createBuffer(),n=0;n<8;++n){if(!e[n]||e[n].length===0){r.fillWithByte(0,a),a=0;continue}var i=S.hexToBytes(e[n]);i.length<2&&r.putByte(0),r.putBytes(i)}return r.getBytes()};S.bytesToIP=function(e){return e.length===4?S.bytesToIPv4(e):e.length===16?S.bytesToIPv6(e):null};S.bytesToIPv4=function(e){if(e.length!==4)return null;for(var t=[],a=0;a<e.length;++a)t.push(e.charCodeAt(a));return t.join(".")};S.bytesToIPv6=function(e){if(e.length!==16)return null;for(var t=[],a=[],r=0,n=0;n<e.length;n+=2){for(var i=S.bytesToHex(e[n]+e[n+1]);i[0]==="0"&&i!=="0";)i=i.substr(1);if(i==="0"){var s=a[a.length-1],o=t.length;!s||o!==s.end+1?a.push({start:o,end:o}):(s.end=o,s.end-s.start>a[r].end-a[r].start&&(r=a.length-1))}t.push(i)}if(a.length>0){var u=a[r];u.end-u.start>0&&(t.splice(u.start,u.end-u.start+1,""),u.start===0&&t.unshift(""),u.end===7&&t.push(""))}return t.join(":")};S.estimateCores=function(e,t){if(typeof e=="function"&&(t=e,e={}),e=e||{},"cores"in S&&!e.update)return t(null,S.cores);if(typeof navigator<"u"&&"hardwareConcurrency"in navigator&&navigator.hardwareConcurrency>0)return S.cores=navigator.hardwareConcurrency,t(null,S.cores);if(typeof Worker>"u")return S.cores=1,t(null,S.cores);if(typeof Blob>"u")return S.cores=2,t(null,S.cores);var a=URL.createObjectURL(new Blob(["(",function(){self.addEventListener("message",function(s){for(var o=Date.now(),u=o+4;Date.now()<u;);self.postMessage({st:o,et:u})})}.toString(),")()"],{type:"application/javascript"}));r([],5,16);function r(s,o,u){if(o===0){var l=Math.floor(s.reduce(function(f,c){return f+c},0)/s.length);return S.cores=Math.max(1,l),URL.revokeObjectURL(a),t(null,S.cores)}n(u,function(f,c){s.push(i(u,c)),r(s,o-1,u)})}function n(s,o){for(var u=[],l=[],f=0;f<s;++f){var c=new Worker(a);c.addEventListener("message",function(y){if(l.push(y.data),l.length===s){for(var m=0;m<s;++m)u[m].terminate();o(null,l)}}),u.push(c)}for(var f=0;f<s;++f)u[f].postMessage(f)}function i(s,o){for(var u=[],l=0;l<s;++l)for(var f=o[l],c=u[l]=[],y=0;y<s;++y)if(l!==y){var m=o[y];(f.st>m.st&&f.st<m.et||m.st>f.st&&m.st<f.et)&&c.push(y)}return u.reduce(function(h,v){return Math.max(h,v.length)},0)}}});var ma=H((cg,Ss)=>{"use strict";var Be=W();re();Ss.exports=Be.cipher=Be.cipher||{};Be.cipher.algorithms=Be.cipher.algorithms||{};Be.cipher.createCipher=function(e,t){var a=e;if(typeof a=="string"&&(a=Be.cipher.getAlgorithm(a),a&&(a=a())),!a)throw new Error("Unsupported algorithm: "+e);return new Be.cipher.BlockCipher({algorithm:a,key:t,decrypt:!1})};Be.cipher.createDecipher=function(e,t){var a=e;if(typeof a=="string"&&(a=Be.cipher.getAlgorithm(a),a&&(a=a())),!a)throw new Error("Unsupported algorithm: "+e);return new Be.cipher.BlockCipher({algorithm:a,key:t,decrypt:!0})};Be.cipher.registerAlgorithm=function(e,t){e=e.toUpperCase(),Be.cipher.algorithms[e]=t};Be.cipher.getAlgorithm=function(e){return e=e.toUpperCase(),e in Be.cipher.algorithms?Be.cipher.algorithms[e]:null};var Pn=Be.cipher.BlockCipher=function(e){this.algorithm=e.algorithm,this.mode=this.algorithm.mode,this.blockSize=this.mode.blockSize,this._finish=!1,this._input=null,this.output=null,this._op=e.decrypt?this.mode.decrypt:this.mode.encrypt,this._decrypt=e.decrypt,this.algorithm.initialize(e)};Pn.prototype.start=function(e){e=e||{};var t={};for(var a in e)t[a]=e[a];t.decrypt=this._decrypt,this._finish=!1,this._input=Be.util.createBuffer(),this.output=e.output||Be.util.createBuffer(),this.mode.start(t)};Pn.prototype.update=function(e){for(e&&this._input.putBuffer(e);!this._op.call(this.mode,this._input,this.output,this._finish)&&!this._finish;);this._input.compact()};Pn.prototype.finish=function(e){e&&(this.mode.name==="ECB"||this.mode.name==="CBC")&&(this.mode.pad=function(a){return e(this.blockSize,a,!1)},this.mode.unpad=function(a){return e(this.blockSize,a,!0)});var t={};return t.decrypt=this._decrypt,t.overflow=this._input.length()%this.blockSize,!(!this._decrypt&&this.mode.pad&&!this.mode.pad(this._input,t)||(this._finish=!0,this.update(),this._decrypt&&this.mode.unpad&&!this.mode.unpad(this.output,t))||this.mode.afterFinish&&!this.mode.afterFinish(this.output,t))}});var Ln=H((dg,Ts)=>{"use strict";var Re=W();re();Re.cipher=Re.cipher||{};var $=Ts.exports=Re.cipher.modes=Re.cipher.modes||{};$.ecb=function(e){e=e||{},this.name="ECB",this.cipher=e.cipher,this.blockSize=e.blockSize||16,this._ints=this.blockSize/4,this._inBlock=new Array(this._ints),this._outBlock=new Array(this._ints)};$.ecb.prototype.start=function(e){};$.ecb.prototype.encrypt=function(e,t,a){if(e.length()<this.blockSize&&!(a&&e.length()>0))return!0;for(var r=0;r<this._ints;++r)this._inBlock[r]=e.getInt32();this.cipher.encrypt(this._inBlock,this._outBlock);for(var r=0;r<this._ints;++r)t.putInt32(this._outBlock[r])};$.ecb.prototype.decrypt=function(e,t,a){if(e.length()<this.blockSize&&!(a&&e.length()>0))return!0;for(var r=0;r<this._ints;++r)this._inBlock[r]=e.getInt32();this.cipher.decrypt(this._inBlock,this._outBlock);for(var r=0;r<this._ints;++r)t.putInt32(this._outBlock[r])};$.ecb.prototype.pad=function(e,t){var a=e.length()===this.blockSize?this.blockSize:this.blockSize-e.length();return e.fillWithByte(a,a),!0};$.ecb.prototype.unpad=function(e,t){if(t.overflow>0)return!1;var a=e.length(),r=e.at(a-1);return r>this.blockSize<<2?!1:(e.truncate(r),!0)};$.cbc=function(e){e=e||{},this.name="CBC",this.cipher=e.cipher,this.blockSize=e.blockSize||16,this._ints=this.blockSize/4,this._inBlock=new Array(this._ints),this._outBlock=new Array(this._ints)};$.cbc.prototype.start=function(e){if(e.iv===null){if(!this._prev)throw new Error("Invalid IV parameter.");this._iv=this._prev.slice(0)}else if("iv"in e)this._iv=va(e.iv,this.blockSize),this._prev=this._iv.slice(0);else throw new Error("Invalid IV parameter.")};$.cbc.prototype.encrypt=function(e,t,a){if(e.length()<this.blockSize&&!(a&&e.length()>0))return!0;for(var r=0;r<this._ints;++r)this._inBlock[r]=this._prev[r]^e.getInt32();this.cipher.encrypt(this._inBlock,this._outBlock);for(var r=0;r<this._ints;++r)t.putInt32(this._outBlock[r]);this._prev=this._outBlock};$.cbc.prototype.decrypt=function(e,t,a){if(e.length()<this.blockSize&&!(a&&e.length()>0))return!0;for(var r=0;r<this._ints;++r)this._inBlock[r]=e.getInt32();this.cipher.decrypt(this._inBlock,this._outBlock);for(var r=0;r<this._ints;++r)t.putInt32(this._prev[r]^this._outBlock[r]);this._prev=this._inBlock.slice(0)};$.cbc.prototype.pad=function(e,t){var a=e.length()===this.blockSize?this.blockSize:this.blockSize-e.length();return e.fillWithByte(a,a),!0};$.cbc.prototype.unpad=function(e,t){if(t.overflow>0)return!1;var a=e.length(),r=e.at(a-1);return r>this.blockSize<<2?!1:(e.truncate(r),!0)};$.cfb=function(e){e=e||{},this.name="CFB",this.cipher=e.cipher,this.blockSize=e.blockSize||16,this._ints=this.blockSize/4,this._inBlock=null,this._outBlock=new Array(this._ints),this._partialBlock=new Array(this._ints),this._partialOutput=Re.util.createBuffer(),this._partialBytes=0};$.cfb.prototype.start=function(e){if(!("iv"in e))throw new Error("Invalid IV parameter.");this._iv=va(e.iv,this.blockSize),this._inBlock=this._iv.slice(0),this._partialBytes=0};$.cfb.prototype.encrypt=function(e,t,a){var r=e.length();if(r===0)return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),this._partialBytes===0&&r>=this.blockSize){for(var n=0;n<this._ints;++n)this._inBlock[n]=e.getInt32()^this._outBlock[n],t.putInt32(this._inBlock[n]);return}var i=(this.blockSize-r)%this.blockSize;i>0&&(i=this.blockSize-i),this._partialOutput.clear();for(var n=0;n<this._ints;++n)this._partialBlock[n]=e.getInt32()^this._outBlock[n],this._partialOutput.putInt32(this._partialBlock[n]);if(i>0)e.read-=this.blockSize;else for(var n=0;n<this._ints;++n)this._inBlock[n]=this._partialBlock[n];if(this._partialBytes>0&&this._partialOutput.getBytes(this._partialBytes),i>0&&!a)return t.putBytes(this._partialOutput.getBytes(i-this._partialBytes)),this._partialBytes=i,!0;t.putBytes(this._partialOutput.getBytes(r-this._partialBytes)),this._partialBytes=0};$.cfb.prototype.decrypt=function(e,t,a){var r=e.length();if(r===0)return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),this._partialBytes===0&&r>=this.blockSize){for(var n=0;n<this._ints;++n)this._inBlock[n]=e.getInt32(),t.putInt32(this._inBlock[n]^this._outBlock[n]);return}var i=(this.blockSize-r)%this.blockSize;i>0&&(i=this.blockSize-i),this._partialOutput.clear();for(var n=0;n<this._ints;++n)this._partialBlock[n]=e.getInt32(),this._partialOutput.putInt32(this._partialBlock[n]^this._outBlock[n]);if(i>0)e.read-=this.blockSize;else for(var n=0;n<this._ints;++n)this._inBlock[n]=this._partialBlock[n];if(this._partialBytes>0&&this._partialOutput.getBytes(this._partialBytes),i>0&&!a)return t.putBytes(this._partialOutput.getBytes(i-this._partialBytes)),this._partialBytes=i,!0;t.putBytes(this._partialOutput.getBytes(r-this._partialBytes)),this._partialBytes=0};$.ofb=function(e){e=e||{},this.name="OFB",this.cipher=e.cipher,this.blockSize=e.blockSize||16,this._ints=this.blockSize/4,this._inBlock=null,this._outBlock=new Array(this._ints),this._partialOutput=Re.util.createBuffer(),this._partialBytes=0};$.ofb.prototype.start=function(e){if(!("iv"in e))throw new Error("Invalid IV parameter.");this._iv=va(e.iv,this.blockSize),this._inBlock=this._iv.slice(0),this._partialBytes=0};$.ofb.prototype.encrypt=function(e,t,a){var r=e.length();if(e.length()===0)return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),this._partialBytes===0&&r>=this.blockSize){for(var n=0;n<this._ints;++n)t.putInt32(e.getInt32()^this._outBlock[n]),this._inBlock[n]=this._outBlock[n];return}var i=(this.blockSize-r)%this.blockSize;i>0&&(i=this.blockSize-i),this._partialOutput.clear();for(var n=0;n<this._ints;++n)this._partialOutput.putInt32(e.getInt32()^this._outBlock[n]);if(i>0)e.read-=this.blockSize;else for(var n=0;n<this._ints;++n)this._inBlock[n]=this._outBlock[n];if(this._partialBytes>0&&this._partialOutput.getBytes(this._partialBytes),i>0&&!a)return t.putBytes(this._partialOutput.getBytes(i-this._partialBytes)),this._partialBytes=i,!0;t.putBytes(this._partialOutput.getBytes(r-this._partialBytes)),this._partialBytes=0};$.ofb.prototype.decrypt=$.ofb.prototype.encrypt;$.ctr=function(e){e=e||{},this.name="CTR",this.cipher=e.cipher,this.blockSize=e.blockSize||16,this._ints=this.blockSize/4,this._inBlock=null,this._outBlock=new Array(this._ints),this._partialOutput=Re.util.createBuffer(),this._partialBytes=0};$.ctr.prototype.start=function(e){if(!("iv"in e))throw new Error("Invalid IV parameter.");this._iv=va(e.iv,this.blockSize),this._inBlock=this._iv.slice(0),this._partialBytes=0};$.ctr.prototype.encrypt=function(e,t,a){var r=e.length();if(r===0)return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),this._partialBytes===0&&r>=this.blockSize)for(var n=0;n<this._ints;++n)t.putInt32(e.getInt32()^this._outBlock[n]);else{var i=(this.blockSize-r)%this.blockSize;i>0&&(i=this.blockSize-i),this._partialOutput.clear();for(var n=0;n<this._ints;++n)this._partialOutput.putInt32(e.getInt32()^this._outBlock[n]);if(i>0&&(e.read-=this.blockSize),this._partialBytes>0&&this._partialOutput.getBytes(this._partialBytes),i>0&&!a)return t.putBytes(this._partialOutput.getBytes(i-this._partialBytes)),this._partialBytes=i,!0;t.putBytes(this._partialOutput.getBytes(r-this._partialBytes)),this._partialBytes=0}Ea(this._inBlock)};$.ctr.prototype.decrypt=$.ctr.prototype.encrypt;$.gcm=function(e){e=e||{},this.name="GCM",this.cipher=e.cipher,this.blockSize=e.blockSize||16,this._ints=this.blockSize/4,this._inBlock=new Array(this._ints),this._outBlock=new Array(this._ints),this._partialOutput=Re.util.createBuffer(),this._partialBytes=0,this._R=3774873600};$.gcm.prototype.start=function(e){if(!("iv"in e))throw new Error("Invalid IV parameter.");var t=Re.util.createBuffer(e.iv);this._cipherLength=0;var a;if("additionalData"in e?a=Re.util.createBuffer(e.additionalData):a=Re.util.createBuffer(),"tagLength"in e?this._tagLength=e.tagLength:this._tagLength=128,this._tag=null,e.decrypt&&(this._tag=Re.util.createBuffer(e.tag).getBytes(),this._tag.length!==this._tagLength/8))throw new Error("Authentication tag does not match tag length.");this._hashBlock=new Array(this._ints),this.tag=null,this._hashSubkey=new Array(this._ints),this.cipher.encrypt([0,0,0,0],this._hashSubkey),this.componentBits=4,this._m=this.generateHashTable(this._hashSubkey,this.componentBits);var r=t.length();if(r===12)this._j0=[t.getInt32(),t.getInt32(),t.getInt32(),1];else{for(this._j0=[0,0,0,0];t.length()>0;)this._j0=this.ghash(this._hashSubkey,this._j0,[t.getInt32(),t.getInt32(),t.getInt32(),t.getInt32()]);this._j0=this.ghash(this._hashSubkey,this._j0,[0,0].concat(Dn(r*8)))}this._inBlock=this._j0.slice(0),Ea(this._inBlock),this._partialBytes=0,a=Re.util.createBuffer(a),this._aDataLength=Dn(a.length()*8);var n=a.length()%this.blockSize;for(n&&a.fillWithByte(0,this.blockSize-n),this._s=[0,0,0,0];a.length()>0;)this._s=this.ghash(this._hashSubkey,this._s,[a.getInt32(),a.getInt32(),a.getInt32(),a.getInt32()])};$.gcm.prototype.encrypt=function(e,t,a){var r=e.length();if(r===0)return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),this._partialBytes===0&&r>=this.blockSize){for(var n=0;n<this._ints;++n)t.putInt32(this._outBlock[n]^=e.getInt32());this._cipherLength+=this.blockSize}else{var i=(this.blockSize-r)%this.blockSize;i>0&&(i=this.blockSize-i),this._partialOutput.clear();for(var n=0;n<this._ints;++n)this._partialOutput.putInt32(e.getInt32()^this._outBlock[n]);if(i<=0||a){if(a){var s=r%this.blockSize;this._cipherLength+=s,this._partialOutput.truncate(this.blockSize-s)}else this._cipherLength+=this.blockSize;for(var n=0;n<this._ints;++n)this._outBlock[n]=this._partialOutput.getInt32();this._partialOutput.read-=this.blockSize}if(this._partialBytes>0&&this._partialOutput.getBytes(this._partialBytes),i>0&&!a)return e.read-=this.blockSize,t.putBytes(this._partialOutput.getBytes(i-this._partialBytes)),this._partialBytes=i,!0;t.putBytes(this._partialOutput.getBytes(r-this._partialBytes)),this._partialBytes=0}this._s=this.ghash(this._hashSubkey,this._s,this._outBlock),Ea(this._inBlock)};$.gcm.prototype.decrypt=function(e,t,a){var r=e.length();if(r<this.blockSize&&!(a&&r>0))return!0;this.cipher.encrypt(this._inBlock,this._outBlock),Ea(this._inBlock),this._hashBlock[0]=e.getInt32(),this._hashBlock[1]=e.getInt32(),this._hashBlock[2]=e.getInt32(),this._hashBlock[3]=e.getInt32(),this._s=this.ghash(this._hashSubkey,this._s,this._hashBlock);for(var n=0;n<this._ints;++n)t.putInt32(this._outBlock[n]^this._hashBlock[n]);r<this.blockSize?this._cipherLength+=r%this.blockSize:this._cipherLength+=this.blockSize};$.gcm.prototype.afterFinish=function(e,t){var a=!0;t.decrypt&&t.overflow&&e.truncate(this.blockSize-t.overflow),this.tag=Re.util.createBuffer();var r=this._aDataLength.concat(Dn(this._cipherLength*8));this._s=this.ghash(this._hashSubkey,this._s,r);var n=[];this.cipher.encrypt(this._j0,n);for(var i=0;i<this._ints;++i)this.tag.putInt32(this._s[i]^n[i]);return this.tag.truncate(this.tag.length()%(this._tagLength/8)),t.decrypt&&this.tag.bytes()!==this._tag&&(a=!1),a};$.gcm.prototype.multiply=function(e,t){for(var a=[0,0,0,0],r=t.slice(0),n=0;n<128;++n){var i=e[n/32|0]&1<<31-n%32;i&&(a[0]^=r[0],a[1]^=r[1],a[2]^=r[2],a[3]^=r[3]),this.pow(r,r)}return a};$.gcm.prototype.pow=function(e,t){for(var a=e[3]&1,r=3;r>0;--r)t[r]=e[r]>>>1|(e[r-1]&1)<<31;t[0]=e[0]>>>1,a&&(t[0]^=this._R)};$.gcm.prototype.tableMultiply=function(e){for(var t=[0,0,0,0],a=0;a<32;++a){var r=a/8|0,n=e[r]>>>(7-a%8)*4&15,i=this._m[a][n];t[0]^=i[0],t[1]^=i[1],t[2]^=i[2],t[3]^=i[3]}return t};$.gcm.prototype.ghash=function(e,t,a){return t[0]^=a[0],t[1]^=a[1],t[2]^=a[2],t[3]^=a[3],this.tableMultiply(t)};$.gcm.prototype.generateHashTable=function(e,t){for(var a=8/t,r=4*a,n=16*a,i=new Array(n),s=0;s<n;++s){var o=[0,0,0,0],u=s/r|0,l=(r-1-s%r)*t;o[u]=1<<t-1<<l,i[s]=this.generateSubHashTable(this.multiply(o,e),t)}return i};$.gcm.prototype.generateSubHashTable=function(e,t){var a=1<<t,r=a>>>1,n=new Array(a);n[r]=e.slice(0);for(var i=r>>>1;i>0;)this.pow(n[2*i],n[i]=[]),i>>=1;for(i=2;i<r;){for(var s=1;s<i;++s){var o=n[i],u=n[s];n[i+s]=[o[0]^u[0],o[1]^u[1],o[2]^u[2],o[3]^u[3]]}i*=2}for(n[0]=[0,0,0,0],i=r+1;i<a;++i){var l=n[i^r];n[i]=[e[0]^l[0],e[1]^l[1],e[2]^l[2],e[3]^l[3]]}return n};function va(e,t){if(typeof e=="string"&&(e=Re.util.createBuffer(e)),Re.util.isArray(e)&&e.length>4){var a=e;e=Re.util.createBuffer();for(var r=0;r<a.length;++r)e.putByte(a[r])}if(e.length()<t)throw new Error("Invalid IV length; got "+e.length()+" bytes and expected "+t+" bytes.");if(!Re.util.isArray(e)){for(var n=[],i=t/4,r=0;r<i;++r)n.push(e.getInt32());e=n}return e}function Ea(e){e[e.length-1]=e[e.length-1]+1&4294967295}function Dn(e){return[e/4294967296|0,e&4294967295]}});var Gt=H((pg,As)=>{"use strict";var de=W();ma();Ln();re();As.exports=de.aes=de.aes||{};de.aes.startEncrypting=function(e,t,a,r){var n=Ca({key:e,output:a,decrypt:!1,mode:r});return n.start(t),n};de.aes.createEncryptionCipher=function(e,t){return Ca({key:e,output:null,decrypt:!1,mode:t})};de.aes.startDecrypting=function(e,t,a,r){var n=Ca({key:e,output:a,decrypt:!0,mode:r});return n.start(t),n};de.aes.createDecryptionCipher=function(e,t){return Ca({key:e,output:null,decrypt:!0,mode:t})};de.aes.Algorithm=function(e,t){Fn||Is();var a=this;a.name=e,a.mode=new t({blockSize:16,cipher:{encrypt:function(r,n){return Un(a._w,r,n,!1)},decrypt:function(r,n){return Un(a._w,r,n,!0)}}}),a._init=!1};de.aes.Algorithm.prototype.initialize=function(e){if(!this._init){var t=e.key,a;if(typeof t=="string"&&(t.length===16||t.length===24||t.length===32))t=de.util.createBuffer(t);else if(de.util.isArray(t)&&(t.length===16||t.length===24||t.length===32)){a=t,t=de.util.createBuffer();for(var r=0;r<a.length;++r)t.putByte(a[r])}if(!de.util.isArray(t)){a=t,t=[];var n=a.length();if(n===16||n===24||n===32){n=n>>>2;for(var r=0;r<n;++r)t.push(a.getInt32())}}if(!de.util.isArray(t)||!(t.length===4||t.length===6||t.length===8))throw new Error("Invalid key parameter.");var i=this.mode.name,s=["CFB","OFB","CTR","GCM"].indexOf(i)!==-1;this._w=ws(t,e.decrypt&&!s),this._init=!0}};de.aes._expandKey=function(e,t){return Fn||Is(),ws(e,t)};de.aes._updateBlock=Un;Sr("AES-ECB",de.cipher.modes.ecb);Sr("AES-CBC",de.cipher.modes.cbc);Sr("AES-CFB",de.cipher.modes.cfb);Sr("AES-OFB",de.cipher.modes.ofb);Sr("AES-CTR",de.cipher.modes.ctr);Sr("AES-GCM",de.cipher.modes.gcm);function Sr(e,t){var a=function(){return new de.aes.Algorithm(e,t)};de.cipher.registerAlgorithm(e,a)}var Fn=!1,xr=4,$e,kn,bs,or,yt;function Is(){Fn=!0,bs=[0,1,2,4,8,16,32,64,128,27,54];for(var e=new Array(256),t=0;t<128;++t)e[t]=t<<1,e[t+128]=t+128<<1^283;$e=new Array(256),kn=new Array(256),or=new Array(4),yt=new Array(4);for(var t=0;t<4;++t)or[t]=new Array(256),yt[t]=new Array(256);for(var a=0,r=0,n,i,s,o,u,l,f,t=0;t<256;++t){o=r^r<<1^r<<2^r<<3^r<<4,o=o>>8^o&255^99,$e[a]=o,kn[o]=a,u=e[o],n=e[a],i=e[n],s=e[i],l=u<<24^o<<16^o<<8^(o^u),f=(n^i^s)<<24^(a^s)<<16^(a^i^s)<<8^(a^n^s);for(var c=0;c<4;++c)or[c][a]=l,yt[c][o]=f,l=l<<24|l>>>8,f=f<<24|f>>>8;a===0?a=r=1:(a=n^e[e[e[n^s]]],r^=e[e[r]])}}function ws(e,t){for(var a=e.slice(0),r,n=1,i=a.length,s=i+6+1,o=xr*s,u=i;u<o;++u)r=a[u-1],u%i===0?(r=$e[r>>>16&255]<<24^$e[r>>>8&255]<<16^$e[r&255]<<8^$e[r>>>24]^bs[n]<<24,n++):i>6&&u%i===4&&(r=$e[r>>>24]<<24^$e[r>>>16&255]<<16^$e[r>>>8&255]<<8^$e[r&255]),a[u]=a[u-i]^r;if(t){var l,f=yt[0],c=yt[1],y=yt[2],m=yt[3],h=a.slice(0);o=a.length;for(var u=0,v=o-xr;u<o;u+=xr,v-=xr)if(u===0||u===o-xr)h[u]=a[v],h[u+1]=a[v+3],h[u+2]=a[v+2],h[u+3]=a[v+1];else for(var C=0;C<xr;++C)l=a[v+C],h[u+(3&-C)]=f[$e[l>>>24]]^c[$e[l>>>16&255]]^y[$e[l>>>8&255]]^m[$e[l&255]];a=h}return a}function Un(e,t,a,r){var n=e.length/4-1,i,s,o,u,l;r?(i=yt[0],s=yt[1],o=yt[2],u=yt[3],l=kn):(i=or[0],s=or[1],o=or[2],u=or[3],l=$e);var f,c,y,m,h,v,C;f=t[0]^e[0],c=t[r?3:1]^e[1],y=t[2]^e[2],m=t[r?1:3]^e[3];for(var T=3,I=1;I<n;++I)h=i[f>>>24]^s[c>>>16&255]^o[y>>>8&255]^u[m&255]^e[++T],v=i[c>>>24]^s[y>>>16&255]^o[m>>>8&255]^u[f&255]^e[++T],C=i[y>>>24]^s[m>>>16&255]^o[f>>>8&255]^u[c&255]^e[++T],m=i[m>>>24]^s[f>>>16&255]^o[c>>>8&255]^u[y&255]^e[++T],f=h,c=v,y=C;a[0]=l[f>>>24]<<24^l[c>>>16&255]<<16^l[y>>>8&255]<<8^l[m&255]^e[++T],a[r?3:1]=l[c>>>24]<<24^l[y>>>16&255]<<16^l[m>>>8&255]<<8^l[f&255]^e[++T],a[2]=l[y>>>24]<<24^l[m>>>16&255]<<16^l[f>>>8&255]<<8^l[c&255]^e[++T],a[r?1:3]=l[m>>>24]<<24^l[f>>>16&255]<<16^l[c>>>8&255]<<8^l[y&255]^e[++T]}function Ca(e){e=e||{};var t=(e.mode||"CBC").toUpperCase(),a="AES-"+t,r;e.decrypt?r=de.cipher.createDecipher(a,e.key):r=de.cipher.createCipher(a,e.key);var n=r.start;return r.start=function(i,s){var o=null;s instanceof de.util.ByteBuffer&&(o=s,s={}),s=s||{},s.output=o,s.iv=i,n.call(r,s)},r}});var Qt=H((hg,Bs)=>{"use strict";var Mr=W();Mr.pki=Mr.pki||{};var On=Bs.exports=Mr.pki.oids=Mr.oids=Mr.oids||{};function _(e,t){On[e]=t,On[t]=e}function ne(e,t){On[e]=t}_("1.2.840.113549.1.1.1","rsaEncryption");_("1.2.840.113549.1.1.4","md5WithRSAEncryption");_("1.2.840.113549.1.1.5","sha1WithRSAEncryption");_("1.2.840.113549.1.1.7","RSAES-OAEP");_("1.2.840.113549.1.1.8","mgf1");_("1.2.840.113549.1.1.9","pSpecified");_("1.2.840.113549.1.1.10","RSASSA-PSS");_("1.2.840.113549.1.1.11","sha256WithRSAEncryption");_("1.2.840.113549.1.1.12","sha384WithRSAEncryption");_("1.2.840.113549.1.1.13","sha512WithRSAEncryption");_("1.3.101.112","EdDSA25519");_("1.2.840.10040.4.3","dsa-with-sha1");_("1.3.14.3.2.7","desCBC");_("1.3.14.3.2.26","sha1");_("1.3.14.3.2.29","sha1WithRSASignature");_("2.16.840.1.101.3.4.2.1","sha256");_("2.16.840.1.101.3.4.2.2","sha384");_("2.16.840.1.101.3.4.2.3","sha512");_("2.16.840.1.101.3.4.2.4","sha224");_("2.16.840.1.101.3.4.2.5","sha512-224");_("2.16.840.1.101.3.4.2.6","sha512-256");_("1.2.840.113549.2.2","md2");_("1.2.840.113549.2.5","md5");_("1.2.840.113549.1.7.1","data");_("1.2.840.113549.1.7.2","signedData");_("1.2.840.113549.1.7.3","envelopedData");_("1.2.840.113549.1.7.4","signedAndEnvelopedData");_("1.2.840.113549.1.7.5","digestedData");_("1.2.840.113549.1.7.6","encryptedData");_("1.2.840.113549.1.9.1","emailAddress");_("1.2.840.113549.1.9.2","unstructuredName");_("1.2.840.113549.1.9.3","contentType");_("1.2.840.113549.1.9.4","messageDigest");_("1.2.840.113549.1.9.5","signingTime");_("1.2.840.113549.1.9.6","counterSignature");_("1.2.840.113549.1.9.7","challengePassword");_("1.2.840.113549.1.9.8","unstructuredAddress");_("1.2.840.113549.1.9.14","extensionRequest");_("1.2.840.113549.1.9.20","friendlyName");_("1.2.840.113549.1.9.21","localKeyId");_("1.2.840.113549.1.9.22.1","x509Certificate");_("1.2.840.113549.1.12.10.1.1","keyBag");_("1.2.840.113549.1.12.10.1.2","pkcs8ShroudedKeyBag");_("1.2.840.113549.1.12.10.1.3","certBag");_("1.2.840.113549.1.12.10.1.4","crlBag");_("1.2.840.113549.1.12.10.1.5","secretBag");_("1.2.840.113549.1.12.10.1.6","safeContentsBag");_("1.2.840.113549.1.5.13","pkcs5PBES2");_("1.2.840.113549.1.5.12","pkcs5PBKDF2");_("1.2.840.113549.1.12.1.1","pbeWithSHAAnd128BitRC4");_("1.2.840.113549.1.12.1.2","pbeWithSHAAnd40BitRC4");_("1.2.840.113549.1.12.1.3","pbeWithSHAAnd3-KeyTripleDES-CBC");_("1.2.840.113549.1.12.1.4","pbeWithSHAAnd2-KeyTripleDES-CBC");_("1.2.840.113549.1.12.1.5","pbeWithSHAAnd128BitRC2-CBC");_("1.2.840.113549.1.12.1.6","pbewithSHAAnd40BitRC2-CBC");_("1.2.840.113549.2.7","hmacWithSHA1");_("1.2.840.113549.2.8","hmacWithSHA224");_("1.2.840.113549.2.9","hmacWithSHA256");_("1.2.840.113549.2.10","hmacWithSHA384");_("1.2.840.113549.2.11","hmacWithSHA512");_("1.2.840.113549.3.7","des-EDE3-CBC");_("2.16.840.1.101.3.4.1.2","aes128-CBC");_("2.16.840.1.101.3.4.1.22","aes192-CBC");_("2.16.840.1.101.3.4.1.42","aes256-CBC");_("2.5.4.3","commonName");_("2.5.4.4","surname");_("2.5.4.5","serialNumber");_("2.5.4.6","countryName");_("2.5.4.7","localityName");_("2.5.4.8","stateOrProvinceName");_("2.5.4.9","streetAddress");_("2.5.4.10","organizationName");_("2.5.4.11","organizationalUnitName");_("2.5.4.12","title");_("2.5.4.13","description");_("2.5.4.15","businessCategory");_("2.5.4.17","postalCode");_("2.5.4.42","givenName");_("1.3.6.1.4.1.311.60.2.1.2","jurisdictionOfIncorporationStateOrProvinceName");_("1.3.6.1.4.1.311.60.2.1.3","jurisdictionOfIncorporationCountryName");_("2.16.840.1.113730.1.1","nsCertType");_("2.16.840.1.113730.1.13","nsComment");ne("2.5.29.1","authorityKeyIdentifier");ne("2.5.29.2","keyAttributes");ne("2.5.29.3","certificatePolicies");ne("2.5.29.4","keyUsageRestriction");ne("2.5.29.5","policyMapping");ne("2.5.29.6","subtreesConstraint");ne("2.5.29.7","subjectAltName");ne("2.5.29.8","issuerAltName");ne("2.5.29.9","subjectDirectoryAttributes");ne("2.5.29.10","basicConstraints");ne("2.5.29.11","nameConstraints");ne("2.5.29.12","policyConstraints");ne("2.5.29.13","basicConstraints");_("2.5.29.14","subjectKeyIdentifier");_("2.5.29.15","keyUsage");ne("2.5.29.16","privateKeyUsagePeriod");_("2.5.29.17","subjectAltName");_("2.5.29.18","issuerAltName");_("2.5.29.19","basicConstraints");ne("2.5.29.20","cRLNumber");ne("2.5.29.21","cRLReason");ne("2.5.29.22","expirationDate");ne("2.5.29.23","instructionCode");ne("2.5.29.24","invalidityDate");ne("2.5.29.25","cRLDistributionPoints");ne("2.5.29.26","issuingDistributionPoint");ne("2.5.29.27","deltaCRLIndicator");ne("2.5.29.28","issuingDistributionPoint");ne("2.5.29.29","certificateIssuer");ne("2.5.29.30","nameConstraints");_("2.5.29.31","cRLDistributionPoints");_("2.5.29.32","certificatePolicies");ne("2.5.29.33","policyMappings");ne("2.5.29.34","policyConstraints");_("2.5.29.35","authorityKeyIdentifier");ne("2.5.29.36","policyConstraints");_("2.5.29.37","extKeyUsage");ne("2.5.29.46","freshestCRL");ne("2.5.29.54","inhibitAnyPolicy");_("1.3.6.1.4.1.11129.2.4.2","timestampList");_("1.3.6.1.5.5.7.1.1","authorityInfoAccess");_("1.3.6.1.5.5.7.3.1","serverAuth");_("1.3.6.1.5.5.7.3.2","clientAuth");_("1.3.6.1.5.5.7.3.3","codeSigning");_("1.3.6.1.5.5.7.3.4","emailProtection");_("1.3.6.1.5.5.7.3.8","timeStamping")});var mt=H((gg,_s)=>{"use strict";var ge=W();re();Qt();var U=_s.exports=ge.asn1=ge.asn1||{};U.Class={UNIVERSAL:0,APPLICATION:64,CONTEXT_SPECIFIC:128,PRIVATE:192};U.Type={NONE:0,BOOLEAN:1,INTEGER:2,BITSTRING:3,OCTETSTRING:4,NULL:5,OID:6,ODESC:7,EXTERNAL:8,REAL:9,ENUMERATED:10,EMBEDDED:11,UTF8:12,ROID:13,SEQUENCE:16,SET:17,PRINTABLESTRING:19,IA5STRING:22,UTCTIME:23,GENERALIZEDTIME:24,BMPSTRING:30};U.create=function(e,t,a,r,n){if(ge.util.isArray(r)){for(var i=[],s=0;s<r.length;++s)r[s]!==void 0&&i.push(r[s]);r=i}var o={tagClass:e,type:t,constructed:a,composed:a||ge.util.isArray(r),value:r};return n&&"bitStringContents"in n&&(o.bitStringContents=n.bitStringContents,o.original=U.copy(o)),o};U.copy=function(e,t){var a;if(ge.util.isArray(e)){a=[];for(var r=0;r<e.length;++r)a.push(U.copy(e[r],t));return a}return typeof e=="string"?e:(a={tagClass:e.tagClass,type:e.type,constructed:e.constructed,composed:e.composed,value:U.copy(e.value,t)},t&&!t.excludeBitStringContents&&(a.bitStringContents=e.bitStringContents),a)};U.equals=function(e,t,a){if(ge.util.isArray(e)){if(!ge.util.isArray(t)||e.length!==t.length)return!1;for(var r=0;r<e.length;++r)if(!U.equals(e[r],t[r]))return!1;return!0}if(typeof e!=typeof t)return!1;if(typeof e=="string")return e===t;var n=e.tagClass===t.tagClass&&e.type===t.type&&e.constructed===t.constructed&&e.composed===t.composed&&U.equals(e.value,t.value);return a&&a.includeBitStringContents&&(n=n&&e.bitStringContents===t.bitStringContents),n};U.getBerValueLength=function(e){var t=e.getByte();if(t!==128){var a,r=t&128;return r?a=e.getInt((t&127)<<3):a=t,a}};function Kr(e,t,a){if(a>t){var r=new Error("Too few bytes to parse DER.");throw r.available=e.length(),r.remaining=t,r.requested=a,r}}var Sf=function(e,t){var a=e.getByte();if(t--,a!==128){var r,n=a&128;if(!n)r=a;else{var i=a&127;Kr(e,t,i),r=e.getInt(i<<3)}if(r<0)throw new Error("Negative length: "+r);return r}};U.fromDer=function(e,t){t===void 0&&(t={strict:!0,parseAllBytes:!0,decodeBitStrings:!0}),typeof t=="boolean"&&(t={strict:t,parseAllBytes:!0,decodeBitStrings:!0}),"strict"in t||(t.strict=!0),"parseAllBytes"in t||(t.parseAllBytes=!0),"decodeBitStrings"in t||(t.decodeBitStrings=!0),typeof e=="string"&&(e=ge.util.createBuffer(e));var a=e.length(),r=xa(e,e.length(),0,t);if(t.parseAllBytes&&e.length()!==0){var n=new Error("Unparsed DER bytes remain after ASN.1 parsing.");throw n.byteCount=a,n.remaining=e.length(),n}return r};function xa(e,t,a,r){var n;Kr(e,t,2);var i=e.getByte();t--;var s=i&192,o=i&31;n=e.length();var u=Sf(e,t);if(t-=n-e.length(),u!==void 0&&u>t){if(r.strict){var l=new Error("Too few bytes to read ASN.1 value.");throw l.available=e.length(),l.remaining=t,l.requested=u,l}u=t}var f,c,y=(i&32)===32;if(y)if(f=[],u===void 0)for(;;){if(Kr(e,t,2),e.bytes(2)==="\0\0"){e.getBytes(2),t-=2;break}n=e.length(),f.push(xa(e,t,a+1,r)),t-=n-e.length()}else for(;u>0;)n=e.length(),f.push(xa(e,u,a+1,r)),t-=n-e.length(),u-=n-e.length();if(f===void 0&&s===U.Class.UNIVERSAL&&o===U.Type.BITSTRING&&(c=e.bytes(u)),f===void 0&&r.decodeBitStrings&&s===U.Class.UNIVERSAL&&o===U.Type.BITSTRING&&u>1){var m=e.read,h=t,v=0;if(o===U.Type.BITSTRING&&(Kr(e,t,1),v=e.getByte(),t--),v===0)try{n=e.length();var C={strict:!0,decodeBitStrings:!0},T=xa(e,t,a+1,C),I=n-e.length();t-=I,o==U.Type.BITSTRING&&I++;var A=T.tagClass;I===u&&(A===U.Class.UNIVERSAL||A===U.Class.CONTEXT_SPECIFIC)&&(f=[T])}catch{}f===void 0&&(e.read=m,t=h)}if(f===void 0){if(u===void 0){if(r.strict)throw new Error("Non-constructed ASN.1 object of indefinite length.");u=t}if(o===U.Type.BMPSTRING)for(f="";u>0;u-=2)Kr(e,t,2),f+=String.fromCharCode(e.getInt16()),t-=2;else f=e.getBytes(u),t-=u}var L=c===void 0?null:{bitStringContents:c};return U.create(s,o,y,f,L)}U.toDer=function(e){var t=ge.util.createBuffer(),a=e.tagClass|e.type,r=ge.util.createBuffer(),n=!1;if("bitStringContents"in e&&(n=!0,e.original&&(n=U.equals(e,e.original))),n)r.putBytes(e.bitStringContents);else if(e.composed){e.constructed?a|=32:r.putByte(0);for(var i=0;i<e.value.length;++i)e.value[i]!==void 0&&r.putBuffer(U.toDer(e.value[i]))}else if(e.type===U.Type.BMPSTRING)for(var i=0;i<e.value.length;++i)r.putInt16(e.value.charCodeAt(i));else e.type===U.Type.INTEGER&&e.value.length>1&&(e.value.charCodeAt(0)===0&&(e.value.charCodeAt(1)&128)===0||e.value.charCodeAt(0)===255&&(e.value.charCodeAt(1)&128)===128)?r.putBytes(e.value.substr(1)):r.putBytes(e.value);if(t.putByte(a),r.length()<=127)t.putByte(r.length()&127);else{var s=r.length(),o="";do o+=String.fromCharCode(s&255),s=s>>>8;while(s>0);t.putByte(o.length|128);for(var i=o.length-1;i>=0;--i)t.putByte(o.charCodeAt(i))}return t.putBuffer(r),t};U.oidToDer=function(e){var t=e.split("."),a=ge.util.createBuffer();a.putByte(40*parseInt(t[0],10)+parseInt(t[1],10));for(var r,n,i,s,o=2;o<t.length;++o){r=!0,n=[],i=parseInt(t[o],10);do s=i&127,i=i>>>7,r||(s|=128),n.push(s),r=!1;while(i>0);for(var u=n.length-1;u>=0;--u)a.putByte(n[u])}return a};U.derToOid=function(e){var t;typeof e=="string"&&(e=ge.util.createBuffer(e));var a=e.getByte();t=Math.floor(a/40)+"."+a%40;for(var r=0;e.length()>0;)a=e.getByte(),r=r<<7,a&128?r+=a&127:(t+="."+(r+a),r=0);return t};U.utcTimeToDate=function(e){var t=new Date,a=parseInt(e.substr(0,2),10);a=a>=50?1900+a:2e3+a;var r=parseInt(e.substr(2,2),10)-1,n=parseInt(e.substr(4,2),10),i=parseInt(e.substr(6,2),10),s=parseInt(e.substr(8,2),10),o=0;if(e.length>11){var u=e.charAt(10),l=10;u!=="+"&&u!=="-"&&(o=parseInt(e.substr(10,2),10),l+=2)}if(t.setUTCFullYear(a,r,n),t.setUTCHours(i,s,o,0),l&&(u=e.charAt(l),u==="+"||u==="-")){var f=parseInt(e.substr(l+1,2),10),c=parseInt(e.substr(l+4,2),10),y=f*60+c;y*=6e4,u==="+"?t.setTime(+t-y):t.setTime(+t+y)}return t};U.generalizedTimeToDate=function(e){var t=new Date,a=parseInt(e.substr(0,4),10),r=parseInt(e.substr(4,2),10)-1,n=parseInt(e.substr(6,2),10),i=parseInt(e.substr(8,2),10),s=parseInt(e.substr(10,2),10),o=parseInt(e.substr(12,2),10),u=0,l=0,f=!1;e.charAt(e.length-1)==="Z"&&(f=!0);var c=e.length-5,y=e.charAt(c);if(y==="+"||y==="-"){var m=parseInt(e.substr(c+1,2),10),h=parseInt(e.substr(c+4,2),10);l=m*60+h,l*=6e4,y==="+"&&(l*=-1),f=!0}return e.charAt(14)==="."&&(u=parseFloat(e.substr(14),10)*1e3),f?(t.setUTCFullYear(a,r,n),t.setUTCHours(i,s,o,u),t.setTime(+t+l)):(t.setFullYear(a,r,n),t.setHours(i,s,o,u)),t};U.dateToUtcTime=function(e){if(typeof e=="string")return e;var t="",a=[];a.push((""+e.getUTCFullYear()).substr(2)),a.push(""+(e.getUTCMonth()+1)),a.push(""+e.getUTCDate()),a.push(""+e.getUTCHours()),a.push(""+e.getUTCMinutes()),a.push(""+e.getUTCSeconds());for(var r=0;r<a.length;++r)a[r].length<2&&(t+="0"),t+=a[r];return t+="Z",t};U.dateToGeneralizedTime=function(e){if(typeof e=="string")return e;var t="",a=[];a.push(""+e.getUTCFullYear()),a.push(""+(e.getUTCMonth()+1)),a.push(""+e.getUTCDate()),a.push(""+e.getUTCHours()),a.push(""+e.getUTCMinutes()),a.push(""+e.getUTCSeconds());for(var r=0;r<a.length;++r)a[r].length<2&&(t+="0"),t+=a[r];return t+="Z",t};U.integerToDer=function(e){var t=ge.util.createBuffer();if(e>=-128&&e<128)return t.putSignedInt(e,8);if(e>=-32768&&e<32768)return t.putSignedInt(e,16);if(e>=-8388608&&e<8388608)return t.putSignedInt(e,24);if(e>=-2147483648&&e<2147483648)return t.putSignedInt(e,32);var a=new Error("Integer too large; max is 32-bits.");throw a.integer=e,a};U.derToInteger=function(e){typeof e=="string"&&(e=ge.util.createBuffer(e));var t=e.length()*8;if(t>32)throw new Error("Integer too large; max is 32-bits.");return e.getSignedInt(t)};U.validate=function(e,t,a,r){var n=!1;if((e.tagClass===t.tagClass||typeof t.tagClass>"u")&&(e.type===t.type||typeof t.type>"u"))if(e.constructed===t.constructed||typeof t.constructed>"u"){if(n=!0,t.value&&ge.util.isArray(t.value))for(var i=0,s=0;n&&s<t.value.length;++s)n=t.value[s].optional||!1,e.value[i]&&(n=U.validate(e.value[i],t.value[s],a,r),n?++i:t.value[s].optional&&(n=!0)),!n&&r&&r.push("["+t.name+'] Tag class "'+t.tagClass+'", type "'+t.type+'" expected value length "'+t.value.length+'", got "'+e.value.length+'"');if(n&&a&&(t.capture&&(a[t.capture]=e.value),t.captureAsn1&&(a[t.captureAsn1]=e),t.captureBitStringContents&&"bitStringContents"in e&&(a[t.captureBitStringContents]=e.bitStringContents),t.captureBitStringValue&&"bitStringContents"in e)){var o;if(e.bitStringContents.length<2)a[t.captureBitStringValue]="";else{var u=e.bitStringContents.charCodeAt(0);if(u!==0)throw new Error("captureBitStringValue only supported for zero unused bits");a[t.captureBitStringValue]=e.bitStringContents.slice(1)}}}else r&&r.push("["+t.name+'] Expected constructed "'+t.constructed+'", got "'+e.constructed+'"');else r&&(e.tagClass!==t.tagClass&&r.push("["+t.name+'] Expected tag class "'+t.tagClass+'", got "'+e.tagClass+'"'),e.type!==t.type&&r.push("["+t.name+'] Expected type "'+t.type+'", got "'+e.type+'"'));return n};var Rs=/[^\\u0000-\\u00ff]/;U.prettyPrint=function(e,t,a){var r="";t=t||0,a=a||2,t>0&&(r+=`
|
|
14
|
+
`);for(var n="",i=0;i<t*a;++i)n+=" ";switch(r+=n+"Tag: ",e.tagClass){case U.Class.UNIVERSAL:r+="Universal:";break;case U.Class.APPLICATION:r+="Application:";break;case U.Class.CONTEXT_SPECIFIC:r+="Context-Specific:";break;case U.Class.PRIVATE:r+="Private:";break}if(e.tagClass===U.Class.UNIVERSAL)switch(r+=e.type,e.type){case U.Type.NONE:r+=" (None)";break;case U.Type.BOOLEAN:r+=" (Boolean)";break;case U.Type.INTEGER:r+=" (Integer)";break;case U.Type.BITSTRING:r+=" (Bit string)";break;case U.Type.OCTETSTRING:r+=" (Octet string)";break;case U.Type.NULL:r+=" (Null)";break;case U.Type.OID:r+=" (Object Identifier)";break;case U.Type.ODESC:r+=" (Object Descriptor)";break;case U.Type.EXTERNAL:r+=" (External or Instance of)";break;case U.Type.REAL:r+=" (Real)";break;case U.Type.ENUMERATED:r+=" (Enumerated)";break;case U.Type.EMBEDDED:r+=" (Embedded PDV)";break;case U.Type.UTF8:r+=" (UTF8)";break;case U.Type.ROID:r+=" (Relative Object Identifier)";break;case U.Type.SEQUENCE:r+=" (Sequence)";break;case U.Type.SET:r+=" (Set)";break;case U.Type.PRINTABLESTRING:r+=" (Printable String)";break;case U.Type.IA5String:r+=" (IA5String (ASCII))";break;case U.Type.UTCTIME:r+=" (UTC time)";break;case U.Type.GENERALIZEDTIME:r+=" (Generalized time)";break;case U.Type.BMPSTRING:r+=" (BMP String)";break}else r+=e.type;if(r+=`
|
|
15
|
+
`,r+=n+"Constructed: "+e.constructed+`
|
|
16
|
+
`,e.composed){for(var s=0,o="",i=0;i<e.value.length;++i)e.value[i]!==void 0&&(s+=1,o+=U.prettyPrint(e.value[i],t+1,a),i+1<e.value.length&&(o+=","));r+=n+"Sub values: "+s+o}else{if(r+=n+"Value: ",e.type===U.Type.OID){var u=U.derToOid(e.value);r+=u,ge.pki&&ge.pki.oids&&u in ge.pki.oids&&(r+=" ("+ge.pki.oids[u]+") ")}if(e.type===U.Type.INTEGER)try{r+=U.derToInteger(e.value)}catch{r+="0x"+ge.util.bytesToHex(e.value)}else if(e.type===U.Type.BITSTRING){if(e.value.length>1?r+="0x"+ge.util.bytesToHex(e.value.slice(1)):r+="(none)",e.value.length>0){var l=e.value.charCodeAt(0);l==1?r+=" (1 unused bit shown)":l>1&&(r+=" ("+l+" unused bits shown)")}}else if(e.type===U.Type.OCTETSTRING)Rs.test(e.value)||(r+="("+e.value+") "),r+="0x"+ge.util.bytesToHex(e.value);else if(e.type===U.Type.UTF8)try{r+=ge.util.decodeUtf8(e.value)}catch(f){if(f.message==="URI malformed")r+="0x"+ge.util.bytesToHex(e.value)+" (malformed UTF8)";else throw f}else e.type===U.Type.PRINTABLESTRING||e.type===U.Type.IA5String?r+=e.value:Rs.test(e.value)?r+="0x"+ge.util.bytesToHex(e.value):e.value.length===0?r+="[null]":r+=e.value}return r}});var St=H((yg,Ns)=>{"use strict";var Sa=W();Ns.exports=Sa.md=Sa.md||{};Sa.md.algorithms=Sa.md.algorithms||{}});var Tr=H((mg,Ps)=>{"use strict";var Pt=W();St();re();var Tf=Ps.exports=Pt.hmac=Pt.hmac||{};Tf.create=function(){var e=null,t=null,a=null,r=null,n={};return n.start=function(i,s){if(i!==null)if(typeof i=="string")if(i=i.toLowerCase(),i in Pt.md.algorithms)t=Pt.md.algorithms[i].create();else throw new Error('Unknown hash algorithm "'+i+'"');else t=i;if(s===null)s=e;else{if(typeof s=="string")s=Pt.util.createBuffer(s);else if(Pt.util.isArray(s)){var o=s;s=Pt.util.createBuffer();for(var u=0;u<o.length;++u)s.putByte(o[u])}var l=s.length();l>t.blockLength&&(t.start(),t.update(s.bytes()),s=t.digest()),a=Pt.util.createBuffer(),r=Pt.util.createBuffer(),l=s.length();for(var u=0;u<l;++u){var o=s.at(u);a.putByte(54^o),r.putByte(92^o)}if(l<t.blockLength)for(var o=t.blockLength-l,u=0;u<o;++u)a.putByte(54),r.putByte(92);e=s,a=a.bytes(),r=r.bytes()}t.start(),t.update(a)},n.update=function(i){t.update(i)},n.getMac=function(){var i=t.digest().bytes();return t.start(),t.update(r),t.update(i),t.digest()},n.digest=n.getMac,n}});var ba=H((vg,Us)=>{"use strict";var Tt=W();St();re();var Ls=Us.exports=Tt.md5=Tt.md5||{};Tt.md.md5=Tt.md.algorithms.md5=Ls;Ls.create=function(){ks||bf();var e=null,t=Tt.util.createBuffer(),a=new Array(16),r={algorithm:"md5",blockLength:64,digestLength:16,messageLength:0,fullMessageLength:null,messageLengthSize:8};return r.start=function(){r.messageLength=0,r.fullMessageLength=r.messageLength64=[];for(var n=r.messageLengthSize/4,i=0;i<n;++i)r.fullMessageLength.push(0);return t=Tt.util.createBuffer(),e={h0:1732584193,h1:4023233417,h2:2562383102,h3:271733878},r},r.start(),r.update=function(n,i){i==="utf8"&&(n=Tt.util.encodeUtf8(n));var s=n.length;r.messageLength+=s,s=[s/4294967296>>>0,s>>>0];for(var o=r.fullMessageLength.length-1;o>=0;--o)r.fullMessageLength[o]+=s[1],s[1]=s[0]+(r.fullMessageLength[o]/4294967296>>>0),r.fullMessageLength[o]=r.fullMessageLength[o]>>>0,s[0]=s[1]/4294967296>>>0;return t.putBytes(n),Ds(e,a,t),(t.read>2048||t.length()===0)&&t.compact(),r},r.digest=function(){var n=Tt.util.createBuffer();n.putBytes(t.bytes());var i=r.fullMessageLength[r.fullMessageLength.length-1]+r.messageLengthSize,s=i&r.blockLength-1;n.putBytes(Vn.substr(0,r.blockLength-s));for(var o,u=0,l=r.fullMessageLength.length-1;l>=0;--l)o=r.fullMessageLength[l]*8+u,u=o/4294967296>>>0,n.putInt32Le(o>>>0);var f={h0:e.h0,h1:e.h1,h2:e.h2,h3:e.h3};Ds(f,a,n);var c=Tt.util.createBuffer();return c.putInt32Le(f.h0),c.putInt32Le(f.h1),c.putInt32Le(f.h2),c.putInt32Le(f.h3),c},r};var Vn=null,Ta=null,qr=null,br=null,ks=!1;function bf(){Vn="\x80",Vn+=Tt.util.fillString("\0",64),Ta=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,1,6,11,0,5,10,15,4,9,14,3,8,13,2,7,12,5,8,11,14,1,4,7,10,13,0,3,6,9,12,15,2,0,7,14,5,12,3,10,1,8,15,6,13,4,11,2,9],qr=[7,12,17,22,7,12,17,22,7,12,17,22,7,12,17,22,5,9,14,20,5,9,14,20,5,9,14,20,5,9,14,20,4,11,16,23,4,11,16,23,4,11,16,23,4,11,16,23,6,10,15,21,6,10,15,21,6,10,15,21,6,10,15,21],br=new Array(64);for(var e=0;e<64;++e)br[e]=Math.floor(Math.abs(Math.sin(e+1))*4294967296);ks=!0}function Ds(e,t,a){for(var r,n,i,s,o,u,l,f,c=a.length();c>=64;){for(n=e.h0,i=e.h1,s=e.h2,o=e.h3,f=0;f<16;++f)t[f]=a.getInt32Le(),u=o^i&(s^o),r=n+u+br[f]+t[f],l=qr[f],n=o,o=s,s=i,i+=r<<l|r>>>32-l;for(;f<32;++f)u=s^o&(i^s),r=n+u+br[f]+t[Ta[f]],l=qr[f],n=o,o=s,s=i,i+=r<<l|r>>>32-l;for(;f<48;++f)u=i^s^o,r=n+u+br[f]+t[Ta[f]],l=qr[f],n=o,o=s,s=i,i+=r<<l|r>>>32-l;for(;f<64;++f)u=s^(i|~o),r=n+u+br[f]+t[Ta[f]],l=qr[f],n=o,o=s,s=i,i+=r<<l|r>>>32-l;e.h0=e.h0+n|0,e.h1=e.h1+i|0,e.h2=e.h2+s|0,e.h3=e.h3+o|0,c-=64}}});var ur=H((Eg,Os)=>{"use strict";var wa=W();re();var Fs=Os.exports=wa.pem=wa.pem||{};Fs.encode=function(e,t){t=t||{};var a="-----BEGIN "+e.type+`-----\r
|
|
17
|
+
`,r;if(e.procType&&(r={name:"Proc-Type",values:[String(e.procType.version),e.procType.type]},a+=Ia(r)),e.contentDomain&&(r={name:"Content-Domain",values:[e.contentDomain]},a+=Ia(r)),e.dekInfo&&(r={name:"DEK-Info",values:[e.dekInfo.algorithm]},e.dekInfo.parameters&&r.values.push(e.dekInfo.parameters),a+=Ia(r)),e.headers)for(var n=0;n<e.headers.length;++n)a+=Ia(e.headers[n]);return e.procType&&(a+=`\r
|
|
18
|
+
`),a+=wa.util.encode64(e.body,t.maxline||64)+`\r
|
|
19
|
+
`,a+="-----END "+e.type+`-----\r
|
|
20
|
+
`,a};Fs.decode=function(e){for(var t=[],a=/\s*-----BEGIN ([A-Z0-9- ]+)-----\r?\n?([\x21-\x7e\s]+?(?:\r?\n\r?\n))?([:A-Za-z0-9+\/=\s]+?)-----END \1-----/g,r=/([\x21-\x7e]+):\s*([\x21-\x7e\s^:]+)/,n=/\r?\n/,i;i=a.exec(e),!!i;){var s=i[1];s==="NEW CERTIFICATE REQUEST"&&(s="CERTIFICATE REQUEST");var o={type:s,procType:null,contentDomain:null,dekInfo:null,headers:[],body:wa.util.decode64(i[3])};if(t.push(o),!!i[2]){for(var u=i[2].split(n),l=0;i&&l<u.length;){for(var f=u[l].replace(/\s+$/,""),c=l+1;c<u.length;++c){var y=u[c];if(!/\s/.test(y[0]))break;f+=y,l=c}if(i=f.match(r),i){for(var m={name:i[1],values:[]},h=i[2].split(","),v=0;v<h.length;++v)m.values.push(If(h[v]));if(o.procType)if(!o.contentDomain&&m.name==="Content-Domain")o.contentDomain=h[0]||"";else if(!o.dekInfo&&m.name==="DEK-Info"){if(m.values.length===0)throw new Error('Invalid PEM formatted message. The "DEK-Info" header must have at least one subfield.');o.dekInfo={algorithm:h[0],parameters:h[1]||null}}else o.headers.push(m);else{if(m.name!=="Proc-Type")throw new Error('Invalid PEM formatted message. The first encapsulated header must be "Proc-Type".');if(m.values.length!==2)throw new Error('Invalid PEM formatted message. The "Proc-Type" header must have two subfields.');o.procType={version:h[0],type:h[1]}}}++l}if(o.procType==="ENCRYPTED"&&!o.dekInfo)throw new Error('Invalid PEM formatted message. The "DEK-Info" header must be present if "Proc-Type" is "ENCRYPTED".')}}if(t.length===0)throw new Error("Invalid PEM formatted message.");return t};function Ia(e){for(var t=e.name+": ",a=[],r=function(u,l){return" "+l},n=0;n<e.values.length;++n)a.push(e.values[n].replace(/^(\S+\r\n)/,r));t+=a.join(",")+`\r
|
|
21
|
+
`;for(var i=0,s=-1,n=0;n<t.length;++n,++i)if(i>65&&s!==-1){var o=t[s];o===","?(++s,t=t.substr(0,s)+`\r
|
|
22
|
+
`+t.substr(s)):t=t.substr(0,s)+`\r
|
|
23
|
+
`+o+t.substr(s+1),i=n-s-1,s=-1,++n}else(t[n]===" "||t[n]===" "||t[n]===",")&&(s=n);return t}function If(e){return e.replace(/^\s+/,"")}});var Hr=H((Cg,Ms)=>{"use strict";var me=W();ma();Ln();re();Ms.exports=me.des=me.des||{};me.des.startEncrypting=function(e,t,a,r){var n=Aa({key:e,output:a,decrypt:!1,mode:r||(t===null?"ECB":"CBC")});return n.start(t),n};me.des.createEncryptionCipher=function(e,t){return Aa({key:e,output:null,decrypt:!1,mode:t})};me.des.startDecrypting=function(e,t,a,r){var n=Aa({key:e,output:a,decrypt:!0,mode:r||(t===null?"ECB":"CBC")});return n.start(t),n};me.des.createDecryptionCipher=function(e,t){return Aa({key:e,output:null,decrypt:!0,mode:t})};me.des.Algorithm=function(e,t){var a=this;a.name=e,a.mode=new t({blockSize:8,cipher:{encrypt:function(r,n){return Vs(a._keys,r,n,!1)},decrypt:function(r,n){return Vs(a._keys,r,n,!0)}}}),a._init=!1};me.des.Algorithm.prototype.initialize=function(e){if(!this._init){var t=me.util.createBuffer(e.key);if(this.name.indexOf("3DES")===0&&t.length()!==24)throw new Error("Invalid Triple-DES key size: "+t.length()*8);this._keys=Lf(t),this._init=!0}};bt("DES-ECB",me.cipher.modes.ecb);bt("DES-CBC",me.cipher.modes.cbc);bt("DES-CFB",me.cipher.modes.cfb);bt("DES-OFB",me.cipher.modes.ofb);bt("DES-CTR",me.cipher.modes.ctr);bt("3DES-ECB",me.cipher.modes.ecb);bt("3DES-CBC",me.cipher.modes.cbc);bt("3DES-CFB",me.cipher.modes.cfb);bt("3DES-OFB",me.cipher.modes.ofb);bt("3DES-CTR",me.cipher.modes.ctr);function bt(e,t){var a=function(){return new me.des.Algorithm(e,t)};me.cipher.registerAlgorithm(e,a)}var wf=[16843776,0,65536,16843780,16842756,66564,4,65536,1024,16843776,16843780,1024,16778244,16842756,16777216,4,1028,16778240,16778240,66560,66560,16842752,16842752,16778244,65540,16777220,16777220,65540,0,1028,66564,16777216,65536,16843780,4,16842752,16843776,16777216,16777216,1024,16842756,65536,66560,16777220,1024,4,16778244,66564,16843780,65540,16842752,16778244,16777220,1028,66564,16843776,1028,16778240,16778240,0,65540,66560,0,16842756],Af=[-2146402272,-2147450880,32768,1081376,1048576,32,-2146435040,-2147450848,-2147483616,-2146402272,-2146402304,-2147483648,-2147450880,1048576,32,-2146435040,1081344,1048608,-2147450848,0,-2147483648,32768,1081376,-2146435072,1048608,-2147483616,0,1081344,32800,-2146402304,-2146435072,32800,0,1081376,-2146435040,1048576,-2147450848,-2146435072,-2146402304,32768,-2146435072,-2147450880,32,-2146402272,1081376,32,32768,-2147483648,32800,-2146402304,1048576,-2147483616,1048608,-2147450848,-2147483616,1048608,1081344,0,-2147450880,32800,-2147483648,-2146435040,-2146402272,1081344],Bf=[520,134349312,0,134348808,134218240,0,131592,134218240,131080,134217736,134217736,131072,134349320,131080,134348800,520,134217728,8,134349312,512,131584,134348800,134348808,131592,134218248,131584,131072,134218248,8,134349320,512,134217728,134349312,134217728,131080,520,131072,134349312,134218240,0,512,131080,134349320,134218240,134217736,512,0,134348808,134218248,131072,134217728,134349320,8,131592,131584,134217736,134348800,134218248,520,134348800,131592,8,134348808,131584],Rf=[8396801,8321,8321,128,8396928,8388737,8388609,8193,0,8396800,8396800,8396929,129,0,8388736,8388609,1,8192,8388608,8396801,128,8388608,8193,8320,8388737,1,8320,8388736,8192,8396928,8396929,129,8388736,8388609,8396800,8396929,129,0,0,8396800,8320,8388736,8388737,1,8396801,8321,8321,128,8396929,129,1,8192,8388609,8193,8396928,8388737,8193,8320,8388608,8396801,128,8388608,8192,8396928],_f=[256,34078976,34078720,1107296512,524288,256,1073741824,34078720,1074266368,524288,33554688,1074266368,1107296512,1107820544,524544,1073741824,33554432,1074266112,1074266112,0,1073742080,1107820800,1107820800,33554688,1107820544,1073742080,0,1107296256,34078976,33554432,1107296256,524544,524288,1107296512,256,33554432,1073741824,34078720,1107296512,1074266368,33554688,1073741824,1107820544,34078976,1074266368,256,33554432,1107820544,1107820800,524544,1107296256,1107820800,34078720,0,1074266112,1107296256,524544,33554688,1073742080,524288,0,1074266112,34078976,1073742080],Nf=[536870928,541065216,16384,541081616,541065216,16,541081616,4194304,536887296,4210704,4194304,536870928,4194320,536887296,536870912,16400,0,4194320,536887312,16384,4210688,536887312,16,541065232,541065232,0,4210704,541081600,16400,4210688,541081600,536870912,536887296,16,541065232,4210688,541081616,4194304,16400,536870928,4194304,536887296,536870912,16400,536870928,541081616,4210688,541065216,4210704,541081600,0,541065232,16,16384,541065216,4210704,16384,4194320,536887312,0,541081600,536870912,4194320,536887312],Pf=[2097152,69206018,67110914,0,2048,67110914,2099202,69208064,69208066,2097152,0,67108866,2,67108864,69206018,2050,67110912,2099202,2097154,67110912,67108866,69206016,69208064,2097154,69206016,2048,2050,69208066,2099200,2,67108864,2099200,67108864,2099200,2097152,67110914,67110914,69206018,69206018,2,2097154,67108864,67110912,2097152,69208064,2050,2099202,69208064,2050,67108866,69208066,69206016,2099200,0,2,69208066,0,2099202,69206016,2048,67108866,67110912,2048,2097154],Df=[268439616,4096,262144,268701760,268435456,268439616,64,268435456,262208,268697600,268701760,266240,268701696,266304,4096,64,268697600,268435520,268439552,4160,266240,262208,268697664,268701696,4160,0,0,268697664,268435520,268439552,266304,262144,266304,262144,268701696,4096,64,268697664,4096,266304,268439552,64,268435520,268697600,268697664,268435456,262144,268439616,0,268701760,262208,268435520,268697600,268439552,268439616,0,268701760,266240,266240,4160,4160,262208,268435456,268701696];function Lf(e){for(var t=[0,4,536870912,536870916,65536,65540,536936448,536936452,512,516,536871424,536871428,66048,66052,536936960,536936964],a=[0,1,1048576,1048577,67108864,67108865,68157440,68157441,256,257,1048832,1048833,67109120,67109121,68157696,68157697],r=[0,8,2048,2056,16777216,16777224,16779264,16779272,0,8,2048,2056,16777216,16777224,16779264,16779272],n=[0,2097152,134217728,136314880,8192,2105344,134225920,136323072,131072,2228224,134348800,136445952,139264,2236416,134356992,136454144],i=[0,262144,16,262160,0,262144,16,262160,4096,266240,4112,266256,4096,266240,4112,266256],s=[0,1024,32,1056,0,1024,32,1056,33554432,33555456,33554464,33555488,33554432,33555456,33554464,33555488],o=[0,268435456,524288,268959744,2,268435458,524290,268959746,0,268435456,524288,268959744,2,268435458,524290,268959746],u=[0,65536,2048,67584,536870912,536936448,536872960,536938496,131072,196608,133120,198656,537001984,537067520,537004032,537069568],l=[0,262144,0,262144,2,262146,2,262146,33554432,33816576,33554432,33816576,33554434,33816578,33554434,33816578],f=[0,268435456,8,268435464,0,268435456,8,268435464,1024,268436480,1032,268436488,1024,268436480,1032,268436488],c=[0,32,0,32,1048576,1048608,1048576,1048608,8192,8224,8192,8224,1056768,1056800,1056768,1056800],y=[0,16777216,512,16777728,2097152,18874368,2097664,18874880,67108864,83886080,67109376,83886592,69206016,85983232,69206528,85983744],m=[0,4096,134217728,134221824,524288,528384,134742016,134746112,16,4112,134217744,134221840,524304,528400,134742032,134746128],h=[0,4,256,260,0,4,256,260,1,5,257,261,1,5,257,261],v=e.length()>8?3:1,C=[],T=[0,0,1,1,1,1,1,1,0,1,1,1,1,1,1,0],I=0,A,L=0;L<v;L++){var N=e.getInt32(),P=e.getInt32();A=(N>>>4^P)&252645135,P^=A,N^=A<<4,A=(P>>>-16^N)&65535,N^=A,P^=A<<-16,A=(N>>>2^P)&858993459,P^=A,N^=A<<2,A=(P>>>-16^N)&65535,N^=A,P^=A<<-16,A=(N>>>1^P)&1431655765,P^=A,N^=A<<1,A=(P>>>8^N)&16711935,N^=A,P^=A<<8,A=(N>>>1^P)&1431655765,P^=A,N^=A<<1,A=N<<8|P>>>20&240,N=P<<24|P<<8&16711680|P>>>8&65280|P>>>24&240,P=A;for(var G=0;G<T.length;++G){T[G]?(N=N<<2|N>>>26,P=P<<2|P>>>26):(N=N<<1|N>>>27,P=P<<1|P>>>27),N&=-15,P&=-15;var j=t[N>>>28]|a[N>>>24&15]|r[N>>>20&15]|n[N>>>16&15]|i[N>>>12&15]|s[N>>>8&15]|o[N>>>4&15],ie=u[P>>>28]|l[P>>>24&15]|f[P>>>20&15]|c[P>>>16&15]|y[P>>>12&15]|m[P>>>8&15]|h[P>>>4&15];A=(ie>>>16^j)&65535,C[I++]=j^A,C[I++]=ie^A<<16}}return C}function Vs(e,t,a,r){var n=e.length===32?3:9,i;n===3?i=r?[30,-2,-2]:[0,32,2]:i=r?[94,62,-2,32,64,2,30,-2,-2]:[0,32,2,62,30,-2,64,96,2];var s,o=t[0],u=t[1];s=(o>>>4^u)&252645135,u^=s,o^=s<<4,s=(o>>>16^u)&65535,u^=s,o^=s<<16,s=(u>>>2^o)&858993459,o^=s,u^=s<<2,s=(u>>>8^o)&16711935,o^=s,u^=s<<8,s=(o>>>1^u)&1431655765,u^=s,o^=s<<1,o=o<<1|o>>>31,u=u<<1|u>>>31;for(var l=0;l<n;l+=3){for(var f=i[l+1],c=i[l+2],y=i[l];y!=f;y+=c){var m=u^e[y],h=(u>>>4|u<<28)^e[y+1];s=o,o=u,u=s^(Af[m>>>24&63]|Rf[m>>>16&63]|Nf[m>>>8&63]|Df[m&63]|wf[h>>>24&63]|Bf[h>>>16&63]|_f[h>>>8&63]|Pf[h&63])}s=o,o=u,u=s}o=o>>>1|o<<31,u=u>>>1|u<<31,s=(o>>>1^u)&1431655765,u^=s,o^=s<<1,s=(u>>>8^o)&16711935,o^=s,u^=s<<8,s=(u>>>2^o)&858993459,o^=s,u^=s<<2,s=(o>>>16^u)&65535,u^=s,o^=s<<16,s=(o>>>4^u)&252645135,u^=s,o^=s<<4,a[0]=o,a[1]=u}function Aa(e){e=e||{};var t=(e.mode||"CBC").toUpperCase(),a="DES-"+t,r;e.decrypt?r=me.cipher.createDecipher(a,e.key):r=me.cipher.createCipher(a,e.key);var n=r.start;return r.start=function(i,s){var o=null;s instanceof me.util.ByteBuffer&&(o=s,s={}),s=s||{},s.output=o,s.iv=i,n.call(r,s)},r}});var Ba=H((xg,Ks)=>{"use strict";var Ye=W();Tr();St();re();var kf=Ye.pkcs5=Ye.pkcs5||{},Dt;Ye.util.isNodejs&&!Ye.options.usePureJavaScript&&(Dt=require("crypto"));Ks.exports=Ye.pbkdf2=kf.pbkdf2=function(e,t,a,r,n,i){if(typeof n=="function"&&(i=n,n=null),Ye.util.isNodejs&&!Ye.options.usePureJavaScript&&Dt.pbkdf2&&(n===null||typeof n!="object")&&(Dt.pbkdf2Sync.length>4||!n||n==="sha1"))return typeof n!="string"&&(n="sha1"),e=Buffer.from(e,"binary"),t=Buffer.from(t,"binary"),i?Dt.pbkdf2Sync.length===4?Dt.pbkdf2(e,t,a,r,function(A,L){if(A)return i(A);i(null,L.toString("binary"))}):Dt.pbkdf2(e,t,a,r,n,function(A,L){if(A)return i(A);i(null,L.toString("binary"))}):Dt.pbkdf2Sync.length===4?Dt.pbkdf2Sync(e,t,a,r).toString("binary"):Dt.pbkdf2Sync(e,t,a,r,n).toString("binary");if((typeof n>"u"||n===null)&&(n="sha1"),typeof n=="string"){if(!(n in Ye.md.algorithms))throw new Error("Unknown hash algorithm: "+n);n=Ye.md[n].create()}var s=n.digestLength;if(r>4294967295*s){var o=new Error("Derived key is too long.");if(i)return i(o);throw o}var u=Math.ceil(r/s),l=r-(u-1)*s,f=Ye.hmac.create();f.start(n,e);var c="",y,m,h;if(!i){for(var v=1;v<=u;++v){f.start(null,null),f.update(t),f.update(Ye.util.int32ToBytes(v)),y=h=f.digest().getBytes();for(var C=2;C<=a;++C)f.start(null,null),f.update(h),m=f.digest().getBytes(),y=Ye.util.xorBytes(y,m,s),h=m;c+=v<u?y:y.substr(0,l)}return c}var v=1,C;function T(){if(v>u)return i(null,c);f.start(null,null),f.update(t),f.update(Ye.util.int32ToBytes(v)),y=h=f.digest().getBytes(),C=2,I()}function I(){if(C<=a)return f.start(null,null),f.update(h),m=f.digest().getBytes(),y=Ye.util.xorBytes(y,m,s),h=m,++C,Ye.util.setImmediate(I);c+=v<u?y:y.substr(0,l),++v,T()}T()}});var Kn=H((Sg,Qs)=>{"use strict";var It=W();St();re();var Hs=Qs.exports=It.sha256=It.sha256||{};It.md.sha256=It.md.algorithms.sha256=Hs;Hs.create=function(){zs||Uf();var e=null,t=It.util.createBuffer(),a=new Array(64),r={algorithm:"sha256",blockLength:64,digestLength:32,messageLength:0,fullMessageLength:null,messageLengthSize:8};return r.start=function(){r.messageLength=0,r.fullMessageLength=r.messageLength64=[];for(var n=r.messageLengthSize/4,i=0;i<n;++i)r.fullMessageLength.push(0);return t=It.util.createBuffer(),e={h0:1779033703,h1:3144134277,h2:1013904242,h3:2773480762,h4:1359893119,h5:2600822924,h6:528734635,h7:1541459225},r},r.start(),r.update=function(n,i){i==="utf8"&&(n=It.util.encodeUtf8(n));var s=n.length;r.messageLength+=s,s=[s/4294967296>>>0,s>>>0];for(var o=r.fullMessageLength.length-1;o>=0;--o)r.fullMessageLength[o]+=s[1],s[1]=s[0]+(r.fullMessageLength[o]/4294967296>>>0),r.fullMessageLength[o]=r.fullMessageLength[o]>>>0,s[0]=s[1]/4294967296>>>0;return t.putBytes(n),qs(e,a,t),(t.read>2048||t.length()===0)&&t.compact(),r},r.digest=function(){var n=It.util.createBuffer();n.putBytes(t.bytes());var i=r.fullMessageLength[r.fullMessageLength.length-1]+r.messageLengthSize,s=i&r.blockLength-1;n.putBytes(Mn.substr(0,r.blockLength-s));for(var o,u,l=r.fullMessageLength[0]*8,f=0;f<r.fullMessageLength.length-1;++f)o=r.fullMessageLength[f+1]*8,u=o/4294967296>>>0,l+=u,n.putInt32(l>>>0),l=o>>>0;n.putInt32(l);var c={h0:e.h0,h1:e.h1,h2:e.h2,h3:e.h3,h4:e.h4,h5:e.h5,h6:e.h6,h7:e.h7};qs(c,a,n);var y=It.util.createBuffer();return y.putInt32(c.h0),y.putInt32(c.h1),y.putInt32(c.h2),y.putInt32(c.h3),y.putInt32(c.h4),y.putInt32(c.h5),y.putInt32(c.h6),y.putInt32(c.h7),y},r};var Mn=null,zs=!1,Gs=null;function Uf(){Mn="\x80",Mn+=It.util.fillString("\0",64),Gs=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],zs=!0}function qs(e,t,a){for(var r,n,i,s,o,u,l,f,c,y,m,h,v,C,T,I=a.length();I>=64;){for(l=0;l<16;++l)t[l]=a.getInt32();for(;l<64;++l)r=t[l-2],r=(r>>>17|r<<15)^(r>>>19|r<<13)^r>>>10,n=t[l-15],n=(n>>>7|n<<25)^(n>>>18|n<<14)^n>>>3,t[l]=r+t[l-7]+n+t[l-16]|0;for(f=e.h0,c=e.h1,y=e.h2,m=e.h3,h=e.h4,v=e.h5,C=e.h6,T=e.h7,l=0;l<64;++l)s=(h>>>6|h<<26)^(h>>>11|h<<21)^(h>>>25|h<<7),o=C^h&(v^C),i=(f>>>2|f<<30)^(f>>>13|f<<19)^(f>>>22|f<<10),u=f&c|y&(f^c),r=T+s+o+Gs[l]+t[l],n=i+u,T=C,C=v,v=h,h=m+r>>>0,m=y,y=c,c=f,f=r+n>>>0;e.h0=e.h0+f|0,e.h1=e.h1+c|0,e.h2=e.h2+y|0,e.h3=e.h3+m|0,e.h4=e.h4+h|0,e.h5=e.h5+v|0,e.h6=e.h6+C|0,e.h7=e.h7+T|0,I-=64}}});var qn=H((Tg,Ws)=>{"use strict";var wt=W();re();var Ra=null;wt.util.isNodejs&&!wt.options.usePureJavaScript&&!process.versions["node-webkit"]&&(Ra=require("crypto"));var Ff=Ws.exports=wt.prng=wt.prng||{};Ff.create=function(e){for(var t={plugin:e,key:null,seed:null,time:null,reseeds:0,generated:0,keyBytes:""},a=e.md,r=new Array(32),n=0;n<32;++n)r[n]=a.create();t.pools=r,t.pool=0,t.generate=function(l,f){if(!f)return t.generateSync(l);var c=t.plugin.cipher,y=t.plugin.increment,m=t.plugin.formatKey,h=t.plugin.formatSeed,v=wt.util.createBuffer();t.key=null,C();function C(T){if(T)return f(T);if(v.length()>=l)return f(null,v.getBytes(l));if(t.generated>1048575&&(t.key=null),t.key===null)return wt.util.nextTick(function(){i(C)});var I=c(t.key,t.seed);t.generated+=I.length,v.putBytes(I),t.key=m(c(t.key,y(t.seed))),t.seed=h(c(t.key,t.seed)),wt.util.setImmediate(C)}},t.generateSync=function(l){var f=t.plugin.cipher,c=t.plugin.increment,y=t.plugin.formatKey,m=t.plugin.formatSeed;t.key=null;for(var h=wt.util.createBuffer();h.length()<l;){t.generated>1048575&&(t.key=null),t.key===null&&s();var v=f(t.key,t.seed);t.generated+=v.length,h.putBytes(v),t.key=y(f(t.key,c(t.seed))),t.seed=m(f(t.key,t.seed))}return h.getBytes(l)};function i(l){if(t.pools[0].messageLength>=32)return o(),l();var f=32-t.pools[0].messageLength<<5;t.seedFile(f,function(c,y){if(c)return l(c);t.collect(y),o(),l()})}function s(){if(t.pools[0].messageLength>=32)return o();var l=32-t.pools[0].messageLength<<5;t.collect(t.seedFileSync(l)),o()}function o(){t.reseeds=t.reseeds===4294967295?0:t.reseeds+1;var l=t.plugin.md.create();l.update(t.keyBytes);for(var f=1,c=0;c<32;++c)t.reseeds%f===0&&(l.update(t.pools[c].digest().getBytes()),t.pools[c].start()),f=f<<1;t.keyBytes=l.digest().getBytes(),l.start(),l.update(t.keyBytes);var y=l.digest().getBytes();t.key=t.plugin.formatKey(t.keyBytes),t.seed=t.plugin.formatSeed(y),t.generated=0}function u(l){var f=null,c=wt.util.globalScope,y=c.crypto||c.msCrypto;y&&y.getRandomValues&&(f=function(N){return y.getRandomValues(N)});var m=wt.util.createBuffer();if(f)for(;m.length()<l;){var h=Math.max(1,Math.min(l-m.length(),65536)/4),v=new Uint32Array(Math.floor(h));try{f(v);for(var C=0;C<v.length;++C)m.putInt32(v[C])}catch(N){if(!(typeof QuotaExceededError<"u"&&N instanceof QuotaExceededError))throw N}}if(m.length()<l)for(var T,I,A,L=Math.floor(Math.random()*65536);m.length()<l;){I=16807*(L&65535),T=16807*(L>>16),I+=(T&32767)<<16,I+=T>>15,I=(I&2147483647)+(I>>31),L=I&4294967295;for(var C=0;C<3;++C)A=L>>>(C<<3),A^=Math.floor(Math.random()*256),m.putByte(A&255)}return m.getBytes(l)}return Ra?(t.seedFile=function(l,f){Ra.randomBytes(l,function(c,y){if(c)return f(c);f(null,y.toString())})},t.seedFileSync=function(l){return Ra.randomBytes(l).toString()}):(t.seedFile=function(l,f){try{f(null,u(l))}catch(c){f(c)}},t.seedFileSync=u),t.collect=function(l){for(var f=l.length,c=0;c<f;++c)t.pools[t.pool].update(l.substr(c,1)),t.pool=t.pool===31?0:t.pool+1},t.collectInt=function(l,f){for(var c="",y=0;y<f;y+=8)c+=String.fromCharCode(l>>y&255);t.collect(c)},t.registerWorker=function(l){if(l===self)t.seedFile=function(c,y){function m(h){var v=h.data;v.forge&&v.forge.prng&&(self.removeEventListener("message",m),y(v.forge.prng.err,v.forge.prng.bytes))}self.addEventListener("message",m),self.postMessage({forge:{prng:{needed:c}}})};else{var f=function(c){var y=c.data;y.forge&&y.forge.prng&&t.seedFile(y.forge.prng.needed,function(m,h){l.postMessage({forge:{prng:{err:m,bytes:h}}})})};l.addEventListener("message",f)}},t}});var lt=H((bg,Hn)=>{"use strict";var _e=W();Gt();Kn();qn();re();(function(){if(_e.random&&_e.random.getBytes){Hn.exports=_e.random;return}(function(e){var t={},a=new Array(4),r=_e.util.createBuffer();t.formatKey=function(c){var y=_e.util.createBuffer(c);return c=new Array(4),c[0]=y.getInt32(),c[1]=y.getInt32(),c[2]=y.getInt32(),c[3]=y.getInt32(),_e.aes._expandKey(c,!1)},t.formatSeed=function(c){var y=_e.util.createBuffer(c);return c=new Array(4),c[0]=y.getInt32(),c[1]=y.getInt32(),c[2]=y.getInt32(),c[3]=y.getInt32(),c},t.cipher=function(c,y){return _e.aes._updateBlock(c,y,a,!1),r.putInt32(a[0]),r.putInt32(a[1]),r.putInt32(a[2]),r.putInt32(a[3]),r.getBytes()},t.increment=function(c){return++c[3],c},t.md=_e.md.sha256;function n(){var c=_e.prng.create(t);return c.getBytes=function(y,m){return c.generate(y,m)},c.getBytesSync=function(y){return c.generate(y)},c}var i=n(),s=null,o=_e.util.globalScope,u=o.crypto||o.msCrypto;if(u&&u.getRandomValues&&(s=function(c){return u.getRandomValues(c)}),_e.options.usePureJavaScript||!_e.util.isNodejs&&!s){if(typeof window>"u"||window.document,i.collectInt(+new Date,32),typeof navigator<"u"){var l="";for(var f in navigator)try{typeof navigator[f]=="string"&&(l+=navigator[f])}catch{}i.collect(l),l=null}e&&(e().mousemove(function(c){i.collectInt(c.clientX,16),i.collectInt(c.clientY,16)}),e().keypress(function(c){i.collectInt(c.charCode,8)}))}if(!_e.random)_e.random=i;else for(var f in i)_e.random[f]=i[f];_e.random.createInstance=n,Hn.exports=_e.random})(typeof jQuery<"u"?jQuery:null)})()});var Gn=H((Ig,Ys)=>{"use strict";var Je=W();re();var zn=[217,120,249,196,25,221,181,237,40,233,253,121,74,160,216,157,198,126,55,131,43,118,83,142,98,76,100,136,68,139,251,162,23,154,89,245,135,179,79,19,97,69,109,141,9,129,125,50,189,143,64,235,134,183,123,11,240,149,33,34,92,107,78,130,84,214,101,147,206,96,178,28,115,86,192,20,167,140,241,220,18,117,202,31,59,190,228,209,66,61,212,48,163,60,182,38,111,191,14,218,70,105,7,87,39,242,29,155,188,148,67,3,248,17,199,246,144,239,62,231,6,195,213,47,200,102,30,215,8,232,234,222,128,82,238,247,132,170,114,172,53,77,106,42,150,26,210,113,90,21,73,116,75,159,208,94,4,24,164,236,194,224,65,110,15,81,203,204,36,145,175,80,161,244,112,57,153,124,58,133,35,184,180,122,252,2,54,91,37,85,151,49,45,93,250,152,227,138,146,174,5,223,41,16,103,108,186,201,211,0,230,207,225,158,168,44,99,22,1,63,88,226,137,169,13,56,52,27,171,51,255,176,187,72,12,95,185,177,205,46,197,243,219,71,229,165,156,119,10,166,32,104,254,127,193,173],js=[1,2,3,5],Of=function(e,t){return e<<t&65535|(e&65535)>>16-t},Vf=function(e,t){return(e&65535)>>t|e<<16-t&65535};Ys.exports=Je.rc2=Je.rc2||{};Je.rc2.expandKey=function(e,t){typeof e=="string"&&(e=Je.util.createBuffer(e)),t=t||128;var a=e,r=e.length(),n=t,i=Math.ceil(n/8),s=255>>(n&7),o;for(o=r;o<128;o++)a.putByte(zn[a.at(o-1)+a.at(o-r)&255]);for(a.setAt(128-i,zn[a.at(128-i)&s]),o=127-i;o>=0;o--)a.setAt(o,zn[a.at(o+1)^a.at(o+i)]);return a};var $s=function(e,t,a){var r=!1,n=null,i=null,s=null,o,u,l,f,c=[];for(e=Je.rc2.expandKey(e,t),l=0;l<64;l++)c.push(e.getInt16Le());a?(o=function(h){for(l=0;l<4;l++)h[l]+=c[f]+(h[(l+3)%4]&h[(l+2)%4])+(~h[(l+3)%4]&h[(l+1)%4]),h[l]=Of(h[l],js[l]),f++},u=function(h){for(l=0;l<4;l++)h[l]+=c[h[(l+3)%4]&63]}):(o=function(h){for(l=3;l>=0;l--)h[l]=Vf(h[l],js[l]),h[l]-=c[f]+(h[(l+3)%4]&h[(l+2)%4])+(~h[(l+3)%4]&h[(l+1)%4]),f--},u=function(h){for(l=3;l>=0;l--)h[l]-=c[h[(l+3)%4]&63]});var y=function(h){var v=[];for(l=0;l<4;l++){var C=n.getInt16Le();s!==null&&(a?C^=s.getInt16Le():s.putInt16Le(C)),v.push(C&65535)}f=a?0:63;for(var T=0;T<h.length;T++)for(var I=0;I<h[T][0];I++)h[T][1](v);for(l=0;l<4;l++)s!==null&&(a?s.putInt16Le(v[l]):v[l]^=s.getInt16Le()),i.putInt16Le(v[l])},m=null;return m={start:function(h,v){h&&typeof h=="string"&&(h=Je.util.createBuffer(h)),r=!1,n=Je.util.createBuffer(),i=v||new Je.util.createBuffer,s=h,m.output=i},update:function(h){for(r||n.putBuffer(h);n.length()>=8;)y([[5,o],[1,u],[6,o],[1,u],[5,o]])},finish:function(h){var v=!0;if(a)if(h)v=h(8,n,!a);else{var C=n.length()===8?8:8-n.length();n.fillWithByte(C,C)}if(v&&(r=!0,m.update()),!a&&(v=n.length()===0,v))if(h)v=h(8,i,!a);else{var T=i.length(),I=i.at(T-1);I>T?v=!1:i.truncate(I)}return v}},m};Je.rc2.startEncrypting=function(e,t,a){var r=Je.rc2.createEncryptionCipher(e,128);return r.start(t,a),r};Je.rc2.createEncryptionCipher=function(e,t){return $s(e,t,!0)};Je.rc2.startDecrypting=function(e,t,a){var r=Je.rc2.createDecryptionCipher(e,128);return r.start(t,a),r};Je.rc2.createDecryptionCipher=function(e,t){return $s(e,t,!1)}});var Gr=H((wg,no)=>{"use strict";var Qn=W();no.exports=Qn.jsbn=Qn.jsbn||{};var Lt,Mf=0xdeadbeefcafe,Xs=(Mf&16777215)==15715070;function B(e,t,a){this.data=[],e!=null&&(typeof e=="number"?this.fromNumber(e,t,a):t==null&&typeof e!="string"?this.fromString(e,256):this.fromString(e,t))}Qn.jsbn.BigInteger=B;function ae(){return new B(null)}function Kf(e,t,a,r,n,i){for(;--i>=0;){var s=t*this.data[e++]+a.data[r]+n;n=Math.floor(s/67108864),a.data[r++]=s&67108863}return n}function qf(e,t,a,r,n,i){for(var s=t&32767,o=t>>15;--i>=0;){var u=this.data[e]&32767,l=this.data[e++]>>15,f=o*u+l*s;u=s*u+((f&32767)<<15)+a.data[r]+(n&1073741823),n=(u>>>30)+(f>>>15)+o*l+(n>>>30),a.data[r++]=u&1073741823}return n}function Zs(e,t,a,r,n,i){for(var s=t&16383,o=t>>14;--i>=0;){var u=this.data[e]&16383,l=this.data[e++]>>14,f=o*u+l*s;u=s*u+((f&16383)<<14)+a.data[r]+n,n=(u>>28)+(f>>14)+o*l,a.data[r++]=u&268435455}return n}typeof navigator>"u"?(B.prototype.am=Zs,Lt=28):Xs&&navigator.appName=="Microsoft Internet Explorer"?(B.prototype.am=qf,Lt=30):Xs&&navigator.appName!="Netscape"?(B.prototype.am=Kf,Lt=26):(B.prototype.am=Zs,Lt=28);B.prototype.DB=Lt;B.prototype.DM=(1<<Lt)-1;B.prototype.DV=1<<Lt;var Wn=52;B.prototype.FV=Math.pow(2,Wn);B.prototype.F1=Wn-Lt;B.prototype.F2=2*Lt-Wn;var Hf="0123456789abcdefghijklmnopqrstuvwxyz",_a=new Array,Ir,ft;Ir=48;for(ft=0;ft<=9;++ft)_a[Ir++]=ft;Ir=97;for(ft=10;ft<36;++ft)_a[Ir++]=ft;Ir=65;for(ft=10;ft<36;++ft)_a[Ir++]=ft;function Js(e){return Hf.charAt(e)}function eo(e,t){var a=_a[e.charCodeAt(t)];return a??-1}function zf(e){for(var t=this.t-1;t>=0;--t)e.data[t]=this.data[t];e.t=this.t,e.s=this.s}function Gf(e){this.t=1,this.s=e<0?-1:0,e>0?this.data[0]=e:e<-1?this.data[0]=e+this.DV:this.t=0}function Wt(e){var t=ae();return t.fromInt(e),t}function Qf(e,t){var a;if(t==16)a=4;else if(t==8)a=3;else if(t==256)a=8;else if(t==2)a=1;else if(t==32)a=5;else if(t==4)a=2;else{this.fromRadix(e,t);return}this.t=0,this.s=0;for(var r=e.length,n=!1,i=0;--r>=0;){var s=a==8?e[r]&255:eo(e,r);if(s<0){e.charAt(r)=="-"&&(n=!0);continue}n=!1,i==0?this.data[this.t++]=s:i+a>this.DB?(this.data[this.t-1]|=(s&(1<<this.DB-i)-1)<<i,this.data[this.t++]=s>>this.DB-i):this.data[this.t-1]|=s<<i,i+=a,i>=this.DB&&(i-=this.DB)}a==8&&(e[0]&128)!=0&&(this.s=-1,i>0&&(this.data[this.t-1]|=(1<<this.DB-i)-1<<i)),this.clamp(),n&&B.ZERO.subTo(this,this)}function Wf(){for(var e=this.s&this.DM;this.t>0&&this.data[this.t-1]==e;)--this.t}function jf(e){if(this.s<0)return"-"+this.negate().toString(e);var t;if(e==16)t=4;else if(e==8)t=3;else if(e==2)t=1;else if(e==32)t=5;else if(e==4)t=2;else return this.toRadix(e);var a=(1<<t)-1,r,n=!1,i="",s=this.t,o=this.DB-s*this.DB%t;if(s-- >0)for(o<this.DB&&(r=this.data[s]>>o)>0&&(n=!0,i=Js(r));s>=0;)o<t?(r=(this.data[s]&(1<<o)-1)<<t-o,r|=this.data[--s]>>(o+=this.DB-t)):(r=this.data[s]>>(o-=t)&a,o<=0&&(o+=this.DB,--s)),r>0&&(n=!0),n&&(i+=Js(r));return n?i:"0"}function $f(){var e=ae();return B.ZERO.subTo(this,e),e}function Yf(){return this.s<0?this.negate():this}function Xf(e){var t=this.s-e.s;if(t!=0)return t;var a=this.t;if(t=a-e.t,t!=0)return this.s<0?-t:t;for(;--a>=0;)if((t=this.data[a]-e.data[a])!=0)return t;return 0}function Na(e){var t=1,a;return(a=e>>>16)!=0&&(e=a,t+=16),(a=e>>8)!=0&&(e=a,t+=8),(a=e>>4)!=0&&(e=a,t+=4),(a=e>>2)!=0&&(e=a,t+=2),(a=e>>1)!=0&&(e=a,t+=1),t}function Zf(){return this.t<=0?0:this.DB*(this.t-1)+Na(this.data[this.t-1]^this.s&this.DM)}function Jf(e,t){var a;for(a=this.t-1;a>=0;--a)t.data[a+e]=this.data[a];for(a=e-1;a>=0;--a)t.data[a]=0;t.t=this.t+e,t.s=this.s}function ec(e,t){for(var a=e;a<this.t;++a)t.data[a-e]=this.data[a];t.t=Math.max(this.t-e,0),t.s=this.s}function tc(e,t){var a=e%this.DB,r=this.DB-a,n=(1<<r)-1,i=Math.floor(e/this.DB),s=this.s<<a&this.DM,o;for(o=this.t-1;o>=0;--o)t.data[o+i+1]=this.data[o]>>r|s,s=(this.data[o]&n)<<a;for(o=i-1;o>=0;--o)t.data[o]=0;t.data[i]=s,t.t=this.t+i+1,t.s=this.s,t.clamp()}function rc(e,t){t.s=this.s;var a=Math.floor(e/this.DB);if(a>=this.t){t.t=0;return}var r=e%this.DB,n=this.DB-r,i=(1<<r)-1;t.data[0]=this.data[a]>>r;for(var s=a+1;s<this.t;++s)t.data[s-a-1]|=(this.data[s]&i)<<n,t.data[s-a]=this.data[s]>>r;r>0&&(t.data[this.t-a-1]|=(this.s&i)<<n),t.t=this.t-a,t.clamp()}function ac(e,t){for(var a=0,r=0,n=Math.min(e.t,this.t);a<n;)r+=this.data[a]-e.data[a],t.data[a++]=r&this.DM,r>>=this.DB;if(e.t<this.t){for(r-=e.s;a<this.t;)r+=this.data[a],t.data[a++]=r&this.DM,r>>=this.DB;r+=this.s}else{for(r+=this.s;a<e.t;)r-=e.data[a],t.data[a++]=r&this.DM,r>>=this.DB;r-=e.s}t.s=r<0?-1:0,r<-1?t.data[a++]=this.DV+r:r>0&&(t.data[a++]=r),t.t=a,t.clamp()}function nc(e,t){var a=this.abs(),r=e.abs(),n=a.t;for(t.t=n+r.t;--n>=0;)t.data[n]=0;for(n=0;n<r.t;++n)t.data[n+a.t]=a.am(0,r.data[n],t,n,0,a.t);t.s=0,t.clamp(),this.s!=e.s&&B.ZERO.subTo(t,t)}function ic(e){for(var t=this.abs(),a=e.t=2*t.t;--a>=0;)e.data[a]=0;for(a=0;a<t.t-1;++a){var r=t.am(a,t.data[a],e,2*a,0,1);(e.data[a+t.t]+=t.am(a+1,2*t.data[a],e,2*a+1,r,t.t-a-1))>=t.DV&&(e.data[a+t.t]-=t.DV,e.data[a+t.t+1]=1)}e.t>0&&(e.data[e.t-1]+=t.am(a,t.data[a],e,2*a,0,1)),e.s=0,e.clamp()}function sc(e,t,a){var r=e.abs();if(!(r.t<=0)){var n=this.abs();if(n.t<r.t){t?.fromInt(0),a!=null&&this.copyTo(a);return}a==null&&(a=ae());var i=ae(),s=this.s,o=e.s,u=this.DB-Na(r.data[r.t-1]);u>0?(r.lShiftTo(u,i),n.lShiftTo(u,a)):(r.copyTo(i),n.copyTo(a));var l=i.t,f=i.data[l-1];if(f!=0){var c=f*(1<<this.F1)+(l>1?i.data[l-2]>>this.F2:0),y=this.FV/c,m=(1<<this.F1)/c,h=1<<this.F2,v=a.t,C=v-l,T=t??ae();for(i.dlShiftTo(C,T),a.compareTo(T)>=0&&(a.data[a.t++]=1,a.subTo(T,a)),B.ONE.dlShiftTo(l,T),T.subTo(i,i);i.t<l;)i.data[i.t++]=0;for(;--C>=0;){var I=a.data[--v]==f?this.DM:Math.floor(a.data[v]*y+(a.data[v-1]+h)*m);if((a.data[v]+=i.am(0,I,a,C,0,l))<I)for(i.dlShiftTo(C,T),a.subTo(T,a);a.data[v]<--I;)a.subTo(T,a)}t!=null&&(a.drShiftTo(l,t),s!=o&&B.ZERO.subTo(t,t)),a.t=l,a.clamp(),u>0&&a.rShiftTo(u,a),s<0&&B.ZERO.subTo(a,a)}}}function oc(e){var t=ae();return this.abs().divRemTo(e,null,t),this.s<0&&t.compareTo(B.ZERO)>0&&e.subTo(t,t),t}function lr(e){this.m=e}function uc(e){return e.s<0||e.compareTo(this.m)>=0?e.mod(this.m):e}function lc(e){return e}function fc(e){e.divRemTo(this.m,null,e)}function cc(e,t,a){e.multiplyTo(t,a),this.reduce(a)}function dc(e,t){e.squareTo(t),this.reduce(t)}lr.prototype.convert=uc;lr.prototype.revert=lc;lr.prototype.reduce=fc;lr.prototype.mulTo=cc;lr.prototype.sqrTo=dc;function pc(){if(this.t<1)return 0;var e=this.data[0];if((e&1)==0)return 0;var t=e&3;return t=t*(2-(e&15)*t)&15,t=t*(2-(e&255)*t)&255,t=t*(2-((e&65535)*t&65535))&65535,t=t*(2-e*t%this.DV)%this.DV,t>0?this.DV-t:-t}function fr(e){this.m=e,this.mp=e.invDigit(),this.mpl=this.mp&32767,this.mph=this.mp>>15,this.um=(1<<e.DB-15)-1,this.mt2=2*e.t}function hc(e){var t=ae();return e.abs().dlShiftTo(this.m.t,t),t.divRemTo(this.m,null,t),e.s<0&&t.compareTo(B.ZERO)>0&&this.m.subTo(t,t),t}function gc(e){var t=ae();return e.copyTo(t),this.reduce(t),t}function yc(e){for(;e.t<=this.mt2;)e.data[e.t++]=0;for(var t=0;t<this.m.t;++t){var a=e.data[t]&32767,r=a*this.mpl+((a*this.mph+(e.data[t]>>15)*this.mpl&this.um)<<15)&e.DM;for(a=t+this.m.t,e.data[a]+=this.m.am(0,r,e,t,0,this.m.t);e.data[a]>=e.DV;)e.data[a]-=e.DV,e.data[++a]++}e.clamp(),e.drShiftTo(this.m.t,e),e.compareTo(this.m)>=0&&e.subTo(this.m,e)}function mc(e,t){e.squareTo(t),this.reduce(t)}function vc(e,t,a){e.multiplyTo(t,a),this.reduce(a)}fr.prototype.convert=hc;fr.prototype.revert=gc;fr.prototype.reduce=yc;fr.prototype.mulTo=vc;fr.prototype.sqrTo=mc;function Ec(){return(this.t>0?this.data[0]&1:this.s)==0}function Cc(e,t){if(e>4294967295||e<1)return B.ONE;var a=ae(),r=ae(),n=t.convert(this),i=Na(e)-1;for(n.copyTo(a);--i>=0;)if(t.sqrTo(a,r),(e&1<<i)>0)t.mulTo(r,n,a);else{var s=a;a=r,r=s}return t.revert(a)}function xc(e,t){var a;return e<256||t.isEven()?a=new lr(t):a=new fr(t),this.exp(e,a)}B.prototype.copyTo=zf;B.prototype.fromInt=Gf;B.prototype.fromString=Qf;B.prototype.clamp=Wf;B.prototype.dlShiftTo=Jf;B.prototype.drShiftTo=ec;B.prototype.lShiftTo=tc;B.prototype.rShiftTo=rc;B.prototype.subTo=ac;B.prototype.multiplyTo=nc;B.prototype.squareTo=ic;B.prototype.divRemTo=sc;B.prototype.invDigit=pc;B.prototype.isEven=Ec;B.prototype.exp=Cc;B.prototype.toString=jf;B.prototype.negate=$f;B.prototype.abs=Yf;B.prototype.compareTo=Xf;B.prototype.bitLength=Zf;B.prototype.mod=oc;B.prototype.modPowInt=xc;B.ZERO=Wt(0);B.ONE=Wt(1);function Sc(){var e=ae();return this.copyTo(e),e}function Tc(){if(this.s<0){if(this.t==1)return this.data[0]-this.DV;if(this.t==0)return-1}else{if(this.t==1)return this.data[0];if(this.t==0)return 0}return(this.data[1]&(1<<32-this.DB)-1)<<this.DB|this.data[0]}function bc(){return this.t==0?this.s:this.data[0]<<24>>24}function Ic(){return this.t==0?this.s:this.data[0]<<16>>16}function wc(e){return Math.floor(Math.LN2*this.DB/Math.log(e))}function Ac(){return this.s<0?-1:this.t<=0||this.t==1&&this.data[0]<=0?0:1}function Bc(e){if(e==null&&(e=10),this.signum()==0||e<2||e>36)return"0";var t=this.chunkSize(e),a=Math.pow(e,t),r=Wt(a),n=ae(),i=ae(),s="";for(this.divRemTo(r,n,i);n.signum()>0;)s=(a+i.intValue()).toString(e).substr(1)+s,n.divRemTo(r,n,i);return i.intValue().toString(e)+s}function Rc(e,t){this.fromInt(0),t==null&&(t=10);for(var a=this.chunkSize(t),r=Math.pow(t,a),n=!1,i=0,s=0,o=0;o<e.length;++o){var u=eo(e,o);if(u<0){e.charAt(o)=="-"&&this.signum()==0&&(n=!0);continue}s=t*s+u,++i>=a&&(this.dMultiply(r),this.dAddOffset(s,0),i=0,s=0)}i>0&&(this.dMultiply(Math.pow(t,i)),this.dAddOffset(s,0)),n&&B.ZERO.subTo(this,this)}function _c(e,t,a){if(typeof t=="number")if(e<2)this.fromInt(1);else for(this.fromNumber(e,a),this.testBit(e-1)||this.bitwiseTo(B.ONE.shiftLeft(e-1),jn,this),this.isEven()&&this.dAddOffset(1,0);!this.isProbablePrime(t);)this.dAddOffset(2,0),this.bitLength()>e&&this.subTo(B.ONE.shiftLeft(e-1),this);else{var r=new Array,n=e&7;r.length=(e>>3)+1,t.nextBytes(r),n>0?r[0]&=(1<<n)-1:r[0]=0,this.fromString(r,256)}}function Nc(){var e=this.t,t=new Array;t[0]=this.s;var a=this.DB-e*this.DB%8,r,n=0;if(e-- >0)for(a<this.DB&&(r=this.data[e]>>a)!=(this.s&this.DM)>>a&&(t[n++]=r|this.s<<this.DB-a);e>=0;)a<8?(r=(this.data[e]&(1<<a)-1)<<8-a,r|=this.data[--e]>>(a+=this.DB-8)):(r=this.data[e]>>(a-=8)&255,a<=0&&(a+=this.DB,--e)),(r&128)!=0&&(r|=-256),n==0&&(this.s&128)!=(r&128)&&++n,(n>0||r!=this.s)&&(t[n++]=r);return t}function Pc(e){return this.compareTo(e)==0}function Dc(e){return this.compareTo(e)<0?this:e}function Lc(e){return this.compareTo(e)>0?this:e}function kc(e,t,a){var r,n,i=Math.min(e.t,this.t);for(r=0;r<i;++r)a.data[r]=t(this.data[r],e.data[r]);if(e.t<this.t){for(n=e.s&this.DM,r=i;r<this.t;++r)a.data[r]=t(this.data[r],n);a.t=this.t}else{for(n=this.s&this.DM,r=i;r<e.t;++r)a.data[r]=t(n,e.data[r]);a.t=e.t}a.s=t(this.s,e.s),a.clamp()}function Uc(e,t){return e&t}function Fc(e){var t=ae();return this.bitwiseTo(e,Uc,t),t}function jn(e,t){return e|t}function Oc(e){var t=ae();return this.bitwiseTo(e,jn,t),t}function to(e,t){return e^t}function Vc(e){var t=ae();return this.bitwiseTo(e,to,t),t}function ro(e,t){return e&~t}function Mc(e){var t=ae();return this.bitwiseTo(e,ro,t),t}function Kc(){for(var e=ae(),t=0;t<this.t;++t)e.data[t]=this.DM&~this.data[t];return e.t=this.t,e.s=~this.s,e}function qc(e){var t=ae();return e<0?this.rShiftTo(-e,t):this.lShiftTo(e,t),t}function Hc(e){var t=ae();return e<0?this.lShiftTo(-e,t):this.rShiftTo(e,t),t}function zc(e){if(e==0)return-1;var t=0;return(e&65535)==0&&(e>>=16,t+=16),(e&255)==0&&(e>>=8,t+=8),(e&15)==0&&(e>>=4,t+=4),(e&3)==0&&(e>>=2,t+=2),(e&1)==0&&++t,t}function Gc(){for(var e=0;e<this.t;++e)if(this.data[e]!=0)return e*this.DB+zc(this.data[e]);return this.s<0?this.t*this.DB:-1}function Qc(e){for(var t=0;e!=0;)e&=e-1,++t;return t}function Wc(){for(var e=0,t=this.s&this.DM,a=0;a<this.t;++a)e+=Qc(this.data[a]^t);return e}function jc(e){var t=Math.floor(e/this.DB);return t>=this.t?this.s!=0:(this.data[t]&1<<e%this.DB)!=0}function $c(e,t){var a=B.ONE.shiftLeft(e);return this.bitwiseTo(a,t,a),a}function Yc(e){return this.changeBit(e,jn)}function Xc(e){return this.changeBit(e,ro)}function Zc(e){return this.changeBit(e,to)}function Jc(e,t){for(var a=0,r=0,n=Math.min(e.t,this.t);a<n;)r+=this.data[a]+e.data[a],t.data[a++]=r&this.DM,r>>=this.DB;if(e.t<this.t){for(r+=e.s;a<this.t;)r+=this.data[a],t.data[a++]=r&this.DM,r>>=this.DB;r+=this.s}else{for(r+=this.s;a<e.t;)r+=e.data[a],t.data[a++]=r&this.DM,r>>=this.DB;r+=e.s}t.s=r<0?-1:0,r>0?t.data[a++]=r:r<-1&&(t.data[a++]=this.DV+r),t.t=a,t.clamp()}function e0(e){var t=ae();return this.addTo(e,t),t}function t0(e){var t=ae();return this.subTo(e,t),t}function r0(e){var t=ae();return this.multiplyTo(e,t),t}function a0(e){var t=ae();return this.divRemTo(e,t,null),t}function n0(e){var t=ae();return this.divRemTo(e,null,t),t}function i0(e){var t=ae(),a=ae();return this.divRemTo(e,t,a),new Array(t,a)}function s0(e){this.data[this.t]=this.am(0,e-1,this,0,0,this.t),++this.t,this.clamp()}function o0(e,t){if(e!=0){for(;this.t<=t;)this.data[this.t++]=0;for(this.data[t]+=e;this.data[t]>=this.DV;)this.data[t]-=this.DV,++t>=this.t&&(this.data[this.t++]=0),++this.data[t]}}function zr(){}function ao(e){return e}function u0(e,t,a){e.multiplyTo(t,a)}function l0(e,t){e.squareTo(t)}zr.prototype.convert=ao;zr.prototype.revert=ao;zr.prototype.mulTo=u0;zr.prototype.sqrTo=l0;function f0(e){return this.exp(e,new zr)}function c0(e,t,a){var r=Math.min(this.t+e.t,t);for(a.s=0,a.t=r;r>0;)a.data[--r]=0;var n;for(n=a.t-this.t;r<n;++r)a.data[r+this.t]=this.am(0,e.data[r],a,r,0,this.t);for(n=Math.min(e.t,t);r<n;++r)this.am(0,e.data[r],a,r,0,t-r);a.clamp()}function d0(e,t,a){--t;var r=a.t=this.t+e.t-t;for(a.s=0;--r>=0;)a.data[r]=0;for(r=Math.max(t-this.t,0);r<e.t;++r)a.data[this.t+r-t]=this.am(t-r,e.data[r],a,0,0,this.t+r-t);a.clamp(),a.drShiftTo(1,a)}function wr(e){this.r2=ae(),this.q3=ae(),B.ONE.dlShiftTo(2*e.t,this.r2),this.mu=this.r2.divide(e),this.m=e}function p0(e){if(e.s<0||e.t>2*this.m.t)return e.mod(this.m);if(e.compareTo(this.m)<0)return e;var t=ae();return e.copyTo(t),this.reduce(t),t}function h0(e){return e}function g0(e){for(e.drShiftTo(this.m.t-1,this.r2),e.t>this.m.t+1&&(e.t=this.m.t+1,e.clamp()),this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3),this.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2);e.compareTo(this.r2)<0;)e.dAddOffset(1,this.m.t+1);for(e.subTo(this.r2,e);e.compareTo(this.m)>=0;)e.subTo(this.m,e)}function y0(e,t){e.squareTo(t),this.reduce(t)}function m0(e,t,a){e.multiplyTo(t,a),this.reduce(a)}wr.prototype.convert=p0;wr.prototype.revert=h0;wr.prototype.reduce=g0;wr.prototype.mulTo=m0;wr.prototype.sqrTo=y0;function v0(e,t){var a=e.bitLength(),r,n=Wt(1),i;if(a<=0)return n;a<18?r=1:a<48?r=3:a<144?r=4:a<768?r=5:r=6,a<8?i=new lr(t):t.isEven()?i=new wr(t):i=new fr(t);var s=new Array,o=3,u=r-1,l=(1<<r)-1;if(s[1]=i.convert(this),r>1){var f=ae();for(i.sqrTo(s[1],f);o<=l;)s[o]=ae(),i.mulTo(f,s[o-2],s[o]),o+=2}var c=e.t-1,y,m=!0,h=ae(),v;for(a=Na(e.data[c])-1;c>=0;){for(a>=u?y=e.data[c]>>a-u&l:(y=(e.data[c]&(1<<a+1)-1)<<u-a,c>0&&(y|=e.data[c-1]>>this.DB+a-u)),o=r;(y&1)==0;)y>>=1,--o;if((a-=o)<0&&(a+=this.DB,--c),m)s[y].copyTo(n),m=!1;else{for(;o>1;)i.sqrTo(n,h),i.sqrTo(h,n),o-=2;o>0?i.sqrTo(n,h):(v=n,n=h,h=v),i.mulTo(h,s[y],n)}for(;c>=0&&(e.data[c]&1<<a)==0;)i.sqrTo(n,h),v=n,n=h,h=v,--a<0&&(a=this.DB-1,--c)}return i.revert(n)}function E0(e){var t=this.s<0?this.negate():this.clone(),a=e.s<0?e.negate():e.clone();if(t.compareTo(a)<0){var r=t;t=a,a=r}var n=t.getLowestSetBit(),i=a.getLowestSetBit();if(i<0)return t;for(n<i&&(i=n),i>0&&(t.rShiftTo(i,t),a.rShiftTo(i,a));t.signum()>0;)(n=t.getLowestSetBit())>0&&t.rShiftTo(n,t),(n=a.getLowestSetBit())>0&&a.rShiftTo(n,a),t.compareTo(a)>=0?(t.subTo(a,t),t.rShiftTo(1,t)):(a.subTo(t,a),a.rShiftTo(1,a));return i>0&&a.lShiftTo(i,a),a}function C0(e){if(e<=0)return 0;var t=this.DV%e,a=this.s<0?e-1:0;if(this.t>0)if(t==0)a=this.data[0]%e;else for(var r=this.t-1;r>=0;--r)a=(t*a+this.data[r])%e;return a}function x0(e){var t=e.isEven();if(this.isEven()&&t||e.signum()==0)return B.ZERO;for(var a=e.clone(),r=this.clone(),n=Wt(1),i=Wt(0),s=Wt(0),o=Wt(1);a.signum()!=0;){for(;a.isEven();)a.rShiftTo(1,a),t?((!n.isEven()||!i.isEven())&&(n.addTo(this,n),i.subTo(e,i)),n.rShiftTo(1,n)):i.isEven()||i.subTo(e,i),i.rShiftTo(1,i);for(;r.isEven();)r.rShiftTo(1,r),t?((!s.isEven()||!o.isEven())&&(s.addTo(this,s),o.subTo(e,o)),s.rShiftTo(1,s)):o.isEven()||o.subTo(e,o),o.rShiftTo(1,o);a.compareTo(r)>=0?(a.subTo(r,a),t&&n.subTo(s,n),i.subTo(o,i)):(r.subTo(a,r),t&&s.subTo(n,s),o.subTo(i,o))}if(r.compareTo(B.ONE)!=0)return B.ZERO;if(o.compareTo(e)>=0)return o.subtract(e);if(o.signum()<0)o.addTo(e,o);else return o;return o.signum()<0?o.add(e):o}var vt=[2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509],S0=(1<<26)/vt[vt.length-1];function T0(e){var t,a=this.abs();if(a.t==1&&a.data[0]<=vt[vt.length-1]){for(t=0;t<vt.length;++t)if(a.data[0]==vt[t])return!0;return!1}if(a.isEven())return!1;for(t=1;t<vt.length;){for(var r=vt[t],n=t+1;n<vt.length&&r<S0;)r*=vt[n++];for(r=a.modInt(r);t<n;)if(r%vt[t++]==0)return!1}return a.millerRabin(e)}function b0(e){var t=this.subtract(B.ONE),a=t.getLowestSetBit();if(a<=0)return!1;for(var r=t.shiftRight(a),n=I0(),i,s=0;s<e;++s){do i=new B(this.bitLength(),n);while(i.compareTo(B.ONE)<=0||i.compareTo(t)>=0);var o=i.modPow(r,this);if(o.compareTo(B.ONE)!=0&&o.compareTo(t)!=0){for(var u=1;u++<a&&o.compareTo(t)!=0;)if(o=o.modPowInt(2,this),o.compareTo(B.ONE)==0)return!1;if(o.compareTo(t)!=0)return!1}}return!0}function I0(){return{nextBytes:function(e){for(var t=0;t<e.length;++t)e[t]=Math.floor(Math.random()*256)}}}B.prototype.chunkSize=wc;B.prototype.toRadix=Bc;B.prototype.fromRadix=Rc;B.prototype.fromNumber=_c;B.prototype.bitwiseTo=kc;B.prototype.changeBit=$c;B.prototype.addTo=Jc;B.prototype.dMultiply=s0;B.prototype.dAddOffset=o0;B.prototype.multiplyLowerTo=c0;B.prototype.multiplyUpperTo=d0;B.prototype.modInt=C0;B.prototype.millerRabin=b0;B.prototype.clone=Sc;B.prototype.intValue=Tc;B.prototype.byteValue=bc;B.prototype.shortValue=Ic;B.prototype.signum=Ac;B.prototype.toByteArray=Nc;B.prototype.equals=Pc;B.prototype.min=Dc;B.prototype.max=Lc;B.prototype.and=Fc;B.prototype.or=Oc;B.prototype.xor=Vc;B.prototype.andNot=Mc;B.prototype.not=Kc;B.prototype.shiftLeft=qc;B.prototype.shiftRight=Hc;B.prototype.getLowestSetBit=Gc;B.prototype.bitCount=Wc;B.prototype.testBit=jc;B.prototype.setBit=Yc;B.prototype.clearBit=Xc;B.prototype.flipBit=Zc;B.prototype.add=e0;B.prototype.subtract=t0;B.prototype.multiply=r0;B.prototype.divide=a0;B.prototype.remainder=n0;B.prototype.divideAndRemainder=i0;B.prototype.modPow=v0;B.prototype.modInverse=x0;B.prototype.pow=f0;B.prototype.gcd=E0;B.prototype.isProbablePrime=T0});var Ar=H((Ag,uo)=>{"use strict";var At=W();St();re();var so=uo.exports=At.sha1=At.sha1||{};At.md.sha1=At.md.algorithms.sha1=so;so.create=function(){oo||w0();var e=null,t=At.util.createBuffer(),a=new Array(80),r={algorithm:"sha1",blockLength:64,digestLength:20,messageLength:0,fullMessageLength:null,messageLengthSize:8};return r.start=function(){r.messageLength=0,r.fullMessageLength=r.messageLength64=[];for(var n=r.messageLengthSize/4,i=0;i<n;++i)r.fullMessageLength.push(0);return t=At.util.createBuffer(),e={h0:1732584193,h1:4023233417,h2:2562383102,h3:271733878,h4:3285377520},r},r.start(),r.update=function(n,i){i==="utf8"&&(n=At.util.encodeUtf8(n));var s=n.length;r.messageLength+=s,s=[s/4294967296>>>0,s>>>0];for(var o=r.fullMessageLength.length-1;o>=0;--o)r.fullMessageLength[o]+=s[1],s[1]=s[0]+(r.fullMessageLength[o]/4294967296>>>0),r.fullMessageLength[o]=r.fullMessageLength[o]>>>0,s[0]=s[1]/4294967296>>>0;return t.putBytes(n),io(e,a,t),(t.read>2048||t.length()===0)&&t.compact(),r},r.digest=function(){var n=At.util.createBuffer();n.putBytes(t.bytes());var i=r.fullMessageLength[r.fullMessageLength.length-1]+r.messageLengthSize,s=i&r.blockLength-1;n.putBytes($n.substr(0,r.blockLength-s));for(var o,u,l=r.fullMessageLength[0]*8,f=0;f<r.fullMessageLength.length-1;++f)o=r.fullMessageLength[f+1]*8,u=o/4294967296>>>0,l+=u,n.putInt32(l>>>0),l=o>>>0;n.putInt32(l);var c={h0:e.h0,h1:e.h1,h2:e.h2,h3:e.h3,h4:e.h4};io(c,a,n);var y=At.util.createBuffer();return y.putInt32(c.h0),y.putInt32(c.h1),y.putInt32(c.h2),y.putInt32(c.h3),y.putInt32(c.h4),y},r};var $n=null,oo=!1;function w0(){$n="\x80",$n+=At.util.fillString("\0",64),oo=!0}function io(e,t,a){for(var r,n,i,s,o,u,l,f,c=a.length();c>=64;){for(n=e.h0,i=e.h1,s=e.h2,o=e.h3,u=e.h4,f=0;f<16;++f)r=a.getInt32(),t[f]=r,l=o^i&(s^o),r=(n<<5|n>>>27)+l+u+1518500249+r,u=o,o=s,s=(i<<30|i>>>2)>>>0,i=n,n=r;for(;f<20;++f)r=t[f-3]^t[f-8]^t[f-14]^t[f-16],r=r<<1|r>>>31,t[f]=r,l=o^i&(s^o),r=(n<<5|n>>>27)+l+u+1518500249+r,u=o,o=s,s=(i<<30|i>>>2)>>>0,i=n,n=r;for(;f<32;++f)r=t[f-3]^t[f-8]^t[f-14]^t[f-16],r=r<<1|r>>>31,t[f]=r,l=i^s^o,r=(n<<5|n>>>27)+l+u+1859775393+r,u=o,o=s,s=(i<<30|i>>>2)>>>0,i=n,n=r;for(;f<40;++f)r=t[f-6]^t[f-16]^t[f-28]^t[f-32],r=r<<2|r>>>30,t[f]=r,l=i^s^o,r=(n<<5|n>>>27)+l+u+1859775393+r,u=o,o=s,s=(i<<30|i>>>2)>>>0,i=n,n=r;for(;f<60;++f)r=t[f-6]^t[f-16]^t[f-28]^t[f-32],r=r<<2|r>>>30,t[f]=r,l=i&s|o&(i^s),r=(n<<5|n>>>27)+l+u+2400959708+r,u=o,o=s,s=(i<<30|i>>>2)>>>0,i=n,n=r;for(;f<80;++f)r=t[f-6]^t[f-16]^t[f-28]^t[f-32],r=r<<2|r>>>30,t[f]=r,l=i^s^o,r=(n<<5|n>>>27)+l+u+3395469782+r,u=o,o=s,s=(i<<30|i>>>2)>>>0,i=n,n=r;e.h0=e.h0+n|0,e.h1=e.h1+i|0,e.h2=e.h2+s|0,e.h3=e.h3+o|0,e.h4=e.h4+u|0,c-=64}}});var Yn=H((Bg,fo)=>{"use strict";var Bt=W();re();lt();Ar();var lo=fo.exports=Bt.pkcs1=Bt.pkcs1||{};lo.encode_rsa_oaep=function(e,t,a){var r,n,i,s;typeof a=="string"?(r=a,n=arguments[3]||void 0,i=arguments[4]||void 0):a&&(r=a.label||void 0,n=a.seed||void 0,i=a.md||void 0,a.mgf1&&a.mgf1.md&&(s=a.mgf1.md)),i?i.start():i=Bt.md.sha1.create(),s||(s=i);var o=Math.ceil(e.n.bitLength()/8),u=o-2*i.digestLength-2;if(t.length>u){var l=new Error("RSAES-OAEP input message length is too long.");throw l.length=t.length,l.maxLength=u,l}r||(r=""),i.update(r,"raw");for(var f=i.digest(),c="",y=u-t.length,m=0;m<y;m++)c+="\0";var h=f.getBytes()+c+""+t;if(!n)n=Bt.random.getBytes(i.digestLength);else if(n.length!==i.digestLength){var l=new Error("Invalid RSAES-OAEP seed. The seed length must match the digest length.");throw l.seedLength=n.length,l.digestLength=i.digestLength,l}var v=Pa(n,o-i.digestLength-1,s),C=Bt.util.xorBytes(h,v,h.length),T=Pa(C,i.digestLength,s),I=Bt.util.xorBytes(n,T,n.length);return"\0"+I+C};lo.decode_rsa_oaep=function(e,t,a){var r,n,i;typeof a=="string"?(r=a,n=arguments[3]||void 0):a&&(r=a.label||void 0,n=a.md||void 0,a.mgf1&&a.mgf1.md&&(i=a.mgf1.md));var s=Math.ceil(e.n.bitLength()/8);if(t.length!==s){var C=new Error("RSAES-OAEP encoded message length is invalid.");throw C.length=t.length,C.expectedLength=s,C}if(n===void 0?n=Bt.md.sha1.create():n.start(),i||(i=n),s<2*n.digestLength+2)throw new Error("RSAES-OAEP key is too short for the hash function.");r||(r=""),n.update(r,"raw");for(var o=n.digest().getBytes(),u=t.charAt(0),l=t.substring(1,n.digestLength+1),f=t.substring(1+n.digestLength),c=Pa(f,n.digestLength,i),y=Bt.util.xorBytes(l,c,l.length),m=Pa(y,s-n.digestLength-1,i),h=Bt.util.xorBytes(f,m,f.length),v=h.substring(0,n.digestLength),C=u!=="\0",T=0;T<n.digestLength;++T)C|=o.charAt(T)!==v.charAt(T);for(var I=1,A=n.digestLength,L=n.digestLength;L<h.length;L++){var N=h.charCodeAt(L),P=N&1^1,G=I?65534:0;C|=N&G,I=I&P,A+=I}if(C||h.charCodeAt(A)!==1)throw new Error("Invalid RSAES-OAEP padding.");return h.substring(A+1)};function Pa(e,t,a){a||(a=Bt.md.sha1.create());for(var r="",n=Math.ceil(t/a.digestLength),i=0;i<n;++i){var s=String.fromCharCode(i>>24&255,i>>16&255,i>>8&255,i&255);a.start(),a.update(e+s),r+=a.digest().getBytes()}return r.substring(0,t)}});var Zn=H((Rg,Xn)=>{"use strict";var jt=W();re();Gr();lt();(function(){if(jt.prime){Xn.exports=jt.prime;return}var e=Xn.exports=jt.prime=jt.prime||{},t=jt.jsbn.BigInteger,a=[6,4,2,4,2,4,6,2],r=new t(null);r.fromInt(30);var n=function(c,y){return c|y};e.generateProbablePrime=function(c,y,m){typeof y=="function"&&(m=y,y={}),y=y||{};var h=y.algorithm||"PRIMEINC";typeof h=="string"&&(h={name:h}),h.options=h.options||{};var v=y.prng||jt.random,C={nextBytes:function(T){for(var I=v.getBytesSync(T.length),A=0;A<T.length;++A)T[A]=I.charCodeAt(A)}};if(h.name==="PRIMEINC")return i(c,C,h.options,m);throw new Error("Invalid prime generation algorithm: "+h.name)};function i(c,y,m,h){return"workers"in m?u(c,y,m,h):s(c,y,m,h)}function s(c,y,m,h){var v=l(c,y),C=0,T=f(v.bitLength());"millerRabinTests"in m&&(T=m.millerRabinTests);var I=10;"maxBlockTime"in m&&(I=m.maxBlockTime),o(v,c,y,C,T,I,h)}function o(c,y,m,h,v,C,T){var I=+new Date;do{if(c.bitLength()>y&&(c=l(y,m)),c.isProbablePrime(v))return T(null,c);c.dAddOffset(a[h++%8],0)}while(C<0||+new Date-I<C);jt.util.setImmediate(function(){o(c,y,m,h,v,C,T)})}function u(c,y,m,h){if(typeof Worker>"u")return s(c,y,m,h);var v=l(c,y),C=m.workers,T=m.workLoad||100,I=T*30/8,A=m.workerScript||"forge/prime.worker.js";if(C===-1)return jt.util.estimateCores(function(N,P){N&&(P=2),C=P-1,L()});L();function L(){C=Math.max(1,C);for(var N=[],P=0;P<C;++P)N[P]=new Worker(A);for(var G=C,P=0;P<C;++P)N[P].addEventListener("message",ie);var j=!1;function ie(oe){if(!j){--G;var ce=oe.data;if(ce.found){for(var he=0;he<N.length;++he)N[he].terminate();return j=!0,h(null,new t(ce.prime,16))}v.bitLength()>c&&(v=l(c,y));var je=v.toString(16);oe.target.postMessage({hex:je,workLoad:T}),v.dAddOffset(I,0)}}}}function l(c,y){var m=new t(c,y),h=c-1;return m.testBit(h)||m.bitwiseTo(t.ONE.shiftLeft(h),n,m),m.dAddOffset(31-m.mod(r).byteValue(),0),m}function f(c){return c<=100?27:c<=150?18:c<=200?15:c<=250?12:c<=300?9:c<=350?8:c<=400?7:c<=500?6:c<=600?5:c<=800?4:c<=1250?3:2}})()});var Qr=H((_g,vo)=>{"use strict";var M=W();mt();Gr();Qt();Yn();Zn();lt();re();typeof ee>"u"&&(ee=M.jsbn.BigInteger);var ee,Jn=M.util.isNodejs?require("crypto"):null,b=M.asn1,ct=M.util;M.pki=M.pki||{};vo.exports=M.pki.rsa=M.rsa=M.rsa||{};var z=M.pki,A0=[6,4,2,4,2,4,6,2],B0={name:"PrivateKeyInfo",tagClass:b.Class.UNIVERSAL,type:b.Type.SEQUENCE,constructed:!0,value:[{name:"PrivateKeyInfo.version",tagClass:b.Class.UNIVERSAL,type:b.Type.INTEGER,constructed:!1,capture:"privateKeyVersion"},{name:"PrivateKeyInfo.privateKeyAlgorithm",tagClass:b.Class.UNIVERSAL,type:b.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:b.Class.UNIVERSAL,type:b.Type.OID,constructed:!1,capture:"privateKeyOid"}]},{name:"PrivateKeyInfo",tagClass:b.Class.UNIVERSAL,type:b.Type.OCTETSTRING,constructed:!1,capture:"privateKey"}]},R0={name:"RSAPrivateKey",tagClass:b.Class.UNIVERSAL,type:b.Type.SEQUENCE,constructed:!0,value:[{name:"RSAPrivateKey.version",tagClass:b.Class.UNIVERSAL,type:b.Type.INTEGER,constructed:!1,capture:"privateKeyVersion"},{name:"RSAPrivateKey.modulus",tagClass:b.Class.UNIVERSAL,type:b.Type.INTEGER,constructed:!1,capture:"privateKeyModulus"},{name:"RSAPrivateKey.publicExponent",tagClass:b.Class.UNIVERSAL,type:b.Type.INTEGER,constructed:!1,capture:"privateKeyPublicExponent"},{name:"RSAPrivateKey.privateExponent",tagClass:b.Class.UNIVERSAL,type:b.Type.INTEGER,constructed:!1,capture:"privateKeyPrivateExponent"},{name:"RSAPrivateKey.prime1",tagClass:b.Class.UNIVERSAL,type:b.Type.INTEGER,constructed:!1,capture:"privateKeyPrime1"},{name:"RSAPrivateKey.prime2",tagClass:b.Class.UNIVERSAL,type:b.Type.INTEGER,constructed:!1,capture:"privateKeyPrime2"},{name:"RSAPrivateKey.exponent1",tagClass:b.Class.UNIVERSAL,type:b.Type.INTEGER,constructed:!1,capture:"privateKeyExponent1"},{name:"RSAPrivateKey.exponent2",tagClass:b.Class.UNIVERSAL,type:b.Type.INTEGER,constructed:!1,capture:"privateKeyExponent2"},{name:"RSAPrivateKey.coefficient",tagClass:b.Class.UNIVERSAL,type:b.Type.INTEGER,constructed:!1,capture:"privateKeyCoefficient"}]},_0={name:"RSAPublicKey",tagClass:b.Class.UNIVERSAL,type:b.Type.SEQUENCE,constructed:!0,value:[{name:"RSAPublicKey.modulus",tagClass:b.Class.UNIVERSAL,type:b.Type.INTEGER,constructed:!1,capture:"publicKeyModulus"},{name:"RSAPublicKey.exponent",tagClass:b.Class.UNIVERSAL,type:b.Type.INTEGER,constructed:!1,capture:"publicKeyExponent"}]},N0=M.pki.rsa.publicKeyValidator={name:"SubjectPublicKeyInfo",tagClass:b.Class.UNIVERSAL,type:b.Type.SEQUENCE,constructed:!0,captureAsn1:"subjectPublicKeyInfo",value:[{name:"SubjectPublicKeyInfo.AlgorithmIdentifier",tagClass:b.Class.UNIVERSAL,type:b.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:b.Class.UNIVERSAL,type:b.Type.OID,constructed:!1,capture:"publicKeyOid"}]},{name:"SubjectPublicKeyInfo.subjectPublicKey",tagClass:b.Class.UNIVERSAL,type:b.Type.BITSTRING,constructed:!1,value:[{name:"SubjectPublicKeyInfo.subjectPublicKey.RSAPublicKey",tagClass:b.Class.UNIVERSAL,type:b.Type.SEQUENCE,constructed:!0,optional:!0,captureAsn1:"rsaPublicKey"}]}]},P0={name:"DigestInfo",tagClass:b.Class.UNIVERSAL,type:b.Type.SEQUENCE,constructed:!0,value:[{name:"DigestInfo.DigestAlgorithm",tagClass:b.Class.UNIVERSAL,type:b.Type.SEQUENCE,constructed:!0,value:[{name:"DigestInfo.DigestAlgorithm.algorithmIdentifier",tagClass:b.Class.UNIVERSAL,type:b.Type.OID,constructed:!1,capture:"algorithmIdentifier"},{name:"DigestInfo.DigestAlgorithm.parameters",tagClass:b.Class.UNIVERSAL,type:b.Type.NULL,capture:"parameters",optional:!0,constructed:!1}]},{name:"DigestInfo.digest",tagClass:b.Class.UNIVERSAL,type:b.Type.OCTETSTRING,constructed:!1,capture:"digest"}]},D0=function(e){var t;if(e.algorithm in z.oids)t=z.oids[e.algorithm];else{var a=new Error("Unknown message digest algorithm.");throw a.algorithm=e.algorithm,a}var r=b.oidToDer(t).getBytes(),n=b.create(b.Class.UNIVERSAL,b.Type.SEQUENCE,!0,[]),i=b.create(b.Class.UNIVERSAL,b.Type.SEQUENCE,!0,[]);i.value.push(b.create(b.Class.UNIVERSAL,b.Type.OID,!1,r)),i.value.push(b.create(b.Class.UNIVERSAL,b.Type.NULL,!1,""));var s=b.create(b.Class.UNIVERSAL,b.Type.OCTETSTRING,!1,e.digest().getBytes());return n.value.push(i),n.value.push(s),b.toDer(n).getBytes()},yo=function(e,t,a){if(a)return e.modPow(t.e,t.n);if(!t.p||!t.q)return e.modPow(t.d,t.n);t.dP||(t.dP=t.d.mod(t.p.subtract(ee.ONE))),t.dQ||(t.dQ=t.d.mod(t.q.subtract(ee.ONE))),t.qInv||(t.qInv=t.q.modInverse(t.p));var r;do r=new ee(M.util.bytesToHex(M.random.getBytes(t.n.bitLength()/8)),16);while(r.compareTo(t.n)>=0||!r.gcd(t.n).equals(ee.ONE));e=e.multiply(r.modPow(t.e,t.n)).mod(t.n);for(var n=e.mod(t.p).modPow(t.dP,t.p),i=e.mod(t.q).modPow(t.dQ,t.q);n.compareTo(i)<0;)n=n.add(t.p);var s=n.subtract(i).multiply(t.qInv).mod(t.p).multiply(t.q).add(i);return s=s.multiply(r.modInverse(t.n)).mod(t.n),s};z.rsa.encrypt=function(e,t,a){var r=a,n,i=Math.ceil(t.n.bitLength()/8);a!==!1&&a!==!0?(r=a===2,n=mo(e,t,a)):(n=M.util.createBuffer(),n.putBytes(e));for(var s=new ee(n.toHex(),16),o=yo(s,t,r),u=o.toString(16),l=M.util.createBuffer(),f=i-Math.ceil(u.length/2);f>0;)l.putByte(0),--f;return l.putBytes(M.util.hexToBytes(u)),l.getBytes()};z.rsa.decrypt=function(e,t,a,r){var n=Math.ceil(t.n.bitLength()/8);if(e.length!==n){var i=new Error("Encrypted message length is invalid.");throw i.length=e.length,i.expected=n,i}var s=new ee(M.util.createBuffer(e).toHex(),16);if(s.compareTo(t.n)>=0)throw new Error("Encrypted message is invalid.");for(var o=yo(s,t,a),u=o.toString(16),l=M.util.createBuffer(),f=n-Math.ceil(u.length/2);f>0;)l.putByte(0),--f;return l.putBytes(M.util.hexToBytes(u)),r!==!1?Da(l.getBytes(),t,a):l.getBytes()};z.rsa.createKeyPairGenerationState=function(e,t,a){typeof e=="string"&&(e=parseInt(e,10)),e=e||2048,a=a||{};var r=a.prng||M.random,n={nextBytes:function(o){for(var u=r.getBytesSync(o.length),l=0;l<o.length;++l)o[l]=u.charCodeAt(l)}},i=a.algorithm||"PRIMEINC",s;if(i==="PRIMEINC")s={algorithm:i,state:0,bits:e,rng:n,eInt:t||65537,e:new ee(null),p:null,q:null,qBits:e>>1,pBits:e-(e>>1),pqState:0,num:null,keys:null},s.e.fromInt(s.eInt);else throw new Error("Invalid key generation algorithm: "+i);return s};z.rsa.stepKeyPairGenerationState=function(e,t){"algorithm"in e||(e.algorithm="PRIMEINC");var a=new ee(null);a.fromInt(30);for(var r=0,n=function(c,y){return c|y},i=+new Date,s,o=0;e.keys===null&&(t<=0||o<t);){if(e.state===0){var u=e.p===null?e.pBits:e.qBits,l=u-1;e.pqState===0?(e.num=new ee(u,e.rng),e.num.testBit(l)||e.num.bitwiseTo(ee.ONE.shiftLeft(l),n,e.num),e.num.dAddOffset(31-e.num.mod(a).byteValue(),0),r=0,++e.pqState):e.pqState===1?e.num.bitLength()>u?e.pqState=0:e.num.isProbablePrime(k0(e.num.bitLength()))?++e.pqState:e.num.dAddOffset(A0[r++%8],0):e.pqState===2?e.pqState=e.num.subtract(ee.ONE).gcd(e.e).compareTo(ee.ONE)===0?3:0:e.pqState===3&&(e.pqState=0,e.p===null?e.p=e.num:e.q=e.num,e.p!==null&&e.q!==null&&++e.state,e.num=null)}else if(e.state===1)e.p.compareTo(e.q)<0&&(e.num=e.p,e.p=e.q,e.q=e.num),++e.state;else if(e.state===2)e.p1=e.p.subtract(ee.ONE),e.q1=e.q.subtract(ee.ONE),e.phi=e.p1.multiply(e.q1),++e.state;else if(e.state===3)e.phi.gcd(e.e).compareTo(ee.ONE)===0?++e.state:(e.p=null,e.q=null,e.state=0);else if(e.state===4)e.n=e.p.multiply(e.q),e.n.bitLength()===e.bits?++e.state:(e.q=null,e.state=0);else if(e.state===5){var f=e.e.modInverse(e.phi);e.keys={privateKey:z.rsa.setPrivateKey(e.n,e.e,f,e.p,e.q,f.mod(e.p1),f.mod(e.q1),e.q.modInverse(e.p)),publicKey:z.rsa.setPublicKey(e.n,e.e)}}s=+new Date,o+=s-i,i=s}return e.keys!==null};z.rsa.generateKeyPair=function(e,t,a,r){if(arguments.length===1?typeof e=="object"?(a=e,e=void 0):typeof e=="function"&&(r=e,e=void 0):arguments.length===2?typeof e=="number"?typeof t=="function"?(r=t,t=void 0):typeof t!="number"&&(a=t,t=void 0):(a=e,r=t,e=void 0,t=void 0):arguments.length===3&&(typeof t=="number"?typeof a=="function"&&(r=a,a=void 0):(r=a,a=t,t=void 0)),a=a||{},e===void 0&&(e=a.bits||2048),t===void 0&&(t=a.e||65537),!M.options.usePureJavaScript&&!a.prng&&e>=256&&e<=16384&&(t===65537||t===3)){if(r){if(co("generateKeyPair"))return Jn.generateKeyPair("rsa",{modulusLength:e,publicExponent:t,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}},function(o,u,l){if(o)return r(o);r(null,{privateKey:z.privateKeyFromPem(l),publicKey:z.publicKeyFromPem(u)})});if(po("generateKey")&&po("exportKey"))return ct.globalScope.crypto.subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:e,publicExponent:go(t),hash:{name:"SHA-256"}},!0,["sign","verify"]).then(function(o){return ct.globalScope.crypto.subtle.exportKey("pkcs8",o.privateKey)}).then(void 0,function(o){r(o)}).then(function(o){if(o){var u=z.privateKeyFromAsn1(b.fromDer(M.util.createBuffer(o)));r(null,{privateKey:u,publicKey:z.setRsaPublicKey(u.n,u.e)})}});if(ho("generateKey")&&ho("exportKey")){var n=ct.globalScope.msCrypto.subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:e,publicExponent:go(t),hash:{name:"SHA-256"}},!0,["sign","verify"]);n.oncomplete=function(o){var u=o.target.result,l=ct.globalScope.msCrypto.subtle.exportKey("pkcs8",u.privateKey);l.oncomplete=function(f){var c=f.target.result,y=z.privateKeyFromAsn1(b.fromDer(M.util.createBuffer(c)));r(null,{privateKey:y,publicKey:z.setRsaPublicKey(y.n,y.e)})},l.onerror=function(f){r(f)}},n.onerror=function(o){r(o)};return}}else if(co("generateKeyPairSync")){var i=Jn.generateKeyPairSync("rsa",{modulusLength:e,publicExponent:t,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}});return{privateKey:z.privateKeyFromPem(i.privateKey),publicKey:z.publicKeyFromPem(i.publicKey)}}}var s=z.rsa.createKeyPairGenerationState(e,t,a);if(!r)return z.rsa.stepKeyPairGenerationState(s,0),s.keys;L0(s,a,r)};z.setRsaPublicKey=z.rsa.setPublicKey=function(e,t){var a={n:e,e:t};return a.encrypt=function(r,n,i){if(typeof n=="string"?n=n.toUpperCase():n===void 0&&(n="RSAES-PKCS1-V1_5"),n==="RSAES-PKCS1-V1_5")n={encode:function(o,u,l){return mo(o,u,2).getBytes()}};else if(n==="RSA-OAEP"||n==="RSAES-OAEP")n={encode:function(o,u){return M.pkcs1.encode_rsa_oaep(u,o,i)}};else if(["RAW","NONE","NULL",null].indexOf(n)!==-1)n={encode:function(o){return o}};else if(typeof n=="string")throw new Error('Unsupported encryption scheme: "'+n+'".');var s=n.encode(r,a,!0);return z.rsa.encrypt(s,a,!0)},a.verify=function(r,n,i,s){typeof i=="string"?i=i.toUpperCase():i===void 0&&(i="RSASSA-PKCS1-V1_5"),s===void 0&&(s={_parseAllDigestBytes:!0}),"_parseAllDigestBytes"in s||(s._parseAllDigestBytes=!0),i==="RSASSA-PKCS1-V1_5"?i={verify:function(u,l){l=Da(l,a,!0);var f=b.fromDer(l,{parseAllBytes:s._parseAllDigestBytes}),c={},y=[];if(!b.validate(f,P0,c,y)){var m=new Error("ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 DigestInfo value.");throw m.errors=y,m}var h=b.derToOid(c.algorithmIdentifier);if(!(h===M.oids.md2||h===M.oids.md5||h===M.oids.sha1||h===M.oids.sha224||h===M.oids.sha256||h===M.oids.sha384||h===M.oids.sha512||h===M.oids["sha512-224"]||h===M.oids["sha512-256"])){var m=new Error("Unknown RSASSA-PKCS1-v1_5 DigestAlgorithm identifier.");throw m.oid=h,m}if((h===M.oids.md2||h===M.oids.md5)&&!("parameters"in c))throw new Error("ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 DigestInfo value. Missing algorithm identifer NULL parameters.");return u===c.digest}}:(i==="NONE"||i==="NULL"||i===null)&&(i={verify:function(u,l){return l=Da(l,a,!0),u===l}});var o=z.rsa.decrypt(n,a,!0,!1);return i.verify(r,o,a.n.bitLength())},a};z.setRsaPrivateKey=z.rsa.setPrivateKey=function(e,t,a,r,n,i,s,o){var u={n:e,e:t,d:a,p:r,q:n,dP:i,dQ:s,qInv:o};return u.decrypt=function(l,f,c){typeof f=="string"?f=f.toUpperCase():f===void 0&&(f="RSAES-PKCS1-V1_5");var y=z.rsa.decrypt(l,u,!1,!1);if(f==="RSAES-PKCS1-V1_5")f={decode:Da};else if(f==="RSA-OAEP"||f==="RSAES-OAEP")f={decode:function(m,h){return M.pkcs1.decode_rsa_oaep(h,m,c)}};else if(["RAW","NONE","NULL",null].indexOf(f)!==-1)f={decode:function(m){return m}};else throw new Error('Unsupported encryption scheme: "'+f+'".');return f.decode(y,u,!1)},u.sign=function(l,f){var c=!1;typeof f=="string"&&(f=f.toUpperCase()),f===void 0||f==="RSASSA-PKCS1-V1_5"?(f={encode:D0},c=1):(f==="NONE"||f==="NULL"||f===null)&&(f={encode:function(){return l}},c=1);var y=f.encode(l,u.n.bitLength());return z.rsa.encrypt(y,u,c)},u};z.wrapRsaPrivateKey=function(e){return b.create(b.Class.UNIVERSAL,b.Type.SEQUENCE,!0,[b.create(b.Class.UNIVERSAL,b.Type.INTEGER,!1,b.integerToDer(0).getBytes()),b.create(b.Class.UNIVERSAL,b.Type.SEQUENCE,!0,[b.create(b.Class.UNIVERSAL,b.Type.OID,!1,b.oidToDer(z.oids.rsaEncryption).getBytes()),b.create(b.Class.UNIVERSAL,b.Type.NULL,!1,"")]),b.create(b.Class.UNIVERSAL,b.Type.OCTETSTRING,!1,b.toDer(e).getBytes())])};z.privateKeyFromAsn1=function(e){var t={},a=[];if(b.validate(e,B0,t,a)&&(e=b.fromDer(M.util.createBuffer(t.privateKey))),t={},a=[],!b.validate(e,R0,t,a)){var r=new Error("Cannot read private key. ASN.1 object does not contain an RSAPrivateKey.");throw r.errors=a,r}var n,i,s,o,u,l,f,c;return n=M.util.createBuffer(t.privateKeyModulus).toHex(),i=M.util.createBuffer(t.privateKeyPublicExponent).toHex(),s=M.util.createBuffer(t.privateKeyPrivateExponent).toHex(),o=M.util.createBuffer(t.privateKeyPrime1).toHex(),u=M.util.createBuffer(t.privateKeyPrime2).toHex(),l=M.util.createBuffer(t.privateKeyExponent1).toHex(),f=M.util.createBuffer(t.privateKeyExponent2).toHex(),c=M.util.createBuffer(t.privateKeyCoefficient).toHex(),z.setRsaPrivateKey(new ee(n,16),new ee(i,16),new ee(s,16),new ee(o,16),new ee(u,16),new ee(l,16),new ee(f,16),new ee(c,16))};z.privateKeyToAsn1=z.privateKeyToRSAPrivateKey=function(e){return b.create(b.Class.UNIVERSAL,b.Type.SEQUENCE,!0,[b.create(b.Class.UNIVERSAL,b.Type.INTEGER,!1,b.integerToDer(0).getBytes()),b.create(b.Class.UNIVERSAL,b.Type.INTEGER,!1,Rt(e.n)),b.create(b.Class.UNIVERSAL,b.Type.INTEGER,!1,Rt(e.e)),b.create(b.Class.UNIVERSAL,b.Type.INTEGER,!1,Rt(e.d)),b.create(b.Class.UNIVERSAL,b.Type.INTEGER,!1,Rt(e.p)),b.create(b.Class.UNIVERSAL,b.Type.INTEGER,!1,Rt(e.q)),b.create(b.Class.UNIVERSAL,b.Type.INTEGER,!1,Rt(e.dP)),b.create(b.Class.UNIVERSAL,b.Type.INTEGER,!1,Rt(e.dQ)),b.create(b.Class.UNIVERSAL,b.Type.INTEGER,!1,Rt(e.qInv))])};z.publicKeyFromAsn1=function(e){var t={},a=[];if(b.validate(e,N0,t,a)){var r=b.derToOid(t.publicKeyOid);if(r!==z.oids.rsaEncryption){var n=new Error("Cannot read public key. Unknown OID.");throw n.oid=r,n}e=t.rsaPublicKey}if(a=[],!b.validate(e,_0,t,a)){var n=new Error("Cannot read public key. ASN.1 object does not contain an RSAPublicKey.");throw n.errors=a,n}var i=M.util.createBuffer(t.publicKeyModulus).toHex(),s=M.util.createBuffer(t.publicKeyExponent).toHex();return z.setRsaPublicKey(new ee(i,16),new ee(s,16))};z.publicKeyToAsn1=z.publicKeyToSubjectPublicKeyInfo=function(e){return b.create(b.Class.UNIVERSAL,b.Type.SEQUENCE,!0,[b.create(b.Class.UNIVERSAL,b.Type.SEQUENCE,!0,[b.create(b.Class.UNIVERSAL,b.Type.OID,!1,b.oidToDer(z.oids.rsaEncryption).getBytes()),b.create(b.Class.UNIVERSAL,b.Type.NULL,!1,"")]),b.create(b.Class.UNIVERSAL,b.Type.BITSTRING,!1,[z.publicKeyToRSAPublicKey(e)])])};z.publicKeyToRSAPublicKey=function(e){return b.create(b.Class.UNIVERSAL,b.Type.SEQUENCE,!0,[b.create(b.Class.UNIVERSAL,b.Type.INTEGER,!1,Rt(e.n)),b.create(b.Class.UNIVERSAL,b.Type.INTEGER,!1,Rt(e.e))])};function mo(e,t,a){var r=M.util.createBuffer(),n=Math.ceil(t.n.bitLength()/8);if(e.length>n-11){var i=new Error("Message is too long for PKCS#1 v1.5 padding.");throw i.length=e.length,i.max=n-11,i}r.putByte(0),r.putByte(a);var s=n-3-e.length,o;if(a===0||a===1){o=a===0?0:255;for(var u=0;u<s;++u)r.putByte(o)}else for(;s>0;){for(var l=0,f=M.random.getBytes(s),u=0;u<s;++u)o=f.charCodeAt(u),o===0?++l:r.putByte(o);s=l}return r.putByte(0),r.putBytes(e),r}function Da(e,t,a,r){var n=Math.ceil(t.n.bitLength()/8),i=M.util.createBuffer(e),s=i.getByte(),o=i.getByte();if(s!==0||a&&o!==0&&o!==1||!a&&o!=2||a&&o===0&&typeof r>"u")throw new Error("Encryption block is invalid.");var u=0;if(o===0){u=n-3-r;for(var l=0;l<u;++l)if(i.getByte()!==0)throw new Error("Encryption block is invalid.")}else if(o===1)for(u=0;i.length()>1;){if(i.getByte()!==255){--i.read;break}++u}else if(o===2)for(u=0;i.length()>1;){if(i.getByte()===0){--i.read;break}++u}var f=i.getByte();if(f!==0||u!==n-3-i.length())throw new Error("Encryption block is invalid.");return i.getBytes()}function L0(e,t,a){typeof t=="function"&&(a=t,t={}),t=t||{};var r={algorithm:{name:t.algorithm||"PRIMEINC",options:{workers:t.workers||2,workLoad:t.workLoad||100,workerScript:t.workerScript}}};"prng"in t&&(r.prng=t.prng),n();function n(){i(e.pBits,function(o,u){if(o)return a(o);if(e.p=u,e.q!==null)return s(o,e.q);i(e.qBits,s)})}function i(o,u){M.prime.generateProbablePrime(o,r,u)}function s(o,u){if(o)return a(o);if(e.q=u,e.p.compareTo(e.q)<0){var l=e.p;e.p=e.q,e.q=l}if(e.p.subtract(ee.ONE).gcd(e.e).compareTo(ee.ONE)!==0){e.p=null,n();return}if(e.q.subtract(ee.ONE).gcd(e.e).compareTo(ee.ONE)!==0){e.q=null,i(e.qBits,s);return}if(e.p1=e.p.subtract(ee.ONE),e.q1=e.q.subtract(ee.ONE),e.phi=e.p1.multiply(e.q1),e.phi.gcd(e.e).compareTo(ee.ONE)!==0){e.p=e.q=null,n();return}if(e.n=e.p.multiply(e.q),e.n.bitLength()!==e.bits){e.q=null,i(e.qBits,s);return}var f=e.e.modInverse(e.phi);e.keys={privateKey:z.rsa.setPrivateKey(e.n,e.e,f,e.p,e.q,f.mod(e.p1),f.mod(e.q1),e.q.modInverse(e.p)),publicKey:z.rsa.setPublicKey(e.n,e.e)},a(null,e.keys)}}function Rt(e){var t=e.toString(16);t[0]>="8"&&(t="00"+t);var a=M.util.hexToBytes(t);return a.length>1&&(a.charCodeAt(0)===0&&(a.charCodeAt(1)&128)===0||a.charCodeAt(0)===255&&(a.charCodeAt(1)&128)===128)?a.substr(1):a}function k0(e){return e<=100?27:e<=150?18:e<=200?15:e<=250?12:e<=300?9:e<=350?8:e<=400?7:e<=500?6:e<=600?5:e<=800?4:e<=1250?3:2}function co(e){return M.util.isNodejs&&typeof Jn[e]=="function"}function po(e){return typeof ct.globalScope<"u"&&typeof ct.globalScope.crypto=="object"&&typeof ct.globalScope.crypto.subtle=="object"&&typeof ct.globalScope.crypto.subtle[e]=="function"}function ho(e){return typeof ct.globalScope<"u"&&typeof ct.globalScope.msCrypto=="object"&&typeof ct.globalScope.msCrypto.subtle=="object"&&typeof ct.globalScope.msCrypto.subtle[e]=="function"}function go(e){for(var t=M.util.hexToBytes(e.toString(16)),a=new Uint8Array(t.length),r=0;r<t.length;++r)a[r]=t.charCodeAt(r);return a}});var ei=H((Ng,To)=>{"use strict";var O=W();Gt();mt();Hr();St();Qt();Ba();ur();lt();Gn();Qr();re();typeof Eo>"u"&&(Eo=O.jsbn.BigInteger);var Eo,w=O.asn1,Q=O.pki=O.pki||{};To.exports=Q.pbe=O.pbe=O.pbe||{};var cr=Q.oids,U0={name:"EncryptedPrivateKeyInfo",tagClass:w.Class.UNIVERSAL,type:w.Type.SEQUENCE,constructed:!0,value:[{name:"EncryptedPrivateKeyInfo.encryptionAlgorithm",tagClass:w.Class.UNIVERSAL,type:w.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:w.Class.UNIVERSAL,type:w.Type.OID,constructed:!1,capture:"encryptionOid"},{name:"AlgorithmIdentifier.parameters",tagClass:w.Class.UNIVERSAL,type:w.Type.SEQUENCE,constructed:!0,captureAsn1:"encryptionParams"}]},{name:"EncryptedPrivateKeyInfo.encryptedData",tagClass:w.Class.UNIVERSAL,type:w.Type.OCTETSTRING,constructed:!1,capture:"encryptedData"}]},F0={name:"PBES2Algorithms",tagClass:w.Class.UNIVERSAL,type:w.Type.SEQUENCE,constructed:!0,value:[{name:"PBES2Algorithms.keyDerivationFunc",tagClass:w.Class.UNIVERSAL,type:w.Type.SEQUENCE,constructed:!0,value:[{name:"PBES2Algorithms.keyDerivationFunc.oid",tagClass:w.Class.UNIVERSAL,type:w.Type.OID,constructed:!1,capture:"kdfOid"},{name:"PBES2Algorithms.params",tagClass:w.Class.UNIVERSAL,type:w.Type.SEQUENCE,constructed:!0,value:[{name:"PBES2Algorithms.params.salt",tagClass:w.Class.UNIVERSAL,type:w.Type.OCTETSTRING,constructed:!1,capture:"kdfSalt"},{name:"PBES2Algorithms.params.iterationCount",tagClass:w.Class.UNIVERSAL,type:w.Type.INTEGER,constructed:!1,capture:"kdfIterationCount"},{name:"PBES2Algorithms.params.keyLength",tagClass:w.Class.UNIVERSAL,type:w.Type.INTEGER,constructed:!1,optional:!0,capture:"keyLength"},{name:"PBES2Algorithms.params.prf",tagClass:w.Class.UNIVERSAL,type:w.Type.SEQUENCE,constructed:!0,optional:!0,value:[{name:"PBES2Algorithms.params.prf.algorithm",tagClass:w.Class.UNIVERSAL,type:w.Type.OID,constructed:!1,capture:"prfOid"}]}]}]},{name:"PBES2Algorithms.encryptionScheme",tagClass:w.Class.UNIVERSAL,type:w.Type.SEQUENCE,constructed:!0,value:[{name:"PBES2Algorithms.encryptionScheme.oid",tagClass:w.Class.UNIVERSAL,type:w.Type.OID,constructed:!1,capture:"encOid"},{name:"PBES2Algorithms.encryptionScheme.iv",tagClass:w.Class.UNIVERSAL,type:w.Type.OCTETSTRING,constructed:!1,capture:"encIv"}]}]},O0={name:"pkcs-12PbeParams",tagClass:w.Class.UNIVERSAL,type:w.Type.SEQUENCE,constructed:!0,value:[{name:"pkcs-12PbeParams.salt",tagClass:w.Class.UNIVERSAL,type:w.Type.OCTETSTRING,constructed:!1,capture:"salt"},{name:"pkcs-12PbeParams.iterations",tagClass:w.Class.UNIVERSAL,type:w.Type.INTEGER,constructed:!1,capture:"iterations"}]};Q.encryptPrivateKeyInfo=function(e,t,a){a=a||{},a.saltSize=a.saltSize||8,a.count=a.count||2048,a.algorithm=a.algorithm||"aes128",a.prfAlgorithm=a.prfAlgorithm||"sha1";var r=O.random.getBytesSync(a.saltSize),n=a.count,i=w.integerToDer(n),s,o,u;if(a.algorithm.indexOf("aes")===0||a.algorithm==="des"){var l,f,c;switch(a.algorithm){case"aes128":s=16,l=16,f=cr["aes128-CBC"],c=O.aes.createEncryptionCipher;break;case"aes192":s=24,l=16,f=cr["aes192-CBC"],c=O.aes.createEncryptionCipher;break;case"aes256":s=32,l=16,f=cr["aes256-CBC"],c=O.aes.createEncryptionCipher;break;case"des":s=8,l=8,f=cr.desCBC,c=O.des.createEncryptionCipher;break;default:var y=new Error("Cannot encrypt private key. Unknown encryption algorithm.");throw y.algorithm=a.algorithm,y}var m="hmacWith"+a.prfAlgorithm.toUpperCase(),h=So(m),v=O.pkcs5.pbkdf2(t,r,n,s,h),C=O.random.getBytesSync(l),T=c(v);T.start(C),T.update(w.toDer(e)),T.finish(),u=T.output.getBytes();var I=V0(r,i,s,m);o=w.create(w.Class.UNIVERSAL,w.Type.SEQUENCE,!0,[w.create(w.Class.UNIVERSAL,w.Type.OID,!1,w.oidToDer(cr.pkcs5PBES2).getBytes()),w.create(w.Class.UNIVERSAL,w.Type.SEQUENCE,!0,[w.create(w.Class.UNIVERSAL,w.Type.SEQUENCE,!0,[w.create(w.Class.UNIVERSAL,w.Type.OID,!1,w.oidToDer(cr.pkcs5PBKDF2).getBytes()),I]),w.create(w.Class.UNIVERSAL,w.Type.SEQUENCE,!0,[w.create(w.Class.UNIVERSAL,w.Type.OID,!1,w.oidToDer(f).getBytes()),w.create(w.Class.UNIVERSAL,w.Type.OCTETSTRING,!1,C)])])])}else if(a.algorithm==="3des"){s=24;var A=new O.util.ByteBuffer(r),v=Q.pbe.generatePkcs12Key(t,A,1,n,s),C=Q.pbe.generatePkcs12Key(t,A,2,n,s),T=O.des.createEncryptionCipher(v);T.start(C),T.update(w.toDer(e)),T.finish(),u=T.output.getBytes(),o=w.create(w.Class.UNIVERSAL,w.Type.SEQUENCE,!0,[w.create(w.Class.UNIVERSAL,w.Type.OID,!1,w.oidToDer(cr["pbeWithSHAAnd3-KeyTripleDES-CBC"]).getBytes()),w.create(w.Class.UNIVERSAL,w.Type.SEQUENCE,!0,[w.create(w.Class.UNIVERSAL,w.Type.OCTETSTRING,!1,r),w.create(w.Class.UNIVERSAL,w.Type.INTEGER,!1,i.getBytes())])])}else{var y=new Error("Cannot encrypt private key. Unknown encryption algorithm.");throw y.algorithm=a.algorithm,y}var L=w.create(w.Class.UNIVERSAL,w.Type.SEQUENCE,!0,[o,w.create(w.Class.UNIVERSAL,w.Type.OCTETSTRING,!1,u)]);return L};Q.decryptPrivateKeyInfo=function(e,t){var a=null,r={},n=[];if(!w.validate(e,U0,r,n)){var i=new Error("Cannot read encrypted private key. ASN.1 object is not a supported EncryptedPrivateKeyInfo.");throw i.errors=n,i}var s=w.derToOid(r.encryptionOid),o=Q.pbe.getCipher(s,r.encryptionParams,t),u=O.util.createBuffer(r.encryptedData);return o.update(u),o.finish()&&(a=w.fromDer(o.output)),a};Q.encryptedPrivateKeyToPem=function(e,t){var a={type:"ENCRYPTED PRIVATE KEY",body:w.toDer(e).getBytes()};return O.pem.encode(a,{maxline:t})};Q.encryptedPrivateKeyFromPem=function(e){var t=O.pem.decode(e)[0];if(t.type!=="ENCRYPTED PRIVATE KEY"){var a=new Error('Could not convert encrypted private key from PEM; PEM header type is "ENCRYPTED PRIVATE KEY".');throw a.headerType=t.type,a}if(t.procType&&t.procType.type==="ENCRYPTED")throw new Error("Could not convert encrypted private key from PEM; PEM is encrypted.");return w.fromDer(t.body)};Q.encryptRsaPrivateKey=function(e,t,a){if(a=a||{},!a.legacy){var r=Q.wrapRsaPrivateKey(Q.privateKeyToAsn1(e));return r=Q.encryptPrivateKeyInfo(r,t,a),Q.encryptedPrivateKeyToPem(r)}var n,i,s,o;switch(a.algorithm){case"aes128":n="AES-128-CBC",s=16,i=O.random.getBytesSync(16),o=O.aes.createEncryptionCipher;break;case"aes192":n="AES-192-CBC",s=24,i=O.random.getBytesSync(16),o=O.aes.createEncryptionCipher;break;case"aes256":n="AES-256-CBC",s=32,i=O.random.getBytesSync(16),o=O.aes.createEncryptionCipher;break;case"3des":n="DES-EDE3-CBC",s=24,i=O.random.getBytesSync(8),o=O.des.createEncryptionCipher;break;case"des":n="DES-CBC",s=8,i=O.random.getBytesSync(8),o=O.des.createEncryptionCipher;break;default:var u=new Error('Could not encrypt RSA private key; unsupported encryption algorithm "'+a.algorithm+'".');throw u.algorithm=a.algorithm,u}var l=O.pbe.opensslDeriveBytes(t,i.substr(0,8),s),f=o(l);f.start(i),f.update(w.toDer(Q.privateKeyToAsn1(e))),f.finish();var c={type:"RSA PRIVATE KEY",procType:{version:"4",type:"ENCRYPTED"},dekInfo:{algorithm:n,parameters:O.util.bytesToHex(i).toUpperCase()},body:f.output.getBytes()};return O.pem.encode(c)};Q.decryptRsaPrivateKey=function(e,t){var a=null,r=O.pem.decode(e)[0];if(r.type!=="ENCRYPTED PRIVATE KEY"&&r.type!=="PRIVATE KEY"&&r.type!=="RSA PRIVATE KEY"){var n=new Error('Could not convert private key from PEM; PEM header type is not "ENCRYPTED PRIVATE KEY", "PRIVATE KEY", or "RSA PRIVATE KEY".');throw n.headerType=n,n}if(r.procType&&r.procType.type==="ENCRYPTED"){var i,s;switch(r.dekInfo.algorithm){case"DES-CBC":i=8,s=O.des.createDecryptionCipher;break;case"DES-EDE3-CBC":i=24,s=O.des.createDecryptionCipher;break;case"AES-128-CBC":i=16,s=O.aes.createDecryptionCipher;break;case"AES-192-CBC":i=24,s=O.aes.createDecryptionCipher;break;case"AES-256-CBC":i=32,s=O.aes.createDecryptionCipher;break;case"RC2-40-CBC":i=5,s=function(c){return O.rc2.createDecryptionCipher(c,40)};break;case"RC2-64-CBC":i=8,s=function(c){return O.rc2.createDecryptionCipher(c,64)};break;case"RC2-128-CBC":i=16,s=function(c){return O.rc2.createDecryptionCipher(c,128)};break;default:var n=new Error('Could not decrypt private key; unsupported encryption algorithm "'+r.dekInfo.algorithm+'".');throw n.algorithm=r.dekInfo.algorithm,n}var o=O.util.hexToBytes(r.dekInfo.parameters),u=O.pbe.opensslDeriveBytes(t,o.substr(0,8),i),l=s(u);if(l.start(o),l.update(O.util.createBuffer(r.body)),l.finish())a=l.output.getBytes();else return a}else a=r.body;return r.type==="ENCRYPTED PRIVATE KEY"?a=Q.decryptPrivateKeyInfo(w.fromDer(a),t):a=w.fromDer(a),a!==null&&(a=Q.privateKeyFromAsn1(a)),a};Q.pbe.generatePkcs12Key=function(e,t,a,r,n,i){var s,o;if(typeof i>"u"||i===null){if(!("sha1"in O.md))throw new Error('"sha1" hash algorithm unavailable.');i=O.md.sha1.create()}var u=i.digestLength,l=i.blockLength,f=new O.util.ByteBuffer,c=new O.util.ByteBuffer;if(e!=null){for(o=0;o<e.length;o++)c.putInt16(e.charCodeAt(o));c.putInt16(0)}var y=c.length(),m=t.length(),h=new O.util.ByteBuffer;h.fillWithByte(a,l);var v=l*Math.ceil(m/l),C=new O.util.ByteBuffer;for(o=0;o<v;o++)C.putByte(t.at(o%m));var T=l*Math.ceil(y/l),I=new O.util.ByteBuffer;for(o=0;o<T;o++)I.putByte(c.at(o%y));var A=C;A.putBuffer(I);for(var L=Math.ceil(n/u),N=1;N<=L;N++){var P=new O.util.ByteBuffer;P.putBytes(h.bytes()),P.putBytes(A.bytes());for(var G=0;G<r;G++)i.start(),i.update(P.getBytes()),P=i.digest();var j=new O.util.ByteBuffer;for(o=0;o<l;o++)j.putByte(P.at(o%u));var ie=Math.ceil(m/l)+Math.ceil(y/l),oe=new O.util.ByteBuffer;for(s=0;s<ie;s++){var ce=new O.util.ByteBuffer(A.getBytes(l)),he=511;for(o=j.length()-1;o>=0;o--)he=he>>8,he+=j.at(o)+ce.at(o),ce.setAt(o,he&255);oe.putBuffer(ce)}A=oe,f.putBuffer(P)}return f.truncate(f.length()-n),f};Q.pbe.getCipher=function(e,t,a){switch(e){case Q.oids.pkcs5PBES2:return Q.pbe.getCipherForPBES2(e,t,a);case Q.oids["pbeWithSHAAnd3-KeyTripleDES-CBC"]:case Q.oids["pbewithSHAAnd40BitRC2-CBC"]:return Q.pbe.getCipherForPKCS12PBE(e,t,a);default:var r=new Error("Cannot read encrypted PBE data block. Unsupported OID.");throw r.oid=e,r.supportedOids=["pkcs5PBES2","pbeWithSHAAnd3-KeyTripleDES-CBC","pbewithSHAAnd40BitRC2-CBC"],r}};Q.pbe.getCipherForPBES2=function(e,t,a){var r={},n=[];if(!w.validate(t,F0,r,n)){var i=new Error("Cannot read password-based-encryption algorithm parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.");throw i.errors=n,i}if(e=w.derToOid(r.kdfOid),e!==Q.oids.pkcs5PBKDF2){var i=new Error("Cannot read encrypted private key. Unsupported key derivation function OID.");throw i.oid=e,i.supportedOids=["pkcs5PBKDF2"],i}if(e=w.derToOid(r.encOid),e!==Q.oids["aes128-CBC"]&&e!==Q.oids["aes192-CBC"]&&e!==Q.oids["aes256-CBC"]&&e!==Q.oids["des-EDE3-CBC"]&&e!==Q.oids.desCBC){var i=new Error("Cannot read encrypted private key. Unsupported encryption scheme OID.");throw i.oid=e,i.supportedOids=["aes128-CBC","aes192-CBC","aes256-CBC","des-EDE3-CBC","desCBC"],i}var s=r.kdfSalt,o=O.util.createBuffer(r.kdfIterationCount);o=o.getInt(o.length()<<3);var u,l;switch(Q.oids[e]){case"aes128-CBC":u=16,l=O.aes.createDecryptionCipher;break;case"aes192-CBC":u=24,l=O.aes.createDecryptionCipher;break;case"aes256-CBC":u=32,l=O.aes.createDecryptionCipher;break;case"des-EDE3-CBC":u=24,l=O.des.createDecryptionCipher;break;case"desCBC":u=8,l=O.des.createDecryptionCipher;break}var f=xo(r.prfOid),c=O.pkcs5.pbkdf2(a,s,o,u,f),y=r.encIv,m=l(c);return m.start(y),m};Q.pbe.getCipherForPKCS12PBE=function(e,t,a){var r={},n=[];if(!w.validate(t,O0,r,n)){var i=new Error("Cannot read password-based-encryption algorithm parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.");throw i.errors=n,i}var s=O.util.createBuffer(r.salt),o=O.util.createBuffer(r.iterations);o=o.getInt(o.length()<<3);var u,l,f;switch(e){case Q.oids["pbeWithSHAAnd3-KeyTripleDES-CBC"]:u=24,l=8,f=O.des.startDecrypting;break;case Q.oids["pbewithSHAAnd40BitRC2-CBC"]:u=5,l=8,f=function(v,C){var T=O.rc2.createDecryptionCipher(v,40);return T.start(C,null),T};break;default:var i=new Error("Cannot read PKCS #12 PBE data block. Unsupported OID.");throw i.oid=e,i}var c=xo(r.prfOid),y=Q.pbe.generatePkcs12Key(a,s,1,o,u,c);c.start();var m=Q.pbe.generatePkcs12Key(a,s,2,o,l,c);return f(y,m)};Q.pbe.opensslDeriveBytes=function(e,t,a,r){if(typeof r>"u"||r===null){if(!("md5"in O.md))throw new Error('"md5" hash algorithm unavailable.');r=O.md.md5.create()}t===null&&(t="");for(var n=[Co(r,e+t)],i=16,s=1;i<a;++s,i+=16)n.push(Co(r,n[s-1]+e+t));return n.join("").substr(0,a)};function Co(e,t){return e.start().update(t).digest().getBytes()}function xo(e){var t;if(!e)t="hmacWithSHA1";else if(t=Q.oids[w.derToOid(e)],!t){var a=new Error("Unsupported PRF OID.");throw a.oid=e,a.supported=["hmacWithSHA1","hmacWithSHA224","hmacWithSHA256","hmacWithSHA384","hmacWithSHA512"],a}return So(t)}function So(e){var t=O.md;switch(e){case"hmacWithSHA224":t=O.md.sha512;case"hmacWithSHA1":case"hmacWithSHA256":case"hmacWithSHA384":case"hmacWithSHA512":e=e.substr(8).toLowerCase();break;default:var a=new Error("Unsupported PRF algorithm.");throw a.algorithm=e,a.supported=["hmacWithSHA1","hmacWithSHA224","hmacWithSHA256","hmacWithSHA384","hmacWithSHA512"],a}if(!t||!(e in t))throw new Error("Unknown hash algorithm: "+e);return t[e].create()}function V0(e,t,a,r){var n=w.create(w.Class.UNIVERSAL,w.Type.SEQUENCE,!0,[w.create(w.Class.UNIVERSAL,w.Type.OCTETSTRING,!1,e),w.create(w.Class.UNIVERSAL,w.Type.INTEGER,!1,t.getBytes())]);return r!=="hmacWithSHA1"&&n.value.push(w.create(w.Class.UNIVERSAL,w.Type.INTEGER,!1,O.util.hexToBytes(a.toString(16))),w.create(w.Class.UNIVERSAL,w.Type.SEQUENCE,!0,[w.create(w.Class.UNIVERSAL,w.Type.OID,!1,w.oidToDer(Q.oids[r]).getBytes()),w.create(w.Class.UNIVERSAL,w.Type.NULL,!1,"")])),n}});var ti=H((Pg,wo)=>{"use strict";var Br=W();mt();re();var F=Br.asn1,Rr=wo.exports=Br.pkcs7asn1=Br.pkcs7asn1||{};Br.pkcs7=Br.pkcs7||{};Br.pkcs7.asn1=Rr;var bo={name:"ContentInfo",tagClass:F.Class.UNIVERSAL,type:F.Type.SEQUENCE,constructed:!0,value:[{name:"ContentInfo.ContentType",tagClass:F.Class.UNIVERSAL,type:F.Type.OID,constructed:!1,capture:"contentType"},{name:"ContentInfo.content",tagClass:F.Class.CONTEXT_SPECIFIC,type:0,constructed:!0,optional:!0,captureAsn1:"content"}]};Rr.contentInfoValidator=bo;var Io={name:"EncryptedContentInfo",tagClass:F.Class.UNIVERSAL,type:F.Type.SEQUENCE,constructed:!0,value:[{name:"EncryptedContentInfo.contentType",tagClass:F.Class.UNIVERSAL,type:F.Type.OID,constructed:!1,capture:"contentType"},{name:"EncryptedContentInfo.contentEncryptionAlgorithm",tagClass:F.Class.UNIVERSAL,type:F.Type.SEQUENCE,constructed:!0,value:[{name:"EncryptedContentInfo.contentEncryptionAlgorithm.algorithm",tagClass:F.Class.UNIVERSAL,type:F.Type.OID,constructed:!1,capture:"encAlgorithm"},{name:"EncryptedContentInfo.contentEncryptionAlgorithm.parameter",tagClass:F.Class.UNIVERSAL,captureAsn1:"encParameter"}]},{name:"EncryptedContentInfo.encryptedContent",tagClass:F.Class.CONTEXT_SPECIFIC,type:0,capture:"encryptedContent",captureAsn1:"encryptedContentAsn1"}]};Rr.envelopedDataValidator={name:"EnvelopedData",tagClass:F.Class.UNIVERSAL,type:F.Type.SEQUENCE,constructed:!0,value:[{name:"EnvelopedData.Version",tagClass:F.Class.UNIVERSAL,type:F.Type.INTEGER,constructed:!1,capture:"version"},{name:"EnvelopedData.RecipientInfos",tagClass:F.Class.UNIVERSAL,type:F.Type.SET,constructed:!0,captureAsn1:"recipientInfos"}].concat(Io)};Rr.encryptedDataValidator={name:"EncryptedData",tagClass:F.Class.UNIVERSAL,type:F.Type.SEQUENCE,constructed:!0,value:[{name:"EncryptedData.Version",tagClass:F.Class.UNIVERSAL,type:F.Type.INTEGER,constructed:!1,capture:"version"}].concat(Io)};var M0={name:"SignerInfo",tagClass:F.Class.UNIVERSAL,type:F.Type.SEQUENCE,constructed:!0,value:[{name:"SignerInfo.version",tagClass:F.Class.UNIVERSAL,type:F.Type.INTEGER,constructed:!1},{name:"SignerInfo.issuerAndSerialNumber",tagClass:F.Class.UNIVERSAL,type:F.Type.SEQUENCE,constructed:!0,value:[{name:"SignerInfo.issuerAndSerialNumber.issuer",tagClass:F.Class.UNIVERSAL,type:F.Type.SEQUENCE,constructed:!0,captureAsn1:"issuer"},{name:"SignerInfo.issuerAndSerialNumber.serialNumber",tagClass:F.Class.UNIVERSAL,type:F.Type.INTEGER,constructed:!1,capture:"serial"}]},{name:"SignerInfo.digestAlgorithm",tagClass:F.Class.UNIVERSAL,type:F.Type.SEQUENCE,constructed:!0,value:[{name:"SignerInfo.digestAlgorithm.algorithm",tagClass:F.Class.UNIVERSAL,type:F.Type.OID,constructed:!1,capture:"digestAlgorithm"},{name:"SignerInfo.digestAlgorithm.parameter",tagClass:F.Class.UNIVERSAL,constructed:!1,captureAsn1:"digestParameter",optional:!0}]},{name:"SignerInfo.authenticatedAttributes",tagClass:F.Class.CONTEXT_SPECIFIC,type:0,constructed:!0,optional:!0,capture:"authenticatedAttributes"},{name:"SignerInfo.digestEncryptionAlgorithm",tagClass:F.Class.UNIVERSAL,type:F.Type.SEQUENCE,constructed:!0,capture:"signatureAlgorithm"},{name:"SignerInfo.encryptedDigest",tagClass:F.Class.UNIVERSAL,type:F.Type.OCTETSTRING,constructed:!1,capture:"signature"},{name:"SignerInfo.unauthenticatedAttributes",tagClass:F.Class.CONTEXT_SPECIFIC,type:1,constructed:!0,optional:!0,capture:"unauthenticatedAttributes"}]};Rr.signedDataValidator={name:"SignedData",tagClass:F.Class.UNIVERSAL,type:F.Type.SEQUENCE,constructed:!0,value:[{name:"SignedData.Version",tagClass:F.Class.UNIVERSAL,type:F.Type.INTEGER,constructed:!1,capture:"version"},{name:"SignedData.DigestAlgorithms",tagClass:F.Class.UNIVERSAL,type:F.Type.SET,constructed:!0,captureAsn1:"digestAlgorithms"},bo,{name:"SignedData.Certificates",tagClass:F.Class.CONTEXT_SPECIFIC,type:0,optional:!0,captureAsn1:"certificates"},{name:"SignedData.CertificateRevocationLists",tagClass:F.Class.CONTEXT_SPECIFIC,type:1,optional:!0,captureAsn1:"crls"},{name:"SignedData.SignerInfos",tagClass:F.Class.UNIVERSAL,type:F.Type.SET,capture:"signerInfos",optional:!0,value:[M0]}]};Rr.recipientInfoValidator={name:"RecipientInfo",tagClass:F.Class.UNIVERSAL,type:F.Type.SEQUENCE,constructed:!0,value:[{name:"RecipientInfo.version",tagClass:F.Class.UNIVERSAL,type:F.Type.INTEGER,constructed:!1,capture:"version"},{name:"RecipientInfo.issuerAndSerial",tagClass:F.Class.UNIVERSAL,type:F.Type.SEQUENCE,constructed:!0,value:[{name:"RecipientInfo.issuerAndSerial.issuer",tagClass:F.Class.UNIVERSAL,type:F.Type.SEQUENCE,constructed:!0,captureAsn1:"issuer"},{name:"RecipientInfo.issuerAndSerial.serialNumber",tagClass:F.Class.UNIVERSAL,type:F.Type.INTEGER,constructed:!1,capture:"serial"}]},{name:"RecipientInfo.keyEncryptionAlgorithm",tagClass:F.Class.UNIVERSAL,type:F.Type.SEQUENCE,constructed:!0,value:[{name:"RecipientInfo.keyEncryptionAlgorithm.algorithm",tagClass:F.Class.UNIVERSAL,type:F.Type.OID,constructed:!1,capture:"encAlgorithm"},{name:"RecipientInfo.keyEncryptionAlgorithm.parameter",tagClass:F.Class.UNIVERSAL,constructed:!1,captureAsn1:"encParameter",optional:!0}]},{name:"RecipientInfo.encryptedKey",tagClass:F.Class.UNIVERSAL,type:F.Type.OCTETSTRING,constructed:!1,capture:"encKey"}]}});var ri=H((Dg,Ao)=>{"use strict";var dr=W();re();dr.mgf=dr.mgf||{};var K0=Ao.exports=dr.mgf.mgf1=dr.mgf1=dr.mgf1||{};K0.create=function(e){var t={generate:function(a,r){for(var n=new dr.util.ByteBuffer,i=Math.ceil(r/e.digestLength),s=0;s<i;s++){var o=new dr.util.ByteBuffer;o.putInt32(s),e.start(),e.update(a+o.getBytes()),n.putBuffer(e.digest())}return n.truncate(n.length()-r),n.getBytes()}};return t}});var Ro=H((Lg,Bo)=>{"use strict";var La=W();ri();Bo.exports=La.mgf=La.mgf||{};La.mgf.mgf1=La.mgf1});var ka=H((kg,_o)=>{"use strict";var pr=W();lt();re();var q0=_o.exports=pr.pss=pr.pss||{};q0.create=function(e){arguments.length===3&&(e={md:arguments[0],mgf:arguments[1],saltLength:arguments[2]});var t=e.md,a=e.mgf,r=t.digestLength,n=e.salt||null;typeof n=="string"&&(n=pr.util.createBuffer(n));var i;if("saltLength"in e)i=e.saltLength;else if(n!==null)i=n.length();else throw new Error("Salt length not specified or specific salt not given.");if(n!==null&&n.length()!==i)throw new Error("Given salt length does not match length of given salt.");var s=e.prng||pr.random,o={};return o.encode=function(u,l){var f,c=l-1,y=Math.ceil(c/8),m=u.digest().getBytes();if(y<r+i+2)throw new Error("Message is too long to encrypt.");var h;n===null?h=s.getBytesSync(i):h=n.bytes();var v=new pr.util.ByteBuffer;v.fillWithByte(0,8),v.putBytes(m),v.putBytes(h),t.start(),t.update(v.getBytes());var C=t.digest().getBytes(),T=new pr.util.ByteBuffer;T.fillWithByte(0,y-i-r-2),T.putByte(1),T.putBytes(h);var I=T.getBytes(),A=y-r-1,L=a.generate(C,A),N="";for(f=0;f<A;f++)N+=String.fromCharCode(I.charCodeAt(f)^L.charCodeAt(f));var P=65280>>8*y-c&255;return N=String.fromCharCode(N.charCodeAt(0)&~P)+N.substr(1),N+C+"\xBC"},o.verify=function(u,l,f){var c,y=f-1,m=Math.ceil(y/8);if(l=l.substr(-m),m<r+i+2)throw new Error("Inconsistent parameters to PSS signature verification.");if(l.charCodeAt(m-1)!==188)throw new Error("Encoded message does not end in 0xBC.");var h=m-r-1,v=l.substr(0,h),C=l.substr(h,r),T=65280>>8*m-y&255;if((v.charCodeAt(0)&T)!==0)throw new Error("Bits beyond keysize not zero as expected.");var I=a.generate(C,h),A="";for(c=0;c<h;c++)A+=String.fromCharCode(v.charCodeAt(c)^I.charCodeAt(c));A=String.fromCharCode(A.charCodeAt(0)&~T)+A.substr(1);var L=m-r-i-2;for(c=0;c<L;c++)if(A.charCodeAt(c)!==0)throw new Error("Leftmost octets not zero as expected");if(A.charCodeAt(L)!==1)throw new Error("Inconsistent PSS signature, 0x01 marker not found");var N=A.substr(-i),P=new pr.util.ByteBuffer;P.fillWithByte(0,8),P.putBytes(u),P.putBytes(N),t.start(),t.update(P.getBytes());var G=t.digest().getBytes();return C===G},o}});var Oa=H((Ug,ko)=>{"use strict";var K=W();Gt();mt();Hr();St();Ro();Qt();ur();ka();Qr();re();var d=K.asn1,D=ko.exports=K.pki=K.pki||{},te=D.oids,Ce={};Ce.CN=te.commonName;Ce.commonName="CN";Ce.C=te.countryName;Ce.countryName="C";Ce.L=te.localityName;Ce.localityName="L";Ce.ST=te.stateOrProvinceName;Ce.stateOrProvinceName="ST";Ce.O=te.organizationName;Ce.organizationName="O";Ce.OU=te.organizationalUnitName;Ce.organizationalUnitName="OU";Ce.E=te.emailAddress;Ce.emailAddress="E";var Po=K.pki.rsa.publicKeyValidator,H0={name:"Certificate",tagClass:d.Class.UNIVERSAL,type:d.Type.SEQUENCE,constructed:!0,value:[{name:"Certificate.TBSCertificate",tagClass:d.Class.UNIVERSAL,type:d.Type.SEQUENCE,constructed:!0,captureAsn1:"tbsCertificate",value:[{name:"Certificate.TBSCertificate.version",tagClass:d.Class.CONTEXT_SPECIFIC,type:0,constructed:!0,optional:!0,value:[{name:"Certificate.TBSCertificate.version.integer",tagClass:d.Class.UNIVERSAL,type:d.Type.INTEGER,constructed:!1,capture:"certVersion"}]},{name:"Certificate.TBSCertificate.serialNumber",tagClass:d.Class.UNIVERSAL,type:d.Type.INTEGER,constructed:!1,capture:"certSerialNumber"},{name:"Certificate.TBSCertificate.signature",tagClass:d.Class.UNIVERSAL,type:d.Type.SEQUENCE,constructed:!0,value:[{name:"Certificate.TBSCertificate.signature.algorithm",tagClass:d.Class.UNIVERSAL,type:d.Type.OID,constructed:!1,capture:"certinfoSignatureOid"},{name:"Certificate.TBSCertificate.signature.parameters",tagClass:d.Class.UNIVERSAL,optional:!0,captureAsn1:"certinfoSignatureParams"}]},{name:"Certificate.TBSCertificate.issuer",tagClass:d.Class.UNIVERSAL,type:d.Type.SEQUENCE,constructed:!0,captureAsn1:"certIssuer"},{name:"Certificate.TBSCertificate.validity",tagClass:d.Class.UNIVERSAL,type:d.Type.SEQUENCE,constructed:!0,value:[{name:"Certificate.TBSCertificate.validity.notBefore (utc)",tagClass:d.Class.UNIVERSAL,type:d.Type.UTCTIME,constructed:!1,optional:!0,capture:"certValidity1UTCTime"},{name:"Certificate.TBSCertificate.validity.notBefore (generalized)",tagClass:d.Class.UNIVERSAL,type:d.Type.GENERALIZEDTIME,constructed:!1,optional:!0,capture:"certValidity2GeneralizedTime"},{name:"Certificate.TBSCertificate.validity.notAfter (utc)",tagClass:d.Class.UNIVERSAL,type:d.Type.UTCTIME,constructed:!1,optional:!0,capture:"certValidity3UTCTime"},{name:"Certificate.TBSCertificate.validity.notAfter (generalized)",tagClass:d.Class.UNIVERSAL,type:d.Type.GENERALIZEDTIME,constructed:!1,optional:!0,capture:"certValidity4GeneralizedTime"}]},{name:"Certificate.TBSCertificate.subject",tagClass:d.Class.UNIVERSAL,type:d.Type.SEQUENCE,constructed:!0,captureAsn1:"certSubject"},Po,{name:"Certificate.TBSCertificate.issuerUniqueID",tagClass:d.Class.CONTEXT_SPECIFIC,type:1,constructed:!0,optional:!0,value:[{name:"Certificate.TBSCertificate.issuerUniqueID.id",tagClass:d.Class.UNIVERSAL,type:d.Type.BITSTRING,constructed:!1,captureBitStringValue:"certIssuerUniqueId"}]},{name:"Certificate.TBSCertificate.subjectUniqueID",tagClass:d.Class.CONTEXT_SPECIFIC,type:2,constructed:!0,optional:!0,value:[{name:"Certificate.TBSCertificate.subjectUniqueID.id",tagClass:d.Class.UNIVERSAL,type:d.Type.BITSTRING,constructed:!1,captureBitStringValue:"certSubjectUniqueId"}]},{name:"Certificate.TBSCertificate.extensions",tagClass:d.Class.CONTEXT_SPECIFIC,type:3,constructed:!0,captureAsn1:"certExtensions",optional:!0}]},{name:"Certificate.signatureAlgorithm",tagClass:d.Class.UNIVERSAL,type:d.Type.SEQUENCE,constructed:!0,value:[{name:"Certificate.signatureAlgorithm.algorithm",tagClass:d.Class.UNIVERSAL,type:d.Type.OID,constructed:!1,capture:"certSignatureOid"},{name:"Certificate.TBSCertificate.signature.parameters",tagClass:d.Class.UNIVERSAL,optional:!0,captureAsn1:"certSignatureParams"}]},{name:"Certificate.signatureValue",tagClass:d.Class.UNIVERSAL,type:d.Type.BITSTRING,constructed:!1,captureBitStringValue:"certSignature"}]},z0={name:"rsapss",tagClass:d.Class.UNIVERSAL,type:d.Type.SEQUENCE,constructed:!0,value:[{name:"rsapss.hashAlgorithm",tagClass:d.Class.CONTEXT_SPECIFIC,type:0,constructed:!0,value:[{name:"rsapss.hashAlgorithm.AlgorithmIdentifier",tagClass:d.Class.UNIVERSAL,type:d.Class.SEQUENCE,constructed:!0,optional:!0,value:[{name:"rsapss.hashAlgorithm.AlgorithmIdentifier.algorithm",tagClass:d.Class.UNIVERSAL,type:d.Type.OID,constructed:!1,capture:"hashOid"}]}]},{name:"rsapss.maskGenAlgorithm",tagClass:d.Class.CONTEXT_SPECIFIC,type:1,constructed:!0,value:[{name:"rsapss.maskGenAlgorithm.AlgorithmIdentifier",tagClass:d.Class.UNIVERSAL,type:d.Class.SEQUENCE,constructed:!0,optional:!0,value:[{name:"rsapss.maskGenAlgorithm.AlgorithmIdentifier.algorithm",tagClass:d.Class.UNIVERSAL,type:d.Type.OID,constructed:!1,capture:"maskGenOid"},{name:"rsapss.maskGenAlgorithm.AlgorithmIdentifier.params",tagClass:d.Class.UNIVERSAL,type:d.Type.SEQUENCE,constructed:!0,value:[{name:"rsapss.maskGenAlgorithm.AlgorithmIdentifier.params.algorithm",tagClass:d.Class.UNIVERSAL,type:d.Type.OID,constructed:!1,capture:"maskGenHashOid"}]}]}]},{name:"rsapss.saltLength",tagClass:d.Class.CONTEXT_SPECIFIC,type:2,optional:!0,value:[{name:"rsapss.saltLength.saltLength",tagClass:d.Class.UNIVERSAL,type:d.Class.INTEGER,constructed:!1,capture:"saltLength"}]},{name:"rsapss.trailerField",tagClass:d.Class.CONTEXT_SPECIFIC,type:3,optional:!0,value:[{name:"rsapss.trailer.trailer",tagClass:d.Class.UNIVERSAL,type:d.Class.INTEGER,constructed:!1,capture:"trailer"}]}]},G0={name:"CertificationRequestInfo",tagClass:d.Class.UNIVERSAL,type:d.Type.SEQUENCE,constructed:!0,captureAsn1:"certificationRequestInfo",value:[{name:"CertificationRequestInfo.integer",tagClass:d.Class.UNIVERSAL,type:d.Type.INTEGER,constructed:!1,capture:"certificationRequestInfoVersion"},{name:"CertificationRequestInfo.subject",tagClass:d.Class.UNIVERSAL,type:d.Type.SEQUENCE,constructed:!0,captureAsn1:"certificationRequestInfoSubject"},Po,{name:"CertificationRequestInfo.attributes",tagClass:d.Class.CONTEXT_SPECIFIC,type:0,constructed:!0,optional:!0,capture:"certificationRequestInfoAttributes",value:[{name:"CertificationRequestInfo.attributes",tagClass:d.Class.UNIVERSAL,type:d.Type.SEQUENCE,constructed:!0,value:[{name:"CertificationRequestInfo.attributes.type",tagClass:d.Class.UNIVERSAL,type:d.Type.OID,constructed:!1},{name:"CertificationRequestInfo.attributes.value",tagClass:d.Class.UNIVERSAL,type:d.Type.SET,constructed:!0}]}]}]},Q0={name:"CertificationRequest",tagClass:d.Class.UNIVERSAL,type:d.Type.SEQUENCE,constructed:!0,captureAsn1:"csr",value:[G0,{name:"CertificationRequest.signatureAlgorithm",tagClass:d.Class.UNIVERSAL,type:d.Type.SEQUENCE,constructed:!0,value:[{name:"CertificationRequest.signatureAlgorithm.algorithm",tagClass:d.Class.UNIVERSAL,type:d.Type.OID,constructed:!1,capture:"csrSignatureOid"},{name:"CertificationRequest.signatureAlgorithm.parameters",tagClass:d.Class.UNIVERSAL,optional:!0,captureAsn1:"csrSignatureParams"}]},{name:"CertificationRequest.signature",tagClass:d.Class.UNIVERSAL,type:d.Type.BITSTRING,constructed:!1,captureBitStringValue:"csrSignature"}]};D.RDNAttributesAsArray=function(e,t){for(var a=[],r,n,i,s=0;s<e.value.length;++s){r=e.value[s];for(var o=0;o<r.value.length;++o)i={},n=r.value[o],i.type=d.derToOid(n.value[0].value),i.value=n.value[1].value,i.valueTagClass=n.value[1].type,i.type in te&&(i.name=te[i.type],i.name in Ce&&(i.shortName=Ce[i.name])),t&&(t.update(i.type),t.update(i.value)),a.push(i)}return a};D.CRIAttributesAsArray=function(e){for(var t=[],a=0;a<e.length;++a)for(var r=e[a],n=d.derToOid(r.value[0].value),i=r.value[1].value,s=0;s<i.length;++s){var o={};if(o.type=n,o.value=i[s].value,o.valueTagClass=i[s].type,o.type in te&&(o.name=te[o.type],o.name in Ce&&(o.shortName=Ce[o.name])),o.type===te.extensionRequest){o.extensions=[];for(var u=0;u<o.value.length;++u)o.extensions.push(D.certificateExtensionFromAsn1(o.value[u]))}t.push(o)}return t};function $t(e,t){typeof t=="string"&&(t={shortName:t});for(var a=null,r,n=0;a===null&&n<e.attributes.length;++n)r=e.attributes[n],(t.type&&t.type===r.type||t.name&&t.name===r.name||t.shortName&&t.shortName===r.shortName)&&(a=r);return a}var Ua=function(e,t,a){var r={};if(e!==te["RSASSA-PSS"])return r;a&&(r={hash:{algorithmOid:te.sha1},mgf:{algorithmOid:te.mgf1,hash:{algorithmOid:te.sha1}},saltLength:20});var n={},i=[];if(!d.validate(t,z0,n,i)){var s=new Error("Cannot read RSASSA-PSS parameter block.");throw s.errors=i,s}return n.hashOid!==void 0&&(r.hash=r.hash||{},r.hash.algorithmOid=d.derToOid(n.hashOid)),n.maskGenOid!==void 0&&(r.mgf=r.mgf||{},r.mgf.algorithmOid=d.derToOid(n.maskGenOid),r.mgf.hash=r.mgf.hash||{},r.mgf.hash.algorithmOid=d.derToOid(n.maskGenHashOid)),n.saltLength!==void 0&&(r.saltLength=n.saltLength.charCodeAt(0)),r},Fa=function(e){switch(te[e.signatureOid]){case"sha1WithRSAEncryption":case"sha1WithRSASignature":return K.md.sha1.create();case"md5WithRSAEncryption":return K.md.md5.create();case"sha256WithRSAEncryption":return K.md.sha256.create();case"sha384WithRSAEncryption":return K.md.sha384.create();case"sha512WithRSAEncryption":return K.md.sha512.create();case"RSASSA-PSS":return K.md.sha256.create();default:var t=new Error("Could not compute "+e.type+" digest. Unknown signature OID.");throw t.signatureOid=e.signatureOid,t}},Do=function(e){var t=e.certificate,a;switch(t.signatureOid){case te.sha1WithRSAEncryption:case te.sha1WithRSASignature:break;case te["RSASSA-PSS"]:var r,n;if(r=te[t.signatureParameters.mgf.hash.algorithmOid],r===void 0||K.md[r]===void 0){var i=new Error("Unsupported MGF hash function.");throw i.oid=t.signatureParameters.mgf.hash.algorithmOid,i.name=r,i}if(n=te[t.signatureParameters.mgf.algorithmOid],n===void 0||K.mgf[n]===void 0){var i=new Error("Unsupported MGF function.");throw i.oid=t.signatureParameters.mgf.algorithmOid,i.name=n,i}if(n=K.mgf[n].create(K.md[r].create()),r=te[t.signatureParameters.hash.algorithmOid],r===void 0||K.md[r]===void 0){var i=new Error("Unsupported RSASSA-PSS hash function.");throw i.oid=t.signatureParameters.hash.algorithmOid,i.name=r,i}a=K.pss.create(K.md[r].create(),n,t.signatureParameters.saltLength);break}return t.publicKey.verify(e.md.digest().getBytes(),e.signature,a)};D.certificateFromPem=function(e,t,a){var r=K.pem.decode(e)[0];if(r.type!=="CERTIFICATE"&&r.type!=="X509 CERTIFICATE"&&r.type!=="TRUSTED CERTIFICATE"){var n=new Error('Could not convert certificate from PEM; PEM header type is not "CERTIFICATE", "X509 CERTIFICATE", or "TRUSTED CERTIFICATE".');throw n.headerType=r.type,n}if(r.procType&&r.procType.type==="ENCRYPTED")throw new Error("Could not convert certificate from PEM; PEM is encrypted.");var i=d.fromDer(r.body,a);return D.certificateFromAsn1(i,t)};D.certificateToPem=function(e,t){var a={type:"CERTIFICATE",body:d.toDer(D.certificateToAsn1(e)).getBytes()};return K.pem.encode(a,{maxline:t})};D.publicKeyFromPem=function(e){var t=K.pem.decode(e)[0];if(t.type!=="PUBLIC KEY"&&t.type!=="RSA PUBLIC KEY"){var a=new Error('Could not convert public key from PEM; PEM header type is not "PUBLIC KEY" or "RSA PUBLIC KEY".');throw a.headerType=t.type,a}if(t.procType&&t.procType.type==="ENCRYPTED")throw new Error("Could not convert public key from PEM; PEM is encrypted.");var r=d.fromDer(t.body);return D.publicKeyFromAsn1(r)};D.publicKeyToPem=function(e,t){var a={type:"PUBLIC KEY",body:d.toDer(D.publicKeyToAsn1(e)).getBytes()};return K.pem.encode(a,{maxline:t})};D.publicKeyToRSAPublicKeyPem=function(e,t){var a={type:"RSA PUBLIC KEY",body:d.toDer(D.publicKeyToRSAPublicKey(e)).getBytes()};return K.pem.encode(a,{maxline:t})};D.getPublicKeyFingerprint=function(e,t){t=t||{};var a=t.md||K.md.sha1.create(),r=t.type||"RSAPublicKey",n;switch(r){case"RSAPublicKey":n=d.toDer(D.publicKeyToRSAPublicKey(e)).getBytes();break;case"SubjectPublicKeyInfo":n=d.toDer(D.publicKeyToAsn1(e)).getBytes();break;default:throw new Error('Unknown fingerprint type "'+t.type+'".')}a.start(),a.update(n);var i=a.digest();if(t.encoding==="hex"){var s=i.toHex();return t.delimiter?s.match(/.{2}/g).join(t.delimiter):s}else{if(t.encoding==="binary")return i.getBytes();if(t.encoding)throw new Error('Unknown encoding "'+t.encoding+'".')}return i};D.certificationRequestFromPem=function(e,t,a){var r=K.pem.decode(e)[0];if(r.type!=="CERTIFICATE REQUEST"){var n=new Error('Could not convert certification request from PEM; PEM header type is not "CERTIFICATE REQUEST".');throw n.headerType=r.type,n}if(r.procType&&r.procType.type==="ENCRYPTED")throw new Error("Could not convert certification request from PEM; PEM is encrypted.");var i=d.fromDer(r.body,a);return D.certificationRequestFromAsn1(i,t)};D.certificationRequestToPem=function(e,t){var a={type:"CERTIFICATE REQUEST",body:d.toDer(D.certificationRequestToAsn1(e)).getBytes()};return K.pem.encode(a,{maxline:t})};D.createCertificate=function(){var e={};return e.version=2,e.serialNumber="00",e.signatureOid=null,e.signature=null,e.siginfo={},e.siginfo.algorithmOid=null,e.validity={},e.validity.notBefore=new Date,e.validity.notAfter=new Date,e.issuer={},e.issuer.getField=function(t){return $t(e.issuer,t)},e.issuer.addField=function(t){dt([t]),e.issuer.attributes.push(t)},e.issuer.attributes=[],e.issuer.hash=null,e.subject={},e.subject.getField=function(t){return $t(e.subject,t)},e.subject.addField=function(t){dt([t]),e.subject.attributes.push(t)},e.subject.attributes=[],e.subject.hash=null,e.extensions=[],e.publicKey=null,e.md=null,e.setSubject=function(t,a){dt(t),e.subject.attributes=t,delete e.subject.uniqueId,a&&(e.subject.uniqueId=a),e.subject.hash=null},e.setIssuer=function(t,a){dt(t),e.issuer.attributes=t,delete e.issuer.uniqueId,a&&(e.issuer.uniqueId=a),e.issuer.hash=null},e.setExtensions=function(t){for(var a=0;a<t.length;++a)Lo(t[a],{cert:e});e.extensions=t},e.getExtension=function(t){typeof t=="string"&&(t={name:t});for(var a=null,r,n=0;a===null&&n<e.extensions.length;++n)r=e.extensions[n],(t.id&&r.id===t.id||t.name&&r.name===t.name)&&(a=r);return a},e.sign=function(t,a){e.md=a||K.md.sha1.create();var r=te[e.md.algorithm+"WithRSAEncryption"];if(!r){var n=new Error("Could not compute certificate digest. Unknown message digest algorithm OID.");throw n.algorithm=e.md.algorithm,n}e.signatureOid=e.siginfo.algorithmOid=r,e.tbsCertificate=D.getTBSCertificate(e);var i=d.toDer(e.tbsCertificate);e.md.update(i.getBytes()),e.signature=t.sign(e.md)},e.verify=function(t){var a=!1;if(!e.issued(t)){var r=t.issuer,n=e.subject,i=new Error("The parent certificate did not issue the given child certificate; the child certificate's issuer does not match the parent's subject.");throw i.expectedIssuer=n.attributes,i.actualIssuer=r.attributes,i}var s=t.md;if(s===null){s=Fa({signatureOid:t.signatureOid,type:"certificate"});var o=t.tbsCertificate||D.getTBSCertificate(t),u=d.toDer(o);s.update(u.getBytes())}return s!==null&&(a=Do({certificate:e,md:s,signature:t.signature})),a},e.isIssuer=function(t){var a=!1,r=e.issuer,n=t.subject;if(r.hash&&n.hash)a=r.hash===n.hash;else if(r.attributes.length===n.attributes.length){a=!0;for(var i,s,o=0;a&&o<r.attributes.length;++o)i=r.attributes[o],s=n.attributes[o],(i.type!==s.type||i.value!==s.value)&&(a=!1)}return a},e.issued=function(t){return t.isIssuer(e)},e.generateSubjectKeyIdentifier=function(){return D.getPublicKeyFingerprint(e.publicKey,{type:"RSAPublicKey"})},e.verifySubjectKeyIdentifier=function(){for(var t=te.subjectKeyIdentifier,a=0;a<e.extensions.length;++a){var r=e.extensions[a];if(r.id===t){var n=e.generateSubjectKeyIdentifier().getBytes();return K.util.hexToBytes(r.subjectKeyIdentifier)===n}}return!1},e};D.certificateFromAsn1=function(e,t){var a={},r=[];if(!d.validate(e,H0,a,r)){var n=new Error("Cannot read X.509 certificate. ASN.1 object is not an X509v3 Certificate.");throw n.errors=r,n}var i=d.derToOid(a.publicKeyOid);if(i!==D.oids.rsaEncryption)throw new Error("Cannot read public key. OID is not RSA.");var s=D.createCertificate();s.version=a.certVersion?a.certVersion.charCodeAt(0):0;var o=K.util.createBuffer(a.certSerialNumber);s.serialNumber=o.toHex(),s.signatureOid=K.asn1.derToOid(a.certSignatureOid),s.signatureParameters=Ua(s.signatureOid,a.certSignatureParams,!0),s.siginfo.algorithmOid=K.asn1.derToOid(a.certinfoSignatureOid),s.siginfo.parameters=Ua(s.siginfo.algorithmOid,a.certinfoSignatureParams,!1),s.signature=a.certSignature;var u=[];if(a.certValidity1UTCTime!==void 0&&u.push(d.utcTimeToDate(a.certValidity1UTCTime)),a.certValidity2GeneralizedTime!==void 0&&u.push(d.generalizedTimeToDate(a.certValidity2GeneralizedTime)),a.certValidity3UTCTime!==void 0&&u.push(d.utcTimeToDate(a.certValidity3UTCTime)),a.certValidity4GeneralizedTime!==void 0&&u.push(d.generalizedTimeToDate(a.certValidity4GeneralizedTime)),u.length>2)throw new Error("Cannot read notBefore/notAfter validity times; more than two times were provided in the certificate.");if(u.length<2)throw new Error("Cannot read notBefore/notAfter validity times; they were not provided as either UTCTime or GeneralizedTime.");if(s.validity.notBefore=u[0],s.validity.notAfter=u[1],s.tbsCertificate=a.tbsCertificate,t){s.md=Fa({signatureOid:s.signatureOid,type:"certificate"});var l=d.toDer(s.tbsCertificate);s.md.update(l.getBytes())}var f=K.md.sha1.create(),c=d.toDer(a.certIssuer);f.update(c.getBytes()),s.issuer.getField=function(h){return $t(s.issuer,h)},s.issuer.addField=function(h){dt([h]),s.issuer.attributes.push(h)},s.issuer.attributes=D.RDNAttributesAsArray(a.certIssuer),a.certIssuerUniqueId&&(s.issuer.uniqueId=a.certIssuerUniqueId),s.issuer.hash=f.digest().toHex();var y=K.md.sha1.create(),m=d.toDer(a.certSubject);return y.update(m.getBytes()),s.subject.getField=function(h){return $t(s.subject,h)},s.subject.addField=function(h){dt([h]),s.subject.attributes.push(h)},s.subject.attributes=D.RDNAttributesAsArray(a.certSubject),a.certSubjectUniqueId&&(s.subject.uniqueId=a.certSubjectUniqueId),s.subject.hash=y.digest().toHex(),a.certExtensions?s.extensions=D.certificateExtensionsFromAsn1(a.certExtensions):s.extensions=[],s.publicKey=D.publicKeyFromAsn1(a.subjectPublicKeyInfo),s};D.certificateExtensionsFromAsn1=function(e){for(var t=[],a=0;a<e.value.length;++a)for(var r=e.value[a],n=0;n<r.value.length;++n)t.push(D.certificateExtensionFromAsn1(r.value[n]));return t};D.certificateExtensionFromAsn1=function(e){var t={};if(t.id=d.derToOid(e.value[0].value),t.critical=!1,e.value[1].type===d.Type.BOOLEAN?(t.critical=e.value[1].value.charCodeAt(0)!==0,t.value=e.value[2].value):t.value=e.value[1].value,t.id in te){if(t.name=te[t.id],t.name==="keyUsage"){var a=d.fromDer(t.value),r=0,n=0;a.value.length>1&&(r=a.value.charCodeAt(1),n=a.value.length>2?a.value.charCodeAt(2):0),t.digitalSignature=(r&128)===128,t.nonRepudiation=(r&64)===64,t.keyEncipherment=(r&32)===32,t.dataEncipherment=(r&16)===16,t.keyAgreement=(r&8)===8,t.keyCertSign=(r&4)===4,t.cRLSign=(r&2)===2,t.encipherOnly=(r&1)===1,t.decipherOnly=(n&128)===128}else if(t.name==="basicConstraints"){var a=d.fromDer(t.value);a.value.length>0&&a.value[0].type===d.Type.BOOLEAN?t.cA=a.value[0].value.charCodeAt(0)!==0:t.cA=!1;var i=null;a.value.length>0&&a.value[0].type===d.Type.INTEGER?i=a.value[0].value:a.value.length>1&&(i=a.value[1].value),i!==null&&(t.pathLenConstraint=d.derToInteger(i))}else if(t.name==="extKeyUsage")for(var a=d.fromDer(t.value),s=0;s<a.value.length;++s){var o=d.derToOid(a.value[s].value);o in te?t[te[o]]=!0:t[o]=!0}else if(t.name==="nsCertType"){var a=d.fromDer(t.value),r=0;a.value.length>1&&(r=a.value.charCodeAt(1)),t.client=(r&128)===128,t.server=(r&64)===64,t.email=(r&32)===32,t.objsign=(r&16)===16,t.reserved=(r&8)===8,t.sslCA=(r&4)===4,t.emailCA=(r&2)===2,t.objCA=(r&1)===1}else if(t.name==="subjectAltName"||t.name==="issuerAltName"){t.altNames=[];for(var u,a=d.fromDer(t.value),l=0;l<a.value.length;++l){u=a.value[l];var f={type:u.type,value:u.value};switch(t.altNames.push(f),u.type){case 1:case 2:case 6:break;case 7:f.ip=K.util.bytesToIP(u.value);break;case 8:f.oid=d.derToOid(u.value);break;default:}}}else if(t.name==="subjectKeyIdentifier"){var a=d.fromDer(t.value);t.subjectKeyIdentifier=K.util.bytesToHex(a.value)}}return t};D.certificationRequestFromAsn1=function(e,t){var a={},r=[];if(!d.validate(e,Q0,a,r)){var n=new Error("Cannot read PKCS#10 certificate request. ASN.1 object is not a PKCS#10 CertificationRequest.");throw n.errors=r,n}var i=d.derToOid(a.publicKeyOid);if(i!==D.oids.rsaEncryption)throw new Error("Cannot read public key. OID is not RSA.");var s=D.createCertificationRequest();if(s.version=a.csrVersion?a.csrVersion.charCodeAt(0):0,s.signatureOid=K.asn1.derToOid(a.csrSignatureOid),s.signatureParameters=Ua(s.signatureOid,a.csrSignatureParams,!0),s.siginfo.algorithmOid=K.asn1.derToOid(a.csrSignatureOid),s.siginfo.parameters=Ua(s.siginfo.algorithmOid,a.csrSignatureParams,!1),s.signature=a.csrSignature,s.certificationRequestInfo=a.certificationRequestInfo,t){s.md=Fa({signatureOid:s.signatureOid,type:"certification request"});var o=d.toDer(s.certificationRequestInfo);s.md.update(o.getBytes())}var u=K.md.sha1.create();return s.subject.getField=function(l){return $t(s.subject,l)},s.subject.addField=function(l){dt([l]),s.subject.attributes.push(l)},s.subject.attributes=D.RDNAttributesAsArray(a.certificationRequestInfoSubject,u),s.subject.hash=u.digest().toHex(),s.publicKey=D.publicKeyFromAsn1(a.subjectPublicKeyInfo),s.getAttribute=function(l){return $t(s,l)},s.addAttribute=function(l){dt([l]),s.attributes.push(l)},s.attributes=D.CRIAttributesAsArray(a.certificationRequestInfoAttributes||[]),s};D.createCertificationRequest=function(){var e={};return e.version=0,e.signatureOid=null,e.signature=null,e.siginfo={},e.siginfo.algorithmOid=null,e.subject={},e.subject.getField=function(t){return $t(e.subject,t)},e.subject.addField=function(t){dt([t]),e.subject.attributes.push(t)},e.subject.attributes=[],e.subject.hash=null,e.publicKey=null,e.attributes=[],e.getAttribute=function(t){return $t(e,t)},e.addAttribute=function(t){dt([t]),e.attributes.push(t)},e.md=null,e.setSubject=function(t){dt(t),e.subject.attributes=t,e.subject.hash=null},e.setAttributes=function(t){dt(t),e.attributes=t},e.sign=function(t,a){e.md=a||K.md.sha1.create();var r=te[e.md.algorithm+"WithRSAEncryption"];if(!r){var n=new Error("Could not compute certification request digest. Unknown message digest algorithm OID.");throw n.algorithm=e.md.algorithm,n}e.signatureOid=e.siginfo.algorithmOid=r,e.certificationRequestInfo=D.getCertificationRequestInfo(e);var i=d.toDer(e.certificationRequestInfo);e.md.update(i.getBytes()),e.signature=t.sign(e.md)},e.verify=function(){var t=!1,a=e.md;if(a===null){a=Fa({signatureOid:e.signatureOid,type:"certification request"});var r=e.certificationRequestInfo||D.getCertificationRequestInfo(e),n=d.toDer(r);a.update(n.getBytes())}return a!==null&&(t=Do({certificate:e,md:a,signature:e.signature})),t},e};function _r(e){for(var t=d.create(d.Class.UNIVERSAL,d.Type.SEQUENCE,!0,[]),a,r,n=e.attributes,i=0;i<n.length;++i){a=n[i];var s=a.value,o=d.Type.PRINTABLESTRING;"valueTagClass"in a&&(o=a.valueTagClass,o===d.Type.UTF8&&(s=K.util.encodeUtf8(s))),r=d.create(d.Class.UNIVERSAL,d.Type.SET,!0,[d.create(d.Class.UNIVERSAL,d.Type.SEQUENCE,!0,[d.create(d.Class.UNIVERSAL,d.Type.OID,!1,d.oidToDer(a.type).getBytes()),d.create(d.Class.UNIVERSAL,o,!1,s)])]),t.value.push(r)}return t}function dt(e){for(var t,a=0;a<e.length;++a){if(t=e[a],typeof t.name>"u"&&(t.type&&t.type in D.oids?t.name=D.oids[t.type]:t.shortName&&t.shortName in Ce&&(t.name=D.oids[Ce[t.shortName]])),typeof t.type>"u")if(t.name&&t.name in D.oids)t.type=D.oids[t.name];else{var r=new Error("Attribute type not specified.");throw r.attribute=t,r}if(typeof t.shortName>"u"&&t.name&&t.name in Ce&&(t.shortName=Ce[t.name]),t.type===te.extensionRequest&&(t.valueConstructed=!0,t.valueTagClass=d.Type.SEQUENCE,!t.value&&t.extensions)){t.value=[];for(var n=0;n<t.extensions.length;++n)t.value.push(D.certificateExtensionToAsn1(Lo(t.extensions[n])))}if(typeof t.value>"u"){var r=new Error("Attribute value not specified.");throw r.attribute=t,r}}}function Lo(e,t){if(t=t||{},typeof e.name>"u"&&e.id&&e.id in D.oids&&(e.name=D.oids[e.id]),typeof e.id>"u")if(e.name&&e.name in D.oids)e.id=D.oids[e.name];else{var a=new Error("Extension ID not specified.");throw a.extension=e,a}if(typeof e.value<"u")return e;if(e.name==="keyUsage"){var r=0,n=0,i=0;e.digitalSignature&&(n|=128,r=7),e.nonRepudiation&&(n|=64,r=6),e.keyEncipherment&&(n|=32,r=5),e.dataEncipherment&&(n|=16,r=4),e.keyAgreement&&(n|=8,r=3),e.keyCertSign&&(n|=4,r=2),e.cRLSign&&(n|=2,r=1),e.encipherOnly&&(n|=1,r=0),e.decipherOnly&&(i|=128,r=7);var s=String.fromCharCode(r);i!==0?s+=String.fromCharCode(n)+String.fromCharCode(i):n!==0&&(s+=String.fromCharCode(n)),e.value=d.create(d.Class.UNIVERSAL,d.Type.BITSTRING,!1,s)}else if(e.name==="basicConstraints")e.value=d.create(d.Class.UNIVERSAL,d.Type.SEQUENCE,!0,[]),e.cA&&e.value.value.push(d.create(d.Class.UNIVERSAL,d.Type.BOOLEAN,!1,"\xFF")),"pathLenConstraint"in e&&e.value.value.push(d.create(d.Class.UNIVERSAL,d.Type.INTEGER,!1,d.integerToDer(e.pathLenConstraint).getBytes()));else if(e.name==="extKeyUsage"){e.value=d.create(d.Class.UNIVERSAL,d.Type.SEQUENCE,!0,[]);var o=e.value.value;for(var u in e)e[u]===!0&&(u in te?o.push(d.create(d.Class.UNIVERSAL,d.Type.OID,!1,d.oidToDer(te[u]).getBytes())):u.indexOf(".")!==-1&&o.push(d.create(d.Class.UNIVERSAL,d.Type.OID,!1,d.oidToDer(u).getBytes())))}else if(e.name==="nsCertType"){var r=0,n=0;e.client&&(n|=128,r=7),e.server&&(n|=64,r=6),e.email&&(n|=32,r=5),e.objsign&&(n|=16,r=4),e.reserved&&(n|=8,r=3),e.sslCA&&(n|=4,r=2),e.emailCA&&(n|=2,r=1),e.objCA&&(n|=1,r=0);var s=String.fromCharCode(r);n!==0&&(s+=String.fromCharCode(n)),e.value=d.create(d.Class.UNIVERSAL,d.Type.BITSTRING,!1,s)}else if(e.name==="subjectAltName"||e.name==="issuerAltName"){e.value=d.create(d.Class.UNIVERSAL,d.Type.SEQUENCE,!0,[]);for(var l,f=0;f<e.altNames.length;++f){l=e.altNames[f];var s=l.value;if(l.type===7&&l.ip){if(s=K.util.bytesFromIP(l.ip),s===null){var a=new Error('Extension "ip" value is not a valid IPv4 or IPv6 address.');throw a.extension=e,a}}else l.type===8&&(l.oid?s=d.oidToDer(d.oidToDer(l.oid)):s=d.oidToDer(s));e.value.value.push(d.create(d.Class.CONTEXT_SPECIFIC,l.type,!1,s))}}else if(e.name==="nsComment"&&t.cert){if(!/^[\x00-\x7F]*$/.test(e.comment)||e.comment.length<1||e.comment.length>128)throw new Error('Invalid "nsComment" content.');e.value=d.create(d.Class.UNIVERSAL,d.Type.IA5STRING,!1,e.comment)}else if(e.name==="subjectKeyIdentifier"&&t.cert){var c=t.cert.generateSubjectKeyIdentifier();e.subjectKeyIdentifier=c.toHex(),e.value=d.create(d.Class.UNIVERSAL,d.Type.OCTETSTRING,!1,c.getBytes())}else if(e.name==="authorityKeyIdentifier"&&t.cert){e.value=d.create(d.Class.UNIVERSAL,d.Type.SEQUENCE,!0,[]);var o=e.value.value;if(e.keyIdentifier){var y=e.keyIdentifier===!0?t.cert.generateSubjectKeyIdentifier().getBytes():e.keyIdentifier;o.push(d.create(d.Class.CONTEXT_SPECIFIC,0,!1,y))}if(e.authorityCertIssuer){var m=[d.create(d.Class.CONTEXT_SPECIFIC,4,!0,[_r(e.authorityCertIssuer===!0?t.cert.issuer:e.authorityCertIssuer)])];o.push(d.create(d.Class.CONTEXT_SPECIFIC,1,!0,m))}if(e.serialNumber){var h=K.util.hexToBytes(e.serialNumber===!0?t.cert.serialNumber:e.serialNumber);o.push(d.create(d.Class.CONTEXT_SPECIFIC,2,!1,h))}}else if(e.name==="cRLDistributionPoints"){e.value=d.create(d.Class.UNIVERSAL,d.Type.SEQUENCE,!0,[]);for(var o=e.value.value,v=d.create(d.Class.UNIVERSAL,d.Type.SEQUENCE,!0,[]),C=d.create(d.Class.CONTEXT_SPECIFIC,0,!0,[]),l,f=0;f<e.altNames.length;++f){l=e.altNames[f];var s=l.value;if(l.type===7&&l.ip){if(s=K.util.bytesFromIP(l.ip),s===null){var a=new Error('Extension "ip" value is not a valid IPv4 or IPv6 address.');throw a.extension=e,a}}else l.type===8&&(l.oid?s=d.oidToDer(d.oidToDer(l.oid)):s=d.oidToDer(s));C.value.push(d.create(d.Class.CONTEXT_SPECIFIC,l.type,!1,s))}v.value.push(d.create(d.Class.CONTEXT_SPECIFIC,0,!0,[C])),o.push(v)}if(typeof e.value>"u"){var a=new Error("Extension value not specified.");throw a.extension=e,a}return e}function ai(e,t){switch(e){case te["RSASSA-PSS"]:var a=[];return t.hash.algorithmOid!==void 0&&a.push(d.create(d.Class.CONTEXT_SPECIFIC,0,!0,[d.create(d.Class.UNIVERSAL,d.Type.SEQUENCE,!0,[d.create(d.Class.UNIVERSAL,d.Type.OID,!1,d.oidToDer(t.hash.algorithmOid).getBytes()),d.create(d.Class.UNIVERSAL,d.Type.NULL,!1,"")])])),t.mgf.algorithmOid!==void 0&&a.push(d.create(d.Class.CONTEXT_SPECIFIC,1,!0,[d.create(d.Class.UNIVERSAL,d.Type.SEQUENCE,!0,[d.create(d.Class.UNIVERSAL,d.Type.OID,!1,d.oidToDer(t.mgf.algorithmOid).getBytes()),d.create(d.Class.UNIVERSAL,d.Type.SEQUENCE,!0,[d.create(d.Class.UNIVERSAL,d.Type.OID,!1,d.oidToDer(t.mgf.hash.algorithmOid).getBytes()),d.create(d.Class.UNIVERSAL,d.Type.NULL,!1,"")])])])),t.saltLength!==void 0&&a.push(d.create(d.Class.CONTEXT_SPECIFIC,2,!0,[d.create(d.Class.UNIVERSAL,d.Type.INTEGER,!1,d.integerToDer(t.saltLength).getBytes())])),d.create(d.Class.UNIVERSAL,d.Type.SEQUENCE,!0,a);default:return d.create(d.Class.UNIVERSAL,d.Type.NULL,!1,"")}}function W0(e){var t=d.create(d.Class.CONTEXT_SPECIFIC,0,!0,[]);if(e.attributes.length===0)return t;for(var a=e.attributes,r=0;r<a.length;++r){var n=a[r],i=n.value,s=d.Type.UTF8;"valueTagClass"in n&&(s=n.valueTagClass),s===d.Type.UTF8&&(i=K.util.encodeUtf8(i));var o=!1;"valueConstructed"in n&&(o=n.valueConstructed);var u=d.create(d.Class.UNIVERSAL,d.Type.SEQUENCE,!0,[d.create(d.Class.UNIVERSAL,d.Type.OID,!1,d.oidToDer(n.type).getBytes()),d.create(d.Class.UNIVERSAL,d.Type.SET,!0,[d.create(d.Class.UNIVERSAL,s,o,i)])]);t.value.push(u)}return t}var j0=new Date("1950-01-01T00:00:00Z"),$0=new Date("2050-01-01T00:00:00Z");function No(e){return e>=j0&&e<$0?d.create(d.Class.UNIVERSAL,d.Type.UTCTIME,!1,d.dateToUtcTime(e)):d.create(d.Class.UNIVERSAL,d.Type.GENERALIZEDTIME,!1,d.dateToGeneralizedTime(e))}D.getTBSCertificate=function(e){var t=No(e.validity.notBefore),a=No(e.validity.notAfter),r=d.create(d.Class.UNIVERSAL,d.Type.SEQUENCE,!0,[d.create(d.Class.CONTEXT_SPECIFIC,0,!0,[d.create(d.Class.UNIVERSAL,d.Type.INTEGER,!1,d.integerToDer(e.version).getBytes())]),d.create(d.Class.UNIVERSAL,d.Type.INTEGER,!1,K.util.hexToBytes(e.serialNumber)),d.create(d.Class.UNIVERSAL,d.Type.SEQUENCE,!0,[d.create(d.Class.UNIVERSAL,d.Type.OID,!1,d.oidToDer(e.siginfo.algorithmOid).getBytes()),ai(e.siginfo.algorithmOid,e.siginfo.parameters)]),_r(e.issuer),d.create(d.Class.UNIVERSAL,d.Type.SEQUENCE,!0,[t,a]),_r(e.subject),D.publicKeyToAsn1(e.publicKey)]);return e.issuer.uniqueId&&r.value.push(d.create(d.Class.CONTEXT_SPECIFIC,1,!0,[d.create(d.Class.UNIVERSAL,d.Type.BITSTRING,!1,"\0"+e.issuer.uniqueId)])),e.subject.uniqueId&&r.value.push(d.create(d.Class.CONTEXT_SPECIFIC,2,!0,[d.create(d.Class.UNIVERSAL,d.Type.BITSTRING,!1,"\0"+e.subject.uniqueId)])),e.extensions.length>0&&r.value.push(D.certificateExtensionsToAsn1(e.extensions)),r};D.getCertificationRequestInfo=function(e){var t=d.create(d.Class.UNIVERSAL,d.Type.SEQUENCE,!0,[d.create(d.Class.UNIVERSAL,d.Type.INTEGER,!1,d.integerToDer(e.version).getBytes()),_r(e.subject),D.publicKeyToAsn1(e.publicKey),W0(e)]);return t};D.distinguishedNameToAsn1=function(e){return _r(e)};D.certificateToAsn1=function(e){var t=e.tbsCertificate||D.getTBSCertificate(e);return d.create(d.Class.UNIVERSAL,d.Type.SEQUENCE,!0,[t,d.create(d.Class.UNIVERSAL,d.Type.SEQUENCE,!0,[d.create(d.Class.UNIVERSAL,d.Type.OID,!1,d.oidToDer(e.signatureOid).getBytes()),ai(e.signatureOid,e.signatureParameters)]),d.create(d.Class.UNIVERSAL,d.Type.BITSTRING,!1,"\0"+e.signature)])};D.certificateExtensionsToAsn1=function(e){var t=d.create(d.Class.CONTEXT_SPECIFIC,3,!0,[]),a=d.create(d.Class.UNIVERSAL,d.Type.SEQUENCE,!0,[]);t.value.push(a);for(var r=0;r<e.length;++r)a.value.push(D.certificateExtensionToAsn1(e[r]));return t};D.certificateExtensionToAsn1=function(e){var t=d.create(d.Class.UNIVERSAL,d.Type.SEQUENCE,!0,[]);t.value.push(d.create(d.Class.UNIVERSAL,d.Type.OID,!1,d.oidToDer(e.id).getBytes())),e.critical&&t.value.push(d.create(d.Class.UNIVERSAL,d.Type.BOOLEAN,!1,"\xFF"));var a=e.value;return typeof e.value!="string"&&(a=d.toDer(a).getBytes()),t.value.push(d.create(d.Class.UNIVERSAL,d.Type.OCTETSTRING,!1,a)),t};D.certificationRequestToAsn1=function(e){var t=e.certificationRequestInfo||D.getCertificationRequestInfo(e);return d.create(d.Class.UNIVERSAL,d.Type.SEQUENCE,!0,[t,d.create(d.Class.UNIVERSAL,d.Type.SEQUENCE,!0,[d.create(d.Class.UNIVERSAL,d.Type.OID,!1,d.oidToDer(e.signatureOid).getBytes()),ai(e.signatureOid,e.signatureParameters)]),d.create(d.Class.UNIVERSAL,d.Type.BITSTRING,!1,"\0"+e.signature)])};D.createCaStore=function(e){var t={certs:{}};t.getIssuer=function(s){var o=a(s.issuer);return o},t.addCertificate=function(s){if(typeof s=="string"&&(s=K.pki.certificateFromPem(s)),r(s.subject),!t.hasCertificate(s))if(s.subject.hash in t.certs){var o=t.certs[s.subject.hash];K.util.isArray(o)||(o=[o]),o.push(s),t.certs[s.subject.hash]=o}else t.certs[s.subject.hash]=s},t.hasCertificate=function(s){typeof s=="string"&&(s=K.pki.certificateFromPem(s));var o=a(s.subject);if(!o)return!1;K.util.isArray(o)||(o=[o]);for(var u=d.toDer(D.certificateToAsn1(s)).getBytes(),l=0;l<o.length;++l){var f=d.toDer(D.certificateToAsn1(o[l])).getBytes();if(u===f)return!0}return!1},t.listAllCertificates=function(){var s=[];for(var o in t.certs)if(t.certs.hasOwnProperty(o)){var u=t.certs[o];if(!K.util.isArray(u))s.push(u);else for(var l=0;l<u.length;++l)s.push(u[l])}return s},t.removeCertificate=function(s){var o;if(typeof s=="string"&&(s=K.pki.certificateFromPem(s)),r(s.subject),!t.hasCertificate(s))return null;var u=a(s.subject);if(!K.util.isArray(u))return o=t.certs[s.subject.hash],delete t.certs[s.subject.hash],o;for(var l=d.toDer(D.certificateToAsn1(s)).getBytes(),f=0;f<u.length;++f){var c=d.toDer(D.certificateToAsn1(u[f])).getBytes();l===c&&(o=u[f],u.splice(f,1))}return u.length===0&&delete t.certs[s.subject.hash],o};function a(s){return r(s),t.certs[s.hash]||null}function r(s){if(!s.hash){var o=K.md.sha1.create();s.attributes=D.RDNAttributesAsArray(_r(s),o),s.hash=o.digest().toHex()}}if(e)for(var n=0;n<e.length;++n){var i=e[n];t.addCertificate(i)}return t};D.certificateError={bad_certificate:"forge.pki.BadCertificate",unsupported_certificate:"forge.pki.UnsupportedCertificate",certificate_revoked:"forge.pki.CertificateRevoked",certificate_expired:"forge.pki.CertificateExpired",certificate_unknown:"forge.pki.CertificateUnknown",unknown_ca:"forge.pki.UnknownCertificateAuthority"};D.verifyCertificateChain=function(e,t,a){typeof a=="function"&&(a={verify:a}),a=a||{},t=t.slice(0);var r=t.slice(0),n=a.validityCheckDate;typeof n>"u"&&(n=new Date);var i=!0,s=null,o=0;do{var u=t.shift(),l=null,f=!1;if(n&&(n<u.validity.notBefore||n>u.validity.notAfter)&&(s={message:"Certificate is not valid yet or has expired.",error:D.certificateError.certificate_expired,notBefore:u.validity.notBefore,notAfter:u.validity.notAfter,now:n}),s===null){if(l=t[0]||e.getIssuer(u),l===null&&u.isIssuer(u)&&(f=!0,l=u),l){var c=l;K.util.isArray(c)||(c=[c]);for(var y=!1;!y&&c.length>0;){l=c.shift();try{y=l.verify(u)}catch{}}y||(s={message:"Certificate signature is invalid.",error:D.certificateError.bad_certificate})}s===null&&(!l||f)&&!e.hasCertificate(u)&&(s={message:"Certificate is not trusted.",error:D.certificateError.unknown_ca})}if(s===null&&l&&!u.isIssuer(l)&&(s={message:"Certificate issuer is invalid.",error:D.certificateError.bad_certificate}),s===null)for(var m={keyUsage:!0,basicConstraints:!0},h=0;s===null&&h<u.extensions.length;++h){var v=u.extensions[h];v.critical&&!(v.name in m)&&(s={message:"Certificate has an unsupported critical extension.",error:D.certificateError.unsupported_certificate})}if(s===null&&(!i||t.length===0&&(!l||f))){var C=u.getExtension("basicConstraints"),T=u.getExtension("keyUsage");if(T!==null&&(!T.keyCertSign||C===null)&&(s={message:"Certificate keyUsage or basicConstraints conflict or indicate that the certificate is not a CA. If the certificate is the only one in the chain or isn't the first then the certificate must be a valid CA.",error:D.certificateError.bad_certificate}),s===null&&C!==null&&!C.cA&&(s={message:"Certificate basicConstraints indicates the certificate is not a CA.",error:D.certificateError.bad_certificate}),s===null&&T!==null&&"pathLenConstraint"in C){var I=o-1;I>C.pathLenConstraint&&(s={message:"Certificate basicConstraints pathLenConstraint violated.",error:D.certificateError.bad_certificate})}}var A=s===null?!0:s.error,L=a.verify?a.verify(A,o,r):A;if(L===!0)s=null;else throw A===!0&&(s={message:"The application rejected the certificate.",error:D.certificateError.bad_certificate}),(L||L===0)&&(typeof L=="object"&&!K.util.isArray(L)?(L.message&&(s.message=L.message),L.error&&(s.error=L.error)):typeof L=="string"&&(s.error=L)),s;i=!1,++o}while(t.length>0);return!0}});var ii=H((Fg,Fo)=>{"use strict";var pe=W();mt();Tr();Qt();ti();ei();lt();Qr();Ar();re();Oa();var E=pe.asn1,Y=pe.pki,jr=Fo.exports=pe.pkcs12=pe.pkcs12||{},Uo={name:"ContentInfo",tagClass:E.Class.UNIVERSAL,type:E.Type.SEQUENCE,constructed:!0,value:[{name:"ContentInfo.contentType",tagClass:E.Class.UNIVERSAL,type:E.Type.OID,constructed:!1,capture:"contentType"},{name:"ContentInfo.content",tagClass:E.Class.CONTEXT_SPECIFIC,constructed:!0,captureAsn1:"content"}]},Y0={name:"PFX",tagClass:E.Class.UNIVERSAL,type:E.Type.SEQUENCE,constructed:!0,value:[{name:"PFX.version",tagClass:E.Class.UNIVERSAL,type:E.Type.INTEGER,constructed:!1,capture:"version"},Uo,{name:"PFX.macData",tagClass:E.Class.UNIVERSAL,type:E.Type.SEQUENCE,constructed:!0,optional:!0,captureAsn1:"mac",value:[{name:"PFX.macData.mac",tagClass:E.Class.UNIVERSAL,type:E.Type.SEQUENCE,constructed:!0,value:[{name:"PFX.macData.mac.digestAlgorithm",tagClass:E.Class.UNIVERSAL,type:E.Type.SEQUENCE,constructed:!0,value:[{name:"PFX.macData.mac.digestAlgorithm.algorithm",tagClass:E.Class.UNIVERSAL,type:E.Type.OID,constructed:!1,capture:"macAlgorithm"},{name:"PFX.macData.mac.digestAlgorithm.parameters",tagClass:E.Class.UNIVERSAL,captureAsn1:"macAlgorithmParameters"}]},{name:"PFX.macData.mac.digest",tagClass:E.Class.UNIVERSAL,type:E.Type.OCTETSTRING,constructed:!1,capture:"macDigest"}]},{name:"PFX.macData.macSalt",tagClass:E.Class.UNIVERSAL,type:E.Type.OCTETSTRING,constructed:!1,capture:"macSalt"},{name:"PFX.macData.iterations",tagClass:E.Class.UNIVERSAL,type:E.Type.INTEGER,constructed:!1,optional:!0,capture:"macIterations"}]}]},X0={name:"SafeBag",tagClass:E.Class.UNIVERSAL,type:E.Type.SEQUENCE,constructed:!0,value:[{name:"SafeBag.bagId",tagClass:E.Class.UNIVERSAL,type:E.Type.OID,constructed:!1,capture:"bagId"},{name:"SafeBag.bagValue",tagClass:E.Class.CONTEXT_SPECIFIC,constructed:!0,captureAsn1:"bagValue"},{name:"SafeBag.bagAttributes",tagClass:E.Class.UNIVERSAL,type:E.Type.SET,constructed:!0,optional:!0,capture:"bagAttributes"}]},Z0={name:"Attribute",tagClass:E.Class.UNIVERSAL,type:E.Type.SEQUENCE,constructed:!0,value:[{name:"Attribute.attrId",tagClass:E.Class.UNIVERSAL,type:E.Type.OID,constructed:!1,capture:"oid"},{name:"Attribute.attrValues",tagClass:E.Class.UNIVERSAL,type:E.Type.SET,constructed:!0,capture:"values"}]},J0={name:"CertBag",tagClass:E.Class.UNIVERSAL,type:E.Type.SEQUENCE,constructed:!0,value:[{name:"CertBag.certId",tagClass:E.Class.UNIVERSAL,type:E.Type.OID,constructed:!1,capture:"certId"},{name:"CertBag.certValue",tagClass:E.Class.CONTEXT_SPECIFIC,constructed:!0,value:[{name:"CertBag.certValue[0]",tagClass:E.Class.UNIVERSAL,type:E.Class.OCTETSTRING,constructed:!1,capture:"cert"}]}]};function Wr(e,t,a,r){for(var n=[],i=0;i<e.length;i++)for(var s=0;s<e[i].safeBags.length;s++){var o=e[i].safeBags[s];if(!(r!==void 0&&o.type!==r)){if(t===null){n.push(o);continue}o.attributes[t]!==void 0&&o.attributes[t].indexOf(a)>=0&&n.push(o)}}return n}jr.pkcs12FromAsn1=function(e,t,a){typeof t=="string"?(a=t,t=!0):t===void 0&&(t=!0);var r={},n=[];if(!E.validate(e,Y0,r,n)){var i=new Error("Cannot read PKCS#12 PFX. ASN.1 object is not an PKCS#12 PFX.");throw i.errors=i,i}var s={version:r.version.charCodeAt(0),safeContents:[],getBags:function(C){var T={},I;return"localKeyId"in C?I=C.localKeyId:"localKeyIdHex"in C&&(I=pe.util.hexToBytes(C.localKeyIdHex)),I===void 0&&!("friendlyName"in C)&&"bagType"in C&&(T[C.bagType]=Wr(s.safeContents,null,null,C.bagType)),I!==void 0&&(T.localKeyId=Wr(s.safeContents,"localKeyId",I,C.bagType)),"friendlyName"in C&&(T.friendlyName=Wr(s.safeContents,"friendlyName",C.friendlyName,C.bagType)),T},getBagsByFriendlyName:function(C,T){return Wr(s.safeContents,"friendlyName",C,T)},getBagsByLocalKeyId:function(C,T){return Wr(s.safeContents,"localKeyId",C,T)}};if(r.version.charCodeAt(0)!==3){var i=new Error("PKCS#12 PFX of version other than 3 not supported.");throw i.version=r.version.charCodeAt(0),i}if(E.derToOid(r.contentType)!==Y.oids.data){var i=new Error("Only PKCS#12 PFX in password integrity mode supported.");throw i.oid=E.derToOid(r.contentType),i}var o=r.content.value[0];if(o.tagClass!==E.Class.UNIVERSAL||o.type!==E.Type.OCTETSTRING)throw new Error("PKCS#12 authSafe content data is not an OCTET STRING.");if(o=ni(o),r.mac){var u=null,l=0,f=E.derToOid(r.macAlgorithm);switch(f){case Y.oids.sha1:u=pe.md.sha1.create(),l=20;break;case Y.oids.sha256:u=pe.md.sha256.create(),l=32;break;case Y.oids.sha384:u=pe.md.sha384.create(),l=48;break;case Y.oids.sha512:u=pe.md.sha512.create(),l=64;break;case Y.oids.md5:u=pe.md.md5.create(),l=16;break}if(u===null)throw new Error("PKCS#12 uses unsupported MAC algorithm: "+f);var c=new pe.util.ByteBuffer(r.macSalt),y="macIterations"in r?parseInt(pe.util.bytesToHex(r.macIterations),16):1,m=jr.generateKey(a,c,3,y,l,u),h=pe.hmac.create();h.start(u,m),h.update(o.value);var v=h.getMac();if(v.getBytes()!==r.macDigest)throw new Error("PKCS#12 MAC could not be verified. Invalid password?")}return ed(s,o.value,t,a),s};function ni(e){if(e.composed||e.constructed){for(var t=pe.util.createBuffer(),a=0;a<e.value.length;++a)t.putBytes(e.value[a].value);e.composed=e.constructed=!1,e.value=t.getBytes()}return e}function ed(e,t,a,r){if(t=E.fromDer(t,a),t.tagClass!==E.Class.UNIVERSAL||t.type!==E.Type.SEQUENCE||t.constructed!==!0)throw new Error("PKCS#12 AuthenticatedSafe expected to be a SEQUENCE OF ContentInfo");for(var n=0;n<t.value.length;n++){var i=t.value[n],s={},o=[];if(!E.validate(i,Uo,s,o)){var u=new Error("Cannot read ContentInfo.");throw u.errors=o,u}var l={encrypted:!1},f=null,c=s.content.value[0];switch(E.derToOid(s.contentType)){case Y.oids.data:if(c.tagClass!==E.Class.UNIVERSAL||c.type!==E.Type.OCTETSTRING)throw new Error("PKCS#12 SafeContents Data is not an OCTET STRING.");f=ni(c).value;break;case Y.oids.encryptedData:f=td(c,r),l.encrypted=!0;break;default:var u=new Error("Unsupported PKCS#12 contentType.");throw u.contentType=E.derToOid(s.contentType),u}l.safeBags=rd(f,a,r),e.safeContents.push(l)}}function td(e,t){var a={},r=[];if(!E.validate(e,pe.pkcs7.asn1.encryptedDataValidator,a,r)){var n=new Error("Cannot read EncryptedContentInfo.");throw n.errors=r,n}var i=E.derToOid(a.contentType);if(i!==Y.oids.data){var n=new Error("PKCS#12 EncryptedContentInfo ContentType is not Data.");throw n.oid=i,n}i=E.derToOid(a.encAlgorithm);var s=Y.pbe.getCipher(i,a.encParameter,t),o=ni(a.encryptedContentAsn1),u=pe.util.createBuffer(o.value);if(s.update(u),!s.finish())throw new Error("Failed to decrypt PKCS#12 SafeContents.");return s.output.getBytes()}function rd(e,t,a){if(!t&&e.length===0)return[];if(e=E.fromDer(e,t),e.tagClass!==E.Class.UNIVERSAL||e.type!==E.Type.SEQUENCE||e.constructed!==!0)throw new Error("PKCS#12 SafeContents expected to be a SEQUENCE OF SafeBag.");for(var r=[],n=0;n<e.value.length;n++){var i=e.value[n],s={},o=[];if(!E.validate(i,X0,s,o)){var u=new Error("Cannot read SafeBag.");throw u.errors=o,u}var l={type:E.derToOid(s.bagId),attributes:ad(s.bagAttributes)};r.push(l);var f,c,y=s.bagValue.value[0];switch(l.type){case Y.oids.pkcs8ShroudedKeyBag:if(y=Y.decryptPrivateKeyInfo(y,a),y===null)throw new Error("Unable to decrypt PKCS#8 ShroudedKeyBag, wrong password?");case Y.oids.keyBag:try{l.key=Y.privateKeyFromAsn1(y)}catch{l.key=null,l.asn1=y}continue;case Y.oids.certBag:f=J0,c=function(){if(E.derToOid(s.certId)!==Y.oids.x509Certificate){var h=new Error("Unsupported certificate type, only X.509 supported.");throw h.oid=E.derToOid(s.certId),h}var v=E.fromDer(s.cert,t);try{l.cert=Y.certificateFromAsn1(v,!0)}catch{l.cert=null,l.asn1=v}};break;default:var u=new Error("Unsupported PKCS#12 SafeBag type.");throw u.oid=l.type,u}if(f!==void 0&&!E.validate(y,f,s,o)){var u=new Error("Cannot read PKCS#12 "+f.name);throw u.errors=o,u}c()}return r}function ad(e){var t={};if(e!==void 0)for(var a=0;a<e.length;++a){var r={},n=[];if(!E.validate(e[a],Z0,r,n)){var i=new Error("Cannot read PKCS#12 BagAttribute.");throw i.errors=n,i}var s=E.derToOid(r.oid);if(Y.oids[s]!==void 0){t[Y.oids[s]]=[];for(var o=0;o<r.values.length;++o)t[Y.oids[s]].push(r.values[o].value)}}return t}jr.toPkcs12Asn1=function(e,t,a,r){r=r||{},r.saltSize=r.saltSize||8,r.count=r.count||2048,r.algorithm=r.algorithm||r.encAlgorithm||"aes128","useMac"in r||(r.useMac=!0),"localKeyId"in r||(r.localKeyId=null),"generateLocalKeyId"in r||(r.generateLocalKeyId=!0);var n=r.localKeyId,i;if(n!==null)n=pe.util.hexToBytes(n);else if(r.generateLocalKeyId)if(t){var s=pe.util.isArray(t)?t[0]:t;typeof s=="string"&&(s=Y.certificateFromPem(s));var o=pe.md.sha1.create();o.update(E.toDer(Y.certificateToAsn1(s)).getBytes()),n=o.digest().getBytes()}else n=pe.random.getBytes(20);var u=[];n!==null&&u.push(E.create(E.Class.UNIVERSAL,E.Type.SEQUENCE,!0,[E.create(E.Class.UNIVERSAL,E.Type.OID,!1,E.oidToDer(Y.oids.localKeyId).getBytes()),E.create(E.Class.UNIVERSAL,E.Type.SET,!0,[E.create(E.Class.UNIVERSAL,E.Type.OCTETSTRING,!1,n)])])),"friendlyName"in r&&u.push(E.create(E.Class.UNIVERSAL,E.Type.SEQUENCE,!0,[E.create(E.Class.UNIVERSAL,E.Type.OID,!1,E.oidToDer(Y.oids.friendlyName).getBytes()),E.create(E.Class.UNIVERSAL,E.Type.SET,!0,[E.create(E.Class.UNIVERSAL,E.Type.BMPSTRING,!1,r.friendlyName)])])),u.length>0&&(i=E.create(E.Class.UNIVERSAL,E.Type.SET,!0,u));var l=[],f=[];t!==null&&(pe.util.isArray(t)?f=t:f=[t]);for(var c=[],y=0;y<f.length;++y){t=f[y],typeof t=="string"&&(t=Y.certificateFromPem(t));var m=y===0?i:void 0,h=Y.certificateToAsn1(t),v=E.create(E.Class.UNIVERSAL,E.Type.SEQUENCE,!0,[E.create(E.Class.UNIVERSAL,E.Type.OID,!1,E.oidToDer(Y.oids.certBag).getBytes()),E.create(E.Class.CONTEXT_SPECIFIC,0,!0,[E.create(E.Class.UNIVERSAL,E.Type.SEQUENCE,!0,[E.create(E.Class.UNIVERSAL,E.Type.OID,!1,E.oidToDer(Y.oids.x509Certificate).getBytes()),E.create(E.Class.CONTEXT_SPECIFIC,0,!0,[E.create(E.Class.UNIVERSAL,E.Type.OCTETSTRING,!1,E.toDer(h).getBytes())])])]),m]);c.push(v)}if(c.length>0){var C=E.create(E.Class.UNIVERSAL,E.Type.SEQUENCE,!0,c),T=E.create(E.Class.UNIVERSAL,E.Type.SEQUENCE,!0,[E.create(E.Class.UNIVERSAL,E.Type.OID,!1,E.oidToDer(Y.oids.data).getBytes()),E.create(E.Class.CONTEXT_SPECIFIC,0,!0,[E.create(E.Class.UNIVERSAL,E.Type.OCTETSTRING,!1,E.toDer(C).getBytes())])]);l.push(T)}var I=null;if(e!==null){var A=Y.wrapRsaPrivateKey(Y.privateKeyToAsn1(e));a===null?I=E.create(E.Class.UNIVERSAL,E.Type.SEQUENCE,!0,[E.create(E.Class.UNIVERSAL,E.Type.OID,!1,E.oidToDer(Y.oids.keyBag).getBytes()),E.create(E.Class.CONTEXT_SPECIFIC,0,!0,[A]),i]):I=E.create(E.Class.UNIVERSAL,E.Type.SEQUENCE,!0,[E.create(E.Class.UNIVERSAL,E.Type.OID,!1,E.oidToDer(Y.oids.pkcs8ShroudedKeyBag).getBytes()),E.create(E.Class.CONTEXT_SPECIFIC,0,!0,[Y.encryptPrivateKeyInfo(A,a,r)]),i]);var L=E.create(E.Class.UNIVERSAL,E.Type.SEQUENCE,!0,[I]),N=E.create(E.Class.UNIVERSAL,E.Type.SEQUENCE,!0,[E.create(E.Class.UNIVERSAL,E.Type.OID,!1,E.oidToDer(Y.oids.data).getBytes()),E.create(E.Class.CONTEXT_SPECIFIC,0,!0,[E.create(E.Class.UNIVERSAL,E.Type.OCTETSTRING,!1,E.toDer(L).getBytes())])]);l.push(N)}var P=E.create(E.Class.UNIVERSAL,E.Type.SEQUENCE,!0,l),G;if(r.useMac){var o=pe.md.sha1.create(),j=new pe.util.ByteBuffer(pe.random.getBytes(r.saltSize)),ie=r.count,e=jr.generateKey(a,j,3,ie,20),oe=pe.hmac.create();oe.start(o,e),oe.update(E.toDer(P).getBytes());var ce=oe.getMac();G=E.create(E.Class.UNIVERSAL,E.Type.SEQUENCE,!0,[E.create(E.Class.UNIVERSAL,E.Type.SEQUENCE,!0,[E.create(E.Class.UNIVERSAL,E.Type.SEQUENCE,!0,[E.create(E.Class.UNIVERSAL,E.Type.OID,!1,E.oidToDer(Y.oids.sha1).getBytes()),E.create(E.Class.UNIVERSAL,E.Type.NULL,!1,"")]),E.create(E.Class.UNIVERSAL,E.Type.OCTETSTRING,!1,ce.getBytes())]),E.create(E.Class.UNIVERSAL,E.Type.OCTETSTRING,!1,j.getBytes()),E.create(E.Class.UNIVERSAL,E.Type.INTEGER,!1,E.integerToDer(ie).getBytes())])}return E.create(E.Class.UNIVERSAL,E.Type.SEQUENCE,!0,[E.create(E.Class.UNIVERSAL,E.Type.INTEGER,!1,E.integerToDer(3).getBytes()),E.create(E.Class.UNIVERSAL,E.Type.SEQUENCE,!0,[E.create(E.Class.UNIVERSAL,E.Type.OID,!1,E.oidToDer(Y.oids.data).getBytes()),E.create(E.Class.CONTEXT_SPECIFIC,0,!0,[E.create(E.Class.UNIVERSAL,E.Type.OCTETSTRING,!1,E.toDer(P).getBytes())])]),G])};jr.generateKey=pe.pbe.generatePkcs12Key});var oi=H((Og,Oo)=>{"use strict";var Yt=W();mt();Qt();ei();ur();Ba();ii();ka();Qr();re();Oa();var si=Yt.asn1,Nr=Oo.exports=Yt.pki=Yt.pki||{};Nr.pemToDer=function(e){var t=Yt.pem.decode(e)[0];if(t.procType&&t.procType.type==="ENCRYPTED")throw new Error("Could not convert PEM to DER; PEM is encrypted.");return Yt.util.createBuffer(t.body)};Nr.privateKeyFromPem=function(e){var t=Yt.pem.decode(e)[0];if(t.type!=="PRIVATE KEY"&&t.type!=="RSA PRIVATE KEY"){var a=new Error('Could not convert private key from PEM; PEM header type is not "PRIVATE KEY" or "RSA PRIVATE KEY".');throw a.headerType=t.type,a}if(t.procType&&t.procType.type==="ENCRYPTED")throw new Error("Could not convert private key from PEM; PEM is encrypted.");var r=si.fromDer(t.body);return Nr.privateKeyFromAsn1(r)};Nr.privateKeyToPem=function(e,t){var a={type:"RSA PRIVATE KEY",body:si.toDer(Nr.privateKeyToAsn1(e)).getBytes()};return Yt.pem.encode(a,{maxline:t})};Nr.privateKeyInfoToPem=function(e,t){var a={type:"PRIVATE KEY",body:si.toDer(e).getBytes()};return Yt.pem.encode(a,{maxline:t})}});var pi=H((Vg,Qo)=>{"use strict";var R=W();mt();Tr();ba();ur();oi();lt();Ar();re();var qa=function(e,t,a,r){var n=R.util.createBuffer(),i=e.length>>1,s=i+(e.length&1),o=e.substr(0,s),u=e.substr(i,s),l=R.util.createBuffer(),f=R.hmac.create();a=t+a;var c=Math.ceil(r/16),y=Math.ceil(r/20);f.start("MD5",o);var m=R.util.createBuffer();l.putBytes(a);for(var h=0;h<c;++h)f.start(null,null),f.update(l.getBytes()),l.putBuffer(f.digest()),f.start(null,null),f.update(l.bytes()+a),m.putBuffer(f.digest());f.start("SHA1",u);var v=R.util.createBuffer();l.clear(),l.putBytes(a);for(var h=0;h<y;++h)f.start(null,null),f.update(l.getBytes()),l.putBuffer(f.digest()),f.start(null,null),f.update(l.bytes()+a),v.putBuffer(f.digest());return n.putBytes(R.util.xorBytes(m.getBytes(),v.getBytes(),r)),n},nd=function(e,t,a){var r=R.hmac.create();r.start("SHA1",e);var n=R.util.createBuffer();return n.putInt32(t[0]),n.putInt32(t[1]),n.putByte(a.type),n.putByte(a.version.major),n.putByte(a.version.minor),n.putInt16(a.length),n.putBytes(a.fragment.bytes()),r.update(n.getBytes()),r.digest().getBytes()},id=function(e,t,a){var r=!1;try{var n=e.deflate(t.fragment.getBytes());t.fragment=R.util.createBuffer(n),t.length=n.length,r=!0}catch{}return r},sd=function(e,t,a){var r=!1;try{var n=e.inflate(t.fragment.getBytes());t.fragment=R.util.createBuffer(n),t.length=n.length,r=!0}catch{}return r},at=function(e,t){var a=0;switch(t){case 1:a=e.getByte();break;case 2:a=e.getInt16();break;case 3:a=e.getInt24();break;case 4:a=e.getInt32();break}return R.util.createBuffer(e.getBytes(a))},pt=function(e,t,a){e.putInt(a.length(),t<<3),e.putBuffer(a)},g={};g.Versions={TLS_1_0:{major:3,minor:1},TLS_1_1:{major:3,minor:2},TLS_1_2:{major:3,minor:3}};g.SupportedVersions=[g.Versions.TLS_1_1,g.Versions.TLS_1_0];g.Version=g.SupportedVersions[0];g.MaxFragment=15360;g.ConnectionEnd={server:0,client:1};g.PRFAlgorithm={tls_prf_sha256:0};g.BulkCipherAlgorithm={none:null,rc4:0,des3:1,aes:2};g.CipherType={stream:0,block:1,aead:2};g.MACAlgorithm={none:null,hmac_md5:0,hmac_sha1:1,hmac_sha256:2,hmac_sha384:3,hmac_sha512:4};g.CompressionMethod={none:0,deflate:1};g.ContentType={change_cipher_spec:20,alert:21,handshake:22,application_data:23,heartbeat:24};g.HandshakeType={hello_request:0,client_hello:1,server_hello:2,certificate:11,server_key_exchange:12,certificate_request:13,server_hello_done:14,certificate_verify:15,client_key_exchange:16,finished:20};g.Alert={};g.Alert.Level={warning:1,fatal:2};g.Alert.Description={close_notify:0,unexpected_message:10,bad_record_mac:20,decryption_failed:21,record_overflow:22,decompression_failure:30,handshake_failure:40,bad_certificate:42,unsupported_certificate:43,certificate_revoked:44,certificate_expired:45,certificate_unknown:46,illegal_parameter:47,unknown_ca:48,access_denied:49,decode_error:50,decrypt_error:51,export_restriction:60,protocol_version:70,insufficient_security:71,internal_error:80,user_canceled:90,no_renegotiation:100};g.HeartbeatMessageType={heartbeat_request:1,heartbeat_response:2};g.CipherSuites={};g.getCipherSuite=function(e){var t=null;for(var a in g.CipherSuites){var r=g.CipherSuites[a];if(r.id[0]===e.charCodeAt(0)&&r.id[1]===e.charCodeAt(1)){t=r;break}}return t};g.handleUnexpected=function(e,t){var a=!e.open&&e.entity===g.ConnectionEnd.client;a||e.error(e,{message:"Unexpected message. Received TLS record out of order.",send:!0,alert:{level:g.Alert.Level.fatal,description:g.Alert.Description.unexpected_message}})};g.handleHelloRequest=function(e,t,a){!e.handshaking&&e.handshakes>0&&(g.queue(e,g.createAlert(e,{level:g.Alert.Level.warning,description:g.Alert.Description.no_renegotiation})),g.flush(e)),e.process()};g.parseHelloMessage=function(e,t,a){var r=null,n=e.entity===g.ConnectionEnd.client;if(a<38)e.error(e,{message:n?"Invalid ServerHello message. Message too short.":"Invalid ClientHello message. Message too short.",send:!0,alert:{level:g.Alert.Level.fatal,description:g.Alert.Description.illegal_parameter}});else{var i=t.fragment,s=i.length();if(r={version:{major:i.getByte(),minor:i.getByte()},random:R.util.createBuffer(i.getBytes(32)),session_id:at(i,1),extensions:[]},n?(r.cipher_suite=i.getBytes(2),r.compression_method=i.getByte()):(r.cipher_suites=at(i,2),r.compression_methods=at(i,1)),s=a-(s-i.length()),s>0){for(var o=at(i,2);o.length()>0;)r.extensions.push({type:[o.getByte(),o.getByte()],data:at(o,2)});if(!n)for(var u=0;u<r.extensions.length;++u){var l=r.extensions[u];if(l.type[0]===0&&l.type[1]===0)for(var f=at(l.data,2);f.length()>0;){var c=f.getByte();if(c!==0)break;e.session.extensions.server_name.serverNameList.push(at(f,2).getBytes())}}}if(e.session.version&&(r.version.major!==e.session.version.major||r.version.minor!==e.session.version.minor))return e.error(e,{message:"TLS version change is disallowed during renegotiation.",send:!0,alert:{level:g.Alert.Level.fatal,description:g.Alert.Description.protocol_version}});if(n)e.session.cipherSuite=g.getCipherSuite(r.cipher_suite);else for(var y=R.util.createBuffer(r.cipher_suites.bytes());y.length()>0&&(e.session.cipherSuite=g.getCipherSuite(y.getBytes(2)),e.session.cipherSuite===null););if(e.session.cipherSuite===null)return e.error(e,{message:"No cipher suites in common.",send:!0,alert:{level:g.Alert.Level.fatal,description:g.Alert.Description.handshake_failure},cipherSuite:R.util.bytesToHex(r.cipher_suite)});n?e.session.compressionMethod=r.compression_method:e.session.compressionMethod=g.CompressionMethod.none}return r};g.createSecurityParameters=function(e,t){var a=e.entity===g.ConnectionEnd.client,r=t.random.bytes(),n=a?e.session.sp.client_random:r,i=a?r:g.createRandom().getBytes();e.session.sp={entity:e.entity,prf_algorithm:g.PRFAlgorithm.tls_prf_sha256,bulk_cipher_algorithm:null,cipher_type:null,enc_key_length:null,block_length:null,fixed_iv_length:null,record_iv_length:null,mac_algorithm:null,mac_length:null,mac_key_length:null,compression_algorithm:e.session.compressionMethod,pre_master_secret:null,master_secret:null,client_random:n,server_random:i}};g.handleServerHello=function(e,t,a){var r=g.parseHelloMessage(e,t,a);if(!e.fail){if(r.version.minor<=e.version.minor)e.version.minor=r.version.minor;else return e.error(e,{message:"Incompatible TLS version.",send:!0,alert:{level:g.Alert.Level.fatal,description:g.Alert.Description.protocol_version}});e.session.version=e.version;var n=r.session_id.bytes();n.length>0&&n===e.session.id?(e.expect=Ko,e.session.resuming=!0,e.session.sp.server_random=r.random.bytes()):(e.expect=ud,e.session.resuming=!1,g.createSecurityParameters(e,r)),e.session.id=n,e.process()}};g.handleClientHello=function(e,t,a){var r=g.parseHelloMessage(e,t,a);if(!e.fail){var n=r.session_id.bytes(),i=null;if(e.sessionCache&&(i=e.sessionCache.getSession(n),i===null?n="":(i.version.major!==r.version.major||i.version.minor>r.version.minor)&&(i=null,n="")),n.length===0&&(n=R.random.getBytes(32)),e.session.id=n,e.session.clientHelloVersion=r.version,e.session.sp={},i)e.version=e.session.version=i.version,e.session.sp=i.sp;else{for(var s,o=1;o<g.SupportedVersions.length&&(s=g.SupportedVersions[o],!(s.minor<=r.version.minor));++o);e.version={major:s.major,minor:s.minor},e.session.version=e.version}i!==null?(e.expect=ci,e.session.resuming=!0,e.session.sp.client_random=r.random.bytes()):(e.expect=e.verifyClient!==!1?gd:fi,e.session.resuming=!1,g.createSecurityParameters(e,r)),e.open=!0,g.queue(e,g.createRecord(e,{type:g.ContentType.handshake,data:g.createServerHello(e)})),e.session.resuming?(g.queue(e,g.createRecord(e,{type:g.ContentType.change_cipher_spec,data:g.createChangeCipherSpec()})),e.state.pending=g.createConnectionState(e),e.state.current.write=e.state.pending.write,g.queue(e,g.createRecord(e,{type:g.ContentType.handshake,data:g.createFinished(e)}))):(g.queue(e,g.createRecord(e,{type:g.ContentType.handshake,data:g.createCertificate(e)})),e.fail||(g.queue(e,g.createRecord(e,{type:g.ContentType.handshake,data:g.createServerKeyExchange(e)})),e.verifyClient!==!1&&g.queue(e,g.createRecord(e,{type:g.ContentType.handshake,data:g.createCertificateRequest(e)})),g.queue(e,g.createRecord(e,{type:g.ContentType.handshake,data:g.createServerHelloDone(e)})))),g.flush(e),e.process()}};g.handleCertificate=function(e,t,a){if(a<3)return e.error(e,{message:"Invalid Certificate message. Message too short.",send:!0,alert:{level:g.Alert.Level.fatal,description:g.Alert.Description.illegal_parameter}});var r=t.fragment,n={certificate_list:at(r,3)},i,s,o=[];try{for(;n.certificate_list.length()>0;)i=at(n.certificate_list,3),s=R.asn1.fromDer(i),i=R.pki.certificateFromAsn1(s,!0),o.push(i)}catch(l){return e.error(e,{message:"Could not parse certificate list.",cause:l,send:!0,alert:{level:g.Alert.Level.fatal,description:g.Alert.Description.bad_certificate}})}var u=e.entity===g.ConnectionEnd.client;(u||e.verifyClient===!0)&&o.length===0?e.error(e,{message:u?"No server certificate provided.":"No client certificate provided.",send:!0,alert:{level:g.Alert.Level.fatal,description:g.Alert.Description.illegal_parameter}}):o.length===0?e.expect=u?Vo:fi:(u?e.session.serverCertificate=o[0]:e.session.clientCertificate=o[0],g.verifyCertificateChain(e,o)&&(e.expect=u?Vo:fi)),e.process()};g.handleServerKeyExchange=function(e,t,a){if(a>0)return e.error(e,{message:"Invalid key parameters. Only RSA is supported.",send:!0,alert:{level:g.Alert.Level.fatal,description:g.Alert.Description.unsupported_certificate}});e.expect=ld,e.process()};g.handleClientKeyExchange=function(e,t,a){if(a<48)return e.error(e,{message:"Invalid key parameters. Only RSA is supported.",send:!0,alert:{level:g.Alert.Level.fatal,description:g.Alert.Description.unsupported_certificate}});var r=t.fragment,n={enc_pre_master_secret:at(r,2).getBytes()},i=null;if(e.getPrivateKey)try{i=e.getPrivateKey(e,e.session.serverCertificate),i=R.pki.privateKeyFromPem(i)}catch(u){e.error(e,{message:"Could not get private key.",cause:u,send:!0,alert:{level:g.Alert.Level.fatal,description:g.Alert.Description.internal_error}})}if(i===null)return e.error(e,{message:"No private key set.",send:!0,alert:{level:g.Alert.Level.fatal,description:g.Alert.Description.internal_error}});try{var s=e.session.sp;s.pre_master_secret=i.decrypt(n.enc_pre_master_secret);var o=e.session.clientHelloVersion;if(o.major!==s.pre_master_secret.charCodeAt(0)||o.minor!==s.pre_master_secret.charCodeAt(1))throw new Error("TLS version rollback attack detected.")}catch{s.pre_master_secret=R.random.getBytes(48)}e.expect=ci,e.session.clientCertificate!==null&&(e.expect=yd),e.process()};g.handleCertificateRequest=function(e,t,a){if(a<3)return e.error(e,{message:"Invalid CertificateRequest. Message too short.",send:!0,alert:{level:g.Alert.Level.fatal,description:g.Alert.Description.illegal_parameter}});var r=t.fragment,n={certificate_types:at(r,1),certificate_authorities:at(r,2)};e.session.certificateRequest=n,e.expect=fd,e.process()};g.handleCertificateVerify=function(e,t,a){if(a<2)return e.error(e,{message:"Invalid CertificateVerify. Message too short.",send:!0,alert:{level:g.Alert.Level.fatal,description:g.Alert.Description.illegal_parameter}});var r=t.fragment;r.read-=4;var n=r.bytes();r.read+=4;var i={signature:at(r,2).getBytes()},s=R.util.createBuffer();s.putBuffer(e.session.md5.digest()),s.putBuffer(e.session.sha1.digest()),s=s.getBytes();try{var o=e.session.clientCertificate;if(!o.publicKey.verify(s,i.signature,"NONE"))throw new Error("CertificateVerify signature does not match.");e.session.md5.update(n),e.session.sha1.update(n)}catch{return e.error(e,{message:"Bad signature in CertificateVerify.",send:!0,alert:{level:g.Alert.Level.fatal,description:g.Alert.Description.handshake_failure}})}e.expect=ci,e.process()};g.handleServerHelloDone=function(e,t,a){if(a>0)return e.error(e,{message:"Invalid ServerHelloDone message. Invalid length.",send:!0,alert:{level:g.Alert.Level.fatal,description:g.Alert.Description.record_overflow}});if(e.serverCertificate===null){var r={message:"No server certificate provided. Not enough security.",send:!0,alert:{level:g.Alert.Level.fatal,description:g.Alert.Description.insufficient_security}},n=0,i=e.verify(e,r.alert.description,n,[]);if(i!==!0)return(i||i===0)&&(typeof i=="object"&&!R.util.isArray(i)?(i.message&&(r.message=i.message),i.alert&&(r.alert.description=i.alert)):typeof i=="number"&&(r.alert.description=i)),e.error(e,r)}e.session.certificateRequest!==null&&(t=g.createRecord(e,{type:g.ContentType.handshake,data:g.createCertificate(e)}),g.queue(e,t)),t=g.createRecord(e,{type:g.ContentType.handshake,data:g.createClientKeyExchange(e)}),g.queue(e,t),e.expect=pd;var s=function(o,u){o.session.certificateRequest!==null&&o.session.clientCertificate!==null&&g.queue(o,g.createRecord(o,{type:g.ContentType.handshake,data:g.createCertificateVerify(o,u)})),g.queue(o,g.createRecord(o,{type:g.ContentType.change_cipher_spec,data:g.createChangeCipherSpec()})),o.state.pending=g.createConnectionState(o),o.state.current.write=o.state.pending.write,g.queue(o,g.createRecord(o,{type:g.ContentType.handshake,data:g.createFinished(o)})),o.expect=Ko,g.flush(o),o.process()};if(e.session.certificateRequest===null||e.session.clientCertificate===null)return s(e,null);g.getClientSignature(e,s)};g.handleChangeCipherSpec=function(e,t){if(t.fragment.getByte()!==1)return e.error(e,{message:"Invalid ChangeCipherSpec message received.",send:!0,alert:{level:g.Alert.Level.fatal,description:g.Alert.Description.illegal_parameter}});var a=e.entity===g.ConnectionEnd.client;(e.session.resuming&&a||!e.session.resuming&&!a)&&(e.state.pending=g.createConnectionState(e)),e.state.current.read=e.state.pending.read,(!e.session.resuming&&a||e.session.resuming&&!a)&&(e.state.pending=null),e.expect=a?cd:md,e.process()};g.handleFinished=function(e,t,a){var r=t.fragment;r.read-=4;var n=r.bytes();r.read+=4;var i=t.fragment.getBytes();r=R.util.createBuffer(),r.putBuffer(e.session.md5.digest()),r.putBuffer(e.session.sha1.digest());var s=e.entity===g.ConnectionEnd.client,o=s?"server finished":"client finished",u=e.session.sp,l=12,f=qa;if(r=f(u.master_secret,o,r.getBytes(),l),r.getBytes()!==i)return e.error(e,{message:"Invalid verify_data in Finished message.",send:!0,alert:{level:g.Alert.Level.fatal,description:g.Alert.Description.decrypt_error}});e.session.md5.update(n),e.session.sha1.update(n),(e.session.resuming&&s||!e.session.resuming&&!s)&&(g.queue(e,g.createRecord(e,{type:g.ContentType.change_cipher_spec,data:g.createChangeCipherSpec()})),e.state.current.write=e.state.pending.write,e.state.pending=null,g.queue(e,g.createRecord(e,{type:g.ContentType.handshake,data:g.createFinished(e)}))),e.expect=s?dd:vd,e.handshaking=!1,++e.handshakes,e.peerCertificate=s?e.session.serverCertificate:e.session.clientCertificate,g.flush(e),e.isConnected=!0,e.connected(e),e.process()};g.handleAlert=function(e,t){var a=t.fragment,r={level:a.getByte(),description:a.getByte()},n;switch(r.description){case g.Alert.Description.close_notify:n="Connection closed.";break;case g.Alert.Description.unexpected_message:n="Unexpected message.";break;case g.Alert.Description.bad_record_mac:n="Bad record MAC.";break;case g.Alert.Description.decryption_failed:n="Decryption failed.";break;case g.Alert.Description.record_overflow:n="Record overflow.";break;case g.Alert.Description.decompression_failure:n="Decompression failed.";break;case g.Alert.Description.handshake_failure:n="Handshake failure.";break;case g.Alert.Description.bad_certificate:n="Bad certificate.";break;case g.Alert.Description.unsupported_certificate:n="Unsupported certificate.";break;case g.Alert.Description.certificate_revoked:n="Certificate revoked.";break;case g.Alert.Description.certificate_expired:n="Certificate expired.";break;case g.Alert.Description.certificate_unknown:n="Certificate unknown.";break;case g.Alert.Description.illegal_parameter:n="Illegal parameter.";break;case g.Alert.Description.unknown_ca:n="Unknown certificate authority.";break;case g.Alert.Description.access_denied:n="Access denied.";break;case g.Alert.Description.decode_error:n="Decode error.";break;case g.Alert.Description.decrypt_error:n="Decrypt error.";break;case g.Alert.Description.export_restriction:n="Export restriction.";break;case g.Alert.Description.protocol_version:n="Unsupported protocol version.";break;case g.Alert.Description.insufficient_security:n="Insufficient security.";break;case g.Alert.Description.internal_error:n="Internal error.";break;case g.Alert.Description.user_canceled:n="User canceled.";break;case g.Alert.Description.no_renegotiation:n="Renegotiation not supported.";break;default:n="Unknown error.";break}if(r.description===g.Alert.Description.close_notify)return e.close();e.error(e,{message:n,send:!1,origin:e.entity===g.ConnectionEnd.client?"server":"client",alert:r}),e.process()};g.handleHandshake=function(e,t){var a=t.fragment,r=a.getByte(),n=a.getInt24();if(n>a.length())return e.fragmented=t,t.fragment=R.util.createBuffer(),a.read-=4,e.process();e.fragmented=null,a.read-=4;var i=a.bytes(n+4);a.read+=4,r in Ka[e.entity][e.expect]?(e.entity===g.ConnectionEnd.server&&!e.open&&!e.fail&&(e.handshaking=!0,e.session={version:null,extensions:{server_name:{serverNameList:[]}},cipherSuite:null,compressionMethod:null,serverCertificate:null,clientCertificate:null,md5:R.md.md5.create(),sha1:R.md.sha1.create()}),r!==g.HandshakeType.hello_request&&r!==g.HandshakeType.certificate_verify&&r!==g.HandshakeType.finished&&(e.session.md5.update(i),e.session.sha1.update(i)),Ka[e.entity][e.expect][r](e,t,n)):g.handleUnexpected(e,t)};g.handleApplicationData=function(e,t){e.data.putBuffer(t.fragment),e.dataReady(e),e.process()};g.handleHeartbeat=function(e,t){var a=t.fragment,r=a.getByte(),n=a.getInt16(),i=a.getBytes(n);if(r===g.HeartbeatMessageType.heartbeat_request){if(e.handshaking||n>i.length)return e.process();g.queue(e,g.createRecord(e,{type:g.ContentType.heartbeat,data:g.createHeartbeat(g.HeartbeatMessageType.heartbeat_response,i)})),g.flush(e)}else if(r===g.HeartbeatMessageType.heartbeat_response){if(i!==e.expectedHeartbeatPayload)return e.process();e.heartbeatReceived&&e.heartbeatReceived(e,R.util.createBuffer(i))}e.process()};var od=0,ud=1,Vo=2,ld=3,fd=4,Ko=5,cd=6,dd=7,pd=8,hd=0,gd=1,fi=2,yd=3,ci=4,md=5,vd=6,p=g.handleUnexpected,qo=g.handleChangeCipherSpec,Pe=g.handleAlert,Xe=g.handleHandshake,Ho=g.handleApplicationData,De=g.handleHeartbeat,di=[];di[g.ConnectionEnd.client]=[[p,Pe,Xe,p,De],[p,Pe,Xe,p,De],[p,Pe,Xe,p,De],[p,Pe,Xe,p,De],[p,Pe,Xe,p,De],[qo,Pe,p,p,De],[p,Pe,Xe,p,De],[p,Pe,Xe,Ho,De],[p,Pe,Xe,p,De]];di[g.ConnectionEnd.server]=[[p,Pe,Xe,p,De],[p,Pe,Xe,p,De],[p,Pe,Xe,p,De],[p,Pe,Xe,p,De],[qo,Pe,p,p,De],[p,Pe,Xe,p,De],[p,Pe,Xe,Ho,De],[p,Pe,Xe,p,De]];var Xt=g.handleHelloRequest,Ed=g.handleServerHello,zo=g.handleCertificate,Mo=g.handleServerKeyExchange,ui=g.handleCertificateRequest,Va=g.handleServerHelloDone,Go=g.handleFinished,Ka=[];Ka[g.ConnectionEnd.client]=[[p,p,Ed,p,p,p,p,p,p,p,p,p,p,p,p,p,p,p,p,p,p],[Xt,p,p,p,p,p,p,p,p,p,p,zo,Mo,ui,Va,p,p,p,p,p,p],[Xt,p,p,p,p,p,p,p,p,p,p,p,Mo,ui,Va,p,p,p,p,p,p],[Xt,p,p,p,p,p,p,p,p,p,p,p,p,ui,Va,p,p,p,p,p,p],[Xt,p,p,p,p,p,p,p,p,p,p,p,p,p,Va,p,p,p,p,p,p],[Xt,p,p,p,p,p,p,p,p,p,p,p,p,p,p,p,p,p,p,p,p],[Xt,p,p,p,p,p,p,p,p,p,p,p,p,p,p,p,p,p,p,p,Go],[Xt,p,p,p,p,p,p,p,p,p,p,p,p,p,p,p,p,p,p,p,p],[Xt,p,p,p,p,p,p,p,p,p,p,p,p,p,p,p,p,p,p,p,p]];var Cd=g.handleClientHello,xd=g.handleClientKeyExchange,Sd=g.handleCertificateVerify;Ka[g.ConnectionEnd.server]=[[p,Cd,p,p,p,p,p,p,p,p,p,p,p,p,p,p,p,p,p,p,p],[p,p,p,p,p,p,p,p,p,p,p,zo,p,p,p,p,p,p,p,p,p],[p,p,p,p,p,p,p,p,p,p,p,p,p,p,p,p,xd,p,p,p,p],[p,p,p,p,p,p,p,p,p,p,p,p,p,p,p,Sd,p,p,p,p,p],[p,p,p,p,p,p,p,p,p,p,p,p,p,p,p,p,p,p,p,p,p],[p,p,p,p,p,p,p,p,p,p,p,p,p,p,p,p,p,p,p,p,Go],[p,p,p,p,p,p,p,p,p,p,p,p,p,p,p,p,p,p,p,p,p],[p,p,p,p,p,p,p,p,p,p,p,p,p,p,p,p,p,p,p,p,p]];g.generateKeys=function(e,t){var a=qa,r=t.client_random+t.server_random;e.session.resuming||(t.master_secret=a(t.pre_master_secret,"master secret",r,48).bytes(),t.pre_master_secret=null),r=t.server_random+t.client_random;var n=2*t.mac_key_length+2*t.enc_key_length,i=e.version.major===g.Versions.TLS_1_0.major&&e.version.minor===g.Versions.TLS_1_0.minor;i&&(n+=2*t.fixed_iv_length);var s=a(t.master_secret,"key expansion",r,n),o={client_write_MAC_key:s.getBytes(t.mac_key_length),server_write_MAC_key:s.getBytes(t.mac_key_length),client_write_key:s.getBytes(t.enc_key_length),server_write_key:s.getBytes(t.enc_key_length)};return i&&(o.client_write_IV=s.getBytes(t.fixed_iv_length),o.server_write_IV=s.getBytes(t.fixed_iv_length)),o};g.createConnectionState=function(e){var t=e.entity===g.ConnectionEnd.client,a=function(){var i={sequenceNumber:[0,0],macKey:null,macLength:0,macFunction:null,cipherState:null,cipherFunction:function(s){return!0},compressionState:null,compressFunction:function(s){return!0},updateSequenceNumber:function(){i.sequenceNumber[1]===4294967295?(i.sequenceNumber[1]=0,++i.sequenceNumber[0]):++i.sequenceNumber[1]}};return i},r={read:a(),write:a()};if(r.read.update=function(i,s){return r.read.cipherFunction(s,r.read)?r.read.compressFunction(i,s,r.read)||i.error(i,{message:"Could not decompress record.",send:!0,alert:{level:g.Alert.Level.fatal,description:g.Alert.Description.decompression_failure}}):i.error(i,{message:"Could not decrypt record or bad MAC.",send:!0,alert:{level:g.Alert.Level.fatal,description:g.Alert.Description.bad_record_mac}}),!i.fail},r.write.update=function(i,s){return r.write.compressFunction(i,s,r.write)?r.write.cipherFunction(s,r.write)||i.error(i,{message:"Could not encrypt record.",send:!1,alert:{level:g.Alert.Level.fatal,description:g.Alert.Description.internal_error}}):i.error(i,{message:"Could not compress record.",send:!1,alert:{level:g.Alert.Level.fatal,description:g.Alert.Description.internal_error}}),!i.fail},e.session){var n=e.session.sp;switch(e.session.cipherSuite.initSecurityParameters(n),n.keys=g.generateKeys(e,n),r.read.macKey=t?n.keys.server_write_MAC_key:n.keys.client_write_MAC_key,r.write.macKey=t?n.keys.client_write_MAC_key:n.keys.server_write_MAC_key,e.session.cipherSuite.initConnectionState(r,e,n),n.compression_algorithm){case g.CompressionMethod.none:break;case g.CompressionMethod.deflate:r.read.compressFunction=sd,r.write.compressFunction=id;break;default:throw new Error("Unsupported compression algorithm.")}}return r};g.createRandom=function(){var e=new Date,t=+e+e.getTimezoneOffset()*6e4,a=R.util.createBuffer();return a.putInt32(t),a.putBytes(R.random.getBytes(28)),a};g.createRecord=function(e,t){if(!t.data)return null;var a={type:t.type,version:{major:e.version.major,minor:e.version.minor},length:t.data.length(),fragment:t.data};return a};g.createAlert=function(e,t){var a=R.util.createBuffer();return a.putByte(t.level),a.putByte(t.description),g.createRecord(e,{type:g.ContentType.alert,data:a})};g.createClientHello=function(e){e.session.clientHelloVersion={major:e.version.major,minor:e.version.minor};for(var t=R.util.createBuffer(),a=0;a<e.cipherSuites.length;++a){var r=e.cipherSuites[a];t.putByte(r.id[0]),t.putByte(r.id[1])}var n=t.length(),i=R.util.createBuffer();i.putByte(g.CompressionMethod.none);var s=i.length(),o=R.util.createBuffer();if(e.virtualHost){var u=R.util.createBuffer();u.putByte(0),u.putByte(0);var l=R.util.createBuffer();l.putByte(0),pt(l,2,R.util.createBuffer(e.virtualHost));var f=R.util.createBuffer();pt(f,2,l),pt(u,2,f),o.putBuffer(u)}var c=o.length();c>0&&(c+=2);var y=e.session.id,m=y.length+1+2+4+28+2+n+1+s+c,h=R.util.createBuffer();return h.putByte(g.HandshakeType.client_hello),h.putInt24(m),h.putByte(e.version.major),h.putByte(e.version.minor),h.putBytes(e.session.sp.client_random),pt(h,1,R.util.createBuffer(y)),pt(h,2,t),pt(h,1,i),c>0&&pt(h,2,o),h};g.createServerHello=function(e){var t=e.session.id,a=t.length+1+2+4+28+2+1,r=R.util.createBuffer();return r.putByte(g.HandshakeType.server_hello),r.putInt24(a),r.putByte(e.version.major),r.putByte(e.version.minor),r.putBytes(e.session.sp.server_random),pt(r,1,R.util.createBuffer(t)),r.putByte(e.session.cipherSuite.id[0]),r.putByte(e.session.cipherSuite.id[1]),r.putByte(e.session.compressionMethod),r};g.createCertificate=function(e){var t=e.entity===g.ConnectionEnd.client,a=null;if(e.getCertificate){var r;t?r=e.session.certificateRequest:r=e.session.extensions.server_name.serverNameList,a=e.getCertificate(e,r)}var n=R.util.createBuffer();if(a!==null)try{R.util.isArray(a)||(a=[a]);for(var i=null,s=0;s<a.length;++s){var o=R.pem.decode(a[s])[0];if(o.type!=="CERTIFICATE"&&o.type!=="X509 CERTIFICATE"&&o.type!=="TRUSTED CERTIFICATE"){var u=new Error('Could not convert certificate from PEM; PEM header type is not "CERTIFICATE", "X509 CERTIFICATE", or "TRUSTED CERTIFICATE".');throw u.headerType=o.type,u}if(o.procType&&o.procType.type==="ENCRYPTED")throw new Error("Could not convert certificate from PEM; PEM is encrypted.");var l=R.util.createBuffer(o.body);i===null&&(i=R.asn1.fromDer(l.bytes(),!1));var f=R.util.createBuffer();pt(f,3,l),n.putBuffer(f)}a=R.pki.certificateFromAsn1(i),t?e.session.clientCertificate=a:e.session.serverCertificate=a}catch(m){return e.error(e,{message:"Could not send certificate list.",cause:m,send:!0,alert:{level:g.Alert.Level.fatal,description:g.Alert.Description.bad_certificate}})}var c=3+n.length(),y=R.util.createBuffer();return y.putByte(g.HandshakeType.certificate),y.putInt24(c),pt(y,3,n),y};g.createClientKeyExchange=function(e){var t=R.util.createBuffer();t.putByte(e.session.clientHelloVersion.major),t.putByte(e.session.clientHelloVersion.minor),t.putBytes(R.random.getBytes(46));var a=e.session.sp;a.pre_master_secret=t.getBytes();var r=e.session.serverCertificate.publicKey;t=r.encrypt(a.pre_master_secret);var n=t.length+2,i=R.util.createBuffer();return i.putByte(g.HandshakeType.client_key_exchange),i.putInt24(n),i.putInt16(t.length),i.putBytes(t),i};g.createServerKeyExchange=function(e){var t=0,a=R.util.createBuffer();return t>0&&(a.putByte(g.HandshakeType.server_key_exchange),a.putInt24(t)),a};g.getClientSignature=function(e,t){var a=R.util.createBuffer();a.putBuffer(e.session.md5.digest()),a.putBuffer(e.session.sha1.digest()),a=a.getBytes(),e.getSignature=e.getSignature||function(r,n,i){var s=null;if(r.getPrivateKey)try{s=r.getPrivateKey(r,r.session.clientCertificate),s=R.pki.privateKeyFromPem(s)}catch(o){r.error(r,{message:"Could not get private key.",cause:o,send:!0,alert:{level:g.Alert.Level.fatal,description:g.Alert.Description.internal_error}})}s===null?r.error(r,{message:"No private key set.",send:!0,alert:{level:g.Alert.Level.fatal,description:g.Alert.Description.internal_error}}):n=s.sign(n,null),i(r,n)},e.getSignature(e,a,t)};g.createCertificateVerify=function(e,t){var a=t.length+2,r=R.util.createBuffer();return r.putByte(g.HandshakeType.certificate_verify),r.putInt24(a),r.putInt16(t.length),r.putBytes(t),r};g.createCertificateRequest=function(e){var t=R.util.createBuffer();t.putByte(1);var a=R.util.createBuffer();for(var r in e.caStore.certs){var n=e.caStore.certs[r],i=R.pki.distinguishedNameToAsn1(n.subject),s=R.asn1.toDer(i);a.putInt16(s.length()),a.putBuffer(s)}var o=1+t.length()+2+a.length(),u=R.util.createBuffer();return u.putByte(g.HandshakeType.certificate_request),u.putInt24(o),pt(u,1,t),pt(u,2,a),u};g.createServerHelloDone=function(e){var t=R.util.createBuffer();return t.putByte(g.HandshakeType.server_hello_done),t.putInt24(0),t};g.createChangeCipherSpec=function(){var e=R.util.createBuffer();return e.putByte(1),e};g.createFinished=function(e){var t=R.util.createBuffer();t.putBuffer(e.session.md5.digest()),t.putBuffer(e.session.sha1.digest());var a=e.entity===g.ConnectionEnd.client,r=e.session.sp,n=12,i=qa,s=a?"client finished":"server finished";t=i(r.master_secret,s,t.getBytes(),n);var o=R.util.createBuffer();return o.putByte(g.HandshakeType.finished),o.putInt24(t.length()),o.putBuffer(t),o};g.createHeartbeat=function(e,t,a){typeof a>"u"&&(a=t.length);var r=R.util.createBuffer();r.putByte(e),r.putInt16(a),r.putBytes(t);var n=r.length(),i=Math.max(16,n-a-3);return r.putBytes(R.random.getBytes(i)),r};g.queue=function(e,t){if(t&&!(t.fragment.length()===0&&(t.type===g.ContentType.handshake||t.type===g.ContentType.alert||t.type===g.ContentType.change_cipher_spec))){if(t.type===g.ContentType.handshake){var a=t.fragment.bytes();e.session.md5.update(a),e.session.sha1.update(a),a=null}var r;if(t.fragment.length()<=g.MaxFragment)r=[t];else{r=[];for(var n=t.fragment.bytes();n.length>g.MaxFragment;)r.push(g.createRecord(e,{type:t.type,data:R.util.createBuffer(n.slice(0,g.MaxFragment))})),n=n.slice(g.MaxFragment);n.length>0&&r.push(g.createRecord(e,{type:t.type,data:R.util.createBuffer(n)}))}for(var i=0;i<r.length&&!e.fail;++i){var s=r[i],o=e.state.current.write;o.update(e,s)&&e.records.push(s)}}};g.flush=function(e){for(var t=0;t<e.records.length;++t){var a=e.records[t];e.tlsData.putByte(a.type),e.tlsData.putByte(a.version.major),e.tlsData.putByte(a.version.minor),e.tlsData.putInt16(a.fragment.length()),e.tlsData.putBuffer(e.records[t].fragment)}return e.records=[],e.tlsDataReady(e)};var li=function(e){switch(e){case!0:return!0;case R.pki.certificateError.bad_certificate:return g.Alert.Description.bad_certificate;case R.pki.certificateError.unsupported_certificate:return g.Alert.Description.unsupported_certificate;case R.pki.certificateError.certificate_revoked:return g.Alert.Description.certificate_revoked;case R.pki.certificateError.certificate_expired:return g.Alert.Description.certificate_expired;case R.pki.certificateError.certificate_unknown:return g.Alert.Description.certificate_unknown;case R.pki.certificateError.unknown_ca:return g.Alert.Description.unknown_ca;default:return g.Alert.Description.bad_certificate}},Td=function(e){switch(e){case!0:return!0;case g.Alert.Description.bad_certificate:return R.pki.certificateError.bad_certificate;case g.Alert.Description.unsupported_certificate:return R.pki.certificateError.unsupported_certificate;case g.Alert.Description.certificate_revoked:return R.pki.certificateError.certificate_revoked;case g.Alert.Description.certificate_expired:return R.pki.certificateError.certificate_expired;case g.Alert.Description.certificate_unknown:return R.pki.certificateError.certificate_unknown;case g.Alert.Description.unknown_ca:return R.pki.certificateError.unknown_ca;default:return R.pki.certificateError.bad_certificate}};g.verifyCertificateChain=function(e,t){try{var a={};for(var r in e.verifyOptions)a[r]=e.verifyOptions[r];a.verify=function(i,s,o){var u=li(i),l=e.verify(e,i,s,o);if(l!==!0){if(typeof l=="object"&&!R.util.isArray(l)){var f=new Error("The application rejected the certificate.");throw f.send=!0,f.alert={level:g.Alert.Level.fatal,description:g.Alert.Description.bad_certificate},l.message&&(f.message=l.message),l.alert&&(f.alert.description=l.alert),f}l!==i&&(l=Td(l))}return l},R.pki.verifyCertificateChain(e.caStore,t,a)}catch(i){var n=i;(typeof n!="object"||R.util.isArray(n))&&(n={send:!0,alert:{level:g.Alert.Level.fatal,description:li(i)}}),"send"in n||(n.send=!0),"alert"in n||(n.alert={level:g.Alert.Level.fatal,description:li(n.error)}),e.error(e,n)}return!e.fail};g.createSessionCache=function(e,t){var a=null;if(e&&e.getSession&&e.setSession&&e.order)a=e;else{a={},a.cache=e||{},a.capacity=Math.max(t||100,1),a.order=[];for(var r in e)a.order.length<=t?a.order.push(r):delete e[r];a.getSession=function(n){var i=null,s=null;if(n?s=R.util.bytesToHex(n):a.order.length>0&&(s=a.order[0]),s!==null&&s in a.cache){i=a.cache[s],delete a.cache[s];for(var o in a.order)if(a.order[o]===s){a.order.splice(o,1);break}}return i},a.setSession=function(n,i){if(a.order.length===a.capacity){var s=a.order.shift();delete a.cache[s]}var s=R.util.bytesToHex(n);a.order.push(s),a.cache[s]=i}}return a};g.createConnection=function(e){var t=null;e.caStore?R.util.isArray(e.caStore)?t=R.pki.createCaStore(e.caStore):t=e.caStore:t=R.pki.createCaStore();var a=e.cipherSuites||null;if(a===null){a=[];for(var r in g.CipherSuites)a.push(g.CipherSuites[r])}var n=e.server?g.ConnectionEnd.server:g.ConnectionEnd.client,i=e.sessionCache?g.createSessionCache(e.sessionCache):null,s={version:{major:g.Version.major,minor:g.Version.minor},entity:n,sessionId:e.sessionId,caStore:t,sessionCache:i,cipherSuites:a,connected:e.connected,virtualHost:e.virtualHost||null,verifyClient:e.verifyClient||!1,verify:e.verify||function(f,c,y,m){return c},verifyOptions:e.verifyOptions||{},getCertificate:e.getCertificate||null,getPrivateKey:e.getPrivateKey||null,getSignature:e.getSignature||null,input:R.util.createBuffer(),tlsData:R.util.createBuffer(),data:R.util.createBuffer(),tlsDataReady:e.tlsDataReady,dataReady:e.dataReady,heartbeatReceived:e.heartbeatReceived,closed:e.closed,error:function(f,c){c.origin=c.origin||(f.entity===g.ConnectionEnd.client?"client":"server"),c.send&&(g.queue(f,g.createAlert(f,c.alert)),g.flush(f));var y=c.fatal!==!1;y&&(f.fail=!0),e.error(f,c),y&&f.close(!1)},deflate:e.deflate||null,inflate:e.inflate||null};s.reset=function(f){s.version={major:g.Version.major,minor:g.Version.minor},s.record=null,s.session=null,s.peerCertificate=null,s.state={pending:null,current:null},s.expect=s.entity===g.ConnectionEnd.client?od:hd,s.fragmented=null,s.records=[],s.open=!1,s.handshakes=0,s.handshaking=!1,s.isConnected=!1,s.fail=!(f||typeof f>"u"),s.input.clear(),s.tlsData.clear(),s.data.clear(),s.state.current=g.createConnectionState(s)},s.reset();var o=function(f,c){var y=c.type-g.ContentType.change_cipher_spec,m=di[f.entity][f.expect];y in m?m[y](f,c):g.handleUnexpected(f,c)},u=function(f){var c=0,y=f.input,m=y.length();if(m<5)c=5-m;else{f.record={type:y.getByte(),version:{major:y.getByte(),minor:y.getByte()},length:y.getInt16(),fragment:R.util.createBuffer(),ready:!1};var h=f.record.version.major===f.version.major;h&&f.session&&f.session.version&&(h=f.record.version.minor===f.version.minor),h||f.error(f,{message:"Incompatible TLS version.",send:!0,alert:{level:g.Alert.Level.fatal,description:g.Alert.Description.protocol_version}})}return c},l=function(f){var c=0,y=f.input,m=y.length();if(m<f.record.length)c=f.record.length-m;else{f.record.fragment.putBytes(y.getBytes(f.record.length)),y.compact();var h=f.state.current.read;h.update(f,f.record)&&(f.fragmented!==null&&(f.fragmented.type===f.record.type?(f.fragmented.fragment.putBuffer(f.record.fragment),f.record=f.fragmented):f.error(f,{message:"Invalid fragmented record.",send:!0,alert:{level:g.Alert.Level.fatal,description:g.Alert.Description.unexpected_message}})),f.record.ready=!0)}return c};return s.handshake=function(f){if(s.entity!==g.ConnectionEnd.client)s.error(s,{message:"Cannot initiate handshake as a server.",fatal:!1});else if(s.handshaking)s.error(s,{message:"Handshake already in progress.",fatal:!1});else{s.fail&&!s.open&&s.handshakes===0&&(s.fail=!1),s.handshaking=!0,f=f||"";var c=null;f.length>0&&(s.sessionCache&&(c=s.sessionCache.getSession(f)),c===null&&(f="")),f.length===0&&s.sessionCache&&(c=s.sessionCache.getSession(),c!==null&&(f=c.id)),s.session={id:f,version:null,cipherSuite:null,compressionMethod:null,serverCertificate:null,certificateRequest:null,clientCertificate:null,sp:{},md5:R.md.md5.create(),sha1:R.md.sha1.create()},c&&(s.version=c.version,s.session.sp=c.sp),s.session.sp.client_random=g.createRandom().getBytes(),s.open=!0,g.queue(s,g.createRecord(s,{type:g.ContentType.handshake,data:g.createClientHello(s)})),g.flush(s)}},s.process=function(f){var c=0;return f&&s.input.putBytes(f),s.fail||(s.record!==null&&s.record.ready&&s.record.fragment.isEmpty()&&(s.record=null),s.record===null&&(c=u(s)),!s.fail&&s.record!==null&&!s.record.ready&&(c=l(s)),!s.fail&&s.record!==null&&s.record.ready&&o(s,s.record)),c},s.prepare=function(f){return g.queue(s,g.createRecord(s,{type:g.ContentType.application_data,data:R.util.createBuffer(f)})),g.flush(s)},s.prepareHeartbeatRequest=function(f,c){return f instanceof R.util.ByteBuffer&&(f=f.bytes()),typeof c>"u"&&(c=f.length),s.expectedHeartbeatPayload=f,g.queue(s,g.createRecord(s,{type:g.ContentType.heartbeat,data:g.createHeartbeat(g.HeartbeatMessageType.heartbeat_request,f,c)})),g.flush(s)},s.close=function(f){if(!s.fail&&s.sessionCache&&s.session){var c={id:s.session.id,version:s.session.version,sp:s.session.sp};c.sp.keys=null,s.sessionCache.setSession(c.id,c)}s.open&&(s.open=!1,s.input.clear(),(s.isConnected||s.handshaking)&&(s.isConnected=s.handshaking=!1,g.queue(s,g.createAlert(s,{level:g.Alert.Level.warning,description:g.Alert.Description.close_notify})),g.flush(s)),s.closed(s)),s.reset(f)},s};Qo.exports=R.tls=R.tls||{};for(Ma in g)typeof g[Ma]!="function"&&(R.tls[Ma]=g[Ma]);var Ma;R.tls.prf_tls1=qa;R.tls.hmac_sha1=nd;R.tls.createSessionCache=g.createSessionCache;R.tls.createConnection=g.createConnection});var $o=H((Mg,jo)=>{"use strict";var Zt=W();Gt();pi();var ht=jo.exports=Zt.tls;ht.CipherSuites.TLS_RSA_WITH_AES_128_CBC_SHA={id:[0,47],name:"TLS_RSA_WITH_AES_128_CBC_SHA",initSecurityParameters:function(e){e.bulk_cipher_algorithm=ht.BulkCipherAlgorithm.aes,e.cipher_type=ht.CipherType.block,e.enc_key_length=16,e.block_length=16,e.fixed_iv_length=16,e.record_iv_length=16,e.mac_algorithm=ht.MACAlgorithm.hmac_sha1,e.mac_length=20,e.mac_key_length=20},initConnectionState:Wo};ht.CipherSuites.TLS_RSA_WITH_AES_256_CBC_SHA={id:[0,53],name:"TLS_RSA_WITH_AES_256_CBC_SHA",initSecurityParameters:function(e){e.bulk_cipher_algorithm=ht.BulkCipherAlgorithm.aes,e.cipher_type=ht.CipherType.block,e.enc_key_length=32,e.block_length=16,e.fixed_iv_length=16,e.record_iv_length=16,e.mac_algorithm=ht.MACAlgorithm.hmac_sha1,e.mac_length=20,e.mac_key_length=20},initConnectionState:Wo};function Wo(e,t,a){var r=t.entity===Zt.tls.ConnectionEnd.client;e.read.cipherState={init:!1,cipher:Zt.cipher.createDecipher("AES-CBC",r?a.keys.server_write_key:a.keys.client_write_key),iv:r?a.keys.server_write_IV:a.keys.client_write_IV},e.write.cipherState={init:!1,cipher:Zt.cipher.createCipher("AES-CBC",r?a.keys.client_write_key:a.keys.server_write_key),iv:r?a.keys.client_write_IV:a.keys.server_write_IV},e.read.cipherFunction=Ad,e.write.cipherFunction=bd,e.read.macLength=e.write.macLength=a.mac_length,e.read.macFunction=e.write.macFunction=ht.hmac_sha1}function bd(e,t){var a=!1,r=t.macFunction(t.macKey,t.sequenceNumber,e);e.fragment.putBytes(r),t.updateSequenceNumber();var n;e.version.minor===ht.Versions.TLS_1_0.minor?n=t.cipherState.init?null:t.cipherState.iv:n=Zt.random.getBytesSync(16),t.cipherState.init=!0;var i=t.cipherState.cipher;return i.start({iv:n}),e.version.minor>=ht.Versions.TLS_1_1.minor&&i.output.putBytes(n),i.update(e.fragment),i.finish(Id)&&(e.fragment=i.output,e.length=e.fragment.length(),a=!0),a}function Id(e,t,a){if(!a){var r=e-t.length()%e;t.fillWithByte(r-1,r)}return!0}function wd(e,t,a){var r=!0;if(a){for(var n=t.length(),i=t.last(),s=n-1-i;s<n-1;++s)r=r&&t.at(s)==i;r&&t.truncate(i+1)}return r}function Ad(e,t){var a=!1,r;e.version.minor===ht.Versions.TLS_1_0.minor?r=t.cipherState.init?null:t.cipherState.iv:r=e.fragment.getBytes(16),t.cipherState.init=!0;var n=t.cipherState.cipher;n.start({iv:r}),n.update(e.fragment),a=n.finish(wd);var i=t.macLength,s=Zt.random.getBytesSync(i),o=n.output.length();o>=i?(e.fragment=n.output.getBytes(o-i),s=n.output.getBytes(i)):e.fragment=n.output.getBytes(),e.fragment=Zt.util.createBuffer(e.fragment),e.length=e.fragment.length();var u=t.macFunction(t.macKey,t.sequenceNumber,e);return t.updateSequenceNumber(),a=Bd(t.macKey,s,u)&&a,a}function Bd(e,t,a){var r=Zt.hmac.create();return r.start("SHA1",e),r.update(t),t=r.digest().getBytes(),r.start(null,null),r.update(a),a=r.digest().getBytes(),t===a}});var yi=H((Kg,Jo)=>{"use strict";var ye=W();St();re();var $r=Jo.exports=ye.sha512=ye.sha512||{};ye.md.sha512=ye.md.algorithms.sha512=$r;var Xo=ye.sha384=ye.sha512.sha384=ye.sha512.sha384||{};Xo.create=function(){return $r.create("SHA-384")};ye.md.sha384=ye.md.algorithms.sha384=Xo;ye.sha512.sha256=ye.sha512.sha256||{create:function(){return $r.create("SHA-512/256")}};ye.md["sha512/256"]=ye.md.algorithms["sha512/256"]=ye.sha512.sha256;ye.sha512.sha224=ye.sha512.sha224||{create:function(){return $r.create("SHA-512/224")}};ye.md["sha512/224"]=ye.md.algorithms["sha512/224"]=ye.sha512.sha224;$r.create=function(e){if(Zo||Rd(),typeof e>"u"&&(e="SHA-512"),!(e in hr))throw new Error("Invalid SHA-512 algorithm: "+e);for(var t=hr[e],a=null,r=ye.util.createBuffer(),n=new Array(80),i=0;i<80;++i)n[i]=new Array(2);var s=64;switch(e){case"SHA-384":s=48;break;case"SHA-512/256":s=32;break;case"SHA-512/224":s=28;break}var o={algorithm:e.replace("-","").toLowerCase(),blockLength:128,digestLength:s,messageLength:0,fullMessageLength:null,messageLengthSize:16};return o.start=function(){o.messageLength=0,o.fullMessageLength=o.messageLength128=[];for(var u=o.messageLengthSize/4,l=0;l<u;++l)o.fullMessageLength.push(0);r=ye.util.createBuffer(),a=new Array(t.length);for(var l=0;l<t.length;++l)a[l]=t[l].slice(0);return o},o.start(),o.update=function(u,l){l==="utf8"&&(u=ye.util.encodeUtf8(u));var f=u.length;o.messageLength+=f,f=[f/4294967296>>>0,f>>>0];for(var c=o.fullMessageLength.length-1;c>=0;--c)o.fullMessageLength[c]+=f[1],f[1]=f[0]+(o.fullMessageLength[c]/4294967296>>>0),o.fullMessageLength[c]=o.fullMessageLength[c]>>>0,f[0]=f[1]/4294967296>>>0;return r.putBytes(u),Yo(a,n,r),(r.read>2048||r.length()===0)&&r.compact(),o},o.digest=function(){var u=ye.util.createBuffer();u.putBytes(r.bytes());var l=o.fullMessageLength[o.fullMessageLength.length-1]+o.messageLengthSize,f=l&o.blockLength-1;u.putBytes(hi.substr(0,o.blockLength-f));for(var c,y,m=o.fullMessageLength[0]*8,h=0;h<o.fullMessageLength.length-1;++h)c=o.fullMessageLength[h+1]*8,y=c/4294967296>>>0,m+=y,u.putInt32(m>>>0),m=c>>>0;u.putInt32(m);for(var v=new Array(a.length),h=0;h<a.length;++h)v[h]=a[h].slice(0);Yo(v,n,u);var C=ye.util.createBuffer(),T;e==="SHA-512"?T=v.length:e==="SHA-384"?T=v.length-2:T=v.length-4;for(var h=0;h<T;++h)C.putInt32(v[h][0]),(h!==T-1||e!=="SHA-512/224")&&C.putInt32(v[h][1]);return C},o};var hi=null,Zo=!1,gi=null,hr=null;function Rd(){hi="\x80",hi+=ye.util.fillString("\0",128),gi=[[1116352408,3609767458],[1899447441,602891725],[3049323471,3964484399],[3921009573,2173295548],[961987163,4081628472],[1508970993,3053834265],[2453635748,2937671579],[2870763221,3664609560],[3624381080,2734883394],[310598401,1164996542],[607225278,1323610764],[1426881987,3590304994],[1925078388,4068182383],[2162078206,991336113],[2614888103,633803317],[3248222580,3479774868],[3835390401,2666613458],[4022224774,944711139],[264347078,2341262773],[604807628,2007800933],[770255983,1495990901],[1249150122,1856431235],[1555081692,3175218132],[1996064986,2198950837],[2554220882,3999719339],[2821834349,766784016],[2952996808,2566594879],[3210313671,3203337956],[3336571891,1034457026],[3584528711,2466948901],[113926993,3758326383],[338241895,168717936],[666307205,1188179964],[773529912,1546045734],[1294757372,1522805485],[1396182291,2643833823],[1695183700,2343527390],[1986661051,1014477480],[2177026350,1206759142],[2456956037,344077627],[2730485921,1290863460],[2820302411,3158454273],[3259730800,3505952657],[3345764771,106217008],[3516065817,3606008344],[3600352804,1432725776],[4094571909,1467031594],[275423344,851169720],[430227734,3100823752],[506948616,1363258195],[659060556,3750685593],[883997877,3785050280],[958139571,3318307427],[1322822218,3812723403],[1537002063,2003034995],[1747873779,3602036899],[1955562222,1575990012],[2024104815,1125592928],[2227730452,2716904306],[2361852424,442776044],[2428436474,593698344],[2756734187,3733110249],[3204031479,2999351573],[3329325298,3815920427],[3391569614,3928383900],[3515267271,566280711],[3940187606,3454069534],[4118630271,4000239992],[116418474,1914138554],[174292421,2731055270],[289380356,3203993006],[460393269,320620315],[685471733,587496836],[852142971,1086792851],[1017036298,365543100],[1126000580,2618297676],[1288033470,3409855158],[1501505948,4234509866],[1607167915,987167468],[1816402316,1246189591]],hr={},hr["SHA-512"]=[[1779033703,4089235720],[3144134277,2227873595],[1013904242,4271175723],[2773480762,1595750129],[1359893119,2917565137],[2600822924,725511199],[528734635,4215389547],[1541459225,327033209]],hr["SHA-384"]=[[3418070365,3238371032],[1654270250,914150663],[2438529370,812702999],[355462360,4144912697],[1731405415,4290775857],[2394180231,1750603025],[3675008525,1694076839],[1203062813,3204075428]],hr["SHA-512/256"]=[[573645204,4230739756],[2673172387,3360449730],[596883563,1867755857],[2520282905,1497426621],[2519219938,2827943907],[3193839141,1401305490],[721525244,746961066],[246885852,2177182882]],hr["SHA-512/224"]=[[2352822216,424955298],[1944164710,2312950998],[502970286,855612546],[1738396948,1479516111],[258812777,2077511080],[2011393907,79989058],[1067287976,1780299464],[286451373,2446758561]],Zo=!0}function Yo(e,t,a){for(var r,n,i,s,o,u,l,f,c,y,m,h,v,C,T,I,A,L,N,P,G,j,ie,oe,ce,he,je,ut,ue,Se,V,ar,Er,Te,be,we=a.length();we>=128;){for(ue=0;ue<16;++ue)t[ue][0]=a.getInt32()>>>0,t[ue][1]=a.getInt32()>>>0;for(;ue<80;++ue)ar=t[ue-2],Se=ar[0],V=ar[1],r=((Se>>>19|V<<13)^(V>>>29|Se<<3)^Se>>>6)>>>0,n=((Se<<13|V>>>19)^(V<<3|Se>>>29)^(Se<<26|V>>>6))>>>0,Te=t[ue-15],Se=Te[0],V=Te[1],i=((Se>>>1|V<<31)^(Se>>>8|V<<24)^Se>>>7)>>>0,s=((Se<<31|V>>>1)^(Se<<24|V>>>8)^(Se<<25|V>>>7))>>>0,Er=t[ue-7],be=t[ue-16],V=n+Er[1]+s+be[1],t[ue][0]=r+Er[0]+i+be[0]+(V/4294967296>>>0)>>>0,t[ue][1]=V>>>0;for(v=e[0][0],C=e[0][1],T=e[1][0],I=e[1][1],A=e[2][0],L=e[2][1],N=e[3][0],P=e[3][1],G=e[4][0],j=e[4][1],ie=e[5][0],oe=e[5][1],ce=e[6][0],he=e[6][1],je=e[7][0],ut=e[7][1],ue=0;ue<80;++ue)l=((G>>>14|j<<18)^(G>>>18|j<<14)^(j>>>9|G<<23))>>>0,f=((G<<18|j>>>14)^(G<<14|j>>>18)^(j<<23|G>>>9))>>>0,c=(ce^G&(ie^ce))>>>0,y=(he^j&(oe^he))>>>0,o=((v>>>28|C<<4)^(C>>>2|v<<30)^(C>>>7|v<<25))>>>0,u=((v<<4|C>>>28)^(C<<30|v>>>2)^(C<<25|v>>>7))>>>0,m=(v&T|A&(v^T))>>>0,h=(C&I|L&(C^I))>>>0,V=ut+f+y+gi[ue][1]+t[ue][1],r=je+l+c+gi[ue][0]+t[ue][0]+(V/4294967296>>>0)>>>0,n=V>>>0,V=u+h,i=o+m+(V/4294967296>>>0)>>>0,s=V>>>0,je=ce,ut=he,ce=ie,he=oe,ie=G,oe=j,V=P+n,G=N+r+(V/4294967296>>>0)>>>0,j=V>>>0,N=A,P=L,A=T,L=I,T=v,I=C,V=n+s,v=r+i+(V/4294967296>>>0)>>>0,C=V>>>0;V=e[0][1]+C,e[0][0]=e[0][0]+v+(V/4294967296>>>0)>>>0,e[0][1]=V>>>0,V=e[1][1]+I,e[1][0]=e[1][0]+T+(V/4294967296>>>0)>>>0,e[1][1]=V>>>0,V=e[2][1]+L,e[2][0]=e[2][0]+A+(V/4294967296>>>0)>>>0,e[2][1]=V>>>0,V=e[3][1]+P,e[3][0]=e[3][0]+N+(V/4294967296>>>0)>>>0,e[3][1]=V>>>0,V=e[4][1]+j,e[4][0]=e[4][0]+G+(V/4294967296>>>0)>>>0,e[4][1]=V>>>0,V=e[5][1]+oe,e[5][0]=e[5][0]+ie+(V/4294967296>>>0)>>>0,e[5][1]=V>>>0,V=e[6][1]+he,e[6][0]=e[6][0]+ce+(V/4294967296>>>0)>>>0,e[6][1]=V>>>0,V=e[7][1]+ut,e[7][0]=e[7][0]+je+(V/4294967296>>>0)>>>0,e[7][1]=V>>>0,we-=128}}});var eu=H(mi=>{"use strict";var _d=W();mt();var Ne=_d.asn1;mi.privateKeyValidator={name:"PrivateKeyInfo",tagClass:Ne.Class.UNIVERSAL,type:Ne.Type.SEQUENCE,constructed:!0,value:[{name:"PrivateKeyInfo.version",tagClass:Ne.Class.UNIVERSAL,type:Ne.Type.INTEGER,constructed:!1,capture:"privateKeyVersion"},{name:"PrivateKeyInfo.privateKeyAlgorithm",tagClass:Ne.Class.UNIVERSAL,type:Ne.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:Ne.Class.UNIVERSAL,type:Ne.Type.OID,constructed:!1,capture:"privateKeyOid"}]},{name:"PrivateKeyInfo",tagClass:Ne.Class.UNIVERSAL,type:Ne.Type.OCTETSTRING,constructed:!1,capture:"privateKey"}]};mi.publicKeyValidator={name:"SubjectPublicKeyInfo",tagClass:Ne.Class.UNIVERSAL,type:Ne.Type.SEQUENCE,constructed:!0,captureAsn1:"subjectPublicKeyInfo",value:[{name:"SubjectPublicKeyInfo.AlgorithmIdentifier",tagClass:Ne.Class.UNIVERSAL,type:Ne.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:Ne.Class.UNIVERSAL,type:Ne.Type.OID,constructed:!1,capture:"publicKeyOid"}]},{tagClass:Ne.Class.UNIVERSAL,type:Ne.Type.BITSTRING,constructed:!1,composed:!0,captureBitStringValue:"ed25519PublicKey"}]}});var pu=H((Hg,du)=>{"use strict";var Le=W();Gr();lt();yi();re();var su=eu(),Nd=su.publicKeyValidator,Pd=su.privateKeyValidator;typeof tu>"u"&&(tu=Le.jsbn.BigInteger);var tu,Ci=Le.util.ByteBuffer,et=typeof Buffer>"u"?Uint8Array:Buffer;Le.pki=Le.pki||{};du.exports=Le.pki.ed25519=Le.ed25519=Le.ed25519||{};var X=Le.ed25519;X.constants={};X.constants.PUBLIC_KEY_BYTE_LENGTH=32;X.constants.PRIVATE_KEY_BYTE_LENGTH=64;X.constants.SEED_BYTE_LENGTH=32;X.constants.SIGN_BYTE_LENGTH=64;X.constants.HASH_BYTE_LENGTH=64;X.generateKeyPair=function(e){e=e||{};var t=e.seed;if(t===void 0)t=Le.random.getBytesSync(X.constants.SEED_BYTE_LENGTH);else if(typeof t=="string"){if(t.length!==X.constants.SEED_BYTE_LENGTH)throw new TypeError('"seed" must be '+X.constants.SEED_BYTE_LENGTH+" bytes in length.")}else if(!(t instanceof Uint8Array))throw new TypeError('"seed" must be a node.js Buffer, Uint8Array, or a binary string.');t=kt({message:t,encoding:"binary"});for(var a=new et(X.constants.PUBLIC_KEY_BYTE_LENGTH),r=new et(X.constants.PRIVATE_KEY_BYTE_LENGTH),n=0;n<32;++n)r[n]=t[n];return Ud(a,r),{publicKey:a,privateKey:r}};X.privateKeyFromAsn1=function(e){var t={},a=[],r=Le.asn1.validate(e,Pd,t,a);if(!r){var n=new Error("Invalid Key.");throw n.errors=a,n}var i=Le.asn1.derToOid(t.privateKeyOid),s=Le.oids.EdDSA25519;if(i!==s)throw new Error('Invalid OID "'+i+'"; OID must be "'+s+'".');var o=t.privateKey,u=kt({message:Le.asn1.fromDer(o).value,encoding:"binary"});return{privateKeyBytes:u}};X.publicKeyFromAsn1=function(e){var t={},a=[],r=Le.asn1.validate(e,Nd,t,a);if(!r){var n=new Error("Invalid Key.");throw n.errors=a,n}var i=Le.asn1.derToOid(t.publicKeyOid),s=Le.oids.EdDSA25519;if(i!==s)throw new Error('Invalid OID "'+i+'"; OID must be "'+s+'".');var o=t.ed25519PublicKey;if(o.length!==X.constants.PUBLIC_KEY_BYTE_LENGTH)throw new Error("Key length is invalid.");return kt({message:o,encoding:"binary"})};X.publicKeyFromPrivateKey=function(e){e=e||{};var t=kt({message:e.privateKey,encoding:"binary"});if(t.length!==X.constants.PRIVATE_KEY_BYTE_LENGTH)throw new TypeError('"options.privateKey" must have a byte length of '+X.constants.PRIVATE_KEY_BYTE_LENGTH);for(var a=new et(X.constants.PUBLIC_KEY_BYTE_LENGTH),r=0;r<a.length;++r)a[r]=t[32+r];return a};X.sign=function(e){e=e||{};var t=kt(e),a=kt({message:e.privateKey,encoding:"binary"});if(a.length===X.constants.SEED_BYTE_LENGTH){var r=X.generateKeyPair({seed:a});a=r.privateKey}else if(a.length!==X.constants.PRIVATE_KEY_BYTE_LENGTH)throw new TypeError('"options.privateKey" must have a byte length of '+X.constants.SEED_BYTE_LENGTH+" or "+X.constants.PRIVATE_KEY_BYTE_LENGTH);var n=new et(X.constants.SIGN_BYTE_LENGTH+t.length);Fd(n,t,t.length,a);for(var i=new et(X.constants.SIGN_BYTE_LENGTH),s=0;s<i.length;++s)i[s]=n[s];return i};X.verify=function(e){e=e||{};var t=kt(e);if(e.signature===void 0)throw new TypeError('"options.signature" must be a node.js Buffer, a Uint8Array, a forge ByteBuffer, or a binary string.');var a=kt({message:e.signature,encoding:"binary"});if(a.length!==X.constants.SIGN_BYTE_LENGTH)throw new TypeError('"options.signature" must have a byte length of '+X.constants.SIGN_BYTE_LENGTH);var r=kt({message:e.publicKey,encoding:"binary"});if(r.length!==X.constants.PUBLIC_KEY_BYTE_LENGTH)throw new TypeError('"options.publicKey" must have a byte length of '+X.constants.PUBLIC_KEY_BYTE_LENGTH);var n=new et(X.constants.SIGN_BYTE_LENGTH+t.length),i=new et(X.constants.SIGN_BYTE_LENGTH+t.length),s;for(s=0;s<X.constants.SIGN_BYTE_LENGTH;++s)n[s]=a[s];for(s=0;s<t.length;++s)n[s+X.constants.SIGN_BYTE_LENGTH]=t[s];return Od(i,n,n.length,r)>=0};function kt(e){var t=e.message;if(t instanceof Uint8Array||t instanceof et)return t;var a=e.encoding;if(t===void 0)if(e.md)t=e.md.digest().getBytes(),a="binary";else throw new TypeError('"options.message" or "options.md" not specified.');if(typeof t=="string"&&!a)throw new TypeError('"options.encoding" must be "binary" or "utf8".');if(typeof t=="string"){if(typeof Buffer<"u")return Buffer.from(t,a);t=new Ci(t,a)}else if(!(t instanceof Ci))throw new TypeError('"options.message" must be a node.js Buffer, a Uint8Array, a forge ByteBuffer, or a string with "options.encoding" specifying its encoding.');for(var r=new et(t.length()),n=0;n<r.length;++n)r[n]=t.at(n);return r}var xi=q(),Ha=q([1]),Dd=q([30883,4953,19914,30187,55467,16705,2637,112,59544,30585,16505,36039,65139,11119,27886,20995]),Ld=q([61785,9906,39828,60374,45398,33411,5274,224,53552,61171,33010,6542,64743,22239,55772,9222]),ru=q([54554,36645,11616,51542,42930,38181,51040,26924,56412,64982,57905,49316,21502,52590,14035,8553]),au=q([26200,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214]),vi=new Float64Array([237,211,245,92,26,99,18,88,214,156,247,162,222,249,222,20,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16]),kd=q([41136,18958,6951,50414,58488,44335,6150,12099,55207,15867,153,11085,57099,20417,9344,11139]);function Yr(e,t){var a=Le.md.sha512.create(),r=new Ci(e);a.update(r.getBytes(t),"binary");var n=a.digest().getBytes();if(typeof Buffer<"u")return Buffer.from(n,"binary");for(var i=new et(X.constants.HASH_BYTE_LENGTH),s=0;s<64;++s)i[s]=n.charCodeAt(s);return i}function Ud(e,t){var a=[q(),q(),q(),q()],r,n=Yr(t,32);for(n[0]&=248,n[31]&=127,n[31]|=64,Ii(a,n),bi(e,a),r=0;r<32;++r)t[r+32]=e[r];return 0}function Fd(e,t,a,r){var n,i,s=new Float64Array(64),o=[q(),q(),q(),q()],u=Yr(r,32);u[0]&=248,u[31]&=127,u[31]|=64;var l=a+64;for(n=0;n<a;++n)e[64+n]=t[n];for(n=0;n<32;++n)e[32+n]=u[32+n];var f=Yr(e.subarray(32),a+32);for(Si(f),Ii(o,f),bi(e,o),n=32;n<64;++n)e[n]=r[n];var c=Yr(e,a+64);for(Si(c),n=32;n<64;++n)s[n]=0;for(n=0;n<32;++n)s[n]=f[n];for(n=0;n<32;++n)for(i=0;i<32;i++)s[n+i]+=c[n]*u[i];return ou(e.subarray(32),s),l}function Od(e,t,a,r){var n,i,s=new et(32),o=[q(),q(),q(),q()],u=[q(),q(),q(),q()];if(i=-1,a<64||Vd(u,r))return-1;for(n=0;n<a;++n)e[n]=t[n];for(n=0;n<32;++n)e[n+32]=r[n];var l=Yr(e,a);if(Si(l),fu(o,u,l),Ii(u,t.subarray(32)),Ti(o,u),bi(s,o),a-=64,uu(t,0,s,0)){for(n=0;n<a;++n)e[n]=0;return-1}for(n=0;n<a;++n)e[n]=t[n+64];return i=a,i}function ou(e,t){var a,r,n,i;for(r=63;r>=32;--r){for(a=0,n=r-32,i=r-12;n<i;++n)t[n]+=a-16*t[r]*vi[n-(r-32)],a=t[n]+128>>8,t[n]-=a*256;t[n]+=a,t[r]=0}for(a=0,n=0;n<32;++n)t[n]+=a-(t[31]>>4)*vi[n],a=t[n]>>8,t[n]&=255;for(n=0;n<32;++n)t[n]-=a*vi[n];for(r=0;r<32;++r)t[r+1]+=t[r]>>8,e[r]=t[r]&255}function Si(e){for(var t=new Float64Array(64),a=0;a<64;++a)t[a]=e[a],e[a]=0;ou(e,t)}function Ti(e,t){var a=q(),r=q(),n=q(),i=q(),s=q(),o=q(),u=q(),l=q(),f=q();Dr(a,e[1],e[0]),Dr(f,t[1],t[0]),le(a,a,f),Pr(r,e[0],e[1]),Pr(f,t[0],t[1]),le(r,r,f),le(n,e[3],t[3]),le(n,n,Ld),le(i,e[2],t[2]),Pr(i,i,i),Dr(s,r,a),Dr(o,i,n),Pr(u,i,n),Pr(l,r,a),le(e[0],s,o),le(e[1],l,u),le(e[2],u,o),le(e[3],s,l)}function nu(e,t,a){for(var r=0;r<4;++r)cu(e[r],t[r],a)}function bi(e,t){var a=q(),r=q(),n=q();Hd(n,t[2]),le(a,t[0],n),le(r,t[1],n),za(e,r),e[31]^=lu(a)<<7}function za(e,t){var a,r,n,i=q(),s=q();for(a=0;a<16;++a)s[a]=t[a];for(Ei(s),Ei(s),Ei(s),r=0;r<2;++r){for(i[0]=s[0]-65517,a=1;a<15;++a)i[a]=s[a]-65535-(i[a-1]>>16&1),i[a-1]&=65535;i[15]=s[15]-32767-(i[14]>>16&1),n=i[15]>>16&1,i[14]&=65535,cu(s,i,1-n)}for(a=0;a<16;a++)e[2*a]=s[a]&255,e[2*a+1]=s[a]>>8}function Vd(e,t){var a=q(),r=q(),n=q(),i=q(),s=q(),o=q(),u=q();return Jt(e[2],Ha),Md(e[1],t),gr(n,e[1]),le(i,n,Dd),Dr(n,n,e[2]),Pr(i,e[2],i),gr(s,i),gr(o,s),le(u,o,s),le(a,u,n),le(a,a,i),Kd(a,a),le(a,a,n),le(a,a,i),le(a,a,i),le(e[0],a,i),gr(r,e[0]),le(r,r,i),iu(r,n)&&le(e[0],e[0],kd),gr(r,e[0]),le(r,r,i),iu(r,n)?-1:(lu(e[0])===t[31]>>7&&Dr(e[0],xi,e[0]),le(e[3],e[0],e[1]),0)}function Md(e,t){var a;for(a=0;a<16;++a)e[a]=t[2*a]+(t[2*a+1]<<8);e[15]&=32767}function Kd(e,t){var a=q(),r;for(r=0;r<16;++r)a[r]=t[r];for(r=250;r>=0;--r)gr(a,a),r!==1&&le(a,a,t);for(r=0;r<16;++r)e[r]=a[r]}function iu(e,t){var a=new et(32),r=new et(32);return za(a,e),za(r,t),uu(a,0,r,0)}function uu(e,t,a,r){return qd(e,t,a,r,32)}function qd(e,t,a,r,n){var i,s=0;for(i=0;i<n;++i)s|=e[t+i]^a[r+i];return(1&s-1>>>8)-1}function lu(e){var t=new et(32);return za(t,e),t[0]&1}function fu(e,t,a){var r,n;for(Jt(e[0],xi),Jt(e[1],Ha),Jt(e[2],Ha),Jt(e[3],xi),n=255;n>=0;--n)r=a[n/8|0]>>(n&7)&1,nu(e,t,r),Ti(t,e),Ti(e,e),nu(e,t,r)}function Ii(e,t){var a=[q(),q(),q(),q()];Jt(a[0],ru),Jt(a[1],au),Jt(a[2],Ha),le(a[3],ru,au),fu(e,a,t)}function Jt(e,t){var a;for(a=0;a<16;a++)e[a]=t[a]|0}function Hd(e,t){var a=q(),r;for(r=0;r<16;++r)a[r]=t[r];for(r=253;r>=0;--r)gr(a,a),r!==2&&r!==4&&le(a,a,t);for(r=0;r<16;++r)e[r]=a[r]}function Ei(e){var t,a,r=1;for(t=0;t<16;++t)a=e[t]+r+65535,r=Math.floor(a/65536),e[t]=a-r*65536;e[0]+=r-1+37*(r-1)}function cu(e,t,a){for(var r,n=~(a-1),i=0;i<16;++i)r=n&(e[i]^t[i]),e[i]^=r,t[i]^=r}function q(e){var t,a=new Float64Array(16);if(e)for(t=0;t<e.length;++t)a[t]=e[t];return a}function Pr(e,t,a){for(var r=0;r<16;++r)e[r]=t[r]+a[r]}function Dr(e,t,a){for(var r=0;r<16;++r)e[r]=t[r]-a[r]}function gr(e,t){le(e,t,t)}function le(e,t,a){var r,n,i=0,s=0,o=0,u=0,l=0,f=0,c=0,y=0,m=0,h=0,v=0,C=0,T=0,I=0,A=0,L=0,N=0,P=0,G=0,j=0,ie=0,oe=0,ce=0,he=0,je=0,ut=0,ue=0,Se=0,V=0,ar=0,Er=0,Te=a[0],be=a[1],we=a[2],ke=a[3],Ue=a[4],Fe=a[5],Oe=a[6],Ve=a[7],Me=a[8],Ke=a[9],qe=a[10],He=a[11],ze=a[12],Ge=a[13],Qe=a[14],We=a[15];r=t[0],i+=r*Te,s+=r*be,o+=r*we,u+=r*ke,l+=r*Ue,f+=r*Fe,c+=r*Oe,y+=r*Ve,m+=r*Me,h+=r*Ke,v+=r*qe,C+=r*He,T+=r*ze,I+=r*Ge,A+=r*Qe,L+=r*We,r=t[1],s+=r*Te,o+=r*be,u+=r*we,l+=r*ke,f+=r*Ue,c+=r*Fe,y+=r*Oe,m+=r*Ve,h+=r*Me,v+=r*Ke,C+=r*qe,T+=r*He,I+=r*ze,A+=r*Ge,L+=r*Qe,N+=r*We,r=t[2],o+=r*Te,u+=r*be,l+=r*we,f+=r*ke,c+=r*Ue,y+=r*Fe,m+=r*Oe,h+=r*Ve,v+=r*Me,C+=r*Ke,T+=r*qe,I+=r*He,A+=r*ze,L+=r*Ge,N+=r*Qe,P+=r*We,r=t[3],u+=r*Te,l+=r*be,f+=r*we,c+=r*ke,y+=r*Ue,m+=r*Fe,h+=r*Oe,v+=r*Ve,C+=r*Me,T+=r*Ke,I+=r*qe,A+=r*He,L+=r*ze,N+=r*Ge,P+=r*Qe,G+=r*We,r=t[4],l+=r*Te,f+=r*be,c+=r*we,y+=r*ke,m+=r*Ue,h+=r*Fe,v+=r*Oe,C+=r*Ve,T+=r*Me,I+=r*Ke,A+=r*qe,L+=r*He,N+=r*ze,P+=r*Ge,G+=r*Qe,j+=r*We,r=t[5],f+=r*Te,c+=r*be,y+=r*we,m+=r*ke,h+=r*Ue,v+=r*Fe,C+=r*Oe,T+=r*Ve,I+=r*Me,A+=r*Ke,L+=r*qe,N+=r*He,P+=r*ze,G+=r*Ge,j+=r*Qe,ie+=r*We,r=t[6],c+=r*Te,y+=r*be,m+=r*we,h+=r*ke,v+=r*Ue,C+=r*Fe,T+=r*Oe,I+=r*Ve,A+=r*Me,L+=r*Ke,N+=r*qe,P+=r*He,G+=r*ze,j+=r*Ge,ie+=r*Qe,oe+=r*We,r=t[7],y+=r*Te,m+=r*be,h+=r*we,v+=r*ke,C+=r*Ue,T+=r*Fe,I+=r*Oe,A+=r*Ve,L+=r*Me,N+=r*Ke,P+=r*qe,G+=r*He,j+=r*ze,ie+=r*Ge,oe+=r*Qe,ce+=r*We,r=t[8],m+=r*Te,h+=r*be,v+=r*we,C+=r*ke,T+=r*Ue,I+=r*Fe,A+=r*Oe,L+=r*Ve,N+=r*Me,P+=r*Ke,G+=r*qe,j+=r*He,ie+=r*ze,oe+=r*Ge,ce+=r*Qe,he+=r*We,r=t[9],h+=r*Te,v+=r*be,C+=r*we,T+=r*ke,I+=r*Ue,A+=r*Fe,L+=r*Oe,N+=r*Ve,P+=r*Me,G+=r*Ke,j+=r*qe,ie+=r*He,oe+=r*ze,ce+=r*Ge,he+=r*Qe,je+=r*We,r=t[10],v+=r*Te,C+=r*be,T+=r*we,I+=r*ke,A+=r*Ue,L+=r*Fe,N+=r*Oe,P+=r*Ve,G+=r*Me,j+=r*Ke,ie+=r*qe,oe+=r*He,ce+=r*ze,he+=r*Ge,je+=r*Qe,ut+=r*We,r=t[11],C+=r*Te,T+=r*be,I+=r*we,A+=r*ke,L+=r*Ue,N+=r*Fe,P+=r*Oe,G+=r*Ve,j+=r*Me,ie+=r*Ke,oe+=r*qe,ce+=r*He,he+=r*ze,je+=r*Ge,ut+=r*Qe,ue+=r*We,r=t[12],T+=r*Te,I+=r*be,A+=r*we,L+=r*ke,N+=r*Ue,P+=r*Fe,G+=r*Oe,j+=r*Ve,ie+=r*Me,oe+=r*Ke,ce+=r*qe,he+=r*He,je+=r*ze,ut+=r*Ge,ue+=r*Qe,Se+=r*We,r=t[13],I+=r*Te,A+=r*be,L+=r*we,N+=r*ke,P+=r*Ue,G+=r*Fe,j+=r*Oe,ie+=r*Ve,oe+=r*Me,ce+=r*Ke,he+=r*qe,je+=r*He,ut+=r*ze,ue+=r*Ge,Se+=r*Qe,V+=r*We,r=t[14],A+=r*Te,L+=r*be,N+=r*we,P+=r*ke,G+=r*Ue,j+=r*Fe,ie+=r*Oe,oe+=r*Ve,ce+=r*Me,he+=r*Ke,je+=r*qe,ut+=r*He,ue+=r*ze,Se+=r*Ge,V+=r*Qe,ar+=r*We,r=t[15],L+=r*Te,N+=r*be,P+=r*we,G+=r*ke,j+=r*Ue,ie+=r*Fe,oe+=r*Oe,ce+=r*Ve,he+=r*Me,je+=r*Ke,ut+=r*qe,ue+=r*He,Se+=r*ze,V+=r*Ge,ar+=r*Qe,Er+=r*We,i+=38*N,s+=38*P,o+=38*G,u+=38*j,l+=38*ie,f+=38*oe,c+=38*ce,y+=38*he,m+=38*je,h+=38*ut,v+=38*ue,C+=38*Se,T+=38*V,I+=38*ar,A+=38*Er,n=1,r=i+n+65535,n=Math.floor(r/65536),i=r-n*65536,r=s+n+65535,n=Math.floor(r/65536),s=r-n*65536,r=o+n+65535,n=Math.floor(r/65536),o=r-n*65536,r=u+n+65535,n=Math.floor(r/65536),u=r-n*65536,r=l+n+65535,n=Math.floor(r/65536),l=r-n*65536,r=f+n+65535,n=Math.floor(r/65536),f=r-n*65536,r=c+n+65535,n=Math.floor(r/65536),c=r-n*65536,r=y+n+65535,n=Math.floor(r/65536),y=r-n*65536,r=m+n+65535,n=Math.floor(r/65536),m=r-n*65536,r=h+n+65535,n=Math.floor(r/65536),h=r-n*65536,r=v+n+65535,n=Math.floor(r/65536),v=r-n*65536,r=C+n+65535,n=Math.floor(r/65536),C=r-n*65536,r=T+n+65535,n=Math.floor(r/65536),T=r-n*65536,r=I+n+65535,n=Math.floor(r/65536),I=r-n*65536,r=A+n+65535,n=Math.floor(r/65536),A=r-n*65536,r=L+n+65535,n=Math.floor(r/65536),L=r-n*65536,i+=n-1+37*(n-1),n=1,r=i+n+65535,n=Math.floor(r/65536),i=r-n*65536,r=s+n+65535,n=Math.floor(r/65536),s=r-n*65536,r=o+n+65535,n=Math.floor(r/65536),o=r-n*65536,r=u+n+65535,n=Math.floor(r/65536),u=r-n*65536,r=l+n+65535,n=Math.floor(r/65536),l=r-n*65536,r=f+n+65535,n=Math.floor(r/65536),f=r-n*65536,r=c+n+65535,n=Math.floor(r/65536),c=r-n*65536,r=y+n+65535,n=Math.floor(r/65536),y=r-n*65536,r=m+n+65535,n=Math.floor(r/65536),m=r-n*65536,r=h+n+65535,n=Math.floor(r/65536),h=r-n*65536,r=v+n+65535,n=Math.floor(r/65536),v=r-n*65536,r=C+n+65535,n=Math.floor(r/65536),C=r-n*65536,r=T+n+65535,n=Math.floor(r/65536),T=r-n*65536,r=I+n+65535,n=Math.floor(r/65536),I=r-n*65536,r=A+n+65535,n=Math.floor(r/65536),A=r-n*65536,r=L+n+65535,n=Math.floor(r/65536),L=r-n*65536,i+=n-1+37*(n-1),e[0]=i,e[1]=s,e[2]=o,e[3]=u,e[4]=l,e[5]=f,e[6]=c,e[7]=y,e[8]=m,e[9]=h,e[10]=v,e[11]=C,e[12]=T,e[13]=I,e[14]=A,e[15]=L}});var mu=H((zg,yu)=>{"use strict";var nt=W();re();lt();Gr();yu.exports=nt.kem=nt.kem||{};var hu=nt.jsbn.BigInteger;nt.kem.rsa={};nt.kem.rsa.create=function(e,t){t=t||{};var a=t.prng||nt.random,r={};return r.encrypt=function(n,i){var s=Math.ceil(n.n.bitLength()/8),o;do o=new hu(nt.util.bytesToHex(a.getBytesSync(s)),16).mod(n.n);while(o.compareTo(hu.ONE)<=0);o=nt.util.hexToBytes(o.toString(16));var u=s-o.length;u>0&&(o=nt.util.fillString("\0",u)+o);var l=n.encrypt(o,"NONE"),f=e.generate(o,i);return{encapsulation:l,key:f}},r.decrypt=function(n,i,s){var o=n.decrypt(i,"NONE");return e.generate(o,s)},r};nt.kem.kdf1=function(e,t){gu(this,e,0,t||e.digestLength)};nt.kem.kdf2=function(e,t){gu(this,e,1,t||e.digestLength)};function gu(e,t,a,r){e.generate=function(n,i){for(var s=new nt.util.ByteBuffer,o=Math.ceil(i/r)+a,u=new nt.util.ByteBuffer,l=a;l<o;++l){u.putInt32(l),t.start(),t.update(n+u.getBytes());var f=t.digest();s.putBytes(f.getBytes(r))}return s.truncate(s.length()-i),s.getBytes()}}});var xu=H((Gg,Cu)=>{"use strict";var J=W();re();Cu.exports=J.log=J.log||{};J.log.levels=["none","error","warning","info","debug","verbose","max"];var Ga={},Bi=[],Zr=null;J.log.LEVEL_LOCKED=2;J.log.NO_LEVEL_CHECK=4;J.log.INTERPOLATE=8;for(_t=0;_t<J.log.levels.length;++_t)wi=J.log.levels[_t],Ga[wi]={index:_t,name:wi.toUpperCase()};var wi,_t;J.log.logMessage=function(e){for(var t=Ga[e.level].index,a=0;a<Bi.length;++a){var r=Bi[a];if(r.flags&J.log.NO_LEVEL_CHECK)r.f(e);else{var n=Ga[r.level].index;t<=n&&r.f(r,e)}}};J.log.prepareStandard=function(e){"standard"in e||(e.standard=Ga[e.level].name+" ["+e.category+"] "+e.message)};J.log.prepareFull=function(e){if(!("full"in e)){var t=[e.message];t=t.concat([]),e.full=J.util.format.apply(this,t)}};J.log.prepareStandardFull=function(e){"standardFull"in e||(J.log.prepareStandard(e),e.standardFull=e.standard)};for(Ai=["error","warning","info","debug","verbose"],_t=0;_t<Ai.length;++_t)(function(t){J.log[t]=function(a,r){var n=Array.prototype.slice.call(arguments).slice(2),i={timestamp:new Date,level:t,category:a,message:r,arguments:n};J.log.logMessage(i)}})(Ai[_t]);var Ai,_t;J.log.makeLogger=function(e){var t={flags:0,f:e};return J.log.setLevel(t,"none"),t};J.log.setLevel=function(e,t){var a=!1;if(e&&!(e.flags&J.log.LEVEL_LOCKED))for(var r=0;r<J.log.levels.length;++r){var n=J.log.levels[r];if(t==n){e.level=t,a=!0;break}}return a};J.log.lock=function(e,t){typeof t>"u"||t?e.flags|=J.log.LEVEL_LOCKED:e.flags&=~J.log.LEVEL_LOCKED};J.log.addLogger=function(e){Bi.push(e)};typeof console<"u"&&"log"in console?(console.error&&console.warn&&console.info&&console.debug?(vu={error:console.error,warning:console.warn,info:console.info,debug:console.debug,verbose:console.debug},Jr=function(e,t){J.log.prepareStandard(t);var a=vu[t.level],r=[t.standard];r=r.concat(t.arguments.slice()),a.apply(console,r)},Lr=J.log.makeLogger(Jr)):(Jr=function(t,a){J.log.prepareStandardFull(a),console.log(a.standardFull)},Lr=J.log.makeLogger(Jr)),J.log.setLevel(Lr,"debug"),J.log.addLogger(Lr),Zr=Lr):console={log:function(){}};var Lr,vu,Jr;Zr!==null&&typeof window<"u"&&window.location&&(Xr=new URL(window.location.href).searchParams,Xr.has("console.level")&&J.log.setLevel(Zr,Xr.get("console.level").slice(-1)[0]),Xr.has("console.lock")&&(Eu=Xr.get("console.lock").slice(-1)[0],Eu=="true"&&J.log.lock(Zr)));var Xr,Eu;J.log.consoleLogger=Zr});var Tu=H((Qg,Su)=>{"use strict";Su.exports=St();ba();Ar();Kn();yi()});var wu=H((Wg,Iu)=>{"use strict";var k=W();Gt();mt();Hr();Qt();ur();ti();lt();re();Oa();var x=k.asn1,Ze=Iu.exports=k.pkcs7=k.pkcs7||{};Ze.messageFromPem=function(e){var t=k.pem.decode(e)[0];if(t.type!=="PKCS7"){var a=new Error('Could not convert PKCS#7 message from PEM; PEM header type is not "PKCS#7".');throw a.headerType=t.type,a}if(t.procType&&t.procType.type==="ENCRYPTED")throw new Error("Could not convert PKCS#7 message from PEM; PEM is encrypted.");var r=x.fromDer(t.body);return Ze.messageFromAsn1(r)};Ze.messageToPem=function(e,t){var a={type:"PKCS7",body:x.toDer(e.toAsn1()).getBytes()};return k.pem.encode(a,{maxline:t})};Ze.messageFromAsn1=function(e){var t={},a=[];if(!x.validate(e,Ze.asn1.contentInfoValidator,t,a)){var r=new Error("Cannot read PKCS#7 message. ASN.1 object is not an PKCS#7 ContentInfo.");throw r.errors=a,r}var n=x.derToOid(t.contentType),i;switch(n){case k.pki.oids.envelopedData:i=Ze.createEnvelopedData();break;case k.pki.oids.encryptedData:i=Ze.createEncryptedData();break;case k.pki.oids.signedData:i=Ze.createSignedData();break;default:throw new Error("Cannot read PKCS#7 message. ContentType with OID "+n+" is not (yet) supported.")}return i.fromAsn1(t.content.value[0]),i};Ze.createSignedData=function(){var e=null;return e={type:k.pki.oids.signedData,version:1,certificates:[],crls:[],signers:[],digestAlgorithmIdentifiers:[],contentInfo:null,signerInfos:[],fromAsn1:function(r){if(_i(e,r,Ze.asn1.signedDataValidator),e.certificates=[],e.crls=[],e.digestAlgorithmIdentifiers=[],e.contentInfo=null,e.signerInfos=[],e.rawCapture.certificates)for(var n=e.rawCapture.certificates.value,i=0;i<n.length;++i)e.certificates.push(k.pki.certificateFromAsn1(n[i]))},toAsn1:function(){e.contentInfo||e.sign();for(var r=[],n=0;n<e.certificates.length;++n)r.push(k.pki.certificateToAsn1(e.certificates[n]));var i=[],s=x.create(x.Class.CONTEXT_SPECIFIC,0,!0,[x.create(x.Class.UNIVERSAL,x.Type.SEQUENCE,!0,[x.create(x.Class.UNIVERSAL,x.Type.INTEGER,!1,x.integerToDer(e.version).getBytes()),x.create(x.Class.UNIVERSAL,x.Type.SET,!0,e.digestAlgorithmIdentifiers),e.contentInfo])]);return r.length>0&&s.value[0].value.push(x.create(x.Class.CONTEXT_SPECIFIC,0,!0,r)),i.length>0&&s.value[0].value.push(x.create(x.Class.CONTEXT_SPECIFIC,1,!0,i)),s.value[0].value.push(x.create(x.Class.UNIVERSAL,x.Type.SET,!0,e.signerInfos)),x.create(x.Class.UNIVERSAL,x.Type.SEQUENCE,!0,[x.create(x.Class.UNIVERSAL,x.Type.OID,!1,x.oidToDer(e.type).getBytes()),s])},addSigner:function(r){var n=r.issuer,i=r.serialNumber;if(r.certificate){var s=r.certificate;typeof s=="string"&&(s=k.pki.certificateFromPem(s)),n=s.issuer.attributes,i=s.serialNumber}var o=r.key;if(!o)throw new Error("Could not add PKCS#7 signer; no private key specified.");typeof o=="string"&&(o=k.pki.privateKeyFromPem(o));var u=r.digestAlgorithm||k.pki.oids.sha1;switch(u){case k.pki.oids.sha1:case k.pki.oids.sha256:case k.pki.oids.sha384:case k.pki.oids.sha512:case k.pki.oids.md5:break;default:throw new Error("Could not add PKCS#7 signer; unknown message digest algorithm: "+u)}var l=r.authenticatedAttributes||[];if(l.length>0){for(var f=!1,c=!1,y=0;y<l.length;++y){var m=l[y];if(!f&&m.type===k.pki.oids.contentType){if(f=!0,c)break;continue}if(!c&&m.type===k.pki.oids.messageDigest){if(c=!0,f)break;continue}}if(!f||!c)throw new Error("Invalid signer.authenticatedAttributes. If signer.authenticatedAttributes is specified, then it must contain at least two attributes, PKCS #9 content-type and PKCS #9 message-digest.")}e.signers.push({key:o,version:1,issuer:n,serialNumber:i,digestAlgorithm:u,signatureAlgorithm:k.pki.oids.rsaEncryption,signature:null,authenticatedAttributes:l,unauthenticatedAttributes:[]})},sign:function(r){if(r=r||{},(typeof e.content!="object"||e.contentInfo===null)&&(e.contentInfo=x.create(x.Class.UNIVERSAL,x.Type.SEQUENCE,!0,[x.create(x.Class.UNIVERSAL,x.Type.OID,!1,x.oidToDer(k.pki.oids.data).getBytes())]),"content"in e)){var n;e.content instanceof k.util.ByteBuffer?n=e.content.bytes():typeof e.content=="string"&&(n=k.util.encodeUtf8(e.content)),r.detached?e.detachedContent=x.create(x.Class.UNIVERSAL,x.Type.OCTETSTRING,!1,n):e.contentInfo.value.push(x.create(x.Class.CONTEXT_SPECIFIC,0,!0,[x.create(x.Class.UNIVERSAL,x.Type.OCTETSTRING,!1,n)]))}if(e.signers.length!==0){var i=t();a(i)}},verify:function(){throw new Error("PKCS#7 signature verification not yet implemented.")},addCertificate:function(r){typeof r=="string"&&(r=k.pki.certificateFromPem(r)),e.certificates.push(r)},addCertificateRevokationList:function(r){throw new Error("PKCS#7 CRL support not yet implemented.")}},e;function t(){for(var r={},n=0;n<e.signers.length;++n){var i=e.signers[n],s=i.digestAlgorithm;s in r||(r[s]=k.md[k.pki.oids[s]].create()),i.authenticatedAttributes.length===0?i.md=r[s]:i.md=k.md[k.pki.oids[s]].create()}e.digestAlgorithmIdentifiers=[];for(var s in r)e.digestAlgorithmIdentifiers.push(x.create(x.Class.UNIVERSAL,x.Type.SEQUENCE,!0,[x.create(x.Class.UNIVERSAL,x.Type.OID,!1,x.oidToDer(s).getBytes()),x.create(x.Class.UNIVERSAL,x.Type.NULL,!1,"")]));return r}function a(r){var n;if(e.detachedContent?n=e.detachedContent:(n=e.contentInfo.value[1],n=n.value[0]),!n)throw new Error("Could not sign PKCS#7 message; there is no content to sign.");var i=x.derToOid(e.contentInfo.value[0].value),s=x.toDer(n);s.getByte(),x.getBerValueLength(s),s=s.getBytes();for(var o in r)r[o].start().update(s);for(var u=new Date,l=0;l<e.signers.length;++l){var f=e.signers[l];if(f.authenticatedAttributes.length===0){if(i!==k.pki.oids.data)throw new Error("Invalid signer; authenticatedAttributes must be present when the ContentInfo content type is not PKCS#7 Data.")}else{f.authenticatedAttributesAsn1=x.create(x.Class.CONTEXT_SPECIFIC,0,!0,[]);for(var c=x.create(x.Class.UNIVERSAL,x.Type.SET,!0,[]),y=0;y<f.authenticatedAttributes.length;++y){var m=f.authenticatedAttributes[y];m.type===k.pki.oids.messageDigest?m.value=r[f.digestAlgorithm].digest():m.type===k.pki.oids.signingTime&&(m.value||(m.value=u)),c.value.push(Ri(m)),f.authenticatedAttributesAsn1.value.push(Ri(m))}s=x.toDer(c).getBytes(),f.md.start().update(s)}f.signature=f.key.sign(f.md,"RSASSA-PKCS1-V1_5")}e.signerInfos=$d(e.signers)}};Ze.createEncryptedData=function(){var e=null;return e={type:k.pki.oids.encryptedData,version:0,encryptedContent:{algorithm:k.pki.oids["aes256-CBC"]},fromAsn1:function(t){_i(e,t,Ze.asn1.encryptedDataValidator)},decrypt:function(t){t!==void 0&&(e.encryptedContent.key=t),bu(e)}},e};Ze.createEnvelopedData=function(){var e=null;return e={type:k.pki.oids.envelopedData,version:0,recipients:[],encryptedContent:{algorithm:k.pki.oids["aes256-CBC"]},fromAsn1:function(t){var a=_i(e,t,Ze.asn1.envelopedDataValidator);e.recipients=Qd(a.recipientInfos.value)},toAsn1:function(){return x.create(x.Class.UNIVERSAL,x.Type.SEQUENCE,!0,[x.create(x.Class.UNIVERSAL,x.Type.OID,!1,x.oidToDer(e.type).getBytes()),x.create(x.Class.CONTEXT_SPECIFIC,0,!0,[x.create(x.Class.UNIVERSAL,x.Type.SEQUENCE,!0,[x.create(x.Class.UNIVERSAL,x.Type.INTEGER,!1,x.integerToDer(e.version).getBytes()),x.create(x.Class.UNIVERSAL,x.Type.SET,!0,Wd(e.recipients)),x.create(x.Class.UNIVERSAL,x.Type.SEQUENCE,!0,Yd(e.encryptedContent))])])])},findRecipient:function(t){for(var a=t.issuer.attributes,r=0;r<e.recipients.length;++r){var n=e.recipients[r],i=n.issuer;if(n.serialNumber===t.serialNumber&&i.length===a.length){for(var s=!0,o=0;o<a.length;++o)if(i[o].type!==a[o].type||i[o].value!==a[o].value){s=!1;break}if(s)return n}}return null},decrypt:function(t,a){if(e.encryptedContent.key===void 0&&t!==void 0&&a!==void 0)switch(t.encryptedContent.algorithm){case k.pki.oids.rsaEncryption:case k.pki.oids.desCBC:var r=a.decrypt(t.encryptedContent.content);e.encryptedContent.key=k.util.createBuffer(r);break;default:throw new Error("Unsupported asymmetric cipher, OID "+t.encryptedContent.algorithm)}bu(e)},addRecipient:function(t){e.recipients.push({version:0,issuer:t.issuer.attributes,serialNumber:t.serialNumber,encryptedContent:{algorithm:k.pki.oids.rsaEncryption,key:t.publicKey}})},encrypt:function(t,a){if(e.encryptedContent.content===void 0){a=a||e.encryptedContent.algorithm,t=t||e.encryptedContent.key;var r,n,i;switch(a){case k.pki.oids["aes128-CBC"]:r=16,n=16,i=k.aes.createEncryptionCipher;break;case k.pki.oids["aes192-CBC"]:r=24,n=16,i=k.aes.createEncryptionCipher;break;case k.pki.oids["aes256-CBC"]:r=32,n=16,i=k.aes.createEncryptionCipher;break;case k.pki.oids["des-EDE3-CBC"]:r=24,n=8,i=k.des.createEncryptionCipher;break;default:throw new Error("Unsupported symmetric cipher, OID "+a)}if(t===void 0)t=k.util.createBuffer(k.random.getBytes(r));else if(t.length()!=r)throw new Error("Symmetric key has wrong length; got "+t.length()+" bytes, expected "+r+".");e.encryptedContent.algorithm=a,e.encryptedContent.key=t,e.encryptedContent.parameter=k.util.createBuffer(k.random.getBytes(n));var s=i(t);if(s.start(e.encryptedContent.parameter.copy()),s.update(e.content),!s.finish())throw new Error("Symmetric encryption failed.");e.encryptedContent.content=s.output}for(var o=0;o<e.recipients.length;++o){var u=e.recipients[o];if(u.encryptedContent.content===void 0)switch(u.encryptedContent.algorithm){case k.pki.oids.rsaEncryption:u.encryptedContent.content=u.encryptedContent.key.encrypt(e.encryptedContent.key.data);break;default:throw new Error("Unsupported asymmetric cipher, OID "+u.encryptedContent.algorithm)}}}},e};function zd(e){var t={},a=[];if(!x.validate(e,Ze.asn1.recipientInfoValidator,t,a)){var r=new Error("Cannot read PKCS#7 RecipientInfo. ASN.1 object is not an PKCS#7 RecipientInfo.");throw r.errors=a,r}return{version:t.version.charCodeAt(0),issuer:k.pki.RDNAttributesAsArray(t.issuer),serialNumber:k.util.createBuffer(t.serial).toHex(),encryptedContent:{algorithm:x.derToOid(t.encAlgorithm),parameter:t.encParameter?t.encParameter.value:void 0,content:t.encKey}}}function Gd(e){return x.create(x.Class.UNIVERSAL,x.Type.SEQUENCE,!0,[x.create(x.Class.UNIVERSAL,x.Type.INTEGER,!1,x.integerToDer(e.version).getBytes()),x.create(x.Class.UNIVERSAL,x.Type.SEQUENCE,!0,[k.pki.distinguishedNameToAsn1({attributes:e.issuer}),x.create(x.Class.UNIVERSAL,x.Type.INTEGER,!1,k.util.hexToBytes(e.serialNumber))]),x.create(x.Class.UNIVERSAL,x.Type.SEQUENCE,!0,[x.create(x.Class.UNIVERSAL,x.Type.OID,!1,x.oidToDer(e.encryptedContent.algorithm).getBytes()),x.create(x.Class.UNIVERSAL,x.Type.NULL,!1,"")]),x.create(x.Class.UNIVERSAL,x.Type.OCTETSTRING,!1,e.encryptedContent.content)])}function Qd(e){for(var t=[],a=0;a<e.length;++a)t.push(zd(e[a]));return t}function Wd(e){for(var t=[],a=0;a<e.length;++a)t.push(Gd(e[a]));return t}function jd(e){var t=x.create(x.Class.UNIVERSAL,x.Type.SEQUENCE,!0,[x.create(x.Class.UNIVERSAL,x.Type.INTEGER,!1,x.integerToDer(e.version).getBytes()),x.create(x.Class.UNIVERSAL,x.Type.SEQUENCE,!0,[k.pki.distinguishedNameToAsn1({attributes:e.issuer}),x.create(x.Class.UNIVERSAL,x.Type.INTEGER,!1,k.util.hexToBytes(e.serialNumber))]),x.create(x.Class.UNIVERSAL,x.Type.SEQUENCE,!0,[x.create(x.Class.UNIVERSAL,x.Type.OID,!1,x.oidToDer(e.digestAlgorithm).getBytes()),x.create(x.Class.UNIVERSAL,x.Type.NULL,!1,"")])]);if(e.authenticatedAttributesAsn1&&t.value.push(e.authenticatedAttributesAsn1),t.value.push(x.create(x.Class.UNIVERSAL,x.Type.SEQUENCE,!0,[x.create(x.Class.UNIVERSAL,x.Type.OID,!1,x.oidToDer(e.signatureAlgorithm).getBytes()),x.create(x.Class.UNIVERSAL,x.Type.NULL,!1,"")])),t.value.push(x.create(x.Class.UNIVERSAL,x.Type.OCTETSTRING,!1,e.signature)),e.unauthenticatedAttributes.length>0){for(var a=x.create(x.Class.CONTEXT_SPECIFIC,1,!0,[]),r=0;r<e.unauthenticatedAttributes.length;++r){var n=e.unauthenticatedAttributes[r];a.values.push(Ri(n))}t.value.push(a)}return t}function $d(e){for(var t=[],a=0;a<e.length;++a)t.push(jd(e[a]));return t}function Ri(e){var t;if(e.type===k.pki.oids.contentType)t=x.create(x.Class.UNIVERSAL,x.Type.OID,!1,x.oidToDer(e.value).getBytes());else if(e.type===k.pki.oids.messageDigest)t=x.create(x.Class.UNIVERSAL,x.Type.OCTETSTRING,!1,e.value.bytes());else if(e.type===k.pki.oids.signingTime){var a=new Date("1950-01-01T00:00:00Z"),r=new Date("2050-01-01T00:00:00Z"),n=e.value;if(typeof n=="string"){var i=Date.parse(n);isNaN(i)?n.length===13?n=x.utcTimeToDate(n):n=x.generalizedTimeToDate(n):n=new Date(i)}n>=a&&n<r?t=x.create(x.Class.UNIVERSAL,x.Type.UTCTIME,!1,x.dateToUtcTime(n)):t=x.create(x.Class.UNIVERSAL,x.Type.GENERALIZEDTIME,!1,x.dateToGeneralizedTime(n))}return x.create(x.Class.UNIVERSAL,x.Type.SEQUENCE,!0,[x.create(x.Class.UNIVERSAL,x.Type.OID,!1,x.oidToDer(e.type).getBytes()),x.create(x.Class.UNIVERSAL,x.Type.SET,!0,[t])])}function Yd(e){return[x.create(x.Class.UNIVERSAL,x.Type.OID,!1,x.oidToDer(k.pki.oids.data).getBytes()),x.create(x.Class.UNIVERSAL,x.Type.SEQUENCE,!0,[x.create(x.Class.UNIVERSAL,x.Type.OID,!1,x.oidToDer(e.algorithm).getBytes()),e.parameter?x.create(x.Class.UNIVERSAL,x.Type.OCTETSTRING,!1,e.parameter.getBytes()):void 0]),x.create(x.Class.CONTEXT_SPECIFIC,0,!0,[x.create(x.Class.UNIVERSAL,x.Type.OCTETSTRING,!1,e.content.getBytes())])]}function _i(e,t,a){var r={},n=[];if(!x.validate(t,a,r,n)){var i=new Error("Cannot read PKCS#7 message. ASN.1 object is not a supported PKCS#7 message.");throw i.errors=i,i}var s=x.derToOid(r.contentType);if(s!==k.pki.oids.data)throw new Error("Unsupported PKCS#7 message. Only wrapped ContentType Data supported.");if(r.encryptedContent){var o="";if(k.util.isArray(r.encryptedContent))for(var u=0;u<r.encryptedContent.length;++u){if(r.encryptedContent[u].type!==x.Type.OCTETSTRING)throw new Error("Malformed PKCS#7 message, expecting encrypted content constructed of only OCTET STRING objects.");o+=r.encryptedContent[u].value}else o=r.encryptedContent;e.encryptedContent={algorithm:x.derToOid(r.encAlgorithm),parameter:k.util.createBuffer(r.encParameter.value),content:k.util.createBuffer(o)}}if(r.content){var o="";if(k.util.isArray(r.content))for(var u=0;u<r.content.length;++u){if(r.content[u].type!==x.Type.OCTETSTRING)throw new Error("Malformed PKCS#7 message, expecting content constructed of only OCTET STRING objects.");o+=r.content[u].value}else o=r.content;e.content=k.util.createBuffer(o)}return e.version=r.version.charCodeAt(0),e.rawCapture=r,r}function bu(e){if(e.encryptedContent.key===void 0)throw new Error("Symmetric key not available.");if(e.content===void 0){var t;switch(e.encryptedContent.algorithm){case k.pki.oids["aes128-CBC"]:case k.pki.oids["aes192-CBC"]:case k.pki.oids["aes256-CBC"]:t=k.aes.createDecryptionCipher(e.encryptedContent.key);break;case k.pki.oids.desCBC:case k.pki.oids["des-EDE3-CBC"]:t=k.des.createDecryptionCipher(e.encryptedContent.key);break;default:throw new Error("Unsupported symmetric cipher, OID "+e.encryptedContent.algorithm)}if(t.start(e.encryptedContent.parameter),t.update(e.encryptedContent.content),!t.finish())throw new Error("Symmetric decryption failed.");e.content=t.output}}});var Bu=H((jg,Au)=>{"use strict";var Ie=W();Gt();Tr();ba();Ar();re();var Wa=Au.exports=Ie.ssh=Ie.ssh||{};Wa.privateKeyToPutty=function(e,t,a){a=a||"",t=t||"";var r="ssh-rsa",n=t===""?"none":"aes256-cbc",i="PuTTY-User-Key-File-2: "+r+`\r
|
|
24
|
+
`;i+="Encryption: "+n+`\r
|
|
25
|
+
`,i+="Comment: "+a+`\r
|
|
26
|
+
`;var s=Ie.util.createBuffer();kr(s,r),Nt(s,e.e),Nt(s,e.n);var o=Ie.util.encode64(s.bytes(),64),u=Math.floor(o.length/66)+1;i+="Public-Lines: "+u+`\r
|
|
27
|
+
`,i+=o;var l=Ie.util.createBuffer();Nt(l,e.d),Nt(l,e.p),Nt(l,e.q),Nt(l,e.qInv);var f;if(!t)f=Ie.util.encode64(l.bytes(),64);else{var c=l.length()+16-1;c-=c%16;var y=Qa(l.bytes());y.truncate(y.length()-c+l.length()),l.putBuffer(y);var m=Ie.util.createBuffer();m.putBuffer(Qa("\0\0\0\0",t)),m.putBuffer(Qa("\0\0\0",t));var h=Ie.aes.createEncryptionCipher(m.truncate(8),"CBC");h.start(Ie.util.createBuffer().fillWithByte(0,16)),h.update(l.copy()),h.finish();var v=h.output;v.truncate(16),f=Ie.util.encode64(v.bytes(),64)}u=Math.floor(f.length/66)+1,i+=`\r
|
|
28
|
+
Private-Lines: `+u+`\r
|
|
29
|
+
`,i+=f;var C=Qa("putty-private-key-file-mac-key",t),T=Ie.util.createBuffer();kr(T,r),kr(T,n),kr(T,a),T.putInt32(s.length()),T.putBuffer(s),T.putInt32(l.length()),T.putBuffer(l);var I=Ie.hmac.create();return I.start("sha1",C),I.update(T.bytes()),i+=`\r
|
|
30
|
+
Private-MAC: `+I.digest().toHex()+`\r
|
|
31
|
+
`,i};Wa.publicKeyToOpenSSH=function(e,t){var a="ssh-rsa";t=t||"";var r=Ie.util.createBuffer();return kr(r,a),Nt(r,e.e),Nt(r,e.n),a+" "+Ie.util.encode64(r.bytes())+" "+t};Wa.privateKeyToOpenSSH=function(e,t){return t?Ie.pki.encryptRsaPrivateKey(e,t,{legacy:!0,algorithm:"aes128"}):Ie.pki.privateKeyToPem(e)};Wa.getPublicKeyFingerprint=function(e,t){t=t||{};var a=t.md||Ie.md.md5.create(),r="ssh-rsa",n=Ie.util.createBuffer();kr(n,r),Nt(n,e.e),Nt(n,e.n),a.start(),a.update(n.getBytes());var i=a.digest();if(t.encoding==="hex"){var s=i.toHex();return t.delimiter?s.match(/.{2}/g).join(t.delimiter):s}else{if(t.encoding==="binary")return i.getBytes();if(t.encoding)throw new Error('Unknown encoding "'+t.encoding+'".')}return i};function Nt(e,t){var a=t.toString(16);a[0]>="8"&&(a="00"+a);var r=Ie.util.hexToBytes(a);e.putInt32(r.length),e.putBytes(r)}function kr(e,t){e.putInt32(t.length),e.putString(t)}function Qa(){for(var e=Ie.md.sha1.create(),t=arguments.length,a=0;a<t;++a)e.update(arguments[a]);return e.digest()}});var _u=H(($g,Ru)=>{"use strict";Ru.exports=W();Gt();$o();mt();ma();Hr();pu();Tr();mu();xu();Tu();ri();Ba();ur();Yn();ii();wu();oi();Zn();qn();ka();lt();Gn();Bu();pi();re()});var Du=H(Pu=>{"use strict";var se=_u();function Nu(e){var t=parseInt(e[0],16);return t<8?e:(t-=8,t.toString()+e.substring(1))}function Xd(e){switch(e){case"sha256":return se.md.sha256.create();default:return se.md.sha1.create()}}Pu.generate=function(t,a,r){typeof t=="function"?(r=t,t=void 0):typeof a=="function"&&(r=a,a={}),a=a||{};var n=function(o){var u=se.pki.createCertificate();u.serialNumber=Nu(se.util.bytesToHex(se.random.getBytesSync(9))),u.validity.notBefore=a.notBeforeDate||new Date;var l=new Date;u.validity.notAfter=l,u.validity.notAfter.setDate(l.getDate()+(a.days||365)),t=t||[{name:"commonName",value:"example.org"},{name:"countryName",value:"US"},{shortName:"ST",value:"Virginia"},{name:"localityName",value:"Blacksburg"},{name:"organizationName",value:"Test"},{shortName:"OU",value:"Test"}],u.setSubject(t),u.setIssuer(t),u.publicKey=o.publicKey,u.setExtensions(a.extensions||[{name:"basicConstraints",cA:!0},{name:"keyUsage",keyCertSign:!0,digitalSignature:!0,nonRepudiation:!0,keyEncipherment:!0,dataEncipherment:!0},{name:"subjectAltName",altNames:[{type:6,value:"http://example.org/webid#me"}]}]),u.sign(o.privateKey,Xd(a&&a.algorithm));let f=se.md.sha1.create().update(se.asn1.toDer(se.pki.certificateToAsn1(u)).getBytes()).digest().toHex().match(/.{2}/g).join(":");var c={private:se.pki.privateKeyToPem(o.privateKey),public:se.pki.publicKeyToPem(o.publicKey),cert:se.pki.certificateToPem(u),fingerprint:f};if(a&&a.pkcs7){var y=se.pkcs7.createSignedData();y.addCertificate(u),c.pkcs7=se.pkcs7.messageToPem(y)}if(a&&a.clientCertificate){var m=se.pki.rsa.generateKeyPair(a.clientCertificateKeySize||1024),h=se.pki.createCertificate();h.serialNumber=Nu(se.util.bytesToHex(se.random.getBytesSync(9))),h.validity.notBefore=new Date,h.validity.notAfter=new Date,h.validity.notAfter.setFullYear(h.validity.notBefore.getFullYear()+1);for(var v=JSON.parse(JSON.stringify(t)),C=0;C<v.length;C++)v[C].name==="commonName"&&(a.clientCertificateCN?v[C]={name:"commonName",value:a.clientCertificateCN}:v[C]={name:"commonName",value:"John Doe jdoe123"});if(h.setSubject(v),h.setIssuer(t),h.publicKey=m.publicKey,h.sign(o.privateKey),c.clientprivate=se.pki.privateKeyToPem(m.privateKey),c.clientpublic=se.pki.publicKeyToPem(m.publicKey),c.clientcert=se.pki.certificateToPem(h),a.pkcs7){var T=se.pkcs7.createSignedData();T.addCertificate(h),c.clientpkcs7=se.pkcs7.messageToPem(T)}}var I=se.pki.createCaStore();I.addCertificate(u);try{se.pki.verifyCertificateChain(I,[u],function(A,L,N){if(A!==!0)throw new Error("Certificate could not be verified.");return!0})}catch(A){throw new Error(A)}return c},i=a.keySize||1024;if(r)return se.pki.rsa.generateKeyPair({bits:i},function(o,u){if(o)return r(o);try{return r(null,n(u))}catch(l){return r(l)}});var s=a.keyPair?{privateKey:se.pki.privateKeyFromPem(a.keyPair.privateKey),publicKey:se.pki.publicKeyFromPem(a.keyPair.publicKey)}:se.pki.rsa.generateKeyPair(i);return n(s)}});function ap(e){return typeof e=="object"&&e!==null&&"type"in e&&"message"in e&&"error"in e&&typeof e.type=="string"&&typeof e.message=="string"}var it,qu,fe,tt=Cr(()=>{"use strict";it=(v=>(v.VALIDATION_ERROR="VALIDATION_ERROR",v.NOT_FOUND="NOT_FOUND",v.UNAUTHORIZED="UNAUTHORIZED",v.FORBIDDEN="FORBIDDEN",v.CONFLICT="CONFLICT",v.RATE_LIMITED="RATE_LIMITED",v.INTERNAL_SERVER_ERROR="INTERNAL_SERVER_ERROR",v.PAYLOAD_TOO_LARGE="PAYLOAD_TOO_LARGE",v.UNSUPPORTED_MEDIA_TYPE="UNSUPPORTED_MEDIA_TYPE",v.UPLOAD_TIMEOUT="UPLOAD_TIMEOUT",v.UNPROCESSABLE_ENTITY="UNPROCESSABLE_ENTITY",v.NETWORK_ERROR="NETWORK_ERROR",v.TIMEOUT_ERROR="TIMEOUT_ERROR",v.PARSE_ERROR="PARSE_ERROR",v.HTTP_ERROR="HTTP_ERROR",v))(it||{}),qu=(n=>(n.LOW="low",n.MEDIUM="medium",n.HIGH="high",n.CRITICAL="critical",n))(qu||{}),fe=class extends Error{type;title;status;correlationId;timestamp;details;constructor(t,a,r,n,i){super(a),this.name=this.constructor.name,this.type=t,this.title=a,this.status=r,this.correlationId=n,this.timestamp=new Date,this.details=i,Object.setPrototypeOf(this,new.target.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}toJSON(){let t={type:this.type,title:this.title,status:this.status,correlationId:this.correlationId,timestamp:this.timestamp.toISOString()};return this.details!==void 0?{...t,details:this.details}:t}toString(){return`${this.name}: ${this.title} [${this.correlationId}]`}}});function Ni(){let e=Date.now().toString(36),t=Math.random().toString(36).substr(2,9);return`req_${e}_${t}`}function xe(){let e=np.getStore();return e&&e.trim()?e:"unknown"}var Hu,np,st=Cr(()=>{"use strict";Hu=require("async_hooks"),np=new Hu.AsyncLocalStorage});var zu={};Or(zu,{InternalServerError:()=>Ft});var Ft,ta=Cr(()=>{"use strict";tt();st();Ft=class extends fe{constructor(t,a=void 0,r=void 0){super("INTERNAL_SERVER_ERROR",t,500,r??xe(),a)}}});var yr={};Or(yr,{ValidationError:()=>Ot});var Ot,Vt=Cr(()=>{"use strict";tt();st();Ot=class extends fe{constructor(t,a=void 0,r=void 0){super("VALIDATION_ERROR",t,400,r??xe(),a)}}});var Pi={};Or(Pi,{PayloadTooLargeError:()=>ra});var ra,Xa=Cr(()=>{"use strict";st();tt();ra=class extends fe{constructor(t,a,r){super("PAYLOAD_TOO_LARGE",t,413,r??xe(),a)}}});var Di={};Or(Di,{UnsupportedMediaTypeError:()=>aa});var aa,Za=Cr(()=>{"use strict";st();tt();aa=class extends fe{constructor(t,a,r){super("UNSUPPORTED_MEDIA_TYPE",t,415,r??xe(),a)}}});var Yh={};Or(Yh,{Blaize:()=>$h,BlaizeError:()=>fe,ConflictError:()=>mn,ErrorSeverity:()=>qu,ErrorType:()=>it,ForbiddenError:()=>yn,InternalServerError:()=>Ft,MiddlewareAPI:()=>nf,NotFoundError:()=>er,PayloadTooLargeError:()=>ra,PluginsAPI:()=>sf,RateLimitError:()=>vn,RequestTimeoutError:()=>En,RouterAPI:()=>af,ServerAPI:()=>rf,UnauthorizedError:()=>gn,UnprocessableEntityError:()=>Cn,UnsupportedMediaTypeError:()=>aa,VERSION:()=>tf,ValidationError:()=>Ot,compose:()=>nr,createDeleteRoute:()=>bn,createGetRoute:()=>xn,createHeadRoute:()=>wn,createMiddleware:()=>da,createOptionsRoute:()=>An,createPatchRoute:()=>In,createPlugin:()=>pa,createPostRoute:()=>Sn,createPutRoute:()=>Tn,createServer:()=>hn,isBodyParseError:()=>ap});module.exports=df(Yh);function ls(e,t,a){if(!e||e.skip&&e.skip(t))return Promise.resolve(a());try{let r=e.execute(t,a);return r instanceof Promise?r:Promise.resolve(r)}catch(r){return Promise.reject(r)}}function nr(e){return e.length===0?async(t,a)=>{await Promise.resolve(a())}:async function(t,a){let r=new Set,n=async i=>{if(i>=e.length)return Promise.resolve(a());let s=e[i];return ls(s,t,()=>{if(r.has(i))throw new Error("next() called multiple times");return r.add(i),n(i+1)})};return n(0)}}function da(e){if(typeof e=="function")return{name:"anonymous",execute:e,debug:!1};let{name:t="anonymous",handler:a,skip:r,debug:n=!1}=e,i={name:t,execute:a,debug:n};return r!==void 0?{...i,skip:r}:i}function pa(e,t,a,r={}){if(!e||typeof e!="string")throw new Error("Plugin name must be a non-empty string");if(!t||typeof t!="string")throw new Error("Plugin version must be a non-empty string");if(typeof a!="function")throw new Error("Plugin setup must be a function");return function(i){let s={...r,...i},o={name:e,version:t,register:async u=>{let l=await a(u,s);l&&typeof l=="object"&&Object.assign(o,l)}};return o}}var ps=require("url");var ha={};function fs(e){ha={...ha,...e}}function cs(){if(!ha.routesDir)throw new Error("Routes directory not configured. Make sure server is properly initialized.");return ha.routesDir}var ds=Ae(require("path"),1);function ga(e,t){e.startsWith("file://")&&(e=e.replace("file://","")),t.startsWith("file://")&&(t=t.replace("file://",""));let a=e.replace(/\\/g,"/"),r=t.replace(/\\/g,"/"),n=r.endsWith("/")?r:`${r}/`,i=a;a.startsWith(n)?i=a.substring(n.length):a.startsWith(r)?(i=a.substring(r.length),i.startsWith("/")&&(i=i.substring(1))):i=ds.relative(r,a).replace(/\\/g,"/"),i=i.replace(/\.[^.]+$/,"");let s=i.split("/").filter(Boolean),o=[],u=s.map(f=>{if(f.startsWith("[")&&f.endsWith("]")){let c=f.slice(1,-1);return o.push(c),`:${c}`}return f}),l=u.length>0?`/${u.join("/")}`:"/";return l.endsWith("/index")&&(l=l.slice(0,-6)||"/"),{filePath:e,routePath:l,params:o}}function pf(){let e=Error.prepareStackTrace;try{Error.prepareStackTrace=(n,i)=>i;let a=new Error().stack[3];if(!a||typeof a.getFileName!="function")throw new Error("Unable to determine caller file frame");let r=a.getFileName();if(!r)throw new Error("Unable to determine caller file name");return r.startsWith("file://")?(0,ps.fileURLToPath)(r):r}finally{Error.prepareStackTrace=e}}function ir(){let e=pf(),t=cs(),a=ga(e,t);return console.log(`\u{1F50E} Parsed route path: ${a.routePath} from file: ${e}`),a.routePath}var xn=e=>{sr("GET",e);let t=ir();return{GET:e,path:t}},Sn=e=>{sr("POST",e);let t=ir();return{POST:e,path:t}},Tn=e=>{sr("PUT",e);let t=ir();return{PUT:e,path:t}},bn=e=>{sr("DELETE",e);let t=ir();return{DELETE:e,path:t}},In=e=>{sr("PATCH",e);let t=ir();return{PATCH:e,path:t}},wn=e=>{sr("HEAD",e);let t=ir();return{HEAD:e,path:t}},An=e=>{sr("OPTIONS",e);let t=ir();return{OPTIONS:e,path:t}};function sr(e,t){if(!t.handler||typeof t.handler!="function")throw new Error(`Handler for method ${e} must be a function`);if(t.middleware&&!Array.isArray(t.middleware))throw new Error(`Middleware for method ${e} must be an array`);switch(t.schema&&hf(e,t.schema),e){case"GET":case"HEAD":case"DELETE":t.schema?.body&&console.warn(`Warning: ${e} requests typically don't have request bodies`);break}}function hf(e,t){let{params:a,query:r,body:n,response:i}=t;if(a&&(!a._def||typeof a.parse!="function"))throw new Error(`Params schema for ${e} must be a valid Zod schema`);if(r&&(!r._def||typeof r.parse!="function"))throw new Error(`Query schema for ${e} must be a valid Zod schema`);if(n&&(!n._def||typeof n.parse!="function"))throw new Error(`Body schema for ${e} must be a valid Zod schema`);if(i&&(!i._def||typeof i.parse!="function"))throw new Error(`Response schema for ${e} must be a valid Zod schema`)}var Jl=require("async_hooks"),ef=Ae(require("events"),1);var Ui=Ae(require("fs"),1),il=Ae(require("http"),1),sl=Ae(require("http2"),1);var Ut=Ae(require("fs"),1),ja=Ae(require("path"),1),Lu=Ae(Du(),1);async function ku(){let e=ja.join(process.cwd(),".blaizejs","certs"),t=ja.join(e,"dev.key"),a=ja.join(e,"dev.cert");if(Ut.existsSync(t)&&Ut.existsSync(a))return{keyFile:t,certFile:a};Ut.existsSync(e)||Ut.mkdirSync(e,{recursive:!0});let i=Lu.generate([{name:"commonName",value:"localhost"}],{days:365,algorithm:"sha256",keySize:2048,extensions:[{name:"basicConstraints",cA:!0},{name:"keyUsage",keyCertSign:!0,digitalSignature:!0,nonRepudiation:!0,keyEncipherment:!0,dataEncipherment:!0},{name:"extKeyUsage",serverAuth:!0,clientAuth:!0},{name:"subjectAltName",altNames:[{type:2,value:"localhost"},{type:7,ip:"127.0.0.1"}]}]});return Ut.writeFileSync(t,Buffer.from(i.private,"utf-8")),Ut.writeFileSync(a,Buffer.from(i.cert,"utf-8")),console.log(`
|
|
32
|
+
\u{1F512} Generated self-signed certificates for development at ${e}
|
|
33
|
+
`),{keyFile:t,certFile:a}}var gt=class extends Error{constructor(t="\u274C Response has already been sent"){super(t),this.name="ResponseSentError"}},ea=class extends gt{constructor(t="Cannot set header after response has been sent"){super(t)}},$a=class extends gt{constructor(t="Cannot set content type after response has been sent"){super(t)}},Ya=class extends gt{constructor(t="Invalide URL"){super(t)}};var Uu=require("async_hooks"),Zd=new Uu.AsyncLocalStorage;function Fu(e,t){return Zd.run(e,t)}var Gu=require("crypto"),Qu=require("fs"),Wu=require("os"),ju=require("path"),Li=require("stream");var Jd=/boundary=([^;]+)/i,ep=/Content-Disposition:\s*form-data;\s*name="([^"]+)"(?:;[\s\r\n]*filename="([^"]*)")?/i,tp=/Content-Type:\s*([^\r\n]+)/i,rp=/multipart\/form-data/i;function Ou(e){let t=e.match(Jd);if(!t||!t[1])return null;let a=t[1].trim();return a.startsWith('"')&&a.endsWith('"')&&(a=a.slice(1,-1)),a||null}function Vu(e){let t=e.match(ep);return!t||!t[1]?null:{name:t[1],filename:t[2]!==void 0?t[2]:void 0}}function Mu(e){let t=e.match(tp);return t&&t[1]?.trim()?t[1].trim():"application/octet-stream"}function Ku(e){return rp.test(e)}var ip={maxFileSize:10*1024*1024,maxFiles:10,maxFieldSize:1*1024*1024,allowedMimeTypes:[],allowedExtensions:[],strategy:"stream",tempDir:(0,Wu.tmpdir)(),computeHash:!1};function sp(e,t={}){return{boundary:Buffer.from(`--${e}`),options:{...ip,...t},fields:new Map,files:new Map,buffer:Buffer.alloc(0),stage:"boundary",currentHeaders:"",currentField:null,currentFilename:void 0,currentMimetype:"application/octet-stream",currentContentLength:0,fileCount:0,fieldCount:0,currentBufferChunks:[],currentStream:null,currentTempPath:null,currentWriteStream:null,streamController:null,cleanupTasks:[],hasFoundValidBoundary:!1,hasProcessedAnyPart:!1,isFinished:!1}}async function op(e,t){let a=Buffer.concat([e.buffer,t]),r={...e,buffer:a};for(;r.buffer.length>0&&!r.isFinished;){let n=await up(r);if(n===r)break;r=n}return r}async function up(e){switch(e.stage){case"boundary":return lp(e);case"headers":return fp(e);case"content":return cp(e);default:{let{InternalServerError:t}=await Promise.resolve().then(()=>(ta(),zu));throw new t("Invalid parser stage",{operation:e.stage})}}}function lp(e){let t=e.buffer.indexOf(e.boundary);if(t===-1)return e;let a=!0,r=e.buffer.subarray(t+e.boundary.length);return r.length>=2&&r.subarray(0,2).equals(Buffer.from("--"))?{...e,buffer:r,hasFoundValidBoundary:a,isFinished:!0,stage:"boundary"}:(r.length>=2&&r.subarray(0,2).equals(Buffer.from(`\r
|
|
34
|
+
`))&&(r=r.subarray(2)),{...e,buffer:r,hasFoundValidBoundary:a,stage:"headers",currentHeaders:""})}async function fp(e){let t=e.buffer.indexOf(`\r
|
|
35
|
+
\r
|
|
36
|
+
`);if(t===-1)return e;let a=e.buffer.subarray(0,t).toString("utf8"),r=e.buffer.subarray(t+4),n=Vu(a);if(!n){let{ValidationError:o}=await Promise.resolve().then(()=>(Vt(),yr));throw new o("Missing or invalid Content-Disposition header")}let i=Mu(a),s=n.filename!==void 0;if(s&&e.fileCount>=e.options.maxFiles){let{PayloadTooLargeError:o}=await Promise.resolve().then(()=>(Xa(),Pi));throw new o("Too many files in upload",{fileCount:e.fileCount+1,maxFiles:e.options.maxFiles,filename:n.filename})}if(s&&e.options.allowedMimeTypes.length>0&&!e.options.allowedMimeTypes.includes(i)){let{UnsupportedMediaTypeError:o}=await Promise.resolve().then(()=>(Za(),Di));throw new o("File type not allowed",{receivedMimeType:i,allowedMimeTypes:e.options.allowedMimeTypes,filename:n.filename})}return{...e,buffer:r,stage:"content",currentHeaders:a,currentField:n.name,currentFilename:n.filename,currentMimetype:i,currentContentLength:0,fileCount:s?e.fileCount+1:e.fileCount,fieldCount:s?e.fieldCount:e.fieldCount+1,currentBufferChunks:[]}}async function cp(e){let t=e.buffer.indexOf(e.boundary),a,r=!1,n=e.buffer;if(t===-1){let s=Math.max(0,e.buffer.length-e.boundary.length);if(s===0)return e;a=e.buffer.subarray(0,s),n=e.buffer.subarray(s)}else{let s=Math.max(0,t-2);a=e.buffer.subarray(0,s),n=e.buffer.subarray(t),r=!0}let i={...e,buffer:n};return a.length>0&&(i=await dp(i,a)),r&&(i=await gp(i),i={...i,stage:"boundary",hasProcessedAnyPart:!0}),i}async function dp(e,t){let a=e.currentContentLength+t.length,r=e.currentFilename!==void 0?e.options.maxFileSize:e.options.maxFieldSize;if(a>r){let n=e.currentFilename!==void 0,{PayloadTooLargeError:i}=await Promise.resolve().then(()=>(Xa(),Pi)),s=e.currentField?{contentType:n?"file":"field",currentSize:a,maxSize:r,field:e.currentField,filename:e.currentFilename}:{contentType:n?"file":"field",currentSize:a,maxSize:r,filename:e.currentFilename};throw new i(`${n?"File":"Field"} size exceeds limit`,s)}return e.currentFilename!==void 0?pp(e,t,a):{...e,currentContentLength:a,currentBufferChunks:[...e.currentBufferChunks,t]}}async function pp(e,t,a){switch(e.options.strategy){case"memory":return{...e,currentContentLength:a,currentBufferChunks:[...e.currentBufferChunks,t]};case"stream":return e.streamController&&e.streamController.enqueue(t),{...e,currentContentLength:a};case"temp":return e.currentWriteStream&&await Cp(e.currentWriteStream,t),{...e,currentContentLength:a};default:{let{ValidationError:r}=await Promise.resolve().then(()=>(Vt(),yr));throw new r("Invalid parsing strategy")}}}async function hp(e){if(e.currentFilename===void 0)return e;switch(e.options.strategy){case"memory":return{...e,currentBufferChunks:[]};case"stream":{let t=null,a=new ReadableStream({start:r=>{t=r}});return{...e,currentStream:a,streamController:t}}case"temp":{let t=(0,ju.join)(e.options.tempDir,`upload-${(0,Gu.randomUUID)()}`),a=(0,Qu.createWriteStream)(t),r=async()=>{try{let{unlink:n}=await import("fs/promises");await n(t)}catch(n){console.warn(`Failed to cleanup temp file: ${t}`,n)}};return{...e,currentTempPath:t,currentWriteStream:a,cleanupTasks:[...e.cleanupTasks,r]}}default:{let{ValidationError:t}=await Promise.resolve().then(()=>(Vt(),yr));throw new t("Invalid file processing strategy")}}}async function gp(e){return e.currentField?e.currentFilename!==void 0?yp(e):mp(e):na(e)}async function yp(e){if(!e.currentField||e.currentFilename===void 0)return na(e);let t,a,r;switch(e.options.strategy){case"memory":a=Buffer.concat(e.currentBufferChunks),t=Li.Readable.from(a);break;case"stream":e.streamController&&e.streamController.close(),t=e.currentStream;break;case"temp":e.currentWriteStream&&await Yu(e.currentWriteStream),r=e.currentTempPath,t=Li.Readable.from(Buffer.alloc(0));break;default:{let{ValidationError:s}=await Promise.resolve().then(()=>(Vt(),yr));throw new s("Invalid file finalization strategy")}}let n={filename:e.currentFilename,fieldname:e.currentField,mimetype:e.currentMimetype,size:e.currentContentLength,stream:t,buffer:a,tempPath:r},i=$u(e.files,e.currentField,n);return{...na(e),files:i}}function mp(e){if(!e.currentField)return na(e);let t=Buffer.concat(e.currentBufferChunks).toString("utf8"),a=$u(e.fields,e.currentField,t);return{...na(e),fields:a}}function na(e){return{...e,currentField:null,currentFilename:void 0,currentContentLength:0,currentBufferChunks:[],currentStream:null,streamController:null,currentTempPath:null,currentWriteStream:null}}function $u(e,t,a){let r=new Map(e),n=r.get(t)||[];return r.set(t,[...n,a]),r}async function vp(e){if(!e.hasFoundValidBoundary){let{ValidationError:r}=await Promise.resolve().then(()=>(Vt(),yr));throw new r("No valid multipart boundary found")}if(e.hasFoundValidBoundary&&!e.hasProcessedAnyPart){let{ValidationError:r}=await Promise.resolve().then(()=>(Vt(),yr));throw new r("Empty multipart request")}let t={};for(let[r,n]of e.fields.entries())t[r]=n.length===1?n[0]:n;let a={};for(let[r,n]of e.files.entries())a[r]=n.length===1?n[0]:n;return{fields:t,files:a}}async function Ep(e){await Promise.allSettled(e.cleanupTasks.map(t=>t())),e.streamController&&e.streamController.close(),e.currentWriteStream&&await Yu(e.currentWriteStream)}async function Cp(e,t){return new Promise((a,r)=>{e.write(t,n=>{n?r(n):a()})})}async function Yu(e){return new Promise(t=>{e.end(()=>t())})}async function Xu(e,t={}){let a=e.headers["content-type"]||"",r=Ou(a);if(!r){let{UnsupportedMediaTypeError:i}=await Promise.resolve().then(()=>(Za(),Di));throw new i("Missing boundary in multipart content-type",{receivedContentType:a,expectedFormat:"multipart/form-data; boundary=..."})}let n=sp(r,t);n.currentFilename!==void 0&&(n=await hp(n));try{for await(let i of e)n=await op(n,i);return vp(n)}finally{await Ep(n)}}var ia="Content-Type",Mt={json:512*1024,form:1024*1024,text:5*1024*1024,multipart:{maxFileSize:50*1024*1024,maxTotalSize:100*1024*1024,maxFiles:10,maxFieldSize:1024*1024},raw:10*1024*1024};function xp(e){let t=e.url||"/",a=e.headers.host||"localhost",n=`${e.socket&&e.socket.encrypted?"https":"http"}://${a}${t.startsWith("/")?"":"/"}${t}`;try{let i=new URL(n),s=i.pathname,o={};return i.searchParams.forEach((u,l)=>{o[l]!==void 0?Array.isArray(o[l])?o[l].push(u):o[l]=[o[l],u]:o[l]=u}),{path:s,url:i,query:o}}catch(i){throw console.warn(`Invalid URL: ${n}`,i),new Ya(`Invalid URL: ${n}`)}}function Sp(e){return"stream"in e||"httpVersionMajor"in e&&e.httpVersionMajor===2}function Tp(e){let t=e.socket&&e.socket.encrypted,a=e.headers["x-forwarded-proto"];return a?Array.isArray(a)?a[0]?.split(",")[0]?.trim()||"http":a.split(",")[0]?.trim()||"http":t?"https":"http"}async function Zu(e,t,a={}){let{path:r,url:n,query:i}=xp(e),s=e.method||"GET",o=Sp(e),u=Tp(e),l={},f={...a.initialState||{}},c={sent:!1},y={request:bp(e,{path:r,url:n,query:i,params:l,method:s,isHttp2:o,protocol:u}),response:{},state:f};return y.response=wp(t,c,y),a.parseBody&&await Up(e,y,a),y}function bp(e,t){return{raw:e,...t,header:Ju(e),headers:Ip(e),body:void 0}}function Ju(e){return t=>{let a=e.headers[t.toLowerCase()];return Array.isArray(a)?a.join(", "):a||void 0}}function Ip(e){let t=Ju(e);return a=>a&&Array.isArray(a)&&a.length>0?a.reduce((r,n)=>(r[n]=t(n),r),{}):Object.entries(e.headers).reduce((r,[n,i])=>(r[n]=Array.isArray(i)?i.join(", "):i||void 0,r),{})}function wp(e,t,a){return{raw:e,get sent(){return t.sent},status:Ap(e,t,a),header:Bp(e,t,a),headers:Rp(e,t,a),type:_p(e,t,a),json:Np(e,t),text:Pp(e,t),html:Dp(e,t),redirect:Lp(e,t),stream:kp(e,t)}}function Ap(e,t,a){return function(n){if(t.sent)throw new gt;return e.statusCode=n,a.response}}function Bp(e,t,a){return function(n,i){if(t.sent)throw new ea;return e.setHeader(n,i),a.response}}function Rp(e,t,a){return function(n){if(t.sent)throw new ea;for(let[i,s]of Object.entries(n))e.setHeader(i,s);return a.response}}function _p(e,t,a){return function(n){if(t.sent)throw new $a;return e.setHeader(ia,n),a.response}}function Np(e,t){return function(r,n){if(t.sent)throw new gt;n!==void 0&&(e.statusCode=n),e.setHeader(ia,"application/json"),e.end(JSON.stringify(r)),t.sent=!0}}function Pp(e,t){return function(r,n){if(t.sent)throw new gt;n!==void 0&&(e.statusCode=n),e.setHeader(ia,"text/plain"),e.end(r),t.sent=!0}}function Dp(e,t){return function(r,n){if(t.sent)throw new gt;n!==void 0&&(e.statusCode=n),e.setHeader(ia,"text/html"),e.end(r),t.sent=!0}}function Lp(e,t){return function(r,n=302){if(t.sent)throw new gt;e.statusCode=n,e.setHeader("Location",r),e.end(),t.sent=!0}}function kp(e,t){return function(r,n={}){if(t.sent)throw new gt;if(n.status!==void 0&&(e.statusCode=n.status),n.contentType&&e.setHeader(ia,n.contentType),n.headers)for(let[i,s]of Object.entries(n.headers))e.setHeader(i,s);r.pipe(e),r.on("end",()=>{t.sent=!0}),r.on("error",i=>{console.error("Stream error:",i),t.sent||(e.statusCode=500,e.end("Stream error"),t.sent=!0)})}}async function Up(e,t,a={}){if(Fp(e.method))return;let r=e.headers["content-type"]||"",n=parseInt(e.headers["content-length"]||"0",10);if(n===0)return;let i={json:a.bodyLimits?.json??Mt.json,form:a.bodyLimits?.form??Mt.form,text:a.bodyLimits?.text??Mt.text,raw:a.bodyLimits?.raw??Mt.raw,multipart:{maxFileSize:a.bodyLimits?.multipart?.maxFileSize??Mt.multipart.maxFileSize,maxFiles:a.bodyLimits?.multipart?.maxFiles??Mt.multipart.maxFiles,maxFieldSize:a.bodyLimits?.multipart?.maxFieldSize??Mt.multipart.maxFieldSize,maxTotalSize:a.bodyLimits?.multipart?.maxTotalSize??Mt.multipart.maxTotalSize}};try{if(r.includes("application/json")){if(n>i.json)throw new Error(`JSON body too large: ${n} > ${i.json} bytes`);await Op(e,t)}else if(r.includes("application/x-www-form-urlencoded")){if(n>i.form)throw new Error(`Form body too large: ${n} > ${i.form} bytes`);await Vp(e,t)}else if(r.includes("text/")){if(n>i.text)throw new Error(`Text body too large: ${n} > ${i.text} bytes`);await Kp(e,t)}else if(Ku(r))await qp(e,t,i.multipart);else{if(n>i.raw)throw new Error(`Request body too large: ${n} > ${i.raw} bytes`);return}}catch(s){let o=r.includes("multipart")?"multipart_parse_error":"body_read_error";Ja(t,o,"Error reading request body",s)}}function Fp(e){return["GET","HEAD","OPTIONS"].includes(e||"GET")}async function Op(e,t){let a=await ki(e);if(!a){console.warn("Empty body, skipping JSON parsing");return}if(a.trim()==="null"){console.warn('Body is the string "null"'),t.request.body=null;return}try{let r=JSON.parse(a);t.request.body=r}catch(r){t.request.body=null,Ja(t,"json_parse_error","Invalid JSON in request body",r)}}async function Vp(e,t){let a=await ki(e);if(a)try{t.request.body=Mp(a)}catch(r){t.request.body=null,Ja(t,"form_parse_error","Invalid form data in request body",r)}}function Mp(e){let t=new URLSearchParams(e),a={};return t.forEach((r,n)=>{a[n]!==void 0?Array.isArray(a[n])?a[n].push(r):a[n]=[a[n],r]:a[n]=r}),a}async function Kp(e,t){let a=await ki(e);a&&(t.request.body=a)}async function qp(e,t,a){try{let r=a||Mt.multipart,n=await Xu(e,{strategy:"stream",maxFileSize:r.maxFileSize,maxFiles:r.maxFiles,maxFieldSize:r.maxFieldSize});t.request.multipart=n,t.request.files=n.files,t.request.body=n.fields}catch(r){t.request.body=null,Ja(t,"multipart_parse_error","Failed to parse multipart data",r)}}function Ja(e,t,a,r){let n={type:t,message:a,error:r};e.state._bodyError=n}async function ki(e){return new Promise((t,a)=>{let r=[];e.on("data",n=>{r.push(Buffer.isBuffer(n)?n:Buffer.from(n))}),e.on("end",()=>{t(Buffer.concat(r).toString("utf8"))}),e.on("error",n=>{a(n)})})}tt();st();var er=class extends fe{constructor(t,a=void 0,r=void 0){super("NOT_FOUND",t,404,r??xe(),a)}};tt();st();ta();function Hp(e){return e instanceof fe}function el(e){if(Hp(e))return{type:e.type,title:e.title,status:e.status,correlationId:e.correlationId,timestamp:e.timestamp.toISOString(),details:e.details};let t=Ni(),a;e instanceof Error?a=e.message:e==null?a="Unknown error occurred":a=String(e);let r=new Ft("Internal Server Error",{originalMessage:a},t);return{type:r.type,title:r.title,status:r.status,correlationId:r.correlationId,timestamp:r.timestamp.toISOString(),details:r.details}}function tl(e){return e("x-correlation-id")??Ni()}function rl(e,t){e("x-correlation-id",t)}function al(e={}){let{debug:t=!1}=e;return{name:"ErrorBoundary",execute:async(r,n)=>{try{await n()}catch(i){if(r.response.sent){t&&console.error("Error occurred after response was sent:",i);return}t&&console.error("Error boundary caught error:",i);let s=tl(r.request.header),o=el(i);o.correlationId=s,rl(r.response.header,s),r.response.status(o.status).json(o)}},debug:t}}function nl(e){return async(t,a)=>{try{let r=await Zu(t,a,{parseBody:!0}),i=[al(),...e.middleware],s=nr(i);await Fu(r,async()=>{await s(r,async()=>{if(!r.response.sent&&(await e.router.handleRequest(r),!r.response.sent))throw new er(`Route not found: ${r.request.method} ${r.request.path}`)})})}catch(r){console.error("Error creating context:",r),a.writeHead(500,{"Content-Type":"application/json"}),a.end(JSON.stringify({error:"Internal Server Error",message:"Failed to process request"}))}}}async function zp(e){if(!e.enabled)return{};let{keyFile:t,certFile:a}=e,r=process.env.NODE_ENV==="development",n=!t||!a;if(n&&r)return await ku();if(n)throw new Error("HTTP/2 requires SSL certificates. Provide keyFile and certFile in http2 options. In development, set NODE_ENV=development to generate them automatically.");return{keyFile:t,certFile:a}}function Gp(e,t){if(!e)return il.createServer();let a={allowHTTP1:!0};try{t.keyFile&&(a.key=Ui.readFileSync(t.keyFile)),t.certFile&&(a.cert=Ui.readFileSync(t.certFile))}catch(r){throw new Error(`Failed to read certificate files: ${r instanceof Error?r.message:String(r)}`)}return sl.createSecureServer(a)}function Qp(e,t,a,r){return new Promise((n,i)=>{e.listen(t,a,()=>{let o=`${r?"https":"http"}://${a}:${t}`;console.log(`
|
|
1751
37
|
\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}
|
|
1752
38
|
|
|
1753
39
|
\u26A1 BlaizeJS DEVELOPMENT SERVER HOT AND READY \u26A1
|
|
1754
40
|
|
|
1755
|
-
\u{1F680} Server: ${
|
|
41
|
+
\u{1F680} Server: ${o}
|
|
1756
42
|
\u{1F525} Hot Reload: Enabled
|
|
1757
43
|
\u{1F6E0}\uFE0F Mode: Development
|
|
1758
44
|
|
|
1759
45
|
Time to build something amazing! \u{1F680}
|
|
1760
46
|
|
|
1761
47
|
\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}
|
|
1762
|
-
`);
|
|
1763
|
-
|
|
1764
|
-
|
|
1765
|
-
|
|
1766
|
-
|
|
1767
|
-
|
|
1768
|
-
|
|
1769
|
-
|
|
1770
|
-
|
|
1771
|
-
async function initializePlugins(serverInstance) {
|
|
1772
|
-
for (const plugin of serverInstance.plugins) {
|
|
1773
|
-
if (typeof plugin.initialize === "function") {
|
|
1774
|
-
await plugin.initialize(serverInstance);
|
|
1775
|
-
}
|
|
1776
|
-
}
|
|
1777
|
-
}
|
|
1778
|
-
async function startServer(serverInstance, serverOptions) {
|
|
1779
|
-
if (serverInstance.server) {
|
|
1780
|
-
return;
|
|
1781
|
-
}
|
|
1782
|
-
try {
|
|
1783
|
-
const port = serverOptions.port;
|
|
1784
|
-
const host = serverOptions.host;
|
|
1785
|
-
await initializePlugins(serverInstance);
|
|
1786
|
-
const http2Options = serverOptions.http2 || { enabled: true };
|
|
1787
|
-
const isHttp2 = !!http2Options.enabled;
|
|
1788
|
-
const certOptions = await prepareCertificates(http2Options);
|
|
1789
|
-
if (serverOptions.http2 && certOptions.keyFile && certOptions.certFile) {
|
|
1790
|
-
serverOptions.http2.keyFile = certOptions.keyFile;
|
|
1791
|
-
serverOptions.http2.certFile = certOptions.certFile;
|
|
1792
|
-
}
|
|
1793
|
-
const server = createServerInstance(isHttp2, certOptions);
|
|
1794
|
-
serverInstance.server = server;
|
|
1795
|
-
serverInstance.port = port;
|
|
1796
|
-
serverInstance.host = host;
|
|
1797
|
-
const requestHandler = createRequestHandler(serverInstance);
|
|
1798
|
-
server.on("request", requestHandler);
|
|
1799
|
-
await listenOnPort(server, port, host, isHttp2);
|
|
1800
|
-
} catch (error) {
|
|
1801
|
-
console.error("Failed to start server:", error);
|
|
1802
|
-
throw error;
|
|
1803
|
-
}
|
|
1804
|
-
}
|
|
1805
|
-
|
|
1806
|
-
// src/server/stop.ts
|
|
1807
|
-
var isShuttingDown = false;
|
|
1808
|
-
async function stopServer(serverInstance, options = {}) {
|
|
1809
|
-
const server = serverInstance.server;
|
|
1810
|
-
const events = serverInstance.events;
|
|
1811
|
-
if (isShuttingDown) {
|
|
1812
|
-
console.log("\u26A0\uFE0F Shutdown already in progress, ignoring duplicate shutdown request");
|
|
1813
|
-
return;
|
|
1814
|
-
}
|
|
1815
|
-
if (!server) {
|
|
1816
|
-
return;
|
|
1817
|
-
}
|
|
1818
|
-
isShuttingDown = true;
|
|
1819
|
-
const timeout = options.timeout || 5e3;
|
|
1820
|
-
try {
|
|
1821
|
-
if (options.onStopping) {
|
|
1822
|
-
await options.onStopping();
|
|
1823
|
-
}
|
|
1824
|
-
events.emit("stopping");
|
|
1825
|
-
if (serverInstance.router && typeof serverInstance.router.close === "function") {
|
|
1826
|
-
console.log("\u{1F50C} Closing router watchers...");
|
|
1827
|
-
try {
|
|
1828
|
-
await Promise.race([
|
|
1829
|
-
serverInstance.router.close(),
|
|
1830
|
-
new Promise(
|
|
1831
|
-
(_, reject) => setTimeout(() => reject(new Error("Router close timeout")), 2e3)
|
|
1832
|
-
)
|
|
1833
|
-
]);
|
|
1834
|
-
console.log("\u2705 Router watchers closed");
|
|
1835
|
-
} catch (error) {
|
|
1836
|
-
console.error("\u274C Error closing router watchers:", error);
|
|
1837
|
-
}
|
|
1838
|
-
}
|
|
1839
|
-
try {
|
|
1840
|
-
await Promise.race([
|
|
1841
|
-
serverInstance.pluginManager.onServerStop(serverInstance, server),
|
|
1842
|
-
new Promise(
|
|
1843
|
-
(_, reject) => setTimeout(() => reject(new Error("Plugin stop timeout")), 2e3)
|
|
1844
|
-
)
|
|
1845
|
-
]);
|
|
1846
|
-
} catch (error) {
|
|
1847
|
-
console.error("\u274C Plugin stop timeout:", error);
|
|
1848
|
-
}
|
|
1849
|
-
const closePromise = new Promise((resolve3, reject) => {
|
|
1850
|
-
server.close((err) => {
|
|
1851
|
-
if (err) return reject(err);
|
|
1852
|
-
resolve3();
|
|
1853
|
-
});
|
|
1854
|
-
});
|
|
1855
|
-
const timeoutPromise = new Promise((_, reject) => {
|
|
1856
|
-
setTimeout(() => {
|
|
1857
|
-
reject(new Error("Server shutdown timeout"));
|
|
1858
|
-
}, timeout);
|
|
1859
|
-
});
|
|
1860
|
-
await Promise.race([closePromise, timeoutPromise]);
|
|
1861
|
-
try {
|
|
1862
|
-
await Promise.race([
|
|
1863
|
-
serverInstance.pluginManager.terminatePlugins(serverInstance),
|
|
1864
|
-
new Promise(
|
|
1865
|
-
(_, reject) => setTimeout(() => reject(new Error("Plugin terminate timeout")), 1e3)
|
|
1866
|
-
)
|
|
1867
|
-
]);
|
|
1868
|
-
} catch (error) {
|
|
1869
|
-
console.error("\u274C Plugin terminate timeout:", error);
|
|
1870
|
-
}
|
|
1871
|
-
if (options.onStopped) {
|
|
1872
|
-
await options.onStopped();
|
|
1873
|
-
}
|
|
1874
|
-
events.emit("stopped");
|
|
1875
|
-
serverInstance.server = null;
|
|
1876
|
-
console.log("\u2705 Graceful shutdown completed");
|
|
1877
|
-
isShuttingDown = false;
|
|
1878
|
-
} catch (error) {
|
|
1879
|
-
isShuttingDown = false;
|
|
1880
|
-
console.error("\u26A0\uFE0F Shutdown error (forcing exit):", error);
|
|
1881
|
-
if (server && typeof server.close === "function") {
|
|
1882
|
-
server.close();
|
|
1883
|
-
}
|
|
1884
|
-
if (process.env.NODE_ENV === "development") {
|
|
1885
|
-
console.log("\u{1F504} Forcing exit for development restart...");
|
|
1886
|
-
process.exit(0);
|
|
1887
|
-
}
|
|
1888
|
-
events.emit("error", error);
|
|
1889
|
-
throw error;
|
|
1890
|
-
}
|
|
1891
|
-
}
|
|
1892
|
-
function registerSignalHandlers(stopFn) {
|
|
1893
|
-
const isDevelopment = process.env.NODE_ENV === "development";
|
|
1894
|
-
if (isDevelopment) {
|
|
1895
|
-
const sigintHandler = () => {
|
|
1896
|
-
console.log("\u{1F4E4} SIGINT received, forcing exit for development restart...");
|
|
1897
|
-
process.exit(0);
|
|
1898
|
-
};
|
|
1899
|
-
const sigtermHandler = () => {
|
|
1900
|
-
console.log("\u{1F4E4} SIGTERM received, forcing exit for development restart...");
|
|
1901
|
-
process.exit(0);
|
|
1902
|
-
};
|
|
1903
|
-
process.on("SIGINT", sigintHandler);
|
|
1904
|
-
process.on("SIGTERM", sigtermHandler);
|
|
1905
|
-
return {
|
|
1906
|
-
unregister: () => {
|
|
1907
|
-
process.removeListener("SIGINT", sigintHandler);
|
|
1908
|
-
process.removeListener("SIGTERM", sigtermHandler);
|
|
1909
|
-
}
|
|
1910
|
-
};
|
|
1911
|
-
} else {
|
|
1912
|
-
const sigintHandler = () => {
|
|
1913
|
-
console.log("\u{1F4E4} SIGINT received, starting graceful shutdown...");
|
|
1914
|
-
stopFn().catch(console.error);
|
|
1915
|
-
};
|
|
1916
|
-
const sigtermHandler = () => {
|
|
1917
|
-
console.log("\u{1F4E4} SIGTERM received, starting graceful shutdown...");
|
|
1918
|
-
stopFn().catch(console.error);
|
|
1919
|
-
};
|
|
1920
|
-
process.on("SIGINT", sigintHandler);
|
|
1921
|
-
process.on("SIGTERM", sigtermHandler);
|
|
1922
|
-
return {
|
|
1923
|
-
unregister: () => {
|
|
1924
|
-
process.removeListener("SIGINT", sigintHandler);
|
|
1925
|
-
process.removeListener("SIGTERM", sigtermHandler);
|
|
1926
|
-
}
|
|
1927
|
-
};
|
|
1928
|
-
}
|
|
1929
|
-
}
|
|
1930
|
-
|
|
1931
|
-
// src/server/validation.ts
|
|
1932
|
-
var import_zod = require("zod");
|
|
1933
|
-
var middlewareSchema = import_zod.z.custom(
|
|
1934
|
-
(data) => data !== null && typeof data === "object" && "execute" in data && typeof data.execute === "function",
|
|
1935
|
-
{
|
|
1936
|
-
message: "Expected middleware to have an execute function"
|
|
1937
|
-
}
|
|
1938
|
-
);
|
|
1939
|
-
var pluginSchema = import_zod.z.custom(
|
|
1940
|
-
(data) => data !== null && typeof data === "object" && "register" in data && typeof data.register === "function",
|
|
1941
|
-
{
|
|
1942
|
-
message: "Expected a valid plugin object with a register method"
|
|
1943
|
-
}
|
|
1944
|
-
);
|
|
1945
|
-
var http2Schema = import_zod.z.object({
|
|
1946
|
-
enabled: import_zod.z.boolean().optional().default(true),
|
|
1947
|
-
keyFile: import_zod.z.string().optional(),
|
|
1948
|
-
certFile: import_zod.z.string().optional()
|
|
1949
|
-
}).refine(
|
|
1950
|
-
(data) => {
|
|
1951
|
-
if (data.enabled && process.env.NODE_ENV === "production") {
|
|
1952
|
-
return data.keyFile && data.certFile;
|
|
1953
|
-
}
|
|
1954
|
-
return true;
|
|
1955
|
-
},
|
|
1956
|
-
{
|
|
1957
|
-
message: "When HTTP/2 is enabled (outside of development mode), both keyFile and certFile must be provided"
|
|
1958
|
-
}
|
|
1959
|
-
);
|
|
1960
|
-
var serverOptionsSchema = import_zod.z.object({
|
|
1961
|
-
port: import_zod.z.number().int().positive().optional().default(3e3),
|
|
1962
|
-
host: import_zod.z.string().optional().default("localhost"),
|
|
1963
|
-
routesDir: import_zod.z.string().optional().default("./routes"),
|
|
1964
|
-
http2: http2Schema.optional().default({
|
|
1965
|
-
enabled: true
|
|
1966
|
-
}),
|
|
1967
|
-
middleware: import_zod.z.array(middlewareSchema).optional().default([]),
|
|
1968
|
-
plugins: import_zod.z.array(pluginSchema).optional().default([])
|
|
1969
|
-
});
|
|
1970
|
-
function validateServerOptions(options) {
|
|
1971
|
-
try {
|
|
1972
|
-
return serverOptionsSchema.parse(options);
|
|
1973
|
-
} catch (error) {
|
|
1974
|
-
if (error instanceof import_zod.z.ZodError) {
|
|
1975
|
-
const formattedError = error.format();
|
|
1976
|
-
throw new Error(`Invalid server options: ${JSON.stringify(formattedError, null, 2)}`);
|
|
1977
|
-
}
|
|
1978
|
-
throw new Error(`Invalid server options: ${String(error)}`);
|
|
1979
|
-
}
|
|
1980
|
-
}
|
|
1981
|
-
|
|
1982
|
-
// src/plugins/lifecycle.ts
|
|
1983
|
-
function createPluginLifecycleManager(options = {}) {
|
|
1984
|
-
const { continueOnError = true, debug = false, onError } = options;
|
|
1985
|
-
function log(message, ...args) {
|
|
1986
|
-
if (debug) {
|
|
1987
|
-
console.log(`[PluginLifecycle] ${message}`, ...args);
|
|
1988
|
-
}
|
|
1989
|
-
}
|
|
1990
|
-
function handleError(plugin, phase, error) {
|
|
1991
|
-
const errorMessage = `Plugin ${plugin.name} failed during ${phase}: ${error.message}`;
|
|
1992
|
-
if (onError) {
|
|
1993
|
-
onError(plugin, phase, error);
|
|
1994
|
-
} else {
|
|
1995
|
-
console.error(errorMessage, error);
|
|
1996
|
-
}
|
|
1997
|
-
if (!continueOnError) {
|
|
1998
|
-
throw new Error(errorMessage);
|
|
1999
|
-
}
|
|
2000
|
-
}
|
|
2001
|
-
return {
|
|
2002
|
-
/**
|
|
2003
|
-
* Initialize all plugins
|
|
2004
|
-
*/
|
|
2005
|
-
async initializePlugins(server) {
|
|
2006
|
-
log("Initializing plugins...");
|
|
2007
|
-
for (const plugin of server.plugins) {
|
|
2008
|
-
if (plugin.initialize) {
|
|
2009
|
-
try {
|
|
2010
|
-
log(`Initializing plugin: ${plugin.name}`);
|
|
2011
|
-
await plugin.initialize(server);
|
|
2012
|
-
} catch (error) {
|
|
2013
|
-
handleError(plugin, "initialize", error);
|
|
2014
|
-
}
|
|
2015
|
-
}
|
|
2016
|
-
}
|
|
2017
|
-
log(`Initialized ${server.plugins.length} plugins`);
|
|
2018
|
-
},
|
|
2019
|
-
/**
|
|
2020
|
-
* Terminate all plugins in reverse order
|
|
2021
|
-
*/
|
|
2022
|
-
async terminatePlugins(server) {
|
|
2023
|
-
log("Terminating plugins...");
|
|
2024
|
-
const pluginsToTerminate = [...server.plugins].reverse();
|
|
2025
|
-
for (const plugin of pluginsToTerminate) {
|
|
2026
|
-
if (plugin.terminate) {
|
|
2027
|
-
try {
|
|
2028
|
-
log(`Terminating plugin: ${plugin.name}`);
|
|
2029
|
-
await plugin.terminate(server);
|
|
2030
|
-
} catch (error) {
|
|
2031
|
-
handleError(plugin, "terminate", error);
|
|
2032
|
-
}
|
|
2033
|
-
}
|
|
2034
|
-
}
|
|
2035
|
-
log(`Terminated ${pluginsToTerminate.length} plugins`);
|
|
2036
|
-
},
|
|
2037
|
-
/**
|
|
2038
|
-
* Notify plugins that the server has started
|
|
2039
|
-
*/
|
|
2040
|
-
async onServerStart(server, httpServer) {
|
|
2041
|
-
log("Notifying plugins of server start...");
|
|
2042
|
-
for (const plugin of server.plugins) {
|
|
2043
|
-
if (plugin.onServerStart) {
|
|
2044
|
-
try {
|
|
2045
|
-
log(`Notifying plugin of server start: ${plugin.name}`);
|
|
2046
|
-
await plugin.onServerStart(httpServer);
|
|
2047
|
-
} catch (error) {
|
|
2048
|
-
handleError(plugin, "onServerStart", error);
|
|
2049
|
-
}
|
|
2050
|
-
}
|
|
2051
|
-
}
|
|
2052
|
-
},
|
|
2053
|
-
/**
|
|
2054
|
-
* Notify plugins that the server is stopping
|
|
2055
|
-
*/
|
|
2056
|
-
async onServerStop(server, httpServer) {
|
|
2057
|
-
log("Notifying plugins of server stop...");
|
|
2058
|
-
const pluginsToNotify = [...server.plugins].reverse();
|
|
2059
|
-
for (const plugin of pluginsToNotify) {
|
|
2060
|
-
if (plugin.onServerStop) {
|
|
2061
|
-
try {
|
|
2062
|
-
log(`Notifying plugin of server stop: ${plugin.name}`);
|
|
2063
|
-
await plugin.onServerStop(httpServer);
|
|
2064
|
-
} catch (error) {
|
|
2065
|
-
handleError(plugin, "onServerStop", error);
|
|
2066
|
-
}
|
|
2067
|
-
}
|
|
2068
|
-
}
|
|
2069
|
-
}
|
|
2070
|
-
};
|
|
2071
|
-
}
|
|
2072
|
-
|
|
2073
|
-
// src/plugins/errors.ts
|
|
2074
|
-
var PluginValidationError = class extends Error {
|
|
2075
|
-
constructor(pluginName, message) {
|
|
2076
|
-
super(`Plugin validation error${pluginName ? ` for "${pluginName}"` : ""}: ${message}`);
|
|
2077
|
-
this.pluginName = pluginName;
|
|
2078
|
-
this.name = "PluginValidationError";
|
|
2079
|
-
}
|
|
2080
|
-
};
|
|
2081
|
-
|
|
2082
|
-
// src/plugins/validation.ts
|
|
2083
|
-
var RESERVED_NAMES = /* @__PURE__ */ new Set([
|
|
2084
|
-
"core",
|
|
2085
|
-
"server",
|
|
2086
|
-
"router",
|
|
2087
|
-
"middleware",
|
|
2088
|
-
"context",
|
|
2089
|
-
"blaize",
|
|
2090
|
-
"blaizejs"
|
|
2091
|
-
]);
|
|
2092
|
-
var VALID_NAME_PATTERN = /^[a-z]([a-z0-9-]*[a-z0-9])?$/;
|
|
2093
|
-
var VALID_VERSION_PATTERN = /^\d+\.\d+\.\d+(?:-[a-zA-Z0-9-.]+)?(?:\+[a-zA-Z0-9-.]+)?$/;
|
|
2094
|
-
function validatePlugin(plugin, options = {}) {
|
|
2095
|
-
const { requireVersion = true, validateNameFormat = true, checkReservedNames = true } = options;
|
|
2096
|
-
if (!plugin || typeof plugin !== "object") {
|
|
2097
|
-
throw new PluginValidationError("", "Plugin must be an object");
|
|
2098
|
-
}
|
|
2099
|
-
const p = plugin;
|
|
2100
|
-
if (!p.name || typeof p.name !== "string") {
|
|
2101
|
-
throw new PluginValidationError("", "Plugin must have a name (string)");
|
|
2102
|
-
}
|
|
2103
|
-
if (validateNameFormat && !VALID_NAME_PATTERN.test(p.name)) {
|
|
2104
|
-
throw new PluginValidationError(
|
|
2105
|
-
p.name,
|
|
2106
|
-
"Plugin name must be lowercase letters, numbers, and hyphens only"
|
|
2107
|
-
);
|
|
2108
|
-
}
|
|
2109
|
-
if (checkReservedNames && RESERVED_NAMES.has(p.name.toLowerCase())) {
|
|
2110
|
-
throw new PluginValidationError(p.name, `Plugin name "${p.name}" is reserved`);
|
|
2111
|
-
}
|
|
2112
|
-
if (requireVersion) {
|
|
2113
|
-
if (!p.version || typeof p.version !== "string") {
|
|
2114
|
-
throw new PluginValidationError(p.name, "Plugin must have a version (string)");
|
|
2115
|
-
}
|
|
2116
|
-
if (!VALID_VERSION_PATTERN.test(p.version)) {
|
|
2117
|
-
throw new PluginValidationError(
|
|
2118
|
-
p.name,
|
|
2119
|
-
'Plugin version must follow semantic versioning (e.g., "1.0.0")'
|
|
2120
|
-
);
|
|
2121
|
-
}
|
|
2122
|
-
}
|
|
2123
|
-
if (!p.register || typeof p.register !== "function") {
|
|
2124
|
-
throw new PluginValidationError(p.name, "Plugin must have a register method (function)");
|
|
2125
|
-
}
|
|
2126
|
-
const lifecycleMethods = ["initialize", "terminate", "onServerStart", "onServerStop"];
|
|
2127
|
-
for (const method of lifecycleMethods) {
|
|
2128
|
-
if (p[method] && typeof p[method] !== "function") {
|
|
2129
|
-
throw new PluginValidationError(p.name, `Plugin ${method} must be a function if provided`);
|
|
2130
|
-
}
|
|
2131
|
-
}
|
|
2132
|
-
}
|
|
2133
|
-
|
|
2134
|
-
// src/router/discovery/cache.ts
|
|
2135
|
-
var crypto = __toESM(require("crypto"), 1);
|
|
2136
|
-
var fs3 = __toESM(require("fs/promises"), 1);
|
|
2137
|
-
var import_node_module = require("module");
|
|
2138
|
-
var path3 = __toESM(require("path"), 1);
|
|
2139
|
-
|
|
2140
|
-
// src/router/discovery/loader.ts
|
|
2141
|
-
async function dynamicImport(filePath) {
|
|
2142
|
-
const cacheBuster = `?t=${Date.now()}`;
|
|
2143
|
-
const importPath = filePath + cacheBuster;
|
|
2144
|
-
try {
|
|
2145
|
-
const module2 = await import(importPath);
|
|
2146
|
-
console.log(`\u2705 Successfully imported module`);
|
|
2147
|
-
return module2;
|
|
2148
|
-
} catch (error) {
|
|
2149
|
-
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
2150
|
-
console.log(`\u26A0\uFE0F Error importing with cache buster, trying original path:`, errorMessage);
|
|
2151
|
-
return import(filePath);
|
|
2152
|
-
}
|
|
2153
|
-
}
|
|
2154
|
-
async function loadRouteModule(filePath, basePath) {
|
|
2155
|
-
try {
|
|
2156
|
-
const parsedRoute = parseRoutePath(filePath, basePath);
|
|
2157
|
-
const module2 = await dynamicImport(filePath);
|
|
2158
|
-
console.log("\u{1F4E6} Module exports:", Object.keys(module2));
|
|
2159
|
-
const routes = [];
|
|
2160
|
-
if (module2.default && typeof module2.default === "object") {
|
|
2161
|
-
const route = {
|
|
2162
|
-
...module2.default,
|
|
2163
|
-
path: parsedRoute.routePath
|
|
2164
|
-
};
|
|
2165
|
-
routes.push(route);
|
|
2166
|
-
}
|
|
2167
|
-
Object.entries(module2).forEach(([exportName, exportValue]) => {
|
|
2168
|
-
if (exportName === "default" || !exportValue || typeof exportValue !== "object") {
|
|
2169
|
-
return;
|
|
2170
|
-
}
|
|
2171
|
-
const potentialRoute = exportValue;
|
|
2172
|
-
if (isValidRoute(potentialRoute)) {
|
|
2173
|
-
const route = {
|
|
2174
|
-
...potentialRoute,
|
|
2175
|
-
// Use the route's own path if it has one, otherwise derive from file
|
|
2176
|
-
path: parsedRoute.routePath
|
|
2177
|
-
};
|
|
2178
|
-
routes.push(route);
|
|
2179
|
-
}
|
|
2180
|
-
});
|
|
2181
|
-
if (routes.length === 0) {
|
|
2182
|
-
console.warn(`Route file ${filePath} does not export any valid route definitions`);
|
|
2183
|
-
return [];
|
|
2184
|
-
}
|
|
2185
|
-
console.log(`\u2705 Successfully Loaded ${routes.length} route(s)`);
|
|
2186
|
-
return routes;
|
|
2187
|
-
} catch (error) {
|
|
2188
|
-
console.error(`Failed to load route module ${filePath}:`, error);
|
|
2189
|
-
return [];
|
|
2190
|
-
}
|
|
2191
|
-
}
|
|
2192
|
-
function isValidRoute(obj) {
|
|
2193
|
-
if (!obj || typeof obj !== "object") {
|
|
2194
|
-
return false;
|
|
2195
|
-
}
|
|
2196
|
-
const httpMethods = ["GET", "POST", "PUT", "DELETE", "PATCH", "HEAD", "OPTIONS"];
|
|
2197
|
-
const hasHttpMethod = httpMethods.some(
|
|
2198
|
-
(method) => obj[method] && typeof obj[method] === "object" && obj[method].handler
|
|
2199
|
-
);
|
|
2200
|
-
return hasHttpMethod;
|
|
2201
|
-
}
|
|
2202
|
-
|
|
2203
|
-
// src/router/discovery/cache.ts
|
|
2204
|
-
var import_meta = {};
|
|
2205
|
-
var fileRouteCache = /* @__PURE__ */ new Map();
|
|
2206
|
-
async function processChangedFile(filePath, routesDir, updateCache = true) {
|
|
2207
|
-
const stat3 = await fs3.stat(filePath);
|
|
2208
|
-
const lastModified = stat3.mtime.getTime();
|
|
2209
|
-
const cachedEntry = fileRouteCache.get(filePath);
|
|
2210
|
-
if (updateCache && cachedEntry && cachedEntry.timestamp === lastModified) {
|
|
2211
|
-
return cachedEntry.routes;
|
|
2212
|
-
}
|
|
2213
|
-
invalidateModuleCache(filePath);
|
|
2214
|
-
const routes = await loadRouteModule(filePath, routesDir);
|
|
2215
|
-
if (updateCache) {
|
|
2216
|
-
const hash = hashRoutes(routes);
|
|
2217
|
-
fileRouteCache.set(filePath, {
|
|
2218
|
-
routes,
|
|
2219
|
-
timestamp: lastModified,
|
|
2220
|
-
hash
|
|
2221
|
-
});
|
|
2222
|
-
}
|
|
2223
|
-
return routes;
|
|
2224
|
-
}
|
|
2225
|
-
function hasRouteContentChanged(filePath, newRoutes) {
|
|
2226
|
-
const cachedEntry = fileRouteCache.get(filePath);
|
|
2227
|
-
if (!cachedEntry) {
|
|
2228
|
-
return true;
|
|
2229
|
-
}
|
|
2230
|
-
const newHash = hashRoutes(newRoutes);
|
|
2231
|
-
return cachedEntry.hash !== newHash;
|
|
2232
|
-
}
|
|
2233
|
-
function clearFileCache(filePath) {
|
|
2234
|
-
if (filePath) {
|
|
2235
|
-
fileRouteCache.delete(filePath);
|
|
2236
|
-
} else {
|
|
2237
|
-
fileRouteCache.clear();
|
|
2238
|
-
}
|
|
2239
|
-
}
|
|
2240
|
-
function hashRoutes(routes) {
|
|
2241
|
-
const routeData = routes.map((route) => ({
|
|
2242
|
-
path: route.path,
|
|
2243
|
-
methods: Object.keys(route).filter((key) => key !== "path").sort().map((method) => {
|
|
2244
|
-
const methodDef = route[method];
|
|
2245
|
-
const handlerString = methodDef?.handler ? methodDef.handler.toString() : null;
|
|
2246
|
-
return {
|
|
2247
|
-
method,
|
|
2248
|
-
// Include handler function string for change detection
|
|
2249
|
-
handler: handlerString,
|
|
2250
|
-
// Include middleware if present
|
|
2251
|
-
middleware: methodDef?.middleware ? methodDef.middleware.length : 0,
|
|
2252
|
-
// Include schema structure (but not full serialization which can be unstable)
|
|
2253
|
-
hasSchema: !!methodDef?.schema,
|
|
2254
|
-
schemaKeys: methodDef?.schema ? Object.keys(methodDef.schema).sort() : []
|
|
2255
|
-
};
|
|
2256
|
-
})
|
|
2257
|
-
}));
|
|
2258
|
-
const dataString = JSON.stringify(routeData);
|
|
2259
|
-
const hash = crypto.createHash("md5").update(dataString).digest("hex");
|
|
2260
|
-
return hash;
|
|
2261
|
-
}
|
|
2262
|
-
function invalidateModuleCache(filePath) {
|
|
2263
|
-
try {
|
|
2264
|
-
const absolutePath = path3.resolve(filePath);
|
|
2265
|
-
if (typeof require !== "undefined") {
|
|
2266
|
-
delete require.cache[absolutePath];
|
|
2267
|
-
try {
|
|
2268
|
-
const resolvedPath = require.resolve(absolutePath);
|
|
2269
|
-
delete require.cache[resolvedPath];
|
|
2270
|
-
} catch (resolveError) {
|
|
2271
|
-
const errorMessage = resolveError instanceof Error ? resolveError.message : String(resolveError);
|
|
2272
|
-
console.log(`\u26A0\uFE0F Could not resolve path: ${errorMessage}`);
|
|
2273
|
-
}
|
|
2274
|
-
} else {
|
|
2275
|
-
try {
|
|
2276
|
-
const require2 = (0, import_node_module.createRequire)(import_meta.url);
|
|
2277
|
-
delete require2.cache[absolutePath];
|
|
2278
|
-
try {
|
|
2279
|
-
const resolvedPath = require2.resolve(absolutePath);
|
|
2280
|
-
delete require2.cache[resolvedPath];
|
|
2281
|
-
} catch {
|
|
2282
|
-
console.log(`\u26A0\uFE0F Could not resolve ESM path`);
|
|
2283
|
-
}
|
|
2284
|
-
} catch {
|
|
2285
|
-
console.log(`\u26A0\uFE0F createRequire not available in pure ESM`);
|
|
2286
|
-
}
|
|
2287
|
-
}
|
|
2288
|
-
} catch (error) {
|
|
2289
|
-
console.log(`\u26A0\uFE0F Error during module cache invalidation for ${filePath}:`, error);
|
|
2290
|
-
}
|
|
2291
|
-
}
|
|
2292
|
-
|
|
2293
|
-
// src/router/discovery/parallel.ts
|
|
2294
|
-
var os = __toESM(require("os"), 1);
|
|
2295
|
-
|
|
2296
|
-
// src/router/discovery/finder.ts
|
|
2297
|
-
var fs4 = __toESM(require("fs/promises"), 1);
|
|
2298
|
-
var path4 = __toESM(require("path"), 1);
|
|
2299
|
-
async function findRouteFiles(routesDir, options = {}) {
|
|
2300
|
-
const absoluteDir = path4.isAbsolute(routesDir) ? routesDir : path4.resolve(process.cwd(), routesDir);
|
|
2301
|
-
console.log("Creating router with routes directory:", absoluteDir);
|
|
2302
|
-
try {
|
|
2303
|
-
const stats = await fs4.stat(absoluteDir);
|
|
2304
|
-
if (!stats.isDirectory()) {
|
|
2305
|
-
throw new Error(`Route directory is not a directory: ${absoluteDir}`);
|
|
2306
|
-
}
|
|
2307
|
-
} catch (error) {
|
|
2308
|
-
if (error.code === "ENOENT") {
|
|
2309
|
-
throw new Error(`Route directory not found: ${absoluteDir}`);
|
|
2310
|
-
}
|
|
2311
|
-
throw error;
|
|
2312
|
-
}
|
|
2313
|
-
const routeFiles = [];
|
|
2314
|
-
const ignore = options.ignore || ["node_modules", ".git"];
|
|
2315
|
-
async function scanDirectory(dir) {
|
|
2316
|
-
const entries = await fs4.readdir(dir, { withFileTypes: true });
|
|
2317
|
-
for (const entry of entries) {
|
|
2318
|
-
const fullPath = path4.join(dir, entry.name);
|
|
2319
|
-
if (entry.isDirectory() && ignore.includes(entry.name)) {
|
|
2320
|
-
continue;
|
|
2321
|
-
}
|
|
2322
|
-
if (entry.isDirectory()) {
|
|
2323
|
-
await scanDirectory(fullPath);
|
|
2324
|
-
} else if (isRouteFile(entry.name)) {
|
|
2325
|
-
routeFiles.push(fullPath);
|
|
2326
|
-
}
|
|
2327
|
-
}
|
|
2328
|
-
}
|
|
2329
|
-
await scanDirectory(absoluteDir);
|
|
2330
|
-
return routeFiles;
|
|
2331
|
-
}
|
|
2332
|
-
function isRouteFile(filename) {
|
|
2333
|
-
return !filename.startsWith("_") && (filename.endsWith(".ts") || filename.endsWith(".js"));
|
|
2334
|
-
}
|
|
2335
|
-
|
|
2336
|
-
// src/router/discovery/parallel.ts
|
|
2337
|
-
async function processFilesInParallel(filePaths, processor, concurrency = Math.max(1, Math.floor(os.cpus().length / 2))) {
|
|
2338
|
-
const chunks = chunkArray(filePaths, concurrency);
|
|
2339
|
-
const results = [];
|
|
2340
|
-
for (const chunk of chunks) {
|
|
2341
|
-
const chunkResults = await Promise.allSettled(chunk.map((filePath) => processor(filePath)));
|
|
2342
|
-
const successfulResults = chunkResults.filter((result) => result.status === "fulfilled").map((result) => result.value);
|
|
2343
|
-
results.push(...successfulResults);
|
|
2344
|
-
}
|
|
2345
|
-
return results;
|
|
2346
|
-
}
|
|
2347
|
-
async function loadInitialRoutesParallel(routesDir) {
|
|
2348
|
-
const files = await findRouteFiles(routesDir);
|
|
2349
|
-
const routeArrays = await processFilesInParallel(
|
|
2350
|
-
files,
|
|
2351
|
-
(filePath) => processChangedFile(filePath, routesDir)
|
|
2352
|
-
);
|
|
2353
|
-
return routeArrays.flat();
|
|
2354
|
-
}
|
|
2355
|
-
function chunkArray(array, chunkSize) {
|
|
2356
|
-
const chunks = [];
|
|
2357
|
-
for (let i = 0; i < array.length; i += chunkSize) {
|
|
2358
|
-
chunks.push(array.slice(i, i + chunkSize));
|
|
2359
|
-
}
|
|
2360
|
-
return chunks;
|
|
2361
|
-
}
|
|
2362
|
-
|
|
2363
|
-
// src/router/discovery/profiler.ts
|
|
2364
|
-
var profilerState = {
|
|
2365
|
-
fileChanges: 0,
|
|
2366
|
-
totalReloadTime: 0,
|
|
2367
|
-
averageReloadTime: 0,
|
|
2368
|
-
slowReloads: []
|
|
2369
|
-
};
|
|
2370
|
-
function trackReloadPerformance(filePath, startTime) {
|
|
2371
|
-
const duration = Date.now() - startTime;
|
|
2372
|
-
profilerState.fileChanges++;
|
|
2373
|
-
profilerState.totalReloadTime += duration;
|
|
2374
|
-
profilerState.averageReloadTime = profilerState.totalReloadTime / profilerState.fileChanges;
|
|
2375
|
-
if (duration > 100) {
|
|
2376
|
-
profilerState.slowReloads.push({ file: filePath, time: duration });
|
|
2377
|
-
if (profilerState.slowReloads.length > 10) {
|
|
2378
|
-
profilerState.slowReloads.shift();
|
|
2379
|
-
}
|
|
2380
|
-
}
|
|
2381
|
-
if (process.env.NODE_ENV === "development") {
|
|
2382
|
-
const emoji = duration < 50 ? "\u26A1" : duration < 100 ? "\u{1F504}" : "\u{1F40C}";
|
|
2383
|
-
console.log(`${emoji} Route reload: ${filePath} (${duration}ms)`);
|
|
2384
|
-
}
|
|
2385
|
-
}
|
|
2386
|
-
function withPerformanceTracking(fn, filePath) {
|
|
2387
|
-
console.log(`Tracking performance for: ${filePath}`);
|
|
2388
|
-
return async (...args) => {
|
|
2389
|
-
const startTime = Date.now();
|
|
2390
|
-
try {
|
|
2391
|
-
const result = await fn(...args);
|
|
2392
|
-
trackReloadPerformance(filePath, startTime);
|
|
2393
|
-
return result;
|
|
2394
|
-
} catch (error) {
|
|
2395
|
-
trackReloadPerformance(filePath, startTime);
|
|
2396
|
-
throw error;
|
|
2397
|
-
}
|
|
2398
|
-
};
|
|
2399
|
-
}
|
|
2400
|
-
|
|
2401
|
-
// src/router/discovery/watchers.ts
|
|
2402
|
-
var path5 = __toESM(require("path"), 1);
|
|
2403
|
-
var import_chokidar = require("chokidar");
|
|
2404
|
-
function watchRoutes(routesDir, options = {}) {
|
|
2405
|
-
const debounceMs = options.debounceMs || 16;
|
|
2406
|
-
const debouncedCallbacks = /* @__PURE__ */ new Map();
|
|
2407
|
-
function createDebouncedCallback(fn, filePath) {
|
|
2408
|
-
return (...args) => {
|
|
2409
|
-
const existingTimeout = debouncedCallbacks.get(filePath);
|
|
2410
|
-
if (existingTimeout) {
|
|
2411
|
-
clearTimeout(existingTimeout);
|
|
2412
|
-
}
|
|
2413
|
-
const timeoutId = setTimeout(() => {
|
|
2414
|
-
fn(...args);
|
|
2415
|
-
debouncedCallbacks.delete(filePath);
|
|
2416
|
-
}, debounceMs);
|
|
2417
|
-
debouncedCallbacks.set(filePath, timeoutId);
|
|
2418
|
-
};
|
|
2419
|
-
}
|
|
2420
|
-
const routesByPath = /* @__PURE__ */ new Map();
|
|
2421
|
-
async function loadInitialRoutes() {
|
|
2422
|
-
try {
|
|
2423
|
-
const files = await findRouteFiles(routesDir, {
|
|
2424
|
-
ignore: options.ignore
|
|
2425
|
-
});
|
|
2426
|
-
for (const filePath of files) {
|
|
2427
|
-
await loadAndNotify(filePath);
|
|
2428
|
-
}
|
|
2429
|
-
} catch (error) {
|
|
2430
|
-
handleError(error);
|
|
2431
|
-
}
|
|
2432
|
-
}
|
|
2433
|
-
async function loadAndNotify(filePath) {
|
|
2434
|
-
try {
|
|
2435
|
-
const existingRoutes = routesByPath.get(filePath);
|
|
2436
|
-
const newRoutes = await processChangedFile(filePath, routesDir, false);
|
|
2437
|
-
if (!newRoutes || newRoutes.length === 0) {
|
|
2438
|
-
return;
|
|
2439
|
-
}
|
|
2440
|
-
if (existingRoutes && !hasRouteContentChanged(filePath, newRoutes)) {
|
|
2441
|
-
return;
|
|
2442
|
-
}
|
|
2443
|
-
await processChangedFile(filePath, routesDir, true);
|
|
2444
|
-
const normalizedPath = path5.normalize(filePath);
|
|
2445
|
-
if (existingRoutes) {
|
|
2446
|
-
routesByPath.set(filePath, newRoutes);
|
|
2447
|
-
if (options.onRouteChanged) {
|
|
2448
|
-
options.onRouteChanged(normalizedPath, newRoutes);
|
|
2449
|
-
}
|
|
2450
|
-
} else {
|
|
2451
|
-
routesByPath.set(filePath, newRoutes);
|
|
2452
|
-
if (options.onRouteAdded) {
|
|
2453
|
-
options.onRouteAdded(normalizedPath, newRoutes);
|
|
2454
|
-
}
|
|
2455
|
-
}
|
|
2456
|
-
} catch (error) {
|
|
2457
|
-
console.log(`\u26A0\uFE0F Error processing file ${filePath}:`, error);
|
|
2458
|
-
handleError(error);
|
|
2459
|
-
}
|
|
2460
|
-
}
|
|
2461
|
-
function handleRemoved(filePath) {
|
|
2462
|
-
const normalizedPath = path5.normalize(filePath);
|
|
2463
|
-
const routes = routesByPath.get(normalizedPath);
|
|
2464
|
-
if (routes && routes.length > 0 && options.onRouteRemoved) {
|
|
2465
|
-
options.onRouteRemoved(normalizedPath, routes);
|
|
2466
|
-
}
|
|
2467
|
-
routesByPath.delete(normalizedPath);
|
|
2468
|
-
}
|
|
2469
|
-
function handleError(error) {
|
|
2470
|
-
if (options.onError && error instanceof Error) {
|
|
2471
|
-
options.onError(error);
|
|
2472
|
-
} else {
|
|
2473
|
-
console.error("\u26A0\uFE0F Route watcher error:", error);
|
|
2474
|
-
}
|
|
2475
|
-
}
|
|
2476
|
-
const watcher = (0, import_chokidar.watch)(routesDir, {
|
|
2477
|
-
// Much faster response times
|
|
2478
|
-
awaitWriteFinish: {
|
|
2479
|
-
stabilityThreshold: 50,
|
|
2480
|
-
// Reduced from 300ms
|
|
2481
|
-
pollInterval: 10
|
|
2482
|
-
// Reduced from 100ms
|
|
2483
|
-
},
|
|
2484
|
-
// Performance optimizations
|
|
2485
|
-
usePolling: false,
|
|
2486
|
-
atomic: true,
|
|
2487
|
-
followSymlinks: false,
|
|
2488
|
-
depth: 10,
|
|
2489
|
-
// More aggressive ignoring
|
|
2490
|
-
ignored: [
|
|
2491
|
-
/(^|[/\\])\../,
|
|
2492
|
-
/node_modules/,
|
|
2493
|
-
/\.git/,
|
|
2494
|
-
/\.DS_Store/,
|
|
2495
|
-
/Thumbs\.db/,
|
|
2496
|
-
/\.(test|spec)\.(ts|js)$/,
|
|
2497
|
-
/\.d\.ts$/,
|
|
2498
|
-
/\.map$/,
|
|
2499
|
-
/~$/,
|
|
2500
|
-
...options.ignore || []
|
|
2501
|
-
]
|
|
2502
|
-
});
|
|
2503
|
-
watcher.on("add", (filePath) => {
|
|
2504
|
-
const debouncedLoad = createDebouncedCallback(loadAndNotify, filePath);
|
|
2505
|
-
debouncedLoad(filePath);
|
|
2506
|
-
}).on("change", (filePath) => {
|
|
2507
|
-
const debouncedLoad = createDebouncedCallback(loadAndNotify, filePath);
|
|
2508
|
-
debouncedLoad(filePath);
|
|
2509
|
-
}).on("unlink", (filePath) => {
|
|
2510
|
-
const debouncedRemove = createDebouncedCallback(handleRemoved, filePath);
|
|
2511
|
-
debouncedRemove(filePath);
|
|
2512
|
-
}).on("error", handleError);
|
|
2513
|
-
loadInitialRoutes().catch(handleError);
|
|
2514
|
-
return {
|
|
2515
|
-
close: () => {
|
|
2516
|
-
debouncedCallbacks.forEach((timeout) => clearTimeout(timeout));
|
|
2517
|
-
debouncedCallbacks.clear();
|
|
2518
|
-
return watcher.close();
|
|
2519
|
-
},
|
|
2520
|
-
getRoutes: () => {
|
|
2521
|
-
const allRoutes = [];
|
|
2522
|
-
for (const routes of routesByPath.values()) {
|
|
2523
|
-
allRoutes.push(...routes);
|
|
2524
|
-
}
|
|
2525
|
-
return allRoutes;
|
|
2526
|
-
},
|
|
2527
|
-
getRoutesByFile: () => new Map(routesByPath)
|
|
2528
|
-
};
|
|
2529
|
-
}
|
|
2530
|
-
|
|
2531
|
-
// src/router/validation/schema.ts
|
|
2532
|
-
var import_zod6 = require("zod");
|
|
2533
|
-
|
|
2534
|
-
// src/router/validation/body.ts
|
|
2535
|
-
var import_zod2 = require("zod");
|
|
2536
|
-
function validateBody(body, schema) {
|
|
2537
|
-
if (schema instanceof import_zod2.z.ZodObject) {
|
|
2538
|
-
return schema.strict().parse(body);
|
|
2539
|
-
}
|
|
2540
|
-
return schema.parse(body);
|
|
2541
|
-
}
|
|
2542
|
-
|
|
2543
|
-
// src/router/validation/params.ts
|
|
2544
|
-
var import_zod3 = require("zod");
|
|
2545
|
-
function validateParams(params, schema) {
|
|
2546
|
-
if (schema instanceof import_zod3.z.ZodObject) {
|
|
2547
|
-
return schema.strict().parse(params);
|
|
2548
|
-
}
|
|
2549
|
-
return schema.parse(params);
|
|
2550
|
-
}
|
|
2551
|
-
|
|
2552
|
-
// src/router/validation/query.ts
|
|
2553
|
-
var import_zod4 = require("zod");
|
|
2554
|
-
function validateQuery(query, schema) {
|
|
2555
|
-
if (schema instanceof import_zod4.z.ZodObject) {
|
|
2556
|
-
return schema.strict().parse(query);
|
|
2557
|
-
}
|
|
2558
|
-
return schema.parse(query);
|
|
2559
|
-
}
|
|
2560
|
-
|
|
2561
|
-
// src/router/validation/response.ts
|
|
2562
|
-
var import_zod5 = require("zod");
|
|
2563
|
-
function validateResponse(response, schema) {
|
|
2564
|
-
if (schema instanceof import_zod5.z.ZodObject) {
|
|
2565
|
-
return schema.strict().parse(response);
|
|
2566
|
-
}
|
|
2567
|
-
return schema.parse(response);
|
|
2568
|
-
}
|
|
2569
|
-
|
|
2570
|
-
// src/router/validation/schema.ts
|
|
2571
|
-
init_internal_server_error();
|
|
2572
|
-
init_validation_error();
|
|
2573
|
-
function createRequestValidator(schema, debug = false) {
|
|
2574
|
-
const middlewareFn = async (ctx, next) => {
|
|
2575
|
-
if (schema.params && ctx.request.params) {
|
|
2576
|
-
try {
|
|
2577
|
-
ctx.request.params = validateParams(ctx.request.params, schema.params);
|
|
2578
|
-
} catch (error) {
|
|
2579
|
-
const fieldErrors = extractZodFieldErrors(error);
|
|
2580
|
-
const errorCount = fieldErrors.reduce((sum, fe) => sum + fe.messages.length, 0);
|
|
2581
|
-
throw new ValidationError("Request validation failed", {
|
|
2582
|
-
fields: fieldErrors,
|
|
2583
|
-
errorCount,
|
|
2584
|
-
section: "params"
|
|
2585
|
-
});
|
|
2586
|
-
}
|
|
2587
|
-
}
|
|
2588
|
-
if (schema.query && ctx.request.query) {
|
|
2589
|
-
try {
|
|
2590
|
-
ctx.request.query = validateQuery(ctx.request.query, schema.query);
|
|
2591
|
-
} catch (error) {
|
|
2592
|
-
const fieldErrors = extractZodFieldErrors(error);
|
|
2593
|
-
const errorCount = fieldErrors.reduce((sum, fe) => sum + fe.messages.length, 0);
|
|
2594
|
-
throw new ValidationError("Request validation failed", {
|
|
2595
|
-
fields: fieldErrors,
|
|
2596
|
-
errorCount,
|
|
2597
|
-
section: "query"
|
|
2598
|
-
});
|
|
2599
|
-
}
|
|
2600
|
-
}
|
|
2601
|
-
if (schema.body) {
|
|
2602
|
-
try {
|
|
2603
|
-
ctx.request.body = validateBody(ctx.request.body, schema.body);
|
|
2604
|
-
} catch (error) {
|
|
2605
|
-
const fieldErrors = extractZodFieldErrors(error);
|
|
2606
|
-
const errorCount = fieldErrors.reduce((sum, fe) => sum + fe.messages.length, 0);
|
|
2607
|
-
throw new ValidationError("Request validation failed", {
|
|
2608
|
-
fields: fieldErrors,
|
|
2609
|
-
errorCount,
|
|
2610
|
-
section: "body"
|
|
2611
|
-
});
|
|
2612
|
-
}
|
|
2613
|
-
}
|
|
2614
|
-
await next();
|
|
2615
|
-
};
|
|
2616
|
-
return {
|
|
2617
|
-
name: "RequestValidator",
|
|
2618
|
-
execute: middlewareFn,
|
|
2619
|
-
debug
|
|
2620
|
-
};
|
|
2621
|
-
}
|
|
2622
|
-
function createResponseValidator(responseSchema, debug = false) {
|
|
2623
|
-
const middlewareFn = async (ctx, next) => {
|
|
2624
|
-
const originalJson = ctx.response.json;
|
|
2625
|
-
ctx.response.json = (body, status) => {
|
|
2626
|
-
try {
|
|
2627
|
-
const validatedBody = validateResponse(body, responseSchema);
|
|
2628
|
-
ctx.response.json = originalJson;
|
|
2629
|
-
return originalJson.call(ctx.response, validatedBody, status);
|
|
2630
|
-
} catch (error) {
|
|
2631
|
-
ctx.response.json = originalJson;
|
|
2632
|
-
throw new InternalServerError("Response validation failed", {
|
|
2633
|
-
responseSchema: responseSchema.description || "Unknown schema",
|
|
2634
|
-
validationError: extractZodFieldErrors(error),
|
|
2635
|
-
originalResponse: body
|
|
2636
|
-
});
|
|
2637
|
-
}
|
|
2638
|
-
};
|
|
2639
|
-
await next();
|
|
2640
|
-
};
|
|
2641
|
-
return {
|
|
2642
|
-
name: "ResponseValidator",
|
|
2643
|
-
execute: middlewareFn,
|
|
2644
|
-
debug
|
|
2645
|
-
};
|
|
2646
|
-
}
|
|
2647
|
-
function extractZodFieldErrors(error) {
|
|
2648
|
-
if (error instanceof import_zod6.z.ZodError) {
|
|
2649
|
-
const fieldErrorMap = /* @__PURE__ */ new Map();
|
|
2650
|
-
for (const issue of error.issues) {
|
|
2651
|
-
const fieldPath = issue.path.length > 0 ? issue.path.join(".") : "root";
|
|
2652
|
-
if (!fieldErrorMap.has(fieldPath)) {
|
|
2653
|
-
fieldErrorMap.set(fieldPath, []);
|
|
2654
|
-
}
|
|
2655
|
-
fieldErrorMap.get(fieldPath).push(issue.message);
|
|
2656
|
-
}
|
|
2657
|
-
return Array.from(fieldErrorMap.entries()).map(([field, messages]) => ({
|
|
2658
|
-
field,
|
|
2659
|
-
messages
|
|
2660
|
-
}));
|
|
2661
|
-
}
|
|
2662
|
-
if (error instanceof Error) {
|
|
2663
|
-
return [{ field: "unknown", messages: [error.message] }];
|
|
2664
|
-
}
|
|
2665
|
-
return [{ field: "unknown", messages: [String(error)] }];
|
|
2666
|
-
}
|
|
2667
|
-
|
|
2668
|
-
// src/router/handlers/executor.ts
|
|
2669
|
-
async function executeHandler(ctx, routeOptions, params) {
|
|
2670
|
-
const middleware = [...routeOptions.middleware || []];
|
|
2671
|
-
if (routeOptions.schema) {
|
|
2672
|
-
if (routeOptions.schema.params || routeOptions.schema.query || routeOptions.schema.body) {
|
|
2673
|
-
middleware.unshift(createRequestValidator(routeOptions.schema));
|
|
2674
|
-
}
|
|
2675
|
-
if (routeOptions.schema.response) {
|
|
2676
|
-
middleware.push(createResponseValidator(routeOptions.schema.response));
|
|
2677
|
-
}
|
|
2678
|
-
}
|
|
2679
|
-
const handler = compose([...middleware]);
|
|
2680
|
-
await handler(ctx, async () => {
|
|
2681
|
-
const result = await routeOptions.handler(ctx, params);
|
|
2682
|
-
if (!ctx.response.sent && result !== void 0) {
|
|
2683
|
-
ctx.response.json(result);
|
|
2684
|
-
}
|
|
2685
|
-
});
|
|
2686
|
-
}
|
|
2687
|
-
|
|
2688
|
-
// src/router/matching/params.ts
|
|
2689
|
-
function extractParams(path6, pattern, paramNames) {
|
|
2690
|
-
const match = pattern.exec(path6);
|
|
2691
|
-
if (!match) {
|
|
2692
|
-
return {};
|
|
2693
|
-
}
|
|
2694
|
-
const params = {};
|
|
2695
|
-
for (let i = 0; i < paramNames.length; i++) {
|
|
2696
|
-
params[paramNames[i]] = match[i + 1] || "";
|
|
2697
|
-
}
|
|
2698
|
-
return params;
|
|
2699
|
-
}
|
|
2700
|
-
function compilePathPattern(path6) {
|
|
2701
|
-
const paramNames = [];
|
|
2702
|
-
if (path6 === "/") {
|
|
2703
|
-
return {
|
|
2704
|
-
pattern: /^\/$/,
|
|
2705
|
-
paramNames: []
|
|
2706
|
-
};
|
|
2707
|
-
}
|
|
2708
|
-
let patternString = path6.replace(/([.+*?^$(){}|\\])/g, "\\$1");
|
|
2709
|
-
patternString = patternString.replace(/\/:([^/]+)/g, (_, paramName) => {
|
|
2710
|
-
paramNames.push(paramName);
|
|
2711
|
-
return "/([^/]+)";
|
|
2712
|
-
}).replace(/\/\[([^\]]+)\]/g, (_, paramName) => {
|
|
2713
|
-
paramNames.push(paramName);
|
|
2714
|
-
return "/([^/]+)";
|
|
2715
|
-
});
|
|
2716
|
-
patternString = `${patternString}(?:/)?`;
|
|
2717
|
-
const pattern = new RegExp(`^${patternString}$`);
|
|
2718
|
-
return {
|
|
2719
|
-
pattern,
|
|
2720
|
-
paramNames
|
|
2721
|
-
};
|
|
2722
|
-
}
|
|
2723
|
-
|
|
2724
|
-
// src/router/matching/matcher.ts
|
|
2725
|
-
function createMatcher() {
|
|
2726
|
-
const routes = [];
|
|
2727
|
-
return {
|
|
2728
|
-
/**
|
|
2729
|
-
* Add a route to the matcher
|
|
2730
|
-
*/
|
|
2731
|
-
add(path6, method, routeOptions) {
|
|
2732
|
-
const { pattern, paramNames } = compilePathPattern(path6);
|
|
2733
|
-
const newRoute = {
|
|
2734
|
-
path: path6,
|
|
2735
|
-
method,
|
|
2736
|
-
pattern,
|
|
2737
|
-
paramNames,
|
|
2738
|
-
routeOptions
|
|
2739
|
-
};
|
|
2740
|
-
const insertIndex = routes.findIndex((route) => paramNames.length < route.paramNames.length);
|
|
2741
|
-
if (insertIndex === -1) {
|
|
2742
|
-
routes.push(newRoute);
|
|
2743
|
-
} else {
|
|
2744
|
-
routes.splice(insertIndex, 0, newRoute);
|
|
2745
|
-
}
|
|
2746
|
-
},
|
|
2747
|
-
/**
|
|
2748
|
-
* Remove a route from the matcher by path
|
|
2749
|
-
*/
|
|
2750
|
-
remove(path6) {
|
|
2751
|
-
for (let i = routes.length - 1; i >= 0; i--) {
|
|
2752
|
-
if (routes[i].path === path6) {
|
|
2753
|
-
routes.splice(i, 1);
|
|
2754
|
-
}
|
|
2755
|
-
}
|
|
2756
|
-
},
|
|
2757
|
-
/**
|
|
2758
|
-
* Clear all routes from the matcher
|
|
2759
|
-
*/
|
|
2760
|
-
clear() {
|
|
2761
|
-
routes.length = 0;
|
|
2762
|
-
},
|
|
2763
|
-
/**
|
|
2764
|
-
* Match a URL path to a route
|
|
2765
|
-
*/
|
|
2766
|
-
match(path6, method) {
|
|
2767
|
-
const pathname = path6.split("?")[0];
|
|
2768
|
-
if (!pathname) return null;
|
|
2769
|
-
for (const route of routes) {
|
|
2770
|
-
if (route.method !== method) continue;
|
|
2771
|
-
const match = route.pattern.exec(pathname);
|
|
2772
|
-
if (match) {
|
|
2773
|
-
const params = extractParams(path6, route.pattern, route.paramNames);
|
|
2774
|
-
return {
|
|
2775
|
-
route: route.routeOptions,
|
|
2776
|
-
params
|
|
2777
|
-
};
|
|
2778
|
-
}
|
|
2779
|
-
}
|
|
2780
|
-
const matchingPath = routes.find(
|
|
2781
|
-
(route) => route.method !== method && route.pattern.test(path6)
|
|
2782
|
-
);
|
|
2783
|
-
if (matchingPath) {
|
|
2784
|
-
return {
|
|
2785
|
-
route: null,
|
|
2786
|
-
params: {},
|
|
2787
|
-
methodNotAllowed: true,
|
|
2788
|
-
allowedMethods: routes.filter((route) => route.pattern.test(path6)).map((route) => route.method)
|
|
2789
|
-
};
|
|
2790
|
-
}
|
|
2791
|
-
return null;
|
|
2792
|
-
},
|
|
2793
|
-
/**
|
|
2794
|
-
* Get all registered routes
|
|
2795
|
-
*/
|
|
2796
|
-
getRoutes() {
|
|
2797
|
-
return routes.map((route) => ({
|
|
2798
|
-
path: route.path,
|
|
2799
|
-
method: route.method
|
|
2800
|
-
}));
|
|
2801
|
-
},
|
|
2802
|
-
/**
|
|
2803
|
-
* Find routes matching a specific path
|
|
2804
|
-
*/
|
|
2805
|
-
findRoutes(path6) {
|
|
2806
|
-
return routes.filter((route) => route.pattern.test(path6)).map((route) => ({
|
|
2807
|
-
path: route.path,
|
|
2808
|
-
method: route.method,
|
|
2809
|
-
params: extractParams(path6, route.pattern, route.paramNames)
|
|
2810
|
-
}));
|
|
2811
|
-
}
|
|
2812
|
-
};
|
|
2813
|
-
}
|
|
2814
|
-
|
|
2815
|
-
// src/router/registry/fast-registry.ts
|
|
2816
|
-
function createRouteRegistry() {
|
|
2817
|
-
return {
|
|
2818
|
-
routesByPath: /* @__PURE__ */ new Map(),
|
|
2819
|
-
routesByFile: /* @__PURE__ */ new Map(),
|
|
2820
|
-
pathToFile: /* @__PURE__ */ new Map()
|
|
2821
|
-
};
|
|
2822
|
-
}
|
|
2823
|
-
function updateRoutesFromFile(registry, filePath, newRoutes) {
|
|
2824
|
-
console.log(`Updating routes from file: ${filePath}`);
|
|
2825
|
-
const oldPaths = registry.routesByFile.get(filePath) || /* @__PURE__ */ new Set();
|
|
2826
|
-
const newPaths = new Set(newRoutes.map((r) => r.path));
|
|
2827
|
-
const added = newRoutes.filter((r) => !oldPaths.has(r.path));
|
|
2828
|
-
const removed = Array.from(oldPaths).filter((p) => !newPaths.has(p));
|
|
2829
|
-
const potentiallyChanged = newRoutes.filter((r) => oldPaths.has(r.path));
|
|
2830
|
-
const changed = potentiallyChanged.filter((route) => {
|
|
2831
|
-
const existingRoute = registry.routesByPath.get(route.path);
|
|
2832
|
-
return !existingRoute || !routesEqual(existingRoute, route);
|
|
2833
|
-
});
|
|
2834
|
-
applyRouteUpdates(registry, filePath, { added, removed, changed });
|
|
2835
|
-
return { added, removed, changed };
|
|
2836
|
-
}
|
|
2837
|
-
function getAllRoutesFromRegistry(registry) {
|
|
2838
|
-
return Array.from(registry.routesByPath.values());
|
|
2839
|
-
}
|
|
2840
|
-
function applyRouteUpdates(registry, filePath, updates) {
|
|
2841
|
-
const { added, removed, changed } = updates;
|
|
2842
|
-
removed.forEach((path6) => {
|
|
2843
|
-
registry.routesByPath.delete(path6);
|
|
2844
|
-
registry.pathToFile.delete(path6);
|
|
2845
|
-
});
|
|
2846
|
-
[...added, ...changed].forEach((route) => {
|
|
2847
|
-
registry.routesByPath.set(route.path, route);
|
|
2848
|
-
registry.pathToFile.set(route.path, filePath);
|
|
2849
|
-
});
|
|
2850
|
-
const allPathsForFile = /* @__PURE__ */ new Set([
|
|
2851
|
-
...added.map((r) => r.path),
|
|
2852
|
-
...changed.map((r) => r.path),
|
|
2853
|
-
...Array.from(registry.routesByFile.get(filePath) || []).filter((p) => !removed.includes(p))
|
|
2854
|
-
]);
|
|
2855
|
-
if (allPathsForFile.size > 0) {
|
|
2856
|
-
registry.routesByFile.set(filePath, allPathsForFile);
|
|
2857
|
-
} else {
|
|
2858
|
-
registry.routesByFile.delete(filePath);
|
|
2859
|
-
}
|
|
2860
|
-
}
|
|
2861
|
-
function routesEqual(route1, route2) {
|
|
2862
|
-
if (route1.path !== route2.path) return false;
|
|
2863
|
-
const methods1 = Object.keys(route1).filter((k) => k !== "path").sort();
|
|
2864
|
-
const methods2 = Object.keys(route2).filter((k) => k !== "path").sort();
|
|
2865
|
-
if (methods1.length !== methods2.length) return false;
|
|
2866
|
-
return methods1.every((method) => {
|
|
2867
|
-
const handler1 = route1[method];
|
|
2868
|
-
const handler2 = route2[method];
|
|
2869
|
-
return typeof handler1 === typeof handler2;
|
|
2870
|
-
});
|
|
2871
|
-
}
|
|
2872
|
-
|
|
2873
|
-
// src/router/utils/matching-helpers.ts
|
|
2874
|
-
function addRouteToMatcher(route, matcher) {
|
|
2875
|
-
Object.entries(route).forEach(([method, methodOptions]) => {
|
|
2876
|
-
if (method === "path" || !methodOptions) return;
|
|
2877
|
-
matcher.add(route.path, method, methodOptions);
|
|
2878
|
-
});
|
|
2879
|
-
}
|
|
2880
|
-
function removeRouteFromMatcher(path6, matcher) {
|
|
2881
|
-
if ("remove" in matcher && typeof matcher.remove === "function") {
|
|
2882
|
-
matcher.remove(path6);
|
|
2883
|
-
} else {
|
|
2884
|
-
console.warn("Matcher does not support selective removal, consider adding remove() method");
|
|
2885
|
-
}
|
|
2886
|
-
}
|
|
2887
|
-
function updateRouteInMatcher(route, matcher) {
|
|
2888
|
-
removeRouteFromMatcher(route.path, matcher);
|
|
2889
|
-
addRouteToMatcher(route, matcher);
|
|
2890
|
-
}
|
|
2891
|
-
|
|
2892
|
-
// src/router/router.ts
|
|
2893
|
-
var DEFAULT_ROUTER_OPTIONS = {
|
|
2894
|
-
routesDir: "./routes",
|
|
2895
|
-
basePath: "/",
|
|
2896
|
-
watchMode: process.env.NODE_ENV === "development"
|
|
2897
|
-
};
|
|
2898
|
-
function createRouter(options) {
|
|
2899
|
-
const routerOptions = {
|
|
2900
|
-
...DEFAULT_ROUTER_OPTIONS,
|
|
2901
|
-
...options
|
|
2902
|
-
};
|
|
2903
|
-
if (options.basePath && !options.basePath.startsWith("/")) {
|
|
2904
|
-
console.warn("Base path does nothing");
|
|
2905
|
-
}
|
|
2906
|
-
const registry = createRouteRegistry();
|
|
2907
|
-
const matcher = createMatcher();
|
|
2908
|
-
let initialized = false;
|
|
2909
|
-
let initializationPromise = null;
|
|
2910
|
-
let _watchers = null;
|
|
2911
|
-
const routeDirectories = /* @__PURE__ */ new Set([routerOptions.routesDir]);
|
|
2912
|
-
function applyMatcherChanges(changes) {
|
|
2913
|
-
console.log("\n\u{1F527} APPLYING MATCHER CHANGES:");
|
|
2914
|
-
console.log(` Adding ${changes.added.length} routes`);
|
|
2915
|
-
console.log(` Removing ${changes.removed.length} routes`);
|
|
2916
|
-
console.log(` Updating ${changes.changed.length} routes`);
|
|
2917
|
-
changes.removed.forEach((routePath) => {
|
|
2918
|
-
console.log(` \u2796 Removing: ${routePath}`);
|
|
2919
|
-
removeRouteFromMatcher(routePath, matcher);
|
|
2920
|
-
});
|
|
2921
|
-
changes.added.forEach((route) => {
|
|
2922
|
-
const methods = Object.keys(route).filter((key) => key !== "path");
|
|
2923
|
-
console.log(` \u2795 Adding: ${route.path} [${methods.join(", ")}]`);
|
|
2924
|
-
addRouteToMatcher(route, matcher);
|
|
2925
|
-
});
|
|
2926
|
-
changes.changed.forEach((route) => {
|
|
2927
|
-
const methods = Object.keys(route).filter((key) => key !== "path");
|
|
2928
|
-
console.log(` \u{1F504} Updating: ${route.path} [${methods.join(", ")}]`);
|
|
2929
|
-
updateRouteInMatcher(route, matcher);
|
|
2930
|
-
});
|
|
2931
|
-
console.log("\u2705 Matcher changes applied\n");
|
|
2932
|
-
}
|
|
2933
|
-
function addRoutesWithSource(routes, source) {
|
|
2934
|
-
try {
|
|
2935
|
-
const changes = updateRoutesFromFile(registry, source, routes);
|
|
2936
|
-
applyMatcherChanges(changes);
|
|
2937
|
-
return changes;
|
|
2938
|
-
} catch (error) {
|
|
2939
|
-
console.error(`\u26A0\uFE0F Route conflicts from ${source}:`, error);
|
|
2940
|
-
throw error;
|
|
2941
|
-
}
|
|
2942
|
-
}
|
|
2943
|
-
async function loadRoutesFromDirectory(directory, source, prefix) {
|
|
2944
|
-
try {
|
|
2945
|
-
const discoveredRoutes = await loadInitialRoutesParallel(directory);
|
|
2946
|
-
const finalRoutes = discoveredRoutes.map(
|
|
2947
|
-
(route) => prefix ? { ...route, path: `${prefix}${route.path}` } : route
|
|
2948
|
-
);
|
|
2949
|
-
const changes = addRoutesWithSource(finalRoutes, source);
|
|
2950
|
-
console.log(
|
|
2951
|
-
`Loaded ${discoveredRoutes.length} routes from ${source}${prefix ? ` with prefix ${prefix}` : ""} (${changes.added.length} added, ${changes.changed.length} changed, ${changes.removed.length} removed)`
|
|
2952
|
-
);
|
|
2953
|
-
} catch (error) {
|
|
2954
|
-
console.error(`\u26A0\uFE0F Failed to load routes from ${source}:`, error);
|
|
2955
|
-
throw error;
|
|
2956
|
-
}
|
|
2957
|
-
}
|
|
2958
|
-
async function initialize() {
|
|
2959
|
-
if (initialized || initializationPromise) {
|
|
2960
|
-
return initializationPromise;
|
|
2961
|
-
}
|
|
2962
|
-
initializationPromise = (async () => {
|
|
2963
|
-
try {
|
|
2964
|
-
await Promise.all(
|
|
2965
|
-
Array.from(routeDirectories).map(
|
|
2966
|
-
(directory) => loadRoutesFromDirectory(directory, directory)
|
|
2967
|
-
)
|
|
2968
|
-
);
|
|
2969
|
-
if (routerOptions.watchMode) {
|
|
2970
|
-
setupOptimizedWatching();
|
|
2971
|
-
}
|
|
2972
|
-
initialized = true;
|
|
2973
|
-
} catch (error) {
|
|
2974
|
-
console.error("\u26A0\uFE0F Failed to initialize router:", error);
|
|
2975
|
-
throw error;
|
|
2976
|
-
}
|
|
2977
|
-
})();
|
|
2978
|
-
return initializationPromise;
|
|
2979
|
-
}
|
|
2980
|
-
function setupOptimizedWatching() {
|
|
2981
|
-
if (!_watchers) {
|
|
2982
|
-
_watchers = /* @__PURE__ */ new Map();
|
|
2983
|
-
}
|
|
2984
|
-
for (const directory of routeDirectories) {
|
|
2985
|
-
if (!_watchers.has(directory)) {
|
|
2986
|
-
const watcher = watchRoutes(directory, {
|
|
2987
|
-
debounceMs: 16,
|
|
2988
|
-
// ~60fps debouncing
|
|
2989
|
-
ignore: ["node_modules", ".git"],
|
|
2990
|
-
onRouteAdded: (filepath, addedRoutes) => {
|
|
2991
|
-
try {
|
|
2992
|
-
const changes = updateRoutesFromFile(registry, filepath, addedRoutes);
|
|
2993
|
-
applyMatcherChanges(changes);
|
|
2994
|
-
} catch (error) {
|
|
2995
|
-
console.error(`Error adding routes from ${directory}:`, error);
|
|
2996
|
-
}
|
|
2997
|
-
},
|
|
2998
|
-
onRouteChanged: withPerformanceTracking(
|
|
2999
|
-
async (filepath, changedRoutes) => {
|
|
3000
|
-
try {
|
|
3001
|
-
console.log(`Processing changes for ${filepath}`);
|
|
3002
|
-
const changes = updateRoutesFromFile(registry, filepath, changedRoutes);
|
|
3003
|
-
console.log(
|
|
3004
|
-
`Changes detected: ${changes.added.length} added, ${changes.changed.length} changed, ${changes.removed.length} removed`
|
|
3005
|
-
);
|
|
3006
|
-
applyMatcherChanges(changes);
|
|
3007
|
-
console.log(
|
|
3008
|
-
`Route changes applied: ${changes.added.length} added, ${changes.changed.length} changed, ${changes.removed.length} removed`
|
|
3009
|
-
);
|
|
3010
|
-
} catch (error) {
|
|
3011
|
-
console.error(`\u26A0\uFE0F Error updating routes from ${directory}:`, error);
|
|
3012
|
-
}
|
|
3013
|
-
},
|
|
3014
|
-
directory
|
|
3015
|
-
),
|
|
3016
|
-
onRouteRemoved: (filePath, removedRoutes) => {
|
|
3017
|
-
console.log(`File removed: ${filePath} with ${removedRoutes.length} routes`);
|
|
3018
|
-
try {
|
|
3019
|
-
removedRoutes.forEach((route) => {
|
|
3020
|
-
removeRouteFromMatcher(route.path, matcher);
|
|
3021
|
-
});
|
|
3022
|
-
clearFileCache(filePath);
|
|
3023
|
-
} catch (error) {
|
|
3024
|
-
console.error(`\u26A0\uFE0F Error removing routes from ${filePath}:`, error);
|
|
3025
|
-
}
|
|
3026
|
-
},
|
|
3027
|
-
onError: (error) => {
|
|
3028
|
-
console.error(`\u26A0\uFE0F Route watcher error for ${directory}:`, error);
|
|
3029
|
-
}
|
|
3030
|
-
});
|
|
3031
|
-
_watchers.set(directory, watcher);
|
|
3032
|
-
}
|
|
3033
|
-
}
|
|
3034
|
-
}
|
|
3035
|
-
function setupWatcherForNewDirectory(directory, prefix) {
|
|
3036
|
-
if (!_watchers) {
|
|
3037
|
-
_watchers = /* @__PURE__ */ new Map();
|
|
3038
|
-
}
|
|
3039
|
-
const watcher = watchRoutes(directory, {
|
|
3040
|
-
debounceMs: 16,
|
|
3041
|
-
ignore: ["node_modules", ".git"],
|
|
3042
|
-
onRouteAdded: (filePath, addedRoutes) => {
|
|
3043
|
-
try {
|
|
3044
|
-
const finalRoutes = addedRoutes.map(
|
|
3045
|
-
(route) => prefix ? { ...route, path: `${prefix}${route.path}` } : route
|
|
3046
|
-
);
|
|
3047
|
-
const changes = updateRoutesFromFile(registry, filePath, finalRoutes);
|
|
3048
|
-
applyMatcherChanges(changes);
|
|
3049
|
-
} catch (error) {
|
|
3050
|
-
console.error(`\u26A0\uFE0F Error adding routes from ${directory}:`, error);
|
|
3051
|
-
}
|
|
3052
|
-
},
|
|
3053
|
-
onRouteChanged: withPerformanceTracking(async (filePath, changedRoutes) => {
|
|
3054
|
-
try {
|
|
3055
|
-
const finalRoutes = changedRoutes.map(
|
|
3056
|
-
(route) => prefix ? { ...route, path: `${prefix}${route.path}` } : route
|
|
3057
|
-
);
|
|
3058
|
-
const changes = updateRoutesFromFile(registry, filePath, finalRoutes);
|
|
3059
|
-
applyMatcherChanges(changes);
|
|
3060
|
-
} catch (error) {
|
|
3061
|
-
console.error(`\u26A0\uFE0F Error updating routes from ${directory}:`, error);
|
|
3062
|
-
}
|
|
3063
|
-
}, directory),
|
|
3064
|
-
onRouteRemoved: (filePath, removedRoutes) => {
|
|
3065
|
-
try {
|
|
3066
|
-
removedRoutes.forEach((route) => {
|
|
3067
|
-
const finalPath = prefix ? `${prefix}${route.path}` : route.path;
|
|
3068
|
-
removeRouteFromMatcher(finalPath, matcher);
|
|
3069
|
-
});
|
|
3070
|
-
clearFileCache(filePath);
|
|
3071
|
-
} catch (error) {
|
|
3072
|
-
console.error(`Error removing routes from ${filePath}:`, error);
|
|
3073
|
-
}
|
|
3074
|
-
},
|
|
3075
|
-
onError: (error) => {
|
|
3076
|
-
console.error(`\u26A0\uFE0F Route watcher error for ${directory}:`, error);
|
|
3077
|
-
}
|
|
3078
|
-
});
|
|
3079
|
-
_watchers.set(directory, watcher);
|
|
3080
|
-
return watcher;
|
|
3081
|
-
}
|
|
3082
|
-
initialize().catch((error) => {
|
|
3083
|
-
console.error("\u26A0\uFE0F Failed to initialize router on creation:", error);
|
|
3084
|
-
});
|
|
3085
|
-
return {
|
|
3086
|
-
/**
|
|
3087
|
-
* Handle an incoming request
|
|
3088
|
-
*/
|
|
3089
|
-
async handleRequest(ctx) {
|
|
3090
|
-
if (!initialized) {
|
|
3091
|
-
console.log("\u{1F504} Router not initialized, initializing...");
|
|
3092
|
-
await initialize();
|
|
3093
|
-
}
|
|
3094
|
-
const { method, path: path6 } = ctx.request;
|
|
3095
|
-
console.log(`
|
|
3096
|
-
\u{1F4E5} Handling request: ${method} ${path6}`);
|
|
3097
|
-
const match = matcher.match(path6, method);
|
|
3098
|
-
if (!match) {
|
|
3099
|
-
console.log(`\u274C No match found for: ${method} ${path6}`);
|
|
3100
|
-
throw new NotFoundError("Not found");
|
|
3101
|
-
}
|
|
3102
|
-
console.log(`\u2705 Route matched: ${method} ${path6}`);
|
|
3103
|
-
console.log(` Params: ${JSON.stringify(match.params)}`);
|
|
3104
|
-
if (match.methodNotAllowed) {
|
|
3105
|
-
ctx.response.status(405).json({
|
|
3106
|
-
error: "\u274C Method Not Allowed",
|
|
3107
|
-
allowed: match.allowedMethods
|
|
3108
|
-
});
|
|
3109
|
-
if (match.allowedMethods && match.allowedMethods.length > 0) {
|
|
3110
|
-
ctx.response.header("Allow", match.allowedMethods.join(", "));
|
|
3111
|
-
}
|
|
3112
|
-
return;
|
|
3113
|
-
}
|
|
3114
|
-
ctx.request.params = match.params;
|
|
3115
|
-
await executeHandler(ctx, match.route, match.params);
|
|
3116
|
-
},
|
|
3117
|
-
/**
|
|
3118
|
-
* Get all registered routes (using optimized registry)
|
|
3119
|
-
*/
|
|
3120
|
-
getRoutes() {
|
|
3121
|
-
return getAllRoutesFromRegistry(registry);
|
|
3122
|
-
},
|
|
3123
|
-
/**
|
|
3124
|
-
* Add a route programmatically
|
|
3125
|
-
*/
|
|
3126
|
-
addRoute(route) {
|
|
3127
|
-
const changes = updateRoutesFromFile(registry, "programmatic", [route]);
|
|
3128
|
-
applyMatcherChanges(changes);
|
|
3129
|
-
},
|
|
3130
|
-
/**
|
|
3131
|
-
* Add multiple routes programmatically with batch processing
|
|
3132
|
-
*/
|
|
3133
|
-
addRoutes(routes) {
|
|
3134
|
-
const changes = updateRoutesFromFile(registry, "programmatic", routes);
|
|
3135
|
-
applyMatcherChanges(changes);
|
|
3136
|
-
return changes;
|
|
3137
|
-
},
|
|
3138
|
-
/**
|
|
3139
|
-
* Add a route directory (for plugins) with optimized loading
|
|
3140
|
-
*/
|
|
3141
|
-
async addRouteDirectory(directory, options2 = {}) {
|
|
3142
|
-
if (routeDirectories.has(directory)) {
|
|
3143
|
-
console.warn(`Route directory ${directory} already registered`);
|
|
3144
|
-
return;
|
|
3145
|
-
}
|
|
3146
|
-
routeDirectories.add(directory);
|
|
3147
|
-
if (initialized) {
|
|
3148
|
-
await loadRoutesFromDirectory(directory, directory, options2.prefix);
|
|
3149
|
-
if (routerOptions.watchMode) {
|
|
3150
|
-
setupWatcherForNewDirectory(directory, options2.prefix);
|
|
3151
|
-
}
|
|
3152
|
-
}
|
|
3153
|
-
},
|
|
3154
|
-
/**
|
|
3155
|
-
* Get route conflicts (using registry)
|
|
3156
|
-
*/
|
|
3157
|
-
getRouteConflicts() {
|
|
3158
|
-
const conflicts = [];
|
|
3159
|
-
return conflicts;
|
|
3160
|
-
},
|
|
3161
|
-
/**
|
|
3162
|
-
* Close watchers and cleanup (useful for testing)
|
|
3163
|
-
*/
|
|
3164
|
-
async close() {
|
|
3165
|
-
if (_watchers) {
|
|
3166
|
-
for (const watcher of _watchers.values()) {
|
|
3167
|
-
await watcher.close();
|
|
3168
|
-
}
|
|
3169
|
-
_watchers.clear();
|
|
3170
|
-
}
|
|
3171
|
-
}
|
|
3172
|
-
};
|
|
3173
|
-
}
|
|
3174
|
-
|
|
3175
|
-
// src/server/create.ts
|
|
3176
|
-
var DEFAULT_OPTIONS2 = {
|
|
3177
|
-
port: 3e3,
|
|
3178
|
-
host: "localhost",
|
|
3179
|
-
routesDir: "./routes",
|
|
3180
|
-
http2: {
|
|
3181
|
-
enabled: true
|
|
3182
|
-
},
|
|
3183
|
-
middleware: [],
|
|
3184
|
-
plugins: []
|
|
3185
|
-
};
|
|
3186
|
-
function createServerOptions(options = {}) {
|
|
3187
|
-
const baseOptions = { ...DEFAULT_OPTIONS2 };
|
|
3188
|
-
setRuntimeConfig({ routesDir: options.routesDir || baseOptions.routesDir });
|
|
3189
|
-
return {
|
|
3190
|
-
port: options.port ?? baseOptions.port,
|
|
3191
|
-
host: options.host ?? baseOptions.host,
|
|
3192
|
-
routesDir: options.routesDir ?? baseOptions.routesDir,
|
|
3193
|
-
http2: {
|
|
3194
|
-
enabled: options.http2?.enabled ?? baseOptions.http2?.enabled,
|
|
3195
|
-
keyFile: options.http2?.keyFile ?? baseOptions.http2?.keyFile,
|
|
3196
|
-
certFile: options.http2?.certFile ?? baseOptions.http2?.certFile
|
|
3197
|
-
},
|
|
3198
|
-
middleware: [...baseOptions.middleware || [], ...options.middleware || []],
|
|
3199
|
-
plugins: [...baseOptions.plugins || [], ...options.plugins || []]
|
|
3200
|
-
};
|
|
3201
|
-
}
|
|
3202
|
-
function createListenMethod(serverInstance, validatedOptions, initialMiddleware, initialPlugins) {
|
|
3203
|
-
return async () => {
|
|
3204
|
-
await initializeComponents(serverInstance, initialMiddleware, initialPlugins);
|
|
3205
|
-
await serverInstance.pluginManager.initializePlugins(serverInstance);
|
|
3206
|
-
await startServer(serverInstance, validatedOptions);
|
|
3207
|
-
await serverInstance.pluginManager.onServerStart(serverInstance, serverInstance.server);
|
|
3208
|
-
setupServerLifecycle(serverInstance);
|
|
3209
|
-
return serverInstance;
|
|
3210
|
-
};
|
|
3211
|
-
}
|
|
3212
|
-
async function initializeComponents(serverInstance, initialMiddleware, initialPlugins) {
|
|
3213
|
-
for (const mw of initialMiddleware) {
|
|
3214
|
-
serverInstance.use(mw);
|
|
3215
|
-
}
|
|
3216
|
-
for (const p of initialPlugins) {
|
|
3217
|
-
await serverInstance.register(p);
|
|
3218
|
-
}
|
|
3219
|
-
}
|
|
3220
|
-
function setupServerLifecycle(serverInstance) {
|
|
3221
|
-
const signalHandlers = registerSignalHandlers(() => serverInstance.close());
|
|
3222
|
-
serverInstance._signalHandlers = signalHandlers;
|
|
3223
|
-
serverInstance.events.emit("started");
|
|
3224
|
-
}
|
|
3225
|
-
function createCloseMethod(serverInstance) {
|
|
3226
|
-
return async (stopOptions) => {
|
|
3227
|
-
if (!serverInstance.server) {
|
|
3228
|
-
return;
|
|
3229
|
-
}
|
|
3230
|
-
const options = { ...stopOptions };
|
|
3231
|
-
if (serverInstance._signalHandlers) {
|
|
3232
|
-
serverInstance._signalHandlers.unregister();
|
|
3233
|
-
delete serverInstance._signalHandlers;
|
|
3234
|
-
}
|
|
3235
|
-
await stopServer(serverInstance, options);
|
|
3236
|
-
};
|
|
3237
|
-
}
|
|
3238
|
-
function createUseMethod(serverInstance) {
|
|
3239
|
-
return (middleware) => {
|
|
3240
|
-
const middlewareArray = Array.isArray(middleware) ? middleware : [middleware];
|
|
3241
|
-
serverInstance.middleware.push(...middlewareArray);
|
|
3242
|
-
return serverInstance;
|
|
3243
|
-
};
|
|
3244
|
-
}
|
|
3245
|
-
function createRegisterMethod(serverInstance) {
|
|
3246
|
-
return async (plugin) => {
|
|
3247
|
-
validatePlugin(plugin);
|
|
3248
|
-
serverInstance.plugins.push(plugin);
|
|
3249
|
-
await plugin.register(serverInstance);
|
|
3250
|
-
return serverInstance;
|
|
3251
|
-
};
|
|
3252
|
-
}
|
|
3253
|
-
function create3(options = {}) {
|
|
3254
|
-
const mergedOptions = createServerOptions(options);
|
|
3255
|
-
let validatedOptions;
|
|
3256
|
-
try {
|
|
3257
|
-
validatedOptions = validateServerOptions(mergedOptions);
|
|
3258
|
-
} catch (error) {
|
|
3259
|
-
if (error instanceof Error) {
|
|
3260
|
-
throw new Error(`Failed to create server: ${error.message}`);
|
|
3261
|
-
}
|
|
3262
|
-
throw new Error(`Failed to create server: ${String(error)}`);
|
|
3263
|
-
}
|
|
3264
|
-
const { port, host, middleware, plugins } = validatedOptions;
|
|
3265
|
-
const initialMiddleware = Array.isArray(middleware) ? [...middleware] : [];
|
|
3266
|
-
const initialPlugins = Array.isArray(plugins) ? [...plugins] : [];
|
|
3267
|
-
const contextStorage2 = new import_node_async_hooks3.AsyncLocalStorage();
|
|
3268
|
-
const router = createRouter({
|
|
3269
|
-
routesDir: validatedOptions.routesDir,
|
|
3270
|
-
watchMode: process.env.NODE_ENV === "development"
|
|
3271
|
-
});
|
|
3272
|
-
const pluginManager = createPluginLifecycleManager({
|
|
3273
|
-
debug: process.env.NODE_ENV === "development",
|
|
3274
|
-
continueOnError: true
|
|
3275
|
-
});
|
|
3276
|
-
const events = new import_node_events.default();
|
|
3277
|
-
const serverInstance = {
|
|
3278
|
-
server: null,
|
|
3279
|
-
port,
|
|
3280
|
-
host,
|
|
3281
|
-
context: contextStorage2,
|
|
3282
|
-
events,
|
|
3283
|
-
plugins: [],
|
|
3284
|
-
middleware: [],
|
|
3285
|
-
_signalHandlers: { unregister: () => {
|
|
3286
|
-
} },
|
|
3287
|
-
use: () => serverInstance,
|
|
3288
|
-
register: async () => serverInstance,
|
|
3289
|
-
listen: async () => serverInstance,
|
|
3290
|
-
close: async () => {
|
|
3291
|
-
},
|
|
3292
|
-
router,
|
|
3293
|
-
pluginManager
|
|
3294
|
-
};
|
|
3295
|
-
serverInstance.listen = createListenMethod(
|
|
3296
|
-
serverInstance,
|
|
3297
|
-
validatedOptions,
|
|
3298
|
-
initialMiddleware,
|
|
3299
|
-
initialPlugins
|
|
3300
|
-
);
|
|
3301
|
-
serverInstance.close = createCloseMethod(serverInstance);
|
|
3302
|
-
serverInstance.use = createUseMethod(serverInstance);
|
|
3303
|
-
serverInstance.register = createRegisterMethod(serverInstance);
|
|
3304
|
-
return serverInstance;
|
|
3305
|
-
}
|
|
3306
|
-
|
|
3307
|
-
// ../blaize-types/src/index.ts
|
|
3308
|
-
init_errors();
|
|
3309
|
-
|
|
3310
|
-
// src/index.ts
|
|
3311
|
-
init_validation_error();
|
|
3312
|
-
|
|
3313
|
-
// src/errors/unauthorized-error.ts
|
|
3314
|
-
init_errors();
|
|
3315
|
-
init_correlation();
|
|
3316
|
-
var UnauthorizedError = class extends BlaizeError {
|
|
3317
|
-
/**
|
|
3318
|
-
* Creates a new UnauthorizedError instance
|
|
3319
|
-
*
|
|
3320
|
-
* @param title - Human-readable error message
|
|
3321
|
-
* @param details - Optional authentication context
|
|
3322
|
-
* @param correlationId - Optional correlation ID (uses current context if not provided)
|
|
3323
|
-
*/
|
|
3324
|
-
constructor(title, details = void 0, correlationId = void 0) {
|
|
3325
|
-
super(
|
|
3326
|
-
"UNAUTHORIZED" /* UNAUTHORIZED */,
|
|
3327
|
-
title,
|
|
3328
|
-
401,
|
|
3329
|
-
// HTTP 401 Unauthorized
|
|
3330
|
-
correlationId ?? getCurrentCorrelationId(),
|
|
3331
|
-
details
|
|
3332
|
-
);
|
|
3333
|
-
}
|
|
3334
|
-
};
|
|
3335
|
-
|
|
3336
|
-
// src/errors/forbidden-error.ts
|
|
3337
|
-
init_errors();
|
|
3338
|
-
init_correlation();
|
|
3339
|
-
var ForbiddenError = class extends BlaizeError {
|
|
3340
|
-
/**
|
|
3341
|
-
* Creates a new ForbiddenError instance
|
|
3342
|
-
*
|
|
3343
|
-
* @param title - Human-readable error message
|
|
3344
|
-
* @param details - Optional permission context
|
|
3345
|
-
* @param correlationId - Optional correlation ID (uses current context if not provided)
|
|
3346
|
-
*/
|
|
3347
|
-
constructor(title, details = void 0, correlationId = void 0) {
|
|
3348
|
-
super(
|
|
3349
|
-
"FORBIDDEN" /* FORBIDDEN */,
|
|
3350
|
-
title,
|
|
3351
|
-
403,
|
|
3352
|
-
// HTTP 403 Forbidden
|
|
3353
|
-
correlationId ?? getCurrentCorrelationId(),
|
|
3354
|
-
details
|
|
3355
|
-
);
|
|
3356
|
-
}
|
|
3357
|
-
};
|
|
3358
|
-
|
|
3359
|
-
// src/errors/conflict-error.ts
|
|
3360
|
-
init_errors();
|
|
3361
|
-
init_correlation();
|
|
3362
|
-
var ConflictError = class extends BlaizeError {
|
|
3363
|
-
/**
|
|
3364
|
-
* Creates a new ConflictError instance
|
|
3365
|
-
*
|
|
3366
|
-
* @param title - Human-readable error message
|
|
3367
|
-
* @param details - Optional conflict context
|
|
3368
|
-
* @param correlationId - Optional correlation ID (uses current context if not provided)
|
|
3369
|
-
*/
|
|
3370
|
-
constructor(title, details = void 0, correlationId = void 0) {
|
|
3371
|
-
super(
|
|
3372
|
-
"CONFLICT" /* CONFLICT */,
|
|
3373
|
-
title,
|
|
3374
|
-
409,
|
|
3375
|
-
// HTTP 409 Conflict
|
|
3376
|
-
correlationId ?? getCurrentCorrelationId(),
|
|
3377
|
-
details
|
|
3378
|
-
);
|
|
3379
|
-
}
|
|
3380
|
-
};
|
|
3381
|
-
|
|
3382
|
-
// src/errors/rate-limit-error.ts
|
|
3383
|
-
init_errors();
|
|
3384
|
-
init_correlation();
|
|
3385
|
-
var RateLimitError = class extends BlaizeError {
|
|
3386
|
-
/**
|
|
3387
|
-
* Creates a new RateLimitError instance
|
|
3388
|
-
*
|
|
3389
|
-
* @param title - Human-readable error message
|
|
3390
|
-
* @param details - Optional rate limit context
|
|
3391
|
-
* @param correlationId - Optional correlation ID (uses current context if not provided)
|
|
3392
|
-
*/
|
|
3393
|
-
constructor(title, details = void 0, correlationId = void 0) {
|
|
3394
|
-
super(
|
|
3395
|
-
"RATE_LIMITED" /* RATE_LIMITED */,
|
|
3396
|
-
title,
|
|
3397
|
-
429,
|
|
3398
|
-
// HTTP 429 Too Many Requests
|
|
3399
|
-
correlationId ?? getCurrentCorrelationId(),
|
|
3400
|
-
details
|
|
3401
|
-
);
|
|
3402
|
-
}
|
|
3403
|
-
};
|
|
3404
|
-
|
|
3405
|
-
// src/index.ts
|
|
3406
|
-
init_internal_server_error();
|
|
3407
|
-
init_payload_too_large_error();
|
|
3408
|
-
|
|
3409
|
-
// src/errors/request-timeout-error.ts
|
|
3410
|
-
init_correlation();
|
|
3411
|
-
init_errors();
|
|
3412
|
-
var RequestTimeoutError = class extends BlaizeError {
|
|
3413
|
-
constructor(title, details, correlationId) {
|
|
3414
|
-
super(
|
|
3415
|
-
"UPLOAD_TIMEOUT" /* UPLOAD_TIMEOUT */,
|
|
3416
|
-
title,
|
|
3417
|
-
408,
|
|
3418
|
-
correlationId ?? getCurrentCorrelationId(),
|
|
3419
|
-
details
|
|
3420
|
-
);
|
|
3421
|
-
}
|
|
3422
|
-
};
|
|
3423
|
-
|
|
3424
|
-
// src/index.ts
|
|
3425
|
-
init_unsupported_media_type_error();
|
|
3426
|
-
|
|
3427
|
-
// src/errors/unprocessable-entity-error.ts
|
|
3428
|
-
init_correlation();
|
|
3429
|
-
init_errors();
|
|
3430
|
-
var UnprocessableEntityError = class extends BlaizeError {
|
|
3431
|
-
constructor(title, details, correlationId) {
|
|
3432
|
-
super(
|
|
3433
|
-
"UNPROCESSABLE_ENTITY" /* UNPROCESSABLE_ENTITY */,
|
|
3434
|
-
title,
|
|
3435
|
-
422,
|
|
3436
|
-
correlationId ?? getCurrentCorrelationId(),
|
|
3437
|
-
details
|
|
3438
|
-
);
|
|
3439
|
-
}
|
|
3440
|
-
};
|
|
3441
|
-
|
|
3442
|
-
// src/index.ts
|
|
3443
|
-
var VERSION = "0.1.0";
|
|
3444
|
-
var ServerAPI = { createServer: create3 };
|
|
3445
|
-
var RouterAPI = {
|
|
3446
|
-
createDeleteRoute,
|
|
3447
|
-
createGetRoute,
|
|
3448
|
-
createHeadRoute,
|
|
3449
|
-
createOptionsRoute,
|
|
3450
|
-
createPatchRoute,
|
|
3451
|
-
createPostRoute,
|
|
3452
|
-
createPutRoute
|
|
3453
|
-
};
|
|
3454
|
-
var MiddlewareAPI = { createMiddleware: create, compose };
|
|
3455
|
-
var PluginsAPI = { createPlugin: create2 };
|
|
3456
|
-
var Blaize = {
|
|
3457
|
-
// Core functions
|
|
3458
|
-
createServer: create3,
|
|
3459
|
-
createMiddleware: create,
|
|
3460
|
-
createPlugin: create2,
|
|
3461
|
-
// Namespaces (using the non-conflicting names)
|
|
3462
|
-
Server: ServerAPI,
|
|
3463
|
-
Router: RouterAPI,
|
|
3464
|
-
Middleware: MiddlewareAPI,
|
|
3465
|
-
Plugins: PluginsAPI,
|
|
3466
|
-
// Constants
|
|
3467
|
-
VERSION
|
|
3468
|
-
};
|
|
3469
|
-
var index_default = Blaize;
|
|
3470
|
-
// Annotate the CommonJS export names for ESM import in node:
|
|
3471
|
-
0 && (module.exports = {
|
|
3472
|
-
Blaize,
|
|
3473
|
-
BlaizeError,
|
|
3474
|
-
ConflictError,
|
|
3475
|
-
ErrorSeverity,
|
|
3476
|
-
ErrorType,
|
|
3477
|
-
ForbiddenError,
|
|
3478
|
-
InternalServerError,
|
|
3479
|
-
MiddlewareAPI,
|
|
3480
|
-
NotFoundError,
|
|
3481
|
-
PayloadTooLargeError,
|
|
3482
|
-
PluginsAPI,
|
|
3483
|
-
RateLimitError,
|
|
3484
|
-
RequestTimeoutError,
|
|
3485
|
-
RouterAPI,
|
|
3486
|
-
ServerAPI,
|
|
3487
|
-
UnauthorizedError,
|
|
3488
|
-
UnprocessableEntityError,
|
|
3489
|
-
UnsupportedMediaTypeError,
|
|
3490
|
-
VERSION,
|
|
3491
|
-
ValidationError,
|
|
3492
|
-
compose,
|
|
3493
|
-
createDeleteRoute,
|
|
3494
|
-
createGetRoute,
|
|
3495
|
-
createHeadRoute,
|
|
3496
|
-
createMiddleware,
|
|
3497
|
-
createOptionsRoute,
|
|
3498
|
-
createPatchRoute,
|
|
3499
|
-
createPlugin,
|
|
3500
|
-
createPostRoute,
|
|
3501
|
-
createPutRoute,
|
|
3502
|
-
createServer,
|
|
3503
|
-
isBodyParseError
|
|
3504
|
-
});
|
|
48
|
+
`),n()}),e.on("error",s=>{console.error("Server error:",s),i(s)})})}async function Wp(e){for(let t of e.plugins)typeof t.initialize=="function"&&await t.initialize(e)}async function ol(e,t){if(!e.server)try{let a=t.port,r=t.host;await Wp(e);let n=t.http2||{enabled:!0},i=!!n.enabled,s=await zp(n);t.http2&&s.keyFile&&s.certFile&&(t.http2.keyFile=s.keyFile,t.http2.certFile=s.certFile);let o=Gp(i,s);e.server=o,e.port=a,e.host=r;let u=nl(e);o.on("request",u),await Qp(o,a,r,i)}catch(a){throw console.error("Failed to start server:",a),a}}var en=!1;async function ul(e,t={}){let a=e.server,r=e.events;if(en){console.log("\u26A0\uFE0F Shutdown already in progress, ignoring duplicate shutdown request");return}if(!a)return;en=!0;let n=t.timeout||5e3;try{if(t.onStopping&&await t.onStopping(),r.emit("stopping"),e.router&&typeof e.router.close=="function"){console.log("\u{1F50C} Closing router watchers...");try{await Promise.race([e.router.close(),new Promise((o,u)=>setTimeout(()=>u(new Error("Router close timeout")),2e3))]),console.log("\u2705 Router watchers closed")}catch(o){console.error("\u274C Error closing router watchers:",o)}}try{await Promise.race([e.pluginManager.onServerStop(e,a),new Promise((o,u)=>setTimeout(()=>u(new Error("Plugin stop timeout")),2e3))])}catch(o){console.error("\u274C Plugin stop timeout:",o)}let i=new Promise((o,u)=>{a.close(l=>{if(l)return u(l);o()})}),s=new Promise((o,u)=>{setTimeout(()=>{u(new Error("Server shutdown timeout"))},n)});await Promise.race([i,s]);try{await Promise.race([e.pluginManager.terminatePlugins(e),new Promise((o,u)=>setTimeout(()=>u(new Error("Plugin terminate timeout")),1e3))])}catch(o){console.error("\u274C Plugin terminate timeout:",o)}t.onStopped&&await t.onStopped(),r.emit("stopped"),e.server=null,console.log("\u2705 Graceful shutdown completed"),en=!1}catch(i){throw en=!1,console.error("\u26A0\uFE0F Shutdown error (forcing exit):",i),a&&typeof a.close=="function"&&a.close(),process.env.NODE_ENV==="development"&&(console.log("\u{1F504} Forcing exit for development restart..."),process.exit(0)),r.emit("error",i),i}}function ll(e){if(process.env.NODE_ENV==="development"){let a=()=>{console.log("\u{1F4E4} SIGINT received, forcing exit for development restart..."),process.exit(0)},r=()=>{console.log("\u{1F4E4} SIGTERM received, forcing exit for development restart..."),process.exit(0)};return process.on("SIGINT",a),process.on("SIGTERM",r),{unregister:()=>{process.removeListener("SIGINT",a),process.removeListener("SIGTERM",r)}}}else{let a=()=>{console.log("\u{1F4E4} SIGINT received, starting graceful shutdown..."),e().catch(console.error)},r=()=>{console.log("\u{1F4E4} SIGTERM received, starting graceful shutdown..."),e().catch(console.error)};return process.on("SIGINT",a),process.on("SIGTERM",r),{unregister:()=>{process.removeListener("SIGINT",a),process.removeListener("SIGTERM",r)}}}}var rt=require("zod"),jp=rt.z.custom(e=>e!==null&&typeof e=="object"&&"execute"in e&&typeof e.execute=="function",{message:"Expected middleware to have an execute function"}),$p=rt.z.custom(e=>e!==null&&typeof e=="object"&&"register"in e&&typeof e.register=="function",{message:"Expected a valid plugin object with a register method"}),Yp=rt.z.object({enabled:rt.z.boolean().optional().default(!0),keyFile:rt.z.string().optional(),certFile:rt.z.string().optional()}).refine(e=>e.enabled&&process.env.NODE_ENV==="production"?e.keyFile&&e.certFile:!0,{message:"When HTTP/2 is enabled (outside of development mode), both keyFile and certFile must be provided"}),Xp=rt.z.object({port:rt.z.number().int().positive().optional().default(3e3),host:rt.z.string().optional().default("localhost"),routesDir:rt.z.string().optional().default("./routes"),http2:Yp.optional().default({enabled:!0}),middleware:rt.z.array(jp).optional().default([]),plugins:rt.z.array($p).optional().default([])});function fl(e){try{return Xp.parse(e)}catch(t){if(t instanceof rt.z.ZodError){let a=t.format();throw new Error(`Invalid server options: ${JSON.stringify(a,null,2)}`)}throw new Error(`Invalid server options: ${String(t)}`)}}function cl(e={}){let{continueOnError:t=!0,debug:a=!1,onError:r}=e;function n(s,...o){a&&console.log(`[PluginLifecycle] ${s}`,...o)}function i(s,o,u){let l=`Plugin ${s.name} failed during ${o}: ${u.message}`;if(r?r(s,o,u):console.error(l,u),!t)throw new Error(l)}return{async initializePlugins(s){n("Initializing plugins...");for(let o of s.plugins)if(o.initialize)try{n(`Initializing plugin: ${o.name}`),await o.initialize(s)}catch(u){i(o,"initialize",u)}n(`Initialized ${s.plugins.length} plugins`)},async terminatePlugins(s){n("Terminating plugins...");let o=[...s.plugins].reverse();for(let u of o)if(u.terminate)try{n(`Terminating plugin: ${u.name}`),await u.terminate(s)}catch(l){i(u,"terminate",l)}n(`Terminated ${o.length} plugins`)},async onServerStart(s,o){n("Notifying plugins of server start...");for(let u of s.plugins)if(u.onServerStart)try{n(`Notifying plugin of server start: ${u.name}`),await u.onServerStart(o)}catch(l){i(u,"onServerStart",l)}},async onServerStop(s,o){n("Notifying plugins of server stop...");let u=[...s.plugins].reverse();for(let l of u)if(l.onServerStop)try{n(`Notifying plugin of server stop: ${l.name}`),await l.onServerStop(o)}catch(f){i(l,"onServerStop",f)}}}}var Et=class extends Error{constructor(a,r){super(`Plugin validation error${a?` for "${a}"`:""}: ${r}`);this.pluginName=a;this.name="PluginValidationError"}};var Zp=new Set(["core","server","router","middleware","context","blaize","blaizejs"]),Jp=/^[a-z]([a-z0-9-]*[a-z0-9])?$/,eh=/^\d+\.\d+\.\d+(?:-[a-zA-Z0-9-.]+)?(?:\+[a-zA-Z0-9-.]+)?$/;function dl(e,t={}){let{requireVersion:a=!0,validateNameFormat:r=!0,checkReservedNames:n=!0}=t;if(!e||typeof e!="object")throw new Et("","Plugin must be an object");let i=e;if(!i.name||typeof i.name!="string")throw new Et("","Plugin must have a name (string)");if(r&&!Jp.test(i.name))throw new Et(i.name,"Plugin name must be lowercase letters, numbers, and hyphens only");if(n&&Zp.has(i.name.toLowerCase()))throw new Et(i.name,`Plugin name "${i.name}" is reserved`);if(a){if(!i.version||typeof i.version!="string")throw new Et(i.name,"Plugin must have a version (string)");if(!eh.test(i.version))throw new Et(i.name,'Plugin version must follow semantic versioning (e.g., "1.0.0")')}if(!i.register||typeof i.register!="function")throw new Et(i.name,"Plugin must have a register method (function)");let s=["initialize","terminate","onServerStart","onServerStop"];for(let o of s)if(i[o]&&typeof i[o]!="function")throw new Et(i.name,`Plugin ${o} must be a function if provided`)}var hl=Ae(require("crypto"),1),gl=Ae(require("fs/promises"),1),yl=require("module"),ml=Ae(require("path"),1);async function th(e){let t=`?t=${Date.now()}`,a=e+t;try{let r=await import(a);return console.log("\u2705 Successfully imported module"),r}catch(r){let n=r instanceof Error?r.message:String(r);return console.log("\u26A0\uFE0F Error importing with cache buster, trying original path:",n),import(e)}}async function pl(e,t){try{let a=ga(e,t),r=await th(e);console.log("\u{1F4E6} Module exports:",Object.keys(r));let n=[];if(r.default&&typeof r.default=="object"){let i={...r.default,path:a.routePath};n.push(i)}return Object.entries(r).forEach(([i,s])=>{if(i==="default"||!s||typeof s!="object")return;let o=s;if(rh(o)){let u={...o,path:a.routePath};n.push(u)}}),n.length===0?(console.warn(`Route file ${e} does not export any valid route definitions`),[]):(console.log(`\u2705 Successfully Loaded ${n.length} route(s)`),n)}catch(a){return console.error(`Failed to load route module ${e}:`,a),[]}}function rh(e){return!e||typeof e!="object"?!1:["GET","POST","PUT","DELETE","PATCH","HEAD","OPTIONS"].some(r=>e[r]&&typeof e[r]=="object"&&e[r].handler)}var nh={},sa=new Map;async function oa(e,t,a=!0){let n=(await gl.stat(e)).mtime.getTime(),i=sa.get(e);if(a&&i&&i.timestamp===n)return i.routes;ah(e);let s=await pl(e,t);if(a){let o=El(s);sa.set(e,{routes:s,timestamp:n,hash:o})}return s}function vl(e,t){let a=sa.get(e);if(!a)return!0;let r=El(t);return a.hash!==r}function Fi(e){e?sa.delete(e):sa.clear()}function El(e){let t=e.map(n=>({path:n.path,methods:Object.keys(n).filter(i=>i!=="path").sort().map(i=>{let s=n[i],o=s?.handler?s.handler.toString():null;return{method:i,handler:o,middleware:s?.middleware?s.middleware.length:0,hasSchema:!!s?.schema,schemaKeys:s?.schema?Object.keys(s.schema).sort():[]}})})),a=JSON.stringify(t);return hl.createHash("md5").update(a).digest("hex")}function ah(e){try{let t=ml.resolve(e);if(typeof require<"u"){delete require.cache[t];try{let a=require.resolve(t);delete require.cache[a]}catch(a){let r=a instanceof Error?a.message:String(a);console.log(`\u26A0\uFE0F Could not resolve path: ${r}`)}}else try{let a=(0,yl.createRequire)(nh.url);delete a.cache[t];try{let r=a.resolve(t);delete a.cache[r]}catch{console.log("\u26A0\uFE0F Could not resolve ESM path")}}catch{console.log("\u26A0\uFE0F createRequire not available in pure ESM")}}catch(t){console.log(`\u26A0\uFE0F Error during module cache invalidation for ${e}:`,t)}}var Cl=Ae(require("os"),1);var tn=Ae(require("fs/promises"),1),Ur=Ae(require("path"),1);async function rn(e,t={}){let a=Ur.isAbsolute(e)?e:Ur.resolve(process.cwd(),e);console.log("Creating router with routes directory:",a);try{if(!(await tn.stat(a)).isDirectory())throw new Error(`Route directory is not a directory: ${a}`)}catch(s){throw s.code==="ENOENT"?new Error(`Route directory not found: ${a}`):s}let r=[],n=t.ignore||["node_modules",".git"];async function i(s){let o=await tn.readdir(s,{withFileTypes:!0});for(let u of o){let l=Ur.join(s,u.name);u.isDirectory()&&n.includes(u.name)||(u.isDirectory()?await i(l):ih(u.name)&&r.push(l))}}return await i(a),r}function ih(e){return!e.startsWith("_")&&(e.endsWith(".ts")||e.endsWith(".js"))}async function sh(e,t,a=Math.max(1,Math.floor(Cl.cpus().length/2))){let r=oh(e,a),n=[];for(let i of r){let o=(await Promise.allSettled(i.map(u=>t(u)))).filter(u=>u.status==="fulfilled").map(u=>u.value);n.push(...o)}return n}async function xl(e){let t=await rn(e);return(await sh(t,r=>oa(r,e))).flat()}function oh(e,t){let a=[];for(let r=0;r<e.length;r+=t)a.push(e.slice(r,r+t));return a}var tr={fileChanges:0,totalReloadTime:0,averageReloadTime:0,slowReloads:[]};function Sl(e,t){let a=Date.now()-t;if(tr.fileChanges++,tr.totalReloadTime+=a,tr.averageReloadTime=tr.totalReloadTime/tr.fileChanges,a>100&&(tr.slowReloads.push({file:e,time:a}),tr.slowReloads.length>10&&tr.slowReloads.shift()),process.env.NODE_ENV==="development"){let r=a<50?"\u26A1":a<100?"\u{1F504}":"\u{1F40C}";console.log(`${r} Route reload: ${e} (${a}ms)`)}}function Oi(e,t){return console.log(`Tracking performance for: ${t}`),async(...a)=>{let r=Date.now();try{let n=await e(...a);return Sl(t,r),n}catch(n){throw Sl(t,r),n}}}var Yi=Ae(require("path"),1);var Vl=require("fs"),cn=require("fs/promises"),Ml=require("events"),Z=Ae(require("path"),1);var Kt=require("fs/promises"),wl=require("stream"),qt=require("path"),ot={FILE_TYPE:"files",DIR_TYPE:"directories",FILE_DIR_TYPE:"files_directories",EVERYTHING_TYPE:"all"},Vi={root:".",fileFilter:e=>!0,directoryFilter:e=>!0,type:ot.FILE_TYPE,lstat:!1,depth:2147483648,alwaysStat:!1,highWaterMark:4096};Object.freeze(Vi);var Al="READDIRP_RECURSIVE_ERROR",uh=new Set(["ENOENT","EPERM","EACCES","ELOOP",Al]),Tl=[ot.DIR_TYPE,ot.EVERYTHING_TYPE,ot.FILE_DIR_TYPE,ot.FILE_TYPE],lh=new Set([ot.DIR_TYPE,ot.EVERYTHING_TYPE,ot.FILE_DIR_TYPE]),fh=new Set([ot.EVERYTHING_TYPE,ot.FILE_DIR_TYPE,ot.FILE_TYPE]),ch=e=>uh.has(e.code),dh=process.platform==="win32",bl=e=>!0,Il=e=>{if(e===void 0)return bl;if(typeof e=="function")return e;if(typeof e=="string"){let t=e.trim();return a=>a.basename===t}if(Array.isArray(e)){let t=e.map(a=>a.trim());return a=>t.some(r=>a.basename===r)}return bl},Mi=class extends wl.Readable{constructor(t={}){super({objectMode:!0,autoDestroy:!0,highWaterMark:t.highWaterMark});let a={...Vi,...t},{root:r,type:n}=a;this._fileFilter=Il(a.fileFilter),this._directoryFilter=Il(a.directoryFilter);let i=a.lstat?Kt.lstat:Kt.stat;dh?this._stat=s=>i(s,{bigint:!0}):this._stat=i,this._maxDepth=a.depth??Vi.depth,this._wantsDir=n?lh.has(n):!1,this._wantsFile=n?fh.has(n):!1,this._wantsEverything=n===ot.EVERYTHING_TYPE,this._root=(0,qt.resolve)(r),this._isDirent=!a.alwaysStat,this._statsProp=this._isDirent?"dirent":"stats",this._rdOptions={encoding:"utf8",withFileTypes:this._isDirent},this.parents=[this._exploreDir(r,1)],this.reading=!1,this.parent=void 0}async _read(t){if(!this.reading){this.reading=!0;try{for(;!this.destroyed&&t>0;){let a=this.parent,r=a&&a.files;if(r&&r.length>0){let{path:n,depth:i}=a,s=r.splice(0,t).map(u=>this._formatEntry(u,n)),o=await Promise.all(s);for(let u of o){if(!u)continue;if(this.destroyed)return;let l=await this._getEntryType(u);l==="directory"&&this._directoryFilter(u)?(i<=this._maxDepth&&this.parents.push(this._exploreDir(u.fullPath,i+1)),this._wantsDir&&(this.push(u),t--)):(l==="file"||this._includeAsFile(u))&&this._fileFilter(u)&&this._wantsFile&&(this.push(u),t--)}}else{let n=this.parents.pop();if(!n){this.push(null);break}if(this.parent=await n,this.destroyed)return}}}catch(a){this.destroy(a)}finally{this.reading=!1}}}async _exploreDir(t,a){let r;try{r=await(0,Kt.readdir)(t,this._rdOptions)}catch(n){this._onError(n)}return{files:r,depth:a,path:t}}async _formatEntry(t,a){let r,n=this._isDirent?t.name:t;try{let i=(0,qt.resolve)((0,qt.join)(a,n));r={path:(0,qt.relative)(this._root,i),fullPath:i,basename:n},r[this._statsProp]=this._isDirent?t:await this._stat(i)}catch(i){this._onError(i);return}return r}_onError(t){ch(t)&&!this.destroyed?this.emit("warn",t):this.destroy(t)}async _getEntryType(t){if(!t&&this._statsProp in t)return"";let a=t[this._statsProp];if(a.isFile())return"file";if(a.isDirectory())return"directory";if(a&&a.isSymbolicLink()){let r=t.fullPath;try{let n=await(0,Kt.realpath)(r),i=await(0,Kt.lstat)(n);if(i.isFile())return"file";if(i.isDirectory()){let s=n.length;if(r.startsWith(n)&&r.substr(s,1)===qt.sep){let o=new Error(`Circular symlink detected: "${r}" points to "${n}"`);return o.code=Al,this._onError(o)}return"directory"}}catch(n){return this._onError(n),""}}}_includeAsFile(t){let a=t&&t[this._statsProp];return a&&this._wantsEverything&&!a.isDirectory()}};function Bl(e,t={}){let a=t.entryType||t.type;if(a==="both"&&(a=ot.FILE_DIR_TYPE),a&&(t.type=a),e){if(typeof e!="string")throw new TypeError("readdirp: root argument must be a string. Usage: readdirp(root, options)");if(a&&!Tl.includes(a))throw new Error(`readdirp: Invalid type passed. Use one of ${Tl.join(", ")}`)}else throw new Error("readdirp: root argument is required. Usage: readdirp(root, options)");return t.root=e,new Mi(t)}var vr=require("fs"),xt=require("fs/promises"),ve=Ae(require("path"),1),_l=require("os"),ph="data",Hi="end",Nl="close",un=()=>{};var ln=process.platform,zi=ln==="win32",hh=ln==="darwin",gh=ln==="linux",yh=ln==="freebsd",Pl=(0,_l.type)()==="OS400",Ee={ALL:"all",READY:"ready",ADD:"add",CHANGE:"change",ADD_DIR:"addDir",UNLINK:"unlink",UNLINK_DIR:"unlinkDir",RAW:"raw",ERROR:"error"},Ct=Ee,mh="watch",vh={lstat:xt.lstat,stat:xt.stat},mr="listeners",an="errHandlers",Fr="rawEmitters",Eh=[mr,an,Fr],Ch=new Set(["3dm","3ds","3g2","3gp","7z","a","aac","adp","afdesign","afphoto","afpub","ai","aif","aiff","alz","ape","apk","appimage","ar","arj","asf","au","avi","bak","baml","bh","bin","bk","bmp","btif","bz2","bzip2","cab","caf","cgm","class","cmx","cpio","cr2","cur","dat","dcm","deb","dex","djvu","dll","dmg","dng","doc","docm","docx","dot","dotm","dra","DS_Store","dsk","dts","dtshd","dvb","dwg","dxf","ecelp4800","ecelp7470","ecelp9600","egg","eol","eot","epub","exe","f4v","fbs","fh","fla","flac","flatpak","fli","flv","fpx","fst","fvt","g3","gh","gif","graffle","gz","gzip","h261","h263","h264","icns","ico","ief","img","ipa","iso","jar","jpeg","jpg","jpgv","jpm","jxr","key","ktx","lha","lib","lvp","lz","lzh","lzma","lzo","m3u","m4a","m4v","mar","mdi","mht","mid","midi","mj2","mka","mkv","mmr","mng","mobi","mov","movie","mp3","mp4","mp4a","mpeg","mpg","mpga","mxu","nef","npx","numbers","nupkg","o","odp","ods","odt","oga","ogg","ogv","otf","ott","pages","pbm","pcx","pdb","pdf","pea","pgm","pic","png","pnm","pot","potm","potx","ppa","ppam","ppm","pps","ppsm","ppsx","ppt","pptm","pptx","psd","pya","pyc","pyo","pyv","qt","rar","ras","raw","resources","rgb","rip","rlc","rmf","rmvb","rpm","rtf","rz","s3m","s7z","scpt","sgi","shar","snap","sil","sketch","slk","smv","snk","so","stl","suo","sub","swf","tar","tbz","tbz2","tga","tgz","thmx","tif","tiff","tlz","ttc","ttf","txz","udf","uvh","uvi","uvm","uvp","uvs","uvu","viv","vob","war","wav","wax","wbmp","wdp","weba","webm","webp","whl","wim","wm","wma","wmv","wmx","woff","woff2","wrm","wvx","xbm","xif","xla","xlam","xls","xlsb","xlsm","xlsx","xlt","xltm","xltx","xm","xmind","xpi","xpm","xwd","xz","z","zip","zipx"]),xh=e=>Ch.has(ve.extname(e).slice(1).toLowerCase()),qi=(e,t)=>{e instanceof Set?e.forEach(t):t(e)},ua=(e,t,a)=>{let r=e[t];r instanceof Set||(e[t]=r=new Set([r])),r.add(a)},Sh=e=>t=>{let a=e[t];a instanceof Set?a.clear():delete e[t]},la=(e,t,a)=>{let r=e[t];r instanceof Set?r.delete(a):r===a&&delete e[t]},Dl=e=>e instanceof Set?e.size===0:!e,nn=new Map;function Rl(e,t,a,r,n){let i=(s,o)=>{a(e),n(s,o,{watchedPath:e}),o&&e!==o&&sn(ve.resolve(e,o),mr,ve.join(e,o))};try{return(0,vr.watch)(e,{persistent:t.persistent},i)}catch(s){r(s);return}}var sn=(e,t,a,r,n)=>{let i=nn.get(e);i&&qi(i[t],s=>{s(a,r,n)})},Th=(e,t,a,r)=>{let{listener:n,errHandler:i,rawEmitter:s}=r,o=nn.get(t),u;if(!a.persistent)return u=Rl(e,a,n,i,s),u?u.close.bind(u):void 0;if(o)ua(o,mr,n),ua(o,an,i),ua(o,Fr,s);else{if(u=Rl(e,a,sn.bind(null,t,mr),i,sn.bind(null,t,Fr)),!u)return;u.on(Ct.ERROR,async l=>{let f=sn.bind(null,t,an);if(o&&(o.watcherUnusable=!0),zi&&l.code==="EPERM")try{await(await(0,xt.open)(e,"r")).close(),f(l)}catch{}else f(l)}),o={listeners:n,errHandlers:i,rawEmitters:s,watcher:u},nn.set(t,o)}return()=>{la(o,mr,n),la(o,an,i),la(o,Fr,s),Dl(o.listeners)&&(o.watcher.close(),nn.delete(t),Eh.forEach(Sh(o)),o.watcher=void 0,Object.freeze(o))}},Ki=new Map,bh=(e,t,a,r)=>{let{listener:n,rawEmitter:i}=r,s=Ki.get(t),o=s&&s.options;return o&&(o.persistent<a.persistent||o.interval>a.interval)&&((0,vr.unwatchFile)(t),s=void 0),s?(ua(s,mr,n),ua(s,Fr,i)):(s={listeners:n,rawEmitters:i,options:a,watcher:(0,vr.watchFile)(t,a,(u,l)=>{qi(s.rawEmitters,c=>{c(Ct.CHANGE,t,{curr:u,prev:l})});let f=u.mtimeMs;(u.size!==l.size||f>l.mtimeMs||f===0)&&qi(s.listeners,c=>c(e,u))})},Ki.set(t,s)),()=>{la(s,mr,n),la(s,Fr,i),Dl(s.listeners)&&(Ki.delete(t),(0,vr.unwatchFile)(t),s.options=s.watcher=void 0,Object.freeze(s))}},on=class{constructor(t){this.fsw=t,this._boundHandleError=a=>t._handleError(a)}_watchWithNodeFs(t,a){let r=this.fsw.options,n=ve.dirname(t),i=ve.basename(t);this.fsw._getWatchedDir(n).add(i);let o=ve.resolve(t),u={persistent:r.persistent};a||(a=un);let l;if(r.usePolling){let f=r.interval!==r.binaryInterval;u.interval=f&&xh(i)?r.binaryInterval:r.interval,l=bh(t,o,u,{listener:a,rawEmitter:this.fsw._emitRaw})}else l=Th(t,o,u,{listener:a,errHandler:this._boundHandleError,rawEmitter:this.fsw._emitRaw});return l}_handleFile(t,a,r){if(this.fsw.closed)return;let n=ve.dirname(t),i=ve.basename(t),s=this.fsw._getWatchedDir(n),o=a;if(s.has(i))return;let u=async(f,c)=>{if(this.fsw._throttle(mh,t,5)){if(!c||c.mtimeMs===0)try{let y=await(0,xt.stat)(t);if(this.fsw.closed)return;let m=y.atimeMs,h=y.mtimeMs;if((!m||m<=h||h!==o.mtimeMs)&&this.fsw._emit(Ct.CHANGE,t,y),(hh||gh||yh)&&o.ino!==y.ino){this.fsw._closeFile(f),o=y;let v=this._watchWithNodeFs(t,u);v&&this.fsw._addPathCloser(f,v)}else o=y}catch{this.fsw._remove(n,i)}else if(s.has(i)){let y=c.atimeMs,m=c.mtimeMs;(!y||y<=m||m!==o.mtimeMs)&&this.fsw._emit(Ct.CHANGE,t,c),o=c}}},l=this._watchWithNodeFs(t,u);if(!(r&&this.fsw.options.ignoreInitial)&&this.fsw._isntIgnored(t)){if(!this.fsw._throttle(Ct.ADD,t,0))return;this.fsw._emit(Ct.ADD,t,a)}return l}async _handleSymlink(t,a,r,n){if(this.fsw.closed)return;let i=t.fullPath,s=this.fsw._getWatchedDir(a);if(!this.fsw.options.followSymlinks){this.fsw._incrReadyCount();let o;try{o=await(0,xt.realpath)(r)}catch{return this.fsw._emitReady(),!0}return this.fsw.closed?void 0:(s.has(n)?this.fsw._symlinkPaths.get(i)!==o&&(this.fsw._symlinkPaths.set(i,o),this.fsw._emit(Ct.CHANGE,r,t.stats)):(s.add(n),this.fsw._symlinkPaths.set(i,o),this.fsw._emit(Ct.ADD,r,t.stats)),this.fsw._emitReady(),!0)}if(this.fsw._symlinkPaths.has(i))return!0;this.fsw._symlinkPaths.set(i,!0)}_handleRead(t,a,r,n,i,s,o){if(t=ve.join(t,""),o=this.fsw._throttle("readdir",t,1e3),!o)return;let u=this.fsw._getWatchedDir(r.path),l=new Set,f=this.fsw._readdirp(t,{fileFilter:c=>r.filterPath(c),directoryFilter:c=>r.filterDir(c)});if(f)return f.on(ph,async c=>{if(this.fsw.closed){f=void 0;return}let y=c.path,m=ve.join(t,y);if(l.add(y),!(c.stats.isSymbolicLink()&&await this._handleSymlink(c,t,m,y))){if(this.fsw.closed){f=void 0;return}(y===n||!n&&!u.has(y))&&(this.fsw._incrReadyCount(),m=ve.join(i,ve.relative(i,m)),this._addToNodeFs(m,a,r,s+1))}}).on(Ct.ERROR,this._boundHandleError),new Promise((c,y)=>{if(!f)return y();f.once(Hi,()=>{if(this.fsw.closed){f=void 0;return}let m=o?o.clear():!1;c(void 0),u.getChildren().filter(h=>h!==t&&!l.has(h)).forEach(h=>{this.fsw._remove(t,h)}),f=void 0,m&&this._handleRead(t,!1,r,n,i,s,o)})})}async _handleDir(t,a,r,n,i,s,o){let u=this.fsw._getWatchedDir(ve.dirname(t)),l=u.has(ve.basename(t));!(r&&this.fsw.options.ignoreInitial)&&!i&&!l&&this.fsw._emit(Ct.ADD_DIR,t,a),u.add(ve.basename(t)),this.fsw._getWatchedDir(t);let f,c,y=this.fsw.options.depth;if((y==null||n<=y)&&!this.fsw._symlinkPaths.has(o)){if(!i&&(await this._handleRead(t,r,s,i,t,n,f),this.fsw.closed))return;c=this._watchWithNodeFs(t,(m,h)=>{h&&h.mtimeMs===0||this._handleRead(m,!1,s,i,t,n,f)})}return c}async _addToNodeFs(t,a,r,n,i){let s=this.fsw._emitReady;if(this.fsw._isIgnored(t)||this.fsw.closed)return s(),!1;let o=this.fsw._getWatchHelpers(t);r&&(o.filterPath=u=>r.filterPath(u),o.filterDir=u=>r.filterDir(u));try{let u=await vh[o.statMethod](o.watchPath);if(this.fsw.closed)return;if(this.fsw._isIgnored(o.watchPath,u))return s(),!1;let l=this.fsw.options.followSymlinks,f;if(u.isDirectory()){let c=ve.resolve(t),y=l?await(0,xt.realpath)(t):t;if(this.fsw.closed||(f=await this._handleDir(o.watchPath,u,a,n,i,o,y),this.fsw.closed))return;c!==y&&y!==void 0&&this.fsw._symlinkPaths.set(c,y)}else if(u.isSymbolicLink()){let c=l?await(0,xt.realpath)(t):t;if(this.fsw.closed)return;let y=ve.dirname(o.watchPath);if(this.fsw._getWatchedDir(y).add(o.watchPath),this.fsw._emit(Ct.ADD,o.watchPath,u),f=await this._handleDir(y,u,a,n,t,o,c),this.fsw.closed)return;c!==void 0&&this.fsw._symlinkPaths.set(ve.resolve(t),c)}else f=this._handleFile(o.watchPath,u,a);return s(),f&&this.fsw._addPathCloser(t,f),!1}catch(u){if(this.fsw._handleError(u))return s(),t}}};var Gi="/",Ih="//",Kl=".",wh="..",Ah="string",Bh=/\\/g,Ll=/\/\//,Rh=/\..*\.(sw[px])$|~$|\.subl.*\.tmp/,_h=/^\.[/\\]/;function fn(e){return Array.isArray(e)?e:[e]}var Qi=e=>typeof e=="object"&&e!==null&&!(e instanceof RegExp);function Nh(e){return typeof e=="function"?e:typeof e=="string"?t=>e===t:e instanceof RegExp?t=>e.test(t):typeof e=="object"&&e!==null?t=>{if(e.path===t)return!0;if(e.recursive){let a=Z.relative(e.path,t);return a?!a.startsWith("..")&&!Z.isAbsolute(a):!1}return!1}:()=>!1}function Ph(e){if(typeof e!="string")throw new Error("string expected");e=Z.normalize(e),e=e.replace(/\\/g,"/");let t=!1;e.startsWith("//")&&(t=!0);let a=/\/\//;for(;e.match(a);)e=e.replace(a,"/");return t&&(e="/"+e),e}function kl(e,t,a){let r=Ph(t);for(let n=0;n<e.length;n++){let i=e[n];if(i(r,a))return!0}return!1}function Dh(e,t){if(e==null)throw new TypeError("anymatch: specify first argument");let r=fn(e).map(n=>Nh(n));return t==null?(n,i)=>kl(r,n,i):kl(r,t)}var Ul=e=>{let t=fn(e).flat();if(!t.every(a=>typeof a===Ah))throw new TypeError(`Non-string provided as watch path: ${t}`);return t.map(ql)},Fl=e=>{let t=e.replace(Bh,Gi),a=!1;for(t.startsWith(Ih)&&(a=!0);t.match(Ll);)t=t.replace(Ll,Gi);return a&&(t=Gi+t),t},ql=e=>Fl(Z.normalize(Fl(e))),Ol=(e="")=>t=>typeof t=="string"?ql(Z.isAbsolute(t)?t:Z.join(e,t)):t,Lh=(e,t)=>Z.isAbsolute(e)?e:Z.join(t,e),kh=Object.freeze(new Set),Wi=class{constructor(t,a){this.path=t,this._removeWatcher=a,this.items=new Set}add(t){let{items:a}=this;a&&t!==Kl&&t!==wh&&a.add(t)}async remove(t){let{items:a}=this;if(!a||(a.delete(t),a.size>0))return;let r=this.path;try{await(0,cn.readdir)(r)}catch{this._removeWatcher&&this._removeWatcher(Z.dirname(r),Z.basename(r))}}has(t){let{items:a}=this;if(a)return a.has(t)}getChildren(){let{items:t}=this;return t?[...t.values()]:[]}dispose(){this.items.clear(),this.path="",this._removeWatcher=un,this.items=kh,Object.freeze(this)}},Uh="stat",Fh="lstat",ji=class{constructor(t,a,r){this.fsw=r;let n=t;this.path=t=t.replace(_h,""),this.watchPath=n,this.fullWatchPath=Z.resolve(n),this.dirParts=[],this.dirParts.forEach(i=>{i.length>1&&i.pop()}),this.followSymlinks=a,this.statMethod=a?Uh:Fh}entryPath(t){return Z.join(this.watchPath,Z.relative(this.watchPath,t.fullPath))}filterPath(t){let{stats:a}=t;if(a&&a.isSymbolicLink())return this.filterDir(t);let r=this.entryPath(t);return this.fsw._isntIgnored(r,a)&&this.fsw._hasReadPermissions(a)}filterDir(t){return this.fsw._isntIgnored(this.entryPath(t),t.stats)}},$i=class extends Ml.EventEmitter{constructor(t={}){super(),this.closed=!1,this._closers=new Map,this._ignoredPaths=new Set,this._throttled=new Map,this._streams=new Set,this._symlinkPaths=new Map,this._watched=new Map,this._pendingWrites=new Map,this._pendingUnlinks=new Map,this._readyCount=0,this._readyEmitted=!1;let a=t.awaitWriteFinish,r={stabilityThreshold:2e3,pollInterval:100},n={persistent:!0,ignoreInitial:!1,ignorePermissionErrors:!1,interval:100,binaryInterval:300,followSymlinks:!0,usePolling:!1,atomic:!0,...t,ignored:t.ignored?fn(t.ignored):fn([]),awaitWriteFinish:a===!0?r:typeof a=="object"?{...r,...a}:!1};Pl&&(n.usePolling=!0),n.atomic===void 0&&(n.atomic=!n.usePolling);let i=process.env.CHOKIDAR_USEPOLLING;if(i!==void 0){let u=i.toLowerCase();u==="false"||u==="0"?n.usePolling=!1:u==="true"||u==="1"?n.usePolling=!0:n.usePolling=!!u}let s=process.env.CHOKIDAR_INTERVAL;s&&(n.interval=Number.parseInt(s,10));let o=0;this._emitReady=()=>{o++,o>=this._readyCount&&(this._emitReady=un,this._readyEmitted=!0,process.nextTick(()=>this.emit(Ee.READY)))},this._emitRaw=(...u)=>this.emit(Ee.RAW,...u),this._boundRemove=this._remove.bind(this),this.options=n,this._nodeFsHandler=new on(this),Object.freeze(n)}_addIgnoredPath(t){if(Qi(t)){for(let a of this._ignoredPaths)if(Qi(a)&&a.path===t.path&&a.recursive===t.recursive)return}this._ignoredPaths.add(t)}_removeIgnoredPath(t){if(this._ignoredPaths.delete(t),typeof t=="string")for(let a of this._ignoredPaths)Qi(a)&&a.path===t&&this._ignoredPaths.delete(a)}add(t,a,r){let{cwd:n}=this.options;this.closed=!1,this._closePromise=void 0;let i=Ul(t);return n&&(i=i.map(s=>Lh(s,n))),i.forEach(s=>{this._removeIgnoredPath(s)}),this._userIgnored=void 0,this._readyCount||(this._readyCount=0),this._readyCount+=i.length,Promise.all(i.map(async s=>{let o=await this._nodeFsHandler._addToNodeFs(s,!r,void 0,0,a);return o&&this._emitReady(),o})).then(s=>{this.closed||s.forEach(o=>{o&&this.add(Z.dirname(o),Z.basename(a||o))})}),this}unwatch(t){if(this.closed)return this;let a=Ul(t),{cwd:r}=this.options;return a.forEach(n=>{!Z.isAbsolute(n)&&!this._closers.has(n)&&(r&&(n=Z.join(r,n)),n=Z.resolve(n)),this._closePath(n),this._addIgnoredPath(n),this._watched.has(n)&&this._addIgnoredPath({path:n,recursive:!0}),this._userIgnored=void 0}),this}close(){if(this._closePromise)return this._closePromise;this.closed=!0,this.removeAllListeners();let t=[];return this._closers.forEach(a=>a.forEach(r=>{let n=r();n instanceof Promise&&t.push(n)})),this._streams.forEach(a=>a.destroy()),this._userIgnored=void 0,this._readyCount=0,this._readyEmitted=!1,this._watched.forEach(a=>a.dispose()),this._closers.clear(),this._watched.clear(),this._streams.clear(),this._symlinkPaths.clear(),this._throttled.clear(),this._closePromise=t.length?Promise.all(t).then(()=>{}):Promise.resolve(),this._closePromise}getWatched(){let t={};return this._watched.forEach((a,r)=>{let i=(this.options.cwd?Z.relative(this.options.cwd,r):r)||Kl;t[i]=a.getChildren().sort()}),t}emitWithAll(t,a){this.emit(t,...a),t!==Ee.ERROR&&this.emit(Ee.ALL,t,...a)}async _emit(t,a,r){if(this.closed)return;let n=this.options;zi&&(a=Z.normalize(a)),n.cwd&&(a=Z.relative(n.cwd,a));let i=[a];r!=null&&i.push(r);let s=n.awaitWriteFinish,o;if(s&&(o=this._pendingWrites.get(a)))return o.lastChange=new Date,this;if(n.atomic){if(t===Ee.UNLINK)return this._pendingUnlinks.set(a,[t,...i]),setTimeout(()=>{this._pendingUnlinks.forEach((u,l)=>{this.emit(...u),this.emit(Ee.ALL,...u),this._pendingUnlinks.delete(l)})},typeof n.atomic=="number"?n.atomic:100),this;t===Ee.ADD&&this._pendingUnlinks.has(a)&&(t=Ee.CHANGE,this._pendingUnlinks.delete(a))}if(s&&(t===Ee.ADD||t===Ee.CHANGE)&&this._readyEmitted){let u=(l,f)=>{l?(t=Ee.ERROR,i[0]=l,this.emitWithAll(t,i)):f&&(i.length>1?i[1]=f:i.push(f),this.emitWithAll(t,i))};return this._awaitWriteFinish(a,s.stabilityThreshold,t,u),this}if(t===Ee.CHANGE&&!this._throttle(Ee.CHANGE,a,50))return this;if(n.alwaysStat&&r===void 0&&(t===Ee.ADD||t===Ee.ADD_DIR||t===Ee.CHANGE)){let u=n.cwd?Z.join(n.cwd,a):a,l;try{l=await(0,cn.stat)(u)}catch{}if(!l||this.closed)return;i.push(l)}return this.emitWithAll(t,i),this}_handleError(t){let a=t&&t.code;return t&&a!=="ENOENT"&&a!=="ENOTDIR"&&(!this.options.ignorePermissionErrors||a!=="EPERM"&&a!=="EACCES")&&this.emit(Ee.ERROR,t),t||this.closed}_throttle(t,a,r){this._throttled.has(t)||this._throttled.set(t,new Map);let n=this._throttled.get(t);if(!n)throw new Error("invalid throttle");let i=n.get(a);if(i)return i.count++,!1;let s,o=()=>{let l=n.get(a),f=l?l.count:0;return n.delete(a),clearTimeout(s),l&&clearTimeout(l.timeoutObject),f};s=setTimeout(o,r);let u={timeoutObject:s,clear:o,count:0};return n.set(a,u),u}_incrReadyCount(){return this._readyCount++}_awaitWriteFinish(t,a,r,n){let i=this.options.awaitWriteFinish;if(typeof i!="object")return;let s=i.pollInterval,o,u=t;this.options.cwd&&!Z.isAbsolute(t)&&(u=Z.join(this.options.cwd,t));let l=new Date,f=this._pendingWrites;function c(y){(0,Vl.stat)(u,(m,h)=>{if(m||!f.has(t)){m&&m.code!=="ENOENT"&&n(m);return}let v=Number(new Date);y&&h.size!==y.size&&(f.get(t).lastChange=v);let C=f.get(t);v-C.lastChange>=a?(f.delete(t),n(void 0,h)):o=setTimeout(c,s,h)})}f.has(t)||(f.set(t,{lastChange:l,cancelWait:()=>(f.delete(t),clearTimeout(o),r)}),o=setTimeout(c,s))}_isIgnored(t,a){if(this.options.atomic&&Rh.test(t))return!0;if(!this._userIgnored){let{cwd:r}=this.options,i=(this.options.ignored||[]).map(Ol(r)),o=[...[...this._ignoredPaths].map(Ol(r)),...i];this._userIgnored=Dh(o,void 0)}return this._userIgnored(t,a)}_isntIgnored(t,a){return!this._isIgnored(t,a)}_getWatchHelpers(t){return new ji(t,this.options.followSymlinks,this)}_getWatchedDir(t){let a=Z.resolve(t);return this._watched.has(a)||this._watched.set(a,new Wi(a,this._boundRemove)),this._watched.get(a)}_hasReadPermissions(t){return this.options.ignorePermissionErrors?!0:!!(Number(t.mode)&256)}_remove(t,a,r){let n=Z.join(t,a),i=Z.resolve(n);if(r=r??(this._watched.has(n)||this._watched.has(i)),!this._throttle("remove",n,100))return;!r&&this._watched.size===1&&this.add(t,a,!0),this._getWatchedDir(n).getChildren().forEach(y=>this._remove(n,y));let u=this._getWatchedDir(t),l=u.has(a);u.remove(a),this._symlinkPaths.has(i)&&this._symlinkPaths.delete(i);let f=n;if(this.options.cwd&&(f=Z.relative(this.options.cwd,n)),this.options.awaitWriteFinish&&this._pendingWrites.has(f)&&this._pendingWrites.get(f).cancelWait()===Ee.ADD)return;this._watched.delete(n),this._watched.delete(i);let c=r?Ee.UNLINK_DIR:Ee.UNLINK;l&&!this._isIgnored(n)&&this._emit(c,n),this._closePath(n)}_closePath(t){this._closeFile(t);let a=Z.dirname(t);this._getWatchedDir(a).remove(Z.basename(t))}_closeFile(t){let a=this._closers.get(t);a&&(a.forEach(r=>r()),this._closers.delete(t))}_addPathCloser(t,a){if(!a)return;let r=this._closers.get(t);r||(r=[],this._closers.set(t,r)),r.push(a)}_readdirp(t,a){if(this.closed)return;let r={type:Ee.ALL,alwaysStat:!0,lstat:!0,...a,depth:0},n=Bl(t,r);return this._streams.add(n),n.once(Nl,()=>{n=void 0}),n.once(Hi,()=>{n&&(this._streams.delete(n),n=void 0)}),n}};function Hl(e,t={}){let a=new $i(t);return a.add(e),a}function Xi(e,t={}){let a=t.debounceMs||16,r=new Map;function n(c,y){return(...m)=>{let h=r.get(y);h&&clearTimeout(h);let v=setTimeout(()=>{c(...m),r.delete(y)},a);r.set(y,v)}}let i=new Map;async function s(){try{let c=await rn(e,{ignore:t.ignore});for(let y of c)await o(y)}catch(c){l(c)}}async function o(c){try{let y=i.get(c),m=await oa(c,e,!1);if(!m||m.length===0||y&&!vl(c,m))return;await oa(c,e,!0);let h=Yi.normalize(c);y?(i.set(c,m),t.onRouteChanged&&t.onRouteChanged(h,m)):(i.set(c,m),t.onRouteAdded&&t.onRouteAdded(h,m))}catch(y){console.log(`\u26A0\uFE0F Error processing file ${c}:`,y),l(y)}}function u(c){let y=Yi.normalize(c),m=i.get(y);m&&m.length>0&&t.onRouteRemoved&&t.onRouteRemoved(y,m),i.delete(y)}function l(c){t.onError&&c instanceof Error?t.onError(c):console.error("\u26A0\uFE0F Route watcher error:",c)}let f=Hl(e,{awaitWriteFinish:{stabilityThreshold:50,pollInterval:10},usePolling:!1,atomic:!0,followSymlinks:!1,depth:10,ignored:[/(^|[/\\])\../,/node_modules/,/\.git/,/\.DS_Store/,/Thumbs\.db/,/\.(test|spec)\.(ts|js)$/,/\.d\.ts$/,/\.map$/,/~$/,...t.ignore||[]]});return f.on("add",c=>{n(o,c)(c)}).on("change",c=>{n(o,c)(c)}).on("unlink",c=>{n(u,c)(c)}).on("error",l),s().catch(l),{close:()=>(r.forEach(c=>clearTimeout(c)),r.clear(),f.close()),getRoutes:()=>{let c=[];for(let y of i.values())c.push(...y);return c},getRoutesByFile:()=>new Map(i)}}var jl=require("zod");var zl=require("zod");function Zi(e,t){return t instanceof zl.z.ZodObject?t.strict().parse(e):t.parse(e)}var Gl=require("zod");function Ji(e,t){return t instanceof Gl.z.ZodObject?t.strict().parse(e):t.parse(e)}var Ql=require("zod");function es(e,t){return t instanceof Ql.z.ZodObject?t.strict().parse(e):t.parse(e)}var Wl=require("zod");function ts(e,t){return t instanceof Wl.z.ZodObject?t.strict().parse(e):t.parse(e)}ta();Vt();function rs(e,t=!1){return{name:"RequestValidator",execute:async(r,n)=>{if(e.params&&r.request.params)try{r.request.params=Ji(r.request.params,e.params)}catch(i){let s=dn(i),o=s.reduce((u,l)=>u+l.messages.length,0);throw new Ot("Request validation failed",{fields:s,errorCount:o,section:"params"})}if(e.query&&r.request.query)try{r.request.query=es(r.request.query,e.query)}catch(i){let s=dn(i),o=s.reduce((u,l)=>u+l.messages.length,0);throw new Ot("Request validation failed",{fields:s,errorCount:o,section:"query"})}if(e.body)try{r.request.body=Zi(r.request.body,e.body)}catch(i){let s=dn(i),o=s.reduce((u,l)=>u+l.messages.length,0);throw new Ot("Request validation failed",{fields:s,errorCount:o,section:"body"})}await n()},debug:t}}function as(e,t=!1){return{name:"ResponseValidator",execute:async(r,n)=>{let i=r.response.json;r.response.json=(s,o)=>{try{let u=ts(s,e);return r.response.json=i,i.call(r.response,u,o)}catch(u){throw r.response.json=i,new Ft("Response validation failed",{responseSchema:e.description||"Unknown schema",validationError:dn(u),originalResponse:s})}},await n()},debug:t}}function dn(e){if(e instanceof jl.z.ZodError){let t=new Map;for(let a of e.issues){let r=a.path.length>0?a.path.join("."):"root";t.has(r)||t.set(r,[]),t.get(r).push(a.message)}return Array.from(t.entries()).map(([a,r])=>({field:a,messages:r}))}return e instanceof Error?[{field:"unknown",messages:[e.message]}]:[{field:"unknown",messages:[String(e)]}]}async function ns(e,t,a){let r=[...t.middleware||[]];t.schema&&((t.schema.params||t.schema.query||t.schema.body)&&r.unshift(rs(t.schema)),t.schema.response&&r.push(as(t.schema.response))),await nr([...r])(e,async()=>{let i=await t.handler(e,a);!e.response.sent&&i!==void 0&&e.response.json(i)})}function pn(e,t,a){let r=t.exec(e);if(!r)return{};let n={};for(let i=0;i<a.length;i++)n[a[i]]=r[i+1]||"";return n}function is(e){let t=[];if(e==="/")return{pattern:/^\/$/,paramNames:[]};let a=e.replace(/([.+*?^$(){}|\\])/g,"\\$1");return a=a.replace(/\/:([^/]+)/g,(n,i)=>(t.push(i),"/([^/]+)")).replace(/\/\[([^\]]+)\]/g,(n,i)=>(t.push(i),"/([^/]+)")),a=`${a}(?:/)?`,{pattern:new RegExp(`^${a}$`),paramNames:t}}function ss(){let e=[];return{add(t,a,r){let{pattern:n,paramNames:i}=is(t),s={path:t,method:a,pattern:n,paramNames:i,routeOptions:r},o=e.findIndex(u=>i.length<u.paramNames.length);o===-1?e.push(s):e.splice(o,0,s)},remove(t){for(let a=e.length-1;a>=0;a--)e[a].path===t&&e.splice(a,1)},clear(){e.length=0},match(t,a){let r=t.split("?")[0];if(!r)return null;for(let i of e){if(i.method!==a)continue;if(i.pattern.exec(r)){let o=pn(t,i.pattern,i.paramNames);return{route:i.routeOptions,params:o}}}return e.find(i=>i.method!==a&&i.pattern.test(t))?{route:null,params:{},methodNotAllowed:!0,allowedMethods:e.filter(i=>i.pattern.test(t)).map(i=>i.method)}:null},getRoutes(){return e.map(t=>({path:t.path,method:t.method}))},findRoutes(t){return e.filter(a=>a.pattern.test(t)).map(a=>({path:a.path,method:a.method,params:pn(t,a.pattern,a.paramNames)}))}}}function $l(){return{routesByPath:new Map,routesByFile:new Map,pathToFile:new Map}}function rr(e,t,a){console.log(`Updating routes from file: ${t}`);let r=e.routesByFile.get(t)||new Set,n=new Set(a.map(l=>l.path)),i=a.filter(l=>!r.has(l.path)),s=Array.from(r).filter(l=>!n.has(l)),u=a.filter(l=>r.has(l.path)).filter(l=>{let f=e.routesByPath.get(l.path);return!f||!Vh(f,l)});return Oh(e,t,{added:i,removed:s,changed:u}),{added:i,removed:s,changed:u}}function Yl(e){return Array.from(e.routesByPath.values())}function Oh(e,t,a){let{added:r,removed:n,changed:i}=a;n.forEach(o=>{e.routesByPath.delete(o),e.pathToFile.delete(o)}),[...r,...i].forEach(o=>{e.routesByPath.set(o.path,o),e.pathToFile.set(o.path,t)});let s=new Set([...r.map(o=>o.path),...i.map(o=>o.path),...Array.from(e.routesByFile.get(t)||[]).filter(o=>!n.includes(o))]);s.size>0?e.routesByFile.set(t,s):e.routesByFile.delete(t)}function Vh(e,t){if(e.path!==t.path)return!1;let a=Object.keys(e).filter(n=>n!=="path").sort(),r=Object.keys(t).filter(n=>n!=="path").sort();return a.length!==r.length?!1:a.every(n=>{let i=e[n],s=t[n];return typeof i==typeof s})}function os(e,t){Object.entries(e).forEach(([a,r])=>{a==="path"||!r||t.add(e.path,a,r)})}function fa(e,t){"remove"in t&&typeof t.remove=="function"?t.remove(e):console.warn("Matcher does not support selective removal, consider adding remove() method")}function Xl(e,t){fa(e.path,t),os(e,t)}var Mh={routesDir:"./routes",basePath:"/",watchMode:process.env.NODE_ENV==="development"};function Zl(e){let t={...Mh,...e};e.basePath&&!e.basePath.startsWith("/")&&console.warn("Base path does nothing");let a=$l(),r=ss(),n=!1,i=null,s=null,o=new Set([t.routesDir]);function u(h){console.log(`
|
|
49
|
+
\u{1F527} APPLYING MATCHER CHANGES:`),console.log(` Adding ${h.added.length} routes`),console.log(` Removing ${h.removed.length} routes`),console.log(` Updating ${h.changed.length} routes`),h.removed.forEach(v=>{console.log(` \u2796 Removing: ${v}`),fa(v,r)}),h.added.forEach(v=>{let C=Object.keys(v).filter(T=>T!=="path");console.log(` \u2795 Adding: ${v.path} [${C.join(", ")}]`),os(v,r)}),h.changed.forEach(v=>{let C=Object.keys(v).filter(T=>T!=="path");console.log(` \u{1F504} Updating: ${v.path} [${C.join(", ")}]`),Xl(v,r)}),console.log(`\u2705 Matcher changes applied
|
|
50
|
+
`)}function l(h,v){try{let C=rr(a,v,h);return u(C),C}catch(C){throw console.error(`\u26A0\uFE0F Route conflicts from ${v}:`,C),C}}async function f(h,v,C){try{let T=await xl(h),I=T.map(L=>C?{...L,path:`${C}${L.path}`}:L),A=l(I,v);console.log(`Loaded ${T.length} routes from ${v}${C?` with prefix ${C}`:""} (${A.added.length} added, ${A.changed.length} changed, ${A.removed.length} removed)`)}catch(T){throw console.error(`\u26A0\uFE0F Failed to load routes from ${v}:`,T),T}}async function c(){return n||i||(i=(async()=>{try{await Promise.all(Array.from(o).map(h=>f(h,h))),t.watchMode&&y(),n=!0}catch(h){throw console.error("\u26A0\uFE0F Failed to initialize router:",h),h}})()),i}function y(){s||(s=new Map);for(let h of o)if(!s.has(h)){let v=Xi(h,{debounceMs:16,ignore:["node_modules",".git"],onRouteAdded:(C,T)=>{try{let I=rr(a,C,T);u(I)}catch(I){console.error(`Error adding routes from ${h}:`,I)}},onRouteChanged:Oi(async(C,T)=>{try{console.log(`Processing changes for ${C}`);let I=rr(a,C,T);console.log(`Changes detected: ${I.added.length} added, ${I.changed.length} changed, ${I.removed.length} removed`),u(I),console.log(`Route changes applied: ${I.added.length} added, ${I.changed.length} changed, ${I.removed.length} removed`)}catch(I){console.error(`\u26A0\uFE0F Error updating routes from ${h}:`,I)}},h),onRouteRemoved:(C,T)=>{console.log(`File removed: ${C} with ${T.length} routes`);try{T.forEach(I=>{fa(I.path,r)}),Fi(C)}catch(I){console.error(`\u26A0\uFE0F Error removing routes from ${C}:`,I)}},onError:C=>{console.error(`\u26A0\uFE0F Route watcher error for ${h}:`,C)}});s.set(h,v)}}function m(h,v){s||(s=new Map);let C=Xi(h,{debounceMs:16,ignore:["node_modules",".git"],onRouteAdded:(T,I)=>{try{let A=I.map(N=>v?{...N,path:`${v}${N.path}`}:N),L=rr(a,T,A);u(L)}catch(A){console.error(`\u26A0\uFE0F Error adding routes from ${h}:`,A)}},onRouteChanged:Oi(async(T,I)=>{try{let A=I.map(N=>v?{...N,path:`${v}${N.path}`}:N),L=rr(a,T,A);u(L)}catch(A){console.error(`\u26A0\uFE0F Error updating routes from ${h}:`,A)}},h),onRouteRemoved:(T,I)=>{try{I.forEach(A=>{let L=v?`${v}${A.path}`:A.path;fa(L,r)}),Fi(T)}catch(A){console.error(`Error removing routes from ${T}:`,A)}},onError:T=>{console.error(`\u26A0\uFE0F Route watcher error for ${h}:`,T)}});return s.set(h,C),C}return c().catch(h=>{console.error("\u26A0\uFE0F Failed to initialize router on creation:",h)}),{async handleRequest(h){n||(console.log("\u{1F504} Router not initialized, initializing..."),await c());let{method:v,path:C}=h.request;console.log(`
|
|
51
|
+
\u{1F4E5} Handling request: ${v} ${C}`);let T=r.match(C,v);if(!T)throw console.log(`\u274C No match found for: ${v} ${C}`),new er("Not found");if(console.log(`\u2705 Route matched: ${v} ${C}`),console.log(` Params: ${JSON.stringify(T.params)}`),T.methodNotAllowed){h.response.status(405).json({error:"\u274C Method Not Allowed",allowed:T.allowedMethods}),T.allowedMethods&&T.allowedMethods.length>0&&h.response.header("Allow",T.allowedMethods.join(", "));return}h.request.params=T.params,await ns(h,T.route,T.params)},getRoutes(){return Yl(a)},addRoute(h){let v=rr(a,"programmatic",[h]);u(v)},addRoutes(h){let v=rr(a,"programmatic",h);return u(v),v},async addRouteDirectory(h,v={}){if(o.has(h)){console.warn(`Route directory ${h} already registered`);return}o.add(h),n&&(await f(h,h,v.prefix),t.watchMode&&m(h,v.prefix))},getRouteConflicts(){return[]},async close(){if(s){for(let h of s.values())await h.close();s.clear()}}}}var Kh={port:3e3,host:"localhost",routesDir:"./routes",http2:{enabled:!0},middleware:[],plugins:[]};function qh(e={}){let t={...Kh};return fs({routesDir:e.routesDir||t.routesDir}),{port:e.port??t.port,host:e.host??t.host,routesDir:e.routesDir??t.routesDir,http2:{enabled:e.http2?.enabled??t.http2?.enabled,keyFile:e.http2?.keyFile??t.http2?.keyFile,certFile:e.http2?.certFile??t.http2?.certFile},middleware:[...t.middleware||[],...e.middleware||[]],plugins:[...t.plugins||[],...e.plugins||[]]}}function Hh(e,t,a,r){return async()=>(await zh(e,a,r),await e.pluginManager.initializePlugins(e),await ol(e,t),await e.pluginManager.onServerStart(e,e.server),Gh(e),e)}async function zh(e,t,a){for(let r of t)e.use(r);for(let r of a)await e.register(r)}function Gh(e){let t=ll(()=>e.close());e._signalHandlers=t,e.events.emit("started")}function Qh(e){return async t=>{if(!e.server)return;let a={...t};e._signalHandlers&&(e._signalHandlers.unregister(),delete e._signalHandlers),await ul(e,a)}}function Wh(e){return t=>{let a=Array.isArray(t)?t:[t];return e.middleware.push(...a),e}}function jh(e){return async t=>(dl(t),e.plugins.push(t),await t.register(e),e)}function hn(e={}){let t=qh(e),a;try{a=fl(t)}catch(h){throw h instanceof Error?new Error(`Failed to create server: ${h.message}`):new Error(`Failed to create server: ${String(h)}`)}let{port:r,host:n,middleware:i,plugins:s}=a,o=Array.isArray(i)?[...i]:[],u=Array.isArray(s)?[...s]:[],l=new Jl.AsyncLocalStorage,f=Zl({routesDir:a.routesDir,watchMode:process.env.NODE_ENV==="development"}),c=cl({debug:process.env.NODE_ENV==="development",continueOnError:!0}),y=new ef.default,m={server:null,port:r,host:n,context:l,events:y,plugins:[],middleware:[],_signalHandlers:{unregister:()=>{}},use:()=>m,register:async()=>m,listen:async()=>m,close:async()=>{},router:f,pluginManager:c};return m.listen=Hh(m,a,o,u),m.close=Qh(m),m.use=Wh(m),m.register=jh(m),m}tt();Vt();tt();st();var gn=class extends fe{constructor(t,a=void 0,r=void 0){super("UNAUTHORIZED",t,401,r??xe(),a)}};tt();st();var yn=class extends fe{constructor(t,a=void 0,r=void 0){super("FORBIDDEN",t,403,r??xe(),a)}};tt();st();var mn=class extends fe{constructor(t,a=void 0,r=void 0){super("CONFLICT",t,409,r??xe(),a)}};tt();st();var vn=class extends fe{constructor(t,a=void 0,r=void 0){super("RATE_LIMITED",t,429,r??xe(),a)}};ta();Xa();st();tt();var En=class extends fe{constructor(t,a,r){super("UPLOAD_TIMEOUT",t,408,r??xe(),a)}};Za();st();tt();var Cn=class extends fe{constructor(t,a,r){super("UNPROCESSABLE_ENTITY",t,422,r??xe(),a)}};var tf="0.1.0",rf={createServer:hn},af={createDeleteRoute:bn,createGetRoute:xn,createHeadRoute:wn,createOptionsRoute:An,createPatchRoute:In,createPostRoute:Sn,createPutRoute:Tn},nf={createMiddleware:da,compose:nr},sf={createPlugin:pa},$h={createServer:hn,createMiddleware:da,createPlugin:pa,Server:rf,Router:af,Middleware:nf,Plugins:sf,VERSION:tf};0&&(module.exports={Blaize,BlaizeError,ConflictError,ErrorSeverity,ErrorType,ForbiddenError,InternalServerError,MiddlewareAPI,NotFoundError,PayloadTooLargeError,PluginsAPI,RateLimitError,RequestTimeoutError,RouterAPI,ServerAPI,UnauthorizedError,UnprocessableEntityError,UnsupportedMediaTypeError,VERSION,ValidationError,compose,createDeleteRoute,createGetRoute,createHeadRoute,createMiddleware,createOptionsRoute,createPatchRoute,createPlugin,createPostRoute,createPutRoute,createServer,isBodyParseError});
|
|
52
|
+
/*! Bundled license information:
|
|
53
|
+
|
|
54
|
+
chokidar/esm/index.js:
|
|
55
|
+
(*! chokidar - MIT License (c) 2012 Paul Miller (paulmillr.com) *)
|
|
56
|
+
*/
|
|
3505
57
|
//# sourceMappingURL=index.cjs.map
|