UNPKG

@copoko/space

Version:
1,737 lines (1,441 loc) 2.31 MB
/*! * * CoPoKo Space * Copyright (C) 2018 CoPoKo Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ /******/ (() => { // webpackBootstrap /******/ var __webpack_modules__ = ({ /***/ 32112: /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; // ESM COMPAT FLAG __webpack_require__.r(__webpack_exports__); // EXPORTS __webpack_require__.d(__webpack_exports__, { "Context": () => (/* binding */ Context) }); // EXTERNAL MODULE: ./node_modules/cookie/index.js var node_modules_cookie = __webpack_require__(76489); ;// CONCATENATED MODULE: ./node_modules/@cfworker/web/dist/cookies.js const noCookies = Object.create(null); class Cookies { constructor(requestHeaders, responseHeaders) { this.responseHeaders = responseHeaders; const cookie = requestHeaders.get('cookie'); this.requestCookies = cookie ? (0,node_modules_cookie/* parse */.Q)(cookie) : noCookies; } get(name) { return this.requestCookies[name] || null; } set(name, val, options) { this.responseHeaders.append('Set-Cookie', (0,node_modules_cookie/* serialize */.q)(name, val, options)); } } // EXTERNAL MODULE: ./node_modules/secure-json-parse/index.js var secure_json_parse = __webpack_require__(58833); // EXTERNAL MODULE: ./node_modules/negotiator/lib/charset.js var charset = __webpack_require__(38558); // EXTERNAL MODULE: ./node_modules/negotiator/lib/encoding.js var encoding = __webpack_require__(44328); // EXTERNAL MODULE: ./node_modules/negotiator/lib/language.js var language = __webpack_require__(8035); // EXTERNAL MODULE: ./node_modules/negotiator/lib/mediaType.js var mediaType = __webpack_require__(54097); ;// CONCATENATED MODULE: ./node_modules/@cfworker/web/dist/accepts.js const parseAccept = mediaType.preferredMediaTypes; const parseAcceptLanguage = language.preferredLanguages; const parseAcceptEncoding = encoding.preferredEncodings; const parseAcceptCharset = charset.preferredCharsets; class Accepts { constructor(headers) { this.headers = headers; this._type = undefined; this._language = undefined; this._encoding = undefined; this._charset = undefined; } type(...values) { if (!this._type) { const header = this.headers.get('accept'); this._type = header ? parseAccept(header.toLowerCase()) : []; } for (const accepted of this._type) { for (const value of values) { if (value === accepted || (accepted.startsWith('*') && value.endsWith(accepted.substr(1))) || (accepted.endsWith('*') && value.startsWith(accepted.substr(0, accepted.length - 2)))) { return value; } } } return false; } language(...values) { if (!this._language) { const header = this.headers.get('accept-language'); this._language = header ? parseAcceptLanguage(header.toLowerCase()) : []; } for (const accepted of this._language) { for (const value of values) { if (value === accepted || value.startsWith(accepted)) { return value; } } } return false; } encoding(...values) { if (!this._encoding) { const header = this.headers.get('accept-encoding'); this._encoding = header ? parseAcceptEncoding(header.toLowerCase()) : []; } for (const accepted of this._encoding) { for (const value of values) { if (value === accepted) { return value; } } } return false; } charset(...values) { if (!this._charset) { const header = this.headers.get('accept-charset'); this._charset = header ? parseAcceptCharset(header.toLowerCase()) : []; } for (const accepted of this._charset) { for (const value of values) { if (value === accepted) { return value; } } } return false; } } ;// CONCATENATED MODULE: ./node_modules/@cfworker/web/dist/req.js class Req { constructor(request) { this.raw = request; this.method = request.method; this.url = new URL(request.url); this.headers = request.headers; this.params = Object.create(null); this.accepts = new Accepts(request.headers); this.body = new ReqBody(request); } } class ReqBody { constructor(request) { this.request = request; } arrayBuffer() { if (!this._arrayBuffer) { this._arrayBuffer = this.request.arrayBuffer(); } return this._arrayBuffer; } formData() { if (!this._formData) { this._formData = this.request.formData(); } return this._formData; } json(reviver) { if (!this._json) { this._json = this.text().then(text => (0,secure_json_parse.safeParse)(text, reviver)); } return this._json; } text() { if (!this._text) { this._text = this.request.text(); } return this._text; } } // EXTERNAL MODULE: ./node_modules/statuses/index.js var statuses = __webpack_require__(54917); var statuses_default = /*#__PURE__*/__webpack_require__.n(statuses); ;// CONCATENATED MODULE: ./node_modules/@cfworker/web/dist/response-builder.js class ResponseBuilder { constructor() { this.headers = new Headers(); this._status = 404; this._explicitStatus = false; this._implicitType = false; this._body = null; this._stringifyBody = false; } get status() { return this._status; } set status(value) { this._explicitStatus = true; this._status = value; if (this.body && (statuses_default()).empty[value]) { this.body = null; } } get statusText() { return (statuses_default()).message[this._status]; } get body() { return this._body; } set body(value) { this._body = value; if (value === null) { if (!(statuses_default()).empty[this.status]) { this._status = 204; } this.headers.delete('content-type'); this.headers.delete('content-length'); this.headers.delete('transfer-encoding'); return; } if (!this._explicitStatus) { this._status = 200; } if (value instanceof Blob || value instanceof FormData || value instanceof URLSearchParams || ArrayBuffer.isView(value) || value instanceof ArrayBuffer || value instanceof ReadableStream) { this._stringifyBody = false; if (this._implicitType) { this._implicitType = false; this.headers.delete('content-type'); } } else if (typeof value === 'string') { this._stringifyBody = false; if (!this.headers.has('content-type') || this._implicitType) { this._implicitType = true; if (/^\s*</.test(value)) { this.headers.set('content-type', 'text/html;charset=UTF-8'); } else { this.headers.set('content-type', 'text/plain;charset=UTF-8'); } } } else { this._stringifyBody = true; this._implicitType = true; this.headers.set('content-type', 'application/json;charset=UTF-8'); } } redirect(url) { if (url instanceof URL) { url = url.href; } this.headers.set('location', url); if (!(statuses_default()).redirect[this.status]) { this.status = 302; } this.type = 'text/plain;charset=UTF-8'; this.body = `Redirecting to ${url}.`; } get type() { const type = this.headers.get('content-type'); if (!type) { return ''; } return type.split(';', 1)[0]; } set type(value) { this._implicitType = false; if (value) { this.headers.set('content-type', value); } else { this.headers.delete('content-type'); } } get lastModified() { const date = this.headers.get('last-modified'); return date ? new Date(date) : null; } set lastModified(value) { if (value === null) { this.headers.delete('last-modified'); return; } if (typeof value === 'string') { value = new Date(value); } this.headers.set('last-modified', value.toUTCString()); } get etag() { return this.headers.get('etag'); } set etag(value) { if (value) { if (!/^(W\/)?"/.test(value)) { value = `"${value}"`; } this.headers.set('etag', value); } else { this.headers.delete('etag'); } } create() { const { body: rawBody, status, statusText, headers } = this; const body = this._stringifyBody ? JSON.stringify(rawBody) : rawBody; return new Response(body, { status, statusText, headers }); } } ;// CONCATENATED MODULE: ./node_modules/@cfworker/web/dist/context.js class Context { constructor(event) { this.event = event; const request = event.request; this.req = new Req(request); this.res = new ResponseBuilder(); this.cookies = new Cookies(request.headers, this.res.headers); this.responded = new Promise(resolve => { this.respondWith = resolve; }); this.state = {}; } waitUntil(promise) { this.event.waitUntil(promise); } } /***/ }), /***/ 13515: /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "HttpError": () => (/* binding */ HttpError) /* harmony export */ }); /* harmony import */ var statuses__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54917); /* harmony import */ var statuses__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(statuses__WEBPACK_IMPORTED_MODULE_0__); class HttpError extends Error { constructor(status, body) { const statusText = (statuses__WEBPACK_IMPORTED_MODULE_0___default().message)[status]; super(statusText); this.name = this.constructor.name; if (typeof Error.captureStackTrace === 'function') { Error.captureStackTrace(this, this.constructor); } this.status = status; this.statusText = statusText; this.body = body; } toResponse() { let body = this.body || this.statusText; let contentType; if (typeof body === 'string') { contentType = 'text/plain'; } else { contentType = 'application/json'; body = JSON.stringify(body); } const { status, statusText } = this; const headers = { 'content-type': contentType }; return new Response(body, { status, statusText, headers }); } } /***/ }), /***/ 28599: /***/ ((module) => { "use strict"; /*globals self, window */ /*eslint-disable @mysticatea/prettier */ const { AbortController, AbortSignal } = typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : /* otherwise */ undefined /*eslint-enable @mysticatea/prettier */ module.exports = AbortController module.exports.AbortSignal = AbortSignal module.exports["default"] = AbortController /***/ }), /***/ 63367: /***/ ((module, exports, __webpack_require__) => { /* provided dependency */ var console = __webpack_require__(25108); var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_RESULT__;(function (factory) { true ? !(__WEBPACK_AMD_DEFINE_FACTORY__ = (factory), __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? (__WEBPACK_AMD_DEFINE_FACTORY__.call(exports, __webpack_require__, exports, module)) : __WEBPACK_AMD_DEFINE_FACTORY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)) : 0; }((function () { 'use strict'; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _possibleConstructorReturn(self, call) { if (call && (typeof call === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; } function _get(target, property, receiver) { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get; } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(receiver); } return desc.value; }; } return _get(target, property, receiver || target); } var Emitter = /*#__PURE__*/function () { function Emitter() { _classCallCheck(this, Emitter); Object.defineProperty(this, 'listeners', { value: {}, writable: true, configurable: true }); } _createClass(Emitter, [{ key: "addEventListener", value: function addEventListener(type, callback, options) { if (!(type in this.listeners)) { this.listeners[type] = []; } this.listeners[type].push({ callback: callback, options: options }); } }, { key: "removeEventListener", value: function removeEventListener(type, callback) { if (!(type in this.listeners)) { return; } var stack = this.listeners[type]; for (var i = 0, l = stack.length; i < l; i++) { if (stack[i].callback === callback) { stack.splice(i, 1); return; } } } }, { key: "dispatchEvent", value: function dispatchEvent(event) { if (!(event.type in this.listeners)) { return; } var stack = this.listeners[event.type]; var stackToCall = stack.slice(); for (var i = 0, l = stackToCall.length; i < l; i++) { var listener = stackToCall[i]; try { listener.callback.call(this, event); } catch (e) { Promise.resolve().then(function () { throw e; }); } if (listener.options && listener.options.once) { this.removeEventListener(event.type, listener.callback); } } return !event.defaultPrevented; } }]); return Emitter; }(); var AbortSignal = /*#__PURE__*/function (_Emitter) { _inherits(AbortSignal, _Emitter); var _super = _createSuper(AbortSignal); function AbortSignal() { var _this; _classCallCheck(this, AbortSignal); _this = _super.call(this); // Some versions of babel does not transpile super() correctly for IE <= 10, if the parent // constructor has failed to run, then "this.listeners" will still be undefined and then we call // the parent constructor directly instead as a workaround. For general details, see babel bug: // https://github.com/babel/babel/issues/3041 // This hack was added as a fix for the issue described here: // https://github.com/Financial-Times/polyfill-library/pull/59#issuecomment-477558042 if (!_this.listeners) { Emitter.call(_assertThisInitialized(_this)); } // Compared to assignment, Object.defineProperty makes properties non-enumerable by default and // we want Object.keys(new AbortController().signal) to be [] for compat with the native impl Object.defineProperty(_assertThisInitialized(_this), 'aborted', { value: false, writable: true, configurable: true }); Object.defineProperty(_assertThisInitialized(_this), 'onabort', { value: null, writable: true, configurable: true }); return _this; } _createClass(AbortSignal, [{ key: "toString", value: function toString() { return '[object AbortSignal]'; } }, { key: "dispatchEvent", value: function dispatchEvent(event) { if (event.type === 'abort') { this.aborted = true; if (typeof this.onabort === 'function') { this.onabort.call(this, event); } } _get(_getPrototypeOf(AbortSignal.prototype), "dispatchEvent", this).call(this, event); } }]); return AbortSignal; }(Emitter); var AbortController = /*#__PURE__*/function () { function AbortController() { _classCallCheck(this, AbortController); // Compared to assignment, Object.defineProperty makes properties non-enumerable by default and // we want Object.keys(new AbortController()) to be [] for compat with the native impl Object.defineProperty(this, 'signal', { value: new AbortSignal(), writable: true, configurable: true }); } _createClass(AbortController, [{ key: "abort", value: function abort() { var event; try { event = new Event('abort'); } catch (e) { if (typeof document !== 'undefined') { if (!document.createEvent) { // For Internet Explorer 8: event = document.createEventObject(); event.type = 'abort'; } else { // For Internet Explorer 11: event = document.createEvent('Event'); event.initEvent('abort', false, false); } } else { // Fallback where document isn't available: event = { type: 'abort', bubbles: false, cancelable: false }; } } this.signal.dispatchEvent(event); } }, { key: "toString", value: function toString() { return '[object AbortController]'; } }]); return AbortController; }(); if (typeof Symbol !== 'undefined' && Symbol.toStringTag) { // These are necessary to make sure that we get correct output for: // Object.prototype.toString.call(new AbortController()) AbortController.prototype[Symbol.toStringTag] = 'AbortController'; AbortSignal.prototype[Symbol.toStringTag] = 'AbortSignal'; } function polyfillNeeded(self) { if (self.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL) { console.log('__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill'); return true; } // Note that the "unfetch" minimal fetch polyfill defines fetch() without // defining window.Request, and this polyfill need to work on top of unfetch // so the below feature detection needs the !self.AbortController part. // The Request.prototype check is also needed because Safari versions 11.1.2 // up to and including 12.1.x has a window.AbortController present but still // does NOT correctly implement abortable fetch: // https://bugs.webkit.org/show_bug.cgi?id=174980#c2 return typeof self.Request === 'function' && !self.Request.prototype.hasOwnProperty('signal') || !self.AbortController; } /** * Note: the "fetch.Request" default value is available for fetch imported from * the "node-fetch" package and not in browsers. This is OK since browsers * will be importing umd-polyfill.js from that path "self" is passed the * decorator so the default value will not be used (because browsers that define * fetch also has Request). One quirky setup where self.fetch exists but * self.Request does not is when the "unfetch" minimal fetch polyfill is used * on top of IE11; for this case the browser will try to use the fetch.Request * default value which in turn will be undefined but then then "if (Request)" * will ensure that you get a patched fetch but still no Request (as expected). * @param {fetch, Request = fetch.Request} * @returns {fetch: abortableFetch, Request: AbortableRequest} */ function abortableFetchDecorator(patchTargets) { if ('function' === typeof patchTargets) { patchTargets = { fetch: patchTargets }; } var _patchTargets = patchTargets, fetch = _patchTargets.fetch, _patchTargets$Request = _patchTargets.Request, NativeRequest = _patchTargets$Request === void 0 ? fetch.Request : _patchTargets$Request, NativeAbortController = _patchTargets.AbortController, _patchTargets$__FORCE = _patchTargets.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL, __FORCE_INSTALL_ABORTCONTROLLER_POLYFILL = _patchTargets$__FORCE === void 0 ? false : _patchTargets$__FORCE; if (!polyfillNeeded({ fetch: fetch, Request: NativeRequest, AbortController: NativeAbortController, __FORCE_INSTALL_ABORTCONTROLLER_POLYFILL: __FORCE_INSTALL_ABORTCONTROLLER_POLYFILL })) { return { fetch: fetch, Request: Request }; } var Request = NativeRequest; // Note that the "unfetch" minimal fetch polyfill defines fetch() without // defining window.Request, and this polyfill need to work on top of unfetch // hence we only patch it if it's available. Also we don't patch it if signal // is already available on the Request prototype because in this case support // is present and the patching below can cause a crash since it assigns to // request.signal which is technically a read-only property. This latter error // happens when you run the main5.js node-fetch example in the repo // "abortcontroller-polyfill-examples". The exact error is: // request.signal = init.signal; // ^ // TypeError: Cannot set property signal of #<Request> which has only a getter if (Request && !Request.prototype.hasOwnProperty('signal') || __FORCE_INSTALL_ABORTCONTROLLER_POLYFILL) { Request = function Request(input, init) { var signal; if (init && init.signal) { signal = init.signal; // Never pass init.signal to the native Request implementation when the polyfill has // been installed because if we're running on top of a browser with a // working native AbortController (i.e. the polyfill was installed due to // __FORCE_INSTALL_ABORTCONTROLLER_POLYFILL being set), then passing our // fake AbortSignal to the native fetch will trigger: // TypeError: Failed to construct 'Request': member signal is not of type AbortSignal. delete init.signal; } var request = new NativeRequest(input, init); if (signal) { Object.defineProperty(request, 'signal', { writable: false, enumerable: false, configurable: true, value: signal }); } return request; }; Request.prototype = NativeRequest.prototype; } var realFetch = fetch; var abortableFetch = function abortableFetch(input, init) { var signal = Request && Request.prototype.isPrototypeOf(input) ? input.signal : init ? init.signal : undefined; if (signal) { var abortError; try { abortError = new DOMException('Aborted', 'AbortError'); } catch (err) { // IE 11 does not support calling the DOMException constructor, use a // regular error object on it instead. abortError = new Error('Aborted'); abortError.name = 'AbortError'; } // Return early if already aborted, thus avoiding making an HTTP request if (signal.aborted) { return Promise.reject(abortError); } // Turn an event into a promise, reject it once `abort` is dispatched var cancellation = new Promise(function (_, reject) { signal.addEventListener('abort', function () { return reject(abortError); }, { once: true }); }); if (init && init.signal) { // Never pass .signal to the native implementation when the polyfill has // been installed because if we're running on top of a browser with a // working native AbortController (i.e. the polyfill was installed due to // __FORCE_INSTALL_ABORTCONTROLLER_POLYFILL being set), then passing our // fake AbortSignal to the native fetch will trigger: // TypeError: Failed to execute 'fetch' on 'Window': member signal is not of type AbortSignal. delete init.signal; } // Return the fastest promise (don't need to wait for request to finish) return Promise.race([cancellation, realFetch(input, init)]); } return realFetch(input, init); }; return { fetch: abortableFetch, Request: Request }; } (function (self) { if (!polyfillNeeded(self)) { return; } if (!self.fetch) { console.warn('fetch() is not available, cannot install abortcontroller-polyfill'); return; } var _abortableFetch = abortableFetchDecorator(self), fetch = _abortableFetch.fetch, Request = _abortableFetch.Request; self.fetch = fetch; self.Request = Request; Object.defineProperty(self, 'AbortController', { writable: true, enumerable: false, configurable: true, value: AbortController }); Object.defineProperty(self, 'AbortSignal', { writable: true, enumerable: false, configurable: true, value: AbortSignal }); })(typeof self !== 'undefined' ? self : __webpack_require__.g); }))); /***/ }), /***/ 39809: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; const asn1 = exports; asn1.bignum = __webpack_require__(4590); asn1.define = (__webpack_require__(22500).define); asn1.base = __webpack_require__(71979); asn1.constants = __webpack_require__(36826); asn1.decoders = __webpack_require__(78307); asn1.encoders = __webpack_require__(56579); /***/ }), /***/ 22500: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; const encoders = __webpack_require__(56579); const decoders = __webpack_require__(78307); const inherits = __webpack_require__(35717); const api = exports; api.define = function define(name, body) { return new Entity(name, body); }; function Entity(name, body) { this.name = name; this.body = body; this.decoders = {}; this.encoders = {}; } Entity.prototype._createNamed = function createNamed(Base) { const name = this.name; function Generated(entity) { this._initNamed(entity, name); } inherits(Generated, Base); Generated.prototype._initNamed = function _initNamed(entity, name) { Base.call(this, entity, name); }; return new Generated(this); }; Entity.prototype._getDecoder = function _getDecoder(enc) { enc = enc || 'der'; // Lazily create decoder if (!this.decoders.hasOwnProperty(enc)) this.decoders[enc] = this._createNamed(decoders[enc]); return this.decoders[enc]; }; Entity.prototype.decode = function decode(data, enc, options) { return this._getDecoder(enc).decode(data, options); }; Entity.prototype._getEncoder = function _getEncoder(enc) { enc = enc || 'der'; // Lazily create encoder if (!this.encoders.hasOwnProperty(enc)) this.encoders[enc] = this._createNamed(encoders[enc]); return this.encoders[enc]; }; Entity.prototype.encode = function encode(data, enc, /* internal */ reporter) { return this._getEncoder(enc).encode(data, reporter); }; /***/ }), /***/ 36625: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; const inherits = __webpack_require__(35717); const Reporter = (__webpack_require__(98465)/* .Reporter */ .b); const Buffer = (__webpack_require__(2399).Buffer); function DecoderBuffer(base, options) { Reporter.call(this, options); if (!Buffer.isBuffer(base)) { this.error('Input not Buffer'); return; } this.base = base; this.offset = 0; this.length = base.length; } inherits(DecoderBuffer, Reporter); exports.C = DecoderBuffer; DecoderBuffer.isDecoderBuffer = function isDecoderBuffer(data) { if (data instanceof DecoderBuffer) { return true; } // Or accept compatible API const isCompatible = typeof data === 'object' && Buffer.isBuffer(data.base) && data.constructor.name === 'DecoderBuffer' && typeof data.offset === 'number' && typeof data.length === 'number' && typeof data.save === 'function' && typeof data.restore === 'function' && typeof data.isEmpty === 'function' && typeof data.readUInt8 === 'function' && typeof data.skip === 'function' && typeof data.raw === 'function'; return isCompatible; }; DecoderBuffer.prototype.save = function save() { return { offset: this.offset, reporter: Reporter.prototype.save.call(this) }; }; DecoderBuffer.prototype.restore = function restore(save) { // Return skipped data const res = new DecoderBuffer(this.base); res.offset = save.offset; res.length = this.offset; this.offset = save.offset; Reporter.prototype.restore.call(this, save.reporter); return res; }; DecoderBuffer.prototype.isEmpty = function isEmpty() { return this.offset === this.length; }; DecoderBuffer.prototype.readUInt8 = function readUInt8(fail) { if (this.offset + 1 <= this.length) return this.base.readUInt8(this.offset++, true); else return this.error(fail || 'DecoderBuffer overrun'); }; DecoderBuffer.prototype.skip = function skip(bytes, fail) { if (!(this.offset + bytes <= this.length)) return this.error(fail || 'DecoderBuffer overrun'); const res = new DecoderBuffer(this.base); // Share reporter state res._reporterState = this._reporterState; res.offset = this.offset; res.length = this.offset + bytes; this.offset += bytes; return res; }; DecoderBuffer.prototype.raw = function raw(save) { return this.base.slice(save ? save.offset : this.offset, this.length); }; function EncoderBuffer(value, reporter) { if (Array.isArray(value)) { this.length = 0; this.value = value.map(function(item) { if (!EncoderBuffer.isEncoderBuffer(item)) item = new EncoderBuffer(item, reporter); this.length += item.length; return item; }, this); } else if (typeof value === 'number') { if (!(0 <= value && value <= 0xff)) return reporter.error('non-byte EncoderBuffer value'); this.value = value; this.length = 1; } else if (typeof value === 'string') { this.value = value; this.length = Buffer.byteLength(value); } else if (Buffer.isBuffer(value)) { this.value = value; this.length = value.length; } else { return reporter.error('Unsupported type: ' + typeof value); } } exports.R = EncoderBuffer; EncoderBuffer.isEncoderBuffer = function isEncoderBuffer(data) { if (data instanceof EncoderBuffer) { return true; } // Or accept compatible API const isCompatible = typeof data === 'object' && data.constructor.name === 'EncoderBuffer' && typeof data.length === 'number' && typeof data.join === 'function'; return isCompatible; }; EncoderBuffer.prototype.join = function join(out, offset) { if (!out) out = Buffer.alloc(this.length); if (!offset) offset = 0; if (this.length === 0) return out; if (Array.isArray(this.value)) { this.value.forEach(function(item) { item.join(out, offset); offset += item.length; }); } else { if (typeof this.value === 'number') out[offset] = this.value; else if (typeof this.value === 'string') out.write(this.value, offset); else if (Buffer.isBuffer(this.value)) this.value.copy(out, offset); offset += this.length; } return out; }; /***/ }), /***/ 71979: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; const base = exports; base.Reporter = (__webpack_require__(98465)/* .Reporter */ .b); base.DecoderBuffer = (__webpack_require__(36625)/* .DecoderBuffer */ .C); base.EncoderBuffer = (__webpack_require__(36625)/* .EncoderBuffer */ .R); base.Node = __webpack_require__(41949); /***/ }), /***/ 41949: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; const Reporter = (__webpack_require__(98465)/* .Reporter */ .b); const EncoderBuffer = (__webpack_require__(36625)/* .EncoderBuffer */ .R); const DecoderBuffer = (__webpack_require__(36625)/* .DecoderBuffer */ .C); const assert = __webpack_require__(79746); // Supported tags const tags = [ 'seq', 'seqof', 'set', 'setof', 'objid', 'bool', 'gentime', 'utctime', 'null_', 'enum', 'int', 'objDesc', 'bitstr', 'bmpstr', 'charstr', 'genstr', 'graphstr', 'ia5str', 'iso646str', 'numstr', 'octstr', 'printstr', 't61str', 'unistr', 'utf8str', 'videostr' ]; // Public methods list const methods = [ 'key', 'obj', 'use', 'optional', 'explicit', 'implicit', 'def', 'choice', 'any', 'contains' ].concat(tags); // Overrided methods list const overrided = [ '_peekTag', '_decodeTag', '_use', '_decodeStr', '_decodeObjid', '_decodeTime', '_decodeNull', '_decodeInt', '_decodeBool', '_decodeList', '_encodeComposite', '_encodeStr', '_encodeObjid', '_encodeTime', '_encodeNull', '_encodeInt', '_encodeBool' ]; function Node(enc, parent, name) { const state = {}; this._baseState = state; state.name = name; state.enc = enc; state.parent = parent || null; state.children = null; // State state.tag = null; state.args = null; state.reverseArgs = null; state.choice = null; state.optional = false; state.any = false; state.obj = false; state.use = null; state.useDecoder = null; state.key = null; state['default'] = null; state.explicit = null; state.implicit = null; state.contains = null; // Should create new instance on each method if (!state.parent) { state.children = []; this._wrap(); } } module.exports = Node; const stateProps = [ 'enc', 'parent', 'children', 'tag', 'args', 'reverseArgs', 'choice', 'optional', 'any', 'obj', 'use', 'alteredUse', 'key', 'default', 'explicit', 'implicit', 'contains' ]; Node.prototype.clone = function clone() { const state = this._baseState; const cstate = {}; stateProps.forEach(function(prop) { cstate[prop] = state[prop]; }); const res = new this.constructor(cstate.parent); res._baseState = cstate; return res; }; Node.prototype._wrap = function wrap() { const state = this._baseState; methods.forEach(function(method) { this[method] = function _wrappedMethod() { const clone = new this.constructor(this); state.children.push(clone); return clone[method].apply(clone, arguments); }; }, this); }; Node.prototype._init = function init(body) { const state = this._baseState; assert(state.parent === null); body.call(this); // Filter children state.children = state.children.filter(function(child) { return child._baseState.parent === this; }, this); assert.equal(state.children.length, 1, 'Root node can have only one child'); }; Node.prototype._useArgs = function useArgs(args) { const state = this._baseState; // Filter children and args const children = args.filter(function(arg) { return arg instanceof this.constructor; }, this); args = args.filter(function(arg) { return !(arg instanceof this.constructor); }, this); if (children.length !== 0) { assert(state.children === null); state.children = children; // Replace parent to maintain backward link children.forEach(function(child) { child._baseState.parent = this; }, this); } if (args.length !== 0) { assert(state.args === null); state.args = args; state.reverseArgs = args.map(function(arg) { if (typeof arg !== 'object' || arg.constructor !== Object) return arg; const res = {}; Object.keys(arg).forEach(function(key) { if (key == (key | 0)) key |= 0; const value = arg[key]; res[value] = key; }); return res; }); } }; // // Overrided methods // overrided.forEach(function(method) { Node.prototype[method] = function _overrided() { const state = this._baseState; throw new Error(method + ' not implemented for encoding: ' + state.enc); }; }); // // Public methods // tags.forEach(function(tag) { Node.prototype[tag] = function _tagMethod() { const state = this._baseState; const args = Array.prototype.slice.call(arguments); assert(state.tag === null); state.tag = tag; this._useArgs(args); return this; }; }); Node.prototype.use = function use(item) { assert(item); const state = this._baseState; assert(state.use === null); state.use = item; return this; }; Node.prototype.optional = function optional() { const state = this._baseState; state.optional = true; return this; }; Node.prototype.def = function def(val) { const state = this._baseState; assert(state['default'] === null); state['default'] = val; state.optional = true; return this; }; Node.prototype.explicit = function explicit(num) { const state = this._baseState; assert(state.explicit === null && state.implicit === null); state.explicit = num; return this; }; Node.prototype.implicit = function implicit(num) { const state = this._baseState; assert(state.explicit === null && state.implicit === null); state.implicit = num; return this; }; Node.prototype.obj = function obj() { const state = this._baseState; const args = Array.prototype.slice.call(arguments); state.obj = true; if (args.length !== 0) this._useArgs(args); return this; }; Node.prototype.key = function key(newKey) { const state = this._baseState; assert(state.key === null); state.key = newKey; return this; }; Node.prototype.any = function any() { const state = this._baseState; state.any = true; return this; }; Node.prototype.choice = function choice(obj) { const state = this._baseState; assert(state.choice === null); state.choice = obj; this._useArgs(Object.keys(obj).map(function(key) { return obj[key]; })); return this; }; Node.prototype.contains = function contains(item) { const state = this._baseState; assert(state.use === null); state.contains = item; return this; }; // // Decoding // Node.prototype._decode = function decode(input, options) { const state = this._baseState; // Decode root node if (state.parent === null) return input.wrapResult(state.children[0]._decode(input, options)); let result = state['default']; let present = true; let prevKey = null; if (state.key !== null) prevKey = input.enterKey(state.key); // Check if tag is there if (state.optional) { let tag = null; if (state.explicit !== null) tag = state.explicit; else if (state.implicit !== null) tag = state.implicit; else if (state.tag !== null) tag = state.tag; if (tag === null && !state.any) { // Trial and Error const save = input.save(); try { if (state.choice === null) this._decodeGeneric(state.tag, input, options); else this._decodeChoice(input, options); present = true; } catch (e) { present = false; } input.restore(save); } else { present = this._peekTag(input, tag, state.any); if (input.isError(present)) return present; } } // Push object on stack let prevObj; if (state.obj && present) prevObj = input.enterObject(); if (present) { // Unwrap explicit values if (state.explicit !== null) { const explicit = this._decodeTag(input, state.explicit); if (input.isError(explicit)) return explicit; input = explicit; } const start = input.offset; // Unwrap implicit and normal values if (state.use === null && state.choice === null) { let save; if (state.any) save = input.save(); const body = this._decodeTag( input, state.implicit !== null ? state.implicit : state.tag, state.any ); if (input.isError(body)) return body; if (state.any) result = input.raw(save); else input = body; } if (options && options.track && state.tag !== null) options.track(input.path(), start, input.length, 'tagged'); if (options && options.track && state.tag !== null) options.track(input.path(), input.offset, input.length, 'content'); // Select proper method for tag if (state.any) { // no-op } else if (state.choice === null) { result = this._decodeGeneric(state.tag, input, options); } else { result = this._decodeChoice(input, options); } if (input.isError(result)) return result; // Decode children if (!state.any && state.choice === null && state.children !== null) { state.children.forEach(function decodeChildren(child) { // NOTE: We are ignoring errors here, to let parser continue with other // parts of encoded data child._decode(input, options); }); } // Decode contained/encoded by schema, only in bit or octet strings if (state.contains && (state.tag === 'octstr' || state.tag === 'bitstr')) { const data = new DecoderBuffer(result); result = this._getUse(state.contains, input._reporterState.obj) ._decode(data, options); } } // Pop object if (state.obj && present) result = input.leaveObject(prevObj); // Set key if (state.key !== null && (result !== null || present === true)) input.leaveKey(prevKey, state.key, result); else if (prevKey !== null) input.exitKey(prevKey); return result; }; Node.prototype._decodeGeneric = function decodeGeneric(tag, input, options) { const state = this._baseState; if (tag === 'seq' || tag === 'set') return null; if (tag === 'seqof' || tag === 'setof') return this._decodeList(input, tag, state.args[0], options); else if (/str$/.test(tag)) return this._decodeStr(input, tag, options); else if (tag === 'objid' && state.args) return this._decodeObjid(input, state.args[0], state.args[1], options); else if (tag === 'objid') return this._decodeObjid(input, null, null, options); else if (tag === 'gentime' || tag === 'utctime') return this._decodeTime(input, tag, options); else if (tag === 'null_') return this._decodeNull(input, options); else if (tag === 'bool') return this._decodeBool(input, options); else if (tag === 'objDesc') return this._decodeStr(input, tag, options); else if (tag === 'int' || tag === 'enum') return this._decodeInt(input, state.args && state.args[0], options); if (state.use !== null) { return this._getUse(state.use, input._reporterState.obj) ._decode(input, options); } else { return input.error('unknown tag: ' + tag); } }; Node.prototype._getUse = function _getUse(entity, obj) { const state = this._baseState; // Create altered use decoder if implicit is set state.useDecoder = this._use(entity, obj); assert(state.useDecoder._baseState.parent === null); state.useDecoder = state.useDecoder._baseState.children[0]; if (state.implicit !== state.useDecoder._baseState.implicit) { state.useDecoder = state.useDecoder.clone(); state.useDecoder._baseState.implicit = state.implicit; } return state.useDecoder; }; Node.prototype._decodeChoice = function decodeChoice(input, options) { const state = this._baseState; let result = null; let match = false; Object.keys(state.choice).some(function(key) { const save = input.save(); const node = state.choice[key]; try { const value = node._decode(input, options); if (input.isError(value)) return false; result = { type: key, value: value }; match = true; } catch (e) { input.restore(save); return false; } return true; }, this); if (!match) return input.error('Choice not matched'); return result; }; // // Encoding // Node.prototype._createEncoderBuffer = function createEncoderBuffer(data) { return new EncoderBuffer(data, this.reporter); }; Node.prototype._encode = function encode(data, reporter, parent) { const state = this._baseState; if (state['default'] !== null && state['default'] === data) return; const result = this._encodeValue(data, reporter, parent); if (result === undefined) return; if (this._skipDefault(result, reporter, parent)) return; return result; }; Node.prototype._encodeValue = function encode(data, reporter, parent) { const state = this._baseState; // Decode root node if (state.parent === null) return state.children[0]._encode(data, reporter || new Reporter()); let result = null; // Set reporter to share it with a child class this.reporter = reporter; // Check if data is there if (state.optional && data === undefined) { if (state['default'] !== null) data = state['default']; else return; } // Encode children first let content = null; let primitive = false; if (state.any) { // Anything that was given is translated to buffer result = this._createEncoderBuffer(data); } else if (state.choice) { result = this._encodeChoice(data, reporter); } else if (state.contains) { content = this._getUse(state.contains, parent)._encode(data, reporter); primitive = true; } else if (state.children) { content = state.children.map(function(child) { if (child._baseState.tag === 'null_') return child._encode(null, reporter, data); if (child._baseState.key === null) return repo