Best JavaScript code snippet using playwright-internal
index.js
Source:index.js
...1722//# sourceMappingURL=proxy.js.map1723/***/ }),1724/***/ 308:1725/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {1726(()=>{"use strict";var e={3497:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:true});t.isExternalAccount=t.isServiceAccountKey=t.parseCredential=void 0;const s=n(6976);const i=n(3102);function parseCredential(e){e=(e||"").trim();if(!e){throw new Error(`Missing service account key JSON (got empty value)`)}if(!e.startsWith("{")){e=(0,i.fromBase64)(e)}try{const t=JSON.parse(e);return t}catch(e){const t=(0,s.errorMessage)(e);throw new SyntaxError(`Failed to parse service account key JSON credentials: ${t}`)}}t.parseCredential=parseCredential;function isServiceAccountKey(e){return e.type==="service_account"}t.isServiceAccountKey=isServiceAccountKey;function isExternalAccount(e){return e.type!=="external_account"}t.isExternalAccount=isExternalAccount;t["default"]={parseCredential:parseCredential,isServiceAccountKey:isServiceAccountKey,isExternalAccount:isExternalAccount}},1848:function(e,t,n){var s=this&&this.__createBinding||(Object.create?function(e,t,n,s){if(s===undefined)s=n;var i=Object.getOwnPropertyDescriptor(t,n);if(!i||("get"in i?!t.__esModule:i.writable||i.configurable)){i={enumerable:true,get:function(){return t[n]}}}Object.defineProperty(e,s,i)}:function(e,t,n,s){if(s===undefined)s=n;e[s]=t[n]});var i=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:true,value:t})}:function(e,t){e["default"]=t});var r=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var n in e)if(n!=="default"&&Object.prototype.hasOwnProperty.call(e,n))s(t,e,n);i(t,e);return t};Object.defineProperty(t,"__esModule",{value:true});t.deepClone=void 0;const o=r(n(4655));function deepClone(e,t=true){if(t&&typeof structuredClone==="function"){return structuredClone(e)}return o.deserialize(o.serialize(e))}t.deepClone=deepClone},7962:(e,t)=>{Object.defineProperty(t,"__esModule",{value:true});t.parseCSV=void 0;function parseCSV(e){e=(e||"").trim();if(!e){return[]}const t=e.split(/(?<!\\),/gi);for(let e=0;e<t.length;e++){t[e]=t[e].trim().replace(/\\,/gi,",")}return t}t.parseCSV=parseCSV},3102:(e,t)=>{Object.defineProperty(t,"__esModule",{value:true});t.fromBase64=t.toBase64=void 0;function toBase64(e){return Buffer.from(e).toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}t.toBase64=toBase64;function fromBase64(e){let t=e.replace(/-/g,"+").replace(/_/g,"/");while(t.length%4)t+="=";return Buffer.from(t,"base64").toString("utf8")}t.fromBase64=fromBase64},6976:(e,t)=>{Object.defineProperty(t,"__esModule",{value:true});t.isNotFoundError=t.errorMessage=void 0;function errorMessage(e){let t;if(e===null){t="null"}else if(e===undefined||typeof e==="undefined"){t="undefined"}else if(typeof e==="bigint"||e instanceof BigInt){t=e.toString()}else if(typeof e==="boolean"||e instanceof Boolean){t=e.toString()}else if(e instanceof Error){t=e.message}else if(typeof e==="function"||e instanceof Function){t=errorMessage(e())}else if(typeof e==="number"||e instanceof Number){t=e.toString()}else if(typeof e==="string"||e instanceof String){t=e.toString()}else if(typeof e==="symbol"||e instanceof Symbol){t=e.toString()}else if(typeof e==="object"||e instanceof Object){t=JSON.stringify(e)}else{t=String(`[${typeof e}] ${e}`)}const n=t.trim().replace("Error: ","").trim();if(!n)return"";if(n.length>1&&isUpper(n[0])&&!isUpper(n[1])){return n[0].toLowerCase()+n.slice(1)}return n}t.errorMessage=errorMessage;function isNotFoundError(e){const t=errorMessage(e);return t.toUpperCase().includes("ENOENT")}t.isNotFoundError=isNotFoundError;function isUpper(e){return e===e.toUpperCase()}},3252:(e,t)=>{Object.defineProperty(t,"__esModule",{value:true});t.readUntil=t.parseFlags=void 0;function parseFlags(e){const t=[];let n="";let s=false;for(let i=0;i<e.length;i++){const r=e[i];if(r===`'`){const t=readUntil(e.slice(i+1),`'`);if(t===null){throw new Error(`Unterminated single quote in ${e} at position ${i}`)}n+=r+t;i+=t.length;continue}if(r===`"`){const t=readUntil(e.slice(i+1),`"`);if(t===null){throw new Error(`Unterminated double quote in ${e} at position ${i}`)}n+=r+t;i+=t.length;continue}if(r==="\r"||r===`\n`||r===` `){s=false;if(n!==``){t.push(n);n=``}continue}if(r===`=`){if(!s&&n[0]===`-`){t.push(n);n=``;s=true;continue}}n+=r}if(n!==""){t.push(n)}return t}t.parseFlags=parseFlags;function readUntil(e,t){let n=false;let s="";for(let i=0;i<e.length;i++){const r=e[i];s+=r;if(r===`\\`){n=true;continue}if(r===t&&!n){return s}n=false}return null}t.readUntil=readUntil},9219:function(e,t,n){var s=this&&this.__awaiter||function(e,t,n,s){function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}return new(n||(n=Promise))((function(n,i){function fulfilled(e){try{step(s.next(e))}catch(e){i(e)}}function rejected(e){try{step(s["throw"](e))}catch(e){i(e)}}function step(e){e.done?n(e.value):adopt(e.value).then(fulfilled,rejected)}step((s=s.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:true});t.removeFile=t.writeSecureFile=t.isEmptyDir=t.forceRemove=void 0;const i=n(7147);const r=n(6976);function forceRemove(e){return s(this,void 0,void 0,(function*(){try{yield i.promises.rm(e,{force:true,recursive:true})}catch(t){if(!(0,r.isNotFoundError)(t)){const n=(0,r.errorMessage)(t);throw new Error(`Failed to remove "${e}": ${n}`)}}}))}t.forceRemove=forceRemove;function isEmptyDir(e){return s(this,void 0,void 0,(function*(){try{const t=yield i.promises.readdir(e);return t.length<=0}catch(e){return true}}))}t.isEmptyDir=isEmptyDir;function writeSecureFile(e,t){return s(this,void 0,void 0,(function*(){yield i.promises.writeFile(e,t,{mode:416,flag:"wx"});return e}))}t.writeSecureFile=writeSecureFile;function removeFile(e){return s(this,void 0,void 0,(function*(){try{yield i.promises.unlink(e);return true}catch(t){if((0,r.isNotFoundError)(t)){return false}const n=(0,r.errorMessage)(t);throw new Error(`Failed to remove "${e}": ${n}`)}}))}t.removeFile=removeFile},546:function(e,t,n){var s=this&&this.__awaiter||function(e,t,n,s){function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}return new(n||(n=Promise))((function(n,i){function fulfilled(e){try{step(s.next(e))}catch(e){i(e)}}function rejected(e){try{step(s["throw"](e))}catch(e){i(e)}}function step(e){e.done?n(e.value):adopt(e.value).then(fulfilled,rejected)}step((s=s.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:true});t.parseGcloudIgnore=void 0;const i=n(7147);const r=n(1017);const o=n(6976);function parseGcloudIgnore(e){return s(this,void 0,void 0,(function*(){const t=(0,r.dirname)(e);let n=[];try{n=(yield i.promises.readFile(e,{encoding:"utf-8"})).toString().split(/\r?\n/).filter(shouldKeepIgnoreLine).map((e=>e.trim()))}catch(e){if(!(0,o.isNotFoundError)(e)){throw e}}for(let e=0;e<n.length;e++){const s=n[e];if(s.startsWith("#!include:")){const o=s.substring(10).trim();const a=(0,r.join)(t,o);const c=(yield i.promises.readFile(a,{encoding:"utf-8"})).toString().split(/\r?\n/).filter(shouldKeepIgnoreLine).map((e=>e.trim()));n.splice(e,1,...c);e+=c.length}}return n}))}t.parseGcloudIgnore=parseGcloudIgnore;function shouldKeepIgnoreLine(e){const t=(e||"").trim();if(t===""){return false}if(t.startsWith("#")&&!t.startsWith("#!")){return false}return true}},6144:function(e,t,n){var s=this&&this.__createBinding||(Object.create?function(e,t,n,s){if(s===undefined)s=n;var i=Object.getOwnPropertyDescriptor(t,n);if(!i||("get"in i?!t.__esModule:i.writable||i.configurable)){i={enumerable:true,get:function(){return t[n]}}}Object.defineProperty(e,s,i)}:function(e,t,n,s){if(s===undefined)s=n;e[s]=t[n]});var i=this&&this.__exportStar||function(e,t){for(var n in e)if(n!=="default"&&!Object.prototype.hasOwnProperty.call(t,n))s(t,e,n)};Object.defineProperty(t,"__esModule",{value:true});i(n(3497),t);i(n(1848),t);i(n(7962),t);i(n(3102),t);i(n(6976),t);i(n(3252),t);i(n(9219),t);i(n(546),t);i(n(575),t);i(n(9497),t);i(n(5737),t);i(n(570),t);i(n(1043),t);i(n(9017),t);i(n(7575),t);i(n(596),t);i(n(9324),t)},575:function(e,t,n){var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:true});t.parseKVStringAndFile=t.parseKVYAML=t.parseKVJSON=t.parseKVFile=t.parseKVString=void 0;const i=s(n(4083));const r=n(7147);const o=n(6976);function parseKVString(e){e=(e||"").trim();if(!e){return{}}const t={};const n=e.split(/(?<!\\)[,\n]/gi);for(let e=0;e<n.length;e++){const s=(n[e]||"").trim();if(!s){continue}const i=s.indexOf("=");if(!i||i===-1){throw new SyntaxError(`Failed to parse KEY=VALUE pair "${s}": missing "="`)}const r=s.slice(0,i).trim().replace(/\\([,\n])/gi,"$1");const o=s.slice(i+1).trim().replace(/\\([,\n])/gi,"$1");if(!r||!o){throw new SyntaxError(`Failed to parse KEY=VALUE pair "${s}": no value`)}t[r]=o}return t}t.parseKVString=parseKVString;function parseKVFile(e){try{const t=(0,r.readFileSync)(e,"utf-8");if(t&&t.trim()&&t.trim()[0]==="{"){return parseKVJSON(t)}return parseKVYAML(t)}catch(t){const n=(0,o.errorMessage)(t);throw new Error(`Failed to read file '${e}': ${n}`)}}t.parseKVFile=parseKVFile;function parseKVJSON(e){e=(e||"").trim();if(!e){return{}}try{const t=JSON.parse(e);const n={};for(const[e,s]of Object.entries(t)){if(typeof e!=="string"){throw new SyntaxError(`Failed to parse key "${e}", expected string, got ${typeof e}`)}if(e.trim()===""){throw new SyntaxError(`Failed to parse key "${e}", expected at least one character`)}if(typeof s!=="string"){const t=JSON.stringify(s);throw new SyntaxError(`Failed to parse value "${t}" for "${e}", expected string, got ${typeof s}`)}if(s.trim()===""){throw new SyntaxError(`Value for key "${e}" cannot be empty (got "${s}")`)}n[e]=s}return n}catch(e){const t=(0,o.errorMessage)(e);throw new Error(`Failed to parse KV pairs as JSON: ${t}`)}}t.parseKVJSON=parseKVJSON;function parseKVYAML(e){if(!e||e.trim().length===0){return{}}const t=i.default.parse(e);const n={};for(const[e,s]of Object.entries(t)){if(typeof e!=="string"||typeof s!=="string"){throw new SyntaxError(`env_vars_file must contain only KEY: VALUE strings. Error parsing key ${e} of type ${typeof e} with value ${s} of type ${typeof s}`)}n[e.trim()]=s.trim()}return n}t.parseKVYAML=parseKVYAML;function parseKVStringAndFile(e,t){e=(e||"").trim();t=(t||"").trim();let n={};if(t){const e=parseKVFile(t);n=Object.assign(Object.assign({},n),e)}if(e){const t=parseKVString(e);n=Object.assign(Object.assign({},n),t)}return n}t.parseKVStringAndFile=parseKVStringAndFile},9497:function(e,t,n){var s=this&&this.__awaiter||function(e,t,n,s){function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}return new(n||(n=Promise))((function(n,i){function fulfilled(e){try{step(s.next(e))}catch(e){i(e)}}function rejected(e){try{step(s["throw"](e))}catch(e){i(e)}}function step(e){e.done?n(e.value):adopt(e.value).then(fulfilled,rejected)}step((s=s.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:true});t.inParallel=void 0;const i=n(2037);function inParallel(e,t,n){return s(this,void 0,void 0,(function*(){const r=Math.min((n===null||n===void 0?void 0:n.concurrency)||(0,i.cpus)().length-1);if(r<1){throw new Error(`concurrency must be at least 1`)}const o=t.map(((e,t)=>({args:e,idx:t})));const a=new Array(t.length);const c=new Array(r).fill(Promise.resolve());const sub=t=>s(this,void 0,void 0,(function*(){const n=o.pop();if(n===undefined){return t}yield t;const s=e.apply(e,n.args);s.then((e=>{a[n.idx]=e}));return sub(s)}));yield Promise.all(c.map(sub));return a}))}t.inParallel=inParallel},5737:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:true});t.toPlatformPath=t.toWin32Path=t.toPosixPath=void 0;const s=n(1017);function toPosixPath(e){return e.replace(/[\\]/g,"/")}t.toPosixPath=toPosixPath;function toWin32Path(e){return e.replace(/[/]/g,"\\")}t.toWin32Path=toWin32Path;function toPlatformPath(e){return e.replace(/[/\\]/g,s.sep)}t.toPlatformPath=toPlatformPath},570:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:true});t.randomFilepath=t.randomFilename=void 0;const s=n(1017);const i=n(6113);const r=n(2037);function randomFilename(e=12){return(0,i.randomBytes)(e).toString("hex")}t.randomFilename=randomFilename;function randomFilepath(e=(0,r.tmpdir)(),t=12){return(0,s.join)(e,randomFilename(t))}t.randomFilepath=randomFilepath;t["default"]={randomFilename:randomFilename,randomFilepath:randomFilepath}},1043:function(e,t,n){var s=this&&this.__awaiter||function(e,t,n,s){function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}return new(n||(n=Promise))((function(n,i){function fulfilled(e){try{step(s.next(e))}catch(e){i(e)}}function rejected(e){try{step(s["throw"](e))}catch(e){i(e)}}function step(e){e.done?n(e.value):adopt(e.value).then(fulfilled,rejected)}step((s=s.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:true});t.withRetries=void 0;const i=n(6976);const r=n(7575);const o=100;function withRetries(e,t){var n;const a=t.retries;const c=typeof(t===null||t===void 0?void 0:t.backoffLimit)!=="undefined"?Math.max(t.backoffLimit,0):undefined;let l=(n=t.backoff)!==null&&n!==void 0?n:o;if(typeof c!=="undefined"){l=Math.min(l,c)}return function(){return s(this,void 0,void 0,(function*(){let n=a+1;let s=l;const o=c;let f=0;let u="unknown";do{try{return yield e()}catch(e){u=(0,i.errorMessage)(e);--n;if(n>0){yield(0,r.sleep)(s);let e=f+s;if(typeof o!=="undefined"){e=Math.min(e,Number(o))}f=s;s=e}}}while(n>0);const d=t.retries+1;const h=d===1?`1 attempt`:`${d} attempts`;throw new Error(`retry function failed after ${h}: ${u}`)}))}}t.withRetries=withRetries},9017:(e,t)=>{Object.defineProperty(t,"__esModule",{value:true});t.clearEnv=t.clearInputs=t.setInputs=t.setInput=void 0;function setInput(e,t){const n=`INPUT_${e.replace(/ /g,"_").toUpperCase()}`;process.env[n]=t}t.setInput=setInput;function setInputs(e){Object.entries(e).forEach((([e,t])=>setInput(e,t)))}t.setInputs=setInputs;function clearInputs(){clearEnv((e=>e.startsWith(`INPUT_`)))}t.clearInputs=clearInputs;function clearEnv(e){Object.keys(process.env).forEach((t=>{if(e(t,process.env[t])){delete process.env[t]}}))}t.clearEnv=clearEnv},7575:function(e,t){var n=this&&this.__awaiter||function(e,t,n,s){function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}return new(n||(n=Promise))((function(n,i){function fulfilled(e){try{step(s.next(e))}catch(e){i(e)}}function rejected(e){try{step(s["throw"](e))}catch(e){i(e)}}function step(e){e.done?n(e.value):adopt(e.value).then(fulfilled,rejected)}step((s=s.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:true});t.sleep=t.parseDuration=void 0;function parseDuration(e){e=(e||"").trim();if(!e){return 0}let t=0;let n="";for(let s=0;s<e.length;s++){const i=e[s];switch(i){case" ":continue;case",":continue;case"s":{t+=+n;n="";break}case"m":{t+=+n*60;n="";break}case"h":{t+=+n*60*60;n="";break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":n+=i;break;default:throw new SyntaxError(`Unsupported character "${i}" at position ${s}`)}}if(n){t+=+n}return t}t.parseDuration=parseDuration;function sleep(e=0){return n(this,void 0,void 0,(function*(){return new Promise((t=>setTimeout(t,e)))}))}t.sleep=sleep},596:(e,t)=>{Object.defineProperty(t,"__esModule",{value:true});t.allOf=t.exactlyOneOf=t.presence=void 0;function presence(e){return(e||"").trim()||undefined}t.presence=presence;function exactlyOneOf(...e){e=e||[];let t=false;for(let n=0;n<e.length;n++){if(e[n]){if(t){return false}else{t=true}}}if(!t){return false}return true}t.exactlyOneOf=exactlyOneOf;function allOf(...e){e=e||[];for(let t=0;t<e.length;t++){if(!e[t])return false}return true}t.allOf=allOf},9324:(e,t)=>{Object.defineProperty(t,"__esModule",{value:true});t.pinnedToHeadWarning=t.isPinnedToHead=void 0;function isPinnedToHead(){const e=process.env.GITHUB_ACTION_REF;return e==="master"||e==="main"}t.isPinnedToHead=isPinnedToHead;function pinnedToHeadWarning(e){const t=process.env.GITHUB_ACTION_REF;const n=process.env.GITHUB_ACTION_REPOSITORY;return`${n} is pinned at "${t}". We strongly advise against `+`pinning to "@${t}" as it may be unstable. Please update your `+`GitHub Action YAML from:\n`+`\n`+` uses: '${n}@${t}'\n`+`\n`+`to:\n`+`\n`+` uses: '${n}@${e}'\n`+`\n`+`Alternatively, you can pin to any git tag or git SHA in the repository.`}t.pinnedToHeadWarning=pinnedToHeadWarning},6113:e=>{e.exports=__nccwpck_require__(6113)},7147:e=>{e.exports=__nccwpck_require__(7147)},2037:e=>{e.exports=__nccwpck_require__(2037)},1017:e=>{e.exports=__nccwpck_require__(1017)},4655:e=>{e.exports=__nccwpck_require__(4655)},8109:(e,t,n)=>{var s=n(1399);var i=n(9338);var r=n(2986);var o=n(2289);var a=n(45);function composeCollection(e,t,n,c,l){let f;switch(n.type){case"block-map":{f=r.resolveBlockMap(e,t,n,l);break}case"block-seq":{f=o.resolveBlockSeq(e,t,n,l);break}case"flow-collection":{f=a.resolveFlowCollection(e,t,n,l);break}}if(!c)return f;const u=t.directives.tagName(c.source,(e=>l(c,"TAG_RESOLVE_FAILED",e)));if(!u)return f;const d=f.constructor;if(u==="!"||u===d.tagName){f.tag=d.tagName;return f}const h=s.isMap(f)?"map":"seq";let p=t.schema.tags.find((e=>e.collection===h&&e.tag===u));if(!p){const e=t.schema.knownTags[u];if(e&&e.collection===h){t.schema.tags.push(Object.assign({},e,{default:false}));p=e}else{l(c,"TAG_RESOLVE_FAILED",`Unresolved tag: ${u}`,true);f.tag=u;return f}}const m=p.resolve(f,(e=>l(c,"TAG_RESOLVE_FAILED",e)),t.options);const y=s.isNode(m)?m:new i.Scalar(m);y.range=f.range;y.tag=u;if(p?.format)y.format=p.format;return y}t.composeCollection=composeCollection},5050:(e,t,n)=>{var s=n(42);var i=n(8676);var r=n(1250);var o=n(6985);function composeDoc(e,t,{offset:n,start:a,value:c,end:l},f){const u=Object.assign({_directives:t},e);const d=new s.Document(undefined,u);const h={atRoot:true,directives:d.directives,options:d.options,schema:d.schema};const p=o.resolveProps(a,{indicator:"doc-start",next:c??l?.[0],offset:n,onError:f,startOnNewline:true});if(p.found){d.directives.docStart=true;if(c&&(c.type==="block-map"||c.type==="block-seq")&&!p.hasNewline)f(p.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")}d.contents=c?i.composeNode(h,c,p,f):i.composeEmptyNode(h,p.end,a,null,p,f);const m=d.contents.range[2];const y=r.resolveEnd(l,m,false,f);if(y.comment)d.comment=y.comment;d.range=[n,m,y.offset];return d}t.composeDoc=composeDoc},8676:(e,t,n)=>{var s=n(5639);var i=n(8109);var r=n(4766);var o=n(1250);var a=n(8781);const c={composeNode:composeNode,composeEmptyNode:composeEmptyNode};function composeNode(e,t,n,s){const{spaceBefore:o,comment:a,anchor:l,tag:f}=n;let u;let d=true;switch(t.type){case"alias":u=composeAlias(e,t,s);if(l||f)s(t,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":u=r.composeScalar(e,t,f,s);if(l)u.anchor=l.source.substring(1);break;case"block-map":case"block-seq":case"flow-collection":u=i.composeCollection(c,e,t,f,s);if(l)u.anchor=l.source.substring(1);break;default:{const i=t.type==="error"?t.message:`Unsupported token (type: ${t.type})`;s(t,"UNEXPECTED_TOKEN",i);u=composeEmptyNode(e,t.offset,undefined,null,n,s);d=false}}if(l&&u.anchor==="")s(l,"BAD_ALIAS","Anchor cannot be an empty string");if(o)u.spaceBefore=true;if(a){if(t.type==="scalar"&&t.source==="")u.comment=a;else u.commentBefore=a}if(e.options.keepSourceTokens&&d)u.srcToken=t;return u}function composeEmptyNode(e,t,n,s,{spaceBefore:i,comment:o,anchor:c,tag:l,end:f},u){const d={type:"scalar",offset:a.emptyScalarPosition(t,n,s),indent:-1,source:""};const h=r.composeScalar(e,d,l,u);if(c){h.anchor=c.source.substring(1);if(h.anchor==="")u(c,"BAD_ALIAS","Anchor cannot be an empty string")}if(i)h.spaceBefore=true;if(o){h.comment=o;h.range[2]=f}return h}function composeAlias({options:e},{offset:t,source:n,end:i},r){const a=new s.Alias(n.substring(1));if(a.source==="")r(t,"BAD_ALIAS","Alias cannot be an empty string");if(a.source.endsWith(":"))r(t+n.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",true);const c=t+n.length;const l=o.resolveEnd(i,c,e.strict,r);a.range=[t,c,l.offset];if(l.comment)a.comment=l.comment;return a}t.composeEmptyNode=composeEmptyNode;t.composeNode=composeNode},4766:(e,t,n)=>{var s=n(1399);var i=n(9338);var r=n(9485);var o=n(7578);function composeScalar(e,t,n,a){const{value:c,type:l,comment:f,range:u}=t.type==="block-scalar"?r.resolveBlockScalar(t,e.options.strict,a):o.resolveFlowScalar(t,e.options.strict,a);const d=n?e.directives.tagName(n.source,(e=>a(n,"TAG_RESOLVE_FAILED",e))):null;const h=n&&d?findScalarTagByName(e.schema,c,d,n,a):t.type==="scalar"?findScalarTagByTest(e,c,t,a):e.schema[s.SCALAR];let p;try{const r=h.resolve(c,(e=>a(n??t,"TAG_RESOLVE_FAILED",e)),e.options);p=s.isScalar(r)?r:new i.Scalar(r)}catch(e){const s=e instanceof Error?e.message:String(e);a(n??t,"TAG_RESOLVE_FAILED",s);p=new i.Scalar(c)}p.range=u;p.source=c;if(l)p.type=l;if(d)p.tag=d;if(h.format)p.format=h.format;if(f)p.comment=f;return p}function findScalarTagByName(e,t,n,i,r){if(n==="!")return e[s.SCALAR];const o=[];for(const t of e.tags){if(!t.collection&&t.tag===n){if(t.default&&t.test)o.push(t);else return t}}for(const e of o)if(e.test?.test(t))return e;const a=e.knownTags[n];if(a&&!a.collection){e.tags.push(Object.assign({},a,{default:false,test:undefined}));return a}r(i,"TAG_RESOLVE_FAILED",`Unresolved tag: ${n}`,n!=="tag:yaml.org,2002:str");return e[s.SCALAR]}function findScalarTagByTest({directives:e,schema:t},n,i,r){const o=t.tags.find((e=>e.default&&e.test?.test(n)))||t[s.SCALAR];if(t.compat){const a=t.compat.find((e=>e.default&&e.test?.test(n)))??t[s.SCALAR];if(o.tag!==a.tag){const t=e.tagString(o.tag);const n=e.tagString(a.tag);const s=`Value may be parsed as either ${t} or ${n}`;r(i,"TAG_RESOLVE_FAILED",s,true)}}return o}t.composeScalar=composeScalar},9493:(e,t,n)=>{var s=n(5400);var i=n(42);var r=n(4236);var o=n(1399);var a=n(5050);var c=n(1250);function getErrorPos(e){if(typeof e==="number")return[e,e+1];if(Array.isArray(e))return e.length===2?e:[e[0],e[1]];const{offset:t,source:n}=e;return[t,t+(typeof n==="string"?n.length:1)]}function parsePrelude(e){let t="";let n=false;let s=false;for(let i=0;i<e.length;++i){const r=e[i];switch(r[0]){case"#":t+=(t===""?"":s?"\n\n":"\n")+(r.substring(1)||" ");n=true;s=false;break;case"%":if(e[i+1]?.[0]!=="#")i+=1;n=false;break;default:if(!n)s=true;n=false}}return{comment:t,afterEmptyLine:s}}class Composer{constructor(e={}){this.doc=null;this.atDirectives=false;this.prelude=[];this.errors=[];this.warnings=[];this.onError=(e,t,n,s)=>{const i=getErrorPos(e);if(s)this.warnings.push(new r.YAMLWarning(i,t,n));else this.errors.push(new r.YAMLParseError(i,t,n))};this.directives=new s.Directives({version:e.version||"1.2"});this.options=e}decorate(e,t){const{comment:n,afterEmptyLine:s}=parsePrelude(this.prelude);if(n){const i=e.contents;if(t){e.comment=e.comment?`${e.comment}\n${n}`:n}else if(s||e.directives.docStart||!i){e.commentBefore=n}else if(o.isCollection(i)&&!i.flow&&i.items.length>0){let e=i.items[0];if(o.isPair(e))e=e.key;const t=e.commentBefore;e.commentBefore=t?`${n}\n${t}`:n}else{const e=i.commentBefore;i.commentBefore=e?`${n}\n${e}`:n}}if(t){Array.prototype.push.apply(e.errors,this.errors);Array.prototype.push.apply(e.warnings,this.warnings)}else{e.errors=this.errors;e.warnings=this.warnings}this.prelude=[];this.errors=[];this.warnings=[]}streamInfo(){return{comment:parsePrelude(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(e,t=false,n=-1){for(const t of e)yield*this.next(t);yield*this.end(t,n)}*next(e){if(process.env.LOG_STREAM)console.dir(e,{depth:null});switch(e.type){case"directive":this.directives.add(e.source,((t,n,s)=>{const i=getErrorPos(e);i[0]+=t;this.onError(i,"BAD_DIRECTIVE",n,s)}));this.prelude.push(e.source);this.atDirectives=true;break;case"document":{const t=a.composeDoc(this.options,this.directives,e,this.onError);if(this.atDirectives&&!t.directives.docStart)this.onError(e,"MISSING_CHAR","Missing directives-end/doc-start indicator line");this.decorate(t,false);if(this.doc)yield this.doc;this.doc=t;this.atDirectives=false;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(e.source);break;case"error":{const t=e.source?`${e.message}: ${JSON.stringify(e.source)}`:e.message;const n=new r.YAMLParseError(getErrorPos(e),"UNEXPECTED_TOKEN",t);if(this.atDirectives||!this.doc)this.errors.push(n);else this.doc.errors.push(n);break}case"doc-end":{if(!this.doc){const t="Unexpected doc-end without preceding document";this.errors.push(new r.YAMLParseError(getErrorPos(e),"UNEXPECTED_TOKEN",t));break}this.doc.directives.docEnd=true;const t=c.resolveEnd(e.end,e.offset+e.source.length,this.doc.options.strict,this.onError);this.decorate(this.doc,true);if(t.comment){const e=this.doc.comment;this.doc.comment=e?`${e}\n${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.push(new r.YAMLParseError(getErrorPos(e),"UNEXPECTED_TOKEN",`Unsupported token ${e.type}`))}}*end(e=false,t=-1){if(this.doc){this.decorate(this.doc,true);yield this.doc;this.doc=null}else if(e){const e=Object.assign({_directives:this.directives},this.options);const n=new i.Document(undefined,e);if(this.atDirectives)this.onError(t,"MISSING_CHAR","Missing directives-end indicator line");n.range=[0,t,t];this.decorate(n,false);yield n}}}t.Composer=Composer},2986:(e,t,n)=>{var s=n(246);var i=n(6011);var r=n(6985);var o=n(976);var a=n(3669);var c=n(6899);const l="All mapping items must start at the same column";function resolveBlockMap({composeNode:e,composeEmptyNode:t},n,f,u){const d=new i.YAMLMap(n.schema);if(n.atRoot)n.atRoot=false;let h=f.offset;let p=null;for(const i of f.items){const{start:m,key:y,sep:g,value:v}=i;const b=r.resolveProps(m,{indicator:"explicit-key-ind",next:y??g?.[0],offset:h,onError:u,startOnNewline:true});const S=!b.found;if(S){if(y){if(y.type==="block-seq")u(h,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key");else if("indent"in y&&y.indent!==f.indent)u(h,"BAD_INDENT",l)}if(!b.anchor&&!b.tag&&!g){p=b.end;if(b.comment){if(d.comment)d.comment+="\n"+b.comment;else d.comment=b.comment}continue}if(b.hasNewlineAfterProp||o.containsNewline(y)){u(y??m[m.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}}else if(b.found?.indent!==f.indent){u(h,"BAD_INDENT",l)}const w=b.end;const k=y?e(n,y,b,u):t(n,w,m,null,b,u);if(n.schema.compat)a.flowIndentCheck(f.indent,y,u);if(c.mapIncludes(n,d.items,k))u(w,"DUPLICATE_KEY","Map keys must be unique");const E=r.resolveProps(g??[],{indicator:"map-value-ind",next:v,offset:k.range[2],onError:u,startOnNewline:!y||y.type==="block-scalar"});h=E.end;if(E.found){if(S){if(v?.type==="block-map"&&!E.hasNewline)u(h,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings");if(n.options.strict&&b.start<E.found.offset-1024)u(k.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key")}const r=v?e(n,v,E,u):t(n,h,g,null,E,u);if(n.schema.compat)a.flowIndentCheck(f.indent,v,u);h=r.range[2];const o=new s.Pair(k,r);if(n.options.keepSourceTokens)o.srcToken=i;d.items.push(o)}else{if(S)u(k.range,"MISSING_CHAR","Implicit map keys need to be followed by map values");if(E.comment){if(k.comment)k.comment+="\n"+E.comment;else k.comment=E.comment}const e=new s.Pair(k);if(n.options.keepSourceTokens)e.srcToken=i;d.items.push(e)}}if(p&&p<h)u(p,"IMPOSSIBLE","Map comment with trailing content");d.range=[f.offset,h,p??h];return d}t.resolveBlockMap=resolveBlockMap},9485:(e,t,n)=>{var s=n(9338);function resolveBlockScalar(e,t,n){const i=e.offset;const r=parseBlockScalarHeader(e,t,n);if(!r)return{value:"",type:null,comment:"",range:[i,i,i]};const o=r.mode===">"?s.Scalar.BLOCK_FOLDED:s.Scalar.BLOCK_LITERAL;const a=e.source?splitLines(e.source):[];let c=a.length;for(let e=a.length-1;e>=0;--e){const t=a[e][1];if(t===""||t==="\r")c=e;else break}if(c===0){const t=r.chomp==="+"&&a.length>0?"\n".repeat(Math.max(1,a.length-1)):"";let n=i+r.length;if(e.source)n+=e.source.length;return{value:t,type:o,comment:r.comment,range:[i,n,n]}}let l=e.indent+r.indent;let f=e.offset+r.length;let u=0;for(let e=0;e<c;++e){const[t,s]=a[e];if(s===""||s==="\r"){if(r.indent===0&&t.length>l)l=t.length}else{if(t.length<l){const e="Block scalars with more-indented leading empty lines must use an explicit indentation indicator";n(f+t.length,"MISSING_CHAR",e)}if(r.indent===0)l=t.length;u=e;break}f+=t.length+s.length+1}for(let e=a.length-1;e>=c;--e){if(a[e][0].length>l)c=e+1}let d="";let h="";let p=false;for(let e=0;e<u;++e)d+=a[e][0].slice(l)+"\n";for(let e=u;e<c;++e){let[t,i]=a[e];f+=t.length+i.length+1;const c=i[i.length-1]==="\r";if(c)i=i.slice(0,-1);if(i&&t.length<l){const e=r.indent?"explicit indentation indicator":"first line";const s=`Block scalar lines must not be less indented than their ${e}`;n(f-i.length-(c?2:1),"BAD_INDENT",s);t=""}if(o===s.Scalar.BLOCK_LITERAL){d+=h+t.slice(l)+i;h="\n"}else if(t.length>l||i[0]==="\t"){if(h===" ")h="\n";else if(!p&&h==="\n")h="\n\n";d+=h+t.slice(l)+i;h="\n";p=true}else if(i===""){if(h==="\n")d+="\n";else h="\n"}else{d+=h+i;h=" ";p=false}}switch(r.chomp){case"-":break;case"+":for(let e=c;e<a.length;++e)d+="\n"+a[e][0].slice(l);if(d[d.length-1]!=="\n")d+="\n";break;default:d+="\n"}const m=i+r.length+e.source.length;return{value:d,type:o,comment:r.comment,range:[i,m,m]}}function parseBlockScalarHeader({offset:e,props:t},n,s){if(t[0].type!=="block-scalar-header"){s(t[0],"IMPOSSIBLE","Block scalar header not found");return null}const{source:i}=t[0];const r=i[0];let o=0;let a="";let c=-1;for(let t=1;t<i.length;++t){const n=i[t];if(!a&&(n==="-"||n==="+"))a=n;else{const s=Number(n);if(!o&&s)o=s;else if(c===-1)c=e+t}}if(c!==-1)s(c,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${i}`);let l=false;let f="";let u=i.length;for(let e=1;e<t.length;++e){const i=t[e];switch(i.type){case"space":l=true;case"newline":u+=i.source.length;break;case"comment":if(n&&!l){const e="Comments must be separated from other tokens by white space characters";s(i,"MISSING_CHAR",e)}u+=i.source.length;f=i.source.substring(1);break;case"error":s(i,"UNEXPECTED_TOKEN",i.message);u+=i.source.length;break;default:{const e=`Unexpected token in block scalar header: ${i.type}`;s(i,"UNEXPECTED_TOKEN",e);const t=i.source;if(t&&typeof t==="string")u+=t.length}}}return{mode:r,indent:o,chomp:a,comment:f,length:u}}function splitLines(e){const t=e.split(/\n( *)/);const n=t[0];const s=n.match(/^( *)/);const i=s?.[1]?[s[1],n.slice(s[1].length)]:["",n];const r=[i];for(let e=1;e<t.length;e+=2)r.push([t[e],t[e+1]]);return r}t.resolveBlockScalar=resolveBlockScalar},2289:(e,t,n)=>{var s=n(5161);var i=n(6985);var r=n(3669);function resolveBlockSeq({composeNode:e,composeEmptyNode:t},n,o,a){const c=new s.YAMLSeq(n.schema);if(n.atRoot)n.atRoot=false;let l=o.offset;let f=null;for(const{start:s,value:u}of o.items){const d=i.resolveProps(s,{indicator:"seq-item-ind",next:u,offset:l,onError:a,startOnNewline:true});if(!d.found){if(d.anchor||d.tag||u){if(u&&u.type==="block-seq")a(d.end,"BAD_INDENT","All sequence items must start at the same column");else a(l,"MISSING_CHAR","Sequence item without - indicator")}else{f=d.end;if(d.comment)c.comment=d.comment;continue}}const h=u?e(n,u,d,a):t(n,d.end,s,null,d,a);if(n.schema.compat)r.flowIndentCheck(o.indent,u,a);l=h.range[2];c.items.push(h)}c.range=[o.offset,l,f??l];return c}t.resolveBlockSeq=resolveBlockSeq},1250:(e,t)=>{function resolveEnd(e,t,n,s){let i="";if(e){let r=false;let o="";for(const a of e){const{source:e,type:c}=a;switch(c){case"space":r=true;break;case"comment":{if(n&&!r)s(a,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");const t=e.substring(1)||" ";if(!i)i=t;else i+=o+t;o="";break}case"newline":if(i)o+=e;r=true;break;default:s(a,"UNEXPECTED_TOKEN",`Unexpected ${c} at node end`)}t+=e.length}}return{comment:i,offset:t}}t.resolveEnd=resolveEnd},45:(e,t,n)=>{var s=n(1399);var i=n(246);var r=n(6011);var o=n(5161);var a=n(1250);var c=n(6985);var l=n(976);var f=n(6899);const u="Block collections are not allowed within flow collections";const isBlock=e=>e&&(e.type==="block-map"||e.type==="block-seq");function resolveFlowCollection({composeNode:e,composeEmptyNode:t},n,d,h){const p=d.start.source==="{";const m=p?"flow map":"flow sequence";const y=p?new r.YAMLMap(n.schema):new o.YAMLSeq(n.schema);y.flow=true;const g=n.atRoot;if(g)n.atRoot=false;let v=d.offset+d.start.source.length;for(let o=0;o<d.items.length;++o){const a=d.items[o];const{start:g,key:b,sep:S,value:w}=a;const k=c.resolveProps(g,{flow:m,indicator:"explicit-key-ind",next:b??S?.[0],offset:v,onError:h,startOnNewline:false});if(!k.found){if(!k.anchor&&!k.tag&&!S&&!w){if(o===0&&k.comma)h(k.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${m}`);else if(o<d.items.length-1)h(k.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${m}`);if(k.comment){if(y.comment)y.comment+="\n"+k.comment;else y.comment=k.comment}v=k.end;continue}if(!p&&n.options.strict&&l.containsNewline(b))h(b,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(o===0){if(k.comma)h(k.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${m}`)}else{if(!k.comma)h(k.start,"MISSING_CHAR",`Missing , between ${m} items`);if(k.comment){let e="";e:for(const t of g){switch(t.type){case"comma":case"space":break;case"comment":e=t.source.substring(1);break e;default:break e}}if(e){let t=y.items[y.items.length-1];if(s.isPair(t))t=t.value??t.key;if(t.comment)t.comment+="\n"+e;else t.comment=e;k.comment=k.comment.substring(e.length+1)}}}if(!p&&!S&&!k.found){const s=w?e(n,w,k,h):t(n,k.end,S,null,k,h);y.items.push(s);v=s.range[2];if(isBlock(w))h(s.range,"BLOCK_IN_FLOW",u)}else{const s=k.end;const o=b?e(n,b,k,h):t(n,s,g,null,k,h);if(isBlock(b))h(o.range,"BLOCK_IN_FLOW",u);const l=c.resolveProps(S??[],{flow:m,indicator:"map-value-ind",next:w,offset:o.range[2],onError:h,startOnNewline:false});if(l.found){if(!p&&!k.found&&n.options.strict){if(S)for(const e of S){if(e===l.found)break;if(e.type==="newline"){h(e,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}if(k.start<l.found.offset-1024)h(l.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else if(w){if("source"in w&&w.source&&w.source[0]===":")h(w,"MISSING_CHAR",`Missing space after : in ${m}`);else h(l.start,"MISSING_CHAR",`Missing , or : between ${m} items`)}const d=w?e(n,w,l,h):l.found?t(n,l.end,S,null,l,h):null;if(d){if(isBlock(w))h(d.range,"BLOCK_IN_FLOW",u)}else if(l.comment){if(o.comment)o.comment+="\n"+l.comment;else o.comment=l.comment}const E=new i.Pair(o,d);if(n.options.keepSourceTokens)E.srcToken=a;if(p){const e=y;if(f.mapIncludes(n,e.items,o))h(s,"DUPLICATE_KEY","Map keys must be unique");e.items.push(E)}else{const e=new r.YAMLMap(n.schema);e.flow=true;e.items.push(E);y.items.push(e)}v=d?d.range[2]:l.end}}const b=p?"}":"]";const[S,...w]=d.end;let k=v;if(S&&S.source===b)k=S.offset+S.source.length;else{const e=m[0].toUpperCase()+m.substring(1);const t=g?`${e} must end with a ${b}`:`${e} in block collection must be sufficiently indented and end with a ${b}`;h(v,g?"MISSING_CHAR":"BAD_INDENT",t);if(S&&S.source.length!==1)w.unshift(S)}if(w.length>0){const e=a.resolveEnd(w,k,n.options.strict,h);if(e.comment){if(y.comment)y.comment+="\n"+e.comment;else y.comment=e.comment}y.range=[d.offset,k,e.offset]}else{y.range=[d.offset,k,k]}return y}t.resolveFlowCollection=resolveFlowCollection},7578:(e,t,n)=>{var s=n(9338);var i=n(1250);function resolveFlowScalar(e,t,n){const{offset:r,type:o,source:a,end:c}=e;let l;let f;const _onError=(e,t,s)=>n(r+e,t,s);switch(o){case"scalar":l=s.Scalar.PLAIN;f=plainValue(a,_onError);break;case"single-quoted-scalar":l=s.Scalar.QUOTE_SINGLE;f=singleQuotedValue(a,_onError);break;case"double-quoted-scalar":l=s.Scalar.QUOTE_DOUBLE;f=doubleQuotedValue(a,_onError);break;default:n(e,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${o}`);return{value:"",type:null,comment:"",range:[r,r+a.length,r+a.length]}}const u=r+a.length;const d=i.resolveEnd(c,u,t,n);return{value:f,type:l,comment:d.comment,range:[r,u,d.offset]}}function plainValue(e,t){let n="";switch(e[0]){case"\t":n="a tab character";break;case",":n="flow indicator character ,";break;case"%":n="directive indicator character %";break;case"|":case">":{n=`block scalar indicator ${e[0]}`;break}case"@":case"`":{n=`reserved character ${e[0]}`;break}}if(n)t(0,"BAD_SCALAR_START",`Plain value cannot start with ${n}`);return foldLines(e)}function singleQuotedValue(e,t){if(e[e.length-1]!=="'"||e.length===1)t(e.length,"MISSING_CHAR","Missing closing 'quote");return foldLines(e.slice(1,-1)).replace(/''/g,"'")}function foldLines(e){let t,n;try{t=new RegExp("(.*?)(?<![ \t])[ \t]*\r?\n","sy");n=new RegExp("[ \t]*(.*?)(?:(?<![ \t])[ \t]*)?\r?\n","sy")}catch(e){t=/(.*?)[ \t]*\r?\n/ys;n=/[ \t]*(.*?)[ \t]*\r?\n/ys}let s=t.exec(e);if(!s)return e;let i=s[1];let r=" ";let o=t.lastIndex;n.lastIndex=o;while(s=n.exec(e)){if(s[1]===""){if(r==="\n")i+=r;else r="\n"}else{i+=r+s[1];r=" "}o=n.lastIndex}const a=/[ \t]*(.*)/ys;a.lastIndex=o;s=a.exec(e);return i+r+(s?.[1]??"")}function doubleQuotedValue(e,t){let n="";for(let s=1;s<e.length-1;++s){const i=e[s];if(i==="\r"&&e[s+1]==="\n")continue;if(i==="\n"){const{fold:t,offset:i}=foldNewline(e,s);n+=t;s=i}else if(i==="\\"){let i=e[++s];const o=r[i];if(o)n+=o;else if(i==="\n"){i=e[s+1];while(i===" "||i==="\t")i=e[++s+1]}else if(i==="\r"&&e[s+1]==="\n"){i=e[++s+1];while(i===" "||i==="\t")i=e[++s+1]}else if(i==="x"||i==="u"||i==="U"){const r={x:2,u:4,U:8}[i];n+=parseCharCode(e,s+1,r,t);s+=r}else{const i=e.substr(s-1,2);t(s-1,"BAD_DQ_ESCAPE",`Invalid escape sequence ${i}`);n+=i}}else if(i===" "||i==="\t"){const t=s;let r=e[s+1];while(r===" "||r==="\t")r=e[++s+1];if(r!=="\n"&&!(r==="\r"&&e[s+2]==="\n"))n+=s>t?e.slice(t,s+1):i}else{n+=i}}if(e[e.length-1]!=='"'||e.length===1)t(e.length,"MISSING_CHAR",'Missing closing "quote');return n}function foldNewline(e,t){let n="";let s=e[t+1];while(s===" "||s==="\t"||s==="\n"||s==="\r"){if(s==="\r"&&e[t+2]!=="\n")break;if(s==="\n")n+="\n";t+=1;s=e[t+1]}if(!n)n=" ";return{fold:n,offset:t}}const r={0:"\0",a:"",b:"\b",e:"",f:"\f",n:"\n",r:"\r",t:"\t",v:"\v",N:"Â
",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\","\t":"\t"};function parseCharCode(e,t,n,s){const i=e.substr(t,n);const r=i.length===n&&/^[0-9a-fA-F]+$/.test(i);const o=r?parseInt(i,16):NaN;if(isNaN(o)){const i=e.substr(t-2,n+2);s(t-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${i}`);return i}return String.fromCodePoint(o)}t.resolveFlowScalar=resolveFlowScalar},6985:(e,t)=>{function resolveProps(e,{flow:t,indicator:n,next:s,offset:i,onError:r,startOnNewline:o}){let a=false;let c=o;let l=o;let f="";let u="";let d=false;let h=false;let p=false;let m=null;let y=null;let g=null;let v=null;let b=null;for(const s of e){if(p){if(s.type!=="space"&&s.type!=="newline"&&s.type!=="comma")r(s.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space");p=false}switch(s.type){case"space":if(!t&&c&&n!=="doc-start"&&s.source[0]==="\t")r(s,"TAB_AS_INDENT","Tabs are not allowed as indentation");l=true;break;case"comment":{if(!l)r(s,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");const e=s.source.substring(1)||" ";if(!f)f=e;else f+=u+e;u="";c=false;break}case"newline":if(c){if(f)f+=s.source;else a=true}else u+=s.source;c=true;d=true;if(m||y)h=true;l=true;break;case"anchor":if(m)r(s,"MULTIPLE_ANCHORS","A node can have at most one anchor");if(s.source.endsWith(":"))r(s.offset+s.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",true);m=s;if(b===null)b=s.offset;c=false;l=false;p=true;break;case"tag":{if(y)r(s,"MULTIPLE_TAGS","A node can have at most one tag");y=s;if(b===null)b=s.offset;c=false;l=false;p=true;break}case n:if(m||y)r(s,"BAD_PROP_ORDER",`Anchors and tags must be after the ${s.source} indicator`);if(v)r(s,"UNEXPECTED_TOKEN",`Unexpected ${s.source} in ${t??"collection"}`);v=s;c=false;l=false;break;case"comma":if(t){if(g)r(s,"UNEXPECTED_TOKEN",`Unexpected , in ${t}`);g=s;c=false;l=false;break}default:r(s,"UNEXPECTED_TOKEN",`Unexpected ${s.type} token`);c=false;l=false}}const S=e[e.length-1];const w=S?S.offset+S.source.length:i;if(p&&s&&s.type!=="space"&&s.type!=="newline"&&s.type!=="comma"&&(s.type!=="scalar"||s.source!==""))r(s.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space");return{comma:g,found:v,spaceBefore:a,comment:f,hasNewline:d,hasNewlineAfterProp:h,anchor:m,tag:y,end:w,start:b??w}}t.resolveProps=resolveProps},976:(e,t)=>{function containsNewline(e){if(!e)return null;switch(e.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(e.source.includes("\n"))return true;if(e.end)for(const t of e.end)if(t.type==="newline")return true;return false;case"flow-collection":for(const t of e.items){for(const e of t.start)if(e.type==="newline")return true;if(t.sep)for(const e of t.sep)if(e.type==="newline")return true;if(containsNewline(t.key)||containsNewline(t.value))return true}return false;default:return true}}t.containsNewline=containsNewline},8781:(e,t)=>{function emptyScalarPosition(e,t,n){if(t){if(n===null)n=t.length;for(let s=n-1;s>=0;--s){let n=t[s];switch(n.type){case"space":case"comment":case"newline":e-=n.source.length;continue}n=t[++s];while(n?.type==="space"){e+=n.source.length;n=t[++s]}break}}return e}t.emptyScalarPosition=emptyScalarPosition},3669:(e,t,n)=>{var s=n(976);function flowIndentCheck(e,t,n){if(t?.type==="flow-collection"){const i=t.end[0];if(i.indent===e&&(i.source==="]"||i.source==="}")&&s.containsNewline(t)){const e="Flow end indicator should be more indented than parent";n(i,"BAD_INDENT",e,true)}}}t.flowIndentCheck=flowIndentCheck},6899:(e,t,n)=>{var s=n(1399);function mapIncludes(e,t,n){const{uniqueKeys:i}=e.options;if(i===false)return false;const r=typeof i==="function"?i:(t,n)=>t===n||s.isScalar(t)&&s.isScalar(n)&&t.value===n.value&&!(t.value==="<<"&&e.schema.merge);return t.some((e=>r(e.key,n)))}t.mapIncludes=mapIncludes},42:(e,t,n)=>{var s=n(5639);var i=n(3466);var r=n(1399);var o=n(246);var a=n(2463);var c=n(6831);var l=n(8409);var f=n(5225);var u=n(8459);var d=n(3412);var h=n(9652);var p=n(5400);class Document{constructor(e,t,n){this.commentBefore=null;this.comment=null;this.errors=[];this.warnings=[];Object.defineProperty(this,r.NODE_TYPE,{value:r.DOC});let s=null;if(typeof t==="function"||Array.isArray(t)){s=t}else if(n===undefined&&t){n=t;t=undefined}const i=Object.assign({intAsBigInt:false,keepSourceTokens:false,logLevel:"warn",prettyErrors:true,strict:true,uniqueKeys:true,version:"1.2"},n);this.options=i;let{version:o}=i;if(n?._directives){this.directives=n._directives.atDocument();if(this.directives.yaml.explicit)o=this.directives.yaml.version}else this.directives=new p.Directives({version:o});this.setSchema(o,n);if(e===undefined)this.contents=null;else{this.contents=this.createNode(e,s,n)}}clone(){const e=Object.create(Document.prototype,{[r.NODE_TYPE]:{value:r.DOC}});e.commentBefore=this.commentBefore;e.comment=this.comment;e.errors=this.errors.slice();e.warnings=this.warnings.slice();e.options=Object.assign({},this.options);if(this.directives)e.directives=this.directives.clone();e.schema=this.schema.clone();e.contents=r.isNode(this.contents)?this.contents.clone(e.schema):this.contents;if(this.range)e.range=this.range.slice();return e}add(e){if(assertCollection(this.contents))this.contents.add(e)}addIn(e,t){if(assertCollection(this.contents))this.contents.addIn(e,t)}createAlias(e,t){if(!e.anchor){const n=u.anchorNames(this);e.anchor=!t||n.has(t)?u.findNewAnchor(t||"a",n):t}return new s.Alias(e.anchor)}createNode(e,t,n){let s=undefined;if(typeof t==="function"){e=t.call({"":e},"",e);s=t}else if(Array.isArray(t)){const keyToStr=e=>typeof e==="number"||e instanceof String||e instanceof Number;const e=t.filter(keyToStr).map(String);if(e.length>0)t=t.concat(e);s=t}else if(n===undefined&&t){n=t;t=undefined}const{aliasDuplicateObjects:i,anchorPrefix:o,flow:a,keepUndefined:c,onTagObj:l,tag:f}=n??{};const{onAnchor:d,setAnchors:p,sourceObjects:m}=u.createNodeAnchors(this,o||"a");const y={aliasDuplicateObjects:i??true,keepUndefined:c??false,onAnchor:d,onTagObj:l,replacer:s,schema:this.schema,sourceObjects:m};const g=h.createNode(e,f,y);if(a&&r.isCollection(g))g.flow=true;p();return g}createPair(e,t,n={}){const s=this.createNode(e,null,n);const i=this.createNode(t,null,n);return new o.Pair(s,i)}delete(e){return assertCollection(this.contents)?this.contents.delete(e):false}deleteIn(e){if(i.isEmptyPath(e)){if(this.contents==null)return false;this.contents=null;return true}return assertCollection(this.contents)?this.contents.deleteIn(e):false}get(e,t){return r.isCollection(this.contents)?this.contents.get(e,t):undefined}getIn(e,t){if(i.isEmptyPath(e))return!t&&r.isScalar(this.contents)?this.contents.value:this.contents;return r.isCollection(this.contents)?this.contents.getIn(e,t):undefined}has(e){return r.isCollection(this.contents)?this.contents.has(e):false}hasIn(e){if(i.isEmptyPath(e))return this.contents!==undefined;return r.isCollection(this.contents)?this.contents.hasIn(e):false}set(e,t){if(this.contents==null){this.contents=i.collectionFromPath(this.schema,[e],t)}else if(assertCollection(this.contents)){this.contents.set(e,t)}}setIn(e,t){if(i.isEmptyPath(e))this.contents=t;else if(this.contents==null){this.contents=i.collectionFromPath(this.schema,Array.from(e),t)}else if(assertCollection(this.contents)){this.contents.setIn(e,t)}}setSchema(e,t={}){if(typeof e==="number")e=String(e);let n;switch(e){case"1.1":if(this.directives)this.directives.yaml.version="1.1";else this.directives=new p.Directives({version:"1.1"});n={merge:true,resolveKnownTags:false,schema:"yaml-1.1"};break;case"1.2":case"next":if(this.directives)this.directives.yaml.version=e;else this.directives=new p.Directives({version:e});n={merge:false,resolveKnownTags:true,schema:"core"};break;case null:if(this.directives)delete this.directives;n=null;break;default:{const t=JSON.stringify(e);throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${t}`)}}if(t.schema instanceof Object)this.schema=t.schema;else if(n)this.schema=new c.Schema(Object.assign(n,t));else throw new Error(`With a null YAML version, the { schema: Schema } option is required`)}toJS({json:e,jsonArg:t,mapAsMap:n,maxAliasCount:s,onAnchor:i,reviver:r}={}){const o={anchors:new Map,doc:this,keep:!e,mapAsMap:n===true,mapKeyWarned:false,maxAliasCount:typeof s==="number"?s:100,stringify:l.stringify};const c=a.toJS(this.contents,t??"",o);if(typeof i==="function")for(const{count:e,res:t}of o.anchors.values())i(t,e);return typeof r==="function"?d.applyReviver(r,{"":c},"",c):c}toJSON(e,t){return this.toJS({json:true,jsonArg:e,mapAsMap:false,onAnchor:t})}toString(e={}){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");if("indent"in e&&(!Number.isInteger(e.indent)||Number(e.indent)<=0)){const t=JSON.stringify(e.indent);throw new Error(`"indent" option must be a positive integer, not ${t}`)}return f.stringifyDocument(this,e)}}function assertCollection(e){if(r.isCollection(e))return true;throw new Error("Expected a YAML collection as document contents")}t.Document=Document},8459:(e,t,n)=>{var s=n(1399);var i=n(6796);function anchorIsValid(e){if(/[\x00-\x19\s,[\]{}]/.test(e)){const t=JSON.stringify(e);const n=`Anchor must not contain whitespace or control characters: ${t}`;throw new Error(n)}return true}function anchorNames(e){const t=new Set;i.visit(e,{Value(e,n){if(n.anchor)t.add(n.anchor)}});return t}function findNewAnchor(e,t){for(let n=1;true;++n){const s=`${e}${n}`;if(!t.has(s))return s}}function createNodeAnchors(e,t){const n=[];const i=new Map;let r=null;return{onAnchor:s=>{n.push(s);if(!r)r=anchorNames(e);const i=findNewAnchor(t,r);r.add(i);return i},setAnchors:()=>{for(const e of n){const t=i.get(e);if(typeof t==="object"&&t.anchor&&(s.isScalar(t.node)||s.isCollection(t.node))){t.node.anchor=t.anchor}else{const t=new Error("Failed to resolve repeated object (this should not happen)");t.source=e;throw t}}},sourceObjects:i}}t.anchorIsValid=anchorIsValid;t.anchorNames=anchorNames;t.createNodeAnchors=createNodeAnchors;t.findNewAnchor=findNewAnchor},3412:(e,t)=>{function applyReviver(e,t,n,s){if(s&&typeof s==="object"){if(Array.isArray(s)){for(let t=0,n=s.length;t<n;++t){const n=s[t];const i=applyReviver(e,s,String(t),n);if(i===undefined)delete s[t];else if(i!==n)s[t]=i}}else if(s instanceof Map){for(const t of Array.from(s.keys())){const n=s.get(t);const i=applyReviver(e,s,t,n);if(i===undefined)s.delete(t);else if(i!==n)s.set(t,i)}}else if(s instanceof Set){for(const t of Array.from(s)){const n=applyReviver(e,s,t,t);if(n===undefined)s.delete(t);else if(n!==t){s.delete(t);s.add(n)}}}else{for(const[t,n]of Object.entries(s)){const i=applyReviver(e,s,t,n);if(i===undefined)delete s[t];else if(i!==n)s[t]=i}}}return e.call(t,n,s)}t.applyReviver=applyReviver},9652:(e,t,n)=>{var s=n(5639);var i=n(1399);var r=n(9338);const o="tag:yaml.org,2002:";function findTagObject(e,t,n){if(t){const e=n.filter((e=>e.tag===t));const s=e.find((e=>!e.format))??e[0];if(!s)throw new Error(`Tag ${t} not found`);return s}return n.find((t=>t.identify?.(e)&&!t.format))}function createNode(e,t,n){if(i.isDocument(e))e=e.contents;if(i.isNode(e))return e;if(i.isPair(e)){const t=n.schema[i.MAP].createNode?.(n.schema,null,n);t.items.push(e);return t}if(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt!=="undefined"&&e instanceof BigInt){e=e.valueOf()}const{aliasDuplicateObjects:a,onAnchor:c,onTagObj:l,schema:f,sourceObjects:u}=n;let d=undefined;if(a&&e&&typeof e==="object"){d=u.get(e);if(d){if(!d.anchor)d.anchor=c(e);return new s.Alias(d.anchor)}else{d={anchor:null,node:null};u.set(e,d)}}if(t?.startsWith("!!"))t=o+t.slice(2);let h=findTagObject(e,t,f.tags);if(!h){if(e&&typeof e.toJSON==="function"){e=e.toJSON()}if(!e||typeof e!=="object"){const t=new r.Scalar(e);if(d)d.node=t;return t}h=e instanceof Map?f[i.MAP]:Symbol.iterator in Object(e)?f[i.SEQ]:f[i.MAP]}if(l){l(h);delete n.onTagObj}const p=h?.createNode?h.createNode(n.schema,e,n):new r.Scalar(e);if(t)p.tag=t;if(d)d.node=p;return p}t.createNode=createNode},5400:(e,t,n)=>{var s=n(1399);var i=n(6796);const r={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"};const escapeTagName=e=>e.replace(/[!,[\]{}]/g,(e=>r[e]));class Directives{constructor(e,t){this.docStart=null;this.docEnd=false;this.yaml=Object.assign({},Directives.defaultYaml,e);this.tags=Object.assign({},Directives.defaultTags,t)}clone(){const e=new Directives(this.yaml,this.tags);e.docStart=this.docStart;return e}atDocument(){const e=new Directives(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=true;break;case"1.2":this.atNextDocument=false;this.yaml={explicit:Directives.defaultYaml.explicit,version:"1.2"};this.tags=Object.assign({},Directives.defaultTags);break}return e}add(e,t){if(this.atNextDocument){this.yaml={explicit:Directives.defaultYaml.explicit,version:"1.1"};this.tags=Object.assign({},Directives.defaultTags);this.atNextDocument=false}const n=e.trim().split(/[ \t]+/);const s=n.shift();switch(s){case"%TAG":{if(n.length!==2){t(0,"%TAG directive should contain exactly two parts");if(n.length<2)return false}const[e,s]=n;this.tags[e]=s;return true}case"%YAML":{this.yaml.explicit=true;if(n.length!==1){t(0,"%YAML directive should contain exactly one part");return false}const[e]=n;if(e==="1.1"||e==="1.2"){this.yaml.version=e;return true}else{const n=/^\d+\.\d+$/.test(e);t(6,`Unsupported YAML version ${e}`,n);return false}}default:t(0,`Unknown directive ${s}`,true);return false}}tagName(e,t){if(e==="!")return"!";if(e[0]!=="!"){t(`Not a valid tag: ${e}`);return null}if(e[1]==="<"){const n=e.slice(2,-1);if(n==="!"||n==="!!"){t(`Verbatim tags aren't resolved, so ${e} is invalid.`);return null}if(e[e.length-1]!==">")t("Verbatim tags must end with a >");return n}const[,n,s]=e.match(/^(.*!)([^!]*)$/);if(!s)t(`The ${e} tag has no suffix`);const i=this.tags[n];if(i)return i+decodeURIComponent(s);if(n==="!")return e;t(`Could not resolve tag: ${e}`);return null}tagString(e){for(const[t,n]of Object.entries(this.tags)){if(e.startsWith(n))return t+escapeTagName(e.substring(n.length))}return e[0]==="!"?e:`!<${e}>`}toString(e){const t=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[];const n=Object.entries(this.tags);let r;if(e&&n.length>0&&s.isNode(e.contents)){const t={};i.visit(e.contents,((e,n)=>{if(s.isNode(n)&&n.tag)t[n.tag]=true}));r=Object.keys(t)}else r=[];for(const[s,i]of n){if(s==="!!"&&i==="tag:yaml.org,2002:")continue;if(!e||r.some((e=>e.startsWith(i))))t.push(`%TAG ${s} ${i}`)}return t.join("\n")}}Directives.defaultYaml={explicit:false,version:"1.2"};Directives.defaultTags={"!!":"tag:yaml.org,2002:"};t.Directives=Directives},4236:(e,t)=>{class YAMLError extends Error{constructor(e,t,n,s){super();this.name=e;this.code=n;this.message=s;this.pos=t}}class YAMLParseError extends YAMLError{constructor(e,t,n){super("YAMLParseError",e,t,n)}}class YAMLWarning extends YAMLError{constructor(e,t,n){super("YAMLWarning",e,t,n)}}const prettifyError=(e,t)=>n=>{if(n.pos[0]===-1)return;n.linePos=n.pos.map((e=>t.linePos(e)));const{line:s,col:i}=n.linePos[0];n.message+=` at line ${s}, column ${i}`;let r=i-1;let o=e.substring(t.lineStarts[s-1],t.lineStarts[s]).replace(/[\n\r]+$/,"");if(r>=60&&o.length>80){const e=Math.min(r-39,o.length-79);o="â¦"+o.substring(e);r-=e-1}if(o.length>80)o=o.substring(0,79)+"â¦";if(s>1&&/^ *$/.test(o.substring(0,r))){let n=e.substring(t.lineStarts[s-2],t.lineStarts[s-1]);if(n.length>80)n=n.substring(0,79)+"â¦\n";o=n+o}if(/[^ ]/.test(o)){let e=1;const t=n.linePos[1];if(t&&t.line===s&&t.col>i){e=Math.min(t.col-i,80-r)}const a=" ".repeat(r)+"^".repeat(e);n.message+=`:\n\n${o}\n${a}\n`}};t.YAMLError=YAMLError;t.YAMLParseError=YAMLParseError;t.YAMLWarning=YAMLWarning;t.prettifyError=prettifyError},4083:(e,t,n)=>{var s=n(9493);var i=n(42);var r=n(6831);var o=n(4236);var a=n(5639);var c=n(1399);var l=n(246);var f=n(9338);var u=n(6011);var d=n(5161);var h=n(9169);var p=n(5976);var m=n(1929);var y=n(3328);var g=n(8649);var v=n(6796);t.Composer=s.Composer;t.Document=i.Document;t.Schema=r.Schema;t.YAMLError=o.YAMLError;t.YAMLParseError=o.YAMLParseError;t.YAMLWarning=o.YAMLWarning;t.Alias=a.Alias;t.isAlias=c.isAlias;t.isCollection=c.isCollection;t.isDocument=c.isDocument;t.isMap=c.isMap;t.isNode=c.isNode;t.isPair=c.isPair;t.isScalar=c.isScalar;t.isSeq=c.isSeq;t.Pair=l.Pair;t.Scalar=f.Scalar;t.YAMLMap=u.YAMLMap;t.YAMLSeq=d.YAMLSeq;t.CST=h;t.Lexer=p.Lexer;t.LineCounter=m.LineCounter;t.Parser=y.Parser;t.parse=g.parse;t.parseAllDocuments=g.parseAllDocuments;t.parseDocument=g.parseDocument;t.stringify=g.stringify;t.visit=v.visit;t.visitAsync=v.visitAsync},6909:(e,t)=>{function debug(e,...t){if(e==="debug")console.log(...t)}function warn(e,t){if(e==="debug"||e==="warn"){if(typeof process!=="undefined"&&process.emitWarning)process.emitWarning(t);else console.warn(t)}}t.debug=debug;t.warn=warn},5639:(e,t,n)=>{var s=n(8459);var i=n(6796);var r=n(1399);class Alias extends r.NodeBase{constructor(e){super(r.ALIAS);this.source=e;Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(e){let t=undefined;i.visit(e,{Node:(e,n)=>{if(n===this)return i.visit.BREAK;if(n.anchor===this.source)t=n}});return t}toJSON(e,t){if(!t)return{source:this.source};const{anchors:n,doc:s,maxAliasCount:i}=t;const r=this.resolve(s);if(!r){const e=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(e)}const o=n.get(r);if(!o||o.res===undefined){const e="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(e)}if(i>=0){o.count+=1;if(o.aliasCount===0)o.aliasCount=getAliasCount(s,r,n);if(o.count*o.aliasCount>i){const e="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(e)}}return o.res}toString(e,t,n){const i=`*${this.source}`;if(e){s.anchorIsValid(this.source);if(e.options.verifyAliasOrder&&!e.anchors.has(this.source)){const e=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(e)}if(e.implicitKey)return`${i} `}return i}}function getAliasCount(e,t,n){if(r.isAlias(t)){const s=t.resolve(e);const i=n&&s&&n.get(s);return i?i.count*i.aliasCount:0}else if(r.isCollection(t)){let s=0;for(const i of t.items){const t=getAliasCount(e,i,n);if(t>s)s=t}return s}else if(r.isPair(t)){const s=getAliasCount(e,t.key,n);const i=getAliasCount(e,t.value,n);return Math.max(s,i)}return 1}t.Alias=Alias},3466:(e,t,n)=>{var s=n(9652);var i=n(1399);function collectionFromPath(e,t,n){let i=n;for(let e=t.length-1;e>=0;--e){const n=t[e];if(typeof n==="number"&&Number.isInteger(n)&&n>=0){const e=[];e[n]=i;i=e}else{i=new Map([[n,i]])}}return s.createNode(i,undefined,{aliasDuplicateObjects:false,keepUndefined:false,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:e,sourceObjects:new Map})}const isEmptyPath=e=>e==null||typeof e==="object"&&!!e[Symbol.iterator]().next().done;class Collection extends i.NodeBase{constructor(e,t){super(e);Object.defineProperty(this,"schema",{value:t,configurable:true,enumerable:false,writable:true})}clone(e){const t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));if(e)t.schema=e;t.items=t.items.map((t=>i.isNode(t)||i.isPair(t)?t.clone(e):t));if(this.range)t.range=this.range.slice();return t}addIn(e,t){if(isEmptyPath(e))this.add(t);else{const[n,...s]=e;const r=this.get(n,true);if(i.isCollection(r))r.addIn(s,t);else if(r===undefined&&this.schema)this.set(n,collectionFromPath(this.schema,s,t));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${s}`)}}deleteIn(e){const[t,...n]=e;if(n.length===0)return this.delete(t);const s=this.get(t,true);if(i.isCollection(s))return s.deleteIn(n);else throw new Error(`Expected YAML collection at ${t}. Remaining path: ${n}`)}getIn(e,t){const[n,...s]=e;const r=this.get(n,true);if(s.length===0)return!t&&i.isScalar(r)?r.value:r;else return i.isCollection(r)?r.getIn(s,t):undefined}hasAllNullValues(e){return this.items.every((t=>{if(!i.isPair(t))return false;const n=t.value;return n==null||e&&i.isScalar(n)&&n.value==null&&!n.commentBefore&&!n.comment&&!n.tag}))}hasIn(e){const[t,...n]=e;if(n.length===0)return this.has(t);const s=this.get(t,true);return i.isCollection(s)?s.hasIn(n):false}setIn(e,t){const[n,...s]=e;if(s.length===0){this.set(n,t)}else{const e=this.get(n,true);if(i.isCollection(e))e.setIn(s,t);else if(e===undefined&&this.schema)this.set(n,collectionFromPath(this.schema,s,t));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${s}`)}}}Collection.maxFlowStringSingleLineLength=60;t.Collection=Collection;t.collectionFromPath=collectionFromPath;t.isEmptyPath=isEmptyPath},1399:(e,t)=>{const n=Symbol.for("yaml.alias");const s=Symbol.for("yaml.document");const i=Symbol.for("yaml.map");const r=Symbol.for("yaml.pair");const o=Symbol.for("yaml.scalar");const a=Symbol.for("yaml.seq");const c=Symbol.for("yaml.node.type");const isAlias=e=>!!e&&typeof e==="object"&&e[c]===n;const isDocument=e=>!!e&&typeof e==="object"&&e[c]===s;const isMap=e=>!!e&&typeof e==="object"&&e[c]===i;const isPair=e=>!!e&&typeof e==="object"&&e[c]===r;const isScalar=e=>!!e&&typeof e==="object"&&e[c]===o;const isSeq=e=>!!e&&typeof e==="object"&&e[c]===a;function isCollection(e){if(e&&typeof e==="object")switch(e[c]){case i:case a:return true}return false}function isNode(e){if(e&&typeof e==="object")switch(e[c]){case n:case i:case o:case a:return true}return false}const hasAnchor=e=>(isScalar(e)||isCollection(e))&&!!e.anchor;class NodeBase{constructor(e){Object.defineProperty(this,c,{value:e})}clone(){const e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));if(this.range)e.range=this.range.slice();return e}}t.ALIAS=n;t.DOC=s;t.MAP=i;t.NODE_TYPE=c;t.NodeBase=NodeBase;t.PAIR=r;t.SCALAR=o;t.SEQ=a;t.hasAnchor=hasAnchor;t.isAlias=isAlias;t.isCollection=isCollection;t.isDocument=isDocument;t.isMap=isMap;t.isNode=isNode;t.isPair=isPair;t.isScalar=isScalar;t.isSeq=isSeq},246:(e,t,n)=>{var s=n(9652);var i=n(4875);var r=n(4676);var o=n(1399);function createPair(e,t,n){const i=s.createNode(e,undefined,n);const r=s.createNode(t,undefined,n);return new Pair(i,r)}class Pair{constructor(e,t=null){Object.defineProperty(this,o.NODE_TYPE,{value:o.PAIR});this.key=e;this.value=t}clone(e){let{key:t,value:n}=this;if(o.isNode(t))t=t.clone(e);if(o.isNode(n))n=n.clone(e);return new Pair(t,n)}toJSON(e,t){const n=t?.mapAsMap?new Map:{};return r.addPairToJSMap(t,n,this)}toString(e,t,n){return e?.doc?i.stringifyPair(this,e,t,n):JSON.stringify(this)}}t.Pair=Pair;t.createPair=createPair},9338:(e,t,n)=>{var s=n(1399);var i=n(2463);const isScalarValue=e=>!e||typeof e!=="function"&&typeof e!=="object";class Scalar extends s.NodeBase{constructor(e){super(s.SCALAR);this.value=e}toJSON(e,t){return t?.keep?this.value:i.toJS(this.value,e,t)}toString(){return String(this.value)}}Scalar.BLOCK_FOLDED="BLOCK_FOLDED";Scalar.BLOCK_LITERAL="BLOCK_LITERAL";Scalar.PLAIN="PLAIN";Scalar.QUOTE_DOUBLE="QUOTE_DOUBLE";Scalar.QUOTE_SINGLE="QUOTE_SINGLE";t.Scalar=Scalar;t.isScalarValue=isScalarValue},6011:(e,t,n)=>{var s=n(2466);var i=n(4676);var r=n(3466);var o=n(1399);var a=n(246);var c=n(9338);function findPair(e,t){const n=o.isScalar(t)?t.value:t;for(const s of e){if(o.isPair(s)){if(s.key===t||s.key===n)return s;if(o.isScalar(s.key)&&s.key.value===n)return s}}return undefined}class YAMLMap extends r.Collection{constructor(e){super(o.MAP,e);this.items=[]}static get tagName(){return"tag:yaml.org,2002:map"}add(e,t){let n;if(o.isPair(e))n=e;else if(!e||typeof e!=="object"||!("key"in e)){n=new a.Pair(e,e?.value)}else n=new a.Pair(e.key,e.value);const s=findPair(this.items,n.key);const i=this.schema?.sortMapEntries;if(s){if(!t)throw new Error(`Key ${n.key} already set`);if(o.isScalar(s.value)&&c.isScalarValue(n.value))s.value.value=n.value;else s.value=n.value}else if(i){const e=this.items.findIndex((e=>i(n,e)<0));if(e===-1)this.items.push(n);else this.items.splice(e,0,n)}else{this.items.push(n)}}delete(e){const t=findPair(this.items,e);if(!t)return false;const n=this.items.splice(this.items.indexOf(t),1);return n.length>0}get(e,t){const n=findPair(this.items,e);const s=n?.value;return(!t&&o.isScalar(s)?s.value:s)??undefined}has(e){return!!findPair(this.items,e)}set(e,t){this.add(new a.Pair(e,t),true)}toJSON(e,t,n){const s=n?new n:t?.mapAsMap?new Map:{};if(t?.onCreate)t.onCreate(s);for(const e of this.items)i.addPairToJSMap(t,s,e);return s}toString(e,t,n){if(!e)return JSON.stringify(this);for(const e of this.items){if(!o.isPair(e))throw new Error(`Map items must all be pairs; found ${JSON.stringify(e)} instead`)}if(!e.allNullValues&&this.hasAllNullValues(false))e=Object.assign({},e,{allNullValues:true});return s.stringifyCollection(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:n,onComment:t})}}t.YAMLMap=YAMLMap;t.findPair=findPair},5161:(e,t,n)=>{var s=n(2466);var i=n(3466);var r=n(1399);var o=n(9338);var a=n(2463);class YAMLSeq extends i.Collection{constructor(e){super(r.SEQ,e);this.items=[]}static get tagName(){return"tag:yaml.org,2002:seq"}add(e){this.items.push(e)}delete(e){const t=asItemIndex(e);if(typeof t!=="number")return false;const n=this.items.splice(t,1);return n.length>0}get(e,t){const n=asItemIndex(e);if(typeof n!=="number")return undefined;const s=this.items[n];return!t&&r.isScalar(s)?s.value:s}has(e){const t=asItemIndex(e);return typeof t==="number"&&t<this.items.length}set(e,t){const n=asItemIndex(e);if(typeof n!=="number")throw new Error(`Expected a valid index, not ${e}.`);const s=this.items[n];if(r.isScalar(s)&&o.isScalarValue(t))s.value=t;else this.items[n]=t}toJSON(e,t){const n=[];if(t?.onCreate)t.onCreate(n);let s=0;for(const e of this.items)n.push(a.toJS(e,String(s++),t));return n}toString(e,t,n){if(!e)return JSON.stringify(this);return s.stringifyCollection(this,e,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(e.indent||"")+" ",onChompKeep:n,onComment:t})}}function asItemIndex(e){let t=r.isScalar(e)?e.value:e;if(t&&typeof t==="string")t=Number(t);return typeof t==="number"&&Number.isInteger(t)&&t>=0?t:null}t.YAMLSeq=YAMLSeq},4676:(e,t,n)=>{var s=n(6909);var i=n(8409);var r=n(1399);var o=n(9338);var a=n(2463);const c="<<";function addPairToJSMap(e,t,{key:n,value:s}){if(e?.doc.schema.merge&&isMergeKey(n)){s=r.isAlias(s)?s.resolve(e.doc):s;if(r.isSeq(s))for(const n of s.items)mergeToJSMap(e,t,n);else if(Array.isArray(s))for(const n of s)mergeToJSMap(e,t,n);else mergeToJSMap(e,t,s)}else{const i=a.toJS(n,"",e);if(t instanceof Map){t.set(i,a.toJS(s,i,e))}else if(t instanceof Set){t.add(i)}else{const r=stringifyKey(n,i,e);const o=a.toJS(s,r,e);if(r in t)Object.defineProperty(t,r,{value:o,writable:true,enumerable:true,configurable:true});else t[r]=o}}return t}const isMergeKey=e=>e===c||r.isScalar(e)&&e.value===c&&(!e.type||e.type===o.Scalar.PLAIN);function mergeToJSMap(e,t,n){const s=e&&r.isAlias(n)?n.resolve(e.doc):n;if(!r.isMap(s))throw new Error("Merge sources must be maps or map aliases");const i=s.toJSON(null,e,Map);for(const[e,n]of i){if(t instanceof Map){if(!t.has(e))t.set(e,n)}else if(t instanceof Set){t.add(e)}else if(!Object.prototype.hasOwnProperty.call(t,e)){Object.defineProperty(t,e,{value:n,writable:true,enumerable:true,configurable:true})}}return t}function stringifyKey(e,t,n){if(t===null)return"";if(typeof t!=="object")return String(t);if(r.isNode(e)&&n&&n.doc){const t=i.createStringifyContext(n.doc,{});t.anchors=new Set;for(const e of n.anchors.keys())t.anchors.add(e.anchor);t.inFlow=true;t.inStringifyKey=true;const r=e.toString(t);if(!n.mapKeyWarned){let e=JSON.stringify(r);if(e.length>40)e=e.substring(0,36)+'..."';s.warn(n.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${e}. Set mapAsMap: true to use object keys.`);n.mapKeyWarned=true}return r}return JSON.stringify(t)}t.addPairToJSMap=addPairToJSMap},2463:(e,t,n)=>{var s=n(1399);function toJS(e,t,n){if(Array.isArray(e))return e.map(((e,t)=>toJS(e,String(t),n)));if(e&&typeof e.toJSON==="function"){if(!n||!s.hasAnchor(e))return e.toJSON(t,n);const i={aliasCount:0,count:1,res:undefined};n.anchors.set(e,i);n.onCreate=e=>{i.res=e;delete n.onCreate};const r=e.toJSON(t,n);if(n.onCreate)n.onCreate(r);return r}if(typeof e==="bigint"&&!n?.keep)return Number(e);return e}t.toJS=toJS},9027:(e,t,n)=>{var s=n(9485);var i=n(7578);var r=n(4236);var o=n(6226);function resolveAsScalar(e,t=true,n){if(e){const _onError=(e,t,s)=>{const i=typeof e==="number"?e:Array.isArray(e)?e[0]:e.offset;if(n)n(i,t,s);else throw new r.YAMLParseError([i,i+1],t,s)};switch(e.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return i.resolveFlowScalar(e,t,_onError);case"block-scalar":return s.resolveBlockScalar(e,t,_onError)}}return null}function createScalarToken(e,t){const{implicitKey:n=false,indent:s,inFlow:i=false,offset:r=-1,type:a="PLAIN"}=t;const c=o.stringifyString({type:a,value:e},{implicitKey:n,indent:s>0?" ".repeat(s):"",inFlow:i,options:{blockQuote:true,lineWidth:-1}});const l=t.end??[{type:"newline",offset:-1,indent:s,source:"\n"}];switch(c[0]){case"|":case">":{const e=c.indexOf("\n");const t=c.substring(0,e);const n=c.substring(e+1)+"\n";const i=[{type:"block-scalar-header",offset:r,indent:s,source:t}];if(!addEndtoBlockProps(i,l))i.push({type:"newline",offset:-1,indent:s,source:"\n"});return{type:"block-scalar",offset:r,indent:s,props:i,source:n}}case'"':return{type:"double-quoted-scalar",offset:r,indent:s,source:c,end:l};case"'":return{type:"single-quoted-scalar",offset:r,indent:s,source:c,end:l};default:return{type:"scalar",offset:r,indent:s,source:c,end:l}}}function setScalarValue(e,t,n={}){let{afterKey:s=false,implicitKey:i=false,inFlow:r=false,type:a}=n;let c="indent"in e?e.indent:null;if(s&&typeof c==="number")c+=2;if(!a)switch(e.type){case"single-quoted-scalar":a="QUOTE_SINGLE";break;case"double-quoted-scalar":a="QUOTE_DOUBLE";break;case"block-scalar":{const t=e.props[0];if(t.type!=="block-scalar-header")throw new Error("Invalid block scalar header");a=t.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:a="PLAIN"}const l=o.stringifyString({type:a,value:t},{implicitKey:i||c===null,indent:c!==null&&c>0?" ".repeat(c):"",inFlow:r,options:{blockQuote:true,lineWidth:-1}});switch(l[0]){case"|":case">":setBlockScalarValue(e,l);break;case'"':setFlowScalarValue(e,l,"double-quoted-scalar");break;case"'":setFlowScalarValue(e,l,"single-quoted-scalar");break;default:setFlowScalarValue(e,l,"scalar")}}function setBlockScalarValue(e,t){const n=t.indexOf("\n");const s=t.substring(0,n);const i=t.substring(n+1)+"\n";if(e.type==="block-scalar"){const t=e.props[0];if(t.type!=="block-scalar-header")throw new Error("Invalid block scalar header");t.source=s;e.source=i}else{const{offset:t}=e;const n="indent"in e?e.indent:-1;const r=[{type:"block-scalar-header",offset:t,indent:n,source:s}];if(!addEndtoBlockProps(r,"end"in e?e.end:undefined))r.push({type:"newline",offset:-1,indent:n,source:"\n"});for(const t of Object.keys(e))if(t!=="type"&&t!=="offset")delete e[t];Object.assign(e,{type:"block-scalar",indent:n,props:r,source:i})}}function addEndtoBlockProps(e,t){if(t)for(const n of t)switch(n.type){case"space":case"comment":e.push(n);break;case"newline":e.push(n);return true}return false}function setFlowScalarValue(e,t,n){switch(e.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":e.type=n;e.source=t;break;case"block-scalar":{const s=e.props.slice(1);let i=t.length;if(e.props[0].type==="block-scalar-header")i-=e.props[0].source.length;for(const e of s)e.offset+=i;delete e.props;Object.assign(e,{type:n,source:t,end:s});break}case"block-map":case"block-seq":{const s=e.offset+t.length;const i={type:"newline",offset:s,indent:e.indent,source:"\n"};delete e.items;Object.assign(e,{type:n,source:t,end:[i]});break}default:{const s="indent"in e?e.indent:-1;const i="end"in e&&Array.isArray(e.end)?e.end.filter((e=>e.type==="space"||e.type==="comment"||e.type==="newline")):[];for(const t of Object.keys(e))if(t!=="type"&&t!=="offset")delete e[t];Object.assign(e,{type:n,indent:s,source:t,end:i})}}}t.createScalarToken=createScalarToken;t.resolveAsScalar=resolveAsScalar;t.setScalarValue=setScalarValue},6307:(e,t)=>{const stringify=e=>"type"in e?stringifyToken(e):stringifyItem(e);function stringifyToken(e){switch(e.type){case"block-scalar":{let t="";for(const n of e.props)t+=stringifyToken(n);return t+e.source}case"block-map":case"block-seq":{let t="";for(const n of e.items)t+=stringifyItem(n);return t}case"flow-collection":{let t=e.start.source;for(const n of e.items)t+=stringifyItem(n);for(const n of e.end)t+=n.source;return t}case"document":{let t=stringifyItem(e);if(e.end)for(const n of e.end)t+=n.source;return t}default:{let t=e.source;if("end"in e&&e.end)for(const n of e.end)t+=n.source;return t}}}function stringifyItem({start:e,key:t,sep:n,value:s}){let i="";for(const t of e)i+=t.source;if(t)i+=stringifyToken(t);if(n)for(const e of n)i+=e.source;if(s)i+=stringifyToken(s);return i}t.stringify=stringify},8497:(e,t)=>{const n=Symbol("break visit");const s=Symbol("skip children");const i=Symbol("remove item");function visit(e,t){if("type"in e&&e.type==="document")e={start:e.start,value:e.value};_visit(Object.freeze([]),e,t)}visit.BREAK=n;visit.SKIP=s;visit.REMOVE=i;visit.itemAtPath=(e,t)=>{let n=e;for(const[e,s]of t){const t=n?.[e];if(t&&"items"in t){n=t.items[s]}else return undefined}return n};visit.parentCollection=(e,t)=>{const n=visit.itemAtPath(e,t.slice(0,-1));const s=t[t.length-1][0];const i=n?.[s];if(i&&"items"in i)return i;throw new Error("Parent collection not found")};function _visit(e,t,s){let r=s(t,e);if(typeof r==="symbol")return r;for(const o of["key","value"]){const a=t[o];if(a&&"items"in a){for(let t=0;t<a.items.length;++t){const r=_visit(Object.freeze(e.concat([[o,t]])),a.items[t],s);if(typeof r==="number")t=r-1;else if(r===n)return n;else if(r===i){a.items.splice(t,1);t-=1}}if(typeof r==="function"&&o==="key")r=r(t,e)}}return typeof r==="function"?r(t,e):r}t.visit=visit},9169:(e,t,n)=>{var s=n(9027);var i=n(6307);var r=n(8497);const o="\ufeff";const a="";const c="";const l="";const isCollection=e=>!!e&&"items"in e;const isScalar=e=>!!e&&(e.type==="scalar"||e.type==="single-quoted-scalar"||e.type==="double-quoted-scalar"||e.type==="block-scalar");function prettyToken(e){switch(e){case o:return"<BOM>";case a:return"<DOC>";case c:return"<FLOW_END>";case l:return"<SCALAR>";default:return JSON.stringify(e)}}function tokenType(e){switch(e){case o:return"byte-order-mark";case a:return"doc-mode";case c:return"flow-error-end";case l:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case"\n":case"\r\n":return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(e[0]){case" ":case"\t":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}t.createScalarToken=s.createScalarToken;t.resolveAsScalar=s.resolveAsScalar;t.setScalarValue=s.setScalarValue;t.stringify=i.stringify;t.visit=r.visit;t.BOM=o;t.DOCUMENT=a;t.FLOW_END=c;t.SCALAR=l;t.isCollection=isCollection;t.isScalar=isScalar;t.prettyToken=prettyToken;t.tokenType=tokenType},5976:(e,t,n)=>{var s=n(9169);function isEmpty(e){switch(e){case undefined:case" ":case"\n":case"\r":case"\t":return true;default:return false}}const i="0123456789ABCDEFabcdef".split("");const r="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()".split("");const o=",[]{}".split("");const a=" ,[]{}\n\r\t".split("");const isNotAnchorChar=e=>!e||a.includes(e);class Lexer{constructor(){this.atEnd=false;this.blockScalarIndent=-1;this.blockScalarKeep=false;this.buffer="";this.flowKey=false;this.flowLevel=0;this.indentNext=0;this.indentValue=0;this.lineEndPos=null;this.next=null;this.pos=0}*lex(e,t=false){if(e){this.buffer=this.buffer?this.buffer+e:e;this.lineEndPos=null}this.atEnd=!t;let n=this.next??"stream";while(n&&(t||this.hasChars(1)))n=yield*this.parseNext(n)}atLineEnd(){let e=this.pos;let t=this.buffer[e];while(t===" "||t==="\t")t=this.buffer[++e];if(!t||t==="#"||t==="\n")return true;if(t==="\r")return this.buffer[e+1]==="\n";return false}charAt(e){return this.buffer[this.pos+e]}continueScalar(e){let t=this.buffer[e];if(this.indentNext>0){let n=0;while(t===" ")t=this.buffer[++n+e];if(t==="\r"){const t=this.buffer[n+e+1];if(t==="\n"||!t&&!this.atEnd)return e+n+1}return t==="\n"||n>=this.indentNext||!t&&!this.atEnd?e+n:-1}if(t==="-"||t==="."){const t=this.buffer.substr(e,3);if((t==="---"||t==="...")&&isEmpty(this.buffer[e+3]))return-1}return e}getLine(){let e=this.lineEndPos;if(typeof e!=="number"||e!==-1&&e<this.pos){e=this.buffer.indexOf("\n",this.pos);this.lineEndPos=e}if(e===-1)return this.atEnd?this.buffer.substring(this.pos):null;if(this.buffer[e-1]==="\r")e-=1;return this.buffer.substring(this.pos,e)}hasChars(e){return this.pos+e<=this.buffer.length}setNext(e){this.buffer=this.buffer.substring(this.pos);this.pos=0;this.lineEndPos=null;this.next=e;return null}peek(e){return this.buffer.substr(this.pos,e)}*parseNext(e){switch(e){case"stream":return yield*this.parseStream();case"line-start":return yield*this.parseLineStart();case"block-start":return yield*this.parseBlockStart();case"doc":return yield*this.parseDocument();case"flow":return yield*this.parseFlowCollection();case"quoted-scalar":return yield*this.parseQuotedScalar();case"block-scalar":return yield*this.parseBlockScalar();case"plain-scalar":return yield*this.parsePlainScalar()}}*parseStream(){let e=this.getLine();if(e===null)return this.setNext("stream");if(e[0]===s.BOM){yield*this.pushCount(1);e=e.substring(1)}if(e[0]==="%"){let t=e.length;const n=e.indexOf("#");if(n!==-1){const s=e[n-1];if(s===" "||s==="\t")t=n-1}while(true){const n=e[t-1];if(n===" "||n==="\t")t-=1;else break}const s=(yield*this.pushCount(t))+(yield*this.pushSpaces(true));yield*this.pushCount(e.length-s);this.pushNewline();return"stream"}if(this.atLineEnd()){const t=yield*this.pushSpaces(true);yield*this.pushCount(e.length-t);yield*this.pushNewline();return"stream"}yield s.DOCUMENT;return yield*this.parseLineStart()}*parseLineStart(){const e=this.charAt(0);if(!e&&!this.atEnd)return this.setNext("line-start");if(e==="-"||e==="."){if(!this.atEnd&&!this.hasChars(4))return this.setNext("line-start");const e=this.peek(3);if(e==="---"&&isEmpty(this.charAt(3))){yield*this.pushCount(3);this.indentValue=0;this.indentNext=0;return"doc"}else if(e==="..."&&isEmpty(this.charAt(3))){yield*this.pushCount(3);return"stream"}}this.indentValue=yield*this.pushSpaces(false);if(this.indentNext>this.indentValue&&!isEmpty(this.charAt(1)))this.indentNext=this.indentValue;return yield*this.parseBlockStart()}*parseBlockStart(){const[e,t]=this.peek(2);if(!t&&!this.atEnd)return this.setNext("block-start");if((e==="-"||e==="?"||e===":")&&isEmpty(t)){const e=(yield*this.pushCount(1))+(yield*this.pushSpaces(true));this.indentNext=this.indentValue+1;this.indentValue+=e;return yield*this.parseBlockStart()}return"doc"}*parseDocument(){yield*this.pushSpaces(true);const e=this.getLine();if(e===null)return this.setNext("doc");let t=yield*this.pushIndicators();switch(e[t]){case"#":yield*this.pushCount(e.length-t);case undefined:yield*this.pushNewline();return yield*this.parseLineStart();case"{":case"[":yield*this.pushCount(1);this.flowKey=false;this.flowLevel=1;return"flow";case"}":case"]":yield*this.pushCount(1);return"doc";case"*":yield*this.pushUntil(isNotAnchorChar);return"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":t+=(yield*this.parseBlockScalarHeader());t+=(yield*this.pushSpaces(true));yield*this.pushCount(e.length-t);yield*this.pushNewline();return yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let e,t;let n=-1;do{e=yield*this.pushNewline();if(e>0){t=yield*this.pushSpaces(false);this.indentValue=n=t}else{t=0}t+=(yield*this.pushSpaces(true))}while(e+t>0);const i=this.getLine();if(i===null)return this.setNext("flow");if(n!==-1&&n<this.indentNext&&i[0]!=="#"||n===0&&(i.startsWith("---")||i.startsWith("..."))&&isEmpty(i[3])){const e=n===this.indentNext-1&&this.flowLevel===1&&(i[0]==="]"||i[0]==="}");if(!e){this.flowLevel=0;yield s.FLOW_END;return yield*this.parseLineStart()}}let r=0;while(i[r]===","){r+=(yield*this.pushCount(1));r+=(yield*this.pushSpaces(true));this.flowKey=false}r+=(yield*this.pushIndicators());switch(i[r]){case undefined:return"flow";case"#":yield*this.pushCount(i.length-r);return"flow";case"{":case"[":yield*this.pushCount(1);this.flowKey=false;this.flowLevel+=1;return"flow";case"}":case"]":yield*this.pushCount(1);this.flowKey=true;this.flowLevel-=1;return this.flowLevel?"flow":"doc";case"*":yield*this.pushUntil(isNotAnchorChar);return"flow";case'"':case"'":this.flowKey=true;return yield*this.parseQuotedScalar();case":":{const e=this.charAt(1);if(this.flowKey||isEmpty(e)||e===","){this.flowKey=false;yield*this.pushCount(1);yield*this.pushSpaces(true);return"flow"}}default:this.flowKey=false;return yield*this.parsePlainScalar()}}*parseQuotedScalar(){const e=this.charAt(0);let t=this.buffer.indexOf(e,this.pos+1);if(e==="'"){while(t!==-1&&this.buffer[t+1]==="'")t=this.buffer.indexOf("'",t+2)}else{while(t!==-1){let e=0;while(this.buffer[t-1-e]==="\\")e+=1;if(e%2===0)break;t=this.buffer.indexOf('"',t+1)}}const n=this.buffer.substring(0,t);let s=n.indexOf("\n",this.pos);if(s!==-1){while(s!==-1){const e=this.continueScalar(s+1);if(e===-1)break;s=n.indexOf("\n",e)}if(s!==-1){t=s-(n[s-1]==="\r"?2:1)}}if(t===-1){if(!this.atEnd)return this.setNext("quoted-scalar");t=this.buffer.length}yield*this.pushToIndex(t+1,false);return this.flowLevel?"flow":"doc"}*parseBlockScalarHeader(){this.blockScalarIndent=-1;this.blockScalarKeep=false;let e=this.pos;while(true){const t=this.buffer[++e];if(t==="+")this.blockScalarKeep=true;else if(t>"0"&&t<="9")this.blockScalarIndent=Number(t)-1;else if(t!=="-")break}return yield*this.pushUntil((e=>isEmpty(e)||e==="#"))}*parseBlockScalar(){let e=this.pos-1;let t=0;let n;e:for(let s=this.pos;n=this.buffer[s];++s){switch(n){case" ":t+=1;break;case"\n":e=s;t=0;break;case"\r":{const e=this.buffer[s+1];if(!e&&!this.atEnd)return this.setNext("block-scalar");if(e==="\n")break}default:break e}}if(!n&&!this.atEnd)return this.setNext("block-scalar");if(t>=this.indentNext){if(this.blockScalarIndent===-1)this.indentNext=t;else this.indentNext+=this.blockScalarIndent;do{const t=this.continueScalar(e+1);if(t===-1)break;e=this.buffer.indexOf("\n",t)}while(e!==-1);if(e===-1){if(!this.atEnd)return this.setNext("block-scalar");e=this.buffer.length}}if(!this.blockScalarKeep){do{let n=e-1;let s=this.buffer[n];if(s==="\r")s=this.buffer[--n];const i=n;while(s===" "||s==="\t")s=this.buffer[--n];if(s==="\n"&&n>=this.pos&&n+1+t>i)e=n;else break}while(true)}yield s.SCALAR;yield*this.pushToIndex(e+1,true);return yield*this.parseLineStart()}*parsePlainScalar(){const e=this.flowLevel>0;let t=this.pos-1;let n=this.pos-1;let i;while(i=this.buffer[++n]){if(i===":"){const s=this.buffer[n+1];if(isEmpty(s)||e&&s===",")break;t=n}else if(isEmpty(i)){let s=this.buffer[n+1];if(i==="\r"){if(s==="\n"){n+=1;i="\n";s=this.buffer[n+1]}else t=n}if(s==="#"||e&&o.includes(s))break;if(i==="\n"){const e=this.continueScalar(n+1);if(e===-1)break;n=Math.max(n,e-2)}}else{if(e&&o.includes(i))break;t=n}}if(!i&&!this.atEnd)return this.setNext("plain-scalar");yield s.SCALAR;yield*this.pushToIndex(t+1,true);return e?"flow":"doc"}*pushCount(e){if(e>0){yield this.buffer.substr(this.pos,e);this.pos+=e;return e}return 0}*pushToIndex(e,t){const n=this.buffer.slice(this.pos,e);if(n){yield n;this.pos+=n.length;return n.length}else if(t)yield"";return 0}*pushIndicators(){switch(this.charAt(0)){case"!":return(yield*this.pushTag())+(yield*this.pushSpaces(true))+(yield*this.pushIndicators());case"&":return(yield*this.pushUntil(isNotAnchorChar))+(yield*this.pushSpaces(true))+(yield*this.pushIndicators());case"-":case"?":case":":{const e=this.flowLevel>0;const t=this.charAt(1);if(isEmpty(t)||e&&o.includes(t)){if(!e)this.indentNext=this.indentValue+1;else if(this.flowKey)this.flowKey=false;return(yield*this.pushCount(1))+(yield*this.pushSpaces(true))+(yield*this.pushIndicators())}}}return 0}*pushTag(){if(this.charAt(1)==="<"){let e=this.pos+2;let t=this.buffer[e];while(!isEmpty(t)&&t!==">")t=this.buffer[++e];return yield*this.pushToIndex(t===">"?e+1:e,false)}else{let e=this.pos+1;let t=this.buffer[e];while(t){if(r.includes(t))t=this.buffer[++e];else if(t==="%"&&i.includes(this.buffer[e+1])&&i.includes(this.buffer[e+2])){t=this.buffer[e+=3]}else break}return yield*this.pushToIndex(e,false)}}*pushNewline(){const e=this.buffer[this.pos];if(e==="\n")return yield*this.pushCount(1);else if(e==="\r"&&this.charAt(1)==="\n")return yield*this.pushCount(2);else return 0}*pushSpaces(e){let t=this.pos-1;let n;do{n=this.buffer[++t]}while(n===" "||e&&n==="\t");const s=t-this.pos;if(s>0){yield this.buffer.substr(this.pos,s);this.pos=t}return s}*pushUntil(e){let t=this.pos;let n=this.buffer[t];while(!e(n))n=this.buffer[++t];return yield*this.pushToIndex(t,false)}}t.Lexer=Lexer},1929:(e,t)=>{class LineCounter{constructor(){this.lineStarts=[];this.addNewLine=e=>this.lineStarts.push(e);this.linePos=e=>{let t=0;let n=this.lineStarts.length;while(t<n){const s=t+n>>1;if(this.lineStarts[s]<e)t=s+1;else n=s}if(this.lineStarts[t]===e)return{line:t+1,col:1};if(t===0)return{line:0,col:e};const s=this.lineStarts[t-1];return{line:t,col:e-s+1}}}}t.LineCounter=LineCounter},3328:(e,t,n)=>{var s=n(9169);var i=n(5976);function includesToken(e,t){for(let n=0;n<e.length;++n)if(e[n].type===t)return true;return false}function findNonEmptyIndex(e){for(let t=0;t<e.length;++t){switch(e[t].type){case"space":case"comment":case"newline":break;default:return t}}return-1}function isFlowToken(e){switch(e?.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"flow-collection":return true;default:return false}}function getPrevProps(e){switch(e.type){case"document":return e.start;case"block-map":{const t=e.items[e.items.length-1];return t.sep??t.start}case"block-seq":return e.items[e.items.length-1].start;default:return[]}}function getFirstKeyStartProps(e){if(e.length===0)return[];let t=e.length;e:while(--t>=0){switch(e[t].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break e}}while(e[++t]?.type==="space"){}return e.splice(t,e.length)}function fixFlowSeqItems(e){if(e.start.type==="flow-seq-start"){for(const t of e.items){if(t.sep&&!t.value&&!includesToken(t.start,"explicit-key-ind")&&!includesToken(t.sep,"map-value-ind")){if(t.key)t.value=t.key;delete t.key;if(isFlowToken(t.value)){if(t.value.end)Array.prototype.push.apply(t.value.end,t.sep);else t.value.end=t.sep}else Array.prototype.push.apply(t.start,t.sep);delete t.sep}}}}class Parser{constructor(e){this.atNewLine=true;this.atScalar=false;this.indent=0;this.offset=0;this.onKeyLine=false;this.stack=[];this.source="";this.type="";this.lexer=new i.Lexer;this.onNewLine=e}*parse(e,t=false){if(this.onNewLine&&this.offset===0)this.onNewLine(0);for(const n of this.lexer.lex(e,t))yield*this.next(n);if(!t)yield*this.end()}*next(e){this.source=e;if(process.env.LOG_TOKENS)console.log("|",s.prettyToken(e));if(this.atScalar){this.atScalar=false;yield*this.step();this.offset+=e.length;return}const t=s.tokenType(e);if(!t){const t=`Not a YAML token: ${e}`;yield*this.pop({type:"error",offset:this.offset,message:t,source:e});this.offset+=e.length}else if(t==="scalar"){this.atNewLine=false;this.atScalar=true;this.type="scalar"}else{this.type=t;yield*this.step();switch(t){case"newline":this.atNewLine=true;this.indent=0;if(this.onNewLine)this.onNewLine(this.offset+e.length);break;case"space":if(this.atNewLine&&e[0]===" ")this.indent+=e.length;break;case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":if(this.atNewLine)this.indent+=e.length;break;case"doc-mode":case"flow-error-end":return;default:this.atNewLine=false}this.offset+=e.length}}*end(){while(this.stack.length>0)yield*this.pop()}get sourceToken(){const e={type:this.type,offset:this.offset,indent:this.indent,source:this.source};return e}*step(){const e=this.peek(1);if(this.type==="doc-end"&&(!e||e.type!=="doc-end")){while(this.stack.length>0)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!e)return yield*this.stream();switch(e.type){case"document":return yield*this.document(e);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(e);case"block-scalar":return yield*this.blockScalar(e);case"block-map":return yield*this.blockMap(e);case"block-seq":return yield*this.blockSequence(e);case"flow-collection":return yield*this.flowCollection(e);case"doc-end":return yield*this.documentEnd(e)}yield*this.pop()}peek(e){return this.stack[this.stack.length-e]}*pop(e){const t=e??this.stack.pop();if(!t){const e="Tried to pop an empty stack";yield{type:"error",offset:this.offset,source:"",message:e}}else if(this.stack.length===0){yield t}else{const e=this.peek(1);if(t.type==="block-scalar"){t.indent="indent"in e?e.indent:0}else if(t.type==="flow-collection"&&e.type==="document"){t.indent=0}if(t.type==="flow-collection")fixFlowSeqItems(t);switch(e.type){case"document":e.value=t;break;case"block-scalar":e.props.push(t);break;case"block-map":{const n=e.items[e.items.length-1];if(n.value){e.items.push({start:[],key:t,sep:[]});this.onKeyLine=true;return}else if(n.sep){n.value=t}else{Object.assign(n,{key:t,sep:[]});this.onKeyLine=!includesToken(n.start,"explicit-key-ind");return}break}case"block-seq":{const n=e.items[e.items.length-1];if(n.value)e.items.push({start:[],value:t});else n.value=t;break}case"flow-collection":{const n=e.items[e.items.length-1];if(!n||n.value)e.items.push({start:[],key:t,sep:[]});else if(n.sep)n.value=t;else Object.assign(n,{key:t,sep:[]});return}default:yield*this.pop();yield*this.pop(t)}if((e.type==="document"||e.type==="block-map"||e.type==="block-seq")&&(t.type==="block-map"||t.type==="block-seq")){const n=t.items[t.items.length-1];if(n&&!n.sep&&!n.value&&n.start.length>0&&findNonEmptyIndex(n.start)===-1&&(t.indent===0||n.start.every((e=>e.type!=="comment"||e.indent<t.indent)))){if(e.type==="document")e.end=n.start;else e.items.push({start:n.start});t.items.splice(-1,1)}}}}*stream(){switch(this.type){case"directive-line":yield{type:"directive",offset:this.offset,source:this.source};return;case"byte-order-mark":case"space":case"comment":case"newline":yield this.sourceToken;return;case"doc-mode":case"doc-start":{const e={type:"document",offset:this.offset,start:[]};if(this.type==="doc-start")e.start.push(this.sourceToken);this.stack.push(e);return}}yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML stream`,source:this.source}}*document(e){if(e.value)return yield*this.lineEnd(e);switch(this.type){case"doc-start":{if(findNonEmptyIndex(e.start)!==-1){yield*this.pop();yield*this.step()}else e.start.push(this.sourceToken);return}case"anchor":case"tag":case"space":case"comment":case"newline":e.start.push(this.sourceToken);return}const t=this.startBlockValue(e);if(t)this.stack.push(t);else{yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML document`,source:this.source}}}*scalar(e){if(this.type==="map-value-ind"){const t=getPrevProps(this.peek(2));const n=getFirstKeyStartProps(t);let s;if(e.end){s=e.end;s.push(this.sourceToken);delete e.end}else s=[this.sourceToken];const i={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:n,key:e,sep:s}]};this.onKeyLine=true;this.stack[this.stack.length-1]=i}else yield*this.lineEnd(e)}*blockScalar(e){switch(this.type){case"space":case"comment":case"newline":e.props.push(this.sourceToken);return;case"scalar":e.source=this.source;this.atNewLine=true;this.indent=0;if(this.onNewLine){let e=this.source.indexOf("\n")+1;while(e!==0){this.onNewLine(this.offset+e);e=this.source.indexOf("\n",e)+1}}yield*this.pop();break;default:yield*this.pop();yield*this.step()}}*blockMap(e){const t=e.items[e.items.length-1];switch(this.type){case"newline":this.onKeyLine=false;if(t.value){const n="end"in t.value?t.value.end:undefined;const s=Array.isArray(n)?n[n.length-1]:undefined;if(s?.type==="comment")n?.push(this.sourceToken);else e.items.push({start:[this.sourceToken]})}else if(t.sep){t.sep.push(this.sourceToken)}else{t.start.push(this.sourceToken)}return;case"space":case"comment":if(t.value){e.items.push({start:[this.sourceToken]})}else if(t.sep){t.sep.push(this.sourceToken)}else{if(this.atIndentedComment(t.start,e.indent)){const n=e.items[e.items.length-2];const s=n?.value?.end;if(Array.isArray(s)){Array.prototype.push.apply(s,t.start);s.push(this.sourceToken);e.items.pop();return}}t.start.push(this.sourceToken)}return}if(this.indent>=e.indent){const n=!this.onKeyLine&&this.indent===e.indent&&t.sep;let s=[];if(n&&t.sep&&!t.value){const n=[];for(let s=0;s<t.sep.length;++s){const i=t.sep[s];switch(i.type){case"newline":n.push(s);break;case"space":break;case"comment":if(i.indent>e.indent)n.length=0;break;default:n.length=0}}if(n.length>=2)s=t.sep.splice(n[1])}switch(this.type){case"anchor":case"tag":if(n||t.value){s.push(this.sourceToken);e.items.push({start:s});this.onKeyLine=true}else if(t.sep){t.sep.push(this.sourceToken)}else{t.start.push(this.sourceToken)}return;case"explicit-key-ind":if(!t.sep&&!includesToken(t.start,"explicit-key-ind")){t.start.push(this.sourceToken)}else if(n||t.value){s.push(this.sourceToken);e.items.push({start:s})}else{this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]})}this.onKeyLine=true;return;case"map-value-ind":if(includesToken(t.start,"explicit-key-ind")){if(!t.sep){if(includesToken(t.start,"newline")){Object.assign(t,{key:null,sep:[this.sourceToken]})}else{const e=getFirstKeyStartProps(t.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:e,key:null,sep:[this.sourceToken]}]})}}else if(t.value){e.items.push({start:[],key:null,sep:[this.sourceToken]})}else if(includesToken(t.sep,"map-value-ind")){this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:s,key:null,sep:[this.sourceToken]}]})}else if(isFlowToken(t.key)&&!includesToken(t.sep,"newline")){const e=getFirstKeyStartProps(t.start);const n=t.key;const s=t.sep;s.push(this.sourceToken);delete t.key,delete t.sep;this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:e,key:n,sep:s}]})}else if(s.length>0){t.sep=t.sep.concat(s,this.sourceToken)}else{t.sep.push(this.sourceToken)}}else{if(!t.sep){Object.assign(t,{key:null,sep:[this.sourceToken]})}else if(t.value||n){e.items.push({start:s,key:null,sep:[this.sourceToken]})}else if(includesToken(t.sep,"map-value-ind")){this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]})}else{t.sep.push(this.sourceToken)}}this.onKeyLine=true;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{const i=this.flowScalar(this.type);if(n||t.value){e.items.push({start:s,key:i,sep:[]});this.onKeyLine=true}else if(t.sep){this.stack.push(i)}else{Object.assign(t,{key:i,sep:[]});this.onKeyLine=true}return}default:{const i=this.startBlockValue(e);if(i){if(n&&i.type!=="block-seq"&&includesToken(t.start,"explicit-key-ind")){e.items.push({start:s})}this.stack.push(i);return}}}}yield*this.pop();yield*this.step()}*blockSequence(e){const t=e.items[e.items.length-1];switch(this.type){case"newline":if(t.value){const n="end"in t.value?t.value.end:undefined;const s=Array.isArray(n)?n[n.length-1]:undefined;if(s?.type==="comment")n?.push(this.sourceToken);else e.items.push({start:[this.sourceToken]})}else t.start.push(this.sourceToken);return;case"space":case"comment":if(t.value)e.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(t.start,e.indent)){const n=e.items[e.items.length-2];const s=n?.value?.end;if(Array.isArray(s)){Array.prototype.push.apply(s,t.start);s.push(this.sourceToken);e.items.pop();return}}t.start.push(this.sourceToken)}return;case"anchor":case"tag":if(t.value||this.indent<=e.indent)break;t.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==e.indent)break;if(t.value||includesToken(t.start,"seq-item-ind"))e.items.push({start:[this.sourceToken]});else t.start.push(this.sourceToken);return}if(this.indent>e.indent){const t=this.startBlockValue(e);if(t){this.stack.push(t);return}}yield*this.pop();yield*this.step()}*flowCollection(e){const t=e.items[e.items.length-1];if(this.type==="flow-error-end"){let e;do{yield*this.pop();e=this.peek(1)}while(e&&e.type==="flow-collection")}else if(e.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":if(!t||t.sep)e.items.push({start:[this.sourceToken]});else t.start.push(this.sourceToken);return;case"map-value-ind":if(!t||t.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(t.sep)t.sep.push(this.sourceToken);else Object.assign(t,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":if(!t||t.value)e.items.push({start:[this.sourceToken]});else if(t.sep)t.sep.push(this.sourceToken);else t.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{const n=this.flowScalar(this.type);if(!t||t.value)e.items.push({start:[],key:n,sep:[]});else if(t.sep)this.stack.push(n);else Object.assign(t,{key:n,sep:[]});return}case"flow-map-end":case"flow-seq-end":e.end.push(this.sourceToken);return}const n=this.startBlockValue(e);if(n)this.stack.push(n);else{yield*this.pop();yield*this.step()}}else{const t=this.peek(2);if(t.type==="block-map"&&(this.type==="map-value-ind"&&t.indent===e.indent||this.type==="newline"&&!t.items[t.items.length-1].sep)){yield*this.pop();yield*this.step()}else if(this.type==="map-value-ind"&&t.type!=="flow-collection"){const n=getPrevProps(t);const s=getFirstKeyStartProps(n);fixFlowSeqItems(e);const i=e.end.splice(1,e.end.length);i.push(this.sourceToken);const r={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:s,key:e,sep:i}]};this.onKeyLine=true;this.stack[this.stack.length-1]=r}else{yield*this.lineEnd(e)}}}flowScalar(e){if(this.onNewLine){let e=this.source.indexOf("\n")+1;while(e!==0){this.onNewLine(this.offset+e);e=this.source.indexOf("\n",e)+1}}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=true;const t=getPrevProps(e);const n=getFirstKeyStartProps(t);n.push(this.sourceToken);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:n}]}}case"map-value-ind":{this.onKeyLine=true;const t=getPrevProps(e);const n=getFirstKeyStartProps(t);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:n,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,t){if(this.type!=="comment")return false;if(this.indent<=t)return false;return e.every((e=>e.type==="newline"||e.type==="space"))}*documentEnd(e){if(this.type!=="doc-mode"){if(e.end)e.end.push(this.sourceToken);else e.end=[this.sourceToken];if(this.type==="newline")yield*this.pop()}}*lineEnd(e){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop();yield*this.step();break;case"newline":this.onKeyLine=false;case"space":case"comment":default:if(e.end)e.end.push(this.sourceToken);else e.end=[this.sourceToken];if(this.type==="newline")yield*this.pop()}}}t.Parser=Parser},8649:(e,t,n)=>{var s=n(9493);var i=n(42);var r=n(4236);var o=n(6909);var a=n(1929);var c=n(3328);function parseOptions(e){const t=e.prettyErrors!==false;const n=e.lineCounter||t&&new a.LineCounter||null;return{lineCounter:n,prettyErrors:t}}function parseAllDocuments(e,t={}){const{lineCounter:n,prettyErrors:i}=parseOptions(t);const o=new c.Parser(n?.addNewLine);const a=new s.Composer(t);const l=Array.from(a.compose(o.parse(e)));if(i&&n)for(const t of l){t.errors.forEach(r.prettifyError(e,n));t.warnings.forEach(r.prettifyError(e,n))}if(l.length>0)return l;return Object.assign([],{empty:true},a.streamInfo())}function parseDocument(e,t={}){const{lineCounter:n,prettyErrors:i}=parseOptions(t);const o=new c.Parser(n?.addNewLine);const a=new s.Composer(t);let l=null;for(const t of a.compose(o.parse(e),true,e.length)){if(!l)l=t;else if(l.options.logLevel!=="silent"){l.errors.push(new r.YAMLParseError(t.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}}if(i&&n){l.errors.forEach(r.prettifyError(e,n));l.warnings.forEach(r.prettifyError(e,n))}return l}function parse(e,t,n){let s=undefined;if(typeof t==="function"){s=t}else if(n===undefined&&t&&typeof t==="object"){n=t}const i=parseDocument(e,n);if(!i)return null;i.warnings.forEach((e=>o.warn(i.options.logLevel,e)));if(i.errors.length>0){if(i.options.logLevel!=="silent")throw i.errors[0];else i.errors=[]}return i.toJS(Object.assign({reviver:s},n))}function stringify(e,t,n){let s=null;if(typeof t==="function"||Array.isArray(t)){s=t}else if(n===undefined&&t){n=t}if(typeof n==="string")n=n.length;if(typeof n==="number"){const e=Math.round(n);n=e<1?undefined:e>8?{indent:8}:{indent:e}}if(e===undefined){const{keepUndefined:e}=n??t??{};if(!e)return undefined}return new i.Document(e,s,n).toString(n)}t.parse=parse;t.parseAllDocuments=parseAllDocuments;t.parseDocument=parseDocument;t.stringify=stringify},6831:(e,t,n)=>{var s=n(1399);var i=n(83);var r=n(1693);var o=n(2201);var a=n(4138);const sortMapEntriesByKey=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0;class Schema{constructor({compat:e,customTags:t,merge:n,resolveKnownTags:c,schema:l,sortMapEntries:f,toStringDefaults:u}){this.compat=Array.isArray(e)?a.getTags(e,"compat"):e?a.getTags(null,e):null;this.merge=!!n;this.name=typeof l==="string"&&l||"core";this.knownTags=c?a.coreKnownTags:{};this.tags=a.getTags(t,this.name);this.toStringOptions=u??null;Object.defineProperty(this,s.MAP,{value:i.map});Object.defineProperty(this,s.SCALAR,{value:o.string});Object.defineProperty(this,s.SEQ,{value:r.seq});this.sortMapEntries=typeof f==="function"?f:f===true?sortMapEntriesByKey:null}clone(){const e=Object.create(Schema.prototype,Object.getOwnPropertyDescriptors(this));e.tags=this.tags.slice();return e}}t.Schema=Schema},83:(e,t,n)=>{var s=n(1399);var i=n(246);var r=n(6011);function createMap(e,t,n){const{keepUndefined:s,replacer:o}=n;const a=new r.YAMLMap(e);const add=(e,r)=>{if(typeof o==="function")r=o.call(t,e,r);else if(Array.isArray(o)&&!o.includes(e))return;if(r!==undefined||s)a.items.push(i.createPair(e,r,n))};if(t instanceof Map){for(const[e,n]of t)add(e,n)}else if(t&&typeof t==="object"){for(const e of Object.keys(t))add(e,t[e])}if(typeof e.sortMapEntries==="function"){a.items.sort(e.sortMapEntries)}return a}const o={collection:"map",createNode:createMap,default:true,nodeClass:r.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(e,t){if(!s.isMap(e))t("Expected a mapping for this tag");return e}};t.map=o},6703:(e,t,n)=>{var s=n(9338);const i={identify:e=>e==null,createNode:()=>new s.Scalar(null),default:true,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new s.Scalar(null),stringify:({source:e},t)=>typeof e==="string"&&i.test.test(e)?e:t.options.nullStr};t.nullTag=i},1693:(e,t,n)=>{var s=n(9652);var i=n(1399);var r=n(5161);function createSeq(e,t,n){const{replacer:i}=n;const o=new r.YAMLSeq(e);if(t&&Symbol.iterator in Object(t)){let e=0;for(let r of t){if(typeof i==="function"){const n=t instanceof Set?r:String(e++);r=i.call(t,n,r)}o.items.push(s.createNode(r,undefined,n))}}return o}const o={collection:"seq",createNode:createSeq,default:true,nodeClass:r.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(e,t){if(!i.isSeq(e))t("Expected a sequence for this tag");return e}};t.seq=o},2201:(e,t,n)=>{var s=n(6226);const i={identify:e=>typeof e==="string",default:true,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify(e,t,n,i){t=Object.assign({actualString:true},t);return s.stringifyString(e,t,n,i)}};t.string=i},2045:(e,t,n)=>{var s=n(9338);const i={identify:e=>typeof e==="boolean",default:true,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new s.Scalar(e[0]==="t"||e[0]==="T"),stringify({source:e,value:t},n){if(e&&i.test.test(e)){const n=e[0]==="t"||e[0]==="T";if(t===n)return e}return t?n.options.trueStr:n.options.falseStr}};t.boolTag=i},6810:(e,t,n)=>{var s=n(9338);var i=n(4174);const r={identify:e=>typeof e==="number",default:true,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF|nan|NaN|NAN))$/,resolve:e=>e.slice(-3).toLowerCase()==="nan"?NaN:e[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:i.stringifyNumber};const o={identify:e=>typeof e==="number",default:true,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e),stringify(e){const t=Number(e.value);return isFinite(t)?t.toExponential():i.stringifyNumber(e)}};const a={identify:e=>typeof e==="number",default:true,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(e){const t=new s.Scalar(parseFloat(e));const n=e.indexOf(".");if(n!==-1&&e[e.length-1]==="0")t.minFractionDigits=e.length-n-1;return t},stringify:i.stringifyNumber};t.float=a;t.floatExp=o;t.floatNaN=r},3019:(e,t,n)=>{var s=n(4174);const intIdentify=e=>typeof e==="bigint"||Number.isInteger(e);const intResolve=(e,t,n,{intAsBigInt:s})=>s?BigInt(e):parseInt(e.substring(t),n);function intStringify(e,t,n){const{value:i}=e;if(intIdentify(i)&&i>=0)return n+i.toString(t);return s.stringifyNumber(e)}const i={identify:e=>intIdentify(e)&&e>=0,default:true,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(e,t,n)=>intResolve(e,2,8,n),stringify:e=>intStringify(e,8,"0o")};const r={identify:intIdentify,default:true,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(e,t,n)=>intResolve(e,0,10,n),stringify:s.stringifyNumber};const o={identify:e=>intIdentify(e)&&e>=0,default:true,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,n)=>intResolve(e,2,16,n),stringify:e=>intStringify(e,16,"0x")};t.int=r;t.intHex=o;t.intOct=i},27:(e,t,n)=>{var s=n(83);var i=n(6703);var r=n(1693);var o=n(2201);var a=n(2045);var c=n(6810);var l=n(3019);const f=[s.map,r.seq,o.string,i.nullTag,a.boolTag,l.intOct,l.int,l.intHex,c.floatNaN,c.floatExp,c.float];t.schema=f},4545:(e,t,n)=>{var s=n(9338);var i=n(83);var r=n(1693);function intIdentify(e){return typeof e==="bigint"||Number.isInteger(e)}const stringifyJSON=({value:e})=>JSON.stringify(e);const o=[{identify:e=>typeof e==="string",default:true,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:stringifyJSON},{identify:e=>e==null,createNode:()=>new s.Scalar(null),default:true,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:stringifyJSON},{identify:e=>typeof e==="boolean",default:true,tag:"tag:yaml.org,2002:bool",test:/^true|false$/,resolve:e=>e==="true",stringify:stringifyJSON},{identify:intIdentify,default:true,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(e,t,{intAsBigInt:n})=>n?BigInt(e):parseInt(e,10),stringify:({value:e})=>intIdentify(e)?e.toString():JSON.stringify(e)},{identify:e=>typeof e==="number",default:true,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:e=>parseFloat(e),stringify:stringifyJSON}];const a={default:true,tag:"",test:/^/,resolve(e,t){t(`Unresolved plain scalar ${JSON.stringify(e)}`);return e}};const c=[i.map,r.seq].concat(o,a);t.schema=c},4138:(e,t,n)=>{var s=n(83);var i=n(6703);var r=n(1693);var o=n(2201);var a=n(2045);var c=n(6810);var l=n(3019);var f=n(27);var u=n(4545);var d=n(5724);var h=n(8974);var p=n(9841);var m=n(5389);var y=n(7847);var g=n(1156);const v=new Map([["core",f.schema],["failsafe",[s.map,r.seq,o.string]],["json",u.schema],["yaml11",m.schema],["yaml-1.1",m.schema]]);const b={binary:d.binary,bool:a.boolTag,float:c.float,floatExp:c.floatExp,floatNaN:c.floatNaN,floatTime:g.floatTime,int:l.int,intHex:l.intHex,intOct:l.intOct,intTime:g.intTime,map:s.map,null:i.nullTag,omap:h.omap,pairs:p.pairs,seq:r.seq,set:y.set,timestamp:g.timestamp};const S={"tag:yaml.org,2002:binary":d.binary,"tag:yaml.org,2002:omap":h.omap,"tag:yaml.org,2002:pairs":p.pairs,"tag:yaml.org,2002:set":y.set,"tag:yaml.org,2002:timestamp":g.timestamp};function getTags(e,t){let n=v.get(t);if(!n){if(Array.isArray(e))n=[];else{const e=Array.from(v.keys()).filter((e=>e!=="yaml11")).map((e=>JSON.stringify(e))).join(", ");throw new Error(`Unknown schema "${t}"; use one of ${e} or define customTags array`)}}if(Array.isArray(e)){for(const t of e)n=n.concat(t)}else if(typeof e==="function"){n=e(n.slice())}return n.map((e=>{if(typeof e!=="string")return e;const t=b[e];if(t)return t;const n=Object.keys(b).map((e=>JSON.stringify(e))).join(", ");throw new Error(`Unknown custom tag "${e}"; use one of ${n}`)}))}t.coreKnownTags=S;t.getTags=getTags},5724:(e,t,n)=>{var s=n(9338);var i=n(6226);const r={identify:e=>e instanceof Uint8Array,default:false,tag:"tag:yaml.org,2002:binary",resolve(e,t){if(typeof Buffer==="function"){return Buffer.from(e,"base64")}else if(typeof atob==="function"){const t=atob(e.replace(/[\n\r]/g,""));const n=new Uint8Array(t.length);for(let e=0;e<t.length;++e)n[e]=t.charCodeAt(e);return n}else{t("This environment does not support reading binary tags; either Buffer or atob is required");return e}},stringify({comment:e,type:t,value:n},r,o,a){const c=n;let l;if(typeof Buffer==="function"){l=c instanceof Buffer?c.toString("base64"):Buffer.from(c.buffer).toString("base64")}else if(typeof btoa==="function"){let e="";for(let t=0;t<c.length;++t)e+=String.fromCharCode(c[t]);l=btoa(e)}else{throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required")}if(!t)t=s.Scalar.BLOCK_LITERAL;if(t!==s.Scalar.QUOTE_DOUBLE){const e=Math.max(r.options.lineWidth-r.indent.length,r.options.minContentWidth);const n=Math.ceil(l.length/e);const i=new Array(n);for(let t=0,s=0;t<n;++t,s+=e){i[t]=l.substr(s,e)}l=i.join(t===s.Scalar.BLOCK_LITERAL?"\n":" ")}return i.stringifyString({comment:e,type:t,value:l},r,o,a)}};t.binary=r},2631:(e,t,n)=>{var s=n(9338);function boolStringify({value:e,source:t},n){const s=e?i:r;if(t&&s.test.test(t))return t;return e?n.options.trueStr:n.options.falseStr}const i={identify:e=>e===true,default:true,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new s.Scalar(true),stringify:boolStringify};const r={identify:e=>e===false,default:true,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/i,resolve:()=>new s.Scalar(false),stringify:boolStringify};t.falseTag=r;t.trueTag=i},8035:(e,t,n)=>{var s=n(9338);var i=n(4174);const r={identify:e=>typeof e==="number",default:true,tag:"tag:yaml.org,2002:float",test:/^[-+]?\.(?:inf|Inf|INF|nan|NaN|NAN)$/,resolve:e=>e.slice(-3).toLowerCase()==="nan"?NaN:e[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:i.stringifyNumber};const o={identify:e=>typeof e==="number",default:true,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e.replace(/_/g,"")),stringify(e){const t=Number(e.value);return isFinite(t)?t.toExponential():i.stringifyNumber(e)}};const a={identify:e=>typeof e==="number",default:true,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(e){const t=new s.Scalar(parseFloat(e.replace(/_/g,"")));const n=e.indexOf(".");if(n!==-1){const s=e.substring(n+1).replace(/_/g,"");if(s[s.length-1]==="0")t.minFractionDigits=s.length}return t},stringify:i.stringifyNumber};t.float=a;t.floatExp=o;t.floatNaN=r},9503:(e,t,n)=>{var s=n(4174);const intIdentify=e=>typeof e==="bigint"||Number.isInteger(e);function intResolve(e,t,n,{intAsBigInt:s}){const i=e[0];if(i==="-"||i==="+")t+=1;e=e.substring(t).replace(/_/g,"");if(s){switch(n){case 2:e=`0b${e}`;break;case 8:e=`0o${e}`;break;case 16:e=`0x${e}`;break}const t=BigInt(e);return i==="-"?BigInt(-1)*t:t}const r=parseInt(e,n);return i==="-"?-1*r:r}function intStringify(e,t,n){const{value:i}=e;if(intIdentify(i)){const e=i.toString(t);return i<0?"-"+n+e.substr(1):n+e}return s.stringifyNumber(e)}const i={identify:intIdentify,default:true,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,n)=>intResolve(e,2,2,n),stringify:e=>intStringify(e,2,"0b")};const r={identify:intIdentify,default:true,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,n)=>intResolve(e,1,8,n),stringify:e=>intStringify(e,8,"0")};const o={identify:intIdentify,default:true,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,n)=>intResolve(e,0,10,n),stringify:s.stringifyNumber};const a={identify:intIdentify,default:true,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,n)=>intResolve(e,2,16,n),stringify:e=>intStringify(e,16,"0x")};t.int=o;t.intBin=i;t.intHex=a;t.intOct=r},8974:(e,t,n)=>{var s=n(5161);var i=n(2463);var r=n(1399);var o=n(6011);var a=n(9841);class YAMLOMap extends s.YAMLSeq{constructor(){super();this.add=o.YAMLMap.prototype.add.bind(this);this.delete=o.YAMLMap.prototype.delete.bind(this);this.get=o.YAMLMap.prototype.get.bind(this);this.has=o.YAMLMap.prototype.has.bind(this);this.set=o.YAMLMap.prototype.set.bind(this);this.tag=YAMLOMap.tag}toJSON(e,t){if(!t)return super.toJSON(e);const n=new Map;if(t?.onCreate)t.onCreate(n);for(const e of this.items){let s,o;if(r.isPair(e)){s=i.toJS(e.key,"",t);o=i.toJS(e.value,s,t)}else{s=i.toJS(e,"",t)}if(n.has(s))throw new Error("Ordered maps must not include duplicate keys");n.set(s,o)}return n}}YAMLOMap.tag="tag:yaml.org,2002:omap";const c={collection:"seq",identify:e=>e instanceof Map,nodeClass:YAMLOMap,default:false,tag:"tag:yaml.org,2002:omap",resolve(e,t){const n=a.resolvePairs(e,t);const s=[];for(const{key:e}of n.items){if(r.isScalar(e)){if(s.includes(e.value)){t(`Ordered maps must not include duplicate keys: ${e.value}`)}else{s.push(e.value)}}}return Object.assign(new YAMLOMap,n)},createNode(e,t,n){const s=a.createPairs(e,t,n);const i=new YAMLOMap;i.items=s.items;return i}};t.YAMLOMap=YAMLOMap;t.omap=c},9841:(e,t,n)=>{var s=n(1399);var i=n(246);var r=n(9338);var o=n(5161);function resolvePairs(e,t){if(s.isSeq(e)){for(let n=0;n<e.items.length;++n){let o=e.items[n];if(s.isPair(o))continue;else if(s.isMap(o)){if(o.items.length>1)t("Each pair must have its own sequence indicator");const e=o.items[0]||new i.Pair(new r.Scalar(null));if(o.commentBefore)e.key.commentBefore=e.key.commentBefore?`${o.commentBefore}\n${e.key.commentBefore}`:o.commentBefore;if(o.comment){const t=e.value??e.key;t.comment=t.comment?`${o.comment}\n${t.comment}`:o.comment}o=e}e.items[n]=s.isPair(o)?o:new i.Pair(o)}}else t("Expected a sequence for this tag");return e}function createPairs(e,t,n){const{replacer:s}=n;const r=new o.YAMLSeq(e);r.tag="tag:yaml.org,2002:pairs";let a=0;if(t&&Symbol.iterator in Object(t))for(let e of t){if(typeof s==="function")e=s.call(t,String(a++),e);let o,c;if(Array.isArray(e)){if(e.length===2){o=e[0];c=e[1]}else throw new TypeError(`Expected [key, value] tuple: ${e}`)}else if(e&&e instanceof Object){const t=Object.keys(e);if(t.length===1){o=t[0];c=e[o]}else throw new TypeError(`Expected { key: value } tuple: ${e}`)}else{o=e}r.items.push(i.createPair(o,c,n))}return r}const a={collection:"seq",default:false,tag:"tag:yaml.org,2002:pairs",resolve:resolvePairs,createNode:createPairs};t.createPairs=createPairs;t.pairs=a;t.resolvePairs=resolvePairs},5389:(e,t,n)=>{var s=n(83);var i=n(6703);var r=n(1693);var o=n(2201);var a=n(5724);var c=n(2631);var l=n(8035);var f=n(9503);var u=n(8974);var d=n(9841);var h=n(7847);var p=n(1156);const m=[s.map,r.seq,o.string,i.nullTag,c.trueTag,c.falseTag,f.intBin,f.intOct,f.int,f.intHex,l.floatNaN,l.floatExp,l.float,a.binary,u.omap,d.pairs,h.set,p.intTime,p.floatTime,p.timestamp];t.schema=m},7847:(e,t,n)=>{var s=n(1399);var i=n(246);var r=n(6011);class YAMLSet extends r.YAMLMap{constructor(e){super(e);this.tag=YAMLSet.tag}add(e){let t;if(s.isPair(e))t=e;else if(e&&typeof e==="object"&&"key"in e&&"value"in e&&e.value===null)t=new i.Pair(e.key,null);else t=new i.Pair(e,null);const n=r.findPair(this.items,t.key);if(!n)this.items.push(t)}get(e,t){const n=r.findPair(this.items,e);return!t&&s.isPair(n)?s.isScalar(n.key)?n.key.value:n.key:n}set(e,t){if(typeof t!=="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof t}`);const n=r.findPair(this.items,e);if(n&&!t){this.items.splice(this.items.indexOf(n),1)}else if(!n&&t){this.items.push(new i.Pair(e))}}toJSON(e,t){return super.toJSON(e,t,Set)}toString(e,t,n){if(!e)return JSON.stringify(this);if(this.hasAllNullValues(true))return super.toString(Object.assign({},e,{allNullValues:true}),t,n);else throw new Error("Set items must all have null values")}}YAMLSet.tag="tag:yaml.org,2002:set";const o={collection:"map",identify:e=>e instanceof Set,nodeClass:YAMLSet,default:false,tag:"tag:yaml.org,2002:set",resolve(e,t){if(s.isMap(e)){if(e.hasAllNullValues(true))return Object.assign(new YAMLSet,e);else t("Set items must all have null values")}else t("Expected a mapping for this tag");return e},createNode(e,t,n){const{replacer:s}=n;const r=new YAMLSet(e);if(t&&Symbol.iterator in Object(t))for(let e of t){if(typeof s==="function")e=s.call(t,e,e);r.items.push(i.createPair(e,null,n))}return r}};t.YAMLSet=YAMLSet;t.set=o},1156:(e,t,n)=>{var s=n(4174);function parseSexagesimal(e,t){const n=e[0];const s=n==="-"||n==="+"?e.substring(1):e;const num=e=>t?BigInt(e):Number(e);const i=s.replace(/_/g,"").split(":").reduce(((e,t)=>e*num(60)+num(t)),num(0));return n==="-"?num(-1)*i:i}function stringifySexagesimal(e){let{value:t}=e;let num=e=>e;if(typeof t==="bigint")num=e=>BigInt(e);else if(isNaN(t)||!isFinite(t))return s.stringifyNumber(e);let n="";if(t<0){n="-";t*=num(-1)}const i=num(60);const r=[t%i];if(t<60){r.unshift(0)}else{t=(t-r[0])/i;r.unshift(t%i);if(t>=60){t=(t-r[0])/i;r.unshift(t)}}return n+r.map((e=>e<10?"0"+String(e):String(e))).join(":").replace(/000000\d*$/,"")}const i={identify:e=>typeof e==="bigint"||Number.isInteger(e),default:true,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(e,t,{intAsBigInt:n})=>parseSexagesimal(e,n),stringify:stringifySexagesimal};const r={identify:e=>typeof e==="number",default:true,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:e=>parseSexagesimal(e,false),stringify:stringifySexagesimal};const o={identify:e=>e instanceof Date,default:true,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})"+"(?:"+"(?:t|T|[ \\t]+)"+"([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)"+"(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?"+")?$"),resolve(e){const t=e.match(o.test);if(!t)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");const[,n,s,i,r,a,c]=t.map(Number);const l=t[7]?Number((t[7]+"00").substr(1,3)):0;let f=Date.UTC(n,s-1,i,r||0,a||0,c||0,l);const u=t[8];if(u&&u!=="Z"){let e=parseSexagesimal(u,false);if(Math.abs(e)<30)e*=60;f-=6e4*e}return new Date(f)},stringify:({value:e})=>e.toISOString().replace(/((T00:00)?:00)?\.000Z$/,"")};t.floatTime=r;t.intTime=i;t.timestamp=o},2889:(e,t)=>{const n="flow";const s="block";const i="quoted";function foldFlowLines(e,t,n="flow",{indentAtStart:r,lineWidth:o=80,minContentWidth:a=20,onFold:c,onOverflow:l}={}){if(!o||o<0)return e;const f=Math.max(1+a,1+o-t.length);if(e.length<=f)return e;const u=[];const d={};let h=o-t.length;if(typeof r==="number"){if(r>o-Math.max(2,a))u.push(0);else h=o-r}let p=undefined;let m=undefined;let y=false;let g=-1;let v=-1;let b=-1;if(n===s){g=consumeMoreIndentedLines(e,g);if(g!==-1)h=g+f}for(let t;t=e[g+=1];){if(n===i&&t==="\\"){v=g;switch(e[g+1]){case"x":g+=3;break;case"u":g+=5;break;case"U":g+=9;break;default:g+=1}b=g}if(t==="\n"){if(n===s)g=consumeMoreIndentedLines(e,g);h=g+f;p=undefined}else{if(t===" "&&m&&m!==" "&&m!=="\n"&&m!=="\t"){const t=e[g+1];if(t&&t!==" "&&t!=="\n"&&t!=="\t")p=g}if(g>=h){if(p){u.push(p);h=p+f;p=undefined}else if(n===i){while(m===" "||m==="\t"){m=t;t=e[g+=1];y=true}const n=g>b+1?g-2:v-1;if(d[n])return e;u.push(n);d[n]=true;h=n+f;p=undefined}else{y=true}}}m=t}if(y&&l)l();if(u.length===0)return e;if(c)c();let S=e.slice(0,u[0]);for(let s=0;s<u.length;++s){const r=u[s];const o=u[s+1]||e.length;if(r===0)S=`\n${t}${e.slice(0,o)}`;else{if(n===i&&d[r])S+=`${e[r]}\\`;S+=`\n${t}${e.slice(r+1,o)}`}}return S}function consumeMoreIndentedLines(e,t){let n=e[t+1];while(n===" "||n==="\t"){do{n=e[t+=1]}while(n&&n!=="\n");n=e[t+1]}return t}t.FOLD_BLOCK=s;t.FOLD_FLOW=n;t.FOLD_QUOTED=i;t.foldFlowLines=foldFlowLines},8409:(e,t,n)=>{var s=n(8459);var i=n(1399);var r=n(5182);var o=n(6226);function createStringifyContext(e,t){const n=Object.assign({blockQuote:true,commentString:r.stringifyComment,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:false,doubleQuotedMinMultiLineLength:40,falseStr:"false",indentSeq:true,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:false,singleQuote:null,trueStr:"true",verifyAliasOrder:true},e.schema.toStringOptions,t);let s;switch(n.collectionStyle){case"block":s=false;break;case"flow":s=true;break;default:s=null}return{anchors:new Set,doc:e,indent:"",indentStep:typeof n.indent==="number"?" ".repeat(n.indent):" ",inFlow:s,options:n}}function getTagObject(e,t){if(t.tag){const n=e.filter((e=>e.tag===t.tag));if(n.length>0)return n.find((e=>e.format===t.format))??n[0]}let n=undefined;let s;if(i.isScalar(t)){s=t.value;const i=e.filter((e=>e.identify?.(s)));n=i.find((e=>e.format===t.format))??i.find((e=>!e.format))}else{s=t;n=e.find((e=>e.nodeClass&&s instanceof e.nodeClass))}if(!n){const e=s?.constructor?.name??typeof s;throw new Error(`Tag not resolved for ${e} value`)}return n}function stringifyProps(e,t,{anchors:n,doc:r}){if(!r.directives)return"";const o=[];const a=(i.isScalar(e)||i.isCollection(e))&&e.anchor;if(a&&s.anchorIsValid(a)){n.add(a);o.push(`&${a}`)}const c=e.tag?e.tag:t.default?null:t.tag;if(c)o.push(r.directives.tagString(c));return o.join(" ")}function stringify(e,t,n,s){if(i.isPair(e))return e.toString(t,n,s);if(i.isAlias(e)){if(t.doc.directives)return e.toString(t);if(t.resolvedAliases?.has(e)){throw new TypeError(`Cannot stringify circular structure without alias nodes`)}else{if(t.resolvedAliases)t.resolvedAliases.add(e);else t.resolvedAliases=new Set([e]);e=e.resolve(t.doc)}}let r=undefined;const a=i.isNode(e)?e:t.doc.createNode(e,{onTagObj:e=>r=e});if(!r)r=getTagObject(t.doc.schema.tags,a);const c=stringifyProps(a,r,t);if(c.length>0)t.indentAtStart=(t.indentAtStart??0)+c.length+1;const l=typeof r.stringify==="function"?r.stringify(a,t,n,s):i.isScalar(a)?o.stringifyString(a,t,n,s):a.toString(t,n,s);if(!c)return l;return i.isScalar(a)||l[0]==="{"||l[0]==="["?`${c} ${l}`:`${c}\n${t.indent}${l}`}t.createStringifyContext=createStringifyContext;t.stringify=stringify},2466:(e,t,n)=>{var s=n(3466);var i=n(1399);var r=n(8409);var o=n(5182);function stringifyCollection(e,t,n){const s=t.inFlow??e.flow;const i=s?stringifyFlowCollection:stringifyBlockCollection;return i(e,t,n)}function stringifyBlockCollection({comment:e,items:t},n,{blockItemPrefix:s,flowChars:a,itemIndent:c,onChompKeep:l,onComment:f}){const{indent:u,options:{commentString:d}}=n;const h=Object.assign({},n,{indent:c,type:null});let p=false;const m=[];for(let e=0;e<t.length;++e){const a=t[e];let l=null;if(i.isNode(a)){if(!p&&a.spaceBefore)m.push("");addCommentBefore(n,m,a.commentBefore,p);if(a.comment)l=a.comment}else if(i.isPair(a)){const e=i.isNode(a.key)?a.key:null;if(e){if(!p&&e.spaceBefore)m.push("");addCommentBefore(n,m,e.commentBefore,p)}}p=false;let f=r.stringify(a,h,(()=>l=null),(()=>p=true));if(l)f+=o.lineComment(f,c,d(l));if(p&&l)p=false;m.push(s+f)}let y;if(m.length===0){y=a.start+a.end}else{y=m[0];for(let e=1;e<m.length;++e){const t=m[e];y+=t?`\n${u}${t}`:"\n"}}if(e){y+="\n"+o.indentComment(d(e),u);if(f)f()}else if(p&&l)l();return y}function stringifyFlowCollection({comment:e,items:t},n,{flowChars:a,itemIndent:c,onComment:l}){const{indent:f,indentStep:u,options:{commentString:d}}=n;c+=u;const h=Object.assign({},n,{indent:c,inFlow:true,type:null});let p=false;let m=0;const y=[];for(let e=0;e<t.length;++e){const s=t[e];let a=null;if(i.isNode(s)){if(s.spaceBefore)y.push("");addCommentBefore(n,y,s.commentBefore,false);if(s.comment)a=s.comment}else if(i.isPair(s)){const e=i.isNode(s.key)?s.key:null;if(e){if(e.spaceBefore)y.push("");addCommentBefore(n,y,e.commentBefore,false);if(e.comment)p=true}const t=i.isNode(s.value)?s.value:null;if(t){if(t.comment)a=t.comment;if(t.commentBefore)p=true}else if(s.value==null&&e&&e.comment){a=e.comment}}if(a)p=true;let l=r.stringify(s,h,(()=>a=null));if(e<t.length-1)l+=",";if(a)l+=o.lineComment(l,c,d(a));if(!p&&(y.length>m||l.includes("\n")))p=true;y.push(l);m=y.length}let g;const{start:v,end:b}=a;if(y.length===0){g=v+b}else{if(!p){const e=y.reduce(((e,t)=>e+t.length+2),2);p=e>s.Collection.maxFlowStringSingleLineLength}if(p){g=v;for(const e of y)g+=e?`\n${u}${f}${e}`:"\n";g+=`\n${f}${b}`}else{g=`${v} ${y.join(" ")} ${b}`}}if(e){g+=o.lineComment(g,d(e),f);if(l)l()}return g}function addCommentBefore({indent:e,options:{commentString:t}},n,s,i){if(s&&i)s=s.replace(/^\n+/,"");if(s){const i=o.indentComment(t(s),e);n.push(i.trimStart())}}t.stringifyCollection=stringifyCollection},5182:(e,t)=>{const stringifyComment=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function indentComment(e,t){if(/^\n+$/.test(e))return e.substring(1);return t?e.replace(/^(?! *$)/gm,t):e}const lineComment=(e,t,n)=>e.endsWith("\n")?indentComment(n,t):n.includes("\n")?"\n"+indentComment(n,t):(e.endsWith(" ")?"":" ")+n;t.indentComment=indentComment;t.lineComment=lineComment;t.stringifyComment=stringifyComment},5225:(e,t,n)=>{var s=n(1399);var i=n(8409);var r=n(5182);function stringifyDocument(e,t){const n=[];let o=t.directives===true;if(t.directives!==false&&e.directives){const t=e.directives.toString(e);if(t){n.push(t);o=true}else if(e.directives.docStart)o=true}if(o)n.push("---");const a=i.createStringifyContext(e,t);const{commentString:c}=a.options;if(e.commentBefore){if(n.length!==1)n.unshift("");const t=c(e.commentBefore);n.unshift(r.indentComment(t,""))}let l=false;let f=null;if(e.contents){if(s.isNode(e.contents)){if(e.contents.spaceBefore&&o)n.push("");if(e.contents.commentBefore){const t=c(e.contents.commentBefore);n.push(r.indentComment(t,""))}a.forceBlockIndent=!!e.comment;f=e.contents.comment}const t=f?undefined:()=>l=true;let u=i.stringify(e.contents,a,(()=>f=null),t);if(f)u+=r.lineComment(u,"",c(f));if((u[0]==="|"||u[0]===">")&&n[n.length-1]==="---"){n[n.length-1]=`--- ${u}`}else n.push(u)}else{n.push(i.stringify(e.contents,a))}if(e.directives?.docEnd){if(e.comment){const t=c(e.comment);if(t.includes("\n")){n.push("...");n.push(r.indentComment(t,""))}else{n.push(`... ${t}`)}}else{n.push("...")}}else{let t=e.comment;if(t&&l)t=t.replace(/^\n+/,"");if(t){if((!l||f)&&n[n.length-1]!=="")n.push("");n.push(r.indentComment(c(t),""))}}return n.join("\n")+"\n"}t.stringifyDocument=stringifyDocument},4174:(e,t)=>{function stringifyNumber({format:e,minFractionDigits:t,tag:n,value:s}){if(typeof s==="bigint")return String(s);const i=typeof s==="number"?s:Number(s);if(!isFinite(i))return isNaN(i)?".nan":i<0?"-.inf":".inf";let r=JSON.stringify(s);if(!e&&t&&(!n||n==="tag:yaml.org,2002:float")&&/^\d/.test(r)){let e=r.indexOf(".");if(e<0){e=r.length;r+="."}let n=t-(r.length-e-1);while(n-- >0)r+="0"}return r}t.stringifyNumber=stringifyNumber},4875:(e,t,n)=>{var s=n(1399);var i=n(9338);var r=n(8409);var o=n(5182);function stringifyPair({key:e,value:t},n,a,c){const{allNullValues:l,doc:f,indent:u,indentStep:d,options:{commentString:h,indentSeq:p,simpleKeys:m}}=n;let y=s.isNode(e)&&e.comment||null;if(m){if(y){throw new Error("With simple keys, key nodes cannot have comments")}if(s.isCollection(e)){const e="With simple keys, collection cannot be used as a key value";throw new Error(e)}}let g=!m&&(!e||y&&t==null&&!n.inFlow||s.isCollection(e)||(s.isScalar(e)?e.type===i.Scalar.BLOCK_FOLDED||e.type===i.Scalar.BLOCK_LITERAL:typeof e==="object"));n=Object.assign({},n,{allNullValues:false,implicitKey:!g&&(m||!l),indent:u+d});let v=false;let b=false;let S=r.stringify(e,n,(()=>v=true),(()=>b=true));if(!g&&!n.inFlow&&S.length>1024){if(m)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");g=true}if(n.inFlow){if(l||t==null){if(v&&a)a();return S===""?"?":g?`? ${S}`:S}}else if(l&&!m||t==null&&g){S=`? ${S}`;if(y&&!v){S+=o.lineComment(S,n.indent,h(y))}else if(b&&c)c();return S}if(v)y=null;if(g){if(y)S+=o.lineComment(S,n.indent,h(y));S=`? ${S}\n${u}:`}else{S=`${S}:`;if(y)S+=o.lineComment(S,n.indent,h(y))}let w="";let k=null;if(s.isNode(t)){if(t.spaceBefore)w="\n";if(t.commentBefore){const e=h(t.commentBefore);w+=`\n${o.indentComment(e,n.indent)}`}k=t.comment}else if(t&&typeof t==="object"){t=f.createNode(t)}n.implicitKey=false;if(!g&&!y&&s.isScalar(t))n.indentAtStart=S.length+1;b=false;if(!p&&d.length>=2&&!n.inFlow&&!g&&s.isSeq(t)&&!t.flow&&!t.tag&&!t.anchor){n.indent=n.indent.substr(2)}let E=false;const A=r.stringify(t,n,(()=>E=true),(()=>b=true));let N=" ";if(w||y){if(A===""&&!n.inFlow)N=w==="\n"?"\n\n":w;else N=`${w}\n${n.indent}`}else if(!g&&s.isCollection(t)){const e=A[0]==="["||A[0]==="{";if(!e||A.includes("\n"))N=`\n${n.indent}`}else if(A===""||A[0]==="\n")N="";S+=N+A;if(n.inFlow){if(E&&a)a()}else if(k&&!E){S+=o.lineComment(S,n.indent,h(k))}else if(b&&c){c()}return S}t.stringifyPair=stringifyPair},6226:(e,t,n)=>{var s=n(9338);var i=n(2889);const getFoldOptions=e=>({indentAtStart:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth});const containsDocumentMarker=e=>/^(%|---|\.\.\.)/m.test(e);function lineLengthOverLimit(e,t,n){if(!t||t<0)return false;const s=t-n;const i=e.length;if(i<=s)return false;for(let t=0,n=0;t<i;++t){if(e[t]==="\n"){if(t-n>s)return true;n=t+1;if(i-n<=s)return false}}return true}function doubleQuotedString(e,t){const n=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return n;const{implicitKey:s}=t;const r=t.options.doubleQuotedMinMultiLineLength;const o=t.indent||(containsDocumentMarker(e)?" ":"");let a="";let c=0;for(let e=0,t=n[e];t;t=n[++e]){if(t===" "&&n[e+1]==="\\"&&n[e+2]==="n"){a+=n.slice(c,e)+"\\ ";e+=1;c=e;t="\\"}if(t==="\\")switch(n[e+1]){case"u":{a+=n.slice(c,e);const t=n.substr(e+2,4);switch(t){case"0000":a+="\\0";break;case"0007":a+="\\a";break;case"000b":a+="\\v";break;case"001b":a+="\\e";break;case"0085":a+="\\N";break;case"00a0":a+="\\_";break;case"2028":a+="\\L";break;case"2029":a+="\\P";break;default:if(t.substr(0,2)==="00")a+="\\x"+t.substr(2);else a+=n.substr(e,6)}e+=5;c=e+1}break;case"n":if(s||n[e+2]==='"'||n.length<r){e+=1}else{a+=n.slice(c,e)+"\n\n";while(n[e+2]==="\\"&&n[e+3]==="n"&&n[e+4]!=='"'){a+="\n";e+=2}a+=o;if(n[e+2]===" ")a+="\\";e+=1;c=e+1}break;default:e+=1}}a=c?a+n.slice(c):n;return s?a:i.foldFlowLines(a,o,i.FOLD_QUOTED,getFoldOptions(t))}function singleQuotedString(e,t){if(t.options.singleQuote===false||t.implicitKey&&e.includes("\n")||/[ \t]\n|\n[ \t]/.test(e))return doubleQuotedString(e,t);const n=t.indent||(containsDocumentMarker(e)?" ":"");const s="'"+e.replace(/'/g,"''").replace(/\n+/g,`$&\n${n}`)+"'";return t.implicitKey?s:i.foldFlowLines(s,n,i.FOLD_FLOW,getFoldOptions(t))}function quotedString(e,t){const{singleQuote:n}=t.options;let s;if(n===false)s=doubleQuotedString;else{const t=e.includes('"');const i=e.includes("'");if(t&&!i)s=singleQuotedString;else if(i&&!t)s=doubleQuotedString;else s=n?singleQuotedString:doubleQuotedString}return s(e,t)}function blockString({comment:e,type:t,value:n},r,o,a){const{blockQuote:c,commentString:l,lineWidth:f}=r.options;if(!c||/\n[\t ]+$/.test(n)||/^\s*$/.test(n)){return quotedString(n,r)}const u=r.indent||(r.forceBlockIndent||containsDocumentMarker(n)?" ":"");const d=c==="literal"?true:c==="folded"||t===s.Scalar.BLOCK_FOLDED?false:t===s.Scalar.BLOCK_LITERAL?true:!lineLengthOverLimit(n,f,u.length);if(!n)return d?"|\n":">\n";let h;let p;for(p=n.length;p>0;--p){const e=n[p-1];if(e!=="\n"&&e!=="\t"&&e!==" ")break}let m=n.substring(p);const y=m.indexOf("\n");if(y===-1){h="-"}else if(n===m||y!==m.length-1){h="+";if(a)a()}else{h=""}if(m){n=n.slice(0,-m.length);if(m[m.length-1]==="\n")m=m.slice(0,-1);m=m.replace(/\n+(?!\n|$)/g,`$&${u}`)}let g=false;let v;let b=-1;for(v=0;v<n.length;++v){const e=n[v];if(e===" ")g=true;else if(e==="\n")b=v;else break}let S=n.substring(0,b<v?b+1:v);if(S){n=n.substring(S.length);S=S.replace(/\n+/g,`$&${u}`)}const w=u?"2":"1";let k=(d?"|":">")+(g?w:"")+h;if(e){k+=" "+l(e.replace(/ ?[\r\n]+/g," "));if(o)o()}if(d){n=n.replace(/\n+/g,`$&${u}`);return`${k}\n${u}${S}${n}${m}`}n=n.replace(/\n+/g,"\n$&").replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${u}`);const E=i.foldFlowLines(`${S}${n}${m}`,u,i.FOLD_BLOCK,getFoldOptions(r));return`${k}\n${u}${E}`}function plainString(e,t,n,r){const{type:o,value:a}=e;const{actualString:c,implicitKey:l,indent:f,inFlow:u}=t;if(l&&/[\n[\]{},]/.test(a)||u&&/[[\]{},]/.test(a)){return quotedString(a,t)}if(!a||/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(a)){return l||u||!a.includes("\n")?quotedString(a,t):blockString(e,t,n,r)}if(!l&&!u&&o!==s.Scalar.PLAIN&&a.includes("\n")){return blockString(e,t,n,r)}if(f===""&&containsDocumentMarker(a)){t.forceBlockIndent=true;return blockString(e,t,n,r)}const d=a.replace(/\n+/g,`$&\n${f}`);if(c){const test=e=>e.default&&e.tag!=="tag:yaml.org,2002:str"&&e.test?.test(d);const{compat:e,tags:n}=t.doc.schema;if(n.some(test)||e?.some(test))return quotedString(a,t)}return l?d:i.foldFlowLines(d,f,i.FOLD_FLOW,getFoldOptions(t))}function stringifyString(e,t,n,i){const{implicitKey:r,inFlow:o}=t;const a=typeof e.value==="string"?e:Object.assign({},e,{value:String(e.value)});let{type:c}=e;if(c!==s.Scalar.QUOTE_DOUBLE){if(/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(a.value))c=s.Scalar.QUOTE_DOUBLE}const _stringify=e=>{switch(e){case s.Scalar.BLOCK_FOLDED:case s.Scalar.BLOCK_LITERAL:return r||o?quotedString(a.value,t):blockString(a,t,n,i);case s.Scalar.QUOTE_DOUBLE:return doubleQuotedString(a.value,t);case s.Scalar.QUOTE_SINGLE:return singleQuotedString(a.value,t);case s.Scalar.PLAIN:return plainString(a,t,n,i);default:return null}};let l=_stringify(c);if(l===null){const{defaultKeyType:e,defaultStringType:n}=t.options;const s=r&&e||n;l=_stringify(s);if(l===null)throw new Error(`Unsupported default string type ${s}`)}return l}t.stringifyString=stringifyString},6796:(e,t,n)=>{var s=n(1399);const i=Symbol("break visit");const r=Symbol("skip children");const o=Symbol("remove node");function visit(e,t){const n=initVisitor(t);if(s.isDocument(e)){const t=visit_(null,e.contents,n,Object.freeze([e]));if(t===o)e.contents=null}else visit_(null,e,n,Object.freeze([]))}visit.BREAK=i;visit.SKIP=r;visit.REMOVE=o;function visit_(e,t,n,r){const a=callVisitor(e,t,n,r);if(s.isNode(a)||s.isPair(a)){replaceNode(e,r,a);return visit_(e,a,n,r)}if(typeof a!=="symbol"){if(s.isCollection(t)){r=Object.freeze(r.concat(t));for(let e=0;e<t.items.length;++e){const s=visit_(e,t.items[e],n,r);if(typeof s==="number")e=s-1;else if(s===i)return i;else if(s===o){t.items.splice(e,1);e-=1}}}else if(s.isPair(t)){r=Object.freeze(r.concat(t));const e=visit_("key",t.key,n,r);if(e===i)return i;else if(e===o)t.key=null;const s=visit_("value",t.value,n,r);if(s===i)return i;else if(s===o)t.value=null}}return a}async function visitAsync(e,t){const n=initVisitor(t);if(s.isDocument(e)){const t=await visitAsync_(null,e.contents,n,Object.freeze([e]));if(t===o)e.contents=null}else await visitAsync_(null,e,n,Object.freeze([]))}visitAsync.BREAK=i;visitAsync.SKIP=r;visitAsync.REMOVE=o;async function visitAsync_(e,t,n,r){const a=await callVisitor(e,t,n,r);if(s.isNode(a)||s.isPair(a)){replaceNode(e,r,a);return visitAsync_(e,a,n,r)}if(typeof a!=="symbol"){if(s.isCollection(t)){r=Object.freeze(r.concat(t));for(let e=0;e<t.items.length;++e){const s=await visitAsync_(e,t.items[e],n,r);if(typeof s==="number")e=s-1;else if(s===i)return i;else if(s===o){t.items.splice(e,1);e-=1}}}else if(s.isPair(t)){r=Object.freeze(r.concat(t));const e=await visitAsync_("key",t.key,n,r);if(e===i)return i;else if(e===o)t.key=null;const s=await visitAsync_("value",t.value,n,r);if(s===i)return i;else if(s===o)t.value=null}}return a}function initVisitor(e){if(typeof e==="object"&&(e.Collection||e.Node||e.Value)){return Object.assign({Alias:e.Node,Map:e.Node,Scalar:e.Node,Seq:e.Node},e.Value&&{Map:e.Value,Scalar:e.Value,Seq:e.Value},e.Collection&&{Map:e.Collection,Seq:e.Collection},e)}return e}function callVisitor(e,t,n,i){if(typeof n==="function")return n(e,t,i);if(s.isMap(t))return n.Map?.(e,t,i);if(s.isSeq(t))return n.Seq?.(e,t,i);if(s.isPair(t))return n.Pair?.(e,t,i);if(s.isScalar(t))return n.Scalar?.(e,t,i);if(s.isAlias(t))return n.Alias?.(e,t,i);return undefined}function replaceNode(e,t,n){const i=t[t.length-1];if(s.isCollection(i)){i.items[e]=n}else if(s.isPair(i)){if(e==="key")i.key=n;else i.value=n}else if(s.isDocument(i)){i.contents=n}else{const e=s.isAlias(i)?"alias":"scalar";throw new Error(`Cannot replace node with ${e} parent`)}}t.visit=visit;t.visitAsync=visitAsync}};var t={};function __nccwpck_require2_(n){var s=t[n];if(s!==undefined){return s.exports}var i=t[n]={exports:{}};var r=true;try{e[n].call(i.exports,i,i.exports,__nccwpck_require2_);r=false}finally{if(r)delete t[n]}return i.exports}if(typeof __nccwpck_require2_!=="undefined")__nccwpck_require2_.ab=__dirname+"/";var n=__nccwpck_require2_(6144);module.exports=n})();1727//# sourceMappingURL=index.js.map1728/***/ }),1729/***/ 9690:1730/***/ (function(module, __unused_webpack_exports, __nccwpck_require__) {1731"use strict";1732var __importDefault = (this && this.__importDefault) || function (mod) {1733 return (mod && mod.__esModule) ? mod : { "default": mod };1734};1735const events_1 = __nccwpck_require__(2361);1736const debug_1 = __importDefault(__nccwpck_require__(8237));1737const promisify_1 = __importDefault(__nccwpck_require__(6570));1738const debug = debug_1.default('agent-base');1739function isAgent(v) {1740 return Boolean(v) && typeof v.addRequest === 'function';1741}1742function isSecureEndpoint() {1743 const { stack } = new Error();1744 if (typeof stack !== 'string')1745 return false;1746 return stack.split('\n').some(l => l.indexOf('(https.js:') !== -1 || l.indexOf('node:https:') !== -1);1747}1748function createAgent(callback, opts) {1749 return new createAgent.Agent(callback, opts);1750}1751(function (createAgent) {1752 /**1753 * Base `http.Agent` implementation.1754 * No pooling/keep-alive is implemented by default.1755 *1756 * @param {Function} callback1757 * @api public1758 */1759 class Agent extends events_1.EventEmitter {1760 constructor(callback, _opts) {1761 super();1762 let opts = _opts;1763 if (typeof callback === 'function') {1764 this.callback = callback;1765 }1766 else if (callback) {1767 opts = callback;1768 }1769 // Timeout for the socket to be returned from the callback1770 this.timeout = null;1771 if (opts && typeof opts.timeout === 'number') {1772 this.timeout = opts.timeout;1773 }1774 // These aren't actually used by `agent-base`, but are required1775 // for the TypeScript definition files in `@types/node` :/1776 this.maxFreeSockets = 1;1777 this.maxSockets = 1;1778 this.maxTotalSockets = Infinity;1779 this.sockets = {};1780 this.freeSockets = {};1781 this.requests = {};1782 this.options = {};1783 }1784 get defaultPort() {1785 if (typeof this.explicitDefaultPort === 'number') {1786 return this.explicitDefaultPort;1787 }1788 return isSecureEndpoint() ? 443 : 80;1789 }1790 set defaultPort(v) {1791 this.explicitDefaultPort = v;1792 }1793 get protocol() {1794 if (typeof this.explicitProtocol === 'string') {1795 return this.explicitProtocol;1796 }1797 return isSecureEndpoint() ? 'https:' : 'http:';1798 }1799 set protocol(v) {1800 this.explicitProtocol = v;1801 }1802 callback(req, opts, fn) {1803 throw new Error('"agent-base" has no default implementation, you must subclass and override `callback()`');1804 }1805 /**1806 * Called by node-core's "_http_client.js" module when creating1807 * a new HTTP request with this Agent instance.1808 *1809 * @api public1810 */1811 addRequest(req, _opts) {1812 const opts = Object.assign({}, _opts);1813 if (typeof opts.secureEndpoint !== 'boolean') {1814 opts.secureEndpoint = isSecureEndpoint();1815 }1816 if (opts.host == null) {1817 opts.host = 'localhost';1818 }1819 if (opts.port == null) {1820 opts.port = opts.secureEndpoint ? 443 : 80;1821 }1822 if (opts.protocol == null) {1823 opts.protocol = opts.secureEndpoint ? 'https:' : 'http:';1824 }1825 if (opts.host && opts.path) {1826 // If both a `host` and `path` are specified then it's most1827 // likely the result of a `url.parse()` call... we need to1828 // remove the `path` portion so that `net.connect()` doesn't1829 // attempt to open that as a unix socket file.1830 delete opts.path;1831 }1832 delete opts.agent;1833 delete opts.hostname;1834 delete opts._defaultAgent;1835 delete opts.defaultPort;1836 delete opts.createConnection;1837 // Hint to use "Connection: close"1838 // XXX: non-documented `http` module API :(1839 req._last = true;1840 req.shouldKeepAlive = false;1841 let timedOut = false;1842 let timeoutId = null;1843 const timeoutMs = opts.timeout || this.timeout;1844 const onerror = (err) => {1845 if (req._hadError)1846 return;1847 req.emit('error', err);1848 // For Safety. Some additional errors might fire later on1849 // and we need to make sure we don't double-fire the error event.1850 req._hadError = true;1851 };1852 const ontimeout = () => {1853 timeoutId = null;1854 timedOut = true;1855 const err = new Error(`A "socket" was not created for HTTP request before ${timeoutMs}ms`);1856 err.code = 'ETIMEOUT';1857 onerror(err);1858 };1859 const callbackError = (err) => {1860 if (timedOut)1861 return;1862 if (timeoutId !== null) {1863 clearTimeout(timeoutId);1864 timeoutId = null;1865 }1866 onerror(err);1867 };1868 const onsocket = (socket) => {1869 if (timedOut)1870 return;1871 if (timeoutId != null) {1872 clearTimeout(timeoutId);1873 timeoutId = null;1874 }1875 if (isAgent(socket)) {1876 // `socket` is actually an `http.Agent` instance, so1877 // relinquish responsibility for this `req` to the Agent1878 // from here on1879 debug('Callback returned another Agent instance %o', socket.constructor.name);1880 socket.addRequest(req, opts);1881 return;1882 }1883 if (socket) {1884 socket.once('free', () => {1885 this.freeSocket(socket, opts);1886 });1887 req.onSocket(socket);1888 return;1889 }1890 const err = new Error(`no Duplex stream was returned to agent-base for \`${req.method} ${req.path}\``);1891 onerror(err);1892 };1893 if (typeof this.callback !== 'function') {1894 onerror(new Error('`callback` is not defined'));1895 return;1896 }1897 if (!this.promisifiedCallback) {1898 if (this.callback.length >= 3) {1899 debug('Converting legacy callback function to promise');1900 this.promisifiedCallback = promisify_1.default(this.callback);1901 }1902 else {1903 this.promisifiedCallback = this.callback;1904 }1905 }1906 if (typeof timeoutMs === 'number' && timeoutMs > 0) {1907 timeoutId = setTimeout(ontimeout, timeoutMs);1908 }1909 if ('port' in opts && typeof opts.port !== 'number') {1910 opts.port = Number(opts.port);1911 }1912 try {1913 debug('Resolving socket for %o request: %o', opts.protocol, `${req.method} ${req.path}`);1914 Promise.resolve(this.promisifiedCallback(req, opts)).then(onsocket, callbackError);1915 }1916 catch (err) {1917 Promise.reject(err).catch(callbackError);1918 }1919 }1920 freeSocket(socket, opts) {1921 debug('Freeing socket %o %o', socket.constructor.name, opts);1922 socket.destroy();1923 }1924 destroy() {1925 debug('Destroying agent %o', this.constructor.name);1926 }1927 }1928 createAgent.Agent = Agent;1929 // So that `instanceof` works correctly1930 createAgent.prototype = createAgent.Agent.prototype;1931})(createAgent || (createAgent = {}));1932module.exports = createAgent;1933//# sourceMappingURL=index.js.map1934/***/ }),1935/***/ 6570:1936/***/ ((__unused_webpack_module, exports) => {1937"use strict";1938Object.defineProperty(exports, "__esModule", ({ value: true }));1939function promisify(fn) {1940 return function (req, opts) {1941 return new Promise((resolve, reject) => {1942 fn.call(this, req, opts, (err, rtn) => {1943 if (err) {1944 reject(err);1945 }1946 else {1947 resolve(rtn);1948 }1949 });1950 });1951 };1952}1953exports["default"] = promisify;1954//# sourceMappingURL=promisify.js.map1955/***/ }),1956/***/ 1546:1957/***/ ((module) => {1958"use strict";1959const arrify = value => {1960 if (value === null || value === undefined) {1961 return [];1962 }1963 if (Array.isArray(value)) {1964 return value;1965 }1966 if (typeof value === 'string') {1967 return [value];1968 }1969 if (typeof value[Symbol.iterator] === 'function') {1970 return [...value];1971 }1972 return [value];1973};1974module.exports = arrify;1975/***/ }),1976/***/ 6463:1977/***/ ((__unused_webpack_module, exports) => {1978"use strict";1979exports.byteLength = byteLength1980exports.toByteArray = toByteArray1981exports.fromByteArray = fromByteArray1982var lookup = []1983var revLookup = []1984var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array1985var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'1986for (var i = 0, len = code.length; i < len; ++i) {1987 lookup[i] = code[i]1988 revLookup[code.charCodeAt(i)] = i1989}1990// Support decoding URL-safe base64 strings, as Node.js does.1991// See: https://en.wikipedia.org/wiki/Base64#URL_applications1992revLookup['-'.charCodeAt(0)] = 621993revLookup['_'.charCodeAt(0)] = 631994function getLens (b64) {1995 var len = b64.length1996 if (len % 4 > 0) {1997 throw new Error('Invalid string. Length must be a multiple of 4')1998 }1999 // Trim off extra bytes after placeholder bytes are found2000 // See: https://github.com/beatgammit/base64-js/issues/422001 var validLen = b64.indexOf('=')2002 if (validLen === -1) validLen = len2003 var placeHoldersLen = validLen === len2004 ? 02005 : 4 - (validLen % 4)2006 return [validLen, placeHoldersLen]2007}2008// base64 is 4/3 + up to two characters of the original data2009function byteLength (b64) {2010 var lens = getLens(b64)2011 var validLen = lens[0]2012 var placeHoldersLen = lens[1]2013 return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen2014}2015function _byteLength (b64, validLen, placeHoldersLen) {2016 return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen2017}2018function toByteArray (b64) {2019 var tmp2020 var lens = getLens(b64)2021 var validLen = lens[0]2022 var placeHoldersLen = lens[1]2023 var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))2024 var curByte = 02025 // if there are placeholders, only get up to the last complete 4 chars2026 var len = placeHoldersLen > 02027 ? validLen - 42028 : validLen2029 var i2030 for (i = 0; i < len; i += 4) {2031 tmp =2032 (revLookup[b64.charCodeAt(i)] << 18) |2033 (revLookup[b64.charCodeAt(i + 1)] << 12) |2034 (revLookup[b64.charCodeAt(i + 2)] << 6) |2035 revLookup[b64.charCodeAt(i + 3)]2036 arr[curByte++] = (tmp >> 16) & 0xFF2037 arr[curByte++] = (tmp >> 8) & 0xFF2038 arr[curByte++] = tmp & 0xFF2039 }2040 if (placeHoldersLen === 2) {2041 tmp =2042 (revLookup[b64.charCodeAt(i)] << 2) |2043 (revLookup[b64.charCodeAt(i + 1)] >> 4)2044 arr[curByte++] = tmp & 0xFF2045 }2046 if (placeHoldersLen === 1) {2047 tmp =2048 (revLookup[b64.charCodeAt(i)] << 10) |2049 (revLookup[b64.charCodeAt(i + 1)] << 4) |2050 (revLookup[b64.charCodeAt(i + 2)] >> 2)2051 arr[curByte++] = (tmp >> 8) & 0xFF2052 arr[curByte++] = tmp & 0xFF2053 }2054 return arr2055}2056function tripletToBase64 (num) {2057 return lookup[num >> 18 & 0x3F] +2058 lookup[num >> 12 & 0x3F] +2059 lookup[num >> 6 & 0x3F] +2060 lookup[num & 0x3F]2061}2062function encodeChunk (uint8, start, end) {2063 var tmp2064 var output = []2065 for (var i = start; i < end; i += 3) {2066 tmp =2067 ((uint8[i] << 16) & 0xFF0000) +2068 ((uint8[i + 1] << 8) & 0xFF00) +2069 (uint8[i + 2] & 0xFF)2070 output.push(tripletToBase64(tmp))2071 }2072 return output.join('')2073}2074function fromByteArray (uint8) {2075 var tmp2076 var len = uint8.length2077 var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes2078 var parts = []2079 var maxChunkLength = 16383 // must be multiple of 32080 // go through the array every three bytes, we'll deal with trailing stuff later2081 for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {2082 parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))2083 }2084 // pad the end with zeros, but make sure to not forget the extra bytes2085 if (extraBytes === 1) {2086 tmp = uint8[len - 1]2087 parts.push(2088 lookup[tmp >> 2] +2089 lookup[(tmp << 4) & 0x3F] +2090 '=='2091 )2092 } else if (extraBytes === 2) {2093 tmp = (uint8[len - 2] << 8) + uint8[len - 1]2094 parts.push(2095 lookup[tmp >> 10] +2096 lookup[(tmp >> 4) & 0x3F] +2097 lookup[(tmp << 2) & 0x3F] +2098 '='2099 )2100 }2101 return parts.join('')2102}2103/***/ }),2104/***/ 7558:2105/***/ (function(module) {2106;(function (globalObject) {2107 'use strict';2108/*2109 * bignumber.js v9.1.02110 * A JavaScript library for arbitrary-precision arithmetic.2111 * https://github.com/MikeMcl/bignumber.js2112 * Copyright (c) 2022 Michael Mclaughlin <M8ch88l@gmail.com>2113 * MIT Licensed.2114 *2115 * BigNumber.prototype methods | BigNumber methods2116 * |2117 * absoluteValue abs | clone2118 * comparedTo | config set2119 * decimalPlaces dp | DECIMAL_PLACES2120 * dividedBy div | ROUNDING_MODE2121 * dividedToIntegerBy idiv | EXPONENTIAL_AT2122 * exponentiatedBy pow | RANGE2123 * integerValue | CRYPTO2124 * isEqualTo eq | MODULO_MODE2125 * isFinite | POW_PRECISION2126 * isGreaterThan gt | FORMAT2127 * isGreaterThanOrEqualTo gte | ALPHABET2128 * isInteger | isBigNumber2129 * isLessThan lt | maximum max2130 * isLessThanOrEqualTo lte | minimum min2131 * isNaN | random2132 * isNegative | sum2133 * isPositive |2134 * isZero |2135 * minus |2136 * modulo mod |2137 * multipliedBy times |2138 * negated |2139 * plus |2140 * precision sd |2141 * shiftedBy |2142 * squareRoot sqrt |2143 * toExponential |2144 * toFixed |2145 * toFormat |2146 * toFraction |2147 * toJSON |2148 * toNumber |2149 * toPrecision |2150 * toString |2151 * valueOf |2152 *2153 */2154 var BigNumber,2155 isNumeric = /^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,2156 mathceil = Math.ceil,2157 mathfloor = Math.floor,2158 bignumberError = '[BigNumber Error] ',2159 tooManyDigits = bignumberError + 'Number primitive has more than 15 significant digits: ',2160 BASE = 1e14,2161 LOG_BASE = 14,2162 MAX_SAFE_INTEGER = 0x1fffffffffffff, // 2^53 - 12163 // MAX_INT32 = 0x7fffffff, // 2^31 - 12164 POWS_TEN = [1, 10, 100, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13],2165 SQRT_BASE = 1e7,2166 // EDITABLE2167 // The limit on the value of DECIMAL_PLACES, TO_EXP_NEG, TO_EXP_POS, MIN_EXP, MAX_EXP, and2168 // the arguments to toExponential, toFixed, toFormat, and toPrecision.2169 MAX = 1E9; // 0 to MAX_INT322170 /*2171 * Create and return a BigNumber constructor.2172 */2173 function clone(configObject) {2174 var div, convertBase, parseNumeric,2175 P = BigNumber.prototype = { constructor: BigNumber, toString: null, valueOf: null },2176 ONE = new BigNumber(1),2177 //----------------------------- EDITABLE CONFIG DEFAULTS -------------------------------2178 // The default values below must be integers within the inclusive ranges stated.2179 // The values can also be changed at run-time using BigNumber.set.2180 // The maximum number of decimal places for operations involving division.2181 DECIMAL_PLACES = 20, // 0 to MAX2182 // The rounding mode used when rounding to the above decimal places, and when using2183 // toExponential, toFixed, toFormat and toPrecision, and round (default value).2184 // UP 0 Away from zero.2185 // DOWN 1 Towards zero.2186 // CEIL 2 Towards +Infinity.2187 // FLOOR 3 Towards -Infinity.2188 // HALF_UP 4 Towards nearest neighbour. If equidistant, up.2189 // HALF_DOWN 5 Towards nearest neighbour. If equidistant, down.2190 // HALF_EVEN 6 Towards nearest neighbour. If equidistant, towards even neighbour.2191 // HALF_CEIL 7 Towards nearest neighbour. If equidistant, towards +Infinity.2192 // HALF_FLOOR 8 Towards nearest neighbour. If equidistant, towards -Infinity.2193 ROUNDING_MODE = 4, // 0 to 82194 // EXPONENTIAL_AT : [TO_EXP_NEG , TO_EXP_POS]2195 // The exponent value at and beneath which toString returns exponential notation.2196 // Number type: -72197 TO_EXP_NEG = -7, // 0 to -MAX2198 // The exponent value at and above which toString returns exponential notation.2199 // Number type: 212200 TO_EXP_POS = 21, // 0 to MAX2201 // RANGE : [MIN_EXP, MAX_EXP]2202 // The minimum exponent value, beneath which underflow to zero occurs.2203 // Number type: -324 (5e-324)2204 MIN_EXP = -1e7, // -1 to -MAX2205 // The maximum exponent value, above which overflow to Infinity occurs.2206 // Number type: 308 (1.7976931348623157e+308)2207 // For MAX_EXP > 1e7, e.g. new BigNumber('1e100000000').plus(1) may be slow.2208 MAX_EXP = 1e7, // 1 to MAX2209 // Whether to use cryptographically-secure random number generation, if available.2210 CRYPTO = false, // true or false2211 // The modulo mode used when calculating the modulus: a mod n.2212 // The quotient (q = a / n) is calculated according to the corresponding rounding mode.2213 // The remainder (r) is calculated as: r = a - n * q.2214 //2215 // UP 0 The remainder is positive if the dividend is negative, else is negative.2216 // DOWN 1 The remainder has the same sign as the dividend.2217 // This modulo mode is commonly known as 'truncated division' and is2218 // equivalent to (a % n) in JavaScript.2219 // FLOOR 3 The remainder has the same sign as the divisor (Python %).2220 // HALF_EVEN 6 This modulo mode implements the IEEE 754 remainder function.2221 // EUCLID 9 Euclidian division. q = sign(n) * floor(a / abs(n)).2222 // The remainder is always positive.2223 //2224 // The truncated division, floored division, Euclidian division and IEEE 754 remainder2225 // modes are commonly used for the modulus operation.2226 // Although the other rounding modes can also be used, they may not give useful results.2227 MODULO_MODE = 1, // 0 to 92228 // The maximum number of significant digits of the result of the exponentiatedBy operation.2229 // If POW_PRECISION is 0, there will be unlimited significant digits.2230 POW_PRECISION = 0, // 0 to MAX2231 // The format specification used by the BigNumber.prototype.toFormat method.2232 FORMAT = {2233 prefix: '',2234 groupSize: 3,2235 secondaryGroupSize: 0,2236 groupSeparator: ',',2237 decimalSeparator: '.',2238 fractionGroupSize: 0,2239 fractionGroupSeparator: '\xA0', // non-breaking space2240 suffix: ''2241 },2242 // The alphabet used for base conversion. It must be at least 2 characters long, with no '+',2243 // '-', '.', whitespace, or repeated character.2244 // '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_'2245 ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyz',2246 alphabetHasNormalDecimalDigits = true;2247 //------------------------------------------------------------------------------------------2248 // CONSTRUCTOR2249 /*2250 * The BigNumber constructor and exported function.2251 * Create and return a new instance of a BigNumber object.2252 *2253 * v {number|string|BigNumber} A numeric value.2254 * [b] {number} The base of v. Integer, 2 to ALPHABET.length inclusive.2255 */2256 function BigNumber(v, b) {2257 var alphabet, c, caseChanged, e, i, isNum, len, str,2258 x = this;2259 // Enable constructor call without `new`.2260 if (!(x instanceof BigNumber)) return new BigNumber(v, b);2261 if (b == null) {2262 if (v && v._isBigNumber === true) {2263 x.s = v.s;2264 if (!v.c || v.e > MAX_EXP) {2265 x.c = x.e = null;2266 } else if (v.e < MIN_EXP) {2267 x.c = [x.e = 0];2268 } else {2269 x.e = v.e;2270 x.c = v.c.slice();2271 }2272 return;2273 }2274 if ((isNum = typeof v == 'number') && v * 0 == 0) {2275 // Use `1 / n` to handle minus zero also.2276 x.s = 1 / v < 0 ? (v = -v, -1) : 1;2277 // Fast path for integers, where n < 2147483648 (2**31).2278 if (v === ~~v) {2279 for (e = 0, i = v; i >= 10; i /= 10, e++);2280 if (e > MAX_EXP) {2281 x.c = x.e = null;2282 } else {2283 x.e = e;2284 x.c = [v];2285 }2286 return;2287 }2288 str = String(v);2289 } else {2290 if (!isNumeric.test(str = String(v))) return parseNumeric(x, str, isNum);2291 x.s = str.charCodeAt(0) == 45 ? (str = str.slice(1), -1) : 1;2292 }2293 // Decimal point?2294 if ((e = str.indexOf('.')) > -1) str = str.replace('.', '');2295 // Exponential form?2296 if ((i = str.search(/e/i)) > 0) {2297 // Determine exponent.2298 if (e < 0) e = i;2299 e += +str.slice(i + 1);2300 str = str.substring(0, i);2301 } else if (e < 0) {2302 // Integer.2303 e = str.length;2304 }2305 } else {2306 // '[BigNumber Error] Base {not a primitive number|not an integer|out of range}: {b}'2307 intCheck(b, 2, ALPHABET.length, 'Base');2308 // Allow exponential notation to be used with base 10 argument, while2309 // also rounding to DECIMAL_PLACES as with other bases.2310 if (b == 10 && alphabetHasNormalDecimalDigits) {2311 x = new BigNumber(v);2312 return round(x, DECIMAL_PLACES + x.e + 1, ROUNDING_MODE);2313 }2314 str = String(v);2315 if (isNum = typeof v == 'number') {2316 // Avoid potential interpretation of Infinity and NaN as base 44+ values.2317 if (v * 0 != 0) return parseNumeric(x, str, isNum, b);2318 x.s = 1 / v < 0 ? (str = str.slice(1), -1) : 1;2319 // '[BigNumber Error] Number primitive has more than 15 significant digits: {n}'2320 if (BigNumber.DEBUG && str.replace(/^0\.0*|\./, '').length > 15) {2321 throw Error2322 (tooManyDigits + v);2323 }2324 } else {2325 x.s = str.charCodeAt(0) === 45 ? (str = str.slice(1), -1) : 1;2326 }2327 alphabet = ALPHABET.slice(0, b);2328 e = i = 0;2329 // Check that str is a valid base b number.2330 // Don't use RegExp, so alphabet can contain special characters.2331 for (len = str.length; i < len; i++) {2332 if (alphabet.indexOf(c = str.charAt(i)) < 0) {2333 if (c == '.') {2334 // If '.' is not the first character and it has not be found before.2335 if (i > e) {2336 e = len;2337 continue;2338 }2339 } else if (!caseChanged) {2340 // Allow e.g. hexadecimal 'FF' as well as 'ff'.2341 if (str == str.toUpperCase() && (str = str.toLowerCase()) ||2342 str == str.toLowerCase() && (str = str.toUpperCase())) {2343 caseChanged = true;2344 i = -1;2345 e = 0;2346 continue;2347 }2348 }2349 return parseNumeric(x, String(v), isNum, b);2350 }2351 }2352 // Prevent later check for length on converted number.2353 isNum = false;2354 str = convertBase(str, b, 10, x.s);2355 // Decimal point?2356 if ((e = str.indexOf('.')) > -1) str = str.replace('.', '');2357 else e = str.length;2358 }2359 // Determine leading zeros.2360 for (i = 0; str.charCodeAt(i) === 48; i++);2361 // Determine trailing zeros.2362 for (len = str.length; str.charCodeAt(--len) === 48;);2363 if (str = str.slice(i, ++len)) {2364 len -= i;2365 // '[BigNumber Error] Number primitive has more than 15 significant digits: {n}'2366 if (isNum && BigNumber.DEBUG &&2367 len > 15 && (v > MAX_SAFE_INTEGER || v !== mathfloor(v))) {2368 throw Error2369 (tooManyDigits + (x.s * v));2370 }2371 // Overflow?2372 if ((e = e - i - 1) > MAX_EXP) {2373 // Infinity.2374 x.c = x.e = null;2375 // Underflow?2376 } else if (e < MIN_EXP) {2377 // Zero.2378 x.c = [x.e = 0];2379 } else {2380 x.e = e;2381 x.c = [];2382 // Transform base2383 // e is the base 10 exponent.2384 // i is where to slice str to get the first element of the coefficient array.2385 i = (e + 1) % LOG_BASE;2386 if (e < 0) i += LOG_BASE; // i < 12387 if (i < len) {2388 if (i) x.c.push(+str.slice(0, i));2389 for (len -= LOG_BASE; i < len;) {2390 x.c.push(+str.slice(i, i += LOG_BASE));2391 }2392 i = LOG_BASE - (str = str.slice(i)).length;2393 } else {2394 i -= len;2395 }2396 for (; i--; str += '0');2397 x.c.push(+str);2398 }2399 } else {2400 // Zero.2401 x.c = [x.e = 0];2402 }2403 }2404 // CONSTRUCTOR PROPERTIES2405 BigNumber.clone = clone;2406 BigNumber.ROUND_UP = 0;2407 BigNumber.ROUND_DOWN = 1;2408 BigNumber.ROUND_CEIL = 2;2409 BigNumber.ROUND_FLOOR = 3;2410 BigNumber.ROUND_HALF_UP = 4;2411 BigNumber.ROUND_HALF_DOWN = 5;2412 BigNumber.ROUND_HALF_EVEN = 6;2413 BigNumber.ROUND_HALF_CEIL = 7;2414 BigNumber.ROUND_HALF_FLOOR = 8;2415 BigNumber.EUCLID = 9;2416 /*2417 * Configure infrequently-changing library-wide settings.2418 *2419 * Accept an object with the following optional properties (if the value of a property is2420 * a number, it must be an integer within the inclusive range stated):2421 *2422 * DECIMAL_PLACES {number} 0 to MAX2423 * ROUNDING_MODE {number} 0 to 82424 * EXPONENTIAL_AT {number|number[]} -MAX to MAX or [-MAX to 0, 0 to MAX]2425 * RANGE {number|number[]} -MAX to MAX (not zero) or [-MAX to -1, 1 to MAX]2426 * CRYPTO {boolean} true or false2427 * MODULO_MODE {number} 0 to 92428 * POW_PRECISION {number} 0 to MAX2429 * ALPHABET {string} A string of two or more unique characters which does2430 * not contain '.'.2431 * FORMAT {object} An object with some of the following properties:2432 * prefix {string}2433 * groupSize {number}2434 * secondaryGroupSize {number}2435 * groupSeparator {string}2436 * decimalSeparator {string}2437 * fractionGroupSize {number}2438 * fractionGroupSeparator {string}2439 * suffix {string}2440 *2441 * (The values assigned to the above FORMAT object properties are not checked for validity.)2442 *2443 * E.g.2444 * BigNumber.config({ DECIMAL_PLACES : 20, ROUNDING_MODE : 4 })2445 *2446 * Ignore properties/parameters set to null or undefined, except for ALPHABET.2447 *2448 * Return an object with the properties current values.2449 */2450 BigNumber.config = BigNumber.set = function (obj) {2451 var p, v;2452 if (obj != null) {2453 if (typeof obj == 'object') {2454 // DECIMAL_PLACES {number} Integer, 0 to MAX inclusive.2455 // '[BigNumber Error] DECIMAL_PLACES {not a primitive number|not an integer|out of range}: {v}'2456 if (obj.hasOwnProperty(p = 'DECIMAL_PLACES')) {2457 v = obj[p];2458 intCheck(v, 0, MAX, p);2459 DECIMAL_PLACES = v;2460 }2461 // ROUNDING_MODE {number} Integer, 0 to 8 inclusive.2462 // '[BigNumber Error] ROUNDING_MODE {not a primitive number|not an integer|out of range}: {v}'2463 if (obj.hasOwnProperty(p = 'ROUNDING_MODE')) {2464 v = obj[p];2465 intCheck(v, 0, 8, p);2466 ROUNDING_MODE = v;2467 }2468 // EXPONENTIAL_AT {number|number[]}2469 // Integer, -MAX to MAX inclusive or2470 // [integer -MAX to 0 inclusive, 0 to MAX inclusive].2471 // '[BigNumber Error] EXPONENTIAL_AT {not a primitive number|not an integer|out of range}: {v}'2472 if (obj.hasOwnProperty(p = 'EXPONENTIAL_AT')) {2473 v = obj[p];2474 if (v && v.pop) {2475 intCheck(v[0], -MAX, 0, p);2476 intCheck(v[1], 0, MAX, p);2477 TO_EXP_NEG = v[0];2478 TO_EXP_POS = v[1];2479 } else {2480 intCheck(v, -MAX, MAX, p);2481 TO_EXP_NEG = -(TO_EXP_POS = v < 0 ? -v : v);2482 }2483 }2484 // RANGE {number|number[]} Non-zero integer, -MAX to MAX inclusive or2485 // [integer -MAX to -1 inclusive, integer 1 to MAX inclusive].2486 // '[BigNumber Error] RANGE {not a primitive number|not an integer|out of range|cannot be zero}: {v}'2487 if (obj.hasOwnProperty(p = 'RANGE')) {2488 v = obj[p];2489 if (v && v.pop) {2490 intCheck(v[0], -MAX, -1, p);2491 intCheck(v[1], 1, MAX, p);2492 MIN_EXP = v[0];2493 MAX_EXP = v[1];2494 } else {2495 intCheck(v, -MAX, MAX, p);2496 if (v) {2497 MIN_EXP = -(MAX_EXP = v < 0 ? -v : v);2498 } else {2499 throw Error2500 (bignumberError + p + ' cannot be zero: ' + v);2501 }2502 }2503 }2504 // CRYPTO {boolean} true or false.2505 // '[BigNumber Error] CRYPTO not true or false: {v}'2506 // '[BigNumber Error] crypto unavailable'2507 if (obj.hasOwnProperty(p = 'CRYPTO')) {2508 v = obj[p];2509 if (v === !!v) {2510 if (v) {2511 if (typeof crypto != 'undefined' && crypto &&2512 (crypto.getRandomValues || crypto.randomBytes)) {2513 CRYPTO = v;2514 } else {2515 CRYPTO = !v;2516 throw Error2517 (bignumberError + 'crypto unavailable');2518 }2519 } else {2520 CRYPTO = v;2521 }2522 } else {2523 throw Error2524 (bignumberError + p + ' not true or false: ' + v);2525 }2526 }2527 // MODULO_MODE {number} Integer, 0 to 9 inclusive.2528 // '[BigNumber Error] MODULO_MODE {not a primitive number|not an integer|out of range}: {v}'2529 if (obj.hasOwnProperty(p = 'MODULO_MODE')) {2530 v = obj[p];2531 intCheck(v, 0, 9, p);2532 MODULO_MODE = v;2533 }2534 // POW_PRECISION {number} Integer, 0 to MAX inclusive.2535 // '[BigNumber Error] POW_PRECISION {not a primitive number|not an integer|out of range}: {v}'2536 if (obj.hasOwnProperty(p = 'POW_PRECISION')) {2537 v = obj[p];2538 intCheck(v, 0, MAX, p);2539 POW_PRECISION = v;2540 }2541 // FORMAT {object}2542 // '[BigNumber Error] FORMAT not an object: {v}'2543 if (obj.hasOwnProperty(p = 'FORMAT')) {2544 v = obj[p];2545 if (typeof v == 'object') FORMAT = v;2546 else throw Error2547 (bignumberError + p + ' not an object: ' + v);2548 }2549 // ALPHABET {string}2550 // '[BigNumber Error] ALPHABET invalid: {v}'2551 if (obj.hasOwnProperty(p = 'ALPHABET')) {2552 v = obj[p];2553 // Disallow if less than two characters,2554 // or if it contains '+', '-', '.', whitespace, or a repeated character.2555 if (typeof v == 'string' && !/^.?$|[+\-.\s]|(.).*\1/.test(v)) {2556 alphabetHasNormalDecimalDigits = v.slice(0, 10) == '0123456789';2557 ALPHABET = v;2558 } else {2559 throw Error2560 (bignumberError + p + ' invalid: ' + v);2561 }2562 }2563 } else {2564 // '[BigNumber Error] Object expected: {v}'2565 throw Error2566 (bignumberError + 'Object expected: ' + obj);2567 }2568 }2569 return {2570 DECIMAL_PLACES: DECIMAL_PLACES,2571 ROUNDING_MODE: ROUNDING_MODE,2572 EXPONENTIAL_AT: [TO_EXP_NEG, TO_EXP_POS],2573 RANGE: [MIN_EXP, MAX_EXP],2574 CRYPTO: CRYPTO,2575 MODULO_MODE: MODULO_MODE,2576 POW_PRECISION: POW_PRECISION,2577 FORMAT: FORMAT,2578 ALPHABET: ALPHABET2579 };2580 };2581 /*2582 * Return true if v is a BigNumber instance, otherwise return false.2583 *2584 * If BigNumber.DEBUG is true, throw if a BigNumber instance is not well-formed.2585 *2586 * v {any}2587 *2588 * '[BigNumber Error] Invalid BigNumber: {v}'2589 */2590 BigNumber.isBigNumber = function (v) {2591 if (!v || v._isBigNumber !== true) return false;2592 if (!BigNumber.DEBUG) return true;2593 var i, n,2594 c = v.c,2595 e = v.e,2596 s = v.s;2597 out: if ({}.toString.call(c) == '[object Array]') {2598 if ((s === 1 || s === -1) && e >= -MAX && e <= MAX && e === mathfloor(e)) {2599 // If the first element is zero, the BigNumber value must be zero.2600 if (c[0] === 0) {2601 if (e === 0 && c.length === 1) return true;2602 break out;2603 }2604 // Calculate number of digits that c[0] should have, based on the exponent.2605 i = (e + 1) % LOG_BASE;2606 if (i < 1) i += LOG_BASE;2607 // Calculate number of digits of c[0].2608 //if (Math.ceil(Math.log(c[0] + 1) / Math.LN10) == i) {2609 if (String(c[0]).length == i) {2610 for (i = 0; i < c.length; i++) {2611 n = c[i];2612 if (n < 0 || n >= BASE || n !== mathfloor(n)) break out;2613 }2614 // Last element cannot be zero, unless it is the only element.2615 if (n !== 0) return true;2616 }2617 }2618 // Infinity/NaN2619 } else if (c === null && e === null && (s === null || s === 1 || s === -1)) {2620 return true;2621 }2622 throw Error2623 (bignumberError + 'Invalid BigNumber: ' + v);2624 };2625 /*2626 * Return a new BigNumber whose value is the maximum of the arguments.2627 *2628 * arguments {number|string|BigNumber}2629 */2630 BigNumber.maximum = BigNumber.max = function () {2631 return maxOrMin(arguments, P.lt);2632 };2633 /*2634 * Return a new BigNumber whose value is the minimum of the arguments.2635 *2636 * arguments {number|string|BigNumber}2637 */2638 BigNumber.minimum = BigNumber.min = function () {2639 return maxOrMin(arguments, P.gt);2640 };2641 /*2642 * Return a new BigNumber with a random value equal to or greater than 0 and less than 1,2643 * and with dp, or DECIMAL_PLACES if dp is omitted, decimal places (or less if trailing2644 * zeros are produced).2645 *2646 * [dp] {number} Decimal places. Integer, 0 to MAX inclusive.2647 *2648 * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp}'2649 * '[BigNumber Error] crypto unavailable'2650 */2651 BigNumber.random = (function () {2652 var pow2_53 = 0x20000000000000;2653 // Return a 53 bit integer n, where 0 <= n < 9007199254740992.2654 // Check if Math.random() produces more than 32 bits of randomness.2655 // If it does, assume at least 53 bits are produced, otherwise assume at least 30 bits.2656 // 0x40000000 is 2^30, 0x800000 is 2^23, 0x1fffff is 2^21 - 1.2657 var random53bitInt = (Math.random() * pow2_53) & 0x1fffff2658 ? function () { return mathfloor(Math.random() * pow2_53); }2659 : function () { return ((Math.random() * 0x40000000 | 0) * 0x800000) +2660 (Math.random() * 0x800000 | 0); };2661 return function (dp) {2662 var a, b, e, k, v,2663 i = 0,2664 c = [],2665 rand = new BigNumber(ONE);2666 if (dp == null) dp = DECIMAL_PLACES;2667 else intCheck(dp, 0, MAX);2668 k = mathceil(dp / LOG_BASE);2669 if (CRYPTO) {2670 // Browsers supporting crypto.getRandomValues.2671 if (crypto.getRandomValues) {2672 a = crypto.getRandomValues(new Uint32Array(k *= 2));2673 for (; i < k;) {2674 // 53 bits:2675 // ((Math.pow(2, 32) - 1) * Math.pow(2, 21)).toString(2)2676 // 11111 11111111 11111111 11111111 11100000 00000000 000000002677 // ((Math.pow(2, 32) - 1) >>> 11).toString(2)2678 // 11111 11111111 111111112679 // 0x20000 is 2^21.2680 v = a[i] * 0x20000 + (a[i + 1] >>> 11);2681 // Rejection sampling:2682 // 0 <= v < 90071992547409922683 // Probability that v >= 9e15, is2684 // 7199254740992 / 9007199254740992 ~= 0.0008, i.e. 1 in 12512685 if (v >= 9e15) {2686 b = crypto.getRandomValues(new Uint32Array(2));2687 a[i] = b[0];2688 a[i + 1] = b[1];2689 } else {2690 // 0 <= v <= 89999999999999992691 // 0 <= (v % 1e14) <= 999999999999992692 c.push(v % 1e14);2693 i += 2;2694 }2695 }2696 i = k / 2;2697 // Node.js supporting crypto.randomBytes.2698 } else if (crypto.randomBytes) {2699 // buffer2700 a = crypto.randomBytes(k *= 7);2701 for (; i < k;) {2702 // 0x1000000000000 is 2^48, 0x10000000000 is 2^402703 // 0x100000000 is 2^32, 0x1000000 is 2^242704 // 11111 11111111 11111111 11111111 11111111 11111111 111111112705 // 0 <= v < 90071992547409922706 v = ((a[i] & 31) * 0x1000000000000) + (a[i + 1] * 0x10000000000) +2707 (a[i + 2] * 0x100000000) + (a[i + 3] * 0x1000000) +2708 (a[i + 4] << 16) + (a[i + 5] << 8) + a[i + 6];2709 if (v >= 9e15) {2710 crypto.randomBytes(7).copy(a, i);2711 } else {2712 // 0 <= (v % 1e14) <= 999999999999992713 c.push(v % 1e14);2714 i += 7;2715 }2716 }2717 i = k / 7;2718 } else {2719 CRYPTO = false;2720 throw Error2721 (bignumberError + 'crypto unavailable');2722 }2723 }2724 // Use Math.random.2725 if (!CRYPTO) {2726 for (; i < k;) {2727 v = random53bitInt();2728 if (v < 9e15) c[i++] = v % 1e14;2729 }2730 }2731 k = c[--i];2732 dp %= LOG_BASE;2733 // Convert trailing digits to zeros according to dp.2734 if (k && dp) {2735 v = POWS_TEN[LOG_BASE - dp];2736 c[i] = mathfloor(k / v) * v;2737 }2738 // Remove trailing elements which are zero.2739 for (; c[i] === 0; c.pop(), i--);2740 // Zero?2741 if (i < 0) {2742 c = [e = 0];2743 } else {2744 // Remove leading elements which are zero and adjust exponent accordingly.2745 for (e = -1 ; c[0] === 0; c.splice(0, 1), e -= LOG_BASE);2746 // Count the digits of the first element of c to determine leading zeros, and...2747 for (i = 1, v = c[0]; v >= 10; v /= 10, i++);2748 // adjust the exponent accordingly.2749 if (i < LOG_BASE) e -= LOG_BASE - i;2750 }2751 rand.e = e;2752 rand.c = c;2753 return rand;2754 };2755 })();2756 /*2757 * Return a BigNumber whose value is the sum of the arguments.2758 *2759 * arguments {number|string|BigNumber}2760 */2761 BigNumber.sum = function () {2762 var i = 1,2763 args = arguments,2764 sum = new BigNumber(args[0]);2765 for (; i < args.length;) sum = sum.plus(args[i++]);2766 return sum;2767 };2768 // PRIVATE FUNCTIONS2769 // Called by BigNumber and BigNumber.prototype.toString.2770 convertBase = (function () {2771 var decimal = '0123456789';2772 /*2773 * Convert string of baseIn to an array of numbers of baseOut.2774 * Eg. toBaseOut('255', 10, 16) returns [15, 15].2775 * Eg. toBaseOut('ff', 16, 10) returns [2, 5, 5].2776 */2777 function toBaseOut(str, baseIn, baseOut, alphabet) {2778 var j,2779 arr = [0],2780 arrL,2781 i = 0,2782 len = str.length;2783 for (; i < len;) {2784 for (arrL = arr.length; arrL--; arr[arrL] *= baseIn);2785 arr[0] += alphabet.indexOf(str.charAt(i++));2786 for (j = 0; j < arr.length; j++) {2787 if (arr[j] > baseOut - 1) {2788 if (arr[j + 1] == null) arr[j + 1] = 0;2789 arr[j + 1] += arr[j] / baseOut | 0;2790 arr[j] %= baseOut;2791 }2792 }2793 }2794 return arr.reverse();2795 }2796 // Convert a numeric string of baseIn to a numeric string of baseOut.2797 // If the caller is toString, we are converting from base 10 to baseOut.2798 // If the caller is BigNumber, we are converting from baseIn to base 10.2799 return function (str, baseIn, baseOut, sign, callerIsToString) {2800 var alphabet, d, e, k, r, x, xc, y,2801 i = str.indexOf('.'),2802 dp = DECIMAL_PLACES,2803 rm = ROUNDING_MODE;2804 // Non-integer.2805 if (i >= 0) {2806 k = POW_PRECISION;2807 // Unlimited precision.2808 POW_PRECISION = 0;2809 str = str.replace('.', '');2810 y = new BigNumber(baseIn);2811 x = y.pow(str.length - i);2812 POW_PRECISION = k;2813 // Convert str as if an integer, then restore the fraction part by dividing the2814 // result by its base raised to a power.2815 y.c = toBaseOut(toFixedPoint(coeffToString(x.c), x.e, '0'),2816 10, baseOut, decimal);2817 y.e = y.c.length;2818 }2819 // Convert the number as integer.2820 xc = toBaseOut(str, baseIn, baseOut, callerIsToString2821 ? (alphabet = ALPHABET, decimal)2822 : (alphabet = decimal, ALPHABET));2823 // xc now represents str as an integer and converted to baseOut. e is the exponent.2824 e = k = xc.length;2825 // Remove trailing zeros.2826 for (; xc[--k] == 0; xc.pop());2827 // Zero?2828 if (!xc[0]) return alphabet.charAt(0);2829 // Does str represent an integer? If so, no need for the division.2830 if (i < 0) {2831 --e;2832 } else {2833 x.c = xc;2834 x.e = e;2835 // The sign is needed for correct rounding.2836 x.s = sign;2837 x = div(x, y, dp, rm, baseOut);2838 xc = x.c;2839 r = x.r;2840 e = x.e;2841 }2842 // xc now represents str converted to baseOut.2843 // THe index of the rounding digit.2844 d = e + dp + 1;2845 // The rounding digit: the digit to the right of the digit that may be rounded up.2846 i = xc[d];2847 // Look at the rounding digits and mode to determine whether to round up.2848 k = baseOut / 2;2849 r = r || d < 0 || xc[d + 1] != null;2850 r = rm < 4 ? (i != null || r) && (rm == 0 || rm == (x.s < 0 ? 3 : 2))2851 : i > k || i == k &&(rm == 4 || r || rm == 6 && xc[d - 1] & 1 ||2852 rm == (x.s < 0 ? 8 : 7));2853 // If the index of the rounding digit is not greater than zero, or xc represents2854 // zero, then the result of the base conversion is zero or, if rounding up, a value2855 // such as 0.00001.2856 if (d < 1 || !xc[0]) {2857 // 1^-dp or 02858 str = r ? toFixedPoint(alphabet.charAt(1), -dp, alphabet.charAt(0)) : alphabet.charAt(0);2859 } else {2860 // Truncate xc to the required number of decimal places.2861 xc.length = d;2862 // Round up?2863 if (r) {2864 // Rounding up may mean the previous digit has to be rounded up and so on.2865 for (--baseOut; ++xc[--d] > baseOut;) {2866 xc[d] = 0;2867 if (!d) {2868 ++e;2869 xc = [1].concat(xc);2870 }2871 }2872 }2873 // Determine trailing zeros.2874 for (k = xc.length; !xc[--k];);2875 // E.g. [4, 11, 15] becomes 4bf.2876 for (i = 0, str = ''; i <= k; str += alphabet.charAt(xc[i++]));2877 // Add leading zeros, decimal point and trailing zeros as required.2878 str = toFixedPoint(str, e, alphabet.charAt(0));2879 }2880 // The caller will add the sign.2881 return str;2882 };2883 })();2884 // Perform division in the specified base. Called by div and convertBase.2885 div = (function () {2886 // Assume non-zero x and k.2887 function multiply(x, k, base) {2888 var m, temp, xlo, xhi,2889 carry = 0,2890 i = x.length,2891 klo = k % SQRT_BASE,2892 khi = k / SQRT_BASE | 0;2893 for (x = x.slice(); i--;) {2894 xlo = x[i] % SQRT_BASE;2895 xhi = x[i] / SQRT_BASE | 0;2896 m = khi * xlo + xhi * klo;2897 temp = klo * xlo + ((m % SQRT_BASE) * SQRT_BASE) + carry;2898 carry = (temp / base | 0) + (m / SQRT_BASE | 0) + khi * xhi;2899 x[i] = temp % base;2900 }2901 if (carry) x = [carry].concat(x);2902 return x;2903 }2904 function compare(a, b, aL, bL) {2905 var i, cmp;2906 if (aL != bL) {2907 cmp = aL > bL ? 1 : -1;2908 } else {2909 for (i = cmp = 0; i < aL; i++) {2910 if (a[i] != b[i]) {2911 cmp = a[i] > b[i] ? 1 : -1;2912 break;2913 }2914 }2915 }2916 return cmp;2917 }2918 function subtract(a, b, aL, base) {2919 var i = 0;2920 // Subtract b from a.2921 for (; aL--;) {2922 a[aL] -= i;2923 i = a[aL] < b[aL] ? 1 : 0;2924 a[aL] = i * base + a[aL] - b[aL];2925 }2926 // Remove leading zeros.2927 for (; !a[0] && a.length > 1; a.splice(0, 1));2928 }2929 // x: dividend, y: divisor.2930 return function (x, y, dp, rm, base) {2931 var cmp, e, i, more, n, prod, prodL, q, qc, rem, remL, rem0, xi, xL, yc0,2932 yL, yz,2933 s = x.s == y.s ? 1 : -1,2934 xc = x.c,2935 yc = y.c;2936 // Either NaN, Infinity or 0?2937 if (!xc || !xc[0] || !yc || !yc[0]) {2938 return new BigNumber(2939 // Return NaN if either NaN, or both Infinity or 0.2940 !x.s || !y.s || (xc ? yc && xc[0] == yc[0] : !yc) ? NaN :2941 // Return ±0 if x is ±0 or y is ±Infinity, or return ±Infinity as y is ±0.2942 xc && xc[0] == 0 || !yc ? s * 0 : s / 02943 );2944 }2945 q = new BigNumber(s);2946 qc = q.c = [];2947 e = x.e - y.e;2948 s = dp + e + 1;2949 if (!base) {2950 base = BASE;2951 e = bitFloor(x.e / LOG_BASE) - bitFloor(y.e / LOG_BASE);2952 s = s / LOG_BASE | 0;2953 }2954 // Result exponent may be one less then the current value of e.2955 // The coefficients of the BigNumbers from convertBase may have trailing zeros.2956 for (i = 0; yc[i] == (xc[i] || 0); i++);2957 if (yc[i] > (xc[i] || 0)) e--;2958 if (s < 0) {2959 qc.push(1);2960 more = true;2961 } else {2962 xL = xc.length;2963 yL = yc.length;2964 i = 0;2965 s += 2;2966 // Normalise xc and yc so highest order digit of yc is >= base / 2.2967 n = mathfloor(base / (yc[0] + 1));2968 // Not necessary, but to handle odd bases where yc[0] == (base / 2) - 1.2969 // if (n > 1 || n++ == 1 && yc[0] < base / 2) {2970 if (n > 1) {2971 yc = multiply(yc, n, base);2972 xc = multiply(xc, n, base);2973 yL = yc.length;2974 xL = xc.length;2975 }2976 xi = yL;2977 rem = xc.slice(0, yL);2978 remL = rem.length;2979 // Add zeros to make remainder as long as divisor.2980 for (; remL < yL; rem[remL++] = 0);2981 yz = yc.slice();2982 yz = [0].concat(yz);2983 yc0 = yc[0];2984 if (yc[1] >= base / 2) yc0++;2985 // Not necessary, but to prevent trial digit n > base, when using base 3.2986 // else if (base == 3 && yc0 == 1) yc0 = 1 + 1e-15;2987 do {2988 n = 0;2989 // Compare divisor and remainder.2990 cmp = compare(yc, rem, yL, remL);2991 // If divisor < remainder.2992 if (cmp < 0) {2993 // Calculate trial digit, n.2994 rem0 = rem[0];2995 if (yL != remL) rem0 = rem0 * base + (rem[1] || 0);2996 // n is how many times the divisor goes into the current remainder.2997 n = mathfloor(rem0 / yc0);2998 // Algorithm:2999 // product = divisor multiplied by trial digit (n).3000 // Compare product and remainder.3001 // If product is greater than remainder:3002 // Subtract divisor from product, decrement trial digit.3003 // Subtract product from remainder.3004 // If product was less than remainder at the last compare:3005 // Compare new remainder and divisor.3006 // If remainder is greater than divisor:3007 // Subtract divisor from remainder, increment trial digit.3008 if (n > 1) {3009 // n may be > base only when base is 3.3010 if (n >= base) n = base - 1;3011 // product = divisor * trial digit.3012 prod = multiply(yc, n, base);3013 prodL = prod.length;3014 remL = rem.length;3015 // Compare product and remainder.3016 // If product > remainder then trial digit n too high.3017 // n is 1 too high about 5% of the time, and is not known to have3018 // ever been more than 1 too high.3019 while (compare(prod, rem, prodL, remL) == 1) {3020 n--;3021 // Subtract divisor from product.3022 subtract(prod, yL < prodL ? yz : yc, prodL, base);3023 prodL = prod.length;3024 cmp = 1;3025 }3026 } else {3027 // n is 0 or 1, cmp is -1.3028 // If n is 0, there is no need to compare yc and rem again below,3029 // so change cmp to 1 to avoid it.3030 // If n is 1, leave cmp as -1, so yc and rem are compared again.3031 if (n == 0) {3032 // divisor < remainder, so n must be at least 1.3033 cmp = n = 1;3034 }3035 // product = divisor3036 prod = yc.slice();3037 prodL = prod.length;3038 }3039 if (prodL < remL) prod = [0].concat(prod);3040 // Subtract product from remainder.3041 subtract(rem, prod, remL, base);3042 remL = rem.length;3043 // If product was < remainder.3044 if (cmp == -1) {3045 // Compare divisor and new remainder.3046 // If divisor < new remainder, subtract divisor from remainder.3047 // Trial digit n too low.3048 // n is 1 too low about 5% of the time, and very rarely 2 too low.3049 while (compare(yc, rem, yL, remL) < 1) {3050 n++;3051 // Subtract divisor from remainder.3052 subtract(rem, yL < remL ? yz : yc, remL, base);3053 remL = rem.length;3054 }3055 }3056 } else if (cmp === 0) {3057 n++;3058 rem = [0];3059 } // else cmp === 1 and n will be 03060 // Add the next digit, n, to the result array.3061 qc[i++] = n;3062 // Update the remainder.3063 if (rem[0]) {3064 rem[remL++] = xc[xi] || 0;3065 } else {3066 rem = [xc[xi]];3067 remL = 1;3068 }3069 } while ((xi++ < xL || rem[0] != null) && s--);3070 more = rem[0] != null;3071 // Leading zero?3072 if (!qc[0]) qc.splice(0, 1);3073 }3074 if (base == BASE) {3075 // To calculate q.e, first get the number of digits of qc[0].3076 for (i = 1, s = qc[0]; s >= 10; s /= 10, i++);3077 round(q, dp + (q.e = i + e * LOG_BASE - 1) + 1, rm, more);3078 // Caller is convertBase.3079 } else {3080 q.e = e;3081 q.r = +more;3082 }3083 return q;3084 };3085 })();3086 /*3087 * Return a string representing the value of BigNumber n in fixed-point or exponential3088 * notation rounded to the specified decimal places or significant digits.3089 *3090 * n: a BigNumber.3091 * i: the index of the last digit required (i.e. the digit that may be rounded up).3092 * rm: the rounding mode.3093 * id: 1 (toExponential) or 2 (toPrecision).3094 */3095 function format(n, i, rm, id) {3096 var c0, e, ne, len, str;3097 if (rm == null) rm = ROUNDING_MODE;3098 else intCheck(rm, 0, 8);3099 if (!n.c) return n.toString();3100 c0 = n.c[0];3101 ne = n.e;3102 if (i == null) {3103 str = coeffToString(n.c);3104 str = id == 1 || id == 2 && (ne <= TO_EXP_NEG || ne >= TO_EXP_POS)3105 ? toExponential(str, ne)3106 : toFixedPoint(str, ne, '0');3107 } else {3108 n = round(new BigNumber(n), i, rm);3109 // n.e may have changed if the value was rounded up.3110 e = n.e;3111 str = coeffToString(n.c);3112 len = str.length;3113 // toPrecision returns exponential notation if the number of significant digits3114 // specified is less than the number of digits necessary to represent the integer3115 // part of the value in fixed-point notation.3116 // Exponential notation.3117 if (id == 1 || id == 2 && (i <= e || e <= TO_EXP_NEG)) {3118 // Append zeros?3119 for (; len < i; str += '0', len++);3120 str = toExponential(str, e);3121 // Fixed-point notation.3122 } else {3123 i -= ne;3124 str = toFixedPoint(str, e, '0');3125 // Append zeros?3126 if (e + 1 > len) {3127 if (--i > 0) for (str += '.'; i--; str += '0');3128 } else {3129 i += e - len;3130 if (i > 0) {3131 if (e + 1 == len) str += '.';3132 for (; i--; str += '0');3133 }3134 }3135 }3136 }3137 return n.s < 0 && c0 ? '-' + str : str;3138 }3139 // Handle BigNumber.max and BigNumber.min.3140 function maxOrMin(args, method) {3141 var n,3142 i = 1,3143 m = new BigNumber(args[0]);3144 for (; i < args.length; i++) {3145 n = new BigNumber(args[i]);3146 // If any number is NaN, return NaN.3147 if (!n.s) {3148 m = n;3149 break;3150 } else if (method.call(m, n)) {3151 m = n;3152 }3153 }3154 return m;3155 }3156 /*3157 * Strip trailing zeros, calculate base 10 exponent and check against MIN_EXP and MAX_EXP.3158 * Called by minus, plus and times.3159 */3160 function normalise(n, c, e) {3161 var i = 1,3162 j = c.length;3163 // Remove trailing zeros.3164 for (; !c[--j]; c.pop());3165 // Calculate the base 10 exponent. First get the number of digits of c[0].3166 for (j = c[0]; j >= 10; j /= 10, i++);3167 // Overflow?3168 if ((e = i + e * LOG_BASE - 1) > MAX_EXP) {3169 // Infinity.3170 n.c = n.e = null;3171 // Underflow?3172 } else if (e < MIN_EXP) {3173 // Zero.3174 n.c = [n.e = 0];3175 } else {3176 n.e = e;3177 n.c = c;3178 }3179 return n;3180 }3181 // Handle values that fail the validity test in BigNumber.3182 parseNumeric = (function () {3183 var basePrefix = /^(-?)0([xbo])(?=\w[\w.]*$)/i,3184 dotAfter = /^([^.]+)\.$/,3185 dotBefore = /^\.([^.]+)$/,3186 isInfinityOrNaN = /^-?(Infinity|NaN)$/,3187 whitespaceOrPlus = /^\s*\+(?=[\w.])|^\s+|\s+$/g;3188 return function (x, str, isNum, b) {3189 var base,3190 s = isNum ? str : str.replace(whitespaceOrPlus, '');3191 // No exception on ±Infinity or NaN.3192 if (isInfinityOrNaN.test(s)) {3193 x.s = isNaN(s) ? null : s < 0 ? -1 : 1;3194 } else {3195 if (!isNum) {3196 // basePrefix = /^(-?)0([xbo])(?=\w[\w.]*$)/i3197 s = s.replace(basePrefix, function (m, p1, p2) {3198 base = (p2 = p2.toLowerCase()) == 'x' ? 16 : p2 == 'b' ? 2 : 8;3199 return !b || b == base ? p1 : m;3200 });3201 if (b) {3202 base = b;3203 // E.g. '1.' to '1', '.1' to '0.1'3204 s = s.replace(dotAfter, '$1').replace(dotBefore, '0.$1');3205 }3206 if (str != s) return new BigNumber(s, base);3207 }3208 // '[BigNumber Error] Not a number: {n}'3209 // '[BigNumber Error] Not a base {b} number: {n}'3210 if (BigNumber.DEBUG) {3211 throw Error3212 (bignumberError + 'Not a' + (b ? ' base ' + b : '') + ' number: ' + str);3213 }3214 // NaN3215 x.s = null;3216 }3217 x.c = x.e = null;3218 }3219 })();3220 /*3221 * Round x to sd significant digits using rounding mode rm. Check for over/under-flow.3222 * If r is truthy, it is known that there are more digits after the rounding digit.3223 */3224 function round(x, sd, rm, r) {3225 var d, i, j, k, n, ni, rd,3226 xc = x.c,3227 pows10 = POWS_TEN;3228 // if x is not Infinity or NaN...3229 if (xc) {3230 // rd is the rounding digit, i.e. the digit after the digit that may be rounded up.3231 // n is a base 1e14 number, the value of the element of array x.c containing rd.3232 // ni is the index of n within x.c.3233 // d is the number of digits of n.3234 // i is the index of rd within n including leading zeros.3235 // j is the actual index of rd within n (if < 0, rd is a leading zero).3236 out: {3237 // Get the number of digits of the first element of xc.3238 for (d = 1, k = xc[0]; k >= 10; k /= 10, d++);3239 i = sd - d;3240 // If the rounding digit is in the first element of xc...3241 if (i < 0) {3242 i += LOG_BASE;3243 j = sd;3244 n = xc[ni = 0];3245 // Get the rounding digit at index j of n.3246 rd = n / pows10[d - j - 1] % 10 | 0;3247 } else {3248 ni = mathceil((i + 1) / LOG_BASE);3249 if (ni >= xc.length) {3250 if (r) {3251 // Needed by sqrt.3252 for (; xc.length <= ni; xc.push(0));3253 n = rd = 0;3254 d = 1;3255 i %= LOG_BASE;3256 j = i - LOG_BASE + 1;3257 } else {3258 break out;3259 }3260 } else {3261 n = k = xc[ni];3262 // Get the number of digits of n.3263 for (d = 1; k >= 10; k /= 10, d++);3264 // Get the index of rd within n.3265 i %= LOG_BASE;3266 // Get the index of rd within n, adjusted for leading zeros.3267 // The number of leading zeros of n is given by LOG_BASE - d.3268 j = i - LOG_BASE + d;3269 // Get the rounding digit at index j of n.3270 rd = j < 0 ? 0 : n / pows10[d - j - 1] % 10 | 0;3271 }3272 }3273 r = r || sd < 0 ||3274 // Are there any non-zero digits after the rounding digit?3275 // The expression n % pows10[d - j - 1] returns all digits of n to the right3276 // of the digit at j, e.g. if n is 908714 and j is 2, the expression gives 714.3277 xc[ni + 1] != null || (j < 0 ? n : n % pows10[d - j - 1]);3278 r = rm < 43279 ? (rd || r) && (rm == 0 || rm == (x.s < 0 ? 3 : 2))3280 : rd > 5 || rd == 5 && (rm == 4 || r || rm == 6 &&3281 // Check whether the digit to the left of the rounding digit is odd.3282 ((i > 0 ? j > 0 ? n / pows10[d - j] : 0 : xc[ni - 1]) % 10) & 1 ||3283 rm == (x.s < 0 ? 8 : 7));3284 if (sd < 1 || !xc[0]) {3285 xc.length = 0;3286 if (r) {3287 // Convert sd to decimal places.3288 sd -= x.e + 1;3289 // 1, 0.1, 0.01, 0.001, 0.0001 etc.3290 xc[0] = pows10[(LOG_BASE - sd % LOG_BASE) % LOG_BASE];3291 x.e = -sd || 0;3292 } else {3293 // Zero.3294 xc[0] = x.e = 0;3295 }3296 return x;3297 }3298 // Remove excess digits.3299 if (i == 0) {3300 xc.length = ni;3301 k = 1;3302 ni--;3303 } else {3304 xc.length = ni + 1;3305 k = pows10[LOG_BASE - i];3306 // E.g. 56700 becomes 56000 if 7 is the rounding digit.3307 // j > 0 means i > number of leading zeros of n.3308 xc[ni] = j > 0 ? mathfloor(n / pows10[d - j] % pows10[j]) * k : 0;3309 }3310 // Round up?3311 if (r) {3312 for (; ;) {3313 // If the digit to be rounded up is in the first element of xc...3314 if (ni == 0) {3315 // i will be the length of xc[0] before k is added.3316 for (i = 1, j = xc[0]; j >= 10; j /= 10, i++);3317 j = xc[0] += k;3318 for (k = 1; j >= 10; j /= 10, k++);3319 // if i != k the length has increased.3320 if (i != k) {3321 x.e++;3322 if (xc[0] == BASE) xc[0] = 1;3323 }3324 break;3325 } else {3326 xc[ni] += k;3327 if (xc[ni] != BASE) break;3328 xc[ni--] = 0;3329 k = 1;3330 }3331 }3332 }3333 // Remove trailing zeros.3334 for (i = xc.length; xc[--i] === 0; xc.pop());3335 }3336 // Overflow? Infinity.3337 if (x.e > MAX_EXP) {3338 x.c = x.e = null;3339 // Underflow? Zero.3340 } else if (x.e < MIN_EXP) {3341 x.c = [x.e = 0];3342 }3343 }3344 return x;3345 }3346 function valueOf(n) {3347 var str,3348 e = n.e;3349 if (e === null) return n.toString();3350 str = coeffToString(n.c);3351 str = e <= TO_EXP_NEG || e >= TO_EXP_POS3352 ? toExponential(str, e)3353 : toFixedPoint(str, e, '0');3354 return n.s < 0 ? '-' + str : str;3355 }3356 // PROTOTYPE/INSTANCE METHODS3357 /*3358 * Return a new BigNumber whose value is the absolute value of this BigNumber.3359 */3360 P.absoluteValue = P.abs = function () {3361 var x = new BigNumber(this);3362 if (x.s < 0) x.s = 1;3363 return x;3364 };3365 /*3366 * Return3367 * 1 if the value of this BigNumber is greater than the value of BigNumber(y, b),3368 * -1 if the value of this BigNumber is less than the value of BigNumber(y, b),3369 * 0 if they have the same value,3370 * or null if the value of either is NaN.3371 */3372 P.comparedTo = function (y, b) {3373 return compare(this, new BigNumber(y, b));3374 };3375 /*3376 * If dp is undefined or null or true or false, return the number of decimal places of the3377 * value of this BigNumber, or null if the value of this BigNumber is ±Infinity or NaN.3378 *3379 * Otherwise, if dp is a number, return a new BigNumber whose value is the value of this3380 * BigNumber rounded to a maximum of dp decimal places using rounding mode rm, or3381 * ROUNDING_MODE if rm is omitted.3382 *3383 * [dp] {number} Decimal places: integer, 0 to MAX inclusive.3384 * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.3385 *3386 * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}'3387 */3388 P.decimalPlaces = P.dp = function (dp, rm) {3389 var c, n, v,3390 x = this;3391 if (dp != null) {3392 intCheck(dp, 0, MAX);3393 if (rm == null) rm = ROUNDING_MODE;3394 else intCheck(rm, 0, 8);3395 return round(new BigNumber(x), dp + x.e + 1, rm);3396 }3397 if (!(c = x.c)) return null;3398 n = ((v = c.length - 1) - bitFloor(this.e / LOG_BASE)) * LOG_BASE;3399 // Subtract the number of trailing zeros of the last number.3400 if (v = c[v]) for (; v % 10 == 0; v /= 10, n--);3401 if (n < 0) n = 0;3402 return n;3403 };3404 /*3405 * n / 0 = I3406 * n / N = N3407 * n / I = 03408 * 0 / n = 03409 * 0 / 0 = N3410 * 0 / N = N3411 * 0 / I = 03412 * N / n = N3413 * N / 0 = N3414 * N / N = N3415 * N / I = N3416 * I / n = I3417 * I / 0 = I3418 * I / N = N3419 * I / I = N3420 *3421 * Return a new BigNumber whose value is the value of this BigNumber divided by the value of3422 * BigNumber(y, b), rounded according to DECIMAL_PLACES and ROUNDING_MODE.3423 */3424 P.dividedBy = P.div = function (y, b) {3425 return div(this, new BigNumber(y, b), DECIMAL_PLACES, ROUNDING_MODE);3426 };3427 /*3428 * Return a new BigNumber whose value is the integer part of dividing the value of this3429 * BigNumber by the value of BigNumber(y, b).3430 */3431 P.dividedToIntegerBy = P.idiv = function (y, b) {3432 return div(this, new BigNumber(y, b), 0, 1);3433 };3434 /*3435 * Return a BigNumber whose value is the value of this BigNumber exponentiated by n.3436 *3437 * If m is present, return the result modulo m.3438 * If n is negative round according to DECIMAL_PLACES and ROUNDING_MODE.3439 * If POW_PRECISION is non-zero and m is not present, round to POW_PRECISION using ROUNDING_MODE.3440 *3441 * The modular power operation works efficiently when x, n, and m are integers, otherwise it3442 * is equivalent to calculating x.exponentiatedBy(n).modulo(m) with a POW_PRECISION of 0.3443 *3444 * n {number|string|BigNumber} The exponent. An integer.3445 * [m] {number|string|BigNumber} The modulus.3446 *3447 * '[BigNumber Error] Exponent not an integer: {n}'3448 */3449 P.exponentiatedBy = P.pow = function (n, m) {3450 var half, isModExp, i, k, more, nIsBig, nIsNeg, nIsOdd, y,3451 x = this;3452 n = new BigNumber(n);3453 // Allow NaN and ±Infinity, but not other non-integers.3454 if (n.c && !n.isInteger()) {3455 throw Error3456 (bignumberError + 'Exponent not an integer: ' + valueOf(n));3457 }3458 if (m != null) m = new BigNumber(m);3459 // Exponent of MAX_SAFE_INTEGER is 15.3460 nIsBig = n.e > 14;3461 // If x is NaN, ±Infinity, ±0 or ±1, or n is ±Infinity, NaN or ±0.3462 if (!x.c || !x.c[0] || x.c[0] == 1 && !x.e && x.c.length == 1 || !n.c || !n.c[0]) {3463 // The sign of the result of pow when x is negative depends on the evenness of n.3464 // If +n overflows to ±Infinity, the evenness of n would be not be known.3465 y = new BigNumber(Math.pow(+valueOf(x), nIsBig ? 2 - isOdd(n) : +valueOf(n)));3466 return m ? y.mod(m) : y;3467 }3468 nIsNeg = n.s < 0;3469 if (m) {3470 // x % m returns NaN if abs(m) is zero, or m is NaN.3471 if (m.c ? !m.c[0] : !m.s) return new BigNumber(NaN);3472 isModExp = !nIsNeg && x.isInteger() && m.isInteger();3473 if (isModExp) x = x.mod(m);3474 // Overflow to ±Infinity: >=2**1e10 or >=1.0000024**1e15.3475 // Underflow to ±0: <=0.79**1e10 or <=0.9999975**1e15.3476 } else if (n.e > 9 && (x.e > 0 || x.e < -1 || (x.e == 03477 // [1, 240000000]3478 ? x.c[0] > 1 || nIsBig && x.c[1] >= 24e73479 // [80000000000000] [99999750000000]3480 : x.c[0] < 8e13 || nIsBig && x.c[0] <= 9999975e7))) {3481 // If x is negative and n is odd, k = -0, else k = 0.3482 k = x.s < 0 && isOdd(n) ? -0 : 0;3483 // If x >= 1, k = ±Infinity.3484 if (x.e > -1) k = 1 / k;3485 // If n is negative return ±0, else return ±Infinity.3486 return new BigNumber(nIsNeg ? 1 / k : k);3487 } else if (POW_PRECISION) {3488 // Truncating each coefficient array to a length of k after each multiplication3489 // equates to truncating significant digits to POW_PRECISION + [28, 41],3490 // i.e. there will be a minimum of 28 guard digits retained.3491 k = mathceil(POW_PRECISION / LOG_BASE + 2);3492 }3493 if (nIsBig) {3494 half = new BigNumber(0.5);3495 if (nIsNeg) n.s = 1;3496 nIsOdd = isOdd(n);3497 } else {3498 i = Math.abs(+valueOf(n));3499 nIsOdd = i % 2;3500 }3501 y = new BigNumber(ONE);3502 // Performs 54 loop iterations for n of 9007199254740991.3503 for (; ;) {3504 if (nIsOdd) {3505 y = y.times(x);3506 if (!y.c) break;3507 if (k) {3508 if (y.c.length > k) y.c.length = k;3509 } else if (isModExp) {3510 y = y.mod(m); //y = y.minus(div(y, m, 0, MODULO_MODE).times(m));3511 }3512 }3513 if (i) {3514 i = mathfloor(i / 2);3515 if (i === 0) break;3516 nIsOdd = i % 2;3517 } else {3518 n = n.times(half);3519 round(n, n.e + 1, 1);3520 if (n.e > 14) {3521 nIsOdd = isOdd(n);3522 } else {3523 i = +valueOf(n);3524 if (i === 0) break;3525 nIsOdd = i % 2;3526 }3527 }3528 x = x.times(x);3529 if (k) {3530 if (x.c && x.c.length > k) x.c.length = k;3531 } else if (isModExp) {3532 x = x.mod(m); //x = x.minus(div(x, m, 0, MODULO_MODE).times(m));3533 }3534 }3535 if (isModExp) return y;3536 if (nIsNeg) y = ONE.div(y);3537 return m ? y.mod(m) : k ? round(y, POW_PRECISION, ROUNDING_MODE, more) : y;3538 };3539 /*3540 * Return a new BigNumber whose value is the value of this BigNumber rounded to an integer3541 * using rounding mode rm, or ROUNDING_MODE if rm is omitted.3542 *3543 * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.3544 *3545 * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {rm}'3546 */3547 P.integerValue = function (rm) {3548 var n = new BigNumber(this);3549 if (rm == null) rm = ROUNDING_MODE;3550 else intCheck(rm, 0, 8);3551 return round(n, n.e + 1, rm);3552 };3553 /*3554 * Return true if the value of this BigNumber is equal to the value of BigNumber(y, b),3555 * otherwise return false.3556 */3557 P.isEqualTo = P.eq = function (y, b) {3558 return compare(this, new BigNumber(y, b)) === 0;3559 };3560 /*3561 * Return true if the value of this BigNumber is a finite number, otherwise return false.3562 */3563 P.isFinite = function () {3564 return !!this.c;3565 };3566 /*3567 * Return true if the value of this BigNumber is greater than the value of BigNumber(y, b),3568 * otherwise return false.3569 */3570 P.isGreaterThan = P.gt = function (y, b) {3571 return compare(this, new BigNumber(y, b)) > 0;3572 };3573 /*3574 * Return true if the value of this BigNumber is greater than or equal to the value of3575 * BigNumber(y, b), otherwise return false.3576 */3577 P.isGreaterThanOrEqualTo = P.gte = function (y, b) {3578 return (b = compare(this, new BigNumber(y, b))) === 1 || b === 0;3579 };3580 /*3581 * Return true if the value of this BigNumber is an integer, otherwise return false.3582 */3583 P.isInteger = function () {3584 return !!this.c && bitFloor(this.e / LOG_BASE) > this.c.length - 2;3585 };3586 /*3587 * Return true if the value of this BigNumber is less than the value of BigNumber(y, b),3588 * otherwise return false.3589 */3590 P.isLessThan = P.lt = function (y, b) {3591 return compare(this, new BigNumber(y, b)) < 0;3592 };3593 /*3594 * Return true if the value of this BigNumber is less than or equal to the value of3595 * BigNumber(y, b), otherwise return false.3596 */3597 P.isLessThanOrEqualTo = P.lte = function (y, b) {3598 return (b = compare(this, new BigNumber(y, b))) === -1 || b === 0;3599 };3600 /*3601 * Return true if the value of this BigNumber is NaN, otherwise return false.3602 */3603 P.isNaN = function () {3604 return !this.s;3605 };3606 /*3607 * Return true if the value of this BigNumber is negative, otherwise return false.3608 */3609 P.isNegative = function () {3610 return this.s < 0;3611 };3612 /*3613 * Return true if the value of this BigNumber is positive, otherwise return false.3614 */3615 P.isPositive = function () {3616 return this.s > 0;3617 };3618 /*3619 * Return true if the value of this BigNumber is 0 or -0, otherwise return false.3620 */3621 P.isZero = function () {3622 return !!this.c && this.c[0] == 0;3623 };3624 /*3625 * n - 0 = n3626 * n - N = N3627 * n - I = -I3628 * 0 - n = -n3629 * 0 - 0 = 03630 * 0 - N = N3631 * 0 - I = -I3632 * N - n = N3633 * N - 0 = N3634 * N - N = N3635 * N - I = N3636 * I - n = I3637 * I - 0 = I3638 * I - N = N3639 * I - I = N3640 *3641 * Return a new BigNumber whose value is the value of this BigNumber minus the value of3642 * BigNumber(y, b).3643 */3644 P.minus = function (y, b) {3645 var i, j, t, xLTy,3646 x = this,3647 a = x.s;3648 y = new BigNumber(y, b);3649 b = y.s;3650 // Either NaN?3651 if (!a || !b) return new BigNumber(NaN);3652 // Signs differ?3653 if (a != b) {3654 y.s = -b;3655 return x.plus(y);3656 }3657 var xe = x.e / LOG_BASE,3658 ye = y.e / LOG_BASE,3659 xc = x.c,3660 yc = y.c;3661 if (!xe || !ye) {3662 // Either Infinity?3663 if (!xc || !yc) return xc ? (y.s = -b, y) : new BigNumber(yc ? x : NaN);3664 // Either zero?3665 if (!xc[0] || !yc[0]) {3666 // Return y if y is non-zero, x if x is non-zero, or zero if both are zero.3667 return yc[0] ? (y.s = -b, y) : new BigNumber(xc[0] ? x :3668 // IEEE 754 (2008) 6.3: n - n = -0 when rounding to -Infinity3669 ROUNDING_MODE == 3 ? -0 : 0);3670 }3671 }3672 xe = bitFloor(xe);3673 ye = bitFloor(ye);3674 xc = xc.slice();3675 // Determine which is the bigger number.3676 if (a = xe - ye) {3677 if (xLTy = a < 0) {3678 a = -a;3679 t = xc;3680 } else {3681 ye = xe;3682 t = yc;3683 }3684 t.reverse();3685 // Prepend zeros to equalise exponents.3686 for (b = a; b--; t.push(0));3687 t.reverse();3688 } else {3689 // Exponents equal. Check digit by digit.3690 j = (xLTy = (a = xc.length) < (b = yc.length)) ? a : b;3691 for (a = b = 0; b < j; b++) {3692 if (xc[b] != yc[b]) {3693 xLTy = xc[b] < yc[b];3694 break;3695 }3696 }3697 }3698 // x < y? Point xc to the array of the bigger number.3699 if (xLTy) {3700 t = xc;3701 xc = yc;3702 yc = t;3703 y.s = -y.s;3704 } 3705 b = (j = yc.length) - (i = xc.length);3706 // Append zeros to xc if shorter.3707 // No need to add zeros to yc if shorter as subtract only needs to start at yc.length.3708 if (b > 0) for (; b--; xc[i++] = 0);3709 b = BASE - 1;3710 // Subtract yc from xc.3711 for (; j > a;) {3712 if (xc[--j] < yc[j]) {3713 for (i = j; i && !xc[--i]; xc[i] = b);3714 --xc[i];3715 xc[j] += BASE;3716 }3717 xc[j] -= yc[j];3718 }3719 // Remove leading zeros and adjust exponent accordingly.3720 for (; xc[0] == 0; xc.splice(0, 1), --ye);3721 // Zero?3722 if (!xc[0]) {3723 // Following IEEE 754 (2008) 6.3,3724 // n - n = +0 but n - n = -0 when rounding towards -Infinity.3725 y.s = ROUNDING_MODE == 3 ? -1 : 1;3726 y.c = [y.e = 0];3727 return y;3728 }3729 // No need to check for Infinity as +x - +y != Infinity && -x - -y != Infinity3730 // for finite x and y.3731 return normalise(y, xc, ye);3732 };3733 /*3734 * n % 0 = N3735 * n % N = N3736 * n % I = n3737 * 0 % n = 03738 * -0 % n = -03739 * 0 % 0 = N3740 * 0 % N = N3741 * 0 % I = 03742 * N % n = N3743 * N % 0 = N3744 * N % N = N3745 * N % I = N3746 * I % n = N3747 * I % 0 = N3748 * I % N = N3749 * I % I = N3750 *3751 * Return a new BigNumber whose value is the value of this BigNumber modulo the value of3752 * BigNumber(y, b). The result depends on the value of MODULO_MODE.3753 */3754 P.modulo = P.mod = function (y, b) {3755 var q, s,3756 x = this;3757 y = new BigNumber(y, b);3758 // Return NaN if x is Infinity or NaN, or y is NaN or zero.3759 if (!x.c || !y.s || y.c && !y.c[0]) {3760 return new BigNumber(NaN);3761 // Return x if y is Infinity or x is zero.3762 } else if (!y.c || x.c && !x.c[0]) {3763 return new BigNumber(x);3764 }3765 if (MODULO_MODE == 9) {3766 // Euclidian division: q = sign(y) * floor(x / abs(y))3767 // r = x - qy where 0 <= r < abs(y)3768 s = y.s;3769 y.s = 1;3770 q = div(x, y, 0, 3);3771 y.s = s;3772 q.s *= s;3773 } else {3774 q = div(x, y, 0, MODULO_MODE);3775 }3776 y = x.minus(q.times(y));3777 // To match JavaScript %, ensure sign of zero is sign of dividend.3778 if (!y.c[0] && MODULO_MODE == 1) y.s = x.s;3779 return y;3780 };3781 /*3782 * n * 0 = 03783 * n * N = N3784 * n * I = I3785 * 0 * n = 03786 * 0 * 0 = 03787 * 0 * N = N3788 * 0 * I = N3789 * N * n = N3790 * N * 0 = N3791 * N * N = N3792 * N * I = N3793 * I * n = I3794 * I * 0 = N3795 * I * N = N3796 * I * I = I3797 *3798 * Return a new BigNumber whose value is the value of this BigNumber multiplied by the value3799 * of BigNumber(y, b).3800 */3801 P.multipliedBy = P.times = function (y, b) {3802 var c, e, i, j, k, m, xcL, xlo, xhi, ycL, ylo, yhi, zc,3803 base, sqrtBase,3804 x = this,3805 xc = x.c,3806 yc = (y = new BigNumber(y, b)).c;3807 // Either NaN, ±Infinity or ±0?3808 if (!xc || !yc || !xc[0] || !yc[0]) {3809 // Return NaN if either is NaN, or one is 0 and the other is Infinity.3810 if (!x.s || !y.s || xc && !xc[0] && !yc || yc && !yc[0] && !xc) {3811 y.c = y.e = y.s = null;3812 } else {3813 y.s *= x.s;3814 // Return ±Infinity if either is ±Infinity.3815 if (!xc || !yc) {3816 y.c = y.e = null;3817 // Return ±0 if either is ±0.3818 } else {3819 y.c = [0];3820 y.e = 0;3821 }3822 }3823 return y;3824 }3825 e = bitFloor(x.e / LOG_BASE) + bitFloor(y.e / LOG_BASE);3826 y.s *= x.s;3827 xcL = xc.length;3828 ycL = yc.length;3829 // Ensure xc points to longer array and xcL to its length.3830 if (xcL < ycL) {3831 zc = xc;3832 xc = yc;3833 yc = zc;3834 i = xcL;3835 xcL = ycL;3836 ycL = i;3837 } 3838 // Initialise the result array with zeros.3839 for (i = xcL + ycL, zc = []; i--; zc.push(0));3840 base = BASE;3841 sqrtBase = SQRT_BASE;3842 for (i = ycL; --i >= 0;) {3843 c = 0;3844 ylo = yc[i] % sqrtBase;3845 yhi = yc[i] / sqrtBase | 0;3846 for (k = xcL, j = i + k; j > i;) {3847 xlo = xc[--k] % sqrtBase;3848 xhi = xc[k] / sqrtBase | 0;3849 m = yhi * xlo + xhi * ylo;3850 xlo = ylo * xlo + ((m % sqrtBase) * sqrtBase) + zc[j] + c;3851 c = (xlo / base | 0) + (m / sqrtBase | 0) + yhi * xhi;3852 zc[j--] = xlo % base;3853 }3854 zc[j] = c;3855 }3856 if (c) {3857 ++e;3858 } else {3859 zc.splice(0, 1);3860 }3861 return normalise(y, zc, e);3862 };3863 /*3864 * Return a new BigNumber whose value is the value of this BigNumber negated,3865 * i.e. multiplied by -1.3866 */3867 P.negated = function () {3868 var x = new BigNumber(this);3869 x.s = -x.s || null;3870 return x;3871 };3872 /*3873 * n + 0 = n3874 * n + N = N3875 * n + I = I3876 * 0 + n = n3877 * 0 + 0 = 03878 * 0 + N = N3879 * 0 + I = I3880 * N + n = N3881 * N + 0 = N3882 * N + N = N3883 * N + I = N3884 * I + n = I3885 * I + 0 = I3886 * I + N = N3887 * I + I = I3888 *3889 * Return a new BigNumber whose value is the value of this BigNumber plus the value of3890 * BigNumber(y, b).3891 */3892 P.plus = function (y, b) {3893 var t,3894 x = this,3895 a = x.s;3896 y = new BigNumber(y, b);3897 b = y.s;3898 // Either NaN?3899 if (!a || !b) return new BigNumber(NaN);3900 // Signs differ?3901 if (a != b) {3902 y.s = -b;3903 return x.minus(y);3904 }3905 var xe = x.e / LOG_BASE,3906 ye = y.e / LOG_BASE,3907 xc = x.c,3908 yc = y.c;3909 if (!xe || !ye) {3910 // Return ±Infinity if either ±Infinity.3911 if (!xc || !yc) return new BigNumber(a / 0);3912 // Either zero?3913 // Return y if y is non-zero, x if x is non-zero, or zero if both are zero.3914 if (!xc[0] || !yc[0]) return yc[0] ? y : new BigNumber(xc[0] ? x : a * 0);3915 }3916 xe = bitFloor(xe);3917 ye = bitFloor(ye);3918 xc = xc.slice();3919 // Prepend zeros to equalise exponents. Faster to use reverse then do unshifts.3920 if (a = xe - ye) {3921 if (a > 0) {3922 ye = xe;3923 t = yc;3924 } else {3925 a = -a;3926 t = xc;3927 }3928 t.reverse();3929 for (; a--; t.push(0));3930 t.reverse();3931 }3932 a = xc.length;3933 b = yc.length;3934 // Point xc to the longer array, and b to the shorter length.3935 if (a - b < 0) {3936 t = yc;3937 yc = xc;3938 xc = t;3939 b = a;3940 } 3941 // Only start adding at yc.length - 1 as the further digits of xc can be ignored.3942 for (a = 0; b;) {3943 a = (xc[--b] = xc[b] + yc[b] + a) / BASE | 0;3944 xc[b] = BASE === xc[b] ? 0 : xc[b] % BASE;3945 }3946 if (a) {3947 xc = [a].concat(xc);3948 ++ye;3949 }3950 // No need to check for zero, as +x + +y != 0 && -x + -y != 03951 // ye = MAX_EXP + 1 possible3952 return normalise(y, xc, ye);3953 };3954 /*3955 * If sd is undefined or null or true or false, return the number of significant digits of3956 * the value of this BigNumber, or null if the value of this BigNumber is ±Infinity or NaN.3957 * If sd is true include integer-part trailing zeros in the count.3958 *3959 * Otherwise, if sd is a number, return a new BigNumber whose value is the value of this3960 * BigNumber rounded to a maximum of sd significant digits using rounding mode rm, or3961 * ROUNDING_MODE if rm is omitted.3962 *3963 * sd {number|boolean} number: significant digits: integer, 1 to MAX inclusive.3964 * boolean: whether to count integer-part trailing zeros: true or false.3965 * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.3966 *3967 * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {sd|rm}'3968 */3969 P.precision = P.sd = function (sd, rm) {3970 var c, n, v,3971 x = this;3972 if (sd != null && sd !== !!sd) {3973 intCheck(sd, 1, MAX);3974 if (rm == null) rm = ROUNDING_MODE;3975 else intCheck(rm, 0, 8);3976 return round(new BigNumber(x), sd, rm);3977 }3978 if (!(c = x.c)) return null;3979 v = c.length - 1;3980 n = v * LOG_BASE + 1;3981 if (v = c[v]) {3982 // Subtract the number of trailing zeros of the last element.3983 for (; v % 10 == 0; v /= 10, n--);3984 // Add the number of digits of the first element.3985 for (v = c[0]; v >= 10; v /= 10, n++);3986 }3987 if (sd && x.e + 1 > n) n = x.e + 1;3988 return n;3989 };3990 /*3991 * Return a new BigNumber whose value is the value of this BigNumber shifted by k places3992 * (powers of 10). Shift to the right if n > 0, and to the left if n < 0.3993 *3994 * k {number} Integer, -MAX_SAFE_INTEGER to MAX_SAFE_INTEGER inclusive.3995 *3996 * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {k}'3997 */3998 P.shiftedBy = function (k) {3999 intCheck(k, -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER);4000 return this.times('1e' + k);4001 };4002 /*4003 * sqrt(-n) = N4004 * sqrt(N) = N4005 * sqrt(-I) = N4006 * sqrt(I) = I4007 * sqrt(0) = 04008 * sqrt(-0) = -04009 *4010 * Return a new BigNumber whose value is the square root of the value of this BigNumber,4011 * rounded according to DECIMAL_PLACES and ROUNDING_MODE.4012 */4013 P.squareRoot = P.sqrt = function () {4014 var m, n, r, rep, t,4015 x = this,4016 c = x.c,4017 s = x.s,4018 e = x.e,4019 dp = DECIMAL_PLACES + 4,4020 half = new BigNumber('0.5');4021 // Negative/NaN/Infinity/zero?4022 if (s !== 1 || !c || !c[0]) {4023 return new BigNumber(!s || s < 0 && (!c || c[0]) ? NaN : c ? x : 1 / 0);4024 }4025 // Initial estimate.4026 s = Math.sqrt(+valueOf(x));4027 // Math.sqrt underflow/overflow?4028 // Pass x to Math.sqrt as integer, then adjust the exponent of the result.4029 if (s == 0 || s == 1 / 0) {4030 n = coeffToString(c);4031 if ((n.length + e) % 2 == 0) n += '0';4032 s = Math.sqrt(+n);4033 e = bitFloor((e + 1) / 2) - (e < 0 || e % 2);4034 if (s == 1 / 0) {4035 n = '5e' + e;4036 } else {4037 n = s.toExponential();4038 n = n.slice(0, n.indexOf('e') + 1) + e;4039 }4040 r = new BigNumber(n);4041 } else {4042 r = new BigNumber(s + '');4043 }4044 // Check for zero.4045 // r could be zero if MIN_EXP is changed after the this value was created.4046 // This would cause a division by zero (x/t) and hence Infinity below, which would cause4047 // coeffToString to throw.4048 if (r.c[0]) {4049 e = r.e;4050 s = e + dp;4051 if (s < 3) s = 0;4052 // Newton-Raphson iteration.4053 for (; ;) {4054 t = r;4055 r = half.times(t.plus(div(x, t, dp, 1)));4056 if (coeffToString(t.c).slice(0, s) === (n = coeffToString(r.c)).slice(0, s)) {4057 // The exponent of r may here be one less than the final result exponent,4058 // e.g 0.0009999 (e-4) --> 0.001 (e-3), so adjust s so the rounding digits4059 // are indexed correctly.4060 if (r.e < e) --s;4061 n = n.slice(s - 3, s + 1);4062 // The 4th rounding digit may be in error by -1 so if the 4 rounding digits4063 // are 9999 or 4999 (i.e. approaching a rounding boundary) continue the4064 // iteration.4065 if (n == '9999' || !rep && n == '4999') {4066 // On the first iteration only, check to see if rounding up gives the4067 // exact result as the nines may infinitely repeat.4068 if (!rep) {4069 round(t, t.e + DECIMAL_PLACES + 2, 0);4070 if (t.times(t).eq(x)) {4071 r = t;4072 break;4073 }4074 }4075 dp += 4;4076 s += 4;4077 rep = 1;4078 } else {4079 // If rounding digits are null, 0{0,4} or 50{0,3}, check for exact4080 // result. If not, then there are further digits and m will be truthy.4081 if (!+n || !+n.slice(1) && n.charAt(0) == '5') {4082 // Truncate to the first rounding digit.4083 round(r, r.e + DECIMAL_PLACES + 2, 1);4084 m = !r.times(r).eq(x);4085 }4086 break;4087 }4088 }4089 }4090 }4091 return round(r, r.e + DECIMAL_PLACES + 1, ROUNDING_MODE, m);4092 };4093 /*4094 * Return a string representing the value of this BigNumber in exponential notation and4095 * rounded using ROUNDING_MODE to dp fixed decimal places.4096 *4097 * [dp] {number} Decimal places. Integer, 0 to MAX inclusive.4098 * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.4099 *4100 * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}'4101 */4102 P.toExponential = function (dp, rm) {4103 if (dp != null) {4104 intCheck(dp, 0, MAX);4105 dp++;4106 }4107 return format(this, dp, rm, 1);4108 };4109 /*4110 * Return a string representing the value of this BigNumber in fixed-point notation rounding4111 * to dp fixed decimal places using rounding mode rm, or ROUNDING_MODE if rm is omitted.4112 *4113 * Note: as with JavaScript's number type, (-0).toFixed(0) is '0',4114 * but e.g. (-0.00001).toFixed(0) is '-0'.4115 *4116 * [dp] {number} Decimal places. Integer, 0 to MAX inclusive.4117 * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.4118 *4119 * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}'4120 */4121 P.toFixed = function (dp, rm) {4122 if (dp != null) {4123 intCheck(dp, 0, MAX);4124 dp = dp + this.e + 1;4125 }4126 return format(this, dp, rm);4127 };4128 /*4129 * Return a string representing the value of this BigNumber in fixed-point notation rounded4130 * using rm or ROUNDING_MODE to dp decimal places, and formatted according to the properties4131 * of the format or FORMAT object (see BigNumber.set).4132 *4133 * The formatting object may contain some or all of the properties shown below.4134 *4135 * FORMAT = {4136 * prefix: '',4137 * groupSize: 3,4138 * secondaryGroupSize: 0,4139 * groupSeparator: ',',4140 * decimalSeparator: '.',4141 * fractionGroupSize: 0,4142 * fractionGroupSeparator: '\xA0', // non-breaking space4143 * suffix: ''4144 * };4145 *4146 * [dp] {number} Decimal places. Integer, 0 to MAX inclusive.4147 * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.4148 * [format] {object} Formatting options. See FORMAT pbject above.4149 *4150 * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}'4151 * '[BigNumber Error] Argument not an object: {format}'4152 */4153 P.toFormat = function (dp, rm, format) {4154 var str,4155 x = this;4156 if (format == null) {4157 if (dp != null && rm && typeof rm == 'object') {4158 format = rm;4159 rm = null;4160 } else if (dp && typeof dp == 'object') {4161 format = dp;4162 dp = rm = null;4163 } else {4164 format = FORMAT;4165 }4166 } else if (typeof format != 'object') {4167 throw Error4168 (bignumberError + 'Argument not an object: ' + format);4169 }4170 str = x.toFixed(dp, rm);4171 if (x.c) {4172 var i,4173 arr = str.split('.'),4174 g1 = +format.groupSize,4175 g2 = +format.secondaryGroupSize,4176 groupSeparator = format.groupSeparator || '',4177 intPart = arr[0],4178 fractionPart = arr[1],4179 isNeg = x.s < 0,4180 intDigits = isNeg ? intPart.slice(1) : intPart,4181 len = intDigits.length;4182 if (g2) {4183 i = g1;4184 g1 = g2;4185 g2 = i;4186 len -= i;4187 } 4188 if (g1 > 0 && len > 0) {4189 i = len % g1 || g1;4190 intPart = intDigits.substr(0, i);4191 for (; i < len; i += g1) intPart += groupSeparator + intDigits.substr(i, g1);4192 if (g2 > 0) intPart += groupSeparator + intDigits.slice(i);4193 if (isNeg) intPart = '-' + intPart;4194 }4195 str = fractionPart4196 ? intPart + (format.decimalSeparator || '') + ((g2 = +format.fractionGroupSize)4197 ? fractionPart.replace(new RegExp('\\d{' + g2 + '}\\B', 'g'),4198 '$&' + (format.fractionGroupSeparator || ''))4199 : fractionPart)4200 : intPart;4201 }4202 return (format.prefix || '') + str + (format.suffix || '');4203 };4204 /*4205 * Return an array of two BigNumbers representing the value of this BigNumber as a simple4206 * fraction with an integer numerator and an integer denominator.4207 * The denominator will be a positive non-zero value less than or equal to the specified4208 * maximum denominator. If a maximum denominator is not specified, the denominator will be4209 * the lowest value necessary to represent the number exactly.4210 *4211 * [md] {number|string|BigNumber} Integer >= 1, or Infinity. The maximum denominator.4212 *4213 * '[BigNumber Error] Argument {not an integer|out of range} : {md}'4214 */4215 P.toFraction = function (md) {4216 var d, d0, d1, d2, e, exp, n, n0, n1, q, r, s,4217 x = this,4218 xc = x.c;4219 if (md != null) {4220 n = new BigNumber(md);4221 // Throw if md is less than one or is not an integer, unless it is Infinity.4222 if (!n.isInteger() && (n.c || n.s !== 1) || n.lt(ONE)) {4223 throw Error4224 (bignumberError + 'Argument ' +4225 (n.isInteger() ? 'out of range: ' : 'not an integer: ') + valueOf(n));4226 }4227 }4228 if (!xc) return new BigNumber(x);4229 d = new BigNumber(ONE);4230 n1 = d0 = new BigNumber(ONE);4231 d1 = n0 = new BigNumber(ONE);4232 s = coeffToString(xc);4233 // Determine initial denominator.4234 // d is a power of 10 and the minimum max denominator that specifies the value exactly.4235 e = d.e = s.length - x.e - 1;4236 d.c[0] = POWS_TEN[(exp = e % LOG_BASE) < 0 ? LOG_BASE + exp : exp];4237 md = !md || n.comparedTo(d) > 0 ? (e > 0 ? d : n1) : n;4238 exp = MAX_EXP;4239 MAX_EXP = 1 / 0;4240 n = new BigNumber(s);4241 // n0 = d1 = 04242 n0.c[0] = 0;4243 for (; ;) {4244 q = div(n, d, 0, 1);4245 d2 = d0.plus(q.times(d1));4246 if (d2.comparedTo(md) == 1) break;4247 d0 = d1;4248 d1 = d2;4249 n1 = n0.plus(q.times(d2 = n1));4250 n0 = d2;4251 d = n.minus(q.times(d2 = d));4252 n = d2;4253 }4254 d2 = div(md.minus(d0), d1, 0, 1);4255 n0 = n0.plus(d2.times(n1));4256 d0 = d0.plus(d2.times(d1));4257 n0.s = n1.s = x.s;4258 e = e * 2;4259 // Determine which fraction is closer to x, n0/d0 or n1/d14260 r = div(n1, d1, e, ROUNDING_MODE).minus(x).abs().comparedTo(4261 div(n0, d0, e, ROUNDING_MODE).minus(x).abs()) < 1 ? [n1, d1] : [n0, d0];4262 MAX_EXP = exp;4263 return r;4264 };4265 /*4266 * Return the value of this BigNumber converted to a number primitive.4267 */4268 P.toNumber = function () {4269 return +valueOf(this);4270 };4271 /*4272 * Return a string representing the value of this BigNumber rounded to sd significant digits4273 * using rounding mode rm or ROUNDING_MODE. If sd is less than the number of digits4274 * necessary to represent the integer part of the value in fixed-point notation, then use4275 * exponential notation.4276 *4277 * [sd] {number} Significant digits. Integer, 1 to MAX inclusive.4278 * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.4279 *4280 * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {sd|rm}'4281 */4282 P.toPrecision = function (sd, rm) {4283 if (sd != null) intCheck(sd, 1, MAX);4284 return format(this, sd, rm, 2);4285 };4286 /*4287 * Return a string representing the value of this BigNumber in base b, or base 10 if b is4288 * omitted. If a base is specified, including base 10, round according to DECIMAL_PLACES and4289 * ROUNDING_MODE. If a base is not specified, and this BigNumber has a positive exponent4290 * that is equal to or greater than TO_EXP_POS, or a negative exponent equal to or less than4291 * TO_EXP_NEG, return exponential notation.4292 *4293 * [b] {number} Integer, 2 to ALPHABET.length inclusive.4294 *4295 * '[BigNumber Error] Base {not a primitive number|not an integer|out of range}: {b}'4296 */4297 P.toString = function (b) {4298 var str,4299 n = this,4300 s = n.s,4301 e = n.e;4302 // Infinity or NaN?4303 if (e === null) {4304 if (s) {4305 str = 'Infinity';4306 if (s < 0) str = '-' + str;4307 } else {4308 str = 'NaN';4309 }4310 } else {4311 if (b == null) {4312 str = e <= TO_EXP_NEG || e >= TO_EXP_POS4313 ? toExponential(coeffToString(n.c), e)4314 : toFixedPoint(coeffToString(n.c), e, '0');4315 } else if (b === 10 && alphabetHasNormalDecimalDigits) {4316 n = round(new BigNumber(n), DECIMAL_PLACES + e + 1, ROUNDING_MODE);4317 str = toFixedPoint(coeffToString(n.c), n.e, '0');4318 } else {4319 intCheck(b, 2, ALPHABET.length, 'Base');4320 str = convertBase(toFixedPoint(coeffToString(n.c), e, '0'), 10, b, s, true);4321 }4322 if (s < 0 && n.c[0]) str = '-' + str;4323 }4324 return str;4325 };4326 /*4327 * Return as toString, but do not accept a base argument, and include the minus sign for4328 * negative zero.4329 */4330 P.valueOf = P.toJSON = function () {4331 return valueOf(this);4332 };4333 P._isBigNumber = true;4334 if (configObject != null) BigNumber.set(configObject);4335 return BigNumber;4336 }4337 // PRIVATE HELPER FUNCTIONS4338 // These functions don't need access to variables,4339 // e.g. DECIMAL_PLACES, in the scope of the `clone` function above.4340 function bitFloor(n) {4341 var i = n | 0;4342 return n > 0 || n === i ? i : i - 1;4343 }4344 // Return a coefficient array as a string of base 10 digits.4345 function coeffToString(a) {4346 var s, z,4347 i = 1,4348 j = a.length,4349 r = a[0] + '';4350 for (; i < j;) {4351 s = a[i++] + '';4352 z = LOG_BASE - s.length;4353 for (; z--; s = '0' + s);4354 r += s;4355 }4356 // Determine trailing zeros.4357 for (j = r.length; r.charCodeAt(--j) === 48;);4358 return r.slice(0, j + 1 || 1);4359 }4360 // Compare the value of BigNumbers x and y.4361 function compare(x, y) {4362 var a, b,4363 xc = x.c,4364 yc = y.c,4365 i = x.s,4366 j = y.s,4367 k = x.e,4368 l = y.e;4369 // Either NaN?4370 if (!i || !j) return null;4371 a = xc && !xc[0];4372 b = yc && !yc[0];4373 // Either zero?4374 if (a || b) return a ? b ? 0 : -j : i;4375 // Signs differ?4376 if (i != j) return i;4377 a = i < 0;4378 b = k == l;4379 // Either Infinity?4380 if (!xc || !yc) return b ? 0 : !xc ^ a ? 1 : -1;4381 // Compare exponents.4382 if (!b) return k > l ^ a ? 1 : -1;4383 j = (k = xc.length) < (l = yc.length) ? k : l;4384 // Compare digit by digit.4385 for (i = 0; i < j; i++) if (xc[i] != yc[i]) return xc[i] > yc[i] ^ a ? 1 : -1;4386 // Compare lengths.4387 return k == l ? 0 : k > l ^ a ? 1 : -1;4388 }4389 /*4390 * Check that n is a primitive number, an integer, and in range, otherwise throw.4391 */4392 function intCheck(n, min, max, name) {4393 if (n < min || n > max || n !== mathfloor(n)) {4394 throw Error4395 (bignumberError + (name || 'Argument') + (typeof n == 'number'4396 ? n < min || n > max ? ' out of range: ' : ' not an integer: '4397 : ' not a primitive number: ') + String(n));4398 }4399 }4400 // Assumes finite n.4401 function isOdd(n) {4402 var k = n.c.length - 1;4403 return bitFloor(n.e / LOG_BASE) == k && n.c[k] % 2 != 0;4404 }4405 function toExponential(str, e) {4406 return (str.length > 1 ? str.charAt(0) + '.' + str.slice(1) : str) +4407 (e < 0 ? 'e' : 'e+') + e;4408 }4409 function toFixedPoint(str, e, z) {4410 var len, zs;4411 // Negative exponent?4412 if (e < 0) {4413 // Prepend zeros.4414 for (zs = z + '.'; ++e; zs += z);4415 str = zs + str;4416 // Positive exponent4417 } else {4418 len = str.length;4419 // Append zeros.4420 if (++e > len) {4421 for (zs = z, e -= len; --e; zs += z);4422 str += zs;4423 } else if (e < len) {4424 str = str.slice(0, e) + '.' + str.slice(e);4425 }4426 }4427 return str;4428 }4429 // EXPORT4430 BigNumber = clone();4431 BigNumber['default'] = BigNumber.BigNumber = BigNumber;4432 // AMD.4433 if (typeof define == 'function' && define.amd) {4434 define(function () { return BigNumber; });4435 // Node.js and other environments that support module.exports.4436 } else if ( true && module.exports) {4437 module.exports = BigNumber;4438 // Browser.4439 } else {4440 if (!globalObject) {4441 globalObject = typeof self != 'undefined' && self ? self : window;4442 }4443 globalObject.BigNumber = BigNumber;4444 }4445})(this);4446/***/ }),4447/***/ 9239:4448/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {4449"use strict";4450/*jshint node:true */4451var Buffer = (__nccwpck_require__(4300).Buffer); // browserify4452var SlowBuffer = (__nccwpck_require__(4300).SlowBuffer);4453module.exports = bufferEq;4454function bufferEq(a, b) {4455 // shortcutting on type is necessary for correctness4456 if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {4457 return false;4458 }4459 // buffer sizes should be well-known information, so despite this4460 // shortcutting, it doesn't leak any information about the *contents* of the4461 // buffers.4462 if (a.length !== b.length) {4463 return false;4464 }4465 var c = 0;4466 for (var i = 0; i < a.length; i++) {4467 /*jshint bitwise:false */4468 c |= a[i] ^ b[i]; // XOR4469 }4470 return c === 0;4471}4472bufferEq.install = function() {4473 Buffer.prototype.equal = SlowBuffer.prototype.equal = function equal(that) {4474 return bufferEq(this, that);4475 };4476};4477var origBufEqual = Buffer.prototype.equal;4478var origSlowBufEqual = SlowBuffer.prototype.equal;4479bufferEq.restore = function() {4480 Buffer.prototype.equal = origBufEqual;4481 SlowBuffer.prototype.equal = origSlowBufEqual;4482};4483/***/ }),4484/***/ 8222:4485/***/ ((module, exports, __nccwpck_require__) => {4486/* eslint-env browser */4487/**4488 * This is the web browser implementation of `debug()`.4489 */4490exports.formatArgs = formatArgs;4491exports.save = save;4492exports.load = load;4493exports.useColors = useColors;4494exports.storage = localstorage();4495exports.destroy = (() => {4496 let warned = false;4497 return () => {4498 if (!warned) {4499 warned = true;4500 console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');4501 }4502 };4503})();4504/**4505 * Colors.4506 */4507exports.colors = [4508 '#0000CC',4509 '#0000FF',4510 '#0033CC',4511 '#0033FF',4512 '#0066CC',4513 '#0066FF',4514 '#0099CC',4515 '#0099FF',4516 '#00CC00',4517 '#00CC33',4518 '#00CC66',4519 '#00CC99',4520 '#00CCCC',4521 '#00CCFF',4522 '#3300CC',4523 '#3300FF',4524 '#3333CC',4525 '#3333FF',4526 '#3366CC',4527 '#3366FF',4528 '#3399CC',4529 '#3399FF',4530 '#33CC00',4531 '#33CC33',4532 '#33CC66',4533 '#33CC99',4534 '#33CCCC',4535 '#33CCFF',4536 '#6600CC',4537 '#6600FF',4538 '#6633CC',4539 '#6633FF',4540 '#66CC00',4541 '#66CC33',4542 '#9900CC',4543 '#9900FF',4544 '#9933CC',4545 '#9933FF',4546 '#99CC00',4547 '#99CC33',4548 '#CC0000',4549 '#CC0033',4550 '#CC0066',4551 '#CC0099',4552 '#CC00CC',4553 '#CC00FF',4554 '#CC3300',4555 '#CC3333',4556 '#CC3366',4557 '#CC3399',4558 '#CC33CC',4559 '#CC33FF',4560 '#CC6600',4561 '#CC6633',4562 '#CC9900',4563 '#CC9933',4564 '#CCCC00',4565 '#CCCC33',4566 '#FF0000',4567 '#FF0033',4568 '#FF0066',4569 '#FF0099',4570 '#FF00CC',4571 '#FF00FF',4572 '#FF3300',4573 '#FF3333',4574 '#FF3366',4575 '#FF3399',4576 '#FF33CC',4577 '#FF33FF',4578 '#FF6600',4579 '#FF6633',4580 '#FF9900',4581 '#FF9933',4582 '#FFCC00',4583 '#FFCC33'4584];4585/**4586 * Currently only WebKit-based Web Inspectors, Firefox >= v31,4587 * and the Firebug extension (any Firefox version) are known4588 * to support "%c" CSS customizations.4589 *4590 * TODO: add a `localStorage` variable to explicitly enable/disable colors4591 */4592// eslint-disable-next-line complexity4593function useColors() {4594 // NB: In an Electron preload script, document will be defined but not fully4595 // initialized. Since we know we're in Chrome, we'll just detect this case4596 // explicitly4597 if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {4598 return true;4599 }4600 // Internet Explorer and Edge do not support colors.4601 if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {4602 return false;4603 }4604 // Is webkit? http://stackoverflow.com/a/16459606/3767734605 // document is undefined in react-native: https://github.com/facebook/react-native/pull/16324606 return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||4607 // Is firebug? http://stackoverflow.com/a/398120/3767734608 (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||4609 // Is firefox >= v31?4610 // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages4611 (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) ||4612 // Double check webkit in userAgent just in case we are in a worker4613 (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/));4614}4615/**4616 * Colorize log arguments if enabled.4617 *4618 * @api public4619 */4620function formatArgs(args) {4621 args[0] = (this.useColors ? '%c' : '') +4622 this.namespace +4623 (this.useColors ? ' %c' : ' ') +4624 args[0] +4625 (this.useColors ? '%c ' : ' ') +4626 '+' + module.exports.humanize(this.diff);4627 if (!this.useColors) {4628 return;4629 }4630 const c = 'color: ' + this.color;4631 args.splice(1, 0, c, 'color: inherit');4632 // The final "%c" is somewhat tricky, because there could be other4633 // arguments passed either before or after the %c, so we need to4634 // figure out the correct index to insert the CSS into4635 let index = 0;4636 let lastC = 0;4637 args[0].replace(/%[a-zA-Z%]/g, match => {4638 if (match === '%%') {4639 return;4640 }4641 index++;4642 if (match === '%c') {4643 // We only are interested in the *last* %c4644 // (the user may have provided their own)4645 lastC = index;4646 }4647 });4648 args.splice(lastC, 0, c);4649}4650/**4651 * Invokes `console.debug()` when available.4652 * No-op when `console.debug` is not a "function".4653 * If `console.debug` is not available, falls back4654 * to `console.log`.4655 *4656 * @api public4657 */4658exports.log = console.debug || console.log || (() => {});4659/**4660 * Save `namespaces`.4661 *4662 * @param {String} namespaces4663 * @api private4664 */4665function save(namespaces) {4666 try {4667 if (namespaces) {4668 exports.storage.setItem('debug', namespaces);4669 } else {4670 exports.storage.removeItem('debug');4671 }4672 } catch (error) {4673 // Swallow4674 // XXX (@Qix-) should we be logging these?4675 }4676}4677/**4678 * Load `namespaces`.4679 *4680 * @return {String} returns the previously persisted debug modes4681 * @api private4682 */4683function load() {4684 let r;4685 try {4686 r = exports.storage.getItem('debug');4687 } catch (error) {4688 // Swallow4689 // XXX (@Qix-) should we be logging these?4690 }4691 // If debug isn't set in LS, and we're in Electron, try to load $DEBUG4692 if (!r && typeof process !== 'undefined' && 'env' in process) {4693 r = process.env.DEBUG;4694 }4695 return r;4696}4697/**4698 * Localstorage attempts to return the localstorage.4699 *4700 * This is necessary because safari throws4701 * when a user disables cookies/localstorage4702 * and you attempt to access it.4703 *4704 * @return {LocalStorage}4705 * @api private4706 */4707function localstorage() {4708 try {4709 // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context4710 // The Browser also has localStorage in the global context.4711 return localStorage;4712 } catch (error) {4713 // Swallow4714 // XXX (@Qix-) should we be logging these?4715 }4716}4717module.exports = __nccwpck_require__(6243)(exports);4718const {formatters} = module.exports;4719/**4720 * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.4721 */4722formatters.j = function (v) {4723 try {4724 return JSON.stringify(v);4725 } catch (error) {4726 return '[UnexpectedJSONParseError]: ' + error.message;4727 }4728};4729/***/ }),4730/***/ 6243:4731/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {4732/**4733 * This is the common logic for both the Node.js and web browser4734 * implementations of `debug()`.4735 */4736function setup(env) {4737 createDebug.debug = createDebug;4738 createDebug.default = createDebug;4739 createDebug.coerce = coerce;4740 createDebug.disable = disable;4741 createDebug.enable = enable;4742 createDebug.enabled = enabled;4743 createDebug.humanize = __nccwpck_require__(900);4744 createDebug.destroy = destroy;4745 Object.keys(env).forEach(key => {4746 createDebug[key] = env[key];4747 });4748 /**4749 * The currently active debug mode names, and names to skip.4750 */4751 createDebug.names = [];4752 createDebug.skips = [];4753 /**4754 * Map of special "%n" handling functions, for the debug "format" argument.4755 *4756 * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".4757 */4758 createDebug.formatters = {};4759 /**4760 * Selects a color for a debug namespace4761 * @param {String} namespace The namespace string for the debug instance to be colored4762 * @return {Number|String} An ANSI color code for the given namespace4763 * @api private4764 */4765 function selectColor(namespace) {4766 let hash = 0;4767 for (let i = 0; i < namespace.length; i++) {4768 hash = ((hash << 5) - hash) + namespace.charCodeAt(i);4769 hash |= 0; // Convert to 32bit integer4770 }4771 return createDebug.colors[Math.abs(hash) % createDebug.colors.length];4772 }4773 createDebug.selectColor = selectColor;4774 /**4775 * Create a debugger with the given `namespace`.4776 *4777 * @param {String} namespace4778 * @return {Function}4779 * @api public4780 */4781 function createDebug(namespace) {4782 let prevTime;4783 let enableOverride = null;4784 let namespacesCache;4785 let enabledCache;4786 function debug(...args) {4787 // Disabled?4788 if (!debug.enabled) {4789 return;4790 }4791 const self = debug;4792 // Set `diff` timestamp4793 const curr = Number(new Date());4794 const ms = curr - (prevTime || curr);4795 self.diff = ms;4796 self.prev = prevTime;4797 self.curr = curr;4798 prevTime = curr;4799 args[0] = createDebug.coerce(args[0]);4800 if (typeof args[0] !== 'string') {4801 // Anything else let's inspect with %O4802 args.unshift('%O');4803 }4804 // Apply any `formatters` transformations4805 let index = 0;4806 args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {4807 // If we encounter an escaped % then don't increase the array index4808 if (match === '%%') {4809 return '%';4810 }4811 index++;4812 const formatter = createDebug.formatters[format];4813 if (typeof formatter === 'function') {4814 const val = args[index];4815 match = formatter.call(self, val);4816 // Now we need to remove `args[index]` since it's inlined in the `format`4817 args.splice(index, 1);4818 index--;4819 }4820 return match;4821 });4822 // Apply env-specific formatting (colors, etc.)4823 createDebug.formatArgs.call(self, args);4824 const logFn = self.log || createDebug.log;4825 logFn.apply(self, args);4826 }4827 debug.namespace = namespace;4828 debug.useColors = createDebug.useColors();4829 debug.color = createDebug.selectColor(namespace);4830 debug.extend = extend;4831 debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release.4832 Object.defineProperty(debug, 'enabled', {4833 enumerable: true,4834 configurable: false,4835 get: () => {4836 if (enableOverride !== null) {4837 return enableOverride;4838 }4839 if (namespacesCache !== createDebug.namespaces) {4840 namespacesCache = createDebug.namespaces;4841 enabledCache = createDebug.enabled(namespace);4842 }4843 return enabledCache;4844 },4845 set: v => {4846 enableOverride = v;4847 }4848 });4849 // Env-specific initialization logic for debug instances4850 if (typeof createDebug.init === 'function') {4851 createDebug.init(debug);4852 }4853 return debug;4854 }4855 function extend(namespace, delimiter) {4856 const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);4857 newDebug.log = this.log;4858 return newDebug;4859 }4860 /**4861 * Enables a debug mode by namespaces. This can include modes4862 * separated by a colon and wildcards.4863 *4864 * @param {String} namespaces4865 * @api public4866 */4867 function enable(namespaces) {4868 createDebug.save(namespaces);4869 createDebug.namespaces = namespaces;4870 createDebug.names = [];4871 createDebug.skips = [];4872 let i;4873 const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/);4874 const len = split.length;4875 for (i = 0; i < len; i++) {4876 if (!split[i]) {4877 // ignore empty strings4878 continue;4879 }4880 namespaces = split[i].replace(/\*/g, '.*?');4881 if (namespaces[0] === '-') {4882 createDebug.skips.push(new RegExp('^' + namespaces.slice(1) + '$'));4883 } else {4884 createDebug.names.push(new RegExp('^' + namespaces + '$'));4885 }4886 }4887 }4888 /**4889 * Disable debug output.4890 *4891 * @return {String} namespaces4892 * @api public4893 */4894 function disable() {4895 const namespaces = [4896 ...createDebug.names.map(toNamespace),4897 ...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace)4898 ].join(',');4899 createDebug.enable('');4900 return namespaces;4901 }4902 /**4903 * Returns true if the given mode name is enabled, false otherwise.4904 *4905 * @param {String} name4906 * @return {Boolean}4907 * @api public4908 */4909 function enabled(name) {4910 if (name[name.length - 1] === '*') {4911 return true;4912 }4913 let i;4914 let len;4915 for (i = 0, len = createDebug.skips.length; i < len; i++) {4916 if (createDebug.skips[i].test(name)) {4917 return false;4918 }4919 }4920 for (i = 0, len = createDebug.names.length; i < len; i++) {4921 if (createDebug.names[i].test(name)) {4922 return true;4923 }4924 }4925 return false;4926 }4927 /**4928 * Convert regexp to namespace4929 *4930 * @param {RegExp} regxep4931 * @return {String} namespace4932 * @api private4933 */4934 function toNamespace(regexp) {4935 return regexp.toString()4936 .substring(2, regexp.toString().length - 2)4937 .replace(/\.\*\?$/, '*');4938 }4939 /**4940 * Coerce `val`.4941 *4942 * @param {Mixed} val4943 * @return {Mixed}4944 * @api private4945 */4946 function coerce(val) {4947 if (val instanceof Error) {4948 return val.stack || val.message;4949 }4950 return val;4951 }4952 /**4953 * XXX DO NOT USE. This is a temporary stub function.4954 * XXX It WILL be removed in the next major release.4955 */4956 function destroy() {4957 console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');4958 }4959 createDebug.enable(createDebug.load());4960 return createDebug;4961}4962module.exports = setup;4963/***/ }),4964/***/ 8237:4965/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {4966/**4967 * Detect Electron renderer / nwjs process, which is node, but we should4968 * treat as a browser.4969 */4970if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) {4971 module.exports = __nccwpck_require__(8222);4972} else {4973 module.exports = __nccwpck_require__(4874);4974}4975/***/ }),4976/***/ 4874:4977/***/ ((module, exports, __nccwpck_require__) => {4978/**4979 * Module dependencies.4980 */4981const tty = __nccwpck_require__(6224);4982const util = __nccwpck_require__(3837);4983/**4984 * This is the Node.js implementation of `debug()`.4985 */4986exports.init = init;4987exports.log = log;4988exports.formatArgs = formatArgs;4989exports.save = save;4990exports.load = load;4991exports.useColors = useColors;4992exports.destroy = util.deprecate(4993 () => {},4994 'Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'4995);4996/**4997 * Colors.4998 */4999exports.colors = [6, 2, 3, 4, 5, 1];5000try {5001 // Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json)5002 // eslint-disable-next-line import/no-extraneous-dependencies5003 const supportsColor = __nccwpck_require__(132);5004 if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) {5005 exports.colors = [5006 20,5007 21,5008 26,5009 27,5010 32,5011 33,5012 38,5013 39,5014 40,5015 41,5016 42,5017 43,5018 44,5019 45,5020 56,5021 57,5022 62,5023 63,5024 68,5025 69,5026 74,5027 75,5028 76,5029 77,5030 78,5031 79,5032 80,5033 81,5034 92,5035 93,5036 98,5037 99,5038 112,5039 113,5040 128,5041 129,5042 134,5043 135,5044 148,5045 149,5046 160,5047 161,5048 162,5049 163,5050 164,5051 165,5052 166,5053 167,5054 168,5055 169,5056 170,5057 171,5058 172,5059 173,5060 178,5061 179,5062 184,5063 185,5064 196,5065 197,5066 198,5067 199,5068 200,5069 201,5070 202,5071 203,5072 204,5073 205,5074 206,5075 207,5076 208,5077 209,5078 214,5079 215,5080 220,5081 2215082 ];5083 }5084} catch (error) {5085 // Swallow - we only care if `supports-color` is available; it doesn't have to be.5086}5087/**5088 * Build up the default `inspectOpts` object from the environment variables.5089 *5090 * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js5091 */5092exports.inspectOpts = Object.keys(process.env).filter(key => {5093 return /^debug_/i.test(key);5094}).reduce((obj, key) => {5095 // Camel-case5096 const prop = key5097 .substring(6)5098 .toLowerCase()5099 .replace(/_([a-z])/g, (_, k) => {5100 return k.toUpperCase();5101 });5102 // Coerce string value into JS value5103 let val = process.env[key];5104 if (/^(yes|on|true|enabled)$/i.test(val)) {5105 val = true;5106 } else if (/^(no|off|false|disabled)$/i.test(val)) {5107 val = false;5108 } else if (val === 'null') {5109 val = null;5110 } else {5111 val = Number(val);5112 }5113 obj[prop] = val;5114 return obj;5115}, {});5116/**5117 * Is stdout a TTY? Colored output is enabled when `true`.5118 */5119function useColors() {5120 return 'colors' in exports.inspectOpts ?5121 Boolean(exports.inspectOpts.colors) :5122 tty.isatty(process.stderr.fd);5123}5124/**5125 * Adds ANSI color escape codes if enabled.5126 *5127 * @api public5128 */5129function formatArgs(args) {5130 const {namespace: name, useColors} = this;5131 if (useColors) {5132 const c = this.color;5133 const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c);5134 const prefix = ` ${colorCode};1m${name} \u001B[0m`;5135 args[0] = prefix + args[0].split('\n').join('\n' + prefix);5136 args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\u001B[0m');5137 } else {5138 args[0] = getDate() + name + ' ' + args[0];5139 }5140}5141function getDate() {5142 if (exports.inspectOpts.hideDate) {5143 return '';5144 }5145 return new Date().toISOString() + ' ';5146}5147/**5148 * Invokes `util.format()` with the specified arguments and writes to stderr.5149 */5150function log(...args) {5151 return process.stderr.write(util.format(...args) + '\n');5152}5153/**5154 * Save `namespaces`.5155 *5156 * @param {String} namespaces5157 * @api private5158 */5159function save(namespaces) {5160 if (namespaces) {5161 process.env.DEBUG = namespaces;5162 } else {5163 // If you set a process.env field to null or undefined, it gets cast to the5164 // string 'null' or 'undefined'. Just delete instead.5165 delete process.env.DEBUG;5166 }5167}5168/**5169 * Load `namespaces`.5170 *5171 * @return {String} returns the previously persisted debug modes5172 * @api private5173 */5174function load() {5175 return process.env.DEBUG;5176}5177/**5178 * Init logic for `debug` instances.5179 *5180 * Create a new `inspectOpts` object in case `useColors` is set5181 * differently for a particular `debug` instance.5182 */5183function init(debug) {5184 debug.inspectOpts = {};5185 const keys = Object.keys(exports.inspectOpts);5186 for (let i = 0; i < keys.length; i++) {5187 debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]];5188 }5189}5190module.exports = __nccwpck_require__(6243)(exports);5191const {formatters} = module.exports;5192/**5193 * Map %o to `util.inspect()`, all on a single line.5194 */5195formatters.o = function (v) {5196 this.inspectOpts.colors = this.useColors;5197 return util.inspect(v, this.inspectOpts)5198 .split('\n')5199 .map(str => str.trim())5200 .join(' ');5201};5202/**5203 * Map %O to `util.inspect()`, allowing multiple lines if needed.5204 */5205formatters.O = function (v) {5206 this.inspectOpts.colors = this.useColors;5207 return util.inspect(v, this.inspectOpts);5208};5209/***/ }),5210/***/ 2437:5211/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {5212const fs = __nccwpck_require__(7147)5213const path = __nccwpck_require__(1017)5214const os = __nccwpck_require__(2037)5215const packageJson = __nccwpck_require__(9968)5216const version = packageJson.version5217const LINE = /(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg5218// Parser src into an Object5219function parse (src) {5220 const obj = {}5221 // Convert buffer to string5222 let lines = src.toString()5223 // Convert line breaks to same format5224 lines = lines.replace(/\r\n?/mg, '\n')5225 let match5226 while ((match = LINE.exec(lines)) != null) {5227 const key = match[1]5228 // Default undefined or null to empty string5229 let value = (match[2] || '')5230 // Remove whitespace5231 value = value.trim()5232 // Check if double quoted5233 const maybeQuote = value[0]5234 // Remove surrounding quotes5235 value = value.replace(/^(['"`])([\s\S]*)\1$/mg, '$2')5236 // Expand newlines if double quoted5237 if (maybeQuote === '"') {5238 value = value.replace(/\\n/g, '\n')5239 value = value.replace(/\\r/g, '\r')5240 }5241 // Add to object5242 obj[key] = value5243 }5244 return obj5245}5246function _log (message) {5247 console.log(`[dotenv@${version}][DEBUG] ${message}`)5248}5249function _resolveHome (envPath) {5250 return envPath[0] === '~' ? path.join(os.homedir(), envPath.slice(1)) : envPath5251}5252// Populates process.env from .env file5253function config (options) {5254 let dotenvPath = path.resolve(process.cwd(), '.env')5255 let encoding = 'utf8'5256 const debug = Boolean(options && options.debug)5257 const override = Boolean(options && options.override)5258 if (options) {5259 if (options.path != null) {5260 dotenvPath = _resolveHome(options.path)5261 }5262 if (options.encoding != null) {5263 encoding = options.encoding5264 }5265 }5266 try {5267 // Specifying an encoding returns a string instead of a buffer5268 const parsed = DotenvModule.parse(fs.readFileSync(dotenvPath, { encoding }))5269 Object.keys(parsed).forEach(function (key) {5270 if (!Object.prototype.hasOwnProperty.call(process.env, key)) {5271 process.env[key] = parsed[key]5272 } else {5273 if (override === true) {5274 process.env[key] = parsed[key]5275 }5276 if (debug) {5277 if (override === true) {5278 _log(`"${key}" is already defined in \`process.env\` and WAS overwritten`)5279 } else {5280 _log(`"${key}" is already defined in \`process.env\` and was NOT overwritten`)5281 }5282 }5283 }5284 })5285 return { parsed }5286 } catch (e) {5287 if (debug) {5288 _log(`Failed to load ${dotenvPath} ${e.message}`)5289 }5290 return { error: e }5291 }5292}5293const DotenvModule = {5294 config,5295 parse5296}5297module.exports.config = DotenvModule.config5298module.exports.parse = DotenvModule.parse5299module.exports = DotenvModule5300/***/ }),5301/***/ 1728:5302/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {5303"use strict";5304var Buffer = (__nccwpck_require__(1867).Buffer);5305var getParamBytesForAlg = __nccwpck_require__(528);5306var MAX_OCTET = 0x80,5307 CLASS_UNIVERSAL = 0,5308 PRIMITIVE_BIT = 0x20,5309 TAG_SEQ = 0x10,5310 TAG_INT = 0x02,5311 ENCODED_TAG_SEQ = (TAG_SEQ | PRIMITIVE_BIT) | (CLASS_UNIVERSAL << 6),5312 ENCODED_TAG_INT = TAG_INT | (CLASS_UNIVERSAL << 6);5313function base64Url(base64) {5314 return base645315 .replace(/=/g, '')5316 .replace(/\+/g, '-')5317 .replace(/\//g, '_');5318}5319function signatureAsBuffer(signature) {5320 if (Buffer.isBuffer(signature)) {5321 return signature;5322 } else if ('string' === typeof signature) {5323 return Buffer.from(signature, 'base64');5324 }5325 throw new TypeError('ECDSA signature must be a Base64 string or a Buffer');5326}5327function derToJose(signature, alg) {5328 signature = signatureAsBuffer(signature);5329 var paramBytes = getParamBytesForAlg(alg);5330 // the DER encoded param should at most be the param size, plus a padding5331 // zero, since due to being a signed integer5332 var maxEncodedParamLength = paramBytes + 1;5333 var inputLength = signature.length;5334 var offset = 0;5335 if (signature[offset++] !== ENCODED_TAG_SEQ) {5336 throw new Error('Could not find expected "seq"');5337 }5338 var seqLength = signature[offset++];5339 if (seqLength === (MAX_OCTET | 1)) {5340 seqLength = signature[offset++];5341 }5342 if (inputLength - offset < seqLength) {5343 throw new Error('"seq" specified length of "' + seqLength + '", only "' + (inputLength - offset) + '" remaining');5344 }5345 if (signature[offset++] !== ENCODED_TAG_INT) {5346 throw new Error('Could not find expected "int" for "r"');5347 }5348 var rLength = signature[offset++];5349 if (inputLength - offset - 2 < rLength) {5350 throw new Error('"r" specified length of "' + rLength + '", only "' + (inputLength - offset - 2) + '" available');5351 }5352 if (maxEncodedParamLength < rLength) {5353 throw new Error('"r" specified length of "' + rLength + '", max of "' + maxEncodedParamLength + '" is acceptable');5354 }5355 var rOffset = offset;5356 offset += rLength;5357 if (signature[offset++] !== ENCODED_TAG_INT) {5358 throw new Error('Could not find expected "int" for "s"');5359 }5360 var sLength = signature[offset++];5361 if (inputLength - offset !== sLength) {5362 throw new Error('"s" specified length of "' + sLength + '", expected "' + (inputLength - offset) + '"');5363 }5364 if (maxEncodedParamLength < sLength) {5365 throw new Error('"s" specified length of "' + sLength + '", max of "' + maxEncodedParamLength + '" is acceptable');5366 }5367 var sOffset = offset;5368 offset += sLength;5369 if (offset !== inputLength) {5370 throw new Error('Expected to consume entire buffer, but "' + (inputLength - offset) + '" bytes remain');5371 }5372 var rPadding = paramBytes - rLength,5373 sPadding = paramBytes - sLength;5374 var dst = Buffer.allocUnsafe(rPadding + rLength + sPadding + sLength);5375 for (offset = 0; offset < rPadding; ++offset) {5376 dst[offset] = 0;5377 }5378 signature.copy(dst, offset, rOffset + Math.max(-rPadding, 0), rOffset + rLength);5379 offset = paramBytes;5380 for (var o = offset; offset < o + sPadding; ++offset) {5381 dst[offset] = 0;5382 }5383 signature.copy(dst, offset, sOffset + Math.max(-sPadding, 0), sOffset + sLength);5384 dst = dst.toString('base64');5385 dst = base64Url(dst);5386 return dst;5387}5388function countPadding(buf, start, stop) {5389 var padding = 0;5390 while (start + padding < stop && buf[start + padding] === 0) {5391 ++padding;5392 }5393 var needsSign = buf[start + padding] >= MAX_OCTET;5394 if (needsSign) {5395 --padding;5396 }5397 return padding;5398}5399function joseToDer(signature, alg) {5400 signature = signatureAsBuffer(signature);5401 var paramBytes = getParamBytesForAlg(alg);5402 var signatureBytes = signature.length;5403 if (signatureBytes !== paramBytes * 2) {5404 throw new TypeError('"' + alg + '" signatures must be "' + paramBytes * 2 + '" bytes, saw "' + signatureBytes + '"');5405 }5406 var rPadding = countPadding(signature, 0, paramBytes);5407 var sPadding = countPadding(signature, paramBytes, signature.length);5408 var rLength = paramBytes - rPadding;5409 var sLength = paramBytes - sPadding;5410 var rsBytes = 1 + 1 + rLength + 1 + 1 + sLength;5411 var shortLength = rsBytes < MAX_OCTET;5412 var dst = Buffer.allocUnsafe((shortLength ? 2 : 3) + rsBytes);5413 var offset = 0;5414 dst[offset++] = ENCODED_TAG_SEQ;5415 if (shortLength) {5416 // Bit 8 has value "0"5417 // bits 7-1 give the length.5418 dst[offset++] = rsBytes;5419 } else {5420 // Bit 8 of first octet has value "1"5421 // bits 7-1 give the number of additional length octets.5422 dst[offset++] = MAX_OCTET | 1;5423 // length, base 2565424 dst[offset++] = rsBytes & 0xff;5425 }5426 dst[offset++] = ENCODED_TAG_INT;5427 dst[offset++] = rLength;5428 if (rPadding < 0) {5429 dst[offset++] = 0;5430 offset += signature.copy(dst, offset, 0, paramBytes);5431 } else {5432 offset += signature.copy(dst, offset, rPadding, paramBytes);5433 }5434 dst[offset++] = ENCODED_TAG_INT;5435 dst[offset++] = sLength;5436 if (sPadding < 0) {5437 dst[offset++] = 0;5438 signature.copy(dst, offset, paramBytes);5439 } else {5440 signature.copy(dst, offset, paramBytes + sPadding);5441 }5442 return dst;5443}5444module.exports = {5445 derToJose: derToJose,5446 joseToDer: joseToDer5447};5448/***/ }),5449/***/ 528:5450/***/ ((module) => {5451"use strict";5452function getParamSize(keySize) {5453 var result = ((keySize / 8) | 0) + (keySize % 8 === 0 ? 0 : 1);5454 return result;5455}5456var paramBytesForAlg = {5457 ES256: getParamSize(256),5458 ES384: getParamSize(384),5459 ES512: getParamSize(521)5460};5461function getParamBytesForAlg(alg) {5462 var paramBytes = paramBytesForAlg[alg];5463 if (paramBytes) {5464 return paramBytes;5465 }5466 throw new Error('Unknown algorithm "' + alg + '"');5467}5468module.exports = getParamBytesForAlg;5469/***/ }),5470/***/ 8171:5471/***/ ((module) => {5472"use strict";5473var hasOwn = Object.prototype.hasOwnProperty;5474var toStr = Object.prototype.toString;5475var defineProperty = Object.defineProperty;5476var gOPD = Object.getOwnPropertyDescriptor;5477var isArray = function isArray(arr) {5478 if (typeof Array.isArray === 'function') {5479 return Array.isArray(arr);5480 }5481 return toStr.call(arr) === '[object Array]';5482};5483var isPlainObject = function isPlainObject(obj) {5484 if (!obj || toStr.call(obj) !== '[object Object]') {5485 return false;5486 }5487 var hasOwnConstructor = hasOwn.call(obj, 'constructor');5488 var hasIsPrototypeOf = obj.constructor && obj.constructor.prototype && hasOwn.call(obj.constructor.prototype, 'isPrototypeOf');5489 // Not own constructor property must be Object5490 if (obj.constructor && !hasOwnConstructor && !hasIsPrototypeOf) {5491 return false;5492 }5493 // Own properties are enumerated firstly, so to speed up,5494 // if last one is own, then all properties are own.5495 var key;5496 for (key in obj) { /**/ }5497 return typeof key === 'undefined' || hasOwn.call(obj, key);5498};5499// If name is '__proto__', and Object.defineProperty is available, define __proto__ as an own property on target5500var setProperty = function setProperty(target, options) {5501 if (defineProperty && options.name === '__proto__') {5502 defineProperty(target, options.name, {5503 enumerable: true,5504 configurable: true,5505 value: options.newValue,5506 writable: true5507 });5508 } else {5509 target[options.name] = options.newValue;5510 }5511};5512// Return undefined instead of __proto__ if '__proto__' is not an own property5513var getProperty = function getProperty(obj, name) {5514 if (name === '__proto__') {5515 if (!hasOwn.call(obj, name)) {5516 return void 0;5517 } else if (gOPD) {5518 // In early versions of node, obj['__proto__'] is buggy when obj has5519 // __proto__ as an own property. Object.getOwnPropertyDescriptor() works.5520 return gOPD(obj, name).value;5521 }5522 }5523 return obj[name];5524};5525module.exports = function extend() {5526 var options, name, src, copy, copyIsArray, clone;5527 var target = arguments[0];5528 var i = 1;5529 var length = arguments.length;5530 var deep = false;5531 // Handle a deep copy situation5532 if (typeof target === 'boolean') {5533 deep = target;5534 target = arguments[1] || {};5535 // skip the boolean and the target5536 i = 2;5537 }5538 if (target == null || (typeof target !== 'object' && typeof target !== 'function')) {5539 target = {};5540 }5541 for (; i < length; ++i) {5542 options = arguments[i];5543 // Only deal with non-null/undefined values5544 if (options != null) {5545 // Extend the base object5546 for (name in options) {5547 src = getProperty(target, name);5548 copy = getProperty(options, name);5549 // Prevent never-ending loop5550 if (target !== copy) {5551 // Recurse if we're merging plain objects or arrays5552 if (deep && copy && (isPlainObject(copy) || (copyIsArray = isArray(copy)))) {5553 if (copyIsArray) {5554 copyIsArray = false;5555 clone = src && isArray(src) ? src : [];5556 } else {5557 clone = src && isPlainObject(src) ? src : {};5558 }5559 // Never move original objects, clone them5560 setProperty(target, { name: name, newValue: extend(deep, clone, copy) });5561 // Don't bring in undefined values5562 } else if (typeof copy !== 'undefined') {5563 setProperty(target, { name: name, newValue: copy });5564 }5565 }5566 }5567 }5568 }5569 // Return the modified object5570 return target;5571};5572/***/ }),5573/***/ 1917:5574/***/ (function() {5575(function(scope) {'use strict';5576function B(r,e){var f;return r instanceof Buffer?f=r:f=Buffer.from(r.buffer,r.byteOffset,r.byteLength),f.toString(e)}var w=function(r){return Buffer.from(r)};function h(r){for(var e=0,f=Math.min(256*256,r.length+1),n=new Uint16Array(f),i=[],o=0;;){var t=e<r.length;if(!t||o>=f-1){var s=n.subarray(0,o),m=s;if(i.push(String.fromCharCode.apply(null,m)),!t)return i.join("");r=r.subarray(e),e=0,o=0}var a=r[e++];if((a&128)===0)n[o++]=a;else if((a&224)===192){var d=r[e++]&63;n[o++]=(a&31)<<6|d}else if((a&240)===224){var d=r[e++]&63,l=r[e++]&63;n[o++]=(a&31)<<12|d<<6|l}else if((a&248)===240){var d=r[e++]&63,l=r[e++]&63,R=r[e++]&63,c=(a&7)<<18|d<<12|l<<6|R;c>65535&&(c-=65536,n[o++]=c>>>10&1023|55296,c=56320|c&1023),n[o++]=c}}}function F(r){for(var e=0,f=r.length,n=0,i=Math.max(32,f+(f>>>1)+7),o=new Uint8Array(i>>>3<<3);e<f;){var t=r.charCodeAt(e++);if(t>=55296&&t<=56319){if(e<f){var s=r.charCodeAt(e);(s&64512)===56320&&(++e,t=((t&1023)<<10)+(s&1023)+65536)}if(t>=55296&&t<=56319)continue}if(n+4>o.length){i+=8,i*=1+e/r.length*2,i=i>>>3<<3;var m=new Uint8Array(i);m.set(o),o=m}if((t&4294967168)===0){o[n++]=t;continue}else if((t&4294965248)===0)o[n++]=t>>>6&31|192;else if((t&4294901760)===0)o[n++]=t>>>12&15|224,o[n++]=t>>>6&63|128;else if((t&4292870144)===0)o[n++]=t>>>18&7|240,o[n++]=t>>>12&63|128,o[n++]=t>>>6&63|128;else continue;o[n++]=t&63|128}return o.slice?o.slice(0,n):o.subarray(0,n)}var u="Failed to ",p=function(r,e,f){if(r)throw new Error("".concat(u).concat(e,": the '").concat(f,"' option is unsupported."))};var x=typeof Buffer=="function"&&Buffer.from;var A=x?w:F;function v(){this.encoding="utf-8"}v.prototype.encode=function(r,e){return p(e&&e.stream,"encode","stream"),A(r)};function U(r){var e;try{var f=new Blob([r],{type:"text/plain;charset=UTF-8"});e=URL.createObjectURL(f);var n=new XMLHttpRequest;return n.open("GET",e,!1),n.send(),n.responseText}finally{e&&URL.revokeObjectURL(e)}}var O=!x&&typeof Blob=="function"&&typeof URL=="function"&&typeof URL.createObjectURL=="function",S=["utf-8","utf8","unicode-1-1-utf-8"],T=h;x?T=B:O&&(T=function(r){try{return U(r)}catch(e){return h(r)}});var y="construct 'TextDecoder'",E="".concat(u," ").concat(y,": the ");function g(r,e){p(e&&e.fatal,y,"fatal"),r=r||"utf-8";var f;if(x?f=Buffer.isEncoding(r):f=S.indexOf(r.toLowerCase())!==-1,!f)throw new RangeError("".concat(E," encoding label provided ('").concat(r,"') is invalid."));this.encoding=r,this.fatal=!1,this.ignoreBOM=!1}g.prototype.decode=function(r,e){p(e&&e.stream,"decode","stream");var f;return r instanceof Uint8Array?f=r:r.buffer instanceof ArrayBuffer?f=new Uint8Array(r.buffer):f=new Uint8Array(r),T(f,this.encoding)};scope.TextEncoder=scope.TextEncoder||v;scope.TextDecoder=scope.TextDecoder||g;5577}(typeof window !== 'undefined' ? window : (typeof global !== 'undefined' ? global : this)));5578/***/ }),5579/***/ 6129:5580/***/ ((__unused_webpack_module, exports) => {5581"use strict";5582// Copyright 2018 Google LLC5583// Licensed under the Apache License, Version 2.0 (the "License");5584// you may not use this file except in compliance with the License.5585// You may obtain a copy of the License at5586//5587// http://www.apache.org/licenses/LICENSE-2.05588//5589// Unless required by applicable law or agreed to in writing, software5590// distributed under the License is distributed on an "AS IS" BASIS,5591// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.5592// See the License for the specific language governing permissions and5593// limitations under the License.5594Object.defineProperty(exports, "__esModule", ({ value: true }));5595exports.GaxiosError = void 0;5596/* eslint-disable @typescript-eslint/no-explicit-any */5597class GaxiosError extends Error {5598 constructor(message, options, response) {5599 super(message);5600 this.response = response;5601 this.config = options;5602 this.code = response.status.toString();5603 }5604}5605exports.GaxiosError = GaxiosError;5606//# sourceMappingURL=common.js.map5607/***/ }),5608/***/ 8133:5609/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {5610"use strict";5611// Copyright 2018 Google LLC5612// Licensed under the Apache License, Version 2.0 (the "License");5613// you may not use this file except in compliance with the License.5614// You may obtain a copy of the License at5615//5616// http://www.apache.org/licenses/LICENSE-2.05617//5618// Unless required by applicable law or agreed to in writing, software5619// distributed under the License is distributed on an "AS IS" BASIS,5620// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.5621// See the License for the specific language governing permissions and5622// limitations under the License.5623var __importDefault = (this && this.__importDefault) || function (mod) {5624 return (mod && mod.__esModule) ? mod : { "default": mod };5625};5626Object.defineProperty(exports, "__esModule", ({ value: true }));5627exports.Gaxios = void 0;5628const extend_1 = __importDefault(__nccwpck_require__(8171));5629const https_1 = __nccwpck_require__(5687);5630const node_fetch_1 = __importDefault(__nccwpck_require__(467));5631const querystring_1 = __importDefault(__nccwpck_require__(3477));5632const is_stream_1 = __importDefault(__nccwpck_require__(1554));5633const url_1 = __nccwpck_require__(7310);5634const common_1 = __nccwpck_require__(6129);5635const retry_1 = __nccwpck_require__(1052);5636/* eslint-disable @typescript-eslint/no-explicit-any */5637const fetch = hasFetch() ? window.fetch : node_fetch_1.default;5638function hasWindow() {5639 return typeof window !== 'undefined' && !!window;5640}5641function hasFetch() {5642 return hasWindow() && !!window.fetch;5643}5644function hasBuffer() {5645 return typeof Buffer !== 'undefined';5646}5647function hasHeader(options, header) {5648 return !!getHeader(options, header);5649}5650function getHeader(options, header) {5651 header = header.toLowerCase();5652 for (const key of Object.keys((options === null || options === void 0 ? void 0 : options.headers) || {})) {5653 if (header === key.toLowerCase()) {5654 return options.headers[key];5655 }5656 }5657 return undefined;5658}5659let HttpsProxyAgent;5660function loadProxy() {5661 var _a, _b, _c, _d;5662 const proxy = ((_a = process === null || process === void 0 ? void 0 : process.env) === null || _a === void 0 ? void 0 : _a.HTTPS_PROXY) ||5663 ((_b = process === null || process === void 0 ? void 0 : process.env) === null || _b === void 0 ? void 0 : _b.https_proxy) ||5664 ((_c = process === null || process === void 0 ? void 0 : process.env) === null || _c === void 0 ? void 0 : _c.HTTP_PROXY) ||5665 ((_d = process === null || process === void 0 ? void 0 : process.env) === null || _d === void 0 ? void 0 : _d.http_proxy);5666 if (proxy) {5667 HttpsProxyAgent = __nccwpck_require__(7219);5668 }5669 return proxy;5670}5671loadProxy();5672function skipProxy(url) {5673 var _a;5674 const noProxyEnv = (_a = process.env.NO_PROXY) !== null && _a !== void 0 ? _a : process.env.no_proxy;5675 if (!noProxyEnv) {5676 return false;5677 }5678 const noProxyUrls = noProxyEnv.split(',');5679 const parsedURL = new url_1.URL(url);5680 return !!noProxyUrls.find(url => {5681 if (url.startsWith('*.') || url.startsWith('.')) {5682 url = url.replace(/^\*\./, '.');5683 return parsedURL.hostname.endsWith(url);5684 }5685 else {5686 return url === parsedURL.origin || url === parsedURL.hostname;5687 }5688 });5689}5690// Figure out if we should be using a proxy. Only if it's required, load5691// the https-proxy-agent module as it adds startup cost.5692function getProxy(url) {5693 // If there is a match between the no_proxy env variables and the url, then do not proxy5694 if (skipProxy(url)) {5695 return undefined;5696 // If there is not a match between the no_proxy env variables and the url, check to see if there should be a proxy5697 }5698 else {5699 return loadProxy();5700 }5701}5702class Gaxios {5703 /**5704 * The Gaxios class is responsible for making HTTP requests.5705 * @param defaults The default set of options to be used for this instance.5706 */5707 constructor(defaults) {5708 this.agentCache = new Map();5709 this.defaults = defaults || {};5710 }5711 /**5712 * Perform an HTTP request with the given options.5713 * @param opts Set of HTTP options that will be used for this HTTP request.5714 */5715 async request(opts = {}) {5716 opts = this.validateOpts(opts);5717 return this._request(opts);5718 }5719 async _defaultAdapter(opts) {5720 const fetchImpl = opts.fetchImplementation || fetch;5721 const res = (await fetchImpl(opts.url, opts));5722 const data = await this.getResponseData(opts, res);5723 return this.translateResponse(opts, res, data);5724 }5725 /**5726 * Internal, retryable version of the `request` method.5727 * @param opts Set of HTTP options that will be used for this HTTP request.5728 */5729 async _request(opts = {}) {5730 try {5731 let translatedResponse;5732 if (opts.adapter) {5733 translatedResponse = await opts.adapter(opts, this._defaultAdapter.bind(this));5734 }5735 else {5736 translatedResponse = await this._defaultAdapter(opts);5737 }5738 if (!opts.validateStatus(translatedResponse.status)) {5739 throw new common_1.GaxiosError(`Request failed with status code ${translatedResponse.status}`, opts, translatedResponse);5740 }5741 return translatedResponse;5742 }5743 catch (e) {5744 const err = e;5745 err.config = opts;5746 const { shouldRetry, config } = await (0, retry_1.getRetryConfig)(err);5747 if (shouldRetry && config) {5748 err.config.retryConfig.currentRetryAttempt =5749 config.retryConfig.currentRetryAttempt;5750 return this._request(err.config);5751 }5752 throw err;5753 }5754 }5755 async getResponseData(opts, res) {5756 switch (opts.responseType) {5757 case 'stream':5758 return res.body;5759 case 'json': {5760 let data = await res.text();5761 try {5762 data = JSON.parse(data);5763 }5764 catch (_a) {5765 // continue5766 }5767 return data;5768 }5769 case 'arraybuffer':5770 return res.arrayBuffer();5771 case 'blob':5772 return res.blob();5773 default:5774 return res.text();5775 }5776 }5777 /**5778 * Validates the options, and merges them with defaults.5779 * @param opts The original options passed from the client.5780 */5781 validateOpts(options) {5782 const opts = (0, extend_1.default)(true, {}, this.defaults, options);5783 if (!opts.url) {5784 throw new Error('URL is required.');5785 }5786 // baseUrl has been deprecated, remove in 2.05787 const baseUrl = opts.baseUrl || opts.baseURL;5788 if (baseUrl) {5789 opts.url = baseUrl + opts.url;5790 }5791 opts.paramsSerializer = opts.paramsSerializer || this.paramsSerializer;5792 if (opts.params && Object.keys(opts.params).length > 0) {5793 let additionalQueryParams = opts.paramsSerializer(opts.params);5794 if (additionalQueryParams.startsWith('?')) {5795 additionalQueryParams = additionalQueryParams.slice(1);5796 }5797 const prefix = opts.url.includes('?') ? '&' : '?';5798 opts.url = opts.url + prefix + additionalQueryParams;5799 }5800 if (typeof options.maxContentLength === 'number') {5801 opts.size = options.maxContentLength;5802 }5803 if (typeof options.maxRedirects === 'number') {5804 opts.follow = options.maxRedirects;5805 }5806 opts.headers = opts.headers || {};5807 if (opts.data) {5808 const isFormData = typeof FormData === 'undefined'5809 ? false5810 : (opts === null || opts === void 0 ? void 0 : opts.data) instanceof FormData;5811 if (is_stream_1.default.readable(opts.data)) {5812 opts.body = opts.data;5813 }5814 else if (hasBuffer() && Buffer.isBuffer(opts.data)) {5815 // Do not attempt to JSON.stringify() a Buffer:5816 opts.body = opts.data;5817 if (!hasHeader(opts, 'Content-Type')) {5818 opts.headers['Content-Type'] = 'application/json';5819 }5820 }5821 else if (typeof opts.data === 'object') {5822 // If www-form-urlencoded content type has been set, but data is5823 // provided as an object, serialize the content using querystring:5824 if (!isFormData) {5825 if (getHeader(opts, 'content-type') ===5826 'application/x-www-form-urlencoded') {5827 opts.body = opts.paramsSerializer(opts.data);5828 }5829 else {5830 // } else if (!(opts.data instanceof FormData)) {5831 if (!hasHeader(opts, 'Content-Type')) {5832 opts.headers['Content-Type'] = 'application/json';5833 }5834 opts.body = JSON.stringify(opts.data);5835 }5836 }5837 }5838 else {5839 opts.body = opts.data;5840 }5841 }5842 opts.validateStatus = opts.validateStatus || this.validateStatus;5843 opts.responseType = opts.responseType || 'json';5844 if (!opts.headers['Accept'] && opts.responseType === 'json') {5845 opts.headers['Accept'] = 'application/json';5846 }5847 opts.method = opts.method || 'GET';5848 const proxy = getProxy(opts.url);5849 if (proxy) {5850 if (this.agentCache.has(proxy)) {5851 opts.agent = this.agentCache.get(proxy);5852 }5853 else {5854 // Proxy is being used in conjunction with mTLS.5855 if (opts.cert && opts.key) {5856 const parsedURL = new url_1.URL(proxy);5857 opts.agent = new HttpsProxyAgent({5858 port: parsedURL.port,5859 host: parsedURL.host,5860 protocol: parsedURL.protocol,5861 cert: opts.cert,5862 key: opts.key,5863 });5864 }5865 else {5866 opts.agent = new HttpsProxyAgent(proxy);5867 }5868 this.agentCache.set(proxy, opts.agent);5869 }5870 }5871 else if (opts.cert && opts.key) {5872 // Configure client for mTLS:5873 if (this.agentCache.has(opts.key)) {5874 opts.agent = this.agentCache.get(opts.key);5875 }5876 else {5877 opts.agent = new https_1.Agent({5878 cert: opts.cert,5879 key: opts.key,5880 });5881 this.agentCache.set(opts.key, opts.agent);5882 }5883 }5884 return opts;5885 }5886 /**5887 * By default, throw for any non-2xx status code5888 * @param status status code from the HTTP response5889 */5890 validateStatus(status) {5891 return status >= 200 && status < 300;5892 }5893 /**5894 * Encode a set of key/value pars into a querystring format (?foo=bar&baz=boo)5895 * @param params key value pars to encode5896 */5897 paramsSerializer(params) {5898 return querystring_1.default.stringify(params);5899 }5900 translateResponse(opts, res, data) {5901 // headers need to be converted from a map to an obj5902 const headers = {};5903 res.headers.forEach((value, key) => {5904 headers[key] = value;5905 });5906 return {5907 config: opts,5908 data: data,5909 headers,5910 status: res.status,5911 statusText: res.statusText,5912 // XMLHttpRequestLike5913 request: {5914 responseURL: res.url,5915 },5916 };5917 }5918}5919exports.Gaxios = Gaxios;5920//# sourceMappingURL=gaxios.js.map5921/***/ }),5922/***/ 9555:5923/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {5924"use strict";5925// Copyright 2018 Google LLC5926// Licensed under the Apache License, Version 2.0 (the "License");5927// you may not use this file except in compliance with the License.5928// You may obtain a copy of the License at5929//5930// http://www.apache.org/licenses/LICENSE-2.05931//5932// Unless required by applicable law or agreed to in writing, software5933// distributed under the License is distributed on an "AS IS" BASIS,5934// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.5935// See the License for the specific language governing permissions and5936// limitations under the License.5937Object.defineProperty(exports, "__esModule", ({ value: true }));5938exports.request = exports.instance = exports.Gaxios = exports.GaxiosError = void 0;5939const gaxios_1 = __nccwpck_require__(8133);5940Object.defineProperty(exports, "Gaxios", ({ enumerable: true, get: function () { return gaxios_1.Gaxios; } }));5941var common_1 = __nccwpck_require__(6129);5942Object.defineProperty(exports, "GaxiosError", ({ enumerable: true, get: function () { return common_1.GaxiosError; } }));5943/**5944 * The default instance used when the `request` method is directly5945 * invoked.5946 */5947exports.instance = new gaxios_1.Gaxios();5948/**5949 * Make an HTTP request using the given options.5950 * @param opts Options for the request5951 */5952async function request(opts) {5953 return exports.instance.request(opts);5954}5955exports.request = request;5956//# sourceMappingURL=index.js.map5957/***/ }),5958/***/ 1052:5959/***/ ((__unused_webpack_module, exports) => {5960"use strict";5961// Copyright 2018 Google LLC5962// Licensed under the Apache License, Version 2.0 (the "License");5963// you may not use this file except in compliance with the License.5964// You may obtain a copy of the License at5965//5966// http://www.apache.org/licenses/LICENSE-2.05967//5968// Unless required by applicable law or agreed to in writing, software5969// distributed under the License is distributed on an "AS IS" BASIS,5970// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.5971// See the License for the specific language governing permissions and5972// limitations under the License.5973Object.defineProperty(exports, "__esModule", ({ value: true }));5974exports.getRetryConfig = void 0;5975async function getRetryConfig(err) {5976 var _a;5977 let config = getConfig(err);5978 if (!err || !err.config || (!config && !err.config.retry)) {5979 return { shouldRetry: false };5980 }5981 config = config || {};5982 config.currentRetryAttempt = config.currentRetryAttempt || 0;5983 config.retry =5984 config.retry === undefined || config.retry === null ? 3 : config.retry;5985 config.httpMethodsToRetry = config.httpMethodsToRetry || [5986 'GET',5987 'HEAD',5988 'PUT',5989 'OPTIONS',5990 'DELETE',5991 ];5992 config.noResponseRetries =5993 config.noResponseRetries === undefined || config.noResponseRetries === null5994 ? 25995 : config.noResponseRetries;5996 // If this wasn't in the list of status codes where we want5997 // to automatically retry, return.5998 const retryRanges = [5999 // https://en.wikipedia.org/wiki/List_of_HTTP_status_codes6000 // 1xx - Retry (Informational, request still processing)6001 // 2xx - Do not retry (Success)6002 // 3xx - Do not retry (Redirect)6003 // 4xx - Do not retry (Client errors)6004 // 429 - Retry ("Too Many Requests")6005 // 5xx - Retry (Server errors)6006 [100, 199],6007 [429, 429],6008 [500, 599],6009 ];6010 config.statusCodesToRetry = config.statusCodesToRetry || retryRanges;6011 // Put the config back into the err6012 err.config.retryConfig = config;6013 // Determine if we should retry the request6014 const shouldRetryFn = config.shouldRetry || shouldRetryRequest;6015 if (!(await shouldRetryFn(err))) {6016 return { shouldRetry: false, config: err.config };6017 }6018 // Calculate time to wait with exponential backoff.6019 // If this is the first retry, look for a configured retryDelay.6020 const retryDelay = config.currentRetryAttempt ? 0 : (_a = config.retryDelay) !== null && _a !== void 0 ? _a : 100;6021 // Formula: retryDelay + ((2^c - 1 / 2) * 1000)6022 const delay = retryDelay + ((Math.pow(2, config.currentRetryAttempt) - 1) / 2) * 1000;6023 // We're going to retry! Incremenent the counter.6024 err.config.retryConfig.currentRetryAttempt += 1;6025 // Create a promise that invokes the retry after the backOffDelay6026 const backoff = new Promise(resolve => {6027 setTimeout(resolve, delay);6028 });6029 // Notify the user if they added an `onRetryAttempt` handler6030 if (config.onRetryAttempt) {6031 config.onRetryAttempt(err);6032 }6033 // Return the promise in which recalls Gaxios to retry the request6034 await backoff;6035 return { shouldRetry: true, config: err.config };6036}6037exports.getRetryConfig = getRetryConfig;6038/**6039 * Determine based on config if we should retry the request.6040 * @param err The GaxiosError passed to the interceptor.6041 */6042function shouldRetryRequest(err) {6043 const config = getConfig(err);6044 // node-fetch raises an AbortError if signaled:6045 // https://github.com/bitinn/node-fetch#request-cancellation-with-abortsignal6046 if (err.name === 'AbortError') {6047 return false;6048 }6049 // If there's no config, or retries are disabled, return.6050 if (!config || config.retry === 0) {6051 return false;6052 }6053 // Check if this error has no response (ETIMEDOUT, ENOTFOUND, etc)6054 if (!err.response &&6055 (config.currentRetryAttempt || 0) >= config.noResponseRetries) {6056 return false;6057 }6058 // Only retry with configured HttpMethods.6059 if (!err.config.method ||6060 config.httpMethodsToRetry.indexOf(err.config.method.toUpperCase()) < 0) {6061 return false;6062 }6063 // If this wasn't in the list of status codes where we want6064 // to automatically retry, return.6065 if (err.response && err.response.status) {6066 let isInRange = false;6067 for (const [min, max] of config.statusCodesToRetry) {6068 const status = err.response.status;6069 if (status >= min && status <= max) {6070 isInRange = true;6071 break;6072 }6073 }6074 if (!isInRange) {6075 return false;6076 }6077 }6078 // If we are out of retry attempts, return6079 config.currentRetryAttempt = config.currentRetryAttempt || 0;6080 if (config.currentRetryAttempt >= config.retry) {6081 return false;6082 }6083 return true;6084}6085/**6086 * Acquire the raxConfig object from an GaxiosError if available.6087 * @param err The Gaxios error with a config object.6088 */6089function getConfig(err) {6090 if (err && err.config && err.config.retryConfig) {6091 return err.config.retryConfig;6092 }6093 return;6094}6095//# sourceMappingURL=retry.js.map6096/***/ }),6097/***/ 3563:6098/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {6099"use strict";6100/**6101 * Copyright 2018 Google LLC6102 *6103 * Distributed under MIT license.6104 * See file LICENSE for detail or copy at https://opensource.org/licenses/MIT6105 */6106Object.defineProperty(exports, "__esModule", ({ value: true }));6107exports.requestTimeout = exports.resetIsAvailableCache = exports.isAvailable = exports.project = exports.instance = exports.HEADERS = exports.HEADER_VALUE = exports.HEADER_NAME = exports.SECONDARY_HOST_ADDRESS = exports.HOST_ADDRESS = exports.BASE_PATH = void 0;6108const gaxios_1 = __nccwpck_require__(9555);6109const jsonBigint = __nccwpck_require__(5031);6110exports.BASE_PATH = '/computeMetadata/v1';6111exports.HOST_ADDRESS = 'http://169.254.169.254';6112exports.SECONDARY_HOST_ADDRESS = 'http://metadata.google.internal.';6113exports.HEADER_NAME = 'Metadata-Flavor';6114exports.HEADER_VALUE = 'Google';6115exports.HEADERS = Object.freeze({ [exports.HEADER_NAME]: exports.HEADER_VALUE });6116/**6117 * Returns the base URL while taking into account the GCE_METADATA_HOST6118 * environment variable if it exists.6119 *6120 * @returns The base URL, e.g., http://169.254.169.254/computeMetadata/v1.6121 */6122function getBaseUrl(baseUrl) {6123 if (!baseUrl) {6124 baseUrl =6125 process.env.GCE_METADATA_IP ||6126 process.env.GCE_METADATA_HOST ||6127 exports.HOST_ADDRESS;6128 }6129 // If no scheme is provided default to HTTP:6130 if (!/^https?:\/\//.test(baseUrl)) {6131 baseUrl = `http://${baseUrl}`;6132 }6133 return new URL(exports.BASE_PATH, baseUrl).href;6134}6135// Accepts an options object passed from the user to the API. In previous6136// versions of the API, it referred to a `Request` or an `Axios` request6137// options object. Now it refers to an object with very limited property6138// names. This is here to help ensure users don't pass invalid options when6139// they upgrade from 0.4 to 0.5 to 0.8.6140function validate(options) {6141 Object.keys(options).forEach(key => {6142 switch (key) {6143 case 'params':6144 case 'property':6145 case 'headers':6146 break;6147 case 'qs':6148 throw new Error("'qs' is not a valid configuration option. Please use 'params' instead.");6149 default:6150 throw new Error(`'${key}' is not a valid configuration option.`);6151 }6152 });6153}6154async function metadataAccessor(type, options, noResponseRetries = 3, fastFail = false) {6155 options = options || {};6156 if (typeof options === 'string') {6157 options = { property: options };6158 }6159 let property = '';6160 if (typeof options === 'object' && options.property) {6161 property = '/' + options.property;6162 }6163 validate(options);6164 try {6165 const requestMethod = fastFail ? fastFailMetadataRequest : gaxios_1.request;6166 const res = await requestMethod({6167 url: `${getBaseUrl()}/${type}${property}`,6168 headers: Object.assign({}, exports.HEADERS, options.headers),6169 retryConfig: { noResponseRetries },6170 params: options.params,6171 responseType: 'text',6172 timeout: requestTimeout(),6173 });6174 // NOTE: node.js converts all incoming headers to lower case.6175 if (res.headers[exports.HEADER_NAME.toLowerCase()] !== exports.HEADER_VALUE) {6176 throw new Error(`Invalid response from metadata service: incorrect ${exports.HEADER_NAME} header.`);6177 }6178 else if (!res.data) {6179 throw new Error('Invalid response from the metadata service');6180 }6181 if (typeof res.data === 'string') {6182 try {6183 return jsonBigint.parse(res.data);6184 }6185 catch (_a) {6186 /* ignore */6187 }6188 }6189 return res.data;6190 }6191 catch (e) {6192 const err = e;6193 if (err.response && err.response.status !== 200) {6194 err.message = `Unsuccessful response status code. ${err.message}`;6195 }6196 throw e;6197 }6198}6199async function fastFailMetadataRequest(options) {6200 const secondaryOptions = {6201 ...options,6202 url: options.url.replace(getBaseUrl(), getBaseUrl(exports.SECONDARY_HOST_ADDRESS)),6203 };6204 // We race a connection between DNS/IP to metadata server. There are a couple6205 // reasons for this:6206 //6207 // 1. the DNS is slow in some GCP environments; by checking both, we might6208 // detect the runtime environment signficantly faster.6209 // 2. we can't just check the IP, which is tarpitted and slow to respond6210 // on a user's local machine.6211 //6212 // Additional logic has been added to make sure that we don't create an6213 // unhandled rejection in scenarios where a failure happens sometime6214 // after a success.6215 //6216 // Note, however, if a failure happens prior to a success, a rejection should6217 // occur, this is for folks running locally.6218 //6219 let responded = false;6220 const r1 = (0, gaxios_1.request)(options)6221 .then(res => {6222 responded = true;6223 return res;6224 })6225 .catch(err => {6226 if (responded) {6227 return r2;6228 }6229 else {6230 responded = true;6231 throw err;6232 }6233 });6234 const r2 = (0, gaxios_1.request)(secondaryOptions)6235 .then(res => {6236 responded = true;6237 return res;6238 })6239 .catch(err => {6240 if (responded) {6241 return r1;6242 }6243 else {6244 responded = true;6245 throw err;6246 }6247 });6248 return Promise.race([r1, r2]);6249}6250/**6251 * Obtain metadata for the current GCE instance6252 */6253// eslint-disable-next-line @typescript-eslint/no-explicit-any6254function instance(options) {6255 return metadataAccessor('instance', options);6256}6257exports.instance = instance;6258/**6259 * Obtain metadata for the current GCP Project.6260 */6261// eslint-disable-next-line @typescript-eslint/no-explicit-any6262function project(options) {6263 return metadataAccessor('project', options);6264}6265exports.project = project;6266/*6267 * How many times should we retry detecting GCP environment.6268 */6269function detectGCPAvailableRetries() {6270 return process.env.DETECT_GCP_RETRIES6271 ? Number(process.env.DETECT_GCP_RETRIES)6272 : 0;6273}6274let cachedIsAvailableResponse;6275/**6276 * Determine if the metadata server is currently available.6277 */6278async function isAvailable() {6279 try {6280 // If a user is instantiating several GCP libraries at the same time,6281 // this may result in multiple calls to isAvailable(), to detect the6282 // runtime environment. We use the same promise for each of these calls6283 // to reduce the network load.6284 if (cachedIsAvailableResponse === undefined) {6285 cachedIsAvailableResponse = metadataAccessor('instance', undefined, detectGCPAvailableRetries(), 6286 // If the default HOST_ADDRESS has been overridden, we should not6287 // make an effort to try SECONDARY_HOST_ADDRESS (as we are likely in6288 // a non-GCP environment):6289 !(process.env.GCE_METADATA_IP || process.env.GCE_METADATA_HOST));6290 }6291 await cachedIsAvailableResponse;6292 return true;6293 }6294 catch (e) {6295 const err = e;6296 if (process.env.DEBUG_AUTH) {6297 console.info(err);6298 }6299 if (err.type === 'request-timeout') {6300 // If running in a GCP environment, metadata endpoint should return6301 // within ms.6302 return false;6303 }6304 if (err.response && err.response.status === 404) {6305 return false;6306 }6307 else {6308 if (!(err.response && err.response.status === 404) &&6309 // A warning is emitted if we see an unexpected err.code, or err.code6310 // is not populated:6311 (!err.code ||6312 ![6313 'EHOSTDOWN',6314 'EHOSTUNREACH',6315 'ENETUNREACH',6316 'ENOENT',6317 'ENOTFOUND',6318 'ECONNREFUSED',6319 ].includes(err.code))) {6320 let code = 'UNKNOWN';6321 if (err.code)6322 code = err.code;6323 process.emitWarning(`received unexpected error = ${err.message} code = ${code}`, 'MetadataLookupWarning');6324 }6325 // Failure to resolve the metadata service means that it is not available.6326 return false;6327 }6328 }6329}6330exports.isAvailable = isAvailable;6331/**6332 * reset the memoized isAvailable() lookup.6333 */6334function resetIsAvailableCache() {6335 cachedIsAvailableResponse = undefined;6336}6337exports.resetIsAvailableCache = resetIsAvailableCache;6338/**6339 * Obtain the timeout for requests to the metadata server.6340 */6341function requestTimeout() {6342 // In testing, we were able to reproduce behavior similar to6343 // https://github.com/googleapis/google-auth-library-nodejs/issues/7986344 // by making many concurrent network requests. Requests do not actually fail,6345 // rather they take significantly longer to complete (and we hit our6346 // default 3000ms timeout).6347 //6348 // This logic detects a GCF environment, using the documented environment6349 // variables K_SERVICE and FUNCTION_NAME:6350 // https://cloud.google.com/functions/docs/env-var and, in a GCF environment6351 // eliminates timeouts (by setting the value to 0 to disable).6352 return process.env.K_SERVICE || process.env.FUNCTION_NAME ? 0 : 3000;6353}6354exports.requestTimeout = requestTimeout;6355//# sourceMappingURL=index.js.map6356/***/ }),6357/***/ 4627:6358/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {6359"use strict";6360// Copyright 2012 Google LLC6361//6362// Licensed under the Apache License, Version 2.0 (the "License");6363// you may not use this file except in compliance with the License.6364// You may obtain a copy of the License at6365//6366// http://www.apache.org/licenses/LICENSE-2.06367//6368// Unless required by applicable law or agreed to in writing, software6369// distributed under the License is distributed on an "AS IS" BASIS,6370// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.6371// See the License for the specific language governing permissions and6372// limitations under the License.6373Object.defineProperty(exports, "__esModule", ({ value: true }));6374exports.AuthClient = void 0;6375const events_1 = __nccwpck_require__(2361);6376const transporters_1 = __nccwpck_require__(2649);6377class AuthClient extends events_1.EventEmitter {6378 constructor() {6379 super(...arguments);6380 this.transporter = new transporters_1.DefaultTransporter();6381 this.credentials = {};6382 this.eagerRefreshThresholdMillis = 5 * 60 * 1000;6383 this.forceRefreshOnFailure = false;6384 }6385 /**6386 * Sets the auth credentials.6387 */6388 setCredentials(credentials) {6389 this.credentials = credentials;6390 }6391 /**6392 * Append additional headers, e.g., x-goog-user-project, shared across the6393 * classes inheriting AuthClient. This method should be used by any method6394 * that overrides getRequestMetadataAsync(), which is a shared helper for6395 * setting request information in both gRPC and HTTP API calls.6396 *6397 * @param headers object to append additional headers to.6398 */6399 addSharedMetadataHeaders(headers) {6400 // quota_project_id, stored in application_default_credentials.json, is set in6401 // the x-goog-user-project header, to indicate an alternate account for6402 // billing and quota:6403 if (!headers['x-goog-user-project'] && // don't override a value the user sets.6404 this.quotaProjectId) {6405 headers['x-goog-user-project'] = this.quotaProjectId;6406 }6407 return headers;6408 }6409}6410exports.AuthClient = AuthClient;6411//# sourceMappingURL=authclient.js.map6412/***/ }),6413/***/ 1569:6414/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {6415"use strict";6416// Copyright 2021 Google LLC6417//6418// Licensed under the Apache License, Version 2.0 (the "License");6419// you may not use this file except in compliance with the License.6420// You may obtain a copy of the License at6421//6422// http://www.apache.org/licenses/LICENSE-2.06423//6424// Unless required by applicable law or agreed to in writing, software6425// distributed under the License is distributed on an "AS IS" BASIS,6426// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.6427// See the License for the specific language governing permissions and6428// limitations under the License.6429Object.defineProperty(exports, "__esModule", ({ value: true }));6430exports.AwsClient = void 0;6431const awsrequestsigner_1 = __nccwpck_require__(1754);6432const baseexternalclient_1 = __nccwpck_require__(7391);6433/**6434 * AWS external account client. This is used for AWS workloads, where6435 * AWS STS GetCallerIdentity serialized signed requests are exchanged for6436 * GCP access token.6437 */6438class AwsClient extends baseexternalclient_1.BaseExternalAccountClient {6439 /**6440 * Instantiates an AwsClient instance using the provided JSON6441 * object loaded from an external account credentials file.6442 * An error is thrown if the credential is not a valid AWS credential.6443 * @param options The external account options object typically loaded6444 * from the external account JSON credential file.6445 * @param additionalOptions Optional additional behavior customization6446 * options. These currently customize expiration threshold time and6447 * whether to retry on 401/403 API request errors.6448 */6449 constructor(options, additionalOptions) {6450 var _a;6451 super(options, additionalOptions);6452 this.environmentId = options.credential_source.environment_id;6453 // This is only required if the AWS region is not available in the6454 // AWS_REGION or AWS_DEFAULT_REGION environment variables.6455 this.regionUrl = options.credential_source.region_url;6456 // This is only required if AWS security credentials are not available in6457 // environment variables.6458 this.securityCredentialsUrl = options.credential_source.url;6459 this.regionalCredVerificationUrl =6460 options.credential_source.regional_cred_verification_url;6461 this.imdsV2SessionTokenUrl =6462 options.credential_source.imdsv2_session_token_url;6463 const match = (_a = this.environmentId) === null || _a === void 0 ? void 0 : _a.match(/^(aws)(\d+)$/);6464 if (!match || !this.regionalCredVerificationUrl) {6465 throw new Error('No valid AWS "credential_source" provided');6466 }6467 else if (parseInt(match[2], 10) !== 1) {6468 throw new Error(`aws version "${match[2]}" is not supported in the current build.`);6469 }6470 this.awsRequestSigner = null;6471 this.region = '';6472 }6473 /**6474 * Triggered when an external subject token is needed to be exchanged for a6475 * GCP access token via GCP STS endpoint.6476 * This uses the `options.credential_source` object to figure out how6477 * to retrieve the token using the current environment. In this case,6478 * this uses a serialized AWS signed request to the STS GetCallerIdentity6479 * endpoint.6480 * The logic is summarized as:6481 * 1. If imdsv2_session_token_url is provided in the credential source, then6482 * fetch the aws session token and include it in the headers of the6483 * metadata requests. This is a requirement for IDMSv2 but optional6484 * for IDMSv1.6485 * 2. Retrieve AWS region from availability-zone.6486 * 3a. Check AWS credentials in environment variables. If not found, get6487 * from security-credentials endpoint.6488 * 3b. Get AWS credentials from security-credentials endpoint. In order6489 * to retrieve this, the AWS role needs to be determined by calling6490 * security-credentials endpoint without any argument. Then the6491 * credentials can be retrieved via: security-credentials/role_name6492 * 4. Generate the signed request to AWS STS GetCallerIdentity action.6493 * 5. Inject x-goog-cloud-target-resource into header and serialize the6494 * signed request. This will be the subject-token to pass to GCP STS.6495 * @return A promise that resolves with the external subject token.6496 */6497 async retrieveSubjectToken() {6498 // Initialize AWS request signer if not already initialized.6499 if (!this.awsRequestSigner) {6500 const metadataHeaders = {};6501 if (this.imdsV2SessionTokenUrl) {6502 metadataHeaders['x-aws-ec2-metadata-token'] =6503 await this.getImdsV2SessionToken();6504 }6505 this.region = await this.getAwsRegion(metadataHeaders);6506 this.awsRequestSigner = new awsrequestsigner_1.AwsRequestSigner(async () => {6507 // Check environment variables for permanent credentials first.6508 // https://docs.aws.amazon.com/general/latest/gr/aws-sec-cred-types.html6509 if (process.env['AWS_ACCESS_KEY_ID'] &&6510 process.env['AWS_SECRET_ACCESS_KEY']) {6511 return {6512 accessKeyId: process.env['AWS_ACCESS_KEY_ID'],6513 secretAccessKey: process.env['AWS_SECRET_ACCESS_KEY'],6514 // This is normally not available for permanent credentials.6515 token: process.env['AWS_SESSION_TOKEN'],6516 };6517 }6518 // Since the role on a VM can change, we don't need to cache it.6519 const roleName = await this.getAwsRoleName(metadataHeaders);6520 // Temporary credentials typically last for several hours.6521 // Expiration is returned in response.6522 // Consider future optimization of this logic to cache AWS tokens6523 // until their natural expiration.6524 const awsCreds = await this.getAwsSecurityCredentials(roleName, metadataHeaders);6525 return {6526 accessKeyId: awsCreds.AccessKeyId,6527 secretAccessKey: awsCreds.SecretAccessKey,6528 token: awsCreds.Token,6529 };6530 }, this.region);6531 }6532 // Generate signed request to AWS STS GetCallerIdentity API.6533 // Use the required regional endpoint. Otherwise, the request will fail.6534 const options = await this.awsRequestSigner.getRequestOptions({6535 url: this.regionalCredVerificationUrl.replace('{region}', this.region),6536 method: 'POST',6537 });6538 // The GCP STS endpoint expects the headers to be formatted as:6539 // [6540 // {key: 'x-amz-date', value: '...'},6541 // {key: 'Authorization', value: '...'},6542 // ...6543 // ]6544 // And then serialized as:6545 // encodeURIComponent(JSON.stringify({6546 // url: '...',6547 // method: 'POST',6548 // headers: [{key: 'x-amz-date', value: '...'}, ...]6549 // }))6550 const reformattedHeader = [];6551 const extendedHeaders = Object.assign({6552 // The full, canonical resource name of the workload identity pool6553 // provider, with or without the HTTPS prefix.6554 // Including this header as part of the signature is recommended to6555 // ensure data integrity.6556 'x-goog-cloud-target-resource': this.audience,6557 }, options.headers);6558 // Reformat header to GCP STS expected format.6559 for (const key in extendedHeaders) {6560 reformattedHeader.push({6561 key,6562 value: extendedHeaders[key],6563 });6564 }6565 // Serialize the reformatted signed request.6566 return encodeURIComponent(JSON.stringify({6567 url: options.url,6568 method: options.method,6569 headers: reformattedHeader,6570 }));6571 }6572 /**6573 * @return A promise that resolves with the IMDSv2 Session Token.6574 */6575 async getImdsV2SessionToken() {6576 const opts = {6577 url: this.imdsV2SessionTokenUrl,6578 method: 'PUT',6579 responseType: 'text',6580 headers: { 'x-aws-ec2-metadata-token-ttl-seconds': '300' },6581 };6582 const response = await this.transporter.request(opts);6583 return response.data;6584 }6585 /**6586 * @param headers The headers to be used in the metadata request.6587 * @return A promise that resolves with the current AWS region.6588 */6589 async getAwsRegion(headers) {6590 // Priority order for region determination:6591 // AWS_REGION > AWS_DEFAULT_REGION > metadata server.6592 if (process.env['AWS_REGION'] || process.env['AWS_DEFAULT_REGION']) {6593 return (process.env['AWS_REGION'] || process.env['AWS_DEFAULT_REGION']);6594 }6595 if (!this.regionUrl) {6596 throw new Error('Unable to determine AWS region due to missing ' +6597 '"options.credential_source.region_url"');6598 }6599 const opts = {6600 url: this.regionUrl,6601 method: 'GET',6602 responseType: 'text',6603 headers: headers,6604 };6605 const response = await this.transporter.request(opts);6606 // Remove last character. For example, if us-east-2b is returned,6607 // the region would be us-east-2.6608 return response.data.substr(0, response.data.length - 1);6609 }6610 /**6611 * @param headers The headers to be used in the metadata request.6612 * @return A promise that resolves with the assigned role to the current6613 * AWS VM. This is needed for calling the security-credentials endpoint.6614 */6615 async getAwsRoleName(headers) {6616 if (!this.securityCredentialsUrl) {6617 throw new Error('Unable to determine AWS role name due to missing ' +6618 '"options.credential_source.url"');6619 }6620 const opts = {6621 url: this.securityCredentialsUrl,6622 method: 'GET',6623 responseType: 'text',6624 headers: headers,6625 };6626 const response = await this.transporter.request(opts);6627 return response.data;6628 }6629 /**6630 * Retrieves the temporary AWS credentials by calling the security-credentials6631 * endpoint as specified in the `credential_source` object.6632 * @param roleName The role attached to the current VM.6633 * @param headers The headers to be used in the metadata request.6634 * @return A promise that resolves with the temporary AWS credentials6635 * needed for creating the GetCallerIdentity signed request.6636 */6637 async getAwsSecurityCredentials(roleName, headers) {6638 const response = await this.transporter.request({6639 url: `${this.securityCredentialsUrl}/${roleName}`,6640 responseType: 'json',6641 headers: headers,6642 });6643 return response.data;6644 }6645}6646exports.AwsClient = AwsClient;6647//# sourceMappingURL=awsclient.js.map6648/***/ }),6649/***/ 1754:6650/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {6651"use strict";6652// Copyright 2021 Google LLC6653//6654// Licensed under the Apache License, Version 2.0 (the "License");6655// you may not use this file except in compliance with the License.6656// You may obtain a copy of the License at6657//6658// http://www.apache.org/licenses/LICENSE-2.06659//6660// Unless required by applicable law or agreed to in writing, software6661// distributed under the License is distributed on an "AS IS" BASIS,6662// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.6663// See the License for the specific language governing permissions and6664// limitations under the License.6665Object.defineProperty(exports, "__esModule", ({ value: true }));6666exports.AwsRequestSigner = void 0;6667const crypto_1 = __nccwpck_require__(8043);6668/** AWS Signature Version 4 signing algorithm identifier. */6669const AWS_ALGORITHM = 'AWS4-HMAC-SHA256';6670/**6671 * The termination string for the AWS credential scope value as defined in6672 * https://docs.aws.amazon.com/general/latest/gr/sigv4-create-string-to-sign.html6673 */6674const AWS_REQUEST_TYPE = 'aws4_request';6675/**6676 * Implements an AWS API request signer based on the AWS Signature Version 46677 * signing process.6678 * https://docs.aws.amazon.com/general/latest/gr/signature-version-4.html6679 */6680class AwsRequestSigner {6681 /**6682 * Instantiates an AWS API request signer used to send authenticated signed6683 * requests to AWS APIs based on the AWS Signature Version 4 signing process.6684 * This also provides a mechanism to generate the signed request without6685 * sending it.6686 * @param getCredentials A mechanism to retrieve AWS security credentials6687 * when needed.6688 * @param region The AWS region to use.6689 */6690 constructor(getCredentials, region) {6691 this.getCredentials = getCredentials;6692 this.region = region;6693 this.crypto = (0, crypto_1.createCrypto)();6694 }6695 /**6696 * Generates the signed request for the provided HTTP request for calling6697 * an AWS API. This follows the steps described at:6698 * https://docs.aws.amazon.com/general/latest/gr/sigv4_signing.html6699 * @param amzOptions The AWS request options that need to be signed.6700 * @return A promise that resolves with the GaxiosOptions containing the6701 * signed HTTP request parameters.6702 */6703 async getRequestOptions(amzOptions) {6704 if (!amzOptions.url) {6705 throw new Error('"url" is required in "amzOptions"');6706 }6707 // Stringify JSON requests. This will be set in the request body of the6708 // generated signed request.6709 const requestPayloadData = typeof amzOptions.data === 'object'6710 ? JSON.stringify(amzOptions.data)6711 : amzOptions.data;6712 const url = amzOptions.url;6713 const method = amzOptions.method || 'GET';6714 const requestPayload = amzOptions.body || requestPayloadData;6715 const additionalAmzHeaders = amzOptions.headers;6716 const awsSecurityCredentials = await this.getCredentials();6717 const uri = new URL(url);6718 const headerMap = await generateAuthenticationHeaderMap({6719 crypto: this.crypto,6720 host: uri.host,6721 canonicalUri: uri.pathname,6722 canonicalQuerystring: uri.search.substr(1),6723 method,6724 region: this.region,6725 securityCredentials: awsSecurityCredentials,6726 requestPayload,6727 additionalAmzHeaders,6728 });6729 // Append additional optional headers, eg. X-Amz-Target, Content-Type, etc.6730 const headers = Object.assign(6731 // Add x-amz-date if available.6732 headerMap.amzDate ? { 'x-amz-date': headerMap.amzDate } : {}, {6733 Authorization: headerMap.authorizationHeader,6734 host: uri.host,6735 }, additionalAmzHeaders || {});6736 if (awsSecurityCredentials.token) {6737 Object.assign(headers, {6738 'x-amz-security-token': awsSecurityCredentials.token,6739 });6740 }6741 const awsSignedReq = {6742 url,6743 method: method,6744 headers,6745 };6746 if (typeof requestPayload !== 'undefined') {6747 awsSignedReq.body = requestPayload;6748 }6749 return awsSignedReq;6750 }6751}6752exports.AwsRequestSigner = AwsRequestSigner;6753/**6754 * Creates the HMAC-SHA256 hash of the provided message using the6755 * provided key.6756 *6757 * @param crypto The crypto instance used to facilitate cryptographic6758 * operations.6759 * @param key The HMAC-SHA256 key to use.6760 * @param msg The message to hash.6761 * @return The computed hash bytes.6762 */6763async function sign(crypto, key, msg) {6764 return await crypto.signWithHmacSha256(key, msg);6765}6766/**6767 * Calculates the signing key used to calculate the signature for6768 * AWS Signature Version 4 based on:6769 * https://docs.aws.amazon.com/general/latest/gr/sigv4-calculate-signature.html6770 *6771 * @param crypto The crypto instance used to facilitate cryptographic6772 * operations.6773 * @param key The AWS secret access key.6774 * @param dateStamp The '%Y%m%d' date format.6775 * @param region The AWS region.6776 * @param serviceName The AWS service name, eg. sts.6777 * @return The signing key bytes.6778 */6779async function getSigningKey(crypto, key, dateStamp, region, serviceName) {6780 const kDate = await sign(crypto, `AWS4${key}`, dateStamp);6781 const kRegion = await sign(crypto, kDate, region);6782 const kService = await sign(crypto, kRegion, serviceName);6783 const kSigning = await sign(crypto, kService, 'aws4_request');6784 return kSigning;6785}6786/**6787 * Generates the authentication header map needed for generating the AWS6788 * Signature Version 4 signed request.6789 *6790 * @param option The options needed to compute the authentication header map.6791 * @return The AWS authentication header map which constitutes of the following6792 * components: amz-date, authorization header and canonical query string.6793 */6794async function generateAuthenticationHeaderMap(options) {6795 const additionalAmzHeaders = options.additionalAmzHeaders || {};6796 const requestPayload = options.requestPayload || '';6797 // iam.amazonaws.com host => iam service.6798 // sts.us-east-2.amazonaws.com => sts service.6799 const serviceName = options.host.split('.')[0];6800 const now = new Date();6801 // Format: '%Y%m%dT%H%M%SZ'.6802 const amzDate = now6803 .toISOString()6804 .replace(/[-:]/g, '')6805 .replace(/\.[0-9]+/, '');6806 // Format: '%Y%m%d'.6807 const dateStamp = now.toISOString().replace(/[-]/g, '').replace(/T.*/, '');6808 // Change all additional headers to be lower case.6809 const reformattedAdditionalAmzHeaders = {};6810 Object.keys(additionalAmzHeaders).forEach(key => {6811 reformattedAdditionalAmzHeaders[key.toLowerCase()] =6812 additionalAmzHeaders[key];6813 });6814 // Add AWS token if available.6815 if (options.securityCredentials.token) {6816 reformattedAdditionalAmzHeaders['x-amz-security-token'] =6817 options.securityCredentials.token;6818 }6819 // Header keys need to be sorted alphabetically.6820 const amzHeaders = Object.assign({6821 host: options.host,6822 }, 6823 // Previously the date was not fixed with x-amz- and could be provided manually.6824 // https://github.com/boto/botocore/blob/879f8440a4e9ace5d3cf145ce8b3d5e5ffb892ef/tests/unit/auth/aws4_testsuite/get-header-value-trim.req6825 reformattedAdditionalAmzHeaders.date ? {} : { 'x-amz-date': amzDate }, reformattedAdditionalAmzHeaders);6826 let canonicalHeaders = '';6827 const signedHeadersList = Object.keys(amzHeaders).sort();6828 signedHeadersList.forEach(key => {6829 canonicalHeaders += `${key}:${amzHeaders[key]}\n`;6830 });6831 const signedHeaders = signedHeadersList.join(';');6832 const payloadHash = await options.crypto.sha256DigestHex(requestPayload);6833 // https://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html6834 const canonicalRequest = `${options.method}\n` +6835 `${options.canonicalUri}\n` +6836 `${options.canonicalQuerystring}\n` +6837 `${canonicalHeaders}\n` +6838 `${signedHeaders}\n` +6839 `${payloadHash}`;6840 const credentialScope = `${dateStamp}/${options.region}/${serviceName}/${AWS_REQUEST_TYPE}`;6841 // https://docs.aws.amazon.com/general/latest/gr/sigv4-create-string-to-sign.html6842 const stringToSign = `${AWS_ALGORITHM}\n` +6843 `${amzDate}\n` +6844 `${credentialScope}\n` +6845 (await options.crypto.sha256DigestHex(canonicalRequest));6846 // https://docs.aws.amazon.com/general/latest/gr/sigv4-calculate-signature.html6847 const signingKey = await getSigningKey(options.crypto, options.securityCredentials.secretAccessKey, dateStamp, options.region, serviceName);6848 const signature = await sign(options.crypto, signingKey, stringToSign);6849 // https://docs.aws.amazon.com/general/latest/gr/sigv4-add-signature-to-request.html6850 const authorizationHeader = `${AWS_ALGORITHM} Credential=${options.securityCredentials.accessKeyId}/` +6851 `${credentialScope}, SignedHeaders=${signedHeaders}, ` +6852 `Signature=${(0, crypto_1.fromArrayBufferToHex)(signature)}`;6853 return {6854 // Do not return x-amz-date if date is available.6855 amzDate: reformattedAdditionalAmzHeaders.date ? undefined : amzDate,6856 authorizationHeader,6857 canonicalQuerystring: options.canonicalQuerystring,6858 };6859}6860//# sourceMappingURL=awsrequestsigner.js.map6861/***/ }),6862/***/ 7391:6863/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {6864"use strict";6865// Copyright 2021 Google LLC6866//6867// Licensed under the Apache License, Version 2.0 (the "License");6868// you may not use this file except in compliance with the License.6869// You may obtain a copy of the License at6870//6871// http://www.apache.org/licenses/LICENSE-2.06872//6873// Unless required by applicable law or agreed to in writing, software6874// distributed under the License is distributed on an "AS IS" BASIS,6875// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.6876// See the License for the specific language governing permissions and6877// limitations under the License.6878Object.defineProperty(exports, "__esModule", ({ value: true }));6879exports.BaseExternalAccountClient = exports.CLOUD_RESOURCE_MANAGER = exports.EXTERNAL_ACCOUNT_TYPE = exports.EXPIRATION_TIME_OFFSET = void 0;6880const stream = __nccwpck_require__(2781);6881const authclient_1 = __nccwpck_require__(4627);6882const sts = __nccwpck_require__(6308);6883/**6884 * The required token exchange grant_type: rfc8693#section-2.16885 */6886const STS_GRANT_TYPE = 'urn:ietf:params:oauth:grant-type:token-exchange';6887/**6888 * The requested token exchange requested_token_type: rfc8693#section-2.16889 */6890const STS_REQUEST_TOKEN_TYPE = 'urn:ietf:params:oauth:token-type:access_token';6891/** The default OAuth scope to request when none is provided. */6892const DEFAULT_OAUTH_SCOPE = 'https://www.googleapis.com/auth/cloud-platform';6893/** The google apis domain pattern. */6894const GOOGLE_APIS_DOMAIN_PATTERN = '\\.googleapis\\.com$';6895/** The variable portion pattern in a Google APIs domain. */6896const VARIABLE_PORTION_PATTERN = '[^\\.\\s\\/\\\\]+';6897/** Default impersonated token lifespan in seconds.*/6898const DEFAULT_TOKEN_LIFESPAN = 3600;6899/**6900 * Offset to take into account network delays and server clock skews.6901 */6902exports.EXPIRATION_TIME_OFFSET = 5 * 60 * 1000;6903/**6904 * The credentials JSON file type for external account clients.6905 * There are 3 types of JSON configs:6906 * 1. authorized_user => Google end user credential6907 * 2. service_account => Google service account credential6908 * 3. external_Account => non-GCP service (eg. AWS, Azure, K8s)6909 */6910exports.EXTERNAL_ACCOUNT_TYPE = 'external_account';6911/** Cloud resource manager URL used to retrieve project information. */6912exports.CLOUD_RESOURCE_MANAGER = 'https://cloudresourcemanager.googleapis.com/v1/projects/';6913/** The workforce audience pattern. */6914const WORKFORCE_AUDIENCE_PATTERN = '//iam.googleapis.com/locations/[^/]+/workforcePools/[^/]+/providers/.+';6915/**6916 * Base external account client. This is used to instantiate AuthClients for6917 * exchanging external account credentials for GCP access token and authorizing6918 * requests to GCP APIs.6919 * The base class implements common logic for exchanging various type of6920 * external credentials for GCP access token. The logic of determining and6921 * retrieving the external credential based on the environment and6922 * credential_source will be left for the subclasses.6923 */6924class BaseExternalAccountClient extends authclient_1.AuthClient {6925 /**6926 * Instantiate a BaseExternalAccountClient instance using the provided JSON6927 * object loaded from an external account credentials file.6928 * @param options The external account options object typically loaded6929 * from the external account JSON credential file.6930 * @param additionalOptions Optional additional behavior customization6931 * options. These currently customize expiration threshold time and6932 * whether to retry on 401/403 API request errors.6933 */6934 constructor(options, additionalOptions) {6935 var _a, _b;6936 super();6937 if (options.type !== exports.EXTERNAL_ACCOUNT_TYPE) {6938 throw new Error(`Expected "${exports.EXTERNAL_ACCOUNT_TYPE}" type but ` +6939 `received "${options.type}"`);6940 }6941 this.clientAuth = options.client_id6942 ? {6943 confidentialClientType: 'basic',6944 clientId: options.client_id,6945 clientSecret: options.client_secret,6946 }6947 : undefined;6948 if (!this.validateGoogleAPIsUrl('sts', options.token_url)) {6949 throw new Error(`"${options.token_url}" is not a valid token url.`);6950 }6951 this.stsCredential = new sts.StsCredentials(options.token_url, this.clientAuth);6952 // Default OAuth scope. This could be overridden via public property.6953 this.scopes = [DEFAULT_OAUTH_SCOPE];6954 this.cachedAccessToken = null;6955 this.audience = options.audience;6956 this.subjectTokenType = options.subject_token_type;6957 this.quotaProjectId = options.quota_project_id;6958 this.workforcePoolUserProject = options.workforce_pool_user_project;6959 const workforceAudiencePattern = new RegExp(WORKFORCE_AUDIENCE_PATTERN);6960 if (this.workforcePoolUserProject &&6961 !this.audience.match(workforceAudiencePattern)) {6962 throw new Error('workforcePoolUserProject should not be set for non-workforce pool ' +6963 'credentials.');6964 }6965 if (typeof options.service_account_impersonation_url !== 'undefined' &&6966 !this.validateGoogleAPIsUrl('iamcredentials', options.service_account_impersonation_url)) {6967 throw new Error(`"${options.service_account_impersonation_url}" is ` +6968 'not a valid service account impersonation url.');6969 }6970 this.serviceAccountImpersonationUrl =6971 options.service_account_impersonation_url;6972 this.serviceAccountImpersonationLifetime =6973 (_b = (_a = options.service_account_impersonation) === null || _a === void 0 ? void 0 : _a.token_lifetime_seconds) !== null && _b !== void 0 ? _b : DEFAULT_TOKEN_LIFESPAN;6974 // As threshold could be zero,6975 // eagerRefreshThresholdMillis || EXPIRATION_TIME_OFFSET will override the6976 // zero value.6977 if (typeof (additionalOptions === null || additionalOptions === void 0 ? void 0 : additionalOptions.eagerRefreshThresholdMillis) !== 'number') {6978 this.eagerRefreshThresholdMillis = exports.EXPIRATION_TIME_OFFSET;6979 }6980 else {6981 this.eagerRefreshThresholdMillis = additionalOptions6982 .eagerRefreshThresholdMillis;6983 }6984 this.forceRefreshOnFailure = !!(additionalOptions === null || additionalOptions === void 0 ? void 0 : additionalOptions.forceRefreshOnFailure);6985 this.projectId = null;6986 this.projectNumber = this.getProjectNumber(this.audience);6987 }6988 /** The service account email to be impersonated, if available. */6989 getServiceAccountEmail() {6990 var _a;6991 if (this.serviceAccountImpersonationUrl) {6992 // Parse email from URL. The formal looks as follows:6993 // https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/name@project-id.iam.gserviceaccount.com:generateAccessToken6994 const re = /serviceAccounts\/(?<email>[^:]+):generateAccessToken$/;6995 const result = re.exec(this.serviceAccountImpersonationUrl);6996 return ((_a = result === null || result === void 0 ? void 0 : result.groups) === null || _a === void 0 ? void 0 : _a.email) || null;6997 }6998 return null;6999 }7000 /**7001 * Provides a mechanism to inject GCP access tokens directly.7002 * When the provided credential expires, a new credential, using the7003 * external account options, is retrieved.7004 * @param credentials The Credentials object to set on the current client.7005 */7006 setCredentials(credentials) {7007 super.setCredentials(credentials);7008 this.cachedAccessToken = credentials;7009 }7010 /**7011 * @return A promise that resolves with the current GCP access token7012 * response. If the current credential is expired, a new one is retrieved.7013 */7014 async getAccessToken() {7015 // If cached access token is unavailable or expired, force refresh.7016 if (!this.cachedAccessToken || this.isExpired(this.cachedAccessToken)) {7017 await this.refreshAccessTokenAsync();7018 }7019 // Return GCP access token in GetAccessTokenResponse format.7020 return {7021 token: this.cachedAccessToken.access_token,7022 res: this.cachedAccessToken.res,7023 };7024 }7025 /**7026 * The main authentication interface. It takes an optional url which when7027 * present is the endpoint being accessed, and returns a Promise which7028 * resolves with authorization header fields.7029 *7030 * The result has the form:7031 * { Authorization: 'Bearer <access_token_value>' }7032 */7033 async getRequestHeaders() {7034 const accessTokenResponse = await this.getAccessToken();7035 const headers = {7036 Authorization: `Bearer ${accessTokenResponse.token}`,7037 };7038 return this.addSharedMetadataHeaders(headers);7039 }7040 request(opts, callback) {7041 if (callback) {7042 this.requestAsync(opts).then(r => callback(null, r), e => {7043 return callback(e, e.response);7044 });7045 }7046 else {7047 return this.requestAsync(opts);7048 }7049 }7050 /**7051 * @return A promise that resolves with the project ID corresponding to the7052 * current workload identity pool or current workforce pool if7053 * determinable. For workforce pool credential, it returns the project ID7054 * corresponding to the workforcePoolUserProject.7055 * This is introduced to match the current pattern of using the Auth7056 * library:7057 * const projectId = await auth.getProjectId();7058 * const url = `https://dns.googleapis.com/dns/v1/projects/${projectId}`;7059 * const res = await client.request({ url });7060 * The resource may not have permission7061 * (resourcemanager.projects.get) to call this API or the required7062 * scopes may not be selected:7063 * https://cloud.google.com/resource-manager/reference/rest/v1/projects/get#authorization-scopes7064 */7065 async getProjectId() {7066 const projectNumber = this.projectNumber || this.workforcePoolUserProject;7067 if (this.projectId) {7068 // Return previously determined project ID.7069 return this.projectId;7070 }7071 else if (projectNumber) {7072 // Preferable not to use request() to avoid retrial policies.7073 const headers = await this.getRequestHeaders();7074 const response = await this.transporter.request({7075 headers,7076 url: `${exports.CLOUD_RESOURCE_MANAGER}${projectNumber}`,7077 responseType: 'json',7078 });7079 this.projectId = response.data.projectId;7080 return this.projectId;7081 }7082 return null;7083 }7084 /**7085 * Authenticates the provided HTTP request, processes it and resolves with the7086 * returned response.7087 * @param opts The HTTP request options.7088 * @param retry Whether the current attempt is a retry after a failed attempt.7089 * @return A promise that resolves with the successful response.7090 */7091 async requestAsync(opts, retry = false) {7092 let response;7093 try {7094 const requestHeaders = await this.getRequestHeaders();7095 opts.headers = opts.headers || {};7096 if (requestHeaders && requestHeaders['x-goog-user-project']) {7097 opts.headers['x-goog-user-project'] =7098 requestHeaders['x-goog-user-project'];7099 }7100 if (requestHeaders && requestHeaders.Authorization) {7101 opts.headers.Authorization = requestHeaders.Authorization;7102 }7103 response = await this.transporter.request(opts);7104 }7105 catch (e) {7106 const res = e.response;7107 if (res) {7108 const statusCode = res.status;7109 // Retry the request for metadata if the following criteria are true:7110 // - We haven't already retried. It only makes sense to retry once.7111 // - The response was a 401 or a 4037112 // - The request didn't send a readableStream7113 // - forceRefreshOnFailure is true7114 const isReadableStream = res.config.data instanceof stream.Readable;7115 const isAuthErr = statusCode === 401 || statusCode === 403;7116 if (!retry &&7117 isAuthErr &&7118 !isReadableStream &&7119 this.forceRefreshOnFailure) {7120 await this.refreshAccessTokenAsync();7121 return await this.requestAsync(opts, true);7122 }7123 }7124 throw e;7125 }7126 return response;7127 }7128 /**7129 * Forces token refresh, even if unexpired tokens are currently cached.7130 * External credentials are exchanged for GCP access tokens via the token7131 * exchange endpoint and other settings provided in the client options7132 * object.7133 * If the service_account_impersonation_url is provided, an additional7134 * step to exchange the external account GCP access token for a service7135 * account impersonated token is performed.7136 * @return A promise that resolves with the fresh GCP access tokens.7137 */7138 async refreshAccessTokenAsync() {7139 // Retrieve the external credential.7140 const subjectToken = await this.retrieveSubjectToken();7141 // Construct the STS credentials options.7142 const stsCredentialsOptions = {7143 grantType: STS_GRANT_TYPE,7144 audience: this.audience,7145 requestedTokenType: STS_REQUEST_TOKEN_TYPE,7146 subjectToken,7147 subjectTokenType: this.subjectTokenType,7148 // generateAccessToken requires the provided access token to have7149 // scopes:7150 // https://www.googleapis.com/auth/iam or7151 // https://www.googleapis.com/auth/cloud-platform7152 // The new service account access token scopes will match the user7153 // provided ones.7154 scope: this.serviceAccountImpersonationUrl7155 ? [DEFAULT_OAUTH_SCOPE]7156 : this.getScopesArray(),7157 };7158 // Exchange the external credentials for a GCP access token.7159 // Client auth is prioritized over passing the workforcePoolUserProject7160 // parameter for STS token exchange.7161 const additionalOptions = !this.clientAuth && this.workforcePoolUserProject7162 ? { userProject: this.workforcePoolUserProject }7163 : undefined;7164 const stsResponse = await this.stsCredential.exchangeToken(stsCredentialsOptions, undefined, additionalOptions);7165 if (this.serviceAccountImpersonationUrl) {7166 this.cachedAccessToken = await this.getImpersonatedAccessToken(stsResponse.access_token);7167 }7168 else if (stsResponse.expires_in) {7169 // Save response in cached access token.7170 this.cachedAccessToken = {7171 access_token: stsResponse.access_token,7172 expiry_date: new Date().getTime() + stsResponse.expires_in * 1000,7173 res: stsResponse.res,7174 };7175 }7176 else {7177 // Save response in cached access token.7178 this.cachedAccessToken = {7179 access_token: stsResponse.access_token,7180 res: stsResponse.res,7181 };7182 }7183 // Save credentials.7184 this.credentials = {};7185 Object.assign(this.credentials, this.cachedAccessToken);7186 delete this.credentials.res;7187 // Trigger tokens event to notify external listeners.7188 this.emit('tokens', {7189 refresh_token: null,7190 expiry_date: this.cachedAccessToken.expiry_date,7191 access_token: this.cachedAccessToken.access_token,7192 token_type: 'Bearer',7193 id_token: null,7194 });7195 // Return the cached access token.7196 return this.cachedAccessToken;7197 }7198 /**7199 * Returns the workload identity pool project number if it is determinable7200 * from the audience resource name.7201 * @param audience The STS audience used to determine the project number.7202 * @return The project number associated with the workload identity pool, if7203 * this can be determined from the STS audience field. Otherwise, null is7204 * returned.7205 */7206 getProjectNumber(audience) {7207 // STS audience pattern:7208 // //iam.googleapis.com/projects/$PROJECT_NUMBER/locations/...7209 const match = audience.match(/\/projects\/([^/]+)/);7210 if (!match) {7211 return null;7212 }7213 return match[1];7214 }7215 /**7216 * Exchanges an external account GCP access token for a service7217 * account impersonated access token using iamcredentials7218 * GenerateAccessToken API.7219 * @param token The access token to exchange for a service account access7220 * token.7221 * @return A promise that resolves with the service account impersonated7222 * credentials response.7223 */7224 async getImpersonatedAccessToken(token) {7225 const opts = {7226 url: this.serviceAccountImpersonationUrl,7227 method: 'POST',7228 headers: {7229 'Content-Type': 'application/json',7230 Authorization: `Bearer ${token}`,7231 },7232 data: {7233 scope: this.getScopesArray(),7234 lifetime: this.serviceAccountImpersonationLifetime + 's',7235 },7236 responseType: 'json',7237 };7238 const response = await this.transporter.request(opts);7239 const successResponse = response.data;7240 return {7241 access_token: successResponse.accessToken,7242 // Convert from ISO format to timestamp.7243 expiry_date: new Date(successResponse.expireTime).getTime(),7244 res: response,7245 };7246 }7247 /**7248 * Returns whether the provided credentials are expired or not.7249 * If there is no expiry time, assumes the token is not expired or expiring.7250 * @param accessToken The credentials to check for expiration.7251 * @return Whether the credentials are expired or not.7252 */7253 isExpired(accessToken) {7254 const now = new Date().getTime();7255 return accessToken.expiry_date7256 ? now >= accessToken.expiry_date - this.eagerRefreshThresholdMillis7257 : false;7258 }7259 /**7260 * @return The list of scopes for the requested GCP access token.7261 */7262 getScopesArray() {7263 // Since scopes can be provided as string or array, the type should7264 // be normalized.7265 if (typeof this.scopes === 'string') {7266 return [this.scopes];7267 }7268 else if (typeof this.scopes === 'undefined') {7269 return [DEFAULT_OAUTH_SCOPE];7270 }7271 else {7272 return this.scopes;7273 }7274 }7275 /**7276 * Checks whether Google APIs URL is valid.7277 * @param apiName The apiName of url.7278 * @param url The Google API URL to validate.7279 * @return Whether the URL is valid or not.7280 */7281 validateGoogleAPIsUrl(apiName, url) {7282 let parsedUrl;7283 // Return false if error is thrown during parsing URL.7284 try {7285 parsedUrl = new URL(url);7286 }7287 catch (e) {7288 return false;7289 }7290 const urlDomain = parsedUrl.hostname;7291 // Check the protocol is https.7292 if (parsedUrl.protocol !== 'https:') {7293 return false;7294 }7295 const googleAPIsDomainPatterns = [7296 new RegExp('^' +7297 VARIABLE_PORTION_PATTERN +7298 '\\.' +7299 apiName +7300 GOOGLE_APIS_DOMAIN_PATTERN),7301 new RegExp('^' + apiName + GOOGLE_APIS_DOMAIN_PATTERN),7302 new RegExp('^' +7303 apiName +7304 '\\.' +7305 VARIABLE_PORTION_PATTERN +7306 GOOGLE_APIS_DOMAIN_PATTERN),7307 new RegExp('^' +7308 VARIABLE_PORTION_PATTERN +7309 '\\-' +7310 apiName +7311 GOOGLE_APIS_DOMAIN_PATTERN),7312 ];7313 for (const googleAPIsDomainPattern of googleAPIsDomainPatterns) {7314 if (urlDomain.match(googleAPIsDomainPattern)) {7315 return true;7316 }7317 }7318 return false;7319 }7320}7321exports.BaseExternalAccountClient = BaseExternalAccountClient;7322//# sourceMappingURL=baseexternalclient.js.map7323/***/ }),7324/***/ 6875:7325/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {7326"use strict";7327// Copyright 2013 Google LLC7328//7329// Licensed under the Apache License, Version 2.0 (the "License");7330// you may not use this file except in compliance with the License.7331// You may obtain a copy of the License at7332//7333// http://www.apache.org/licenses/LICENSE-2.07334//7335// Unless required by applicable law or agreed to in writing, software7336// distributed under the License is distributed on an "AS IS" BASIS,7337// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.7338// See the License for the specific language governing permissions and7339// limitations under the License.7340Object.defineProperty(exports, "__esModule", ({ value: true }));7341exports.Compute = void 0;7342const arrify = __nccwpck_require__(1546);7343const gaxios_1 = __nccwpck_require__(9555);7344const gcpMetadata = __nccwpck_require__(3563);7345const oauth2client_1 = __nccwpck_require__(3936);7346class Compute extends oauth2client_1.OAuth2Client {7347 /**7348 * Google Compute Engine service account credentials.7349 *7350 * Retrieve access token from the metadata server.7351 * See: https://developers.google.com/compute/docs/authentication7352 */7353 constructor(options = {}) {7354 super(options);7355 // Start with an expired refresh token, which will automatically be7356 // refreshed before the first API call is made.7357 this.credentials = { expiry_date: 1, refresh_token: 'compute-placeholder' };7358 this.serviceAccountEmail = options.serviceAccountEmail || 'default';7359 this.scopes = arrify(options.scopes);7360 }7361 /**7362 * Refreshes the access token.7363 * @param refreshToken Unused parameter7364 */7365 async refreshTokenNoCache(7366 // eslint-disable-next-line @typescript-eslint/no-unused-vars7367 refreshToken) {7368 const tokenPath = `service-accounts/${this.serviceAccountEmail}/token`;7369 let data;7370 try {7371 const instanceOptions = {7372 property: tokenPath,7373 };7374 if (this.scopes.length > 0) {7375 instanceOptions.params = {7376 scopes: this.scopes.join(','),7377 };7378 }7379 data = await gcpMetadata.instance(instanceOptions);7380 }7381 catch (e) {7382 if (e instanceof gaxios_1.GaxiosError) {7383 e.message = `Could not refresh access token: ${e.message}`;7384 this.wrapError(e);7385 }7386 throw e;7387 }7388 const tokens = data;7389 if (data && data.expires_in) {7390 tokens.expiry_date = new Date().getTime() + data.expires_in * 1000;7391 delete tokens.expires_in;7392 }7393 this.emit('tokens', tokens);7394 return { tokens, res: null };7395 }7396 /**7397 * Fetches an ID token.7398 * @param targetAudience the audience for the fetched ID token.7399 */7400 async fetchIdToken(targetAudience) {7401 const idTokenPath = `service-accounts/${this.serviceAccountEmail}/identity` +7402 `?format=full&audience=${targetAudience}`;7403 let idToken;7404 try {7405 const instanceOptions = {7406 property: idTokenPath,7407 };7408 idToken = await gcpMetadata.instance(instanceOptions);7409 }7410 catch (e) {7411 if (e instanceof Error) {7412 e.message = `Could not fetch ID token: ${e.message}`;7413 }7414 throw e;7415 }7416 return idToken;7417 }7418 wrapError(e) {7419 const res = e.response;7420 if (res && res.status) {7421 e.code = res.status.toString();7422 if (res.status === 403) {7423 e.message =7424 'A Forbidden error was returned while attempting to retrieve an access ' +7425 'token for the Compute Engine built-in service account. This may be because the Compute ' +7426 'Engine instance does not have the correct permission scopes specified: ' +7427 e.message;7428 }7429 else if (res.status === 404) {7430 e.message =7431 'A Not Found error was returned while attempting to retrieve an access' +7432 'token for the Compute Engine built-in service account. This may be because the Compute ' +7433 'Engine instance does not have any permission scopes specified: ' +7434 e.message;7435 }7436 }7437 }7438}7439exports.Compute = Compute;7440//# sourceMappingURL=computeclient.js.map7441/***/ }),7442/***/ 6270:7443/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {7444"use strict";7445// Copyright 2021 Google LLC7446//7447// Licensed under the Apache License, Version 2.0 (the "License");7448// you may not use this file except in compliance with the License.7449// You may obtain a copy of the License at7450//7451// http://www.apache.org/licenses/LICENSE-2.07452//7453// Unless required by applicable law or agreed to in writing, software7454// distributed under the License is distributed on an "AS IS" BASIS,7455// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.7456// See the License for the specific language governing permissions and7457// limitations under the License.7458Object.defineProperty(exports, "__esModule", ({ value: true }));7459exports.DownscopedClient = exports.EXPIRATION_TIME_OFFSET = exports.MAX_ACCESS_BOUNDARY_RULES_COUNT = void 0;7460const stream = __nccwpck_require__(2781);7461const authclient_1 = __nccwpck_require__(4627);7462const sts = __nccwpck_require__(6308);7463/**7464 * The required token exchange grant_type: rfc8693#section-2.17465 */7466const STS_GRANT_TYPE = 'urn:ietf:params:oauth:grant-type:token-exchange';7467/**7468 * The requested token exchange requested_token_type: rfc8693#section-2.17469 */7470const STS_REQUEST_TOKEN_TYPE = 'urn:ietf:params:oauth:token-type:access_token';7471/**7472 * The requested token exchange subject_token_type: rfc8693#section-2.17473 */7474const STS_SUBJECT_TOKEN_TYPE = 'urn:ietf:params:oauth:token-type:access_token';7475/** The STS access token exchange end point. */7476const STS_ACCESS_TOKEN_URL = 'https://sts.googleapis.com/v1/token';7477/**7478 * The maximum number of access boundary rules a Credential Access Boundary7479 * can contain.7480 */7481exports.MAX_ACCESS_BOUNDARY_RULES_COUNT = 10;7482/**7483 * Offset to take into account network delays and server clock skews.7484 */7485exports.EXPIRATION_TIME_OFFSET = 5 * 60 * 1000;7486/**7487 * Defines a set of Google credentials that are downscoped from an existing set7488 * of Google OAuth2 credentials. This is useful to restrict the Identity and7489 * Access Management (IAM) permissions that a short-lived credential can use.7490 * The common pattern of usage is to have a token broker with elevated access7491 * generate these downscoped credentials from higher access source credentials7492 * and pass the downscoped short-lived access tokens to a token consumer via7493 * some secure authenticated channel for limited access to Google Cloud Storage7494 * resources.7495 */7496class DownscopedClient extends authclient_1.AuthClient {7497 /**7498 * Instantiates a downscoped client object using the provided source7499 * AuthClient and credential access boundary rules.7500 * To downscope permissions of a source AuthClient, a Credential Access7501 * Boundary that specifies which resources the new credential can access, as7502 * well as an upper bound on the permissions that are available on each7503 * resource, has to be defined. A downscoped client can then be instantiated7504 * using the source AuthClient and the Credential Access Boundary.7505 * @param authClient The source AuthClient to be downscoped based on the7506 * provided Credential Access Boundary rules.7507 * @param credentialAccessBoundary The Credential Access Boundary which7508 * contains a list of access boundary rules. Each rule contains information7509 * on the resource that the rule applies to, the upper bound of the7510 * permissions that are available on that resource and an optional7511 * condition to further restrict permissions.7512 * @param additionalOptions Optional additional behavior customization7513 * options. These currently customize expiration threshold time and7514 * whether to retry on 401/403 API request errors.7515 * @param quotaProjectId Optional quota project id for setting up in the7516 * x-goog-user-project header.7517 */7518 constructor(authClient, credentialAccessBoundary, additionalOptions, quotaProjectId) {7519 super();7520 this.authClient = authClient;7521 this.credentialAccessBoundary = credentialAccessBoundary;7522 // Check 1-10 Access Boundary Rules are defined within Credential Access7523 // Boundary.7524 if (credentialAccessBoundary.accessBoundary.accessBoundaryRules.length === 0) {7525 throw new Error('At least one access boundary rule needs to be defined.');7526 }7527 else if (credentialAccessBoundary.accessBoundary.accessBoundaryRules.length >7528 exports.MAX_ACCESS_BOUNDARY_RULES_COUNT) {7529 throw new Error('The provided access boundary has more than ' +7530 `${exports.MAX_ACCESS_BOUNDARY_RULES_COUNT} access boundary rules.`);7531 }7532 // Check at least one permission should be defined in each Access Boundary7533 // Rule.7534 for (const rule of credentialAccessBoundary.accessBoundary7535 .accessBoundaryRules) {7536 if (rule.availablePermissions.length === 0) {7537 throw new Error('At least one permission should be defined in access boundary rules.');7538 }7539 }7540 this.stsCredential = new sts.StsCredentials(STS_ACCESS_TOKEN_URL);7541 this.cachedDownscopedAccessToken = null;7542 // As threshold could be zero,7543 // eagerRefreshThresholdMillis || EXPIRATION_TIME_OFFSET will override the7544 // zero value.7545 if (typeof (additionalOptions === null || additionalOptions === void 0 ? void 0 : additionalOptions.eagerRefreshThresholdMillis) !== 'number') {7546 this.eagerRefreshThresholdMillis = exports.EXPIRATION_TIME_OFFSET;7547 }7548 else {7549 this.eagerRefreshThresholdMillis = additionalOptions7550 .eagerRefreshThresholdMillis;7551 }7552 this.forceRefreshOnFailure = !!(additionalOptions === null || additionalOptions === void 0 ? void 0 : additionalOptions.forceRefreshOnFailure);7553 this.quotaProjectId = quotaProjectId;7554 }7555 /**7556 * Provides a mechanism to inject Downscoped access tokens directly.7557 * The expiry_date field is required to facilitate determination of the token7558 * expiration which would make it easier for the token consumer to handle.7559 * @param credentials The Credentials object to set on the current client.7560 */7561 setCredentials(credentials) {7562 if (!credentials.expiry_date) {7563 throw new Error('The access token expiry_date field is missing in the provided ' +7564 'credentials.');7565 }7566 super.setCredentials(credentials);7567 this.cachedDownscopedAccessToken = credentials;7568 }7569 async getAccessToken() {7570 // If the cached access token is unavailable or expired, force refresh.7571 // The Downscoped access token will be returned in7572 // DownscopedAccessTokenResponse format.7573 if (!this.cachedDownscopedAccessToken ||7574 this.isExpired(this.cachedDownscopedAccessToken)) {7575 await this.refreshAccessTokenAsync();7576 }7577 // Return Downscoped access token in DownscopedAccessTokenResponse format.7578 return {7579 token: this.cachedDownscopedAccessToken.access_token,7580 expirationTime: this.cachedDownscopedAccessToken.expiry_date,7581 res: this.cachedDownscopedAccessToken.res,7582 };7583 }7584 /**7585 * The main authentication interface. It takes an optional url which when7586 * present is the endpoint being accessed, and returns a Promise which7587 * resolves with authorization header fields.7588 *7589 * The result has the form:7590 * { Authorization: 'Bearer <access_token_value>' }7591 */7592 async getRequestHeaders() {7593 const accessTokenResponse = await this.getAccessToken();7594 const headers = {7595 Authorization: `Bearer ${accessTokenResponse.token}`,7596 };7597 return this.addSharedMetadataHeaders(headers);7598 }7599 request(opts, callback) {7600 if (callback) {7601 this.requestAsync(opts).then(r => callback(null, r), e => {7602 return callback(e, e.response);7603 });7604 }7605 else {7606 return this.requestAsync(opts);7607 }7608 }7609 /**7610 * Authenticates the provided HTTP request, processes it and resolves with the7611 * returned response.7612 * @param opts The HTTP request options.7613 * @param retry Whether the current attempt is a retry after a failed attempt.7614 * @return A promise that resolves with the successful response.7615 */7616 async requestAsync(opts, retry = false) {7617 let response;7618 try {7619 const requestHeaders = await this.getRequestHeaders();7620 opts.headers = opts.headers || {};7621 if (requestHeaders && requestHeaders['x-goog-user-project']) {7622 opts.headers['x-goog-user-project'] =7623 requestHeaders['x-goog-user-project'];7624 }7625 if (requestHeaders && requestHeaders.Authorization) {7626 opts.headers.Authorization = requestHeaders.Authorization;7627 }7628 response = await this.transporter.request(opts);7629 }7630 catch (e) {7631 const res = e.response;7632 if (res) {7633 const statusCode = res.status;7634 // Retry the request for metadata if the following criteria are true:7635 // - We haven't already retried. It only makes sense to retry once.7636 // - The response was a 401 or a 4037637 // - The request didn't send a readableStream7638 // - forceRefreshOnFailure is true7639 const isReadableStream = res.config.data instanceof stream.Readable;7640 const isAuthErr = statusCode === 401 || statusCode === 403;7641 if (!retry &&7642 isAuthErr &&7643 !isReadableStream &&7644 this.forceRefreshOnFailure) {7645 await this.refreshAccessTokenAsync();7646 return await this.requestAsync(opts, true);7647 }7648 }7649 throw e;7650 }7651 return response;7652 }7653 /**7654 * Forces token refresh, even if unexpired tokens are currently cached.7655 * GCP access tokens are retrieved from authclient object/source credential.7656 * Then GCP access tokens are exchanged for downscoped access tokens via the7657 * token exchange endpoint.7658 * @return A promise that resolves with the fresh downscoped access token.7659 */7660 async refreshAccessTokenAsync() {7661 var _a;7662 // Retrieve GCP access token from source credential.7663 const subjectToken = (await this.authClient.getAccessToken()).token;7664 // Construct the STS credentials options.7665 const stsCredentialsOptions = {7666 grantType: STS_GRANT_TYPE,7667 requestedTokenType: STS_REQUEST_TOKEN_TYPE,7668 subjectToken: subjectToken,7669 subjectTokenType: STS_SUBJECT_TOKEN_TYPE,7670 };7671 // Exchange the source AuthClient access token for a Downscoped access7672 // token.7673 const stsResponse = await this.stsCredential.exchangeToken(stsCredentialsOptions, undefined, this.credentialAccessBoundary);7674 /**7675 * The STS endpoint will only return the expiration time for the downscoped7676 * access token if the original access token represents a service account.7677 * The downscoped token's expiration time will always match the source7678 * credential expiration. When no expires_in is returned, we can copy the7679 * source credential's expiration time.7680 */7681 const sourceCredExpireDate = ((_a = this.authClient.credentials) === null || _a === void 0 ? void 0 : _a.expiry_date) || null;7682 const expiryDate = stsResponse.expires_in7683 ? new Date().getTime() + stsResponse.expires_in * 10007684 : sourceCredExpireDate;7685 // Save response in cached access token.7686 this.cachedDownscopedAccessToken = {7687 access_token: stsResponse.access_token,7688 expiry_date: expiryDate,7689 res: stsResponse.res,7690 };7691 // Save credentials.7692 this.credentials = {};7693 Object.assign(this.credentials, this.cachedDownscopedAccessToken);7694 delete this.credentials.res;7695 // Trigger tokens event to notify external listeners.7696 this.emit('tokens', {7697 refresh_token: null,7698 expiry_date: this.cachedDownscopedAccessToken.expiry_date,7699 access_token: this.cachedDownscopedAccessToken.access_token,7700 token_type: 'Bearer',7701 id_token: null,7702 });7703 // Return the cached access token.7704 return this.cachedDownscopedAccessToken;7705 }7706 /**7707 * Returns whether the provided credentials are expired or not.7708 * If there is no expiry time, assumes the token is not expired or expiring.7709 * @param downscopedAccessToken The credentials to check for expiration.7710 * @return Whether the credentials are expired or not.7711 */7712 isExpired(downscopedAccessToken) {7713 const now = new Date().getTime();7714 return downscopedAccessToken.expiry_date7715 ? now >=7716 downscopedAccessToken.expiry_date - this.eagerRefreshThresholdMillis7717 : false;7718 }7719}7720exports.DownscopedClient = DownscopedClient;7721//# sourceMappingURL=downscopedclient.js.map7722/***/ }),7723/***/ 1380:7724/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {7725"use strict";7726// Copyright 2018 Google LLC7727//7728// Licensed under the Apache License, Version 2.0 (the "License");7729// you may not use this file except in compliance with the License.7730// You may obtain a copy of the License at7731//7732// http://www.apache.org/licenses/LICENSE-2.07733//7734// Unless required by applicable law or agreed to in writing, software7735// distributed under the License is distributed on an "AS IS" BASIS,7736// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.7737// See the License for the specific language governing permissions and7738// limitations under the License.7739Object.defineProperty(exports, "__esModule", ({ value: true }));7740exports.getEnv = exports.clear = exports.GCPEnv = void 0;7741const gcpMetadata = __nccwpck_require__(3563);7742var GCPEnv;7743(function (GCPEnv) {7744 GCPEnv["APP_ENGINE"] = "APP_ENGINE";7745 GCPEnv["KUBERNETES_ENGINE"] = "KUBERNETES_ENGINE";7746 GCPEnv["CLOUD_FUNCTIONS"] = "CLOUD_FUNCTIONS";7747 GCPEnv["COMPUTE_ENGINE"] = "COMPUTE_ENGINE";7748 GCPEnv["CLOUD_RUN"] = "CLOUD_RUN";7749 GCPEnv["NONE"] = "NONE";7750})(GCPEnv = exports.GCPEnv || (exports.GCPEnv = {}));7751let envPromise;7752function clear() {7753 envPromise = undefined;7754}7755exports.clear = clear;7756async function getEnv() {7757 if (envPromise) {7758 return envPromise;7759 }7760 envPromise = getEnvMemoized();7761 return envPromise;7762}7763exports.getEnv = getEnv;7764async function getEnvMemoized() {7765 let env = GCPEnv.NONE;7766 if (isAppEngine()) {7767 env = GCPEnv.APP_ENGINE;7768 }7769 else if (isCloudFunction()) {7770 env = GCPEnv.CLOUD_FUNCTIONS;7771 }7772 else if (await isComputeEngine()) {7773 if (await isKubernetesEngine()) {7774 env = GCPEnv.KUBERNETES_ENGINE;7775 }7776 else if (isCloudRun()) {7777 env = GCPEnv.CLOUD_RUN;7778 }7779 else {7780 env = GCPEnv.COMPUTE_ENGINE;7781 }7782 }7783 else {7784 env = GCPEnv.NONE;7785 }7786 return env;7787}7788function isAppEngine() {7789 return !!(process.env.GAE_SERVICE || process.env.GAE_MODULE_NAME);7790}7791function isCloudFunction() {7792 return !!(process.env.FUNCTION_NAME || process.env.FUNCTION_TARGET);7793}7794/**7795 * This check only verifies that the environment is running knative.7796 * This must be run *after* checking for Kubernetes, otherwise it will7797 * return a false positive.7798 */7799function isCloudRun() {7800 return !!process.env.K_CONFIGURATION;7801}7802async function isKubernetesEngine() {7803 try {7804 await gcpMetadata.instance('attributes/cluster-name');7805 return true;7806 }7807 catch (e) {7808 return false;7809 }7810}7811async function isComputeEngine() {7812 return gcpMetadata.isAvailable();7813}7814//# sourceMappingURL=envDetect.js.map7815/***/ }),7816/***/ 8749:7817/***/ ((__unused_webpack_module, exports) => {7818"use strict";7819// Copyright 2022 Google LLC7820//7821// Licensed under the Apache License, Version 2.0 (the "License");7822// you may not use this file except in compliance with the License.7823// You may obtain a copy of the License at7824//7825// http://www.apache.org/licenses/LICENSE-2.07826//7827// Unless required by applicable law or agreed to in writing, software7828// distributed under the License is distributed on an "AS IS" BASIS,7829// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.7830// See the License for the specific language governing permissions and7831// limitations under the License.7832Object.defineProperty(exports, "__esModule", ({ value: true }));7833exports.InvalidSubjectTokenError = exports.InvalidMessageFieldError = exports.InvalidCodeFieldError = exports.InvalidTokenTypeFieldError = exports.InvalidExpirationTimeFieldError = exports.InvalidSuccessFieldError = exports.InvalidVersionFieldError = exports.ExecutableResponseError = exports.ExecutableResponse = void 0;7834const SAML_SUBJECT_TOKEN_TYPE = 'urn:ietf:params:oauth:token-type:saml2';7835const OIDC_SUBJECT_TOKEN_TYPE1 = 'urn:ietf:params:oauth:token-type:id_token';7836const OIDC_SUBJECT_TOKEN_TYPE2 = 'urn:ietf:params:oauth:token-type:jwt';7837/**7838 * Defines the response of a 3rd party executable run by the pluggable auth client.7839 */7840class ExecutableResponse {7841 /**7842 * Instantiates an ExecutableResponse instance using the provided JSON object7843 * from the output of the executable.7844 * @param responseJson Response from a 3rd party executable, loaded from a7845 * run of the executable or a cached output file.7846 */7847 constructor(responseJson) {7848 // Check that the required fields exist in the json response.7849 if (!responseJson.version) {7850 throw new InvalidVersionFieldError("Executable response must contain a 'version' field.");7851 }7852 if (responseJson.success === undefined) {7853 throw new InvalidSuccessFieldError("Executable response must contain a 'success' field.");7854 }7855 this.version = responseJson.version;7856 this.success = responseJson.success;7857 // Validate required fields for a successful response.7858 if (this.success) {7859 this.expirationTime = responseJson.expiration_time;7860 this.tokenType = responseJson.token_type;7861 // Validate token type field.7862 if (this.tokenType !== SAML_SUBJECT_TOKEN_TYPE &&7863 this.tokenType !== OIDC_SUBJECT_TOKEN_TYPE1 &&7864 this.tokenType !== OIDC_SUBJECT_TOKEN_TYPE2) {7865 throw new InvalidTokenTypeFieldError("Executable response must contain a 'token_type' field when successful " +7866 `and it must be one of ${OIDC_SUBJECT_TOKEN_TYPE1}, ${OIDC_SUBJECT_TOKEN_TYPE2}, or ${SAML_SUBJECT_TOKEN_TYPE}.`);7867 }7868 // Validate subject token.7869 if (this.tokenType === SAML_SUBJECT_TOKEN_TYPE) {7870 if (!responseJson.saml_response) {7871 throw new InvalidSubjectTokenError(`Executable response must contain a 'saml_response' field when token_type=${SAML_SUBJECT_TOKEN_TYPE}.`);7872 }7873 this.subjectToken = responseJson.saml_response;7874 }7875 else {7876 if (!responseJson.id_token) {7877 throw new InvalidSubjectTokenError("Executable response must contain a 'id_token' field when " +7878 `token_type=${OIDC_SUBJECT_TOKEN_TYPE1} or ${OIDC_SUBJECT_TOKEN_TYPE2}.`);7879 }7880 this.subjectToken = responseJson.id_token;7881 }7882 }7883 else {7884 // Both code and message must be provided for unsuccessful responses.7885 if (!responseJson.code) {7886 throw new InvalidCodeFieldError("Executable response must contain a 'code' field when unsuccessful.");7887 }7888 if (!responseJson.message) {7889 throw new InvalidMessageFieldError("Executable response must contain a 'message' field when unsuccessful.");7890 }7891 this.errorCode = responseJson.code;7892 this.errorMessage = responseJson.message;7893 }7894 }7895 /**7896 * @return A boolean representing if the response has a valid token. Returns7897 * true when the response was successful and the token is not expired.7898 */7899 isValid() {7900 return !this.isExpired() && this.success;7901 }7902 /**7903 * @return A boolean representing if the response is expired. Returns true if the7904 * provided timeout has passed.7905 */7906 isExpired() {7907 return (this.expirationTime !== undefined &&7908 this.expirationTime < Math.round(Date.now() / 1000));7909 }7910}7911exports.ExecutableResponse = ExecutableResponse;7912/**7913 * An error thrown by the ExecutableResponse class.7914 */7915class ExecutableResponseError extends Error {7916 constructor(message) {7917 super(message);7918 Object.setPrototypeOf(this, new.target.prototype);7919 }7920}7921exports.ExecutableResponseError = ExecutableResponseError;7922/**7923 * An error thrown when the 'version' field in an executable response is missing or invalid.7924 */7925class InvalidVersionFieldError extends ExecutableResponseError {7926}7927exports.InvalidVersionFieldError = InvalidVersionFieldError;7928/**7929 * An error thrown when the 'success' field in an executable response is missing or invalid.7930 */7931class InvalidSuccessFieldError extends ExecutableResponseError {7932}7933exports.InvalidSuccessFieldError = InvalidSuccessFieldError;7934/**7935 * An error thrown when the 'expiration_time' field in an executable response is missing or invalid.7936 */7937class InvalidExpirationTimeFieldError extends ExecutableResponseError {7938}7939exports.InvalidExpirationTimeFieldError = InvalidExpirationTimeFieldError;7940/**7941 * An error thrown when the 'token_type' field in an executable response is missing or invalid.7942 */7943class InvalidTokenTypeFieldError extends ExecutableResponseError {7944}7945exports.InvalidTokenTypeFieldError = InvalidTokenTypeFieldError;7946/**7947 * An error thrown when the 'code' field in an executable response is missing or invalid.7948 */7949class InvalidCodeFieldError extends ExecutableResponseError {7950}7951exports.InvalidCodeFieldError = InvalidCodeFieldError;7952/**7953 * An error thrown when the 'message' field in an executable response is missing or invalid.7954 */7955class InvalidMessageFieldError extends ExecutableResponseError {7956}7957exports.InvalidMessageFieldError = InvalidMessageFieldError;7958/**7959 * An error thrown when the subject token in an executable response is missing or invalid.7960 */7961class InvalidSubjectTokenError extends ExecutableResponseError {7962}7963exports.InvalidSubjectTokenError = InvalidSubjectTokenError;7964//# sourceMappingURL=executable-response.js.map7965/***/ }),7966/***/ 4381:7967/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {7968"use strict";7969// Copyright 2021 Google LLC7970//7971// Licensed under the Apache License, Version 2.0 (the "License");7972// you may not use this file except in compliance with the License.7973// You may obtain a copy of the License at7974//7975// http://www.apache.org/licenses/LICENSE-2.07976//7977// Unless required by applicable law or agreed to in writing, software7978// distributed under the License is distributed on an "AS IS" BASIS,7979// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.7980// See the License for the specific language governing permissions and7981// limitations under the License.7982Object.defineProperty(exports, "__esModule", ({ value: true }));7983exports.ExternalAccountClient = void 0;7984const baseexternalclient_1 = __nccwpck_require__(7391);7985const identitypoolclient_1 = __nccwpck_require__(117);7986const awsclient_1 = __nccwpck_require__(1569);7987const pluggable_auth_client_1 = __nccwpck_require__(4782);7988/**7989 * Dummy class with no constructor. Developers are expected to use fromJSON.7990 */7991class ExternalAccountClient {7992 constructor() {7993 throw new Error('ExternalAccountClients should be initialized via: ' +7994 'ExternalAccountClient.fromJSON(), ' +7995 'directly via explicit constructors, eg. ' +7996 'new AwsClient(options), new IdentityPoolClient(options), new' +7997 'PluggableAuthClientOptions, or via ' +7998 'new GoogleAuth(options).getClient()');7999 }8000 /**8001 * This static method will instantiate the8002 * corresponding type of external account credential depending on the8003 * underlying credential source.8004 * @param options The external account options object typically loaded8005 * from the external account JSON credential file.8006 * @param additionalOptions Optional additional behavior customization8007 * options. These currently customize expiration threshold time and8008 * whether to retry on 401/403 API request errors.8009 * @return A BaseExternalAccountClient instance or null if the options8010 * provided do not correspond to an external account credential.8011 */8012 static fromJSON(options, additionalOptions) {8013 var _a, _b;8014 if (options && options.type === baseexternalclient_1.EXTERNAL_ACCOUNT_TYPE) {8015 if ((_a = options.credential_source) === null || _a === void 0 ? void 0 : _a.environment_id) {8016 return new awsclient_1.AwsClient(options, additionalOptions);8017 }8018 else if ((_b = options.credential_source) === null || _b === void 0 ? void 0 : _b.executable) {8019 return new pluggable_auth_client_1.PluggableAuthClient(options, additionalOptions);8020 }8021 else {8022 return new identitypoolclient_1.IdentityPoolClient(options, additionalOptions);8023 }8024 }8025 else {8026 return null;8027 }8028 }8029}8030exports.ExternalAccountClient = ExternalAccountClient;8031//# sourceMappingURL=externalclient.js.map8032/***/ }),8033/***/ 695:8034/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {8035"use strict";8036// Copyright 2019 Google LLC8037//8038// Licensed under the Apache License, Version 2.0 (the "License");8039// you may not use this file except in compliance with the License.8040// You may obtain a copy of the License at8041//8042// http://www.apache.org/licenses/LICENSE-2.08043//8044// Unless required by applicable law or agreed to in writing, software8045// distributed under the License is distributed on an "AS IS" BASIS,8046// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.8047// See the License for the specific language governing permissions and8048// limitations under the License.8049Object.defineProperty(exports, "__esModule", ({ value: true }));8050exports.GoogleAuth = exports.CLOUD_SDK_CLIENT_ID = void 0;8051const child_process_1 = __nccwpck_require__(2081);8052const fs = __nccwpck_require__(7147);8053const gcpMetadata = __nccwpck_require__(3563);8054const os = __nccwpck_require__(2037);8055const path = __nccwpck_require__(1017);8056const crypto_1 = __nccwpck_require__(8043);8057const transporters_1 = __nccwpck_require__(2649);8058const computeclient_1 = __nccwpck_require__(6875);8059const idtokenclient_1 = __nccwpck_require__(298);8060const envDetect_1 = __nccwpck_require__(1380);8061const jwtclient_1 = __nccwpck_require__(3959);8062const refreshclient_1 = __nccwpck_require__(8790);8063const impersonated_1 = __nccwpck_require__(1103);8064const externalclient_1 = __nccwpck_require__(4381);8065const baseexternalclient_1 = __nccwpck_require__(7391);8066exports.CLOUD_SDK_CLIENT_ID = '764086051850-6qr4p6gpi6hn506pt8ejuq83di341hur.apps.googleusercontent.com';8067const GoogleAuthExceptionMessages = {8068 NO_PROJECT_ID_FOUND: 'Unable to detect a Project Id in the current environment. \n' +8069 'To learn more about authentication and Google APIs, visit: \n' +8070 'https://cloud.google.com/docs/authentication/getting-started',8071};8072class GoogleAuth {8073 constructor(opts) {8074 /**8075 * Caches a value indicating whether the auth layer is running on Google8076 * Compute Engine.8077 * @private8078 */8079 this.checkIsGCE = undefined;8080 // To save the contents of the JSON credential file8081 this.jsonContent = null;8082 this.cachedCredential = null;8083 opts = opts || {};8084 this._cachedProjectId = opts.projectId || null;8085 this.cachedCredential = opts.authClient || null;8086 this.keyFilename = opts.keyFilename || opts.keyFile;8087 this.scopes = opts.scopes;8088 this.jsonContent = opts.credentials || null;8089 this.clientOptions = opts.clientOptions;8090 }8091 // Note: this properly is only public to satisify unit tests.8092 // https://github.com/Microsoft/TypeScript/issues/52288093 get isGCE() {8094 return this.checkIsGCE;8095 }8096 // GAPIC client libraries should always use self-signed JWTs. The following8097 // variables are set on the JWT client in order to indicate the type of library,8098 // and sign the JWT with the correct audience and scopes (if not supplied).8099 setGapicJWTValues(client) {8100 client.defaultServicePath = this.defaultServicePath;8101 client.useJWTAccessWithScope = this.useJWTAccessWithScope;8102 client.defaultScopes = this.defaultScopes;8103 }8104 getProjectId(callback) {8105 if (callback) {8106 this.getProjectIdAsync().then(r => callback(null, r), callback);8107 }8108 else {8109 return this.getProjectIdAsync();8110 }8111 }8112 /**8113 * A temporary method for internal `getProjectId` usages where `null` is8114 * acceptable. In a future major release, `getProjectId` should return `null`8115 * (as the `Promise<string | null>` base signature describes) and this private8116 * method should be removed.8117 *8118 * @returns Promise that resolves with project id (or `null`)8119 */8120 async getProjectIdOptional() {8121 try {8122 return await this.getProjectId();8123 }8124 catch (e) {8125 if (e instanceof Error &&8126 e.message === GoogleAuthExceptionMessages.NO_PROJECT_ID_FOUND) {8127 return null;8128 }8129 else {8130 throw e;8131 }8132 }8133 }8134 /*8135 * A private method for finding and caching a projectId.8136 *8137 * Supports environments in order of precedence:8138 * - GCLOUD_PROJECT or GOOGLE_CLOUD_PROJECT environment variable8139 * - GOOGLE_APPLICATION_CREDENTIALS JSON file8140 * - Cloud SDK: `gcloud config config-helper --format json`8141 * - GCE project ID from metadata server8142 *8143 * @returns projectId8144 */8145 async findAndCacheProjectId() {8146 let projectId = null;8147 projectId || (projectId = await this.getProductionProjectId());8148 projectId || (projectId = await this.getFileProjectId());8149 projectId || (projectId = await this.getDefaultServiceProjectId());8150 projectId || (projectId = await this.getGCEProjectId());8151 projectId || (projectId = await this.getExternalAccountClientProjectId());8152 if (projectId) {8153 this._cachedProjectId = projectId;8154 return projectId;8155 }8156 else {8157 throw new Error(GoogleAuthExceptionMessages.NO_PROJECT_ID_FOUND);8158 }8159 }8160 async getProjectIdAsync() {8161 if (this._cachedProjectId) {8162 return this._cachedProjectId;8163 }8164 if (!this._findProjectIdPromise) {8165 this._findProjectIdPromise = this.findAndCacheProjectId();8166 }8167 return this._findProjectIdPromise;8168 }8169 /**8170 * @returns Any scopes (user-specified or default scopes specified by the8171 * client library) that need to be set on the current Auth client.8172 */8173 getAnyScopes() {8174 return this.scopes || this.defaultScopes;8175 }8176 getApplicationDefault(optionsOrCallback = {}, callback) {8177 let options;8178 if (typeof optionsOrCallback === 'function') {8179 callback = optionsOrCallback;8180 }8181 else {8182 options = optionsOrCallback;8183 }8184 if (callback) {8185 this.getApplicationDefaultAsync(options).then(r => callback(null, r.credential, r.projectId), callback);8186 }8187 else {8188 return this.getApplicationDefaultAsync(options);8189 }8190 }8191 async getApplicationDefaultAsync(options = {}) {8192 // If we've already got a cached credential, just return it.8193 if (this.cachedCredential) {8194 return {8195 credential: this.cachedCredential,8196 projectId: await this.getProjectIdOptional(),8197 };8198 }8199 let credential;8200 let projectId;8201 // Check for the existence of a local environment variable pointing to the8202 // location of the credential file. This is typically used in local8203 // developer scenarios.8204 credential =8205 await this._tryGetApplicationCredentialsFromEnvironmentVariable(options);8206 if (credential) {8207 if (credential instanceof jwtclient_1.JWT) {8208 credential.scopes = this.scopes;8209 }8210 else if (credential instanceof baseexternalclient_1.BaseExternalAccountClient) {8211 credential.scopes = this.getAnyScopes();8212 }8213 this.cachedCredential = credential;8214 projectId = await this.getProjectIdOptional();8215 return { credential, projectId };8216 }8217 // Look in the well-known credential file location.8218 credential = await this._tryGetApplicationCredentialsFromWellKnownFile(options);8219 if (credential) {8220 if (credential instanceof jwtclient_1.JWT) {8221 credential.scopes = this.scopes;8222 }8223 else if (credential instanceof baseexternalclient_1.BaseExternalAccountClient) {8224 credential.scopes = this.getAnyScopes();8225 }8226 this.cachedCredential = credential;8227 projectId = await this.getProjectIdOptional();8228 return { credential, projectId };8229 }8230 // Determine if we're running on GCE.8231 let isGCE;8232 try {8233 isGCE = await this._checkIsGCE();8234 }8235 catch (e) {8236 if (e instanceof Error) {8237 e.message = `Unexpected error determining execution environment: ${e.message}`;8238 }8239 throw e;8240 }8241 if (!isGCE) {8242 // We failed to find the default credentials. Bail out with an error.8243 throw new Error('Could not load the default credentials. Browse to https://cloud.google.com/docs/authentication/getting-started for more information.');8244 }8245 // For GCE, just return a default ComputeClient. It will take care of8246 // the rest.8247 options.scopes = this.getAnyScopes();8248 this.cachedCredential = new computeclient_1.Compute(options);8249 projectId = await this.getProjectIdOptional();8250 return { projectId, credential: this.cachedCredential };8251 }8252 /**8253 * Determines whether the auth layer is running on Google Compute Engine.8254 * @returns A promise that resolves with the boolean.8255 * @api private8256 */8257 async _checkIsGCE() {8258 if (this.checkIsGCE === undefined) {8259 this.checkIsGCE = await gcpMetadata.isAvailable();8260 }8261 return this.checkIsGCE;8262 }8263 /**8264 * Attempts to load default credentials from the environment variable path..8265 * @returns Promise that resolves with the OAuth2Client or null.8266 * @api private8267 */8268 async _tryGetApplicationCredentialsFromEnvironmentVariable(options) {8269 const credentialsPath = process.env['GOOGLE_APPLICATION_CREDENTIALS'] ||8270 process.env['google_application_credentials'];8271 if (!credentialsPath || credentialsPath.length === 0) {8272 return null;8273 }8274 try {8275 return this._getApplicationCredentialsFromFilePath(credentialsPath, options);8276 }8277 catch (e) {8278 if (e instanceof Error) {8279 e.message = `Unable to read the credential file specified by the GOOGLE_APPLICATION_CREDENTIALS environment variable: ${e.message}`;8280 }8281 throw e;8282 }8283 }8284 /**8285 * Attempts to load default credentials from a well-known file location8286 * @return Promise that resolves with the OAuth2Client or null.8287 * @api private8288 */8289 async _tryGetApplicationCredentialsFromWellKnownFile(options) {8290 // First, figure out the location of the file, depending upon the OS type.8291 let location = null;8292 if (this._isWindows()) {8293 // Windows8294 location = process.env['APPDATA'];8295 }8296 else {8297 // Linux or Mac8298 const home = process.env['HOME'];8299 if (home) {8300 location = path.join(home, '.config');8301 }8302 }8303 // If we found the root path, expand it.8304 if (location) {8305 location = path.join(location, 'gcloud', 'application_default_credentials.json');8306 if (!fs.existsSync(location)) {8307 location = null;8308 }8309 }8310 // The file does not exist.8311 if (!location) {8312 return null;8313 }8314 // The file seems to exist. Try to use it.8315 const client = await this._getApplicationCredentialsFromFilePath(location, options);8316 return client;8317 }8318 /**8319 * Attempts to load default credentials from a file at the given path..8320 * @param filePath The path to the file to read.8321 * @returns Promise that resolves with the OAuth2Client8322 * @api private8323 */8324 async _getApplicationCredentialsFromFilePath(filePath, options = {}) {8325 // Make sure the path looks like a string.8326 if (!filePath || filePath.length === 0) {8327 throw new Error('The file path is invalid.');8328 }8329 // Make sure there is a file at the path. lstatSync will throw if there is8330 // nothing there.8331 try {8332 // Resolve path to actual file in case of symlink. Expect a thrown error8333 // if not resolvable.8334 filePath = fs.realpathSync(filePath);8335 if (!fs.lstatSync(filePath).isFile()) {8336 throw new Error();8337 }8338 }8339 catch (err) {8340 if (err instanceof Error) {8341 err.message = `The file at ${filePath} does not exist, or it is not a file. ${err.message}`;8342 }8343 throw err;8344 }8345 // Now open a read stream on the file, and parse it.8346 const readStream = fs.createReadStream(filePath);8347 return this.fromStream(readStream, options);8348 }8349 /**8350 * Create a credentials instance using a given impersonated input options.8351 * @param json The impersonated input object.8352 * @returns JWT or UserRefresh Client with data8353 */8354 fromImpersonatedJSON(json) {8355 var _a, _b, _c, _d;8356 if (!json) {8357 throw new Error('Must pass in a JSON object containing an impersonated refresh token');8358 }8359 if (json.type !== impersonated_1.IMPERSONATED_ACCOUNT_TYPE) {8360 throw new Error(`The incoming JSON object does not have the "${impersonated_1.IMPERSONATED_ACCOUNT_TYPE}" type`);8361 }8362 if (!json.source_credentials) {8363 throw new Error('The incoming JSON object does not contain a source_credentials field');8364 }8365 if (!json.service_account_impersonation_url) {8366 throw new Error('The incoming JSON object does not contain a service_account_impersonation_url field');8367 }8368 // Create source client for impersonation8369 const sourceClient = new refreshclient_1.UserRefreshClient(json.source_credentials.client_id, json.source_credentials.client_secret, json.source_credentials.refresh_token);8370 // Extreact service account from service_account_impersonation_url8371 const targetPrincipal = (_b = (_a = /(?<target>[^/]+):generateAccessToken$/.exec(json.service_account_impersonation_url)) === null || _a === void 0 ? void 0 : _a.groups) === null || _b === void 0 ? void 0 : _b.target;8372 if (!targetPrincipal) {8373 throw new RangeError(`Cannot extract target principal from ${json.service_account_impersonation_url}`);8374 }8375 const targetScopes = (_c = this.getAnyScopes()) !== null && _c !== void 0 ? _c : [];8376 const client = new impersonated_1.Impersonated({8377 delegates: (_d = json.delegates) !== null && _d !== void 0 ? _d : [],8378 sourceClient: sourceClient,8379 targetPrincipal: targetPrincipal,8380 targetScopes: Array.isArray(targetScopes) ? targetScopes : [targetScopes],8381 });8382 return client;8383 }8384 /**8385 * Create a credentials instance using the given input options.8386 * @param json The input object.8387 * @param options The JWT or UserRefresh options for the client8388 * @returns JWT or UserRefresh Client with data8389 */8390 fromJSON(json, options) {8391 let client;8392 if (!json) {8393 throw new Error('Must pass in a JSON object containing the Google auth settings.');8394 }8395 options = options || {};8396 if (json.type === 'authorized_user') {8397 client = new refreshclient_1.UserRefreshClient(options);8398 client.fromJSON(json);8399 }8400 else if (json.type === impersonated_1.IMPERSONATED_ACCOUNT_TYPE) {8401 client = this.fromImpersonatedJSON(json);8402 }8403 else if (json.type === baseexternalclient_1.EXTERNAL_ACCOUNT_TYPE) {8404 client = externalclient_1.ExternalAccountClient.fromJSON(json, options);8405 client.scopes = this.getAnyScopes();8406 }8407 else {8408 options.scopes = this.scopes;8409 client = new jwtclient_1.JWT(options);8410 this.setGapicJWTValues(client);8411 client.fromJSON(json);8412 }8413 return client;8414 }8415 /**8416 * Return a JWT or UserRefreshClient from JavaScript object, caching both the8417 * object used to instantiate and the client.8418 * @param json The input object.8419 * @param options The JWT or UserRefresh options for the client8420 * @returns JWT or UserRefresh Client with data8421 */8422 _cacheClientFromJSON(json, options) {8423 let client;8424 // create either a UserRefreshClient or JWT client.8425 options = options || {};8426 if (json.type === 'authorized_user') {8427 client = new refreshclient_1.UserRefreshClient(options);8428 client.fromJSON(json);8429 }8430 else if (json.type === impersonated_1.IMPERSONATED_ACCOUNT_TYPE) {8431 client = this.fromImpersonatedJSON(json);8432 }8433 else if (json.type === baseexternalclient_1.EXTERNAL_ACCOUNT_TYPE) {8434 client = externalclient_1.ExternalAccountClient.fromJSON(json, options);8435 client.scopes = this.getAnyScopes();8436 }8437 else {8438 options.scopes = this.scopes;8439 client = new jwtclient_1.JWT(options);8440 this.setGapicJWTValues(client);8441 client.fromJSON(json);8442 }8443 // cache both raw data used to instantiate client and client itself.8444 this.jsonContent = json;8445 this.cachedCredential = client;8446 return client;8447 }8448 fromStream(inputStream, optionsOrCallback = {}, callback) {8449 let options = {};8450 if (typeof optionsOrCallback === 'function') {8451 callback = optionsOrCallback;8452 }8453 else {8454 options = optionsOrCallback;8455 }8456 if (callback) {8457 this.fromStreamAsync(inputStream, options).then(r => callback(null, r), callback);8458 }8459 else {8460 return this.fromStreamAsync(inputStream, options);8461 }8462 }8463 fromStreamAsync(inputStream, options) {8464 return new Promise((resolve, reject) => {8465 if (!inputStream) {8466 throw new Error('Must pass in a stream containing the Google auth settings.');8467 }8468 let s = '';8469 inputStream8470 .setEncoding('utf8')8471 .on('error', reject)8472 .on('data', chunk => (s += chunk))8473 .on('end', () => {8474 try {8475 try {8476 const data = JSON.parse(s);8477 const r = this._cacheClientFromJSON(data, options);8478 return resolve(r);8479 }8480 catch (err) {8481 // If we failed parsing this.keyFileName, assume that it8482 // is a PEM or p12 certificate:8483 if (!this.keyFilename)8484 throw err;8485 const client = new jwtclient_1.JWT({8486 ...this.clientOptions,8487 keyFile: this.keyFilename,8488 });8489 this.cachedCredential = client;8490 this.setGapicJWTValues(client);8491 return resolve(client);8492 }8493 }8494 catch (err) {8495 return reject(err);8496 }8497 });8498 });8499 }8500 /**8501 * Create a credentials instance using the given API key string.8502 * @param apiKey The API key string8503 * @param options An optional options object.8504 * @returns A JWT loaded from the key8505 */8506 fromAPIKey(apiKey, options) {8507 options = options || {};8508 const client = new jwtclient_1.JWT(options);8509 client.fromAPIKey(apiKey);8510 return client;8511 }8512 /**8513 * Determines whether the current operating system is Windows.8514 * @api private8515 */8516 _isWindows() {8517 const sys = os.platform();8518 if (sys && sys.length >= 3) {8519 if (sys.substring(0, 3).toLowerCase() === 'win') {8520 return true;8521 }8522 }8523 return false;8524 }8525 /**8526 * Run the Google Cloud SDK command that prints the default project ID8527 */8528 async getDefaultServiceProjectId() {8529 return new Promise(resolve => {8530 (0, child_process_1.exec)('gcloud config config-helper --format json', (err, stdout) => {8531 if (!err && stdout) {8532 try {8533 const projectId = JSON.parse(stdout).configuration.properties.core.project;8534 resolve(projectId);8535 return;8536 }8537 catch (e) {8538 // ignore errors8539 }8540 }8541 resolve(null);8542 });8543 });8544 }8545 /**8546 * Loads the project id from environment variables.8547 * @api private8548 */8549 getProductionProjectId() {8550 return (process.env['GCLOUD_PROJECT'] ||8551 process.env['GOOGLE_CLOUD_PROJECT'] ||8552 process.env['gcloud_project'] ||8553 process.env['google_cloud_project']);8554 }8555 /**8556 * Loads the project id from the GOOGLE_APPLICATION_CREDENTIALS json file.8557 * @api private8558 */8559 async getFileProjectId() {8560 if (this.cachedCredential) {8561 // Try to read the project ID from the cached credentials file8562 return this.cachedCredential.projectId;8563 }8564 // Ensure the projectId is loaded from the keyFile if available.8565 if (this.keyFilename) {8566 const creds = await this.getClient();8567 if (creds && creds.projectId) {8568 return creds.projectId;8569 }8570 }8571 // Try to load a credentials file and read its project ID8572 const r = await this._tryGetApplicationCredentialsFromEnvironmentVariable();8573 if (r) {8574 return r.projectId;8575 }8576 else {8577 return null;8578 }8579 }8580 /**8581 * Gets the project ID from external account client if available.8582 */8583 async getExternalAccountClientProjectId() {8584 if (!this.jsonContent || this.jsonContent.type !== baseexternalclient_1.EXTERNAL_ACCOUNT_TYPE) {8585 return null;8586 }8587 const creds = await this.getClient();8588 // Do not suppress the underlying error, as the error could contain helpful8589 // information for debugging and fixing. This is especially true for8590 // external account creds as in order to get the project ID, the following8591 // operations have to succeed:8592 // 1. Valid credentials file should be supplied.8593 // 2. Ability to retrieve access tokens from STS token exchange API.8594 // 3. Ability to exchange for service account impersonated credentials (if8595 // enabled).8596 // 4. Ability to get project info using the access token from step 2 or 3.8597 // Without surfacing the error, it is harder for developers to determine8598 // which step went wrong.8599 return await creds.getProjectId();8600 }8601 /**8602 * Gets the Compute Engine project ID if it can be inferred.8603 */8604 async getGCEProjectId() {8605 try {8606 const r = await gcpMetadata.project('project-id');8607 return r;8608 }8609 catch (e) {8610 // Ignore any errors8611 return null;8612 }8613 }8614 getCredentials(callback) {8615 if (callback) {8616 this.getCredentialsAsync().then(r => callback(null, r), callback);8617 }8618 else {8619 return this.getCredentialsAsync();8620 }8621 }8622 async getCredentialsAsync() {8623 const client = await this.getClient();8624 if (client instanceof baseexternalclient_1.BaseExternalAccountClient) {8625 const serviceAccountEmail = client.getServiceAccountEmail();8626 if (serviceAccountEmail) {8627 return { client_email: serviceAccountEmail };8628 }8629 }8630 if (this.jsonContent) {8631 const credential = {8632 client_email: this.jsonContent.client_email,8633 private_key: this.jsonContent.private_key,8634 };8635 return credential;8636 }8637 const isGCE = await this._checkIsGCE();8638 if (!isGCE) {8639 throw new Error('Unknown error.');8640 }8641 // For GCE, return the service account details from the metadata server8642 // NOTE: The trailing '/' at the end of service-accounts/ is very important!8643 // The GCF metadata server doesn't respect querystring params if this / is8644 // not included.8645 const data = await gcpMetadata.instance({8646 property: 'service-accounts/',8647 params: { recursive: 'true' },8648 });8649 if (!data || !data.default || !data.default.email) {8650 throw new Error('Failure from metadata server.');8651 }8652 return { client_email: data.default.email };8653 }8654 /**8655 * Automatically obtain a client based on the provided configuration. If no8656 * options were passed, use Application Default Credentials.8657 */8658 async getClient() {8659 if (!this.cachedCredential) {8660 if (this.jsonContent) {8661 this._cacheClientFromJSON(this.jsonContent, this.clientOptions);8662 }8663 else if (this.keyFilename) {8664 const filePath = path.resolve(this.keyFilename);8665 const stream = fs.createReadStream(filePath);8666 await this.fromStreamAsync(stream, this.clientOptions);8667 }8668 else {8669 await this.getApplicationDefaultAsync(this.clientOptions);8670 }8671 }8672 return this.cachedCredential;8673 }8674 /**8675 * Creates a client which will fetch an ID token for authorization.8676 * @param targetAudience the audience for the fetched ID token.8677 * @returns IdTokenClient for making HTTP calls authenticated with ID tokens.8678 */8679 async getIdTokenClient(targetAudience) {8680 const client = await this.getClient();8681 if (!('fetchIdToken' in client)) {8682 throw new Error('Cannot fetch ID token in this environment, use GCE or set the GOOGLE_APPLICATION_CREDENTIALS environment variable to a service account credentials JSON file.');8683 }8684 return new idtokenclient_1.IdTokenClient({ targetAudience, idTokenProvider: client });8685 }8686 /**8687 * Automatically obtain application default credentials, and return8688 * an access token for making requests.8689 */8690 async getAccessToken() {8691 const client = await this.getClient();8692 return (await client.getAccessToken()).token;8693 }8694 /**8695 * Obtain the HTTP headers that will provide authorization for a given8696 * request.8697 */8698 async getRequestHeaders(url) {8699 const client = await this.getClient();8700 return client.getRequestHeaders(url);8701 }8702 /**8703 * Obtain credentials for a request, then attach the appropriate headers to8704 * the request options.8705 * @param opts Axios or Request options on which to attach the headers8706 */8707 async authorizeRequest(opts) {8708 opts = opts || {};8709 const url = opts.url || opts.uri;8710 const client = await this.getClient();8711 const headers = await client.getRequestHeaders(url);8712 opts.headers = Object.assign(opts.headers || {}, headers);8713 return opts;8714 }8715 /**8716 * Automatically obtain application default credentials, and make an8717 * HTTP request using the given options.8718 * @param opts Axios request options for the HTTP request.8719 */8720 // eslint-disable-next-line @typescript-eslint/no-explicit-any8721 async request(opts) {8722 const client = await this.getClient();8723 return client.request(opts);8724 }8725 /**8726 * Determine the compute environment in which the code is running.8727 */8728 getEnv() {8729 return (0, envDetect_1.getEnv)();8730 }8731 /**8732 * Sign the given data with the current private key, or go out8733 * to the IAM API to sign it.8734 * @param data The data to be signed.8735 */8736 async sign(data) {8737 const client = await this.getClient();8738 const crypto = (0, crypto_1.createCrypto)();8739 if (client instanceof jwtclient_1.JWT && client.key) {8740 const sign = await crypto.sign(client.key, data);8741 return sign;8742 }8743 const creds = await this.getCredentials();8744 if (!creds.client_email) {8745 throw new Error('Cannot sign data without `client_email`.');8746 }8747 return this.signBlob(crypto, creds.client_email, data);8748 }8749 async signBlob(crypto, emailOrUniqueId, data) {8750 const url = 'https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/' +8751 `${emailOrUniqueId}:signBlob`;8752 const res = await this.request({8753 method: 'POST',8754 url,8755 data: {8756 payload: crypto.encodeBase64StringUtf8(data),8757 },8758 });8759 return res.data.signedBlob;8760 }8761}8762exports.GoogleAuth = GoogleAuth;8763/**8764 * Export DefaultTransporter as a static property of the class.8765 */8766GoogleAuth.DefaultTransporter = transporters_1.DefaultTransporter;8767//# sourceMappingURL=googleauth.js.map8768/***/ }),8769/***/ 9735:8770/***/ ((__unused_webpack_module, exports) => {8771"use strict";8772// Copyright 2014 Google LLC8773//8774// Licensed under the Apache License, Version 2.0 (the "License");8775// you may not use this file except in compliance with the License.8776// You may obtain a copy of the License at8777//8778// http://www.apache.org/licenses/LICENSE-2.08779//8780// Unless required by applicable law or agreed to in writing, software8781// distributed under the License is distributed on an "AS IS" BASIS,8782// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.8783// See the License for the specific language governing permissions and8784// limitations under the License.8785Object.defineProperty(exports, "__esModule", ({ value: true }));8786exports.IAMAuth = void 0;8787class IAMAuth {8788 /**8789 * IAM credentials.8790 *8791 * @param selector the iam authority selector8792 * @param token the token8793 * @constructor8794 */8795 constructor(selector, token) {8796 this.selector = selector;8797 this.token = token;8798 this.selector = selector;8799 this.token = token;8800 }8801 /**8802 * Acquire the HTTP headers required to make an authenticated request.8803 */8804 getRequestHeaders() {8805 return {8806 'x-goog-iam-authority-selector': this.selector,8807 'x-goog-iam-authorization-token': this.token,8808 };8809 }8810}8811exports.IAMAuth = IAMAuth;8812//# sourceMappingURL=iam.js.map8813/***/ }),8814/***/ 117:8815/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {8816"use strict";8817// Copyright 2021 Google LLC8818//8819// Licensed under the Apache License, Version 2.0 (the "License");8820// you may not use this file except in compliance with the License.8821// You may obtain a copy of the License at8822//8823// http://www.apache.org/licenses/LICENSE-2.08824//8825// Unless required by applicable law or agreed to in writing, software8826// distributed under the License is distributed on an "AS IS" BASIS,8827// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.8828// See the License for the specific language governing permissions and8829// limitations under the License.8830var _a, _b, _c;8831Object.defineProperty(exports, "__esModule", ({ value: true }));8832exports.IdentityPoolClient = void 0;8833const fs = __nccwpck_require__(7147);8834const util_1 = __nccwpck_require__(3837);8835const baseexternalclient_1 = __nccwpck_require__(7391);8836// fs.readfile is undefined in browser karma tests causing8837// `npm run browser-test` to fail as test.oauth2.ts imports this file via8838// src/index.ts.8839// Fallback to void function to avoid promisify throwing a TypeError.8840const readFile = (0, util_1.promisify)((_a = fs.readFile) !== null && _a !== void 0 ? _a : (() => { }));8841const realpath = (0, util_1.promisify)((_b = fs.realpath) !== null && _b !== void 0 ? _b : (() => { }));8842const lstat = (0, util_1.promisify)((_c = fs.lstat) !== null && _c !== void 0 ? _c : (() => { }));8843/**8844 * Defines the Url-sourced and file-sourced external account clients mainly8845 * used for K8s and Azure workloads.8846 */8847class IdentityPoolClient extends baseexternalclient_1.BaseExternalAccountClient {8848 /**8849 * Instantiate an IdentityPoolClient instance using the provided JSON8850 * object loaded from an external account credentials file.8851 * An error is thrown if the credential is not a valid file-sourced or8852 * url-sourced credential or a workforce pool user project is provided8853 * with a non workforce audience.8854 * @param options The external account options object typically loaded8855 * from the external account JSON credential file.8856 * @param additionalOptions Optional additional behavior customization8857 * options. These currently customize expiration threshold time and8858 * whether to retry on 401/403 API request errors.8859 */8860 constructor(options, additionalOptions) {8861 var _a, _b;8862 super(options, additionalOptions);8863 this.file = options.credential_source.file;8864 this.url = options.credential_source.url;8865 this.headers = options.credential_source.headers;8866 if (!this.file && !this.url) {8867 throw new Error('No valid Identity Pool "credential_source" provided');8868 }8869 // Text is the default format type.8870 this.formatType = ((_a = options.credential_source.format) === null || _a === void 0 ? void 0 : _a.type) || 'text';8871 this.formatSubjectTokenFieldName =8872 (_b = options.credential_source.format) === null || _b === void 0 ? void 0 : _b.subject_token_field_name;8873 if (this.formatType !== 'json' && this.formatType !== 'text') {8874 throw new Error(`Invalid credential_source format "${this.formatType}"`);8875 }8876 if (this.formatType === 'json' && !this.formatSubjectTokenFieldName) {8877 throw new Error('Missing subject_token_field_name for JSON credential_source format');8878 }8879 }8880 /**8881 * Triggered when a external subject token is needed to be exchanged for a GCP8882 * access token via GCP STS endpoint.8883 * This uses the `options.credential_source` object to figure out how8884 * to retrieve the token using the current environment. In this case,8885 * this either retrieves the local credential from a file location (k8s8886 * workload) or by sending a GET request to a local metadata server (Azure8887 * workloads).8888 * @return A promise that resolves with the external subject token.8889 */8890 async retrieveSubjectToken() {8891 if (this.file) {8892 return await this.getTokenFromFile(this.file, this.formatType, this.formatSubjectTokenFieldName);8893 }8894 return await this.getTokenFromUrl(this.url, this.formatType, this.formatSubjectTokenFieldName, this.headers);8895 }8896 /**8897 * Looks up the external subject token in the file path provided and8898 * resolves with that token.8899 * @param file The file path where the external credential is located.8900 * @param formatType The token file or URL response type (JSON or text).8901 * @param formatSubjectTokenFieldName For JSON response types, this is the8902 * subject_token field name. For Azure, this is access_token. For text8903 * response types, this is ignored.8904 * @return A promise that resolves with the external subject token.8905 */8906 async getTokenFromFile(filePath, formatType, formatSubjectTokenFieldName) {8907 // Make sure there is a file at the path. lstatSync will throw if there is8908 // nothing there.8909 try {8910 // Resolve path to actual file in case of symlink. Expect a thrown error8911 // if not resolvable.8912 filePath = await realpath(filePath);8913 if (!(await lstat(filePath)).isFile()) {8914 throw new Error();8915 }8916 }8917 catch (err) {8918 if (err instanceof Error) {8919 err.message = `The file at ${filePath} does not exist, or it is not a file. ${err.message}`;8920 }8921 throw err;8922 }8923 let subjectToken;8924 const rawText = await readFile(filePath, { encoding: 'utf8' });8925 if (formatType === 'text') {8926 subjectToken = rawText;8927 }8928 else if (formatType === 'json' && formatSubjectTokenFieldName) {8929 const json = JSON.parse(rawText);8930 subjectToken = json[formatSubjectTokenFieldName];8931 }8932 if (!subjectToken) {8933 throw new Error('Unable to parse the subject_token from the credential_source file');8934 }8935 return subjectToken;8936 }8937 /**8938 * Sends a GET request to the URL provided and resolves with the returned8939 * external subject token.8940 * @param url The URL to call to retrieve the subject token. This is typically8941 * a local metadata server.8942 * @param formatType The token file or URL response type (JSON or text).8943 * @param formatSubjectTokenFieldName For JSON response types, this is the8944 * subject_token field name. For Azure, this is access_token. For text8945 * response types, this is ignored.8946 * @param headers The optional additional headers to send with the request to8947 * the metadata server url.8948 * @return A promise that resolves with the external subject token.8949 */8950 async getTokenFromUrl(url, formatType, formatSubjectTokenFieldName, headers) {8951 const opts = {8952 url,8953 method: 'GET',8954 headers,8955 responseType: formatType,8956 };8957 let subjectToken;8958 if (formatType === 'text') {8959 const response = await this.transporter.request(opts);8960 subjectToken = response.data;8961 }8962 else if (formatType === 'json' && formatSubjectTokenFieldName) {8963 const response = await this.transporter.request(opts);8964 subjectToken = response.data[formatSubjectTokenFieldName];8965 }8966 if (!subjectToken) {8967 throw new Error('Unable to parse the subject_token from the credential_source URL');8968 }8969 return subjectToken;8970 }8971}8972exports.IdentityPoolClient = IdentityPoolClient;8973//# sourceMappingURL=identitypoolclient.js.map8974/***/ }),8975/***/ 298:8976/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {8977"use strict";8978// Copyright 2020 Google LLC8979//8980// Licensed under the Apache License, Version 2.0 (the "License");8981// you may not use this file except in compliance with the License.8982// You may obtain a copy of the License at8983//8984// http://www.apache.org/licenses/LICENSE-2.08985//8986// Unless required by applicable law or agreed to in writing, software8987// distributed under the License is distributed on an "AS IS" BASIS,8988// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.8989// See the License for the specific language governing permissions and8990// limitations under the License.8991Object.defineProperty(exports, "__esModule", ({ value: true }));8992exports.IdTokenClient = void 0;8993const oauth2client_1 = __nccwpck_require__(3936);8994class IdTokenClient extends oauth2client_1.OAuth2Client {8995 /**8996 * Google ID Token client8997 *8998 * Retrieve access token from the metadata server.8999 * See: https://developers.google.com/compute/docs/authentication9000 */9001 constructor(options) {9002 super();9003 this.targetAudience = options.targetAudience;9004 this.idTokenProvider = options.idTokenProvider;9005 }9006 async getRequestMetadataAsync(9007 // eslint-disable-next-line @typescript-eslint/no-unused-vars9008 url) {9009 if (!this.credentials.id_token ||9010 (this.credentials.expiry_date || 0) < Date.now()) {9011 const idToken = await this.idTokenProvider.fetchIdToken(this.targetAudience);9012 this.credentials = {9013 id_token: idToken,9014 expiry_date: this.getIdTokenExpiryDate(idToken),9015 };9016 }9017 const headers = {9018 Authorization: 'Bearer ' + this.credentials.id_token,9019 };9020 return { headers };9021 }9022 getIdTokenExpiryDate(idToken) {9023 const payloadB64 = idToken.split('.')[1];9024 if (payloadB64) {9025 const payload = JSON.parse(Buffer.from(payloadB64, 'base64').toString('ascii'));9026 return payload.exp * 1000;9027 }9028 }9029}9030exports.IdTokenClient = IdTokenClient;9031//# sourceMappingURL=idtokenclient.js.map9032/***/ }),9033/***/ 1103:9034/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {9035"use strict";9036/**9037 * Copyright 2021 Google LLC9038 *9039 * Licensed under the Apache License, Version 2.0 (the "License");9040 * you may not use this file except in compliance with the License.9041 * You may obtain a copy of the License at9042 *9043 * http://www.apache.org/licenses/LICENSE-2.09044 *9045 * Unless required by applicable law or agreed to in writing, software9046 * distributed under the License is distributed on an "AS IS" BASIS,9047 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.9048 * See the License for the specific language governing permissions and9049 * limitations under the License.9050 */9051Object.defineProperty(exports, "__esModule", ({ value: true }));9052exports.Impersonated = exports.IMPERSONATED_ACCOUNT_TYPE = void 0;9053const oauth2client_1 = __nccwpck_require__(3936);9054const gaxios_1 = __nccwpck_require__(9555);9055exports.IMPERSONATED_ACCOUNT_TYPE = 'impersonated_service_account';9056class Impersonated extends oauth2client_1.OAuth2Client {9057 /**9058 * Impersonated service account credentials.9059 *9060 * Create a new access token by impersonating another service account.9061 *9062 * Impersonated Credentials allowing credentials issued to a user or9063 * service account to impersonate another. The source project using9064 * Impersonated Credentials must enable the "IAMCredentials" API.9065 * Also, the target service account must grant the orginating principal9066 * the "Service Account Token Creator" IAM role.9067 *9068 * @param {object} options - The configuration object.9069 * @param {object} [options.sourceClient] the source credential used as to9070 * acquire the impersonated credentials.9071 * @param {string} [options.targetPrincipal] the service account to9072 * impersonate.9073 * @param {string[]} [options.delegates] the chained list of delegates9074 * required to grant the final access_token. If set, the sequence of9075 * identities must have "Service Account Token Creator" capability granted to9076 * the preceding identity. For example, if set to [serviceAccountB,9077 * serviceAccountC], the sourceCredential must have the Token Creator role on9078 * serviceAccountB. serviceAccountB must have the Token Creator on9079 * serviceAccountC. Finally, C must have Token Creator on target_principal.9080 * If left unset, sourceCredential must have that role on targetPrincipal.9081 * @param {string[]} [options.targetScopes] scopes to request during the9082 * authorization grant.9083 * @param {number} [options.lifetime] number of seconds the delegated9084 * credential should be valid for up to 3600 seconds by default, or 43,2009085 * seconds by extending the token's lifetime, see:9086 * https://cloud.google.com/iam/docs/creating-short-lived-service-account-credentials#sa-credentials-oauth9087 * @param {string} [options.endpoint] api endpoint override.9088 */9089 constructor(options = {}) {9090 var _a, _b, _c, _d, _e, _f;9091 super(options);9092 this.credentials = {9093 expiry_date: 1,9094 refresh_token: 'impersonated-placeholder',9095 };9096 this.sourceClient = (_a = options.sourceClient) !== null && _a !== void 0 ? _a : new oauth2client_1.OAuth2Client();9097 this.targetPrincipal = (_b = options.targetPrincipal) !== null && _b !== void 0 ? _b : '';9098 this.delegates = (_c = options.delegates) !== null && _c !== void 0 ? _c : [];9099 this.targetScopes = (_d = options.targetScopes) !== null && _d !== void 0 ? _d : [];9100 this.lifetime = (_e = options.lifetime) !== null && _e !== void 0 ? _e : 3600;9101 this.endpoint = (_f = options.endpoint) !== null && _f !== void 0 ? _f : 'https://iamcredentials.googleapis.com';9102 }9103 /**9104 * Refreshes the access token.9105 * @param refreshToken Unused parameter9106 */9107 async refreshToken(refreshToken) {9108 var _a, _b, _c, _d, _e, _f;9109 try {9110 await this.sourceClient.getAccessToken();9111 const name = 'projects/-/serviceAccounts/' + this.targetPrincipal;9112 const u = `${this.endpoint}/v1/${name}:generateAccessToken`;9113 const body = {9114 delegates: this.delegates,9115 scope: this.targetScopes,9116 lifetime: this.lifetime + 's',9117 };9118 const res = await this.sourceClient.request({9119 url: u,9120 data: body,9121 method: 'POST',9122 });9123 const tokenResponse = res.data;9124 this.credentials.access_token = tokenResponse.accessToken;9125 this.credentials.expiry_date = Date.parse(tokenResponse.expireTime);9126 return {9127 tokens: this.credentials,9128 res,9129 };9130 }9131 catch (error) {9132 if (!(error instanceof Error))9133 throw error;9134 let status = 0;9135 let message = '';9136 if (error instanceof gaxios_1.GaxiosError) {9137 status = (_c = (_b = (_a = error === null || error === void 0 ? void 0 : error.response) === null || _a === void 0 ? void 0 : _a.data) === null || _b === void 0 ? void 0 : _b.error) === null || _c === void 0 ? void 0 : _c.status;9138 message = (_f = (_e = (_d = error === null || error === void 0 ? void 0 : error.response) === null || _d === void 0 ? void 0 : _d.data) === null || _e === void 0 ? void 0 : _e.error) === null || _f === void 0 ? void 0 : _f.message;9139 }9140 if (status && message) {9141 error.message = `${status}: unable to impersonate: ${message}`;9142 throw error;9143 }9144 else {9145 error.message = `unable to impersonate: ${error}`;9146 throw error;9147 }9148 }9149 }9150 /**9151 * Generates an OpenID Connect ID token for a service account.9152 *9153 * {@link https://cloud.google.com/iam/docs/reference/credentials/rest/v1/projects.serviceAccounts/generateIdToken Reference Documentation}9154 *9155 * @param targetAudience the audience for the fetched ID token.9156 * @param options the for the request9157 * @return an OpenID Connect ID token9158 */9159 async fetchIdToken(targetAudience, options) {9160 var _a;9161 await this.sourceClient.getAccessToken();9162 const name = `projects/-/serviceAccounts/${this.targetPrincipal}`;9163 const u = `${this.endpoint}/v1/${name}:generateIdToken`;9164 const body = {9165 delegates: this.delegates,9166 audience: targetAudience,9167 includeEmail: (_a = options === null || options === void 0 ? void 0 : options.includeEmail) !== null && _a !== void 0 ? _a : true,9168 };9169 const res = await this.sourceClient.request({9170 url: u,9171 data: body,9172 method: 'POST',9173 });9174 return res.data.token;9175 }9176}9177exports.Impersonated = Impersonated;9178//# sourceMappingURL=impersonated.js.map9179/***/ }),9180/***/ 8740:9181/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {9182"use strict";9183// Copyright 2015 Google LLC9184//9185// Licensed under the Apache License, Version 2.0 (the "License");9186// you may not use this file except in compliance with the License.9187// You may obtain a copy of the License at9188//9189// http://www.apache.org/licenses/LICENSE-2.09190//9191// Unless required by applicable law or agreed to in writing, software9192// distributed under the License is distributed on an "AS IS" BASIS,9193// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.9194// See the License for the specific language governing permissions and9195// limitations under the License.9196Object.defineProperty(exports, "__esModule", ({ value: true }));9197exports.JWTAccess = void 0;9198const jws = __nccwpck_require__(4636);9199const LRU = __nccwpck_require__(7129);9200const DEFAULT_HEADER = {9201 alg: 'RS256',9202 typ: 'JWT',9203};9204class JWTAccess {9205 /**9206 * JWTAccess service account credentials.9207 *9208 * Create a new access token by using the credential to create a new JWT token9209 * that's recognized as the access token.9210 *9211 * @param email the service account email address.9212 * @param key the private key that will be used to sign the token.9213 * @param keyId the ID of the private key used to sign the token.9214 */9215 constructor(email, key, keyId, eagerRefreshThresholdMillis) {9216 this.cache = new LRU({9217 max: 500,9218 maxAge: 60 * 60 * 1000,9219 });9220 this.email = email;9221 this.key = key;9222 this.keyId = keyId;9223 this.eagerRefreshThresholdMillis =9224 eagerRefreshThresholdMillis !== null && eagerRefreshThresholdMillis !== void 0 ? eagerRefreshThresholdMillis : 5 * 60 * 1000;9225 }9226 /**9227 * Ensures that we're caching a key appropriately, giving precedence to scopes vs. url9228 *9229 * @param url The URI being authorized.9230 * @param scopes The scope or scopes being authorized9231 * @returns A string that returns the cached key.9232 */9233 getCachedKey(url, scopes) {9234 let cacheKey = url;9235 if (scopes && Array.isArray(scopes) && scopes.length) {9236 cacheKey = url ? `${url}_${scopes.join('_')}` : `${scopes.join('_')}`;9237 }9238 else if (typeof scopes === 'string') {9239 cacheKey = url ? `${url}_${scopes}` : scopes;9240 }9241 if (!cacheKey) {9242 throw Error('Scopes or url must be provided');9243 }9244 return cacheKey;9245 }9246 /**9247 * Get a non-expired access token, after refreshing if necessary.9248 *9249 * @param url The URI being authorized.9250 * @param additionalClaims An object with a set of additional claims to9251 * include in the payload.9252 * @returns An object that includes the authorization header.9253 */9254 getRequestHeaders(url, additionalClaims, scopes) {9255 // Return cached authorization headers, unless we are within9256 // eagerRefreshThresholdMillis ms of them expiring:9257 const key = this.getCachedKey(url, scopes);9258 const cachedToken = this.cache.get(key);9259 const now = Date.now();9260 if (cachedToken &&9261 cachedToken.expiration - now > this.eagerRefreshThresholdMillis) {9262 return cachedToken.headers;9263 }9264 const iat = Math.floor(Date.now() / 1000);9265 const exp = JWTAccess.getExpirationTime(iat);9266 let defaultClaims;9267 // Turn scopes into space-separated string9268 if (Array.isArray(scopes)) {9269 scopes = scopes.join(' ');9270 }9271 // If scopes are specified, sign with scopes9272 if (scopes) {9273 defaultClaims = {9274 iss: this.email,9275 sub: this.email,9276 scope: scopes,9277 exp,9278 iat,9279 };9280 }9281 else {9282 defaultClaims = {9283 iss: this.email,9284 sub: this.email,9285 aud: url,9286 exp,9287 iat,9288 };9289 }9290 // if additionalClaims are provided, ensure they do not collide with9291 // other required claims.9292 if (additionalClaims) {9293 for (const claim in defaultClaims) {9294 if (additionalClaims[claim]) {9295 throw new Error(`The '${claim}' property is not allowed when passing additionalClaims. This claim is included in the JWT by default.`);9296 }9297 }9298 }9299 const header = this.keyId9300 ? { ...DEFAULT_HEADER, kid: this.keyId }9301 : DEFAULT_HEADER;9302 const payload = Object.assign(defaultClaims, additionalClaims);9303 // Sign the jwt and add it to the cache9304 const signedJWT = jws.sign({ header, payload, secret: this.key });9305 const headers = { Authorization: `Bearer ${signedJWT}` };9306 this.cache.set(key, {9307 expiration: exp * 1000,9308 headers,9309 });9310 return headers;9311 }9312 /**9313 * Returns an expiration time for the JWT token.9314 *9315 * @param iat The issued at time for the JWT.9316 * @returns An expiration time for the JWT.9317 */9318 static getExpirationTime(iat) {9319 const exp = iat + 3600; // 3600 seconds = 1 hour9320 return exp;9321 }9322 /**9323 * Create a JWTAccess credentials instance using the given input options.9324 * @param json The input object.9325 */9326 fromJSON(json) {9327 if (!json) {9328 throw new Error('Must pass in a JSON object containing the service account auth settings.');9329 }9330 if (!json.client_email) {9331 throw new Error('The incoming JSON object does not contain a client_email field');9332 }9333 if (!json.private_key) {9334 throw new Error('The incoming JSON object does not contain a private_key field');9335 }9336 // Extract the relevant information from the json key file.9337 this.email = json.client_email;9338 this.key = json.private_key;9339 this.keyId = json.private_key_id;9340 this.projectId = json.project_id;9341 }9342 fromStream(inputStream, callback) {9343 if (callback) {9344 this.fromStreamAsync(inputStream).then(() => callback(), callback);9345 }9346 else {9347 return this.fromStreamAsync(inputStream);9348 }9349 }9350 fromStreamAsync(inputStream) {9351 return new Promise((resolve, reject) => {9352 if (!inputStream) {9353 reject(new Error('Must pass in a stream containing the service account auth settings.'));9354 }9355 let s = '';9356 inputStream9357 .setEncoding('utf8')9358 .on('data', chunk => (s += chunk))9359 .on('error', reject)9360 .on('end', () => {9361 try {9362 const data = JSON.parse(s);9363 this.fromJSON(data);9364 resolve();9365 }9366 catch (err) {9367 reject(err);9368 }9369 });9370 });9371 }9372}9373exports.JWTAccess = JWTAccess;9374//# sourceMappingURL=jwtaccess.js.map9375/***/ }),9376/***/ 3959:9377/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {9378"use strict";9379// Copyright 2013 Google LLC9380//9381// Licensed under the Apache License, Version 2.0 (the "License");9382// you may not use this file except in compliance with the License.9383// You may obtain a copy of the License at9384//9385// http://www.apache.org/licenses/LICENSE-2.09386//9387// Unless required by applicable law or agreed to in writing, software9388// distributed under the License is distributed on an "AS IS" BASIS,9389// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.9390// See the License for the specific language governing permissions and9391// limitations under the License.9392Object.defineProperty(exports, "__esModule", ({ value: true }));9393exports.JWT = void 0;9394const gtoken_1 = __nccwpck_require__(6031);9395const jwtaccess_1 = __nccwpck_require__(8740);9396const oauth2client_1 = __nccwpck_require__(3936);9397class JWT extends oauth2client_1.OAuth2Client {9398 constructor(optionsOrEmail, keyFile, key, scopes, subject, keyId) {9399 const opts = optionsOrEmail && typeof optionsOrEmail === 'object'9400 ? optionsOrEmail9401 : { email: optionsOrEmail, keyFile, key, keyId, scopes, subject };9402 super({9403 eagerRefreshThresholdMillis: opts.eagerRefreshThresholdMillis,9404 forceRefreshOnFailure: opts.forceRefreshOnFailure,9405 });9406 this.email = opts.email;9407 this.keyFile = opts.keyFile;9408 this.key = opts.key;9409 this.keyId = opts.keyId;9410 this.scopes = opts.scopes;9411 this.subject = opts.subject;9412 this.additionalClaims = opts.additionalClaims;9413 this.credentials = { refresh_token: 'jwt-placeholder', expiry_date: 1 };9414 }9415 /**9416 * Creates a copy of the credential with the specified scopes.9417 * @param scopes List of requested scopes or a single scope.9418 * @return The cloned instance.9419 */9420 createScoped(scopes) {9421 return new JWT({9422 email: this.email,9423 keyFile: this.keyFile,9424 key: this.key,9425 keyId: this.keyId,9426 scopes,9427 subject: this.subject,9428 additionalClaims: this.additionalClaims,9429 });9430 }9431 /**9432 * Obtains the metadata to be sent with the request.9433 *9434 * @param url the URI being authorized.9435 */9436 async getRequestMetadataAsync(url) {9437 url = this.defaultServicePath ? `https://${this.defaultServicePath}/` : url;9438 const useSelfSignedJWT = (!this.hasUserScopes() && url) ||9439 (this.useJWTAccessWithScope && this.hasAnyScopes());9440 if (!this.apiKey && useSelfSignedJWT) {9441 if (this.additionalClaims &&9442 this.additionalClaims.target_audience) {9443 const { tokens } = await this.refreshToken();9444 return {9445 headers: this.addSharedMetadataHeaders({9446 Authorization: `Bearer ${tokens.id_token}`,9447 }),9448 };9449 }9450 else {9451 // no scopes have been set, but a uri has been provided. Use JWTAccess9452 // credentials.9453 if (!this.access) {9454 this.access = new jwtaccess_1.JWTAccess(this.email, this.key, this.keyId, this.eagerRefreshThresholdMillis);9455 }9456 let scopes;9457 if (this.hasUserScopes()) {9458 scopes = this.scopes;9459 }9460 else if (!url) {9461 scopes = this.defaultScopes;9462 }9463 const headers = await this.access.getRequestHeaders(url !== null && url !== void 0 ? url : undefined, this.additionalClaims, 9464 // Scopes take precedent over audience for signing,9465 // so we only provide them if useJWTAccessWithScope is on9466 this.useJWTAccessWithScope ? scopes : undefined);9467 return { headers: this.addSharedMetadataHeaders(headers) };9468 }9469 }9470 else if (this.hasAnyScopes() || this.apiKey) {9471 return super.getRequestMetadataAsync(url);9472 }9473 else {9474 // If no audience, apiKey, or scopes are provided, we should not attempt9475 // to populate any headers:9476 return { headers: {} };9477 }9478 }9479 /**9480 * Fetches an ID token.9481 * @param targetAudience the audience for the fetched ID token.9482 */9483 async fetchIdToken(targetAudience) {9484 // Create a new gToken for fetching an ID token9485 const gtoken = new gtoken_1.GoogleToken({9486 iss: this.email,9487 sub: this.subject,9488 scope: this.scopes || this.defaultScopes,9489 keyFile: this.keyFile,9490 key: this.key,9491 additionalClaims: { target_audience: targetAudience },9492 transporter: this.transporter,9493 });9494 await gtoken.getToken({9495 forceRefresh: true,9496 });9497 if (!gtoken.idToken) {9498 throw new Error('Unknown error: Failed to fetch ID token');9499 }9500 return gtoken.idToken;9501 }9502 /**9503 * Determine if there are currently scopes available.9504 */9505 hasUserScopes() {9506 if (!this.scopes) {9507 return false;9508 }9509 return this.scopes.length > 0;9510 }9511 /**9512 * Are there any default or user scopes defined.9513 */9514 hasAnyScopes() {9515 if (this.scopes && this.scopes.length > 0)9516 return true;9517 if (this.defaultScopes && this.defaultScopes.length > 0)9518 return true;9519 return false;9520 }9521 authorize(callback) {9522 if (callback) {9523 this.authorizeAsync().then(r => callback(null, r), callback);9524 }9525 else {9526 return this.authorizeAsync();9527 }9528 }9529 async authorizeAsync() {9530 const result = await this.refreshToken();9531 if (!result) {9532 throw new Error('No result returned');9533 }9534 this.credentials = result.tokens;9535 this.credentials.refresh_token = 'jwt-placeholder';9536 this.key = this.gtoken.key;9537 this.email = this.gtoken.iss;9538 return result.tokens;9539 }9540 /**9541 * Refreshes the access token.9542 * @param refreshToken ignored9543 * @private9544 */9545 async refreshTokenNoCache(9546 // eslint-disable-next-line @typescript-eslint/no-unused-vars9547 refreshToken) {9548 const gtoken = this.createGToken();9549 const token = await gtoken.getToken({9550 forceRefresh: this.isTokenExpiring(),9551 });9552 const tokens = {9553 access_token: token.access_token,9554 token_type: 'Bearer',9555 expiry_date: gtoken.expiresAt,9556 id_token: gtoken.idToken,9557 };9558 this.emit('tokens', tokens);9559 return { res: null, tokens };9560 }9561 /**9562 * Create a gToken if it doesn't already exist.9563 */9564 createGToken() {9565 if (!this.gtoken) {9566 this.gtoken = new gtoken_1.GoogleToken({9567 iss: this.email,9568 sub: this.subject,9569 scope: this.scopes || this.defaultScopes,9570 keyFile: this.keyFile,9571 key: this.key,9572 additionalClaims: this.additionalClaims,9573 transporter: this.transporter,9574 });9575 }9576 return this.gtoken;9577 }9578 /**9579 * Create a JWT credentials instance using the given input options.9580 * @param json The input object.9581 */9582 fromJSON(json) {9583 if (!json) {9584 throw new Error('Must pass in a JSON object containing the service account auth settings.');9585 }9586 if (!json.client_email) {9587 throw new Error('The incoming JSON object does not contain a client_email field');9588 }9589 if (!json.private_key) {9590 throw new Error('The incoming JSON object does not contain a private_key field');9591 }9592 // Extract the relevant information from the json key file.9593 this.email = json.client_email;9594 this.key = json.private_key;9595 this.keyId = json.private_key_id;9596 this.projectId = json.project_id;9597 this.quotaProjectId = json.quota_project_id;9598 }9599 fromStream(inputStream, callback) {9600 if (callback) {9601 this.fromStreamAsync(inputStream).then(() => callback(), callback);9602 }9603 else {9604 return this.fromStreamAsync(inputStream);9605 }9606 }9607 fromStreamAsync(inputStream) {9608 return new Promise((resolve, reject) => {9609 if (!inputStream) {9610 throw new Error('Must pass in a stream containing the service account auth settings.');9611 }9612 let s = '';9613 inputStream9614 .setEncoding('utf8')9615 .on('error', reject)9616 .on('data', chunk => (s += chunk))9617 .on('end', () => {9618 try {9619 const data = JSON.parse(s);9620 this.fromJSON(data);9621 resolve();9622 }9623 catch (e) {9624 reject(e);9625 }9626 });9627 });9628 }9629 /**9630 * Creates a JWT credentials instance using an API Key for authentication.9631 * @param apiKey The API Key in string form.9632 */9633 fromAPIKey(apiKey) {9634 if (typeof apiKey !== 'string') {9635 throw new Error('Must provide an API Key string.');9636 }9637 this.apiKey = apiKey;9638 }9639 /**9640 * Using the key or keyFile on the JWT client, obtain an object that contains9641 * the key and the client email.9642 */9643 async getCredentials() {9644 if (this.key) {9645 return { private_key: this.key, client_email: this.email };9646 }9647 else if (this.keyFile) {9648 const gtoken = this.createGToken();9649 const creds = await gtoken.getCredentials(this.keyFile);9650 return { private_key: creds.privateKey, client_email: creds.clientEmail };9651 }9652 throw new Error('A key or a keyFile must be provided to getCredentials.');9653 }9654}9655exports.JWT = JWT;9656//# sourceMappingURL=jwtclient.js.map9657/***/ }),9658/***/ 4524:9659/***/ ((__unused_webpack_module, exports) => {9660"use strict";9661// Copyright 2014 Google LLC9662//9663// Licensed under the Apache License, Version 2.0 (the "License");9664// you may not use this file except in compliance with the License.9665// You may obtain a copy of the License at9666//9667// http://www.apache.org/licenses/LICENSE-2.09668//9669// Unless required by applicable law or agreed to in writing, software9670// distributed under the License is distributed on an "AS IS" BASIS,9671// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.9672// See the License for the specific language governing permissions and9673// limitations under the License.9674Object.defineProperty(exports, "__esModule", ({ value: true }));9675exports.LoginTicket = void 0;9676class LoginTicket {9677 /**9678 * Create a simple class to extract user ID from an ID Token9679 *9680 * @param {string} env Envelope of the jwt9681 * @param {TokenPayload} pay Payload of the jwt9682 * @constructor9683 */9684 constructor(env, pay) {9685 this.envelope = env;9686 this.payload = pay;9687 }9688 getEnvelope() {9689 return this.envelope;9690 }9691 getPayload() {9692 return this.payload;9693 }9694 /**9695 * Create a simple class to extract user ID from an ID Token9696 *9697 * @return The user ID9698 */9699 getUserId() {9700 const payload = this.getPayload();9701 if (payload && payload.sub) {9702 return payload.sub;9703 }9704 return null;9705 }9706 /**9707 * Returns attributes from the login ticket. This can contain9708 * various information about the user session.9709 *9710 * @return The envelope and payload9711 */9712 getAttributes() {9713 return { envelope: this.getEnvelope(), payload: this.getPayload() };9714 }9715}9716exports.LoginTicket = LoginTicket;9717//# sourceMappingURL=loginticket.js.map9718/***/ }),9719/***/ 3936:9720/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {9721"use strict";9722// Copyright 2019 Google LLC9723//9724// Licensed under the Apache License, Version 2.0 (the "License");9725// you may not use this file except in compliance with the License.9726// You may obtain a copy of the License at9727//9728// http://www.apache.org/licenses/LICENSE-2.09729//9730// Unless required by applicable law or agreed to in writing, software9731// distributed under the License is distributed on an "AS IS" BASIS,9732// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.9733// See the License for the specific language governing permissions and9734// limitations under the License.9735Object.defineProperty(exports, "__esModule", ({ value: true }));9736exports.OAuth2Client = exports.CertificateFormat = exports.CodeChallengeMethod = void 0;9737const gaxios_1 = __nccwpck_require__(9555);9738const querystring = __nccwpck_require__(3477);9739const stream = __nccwpck_require__(2781);9740const formatEcdsa = __nccwpck_require__(1728);9741const crypto_1 = __nccwpck_require__(8043);9742const authclient_1 = __nccwpck_require__(4627);9743const loginticket_1 = __nccwpck_require__(4524);9744var CodeChallengeMethod;9745(function (CodeChallengeMethod) {9746 CodeChallengeMethod["Plain"] = "plain";9747 CodeChallengeMethod["S256"] = "S256";9748})(CodeChallengeMethod = exports.CodeChallengeMethod || (exports.CodeChallengeMethod = {}));9749var CertificateFormat;9750(function (CertificateFormat) {9751 CertificateFormat["PEM"] = "PEM";9752 CertificateFormat["JWK"] = "JWK";9753})(CertificateFormat = exports.CertificateFormat || (exports.CertificateFormat = {}));9754class OAuth2Client extends authclient_1.AuthClient {9755 constructor(optionsOrClientId, clientSecret, redirectUri) {9756 super();9757 this.certificateCache = {};9758 this.certificateExpiry = null;9759 this.certificateCacheFormat = CertificateFormat.PEM;9760 this.refreshTokenPromises = new Map();9761 const opts = optionsOrClientId && typeof optionsOrClientId === 'object'9762 ? optionsOrClientId9763 : { clientId: optionsOrClientId, clientSecret, redirectUri };9764 this._clientId = opts.clientId;9765 this._clientSecret = opts.clientSecret;9766 this.redirectUri = opts.redirectUri;9767 this.eagerRefreshThresholdMillis =9768 opts.eagerRefreshThresholdMillis || 5 * 60 * 1000;9769 this.forceRefreshOnFailure = !!opts.forceRefreshOnFailure;9770 }9771 /**9772 * Generates URL for consent page landing.9773 * @param opts Options.9774 * @return URL to consent page.9775 */9776 generateAuthUrl(opts = {}) {9777 if (opts.code_challenge_method && !opts.code_challenge) {9778 throw new Error('If a code_challenge_method is provided, code_challenge must be included.');9779 }9780 opts.response_type = opts.response_type || 'code';9781 opts.client_id = opts.client_id || this._clientId;9782 opts.redirect_uri = opts.redirect_uri || this.redirectUri;9783 // Allow scopes to be passed either as array or a string9784 if (Array.isArray(opts.scope)) {9785 opts.scope = opts.scope.join(' ');9786 }9787 const rootUrl = OAuth2Client.GOOGLE_OAUTH2_AUTH_BASE_URL_;9788 return (rootUrl +9789 '?' +9790 querystring.stringify(opts));9791 }9792 generateCodeVerifier() {9793 // To make the code compatible with browser SubtleCrypto we need to make9794 // this method async.9795 throw new Error('generateCodeVerifier is removed, please use generateCodeVerifierAsync instead.');9796 }9797 /**9798 * Convenience method to automatically generate a code_verifier, and its9799 * resulting SHA256. If used, this must be paired with a S2569800 * code_challenge_method.9801 *9802 * For a full example see:9803 * https://github.com/googleapis/google-auth-library-nodejs/blob/main/samples/oauth2-codeVerifier.js9804 */9805 async generateCodeVerifierAsync() {9806 // base64 encoding uses 6 bits per character, and we want to generate1289807 // characters. 6*128/8 = 96.9808 const crypto = (0, crypto_1.createCrypto)();9809 const randomString = crypto.randomBytesBase64(96);9810 // The valid characters in the code_verifier are [A-Z]/[a-z]/[0-9]/9811 // "-"/"."/"_"/"~". Base64 encoded strings are pretty close, so we're just9812 // swapping out a few chars.9813 const codeVerifier = randomString9814 .replace(/\+/g, '~')9815 .replace(/=/g, '_')9816 .replace(/\//g, '-');9817 // Generate the base64 encoded SHA2569818 const unencodedCodeChallenge = await crypto.sha256DigestBase64(codeVerifier);9819 // We need to use base64UrlEncoding instead of standard base649820 const codeChallenge = unencodedCodeChallenge9821 .split('=')[0]9822 .replace(/\+/g, '-')9823 .replace(/\//g, '_');9824 return { codeVerifier, codeChallenge };9825 }9826 getToken(codeOrOptions, callback) {9827 const options = typeof codeOrOptions === 'string' ? { code: codeOrOptions } : codeOrOptions;9828 if (callback) {9829 this.getTokenAsync(options).then(r => callback(null, r.tokens, r.res), e => callback(e, null, e.response));9830 }9831 else {9832 return this.getTokenAsync(options);9833 }9834 }9835 async getTokenAsync(options) {9836 const url = OAuth2Client.GOOGLE_OAUTH2_TOKEN_URL_;9837 const values = {9838 code: options.code,9839 client_id: options.client_id || this._clientId,9840 client_secret: this._clientSecret,9841 redirect_uri: options.redirect_uri || this.redirectUri,9842 grant_type: 'authorization_code',9843 code_verifier: options.codeVerifier,9844 };9845 const res = await this.transporter.request({9846 method: 'POST',9847 url,9848 data: querystring.stringify(values),9849 headers: { 'Content-Type': 'application/x-www-form-urlencoded' },9850 });9851 const tokens = res.data;9852 if (res.data && res.data.expires_in) {9853 tokens.expiry_date = new Date().getTime() + res.data.expires_in * 1000;9854 delete tokens.expires_in;9855 }9856 this.emit('tokens', tokens);9857 return { tokens, res };9858 }9859 /**9860 * Refreshes the access token.9861 * @param refresh_token Existing refresh token.9862 * @private9863 */9864 async refreshToken(refreshToken) {9865 if (!refreshToken) {9866 return this.refreshTokenNoCache(refreshToken);9867 }9868 // If a request to refresh using the same token has started,9869 // return the same promise.9870 if (this.refreshTokenPromises.has(refreshToken)) {9871 return this.refreshTokenPromises.get(refreshToken);9872 }9873 const p = this.refreshTokenNoCache(refreshToken).then(r => {9874 this.refreshTokenPromises.delete(refreshToken);9875 return r;9876 }, e => {9877 this.refreshTokenPromises.delete(refreshToken);9878 throw e;9879 });9880 this.refreshTokenPromises.set(refreshToken, p);9881 return p;9882 }9883 async refreshTokenNoCache(refreshToken) {9884 var _a;9885 if (!refreshToken) {9886 throw new Error('No refresh token is set.');9887 }9888 const url = OAuth2Client.GOOGLE_OAUTH2_TOKEN_URL_;9889 const data = {9890 refresh_token: refreshToken,9891 client_id: this._clientId,9892 client_secret: this._clientSecret,9893 grant_type: 'refresh_token',9894 };9895 let res;9896 try {9897 // request for new token9898 res = await this.transporter.request({9899 method: 'POST',9900 url,9901 data: querystring.stringify(data),9902 headers: { 'Content-Type': 'application/x-www-form-urlencoded' },9903 });9904 }9905 catch (e) {9906 if (e instanceof gaxios_1.GaxiosError &&9907 e.message === 'invalid_grant' &&9908 ((_a = e.response) === null || _a === void 0 ? void 0 : _a.data) &&9909 /ReAuth/i.test(e.response.data.error_description)) {9910 e.message = JSON.stringify(e.response.data);9911 }9912 throw e;9913 }9914 const tokens = res.data;9915 // TODO: de-duplicate this code from a few spots9916 if (res.data && res.data.expires_in) {9917 tokens.expiry_date = new Date().getTime() + res.data.expires_in * 1000;9918 delete tokens.expires_in;9919 }9920 this.emit('tokens', tokens);9921 return { tokens, res };9922 }9923 refreshAccessToken(callback) {9924 if (callback) {9925 this.refreshAccessTokenAsync().then(r => callback(null, r.credentials, r.res), callback);9926 }9927 else {9928 return this.refreshAccessTokenAsync();9929 }9930 }9931 async refreshAccessTokenAsync() {9932 const r = await this.refreshToken(this.credentials.refresh_token);9933 const tokens = r.tokens;9934 tokens.refresh_token = this.credentials.refresh_token;9935 this.credentials = tokens;9936 return { credentials: this.credentials, res: r.res };9937 }9938 getAccessToken(callback) {9939 if (callback) {9940 this.getAccessTokenAsync().then(r => callback(null, r.token, r.res), callback);9941 }9942 else {9943 return this.getAccessTokenAsync();9944 }9945 }9946 async getAccessTokenAsync() {9947 const shouldRefresh = !this.credentials.access_token || this.isTokenExpiring();9948 if (shouldRefresh) {9949 if (!this.credentials.refresh_token) {9950 if (this.refreshHandler) {9951 const refreshedAccessToken = await this.processAndValidateRefreshHandler();9952 if (refreshedAccessToken === null || refreshedAccessToken === void 0 ? void 0 : refreshedAccessToken.access_token) {9953 this.setCredentials(refreshedAccessToken);9954 return { token: this.credentials.access_token };9955 }9956 }9957 else {9958 throw new Error('No refresh token or refresh handler callback is set.');9959 }9960 }9961 const r = await this.refreshAccessTokenAsync();9962 if (!r.credentials || (r.credentials && !r.credentials.access_token)) {9963 throw new Error('Could not refresh access token.');9964 }9965 return { token: r.credentials.access_token, res: r.res };9966 }9967 else {9968 return { token: this.credentials.access_token };9969 }9970 }9971 /**9972 * The main authentication interface. It takes an optional url which when9973 * present is the endpoint being accessed, and returns a Promise which9974 * resolves with authorization header fields.9975 *9976 * In OAuth2Client, the result has the form:9977 * { Authorization: 'Bearer <access_token_value>' }9978 * @param url The optional url being authorized9979 */9980 async getRequestHeaders(url) {9981 const headers = (await this.getRequestMetadataAsync(url)).headers;9982 return headers;9983 }9984 async getRequestMetadataAsync(9985 // eslint-disable-next-line @typescript-eslint/no-unused-vars9986 url) {9987 const thisCreds = this.credentials;9988 if (!thisCreds.access_token &&9989 !thisCreds.refresh_token &&9990 !this.apiKey &&9991 !this.refreshHandler) {9992 throw new Error('No access, refresh token, API key or refresh handler callback is set.');9993 }9994 if (thisCreds.access_token && !this.isTokenExpiring()) {9995 thisCreds.token_type = thisCreds.token_type || 'Bearer';9996 const headers = {9997 Authorization: thisCreds.token_type + ' ' + thisCreds.access_token,9998 };9999 return { headers: this.addSharedMetadataHeaders(headers) };10000 }10001 // If refreshHandler exists, call processAndValidateRefreshHandler().10002 if (this.refreshHandler) {10003 const refreshedAccessToken = await this.processAndValidateRefreshHandler();10004 if (refreshedAccessToken === null || refreshedAccessToken === void 0 ? void 0 : refreshedAccessToken.access_token) {10005 this.setCredentials(refreshedAccessToken);10006 const headers = {10007 Authorization: 'Bearer ' + this.credentials.access_token,10008 };10009 return { headers: this.addSharedMetadataHeaders(headers) };10010 }10011 }10012 if (this.apiKey) {10013 return { headers: { 'X-Goog-Api-Key': this.apiKey } };10014 }10015 let r = null;10016 let tokens = null;10017 try {10018 r = await this.refreshToken(thisCreds.refresh_token);10019 tokens = r.tokens;10020 }10021 catch (err) {10022 const e = err;10023 if (e.response &&10024 (e.response.status === 403 || e.response.status === 404)) {10025 e.message = `Could not refresh access token: ${e.message}`;10026 }10027 throw e;10028 }10029 const credentials = this.credentials;10030 credentials.token_type = credentials.token_type || 'Bearer';10031 tokens.refresh_token = credentials.refresh_token;10032 this.credentials = tokens;10033 const headers = {10034 Authorization: credentials.token_type + ' ' + tokens.access_token,10035 };10036 return { headers: this.addSharedMetadataHeaders(headers), res: r.res };10037 }10038 /**10039 * Generates an URL to revoke the given token.10040 * @param token The existing token to be revoked.10041 */10042 static getRevokeTokenUrl(token) {10043 const parameters = querystring.stringify({ token });10044 return `${OAuth2Client.GOOGLE_OAUTH2_REVOKE_URL_}?${parameters}`;10045 }10046 revokeToken(token, callback) {10047 const opts = {10048 url: OAuth2Client.getRevokeTokenUrl(token),10049 method: 'POST',10050 };10051 if (callback) {10052 this.transporter10053 .request(opts)10054 .then(r => callback(null, r), callback);10055 }10056 else {10057 return this.transporter.request(opts);10058 }10059 }10060 revokeCredentials(callback) {10061 if (callback) {10062 this.revokeCredentialsAsync().then(res => callback(null, res), callback);10063 }10064 else {10065 return this.revokeCredentialsAsync();10066 }10067 }10068 async revokeCredentialsAsync() {10069 const token = this.credentials.access_token;10070 this.credentials = {};10071 if (token) {10072 return this.revokeToken(token);10073 }10074 else {10075 throw new Error('No access token to revoke.');10076 }10077 }10078 request(opts, callback) {10079 if (callback) {10080 this.requestAsync(opts).then(r => callback(null, r), e => {10081 return callback(e, e.response);10082 });10083 }10084 else {10085 return this.requestAsync(opts);10086 }10087 }10088 async requestAsync(opts, retry = false) {10089 let r2;10090 try {10091 const r = await this.getRequestMetadataAsync(opts.url);10092 opts.headers = opts.headers || {};10093 if (r.headers && r.headers['x-goog-user-project']) {10094 opts.headers['x-goog-user-project'] = r.headers['x-goog-user-project'];10095 }10096 if (r.headers && r.headers.Authorization) {10097 opts.headers.Authorization = r.headers.Authorization;10098 }10099 if (this.apiKey) {10100 opts.headers['X-Goog-Api-Key'] = this.apiKey;10101 }10102 r2 = await this.transporter.request(opts);10103 }10104 catch (e) {10105 const res = e.response;10106 if (res) {10107 const statusCode = res.status;10108 // Retry the request for metadata if the following criteria are true:10109 // - We haven't already retried. It only makes sense to retry once.10110 // - The response was a 401 or a 40310111 // - The request didn't send a readableStream10112 // - An access_token and refresh_token were available, but either no10113 // expiry_date was available or the forceRefreshOnFailure flag is set.10114 // The absent expiry_date case can happen when developers stash the10115 // access_token and refresh_token for later use, but the access_token10116 // fails on the first try because it's expired. Some developers may10117 // choose to enable forceRefreshOnFailure to mitigate time-related10118 // errors.10119 // Or the following criteria are true:10120 // - We haven't already retried. It only makes sense to retry once.10121 // - The response was a 401 or a 40310122 // - The request didn't send a readableStream10123 // - No refresh_token was available10124 // - An access_token and a refreshHandler callback were available, but10125 // either no expiry_date was available or the forceRefreshOnFailure10126 // flag is set. The access_token fails on the first try because it's10127 // expired. Some developers may choose to enable forceRefreshOnFailure10128 // to mitigate time-related errors.10129 const mayRequireRefresh = this.credentials &&10130 this.credentials.access_token &&10131 this.credentials.refresh_token &&10132 (!this.credentials.expiry_date || this.forceRefreshOnFailure);10133 const mayRequireRefreshWithNoRefreshToken = this.credentials &&10134 this.credentials.access_token &&10135 !this.credentials.refresh_token &&10136 (!this.credentials.expiry_date || this.forceRefreshOnFailure) &&10137 this.refreshHandler;10138 const isReadableStream = res.config.data instanceof stream.Readable;10139 const isAuthErr = statusCode === 401 || statusCode === 403;10140 if (!retry && isAuthErr && !isReadableStream && mayRequireRefresh) {10141 await this.refreshAccessTokenAsync();10142 return this.requestAsync(opts, true);10143 }10144 else if (!retry &&10145 isAuthErr &&10146 !isReadableStream &&10147 mayRequireRefreshWithNoRefreshToken) {10148 const refreshedAccessToken = await this.processAndValidateRefreshHandler();10149 if (refreshedAccessToken === null || refreshedAccessToken === void 0 ? void 0 : refreshedAccessToken.access_token) {10150 this.setCredentials(refreshedAccessToken);10151 }10152 return this.requestAsync(opts, true);10153 }10154 }10155 throw e;10156 }10157 return r2;10158 }10159 verifyIdToken(options, callback) {10160 // This function used to accept two arguments instead of an options object.10161 // Check the types to help users upgrade with less pain.10162 // This check can be removed after a 2.0 release.10163 if (callback && typeof callback !== 'function') {10164 throw new Error('This method accepts an options object as the first parameter, which includes the idToken, audience, and maxExpiry.');10165 }10166 if (callback) {10167 this.verifyIdTokenAsync(options).then(r => callback(null, r), callback);10168 }10169 else {10170 return this.verifyIdTokenAsync(options);10171 }10172 }10173 async verifyIdTokenAsync(options) {10174 if (!options.idToken) {10175 throw new Error('The verifyIdToken method requires an ID Token');10176 }10177 const response = await this.getFederatedSignonCertsAsync();10178 const login = await this.verifySignedJwtWithCertsAsync(options.idToken, response.certs, options.audience, OAuth2Client.ISSUERS_, options.maxExpiry);10179 return login;10180 }10181 /**10182 * Obtains information about the provisioned access token. Especially useful10183 * if you want to check the scopes that were provisioned to a given token.10184 *10185 * @param accessToken Required. The Access Token for which you want to get10186 * user info.10187 */10188 async getTokenInfo(accessToken) {10189 const { data } = await this.transporter.request({10190 method: 'POST',10191 headers: {10192 'Content-Type': 'application/x-www-form-urlencoded',10193 Authorization: `Bearer ${accessToken}`,10194 },10195 url: OAuth2Client.GOOGLE_TOKEN_INFO_URL,10196 });10197 const info = Object.assign({10198 expiry_date: new Date().getTime() + data.expires_in * 1000,10199 scopes: data.scope.split(' '),10200 }, data);10201 delete info.expires_in;10202 delete info.scope;10203 return info;10204 }10205 getFederatedSignonCerts(callback) {10206 if (callback) {10207 this.getFederatedSignonCertsAsync().then(r => callback(null, r.certs, r.res), callback);10208 }10209 else {10210 return this.getFederatedSignonCertsAsync();10211 }10212 }10213 async getFederatedSignonCertsAsync() {10214 const nowTime = new Date().getTime();10215 const format = (0, crypto_1.hasBrowserCrypto)()10216 ? CertificateFormat.JWK10217 : CertificateFormat.PEM;10218 if (this.certificateExpiry &&10219 nowTime < this.certificateExpiry.getTime() &&10220 this.certificateCacheFormat === format) {10221 return { certs: this.certificateCache, format };10222 }10223 let res;10224 let url;10225 switch (format) {10226 case CertificateFormat.PEM:10227 url = OAuth2Client.GOOGLE_OAUTH2_FEDERATED_SIGNON_PEM_CERTS_URL_;10228 break;10229 case CertificateFormat.JWK:10230 url = OAuth2Client.GOOGLE_OAUTH2_FEDERATED_SIGNON_JWK_CERTS_URL_;10231 break;10232 default:10233 throw new Error(`Unsupported certificate format ${format}`);10234 }10235 try {10236 res = await this.transporter.request({ url });10237 }10238 catch (e) {10239 if (e instanceof Error) {10240 e.message = `Failed to retrieve verification certificates: ${e.message}`;10241 }10242 throw e;10243 }10244 const cacheControl = res ? res.headers['cache-control'] : undefined;10245 let cacheAge = -1;10246 if (cacheControl) {10247 const pattern = new RegExp('max-age=([0-9]*)');10248 const regexResult = pattern.exec(cacheControl);10249 if (regexResult && regexResult.length === 2) {10250 // Cache results with max-age (in seconds)10251 cacheAge = Number(regexResult[1]) * 1000; // milliseconds10252 }10253 }10254 let certificates = {};10255 switch (format) {10256 case CertificateFormat.PEM:10257 certificates = res.data;10258 break;10259 case CertificateFormat.JWK:10260 for (const key of res.data.keys) {10261 certificates[key.kid] = key;10262 }10263 break;10264 default:10265 throw new Error(`Unsupported certificate format ${format}`);10266 }10267 const now = new Date();10268 this.certificateExpiry =10269 cacheAge === -1 ? null : new Date(now.getTime() + cacheAge);10270 this.certificateCache = certificates;10271 this.certificateCacheFormat = format;10272 return { certs: certificates, format, res };10273 }10274 getIapPublicKeys(callback) {10275 if (callback) {10276 this.getIapPublicKeysAsync().then(r => callback(null, r.pubkeys, r.res), callback);10277 }10278 else {10279 return this.getIapPublicKeysAsync();10280 }10281 }10282 async getIapPublicKeysAsync() {10283 let res;10284 const url = OAuth2Client.GOOGLE_OAUTH2_IAP_PUBLIC_KEY_URL_;10285 try {10286 res = await this.transporter.request({ url });10287 }10288 catch (e) {10289 if (e instanceof Error) {10290 e.message = `Failed to retrieve verification certificates: ${e.message}`;10291 }10292 throw e;10293 }10294 return { pubkeys: res.data, res };10295 }10296 verifySignedJwtWithCerts() {10297 // To make the code compatible with browser SubtleCrypto we need to make10298 // this method async.10299 throw new Error('verifySignedJwtWithCerts is removed, please use verifySignedJwtWithCertsAsync instead.');10300 }10301 /**10302 * Verify the id token is signed with the correct certificate10303 * and is from the correct audience.10304 * @param jwt The jwt to verify (The ID Token in this case).10305 * @param certs The array of certs to test the jwt against.10306 * @param requiredAudience The audience to test the jwt against.10307 * @param issuers The allowed issuers of the jwt (Optional).10308 * @param maxExpiry The max expiry the certificate can be (Optional).10309 * @return Returns a promise resolving to LoginTicket on verification.10310 */10311 async verifySignedJwtWithCertsAsync(jwt, certs, requiredAudience, issuers, maxExpiry) {10312 const crypto = (0, crypto_1.createCrypto)();10313 if (!maxExpiry) {10314 maxExpiry = OAuth2Client.MAX_TOKEN_LIFETIME_SECS_;10315 }10316 const segments = jwt.split('.');10317 if (segments.length !== 3) {10318 throw new Error('Wrong number of segments in token: ' + jwt);10319 }10320 const signed = segments[0] + '.' + segments[1];10321 let signature = segments[2];10322 let envelope;10323 let payload;10324 try {10325 envelope = JSON.parse(crypto.decodeBase64StringUtf8(segments[0]));10326 }10327 catch (err) {10328 if (err instanceof Error) {10329 err.message = `Can't parse token envelope: ${segments[0]}': ${err.message}`;10330 }10331 throw err;10332 }10333 if (!envelope) {10334 throw new Error("Can't parse token envelope: " + segments[0]);10335 }10336 try {10337 payload = JSON.parse(crypto.decodeBase64StringUtf8(segments[1]));10338 }10339 catch (err) {10340 if (err instanceof Error) {10341 err.message = `Can't parse token payload '${segments[0]}`;10342 }10343 throw err;10344 }10345 if (!payload) {10346 throw new Error("Can't parse token payload: " + segments[1]);10347 }10348 if (!Object.prototype.hasOwnProperty.call(certs, envelope.kid)) {10349 // If this is not present, then there's no reason to attempt verification10350 throw new Error('No pem found for envelope: ' + JSON.stringify(envelope));10351 }10352 const cert = certs[envelope.kid];10353 if (envelope.alg === 'ES256') {10354 signature = formatEcdsa.joseToDer(signature, 'ES256').toString('base64');10355 }10356 const verified = await crypto.verify(cert, signed, signature);10357 if (!verified) {10358 throw new Error('Invalid token signature: ' + jwt);10359 }10360 if (!payload.iat) {10361 throw new Error('No issue time in token: ' + JSON.stringify(payload));10362 }10363 if (!payload.exp) {10364 throw new Error('No expiration time in token: ' + JSON.stringify(payload));10365 }10366 const iat = Number(payload.iat);10367 if (isNaN(iat))10368 throw new Error('iat field using invalid format');10369 const exp = Number(payload.exp);10370 if (isNaN(exp))10371 throw new Error('exp field using invalid format');10372 const now = new Date().getTime() / 1000;10373 if (exp >= now + maxExpiry) {10374 throw new Error('Expiration time too far in future: ' + JSON.stringify(payload));10375 }10376 const earliest = iat - OAuth2Client.CLOCK_SKEW_SECS_;10377 const latest = exp + OAuth2Client.CLOCK_SKEW_SECS_;10378 if (now < earliest) {10379 throw new Error('Token used too early, ' +10380 now +10381 ' < ' +10382 earliest +10383 ': ' +10384 JSON.stringify(payload));10385 }10386 if (now > latest) {10387 throw new Error('Token used too late, ' +10388 now +10389 ' > ' +10390 latest +10391 ': ' +10392 JSON.stringify(payload));10393 }10394 if (issuers && issuers.indexOf(payload.iss) < 0) {10395 throw new Error('Invalid issuer, expected one of [' +10396 issuers +10397 '], but got ' +10398 payload.iss);10399 }10400 // Check the audience matches if we have one10401 if (typeof requiredAudience !== 'undefined' && requiredAudience !== null) {10402 const aud = payload.aud;10403 let audVerified = false;10404 // If the requiredAudience is an array, check if it contains token10405 // audience10406 if (requiredAudience.constructor === Array) {10407 audVerified = requiredAudience.indexOf(aud) > -1;10408 }10409 else {10410 audVerified = aud === requiredAudience;10411 }10412 if (!audVerified) {10413 throw new Error('Wrong recipient, payload audience != requiredAudience');10414 }10415 }10416 return new loginticket_1.LoginTicket(envelope, payload);10417 }10418 /**10419 * Returns a promise that resolves with AccessTokenResponse type if10420 * refreshHandler is defined.10421 * If not, nothing is returned.10422 */10423 async processAndValidateRefreshHandler() {10424 if (this.refreshHandler) {10425 const accessTokenResponse = await this.refreshHandler();10426 if (!accessTokenResponse.access_token) {10427 throw new Error('No access token is returned by the refreshHandler callback.');10428 }10429 return accessTokenResponse;10430 }10431 return;10432 }10433 /**10434 * Returns true if a token is expired or will expire within10435 * eagerRefreshThresholdMillismilliseconds.10436 * If there is no expiry time, assumes the token is not expired or expiring.10437 */10438 isTokenExpiring() {10439 const expiryDate = this.credentials.expiry_date;10440 return expiryDate10441 ? expiryDate <= new Date().getTime() + this.eagerRefreshThresholdMillis10442 : false;10443 }10444}10445exports.OAuth2Client = OAuth2Client;10446OAuth2Client.GOOGLE_TOKEN_INFO_URL = 'https://oauth2.googleapis.com/tokeninfo';10447/**10448 * The base URL for auth endpoints.10449 */10450OAuth2Client.GOOGLE_OAUTH2_AUTH_BASE_URL_ = 'https://accounts.google.com/o/oauth2/v2/auth';10451/**10452 * The base endpoint for token retrieval.10453 */10454OAuth2Client.GOOGLE_OAUTH2_TOKEN_URL_ = 'https://oauth2.googleapis.com/token';10455/**10456 * The base endpoint to revoke tokens.10457 */10458OAuth2Client.GOOGLE_OAUTH2_REVOKE_URL_ = 'https://oauth2.googleapis.com/revoke';10459/**10460 * Google Sign on certificates in PEM format.10461 */10462OAuth2Client.GOOGLE_OAUTH2_FEDERATED_SIGNON_PEM_CERTS_URL_ = 'https://www.googleapis.com/oauth2/v1/certs';10463/**10464 * Google Sign on certificates in JWK format.10465 */10466OAuth2Client.GOOGLE_OAUTH2_FEDERATED_SIGNON_JWK_CERTS_URL_ = 'https://www.googleapis.com/oauth2/v3/certs';10467/**10468 * Google Sign on certificates in JWK format.10469 */10470OAuth2Client.GOOGLE_OAUTH2_IAP_PUBLIC_KEY_URL_ = 'https://www.gstatic.com/iap/verify/public_key';10471/**10472 * Clock skew - five minutes in seconds10473 */10474OAuth2Client.CLOCK_SKEW_SECS_ = 300;10475/**10476 * Max Token Lifetime is one day in seconds10477 */10478OAuth2Client.MAX_TOKEN_LIFETIME_SECS_ = 86400;10479/**10480 * The allowed oauth token issuers.10481 */10482OAuth2Client.ISSUERS_ = [10483 'accounts.google.com',10484 'https://accounts.google.com',10485];10486//# sourceMappingURL=oauth2client.js.map10487/***/ }),10488/***/ 9510:10489/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {10490"use strict";10491// Copyright 2021 Google LLC10492//10493// Licensed under the Apache License, Version 2.0 (the "License");10494// you may not use this file except in compliance with the License.10495// You may obtain a copy of the License at10496//10497// http://www.apache.org/licenses/LICENSE-2.010498//10499// Unless required by applicable law or agreed to in writing, software10500// distributed under the License is distributed on an "AS IS" BASIS,10501// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.10502// See the License for the specific language governing permissions and10503// limitations under the License.10504Object.defineProperty(exports, "__esModule", ({ value: true }));10505exports.getErrorFromOAuthErrorResponse = exports.OAuthClientAuthHandler = void 0;10506const querystring = __nccwpck_require__(3477);10507const crypto_1 = __nccwpck_require__(8043);10508/** List of HTTP methods that accept request bodies. */10509const METHODS_SUPPORTING_REQUEST_BODY = ['PUT', 'POST', 'PATCH'];10510/**10511 * Abstract class for handling client authentication in OAuth-based10512 * operations.10513 * When request-body client authentication is used, only application/json and10514 * application/x-www-form-urlencoded content types for HTTP methods that support10515 * request bodies are supported.10516 */10517class OAuthClientAuthHandler {10518 /**10519 * Instantiates an OAuth client authentication handler.10520 * @param clientAuthentication The client auth credentials.10521 */10522 constructor(clientAuthentication) {10523 this.clientAuthentication = clientAuthentication;10524 this.crypto = (0, crypto_1.createCrypto)();10525 }10526 /**10527 * Applies client authentication on the OAuth request's headers or POST10528 * body but does not process the request.10529 * @param opts The GaxiosOptions whose headers or data are to be modified10530 * depending on the client authentication mechanism to be used.10531 * @param bearerToken The optional bearer token to use for authentication.10532 * When this is used, no client authentication credentials are needed.10533 */10534 applyClientAuthenticationOptions(opts, bearerToken) {10535 // Inject authenticated header.10536 this.injectAuthenticatedHeaders(opts, bearerToken);10537 // Inject authenticated request body.10538 if (!bearerToken) {10539 this.injectAuthenticatedRequestBody(opts);10540 }10541 }10542 /**10543 * Applies client authentication on the request's header if either10544 * basic authentication or bearer token authentication is selected.10545 *10546 * @param opts The GaxiosOptions whose headers or data are to be modified10547 * depending on the client authentication mechanism to be used.10548 * @param bearerToken The optional bearer token to use for authentication.10549 * When this is used, no client authentication credentials are needed.10550 */10551 injectAuthenticatedHeaders(opts, bearerToken) {10552 var _a;10553 // Bearer token prioritized higher than basic Auth.10554 if (bearerToken) {10555 opts.headers = opts.headers || {};10556 Object.assign(opts.headers, {10557 Authorization: `Bearer ${bearerToken}}`,10558 });10559 }10560 else if (((_a = this.clientAuthentication) === null || _a === void 0 ? void 0 : _a.confidentialClientType) === 'basic') {10561 opts.headers = opts.headers || {};10562 const clientId = this.clientAuthentication.clientId;10563 const clientSecret = this.clientAuthentication.clientSecret || '';10564 const base64EncodedCreds = this.crypto.encodeBase64StringUtf8(`${clientId}:${clientSecret}`);10565 Object.assign(opts.headers, {10566 Authorization: `Basic ${base64EncodedCreds}`,10567 });10568 }10569 }10570 /**10571 * Applies client authentication on the request's body if request-body10572 * client authentication is selected.10573 *10574 * @param opts The GaxiosOptions whose headers or data are to be modified10575 * depending on the client authentication mechanism to be used.10576 */10577 injectAuthenticatedRequestBody(opts) {10578 var _a;10579 if (((_a = this.clientAuthentication) === null || _a === void 0 ? void 0 : _a.confidentialClientType) === 'request-body') {10580 const method = (opts.method || 'GET').toUpperCase();10581 // Inject authenticated request body.10582 if (METHODS_SUPPORTING_REQUEST_BODY.indexOf(method) !== -1) {10583 // Get content-type.10584 let contentType;10585 const headers = opts.headers || {};10586 for (const key in headers) {10587 if (key.toLowerCase() === 'content-type' && headers[key]) {10588 contentType = headers[key].toLowerCase();10589 break;10590 }10591 }10592 if (contentType === 'application/x-www-form-urlencoded') {10593 opts.data = opts.data || '';10594 const data = querystring.parse(opts.data);10595 Object.assign(data, {10596 client_id: this.clientAuthentication.clientId,10597 client_secret: this.clientAuthentication.clientSecret || '',10598 });10599 opts.data = querystring.stringify(data);10600 }10601 else if (contentType === 'application/json') {10602 opts.data = opts.data || {};10603 Object.assign(opts.data, {10604 client_id: this.clientAuthentication.clientId,10605 client_secret: this.clientAuthentication.clientSecret || '',10606 });10607 }10608 else {10609 throw new Error(`${contentType} content-types are not supported with ` +10610 `${this.clientAuthentication.confidentialClientType} ` +10611 'client authentication');10612 }10613 }10614 else {10615 throw new Error(`${method} HTTP method does not support ` +10616 `${this.clientAuthentication.confidentialClientType} ` +10617 'client authentication');10618 }10619 }10620 }10621}10622exports.OAuthClientAuthHandler = OAuthClientAuthHandler;10623/**10624 * Converts an OAuth error response to a native JavaScript Error.10625 * @param resp The OAuth error response to convert to a native Error object.10626 * @param err The optional original error. If provided, the error properties10627 * will be copied to the new error.10628 * @return The converted native Error object.10629 */10630function getErrorFromOAuthErrorResponse(resp, err) {10631 // Error response.10632 const errorCode = resp.error;10633 const errorDescription = resp.error_description;10634 const errorUri = resp.error_uri;10635 let message = `Error code ${errorCode}`;10636 if (typeof errorDescription !== 'undefined') {10637 message += `: ${errorDescription}`;10638 }10639 if (typeof errorUri !== 'undefined') {10640 message += ` - ${errorUri}`;10641 }10642 const newError = new Error(message);10643 // Copy properties from original error to newly generated error.10644 if (err) {10645 const keys = Object.keys(err);10646 if (err.stack) {10647 // Copy error.stack if available.10648 keys.push('stack');10649 }10650 keys.forEach(key => {10651 // Do not overwrite the message field.10652 if (key !== 'message') {10653 Object.defineProperty(newError, key, {10654 // eslint-disable-next-line @typescript-eslint/no-explicit-any10655 value: err[key],10656 writable: false,10657 enumerable: true,10658 });10659 }10660 });10661 }10662 return newError;10663}10664exports.getErrorFromOAuthErrorResponse = getErrorFromOAuthErrorResponse;10665//# sourceMappingURL=oauth2common.js.map10666/***/ }),10667/***/ 4782:10668/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {10669"use strict";10670// Copyright 2022 Google LLC10671//10672// Licensed under the Apache License, Version 2.0 (the "License");10673// you may not use this file except in compliance with the License.10674// You may obtain a copy of the License at10675//10676// http://www.apache.org/licenses/LICENSE-2.010677//10678// Unless required by applicable law or agreed to in writing, software10679// distributed under the License is distributed on an "AS IS" BASIS,10680// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.10681// See the License for the specific language governing permissions and10682// limitations under the License.10683Object.defineProperty(exports, "__esModule", ({ value: true }));10684exports.PluggableAuthClient = exports.ExecutableError = void 0;10685const baseexternalclient_1 = __nccwpck_require__(7391);10686const executable_response_1 = __nccwpck_require__(8749);10687const pluggable_auth_handler_1 = __nccwpck_require__(8941);10688/**10689 * Error thrown from the executable run by PluggableAuthClient.10690 */10691class ExecutableError extends Error {10692 constructor(message, code) {10693 super(`The executable failed with exit code: ${code} and error message: ${message}.`);10694 this.code = code;10695 Object.setPrototypeOf(this, new.target.prototype);10696 }10697}10698exports.ExecutableError = ExecutableError;10699/**10700 * The default executable timeout when none is provided, in milliseconds.10701 */10702const DEFAULT_EXECUTABLE_TIMEOUT_MILLIS = 30 * 1000;10703/**10704 * The minimum allowed executable timeout in milliseconds.10705 */10706const MINIMUM_EXECUTABLE_TIMEOUT_MILLIS = 5 * 1000;10707/**10708 * The maximum allowed executable timeout in milliseconds.10709 */10710const MAXIMUM_EXECUTABLE_TIMEOUT_MILLIS = 120 * 1000;10711/**10712 * The environment variable to check to see if executable can be run.10713 * Value must be set to '1' for the executable to run.10714 */10715const GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES = 'GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES';10716/**10717 * The maximum currently supported executable version.10718 */10719const MAXIMUM_EXECUTABLE_VERSION = 1;10720/**10721 * PluggableAuthClient enables the exchange of workload identity pool external credentials for10722 * Google access tokens by retrieving 3rd party tokens through a user supplied executable. These10723 * scripts/executables are completely independent of the Google Cloud Auth libraries. These10724 * credentials plug into ADC and will call the specified executable to retrieve the 3rd party token10725 * to be exchanged for a Google access token.10726 *10727 * <p>To use these credentials, the GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES environment variable10728 * must be set to '1'. This is for security reasons.10729 *10730 * <p>Both OIDC and SAML are supported. The executable must adhere to a specific response format10731 * defined below.10732 *10733 * <p>The executable must print out the 3rd party token to STDOUT in JSON format. When an10734 * output_file is specified in the credential configuration, the executable must also handle writing the10735 * JSON response to this file.10736 *10737 * <pre>10738 * OIDC response sample:10739 * {10740 * "version": 1,10741 * "success": true,10742 * "token_type": "urn:ietf:params:oauth:token-type:id_token",10743 * "id_token": "HEADER.PAYLOAD.SIGNATURE",10744 * "expiration_time": 162043334110745 * }10746 *10747 * SAML2 response sample:10748 * {10749 * "version": 1,10750 * "success": true,10751 * "token_type": "urn:ietf:params:oauth:token-type:saml2",10752 * "saml_response": "...",10753 * "expiration_time": 162043334110754 * }10755 *10756 * Error response sample:10757 * {10758 * "version": 1,10759 * "success": false,10760 * "code": "401",10761 * "message": "Error message."10762 * }10763 * </pre>10764 *10765 * <p>The "expiration_time" field in the JSON response is only required for successful10766 * responses when an output file was specified in the credential configuration10767 *10768 * <p>The auth libraries will populate certain environment variables that will be accessible by the10769 * executable, such as: GOOGLE_EXTERNAL_ACCOUNT_AUDIENCE, GOOGLE_EXTERNAL_ACCOUNT_TOKEN_TYPE,10770 * GOOGLE_EXTERNAL_ACCOUNT_INTERACTIVE, GOOGLE_EXTERNAL_ACCOUNT_IMPERSONATED_EMAIL, and10771 * GOOGLE_EXTERNAL_ACCOUNT_OUTPUT_FILE.10772 *10773 * <p>Please see this repositories README for a complete executable request/response specification.10774 */10775class PluggableAuthClient extends baseexternalclient_1.BaseExternalAccountClient {10776 /**10777 * Instantiates a PluggableAuthClient instance using the provided JSON10778 * object loaded from an external account credentials file.10779 * An error is thrown if the credential is not a valid pluggable auth credential.10780 * @param options The external account options object typically loaded from10781 * the external account JSON credential file.10782 * @param additionalOptions Optional additional behavior customization10783 * options. These currently customize expiration threshold time and10784 * whether to retry on 401/403 API request errors.10785 */10786 constructor(options, additionalOptions) {10787 super(options, additionalOptions);10788 if (!options.credential_source.executable) {10789 throw new Error('No valid Pluggable Auth "credential_source" provided.');10790 }10791 this.command = options.credential_source.executable.command;10792 if (!this.command) {10793 throw new Error('No valid Pluggable Auth "credential_source" provided.');10794 }10795 // Check if the provided timeout exists and if it is valid.10796 if (options.credential_source.executable.timeout_millis === undefined) {10797 this.timeoutMillis = DEFAULT_EXECUTABLE_TIMEOUT_MILLIS;10798 }10799 else {10800 this.timeoutMillis = options.credential_source.executable.timeout_millis;10801 if (this.timeoutMillis < MINIMUM_EXECUTABLE_TIMEOUT_MILLIS ||10802 this.timeoutMillis > MAXIMUM_EXECUTABLE_TIMEOUT_MILLIS) {10803 throw new Error(`Timeout must be between ${MINIMUM_EXECUTABLE_TIMEOUT_MILLIS} and ` +10804 `${MAXIMUM_EXECUTABLE_TIMEOUT_MILLIS} milliseconds.`);10805 }10806 }10807 this.outputFile = options.credential_source.executable.output_file;10808 this.handler = new pluggable_auth_handler_1.PluggableAuthHandler({10809 command: this.command,10810 timeoutMillis: this.timeoutMillis,10811 outputFile: this.outputFile,10812 });10813 }10814 /**10815 * Triggered when an external subject token is needed to be exchanged for a10816 * GCP access token via GCP STS endpoint.10817 * This uses the `options.credential_source` object to figure out how10818 * to retrieve the token using the current environment. In this case,10819 * this calls a user provided executable which returns the subject token.10820 * The logic is summarized as:10821 * 1. Validated that the executable is allowed to run. The10822 * GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES environment must be set to10823 * 1 for security reasons.10824 * 2. If an output file is specified by the user, check the file location10825 * for a response. If the file exists and contains a valid response,10826 * return the subject token from the file.10827 * 3. Call the provided executable and return response.10828 * @return A promise that resolves with the external subject token.10829 */10830 async retrieveSubjectToken() {10831 // Check if the executable is allowed to run.10832 if (process.env[GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES] !== '1') {10833 throw new Error('Pluggable Auth executables need to be explicitly allowed to run by ' +10834 'setting the GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES environment ' +10835 'Variable to 1.');10836 }10837 let executableResponse = undefined;10838 // Try to get cached executable response from output file.10839 if (this.outputFile) {10840 executableResponse = await this.handler.retrieveCachedResponse();10841 }10842 // If no response from output file, call the executable.10843 if (!executableResponse) {10844 // Set up environment map with required values for the executable.10845 const envMap = new Map();10846 envMap.set('GOOGLE_EXTERNAL_ACCOUNT_AUDIENCE', this.audience);10847 envMap.set('GOOGLE_EXTERNAL_ACCOUNT_TOKEN_TYPE', this.subjectTokenType);10848 // Always set to 0 because interactive mode is not supported.10849 envMap.set('GOOGLE_EXTERNAL_ACCOUNT_INTERACTIVE', '0');10850 if (this.outputFile) {10851 envMap.set('GOOGLE_EXTERNAL_ACCOUNT_OUTPUT_FILE', this.outputFile);10852 }10853 const serviceAccountEmail = this.getServiceAccountEmail();10854 if (serviceAccountEmail) {10855 envMap.set('GOOGLE_EXTERNAL_ACCOUNT_IMPERSONATED_EMAIL', serviceAccountEmail);10856 }10857 executableResponse = await this.handler.retrieveResponseFromExecutable(envMap);10858 }10859 if (executableResponse.version > MAXIMUM_EXECUTABLE_VERSION) {10860 throw new Error(`Version of executable is not currently supported, maximum supported version is ${MAXIMUM_EXECUTABLE_VERSION}.`);10861 }10862 // Check that response was successful.10863 if (!executableResponse.success) {10864 throw new ExecutableError(executableResponse.errorMessage, executableResponse.errorCode);10865 }10866 // Check that response contains expiration time if output file was specified.10867 if (this.outputFile) {10868 if (!executableResponse.expirationTime) {10869 throw new executable_response_1.InvalidExpirationTimeFieldError('The executable response must contain the `expiration_time` field for successful responses when an output_file has been specified in the configuration.');10870 }10871 }10872 // Check that response is not expired.10873 if (executableResponse.isExpired()) {10874 throw new Error('Executable response is expired.');10875 }10876 // Return subject token from response.10877 return executableResponse.subjectToken;10878 }10879}10880exports.PluggableAuthClient = PluggableAuthClient;10881//# sourceMappingURL=pluggable-auth-client.js.map10882/***/ }),10883/***/ 8941:10884/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {10885"use strict";10886// Copyright 2022 Google LLC10887//10888// Licensed under the Apache License, Version 2.0 (the "License");10889// you may not use this file except in compliance with the License.10890// You may obtain a copy of the License at10891//10892// http://www.apache.org/licenses/LICENSE-2.010893//10894// Unless required by applicable law or agreed to in writing, software10895// distributed under the License is distributed on an "AS IS" BASIS,10896// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.10897// See the License for the specific language governing permissions and10898// limitations under the License.10899Object.defineProperty(exports, "__esModule", ({ value: true }));10900exports.PluggableAuthHandler = void 0;10901const pluggable_auth_client_1 = __nccwpck_require__(4782);10902const executable_response_1 = __nccwpck_require__(8749);10903const childProcess = __nccwpck_require__(2081);10904const fs = __nccwpck_require__(7147);10905/**10906 * A handler used to retrieve 3rd party token responses from user defined10907 * executables and cached file output for the PluggableAuthClient class.10908 */10909class PluggableAuthHandler {10910 /**10911 * Instantiates a PluggableAuthHandler instance using the provided10912 * PluggableAuthHandlerOptions object.10913 */10914 constructor(options) {10915 if (!options.command) {10916 throw new Error('No command provided.');10917 }10918 this.commandComponents = PluggableAuthHandler.parseCommand(options.command);10919 this.timeoutMillis = options.timeoutMillis;10920 if (!this.timeoutMillis) {10921 throw new Error('No timeoutMillis provided.');10922 }10923 this.outputFile = options.outputFile;10924 }10925 /**10926 * Calls user provided executable to get a 3rd party subject token and10927 * returns the response.10928 * @param envMap a Map of additional Environment Variables required for10929 * the executable.10930 * @return A promise that resolves with the executable response.10931 */10932 retrieveResponseFromExecutable(envMap) {10933 return new Promise((resolve, reject) => {10934 // Spawn process to run executable using added environment variables.10935 const child = childProcess.spawn(this.commandComponents[0], this.commandComponents.slice(1), {10936 env: { ...process.env, ...Object.fromEntries(envMap) },10937 });10938 let output = '';10939 // Append stdout to output as executable runs.10940 child.stdout.on('data', (data) => {10941 output += data;10942 });10943 // Append stderr as executable runs.10944 child.stderr.on('data', (err) => {10945 output += err;10946 });10947 // Set up a timeout to end the child process and throw an error.10948 const timeout = setTimeout(() => {10949 // Kill child process and remove listeners so 'close' event doesn't get10950 // read after child process is killed.10951 child.removeAllListeners();10952 child.kill();10953 return reject(new Error('The executable failed to finish within the timeout specified.'));10954 }, this.timeoutMillis);10955 child.on('close', (code) => {10956 // Cancel timeout if executable closes before timeout is reached.10957 clearTimeout(timeout);10958 if (code === 0) {10959 // If the executable completed successfully, try to return the parsed response.10960 try {10961 const responseJson = JSON.parse(output);10962 const response = new executable_response_1.ExecutableResponse(responseJson);10963 return resolve(response);10964 }10965 catch (error) {10966 if (error instanceof executable_response_1.ExecutableResponseError) {10967 return reject(error);10968 }10969 return reject(new executable_response_1.ExecutableResponseError(`The executable returned an invalid response: ${output}`));10970 }10971 }10972 else {10973 return reject(new pluggable_auth_client_1.ExecutableError(output, code.toString()));10974 }10975 });10976 });10977 }10978 /**10979 * Checks user provided output file for response from previous run of10980 * executable and return the response if it exists, is formatted correctly, and is not expired.10981 */10982 async retrieveCachedResponse() {10983 if (!this.outputFile || this.outputFile.length === 0) {10984 return undefined;10985 }10986 let filePath;10987 try {10988 filePath = await fs.promises.realpath(this.outputFile);10989 }10990 catch (_a) {10991 // If file path cannot be resolved, return undefined.10992 return undefined;10993 }10994 if (!(await fs.promises.lstat(filePath)).isFile()) {10995 // If path does not lead to file, return undefined.10996 return undefined;10997 }10998 const responseString = await fs.promises.readFile(filePath, {10999 encoding: 'utf8',11000 });11001 if (responseString === '') {11002 return undefined;11003 }11004 try {11005 const responseJson = JSON.parse(responseString);11006 const response = new executable_response_1.ExecutableResponse(responseJson);11007 // Check if response is successful and unexpired.11008 if (response.isValid()) {11009 return new executable_response_1.ExecutableResponse(responseJson);11010 }11011 return undefined;11012 }11013 catch (error) {11014 if (error instanceof executable_response_1.ExecutableResponseError) {11015 throw error;11016 }11017 throw new executable_response_1.ExecutableResponseError(`The output file contained an invalid response: ${responseString}`);11018 }11019 }11020 /**11021 * Parses given command string into component array, splitting on spaces unless11022 * spaces are between quotation marks.11023 */11024 static parseCommand(command) {11025 // Split the command into components by splitting on spaces,11026 // unless spaces are contained in quotation marks.11027 const components = command.match(/(?:[^\s"]+|"[^"]*")+/g);11028 if (!components) {11029 throw new Error(`Provided command: "${command}" could not be parsed.`);11030 }11031 // Remove quotation marks from the beginning and end of each component if they are present.11032 for (let i = 0; i < components.length; i++) {11033 if (components[i][0] === '"' && components[i].slice(-1) === '"') {11034 components[i] = components[i].slice(1, -1);11035 }11036 }11037 return components;11038 }11039}11040exports.PluggableAuthHandler = PluggableAuthHandler;11041//# sourceMappingURL=pluggable-auth-handler.js.map11042/***/ }),11043/***/ 8790:11044/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {11045"use strict";11046// Copyright 2015 Google LLC11047//11048// Licensed under the Apache License, Version 2.0 (the "License");11049// you may not use this file except in compliance with the License.11050// You may obtain a copy of the License at11051//11052// http://www.apache.org/licenses/LICENSE-2.011053//11054// Unless required by applicable law or agreed to in writing, software11055// distributed under the License is distributed on an "AS IS" BASIS,11056// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.11057// See the License for the specific language governing permissions and11058// limitations under the License.11059Object.defineProperty(exports, "__esModule", ({ value: true }));11060exports.UserRefreshClient = void 0;11061const oauth2client_1 = __nccwpck_require__(3936);11062class UserRefreshClient extends oauth2client_1.OAuth2Client {11063 constructor(optionsOrClientId, clientSecret, refreshToken, eagerRefreshThresholdMillis, forceRefreshOnFailure) {11064 const opts = optionsOrClientId && typeof optionsOrClientId === 'object'11065 ? optionsOrClientId11066 : {11067 clientId: optionsOrClientId,11068 clientSecret,11069 refreshToken,11070 eagerRefreshThresholdMillis,11071 forceRefreshOnFailure,11072 };11073 super({11074 clientId: opts.clientId,11075 clientSecret: opts.clientSecret,11076 eagerRefreshThresholdMillis: opts.eagerRefreshThresholdMillis,11077 forceRefreshOnFailure: opts.forceRefreshOnFailure,11078 });11079 this._refreshToken = opts.refreshToken;11080 this.credentials.refresh_token = opts.refreshToken;11081 }11082 /**11083 * Refreshes the access token.11084 * @param refreshToken An ignored refreshToken..11085 * @param callback Optional callback.11086 */11087 async refreshTokenNoCache(11088 // eslint-disable-next-line @typescript-eslint/no-unused-vars11089 refreshToken) {11090 return super.refreshTokenNoCache(this._refreshToken);11091 }11092 /**11093 * Create a UserRefreshClient credentials instance using the given input11094 * options.11095 * @param json The input object.11096 */11097 fromJSON(json) {11098 if (!json) {11099 throw new Error('Must pass in a JSON object containing the user refresh token');11100 }11101 if (json.type !== 'authorized_user') {11102 throw new Error('The incoming JSON object does not have the "authorized_user" type');11103 }11104 if (!json.client_id) {11105 throw new Error('The incoming JSON object does not contain a client_id field');11106 }11107 if (!json.client_secret) {11108 throw new Error('The incoming JSON object does not contain a client_secret field');11109 }11110 if (!json.refresh_token) {11111 throw new Error('The incoming JSON object does not contain a refresh_token field');11112 }11113 this._clientId = json.client_id;11114 this._clientSecret = json.client_secret;11115 this._refreshToken = json.refresh_token;11116 this.credentials.refresh_token = json.refresh_token;11117 this.quotaProjectId = json.quota_project_id;11118 }11119 fromStream(inputStream, callback) {11120 if (callback) {11121 this.fromStreamAsync(inputStream).then(() => callback(), callback);11122 }11123 else {11124 return this.fromStreamAsync(inputStream);11125 }11126 }11127 async fromStreamAsync(inputStream) {11128 return new Promise((resolve, reject) => {11129 if (!inputStream) {11130 return reject(new Error('Must pass in a stream containing the user refresh token.'));11131 }11132 let s = '';11133 inputStream11134 .setEncoding('utf8')11135 .on('error', reject)11136 .on('data', chunk => (s += chunk))11137 .on('end', () => {11138 try {11139 const data = JSON.parse(s);11140 this.fromJSON(data);11141 return resolve();11142 }11143 catch (err) {11144 return reject(err);11145 }11146 });11147 });11148 }11149}11150exports.UserRefreshClient = UserRefreshClient;11151//# sourceMappingURL=refreshclient.js.map11152/***/ }),11153/***/ 6308:11154/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {11155"use strict";11156// Copyright 2021 Google LLC11157//11158// Licensed under the Apache License, Version 2.0 (the "License");11159// you may not use this file except in compliance with the License.11160// You may obtain a copy of the License at11161//11162// http://www.apache.org/licenses/LICENSE-2.011163//11164// Unless required by applicable law or agreed to in writing, software11165// distributed under the License is distributed on an "AS IS" BASIS,11166// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.11167// See the License for the specific language governing permissions and11168// limitations under the License.11169Object.defineProperty(exports, "__esModule", ({ value: true }));11170exports.StsCredentials = void 0;11171const gaxios_1 = __nccwpck_require__(9555);11172const querystring = __nccwpck_require__(3477);11173const transporters_1 = __nccwpck_require__(2649);11174const oauth2common_1 = __nccwpck_require__(9510);11175/**11176 * Implements the OAuth 2.0 token exchange based on11177 * https://tools.ietf.org/html/rfc869311178 */11179class StsCredentials extends oauth2common_1.OAuthClientAuthHandler {11180 /**11181 * Initializes an STS credentials instance.11182 * @param tokenExchangeEndpoint The token exchange endpoint.11183 * @param clientAuthentication The client authentication credentials if11184 * available.11185 */11186 constructor(tokenExchangeEndpoint, clientAuthentication) {11187 super(clientAuthentication);11188 this.tokenExchangeEndpoint = tokenExchangeEndpoint;11189 this.transporter = new transporters_1.DefaultTransporter();11190 }11191 /**11192 * Exchanges the provided token for another type of token based on the11193 * rfc8693 spec.11194 * @param stsCredentialsOptions The token exchange options used to populate11195 * the token exchange request.11196 * @param additionalHeaders Optional additional headers to pass along the11197 * request.11198 * @param options Optional additional GCP-specific non-spec defined options11199 * to send with the request.11200 * Example: `&options=${encodeUriComponent(JSON.stringified(options))}`11201 * @return A promise that resolves with the token exchange response containing11202 * the requested token and its expiration time.11203 */11204 async exchangeToken(stsCredentialsOptions, additionalHeaders, 11205 // eslint-disable-next-line @typescript-eslint/no-explicit-any11206 options) {11207 var _a, _b, _c;11208 const values = {11209 grant_type: stsCredentialsOptions.grantType,11210 resource: stsCredentialsOptions.resource,11211 audience: stsCredentialsOptions.audience,11212 scope: (_a = stsCredentialsOptions.scope) === null || _a === void 0 ? void 0 : _a.join(' '),11213 requested_token_type: stsCredentialsOptions.requestedTokenType,11214 subject_token: stsCredentialsOptions.subjectToken,11215 subject_token_type: stsCredentialsOptions.subjectTokenType,11216 actor_token: (_b = stsCredentialsOptions.actingParty) === null || _b === void 0 ? void 0 : _b.actorToken,11217 actor_token_type: (_c = stsCredentialsOptions.actingParty) === null || _c === void 0 ? void 0 : _c.actorTokenType,11218 // Non-standard GCP-specific options.11219 options: options && JSON.stringify(options),11220 };11221 // Remove undefined fields.11222 Object.keys(values).forEach(key => {11223 // eslint-disable-next-line @typescript-eslint/no-explicit-any11224 if (typeof values[key] === 'undefined') {11225 // eslint-disable-next-line @typescript-eslint/no-explicit-any11226 delete values[key];11227 }11228 });11229 const headers = {11230 'Content-Type': 'application/x-www-form-urlencoded',11231 };11232 // Inject additional STS headers if available.11233 Object.assign(headers, additionalHeaders || {});11234 const opts = {11235 url: this.tokenExchangeEndpoint,11236 method: 'POST',11237 headers,11238 data: querystring.stringify(values),11239 responseType: 'json',11240 };11241 // Apply OAuth client authentication.11242 this.applyClientAuthenticationOptions(opts);11243 try {11244 const response = await this.transporter.request(opts);11245 // Successful response.11246 const stsSuccessfulResponse = response.data;11247 stsSuccessfulResponse.res = response;11248 return stsSuccessfulResponse;11249 }11250 catch (error) {11251 // Translate error to OAuthError.11252 if (error instanceof gaxios_1.GaxiosError && error.response) {11253 throw (0, oauth2common_1.getErrorFromOAuthErrorResponse)(error.response.data, 11254 // Preserve other fields from the original error.11255 error);11256 }11257 // Request could fail before the server responds.11258 throw error;11259 }11260 }11261}11262exports.StsCredentials = StsCredentials;11263//# sourceMappingURL=stscredentials.js.map11264/***/ }),11265/***/ 4693:11266/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {11267"use strict";11268// Copyright 2019 Google LLC11269//11270// Licensed under the Apache License, Version 2.0 (the "License");11271// you may not use this file except in compliance with the License.11272// You may obtain a copy of the License at11273//11274// http://www.apache.org/licenses/LICENSE-2.011275//11276// Unless required by applicable law or agreed to in writing, software11277// distributed under the License is distributed on an "AS IS" BASIS,11278// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.11279// See the License for the specific language governing permissions and11280// limitations under the License.11281/* global window */11282Object.defineProperty(exports, "__esModule", ({ value: true }));11283exports.BrowserCrypto = void 0;11284// This file implements crypto functions we need using in-browser11285// SubtleCrypto interface `window.crypto.subtle`.11286const base64js = __nccwpck_require__(6463);11287// Not all browsers support `TextEncoder`. The following `require` will11288// provide a fast UTF8-only replacement for those browsers that don't support11289// text encoding natively.11290// eslint-disable-next-line node/no-unsupported-features/node-builtins11291if (typeof process === 'undefined' && typeof TextEncoder === 'undefined') {11292 __nccwpck_require__(1917);11293}11294const crypto_1 = __nccwpck_require__(8043);11295class BrowserCrypto {11296 constructor() {11297 if (typeof window === 'undefined' ||11298 window.crypto === undefined ||11299 window.crypto.subtle === undefined) {11300 throw new Error("SubtleCrypto not found. Make sure it's an https:// website.");11301 }11302 }11303 async sha256DigestBase64(str) {11304 // SubtleCrypto digest() method is async, so we must make11305 // this method async as well.11306 // To calculate SHA256 digest using SubtleCrypto, we first11307 // need to convert an input string to an ArrayBuffer:11308 // eslint-disable-next-line node/no-unsupported-features/node-builtins11309 const inputBuffer = new TextEncoder().encode(str);11310 // Result is ArrayBuffer as well.11311 const outputBuffer = await window.crypto.subtle.digest('SHA-256', inputBuffer);11312 return base64js.fromByteArray(new Uint8Array(outputBuffer));11313 }11314 randomBytesBase64(count) {11315 const array = new Uint8Array(count);11316 window.crypto.getRandomValues(array);11317 return base64js.fromByteArray(array);11318 }11319 static padBase64(base64) {11320 // base64js requires padding, so let's add some '='11321 while (base64.length % 4 !== 0) {11322 base64 += '=';11323 }11324 return base64;11325 }11326 async verify(pubkey, data, signature) {11327 const algo = {11328 name: 'RSASSA-PKCS1-v1_5',11329 hash: { name: 'SHA-256' },11330 };11331 // eslint-disable-next-line node/no-unsupported-features/node-builtins11332 const dataArray = new TextEncoder().encode(data);11333 const signatureArray = base64js.toByteArray(BrowserCrypto.padBase64(signature));11334 const cryptoKey = await window.crypto.subtle.importKey('jwk', pubkey, algo, true, ['verify']);11335 // SubtleCrypto's verify method is async so we must make11336 // this method async as well.11337 const result = await window.crypto.subtle.verify(algo, cryptoKey, signatureArray, dataArray);11338 return result;11339 }11340 async sign(privateKey, data) {11341 const algo = {11342 name: 'RSASSA-PKCS1-v1_5',11343 hash: { name: 'SHA-256' },11344 };11345 // eslint-disable-next-line node/no-unsupported-features/node-builtins11346 const dataArray = new TextEncoder().encode(data);11347 const cryptoKey = await window.crypto.subtle.importKey('jwk', privateKey, algo, true, ['sign']);11348 // SubtleCrypto's sign method is async so we must make11349 // this method async as well.11350 const result = await window.crypto.subtle.sign(algo, cryptoKey, dataArray);11351 return base64js.fromByteArray(new Uint8Array(result));11352 }11353 decodeBase64StringUtf8(base64) {11354 const uint8array = base64js.toByteArray(BrowserCrypto.padBase64(base64));11355 // eslint-disable-next-line node/no-unsupported-features/node-builtins11356 const result = new TextDecoder().decode(uint8array);11357 return result;11358 }11359 encodeBase64StringUtf8(text) {11360 // eslint-disable-next-line node/no-unsupported-features/node-builtins11361 const uint8array = new TextEncoder().encode(text);11362 const result = base64js.fromByteArray(uint8array);11363 return result;11364 }11365 /**11366 * Computes the SHA-256 hash of the provided string.11367 * @param str The plain text string to hash.11368 * @return A promise that resolves with the SHA-256 hash of the provided11369 * string in hexadecimal encoding.11370 */11371 async sha256DigestHex(str) {11372 // SubtleCrypto digest() method is async, so we must make11373 // this method async as well.11374 // To calculate SHA256 digest using SubtleCrypto, we first11375 // need to convert an input string to an ArrayBuffer:11376 // eslint-disable-next-line node/no-unsupported-features/node-builtins11377 const inputBuffer = new TextEncoder().encode(str);11378 // Result is ArrayBuffer as well.11379 const outputBuffer = await window.crypto.subtle.digest('SHA-256', inputBuffer);11380 return (0, crypto_1.fromArrayBufferToHex)(outputBuffer);11381 }11382 /**11383 * Computes the HMAC hash of a message using the provided crypto key and the11384 * SHA-256 algorithm.11385 * @param key The secret crypto key in utf-8 or ArrayBuffer format.11386 * @param msg The plain text message.11387 * @return A promise that resolves with the HMAC-SHA256 hash in ArrayBuffer11388 * format.11389 */11390 async signWithHmacSha256(key, msg) {11391 // Convert key, if provided in ArrayBuffer format, to string.11392 const rawKey = typeof key === 'string'11393 ? key11394 : String.fromCharCode(...new Uint16Array(key));11395 // eslint-disable-next-line node/no-unsupported-features/node-builtins11396 const enc = new TextEncoder();11397 const cryptoKey = await window.crypto.subtle.importKey('raw', enc.encode(rawKey), {11398 name: 'HMAC',11399 hash: {11400 name: 'SHA-256',11401 },11402 }, false, ['sign']);11403 return window.crypto.subtle.sign('HMAC', cryptoKey, enc.encode(msg));11404 }11405}11406exports.BrowserCrypto = BrowserCrypto;11407//# sourceMappingURL=crypto.js.map11408/***/ }),11409/***/ 8043:11410/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {11411"use strict";11412// Copyright 2019 Google LLC11413//11414// Licensed under the Apache License, Version 2.0 (the "License");11415// you may not use this file except in compliance with the License.11416// You may obtain a copy of the License at11417//11418// http://www.apache.org/licenses/LICENSE-2.011419//11420// Unless required by applicable law or agreed to in writing, software11421// distributed under the License is distributed on an "AS IS" BASIS,11422// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.11423// See the License for the specific language governing permissions and11424// limitations under the License.11425/* global window */11426Object.defineProperty(exports, "__esModule", ({ value: true }));11427exports.fromArrayBufferToHex = exports.hasBrowserCrypto = exports.createCrypto = void 0;11428const crypto_1 = __nccwpck_require__(4693);11429const crypto_2 = __nccwpck_require__(757);11430function createCrypto() {11431 if (hasBrowserCrypto()) {11432 return new crypto_1.BrowserCrypto();11433 }11434 return new crypto_2.NodeCrypto();11435}11436exports.createCrypto = createCrypto;11437function hasBrowserCrypto() {11438 return (typeof window !== 'undefined' &&11439 typeof window.crypto !== 'undefined' &&11440 typeof window.crypto.subtle !== 'undefined');11441}11442exports.hasBrowserCrypto = hasBrowserCrypto;11443/**11444 * Converts an ArrayBuffer to a hexadecimal string.11445 * @param arrayBuffer The ArrayBuffer to convert to hexadecimal string.11446 * @return The hexadecimal encoding of the ArrayBuffer.11447 */11448function fromArrayBufferToHex(arrayBuffer) {11449 // Convert buffer to byte array.11450 const byteArray = Array.from(new Uint8Array(arrayBuffer));11451 // Convert bytes to hex string.11452 return byteArray11453 .map(byte => {11454 return byte.toString(16).padStart(2, '0');11455 })11456 .join('');11457}11458exports.fromArrayBufferToHex = fromArrayBufferToHex;11459//# sourceMappingURL=crypto.js.map11460/***/ }),11461/***/ 757:11462/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {11463"use strict";11464// Copyright 2019 Google LLC11465//11466// Licensed under the Apache License, Version 2.0 (the "License");11467// you may not use this file except in compliance with the License.11468// You may obtain a copy of the License at11469//11470// http://www.apache.org/licenses/LICENSE-2.011471//11472// Unless required by applicable law or agreed to in writing, software11473// distributed under the License is distributed on an "AS IS" BASIS,11474// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.11475// See the License for the specific language governing permissions and11476// limitations under the License.11477Object.defineProperty(exports, "__esModule", ({ value: true }));11478exports.NodeCrypto = void 0;11479const crypto = __nccwpck_require__(6113);11480class NodeCrypto {11481 async sha256DigestBase64(str) {11482 return crypto.createHash('sha256').update(str).digest('base64');11483 }11484 randomBytesBase64(count) {11485 return crypto.randomBytes(count).toString('base64');11486 }11487 async verify(pubkey, data, signature) {11488 const verifier = crypto.createVerify('sha256');11489 verifier.update(data);11490 verifier.end();11491 return verifier.verify(pubkey, signature, 'base64');11492 }11493 async sign(privateKey, data) {11494 const signer = crypto.createSign('RSA-SHA256');11495 signer.update(data);11496 signer.end();11497 return signer.sign(privateKey, 'base64');11498 }11499 decodeBase64StringUtf8(base64) {11500 return Buffer.from(base64, 'base64').toString('utf-8');11501 }11502 encodeBase64StringUtf8(text) {11503 return Buffer.from(text, 'utf-8').toString('base64');11504 }11505 /**11506 * Computes the SHA-256 hash of the provided string.11507 * @param str The plain text string to hash.11508 * @return A promise that resolves with the SHA-256 hash of the provided11509 * string in hexadecimal encoding.11510 */11511 async sha256DigestHex(str) {11512 return crypto.createHash('sha256').update(str).digest('hex');11513 }11514 /**11515 * Computes the HMAC hash of a message using the provided crypto key and the11516 * SHA-256 algorithm.11517 * @param key The secret crypto key in utf-8 or ArrayBuffer format.11518 * @param msg The plain text message.11519 * @return A promise that resolves with the HMAC-SHA256 hash in ArrayBuffer11520 * format.11521 */11522 async signWithHmacSha256(key, msg) {11523 const cryptoKey = typeof key === 'string' ? key : toBuffer(key);11524 return toArrayBuffer(crypto.createHmac('sha256', cryptoKey).update(msg).digest());11525 }11526}11527exports.NodeCrypto = NodeCrypto;11528/**11529 * Converts a Node.js Buffer to an ArrayBuffer.11530 * https://stackoverflow.com/questions/8609289/convert-a-binary-nodejs-buffer-to-javascript-arraybuffer11531 * @param buffer The Buffer input to covert.11532 * @return The ArrayBuffer representation of the input.11533 */11534function toArrayBuffer(buffer) {11535 return buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength);11536}11537/**11538 * Converts an ArrayBuffer to a Node.js Buffer.11539 * @param arrayBuffer The ArrayBuffer input to covert.11540 * @return The Buffer representation of the input.11541 */11542function toBuffer(arrayBuffer) {11543 return Buffer.from(arrayBuffer);11544}11545//# sourceMappingURL=crypto.js.map11546/***/ }),11547/***/ 810:11548/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {11549"use strict";11550Object.defineProperty(exports, "__esModule", ({ value: true }));11551exports.GoogleAuth = exports.auth = exports.DefaultTransporter = exports.PluggableAuthClient = exports.DownscopedClient = exports.BaseExternalAccountClient = exports.ExternalAccountClient = exports.IdentityPoolClient = exports.AwsClient = exports.UserRefreshClient = exports.LoginTicket = exports.OAuth2Client = exports.CodeChallengeMethod = exports.Impersonated = exports.JWT = exports.JWTAccess = exports.IdTokenClient = exports.IAMAuth = exports.GCPEnv = exports.Compute = exports.AuthClient = void 0;11552// Copyright 2017 Google LLC11553//11554// Licensed under the Apache License, Version 2.0 (the "License");11555// you may not use this file except in compliance with the License.11556// You may obtain a copy of the License at11557//11558// http://www.apache.org/licenses/LICENSE-2.011559//11560// Unless required by applicable law or agreed to in writing, software11561// distributed under the License is distributed on an "AS IS" BASIS,11562// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.11563// See the License for the specific language governing permissions and11564// limitations under the License.11565const googleauth_1 = __nccwpck_require__(695);11566Object.defineProperty(exports, "GoogleAuth", ({ enumerable: true, get: function () { return googleauth_1.GoogleAuth; } }));11567var authclient_1 = __nccwpck_require__(4627);11568Object.defineProperty(exports, "AuthClient", ({ enumerable: true, get: function () { return authclient_1.AuthClient; } }));11569var computeclient_1 = __nccwpck_require__(6875);11570Object.defineProperty(exports, "Compute", ({ enumerable: true, get: function () { return computeclient_1.Compute; } }));11571var envDetect_1 = __nccwpck_require__(1380);11572Object.defineProperty(exports, "GCPEnv", ({ enumerable: true, get: function () { return envDetect_1.GCPEnv; } }));11573var iam_1 = __nccwpck_require__(9735);11574Object.defineProperty(exports, "IAMAuth", ({ enumerable: true, get: function () { return iam_1.IAMAuth; } }));11575var idtokenclient_1 = __nccwpck_require__(298);11576Object.defineProperty(exports, "IdTokenClient", ({ enumerable: true, get: function () { return idtokenclient_1.IdTokenClient; } }));11577var jwtaccess_1 = __nccwpck_require__(8740);11578Object.defineProperty(exports, "JWTAccess", ({ enumerable: true, get: function () { return jwtaccess_1.JWTAccess; } }));11579var jwtclient_1 = __nccwpck_require__(3959);11580Object.defineProperty(exports, "JWT", ({ enumerable: true, get: function () { return jwtclient_1.JWT; } }));11581var impersonated_1 = __nccwpck_require__(1103);11582Object.defineProperty(exports, "Impersonated", ({ enumerable: true, get: function () { return impersonated_1.Impersonated; } }));11583var oauth2client_1 = __nccwpck_require__(3936);11584Object.defineProperty(exports, "CodeChallengeMethod", ({ enumerable: true, get: function () { return oauth2client_1.CodeChallengeMethod; } }));11585Object.defineProperty(exports, "OAuth2Client", ({ enumerable: true, get: function () { return oauth2client_1.OAuth2Client; } }));11586var loginticket_1 = __nccwpck_require__(4524);11587Object.defineProperty(exports, "LoginTicket", ({ enumerable: true, get: function () { return loginticket_1.LoginTicket; } }));11588var refreshclient_1 = __nccwpck_require__(8790);11589Object.defineProperty(exports, "UserRefreshClient", ({ enumerable: true, get: function () { return refreshclient_1.UserRefreshClient; } }));11590var awsclient_1 = __nccwpck_require__(1569);11591Object.defineProperty(exports, "AwsClient", ({ enumerable: true, get: function () { return awsclient_1.AwsClient; } }));11592var identitypoolclient_1 = __nccwpck_require__(117);11593Object.defineProperty(exports, "IdentityPoolClient", ({ enumerable: true, get: function () { return identitypoolclient_1.IdentityPoolClient; } }));11594var externalclient_1 = __nccwpck_require__(4381);11595Object.defineProperty(exports, "ExternalAccountClient", ({ enumerable: true, get: function () { return externalclient_1.ExternalAccountClient; } }));11596var baseexternalclient_1 = __nccwpck_require__(7391);11597Object.defineProperty(exports, "BaseExternalAccountClient", ({ enumerable: true, get: function () { return baseexternalclient_1.BaseExternalAccountClient; } }));11598var downscopedclient_1 = __nccwpck_require__(6270);11599Object.defineProperty(exports, "DownscopedClient", ({ enumerable: true, get: function () { return downscopedclient_1.DownscopedClient; } }));11600var pluggable_auth_client_1 = __nccwpck_require__(4782);11601Object.defineProperty(exports, "PluggableAuthClient", ({ enumerable: true, get: function () { return pluggable_auth_client_1.PluggableAuthClient; } }));11602var transporters_1 = __nccwpck_require__(2649);11603Object.defineProperty(exports, "DefaultTransporter", ({ enumerable: true, get: function () { return transporters_1.DefaultTransporter; } }));11604const auth = new googleauth_1.GoogleAuth();11605exports.auth = auth;11606//# sourceMappingURL=index.js.map11607/***/ }),11608/***/ 6608:11609/***/ ((__unused_webpack_module, exports) => {11610"use strict";11611// Copyright 2017 Google LLC11612//11613// Licensed under the Apache License, Version 2.0 (the "License");11614// you may not use this file except in compliance with the License.11615// You may obtain a copy of the License at11616//11617// http://www.apache.org/licenses/LICENSE-2.011618//11619// Unless required by applicable law or agreed to in writing, software11620// distributed under the License is distributed on an "AS IS" BASIS,11621// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.11622// See the License for the specific language governing permissions and11623// limitations under the License.11624Object.defineProperty(exports, "__esModule", ({ value: true }));11625exports.validate = void 0;11626// Accepts an options object passed from the user to the API. In the11627// previous version of the API, it referred to a `Request` options object.11628// Now it refers to an Axiox Request Config object. This is here to help11629// ensure users don't pass invalid options when they upgrade from 0.x to 1.x.11630// eslint-disable-next-line @typescript-eslint/no-explicit-any11631function validate(options) {11632 const vpairs = [11633 { invalid: 'uri', expected: 'url' },11634 { invalid: 'json', expected: 'data' },11635 { invalid: 'qs', expected: 'params' },11636 ];11637 for (const pair of vpairs) {11638 if (options[pair.invalid]) {11639 const e = `'${pair.invalid}' is not a valid configuration option. Please use '${pair.expected}' instead. This library is using Axios for requests. Please see https://github.com/axios/axios to learn more about the valid request options.`;11640 throw new Error(e);11641 }11642 }11643}11644exports.validate = validate;11645//# sourceMappingURL=options.js.map11646/***/ }),11647/***/ 2649:11648/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {11649"use strict";11650// Copyright 2019 Google LLC11651//11652// Licensed under the Apache License, Version 2.0 (the "License");11653// you may not use this file except in compliance with the License.11654// You may obtain a copy of the License at11655//11656// http://www.apache.org/licenses/LICENSE-2.011657//11658// Unless required by applicable law or agreed to in writing, software11659// distributed under the License is distributed on an "AS IS" BASIS,11660// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.11661// See the License for the specific language governing permissions and11662// limitations under the License.11663Object.defineProperty(exports, "__esModule", ({ value: true }));11664exports.DefaultTransporter = void 0;11665const gaxios_1 = __nccwpck_require__(9555);11666const options_1 = __nccwpck_require__(6608);11667// eslint-disable-next-line @typescript-eslint/no-var-requires11668const pkg = __nccwpck_require__(1402);11669const PRODUCT_NAME = 'google-api-nodejs-client';11670class DefaultTransporter {11671 /**11672 * Configures request options before making a request.11673 * @param opts GaxiosOptions options.11674 * @return Configured options.11675 */11676 configure(opts = {}) {11677 opts.headers = opts.headers || {};11678 if (typeof window === 'undefined') {11679 // set transporter user agent if not in browser11680 const uaValue = opts.headers['User-Agent'];11681 if (!uaValue) {11682 opts.headers['User-Agent'] = DefaultTransporter.USER_AGENT;11683 }11684 else if (!uaValue.includes(`${PRODUCT_NAME}/`)) {11685 opts.headers['User-Agent'] = `${uaValue} ${DefaultTransporter.USER_AGENT}`;11686 }11687 // track google-auth-library-nodejs version:11688 const authVersion = `auth/${pkg.version}`;11689 if (opts.headers['x-goog-api-client'] &&11690 !opts.headers['x-goog-api-client'].includes(authVersion)) {11691 opts.headers['x-goog-api-client'] = `${opts.headers['x-goog-api-client']} ${authVersion}`;11692 }11693 else if (!opts.headers['x-goog-api-client']) {11694 const nodeVersion = process.version.replace(/^v/, '');11695 opts.headers['x-goog-api-client'] = `gl-node/${nodeVersion} ${authVersion}`;11696 }11697 }11698 return opts;11699 }11700 request(opts, callback) {11701 // ensure the user isn't passing in request-style options11702 opts = this.configure(opts);11703 try {11704 (0, options_1.validate)(opts);11705 }11706 catch (e) {11707 if (callback) {11708 return callback(e);11709 }11710 else {11711 throw e;11712 }11713 }11714 if (callback) {11715 (0, gaxios_1.request)(opts).then(r => {11716 callback(null, r);11717 }, e => {11718 callback(this.processError(e));11719 });11720 }11721 else {11722 return (0, gaxios_1.request)(opts).catch(e => {11723 throw this.processError(e);11724 });11725 }11726 }11727 /**11728 * Changes the error to include details from the body.11729 */11730 processError(e) {11731 const res = e.response;11732 const err = e;11733 const body = res ? res.data : null;11734 if (res && body && body.error && res.status !== 200) {11735 if (typeof body.error === 'string') {11736 err.message = body.error;11737 err.code = res.status.toString();11738 }11739 else if (Array.isArray(body.error.errors)) {11740 err.message = body.error.errors11741 .map((err2) => err2.message)11742 .join('\n');11743 err.code = body.error.code;11744 err.errors = body.error.errors;11745 }11746 else {11747 err.message = body.error.message;11748 err.code = body.error.code || res.status;11749 }11750 }11751 else if (res && res.status >= 400) {11752 // Consider all 4xx and 5xx responses errors.11753 err.message = body;11754 err.code = res.status.toString();11755 }11756 return err;11757 }11758}11759exports.DefaultTransporter = DefaultTransporter;11760/**11761 * Default user agent.11762 */11763DefaultTransporter.USER_AGENT = `${PRODUCT_NAME}/${pkg.version}`;11764//# sourceMappingURL=transporters.js.map11765/***/ }),11766/***/ 2098:11767/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {11768"use strict";11769/**11770 * Copyright 2018 Google LLC11771 *11772 * Distributed under MIT license.11773 * See file LICENSE for detail or copy at https://opensource.org/licenses/MIT11774 */11775Object.defineProperty(exports, "__esModule", ({ value: true }));11776exports.getPem = void 0;11777const fs = __nccwpck_require__(7147);11778const forge = __nccwpck_require__(7655);11779const util_1 = __nccwpck_require__(3837);11780const readFile = (0, util_1.promisify)(fs.readFile);11781function getPem(filename, callback) {11782 if (callback) {11783 getPemAsync(filename)11784 .then(pem => callback(null, pem))11785 .catch(err => callback(err, null));11786 }11787 else {11788 return getPemAsync(filename);11789 }11790}11791exports.getPem = getPem;11792function getPemAsync(filename) {11793 return readFile(filename, { encoding: 'base64' }).then(keyp12 => {11794 return convertToPem(keyp12);11795 });11796}11797/**11798 * Converts a P12 in base64 encoding to a pem.11799 * @param p12base64 String containing base64 encoded p12.11800 * @returns a string containing the pem.11801 */11802function convertToPem(p12base64) {11803 const p12Der = forge.util.decode64(p12base64);11804 const p12Asn1 = forge.asn1.fromDer(p12Der);11805 const p12 = forge.pkcs12.pkcs12FromAsn1(p12Asn1, 'notasecret');11806 const bags = p12.getBags({ friendlyName: 'privatekey' });11807 if (bags.friendlyName) {11808 const privateKey = bags.friendlyName[0].key;11809 const pem = forge.pki.privateKeyToPem(privateKey);11810 return pem.replace(/\r\n/g, '\n');11811 }11812 else {11813 throw new Error('Unable to get friendly name.');11814 }11815}11816//# sourceMappingURL=index.js.map11817/***/ }),11818/***/ 6031:11819/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {11820"use strict";11821/**11822 * Copyright 2018 Google LLC11823 *11824 * Distributed under MIT license.11825 * See file LICENSE for detail or copy at https://opensource.org/licenses/MIT11826 */11827Object.defineProperty(exports, "__esModule", ({ value: true }));11828exports.GoogleToken = void 0;11829const fs = __nccwpck_require__(7147);11830const gaxios_1 = __nccwpck_require__(9555);11831const jws = __nccwpck_require__(4636);11832const path = __nccwpck_require__(1017);11833const util_1 = __nccwpck_require__(3837);11834const readFile = fs.readFile11835 ? (0, util_1.promisify)(fs.readFile)11836 : async () => {11837 // if running in the web-browser, fs.readFile may not have been shimmed.11838 throw new ErrorWithCode('use key rather than keyFile.', 'MISSING_CREDENTIALS');11839 };11840const GOOGLE_TOKEN_URL = 'https://www.googleapis.com/oauth2/v4/token';11841const GOOGLE_REVOKE_TOKEN_URL = 'https://accounts.google.com/o/oauth2/revoke?token=';11842class ErrorWithCode extends Error {11843 constructor(message, code) {11844 super(message);11845 this.code = code;11846 }11847}11848let getPem;11849class GoogleToken {11850 /**11851 * Create a GoogleToken.11852 *11853 * @param options Configuration object.11854 */11855 constructor(options) {11856 this.transporter = {11857 request: opts => (0, gaxios_1.request)(opts),11858 };11859 this.configure(options);11860 }11861 get accessToken() {11862 return this.rawToken ? this.rawToken.access_token : undefined;11863 }11864 get idToken() {11865 return this.rawToken ? this.rawToken.id_token : undefined;11866 }11867 get tokenType() {11868 return this.rawToken ? this.rawToken.token_type : undefined;11869 }11870 get refreshToken() {11871 return this.rawToken ? this.rawToken.refresh_token : undefined;11872 }11873 /**11874 * Returns whether the token has expired.11875 *11876 * @return true if the token has expired, false otherwise.11877 */11878 hasExpired() {11879 const now = new Date().getTime();11880 if (this.rawToken && this.expiresAt) {11881 return now >= this.expiresAt;11882 }11883 else {11884 return true;11885 }11886 }11887 /**11888 * Returns whether the token will expire within eagerRefreshThresholdMillis11889 *11890 * @return true if the token will be expired within eagerRefreshThresholdMillis, false otherwise.11891 */11892 isTokenExpiring() {11893 var _a;11894 const now = new Date().getTime();11895 const eagerRefreshThresholdMillis = (_a = this.eagerRefreshThresholdMillis) !== null && _a !== void 0 ? _a : 0;11896 if (this.rawToken && this.expiresAt) {11897 return this.expiresAt <= now + eagerRefreshThresholdMillis;11898 }11899 else {11900 return true;11901 }11902 }11903 getToken(callback, opts = {}) {11904 if (typeof callback === 'object') {11905 opts = callback;11906 callback = undefined;11907 }11908 opts = Object.assign({11909 forceRefresh: false,11910 }, opts);11911 if (callback) {11912 const cb = callback;11913 this.getTokenAsync(opts).then(t => cb(null, t), callback);11914 return;11915 }11916 return this.getTokenAsync(opts);11917 }11918 /**11919 * Given a keyFile, extract the key and client email if available11920 * @param keyFile Path to a json, pem, or p12 file that contains the key.11921 * @returns an object with privateKey and clientEmail properties11922 */11923 async getCredentials(keyFile) {11924 const ext = path.extname(keyFile);11925 switch (ext) {11926 case '.json': {11927 const key = await readFile(keyFile, 'utf8');11928 const body = JSON.parse(key);11929 const privateKey = body.private_key;11930 const clientEmail = body.client_email;11931 if (!privateKey || !clientEmail) {11932 throw new ErrorWithCode('private_key and client_email are required.', 'MISSING_CREDENTIALS');11933 }11934 return { privateKey, clientEmail };11935 }11936 case '.der':11937 case '.crt':11938 case '.pem': {11939 const privateKey = await readFile(keyFile, 'utf8');11940 return { privateKey };11941 }11942 case '.p12':11943 case '.pfx': {11944 // NOTE: The loading of `google-p12-pem` is deferred for performance11945 // reasons. The `node-forge` npm module in `google-p12-pem` adds a fair11946 // bit time to overall module loading, and is likely not frequently11947 // used. In a future release, p12 support will be entirely removed.11948 if (!getPem) {11949 getPem = (await Promise.resolve().then(() => __nccwpck_require__(2098))).getPem;11950 }11951 const privateKey = await getPem(keyFile);11952 return { privateKey };11953 }11954 default:11955 throw new ErrorWithCode('Unknown certificate type. Type is determined based on file extension. ' +11956 'Current supported extensions are *.json, *.pem, and *.p12.', 'UNKNOWN_CERTIFICATE_TYPE');11957 }11958 }11959 async getTokenAsync(opts) {11960 if (this.inFlightRequest && !opts.forceRefresh) {11961 return this.inFlightRequest;11962 }11963 try {11964 return await (this.inFlightRequest = this.getTokenAsyncInner(opts));11965 }11966 finally {11967 this.inFlightRequest = undefined;11968 }11969 }11970 async getTokenAsyncInner(opts) {11971 if (this.isTokenExpiring() === false && opts.forceRefresh === false) {11972 return Promise.resolve(this.rawToken);11973 }11974 if (!this.key && !this.keyFile) {11975 throw new Error('No key or keyFile set.');11976 }11977 if (!this.key && this.keyFile) {11978 const creds = await this.getCredentials(this.keyFile);11979 this.key = creds.privateKey;11980 this.iss = creds.clientEmail || this.iss;11981 if (!creds.clientEmail) {11982 this.ensureEmail();11983 }11984 }11985 return this.requestToken();11986 }11987 ensureEmail() {11988 if (!this.iss) {11989 throw new ErrorWithCode('email is required.', 'MISSING_CREDENTIALS');11990 }11991 }11992 revokeToken(callback) {11993 if (callback) {11994 this.revokeTokenAsync().then(() => callback(), callback);11995 return;11996 }11997 return this.revokeTokenAsync();11998 }11999 async revokeTokenAsync() {12000 if (!this.accessToken) {12001 throw new Error('No token to revoke.');12002 }12003 const url = GOOGLE_REVOKE_TOKEN_URL + this.accessToken;12004 await this.transporter.request({ url });12005 this.configure({12006 email: this.iss,12007 sub: this.sub,12008 key: this.key,12009 keyFile: this.keyFile,12010 scope: this.scope,12011 additionalClaims: this.additionalClaims,12012 });12013 }12014 /**12015 * Configure the GoogleToken for re-use.12016 * @param {object} options Configuration object.12017 */12018 configure(options = {}) {12019 this.keyFile = options.keyFile;12020 this.key = options.key;12021 this.rawToken = undefined;12022 this.iss = options.email || options.iss;12023 this.sub = options.sub;12024 this.additionalClaims = options.additionalClaims;12025 if (typeof options.scope === 'object') {12026 this.scope = options.scope.join(' ');12027 }12028 else {12029 this.scope = options.scope;12030 }12031 this.eagerRefreshThresholdMillis = options.eagerRefreshThresholdMillis;12032 if (options.transporter) {12033 this.transporter = options.transporter;12034 }12035 }12036 /**12037 * Request the token from Google.12038 */12039 async requestToken() {12040 var _a, _b;12041 const iat = Math.floor(new Date().getTime() / 1000);12042 const additionalClaims = this.additionalClaims || {};12043 const payload = Object.assign({12044 iss: this.iss,12045 scope: this.scope,12046 aud: GOOGLE_TOKEN_URL,12047 exp: iat + 3600,12048 iat,12049 sub: this.sub,12050 }, additionalClaims);12051 const signedJWT = jws.sign({12052 header: { alg: 'RS256' },12053 payload,12054 secret: this.key,12055 });12056 try {12057 const r = await this.transporter.request({12058 method: 'POST',12059 url: GOOGLE_TOKEN_URL,12060 data: {12061 grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer',12062 assertion: signedJWT,12063 },12064 headers: { 'Content-Type': 'application/x-www-form-urlencoded' },12065 responseType: 'json',12066 });12067 this.rawToken = r.data;12068 this.expiresAt =12069 r.data.expires_in === null || r.data.expires_in === undefined12070 ? undefined12071 : (iat + r.data.expires_in) * 1000;12072 return this.rawToken;12073 }12074 catch (e) {12075 this.rawToken = undefined;12076 this.tokenExpires = undefined;12077 const body = e.response && ((_a = e.response) === null || _a === void 0 ? void 0 : _a.data)12078 ? (_b = e.response) === null || _b === void 0 ? void 0 : _b.data12079 : {};12080 if (body.error) {12081 const desc = body.error_description12082 ? `: ${body.error_description}`12083 : '';12084 e.message = `${body.error}${desc}`;12085 }12086 throw e;12087 }12088 }12089}12090exports.GoogleToken = GoogleToken;12091//# sourceMappingURL=index.js.map12092/***/ }),12093/***/ 5098:12094/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {12095"use strict";12096var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {12097 function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }12098 return new (P || (P = Promise))(function (resolve, reject) {12099 function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }12100 function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }12101 function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }12102 step((generator = generator.apply(thisArg, _arguments || [])).next());12103 });12104};12105var __importDefault = (this && this.__importDefault) || function (mod) {12106 return (mod && mod.__esModule) ? mod : { "default": mod };12107};12108Object.defineProperty(exports, "__esModule", ({ value: true }));12109const net_1 = __importDefault(__nccwpck_require__(1808));12110const tls_1 = __importDefault(__nccwpck_require__(4404));12111const url_1 = __importDefault(__nccwpck_require__(7310));12112const assert_1 = __importDefault(__nccwpck_require__(9491));12113const debug_1 = __importDefault(__nccwpck_require__(8237));12114const agent_base_1 = __nccwpck_require__(9690);12115const parse_proxy_response_1 = __importDefault(__nccwpck_require__(595));12116const debug = debug_1.default('https-proxy-agent:agent');12117/**12118 * The `HttpsProxyAgent` implements an HTTP Agent subclass that connects to12119 * the specified "HTTP(s) proxy server" in order to proxy HTTPS requests.12120 *12121 * Outgoing HTTP requests are first tunneled through the proxy server using the12122 * `CONNECT` HTTP request method to establish a connection to the proxy server,12123 * and then the proxy server connects to the destination target and issues the12124 * HTTP request from the proxy server.12125 *12126 * `https:` requests have their socket connection upgraded to TLS once12127 * the connection to the proxy server has been established.12128 *12129 * @api public12130 */12131class HttpsProxyAgent extends agent_base_1.Agent {12132 constructor(_opts) {12133 let opts;12134 if (typeof _opts === 'string') {12135 opts = url_1.default.parse(_opts);12136 }12137 else {12138 opts = _opts;12139 }12140 if (!opts) {12141 throw new Error('an HTTP(S) proxy server `host` and `port` must be specified!');12142 }12143 debug('creating new HttpsProxyAgent instance: %o', opts);12144 super(opts);12145 const proxy = Object.assign({}, opts);12146 // If `true`, then connect to the proxy server over TLS.12147 // Defaults to `false`.12148 this.secureProxy = opts.secureProxy || isHTTPS(proxy.protocol);12149 // Prefer `hostname` over `host`, and set the `port` if needed.12150 proxy.host = proxy.hostname || proxy.host;12151 if (typeof proxy.port === 'string') {12152 proxy.port = parseInt(proxy.port, 10);12153 }12154 if (!proxy.port && proxy.host) {12155 proxy.port = this.secureProxy ? 443 : 80;12156 }12157 // ALPN is supported by Node.js >= v5.12158 // attempt to negotiate http/1.1 for proxy servers that support http/212159 if (this.secureProxy && !('ALPNProtocols' in proxy)) {12160 proxy.ALPNProtocols = ['http 1.1'];12161 }12162 if (proxy.host && proxy.path) {12163 // If both a `host` and `path` are specified then it's most likely12164 // the result of a `url.parse()` call... we need to remove the12165 // `path` portion so that `net.connect()` doesn't attempt to open12166 // that as a Unix socket file.12167 delete proxy.path;12168 delete proxy.pathname;12169 }12170 this.proxy = proxy;12171 }12172 /**12173 * Called when the node-core HTTP client library is creating a12174 * new HTTP request.12175 *12176 * @api protected12177 */12178 callback(req, opts) {12179 return __awaiter(this, void 0, void 0, function* () {12180 const { proxy, secureProxy } = this;12181 // Create a socket connection to the proxy server.12182 let socket;12183 if (secureProxy) {12184 debug('Creating `tls.Socket`: %o', proxy);12185 socket = tls_1.default.connect(proxy);12186 }12187 else {12188 debug('Creating `net.Socket`: %o', proxy);12189 socket = net_1.default.connect(proxy);12190 }12191 const headers = Object.assign({}, proxy.headers);12192 const hostname = `${opts.host}:${opts.port}`;12193 let payload = `CONNECT ${hostname} HTTP/1.1\r\n`;12194 // Inject the `Proxy-Authorization` header if necessary.12195 if (proxy.auth) {12196 headers['Proxy-Authorization'] = `Basic ${Buffer.from(proxy.auth).toString('base64')}`;12197 }12198 // The `Host` header should only include the port12199 // number when it is not the default port.12200 let { host, port, secureEndpoint } = opts;12201 if (!isDefaultPort(port, secureEndpoint)) {12202 host += `:${port}`;12203 }12204 headers.Host = host;12205 headers.Connection = 'close';12206 for (const name of Object.keys(headers)) {12207 payload += `${name}: ${headers[name]}\r\n`;12208 }12209 const proxyResponsePromise = parse_proxy_response_1.default(socket);12210 socket.write(`${payload}\r\n`);12211 const { statusCode, buffered } = yield proxyResponsePromise;12212 if (statusCode === 200) {12213 req.once('socket', resume);12214 if (opts.secureEndpoint) {12215 // The proxy is connecting to a TLS server, so upgrade12216 // this socket connection to a TLS connection.12217 debug('Upgrading socket connection to TLS');12218 const servername = opts.servername || opts.host;12219 return tls_1.default.connect(Object.assign(Object.assign({}, omit(opts, 'host', 'hostname', 'path', 'port')), { socket,12220 servername }));12221 }12222 return socket;12223 }12224 // Some other status code that's not 200... need to re-play the HTTP12225 // header "data" events onto the socket once the HTTP machinery is12226 // attached so that the node core `http` can parse and handle the12227 // error status code.12228 // Close the original socket, and a new "fake" socket is returned12229 // instead, so that the proxy doesn't get the HTTP request12230 // written to it (which may contain `Authorization` headers or other12231 // sensitive data).12232 //12233 // See: https://hackerone.com/reports/54150212234 socket.destroy();12235 const fakeSocket = new net_1.default.Socket({ writable: false });12236 fakeSocket.readable = true;12237 // Need to wait for the "socket" event to re-play the "data" events.12238 req.once('socket', (s) => {12239 debug('replaying proxy buffer for failed request');12240 assert_1.default(s.listenerCount('data') > 0);12241 // Replay the "buffered" Buffer onto the fake `socket`, since at12242 // this point the HTTP module machinery has been hooked up for12243 // the user.12244 s.push(buffered);12245 s.push(null);12246 });12247 return fakeSocket;12248 });12249 }12250}12251exports["default"] = HttpsProxyAgent;12252function resume(socket) {12253 socket.resume();12254}12255function isDefaultPort(port, secure) {12256 return Boolean((!secure && port === 80) || (secure && port === 443));12257}12258function isHTTPS(protocol) {12259 return typeof protocol === 'string' ? /^https:?$/i.test(protocol) : false;12260}12261function omit(obj, ...keys) {12262 const ret = {};12263 let key;12264 for (key in obj) {12265 if (!keys.includes(key)) {12266 ret[key] = obj[key];12267 }12268 }12269 return ret;12270}12271//# sourceMappingURL=agent.js.map12272/***/ }),12273/***/ 7219:12274/***/ (function(module, __unused_webpack_exports, __nccwpck_require__) {12275"use strict";12276var __importDefault = (this && this.__importDefault) || function (mod) {12277 return (mod && mod.__esModule) ? mod : { "default": mod };12278};12279const agent_1 = __importDefault(__nccwpck_require__(5098));12280function createHttpsProxyAgent(opts) {12281 return new agent_1.default(opts);12282}12283(function (createHttpsProxyAgent) {12284 createHttpsProxyAgent.HttpsProxyAgent = agent_1.default;12285 createHttpsProxyAgent.prototype = agent_1.default.prototype;12286})(createHttpsProxyAgent || (createHttpsProxyAgent = {}));12287module.exports = createHttpsProxyAgent;12288//# sourceMappingURL=index.js.map12289/***/ }),12290/***/ 595:12291/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {12292"use strict";12293var __importDefault = (this && this.__importDefault) || function (mod) {12294 return (mod && mod.__esModule) ? mod : { "default": mod };12295};12296Object.defineProperty(exports, "__esModule", ({ value: true }));12297const debug_1 = __importDefault(__nccwpck_require__(8237));12298const debug = debug_1.default('https-proxy-agent:parse-proxy-response');12299function parseProxyResponse(socket) {12300 return new Promise((resolve, reject) => {12301 // we need to buffer any HTTP traffic that happens with the proxy before we get12302 // the CONNECT response, so that if the response is anything other than an "200"12303 // response code, then we can re-play the "data" events on the socket once the12304 // HTTP parser is hooked up...12305 let buffersLength = 0;12306 const buffers = [];12307 function read() {12308 const b = socket.read();12309 if (b)12310 ondata(b);12311 else12312 socket.once('readable', read);12313 }12314 function cleanup() {12315 socket.removeListener('end', onend);12316 socket.removeListener('error', onerror);12317 socket.removeListener('close', onclose);12318 socket.removeListener('readable', read);12319 }12320 function onclose(err) {12321 debug('onclose had error %o', err);12322 }12323 function onend() {12324 debug('onend');12325 }12326 function onerror(err) {12327 cleanup();12328 debug('onerror %o', err);12329 reject(err);12330 }12331 function ondata(b) {12332 buffers.push(b);12333 buffersLength += b.length;12334 const buffered = Buffer.concat(buffers, buffersLength);12335 const endOfHeaders = buffered.indexOf('\r\n\r\n');12336 if (endOfHeaders === -1) {12337 // keep buffering12338 debug('have not received end of HTTP headers yet...');12339 read();12340 return;12341 }12342 const firstLine = buffered.toString('ascii', 0, buffered.indexOf('\r\n'));12343 const statusCode = +firstLine.split(' ')[1];12344 debug('got proxy server response: %o', firstLine);12345 resolve({12346 statusCode,12347 buffered12348 });12349 }12350 socket.on('error', onerror);12351 socket.on('close', onclose);12352 socket.on('end', onend);12353 read();12354 });12355}12356exports["default"] = parseProxyResponse;12357//# sourceMappingURL=parse-proxy-response.js.map12358/***/ }),12359/***/ 1554:12360/***/ ((module) => {12361"use strict";12362const isStream = stream =>12363 stream !== null &&12364 typeof stream === 'object' &&12365 typeof stream.pipe === 'function';12366isStream.writable = stream =>12367 isStream(stream) &&12368 stream.writable !== false &&12369 typeof stream._write === 'function' &&12370 typeof stream._writableState === 'object';12371isStream.readable = stream =>12372 isStream(stream) &&12373 stream.readable !== false &&12374 typeof stream._read === 'function' &&12375 typeof stream._readableState === 'object';12376isStream.duplex = stream =>12377 isStream.writable(stream) &&12378 isStream.readable(stream);12379isStream.transform = stream =>12380 isStream.duplex(stream) &&12381 typeof stream._transform === 'function';12382module.exports = isStream;12383/***/ }),12384/***/ 5031:12385/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {12386var json_stringify = (__nccwpck_require__(8574).stringify);12387var json_parse = __nccwpck_require__(9099);12388module.exports = function(options) {12389 return {12390 parse: json_parse(options),12391 stringify: json_stringify12392 }12393};12394//create the default method members with no options applied for backwards compatibility12395module.exports.parse = json_parse();12396module.exports.stringify = json_stringify;12397/***/ }),12398/***/ 9099:12399/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {12400var BigNumber = null;12401// regexpxs extracted from12402// (c) BSD-3-Clause12403// https://github.com/fastify/secure-json-parse/graphs/contributors and https://github.com/hapijs/bourne/graphs/contributors12404const suspectProtoRx = /(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])/;12405const suspectConstructorRx = /(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)/;12406/*12407 json_parse.js12408 2012-06-2012409 Public Domain.12410 NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.12411 This file creates a json_parse function.12412 During create you can (optionally) specify some behavioural switches12413 require('json-bigint')(options)12414 The optional options parameter holds switches that drive certain12415 aspects of the parsing process:12416 * options.strict = true will warn about duplicate-key usage in the json.12417 The default (strict = false) will silently ignore those and overwrite12418 values for keys that are in duplicate use.12419 The resulting function follows this signature:12420 json_parse(text, reviver)12421 This method parses a JSON text to produce an object or array.12422 It can throw a SyntaxError exception.12423 The optional reviver parameter is a function that can filter and12424 transform the results. It receives each of the keys and values,12425 and its return value is used instead of the original value.12426 If it returns what it received, then the structure is not modified.12427 If it returns undefined then the member is deleted.12428 Example:12429 // Parse the text. Values that look like ISO date strings will12430 // be converted to Date objects.12431 myData = json_parse(text, function (key, value) {12432 var a;12433 if (typeof value === 'string') {12434 a =12435/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);12436 if (a) {12437 return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],12438 +a[5], +a[6]));12439 }12440 }12441 return value;12442 });12443 This is a reference implementation. You are free to copy, modify, or12444 redistribute.12445 This code should be minified before deployment.12446 See http://javascript.crockford.com/jsmin.html12447 USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO12448 NOT CONTROL.12449*/12450/*members "", "\"", "\/", "\\", at, b, call, charAt, f, fromCharCode,12451 hasOwnProperty, message, n, name, prototype, push, r, t, text12452*/12453var json_parse = function (options) {12454 'use strict';12455 // This is a function that can parse a JSON text, producing a JavaScript12456 // data structure. It is a simple, recursive descent parser. It does not use12457 // eval or regular expressions, so it can be used as a model for implementing12458 // a JSON parser in other languages.12459 // We are defining the function inside of another function to avoid creating12460 // global variables.12461 // Default options one can override by passing options to the parse()12462 var _options = {12463 strict: false, // not being strict means do not generate syntax errors for "duplicate key"12464 storeAsString: false, // toggles whether the values should be stored as BigNumber (default) or a string12465 alwaysParseAsBig: false, // toggles whether all numbers should be Big12466 useNativeBigInt: false, // toggles whether to use native BigInt instead of bignumber.js12467 protoAction: 'error',12468 constructorAction: 'error',12469 };12470 // If there are options, then use them to override the default _options12471 if (options !== undefined && options !== null) {12472 if (options.strict === true) {12473 _options.strict = true;12474 }12475 if (options.storeAsString === true) {12476 _options.storeAsString = true;12477 }12478 _options.alwaysParseAsBig =12479 options.alwaysParseAsBig === true ? options.alwaysParseAsBig : false;12480 _options.useNativeBigInt =12481 options.useNativeBigInt === true ? options.useNativeBigInt : false;12482 if (typeof options.constructorAction !== 'undefined') {12483 if (12484 options.constructorAction === 'error' ||12485 options.constructorAction === 'ignore' ||12486 options.constructorAction === 'preserve'12487 ) {12488 _options.constructorAction = options.constructorAction;12489 } else {12490 throw new Error(12491 `Incorrect value for constructorAction option, must be "error", "ignore" or undefined but passed ${options.constructorAction}`12492 );12493 }12494 }12495 if (typeof options.protoAction !== 'undefined') {12496 if (12497 options.protoAction === 'error' ||12498 options.protoAction === 'ignore' ||12499 options.protoAction === 'preserve'12500 ) {12501 _options.protoAction = options.protoAction;12502 } else {12503 throw new Error(12504 `Incorrect value for protoAction option, must be "error", "ignore" or undefined but passed ${options.protoAction}`12505 );12506 }12507 }12508 }12509 var at, // The index of the current character12510 ch, // The current character12511 escapee = {12512 '"': '"',12513 '\\': '\\',12514 '/': '/',12515 b: '\b',12516 f: '\f',12517 n: '\n',12518 r: '\r',12519 t: '\t',12520 },12521 text,12522 error = function (m) {12523 // Call error when something is wrong.12524 throw {12525 name: 'SyntaxError',12526 message: m,12527 at: at,12528 text: text,12529 };12530 },12531 next = function (c) {12532 // If a c parameter is provided, verify that it matches the current character.12533 if (c && c !== ch) {12534 error("Expected '" + c + "' instead of '" + ch + "'");12535 }12536 // Get the next character. When there are no more characters,12537 // return the empty string.12538 ch = text.charAt(at);12539 at += 1;12540 return ch;12541 },12542 number = function () {12543 // Parse a number value.12544 var number,12545 string = '';12546 if (ch === '-') {12547 string = '-';12548 next('-');12549 }12550 while (ch >= '0' && ch <= '9') {12551 string += ch;12552 next();12553 }12554 if (ch === '.') {12555 string += '.';12556 while (next() && ch >= '0' && ch <= '9') {12557 string += ch;12558 }12559 }12560 if (ch === 'e' || ch === 'E') {12561 string += ch;12562 next();12563 if (ch === '-' || ch === '+') {12564 string += ch;12565 next();12566 }12567 while (ch >= '0' && ch <= '9') {12568 string += ch;12569 next();12570 }12571 }12572 number = +string;12573 if (!isFinite(number)) {12574 error('Bad number');12575 } else {12576 if (BigNumber == null) BigNumber = __nccwpck_require__(7558);12577 //if (number > 9007199254740992 || number < -9007199254740992)12578 // Bignumber has stricter check: everything with length > 15 digits disallowed12579 if (string.length > 15)12580 return _options.storeAsString12581 ? string12582 : _options.useNativeBigInt12583 ? BigInt(string)12584 : new BigNumber(string);12585 else12586 return !_options.alwaysParseAsBig12587 ? number12588 : _options.useNativeBigInt12589 ? BigInt(number)12590 : new BigNumber(number);12591 }12592 },12593 string = function () {12594 // Parse a string value.12595 var hex,12596 i,12597 string = '',12598 uffff;12599 // When parsing for string values, we must look for " and \ characters.12600 if (ch === '"') {12601 var startAt = at;12602 while (next()) {12603 if (ch === '"') {12604 if (at - 1 > startAt) string += text.substring(startAt, at - 1);12605 next();12606 return string;12607 }12608 if (ch === '\\') {12609 if (at - 1 > startAt) string += text.substring(startAt, at - 1);12610 next();12611 if (ch === 'u') {12612 uffff = 0;12613 for (i = 0; i < 4; i += 1) {12614 hex = parseInt(next(), 16);12615 if (!isFinite(hex)) {12616 break;12617 }12618 uffff = uffff * 16 + hex;12619 }12620 string += String.fromCharCode(uffff);12621 } else if (typeof escapee[ch] === 'string') {12622 string += escapee[ch];12623 } else {12624 break;12625 }12626 startAt = at;12627 }12628 }12629 }12630 error('Bad string');12631 },12632 white = function () {12633 // Skip whitespace.12634 while (ch && ch <= ' ') {12635 next();12636 }12637 },12638 word = function () {12639 // true, false, or null.12640 switch (ch) {12641 case 't':12642 next('t');12643 next('r');12644 next('u');12645 next('e');12646 return true;12647 case 'f':12648 next('f');12649 next('a');12650 next('l');12651 next('s');12652 next('e');12653 return false;12654 case 'n':12655 next('n');12656 next('u');12657 next('l');12658 next('l');12659 return null;12660 }12661 error("Unexpected '" + ch + "'");12662 },12663 value, // Place holder for the value function.12664 array = function () {12665 // Parse an array value.12666 var array = [];12667 if (ch === '[') {12668 next('[');12669 white();12670 if (ch === ']') {12671 next(']');12672 return array; // empty array12673 }12674 while (ch) {12675 array.push(value());12676 white();12677 if (ch === ']') {12678 next(']');12679 return array;12680 }12681 next(',');12682 white();12683 }12684 }12685 error('Bad array');12686 },12687 object = function () {12688 // Parse an object value.12689 var key,12690 object = Object.create(null);12691 if (ch === '{') {12692 next('{');12693 white();12694 if (ch === '}') {12695 next('}');12696 return object; // empty object12697 }12698 while (ch) {12699 key = string();12700 white();12701 next(':');12702 if (12703 _options.strict === true &&12704 Object.hasOwnProperty.call(object, key)12705 ) {12706 error('Duplicate key "' + key + '"');12707 }12708 if (suspectProtoRx.test(key) === true) {12709 if (_options.protoAction === 'error') {12710 error('Object contains forbidden prototype property');12711 } else if (_options.protoAction === 'ignore') {12712 value();12713 } else {12714 object[key] = value();12715 }12716 } else if (suspectConstructorRx.test(key) === true) {12717 if (_options.constructorAction === 'error') {12718 error('Object contains forbidden constructor property');12719 } else if (_options.constructorAction === 'ignore') {12720 value();12721 } else {12722 object[key] = value();12723 }12724 } else {12725 object[key] = value();12726 }12727 white();12728 if (ch === '}') {12729 next('}');12730 return object;12731 }12732 next(',');12733 white();12734 }12735 }12736 error('Bad object');12737 };12738 value = function () {12739 // Parse a JSON value. It could be an object, an array, a string, a number,12740 // or a word.12741 white();12742 switch (ch) {12743 case '{':12744 return object();12745 case '[':12746 return array();12747 case '"':12748 return string();12749 case '-':12750 return number();12751 default:12752 return ch >= '0' && ch <= '9' ? number() : word();12753 }12754 };12755 // Return the json_parse function. It will have access to all of the above12756 // functions and variables.12757 return function (source, reviver) {12758 var result;12759 text = source + '';12760 at = 0;12761 ch = ' ';12762 result = value();12763 white();12764 if (ch) {12765 error('Syntax error');12766 }12767 // If there is a reviver function, we recursively walk the new structure,12768 // passing each name/value pair to the reviver function for possible12769 // transformation, starting with a temporary root object that holds the result12770 // in an empty key. If there is not a reviver function, we simply return the12771 // result.12772 return typeof reviver === 'function'12773 ? (function walk(holder, key) {12774 var k,12775 v,12776 value = holder[key];12777 if (value && typeof value === 'object') {12778 Object.keys(value).forEach(function (k) {12779 v = walk(value, k);12780 if (v !== undefined) {12781 value[k] = v;12782 } else {12783 delete value[k];12784 }12785 });12786 }12787 return reviver.call(holder, key, value);12788 })({ '': result }, '')12789 : result;12790 };12791};12792module.exports = json_parse;12793/***/ }),12794/***/ 8574:12795/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {12796var BigNumber = __nccwpck_require__(7558);12797/*12798 json2.js12799 2013-05-2612800 Public Domain.12801 NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.12802 See http://www.JSON.org/js.html12803 This code should be minified before deployment.12804 See http://javascript.crockford.com/jsmin.html12805 USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO12806 NOT CONTROL.12807 This file creates a global JSON object containing two methods: stringify12808 and parse.12809 JSON.stringify(value, replacer, space)12810 value any JavaScript value, usually an object or array.12811 replacer an optional parameter that determines how object12812 values are stringified for objects. It can be a12813 function or an array of strings.12814 space an optional parameter that specifies the indentation12815 of nested structures. If it is omitted, the text will12816 be packed without extra whitespace. If it is a number,12817 it will specify the number of spaces to indent at each12818 level. If it is a string (such as '\t' or ' '),12819 it contains the characters used to indent at each level.12820 This method produces a JSON text from a JavaScript value.12821 When an object value is found, if the object contains a toJSON12822 method, its toJSON method will be called and the result will be12823 stringified. A toJSON method does not serialize: it returns the12824 value represented by the name/value pair that should be serialized,12825 or undefined if nothing should be serialized. The toJSON method12826 will be passed the key associated with the value, and this will be12827 bound to the value12828 For example, this would serialize Dates as ISO strings.12829 Date.prototype.toJSON = function (key) {12830 function f(n) {12831 // Format integers to have at least two digits.12832 return n < 10 ? '0' + n : n;12833 }12834 return this.getUTCFullYear() + '-' +12835 f(this.getUTCMonth() + 1) + '-' +12836 f(this.getUTCDate()) + 'T' +12837 f(this.getUTCHours()) + ':' +12838 f(this.getUTCMinutes()) + ':' +12839 f(this.getUTCSeconds()) + 'Z';12840 };12841 You can provide an optional replacer method. It will be passed the12842 key and value of each member, with this bound to the containing12843 object. The value that is returned from your method will be12844 serialized. If your method returns undefined, then the member will12845 be excluded from the serialization.12846 If the replacer parameter is an array of strings, then it will be12847 used to select the members to be serialized. It filters the results12848 such that only members with keys listed in the replacer array are12849 stringified.12850 Values that do not have JSON representations, such as undefined or12851 functions, will not be serialized. Such values in objects will be12852 dropped; in arrays they will be replaced with null. You can use12853 a replacer function to replace those with JSON values.12854 JSON.stringify(undefined) returns undefined.12855 The optional space parameter produces a stringification of the12856 value that is filled with line breaks and indentation to make it12857 easier to read.12858 If the space parameter is a non-empty string, then that string will12859 be used for indentation. If the space parameter is a number, then12860 the indentation will be that many spaces.12861 Example:12862 text = JSON.stringify(['e', {pluribus: 'unum'}]);12863 // text is '["e",{"pluribus":"unum"}]'12864 text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t');12865 // text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]'12866 text = JSON.stringify([new Date()], function (key, value) {12867 return this[key] instanceof Date ?12868 'Date(' + this[key] + ')' : value;12869 });12870 // text is '["Date(---current time---)"]'12871 JSON.parse(text, reviver)12872 This method parses a JSON text to produce an object or array.12873 It can throw a SyntaxError exception.12874 The optional reviver parameter is a function that can filter and12875 transform the results. It receives each of the keys and values,12876 and its return value is used instead of the original value.12877 If it returns what it received, then the structure is not modified.12878 If it returns undefined then the member is deleted.12879 Example:12880 // Parse the text. Values that look like ISO date strings will12881 // be converted to Date objects.12882 myData = JSON.parse(text, function (key, value) {12883 var a;12884 if (typeof value === 'string') {12885 a =12886/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);12887 if (a) {12888 return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],12889 +a[5], +a[6]));12890 }12891 }12892 return value;12893 });12894 myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) {12895 var d;12896 if (typeof value === 'string' &&12897 value.slice(0, 5) === 'Date(' &&12898 value.slice(-1) === ')') {12899 d = new Date(value.slice(5, -1));12900 if (d) {12901 return d;12902 }12903 }12904 return value;12905 });12906 This is a reference implementation. You are free to copy, modify, or12907 redistribute.12908*/12909/*jslint evil: true, regexp: true */12910/*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply,12911 call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours,12912 getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join,12913 lastIndex, length, parse, prototype, push, replace, slice, stringify,12914 test, toJSON, toString, valueOf12915*/12916// Create a JSON object only if one does not already exist. We create the12917// methods in a closure to avoid creating global variables.12918var JSON = module.exports;12919(function () {12920 'use strict';12921 function f(n) {12922 // Format integers to have at least two digits.12923 return n < 10 ? '0' + n : n;12924 }12925 var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,12926 escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,12927 gap,12928 indent,12929 meta = { // table of character substitutions12930 '\b': '\\b',12931 '\t': '\\t',12932 '\n': '\\n',12933 '\f': '\\f',12934 '\r': '\\r',12935 '"' : '\\"',12936 '\\': '\\\\'12937 },12938 rep;12939 function quote(string) {12940// If the string contains no control characters, no quote characters, and no12941// backslash characters, then we can safely slap some quotes around it.12942// Otherwise we must also replace the offending characters with safe escape12943// sequences.12944 escapable.lastIndex = 0;12945 return escapable.test(string) ? '"' + string.replace(escapable, function (a) {12946 var c = meta[a];12947 return typeof c === 'string'12948 ? c12949 : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);12950 }) + '"' : '"' + string + '"';12951 }12952 function str(key, holder) {12953// Produce a string from holder[key].12954 var i, // The loop counter.12955 k, // The member key.12956 v, // The member value.12957 length,12958 mind = gap,12959 partial,12960 value = holder[key],12961 isBigNumber = value != null && (value instanceof BigNumber || BigNumber.isBigNumber(value));12962// If the value has a toJSON method, call it to obtain a replacement value.12963 if (value && typeof value === 'object' &&12964 typeof value.toJSON === 'function') {12965 value = value.toJSON(key);12966 }12967// If we were called with a replacer function, then call the replacer to12968// obtain a replacement value.12969 if (typeof rep === 'function') {12970 value = rep.call(holder, key, value);12971 }12972// What happens next depends on the value's type.12973 switch (typeof value) {12974 case 'string':12975 if (isBigNumber) {12976 return value;12977 } else {12978 return quote(value);12979 }12980 case 'number':12981// JSON numbers must be finite. Encode non-finite numbers as null.12982 return isFinite(value) ? String(value) : 'null';12983 case 'boolean':12984 case 'null':12985 case 'bigint':12986// If the value is a boolean or null, convert it to a string. Note:12987// typeof null does not produce 'null'. The case is included here in12988// the remote chance that this gets fixed someday.12989 return String(value);12990// If the type is 'object', we might be dealing with an object or an array or12991// null.12992 case 'object':12993// Due to a specification blunder in ECMAScript, typeof null is 'object',12994// so watch out for that case.12995 if (!value) {12996 return 'null';12997 }12998// Make an array to hold the partial results of stringifying this object value.12999 gap += indent;13000 partial = [];13001// Is the value an array?13002 if (Object.prototype.toString.apply(value) === '[object Array]') {13003// The value is an array. Stringify every element. Use null as a placeholder13004// for non-JSON values.13005 length = value.length;13006 for (i = 0; i < length; i += 1) {13007 partial[i] = str(i, value) || 'null';13008 }13009// Join all of the elements together, separated with commas, and wrap them in13010// brackets.13011 v = partial.length === 013012 ? '[]'13013 : gap13014 ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']'13015 : '[' + partial.join(',') + ']';13016 gap = mind;13017 return v;13018 }13019// If the replacer is an array, use it to select the members to be stringified.13020 if (rep && typeof rep === 'object') {13021 length = rep.length;13022 for (i = 0; i < length; i += 1) {13023 if (typeof rep[i] === 'string') {13024 k = rep[i];13025 v = str(k, value);13026 if (v) {13027 partial.push(quote(k) + (gap ? ': ' : ':') + v);13028 }13029 }13030 }13031 } else {13032// Otherwise, iterate through all of the keys in the object.13033 Object.keys(value).forEach(function(k) {13034 var v = str(k, value);13035 if (v) {13036 partial.push(quote(k) + (gap ? ': ' : ':') + v);13037 }13038 });13039 }13040// Join all of the member texts together, separated with commas,13041// and wrap them in braces.13042 v = partial.length === 013043 ? '{}'13044 : gap13045 ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}'13046 : '{' + partial.join(',') + '}';13047 gap = mind;13048 return v;13049 }13050 }13051// If the JSON object does not yet have a stringify method, give it one.13052 if (typeof JSON.stringify !== 'function') {13053 JSON.stringify = function (value, replacer, space) {13054// The stringify method takes a value and an optional replacer, and an optional13055// space parameter, and returns a JSON text. The replacer can be a function13056// that can replace values, or an array of strings that will select the keys.13057// A default replacer method can be provided. Use of the space parameter can13058// produce text that is more easily readable.13059 var i;13060 gap = '';13061 indent = '';13062// If the space parameter is a number, make an indent string containing that13063// many spaces.13064 if (typeof space === 'number') {13065 for (i = 0; i < space; i += 1) {13066 indent += ' ';13067 }13068// If the space parameter is a string, it will be used as the indent string.13069 } else if (typeof space === 'string') {13070 indent = space;13071 }13072// If there is a replacer, it must be a function or an array.13073// Otherwise, throw an error.13074 rep = replacer;13075 if (replacer && typeof replacer !== 'function' &&13076 (typeof replacer !== 'object' ||13077 typeof replacer.length !== 'number')) {13078 throw new Error('JSON.stringify');13079 }13080// Make a fake root object containing our value under the key of ''.13081// Return the result of stringifying the value.13082 return str('', {'': value});13083 };13084 }13085}());13086/***/ }),13087/***/ 6010:13088/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {13089var bufferEqual = __nccwpck_require__(9239);13090var Buffer = (__nccwpck_require__(1867).Buffer);13091var crypto = __nccwpck_require__(6113);13092var formatEcdsa = __nccwpck_require__(1728);13093var util = __nccwpck_require__(3837);13094var MSG_INVALID_ALGORITHM = '"%s" is not a valid algorithm.\n Supported algorithms are:\n "HS256", "HS384", "HS512", "RS256", "RS384", "RS512", "PS256", "PS384", "PS512", "ES256", "ES384", "ES512" and "none".'13095var MSG_INVALID_SECRET = 'secret must be a string or buffer';13096var MSG_INVALID_VERIFIER_KEY = 'key must be a string or a buffer';13097var MSG_INVALID_SIGNER_KEY = 'key must be a string, a buffer or an object';13098var supportsKeyObjects = typeof crypto.createPublicKey === 'function';13099if (supportsKeyObjects) {13100 MSG_INVALID_VERIFIER_KEY += ' or a KeyObject';13101 MSG_INVALID_SECRET += 'or a KeyObject';13102}13103function checkIsPublicKey(key) {13104 if (Buffer.isBuffer(key)) {13105 return;13106 }13107 if (typeof key === 'string') {13108 return;13109 }13110 if (!supportsKeyObjects) {13111 throw typeError(MSG_INVALID_VERIFIER_KEY);13112 }13113 if (typeof key !== 'object') {13114 throw typeError(MSG_INVALID_VERIFIER_KEY);13115 }13116 if (typeof key.type !== 'string') {13117 throw typeError(MSG_INVALID_VERIFIER_KEY);13118 }13119 if (typeof key.asymmetricKeyType !== 'string') {13120 throw typeError(MSG_INVALID_VERIFIER_KEY);13121 }13122 if (typeof key.export !== 'function') {13123 throw typeError(MSG_INVALID_VERIFIER_KEY);13124 }13125};13126function checkIsPrivateKey(key) {13127 if (Buffer.isBuffer(key)) {13128 return;13129 }13130 if (typeof key === 'string') {13131 return;13132 }13133 if (typeof key === 'object') {13134 return;13135 }13136 throw typeError(MSG_INVALID_SIGNER_KEY);13137};13138function checkIsSecretKey(key) {13139 if (Buffer.isBuffer(key)) {13140 return;13141 }13142 if (typeof key === 'string') {13143 return key;13144 }13145 if (!supportsKeyObjects) {13146 throw typeError(MSG_INVALID_SECRET);13147 }13148 if (typeof key !== 'object') {13149 throw typeError(MSG_INVALID_SECRET);13150 }13151 if (key.type !== 'secret') {13152 throw typeError(MSG_INVALID_SECRET);13153 }13154 if (typeof key.export !== 'function') {13155 throw typeError(MSG_INVALID_SECRET);13156 }13157}13158function fromBase64(base64) {13159 return base6413160 .replace(/=/g, '')13161 .replace(/\+/g, '-')13162 .replace(/\//g, '_');13163}13164function toBase64(base64url) {13165 base64url = base64url.toString();13166 var padding = 4 - base64url.length % 4;13167 if (padding !== 4) {13168 for (var i = 0; i < padding; ++i) {13169 base64url += '=';13170 }13171 }13172 return base64url13173 .replace(/\-/g, '+')13174 .replace(/_/g, '/');13175}13176function typeError(template) {13177 var args = [].slice.call(arguments, 1);13178 var errMsg = util.format.bind(util, template).apply(null, args);13179 return new TypeError(errMsg);13180}13181function bufferOrString(obj) {13182 return Buffer.isBuffer(obj) || typeof obj === 'string';13183}13184function normalizeInput(thing) {13185 if (!bufferOrString(thing))13186 thing = JSON.stringify(thing);13187 return thing;13188}13189function createHmacSigner(bits) {13190 return function sign(thing, secret) {13191 checkIsSecretKey(secret);13192 thing = normalizeInput(thing);13193 var hmac = crypto.createHmac('sha' + bits, secret);13194 var sig = (hmac.update(thing), hmac.digest('base64'))13195 return fromBase64(sig);13196 }13197}13198function createHmacVerifier(bits) {13199 return function verify(thing, signature, secret) {13200 var computedSig = createHmacSigner(bits)(thing, secret);13201 return bufferEqual(Buffer.from(signature), Buffer.from(computedSig));13202 }13203}13204function createKeySigner(bits) {13205 return function sign(thing, privateKey) {13206 checkIsPrivateKey(privateKey);13207 thing = normalizeInput(thing);13208 // Even though we are specifying "RSA" here, this works with ECDSA13209 // keys as well.13210 var signer = crypto.createSign('RSA-SHA' + bits);13211 var sig = (signer.update(thing), signer.sign(privateKey, 'base64'));13212 return fromBase64(sig);13213 }13214}13215function createKeyVerifier(bits) {13216 return function verify(thing, signature, publicKey) {13217 checkIsPublicKey(publicKey);13218 thing = normalizeInput(thing);13219 signature = toBase64(signature);13220 var verifier = crypto.createVerify('RSA-SHA' + bits);13221 verifier.update(thing);13222 return verifier.verify(publicKey, signature, 'base64');13223 }13224}13225function createPSSKeySigner(bits) {13226 return function sign(thing, privateKey) {13227 checkIsPrivateKey(privateKey);13228 thing = normalizeInput(thing);13229 var signer = crypto.createSign('RSA-SHA' + bits);13230 var sig = (signer.update(thing), signer.sign({13231 key: privateKey,13232 padding: crypto.constants.RSA_PKCS1_PSS_PADDING,13233 saltLength: crypto.constants.RSA_PSS_SALTLEN_DIGEST13234 }, 'base64'));13235 return fromBase64(sig);13236 }13237}13238function createPSSKeyVerifier(bits) {13239 return function verify(thing, signature, publicKey) {13240 checkIsPublicKey(publicKey);13241 thing = normalizeInput(thing);13242 signature = toBase64(signature);13243 var verifier = crypto.createVerify('RSA-SHA' + bits);13244 verifier.update(thing);13245 return verifier.verify({13246 key: publicKey,13247 padding: crypto.constants.RSA_PKCS1_PSS_PADDING,13248 saltLength: crypto.constants.RSA_PSS_SALTLEN_DIGEST13249 }, signature, 'base64');13250 }13251}13252function createECDSASigner(bits) {13253 var inner = createKeySigner(bits);13254 return function sign() {13255 var signature = inner.apply(null, arguments);13256 signature = formatEcdsa.derToJose(signature, 'ES' + bits);13257 return signature;13258 };13259}13260function createECDSAVerifer(bits) {13261 var inner = createKeyVerifier(bits);13262 return function verify(thing, signature, publicKey) {13263 signature = formatEcdsa.joseToDer(signature, 'ES' + bits).toString('base64');13264 var result = inner(thing, signature, publicKey);13265 return result;13266 };13267}13268function createNoneSigner() {13269 return function sign() {13270 return '';13271 }13272}13273function createNoneVerifier() {13274 return function verify(thing, signature) {13275 return signature === '';13276 }13277}13278module.exports = function jwa(algorithm) {13279 var signerFactories = {13280 hs: createHmacSigner,13281 rs: createKeySigner,13282 ps: createPSSKeySigner,13283 es: createECDSASigner,13284 none: createNoneSigner,13285 }13286 var verifierFactories = {13287 hs: createHmacVerifier,13288 rs: createKeyVerifier,13289 ps: createPSSKeyVerifier,13290 es: createECDSAVerifer,13291 none: createNoneVerifier,13292 }13293 var match = algorithm.match(/^(RS|PS|ES|HS)(256|384|512)$|^(none)$/);13294 if (!match)13295 throw typeError(MSG_INVALID_ALGORITHM, algorithm);13296 var algo = (match[1] || match[3]).toLowerCase();13297 var bits = match[2];13298 return {13299 sign: signerFactories[algo](bits),13300 verify: verifierFactories[algo](bits),13301 }13302};13303/***/ }),13304/***/ 4636:13305/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {13306/*global exports*/13307var SignStream = __nccwpck_require__(3334);13308var VerifyStream = __nccwpck_require__(5522);13309var ALGORITHMS = [13310 'HS256', 'HS384', 'HS512',13311 'RS256', 'RS384', 'RS512',13312 'PS256', 'PS384', 'PS512',13313 'ES256', 'ES384', 'ES512'13314];13315exports.ALGORITHMS = ALGORITHMS;13316exports.sign = SignStream.sign;13317exports.verify = VerifyStream.verify;13318exports.decode = VerifyStream.decode;13319exports.isValid = VerifyStream.isValid;13320exports.createSign = function createSign(opts) {13321 return new SignStream(opts);13322};13323exports.createVerify = function createVerify(opts) {13324 return new VerifyStream(opts);13325};13326/***/ }),13327/***/ 1868:13328/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {13329/*global module, process*/13330var Buffer = (__nccwpck_require__(1867).Buffer);13331var Stream = __nccwpck_require__(2781);13332var util = __nccwpck_require__(3837);13333function DataStream(data) {13334 this.buffer = null;13335 this.writable = true;13336 this.readable = true;13337 // No input13338 if (!data) {13339 this.buffer = Buffer.alloc(0);13340 return this;13341 }13342 // Stream13343 if (typeof data.pipe === 'function') {13344 this.buffer = Buffer.alloc(0);13345 data.pipe(this);13346 return this;13347 }13348 // Buffer or String13349 // or Object (assumedly a passworded key)13350 if (data.length || typeof data === 'object') {13351 this.buffer = data;13352 this.writable = false;13353 process.nextTick(function () {13354 this.emit('end', data);13355 this.readable = false;13356 this.emit('close');13357 }.bind(this));13358 return this;13359 }13360 throw new TypeError('Unexpected data type ('+ typeof data + ')');13361}13362util.inherits(DataStream, Stream);13363DataStream.prototype.write = function write(data) {13364 this.buffer = Buffer.concat([this.buffer, Buffer.from(data)]);13365 this.emit('data', data);13366};13367DataStream.prototype.end = function end(data) {13368 if (data)13369 this.write(data);13370 this.emit('end', data);13371 this.emit('close');13372 this.writable = false;13373 this.readable = false;13374};13375module.exports = DataStream;13376/***/ }),13377/***/ 3334:13378/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {13379/*global module*/13380var Buffer = (__nccwpck_require__(1867).Buffer);13381var DataStream = __nccwpck_require__(1868);13382var jwa = __nccwpck_require__(6010);13383var Stream = __nccwpck_require__(2781);13384var toString = __nccwpck_require__(5292);13385var util = __nccwpck_require__(3837);13386function base64url(string, encoding) {13387 return Buffer13388 .from(string, encoding)13389 .toString('base64')13390 .replace(/=/g, '')13391 .replace(/\+/g, '-')13392 .replace(/\//g, '_');13393}13394function jwsSecuredInput(header, payload, encoding) {13395 encoding = encoding || 'utf8';13396 var encodedHeader = base64url(toString(header), 'binary');13397 var encodedPayload = base64url(toString(payload), encoding);13398 return util.format('%s.%s', encodedHeader, encodedPayload);13399}13400function jwsSign(opts) {13401 var header = opts.header;13402 var payload = opts.payload;13403 var secretOrKey = opts.secret || opts.privateKey;13404 var encoding = opts.encoding;13405 var algo = jwa(header.alg);13406 var securedInput = jwsSecuredInput(header, payload, encoding);13407 var signature = algo.sign(securedInput, secretOrKey);13408 return util.format('%s.%s', securedInput, signature);13409}13410function SignStream(opts) {13411 var secret = opts.secret||opts.privateKey||opts.key;13412 var secretStream = new DataStream(secret);13413 this.readable = true;13414 this.header = opts.header;13415 this.encoding = opts.encoding;13416 this.secret = this.privateKey = this.key = secretStream;13417 this.payload = new DataStream(opts.payload);13418 this.secret.once('close', function () {13419 if (!this.payload.writable && this.readable)13420 this.sign();13421 }.bind(this));13422 this.payload.once('close', function () {13423 if (!this.secret.writable && this.readable)13424 this.sign();13425 }.bind(this));13426}13427util.inherits(SignStream, Stream);13428SignStream.prototype.sign = function sign() {13429 try {13430 var signature = jwsSign({13431 header: this.header,13432 payload: this.payload.buffer,13433 secret: this.secret.buffer,13434 encoding: this.encoding13435 });13436 this.emit('done', signature);13437 this.emit('data', signature);13438 this.emit('end');13439 this.readable = false;13440 return signature;13441 } catch (e) {13442 this.readable = false;13443 this.emit('error', e);13444 this.emit('close');13445 }13446};13447SignStream.sign = jwsSign;13448module.exports = SignStream;13449/***/ }),13450/***/ 5292:13451/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {13452/*global module*/13453var Buffer = (__nccwpck_require__(4300).Buffer);13454module.exports = function toString(obj) {13455 if (typeof obj === 'string')13456 return obj;13457 if (typeof obj === 'number' || Buffer.isBuffer(obj))13458 return obj.toString();13459 return JSON.stringify(obj);13460};13461/***/ }),13462/***/ 5522:13463/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {13464/*global module*/13465var Buffer = (__nccwpck_require__(1867).Buffer);13466var DataStream = __nccwpck_require__(1868);13467var jwa = __nccwpck_require__(6010);13468var Stream = __nccwpck_require__(2781);13469var toString = __nccwpck_require__(5292);13470var util = __nccwpck_require__(3837);13471var JWS_REGEX = /^[a-zA-Z0-9\-_]+?\.[a-zA-Z0-9\-_]+?\.([a-zA-Z0-9\-_]+)?$/;13472function isObject(thing) {13473 return Object.prototype.toString.call(thing) === '[object Object]';13474}13475function safeJsonParse(thing) {13476 if (isObject(thing))13477 return thing;13478 try { return JSON.parse(thing); }13479 catch (e) { return undefined; }13480}13481function headerFromJWS(jwsSig) {13482 var encodedHeader = jwsSig.split('.', 1)[0];13483 return safeJsonParse(Buffer.from(encodedHeader, 'base64').toString('binary'));13484}13485function securedInputFromJWS(jwsSig) {13486 return jwsSig.split('.', 2).join('.');13487}13488function signatureFromJWS(jwsSig) {13489 return jwsSig.split('.')[2];13490}13491function payloadFromJWS(jwsSig, encoding) {13492 encoding = encoding || 'utf8';13493 var payload = jwsSig.split('.')[1];13494 return Buffer.from(payload, 'base64').toString(encoding);13495}13496function isValidJws(string) {13497 return JWS_REGEX.test(string) && !!headerFromJWS(string);13498}13499function jwsVerify(jwsSig, algorithm, secretOrKey) {13500 if (!algorithm) {13501 var err = new Error("Missing algorithm parameter for jws.verify");13502 err.code = "MISSING_ALGORITHM";13503 throw err;13504 }13505 jwsSig = toString(jwsSig);13506 var signature = signatureFromJWS(jwsSig);13507 var securedInput = securedInputFromJWS(jwsSig);13508 var algo = jwa(algorithm);13509 return algo.verify(securedInput, signature, secretOrKey);13510}13511function jwsDecode(jwsSig, opts) {13512 opts = opts || {};13513 jwsSig = toString(jwsSig);13514 if (!isValidJws(jwsSig))13515 return null;13516 var header = headerFromJWS(jwsSig);13517 if (!header)13518 return null;13519 var payload = payloadFromJWS(jwsSig);13520 if (header.typ === 'JWT' || opts.json)13521 payload = JSON.parse(payload, opts.encoding);13522 return {13523 header: header,13524 payload: payload,13525 signature: signatureFromJWS(jwsSig)13526 };13527}13528function VerifyStream(opts) {13529 opts = opts || {};13530 var secretOrKey = opts.secret||opts.publicKey||opts.key;13531 var secretStream = new DataStream(secretOrKey);13532 this.readable = true;13533 this.algorithm = opts.algorithm;13534 this.encoding = opts.encoding;13535 this.secret = this.publicKey = this.key = secretStream;13536 this.signature = new DataStream(opts.signature);13537 this.secret.once('close', function () {13538 if (!this.signature.writable && this.readable)13539 this.verify();13540 }.bind(this));13541 this.signature.once('close', function () {13542 if (!this.secret.writable && this.readable)13543 this.verify();13544 }.bind(this));13545}13546util.inherits(VerifyStream, Stream);13547VerifyStream.prototype.verify = function verify() {13548 try {13549 var valid = jwsVerify(this.signature.buffer, this.algorithm, this.key.buffer);13550 var obj = jwsDecode(this.signature.buffer, this.encoding);13551 this.emit('done', valid, obj);13552 this.emit('data', valid);13553 this.emit('end');13554 this.readable = false;13555 return valid;13556 } catch (e) {13557 this.readable = false;13558 this.emit('error', e);13559 this.emit('close');13560 }13561};13562VerifyStream.decode = jwsDecode;13563VerifyStream.isValid = isValidJws;13564VerifyStream.verify = jwsVerify;13565module.exports = VerifyStream;13566/***/ }),13567/***/ 7129:13568/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {13569"use strict";13570// A linked list to keep track of recently-used-ness13571const Yallist = __nccwpck_require__(665)13572const MAX = Symbol('max')13573const LENGTH = Symbol('length')13574const LENGTH_CALCULATOR = Symbol('lengthCalculator')13575const ALLOW_STALE = Symbol('allowStale')13576const MAX_AGE = Symbol('maxAge')13577const DISPOSE = Symbol('dispose')13578const NO_DISPOSE_ON_SET = Symbol('noDisposeOnSet')13579const LRU_LIST = Symbol('lruList')13580const CACHE = Symbol('cache')13581const UPDATE_AGE_ON_GET = Symbol('updateAgeOnGet')13582const naiveLength = () => 113583// lruList is a yallist where the head is the youngest13584// item, and the tail is the oldest. the list contains the Hit13585// objects as the entries.13586// Each Hit object has a reference to its Yallist.Node. This13587// never changes.13588//13589// cache is a Map (or PseudoMap) that matches the keys to13590// the Yallist.Node object.13591class LRUCache {13592 constructor (options) {13593 if (typeof options === 'number')13594 options = { max: options }13595 if (!options)13596 options = {}13597 if (options.max && (typeof options.max !== 'number' || options.max < 0))13598 throw new TypeError('max must be a non-negative number')13599 // Kind of weird to have a default max of Infinity, but oh well.13600 const max = this[MAX] = options.max || Infinity13601 const lc = options.length || naiveLength13602 this[LENGTH_CALCULATOR] = (typeof lc !== 'function') ? naiveLength : lc13603 this[ALLOW_STALE] = options.stale || false13604 if (options.maxAge && typeof options.maxAge !== 'number')13605 throw new TypeError('maxAge must be a number')13606 this[MAX_AGE] = options.maxAge || 013607 this[DISPOSE] = options.dispose13608 this[NO_DISPOSE_ON_SET] = options.noDisposeOnSet || false13609 this[UPDATE_AGE_ON_GET] = options.updateAgeOnGet || false13610 this.reset()13611 }13612 // resize the cache when the max changes.13613 set max (mL) {13614 if (typeof mL !== 'number' || mL < 0)13615 throw new TypeError('max must be a non-negative number')13616 this[MAX] = mL || Infinity13617 trim(this)13618 }13619 get max () {13620 return this[MAX]13621 }13622 set allowStale (allowStale) {13623 this[ALLOW_STALE] = !!allowStale13624 }13625 get allowStale () {13626 return this[ALLOW_STALE]13627 }13628 set maxAge (mA) {13629 if (typeof mA !== 'number')13630 throw new TypeError('maxAge must be a non-negative number')13631 this[MAX_AGE] = mA13632 trim(this)13633 }13634 get maxAge () {13635 return this[MAX_AGE]13636 }13637 // resize the cache when the lengthCalculator changes.13638 set lengthCalculator (lC) {13639 if (typeof lC !== 'function')13640 lC = naiveLength13641 if (lC !== this[LENGTH_CALCULATOR]) {13642 this[LENGTH_CALCULATOR] = lC13643 this[LENGTH] = 013644 this[LRU_LIST].forEach(hit => {13645 hit.length = this[LENGTH_CALCULATOR](hit.value, hit.key)13646 this[LENGTH] += hit.length13647 })13648 }13649 trim(this)13650 }13651 get lengthCalculator () { return this[LENGTH_CALCULATOR] }13652 get length () { return this[LENGTH] }13653 get itemCount () { return this[LRU_LIST].length }13654 rforEach (fn, thisp) {13655 thisp = thisp || this13656 for (let walker = this[LRU_LIST].tail; walker !== null;) {13657 const prev = walker.prev13658 forEachStep(this, fn, walker, thisp)13659 walker = prev13660 }13661 }13662 forEach (fn, thisp) {13663 thisp = thisp || this13664 for (let walker = this[LRU_LIST].head; walker !== null;) {13665 const next = walker.next13666 forEachStep(this, fn, walker, thisp)13667 walker = next13668 }13669 }13670 keys () {13671 return this[LRU_LIST].toArray().map(k => k.key)13672 }13673 values () {13674 return this[LRU_LIST].toArray().map(k => k.value)13675 }13676 reset () {13677 if (this[DISPOSE] &&13678 this[LRU_LIST] &&13679 this[LRU_LIST].length) {13680 this[LRU_LIST].forEach(hit => this[DISPOSE](hit.key, hit.value))13681 }13682 this[CACHE] = new Map() // hash of items by key13683 this[LRU_LIST] = new Yallist() // list of items in order of use recency13684 this[LENGTH] = 0 // length of items in the list13685 }13686 dump () {13687 return this[LRU_LIST].map(hit =>13688 isStale(this, hit) ? false : {13689 k: hit.key,13690 v: hit.value,13691 e: hit.now + (hit.maxAge || 0)13692 }).toArray().filter(h => h)13693 }13694 dumpLru () {13695 return this[LRU_LIST]13696 }13697 set (key, value, maxAge) {13698 maxAge = maxAge || this[MAX_AGE]13699 if (maxAge && typeof maxAge !== 'number')13700 throw new TypeError('maxAge must be a number')13701 const now = maxAge ? Date.now() : 013702 const len = this[LENGTH_CALCULATOR](value, key)13703 if (this[CACHE].has(key)) {13704 if (len > this[MAX]) {13705 del(this, this[CACHE].get(key))13706 return false13707 }13708 const node = this[CACHE].get(key)13709 const item = node.value13710 // dispose of the old one before overwriting13711 // split out into 2 ifs for better coverage tracking13712 if (this[DISPOSE]) {13713 if (!this[NO_DISPOSE_ON_SET])13714 this[DISPOSE](key, item.value)13715 }13716 item.now = now13717 item.maxAge = maxAge13718 item.value = value13719 this[LENGTH] += len - item.length13720 item.length = len13721 this.get(key)13722 trim(this)13723 return true13724 }13725 const hit = new Entry(key, value, len, now, maxAge)13726 // oversized objects fall out of cache automatically.13727 if (hit.length > this[MAX]) {13728 if (this[DISPOSE])13729 this[DISPOSE](key, value)13730 return false13731 }13732 this[LENGTH] += hit.length13733 this[LRU_LIST].unshift(hit)13734 this[CACHE].set(key, this[LRU_LIST].head)13735 trim(this)13736 return true13737 }13738 has (key) {13739 if (!this[CACHE].has(key)) return false13740 const hit = this[CACHE].get(key).value13741 return !isStale(this, hit)13742 }13743 get (key) {13744 return get(this, key, true)13745 }13746 peek (key) {13747 return get(this, key, false)13748 }13749 pop () {13750 const node = this[LRU_LIST].tail13751 if (!node)13752 return null13753 del(this, node)13754 return node.value13755 }13756 del (key) {13757 del(this, this[CACHE].get(key))13758 }13759 load (arr) {13760 // reset the cache13761 this.reset()13762 const now = Date.now()13763 // A previous serialized cache has the most recent items first13764 for (let l = arr.length - 1; l >= 0; l--) {13765 const hit = arr[l]13766 const expiresAt = hit.e || 013767 if (expiresAt === 0)13768 // the item was created without expiration in a non aged cache13769 this.set(hit.k, hit.v)13770 else {13771 const maxAge = expiresAt - now13772 // dont add already expired items13773 if (maxAge > 0) {13774 this.set(hit.k, hit.v, maxAge)13775 }13776 }13777 }13778 }13779 prune () {13780 this[CACHE].forEach((value, key) => get(this, key, false))13781 }13782}13783const get = (self, key, doUse) => {13784 const node = self[CACHE].get(key)13785 if (node) {13786 const hit = node.value13787 if (isStale(self, hit)) {13788 del(self, node)13789 if (!self[ALLOW_STALE])13790 return undefined13791 } else {13792 if (doUse) {13793 if (self[UPDATE_AGE_ON_GET])13794 node.value.now = Date.now()13795 self[LRU_LIST].unshiftNode(node)13796 }13797 }13798 return hit.value13799 }13800}13801const isStale = (self, hit) => {13802 if (!hit || (!hit.maxAge && !self[MAX_AGE]))13803 return false13804 const diff = Date.now() - hit.now13805 return hit.maxAge ? diff > hit.maxAge13806 : self[MAX_AGE] && (diff > self[MAX_AGE])13807}13808const trim = self => {13809 if (self[LENGTH] > self[MAX]) {13810 for (let walker = self[LRU_LIST].tail;13811 self[LENGTH] > self[MAX] && walker !== null;) {13812 // We know that we're about to delete this one, and also13813 // what the next least recently used key will be, so just13814 // go ahead and set it now.13815 const prev = walker.prev13816 del(self, walker)13817 walker = prev13818 }13819 }13820}13821const del = (self, node) => {13822 if (node) {13823 const hit = node.value13824 if (self[DISPOSE])13825 self[DISPOSE](hit.key, hit.value)13826 self[LENGTH] -= hit.length13827 self[CACHE].delete(hit.key)13828 self[LRU_LIST].removeNode(node)13829 }13830}13831class Entry {13832 constructor (key, value, length, now, maxAge) {13833 this.key = key13834 this.value = value13835 this.length = length13836 this.now = now13837 this.maxAge = maxAge || 013838 }13839}13840const forEachStep = (self, fn, node, thisp) => {13841 let hit = node.value13842 if (isStale(self, hit)) {13843 del(self, node)13844 if (!self[ALLOW_STALE])13845 hit = undefined13846 }13847 if (hit)13848 fn.call(thisp, hit.value, hit.key, self)13849}13850module.exports = LRUCache13851/***/ }),13852/***/ 900:13853/***/ ((module) => {13854/**13855 * Helpers.13856 */13857var s = 1000;13858var m = s * 60;13859var h = m * 60;13860var d = h * 24;13861var w = d * 7;13862var y = d * 365.25;13863/**13864 * Parse or format the given `val`.13865 *13866 * Options:13867 *13868 * - `long` verbose formatting [false]13869 *13870 * @param {String|Number} val13871 * @param {Object} [options]13872 * @throws {Error} throw an error if val is not a non-empty string or a number13873 * @return {String|Number}13874 * @api public13875 */13876module.exports = function(val, options) {13877 options = options || {};13878 var type = typeof val;13879 if (type === 'string' && val.length > 0) {13880 return parse(val);13881 } else if (type === 'number' && isFinite(val)) {13882 return options.long ? fmtLong(val) : fmtShort(val);13883 }13884 throw new Error(13885 'val is not a non-empty string or a valid number. val=' +13886 JSON.stringify(val)13887 );13888};13889/**13890 * Parse the given `str` and return milliseconds.13891 *13892 * @param {String} str13893 * @return {Number}13894 * @api private13895 */13896function parse(str) {13897 str = String(str);13898 if (str.length > 100) {13899 return;13900 }13901 var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(13902 str13903 );13904 if (!match) {13905 return;13906 }13907 var n = parseFloat(match[1]);13908 var type = (match[2] || 'ms').toLowerCase();13909 switch (type) {13910 case 'years':13911 case 'year':13912 case 'yrs':13913 case 'yr':13914 case 'y':13915 return n * y;13916 case 'weeks':13917 case 'week':13918 case 'w':13919 return n * w;13920 case 'days':13921 case 'day':13922 case 'd':13923 return n * d;13924 case 'hours':13925 case 'hour':13926 case 'hrs':13927 case 'hr':13928 case 'h':13929 return n * h;13930 case 'minutes':13931 case 'minute':13932 case 'mins':13933 case 'min':13934 case 'm':13935 return n * m;13936 case 'seconds':13937 case 'second':13938 case 'secs':13939 case 'sec':13940 case 's':13941 return n * s;13942 case 'milliseconds':13943 case 'millisecond':13944 case 'msecs':13945 case 'msec':13946 case 'ms':13947 return n;13948 default:13949 return undefined;13950 }13951}13952/**13953 * Short format for `ms`.13954 *13955 * @param {Number} ms13956 * @return {String}13957 * @api private13958 */13959function fmtShort(ms) {13960 var msAbs = Math.abs(ms);13961 if (msAbs >= d) {13962 return Math.round(ms / d) + 'd';13963 }13964 if (msAbs >= h) {13965 return Math.round(ms / h) + 'h';13966 }13967 if (msAbs >= m) {13968 return Math.round(ms / m) + 'm';13969 }13970 if (msAbs >= s) {13971 return Math.round(ms / s) + 's';13972 }13973 return ms + 'ms';13974}13975/**13976 * Long format for `ms`.13977 *13978 * @param {Number} ms13979 * @return {String}13980 * @api private13981 */13982function fmtLong(ms) {13983 var msAbs = Math.abs(ms);13984 if (msAbs >= d) {13985 return plural(ms, msAbs, d, 'day');13986 }13987 if (msAbs >= h) {13988 return plural(ms, msAbs, h, 'hour');13989 }13990 if (msAbs >= m) {13991 return plural(ms, msAbs, m, 'minute');13992 }13993 if (msAbs >= s) {13994 return plural(ms, msAbs, s, 'second');13995 }13996 return ms + ' ms';13997}13998/**13999 * Pluralization helper.14000 */14001function plural(ms, msAbs, n, name) {14002 var isPlural = msAbs >= n * 1.5;14003 return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');14004}14005/***/ }),14006/***/ 467:14007/***/ ((module, exports, __nccwpck_require__) => {14008"use strict";14009Object.defineProperty(exports, "__esModule", ({ value: true }));14010function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }14011var Stream = _interopDefault(__nccwpck_require__(2781));14012var http = _interopDefault(__nccwpck_require__(3685));14013var Url = _interopDefault(__nccwpck_require__(7310));14014var whatwgUrl = _interopDefault(__nccwpck_require__(8665));14015var https = _interopDefault(__nccwpck_require__(5687));14016var zlib = _interopDefault(__nccwpck_require__(9796));14017// Based on https://github.com/tmpvar/jsdom/blob/aa85b2abf07766ff7bf5c1f6daafb3726f2f2db5/lib/jsdom/living/blob.js14018// fix for "Readable" isn't a named export issue14019const Readable = Stream.Readable;14020const BUFFER = Symbol('buffer');14021const TYPE = Symbol('type');14022class Blob {14023 constructor() {14024 this[TYPE] = '';14025 const blobParts = arguments[0];14026 const options = arguments[1];14027 const buffers = [];14028 let size = 0;14029 if (blobParts) {14030 const a = blobParts;14031 const length = Number(a.length);14032 for (let i = 0; i < length; i++) {14033 const element = a[i];14034 let buffer;14035 if (element instanceof Buffer) {14036 buffer = element;14037 } else if (ArrayBuffer.isView(element)) {14038 buffer = Buffer.from(element.buffer, element.byteOffset, element.byteLength);14039 } else if (element instanceof ArrayBuffer) {14040 buffer = Buffer.from(element);14041 } else if (element instanceof Blob) {14042 buffer = element[BUFFER];14043 } else {14044 buffer = Buffer.from(typeof element === 'string' ? element : String(element));14045 }14046 size += buffer.length;14047 buffers.push(buffer);14048 }14049 }14050 this[BUFFER] = Buffer.concat(buffers);14051 let type = options && options.type !== undefined && String(options.type).toLowerCase();14052 if (type && !/[^\u0020-\u007E]/.test(type)) {14053 this[TYPE] = type;14054 }14055 }14056 get size() {14057 return this[BUFFER].length;14058 }14059 get type() {14060 return this[TYPE];14061 }14062 text() {14063 return Promise.resolve(this[BUFFER].toString());14064 }14065 arrayBuffer() {14066 const buf = this[BUFFER];14067 const ab = buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);14068 return Promise.resolve(ab);14069 }14070 stream() {14071 const readable = new Readable();14072 readable._read = function () {};14073 readable.push(this[BUFFER]);14074 readable.push(null);14075 return readable;14076 }14077 toString() {14078 return '[object Blob]';14079 }14080 slice() {14081 const size = this.size;14082 const start = arguments[0];14083 const end = arguments[1];14084 let relativeStart, relativeEnd;14085 if (start === undefined) {14086 relativeStart = 0;14087 } else if (start < 0) {14088 relativeStart = Math.max(size + start, 0);14089 } else {14090 relativeStart = Math.min(start, size);14091 }14092 if (end === undefined) {14093 relativeEnd = size;14094 } else if (end < 0) {14095 relativeEnd = Math.max(size + end, 0);14096 } else {14097 relativeEnd = Math.min(end, size);14098 }14099 const span = Math.max(relativeEnd - relativeStart, 0);14100 const buffer = this[BUFFER];14101 const slicedBuffer = buffer.slice(relativeStart, relativeStart + span);14102 const blob = new Blob([], { type: arguments[2] });14103 blob[BUFFER] = slicedBuffer;14104 return blob;14105 }14106}14107Object.defineProperties(Blob.prototype, {14108 size: { enumerable: true },14109 type: { enumerable: true },14110 slice: { enumerable: true }14111});14112Object.defineProperty(Blob.prototype, Symbol.toStringTag, {14113 value: 'Blob',14114 writable: false,14115 enumerable: false,14116 configurable: true14117});14118/**14119 * fetch-error.js14120 *14121 * FetchError interface for operational errors14122 */14123/**14124 * Create FetchError instance14125 *14126 * @param String message Error message for human14127 * @param String type Error type for machine14128 * @param String systemError For Node.js system error14129 * @return FetchError14130 */14131function FetchError(message, type, systemError) {14132 Error.call(this, message);14133 this.message = message;14134 this.type = type;14135 // when err.type is `system`, err.code contains system error code14136 if (systemError) {14137 this.code = this.errno = systemError.code;14138 }14139 // hide custom error implementation details from end-users14140 Error.captureStackTrace(this, this.constructor);14141}14142FetchError.prototype = Object.create(Error.prototype);14143FetchError.prototype.constructor = FetchError;14144FetchError.prototype.name = 'FetchError';14145let convert;14146try {14147 convert = (__nccwpck_require__(2877).convert);14148} catch (e) {}14149const INTERNALS = Symbol('Body internals');14150// fix an issue where "PassThrough" isn't a named export for node <1014151const PassThrough = Stream.PassThrough;14152/**14153 * Body mixin14154 *14155 * Ref: https://fetch.spec.whatwg.org/#body14156 *14157 * @param Stream body Readable stream14158 * @param Object opts Response options14159 * @return Void14160 */14161function Body(body) {14162 var _this = this;14163 var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},14164 _ref$size = _ref.size;14165 let size = _ref$size === undefined ? 0 : _ref$size;14166 var _ref$timeout = _ref.timeout;14167 let timeout = _ref$timeout === undefined ? 0 : _ref$timeout;14168 if (body == null) {14169 // body is undefined or null14170 body = null;14171 } else if (isURLSearchParams(body)) {14172 // body is a URLSearchParams14173 body = Buffer.from(body.toString());14174 } else if (isBlob(body)) ; else if (Buffer.isBuffer(body)) ; else if (Object.prototype.toString.call(body) === '[object ArrayBuffer]') {14175 // body is ArrayBuffer14176 body = Buffer.from(body);14177 } else if (ArrayBuffer.isView(body)) {14178 // body is ArrayBufferView14179 body = Buffer.from(body.buffer, body.byteOffset, body.byteLength);14180 } else if (body instanceof Stream) ; else {14181 // none of the above14182 // coerce to string then buffer14183 body = Buffer.from(String(body));14184 }14185 this[INTERNALS] = {14186 body,14187 disturbed: false,14188 error: null14189 };14190 this.size = size;14191 this.timeout = timeout;14192 if (body instanceof Stream) {14193 body.on('error', function (err) {14194 const error = err.name === 'AbortError' ? err : new FetchError(`Invalid response body while trying to fetch ${_this.url}: ${err.message}`, 'system', err);14195 _this[INTERNALS].error = error;14196 });14197 }14198}14199Body.prototype = {14200 get body() {14201 return this[INTERNALS].body;14202 },14203 get bodyUsed() {14204 return this[INTERNALS].disturbed;14205 },14206 /**14207 * Decode response as ArrayBuffer14208 *14209 * @return Promise14210 */14211 arrayBuffer() {14212 return consumeBody.call(this).then(function (buf) {14213 return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);14214 });14215 },14216 /**14217 * Return raw response as Blob14218 *14219 * @return Promise14220 */14221 blob() {14222 let ct = this.headers && this.headers.get('content-type') || '';14223 return consumeBody.call(this).then(function (buf) {14224 return Object.assign(14225 // Prevent copying14226 new Blob([], {14227 type: ct.toLowerCase()14228 }), {14229 [BUFFER]: buf14230 });14231 });14232 },14233 /**14234 * Decode response as json14235 *14236 * @return Promise14237 */14238 json() {14239 var _this2 = this;14240 return consumeBody.call(this).then(function (buffer) {14241 try {14242 return JSON.parse(buffer.toString());14243 } catch (err) {14244 return Body.Promise.reject(new FetchError(`invalid json response body at ${_this2.url} reason: ${err.message}`, 'invalid-json'));14245 }14246 });14247 },14248 /**14249 * Decode response as text14250 *14251 * @return Promise14252 */14253 text() {14254 return consumeBody.call(this).then(function (buffer) {14255 return buffer.toString();14256 });14257 },14258 /**14259 * Decode response as buffer (non-spec api)14260 *14261 * @return Promise14262 */14263 buffer() {14264 return consumeBody.call(this);14265 },14266 /**14267 * Decode response as text, while automatically detecting the encoding and14268 * trying to decode to UTF-8 (non-spec api)14269 *14270 * @return Promise14271 */14272 textConverted() {14273 var _this3 = this;14274 return consumeBody.call(this).then(function (buffer) {14275 return convertBody(buffer, _this3.headers);14276 });14277 }14278};14279// In browsers, all properties are enumerable.14280Object.defineProperties(Body.prototype, {14281 body: { enumerable: true },14282 bodyUsed: { enumerable: true },14283 arrayBuffer: { enumerable: true },14284 blob: { enumerable: true },14285 json: { enumerable: true },14286 text: { enumerable: true }14287});14288Body.mixIn = function (proto) {14289 for (const name of Object.getOwnPropertyNames(Body.prototype)) {14290 // istanbul ignore else: future proof14291 if (!(name in proto)) {14292 const desc = Object.getOwnPropertyDescriptor(Body.prototype, name);14293 Object.defineProperty(proto, name, desc);14294 }14295 }14296};14297/**14298 * Consume and convert an entire Body to a Buffer.14299 *14300 * Ref: https://fetch.spec.whatwg.org/#concept-body-consume-body14301 *14302 * @return Promise14303 */14304function consumeBody() {14305 var _this4 = this;14306 if (this[INTERNALS].disturbed) {14307 return Body.Promise.reject(new TypeError(`body used already for: ${this.url}`));14308 }14309 this[INTERNALS].disturbed = true;14310 if (this[INTERNALS].error) {14311 return Body.Promise.reject(this[INTERNALS].error);14312 }14313 let body = this.body;14314 // body is null14315 if (body === null) {14316 return Body.Promise.resolve(Buffer.alloc(0));14317 }14318 // body is blob14319 if (isBlob(body)) {14320 body = body.stream();14321 }14322 // body is buffer14323 if (Buffer.isBuffer(body)) {14324 return Body.Promise.resolve(body);14325 }14326 // istanbul ignore if: should never happen14327 if (!(body instanceof Stream)) {14328 return Body.Promise.resolve(Buffer.alloc(0));14329 }14330 // body is stream14331 // get ready to actually consume the body14332 let accum = [];14333 let accumBytes = 0;14334 let abort = false;14335 return new Body.Promise(function (resolve, reject) {14336 let resTimeout;14337 // allow timeout on slow response body14338 if (_this4.timeout) {14339 resTimeout = setTimeout(function () {14340 abort = true;14341 reject(new FetchError(`Response timeout while trying to fetch ${_this4.url} (over ${_this4.timeout}ms)`, 'body-timeout'));14342 }, _this4.timeout);14343 }14344 // handle stream errors14345 body.on('error', function (err) {14346 if (err.name === 'AbortError') {14347 // if the request was aborted, reject with this Error14348 abort = true;14349 reject(err);14350 } else {14351 // other errors, such as incorrect content-encoding14352 reject(new FetchError(`Invalid response body while trying to fetch ${_this4.url}: ${err.message}`, 'system', err));14353 }14354 });14355 body.on('data', function (chunk) {14356 if (abort || chunk === null) {14357 return;14358 }14359 if (_this4.size && accumBytes + chunk.length > _this4.size) {14360 abort = true;14361 reject(new FetchError(`content size at ${_this4.url} over limit: ${_this4.size}`, 'max-size'));14362 return;14363 }14364 accumBytes += chunk.length;14365 accum.push(chunk);14366 });14367 body.on('end', function () {14368 if (abort) {14369 return;14370 }14371 clearTimeout(resTimeout);14372 try {14373 resolve(Buffer.concat(accum, accumBytes));14374 } catch (err) {14375 // handle streams that have accumulated too much data (issue #414)14376 reject(new FetchError(`Could not create Buffer from response body for ${_this4.url}: ${err.message}`, 'system', err));14377 }14378 });14379 });14380}14381/**14382 * Detect buffer encoding and convert to target encoding14383 * ref: http://www.w3.org/TR/2011/WD-html5-20110113/parsing.html#determining-the-character-encoding14384 *14385 * @param Buffer buffer Incoming buffer14386 * @param String encoding Target encoding14387 * @return String14388 */14389function convertBody(buffer, headers) {14390 if (typeof convert !== 'function') {14391 throw new Error('The package `encoding` must be installed to use the textConverted() function');14392 }14393 const ct = headers.get('content-type');14394 let charset = 'utf-8';14395 let res, str;14396 // header14397 if (ct) {14398 res = /charset=([^;]*)/i.exec(ct);14399 }14400 // no charset in content type, peek at response body for at most 1024 bytes14401 str = buffer.slice(0, 1024).toString();14402 // html514403 if (!res && str) {14404 res = /<meta.+?charset=(['"])(.+?)\1/i.exec(str);14405 }14406 // html414407 if (!res && str) {14408 res = /<meta[\s]+?http-equiv=(['"])content-type\1[\s]+?content=(['"])(.+?)\2/i.exec(str);14409 if (!res) {14410 res = /<meta[\s]+?content=(['"])(.+?)\1[\s]+?http-equiv=(['"])content-type\3/i.exec(str);14411 if (res) {14412 res.pop(); // drop last quote14413 }14414 }14415 if (res) {14416 res = /charset=(.*)/i.exec(res.pop());14417 }14418 }14419 // xml14420 if (!res && str) {14421 res = /<\?xml.+?encoding=(['"])(.+?)\1/i.exec(str);14422 }14423 // found charset14424 if (res) {14425 charset = res.pop();14426 // prevent decode issues when sites use incorrect encoding14427 // ref: https://hsivonen.fi/encoding-menu/14428 if (charset === 'gb2312' || charset === 'gbk') {14429 charset = 'gb18030';14430 }14431 }14432 // turn raw buffers into a single utf-8 buffer14433 return convert(buffer, 'UTF-8', charset).toString();14434}14435/**14436 * Detect a URLSearchParams object14437 * ref: https://github.com/bitinn/node-fetch/issues/296#issuecomment-30759814314438 *14439 * @param Object obj Object to detect by type or brand14440 * @return String14441 */14442function isURLSearchParams(obj) {14443 // Duck-typing as a necessary condition.14444 if (typeof obj !== 'object' || typeof obj.append !== 'function' || typeof obj.delete !== 'function' || typeof obj.get !== 'function' || typeof obj.getAll !== 'function' || typeof obj.has !== 'function' || typeof obj.set !== 'function') {14445 return false;14446 }14447 // Brand-checking and more duck-typing as optional condition.14448 return obj.constructor.name === 'URLSearchParams' || Object.prototype.toString.call(obj) === '[object URLSearchParams]' || typeof obj.sort === 'function';14449}14450/**14451 * Check if `obj` is a W3C `Blob` object (which `File` inherits from)14452 * @param {*} obj14453 * @return {boolean}14454 */14455function isBlob(obj) {14456 return typeof obj === 'object' && typeof obj.arrayBuffer === 'function' && typeof obj.type === 'string' && typeof obj.stream === 'function' && typeof obj.constructor === 'function' && typeof obj.constructor.name === 'string' && /^(Blob|File)$/.test(obj.constructor.name) && /^(Blob|File)$/.test(obj[Symbol.toStringTag]);14457}14458/**14459 * Clone body given Res/Req instance14460 *14461 * @param Mixed instance Response or Request instance14462 * @return Mixed14463 */14464function clone(instance) {14465 let p1, p2;14466 let body = instance.body;14467 // don't allow cloning a used body14468 if (instance.bodyUsed) {14469 throw new Error('cannot clone body after it is used');14470 }14471 // check that body is a stream and not form-data object14472 // note: we can't clone the form-data object without having it as a dependency14473 if (body instanceof Stream && typeof body.getBoundary !== 'function') {14474 // tee instance body14475 p1 = new PassThrough();14476 p2 = new PassThrough();14477 body.pipe(p1);14478 body.pipe(p2);14479 // set instance body to teed body and return the other teed body14480 instance[INTERNALS].body = p1;14481 body = p2;14482 }14483 return body;14484}14485/**14486 * Performs the operation "extract a `Content-Type` value from |object|" as14487 * specified in the specification:14488 * https://fetch.spec.whatwg.org/#concept-bodyinit-extract14489 *14490 * This function assumes that instance.body is present.14491 *14492 * @param Mixed instance Any options.body input14493 */14494function extractContentType(body) {14495 if (body === null) {14496 // body is null14497 return null;14498 } else if (typeof body === 'string') {14499 // body is string14500 return 'text/plain;charset=UTF-8';14501 } else if (isURLSearchParams(body)) {14502 // body is a URLSearchParams14503 return 'application/x-www-form-urlencoded;charset=UTF-8';14504 } else if (isBlob(body)) {14505 // body is blob14506 return body.type || null;14507 } else if (Buffer.isBuffer(body)) {14508 // body is buffer14509 return null;14510 } else if (Object.prototype.toString.call(body) === '[object ArrayBuffer]') {14511 // body is ArrayBuffer14512 return null;14513 } else if (ArrayBuffer.isView(body)) {14514 // body is ArrayBufferView14515 return null;14516 } else if (typeof body.getBoundary === 'function') {14517 // detect form data input from form-data module14518 return `multipart/form-data;boundary=${body.getBoundary()}`;14519 } else if (body instanceof Stream) {14520 // body is stream14521 // can't really do much about this14522 return null;14523 } else {14524 // Body constructor defaults other things to string14525 return 'text/plain;charset=UTF-8';14526 }14527}14528/**14529 * The Fetch Standard treats this as if "total bytes" is a property on the body.14530 * For us, we have to explicitly get it with a function.14531 *14532 * ref: https://fetch.spec.whatwg.org/#concept-body-total-bytes14533 *14534 * @param Body instance Instance of Body14535 * @return Number? Number of bytes, or null if not possible14536 */14537function getTotalBytes(instance) {14538 const body = instance.body;14539 if (body === null) {14540 // body is null14541 return 0;14542 } else if (isBlob(body)) {14543 return body.size;14544 } else if (Buffer.isBuffer(body)) {14545 // body is buffer14546 return body.length;14547 } else if (body && typeof body.getLengthSync === 'function') {14548 // detect form data input from form-data module14549 if (body._lengthRetrievers && body._lengthRetrievers.length == 0 || // 1.x14550 body.hasKnownLength && body.hasKnownLength()) {14551 // 2.x14552 return body.getLengthSync();14553 }14554 return null;14555 } else {14556 // body is stream14557 return null;14558 }14559}14560/**14561 * Write a Body to a Node.js WritableStream (e.g. http.Request) object.14562 *14563 * @param Body instance Instance of Body14564 * @return Void14565 */14566function writeToStream(dest, instance) {14567 const body = instance.body;14568 if (body === null) {14569 // body is null14570 dest.end();14571 } else if (isBlob(body)) {14572 body.stream().pipe(dest);14573 } else if (Buffer.isBuffer(body)) {14574 // body is buffer14575 dest.write(body);14576 dest.end();14577 } else {14578 // body is stream14579 body.pipe(dest);14580 }14581}14582// expose Promise14583Body.Promise = global.Promise;14584/**14585 * headers.js14586 *14587 * Headers class offers convenient helpers14588 */14589const invalidTokenRegex = /[^\^_`a-zA-Z\-0-9!#$%&'*+.|~]/;14590const invalidHeaderCharRegex = /[^\t\x20-\x7e\x80-\xff]/;14591function validateName(name) {14592 name = `${name}`;14593 if (invalidTokenRegex.test(name) || name === '') {14594 throw new TypeError(`${name} is not a legal HTTP header name`);14595 }14596}14597function validateValue(value) {14598 value = `${value}`;14599 if (invalidHeaderCharRegex.test(value)) {14600 throw new TypeError(`${value} is not a legal HTTP header value`);14601 }14602}14603/**14604 * Find the key in the map object given a header name.14605 *14606 * Returns undefined if not found.14607 *14608 * @param String name Header name14609 * @return String|Undefined14610 */14611function find(map, name) {14612 name = name.toLowerCase();14613 for (const key in map) {14614 if (key.toLowerCase() === name) {14615 return key;14616 }14617 }14618 return undefined;14619}14620const MAP = Symbol('map');14621class Headers {14622 /**14623 * Headers class14624 *14625 * @param Object headers Response headers14626 * @return Void14627 */14628 constructor() {14629 let init = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : undefined;14630 this[MAP] = Object.create(null);14631 if (init instanceof Headers) {14632 const rawHeaders = init.raw();14633 const headerNames = Object.keys(rawHeaders);14634 for (const headerName of headerNames) {14635 for (const value of rawHeaders[headerName]) {14636 this.append(headerName, value);14637 }14638 }14639 return;14640 }14641 // We don't worry about converting prop to ByteString here as append()14642 // will handle it.14643 if (init == null) ; else if (typeof init === 'object') {14644 const method = init[Symbol.iterator];14645 if (method != null) {14646 if (typeof method !== 'function') {14647 throw new TypeError('Header pairs must be iterable');14648 }14649 // sequence<sequence<ByteString>>14650 // Note: per spec we have to first exhaust the lists then process them14651 const pairs = [];14652 for (const pair of init) {14653 if (typeof pair !== 'object' || typeof pair[Symbol.iterator] !== 'function') {14654 throw new TypeError('Each header pair must be iterable');14655 }14656 pairs.push(Array.from(pair));14657 }14658 for (const pair of pairs) {14659 if (pair.length !== 2) {14660 throw new TypeError('Each header pair must be a name/value tuple');14661 }14662 this.append(pair[0], pair[1]);14663 }14664 } else {14665 // record<ByteString, ByteString>14666 for (const key of Object.keys(init)) {14667 const value = init[key];14668 this.append(key, value);14669 }14670 }14671 } else {14672 throw new TypeError('Provided initializer must be an object');14673 }14674 }14675 /**14676 * Return combined header value given name14677 *14678 * @param String name Header name14679 * @return Mixed14680 */14681 get(name) {14682 name = `${name}`;14683 validateName(name);14684 const key = find(this[MAP], name);14685 if (key === undefined) {14686 return null;14687 }14688 return this[MAP][key].join(', ');14689 }14690 /**14691 * Iterate over all headers14692 *14693 * @param Function callback Executed for each item with parameters (value, name, thisArg)14694 * @param Boolean thisArg `this` context for callback function14695 * @return Void14696 */14697 forEach(callback) {14698 let thisArg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined;14699 let pairs = getHeaders(this);14700 let i = 0;14701 while (i < pairs.length) {14702 var _pairs$i = pairs[i];14703 const name = _pairs$i[0],14704 value = _pairs$i[1];14705 callback.call(thisArg, value, name, this);14706 pairs = getHeaders(this);14707 i++;14708 }14709 }14710 /**14711 * Overwrite header values given name14712 *14713 * @param String name Header name14714 * @param String value Header value14715 * @return Void14716 */14717 set(name, value) {14718 name = `${name}`;14719 value = `${value}`;14720 validateName(name);14721 validateValue(value);14722 const key = find(this[MAP], name);14723 this[MAP][key !== undefined ? key : name] = [value];14724 }14725 /**14726 * Append a value onto existing header14727 *14728 * @param String name Header name14729 * @param String value Header value14730 * @return Void14731 */14732 append(name, value) {14733 name = `${name}`;14734 value = `${value}`;14735 validateName(name);14736 validateValue(value);14737 const key = find(this[MAP], name);14738 if (key !== undefined) {14739 this[MAP][key].push(value);14740 } else {14741 this[MAP][name] = [value];14742 }14743 }14744 /**14745 * Check for header name existence14746 *14747 * @param String name Header name14748 * @return Boolean14749 */14750 has(name) {14751 name = `${name}`;14752 validateName(name);14753 return find(this[MAP], name) !== undefined;14754 }14755 /**14756 * Delete all header values given name14757 *14758 * @param String name Header name14759 * @return Void14760 */14761 delete(name) {14762 name = `${name}`;14763 validateName(name);14764 const key = find(this[MAP], name);14765 if (key !== undefined) {14766 delete this[MAP][key];14767 }14768 }14769 /**14770 * Return raw headers (non-spec api)14771 *14772 * @return Object14773 */14774 raw() {14775 return this[MAP];14776 }14777 /**14778 * Get an iterator on keys.14779 *14780 * @return Iterator14781 */14782 keys() {14783 return createHeadersIterator(this, 'key');14784 }14785 /**14786 * Get an iterator on values.14787 *14788 * @return Iterator14789 */14790 values() {14791 return createHeadersIterator(this, 'value');14792 }14793 /**14794 * Get an iterator on entries.14795 *14796 * This is the default iterator of the Headers object.14797 *14798 * @return Iterator14799 */14800 [Symbol.iterator]() {14801 return createHeadersIterator(this, 'key+value');14802 }14803}14804Headers.prototype.entries = Headers.prototype[Symbol.iterator];14805Object.defineProperty(Headers.prototype, Symbol.toStringTag, {14806 value: 'Headers',14807 writable: false,14808 enumerable: false,14809 configurable: true14810});14811Object.defineProperties(Headers.prototype, {14812 get: { enumerable: true },14813 forEach: { enumerable: true },14814 set: { enumerable: true },14815 append: { enumerable: true },14816 has: { enumerable: true },14817 delete: { enumerable: true },14818 keys: { enumerable: true },14819 values: { enumerable: true },14820 entries: { enumerable: true }14821});14822function getHeaders(headers) {14823 let kind = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'key+value';14824 const keys = Object.keys(headers[MAP]).sort();14825 return keys.map(kind === 'key' ? function (k) {14826 return k.toLowerCase();14827 } : kind === 'value' ? function (k) {14828 return headers[MAP][k].join(', ');14829 } : function (k) {14830 return [k.toLowerCase(), headers[MAP][k].join(', ')];14831 });14832}14833const INTERNAL = Symbol('internal');14834function createHeadersIterator(target, kind) {14835 const iterator = Object.create(HeadersIteratorPrototype);14836 iterator[INTERNAL] = {14837 target,14838 kind,14839 index: 014840 };14841 return iterator;14842}14843const HeadersIteratorPrototype = Object.setPrototypeOf({14844 next() {14845 // istanbul ignore if14846 if (!this || Object.getPrototypeOf(this) !== HeadersIteratorPrototype) {14847 throw new TypeError('Value of `this` is not a HeadersIterator');14848 }14849 var _INTERNAL = this[INTERNAL];14850 const target = _INTERNAL.target,14851 kind = _INTERNAL.kind,14852 index = _INTERNAL.index;14853 const values = getHeaders(target, kind);14854 const len = values.length;14855 if (index >= len) {14856 return {14857 value: undefined,14858 done: true14859 };14860 }14861 this[INTERNAL].index = index + 1;14862 return {14863 value: values[index],14864 done: false14865 };14866 }14867}, Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]())));14868Object.defineProperty(HeadersIteratorPrototype, Symbol.toStringTag, {14869 value: 'HeadersIterator',14870 writable: false,14871 enumerable: false,14872 configurable: true14873});14874/**14875 * Export the Headers object in a form that Node.js can consume.14876 *14877 * @param Headers headers14878 * @return Object14879 */14880function exportNodeCompatibleHeaders(headers) {14881 const obj = Object.assign({ __proto__: null }, headers[MAP]);14882 // http.request() only supports string as Host header. This hack makes14883 // specifying custom Host header possible.14884 const hostHeaderKey = find(headers[MAP], 'Host');14885 if (hostHeaderKey !== undefined) {14886 obj[hostHeaderKey] = obj[hostHeaderKey][0];14887 }14888 return obj;14889}14890/**14891 * Create a Headers object from an object of headers, ignoring those that do14892 * not conform to HTTP grammar productions.14893 *14894 * @param Object obj Object of headers14895 * @return Headers14896 */14897function createHeadersLenient(obj) {14898 const headers = new Headers();14899 for (const name of Object.keys(obj)) {14900 if (invalidTokenRegex.test(name)) {14901 continue;14902 }14903 if (Array.isArray(obj[name])) {14904 for (const val of obj[name]) {14905 if (invalidHeaderCharRegex.test(val)) {14906 continue;14907 }14908 if (headers[MAP][name] === undefined) {14909 headers[MAP][name] = [val];14910 } else {14911 headers[MAP][name].push(val);14912 }14913 }14914 } else if (!invalidHeaderCharRegex.test(obj[name])) {14915 headers[MAP][name] = [obj[name]];14916 }14917 }14918 return headers;14919}14920const INTERNALS$1 = Symbol('Response internals');14921// fix an issue where "STATUS_CODES" aren't a named export for node <1014922const STATUS_CODES = http.STATUS_CODES;14923/**14924 * Response class14925 *14926 * @param Stream body Readable stream14927 * @param Object opts Response options14928 * @return Void14929 */14930class Response {14931 constructor() {14932 let body = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;14933 let opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};14934 Body.call(this, body, opts);14935 const status = opts.status || 200;14936 const headers = new Headers(opts.headers);14937 if (body != null && !headers.has('Content-Type')) {14938 const contentType = extractContentType(body);14939 if (contentType) {14940 headers.append('Content-Type', contentType);14941 }14942 }14943 this[INTERNALS$1] = {14944 url: opts.url,14945 status,14946 statusText: opts.statusText || STATUS_CODES[status],14947 headers,14948 counter: opts.counter14949 };14950 }14951 get url() {14952 return this[INTERNALS$1].url || '';14953 }14954 get status() {14955 return this[INTERNALS$1].status;14956 }14957 /**14958 * Convenience property representing if the request ended normally14959 */14960 get ok() {14961 return this[INTERNALS$1].status >= 200 && this[INTERNALS$1].status < 300;14962 }14963 get redirected() {14964 return this[INTERNALS$1].counter > 0;14965 }14966 get statusText() {14967 return this[INTERNALS$1].statusText;14968 }14969 get headers() {14970 return this[INTERNALS$1].headers;14971 }14972 /**14973 * Clone this response14974 *14975 * @return Response14976 */14977 clone() {14978 return new Response(clone(this), {14979 url: this.url,14980 status: this.status,14981 statusText: this.statusText,14982 headers: this.headers,14983 ok: this.ok,14984 redirected: this.redirected14985 });14986 }14987}14988Body.mixIn(Response.prototype);14989Object.defineProperties(Response.prototype, {14990 url: { enumerable: true },14991 status: { enumerable: true },14992 ok: { enumerable: true },14993 redirected: { enumerable: true },14994 statusText: { enumerable: true },14995 headers: { enumerable: true },14996 clone: { enumerable: true }14997});14998Object.defineProperty(Response.prototype, Symbol.toStringTag, {14999 value: 'Response',15000 writable: false,15001 enumerable: false,15002 configurable: true15003});15004const INTERNALS$2 = Symbol('Request internals');15005const URL = Url.URL || whatwgUrl.URL;15006// fix an issue where "format", "parse" aren't a named export for node <1015007const parse_url = Url.parse;15008const format_url = Url.format;15009/**15010 * Wrapper around `new URL` to handle arbitrary URLs15011 *15012 * @param {string} urlStr15013 * @return {void}15014 */15015function parseURL(urlStr) {15016 /*15017 Check whether the URL is absolute or not15018 Scheme: https://tools.ietf.org/html/rfc3986#section-3.115019 Absolute URL: https://tools.ietf.org/html/rfc3986#section-4.315020 */15021 if (/^[a-zA-Z][a-zA-Z\d+\-.]*:/.exec(urlStr)) {15022 urlStr = new URL(urlStr).toString();15023 }15024 // Fallback to old implementation for arbitrary URLs15025 return parse_url(urlStr);15026}15027const streamDestructionSupported = 'destroy' in Stream.Readable.prototype;15028/**15029 * Check if a value is an instance of Request.15030 *15031 * @param Mixed input15032 * @return Boolean15033 */15034function isRequest(input) {15035 return typeof input === 'object' && typeof input[INTERNALS$2] === 'object';15036}15037function isAbortSignal(signal) {15038 const proto = signal && typeof signal === 'object' && Object.getPrototypeOf(signal);15039 return !!(proto && proto.constructor.name === 'AbortSignal');15040}15041/**15042 * Request class15043 *15044 * @param Mixed input Url or Request instance15045 * @param Object init Custom options15046 * @return Void15047 */15048class Request {15049 constructor(input) {15050 let init = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};15051 let parsedURL;15052 // normalize input15053 if (!isRequest(input)) {15054 if (input && input.href) {15055 // in order to support Node.js' Url objects; though WHATWG's URL objects15056 // will fall into this branch also (since their `toString()` will return15057 // `href` property anyway)15058 parsedURL = parseURL(input.href);15059 } else {15060 // coerce input to a string before attempting to parse15061 parsedURL = parseURL(`${input}`);15062 }15063 input = {};15064 } else {15065 parsedURL = parseURL(input.url);15066 }15067 let method = init.method || input.method || 'GET';15068 method = method.toUpperCase();15069 if ((init.body != null || isRequest(input) && input.body !== null) && (method === 'GET' || method === 'HEAD')) {15070 throw new TypeError('Request with GET/HEAD method cannot have body');15071 }15072 let inputBody = init.body != null ? init.body : isRequest(input) && input.body !== null ? clone(input) : null;15073 Body.call(this, inputBody, {15074 timeout: init.timeout || input.timeout || 0,15075 size: init.size || input.size || 015076 });15077 const headers = new Headers(init.headers || input.headers || {});15078 if (inputBody != null && !headers.has('Content-Type')) {15079 const contentType = extractContentType(inputBody);15080 if (contentType) {15081 headers.append('Content-Type', contentType);15082 }15083 }15084 let signal = isRequest(input) ? input.signal : null;15085 if ('signal' in init) signal = init.signal;15086 if (signal != null && !isAbortSignal(signal)) {15087 throw new TypeError('Expected signal to be an instanceof AbortSignal');15088 }15089 this[INTERNALS$2] = {15090 method,15091 redirect: init.redirect || input.redirect || 'follow',15092 headers,15093 parsedURL,15094 signal15095 };15096 // node-fetch-only options15097 this.follow = init.follow !== undefined ? init.follow : input.follow !== undefined ? input.follow : 20;15098 this.compress = init.compress !== undefined ? init.compress : input.compress !== undefined ? input.compress : true;15099 this.counter = init.counter || input.counter || 0;15100 this.agent = init.agent || input.agent;15101 }15102 get method() {15103 return this[INTERNALS$2].method;15104 }15105 get url() {15106 return format_url(this[INTERNALS$2].parsedURL);15107 }15108 get headers() {15109 return this[INTERNALS$2].headers;15110 }15111 get redirect() {15112 return this[INTERNALS$2].redirect;15113 }15114 get signal() {15115 return this[INTERNALS$2].signal;15116 }15117 /**15118 * Clone this request15119 *15120 * @return Request15121 */15122 clone() {15123 return new Request(this);15124 }15125}15126Body.mixIn(Request.prototype);15127Object.defineProperty(Request.prototype, Symbol.toStringTag, {15128 value: 'Request',15129 writable: false,15130 enumerable: false,15131 configurable: true15132});15133Object.defineProperties(Request.prototype, {15134 method: { enumerable: true },15135 url: { enumerable: true },15136 headers: { enumerable: true },15137 redirect: { enumerable: true },15138 clone: { enumerable: true },15139 signal: { enumerable: true }15140});15141/**15142 * Convert a Request to Node.js http request options.15143 *15144 * @param Request A Request instance15145 * @return Object The options object to be passed to http.request15146 */15147function getNodeRequestOptions(request) {15148 const parsedURL = request[INTERNALS$2].parsedURL;15149 const headers = new Headers(request[INTERNALS$2].headers);15150 // fetch step 1.315151 if (!headers.has('Accept')) {15152 headers.set('Accept', '*/*');15153 }15154 // Basic fetch15155 if (!parsedURL.protocol || !parsedURL.hostname) {15156 throw new TypeError('Only absolute URLs are supported');15157 }15158 if (!/^https?:$/.test(parsedURL.protocol)) {15159 throw new TypeError('Only HTTP(S) protocols are supported');15160 }15161 if (request.signal && request.body instanceof Stream.Readable && !streamDestructionSupported) {15162 throw new Error('Cancellation of streamed requests with AbortSignal is not supported in node < 8');15163 }15164 // HTTP-network-or-cache fetch steps 2.4-2.715165 let contentLengthValue = null;15166 if (request.body == null && /^(POST|PUT)$/i.test(request.method)) {15167 contentLengthValue = '0';15168 }15169 if (request.body != null) {15170 const totalBytes = getTotalBytes(request);15171 if (typeof totalBytes === 'number') {15172 contentLengthValue = String(totalBytes);15173 }15174 }15175 if (contentLengthValue) {15176 headers.set('Content-Length', contentLengthValue);15177 }15178 // HTTP-network-or-cache fetch step 2.1115179 if (!headers.has('User-Agent')) {15180 headers.set('User-Agent', 'node-fetch/1.0 (+https://github.com/bitinn/node-fetch)');15181 }15182 // HTTP-network-or-cache fetch step 2.1515183 if (request.compress && !headers.has('Accept-Encoding')) {15184 headers.set('Accept-Encoding', 'gzip,deflate');15185 }15186 let agent = request.agent;15187 if (typeof agent === 'function') {15188 agent = agent(parsedURL);15189 }15190 if (!headers.has('Connection') && !agent) {15191 headers.set('Connection', 'close');15192 }15193 // HTTP-network fetch step 4.215194 // chunked encoding is handled by Node.js15195 return Object.assign({}, parsedURL, {15196 method: request.method,15197 headers: exportNodeCompatibleHeaders(headers),15198 agent15199 });15200}15201/**15202 * abort-error.js15203 *15204 * AbortError interface for cancelled requests15205 */15206/**15207 * Create AbortError instance15208 *15209 * @param String message Error message for human15210 * @return AbortError15211 */15212function AbortError(message) {15213 Error.call(this, message);15214 this.type = 'aborted';15215 this.message = message;15216 // hide custom error implementation details from end-users15217 Error.captureStackTrace(this, this.constructor);15218}15219AbortError.prototype = Object.create(Error.prototype);15220AbortError.prototype.constructor = AbortError;15221AbortError.prototype.name = 'AbortError';15222const URL$1 = Url.URL || whatwgUrl.URL;15223// fix an issue where "PassThrough", "resolve" aren't a named export for node <1015224const PassThrough$1 = Stream.PassThrough;15225const isDomainOrSubdomain = function isDomainOrSubdomain(destination, original) {15226 const orig = new URL$1(original).hostname;15227 const dest = new URL$1(destination).hostname;15228 return orig === dest || orig[orig.length - dest.length - 1] === '.' && orig.endsWith(dest);15229};15230/**15231 * Fetch function15232 *15233 * @param Mixed url Absolute url or Request instance15234 * @param Object opts Fetch options15235 * @return Promise15236 */15237function fetch(url, opts) {15238 // allow custom promise15239 if (!fetch.Promise) {15240 throw new Error('native promise missing, set fetch.Promise to your favorite alternative');15241 }15242 Body.Promise = fetch.Promise;15243 // wrap http.request into fetch15244 return new fetch.Promise(function (resolve, reject) {15245 // build request object15246 const request = new Request(url, opts);15247 const options = getNodeRequestOptions(request);15248 const send = (options.protocol === 'https:' ? https : http).request;15249 const signal = request.signal;15250 let response = null;15251 const abort = function abort() {15252 let error = new AbortError('The user aborted a request.');15253 reject(error);15254 if (request.body && request.body instanceof Stream.Readable) {15255 request.body.destroy(error);15256 }15257 if (!response || !response.body) return;15258 response.body.emit('error', error);15259 };15260 if (signal && signal.aborted) {15261 abort();15262 return;15263 }15264 const abortAndFinalize = function abortAndFinalize() {15265 abort();15266 finalize();15267 };15268 // send request15269 const req = send(options);15270 let reqTimeout;15271 if (signal) {15272 signal.addEventListener('abort', abortAndFinalize);15273 }15274 function finalize() {15275 req.abort();15276 if (signal) signal.removeEventListener('abort', abortAndFinalize);15277 clearTimeout(reqTimeout);15278 }15279 if (request.timeout) {15280 req.once('socket', function (socket) {15281 reqTimeout = setTimeout(function () {15282 reject(new FetchError(`network timeout at: ${request.url}`, 'request-timeout'));15283 finalize();15284 }, request.timeout);15285 });15286 }15287 req.on('error', function (err) {15288 reject(new FetchError(`request to ${request.url} failed, reason: ${err.message}`, 'system', err));15289 finalize();15290 });15291 req.on('response', function (res) {15292 clearTimeout(reqTimeout);15293 const headers = createHeadersLenient(res.headers);15294 // HTTP fetch step 515295 if (fetch.isRedirect(res.statusCode)) {15296 // HTTP fetch step 5.215297 const location = headers.get('Location');15298 // HTTP fetch step 5.315299 let locationURL = null;15300 try {15301 locationURL = location === null ? null : new URL$1(location, request.url).toString();15302 } catch (err) {15303 // error here can only be invalid URL in Location: header15304 // do not throw when options.redirect == manual15305 // let the user extract the errorneous redirect URL15306 if (request.redirect !== 'manual') {15307 reject(new FetchError(`uri requested responds with an invalid redirect URL: ${location}`, 'invalid-redirect'));15308 finalize();15309 return;15310 }15311 }15312 // HTTP fetch step 5.515313 switch (request.redirect) {15314 case 'error':15315 reject(new FetchError(`uri requested responds with a redirect, redirect mode is set to error: ${request.url}`, 'no-redirect'));15316 finalize();15317 return;15318 case 'manual':15319 // node-fetch-specific step: make manual redirect a bit easier to use by setting the Location header value to the resolved URL.15320 if (locationURL !== null) {15321 // handle corrupted header15322 try {15323 headers.set('Location', locationURL);15324 } catch (err) {15325 // istanbul ignore next: nodejs server prevent invalid response headers, we can't test this through normal request15326 reject(err);15327 }15328 }15329 break;15330 case 'follow':15331 // HTTP-redirect fetch step 215332 if (locationURL === null) {15333 break;15334 }15335 // HTTP-redirect fetch step 515336 if (request.counter >= request.follow) {15337 reject(new FetchError(`maximum redirect reached at: ${request.url}`, 'max-redirect'));15338 finalize();15339 return;15340 }15341 // HTTP-redirect fetch step 6 (counter increment)15342 // Create a new Request object.15343 const requestOpts = {15344 headers: new Headers(request.headers),15345 follow: request.follow,15346 counter: request.counter + 1,15347 agent: request.agent,15348 compress: request.compress,15349 method: request.method,15350 body: request.body,15351 signal: request.signal,15352 timeout: request.timeout,15353 size: request.size15354 };15355 if (!isDomainOrSubdomain(request.url, locationURL)) {15356 for (const name of ['authorization', 'www-authenticate', 'cookie', 'cookie2']) {15357 requestOpts.headers.delete(name);15358 }15359 }15360 // HTTP-redirect fetch step 915361 if (res.statusCode !== 303 && request.body && getTotalBytes(request) === null) {15362 reject(new FetchError('Cannot follow redirect with body being a readable stream', 'unsupported-redirect'));15363 finalize();15364 return;15365 }15366 // HTTP-redirect fetch step 1115367 if (res.statusCode === 303 || (res.statusCode === 301 || res.statusCode === 302) && request.method === 'POST') {15368 requestOpts.method = 'GET';15369 requestOpts.body = undefined;15370 requestOpts.headers.delete('content-length');15371 }15372 // HTTP-redirect fetch step 1515373 resolve(fetch(new Request(locationURL, requestOpts)));15374 finalize();15375 return;15376 }15377 }15378 // prepare response15379 res.once('end', function () {15380 if (signal) signal.removeEventListener('abort', abortAndFinalize);15381 });15382 let body = res.pipe(new PassThrough$1());15383 const response_options = {15384 url: request.url,15385 status: res.statusCode,15386 statusText: res.statusMessage,15387 headers: headers,15388 size: request.size,15389 timeout: request.timeout,15390 counter: request.counter15391 };15392 // HTTP-network fetch step 12.1.1.315393 const codings = headers.get('Content-Encoding');15394 // HTTP-network fetch step 12.1.1.4: handle content codings15395 // in following scenarios we ignore compression support15396 // 1. compression support is disabled15397 // 2. HEAD request15398 // 3. no Content-Encoding header15399 // 4. no content response (204)15400 // 5. content not modified response (304)15401 if (!request.compress || request.method === 'HEAD' || codings === null || res.statusCode === 204 || res.statusCode === 304) {15402 response = new Response(body, response_options);15403 resolve(response);15404 return;15405 }15406 // For Node v6+15407 // Be less strict when decoding compressed responses, since sometimes15408 // servers send slightly invalid responses that are still accepted15409 // by common browsers.15410 // Always using Z_SYNC_FLUSH is what cURL does.15411 const zlibOptions = {15412 flush: zlib.Z_SYNC_FLUSH,15413 finishFlush: zlib.Z_SYNC_FLUSH15414 };15415 // for gzip15416 if (codings == 'gzip' || codings == 'x-gzip') {15417 body = body.pipe(zlib.createGunzip(zlibOptions));15418 response = new Response(body, response_options);15419 resolve(response);15420 return;15421 }15422 // for deflate15423 if (codings == 'deflate' || codings == 'x-deflate') {15424 // handle the infamous raw deflate response from old servers15425 // a hack for old IIS and Apache servers15426 const raw = res.pipe(new PassThrough$1());15427 raw.once('data', function (chunk) {15428 // see http://stackoverflow.com/questions/3751982815429 if ((chunk[0] & 0x0F) === 0x08) {15430 body = body.pipe(zlib.createInflate());15431 } else {15432 body = body.pipe(zlib.createInflateRaw());15433 }15434 response = new Response(body, response_options);15435 resolve(response);15436 });15437 return;15438 }15439 // for br15440 if (codings == 'br' && typeof zlib.createBrotliDecompress === 'function') {15441 body = body.pipe(zlib.createBrotliDecompress());15442 response = new Response(body, response_options);15443 resolve(response);15444 return;15445 }15446 // otherwise, use response as-is15447 response = new Response(body, response_options);15448 resolve(response);15449 });15450 writeToStream(req, request);15451 });15452}15453/**15454 * Redirect code matching15455 *15456 * @param Number code Status code15457 * @return Boolean15458 */15459fetch.isRedirect = function (code) {15460 return code === 301 || code === 302 || code === 303 || code === 307 || code === 308;15461};15462// expose Promise15463fetch.Promise = global.Promise;15464module.exports = exports = fetch;15465Object.defineProperty(exports, "__esModule", ({ value: true }));15466exports["default"] = exports;15467exports.Headers = Headers;15468exports.Request = Request;15469exports.Response = Response;15470exports.FetchError = FetchError;15471/***/ }),15472/***/ 7994:15473/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {15474/**15475 * Advanced Encryption Standard (AES) implementation.15476 *15477 * This implementation is based on the public domain library 'jscrypto' which15478 * was written by:15479 *15480 * Emily Stark (estark@stanford.edu)15481 * Mike Hamburg (mhamburg@stanford.edu)15482 * Dan Boneh (dabo@cs.stanford.edu)15483 *15484 * Parts of this code are based on the OpenSSL implementation of AES:15485 * http://www.openssl.org15486 *15487 * @author Dave Longley15488 *15489 * Copyright (c) 2010-2014 Digital Bazaar, Inc.15490 */15491var forge = __nccwpck_require__(9177);15492__nccwpck_require__(7088);15493__nccwpck_require__(873);15494__nccwpck_require__(8339);15495/* AES API */15496module.exports = forge.aes = forge.aes || {};15497/**15498 * Deprecated. Instead, use:15499 *15500 * var cipher = forge.cipher.createCipher('AES-<mode>', key);15501 * cipher.start({iv: iv});15502 *15503 * Creates an AES cipher object to encrypt data using the given symmetric key.15504 * The output will be stored in the 'output' member of the returned cipher.15505 *15506 * The key and iv may be given as a string of bytes, an array of bytes,15507 * a byte buffer, or an array of 32-bit words.15508 *15509 * @param key the symmetric key to use.15510 * @param iv the initialization vector to use.15511 * @param output the buffer to write to, null to create one.15512 * @param mode the cipher mode to use (default: 'CBC').15513 *15514 * @return the cipher.15515 */15516forge.aes.startEncrypting = function(key, iv, output, mode) {15517 var cipher = _createCipher({15518 key: key,15519 output: output,15520 decrypt: false,15521 mode: mode15522 });15523 cipher.start(iv);15524 return cipher;15525};15526/**15527 * Deprecated. Instead, use:15528 *15529 * var cipher = forge.cipher.createCipher('AES-<mode>', key);15530 *15531 * Creates an AES cipher object to encrypt data using the given symmetric key.15532 *15533 * The key may be given as a string of bytes, an array of bytes, a15534 * byte buffer, or an array of 32-bit words.15535 *15536 * @param key the symmetric key to use.15537 * @param mode the cipher mode to use (default: 'CBC').15538 *15539 * @return the cipher.15540 */15541forge.aes.createEncryptionCipher = function(key, mode) {15542 return _createCipher({15543 key: key,15544 output: null,15545 decrypt: false,15546 mode: mode15547 });15548};15549/**15550 * Deprecated. Instead, use:15551 *15552 * var decipher = forge.cipher.createDecipher('AES-<mode>', key);15553 * decipher.start({iv: iv});15554 *15555 * Creates an AES cipher object to decrypt data using the given symmetric key.15556 * The output will be stored in the 'output' member of the returned cipher.15557 *15558 * The key and iv may be given as a string of bytes, an array of bytes,15559 * a byte buffer, or an array of 32-bit words.15560 *15561 * @param key the symmetric key to use.15562 * @param iv the initialization vector to use.15563 * @param output the buffer to write to, null to create one.15564 * @param mode the cipher mode to use (default: 'CBC').15565 *15566 * @return the cipher.15567 */15568forge.aes.startDecrypting = function(key, iv, output, mode) {15569 var cipher = _createCipher({15570 key: key,15571 output: output,15572 decrypt: true,15573 mode: mode15574 });15575 cipher.start(iv);15576 return cipher;15577};15578/**15579 * Deprecated. Instead, use:15580 *15581 * var decipher = forge.cipher.createDecipher('AES-<mode>', key);15582 *15583 * Creates an AES cipher object to decrypt data using the given symmetric key.15584 *15585 * The key may be given as a string of bytes, an array of bytes, a15586 * byte buffer, or an array of 32-bit words.15587 *15588 * @param key the symmetric key to use.15589 * @param mode the cipher mode to use (default: 'CBC').15590 *15591 * @return the cipher.15592 */15593forge.aes.createDecryptionCipher = function(key, mode) {15594 return _createCipher({15595 key: key,15596 output: null,15597 decrypt: true,15598 mode: mode15599 });15600};15601/**15602 * Creates a new AES cipher algorithm object.15603 *15604 * @param name the name of the algorithm.15605 * @param mode the mode factory function.15606 *15607 * @return the AES algorithm object.15608 */15609forge.aes.Algorithm = function(name, mode) {15610 if(!init) {15611 initialize();15612 }15613 var self = this;15614 self.name = name;15615 self.mode = new mode({15616 blockSize: 16,15617 cipher: {15618 encrypt: function(inBlock, outBlock) {15619 return _updateBlock(self._w, inBlock, outBlock, false);15620 },15621 decrypt: function(inBlock, outBlock) {15622 return _updateBlock(self._w, inBlock, outBlock, true);15623 }15624 }15625 });15626 self._init = false;15627};15628/**15629 * Initializes this AES algorithm by expanding its key.15630 *15631 * @param options the options to use.15632 * key the key to use with this algorithm.15633 * decrypt true if the algorithm should be initialized for decryption,15634 * false for encryption.15635 */15636forge.aes.Algorithm.prototype.initialize = function(options) {15637 if(this._init) {15638 return;15639 }15640 var key = options.key;15641 var tmp;15642 /* Note: The key may be a string of bytes, an array of bytes, a byte15643 buffer, or an array of 32-bit integers. If the key is in bytes, then15644 it must be 16, 24, or 32 bytes in length. If it is in 32-bit15645 integers, it must be 4, 6, or 8 integers long. */15646 if(typeof key === 'string' &&15647 (key.length === 16 || key.length === 24 || key.length === 32)) {15648 // convert key string into byte buffer15649 key = forge.util.createBuffer(key);15650 } else if(forge.util.isArray(key) &&15651 (key.length === 16 || key.length === 24 || key.length === 32)) {15652 // convert key integer array into byte buffer15653 tmp = key;15654 key = forge.util.createBuffer();15655 for(var i = 0; i < tmp.length; ++i) {15656 key.putByte(tmp[i]);15657 }15658 }15659 // convert key byte buffer into 32-bit integer array15660 if(!forge.util.isArray(key)) {15661 tmp = key;15662 key = [];15663 // key lengths of 16, 24, 32 bytes allowed15664 var len = tmp.length();15665 if(len === 16 || len === 24 || len === 32) {15666 len = len >>> 2;15667 for(var i = 0; i < len; ++i) {15668 key.push(tmp.getInt32());15669 }15670 }15671 }15672 // key must be an array of 32-bit integers by now15673 if(!forge.util.isArray(key) ||15674 !(key.length === 4 || key.length === 6 || key.length === 8)) {15675 throw new Error('Invalid key parameter.');15676 }15677 // encryption operation is always used for these modes15678 var mode = this.mode.name;15679 var encryptOp = (['CFB', 'OFB', 'CTR', 'GCM'].indexOf(mode) !== -1);15680 // do key expansion15681 this._w = _expandKey(key, options.decrypt && !encryptOp);15682 this._init = true;15683};15684/**15685 * Expands a key. Typically only used for testing.15686 *15687 * @param key the symmetric key to expand, as an array of 32-bit words.15688 * @param decrypt true to expand for decryption, false for encryption.15689 *15690 * @return the expanded key.15691 */15692forge.aes._expandKey = function(key, decrypt) {15693 if(!init) {15694 initialize();15695 }15696 return _expandKey(key, decrypt);15697};15698/**15699 * Updates a single block. Typically only used for testing.15700 *15701 * @param w the expanded key to use.15702 * @param input an array of block-size 32-bit words.15703 * @param output an array of block-size 32-bit words.15704 * @param decrypt true to decrypt, false to encrypt.15705 */15706forge.aes._updateBlock = _updateBlock;15707/** Register AES algorithms **/15708registerAlgorithm('AES-ECB', forge.cipher.modes.ecb);15709registerAlgorithm('AES-CBC', forge.cipher.modes.cbc);15710registerAlgorithm('AES-CFB', forge.cipher.modes.cfb);15711registerAlgorithm('AES-OFB', forge.cipher.modes.ofb);15712registerAlgorithm('AES-CTR', forge.cipher.modes.ctr);15713registerAlgorithm('AES-GCM', forge.cipher.modes.gcm);15714function registerAlgorithm(name, mode) {15715 var factory = function() {15716 return new forge.aes.Algorithm(name, mode);15717 };15718 forge.cipher.registerAlgorithm(name, factory);15719}15720/** AES implementation **/15721var init = false; // not yet initialized15722var Nb = 4; // number of words comprising the state (AES = 4)15723var sbox; // non-linear substitution table used in key expansion15724var isbox; // inversion of sbox15725var rcon; // round constant word array15726var mix; // mix-columns table15727var imix; // inverse mix-columns table15728/**15729 * Performs initialization, ie: precomputes tables to optimize for speed.15730 *15731 * One way to understand how AES works is to imagine that 'addition' and15732 * 'multiplication' are interfaces that require certain mathematical15733 * properties to hold true (ie: they are associative) but they might have15734 * different implementations and produce different kinds of results ...15735 * provided that their mathematical properties remain true. AES defines15736 * its own methods of addition and multiplication but keeps some important15737 * properties the same, ie: associativity and distributivity. The15738 * explanation below tries to shed some light on how AES defines addition15739 * and multiplication of bytes and 32-bit words in order to perform its15740 * encryption and decryption algorithms.15741 *15742 * The basics:15743 *15744 * The AES algorithm views bytes as binary representations of polynomials15745 * that have either 1 or 0 as the coefficients. It defines the addition15746 * or subtraction of two bytes as the XOR operation. It also defines the15747 * multiplication of two bytes as a finite field referred to as GF(2^8)15748 * (Note: 'GF' means "Galois Field" which is a field that contains a finite15749 * number of elements so GF(2^8) has 256 elements).15750 *15751 * This means that any two bytes can be represented as binary polynomials;15752 * when they multiplied together and modularly reduced by an irreducible15753 * polynomial of the 8th degree, the results are the field GF(2^8). The15754 * specific irreducible polynomial that AES uses in hexadecimal is 0x11b.15755 * This multiplication is associative with 0x01 as the identity:15756 *15757 * (b * 0x01 = GF(b, 0x01) = b).15758 *15759 * The operation GF(b, 0x02) can be performed at the byte level by left15760 * shifting b once and then XOR'ing it (to perform the modular reduction)15761 * with 0x11b if b is >= 128. Repeated application of the multiplication15762 * of 0x02 can be used to implement the multiplication of any two bytes.15763 *15764 * For instance, multiplying 0x57 and 0x13, denoted as GF(0x57, 0x13), can15765 * be performed by factoring 0x13 into 0x01, 0x02, and 0x10. Then these15766 * factors can each be multiplied by 0x57 and then added together. To do15767 * the multiplication, values for 0x57 multiplied by each of these 3 factors15768 * can be precomputed and stored in a table. To add them, the values from15769 * the table are XOR'd together.15770 *15771 * AES also defines addition and multiplication of words, that is 4-byte15772 * numbers represented as polynomials of 3 degrees where the coefficients15773 * are the values of the bytes.15774 *15775 * The word [a0, a1, a2, a3] is a polynomial a3x^3 + a2x^2 + a1x + a0.15776 *15777 * Addition is performed by XOR'ing like powers of x. Multiplication15778 * is performed in two steps, the first is an algebriac expansion as15779 * you would do normally (where addition is XOR). But the result is15780 * a polynomial larger than 3 degrees and thus it cannot fit in a word. So15781 * next the result is modularly reduced by an AES-specific polynomial of15782 * degree 4 which will always produce a polynomial of less than 4 degrees15783 * such that it will fit in a word. In AES, this polynomial is x^4 + 1.15784 *15785 * The modular product of two polynomials 'a' and 'b' is thus:15786 *15787 * d(x) = d3x^3 + d2x^2 + d1x + d015788 * with15789 * d0 = GF(a0, b0) ^ GF(a3, b1) ^ GF(a2, b2) ^ GF(a1, b3)15790 * d1 = GF(a1, b0) ^ GF(a0, b1) ^ GF(a3, b2) ^ GF(a2, b3)15791 * d2 = GF(a2, b0) ^ GF(a1, b1) ^ GF(a0, b2) ^ GF(a3, b3)15792 * d3 = GF(a3, b0) ^ GF(a2, b1) ^ GF(a1, b2) ^ GF(a0, b3)15793 *15794 * As a matrix:15795 *15796 * [d0] = [a0 a3 a2 a1][b0]15797 * [d1] [a1 a0 a3 a2][b1]15798 * [d2] [a2 a1 a0 a3][b2]15799 * [d3] [a3 a2 a1 a0][b3]15800 *15801 * Special polynomials defined by AES (0x02 == {02}):15802 * a(x) = {03}x^3 + {01}x^2 + {01}x + {02}15803 * a^-1(x) = {0b}x^3 + {0d}x^2 + {09}x + {0e}.15804 *15805 * These polynomials are used in the MixColumns() and InverseMixColumns()15806 * operations, respectively, to cause each element in the state to affect15807 * the output (referred to as diffusing).15808 *15809 * RotWord() uses: a0 = a1 = a2 = {00} and a3 = {01}, which is the15810 * polynomial x3.15811 *15812 * The ShiftRows() method modifies the last 3 rows in the state (where15813 * the state is 4 words with 4 bytes per word) by shifting bytes cyclically.15814 * The 1st byte in the second row is moved to the end of the row. The 1st15815 * and 2nd bytes in the third row are moved to the end of the row. The 1st,15816 * 2nd, and 3rd bytes are moved in the fourth row.15817 *15818 * More details on how AES arithmetic works:15819 *15820 * In the polynomial representation of binary numbers, XOR performs addition15821 * and subtraction and multiplication in GF(2^8) denoted as GF(a, b)15822 * corresponds with the multiplication of polynomials modulo an irreducible15823 * polynomial of degree 8. In other words, for AES, GF(a, b) will multiply15824 * polynomial 'a' with polynomial 'b' and then do a modular reduction by15825 * an AES-specific irreducible polynomial of degree 8.15826 *15827 * A polynomial is irreducible if its only divisors are one and itself. For15828 * the AES algorithm, this irreducible polynomial is:15829 *15830 * m(x) = x^8 + x^4 + x^3 + x + 1,15831 *15832 * or {01}{1b} in hexadecimal notation, where each coefficient is a bit:15833 * 100011011 = 283 = 0x11b.15834 *15835 * For example, GF(0x57, 0x83) = 0xc1 because15836 *15837 * 0x57 = 87 = 01010111 = x^6 + x^4 + x^2 + x + 115838 * 0x85 = 131 = 10000101 = x^7 + x + 115839 *15840 * (x^6 + x^4 + x^2 + x + 1) * (x^7 + x + 1)15841 * = x^13 + x^11 + x^9 + x^8 + x^7 +15842 * x^7 + x^5 + x^3 + x^2 + x +15843 * x^6 + x^4 + x^2 + x + 115844 * = x^13 + x^11 + x^9 + x^8 + x^6 + x^5 + x^4 + x^3 + 1 = y15845 * y modulo (x^8 + x^4 + x^3 + x + 1)15846 * = x^7 + x^6 + 1.15847 *15848 * The modular reduction by m(x) guarantees the result will be a binary15849 * polynomial of less than degree 8, so that it can fit in a byte.15850 *15851 * The operation to multiply a binary polynomial b with x (the polynomial15852 * x in binary representation is 00000010) is:15853 *15854 * b_7x^8 + b_6x^7 + b_5x^6 + b_4x^5 + b_3x^4 + b_2x^3 + b_1x^2 + b_0x^115855 *15856 * To get GF(b, x) we must reduce that by m(x). If b_7 is 0 (that is the15857 * most significant bit is 0 in b) then the result is already reduced. If15858 * it is 1, then we can reduce it by subtracting m(x) via an XOR.15859 *15860 * It follows that multiplication by x (00000010 or 0x02) can be implemented15861 * by performing a left shift followed by a conditional bitwise XOR with15862 * 0x1b. This operation on bytes is denoted by xtime(). Multiplication by15863 * higher powers of x can be implemented by repeated application of xtime().15864 *15865 * By adding intermediate results, multiplication by any constant can be15866 * implemented. For instance:15867 *15868 * GF(0x57, 0x13) = 0xfe because:15869 *15870 * xtime(b) = (b & 128) ? (b << 1 ^ 0x11b) : (b << 1)15871 *15872 * Note: We XOR with 0x11b instead of 0x1b because in javascript our15873 * datatype for b can be larger than 1 byte, so a left shift will not15874 * automatically eliminate bits that overflow a byte ... by XOR'ing the15875 * overflow bit with 1 (the extra one from 0x11b) we zero it out.15876 *15877 * GF(0x57, 0x02) = xtime(0x57) = 0xae15878 * GF(0x57, 0x04) = xtime(0xae) = 0x4715879 * GF(0x57, 0x08) = xtime(0x47) = 0x8e15880 * GF(0x57, 0x10) = xtime(0x8e) = 0x0715881 *15882 * GF(0x57, 0x13) = GF(0x57, (0x01 ^ 0x02 ^ 0x10))15883 *15884 * And by the distributive property (since XOR is addition and GF() is15885 * multiplication):15886 *15887 * = GF(0x57, 0x01) ^ GF(0x57, 0x02) ^ GF(0x57, 0x10)15888 * = 0x57 ^ 0xae ^ 0x0715889 * = 0xfe.15890 */15891function initialize() {15892 init = true;15893 /* Populate the Rcon table. These are the values given by15894 [x^(i-1),{00},{00},{00}] where x^(i-1) are powers of x (and x = 0x02)15895 in the field of GF(2^8), where i starts at 1.15896 rcon[0] = [0x00, 0x00, 0x00, 0x00]15897 rcon[1] = [0x01, 0x00, 0x00, 0x00] 2^(1-1) = 2^0 = 115898 rcon[2] = [0x02, 0x00, 0x00, 0x00] 2^(2-1) = 2^1 = 215899 ...15900 rcon[9] = [0x1B, 0x00, 0x00, 0x00] 2^(9-1) = 2^8 = 0x1B15901 rcon[10] = [0x36, 0x00, 0x00, 0x00] 2^(10-1) = 2^9 = 0x3615902 We only store the first byte because it is the only one used.15903 */15904 rcon = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1B, 0x36];15905 // compute xtime table which maps i onto GF(i, 0x02)15906 var xtime = new Array(256);15907 for(var i = 0; i < 128; ++i) {15908 xtime[i] = i << 1;15909 xtime[i + 128] = (i + 128) << 1 ^ 0x11B;15910 }15911 // compute all other tables15912 sbox = new Array(256);15913 isbox = new Array(256);15914 mix = new Array(4);15915 imix = new Array(4);15916 for(var i = 0; i < 4; ++i) {15917 mix[i] = new Array(256);15918 imix[i] = new Array(256);15919 }15920 var e = 0, ei = 0, e2, e4, e8, sx, sx2, me, ime;15921 for(var i = 0; i < 256; ++i) {15922 /* We need to generate the SubBytes() sbox and isbox tables so that15923 we can perform byte substitutions. This requires us to traverse15924 all of the elements in GF, find their multiplicative inverses,15925 and apply to each the following affine transformation:15926 bi' = bi ^ b(i + 4) mod 8 ^ b(i + 5) mod 8 ^ b(i + 6) mod 8 ^15927 b(i + 7) mod 8 ^ ci15928 for 0 <= i < 8, where bi is the ith bit of the byte, and ci is the15929 ith bit of a byte c with the value {63} or {01100011}.15930 It is possible to traverse every possible value in a Galois field15931 using what is referred to as a 'generator'. There are many15932 generators (128 out of 256): 3,5,6,9,11,82 to name a few. To fully15933 traverse GF we iterate 255 times, multiplying by our generator15934 each time.15935 On each iteration we can determine the multiplicative inverse for15936 the current element.15937 Suppose there is an element in GF 'e'. For a given generator 'g',15938 e = g^x. The multiplicative inverse of e is g^(255 - x). It turns15939 out that if use the inverse of a generator as another generator15940 it will produce all of the corresponding multiplicative inverses15941 at the same time. For this reason, we choose 5 as our inverse15942 generator because it only requires 2 multiplies and 1 add and its15943 inverse, 82, requires relatively few operations as well.15944 In order to apply the affine transformation, the multiplicative15945 inverse 'ei' of 'e' can be repeatedly XOR'd (4 times) with a15946 bit-cycling of 'ei'. To do this 'ei' is first stored in 's' and15947 'x'. Then 's' is left shifted and the high bit of 's' is made the15948 low bit. The resulting value is stored in 's'. Then 'x' is XOR'd15949 with 's' and stored in 'x'. On each subsequent iteration the same15950 operation is performed. When 4 iterations are complete, 'x' is15951 XOR'd with 'c' (0x63) and the transformed value is stored in 'x'.15952 For example:15953 s = 0100000115954 x = 0100000115955 iteration 1: s = 10000010, x ^= s15956 iteration 2: s = 00000101, x ^= s15957 iteration 3: s = 00001010, x ^= s15958 iteration 4: s = 00010100, x ^= s15959 x ^= 0x6315960 This can be done with a loop where s = (s << 1) | (s >> 7). However,15961 it can also be done by using a single 16-bit (in this case 32-bit)15962 number 'sx'. Since XOR is an associative operation, we can set 'sx'15963 to 'ei' and then XOR it with 'sx' left-shifted 1,2,3, and 4 times.15964 The most significant bits will flow into the high 8 bit positions15965 and be correctly XOR'd with one another. All that remains will be15966 to cycle the high 8 bits by XOR'ing them all with the lower 8 bits15967 afterwards.15968 At the same time we're populating sbox and isbox we can precompute15969 the multiplication we'll need to do to do MixColumns() later.15970 */15971 // apply affine transformation15972 sx = ei ^ (ei << 1) ^ (ei << 2) ^ (ei << 3) ^ (ei << 4);15973 sx = (sx >> 8) ^ (sx & 255) ^ 0x63;15974 // update tables15975 sbox[e] = sx;15976 isbox[sx] = e;15977 /* Mixing columns is done using matrix multiplication. The columns15978 that are to be mixed are each a single word in the current state.15979 The state has Nb columns (4 columns). Therefore each column is a15980 4 byte word. So to mix the columns in a single column 'c' where15981 its rows are r0, r1, r2, and r3, we use the following matrix15982 multiplication:15983 [2 3 1 1]*[r0,c]=[r'0,c]15984 [1 2 3 1] [r1,c] [r'1,c]15985 [1 1 2 3] [r2,c] [r'2,c]15986 [3 1 1 2] [r3,c] [r'3,c]15987 r0, r1, r2, and r3 are each 1 byte of one of the words in the15988 state (a column). To do matrix multiplication for each mixed15989 column c' we multiply the corresponding row from the left matrix15990 with the corresponding column from the right matrix. In total, we15991 get 4 equations:15992 r0,c' = 2*r0,c + 3*r1,c + 1*r2,c + 1*r3,c15993 r1,c' = 1*r0,c + 2*r1,c + 3*r2,c + 1*r3,c15994 r2,c' = 1*r0,c + 1*r1,c + 2*r2,c + 3*r3,c15995 r3,c' = 3*r0,c + 1*r1,c + 1*r2,c + 2*r3,c15996 As usual, the multiplication is as previously defined and the15997 addition is XOR. In order to optimize mixing columns we can store15998 the multiplication results in tables. If you think of the whole15999 column as a word (it might help to visualize by mentally rotating16000 the equations above by counterclockwise 90 degrees) then you can16001 see that it would be useful to map the multiplications performed on16002 each byte (r0, r1, r2, r3) onto a word as well. For instance, we16003 could map 2*r0,1*r0,1*r0,3*r0 onto a word by storing 2*r0 in the16004 highest 8 bits and 3*r0 in the lowest 8 bits (with the other two16005 respectively in the middle). This means that a table can be16006 constructed that uses r0 as an index to the word. We can do the16007 same with r1, r2, and r3, creating a total of 4 tables.16008 To construct a full c', we can just look up each byte of c in16009 their respective tables and XOR the results together.16010 Also, to build each table we only have to calculate the word16011 for 2,1,1,3 for every byte ... which we can do on each iteration16012 of this loop since we will iterate over every byte. After we have16013 calculated 2,1,1,3 we can get the results for the other tables16014 by cycling the byte at the end to the beginning. For instance16015 we can take the result of table 2,1,1,3 and produce table 3,2,1,116016 by moving the right most byte to the left most position just like16017 how you can imagine the 3 moved out of 2,1,1,3 and to the front16018 to produce 3,2,1,1.16019 There is another optimization in that the same multiples of16020 the current element we need in order to advance our generator16021 to the next iteration can be reused in performing the 2,1,1,316022 calculation. We also calculate the inverse mix column tables,16023 with e,9,d,b being the inverse of 2,1,1,3.16024 When we're done, and we need to actually mix columns, the first16025 byte of each state word should be put through mix[0] (2,1,1,3),16026 the second through mix[1] (3,2,1,1) and so forth. Then they should16027 be XOR'd together to produce the fully mixed column.16028 */16029 // calculate mix and imix table values16030 sx2 = xtime[sx];16031 e2 = xtime[e];16032 e4 = xtime[e2];16033 e8 = xtime[e4];16034 me =16035 (sx2 << 24) ^ // 216036 (sx << 16) ^ // 116037 (sx << 8) ^ // 116038 (sx ^ sx2); // 316039 ime =16040 (e2 ^ e4 ^ e8) << 24 ^ // E (14)16041 (e ^ e8) << 16 ^ // 916042 (e ^ e4 ^ e8) << 8 ^ // D (13)16043 (e ^ e2 ^ e8); // B (11)16044 // produce each of the mix tables by rotating the 2,1,1,3 value16045 for(var n = 0; n < 4; ++n) {16046 mix[n][e] = me;16047 imix[n][sx] = ime;16048 // cycle the right most byte to the left most position16049 // ie: 2,1,1,3 becomes 3,2,1,116050 me = me << 24 | me >>> 8;16051 ime = ime << 24 | ime >>> 8;16052 }16053 // get next element and inverse16054 if(e === 0) {16055 // 1 is the inverse of 116056 e = ei = 1;16057 } else {16058 // e = 2e + 2*2*2*(10e)) = multiply e by 82 (chosen generator)16059 // ei = ei + 2*2*ei = multiply ei by 5 (inverse generator)16060 e = e2 ^ xtime[xtime[xtime[e2 ^ e8]]];16061 ei ^= xtime[xtime[ei]];16062 }16063 }16064}16065/**16066 * Generates a key schedule using the AES key expansion algorithm.16067 *16068 * The AES algorithm takes the Cipher Key, K, and performs a Key Expansion16069 * routine to generate a key schedule. The Key Expansion generates a total16070 * of Nb*(Nr + 1) words: the algorithm requires an initial set of Nb words,16071 * and each of the Nr rounds requires Nb words of key data. The resulting16072 * key schedule consists of a linear array of 4-byte words, denoted [wi ],16073 * with i in the range 0 <= i < Nb(Nr + 1).16074 *16075 * KeyExpansion(byte key[4*Nk], word w[Nb*(Nr+1)], Nk)16076 * AES-128 (Nb=4, Nk=4, Nr=10)16077 * AES-192 (Nb=4, Nk=6, Nr=12)16078 * AES-256 (Nb=4, Nk=8, Nr=14)16079 * Note: Nr=Nk+6.16080 *16081 * Nb is the number of columns (32-bit words) comprising the State (or16082 * number of bytes in a block). For AES, Nb=4.16083 *16084 * @param key the key to schedule (as an array of 32-bit words).16085 * @param decrypt true to modify the key schedule to decrypt, false not to.16086 *16087 * @return the generated key schedule.16088 */16089function _expandKey(key, decrypt) {16090 // copy the key's words to initialize the key schedule16091 var w = key.slice(0);16092 /* RotWord() will rotate a word, moving the first byte to the last16093 byte's position (shifting the other bytes left).16094 We will be getting the value of Rcon at i / Nk. 'i' will iterate16095 from Nk to (Nb * Nr+1). Nk = 4 (4 byte key), Nb = 4 (4 words in16096 a block), Nr = Nk + 6 (10). Therefore 'i' will iterate from16097 4 to 44 (exclusive). Each time we iterate 4 times, i / Nk will16098 increase by 1. We use a counter iNk to keep track of this.16099 */16100 // go through the rounds expanding the key16101 var temp, iNk = 1;16102 var Nk = w.length;16103 var Nr1 = Nk + 6 + 1;16104 var end = Nb * Nr1;16105 for(var i = Nk; i < end; ++i) {16106 temp = w[i - 1];16107 if(i % Nk === 0) {16108 // temp = SubWord(RotWord(temp)) ^ Rcon[i / Nk]16109 temp =16110 sbox[temp >>> 16 & 255] << 24 ^16111 sbox[temp >>> 8 & 255] << 16 ^16112 sbox[temp & 255] << 8 ^16113 sbox[temp >>> 24] ^ (rcon[iNk] << 24);16114 iNk++;16115 } else if(Nk > 6 && (i % Nk === 4)) {16116 // temp = SubWord(temp)16117 temp =16118 sbox[temp >>> 24] << 24 ^16119 sbox[temp >>> 16 & 255] << 16 ^16120 sbox[temp >>> 8 & 255] << 8 ^16121 sbox[temp & 255];16122 }16123 w[i] = w[i - Nk] ^ temp;16124 }16125 /* When we are updating a cipher block we always use the code path for16126 encryption whether we are decrypting or not (to shorten code and16127 simplify the generation of look up tables). However, because there16128 are differences in the decryption algorithm, other than just swapping16129 in different look up tables, we must transform our key schedule to16130 account for these changes:16131 1. The decryption algorithm gets its key rounds in reverse order.16132 2. The decryption algorithm adds the round key before mixing columns16133 instead of afterwards.16134 We don't need to modify our key schedule to handle the first case,16135 we can just traverse the key schedule in reverse order when decrypting.16136 The second case requires a little work.16137 The tables we built for performing rounds will take an input and then16138 perform SubBytes() and MixColumns() or, for the decrypt version,16139 InvSubBytes() and InvMixColumns(). But the decrypt algorithm requires16140 us to AddRoundKey() before InvMixColumns(). This means we'll need to16141 apply some transformations to the round key to inverse-mix its columns16142 so they'll be correct for moving AddRoundKey() to after the state has16143 had its columns inverse-mixed.16144 To inverse-mix the columns of the state when we're decrypting we use a16145 lookup table that will apply InvSubBytes() and InvMixColumns() at the16146 same time. However, the round key's bytes are not inverse-substituted16147 in the decryption algorithm. To get around this problem, we can first16148 substitute the bytes in the round key so that when we apply the16149 transformation via the InvSubBytes()+InvMixColumns() table, it will16150 undo our substitution leaving us with the original value that we16151 want -- and then inverse-mix that value.16152 This change will correctly alter our key schedule so that we can XOR16153 each round key with our already transformed decryption state. This16154 allows us to use the same code path as the encryption algorithm.16155 We make one more change to the decryption key. Since the decryption16156 algorithm runs in reverse from the encryption algorithm, we reverse16157 the order of the round keys to avoid having to iterate over the key16158 schedule backwards when running the encryption algorithm later in16159 decryption mode. In addition to reversing the order of the round keys,16160 we also swap each round key's 2nd and 4th rows. See the comments16161 section where rounds are performed for more details about why this is16162 done. These changes are done inline with the other substitution16163 described above.16164 */16165 if(decrypt) {16166 var tmp;16167 var m0 = imix[0];16168 var m1 = imix[1];16169 var m2 = imix[2];16170 var m3 = imix[3];16171 var wnew = w.slice(0);16172 end = w.length;16173 for(var i = 0, wi = end - Nb; i < end; i += Nb, wi -= Nb) {16174 // do not sub the first or last round key (round keys are Nb16175 // words) as no column mixing is performed before they are added,16176 // but do change the key order16177 if(i === 0 || i === (end - Nb)) {16178 wnew[i] = w[wi];16179 wnew[i + 1] = w[wi + 3];16180 wnew[i + 2] = w[wi + 2];16181 wnew[i + 3] = w[wi + 1];16182 } else {16183 // substitute each round key byte because the inverse-mix16184 // table will inverse-substitute it (effectively cancel the16185 // substitution because round key bytes aren't sub'd in16186 // decryption mode) and swap indexes 3 and 116187 for(var n = 0; n < Nb; ++n) {16188 tmp = w[wi + n];16189 wnew[i + (3&-n)] =16190 m0[sbox[tmp >>> 24]] ^16191 m1[sbox[tmp >>> 16 & 255]] ^16192 m2[sbox[tmp >>> 8 & 255]] ^16193 m3[sbox[tmp & 255]];16194 }16195 }16196 }16197 w = wnew;16198 }16199 return w;16200}16201/**16202 * Updates a single block (16 bytes) using AES. The update will either16203 * encrypt or decrypt the block.16204 *16205 * @param w the key schedule.16206 * @param input the input block (an array of 32-bit words).16207 * @param output the updated output block.16208 * @param decrypt true to decrypt the block, false to encrypt it.16209 */16210function _updateBlock(w, input, output, decrypt) {16211 /*16212 Cipher(byte in[4*Nb], byte out[4*Nb], word w[Nb*(Nr+1)])16213 begin16214 byte state[4,Nb]16215 state = in16216 AddRoundKey(state, w[0, Nb-1])16217 for round = 1 step 1 to Nr-116218 SubBytes(state)16219 ShiftRows(state)16220 MixColumns(state)16221 AddRoundKey(state, w[round*Nb, (round+1)*Nb-1])16222 end for16223 SubBytes(state)16224 ShiftRows(state)16225 AddRoundKey(state, w[Nr*Nb, (Nr+1)*Nb-1])16226 out = state16227 end16228 InvCipher(byte in[4*Nb], byte out[4*Nb], word w[Nb*(Nr+1)])16229 begin16230 byte state[4,Nb]16231 state = in16232 AddRoundKey(state, w[Nr*Nb, (Nr+1)*Nb-1])16233 for round = Nr-1 step -1 downto 116234 InvShiftRows(state)16235 InvSubBytes(state)16236 AddRoundKey(state, w[round*Nb, (round+1)*Nb-1])16237 InvMixColumns(state)16238 end for16239 InvShiftRows(state)16240 InvSubBytes(state)16241 AddRoundKey(state, w[0, Nb-1])16242 out = state16243 end16244 */16245 // Encrypt: AddRoundKey(state, w[0, Nb-1])16246 // Decrypt: AddRoundKey(state, w[Nr*Nb, (Nr+1)*Nb-1])16247 var Nr = w.length / 4 - 1;16248 var m0, m1, m2, m3, sub;16249 if(decrypt) {16250 m0 = imix[0];16251 m1 = imix[1];16252 m2 = imix[2];16253 m3 = imix[3];16254 sub = isbox;16255 } else {16256 m0 = mix[0];16257 m1 = mix[1];16258 m2 = mix[2];16259 m3 = mix[3];16260 sub = sbox;16261 }16262 var a, b, c, d, a2, b2, c2;16263 a = input[0] ^ w[0];16264 b = input[decrypt ? 3 : 1] ^ w[1];16265 c = input[2] ^ w[2];16266 d = input[decrypt ? 1 : 3] ^ w[3];16267 var i = 3;16268 /* In order to share code we follow the encryption algorithm when both16269 encrypting and decrypting. To account for the changes required in the16270 decryption algorithm, we use different lookup tables when decrypting16271 and use a modified key schedule to account for the difference in the16272 order of transformations applied when performing rounds. We also get16273 key rounds in reverse order (relative to encryption). */16274 for(var round = 1; round < Nr; ++round) {16275 /* As described above, we'll be using table lookups to perform the16276 column mixing. Each column is stored as a word in the state (the16277 array 'input' has one column as a word at each index). In order to16278 mix a column, we perform these transformations on each row in c,16279 which is 1 byte in each word. The new column for c0 is c'0:16280 m0 m1 m2 m316281 r0,c'0 = 2*r0,c0 + 3*r1,c0 + 1*r2,c0 + 1*r3,c016282 r1,c'0 = 1*r0,c0 + 2*r1,c0 + 3*r2,c0 + 1*r3,c016283 r2,c'0 = 1*r0,c0 + 1*r1,c0 + 2*r2,c0 + 3*r3,c016284 r3,c'0 = 3*r0,c0 + 1*r1,c0 + 1*r2,c0 + 2*r3,c016285 So using mix tables where c0 is a word with r0 being its upper16286 8 bits and r3 being its lower 8 bits:16287 m0[c0 >> 24] will yield this word: [2*r0,1*r0,1*r0,3*r0]16288 ...16289 m3[c0 & 255] will yield this word: [1*r3,1*r3,3*r3,2*r3]16290 Therefore to mix the columns in each word in the state we16291 do the following (& 255 omitted for brevity):16292 c'0,r0 = m0[c0 >> 24] ^ m1[c1 >> 16] ^ m2[c2 >> 8] ^ m3[c3]16293 c'0,r1 = m0[c0 >> 24] ^ m1[c1 >> 16] ^ m2[c2 >> 8] ^ m3[c3]16294 c'0,r2 = m0[c0 >> 24] ^ m1[c1 >> 16] ^ m2[c2 >> 8] ^ m3[c3]16295 c'0,r3 = m0[c0 >> 24] ^ m1[c1 >> 16] ^ m2[c2 >> 8] ^ m3[c3]16296 However, before mixing, the algorithm requires us to perform16297 ShiftRows(). The ShiftRows() transformation cyclically shifts the16298 last 3 rows of the state over different offsets. The first row16299 (r = 0) is not shifted.16300 s'_r,c = s_r,(c + shift(r, Nb) mod Nb16301 for 0 < r < 4 and 0 <= c < Nb and16302 shift(1, 4) = 116303 shift(2, 4) = 216304 shift(3, 4) = 3.16305 This causes the first byte in r = 1 to be moved to the end of16306 the row, the first 2 bytes in r = 2 to be moved to the end of16307 the row, the first 3 bytes in r = 3 to be moved to the end of16308 the row:16309 r1: [c0 c1 c2 c3] => [c1 c2 c3 c0]16310 r2: [c0 c1 c2 c3] [c2 c3 c0 c1]16311 r3: [c0 c1 c2 c3] [c3 c0 c1 c2]16312 We can make these substitutions inline with our column mixing to16313 generate an updated set of equations to produce each word in the16314 state (note the columns have changed positions):16315 c0 c1 c2 c3 => c0 c1 c2 c316316 c0 c1 c2 c3 c1 c2 c3 c0 (cycled 1 byte)16317 c0 c1 c2 c3 c2 c3 c0 c1 (cycled 2 bytes)16318 c0 c1 c2 c3 c3 c0 c1 c2 (cycled 3 bytes)16319 Therefore:16320 c'0 = 2*r0,c0 + 3*r1,c1 + 1*r2,c2 + 1*r3,c316321 c'0 = 1*r0,c0 + 2*r1,c1 + 3*r2,c2 + 1*r3,c316322 c'0 = 1*r0,c0 + 1*r1,c1 + 2*r2,c2 + 3*r3,c316323 c'0 = 3*r0,c0 + 1*r1,c1 + 1*r2,c2 + 2*r3,c316324 c'1 = 2*r0,c1 + 3*r1,c2 + 1*r2,c3 + 1*r3,c016325 c'1 = 1*r0,c1 + 2*r1,c2 + 3*r2,c3 + 1*r3,c016326 c'1 = 1*r0,c1 + 1*r1,c2 + 2*r2,c3 + 3*r3,c016327 c'1 = 3*r0,c1 + 1*r1,c2 + 1*r2,c3 + 2*r3,c016328 ... and so forth for c'2 and c'3. The important distinction is16329 that the columns are cycling, with c0 being used with the m016330 map when calculating c0, but c1 being used with the m0 map when16331 calculating c1 ... and so forth.16332 When performing the inverse we transform the mirror image and16333 skip the bottom row, instead of the top one, and move upwards:16334 c3 c2 c1 c0 => c0 c3 c2 c1 (cycled 3 bytes) *same as encryption16335 c3 c2 c1 c0 c1 c0 c3 c2 (cycled 2 bytes)16336 c3 c2 c1 c0 c2 c1 c0 c3 (cycled 1 byte) *same as encryption16337 c3 c2 c1 c0 c3 c2 c1 c016338 If you compare the resulting matrices for ShiftRows()+MixColumns()16339 and for InvShiftRows()+InvMixColumns() the 2nd and 4th columns are16340 different (in encrypt mode vs. decrypt mode). So in order to use16341 the same code to handle both encryption and decryption, we will16342 need to do some mapping.16343 If in encryption mode we let a=c0, b=c1, c=c2, d=c3, and r<N> be16344 a row number in the state, then the resulting matrix in encryption16345 mode for applying the above transformations would be:16346 r1: a b c d16347 r2: b c d a16348 r3: c d a b16349 r4: d a b c16350 If we did the same in decryption mode we would get:16351 r1: a d c b16352 r2: b a d c16353 r3: c b a d16354 r4: d c b a16355 If instead we swap d and b (set b=c3 and d=c1), then we get:16356 r1: a b c d16357 r2: d a b c16358 r3: c d a b16359 r4: b c d a16360 Now the 1st and 3rd rows are the same as the encryption matrix. All16361 we need to do then to make the mapping exactly the same is to swap16362 the 2nd and 4th rows when in decryption mode. To do this without16363 having to do it on each iteration, we swapped the 2nd and 4th rows16364 in the decryption key schedule. We also have to do the swap above16365 when we first pull in the input and when we set the final output. */16366 a2 =16367 m0[a >>> 24] ^16368 m1[b >>> 16 & 255] ^16369 m2[c >>> 8 & 255] ^16370 m3[d & 255] ^ w[++i];16371 b2 =16372 m0[b >>> 24] ^16373 m1[c >>> 16 & 255] ^16374 m2[d >>> 8 & 255] ^16375 m3[a & 255] ^ w[++i];16376 c2 =16377 m0[c >>> 24] ^16378 m1[d >>> 16 & 255] ^16379 m2[a >>> 8 & 255] ^16380 m3[b & 255] ^ w[++i];16381 d =16382 m0[d >>> 24] ^16383 m1[a >>> 16 & 255] ^16384 m2[b >>> 8 & 255] ^16385 m3[c & 255] ^ w[++i];16386 a = a2;16387 b = b2;16388 c = c2;16389 }16390 /*16391 Encrypt:16392 SubBytes(state)16393 ShiftRows(state)16394 AddRoundKey(state, w[Nr*Nb, (Nr+1)*Nb-1])16395 Decrypt:16396 InvShiftRows(state)16397 InvSubBytes(state)16398 AddRoundKey(state, w[0, Nb-1])16399 */16400 // Note: rows are shifted inline16401 output[0] =16402 (sub[a >>> 24] << 24) ^16403 (sub[b >>> 16 & 255] << 16) ^16404 (sub[c >>> 8 & 255] << 8) ^16405 (sub[d & 255]) ^ w[++i];16406 output[decrypt ? 3 : 1] =16407 (sub[b >>> 24] << 24) ^16408 (sub[c >>> 16 & 255] << 16) ^16409 (sub[d >>> 8 & 255] << 8) ^16410 (sub[a & 255]) ^ w[++i];16411 output[2] =16412 (sub[c >>> 24] << 24) ^16413 (sub[d >>> 16 & 255] << 16) ^16414 (sub[a >>> 8 & 255] << 8) ^16415 (sub[b & 255]) ^ w[++i];16416 output[decrypt ? 1 : 3] =16417 (sub[d >>> 24] << 24) ^16418 (sub[a >>> 16 & 255] << 16) ^16419 (sub[b >>> 8 & 255] << 8) ^16420 (sub[c & 255]) ^ w[++i];16421}16422/**16423 * Deprecated. Instead, use:16424 *16425 * forge.cipher.createCipher('AES-<mode>', key);16426 * forge.cipher.createDecipher('AES-<mode>', key);16427 *16428 * Creates a deprecated AES cipher object. This object's mode will default to16429 * CBC (cipher-block-chaining).16430 *16431 * The key and iv may be given as a string of bytes, an array of bytes, a16432 * byte buffer, or an array of 32-bit words.16433 *16434 * @param options the options to use.16435 * key the symmetric key to use.16436 * output the buffer to write to.16437 * decrypt true for decryption, false for encryption.16438 * mode the cipher mode to use (default: 'CBC').16439 *16440 * @return the cipher.16441 */16442function _createCipher(options) {16443 options = options || {};16444 var mode = (options.mode || 'CBC').toUpperCase();16445 var algorithm = 'AES-' + mode;16446 var cipher;16447 if(options.decrypt) {16448 cipher = forge.cipher.createDecipher(algorithm, options.key);16449 } else {16450 cipher = forge.cipher.createCipher(algorithm, options.key);16451 }16452 // backwards compatible start API16453 var start = cipher.start;16454 cipher.start = function(iv, options) {16455 // backwards compatibility: support second arg as output buffer16456 var output = null;16457 if(options instanceof forge.util.ByteBuffer) {16458 output = options;16459 options = {};16460 }16461 options = options || {};16462 options.output = output;16463 options.iv = iv;16464 start.call(cipher, options);16465 };16466 return cipher;16467}16468/***/ }),16469/***/ 1449:16470/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {16471/**16472 * A Javascript implementation of AES Cipher Suites for TLS.16473 *16474 * @author Dave Longley16475 *16476 * Copyright (c) 2009-2015 Digital Bazaar, Inc.16477 *16478 */16479var forge = __nccwpck_require__(9177);16480__nccwpck_require__(7994);16481__nccwpck_require__(9167);16482var tls = module.exports = forge.tls;16483/**16484 * Supported cipher suites.16485 */16486tls.CipherSuites['TLS_RSA_WITH_AES_128_CBC_SHA'] = {16487 id: [0x00, 0x2f],16488 name: 'TLS_RSA_WITH_AES_128_CBC_SHA',16489 initSecurityParameters: function(sp) {16490 sp.bulk_cipher_algorithm = tls.BulkCipherAlgorithm.aes;16491 sp.cipher_type = tls.CipherType.block;16492 sp.enc_key_length = 16;16493 sp.block_length = 16;16494 sp.fixed_iv_length = 16;16495 sp.record_iv_length = 16;16496 sp.mac_algorithm = tls.MACAlgorithm.hmac_sha1;16497 sp.mac_length = 20;16498 sp.mac_key_length = 20;16499 },16500 initConnectionState: initConnectionState16501};16502tls.CipherSuites['TLS_RSA_WITH_AES_256_CBC_SHA'] = {16503 id: [0x00, 0x35],16504 name: 'TLS_RSA_WITH_AES_256_CBC_SHA',16505 initSecurityParameters: function(sp) {16506 sp.bulk_cipher_algorithm = tls.BulkCipherAlgorithm.aes;16507 sp.cipher_type = tls.CipherType.block;16508 sp.enc_key_length = 32;16509 sp.block_length = 16;16510 sp.fixed_iv_length = 16;16511 sp.record_iv_length = 16;16512 sp.mac_algorithm = tls.MACAlgorithm.hmac_sha1;16513 sp.mac_length = 20;16514 sp.mac_key_length = 20;16515 },16516 initConnectionState: initConnectionState16517};16518function initConnectionState(state, c, sp) {16519 var client = (c.entity === forge.tls.ConnectionEnd.client);16520 // cipher setup16521 state.read.cipherState = {16522 init: false,16523 cipher: forge.cipher.createDecipher('AES-CBC', client ?16524 sp.keys.server_write_key : sp.keys.client_write_key),16525 iv: client ? sp.keys.server_write_IV : sp.keys.client_write_IV16526 };16527 state.write.cipherState = {16528 init: false,16529 cipher: forge.cipher.createCipher('AES-CBC', client ?16530 sp.keys.client_write_key : sp.keys.server_write_key),16531 iv: client ? sp.keys.client_write_IV : sp.keys.server_write_IV16532 };16533 state.read.cipherFunction = decrypt_aes_cbc_sha1;16534 state.write.cipherFunction = encrypt_aes_cbc_sha1;16535 // MAC setup16536 state.read.macLength = state.write.macLength = sp.mac_length;16537 state.read.macFunction = state.write.macFunction = tls.hmac_sha1;16538}16539/**16540 * Encrypts the TLSCompressed record into a TLSCipherText record using AES16541 * in CBC mode.16542 *16543 * @param record the TLSCompressed record to encrypt.16544 * @param s the ConnectionState to use.16545 *16546 * @return true on success, false on failure.16547 */16548function encrypt_aes_cbc_sha1(record, s) {16549 var rval = false;16550 // append MAC to fragment, update sequence number16551 var mac = s.macFunction(s.macKey, s.sequenceNumber, record);16552 record.fragment.putBytes(mac);16553 s.updateSequenceNumber();16554 // TLS 1.1+ use an explicit IV every time to protect against CBC attacks16555 var iv;16556 if(record.version.minor === tls.Versions.TLS_1_0.minor) {16557 // use the pre-generated IV when initializing for TLS 1.0, otherwise use16558 // the residue from the previous encryption16559 iv = s.cipherState.init ? null : s.cipherState.iv;16560 } else {16561 iv = forge.random.getBytesSync(16);16562 }16563 s.cipherState.init = true;16564 // start cipher16565 var cipher = s.cipherState.cipher;16566 cipher.start({iv: iv});16567 // TLS 1.1+ write IV into output16568 if(record.version.minor >= tls.Versions.TLS_1_1.minor) {16569 cipher.output.putBytes(iv);16570 }16571 // do encryption (default padding is appropriate)16572 cipher.update(record.fragment);16573 if(cipher.finish(encrypt_aes_cbc_sha1_padding)) {16574 // set record fragment to encrypted output16575 record.fragment = cipher.output;16576 record.length = record.fragment.length();16577 rval = true;16578 }16579 return rval;16580}16581/**16582 * Handles padding for aes_cbc_sha1 in encrypt mode.16583 *16584 * @param blockSize the block size.16585 * @param input the input buffer.16586 * @param decrypt true in decrypt mode, false in encrypt mode.16587 *16588 * @return true on success, false on failure.16589 */16590function encrypt_aes_cbc_sha1_padding(blockSize, input, decrypt) {16591 /* The encrypted data length (TLSCiphertext.length) is one more than the sum16592 of SecurityParameters.block_length, TLSCompressed.length,16593 SecurityParameters.mac_length, and padding_length.16594 The padding may be any length up to 255 bytes long, as long as it results in16595 the TLSCiphertext.length being an integral multiple of the block length.16596 Lengths longer than necessary might be desirable to frustrate attacks on a16597 protocol based on analysis of the lengths of exchanged messages. Each uint816598 in the padding data vector must be filled with the padding length value.16599 The padding length should be such that the total size of the16600 GenericBlockCipher structure is a multiple of the cipher's block length.16601 Legal values range from zero to 255, inclusive. This length specifies the16602 length of the padding field exclusive of the padding_length field itself.16603 This is slightly different from PKCS#7 because the padding value is 116604 less than the actual number of padding bytes if you include the16605 padding_length uint8 itself as a padding byte. */16606 if(!decrypt) {16607 // get the number of padding bytes required to reach the blockSize and16608 // subtract 1 for the padding value (to make room for the padding_length16609 // uint8)16610 var padding = blockSize - (input.length() % blockSize);16611 input.fillWithByte(padding - 1, padding);16612 }16613 return true;16614}16615/**16616 * Handles padding for aes_cbc_sha1 in decrypt mode.16617 *16618 * @param blockSize the block size.16619 * @param output the output buffer.16620 * @param decrypt true in decrypt mode, false in encrypt mode.16621 *16622 * @return true on success, false on failure.16623 */16624function decrypt_aes_cbc_sha1_padding(blockSize, output, decrypt) {16625 var rval = true;16626 if(decrypt) {16627 /* The last byte in the output specifies the number of padding bytes not16628 including itself. Each of the padding bytes has the same value as that16629 last byte (known as the padding_length). Here we check all padding16630 bytes to ensure they have the value of padding_length even if one of16631 them is bad in order to ward-off timing attacks. */16632 var len = output.length();16633 var paddingLength = output.last();16634 for(var i = len - 1 - paddingLength; i < len - 1; ++i) {16635 rval = rval && (output.at(i) == paddingLength);16636 }16637 if(rval) {16638 // trim off padding bytes and last padding length byte16639 output.truncate(paddingLength + 1);16640 }16641 }16642 return rval;16643}16644/**16645 * Decrypts a TLSCipherText record into a TLSCompressed record using16646 * AES in CBC mode.16647 *16648 * @param record the TLSCipherText record to decrypt.16649 * @param s the ConnectionState to use.16650 *16651 * @return true on success, false on failure.16652 */16653function decrypt_aes_cbc_sha1(record, s) {16654 var rval = false;16655 var iv;16656 if(record.version.minor === tls.Versions.TLS_1_0.minor) {16657 // use pre-generated IV when initializing for TLS 1.0, otherwise use the16658 // residue from the previous decryption16659 iv = s.cipherState.init ? null : s.cipherState.iv;16660 } else {16661 // TLS 1.1+ use an explicit IV every time to protect against CBC attacks16662 // that is appended to the record fragment16663 iv = record.fragment.getBytes(16);16664 }16665 s.cipherState.init = true;16666 // start cipher16667 var cipher = s.cipherState.cipher;16668 cipher.start({iv: iv});16669 // do decryption16670 cipher.update(record.fragment);16671 rval = cipher.finish(decrypt_aes_cbc_sha1_padding);16672 // even if decryption fails, keep going to minimize timing attacks16673 // decrypted data:16674 // first (len - 20) bytes = application data16675 // last 20 bytes = MAC16676 var macLen = s.macLength;16677 // create a random MAC to check against should the mac length check fail16678 // Note: do this regardless of the failure to keep timing consistent16679 var mac = forge.random.getBytesSync(macLen);16680 // get fragment and mac16681 var len = cipher.output.length();16682 if(len >= macLen) {16683 record.fragment = cipher.output.getBytes(len - macLen);16684 mac = cipher.output.getBytes(macLen);16685 } else {16686 // bad data, but get bytes anyway to try to keep timing consistent16687 record.fragment = cipher.output.getBytes();16688 }16689 record.fragment = forge.util.createBuffer(record.fragment);16690 record.length = record.fragment.length();16691 // see if data integrity checks out, update sequence number16692 var mac2 = s.macFunction(s.macKey, s.sequenceNumber, record);16693 s.updateSequenceNumber();16694 rval = compareMacs(s.macKey, mac, mac2) && rval;16695 return rval;16696}16697/**16698 * Safely compare two MACs. This function will compare two MACs in a way16699 * that protects against timing attacks.16700 *16701 * TODO: Expose elsewhere as a utility API.16702 *16703 * See: https://www.nccgroup.trust/us/about-us/newsroom-and-events/blog/2011/february/double-hmac-verification/16704 *16705 * @param key the MAC key to use.16706 * @param mac1 as a binary-encoded string of bytes.16707 * @param mac2 as a binary-encoded string of bytes.16708 *16709 * @return true if the MACs are the same, false if not.16710 */16711function compareMacs(key, mac1, mac2) {16712 var hmac = forge.hmac.create();16713 hmac.start('SHA1', key);16714 hmac.update(mac1);16715 mac1 = hmac.digest().getBytes();16716 hmac.start(null, null);16717 hmac.update(mac2);16718 mac2 = hmac.digest().getBytes();16719 return mac1 === mac2;16720}16721/***/ }),16722/***/ 9414:16723/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {16724/**16725 * Copyright (c) 2019 Digital Bazaar, Inc.16726 */16727var forge = __nccwpck_require__(9177);16728__nccwpck_require__(9549);16729var asn1 = forge.asn1;16730exports.privateKeyValidator = {16731 // PrivateKeyInfo16732 name: 'PrivateKeyInfo',16733 tagClass: asn1.Class.UNIVERSAL,16734 type: asn1.Type.SEQUENCE,16735 constructed: true,16736 value: [{16737 // Version (INTEGER)16738 name: 'PrivateKeyInfo.version',16739 tagClass: asn1.Class.UNIVERSAL,16740 type: asn1.Type.INTEGER,16741 constructed: false,16742 capture: 'privateKeyVersion'16743 }, {16744 // privateKeyAlgorithm16745 name: 'PrivateKeyInfo.privateKeyAlgorithm',16746 tagClass: asn1.Class.UNIVERSAL,16747 type: asn1.Type.SEQUENCE,16748 constructed: true,16749 value: [{16750 name: 'AlgorithmIdentifier.algorithm',16751 tagClass: asn1.Class.UNIVERSAL,16752 type: asn1.Type.OID,16753 constructed: false,16754 capture: 'privateKeyOid'16755 }]16756 }, {16757 // PrivateKey16758 name: 'PrivateKeyInfo',16759 tagClass: asn1.Class.UNIVERSAL,16760 type: asn1.Type.OCTETSTRING,16761 constructed: false,16762 capture: 'privateKey'16763 }]16764};16765exports.publicKeyValidator = {16766 name: 'SubjectPublicKeyInfo',16767 tagClass: asn1.Class.UNIVERSAL,16768 type: asn1.Type.SEQUENCE,16769 constructed: true,16770 captureAsn1: 'subjectPublicKeyInfo',16771 value: [{16772 name: 'SubjectPublicKeyInfo.AlgorithmIdentifier',16773 tagClass: asn1.Class.UNIVERSAL,16774 type: asn1.Type.SEQUENCE,16775 constructed: true,16776 value: [{16777 name: 'AlgorithmIdentifier.algorithm',16778 tagClass: asn1.Class.UNIVERSAL,16779 type: asn1.Type.OID,16780 constructed: false,16781 capture: 'publicKeyOid'16782 }]16783 },16784 // capture group for ed25519PublicKey16785 {16786 tagClass: asn1.Class.UNIVERSAL,16787 type: asn1.Type.BITSTRING,16788 constructed: false,16789 composed: true,16790 captureBitStringValue: 'ed25519PublicKey'16791 }16792 // FIXME: this is capture group for rsaPublicKey, use it in this API or16793 // discard?16794 /* {16795 // subjectPublicKey16796 name: 'SubjectPublicKeyInfo.subjectPublicKey',16797 tagClass: asn1.Class.UNIVERSAL,16798 type: asn1.Type.BITSTRING,16799 constructed: false,16800 value: [{16801 // RSAPublicKey16802 name: 'SubjectPublicKeyInfo.subjectPublicKey.RSAPublicKey',16803 tagClass: asn1.Class.UNIVERSAL,16804 type: asn1.Type.SEQUENCE,16805 constructed: true,16806 optional: true,16807 captureAsn1: 'rsaPublicKey'16808 }]16809 } */16810 ]16811};16812/***/ }),16813/***/ 9549:16814/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {16815/**16816 * Javascript implementation of Abstract Syntax Notation Number One.16817 *16818 * @author Dave Longley16819 *16820 * Copyright (c) 2010-2015 Digital Bazaar, Inc.16821 *16822 * An API for storing data using the Abstract Syntax Notation Number One16823 * format using DER (Distinguished Encoding Rules) encoding. This encoding is16824 * commonly used to store data for PKI, i.e. X.509 Certificates, and this16825 * implementation exists for that purpose.16826 *16827 * Abstract Syntax Notation Number One (ASN.1) is used to define the abstract16828 * syntax of information without restricting the way the information is encoded16829 * for transmission. It provides a standard that allows for open systems16830 * communication. ASN.1 defines the syntax of information data and a number of16831 * simple data types as well as a notation for describing them and specifying16832 * values for them.16833 *16834 * The RSA algorithm creates public and private keys that are often stored in16835 * X.509 or PKCS#X formats -- which use ASN.1 (encoded in DER format). This16836 * class provides the most basic functionality required to store and load DSA16837 * keys that are encoded according to ASN.1.16838 *16839 * The most common binary encodings for ASN.1 are BER (Basic Encoding Rules)16840 * and DER (Distinguished Encoding Rules). DER is just a subset of BER that16841 * has stricter requirements for how data must be encoded.16842 *16843 * Each ASN.1 structure has a tag (a byte identifying the ASN.1 structure type)16844 * and a byte array for the value of this ASN1 structure which may be data or a16845 * list of ASN.1 structures.16846 *16847 * Each ASN.1 structure using BER is (Tag-Length-Value):16848 *16849 * | byte 0 | bytes X | bytes Y |16850 * |--------|---------|----------16851 * | tag | length | value |16852 *16853 * ASN.1 allows for tags to be of "High-tag-number form" which allows a tag to16854 * be two or more octets, but that is not supported by this class. A tag is16855 * only 1 byte. Bits 1-5 give the tag number (ie the data type within a16856 * particular 'class'), 6 indicates whether or not the ASN.1 value is16857 * constructed from other ASN.1 values, and bits 7 and 8 give the 'class'. If16858 * bits 7 and 8 are both zero, the class is UNIVERSAL. If only bit 7 is set,16859 * then the class is APPLICATION. If only bit 8 is set, then the class is16860 * CONTEXT_SPECIFIC. If both bits 7 and 8 are set, then the class is PRIVATE.16861 * The tag numbers for the data types for the class UNIVERSAL are listed below:16862 *16863 * UNIVERSAL 0 Reserved for use by the encoding rules16864 * UNIVERSAL 1 Boolean type16865 * UNIVERSAL 2 Integer type16866 * UNIVERSAL 3 Bitstring type16867 * UNIVERSAL 4 Octetstring type16868 * UNIVERSAL 5 Null type16869 * UNIVERSAL 6 Object identifier type16870 * UNIVERSAL 7 Object descriptor type16871 * UNIVERSAL 8 External type and Instance-of type16872 * UNIVERSAL 9 Real type16873 * UNIVERSAL 10 Enumerated type16874 * UNIVERSAL 11 Embedded-pdv type16875 * UNIVERSAL 12 UTF8String type16876 * UNIVERSAL 13 Relative object identifier type16877 * UNIVERSAL 14-15 Reserved for future editions16878 * UNIVERSAL 16 Sequence and Sequence-of types16879 * UNIVERSAL 17 Set and Set-of types16880 * UNIVERSAL 18-22, 25-30 Character string types16881 * UNIVERSAL 23-24 Time types16882 *16883 * The length of an ASN.1 structure is specified after the tag identifier.16884 * There is a definite form and an indefinite form. The indefinite form may16885 * be used if the encoding is constructed and not all immediately available.16886 * The indefinite form is encoded using a length byte with only the 8th bit16887 * set. The end of the constructed object is marked using end-of-contents16888 * octets (two zero bytes).16889 *16890 * The definite form looks like this:16891 *16892 * The length may take up 1 or more bytes, it depends on the length of the16893 * value of the ASN.1 structure. DER encoding requires that if the ASN.116894 * structure has a value that has a length greater than 127, more than 1 byte16895 * will be used to store its length, otherwise just one byte will be used.16896 * This is strict.16897 *16898 * In the case that the length of the ASN.1 value is less than 127, 1 octet16899 * (byte) is used to store the "short form" length. The 8th bit has a value of16900 * 0 indicating the length is "short form" and not "long form" and bits 7-116901 * give the length of the data. (The 8th bit is the left-most, most significant16902 * bit: also known as big endian or network format).16903 *16904 * In the case that the length of the ASN.1 value is greater than 127, 2 to16905 * 127 octets (bytes) are used to store the "long form" length. The first16906 * byte's 8th bit is set to 1 to indicate the length is "long form." Bits 7-116907 * give the number of additional octets. All following octets are in base 25616908 * with the most significant digit first (typical big-endian binary unsigned16909 * integer storage). So, for instance, if the length of a value was 257, the16910 * first byte would be set to:16911 *16912 * 10000010 = 130 = 0x82.16913 *16914 * This indicates there are 2 octets (base 256) for the length. The second and16915 * third bytes (the octets just mentioned) would store the length in base 256:16916 *16917 * octet 2: 00000001 = 1 * 256^1 = 25616918 * octet 3: 00000001 = 1 * 256^0 = 116919 * total = 25716920 *16921 * The algorithm for converting a js integer value of 257 to base-256 is:16922 *16923 * var value = 257;16924 * var bytes = [];16925 * bytes[0] = (value >>> 8) & 0xFF; // most significant byte first16926 * bytes[1] = value & 0xFF; // least significant byte last16927 *16928 * On the ASN.1 UNIVERSAL Object Identifier (OID) type:16929 *16930 * An OID can be written like: "value1.value2.value3...valueN"16931 *16932 * The DER encoding rules:16933 *16934 * The first byte has the value 40 * value1 + value2.16935 * The following bytes, if any, encode the remaining values. Each value is16936 * encoded in base 128, most significant digit first (big endian), with as16937 * few digits as possible, and the most significant bit of each byte set16938 * to 1 except the last in each value's encoding. For example: Given the16939 * OID "1.2.840.113549", its DER encoding is (remember each byte except the16940 * last one in each encoding is OR'd with 0x80):16941 *16942 * byte 1: 40 * 1 + 2 = 42 = 0x2A.16943 * bytes 2-3: 128 * 6 + 72 = 840 = 6 72 = 6 72 = 0x0648 = 0x864816944 * bytes 4-6: 16384 * 6 + 128 * 119 + 13 = 6 119 13 = 0x06770D = 0x86F70D16945 *16946 * The final value is: 0x2A864886F70D.16947 * The full OID (including ASN.1 tag and length of 6 bytes) is:16948 * 0x06062A864886F70D16949 */16950var forge = __nccwpck_require__(9177);16951__nccwpck_require__(8339);16952__nccwpck_require__(1925);16953/* ASN.1 API */16954var asn1 = module.exports = forge.asn1 = forge.asn1 || {};16955/**16956 * ASN.1 classes.16957 */16958asn1.Class = {16959 UNIVERSAL: 0x00,16960 APPLICATION: 0x40,16961 CONTEXT_SPECIFIC: 0x80,16962 PRIVATE: 0xC016963};16964/**16965 * ASN.1 types. Not all types are supported by this implementation, only16966 * those necessary to implement a simple PKI are implemented.16967 */16968asn1.Type = {16969 NONE: 0,16970 BOOLEAN: 1,16971 INTEGER: 2,16972 BITSTRING: 3,16973 OCTETSTRING: 4,16974 NULL: 5,16975 OID: 6,16976 ODESC: 7,16977 EXTERNAL: 8,16978 REAL: 9,16979 ENUMERATED: 10,16980 EMBEDDED: 11,16981 UTF8: 12,16982 ROID: 13,16983 SEQUENCE: 16,16984 SET: 17,16985 PRINTABLESTRING: 19,16986 IA5STRING: 22,16987 UTCTIME: 23,16988 GENERALIZEDTIME: 24,16989 BMPSTRING: 3016990};16991/**16992 * Creates a new asn1 object.16993 *16994 * @param tagClass the tag class for the object.16995 * @param type the data type (tag number) for the object.16996 * @param constructed true if the asn1 object is in constructed form.16997 * @param value the value for the object, if it is not constructed.16998 * @param [options] the options to use:16999 * [bitStringContents] the plain BIT STRING content including padding17000 * byte.17001 *17002 * @return the asn1 object.17003 */17004asn1.create = function(tagClass, type, constructed, value, options) {17005 /* An asn1 object has a tagClass, a type, a constructed flag, and a17006 value. The value's type depends on the constructed flag. If17007 constructed, it will contain a list of other asn1 objects. If not,17008 it will contain the ASN.1 value as an array of bytes formatted17009 according to the ASN.1 data type. */17010 // remove undefined values17011 if(forge.util.isArray(value)) {17012 var tmp = [];17013 for(var i = 0; i < value.length; ++i) {17014 if(value[i] !== undefined) {17015 tmp.push(value[i]);17016 }17017 }17018 value = tmp;17019 }17020 var obj = {17021 tagClass: tagClass,17022 type: type,17023 constructed: constructed,17024 composed: constructed || forge.util.isArray(value),17025 value: value17026 };17027 if(options && 'bitStringContents' in options) {17028 // TODO: copy byte buffer if it's a buffer not a string17029 obj.bitStringContents = options.bitStringContents;17030 // TODO: add readonly flag to avoid this overhead17031 // save copy to detect changes17032 obj.original = asn1.copy(obj);17033 }17034 return obj;17035};17036/**17037 * Copies an asn1 object.17038 *17039 * @param obj the asn1 object.17040 * @param [options] copy options:17041 * [excludeBitStringContents] true to not copy bitStringContents17042 *17043 * @return the a copy of the asn1 object.17044 */17045asn1.copy = function(obj, options) {17046 var copy;17047 if(forge.util.isArray(obj)) {17048 copy = [];17049 for(var i = 0; i < obj.length; ++i) {17050 copy.push(asn1.copy(obj[i], options));17051 }17052 return copy;17053 }17054 if(typeof obj === 'string') {17055 // TODO: copy byte buffer if it's a buffer not a string17056 return obj;17057 }17058 copy = {17059 tagClass: obj.tagClass,17060 type: obj.type,17061 constructed: obj.constructed,17062 composed: obj.composed,17063 value: asn1.copy(obj.value, options)17064 };17065 if(options && !options.excludeBitStringContents) {17066 // TODO: copy byte buffer if it's a buffer not a string17067 copy.bitStringContents = obj.bitStringContents;17068 }17069 return copy;17070};17071/**17072 * Compares asn1 objects for equality.17073 *17074 * Note this function does not run in constant time.17075 *17076 * @param obj1 the first asn1 object.17077 * @param obj2 the second asn1 object.17078 * @param [options] compare options:17079 * [includeBitStringContents] true to compare bitStringContents17080 *17081 * @return true if the asn1 objects are equal.17082 */17083asn1.equals = function(obj1, obj2, options) {17084 if(forge.util.isArray(obj1)) {17085 if(!forge.util.isArray(obj2)) {17086 return false;17087 }17088 if(obj1.length !== obj2.length) {17089 return false;17090 }17091 for(var i = 0; i < obj1.length; ++i) {17092 if(!asn1.equals(obj1[i], obj2[i])) {17093 return false;17094 }17095 }17096 return true;17097 }17098 if(typeof obj1 !== typeof obj2) {17099 return false;17100 }17101 if(typeof obj1 === 'string') {17102 return obj1 === obj2;17103 }17104 var equal = obj1.tagClass === obj2.tagClass &&17105 obj1.type === obj2.type &&17106 obj1.constructed === obj2.constructed &&17107 obj1.composed === obj2.composed &&17108 asn1.equals(obj1.value, obj2.value);17109 if(options && options.includeBitStringContents) {17110 equal = equal && (obj1.bitStringContents === obj2.bitStringContents);17111 }17112 return equal;17113};17114/**17115 * Gets the length of a BER-encoded ASN.1 value.17116 *17117 * In case the length is not specified, undefined is returned.17118 *17119 * @param b the BER-encoded ASN.1 byte buffer, starting with the first17120 * length byte.17121 *17122 * @return the length of the BER-encoded ASN.1 value or undefined.17123 */17124asn1.getBerValueLength = function(b) {17125 // TODO: move this function and related DER/BER functions to a der.js17126 // file; better abstract ASN.1 away from der/ber.17127 var b2 = b.getByte();17128 if(b2 === 0x80) {17129 return undefined;17130 }17131 // see if the length is "short form" or "long form" (bit 8 set)17132 var length;17133 var longForm = b2 & 0x80;17134 if(!longForm) {17135 // length is just the first byte17136 length = b2;17137 } else {17138 // the number of bytes the length is specified in bits 7 through 117139 // and each length byte is in big-endian base-25617140 length = b.getInt((b2 & 0x7F) << 3);17141 }17142 return length;17143};17144/**17145 * Check if the byte buffer has enough bytes. Throws an Error if not.17146 *17147 * @param bytes the byte buffer to parse from.17148 * @param remaining the bytes remaining in the current parsing state.17149 * @param n the number of bytes the buffer must have.17150 */17151function _checkBufferLength(bytes, remaining, n) {17152 if(n > remaining) {17153 var error = new Error('Too few bytes to parse DER.');17154 error.available = bytes.length();17155 error.remaining = remaining;17156 error.requested = n;17157 throw error;17158 }17159}17160/**17161 * Gets the length of a BER-encoded ASN.1 value.17162 *17163 * In case the length is not specified, undefined is returned.17164 *17165 * @param bytes the byte buffer to parse from.17166 * @param remaining the bytes remaining in the current parsing state.17167 *17168 * @return the length of the BER-encoded ASN.1 value or undefined.17169 */17170var _getValueLength = function(bytes, remaining) {17171 // TODO: move this function and related DER/BER functions to a der.js17172 // file; better abstract ASN.1 away from der/ber.17173 // fromDer already checked that this byte exists17174 var b2 = bytes.getByte();17175 remaining--;17176 if(b2 === 0x80) {17177 return undefined;17178 }17179 // see if the length is "short form" or "long form" (bit 8 set)17180 var length;17181 var longForm = b2 & 0x80;17182 if(!longForm) {17183 // length is just the first byte17184 length = b2;17185 } else {17186 // the number of bytes the length is specified in bits 7 through 117187 // and each length byte is in big-endian base-25617188 var longFormBytes = b2 & 0x7F;17189 _checkBufferLength(bytes, remaining, longFormBytes);17190 length = bytes.getInt(longFormBytes << 3);17191 }17192 // FIXME: this will only happen for 32 bit getInt with high bit set17193 if(length < 0) {17194 throw new Error('Negative length: ' + length);17195 }17196 return length;17197};17198/**17199 * Parses an asn1 object from a byte buffer in DER format.17200 *17201 * @param bytes the byte buffer to parse from.17202 * @param [strict] true to be strict when checking value lengths, false to17203 * allow truncated values (default: true).17204 * @param [options] object with options or boolean strict flag17205 * [strict] true to be strict when checking value lengths, false to17206 * allow truncated values (default: true).17207 * [parseAllBytes] true to ensure all bytes are parsed17208 * (default: true)17209 * [decodeBitStrings] true to attempt to decode the content of17210 * BIT STRINGs (not OCTET STRINGs) using strict mode. Note that17211 * without schema support to understand the data context this can17212 * erroneously decode values that happen to be valid ASN.1. This17213 * flag will be deprecated or removed as soon as schema support is17214 * available. (default: true)17215 *17216 * @throws Will throw an error for various malformed input conditions.17217 *17218 * @return the parsed asn1 object.17219 */17220asn1.fromDer = function(bytes, options) {17221 if(options === undefined) {17222 options = {17223 strict: true,17224 parseAllBytes: true,17225 decodeBitStrings: true17226 };17227 }17228 if(typeof options === 'boolean') {17229 options = {17230 strict: options,17231 parseAllBytes: true,17232 decodeBitStrings: true17233 };17234 }17235 if(!('strict' in options)) {17236 options.strict = true;17237 }17238 if(!('parseAllBytes' in options)) {17239 options.parseAllBytes = true;17240 }17241 if(!('decodeBitStrings' in options)) {17242 options.decodeBitStrings = true;17243 }17244 // wrap in buffer if needed17245 if(typeof bytes === 'string') {17246 bytes = forge.util.createBuffer(bytes);17247 }17248 var byteCount = bytes.length();17249 var value = _fromDer(bytes, bytes.length(), 0, options);17250 if(options.parseAllBytes && bytes.length() !== 0) {17251 var error = new Error('Unparsed DER bytes remain after ASN.1 parsing.');17252 error.byteCount = byteCount;17253 error.remaining = bytes.length();17254 throw error;17255 }17256 return value;17257};17258/**17259 * Internal function to parse an asn1 object from a byte buffer in DER format.17260 *17261 * @param bytes the byte buffer to parse from.17262 * @param remaining the number of bytes remaining for this chunk.17263 * @param depth the current parsing depth.17264 * @param options object with same options as fromDer().17265 *17266 * @return the parsed asn1 object.17267 */17268function _fromDer(bytes, remaining, depth, options) {17269 // temporary storage for consumption calculations17270 var start;17271 // minimum length for ASN.1 DER structure is 217272 _checkBufferLength(bytes, remaining, 2);17273 // get the first byte17274 var b1 = bytes.getByte();17275 // consumed one byte17276 remaining--;17277 // get the tag class17278 var tagClass = (b1 & 0xC0);17279 // get the type (bits 1-5)17280 var type = b1 & 0x1F;17281 // get the variable value length and adjust remaining bytes17282 start = bytes.length();17283 var length = _getValueLength(bytes, remaining);17284 remaining -= start - bytes.length();17285 // ensure there are enough bytes to get the value17286 if(length !== undefined && length > remaining) {17287 if(options.strict) {17288 var error = new Error('Too few bytes to read ASN.1 value.');17289 error.available = bytes.length();17290 error.remaining = remaining;17291 error.requested = length;17292 throw error;17293 }17294 // Note: be lenient with truncated values and use remaining state bytes17295 length = remaining;17296 }17297 // value storage17298 var value;17299 // possible BIT STRING contents storage17300 var bitStringContents;17301 // constructed flag is bit 6 (32 = 0x20) of the first byte17302 var constructed = ((b1 & 0x20) === 0x20);17303 if(constructed) {17304 // parse child asn1 objects from the value17305 value = [];17306 if(length === undefined) {17307 // asn1 object of indefinite length, read until end tag17308 for(;;) {17309 _checkBufferLength(bytes, remaining, 2);17310 if(bytes.bytes(2) === String.fromCharCode(0, 0)) {17311 bytes.getBytes(2);17312 remaining -= 2;17313 break;17314 }17315 start = bytes.length();17316 value.push(_fromDer(bytes, remaining, depth + 1, options));17317 remaining -= start - bytes.length();17318 }17319 } else {17320 // parsing asn1 object of definite length17321 while(length > 0) {17322 start = bytes.length();17323 value.push(_fromDer(bytes, length, depth + 1, options));17324 remaining -= start - bytes.length();17325 length -= start - bytes.length();17326 }17327 }17328 }17329 // if a BIT STRING, save the contents including padding17330 if(value === undefined && tagClass === asn1.Class.UNIVERSAL &&17331 type === asn1.Type.BITSTRING) {17332 bitStringContents = bytes.bytes(length);17333 }17334 // determine if a non-constructed value should be decoded as a composed17335 // value that contains other ASN.1 objects. BIT STRINGs (and OCTET STRINGs)17336 // can be used this way.17337 if(value === undefined && options.decodeBitStrings &&17338 tagClass === asn1.Class.UNIVERSAL &&17339 // FIXME: OCTET STRINGs not yet supported here17340 // .. other parts of forge expect to decode OCTET STRINGs manually17341 (type === asn1.Type.BITSTRING /*|| type === asn1.Type.OCTETSTRING*/) &&17342 length > 1) {17343 // save read position17344 var savedRead = bytes.read;17345 var savedRemaining = remaining;17346 var unused = 0;17347 if(type === asn1.Type.BITSTRING) {17348 /* The first octet gives the number of bits by which the length of the17349 bit string is less than the next multiple of eight (this is called17350 the "number of unused bits").17351 The second and following octets give the value of the bit string17352 converted to an octet string. */17353 _checkBufferLength(bytes, remaining, 1);17354 unused = bytes.getByte();17355 remaining--;17356 }17357 // if all bits are used, maybe the BIT/OCTET STRING holds ASN.1 objs17358 if(unused === 0) {17359 try {17360 // attempt to parse child asn1 object from the value17361 // (stored in array to signal composed value)17362 start = bytes.length();17363 var subOptions = {17364 // enforce strict mode to avoid parsing ASN.1 from plain data17365 strict: true,17366 decodeBitStrings: true17367 };17368 var composed = _fromDer(bytes, remaining, depth + 1, subOptions);17369 var used = start - bytes.length();17370 remaining -= used;17371 if(type == asn1.Type.BITSTRING) {17372 used++;17373 }17374 // if the data all decoded and the class indicates UNIVERSAL or17375 // CONTEXT_SPECIFIC then assume we've got an encapsulated ASN.1 object17376 var tc = composed.tagClass;17377 if(used === length &&17378 (tc === asn1.Class.UNIVERSAL || tc === asn1.Class.CONTEXT_SPECIFIC)) {17379 value = [composed];17380 }17381 } catch(ex) {17382 }17383 }17384 if(value === undefined) {17385 // restore read position17386 bytes.read = savedRead;17387 remaining = savedRemaining;17388 }17389 }17390 if(value === undefined) {17391 // asn1 not constructed or composed, get raw value17392 // TODO: do DER to OID conversion and vice-versa in .toDer?17393 if(length === undefined) {17394 if(options.strict) {17395 throw new Error('Non-constructed ASN.1 object of indefinite length.');17396 }17397 // be lenient and use remaining state bytes17398 length = remaining;17399 }17400 if(type === asn1.Type.BMPSTRING) {17401 value = '';17402 for(; length > 0; length -= 2) {17403 _checkBufferLength(bytes, remaining, 2);17404 value += String.fromCharCode(bytes.getInt16());17405 remaining -= 2;17406 }17407 } else {17408 value = bytes.getBytes(length);17409 remaining -= length;17410 }17411 }17412 // add BIT STRING contents if available17413 var asn1Options = bitStringContents === undefined ? null : {17414 bitStringContents: bitStringContents17415 };17416 // create and return asn1 object17417 return asn1.create(tagClass, type, constructed, value, asn1Options);17418}17419/**17420 * Converts the given asn1 object to a buffer of bytes in DER format.17421 *17422 * @param asn1 the asn1 object to convert to bytes.17423 *17424 * @return the buffer of bytes.17425 */17426asn1.toDer = function(obj) {17427 var bytes = forge.util.createBuffer();17428 // build the first byte17429 var b1 = obj.tagClass | obj.type;17430 // for storing the ASN.1 value17431 var value = forge.util.createBuffer();17432 // use BIT STRING contents if available and data not changed17433 var useBitStringContents = false;17434 if('bitStringContents' in obj) {17435 useBitStringContents = true;17436 if(obj.original) {17437 useBitStringContents = asn1.equals(obj, obj.original);17438 }17439 }17440 if(useBitStringContents) {17441 value.putBytes(obj.bitStringContents);17442 } else if(obj.composed) {17443 // if composed, use each child asn1 object's DER bytes as value17444 // turn on 6th bit (0x20 = 32) to indicate asn1 is constructed17445 // from other asn1 objects17446 if(obj.constructed) {17447 b1 |= 0x20;17448 } else {17449 // type is a bit string, add unused bits of 0x0017450 value.putByte(0x00);17451 }17452 // add all of the child DER bytes together17453 for(var i = 0; i < obj.value.length; ++i) {17454 if(obj.value[i] !== undefined) {17455 value.putBuffer(asn1.toDer(obj.value[i]));17456 }17457 }17458 } else {17459 // use asn1.value directly17460 if(obj.type === asn1.Type.BMPSTRING) {17461 for(var i = 0; i < obj.value.length; ++i) {17462 value.putInt16(obj.value.charCodeAt(i));17463 }17464 } else {17465 // ensure integer is minimally-encoded17466 // TODO: should all leading bytes be stripped vs just one?17467 // .. ex '00 00 01' => '01'?17468 if(obj.type === asn1.Type.INTEGER &&17469 obj.value.length > 1 &&17470 // leading 0x00 for positive integer17471 ((obj.value.charCodeAt(0) === 0 &&17472 (obj.value.charCodeAt(1) & 0x80) === 0) ||17473 // leading 0xFF for negative integer17474 (obj.value.charCodeAt(0) === 0xFF &&17475 (obj.value.charCodeAt(1) & 0x80) === 0x80))) {17476 value.putBytes(obj.value.substr(1));17477 } else {17478 value.putBytes(obj.value);17479 }17480 }17481 }17482 // add tag byte17483 bytes.putByte(b1);17484 // use "short form" encoding17485 if(value.length() <= 127) {17486 // one byte describes the length17487 // bit 8 = 0 and bits 7-1 = length17488 bytes.putByte(value.length() & 0x7F);17489 } else {17490 // use "long form" encoding17491 // 2 to 127 bytes describe the length17492 // first byte: bit 8 = 1 and bits 7-1 = # of additional bytes17493 // other bytes: length in base 256, big-endian17494 var len = value.length();17495 var lenBytes = '';17496 do {17497 lenBytes += String.fromCharCode(len & 0xFF);17498 len = len >>> 8;17499 } while(len > 0);17500 // set first byte to # bytes used to store the length and turn on17501 // bit 8 to indicate long-form length is used17502 bytes.putByte(lenBytes.length | 0x80);17503 // concatenate length bytes in reverse since they were generated17504 // little endian and we need big endian17505 for(var i = lenBytes.length - 1; i >= 0; --i) {17506 bytes.putByte(lenBytes.charCodeAt(i));17507 }17508 }17509 // concatenate value bytes17510 bytes.putBuffer(value);17511 return bytes;17512};17513/**17514 * Converts an OID dot-separated string to a byte buffer. The byte buffer17515 * contains only the DER-encoded value, not any tag or length bytes.17516 *17517 * @param oid the OID dot-separated string.17518 *17519 * @return the byte buffer.17520 */17521asn1.oidToDer = function(oid) {17522 // split OID into individual values17523 var values = oid.split('.');17524 var bytes = forge.util.createBuffer();17525 // first byte is 40 * value1 + value217526 bytes.putByte(40 * parseInt(values[0], 10) + parseInt(values[1], 10));17527 // other bytes are each value in base 128 with 8th bit set except for17528 // the last byte for each value17529 var last, valueBytes, value, b;17530 for(var i = 2; i < values.length; ++i) {17531 // produce value bytes in reverse because we don't know how many17532 // bytes it will take to store the value17533 last = true;17534 valueBytes = [];17535 value = parseInt(values[i], 10);17536 do {17537 b = value & 0x7F;17538 value = value >>> 7;17539 // if value is not last, then turn on 8th bit17540 if(!last) {17541 b |= 0x80;17542 }17543 valueBytes.push(b);17544 last = false;17545 } while(value > 0);17546 // add value bytes in reverse (needs to be in big endian)17547 for(var n = valueBytes.length - 1; n >= 0; --n) {17548 bytes.putByte(valueBytes[n]);17549 }17550 }17551 return bytes;17552};17553/**17554 * Converts a DER-encoded byte buffer to an OID dot-separated string. The17555 * byte buffer should contain only the DER-encoded value, not any tag or17556 * length bytes.17557 *17558 * @param bytes the byte buffer.17559 *17560 * @return the OID dot-separated string.17561 */17562asn1.derToOid = function(bytes) {17563 var oid;17564 // wrap in buffer if needed17565 if(typeof bytes === 'string') {17566 bytes = forge.util.createBuffer(bytes);17567 }17568 // first byte is 40 * value1 + value217569 var b = bytes.getByte();17570 oid = Math.floor(b / 40) + '.' + (b % 40);17571 // other bytes are each value in base 128 with 8th bit set except for17572 // the last byte for each value17573 var value = 0;17574 while(bytes.length() > 0) {17575 b = bytes.getByte();17576 value = value << 7;17577 // not the last byte for the value17578 if(b & 0x80) {17579 value += b & 0x7F;17580 } else {17581 // last byte17582 oid += '.' + (value + b);17583 value = 0;17584 }17585 }17586 return oid;17587};17588/**17589 * Converts a UTCTime value to a date.17590 *17591 * Note: GeneralizedTime has 4 digits for the year and is used for X.50917592 * dates past 2049. Parsing that structure hasn't been implemented yet.17593 *17594 * @param utc the UTCTime value to convert.17595 *17596 * @return the date.17597 */17598asn1.utcTimeToDate = function(utc) {17599 /* The following formats can be used:17600 YYMMDDhhmmZ17601 YYMMDDhhmm+hh'mm'17602 YYMMDDhhmm-hh'mm'17603 YYMMDDhhmmssZ17604 YYMMDDhhmmss+hh'mm'17605 YYMMDDhhmmss-hh'mm'17606 Where:17607 YY is the least significant two digits of the year17608 MM is the month (01 to 12)17609 DD is the day (01 to 31)17610 hh is the hour (00 to 23)17611 mm are the minutes (00 to 59)17612 ss are the seconds (00 to 59)17613 Z indicates that local time is GMT, + indicates that local time is17614 later than GMT, and - indicates that local time is earlier than GMT17615 hh' is the absolute value of the offset from GMT in hours17616 mm' is the absolute value of the offset from GMT in minutes */17617 var date = new Date();17618 // if YY >= 50 use 19xx, if YY < 50 use 20xx17619 var year = parseInt(utc.substr(0, 2), 10);17620 year = (year >= 50) ? 1900 + year : 2000 + year;17621 var MM = parseInt(utc.substr(2, 2), 10) - 1; // use 0-11 for month17622 var DD = parseInt(utc.substr(4, 2), 10);17623 var hh = parseInt(utc.substr(6, 2), 10);17624 var mm = parseInt(utc.substr(8, 2), 10);17625 var ss = 0;17626 // not just YYMMDDhhmmZ17627 if(utc.length > 11) {17628 // get character after minutes17629 var c = utc.charAt(10);17630 var end = 10;17631 // see if seconds are present17632 if(c !== '+' && c !== '-') {17633 // get seconds17634 ss = parseInt(utc.substr(10, 2), 10);17635 end += 2;17636 }17637 }17638 // update date17639 date.setUTCFullYear(year, MM, DD);17640 date.setUTCHours(hh, mm, ss, 0);17641 if(end) {17642 // get +/- after end of time17643 c = utc.charAt(end);17644 if(c === '+' || c === '-') {17645 // get hours+minutes offset17646 var hhoffset = parseInt(utc.substr(end + 1, 2), 10);17647 var mmoffset = parseInt(utc.substr(end + 4, 2), 10);17648 // calculate offset in milliseconds17649 var offset = hhoffset * 60 + mmoffset;17650 offset *= 60000;17651 // apply offset17652 if(c === '+') {17653 date.setTime(+date - offset);17654 } else {17655 date.setTime(+date + offset);17656 }17657 }17658 }17659 return date;17660};17661/**17662 * Converts a GeneralizedTime value to a date.17663 *17664 * @param gentime the GeneralizedTime value to convert.17665 *17666 * @return the date.17667 */17668asn1.generalizedTimeToDate = function(gentime) {17669 /* The following formats can be used:17670 YYYYMMDDHHMMSS17671 YYYYMMDDHHMMSS.fff17672 YYYYMMDDHHMMSSZ17673 YYYYMMDDHHMMSS.fffZ17674 YYYYMMDDHHMMSS+hh'mm'17675 YYYYMMDDHHMMSS.fff+hh'mm'17676 YYYYMMDDHHMMSS-hh'mm'17677 YYYYMMDDHHMMSS.fff-hh'mm'17678 Where:17679 YYYY is the year17680 MM is the month (01 to 12)17681 DD is the day (01 to 31)17682 hh is the hour (00 to 23)17683 mm are the minutes (00 to 59)17684 ss are the seconds (00 to 59)17685 .fff is the second fraction, accurate to three decimal places17686 Z indicates that local time is GMT, + indicates that local time is17687 later than GMT, and - indicates that local time is earlier than GMT17688 hh' is the absolute value of the offset from GMT in hours17689 mm' is the absolute value of the offset from GMT in minutes */17690 var date = new Date();17691 var YYYY = parseInt(gentime.substr(0, 4), 10);17692 var MM = parseInt(gentime.substr(4, 2), 10) - 1; // use 0-11 for month17693 var DD = parseInt(gentime.substr(6, 2), 10);17694 var hh = parseInt(gentime.substr(8, 2), 10);17695 var mm = parseInt(gentime.substr(10, 2), 10);17696 var ss = parseInt(gentime.substr(12, 2), 10);17697 var fff = 0;17698 var offset = 0;17699 var isUTC = false;17700 if(gentime.charAt(gentime.length - 1) === 'Z') {17701 isUTC = true;17702 }17703 var end = gentime.length - 5, c = gentime.charAt(end);17704 if(c === '+' || c === '-') {17705 // get hours+minutes offset17706 var hhoffset = parseInt(gentime.substr(end + 1, 2), 10);17707 var mmoffset = parseInt(gentime.substr(end + 4, 2), 10);17708 // calculate offset in milliseconds17709 offset = hhoffset * 60 + mmoffset;17710 offset *= 60000;17711 // apply offset17712 if(c === '+') {17713 offset *= -1;17714 }17715 isUTC = true;17716 }17717 // check for second fraction17718 if(gentime.charAt(14) === '.') {17719 fff = parseFloat(gentime.substr(14), 10) * 1000;17720 }17721 if(isUTC) {17722 date.setUTCFullYear(YYYY, MM, DD);17723 date.setUTCHours(hh, mm, ss, fff);17724 // apply offset17725 date.setTime(+date + offset);17726 } else {17727 date.setFullYear(YYYY, MM, DD);17728 date.setHours(hh, mm, ss, fff);17729 }17730 return date;17731};17732/**17733 * Converts a date to a UTCTime value.17734 *17735 * Note: GeneralizedTime has 4 digits for the year and is used for X.50917736 * dates past 2049. Converting to a GeneralizedTime hasn't been17737 * implemented yet.17738 *17739 * @param date the date to convert.17740 *17741 * @return the UTCTime value.17742 */17743asn1.dateToUtcTime = function(date) {17744 // TODO: validate; currently assumes proper format17745 if(typeof date === 'string') {17746 return date;17747 }17748 var rval = '';17749 // create format YYMMDDhhmmssZ17750 var format = [];17751 format.push(('' + date.getUTCFullYear()).substr(2));17752 format.push('' + (date.getUTCMonth() + 1));17753 format.push('' + date.getUTCDate());17754 format.push('' + date.getUTCHours());17755 format.push('' + date.getUTCMinutes());17756 format.push('' + date.getUTCSeconds());17757 // ensure 2 digits are used for each format entry17758 for(var i = 0; i < format.length; ++i) {17759 if(format[i].length < 2) {17760 rval += '0';17761 }17762 rval += format[i];17763 }17764 rval += 'Z';17765 return rval;17766};17767/**17768 * Converts a date to a GeneralizedTime value.17769 *17770 * @param date the date to convert.17771 *17772 * @return the GeneralizedTime value as a string.17773 */17774asn1.dateToGeneralizedTime = function(date) {17775 // TODO: validate; currently assumes proper format17776 if(typeof date === 'string') {17777 return date;17778 }17779 var rval = '';17780 // create format YYYYMMDDHHMMSSZ17781 var format = [];17782 format.push('' + date.getUTCFullYear());17783 format.push('' + (date.getUTCMonth() + 1));17784 format.push('' + date.getUTCDate());17785 format.push('' + date.getUTCHours());17786 format.push('' + date.getUTCMinutes());17787 format.push('' + date.getUTCSeconds());17788 // ensure 2 digits are used for each format entry17789 for(var i = 0; i < format.length; ++i) {17790 if(format[i].length < 2) {17791 rval += '0';17792 }17793 rval += format[i];17794 }17795 rval += 'Z';17796 return rval;17797};17798/**17799 * Converts a javascript integer to a DER-encoded byte buffer to be used17800 * as the value for an INTEGER type.17801 *17802 * @param x the integer.17803 *17804 * @return the byte buffer.17805 */17806asn1.integerToDer = function(x) {17807 var rval = forge.util.createBuffer();17808 if(x >= -0x80 && x < 0x80) {17809 return rval.putSignedInt(x, 8);17810 }17811 if(x >= -0x8000 && x < 0x8000) {17812 return rval.putSignedInt(x, 16);17813 }17814 if(x >= -0x800000 && x < 0x800000) {17815 return rval.putSignedInt(x, 24);17816 }17817 if(x >= -0x80000000 && x < 0x80000000) {17818 return rval.putSignedInt(x, 32);17819 }17820 var error = new Error('Integer too large; max is 32-bits.');17821 error.integer = x;17822 throw error;17823};17824/**17825 * Converts a DER-encoded byte buffer to a javascript integer. This is17826 * typically used to decode the value of an INTEGER type.17827 *17828 * @param bytes the byte buffer.17829 *17830 * @return the integer.17831 */17832asn1.derToInteger = function(bytes) {17833 // wrap in buffer if needed17834 if(typeof bytes === 'string') {17835 bytes = forge.util.createBuffer(bytes);17836 }17837 var n = bytes.length() * 8;17838 if(n > 32) {17839 throw new Error('Integer too large; max is 32-bits.');17840 }17841 return bytes.getSignedInt(n);17842};17843/**17844 * Validates that the given ASN.1 object is at least a super set of the17845 * given ASN.1 structure. Only tag classes and types are checked. An17846 * optional map may also be provided to capture ASN.1 values while the17847 * structure is checked.17848 *17849 * To capture an ASN.1 value, set an object in the validator's 'capture'17850 * parameter to the key to use in the capture map. To capture the full17851 * ASN.1 object, specify 'captureAsn1'. To capture BIT STRING bytes, including17852 * the leading unused bits counter byte, specify 'captureBitStringContents'.17853 * To capture BIT STRING bytes, without the leading unused bits counter byte,17854 * specify 'captureBitStringValue'.17855 *17856 * Objects in the validator may set a field 'optional' to true to indicate17857 * that it isn't necessary to pass validation.17858 *17859 * @param obj the ASN.1 object to validate.17860 * @param v the ASN.1 structure validator.17861 * @param capture an optional map to capture values in.17862 * @param errors an optional array for storing validation errors.17863 *17864 * @return true on success, false on failure.17865 */17866asn1.validate = function(obj, v, capture, errors) {17867 var rval = false;17868 // ensure tag class and type are the same if specified17869 if((obj.tagClass === v.tagClass || typeof(v.tagClass) === 'undefined') &&17870 (obj.type === v.type || typeof(v.type) === 'undefined')) {17871 // ensure constructed flag is the same if specified17872 if(obj.constructed === v.constructed ||17873 typeof(v.constructed) === 'undefined') {17874 rval = true;17875 // handle sub values17876 if(v.value && forge.util.isArray(v.value)) {17877 var j = 0;17878 for(var i = 0; rval && i < v.value.length; ++i) {17879 rval = v.value[i].optional || false;17880 if(obj.value[j]) {17881 rval = asn1.validate(obj.value[j], v.value[i], capture, errors);17882 if(rval) {17883 ++j;17884 } else if(v.value[i].optional) {17885 rval = true;17886 }17887 }17888 if(!rval && errors) {17889 errors.push(17890 '[' + v.name + '] ' +17891 'Tag class "' + v.tagClass + '", type "' +17892 v.type + '" expected value length "' +17893 v.value.length + '", got "' +17894 obj.value.length + '"');17895 }17896 }17897 }17898 if(rval && capture) {17899 if(v.capture) {17900 capture[v.capture] = obj.value;17901 }17902 if(v.captureAsn1) {17903 capture[v.captureAsn1] = obj;17904 }17905 if(v.captureBitStringContents && 'bitStringContents' in obj) {17906 capture[v.captureBitStringContents] = obj.bitStringContents;17907 }17908 if(v.captureBitStringValue && 'bitStringContents' in obj) {17909 var value;17910 if(obj.bitStringContents.length < 2) {17911 capture[v.captureBitStringValue] = '';17912 } else {17913 // FIXME: support unused bits with data shifting17914 var unused = obj.bitStringContents.charCodeAt(0);17915 if(unused !== 0) {17916 throw new Error(17917 'captureBitStringValue only supported for zero unused bits');17918 }17919 capture[v.captureBitStringValue] = obj.bitStringContents.slice(1);17920 }17921 }17922 }17923 } else if(errors) {17924 errors.push(17925 '[' + v.name + '] ' +17926 'Expected constructed "' + v.constructed + '", got "' +17927 obj.constructed + '"');17928 }17929 } else if(errors) {17930 if(obj.tagClass !== v.tagClass) {17931 errors.push(17932 '[' + v.name + '] ' +17933 'Expected tag class "' + v.tagClass + '", got "' +17934 obj.tagClass + '"');17935 }17936 if(obj.type !== v.type) {17937 errors.push(17938 '[' + v.name + '] ' +17939 'Expected type "' + v.type + '", got "' + obj.type + '"');17940 }17941 }17942 return rval;17943};17944// regex for testing for non-latin characters17945var _nonLatinRegex = /[^\\u0000-\\u00ff]/;17946/**17947 * Pretty prints an ASN.1 object to a string.17948 *17949 * @param obj the object to write out.17950 * @param level the level in the tree.17951 * @param indentation the indentation to use.17952 *17953 * @return the string.17954 */17955asn1.prettyPrint = function(obj, level, indentation) {17956 var rval = '';17957 // set default level and indentation17958 level = level || 0;17959 indentation = indentation || 2;17960 // start new line for deep levels17961 if(level > 0) {17962 rval += '\n';17963 }17964 // create indent17965 var indent = '';17966 for(var i = 0; i < level * indentation; ++i) {17967 indent += ' ';17968 }17969 // print class:type17970 rval += indent + 'Tag: ';17971 switch(obj.tagClass) {17972 case asn1.Class.UNIVERSAL:17973 rval += 'Universal:';17974 break;17975 case asn1.Class.APPLICATION:17976 rval += 'Application:';17977 break;17978 case asn1.Class.CONTEXT_SPECIFIC:17979 rval += 'Context-Specific:';17980 break;17981 case asn1.Class.PRIVATE:17982 rval += 'Private:';17983 break;17984 }17985 if(obj.tagClass === asn1.Class.UNIVERSAL) {17986 rval += obj.type;17987 // known types17988 switch(obj.type) {17989 case asn1.Type.NONE:17990 rval += ' (None)';17991 break;17992 case asn1.Type.BOOLEAN:17993 rval += ' (Boolean)';17994 break;17995 case asn1.Type.INTEGER:17996 rval += ' (Integer)';17997 break;17998 case asn1.Type.BITSTRING:17999 rval += ' (Bit string)';18000 break;18001 case asn1.Type.OCTETSTRING:18002 rval += ' (Octet string)';18003 break;18004 case asn1.Type.NULL:18005 rval += ' (Null)';18006 break;18007 case asn1.Type.OID:18008 rval += ' (Object Identifier)';18009 break;18010 case asn1.Type.ODESC:18011 rval += ' (Object Descriptor)';18012 break;18013 case asn1.Type.EXTERNAL:18014 rval += ' (External or Instance of)';18015 break;18016 case asn1.Type.REAL:18017 rval += ' (Real)';18018 break;18019 case asn1.Type.ENUMERATED:18020 rval += ' (Enumerated)';18021 break;18022 case asn1.Type.EMBEDDED:18023 rval += ' (Embedded PDV)';18024 break;18025 case asn1.Type.UTF8:18026 rval += ' (UTF8)';18027 break;18028 case asn1.Type.ROID:18029 rval += ' (Relative Object Identifier)';18030 break;18031 case asn1.Type.SEQUENCE:18032 rval += ' (Sequence)';18033 break;18034 case asn1.Type.SET:18035 rval += ' (Set)';18036 break;18037 case asn1.Type.PRINTABLESTRING:18038 rval += ' (Printable String)';18039 break;18040 case asn1.Type.IA5String:18041 rval += ' (IA5String (ASCII))';18042 break;18043 case asn1.Type.UTCTIME:18044 rval += ' (UTC time)';18045 break;18046 case asn1.Type.GENERALIZEDTIME:18047 rval += ' (Generalized time)';18048 break;18049 case asn1.Type.BMPSTRING:18050 rval += ' (BMP String)';18051 break;18052 }18053 } else {18054 rval += obj.type;18055 }18056 rval += '\n';18057 rval += indent + 'Constructed: ' + obj.constructed + '\n';18058 if(obj.composed) {18059 var subvalues = 0;18060 var sub = '';18061 for(var i = 0; i < obj.value.length; ++i) {18062 if(obj.value[i] !== undefined) {18063 subvalues += 1;18064 sub += asn1.prettyPrint(obj.value[i], level + 1, indentation);18065 if((i + 1) < obj.value.length) {18066 sub += ',';18067 }18068 }18069 }18070 rval += indent + 'Sub values: ' + subvalues + sub;18071 } else {18072 rval += indent + 'Value: ';18073 if(obj.type === asn1.Type.OID) {18074 var oid = asn1.derToOid(obj.value);18075 rval += oid;18076 if(forge.pki && forge.pki.oids) {18077 if(oid in forge.pki.oids) {18078 rval += ' (' + forge.pki.oids[oid] + ') ';18079 }18080 }18081 }18082 if(obj.type === asn1.Type.INTEGER) {18083 try {18084 rval += asn1.derToInteger(obj.value);18085 } catch(ex) {18086 rval += '0x' + forge.util.bytesToHex(obj.value);18087 }18088 } else if(obj.type === asn1.Type.BITSTRING) {18089 // TODO: shift bits as needed to display without padding18090 if(obj.value.length > 1) {18091 // remove unused bits field18092 rval += '0x' + forge.util.bytesToHex(obj.value.slice(1));18093 } else {18094 rval += '(none)';18095 }18096 // show unused bit count18097 if(obj.value.length > 0) {18098 var unused = obj.value.charCodeAt(0);18099 if(unused == 1) {18100 rval += ' (1 unused bit shown)';18101 } else if(unused > 1) {18102 rval += ' (' + unused + ' unused bits shown)';18103 }18104 }18105 } else if(obj.type === asn1.Type.OCTETSTRING) {18106 if(!_nonLatinRegex.test(obj.value)) {18107 rval += '(' + obj.value + ') ';18108 }18109 rval += '0x' + forge.util.bytesToHex(obj.value);18110 } else if(obj.type === asn1.Type.UTF8) {18111 try {18112 rval += forge.util.decodeUtf8(obj.value);18113 } catch(e) {18114 if(e.message === 'URI malformed') {18115 rval +=18116 '0x' + forge.util.bytesToHex(obj.value) + ' (malformed UTF8)';18117 } else {18118 throw e;18119 }18120 }18121 } else if(obj.type === asn1.Type.PRINTABLESTRING ||18122 obj.type === asn1.Type.IA5String) {18123 rval += obj.value;18124 } else if(_nonLatinRegex.test(obj.value)) {18125 rval += '0x' + forge.util.bytesToHex(obj.value);18126 } else if(obj.value.length === 0) {18127 rval += '[null]';18128 } else {18129 rval += obj.value;18130 }18131 }18132 return rval;18133};18134/***/ }),18135/***/ 2300:18136/***/ ((module) => {18137/**18138 * Base-N/Base-X encoding/decoding functions.18139 *18140 * Original implementation from base-x:18141 * https://github.com/cryptocoinjs/base-x18142 *18143 * Which is MIT licensed:18144 *18145 * The MIT License (MIT)18146 *18147 * Copyright base-x contributors (c) 201618148 *18149 * Permission is hereby granted, free of charge, to any person obtaining a copy18150 * of this software and associated documentation files (the "Software"), to deal18151 * in the Software without restriction, including without limitation the rights18152 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell18153 * copies of the Software, and to permit persons to whom the Software is18154 * furnished to do so, subject to the following conditions:18155 *18156 * The above copyright notice and this permission notice shall be included in18157 * all copies or substantial portions of the Software.18158 *18159 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR18160 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,18161 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE18162 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER18163 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING18164 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER18165 * DEALINGS IN THE SOFTWARE.18166 */18167var api = {};18168module.exports = api;18169// baseN alphabet indexes18170var _reverseAlphabets = {};18171/**18172 * BaseN-encodes a Uint8Array using the given alphabet.18173 *18174 * @param input the Uint8Array to encode.18175 * @param maxline the maximum number of encoded characters per line to use,18176 * defaults to none.18177 *18178 * @return the baseN-encoded output string.18179 */18180api.encode = function(input, alphabet, maxline) {18181 if(typeof alphabet !== 'string') {18182 throw new TypeError('"alphabet" must be a string.');18183 }18184 if(maxline !== undefined && typeof maxline !== 'number') {18185 throw new TypeError('"maxline" must be a number.');18186 }18187 var output = '';18188 if(!(input instanceof Uint8Array)) {18189 // assume forge byte buffer18190 output = _encodeWithByteBuffer(input, alphabet);18191 } else {18192 var i = 0;18193 var base = alphabet.length;18194 var first = alphabet.charAt(0);18195 var digits = [0];18196 for(i = 0; i < input.length; ++i) {18197 for(var j = 0, carry = input[i]; j < digits.length; ++j) {18198 carry += digits[j] << 8;18199 digits[j] = carry % base;18200 carry = (carry / base) | 0;18201 }18202 while(carry > 0) {18203 digits.push(carry % base);18204 carry = (carry / base) | 0;18205 }18206 }18207 // deal with leading zeros18208 for(i = 0; input[i] === 0 && i < input.length - 1; ++i) {18209 output += first;18210 }18211 // convert digits to a string18212 for(i = digits.length - 1; i >= 0; --i) {18213 output += alphabet[digits[i]];18214 }18215 }18216 if(maxline) {18217 var regex = new RegExp('.{1,' + maxline + '}', 'g');18218 output = output.match(regex).join('\r\n');18219 }18220 return output;18221};18222/**18223 * Decodes a baseN-encoded (using the given alphabet) string to a18224 * Uint8Array.18225 *18226 * @param input the baseN-encoded input string.18227 *18228 * @return the Uint8Array.18229 */18230api.decode = function(input, alphabet) {18231 if(typeof input !== 'string') {18232 throw new TypeError('"input" must be a string.');18233 }18234 if(typeof alphabet !== 'string') {18235 throw new TypeError('"alphabet" must be a string.');18236 }18237 var table = _reverseAlphabets[alphabet];18238 if(!table) {18239 // compute reverse alphabet18240 table = _reverseAlphabets[alphabet] = [];18241 for(var i = 0; i < alphabet.length; ++i) {18242 table[alphabet.charCodeAt(i)] = i;18243 }18244 }18245 // remove whitespace characters18246 input = input.replace(/\s/g, '');18247 var base = alphabet.length;18248 var first = alphabet.charAt(0);18249 var bytes = [0];18250 for(var i = 0; i < input.length; i++) {18251 var value = table[input.charCodeAt(i)];18252 if(value === undefined) {18253 return;18254 }18255 for(var j = 0, carry = value; j < bytes.length; ++j) {18256 carry += bytes[j] * base;18257 bytes[j] = carry & 0xff;18258 carry >>= 8;18259 }18260 while(carry > 0) {18261 bytes.push(carry & 0xff);18262 carry >>= 8;18263 }18264 }18265 // deal with leading zeros18266 for(var k = 0; input[k] === first && k < input.length - 1; ++k) {18267 bytes.push(0);18268 }18269 if(typeof Buffer !== 'undefined') {18270 return Buffer.from(bytes.reverse());18271 }18272 return new Uint8Array(bytes.reverse());18273};18274function _encodeWithByteBuffer(input, alphabet) {18275 var i = 0;18276 var base = alphabet.length;18277 var first = alphabet.charAt(0);18278 var digits = [0];18279 for(i = 0; i < input.length(); ++i) {18280 for(var j = 0, carry = input.at(i); j < digits.length; ++j) {18281 carry += digits[j] << 8;18282 digits[j] = carry % base;18283 carry = (carry / base) | 0;18284 }18285 while(carry > 0) {18286 digits.push(carry % base);18287 carry = (carry / base) | 0;18288 }18289 }18290 var output = '';18291 // deal with leading zeros18292 for(i = 0; input.at(i) === 0 && i < input.length() - 1; ++i) {18293 output += first;18294 }18295 // convert digits to a string18296 for(i = digits.length - 1; i >= 0; --i) {18297 output += alphabet[digits[i]];18298 }18299 return output;18300}18301/***/ }),18302/***/ 7088:18303/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {18304/**18305 * Cipher base API.18306 *18307 * @author Dave Longley18308 *18309 * Copyright (c) 2010-2014 Digital Bazaar, Inc.18310 */18311var forge = __nccwpck_require__(9177);18312__nccwpck_require__(8339);18313module.exports = forge.cipher = forge.cipher || {};18314// registered algorithms18315forge.cipher.algorithms = forge.cipher.algorithms || {};18316/**18317 * Creates a cipher object that can be used to encrypt data using the given18318 * algorithm and key. The algorithm may be provided as a string value for a18319 * previously registered algorithm or it may be given as a cipher algorithm18320 * API object.18321 *18322 * @param algorithm the algorithm to use, either a string or an algorithm API18323 * object.18324 * @param key the key to use, as a binary-encoded string of bytes or a18325 * byte buffer.18326 *18327 * @return the cipher.18328 */18329forge.cipher.createCipher = function(algorithm, key) {18330 var api = algorithm;18331 if(typeof api === 'string') {18332 api = forge.cipher.getAlgorithm(api);18333 if(api) {18334 api = api();18335 }18336 }18337 if(!api) {18338 throw new Error('Unsupported algorithm: ' + algorithm);18339 }18340 // assume block cipher18341 return new forge.cipher.BlockCipher({18342 algorithm: api,18343 key: key,18344 decrypt: false18345 });18346};18347/**18348 * Creates a decipher object that can be used to decrypt data using the given18349 * algorithm and key. The algorithm may be provided as a string value for a18350 * previously registered algorithm or it may be given as a cipher algorithm18351 * API object.18352 *18353 * @param algorithm the algorithm to use, either a string or an algorithm API18354 * object.18355 * @param key the key to use, as a binary-encoded string of bytes or a18356 * byte buffer.18357 *18358 * @return the cipher.18359 */18360forge.cipher.createDecipher = function(algorithm, key) {18361 var api = algorithm;18362 if(typeof api === 'string') {18363 api = forge.cipher.getAlgorithm(api);18364 if(api) {18365 api = api();18366 }18367 }18368 if(!api) {18369 throw new Error('Unsupported algorithm: ' + algorithm);18370 }18371 // assume block cipher18372 return new forge.cipher.BlockCipher({18373 algorithm: api,18374 key: key,18375 decrypt: true18376 });18377};18378/**18379 * Registers an algorithm by name. If the name was already registered, the18380 * algorithm API object will be overwritten.18381 *18382 * @param name the name of the algorithm.18383 * @param algorithm the algorithm API object.18384 */18385forge.cipher.registerAlgorithm = function(name, algorithm) {18386 name = name.toUpperCase();18387 forge.cipher.algorithms[name] = algorithm;18388};18389/**18390 * Gets a registered algorithm by name.18391 *18392 * @param name the name of the algorithm.18393 *18394 * @return the algorithm, if found, null if not.18395 */18396forge.cipher.getAlgorithm = function(name) {18397 name = name.toUpperCase();18398 if(name in forge.cipher.algorithms) {18399 return forge.cipher.algorithms[name];18400 }18401 return null;18402};18403var BlockCipher = forge.cipher.BlockCipher = function(options) {18404 this.algorithm = options.algorithm;18405 this.mode = this.algorithm.mode;18406 this.blockSize = this.mode.blockSize;18407 this._finish = false;18408 this._input = null;18409 this.output = null;18410 this._op = options.decrypt ? this.mode.decrypt : this.mode.encrypt;18411 this._decrypt = options.decrypt;18412 this.algorithm.initialize(options);18413};18414/**18415 * Starts or restarts the encryption or decryption process, whichever18416 * was previously configured.18417 *18418 * For non-GCM mode, the IV may be a binary-encoded string of bytes, an array18419 * of bytes, a byte buffer, or an array of 32-bit integers. If the IV is in18420 * bytes, then it must be Nb (16) bytes in length. If the IV is given in as18421 * 32-bit integers, then it must be 4 integers long.18422 *18423 * Note: an IV is not required or used in ECB mode.18424 *18425 * For GCM-mode, the IV must be given as a binary-encoded string of bytes or18426 * a byte buffer. The number of bytes should be 12 (96 bits) as recommended18427 * by NIST SP-800-38D but another length may be given.18428 *18429 * @param options the options to use:18430 * iv the initialization vector to use as a binary-encoded string of18431 * bytes, null to reuse the last ciphered block from a previous18432 * update() (this "residue" method is for legacy support only).18433 * additionalData additional authentication data as a binary-encoded18434 * string of bytes, for 'GCM' mode, (default: none).18435 * tagLength desired length of authentication tag, in bits, for18436 * 'GCM' mode (0-128, default: 128).18437 * tag the authentication tag to check if decrypting, as a18438 * binary-encoded string of bytes.18439 * output the output the buffer to write to, null to create one.18440 */18441BlockCipher.prototype.start = function(options) {18442 options = options || {};18443 var opts = {};18444 for(var key in options) {18445 opts[key] = options[key];18446 }18447 opts.decrypt = this._decrypt;18448 this._finish = false;18449 this._input = forge.util.createBuffer();18450 this.output = options.output || forge.util.createBuffer();18451 this.mode.start(opts);18452};18453/**18454 * Updates the next block according to the cipher mode.18455 *18456 * @param input the buffer to read from.18457 */18458BlockCipher.prototype.update = function(input) {18459 if(input) {18460 // input given, so empty it into the input buffer18461 this._input.putBuffer(input);18462 }18463 // do cipher operation until it needs more input and not finished18464 while(!this._op.call(this.mode, this._input, this.output, this._finish) &&18465 !this._finish) {}18466 // free consumed memory from input buffer18467 this._input.compact();18468};18469/**18470 * Finishes encrypting or decrypting.18471 *18472 * @param pad a padding function to use in CBC mode, null for default,18473 * signature(blockSize, buffer, decrypt).18474 *18475 * @return true if successful, false on error.18476 */18477BlockCipher.prototype.finish = function(pad) {18478 // backwards-compatibility w/deprecated padding API18479 // Note: will overwrite padding functions even after another start() call18480 if(pad && (this.mode.name === 'ECB' || this.mode.name === 'CBC')) {18481 this.mode.pad = function(input) {18482 return pad(this.blockSize, input, false);18483 };18484 this.mode.unpad = function(output) {18485 return pad(this.blockSize, output, true);18486 };18487 }18488 // build options for padding and afterFinish functions18489 var options = {};18490 options.decrypt = this._decrypt;18491 // get # of bytes that won't fill a block18492 options.overflow = this._input.length() % this.blockSize;18493 if(!this._decrypt && this.mode.pad) {18494 if(!this.mode.pad(this._input, options)) {18495 return false;18496 }18497 }18498 // do final update18499 this._finish = true;18500 this.update();18501 if(this._decrypt && this.mode.unpad) {18502 if(!this.mode.unpad(this.output, options)) {18503 return false;18504 }18505 }18506 if(this.mode.afterFinish) {18507 if(!this.mode.afterFinish(this.output, options)) {18508 return false;18509 }18510 }18511 return true;18512};18513/***/ }),18514/***/ 873:18515/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {18516/**18517 * Supported cipher modes.18518 *18519 * @author Dave Longley18520 *18521 * Copyright (c) 2010-2014 Digital Bazaar, Inc.18522 */18523var forge = __nccwpck_require__(9177);18524__nccwpck_require__(8339);18525forge.cipher = forge.cipher || {};18526// supported cipher modes18527var modes = module.exports = forge.cipher.modes = forge.cipher.modes || {};18528/** Electronic codebook (ECB) (Don't use this; it's not secure) **/18529modes.ecb = function(options) {18530 options = options || {};18531 this.name = 'ECB';18532 this.cipher = options.cipher;18533 this.blockSize = options.blockSize || 16;18534 this._ints = this.blockSize / 4;18535 this._inBlock = new Array(this._ints);18536 this._outBlock = new Array(this._ints);18537};18538modes.ecb.prototype.start = function(options) {};18539modes.ecb.prototype.encrypt = function(input, output, finish) {18540 // not enough input to encrypt18541 if(input.length() < this.blockSize && !(finish && input.length() > 0)) {18542 return true;18543 }18544 // get next block18545 for(var i = 0; i < this._ints; ++i) {18546 this._inBlock[i] = input.getInt32();18547 }18548 // encrypt block18549 this.cipher.encrypt(this._inBlock, this._outBlock);18550 // write output18551 for(var i = 0; i < this._ints; ++i) {18552 output.putInt32(this._outBlock[i]);18553 }18554};18555modes.ecb.prototype.decrypt = function(input, output, finish) {18556 // not enough input to decrypt18557 if(input.length() < this.blockSize && !(finish && input.length() > 0)) {18558 return true;18559 }18560 // get next block18561 for(var i = 0; i < this._ints; ++i) {18562 this._inBlock[i] = input.getInt32();18563 }18564 // decrypt block18565 this.cipher.decrypt(this._inBlock, this._outBlock);18566 // write output18567 for(var i = 0; i < this._ints; ++i) {18568 output.putInt32(this._outBlock[i]);18569 }18570};18571modes.ecb.prototype.pad = function(input, options) {18572 // add PKCS#7 padding to block (each pad byte is the18573 // value of the number of pad bytes)18574 var padding = (input.length() === this.blockSize ?18575 this.blockSize : (this.blockSize - input.length()));18576 input.fillWithByte(padding, padding);18577 return true;18578};18579modes.ecb.prototype.unpad = function(output, options) {18580 // check for error: input data not a multiple of blockSize18581 if(options.overflow > 0) {18582 return false;18583 }18584 // ensure padding byte count is valid18585 var len = output.length();18586 var count = output.at(len - 1);18587 if(count > (this.blockSize << 2)) {18588 return false;18589 }18590 // trim off padding bytes18591 output.truncate(count);18592 return true;18593};18594/** Cipher-block Chaining (CBC) **/18595modes.cbc = function(options) {18596 options = options || {};18597 this.name = 'CBC';18598 this.cipher = options.cipher;18599 this.blockSize = options.blockSize || 16;18600 this._ints = this.blockSize / 4;18601 this._inBlock = new Array(this._ints);18602 this._outBlock = new Array(this._ints);18603};18604modes.cbc.prototype.start = function(options) {18605 // Note: legacy support for using IV residue (has security flaws)18606 // if IV is null, reuse block from previous processing18607 if(options.iv === null) {18608 // must have a previous block18609 if(!this._prev) {18610 throw new Error('Invalid IV parameter.');18611 }18612 this._iv = this._prev.slice(0);18613 } else if(!('iv' in options)) {18614 throw new Error('Invalid IV parameter.');18615 } else {18616 // save IV as "previous" block18617 this._iv = transformIV(options.iv, this.blockSize);18618 this._prev = this._iv.slice(0);18619 }18620};18621modes.cbc.prototype.encrypt = function(input, output, finish) {18622 // not enough input to encrypt18623 if(input.length() < this.blockSize && !(finish && input.length() > 0)) {18624 return true;18625 }18626 // get next block18627 // CBC XOR's IV (or previous block) with plaintext18628 for(var i = 0; i < this._ints; ++i) {18629 this._inBlock[i] = this._prev[i] ^ input.getInt32();18630 }18631 // encrypt block18632 this.cipher.encrypt(this._inBlock, this._outBlock);18633 // write output, save previous block18634 for(var i = 0; i < this._ints; ++i) {18635 output.putInt32(this._outBlock[i]);18636 }18637 this._prev = this._outBlock;18638};18639modes.cbc.prototype.decrypt = function(input, output, finish) {18640 // not enough input to decrypt18641 if(input.length() < this.blockSize && !(finish && input.length() > 0)) {18642 return true;18643 }18644 // get next block18645 for(var i = 0; i < this._ints; ++i) {18646 this._inBlock[i] = input.getInt32();18647 }18648 // decrypt block18649 this.cipher.decrypt(this._inBlock, this._outBlock);18650 // write output, save previous ciphered block18651 // CBC XOR's IV (or previous block) with ciphertext18652 for(var i = 0; i < this._ints; ++i) {18653 output.putInt32(this._prev[i] ^ this._outBlock[i]);18654 }18655 this._prev = this._inBlock.slice(0);18656};18657modes.cbc.prototype.pad = function(input, options) {18658 // add PKCS#7 padding to block (each pad byte is the18659 // value of the number of pad bytes)18660 var padding = (input.length() === this.blockSize ?18661 this.blockSize : (this.blockSize - input.length()));18662 input.fillWithByte(padding, padding);18663 return true;18664};18665modes.cbc.prototype.unpad = function(output, options) {18666 // check for error: input data not a multiple of blockSize18667 if(options.overflow > 0) {18668 return false;18669 }18670 // ensure padding byte count is valid18671 var len = output.length();18672 var count = output.at(len - 1);18673 if(count > (this.blockSize << 2)) {18674 return false;18675 }18676 // trim off padding bytes18677 output.truncate(count);18678 return true;18679};18680/** Cipher feedback (CFB) **/18681modes.cfb = function(options) {18682 options = options || {};18683 this.name = 'CFB';18684 this.cipher = options.cipher;18685 this.blockSize = options.blockSize || 16;18686 this._ints = this.blockSize / 4;18687 this._inBlock = null;18688 this._outBlock = new Array(this._ints);18689 this._partialBlock = new Array(this._ints);18690 this._partialOutput = forge.util.createBuffer();18691 this._partialBytes = 0;18692};18693modes.cfb.prototype.start = function(options) {18694 if(!('iv' in options)) {18695 throw new Error('Invalid IV parameter.');18696 }18697 // use IV as first input18698 this._iv = transformIV(options.iv, this.blockSize);18699 this._inBlock = this._iv.slice(0);18700 this._partialBytes = 0;18701};18702modes.cfb.prototype.encrypt = function(input, output, finish) {18703 // not enough input to encrypt18704 var inputLength = input.length();18705 if(inputLength === 0) {18706 return true;18707 }18708 // encrypt block18709 this.cipher.encrypt(this._inBlock, this._outBlock);18710 // handle full block18711 if(this._partialBytes === 0 && inputLength >= this.blockSize) {18712 // XOR input with output, write input as output18713 for(var i = 0; i < this._ints; ++i) {18714 this._inBlock[i] = input.getInt32() ^ this._outBlock[i];18715 output.putInt32(this._inBlock[i]);18716 }18717 return;18718 }18719 // handle partial block18720 var partialBytes = (this.blockSize - inputLength) % this.blockSize;18721 if(partialBytes > 0) {18722 partialBytes = this.blockSize - partialBytes;18723 }18724 // XOR input with output, write input as partial output18725 this._partialOutput.clear();18726 for(var i = 0; i < this._ints; ++i) {18727 this._partialBlock[i] = input.getInt32() ^ this._outBlock[i];18728 this._partialOutput.putInt32(this._partialBlock[i]);18729 }18730 if(partialBytes > 0) {18731 // block still incomplete, restore input buffer18732 input.read -= this.blockSize;18733 } else {18734 // block complete, update input block18735 for(var i = 0; i < this._ints; ++i) {18736 this._inBlock[i] = this._partialBlock[i];18737 }18738 }18739 // skip any previous partial bytes18740 if(this._partialBytes > 0) {18741 this._partialOutput.getBytes(this._partialBytes);18742 }18743 if(partialBytes > 0 && !finish) {18744 output.putBytes(this._partialOutput.getBytes(18745 partialBytes - this._partialBytes));18746 this._partialBytes = partialBytes;18747 return true;18748 }18749 output.putBytes(this._partialOutput.getBytes(18750 inputLength - this._partialBytes));18751 this._partialBytes = 0;18752};18753modes.cfb.prototype.decrypt = function(input, output, finish) {18754 // not enough input to decrypt18755 var inputLength = input.length();18756 if(inputLength === 0) {18757 return true;18758 }18759 // encrypt block (CFB always uses encryption mode)18760 this.cipher.encrypt(this._inBlock, this._outBlock);18761 // handle full block18762 if(this._partialBytes === 0 && inputLength >= this.blockSize) {18763 // XOR input with output, write input as output18764 for(var i = 0; i < this._ints; ++i) {18765 this._inBlock[i] = input.getInt32();18766 output.putInt32(this._inBlock[i] ^ this._outBlock[i]);18767 }18768 return;18769 }18770 // handle partial block18771 var partialBytes = (this.blockSize - inputLength) % this.blockSize;18772 if(partialBytes > 0) {18773 partialBytes = this.blockSize - partialBytes;18774 }18775 // XOR input with output, write input as partial output18776 this._partialOutput.clear();18777 for(var i = 0; i < this._ints; ++i) {18778 this._partialBlock[i] = input.getInt32();18779 this._partialOutput.putInt32(this._partialBlock[i] ^ this._outBlock[i]);18780 }18781 if(partialBytes > 0) {18782 // block still incomplete, restore input buffer18783 input.read -= this.blockSize;18784 } else {18785 // block complete, update input block18786 for(var i = 0; i < this._ints; ++i) {18787 this._inBlock[i] = this._partialBlock[i];18788 }18789 }18790 // skip any previous partial bytes18791 if(this._partialBytes > 0) {18792 this._partialOutput.getBytes(this._partialBytes);18793 }18794 if(partialBytes > 0 && !finish) {18795 output.putBytes(this._partialOutput.getBytes(18796 partialBytes - this._partialBytes));18797 this._partialBytes = partialBytes;18798 return true;18799 }18800 output.putBytes(this._partialOutput.getBytes(18801 inputLength - this._partialBytes));18802 this._partialBytes = 0;18803};18804/** Output feedback (OFB) **/18805modes.ofb = function(options) {18806 options = options || {};18807 this.name = 'OFB';18808 this.cipher = options.cipher;18809 this.blockSize = options.blockSize || 16;18810 this._ints = this.blockSize / 4;18811 this._inBlock = null;18812 this._outBlock = new Array(this._ints);18813 this._partialOutput = forge.util.createBuffer();18814 this._partialBytes = 0;18815};18816modes.ofb.prototype.start = function(options) {18817 if(!('iv' in options)) {18818 throw new Error('Invalid IV parameter.');18819 }18820 // use IV as first input18821 this._iv = transformIV(options.iv, this.blockSize);18822 this._inBlock = this._iv.slice(0);18823 this._partialBytes = 0;18824};18825modes.ofb.prototype.encrypt = function(input, output, finish) {18826 // not enough input to encrypt18827 var inputLength = input.length();18828 if(input.length() === 0) {18829 return true;18830 }18831 // encrypt block (OFB always uses encryption mode)18832 this.cipher.encrypt(this._inBlock, this._outBlock);18833 // handle full block18834 if(this._partialBytes === 0 && inputLength >= this.blockSize) {18835 // XOR input with output and update next input18836 for(var i = 0; i < this._ints; ++i) {18837 output.putInt32(input.getInt32() ^ this._outBlock[i]);18838 this._inBlock[i] = this._outBlock[i];18839 }18840 return;18841 }18842 // handle partial block18843 var partialBytes = (this.blockSize - inputLength) % this.blockSize;18844 if(partialBytes > 0) {18845 partialBytes = this.blockSize - partialBytes;18846 }18847 // XOR input with output18848 this._partialOutput.clear();18849 for(var i = 0; i < this._ints; ++i) {18850 this._partialOutput.putInt32(input.getInt32() ^ this._outBlock[i]);18851 }18852 if(partialBytes > 0) {18853 // block still incomplete, restore input buffer18854 input.read -= this.blockSize;18855 } else {18856 // block complete, update input block18857 for(var i = 0; i < this._ints; ++i) {18858 this._inBlock[i] = this._outBlock[i];18859 }18860 }18861 // skip any previous partial bytes18862 if(this._partialBytes > 0) {18863 this._partialOutput.getBytes(this._partialBytes);18864 }18865 if(partialBytes > 0 && !finish) {18866 output.putBytes(this._partialOutput.getBytes(18867 partialBytes - this._partialBytes));18868 this._partialBytes = partialBytes;18869 return true;18870 }18871 output.putBytes(this._partialOutput.getBytes(18872 inputLength - this._partialBytes));18873 this._partialBytes = 0;18874};18875modes.ofb.prototype.decrypt = modes.ofb.prototype.encrypt;18876/** Counter (CTR) **/18877modes.ctr = function(options) {18878 options = options || {};18879 this.name = 'CTR';18880 this.cipher = options.cipher;18881 this.blockSize = options.blockSize || 16;18882 this._ints = this.blockSize / 4;18883 this._inBlock = null;18884 this._outBlock = new Array(this._ints);18885 this._partialOutput = forge.util.createBuffer();18886 this._partialBytes = 0;18887};18888modes.ctr.prototype.start = function(options) {18889 if(!('iv' in options)) {18890 throw new Error('Invalid IV parameter.');18891 }18892 // use IV as first input18893 this._iv = transformIV(options.iv, this.blockSize);18894 this._inBlock = this._iv.slice(0);18895 this._partialBytes = 0;18896};18897modes.ctr.prototype.encrypt = function(input, output, finish) {18898 // not enough input to encrypt18899 var inputLength = input.length();18900 if(inputLength === 0) {18901 return true;18902 }18903 // encrypt block (CTR always uses encryption mode)18904 this.cipher.encrypt(this._inBlock, this._outBlock);18905 // handle full block18906 if(this._partialBytes === 0 && inputLength >= this.blockSize) {18907 // XOR input with output18908 for(var i = 0; i < this._ints; ++i) {18909 output.putInt32(input.getInt32() ^ this._outBlock[i]);18910 }18911 } else {18912 // handle partial block18913 var partialBytes = (this.blockSize - inputLength) % this.blockSize;18914 if(partialBytes > 0) {18915 partialBytes = this.blockSize - partialBytes;18916 }18917 // XOR input with output18918 this._partialOutput.clear();18919 for(var i = 0; i < this._ints; ++i) {18920 this._partialOutput.putInt32(input.getInt32() ^ this._outBlock[i]);18921 }18922 if(partialBytes > 0) {18923 // block still incomplete, restore input buffer18924 input.read -= this.blockSize;18925 }18926 // skip any previous partial bytes18927 if(this._partialBytes > 0) {18928 this._partialOutput.getBytes(this._partialBytes);18929 }18930 if(partialBytes > 0 && !finish) {18931 output.putBytes(this._partialOutput.getBytes(18932 partialBytes - this._partialBytes));18933 this._partialBytes = partialBytes;18934 return true;18935 }18936 output.putBytes(this._partialOutput.getBytes(18937 inputLength - this._partialBytes));18938 this._partialBytes = 0;18939 }18940 // block complete, increment counter (input block)18941 inc32(this._inBlock);18942};18943modes.ctr.prototype.decrypt = modes.ctr.prototype.encrypt;18944/** Galois/Counter Mode (GCM) **/18945modes.gcm = function(options) {18946 options = options || {};18947 this.name = 'GCM';18948 this.cipher = options.cipher;18949 this.blockSize = options.blockSize || 16;18950 this._ints = this.blockSize / 4;18951 this._inBlock = new Array(this._ints);18952 this._outBlock = new Array(this._ints);18953 this._partialOutput = forge.util.createBuffer();18954 this._partialBytes = 0;18955 // R is actually this value concatenated with 120 more zero bits, but18956 // we only XOR against R so the other zeros have no effect -- we just18957 // apply this value to the first integer in a block18958 this._R = 0xE1000000;18959};18960modes.gcm.prototype.start = function(options) {18961 if(!('iv' in options)) {18962 throw new Error('Invalid IV parameter.');18963 }18964 // ensure IV is a byte buffer18965 var iv = forge.util.createBuffer(options.iv);18966 // no ciphered data processed yet18967 this._cipherLength = 0;18968 // default additional data is none18969 var additionalData;18970 if('additionalData' in options) {18971 additionalData = forge.util.createBuffer(options.additionalData);18972 } else {18973 additionalData = forge.util.createBuffer();18974 }18975 // default tag length is 128 bits18976 if('tagLength' in options) {18977 this._tagLength = options.tagLength;18978 } else {18979 this._tagLength = 128;18980 }18981 // if tag is given, ensure tag matches tag length18982 this._tag = null;18983 if(options.decrypt) {18984 // save tag to check later18985 this._tag = forge.util.createBuffer(options.tag).getBytes();18986 if(this._tag.length !== (this._tagLength / 8)) {18987 throw new Error('Authentication tag does not match tag length.');18988 }18989 }18990 // create tmp storage for hash calculation18991 this._hashBlock = new Array(this._ints);18992 // no tag generated yet18993 this.tag = null;18994 // generate hash subkey18995 // (apply block cipher to "zero" block)18996 this._hashSubkey = new Array(this._ints);18997 this.cipher.encrypt([0, 0, 0, 0], this._hashSubkey);18998 // generate table M18999 // use 4-bit tables (32 component decomposition of a 16 byte value)19000 // 8-bit tables take more space and are known to have security19001 // vulnerabilities (in native implementations)19002 this.componentBits = 4;19003 this._m = this.generateHashTable(this._hashSubkey, this.componentBits);19004 // Note: support IV length different from 96 bits? (only supporting19005 // 96 bits is recommended by NIST SP-800-38D)19006 // generate J_019007 var ivLength = iv.length();19008 if(ivLength === 12) {19009 // 96-bit IV19010 this._j0 = [iv.getInt32(), iv.getInt32(), iv.getInt32(), 1];19011 } else {19012 // IV is NOT 96-bits19013 this._j0 = [0, 0, 0, 0];19014 while(iv.length() > 0) {19015 this._j0 = this.ghash(19016 this._hashSubkey, this._j0,19017 [iv.getInt32(), iv.getInt32(), iv.getInt32(), iv.getInt32()]);19018 }19019 this._j0 = this.ghash(19020 this._hashSubkey, this._j0, [0, 0].concat(from64To32(ivLength * 8)));19021 }19022 // generate ICB (initial counter block)19023 this._inBlock = this._j0.slice(0);19024 inc32(this._inBlock);19025 this._partialBytes = 0;19026 // consume authentication data19027 additionalData = forge.util.createBuffer(additionalData);19028 // save additional data length as a BE 64-bit number19029 this._aDataLength = from64To32(additionalData.length() * 8);19030 // pad additional data to 128 bit (16 byte) block size19031 var overflow = additionalData.length() % this.blockSize;19032 if(overflow) {19033 additionalData.fillWithByte(0, this.blockSize - overflow);19034 }19035 this._s = [0, 0, 0, 0];19036 while(additionalData.length() > 0) {19037 this._s = this.ghash(this._hashSubkey, this._s, [19038 additionalData.getInt32(),19039 additionalData.getInt32(),19040 additionalData.getInt32(),19041 additionalData.getInt32()19042 ]);19043 }19044};19045modes.gcm.prototype.encrypt = function(input, output, finish) {19046 // not enough input to encrypt19047 var inputLength = input.length();19048 if(inputLength === 0) {19049 return true;19050 }19051 // encrypt block19052 this.cipher.encrypt(this._inBlock, this._outBlock);19053 // handle full block19054 if(this._partialBytes === 0 && inputLength >= this.blockSize) {19055 // XOR input with output19056 for(var i = 0; i < this._ints; ++i) {19057 output.putInt32(this._outBlock[i] ^= input.getInt32());19058 }19059 this._cipherLength += this.blockSize;19060 } else {19061 // handle partial block19062 var partialBytes = (this.blockSize - inputLength) % this.blockSize;19063 if(partialBytes > 0) {19064 partialBytes = this.blockSize - partialBytes;19065 }19066 // XOR input with output19067 this._partialOutput.clear();19068 for(var i = 0; i < this._ints; ++i) {19069 this._partialOutput.putInt32(input.getInt32() ^ this._outBlock[i]);19070 }19071 if(partialBytes <= 0 || finish) {19072 // handle overflow prior to hashing19073 if(finish) {19074 // get block overflow19075 var overflow = inputLength % this.blockSize;19076 this._cipherLength += overflow;19077 // truncate for hash function19078 this._partialOutput.truncate(this.blockSize - overflow);19079 } else {19080 this._cipherLength += this.blockSize;19081 }19082 // get output block for hashing19083 for(var i = 0; i < this._ints; ++i) {19084 this._outBlock[i] = this._partialOutput.getInt32();19085 }19086 this._partialOutput.read -= this.blockSize;19087 }19088 // skip any previous partial bytes19089 if(this._partialBytes > 0) {19090 this._partialOutput.getBytes(this._partialBytes);19091 }19092 if(partialBytes > 0 && !finish) {19093 // block still incomplete, restore input buffer, get partial output,19094 // and return early19095 input.read -= this.blockSize;19096 output.putBytes(this._partialOutput.getBytes(19097 partialBytes - this._partialBytes));19098 this._partialBytes = partialBytes;19099 return true;19100 }19101 output.putBytes(this._partialOutput.getBytes(19102 inputLength - this._partialBytes));19103 this._partialBytes = 0;19104 }19105 // update hash block S19106 this._s = this.ghash(this._hashSubkey, this._s, this._outBlock);19107 // increment counter (input block)19108 inc32(this._inBlock);19109};19110modes.gcm.prototype.decrypt = function(input, output, finish) {19111 // not enough input to decrypt19112 var inputLength = input.length();19113 if(inputLength < this.blockSize && !(finish && inputLength > 0)) {19114 return true;19115 }19116 // encrypt block (GCM always uses encryption mode)19117 this.cipher.encrypt(this._inBlock, this._outBlock);19118 // increment counter (input block)19119 inc32(this._inBlock);19120 // update hash block S19121 this._hashBlock[0] = input.getInt32();19122 this._hashBlock[1] = input.getInt32();19123 this._hashBlock[2] = input.getInt32();19124 this._hashBlock[3] = input.getInt32();19125 this._s = this.ghash(this._hashSubkey, this._s, this._hashBlock);19126 // XOR hash input with output19127 for(var i = 0; i < this._ints; ++i) {19128 output.putInt32(this._outBlock[i] ^ this._hashBlock[i]);19129 }19130 // increment cipher data length19131 if(inputLength < this.blockSize) {19132 this._cipherLength += inputLength % this.blockSize;19133 } else {19134 this._cipherLength += this.blockSize;19135 }19136};19137modes.gcm.prototype.afterFinish = function(output, options) {19138 var rval = true;19139 // handle overflow19140 if(options.decrypt && options.overflow) {19141 output.truncate(this.blockSize - options.overflow);19142 }19143 // handle authentication tag19144 this.tag = forge.util.createBuffer();19145 // concatenate additional data length with cipher length19146 var lengths = this._aDataLength.concat(from64To32(this._cipherLength * 8));19147 // include lengths in hash19148 this._s = this.ghash(this._hashSubkey, this._s, lengths);19149 // do GCTR(J_0, S)19150 var tag = [];19151 this.cipher.encrypt(this._j0, tag);19152 for(var i = 0; i < this._ints; ++i) {19153 this.tag.putInt32(this._s[i] ^ tag[i]);19154 }19155 // trim tag to length19156 this.tag.truncate(this.tag.length() % (this._tagLength / 8));19157 // check authentication tag19158 if(options.decrypt && this.tag.bytes() !== this._tag) {19159 rval = false;19160 }19161 return rval;19162};19163/**19164 * See NIST SP-800-38D 6.3 (Algorithm 1). This function performs Galois19165 * field multiplication. The field, GF(2^128), is defined by the polynomial:19166 *19167 * x^128 + x^7 + x^2 + x + 119168 *19169 * Which is represented in little-endian binary form as: 11100001 (0xe1). When19170 * the value of a coefficient is 1, a bit is set. The value R, is the19171 * concatenation of this value and 120 zero bits, yielding a 128-bit value19172 * which matches the block size.19173 *19174 * This function will multiply two elements (vectors of bytes), X and Y, in19175 * the field GF(2^128). The result is initialized to zero. For each bit of19176 * X (out of 128), x_i, if x_i is set, then the result is multiplied (XOR'd)19177 * by the current value of Y. For each bit, the value of Y will be raised by19178 * a power of x (multiplied by the polynomial x). This can be achieved by19179 * shifting Y once to the right. If the current value of Y, prior to being19180 * multiplied by x, has 0 as its LSB, then it is a 127th degree polynomial.19181 * Otherwise, we must divide by R after shifting to find the remainder.19182 *19183 * @param x the first block to multiply by the second.19184 * @param y the second block to multiply by the first.19185 *19186 * @return the block result of the multiplication.19187 */19188modes.gcm.prototype.multiply = function(x, y) {19189 var z_i = [0, 0, 0, 0];19190 var v_i = y.slice(0);19191 // calculate Z_128 (block has 128 bits)19192 for(var i = 0; i < 128; ++i) {19193 // if x_i is 0, Z_{i+1} = Z_i (unchanged)19194 // else Z_{i+1} = Z_i ^ V_i19195 // get x_i by finding 32-bit int position, then left shift 1 by remainder19196 var x_i = x[(i / 32) | 0] & (1 << (31 - i % 32));19197 if(x_i) {19198 z_i[0] ^= v_i[0];19199 z_i[1] ^= v_i[1];19200 z_i[2] ^= v_i[2];19201 z_i[3] ^= v_i[3];19202 }19203 // if LSB(V_i) is 1, V_i = V_i >> 119204 // else V_i = (V_i >> 1) ^ R19205 this.pow(v_i, v_i);19206 }19207 return z_i;19208};19209modes.gcm.prototype.pow = function(x, out) {19210 // if LSB(x) is 1, x = x >>> 119211 // else x = (x >>> 1) ^ R19212 var lsb = x[3] & 1;19213 // always do x >>> 1:19214 // starting with the rightmost integer, shift each integer to the right19215 // one bit, pulling in the bit from the integer to the left as its top19216 // most bit (do this for the last 3 integers)19217 for(var i = 3; i > 0; --i) {19218 out[i] = (x[i] >>> 1) | ((x[i - 1] & 1) << 31);19219 }19220 // shift the first integer normally19221 out[0] = x[0] >>> 1;19222 // if lsb was not set, then polynomial had a degree of 127 and doesn't19223 // need to divided; otherwise, XOR with R to find the remainder; we only19224 // need to XOR the first integer since R technically ends w/120 zero bits19225 if(lsb) {19226 out[0] ^= this._R;19227 }19228};19229modes.gcm.prototype.tableMultiply = function(x) {19230 // assumes 4-bit tables are used19231 var z = [0, 0, 0, 0];19232 for(var i = 0; i < 32; ++i) {19233 var idx = (i / 8) | 0;19234 var x_i = (x[idx] >>> ((7 - (i % 8)) * 4)) & 0xF;19235 var ah = this._m[i][x_i];19236 z[0] ^= ah[0];19237 z[1] ^= ah[1];19238 z[2] ^= ah[2];19239 z[3] ^= ah[3];19240 }19241 return z;19242};19243/**19244 * A continuing version of the GHASH algorithm that operates on a single19245 * block. The hash block, last hash value (Ym) and the new block to hash19246 * are given.19247 *19248 * @param h the hash block.19249 * @param y the previous value for Ym, use [0, 0, 0, 0] for a new hash.19250 * @param x the block to hash.19251 *19252 * @return the hashed value (Ym).19253 */19254modes.gcm.prototype.ghash = function(h, y, x) {19255 y[0] ^= x[0];19256 y[1] ^= x[1];19257 y[2] ^= x[2];19258 y[3] ^= x[3];19259 return this.tableMultiply(y);19260 //return this.multiply(y, h);19261};19262/**19263 * Precomputes a table for multiplying against the hash subkey. This19264 * mechanism provides a substantial speed increase over multiplication19265 * performed without a table. The table-based multiplication this table is19266 * for solves X * H by multiplying each component of X by H and then19267 * composing the results together using XOR.19268 *19269 * This function can be used to generate tables with different bit sizes19270 * for the components, however, this implementation assumes there are19271 * 32 components of X (which is a 16 byte vector), therefore each component19272 * takes 4-bits (so the table is constructed with bits=4).19273 *19274 * @param h the hash subkey.19275 * @param bits the bit size for a component.19276 */19277modes.gcm.prototype.generateHashTable = function(h, bits) {19278 // TODO: There are further optimizations that would use only the19279 // first table M_0 (or some variant) along with a remainder table;19280 // this can be explored in the future19281 var multiplier = 8 / bits;19282 var perInt = 4 * multiplier;19283 var size = 16 * multiplier;19284 var m = new Array(size);19285 for(var i = 0; i < size; ++i) {19286 var tmp = [0, 0, 0, 0];19287 var idx = (i / perInt) | 0;19288 var shft = ((perInt - 1 - (i % perInt)) * bits);19289 tmp[idx] = (1 << (bits - 1)) << shft;19290 m[i] = this.generateSubHashTable(this.multiply(tmp, h), bits);19291 }19292 return m;19293};19294/**19295 * Generates a table for multiplying against the hash subkey for one19296 * particular component (out of all possible component values).19297 *19298 * @param mid the pre-multiplied value for the middle key of the table.19299 * @param bits the bit size for a component.19300 */19301modes.gcm.prototype.generateSubHashTable = function(mid, bits) {19302 // compute the table quickly by minimizing the number of19303 // POW operations -- they only need to be performed for powers of 2,19304 // all other entries can be composed from those powers using XOR19305 var size = 1 << bits;19306 var half = size >>> 1;19307 var m = new Array(size);19308 m[half] = mid.slice(0);19309 var i = half >>> 1;19310 while(i > 0) {19311 // raise m0[2 * i] and store in m0[i]19312 this.pow(m[2 * i], m[i] = []);19313 i >>= 1;19314 }19315 i = 2;19316 while(i < half) {19317 for(var j = 1; j < i; ++j) {19318 var m_i = m[i];19319 var m_j = m[j];19320 m[i + j] = [19321 m_i[0] ^ m_j[0],19322 m_i[1] ^ m_j[1],19323 m_i[2] ^ m_j[2],19324 m_i[3] ^ m_j[3]19325 ];19326 }19327 i *= 2;19328 }19329 m[0] = [0, 0, 0, 0];19330 /* Note: We could avoid storing these by doing composition during multiply19331 calculate top half using composition by speed is preferred. */19332 for(i = half + 1; i < size; ++i) {19333 var c = m[i ^ half];19334 m[i] = [mid[0] ^ c[0], mid[1] ^ c[1], mid[2] ^ c[2], mid[3] ^ c[3]];19335 }19336 return m;19337};19338/** Utility functions */19339function transformIV(iv, blockSize) {19340 if(typeof iv === 'string') {19341 // convert iv string into byte buffer19342 iv = forge.util.createBuffer(iv);19343 }19344 if(forge.util.isArray(iv) && iv.length > 4) {19345 // convert iv byte array into byte buffer19346 var tmp = iv;19347 iv = forge.util.createBuffer();19348 for(var i = 0; i < tmp.length; ++i) {19349 iv.putByte(tmp[i]);19350 }19351 }19352 if(iv.length() < blockSize) {19353 throw new Error(19354 'Invalid IV length; got ' + iv.length() +19355 ' bytes and expected ' + blockSize + ' bytes.');19356 }19357 if(!forge.util.isArray(iv)) {19358 // convert iv byte buffer into 32-bit integer array19359 var ints = [];19360 var blocks = blockSize / 4;19361 for(var i = 0; i < blocks; ++i) {19362 ints.push(iv.getInt32());19363 }19364 iv = ints;19365 }19366 return iv;19367}19368function inc32(block) {19369 // increment last 32 bits of block only19370 block[block.length - 1] = (block[block.length - 1] + 1) & 0xFFFFFFFF;19371}19372function from64To32(num) {19373 // convert 64-bit number to two BE Int32s19374 return [(num / 0x100000000) | 0, num & 0xFFFFFFFF];19375}19376/***/ }),19377/***/ 7157:19378/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {19379/**19380 * DES (Data Encryption Standard) implementation.19381 *19382 * This implementation supports DES as well as 3DES-EDE in ECB and CBC mode.19383 * It is based on the BSD-licensed implementation by Paul Tero:19384 *19385 * Paul Tero, July 200119386 * http://www.tero.co.uk/des/19387 *19388 * Optimised for performance with large blocks by19389 * Michael Hayworth, November 200119390 * http://www.netdealing.com19391 *19392 * THIS SOFTWARE IS PROVIDED "AS IS" AND19393 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE19394 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE19395 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE19396 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL19397 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS19398 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)19399 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT19400 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY19401 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF19402 * SUCH DAMAGE.19403 *19404 * @author Stefan Siegl19405 * @author Dave Longley19406 *19407 * Copyright (c) 2012 Stefan Siegl <stesie@brokenpipe.de>19408 * Copyright (c) 2012-2014 Digital Bazaar, Inc.19409 */19410var forge = __nccwpck_require__(9177);19411__nccwpck_require__(7088);19412__nccwpck_require__(873);19413__nccwpck_require__(8339);19414/* DES API */19415module.exports = forge.des = forge.des || {};19416/**19417 * Deprecated. Instead, use:19418 *19419 * var cipher = forge.cipher.createCipher('DES-<mode>', key);19420 * cipher.start({iv: iv});19421 *19422 * Creates an DES cipher object to encrypt data using the given symmetric key.19423 * The output will be stored in the 'output' member of the returned cipher.19424 *19425 * The key and iv may be given as binary-encoded strings of bytes or19426 * byte buffers.19427 *19428 * @param key the symmetric key to use (64 or 192 bits).19429 * @param iv the initialization vector to use.19430 * @param output the buffer to write to, null to create one.19431 * @param mode the cipher mode to use (default: 'CBC' if IV is19432 * given, 'ECB' if null).19433 *19434 * @return the cipher.19435 */19436forge.des.startEncrypting = function(key, iv, output, mode) {19437 var cipher = _createCipher({19438 key: key,19439 output: output,19440 decrypt: false,19441 mode: mode || (iv === null ? 'ECB' : 'CBC')19442 });19443 cipher.start(iv);19444 return cipher;19445};19446/**19447 * Deprecated. Instead, use:19448 *19449 * var cipher = forge.cipher.createCipher('DES-<mode>', key);19450 *19451 * Creates an DES cipher object to encrypt data using the given symmetric key.19452 *19453 * The key may be given as a binary-encoded string of bytes or a byte buffer.19454 *19455 * @param key the symmetric key to use (64 or 192 bits).19456 * @param mode the cipher mode to use (default: 'CBC').19457 *19458 * @return the cipher.19459 */19460forge.des.createEncryptionCipher = function(key, mode) {19461 return _createCipher({19462 key: key,19463 output: null,19464 decrypt: false,19465 mode: mode19466 });19467};19468/**19469 * Deprecated. Instead, use:19470 *19471 * var decipher = forge.cipher.createDecipher('DES-<mode>', key);19472 * decipher.start({iv: iv});19473 *19474 * Creates an DES cipher object to decrypt data using the given symmetric key.19475 * The output will be stored in the 'output' member of the returned cipher.19476 *19477 * The key and iv may be given as binary-encoded strings of bytes or19478 * byte buffers.19479 *19480 * @param key the symmetric key to use (64 or 192 bits).19481 * @param iv the initialization vector to use.19482 * @param output the buffer to write to, null to create one.19483 * @param mode the cipher mode to use (default: 'CBC' if IV is19484 * given, 'ECB' if null).19485 *19486 * @return the cipher.19487 */19488forge.des.startDecrypting = function(key, iv, output, mode) {19489 var cipher = _createCipher({19490 key: key,19491 output: output,19492 decrypt: true,19493 mode: mode || (iv === null ? 'ECB' : 'CBC')19494 });19495 cipher.start(iv);19496 return cipher;19497};19498/**19499 * Deprecated. Instead, use:19500 *19501 * var decipher = forge.cipher.createDecipher('DES-<mode>', key);19502 *19503 * Creates an DES cipher object to decrypt data using the given symmetric key.19504 *19505 * The key may be given as a binary-encoded string of bytes or a byte buffer.19506 *19507 * @param key the symmetric key to use (64 or 192 bits).19508 * @param mode the cipher mode to use (default: 'CBC').19509 *19510 * @return the cipher.19511 */19512forge.des.createDecryptionCipher = function(key, mode) {19513 return _createCipher({19514 key: key,19515 output: null,19516 decrypt: true,19517 mode: mode19518 });19519};19520/**19521 * Creates a new DES cipher algorithm object.19522 *19523 * @param name the name of the algorithm.19524 * @param mode the mode factory function.19525 *19526 * @return the DES algorithm object.19527 */19528forge.des.Algorithm = function(name, mode) {19529 var self = this;19530 self.name = name;19531 self.mode = new mode({19532 blockSize: 8,19533 cipher: {19534 encrypt: function(inBlock, outBlock) {19535 return _updateBlock(self._keys, inBlock, outBlock, false);19536 },19537 decrypt: function(inBlock, outBlock) {19538 return _updateBlock(self._keys, inBlock, outBlock, true);19539 }19540 }19541 });19542 self._init = false;19543};19544/**19545 * Initializes this DES algorithm by expanding its key.19546 *19547 * @param options the options to use.19548 * key the key to use with this algorithm.19549 * decrypt true if the algorithm should be initialized for decryption,19550 * false for encryption.19551 */19552forge.des.Algorithm.prototype.initialize = function(options) {19553 if(this._init) {19554 return;19555 }19556 var key = forge.util.createBuffer(options.key);19557 if(this.name.indexOf('3DES') === 0) {19558 if(key.length() !== 24) {19559 throw new Error('Invalid Triple-DES key size: ' + key.length() * 8);19560 }19561 }19562 // do key expansion to 16 or 48 subkeys (single or triple DES)19563 this._keys = _createKeys(key);19564 this._init = true;19565};19566/** Register DES algorithms **/19567registerAlgorithm('DES-ECB', forge.cipher.modes.ecb);19568registerAlgorithm('DES-CBC', forge.cipher.modes.cbc);19569registerAlgorithm('DES-CFB', forge.cipher.modes.cfb);19570registerAlgorithm('DES-OFB', forge.cipher.modes.ofb);19571registerAlgorithm('DES-CTR', forge.cipher.modes.ctr);19572registerAlgorithm('3DES-ECB', forge.cipher.modes.ecb);19573registerAlgorithm('3DES-CBC', forge.cipher.modes.cbc);19574registerAlgorithm('3DES-CFB', forge.cipher.modes.cfb);19575registerAlgorithm('3DES-OFB', forge.cipher.modes.ofb);19576registerAlgorithm('3DES-CTR', forge.cipher.modes.ctr);19577function registerAlgorithm(name, mode) {19578 var factory = function() {19579 return new forge.des.Algorithm(name, mode);19580 };19581 forge.cipher.registerAlgorithm(name, factory);19582}19583/** DES implementation **/19584var spfunction1 = [0x1010400,0,0x10000,0x1010404,0x1010004,0x10404,0x4,0x10000,0x400,0x1010400,0x1010404,0x400,0x1000404,0x1010004,0x1000000,0x4,0x404,0x1000400,0x1000400,0x10400,0x10400,0x1010000,0x1010000,0x1000404,0x10004,0x1000004,0x1000004,0x10004,0,0x404,0x10404,0x1000000,0x10000,0x1010404,0x4,0x1010000,0x1010400,0x1000000,0x1000000,0x400,0x1010004,0x10000,0x10400,0x1000004,0x400,0x4,0x1000404,0x10404,0x1010404,0x10004,0x1010000,0x1000404,0x1000004,0x404,0x10404,0x1010400,0x404,0x1000400,0x1000400,0,0x10004,0x10400,0,0x1010004];19585var spfunction2 = [-0x7fef7fe0,-0x7fff8000,0x8000,0x108020,0x100000,0x20,-0x7fefffe0,-0x7fff7fe0,-0x7fffffe0,-0x7fef7fe0,-0x7fef8000,-0x80000000,-0x7fff8000,0x100000,0x20,-0x7fefffe0,0x108000,0x100020,-0x7fff7fe0,0,-0x80000000,0x8000,0x108020,-0x7ff00000,0x100020,-0x7fffffe0,0,0x108000,0x8020,-0x7fef8000,-0x7ff00000,0x8020,0,0x108020,-0x7fefffe0,0x100000,-0x7fff7fe0,-0x7ff00000,-0x7fef8000,0x8000,-0x7ff00000,-0x7fff8000,0x20,-0x7fef7fe0,0x108020,0x20,0x8000,-0x80000000,0x8020,-0x7fef8000,0x100000,-0x7fffffe0,0x100020,-0x7fff7fe0,-0x7fffffe0,0x100020,0x108000,0,-0x7fff8000,0x8020,-0x80000000,-0x7fefffe0,-0x7fef7fe0,0x108000];19586var spfunction3 = [0x208,0x8020200,0,0x8020008,0x8000200,0,0x20208,0x8000200,0x20008,0x8000008,0x8000008,0x20000,0x8020208,0x20008,0x8020000,0x208,0x8000000,0x8,0x8020200,0x200,0x20200,0x8020000,0x8020008,0x20208,0x8000208,0x20200,0x20000,0x8000208,0x8,0x8020208,0x200,0x8000000,0x8020200,0x8000000,0x20008,0x208,0x20000,0x8020200,0x8000200,0,0x200,0x20008,0x8020208,0x8000200,0x8000008,0x200,0,0x8020008,0x8000208,0x20000,0x8000000,0x8020208,0x8,0x20208,0x20200,0x8000008,0x8020000,0x8000208,0x208,0x8020000,0x20208,0x8,0x8020008,0x20200];19587var spfunction4 = [0x802001,0x2081,0x2081,0x80,0x802080,0x800081,0x800001,0x2001,0,0x802000,0x802000,0x802081,0x81,0,0x800080,0x800001,0x1,0x2000,0x800000,0x802001,0x80,0x800000,0x2001,0x2080,0x800081,0x1,0x2080,0x800080,0x2000,0x802080,0x802081,0x81,0x800080,0x800001,0x802000,0x802081,0x81,0,0,0x802000,0x2080,0x800080,0x800081,0x1,0x802001,0x2081,0x2081,0x80,0x802081,0x81,0x1,0x2000,0x800001,0x2001,0x802080,0x800081,0x2001,0x2080,0x800000,0x802001,0x80,0x800000,0x2000,0x802080];19588var spfunction5 = [0x100,0x2080100,0x2080000,0x42000100,0x80000,0x100,0x40000000,0x2080000,0x40080100,0x80000,0x2000100,0x40080100,0x42000100,0x42080000,0x80100,0x40000000,0x2000000,0x40080000,0x40080000,0,0x40000100,0x42080100,0x42080100,0x2000100,0x42080000,0x40000100,0,0x42000000,0x2080100,0x2000000,0x42000000,0x80100,0x80000,0x42000100,0x100,0x2000000,0x40000000,0x2080000,0x42000100,0x40080100,0x2000100,0x40000000,0x42080000,0x2080100,0x40080100,0x100,0x2000000,0x42080000,0x42080100,0x80100,0x42000000,0x42080100,0x2080000,0,0x40080000,0x42000000,0x80100,0x2000100,0x40000100,0x80000,0,0x40080000,0x2080100,0x40000100];19589var spfunction6 = [0x20000010,0x20400000,0x4000,0x20404010,0x20400000,0x10,0x20404010,0x400000,0x20004000,0x404010,0x400000,0x20000010,0x400010,0x20004000,0x20000000,0x4010,0,0x400010,0x20004010,0x4000,0x404000,0x20004010,0x10,0x20400010,0x20400010,0,0x404010,0x20404000,0x4010,0x404000,0x20404000,0x20000000,0x20004000,0x10,0x20400010,0x404000,0x20404010,0x400000,0x4010,0x20000010,0x400000,0x20004000,0x20000000,0x4010,0x20000010,0x20404010,0x404000,0x20400000,0x404010,0x20404000,0,0x20400010,0x10,0x4000,0x20400000,0x404010,0x4000,0x400010,0x20004010,0,0x20404000,0x20000000,0x400010,0x20004010];19590var spfunction7 = [0x200000,0x4200002,0x4000802,0,0x800,0x4000802,0x200802,0x4200800,0x4200802,0x200000,0,0x4000002,0x2,0x4000000,0x4200002,0x802,0x4000800,0x200802,0x200002,0x4000800,0x4000002,0x4200000,0x4200800,0x200002,0x4200000,0x800,0x802,0x4200802,0x200800,0x2,0x4000000,0x200800,0x4000000,0x200800,0x200000,0x4000802,0x4000802,0x4200002,0x4200002,0x2,0x200002,0x4000000,0x4000800,0x200000,0x4200800,0x802,0x200802,0x4200800,0x802,0x4000002,0x4200802,0x4200000,0x200800,0,0x2,0x4200802,0,0x200802,0x4200000,0x800,0x4000002,0x4000800,0x800,0x200002];19591var spfunction8 = [0x10001040,0x1000,0x40000,0x10041040,0x10000000,0x10001040,0x40,0x10000000,0x40040,0x10040000,0x10041040,0x41000,0x10041000,0x41040,0x1000,0x40,0x10040000,0x10000040,0x10001000,0x1040,0x41000,0x40040,0x10040040,0x10041000,0x1040,0,0,0x10040040,0x10000040,0x10001000,0x41040,0x40000,0x41040,0x40000,0x10041000,0x1000,0x40,0x10040040,0x1000,0x41040,0x10001000,0x40,0x10000040,0x10040000,0x10040040,0x10000000,0x40000,0x10001040,0,0x10041040,0x40040,0x10000040,0x10040000,0x10001000,0x10001040,0,0x10041040,0x41000,0x41000,0x1040,0x1040,0x40040,0x10000000,0x10041000];19592/**19593 * Create necessary sub keys.19594 *19595 * @param key the 64-bit or 192-bit key.19596 *19597 * @return the expanded keys.19598 */19599function _createKeys(key) {19600 var pc2bytes0 = [0,0x4,0x20000000,0x20000004,0x10000,0x10004,0x20010000,0x20010004,0x200,0x204,0x20000200,0x20000204,0x10200,0x10204,0x20010200,0x20010204],19601 pc2bytes1 = [0,0x1,0x100000,0x100001,0x4000000,0x4000001,0x4100000,0x4100001,0x100,0x101,0x100100,0x100101,0x4000100,0x4000101,0x4100100,0x4100101],19602 pc2bytes2 = [0,0x8,0x800,0x808,0x1000000,0x1000008,0x1000800,0x1000808,0,0x8,0x800,0x808,0x1000000,0x1000008,0x1000800,0x1000808],19603 pc2bytes3 = [0,0x200000,0x8000000,0x8200000,0x2000,0x202000,0x8002000,0x8202000,0x20000,0x220000,0x8020000,0x8220000,0x22000,0x222000,0x8022000,0x8222000],19604 pc2bytes4 = [0,0x40000,0x10,0x40010,0,0x40000,0x10,0x40010,0x1000,0x41000,0x1010,0x41010,0x1000,0x41000,0x1010,0x41010],19605 pc2bytes5 = [0,0x400,0x20,0x420,0,0x400,0x20,0x420,0x2000000,0x2000400,0x2000020,0x2000420,0x2000000,0x2000400,0x2000020,0x2000420],19606 pc2bytes6 = [0,0x10000000,0x80000,0x10080000,0x2,0x10000002,0x80002,0x10080002,0,0x10000000,0x80000,0x10080000,0x2,0x10000002,0x80002,0x10080002],19607 pc2bytes7 = [0,0x10000,0x800,0x10800,0x20000000,0x20010000,0x20000800,0x20010800,0x20000,0x30000,0x20800,0x30800,0x20020000,0x20030000,0x20020800,0x20030800],19608 pc2bytes8 = [0,0x40000,0,0x40000,0x2,0x40002,0x2,0x40002,0x2000000,0x2040000,0x2000000,0x2040000,0x2000002,0x2040002,0x2000002,0x2040002],19609 pc2bytes9 = [0,0x10000000,0x8,0x10000008,0,0x10000000,0x8,0x10000008,0x400,0x10000400,0x408,0x10000408,0x400,0x10000400,0x408,0x10000408],19610 pc2bytes10 = [0,0x20,0,0x20,0x100000,0x100020,0x100000,0x100020,0x2000,0x2020,0x2000,0x2020,0x102000,0x102020,0x102000,0x102020],19611 pc2bytes11 = [0,0x1000000,0x200,0x1000200,0x200000,0x1200000,0x200200,0x1200200,0x4000000,0x5000000,0x4000200,0x5000200,0x4200000,0x5200000,0x4200200,0x5200200],19612 pc2bytes12 = [0,0x1000,0x8000000,0x8001000,0x80000,0x81000,0x8080000,0x8081000,0x10,0x1010,0x8000010,0x8001010,0x80010,0x81010,0x8080010,0x8081010],19613 pc2bytes13 = [0,0x4,0x100,0x104,0,0x4,0x100,0x104,0x1,0x5,0x101,0x105,0x1,0x5,0x101,0x105];19614 // how many iterations (1 for des, 3 for triple des)19615 // changed by Paul 16/6/2007 to use Triple DES for 9+ byte keys19616 var iterations = key.length() > 8 ? 3 : 1;19617 // stores the return keys19618 var keys = [];19619 // now define the left shifts which need to be done19620 var shifts = [0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0];19621 var n = 0, tmp;19622 for(var j = 0; j < iterations; j++) {19623 var left = key.getInt32();19624 var right = key.getInt32();19625 tmp = ((left >>> 4) ^ right) & 0x0f0f0f0f;19626 right ^= tmp;19627 left ^= (tmp << 4);19628 tmp = ((right >>> -16) ^ left) & 0x0000ffff;19629 left ^= tmp;19630 right ^= (tmp << -16);19631 tmp = ((left >>> 2) ^ right) & 0x33333333;19632 right ^= tmp;19633 left ^= (tmp << 2);19634 tmp = ((right >>> -16) ^ left) & 0x0000ffff;19635 left ^= tmp;19636 right ^= (tmp << -16);19637 tmp = ((left >>> 1) ^ right) & 0x55555555;19638 right ^= tmp;19639 left ^= (tmp << 1);19640 tmp = ((right >>> 8) ^ left) & 0x00ff00ff;19641 left ^= tmp;19642 right ^= (tmp << 8);19643 tmp = ((left >>> 1) ^ right) & 0x55555555;19644 right ^= tmp;19645 left ^= (tmp << 1);19646 // right needs to be shifted and OR'd with last four bits of left19647 tmp = (left << 8) | ((right >>> 20) & 0x000000f0);19648 // left needs to be put upside down19649 left = ((right << 24) | ((right << 8) & 0xff0000) |19650 ((right >>> 8) & 0xff00) | ((right >>> 24) & 0xf0));19651 right = tmp;19652 // now go through and perform these shifts on the left and right keys19653 for(var i = 0; i < shifts.length; ++i) {19654 //shift the keys either one or two bits to the left19655 if(shifts[i]) {19656 left = (left << 2) | (left >>> 26);19657 right = (right << 2) | (right >>> 26);19658 } else {19659 left = (left << 1) | (left >>> 27);19660 right = (right << 1) | (right >>> 27);19661 }19662 left &= -0xf;19663 right &= -0xf;19664 // now apply PC-2, in such a way that E is easier when encrypting or19665 // decrypting this conversion will look like PC-2 except only the last 619666 // bits of each byte are used rather than 48 consecutive bits and the19667 // order of lines will be according to how the S selection functions will19668 // be applied: S2, S4, S6, S8, S1, S3, S5, S719669 var lefttmp = (19670 pc2bytes0[left >>> 28] | pc2bytes1[(left >>> 24) & 0xf] |19671 pc2bytes2[(left >>> 20) & 0xf] | pc2bytes3[(left >>> 16) & 0xf] |19672 pc2bytes4[(left >>> 12) & 0xf] | pc2bytes5[(left >>> 8) & 0xf] |19673 pc2bytes6[(left >>> 4) & 0xf]);19674 var righttmp = (19675 pc2bytes7[right >>> 28] | pc2bytes8[(right >>> 24) & 0xf] |19676 pc2bytes9[(right >>> 20) & 0xf] | pc2bytes10[(right >>> 16) & 0xf] |19677 pc2bytes11[(right >>> 12) & 0xf] | pc2bytes12[(right >>> 8) & 0xf] |19678 pc2bytes13[(right >>> 4) & 0xf]);19679 tmp = ((righttmp >>> 16) ^ lefttmp) & 0x0000ffff;19680 keys[n++] = lefttmp ^ tmp;19681 keys[n++] = righttmp ^ (tmp << 16);19682 }19683 }19684 return keys;19685}19686/**19687 * Updates a single block (1 byte) using DES. The update will either19688 * encrypt or decrypt the block.19689 *19690 * @param keys the expanded keys.19691 * @param input the input block (an array of 32-bit words).19692 * @param output the updated output block.19693 * @param decrypt true to decrypt the block, false to encrypt it.19694 */19695function _updateBlock(keys, input, output, decrypt) {19696 // set up loops for single or triple DES19697 var iterations = keys.length === 32 ? 3 : 9;19698 var looping;19699 if(iterations === 3) {19700 looping = decrypt ? [30, -2, -2] : [0, 32, 2];19701 } else {19702 looping = (decrypt ?19703 [94, 62, -2, 32, 64, 2, 30, -2, -2] :19704 [0, 32, 2, 62, 30, -2, 64, 96, 2]);19705 }19706 var tmp;19707 var left = input[0];19708 var right = input[1];19709 // first each 64 bit chunk of the message must be permuted according to IP19710 tmp = ((left >>> 4) ^ right) & 0x0f0f0f0f;19711 right ^= tmp;19712 left ^= (tmp << 4);19713 tmp = ((left >>> 16) ^ right) & 0x0000ffff;19714 right ^= tmp;19715 left ^= (tmp << 16);19716 tmp = ((right >>> 2) ^ left) & 0x33333333;19717 left ^= tmp;19718 right ^= (tmp << 2);19719 tmp = ((right >>> 8) ^ left) & 0x00ff00ff;19720 left ^= tmp;19721 right ^= (tmp << 8);19722 tmp = ((left >>> 1) ^ right) & 0x55555555;19723 right ^= tmp;19724 left ^= (tmp << 1);19725 // rotate left 1 bit19726 left = ((left << 1) | (left >>> 31));19727 right = ((right << 1) | (right >>> 31));19728 for(var j = 0; j < iterations; j += 3) {19729 var endloop = looping[j + 1];19730 var loopinc = looping[j + 2];19731 // now go through and perform the encryption or decryption19732 for(var i = looping[j]; i != endloop; i += loopinc) {19733 var right1 = right ^ keys[i];19734 var right2 = ((right >>> 4) | (right << 28)) ^ keys[i + 1];19735 // passing these bytes through the S selection functions19736 tmp = left;19737 left = right;19738 right = tmp ^ (19739 spfunction2[(right1 >>> 24) & 0x3f] |19740 spfunction4[(right1 >>> 16) & 0x3f] |19741 spfunction6[(right1 >>> 8) & 0x3f] |19742 spfunction8[right1 & 0x3f] |19743 spfunction1[(right2 >>> 24) & 0x3f] |19744 spfunction3[(right2 >>> 16) & 0x3f] |19745 spfunction5[(right2 >>> 8) & 0x3f] |19746 spfunction7[right2 & 0x3f]);19747 }19748 // unreverse left and right19749 tmp = left;19750 left = right;19751 right = tmp;19752 }19753 // rotate right 1 bit19754 left = ((left >>> 1) | (left << 31));19755 right = ((right >>> 1) | (right << 31));19756 // now perform IP-1, which is IP in the opposite direction19757 tmp = ((left >>> 1) ^ right) & 0x55555555;19758 right ^= tmp;19759 left ^= (tmp << 1);19760 tmp = ((right >>> 8) ^ left) & 0x00ff00ff;19761 left ^= tmp;19762 right ^= (tmp << 8);19763 tmp = ((right >>> 2) ^ left) & 0x33333333;19764 left ^= tmp;19765 right ^= (tmp << 2);19766 tmp = ((left >>> 16) ^ right) & 0x0000ffff;19767 right ^= tmp;19768 left ^= (tmp << 16);19769 tmp = ((left >>> 4) ^ right) & 0x0f0f0f0f;19770 right ^= tmp;19771 left ^= (tmp << 4);19772 output[0] = left;19773 output[1] = right;19774}19775/**19776 * Deprecated. Instead, use:19777 *19778 * forge.cipher.createCipher('DES-<mode>', key);19779 * forge.cipher.createDecipher('DES-<mode>', key);19780 *19781 * Creates a deprecated DES cipher object. This object's mode will default to19782 * CBC (cipher-block-chaining).19783 *19784 * The key may be given as a binary-encoded string of bytes or a byte buffer.19785 *19786 * @param options the options to use.19787 * key the symmetric key to use (64 or 192 bits).19788 * output the buffer to write to.19789 * decrypt true for decryption, false for encryption.19790 * mode the cipher mode to use (default: 'CBC').19791 *19792 * @return the cipher.19793 */19794function _createCipher(options) {19795 options = options || {};19796 var mode = (options.mode || 'CBC').toUpperCase();19797 var algorithm = 'DES-' + mode;19798 var cipher;19799 if(options.decrypt) {19800 cipher = forge.cipher.createDecipher(algorithm, options.key);19801 } else {19802 cipher = forge.cipher.createCipher(algorithm, options.key);19803 }19804 // backwards compatible start API19805 var start = cipher.start;19806 cipher.start = function(iv, options) {19807 // backwards compatibility: support second arg as output buffer19808 var output = null;19809 if(options instanceof forge.util.ByteBuffer) {19810 output = options;19811 options = {};19812 }19813 options = options || {};19814 options.output = output;19815 options.iv = iv;19816 start.call(cipher, options);19817 };19818 return cipher;19819}19820/***/ }),19821/***/ 0:19822/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {19823/**19824 * JavaScript implementation of Ed25519.19825 *19826 * Copyright (c) 2017-2019 Digital Bazaar, Inc.19827 *19828 * This implementation is based on the most excellent TweetNaCl which is19829 * in the public domain. Many thanks to its contributors:19830 *19831 * https://github.com/dchest/tweetnacl-js19832 */19833var forge = __nccwpck_require__(9177);19834__nccwpck_require__(7052);19835__nccwpck_require__(7821);19836__nccwpck_require__(9542);19837__nccwpck_require__(8339);19838var asn1Validator = __nccwpck_require__(9414);19839var publicKeyValidator = asn1Validator.publicKeyValidator;19840var privateKeyValidator = asn1Validator.privateKeyValidator;19841if(typeof BigInteger === 'undefined') {19842 var BigInteger = forge.jsbn.BigInteger;19843}19844var ByteBuffer = forge.util.ByteBuffer;19845var NativeBuffer = typeof Buffer === 'undefined' ? Uint8Array : Buffer;19846/*19847 * Ed25519 algorithms, see RFC 8032:19848 * https://tools.ietf.org/html/rfc803219849 */19850forge.pki = forge.pki || {};19851module.exports = forge.pki.ed25519 = forge.ed25519 = forge.ed25519 || {};19852var ed25519 = forge.ed25519;19853ed25519.constants = {};19854ed25519.constants.PUBLIC_KEY_BYTE_LENGTH = 32;19855ed25519.constants.PRIVATE_KEY_BYTE_LENGTH = 64;19856ed25519.constants.SEED_BYTE_LENGTH = 32;19857ed25519.constants.SIGN_BYTE_LENGTH = 64;19858ed25519.constants.HASH_BYTE_LENGTH = 64;19859ed25519.generateKeyPair = function(options) {19860 options = options || {};19861 var seed = options.seed;19862 if(seed === undefined) {19863 // generate seed19864 seed = forge.random.getBytesSync(ed25519.constants.SEED_BYTE_LENGTH);19865 } else if(typeof seed === 'string') {19866 if(seed.length !== ed25519.constants.SEED_BYTE_LENGTH) {19867 throw new TypeError(19868 '"seed" must be ' + ed25519.constants.SEED_BYTE_LENGTH +19869 ' bytes in length.');19870 }19871 } else if(!(seed instanceof Uint8Array)) {19872 throw new TypeError(19873 '"seed" must be a node.js Buffer, Uint8Array, or a binary string.');19874 }19875 seed = messageToNativeBuffer({message: seed, encoding: 'binary'});19876 var pk = new NativeBuffer(ed25519.constants.PUBLIC_KEY_BYTE_LENGTH);19877 var sk = new NativeBuffer(ed25519.constants.PRIVATE_KEY_BYTE_LENGTH);19878 for(var i = 0; i < 32; ++i) {19879 sk[i] = seed[i];19880 }19881 crypto_sign_keypair(pk, sk);19882 return {publicKey: pk, privateKey: sk};19883};19884/**19885 * Converts a private key from a RFC8410 ASN.1 encoding.19886 *19887 * @param obj - The asn1 representation of a private key.19888 *19889 * @returns {Object} keyInfo - The key information.19890 * @returns {Buffer|Uint8Array} keyInfo.privateKeyBytes - 32 private key bytes.19891 */19892ed25519.privateKeyFromAsn1 = function(obj) {19893 var capture = {};19894 var errors = [];19895 var valid = forge.asn1.validate(obj, privateKeyValidator, capture, errors);19896 if(!valid) {19897 var error = new Error('Invalid Key.');19898 error.errors = errors;19899 throw error;19900 }19901 var oid = forge.asn1.derToOid(capture.privateKeyOid);19902 var ed25519Oid = forge.oids.EdDSA25519;19903 if(oid !== ed25519Oid) {19904 throw new Error('Invalid OID "' + oid + '"; OID must be "' +19905 ed25519Oid + '".');19906 }19907 var privateKey = capture.privateKey;19908 // manually extract the private key bytes from nested octet string, see FIXME:19909 // https://github.com/digitalbazaar/forge/blob/master/lib/asn1.js#L54219910 var privateKeyBytes = messageToNativeBuffer({19911 message: forge.asn1.fromDer(privateKey).value,19912 encoding: 'binary'19913 });19914 // TODO: RFC8410 specifies a format for encoding the public key bytes along19915 // with the private key bytes. `publicKeyBytes` can be returned in the19916 // future. https://tools.ietf.org/html/rfc8410#section-10.319917 return {privateKeyBytes: privateKeyBytes};19918};19919/**19920 * Converts a public key from a RFC8410 ASN.1 encoding.19921 *19922 * @param obj - The asn1 representation of a public key.19923 *19924 * @return {Buffer|Uint8Array} - 32 public key bytes.19925 */19926ed25519.publicKeyFromAsn1 = function(obj) {19927 // get SubjectPublicKeyInfo19928 var capture = {};19929 var errors = [];19930 var valid = forge.asn1.validate(obj, publicKeyValidator, capture, errors);19931 if(!valid) {19932 var error = new Error('Invalid Key.');19933 error.errors = errors;19934 throw error;19935 }19936 var oid = forge.asn1.derToOid(capture.publicKeyOid);19937 var ed25519Oid = forge.oids.EdDSA25519;19938 if(oid !== ed25519Oid) {19939 throw new Error('Invalid OID "' + oid + '"; OID must be "' +19940 ed25519Oid + '".');19941 }19942 var publicKeyBytes = capture.ed25519PublicKey;19943 if(publicKeyBytes.length !== ed25519.constants.PUBLIC_KEY_BYTE_LENGTH) {19944 throw new Error('Key length is invalid.');19945 }19946 return messageToNativeBuffer({19947 message: publicKeyBytes,19948 encoding: 'binary'19949 });19950};19951ed25519.publicKeyFromPrivateKey = function(options) {19952 options = options || {};19953 var privateKey = messageToNativeBuffer({19954 message: options.privateKey, encoding: 'binary'19955 });19956 if(privateKey.length !== ed25519.constants.PRIVATE_KEY_BYTE_LENGTH) {19957 throw new TypeError(19958 '"options.privateKey" must have a byte length of ' +19959 ed25519.constants.PRIVATE_KEY_BYTE_LENGTH);19960 }19961 var pk = new NativeBuffer(ed25519.constants.PUBLIC_KEY_BYTE_LENGTH);19962 for(var i = 0; i < pk.length; ++i) {19963 pk[i] = privateKey[32 + i];19964 }19965 return pk;19966};19967ed25519.sign = function(options) {19968 options = options || {};19969 var msg = messageToNativeBuffer(options);19970 var privateKey = messageToNativeBuffer({19971 message: options.privateKey,19972 encoding: 'binary'19973 });19974 if(privateKey.length === ed25519.constants.SEED_BYTE_LENGTH) {19975 var keyPair = ed25519.generateKeyPair({seed: privateKey});19976 privateKey = keyPair.privateKey;19977 } else if(privateKey.length !== ed25519.constants.PRIVATE_KEY_BYTE_LENGTH) {19978 throw new TypeError(19979 '"options.privateKey" must have a byte length of ' +19980 ed25519.constants.SEED_BYTE_LENGTH + ' or ' +19981 ed25519.constants.PRIVATE_KEY_BYTE_LENGTH);19982 }19983 var signedMsg = new NativeBuffer(19984 ed25519.constants.SIGN_BYTE_LENGTH + msg.length);19985 crypto_sign(signedMsg, msg, msg.length, privateKey);19986 var sig = new NativeBuffer(ed25519.constants.SIGN_BYTE_LENGTH);19987 for(var i = 0; i < sig.length; ++i) {19988 sig[i] = signedMsg[i];19989 }19990 return sig;19991};19992ed25519.verify = function(options) {19993 options = options || {};19994 var msg = messageToNativeBuffer(options);19995 if(options.signature === undefined) {19996 throw new TypeError(19997 '"options.signature" must be a node.js Buffer, a Uint8Array, a forge ' +19998 'ByteBuffer, or a binary string.');19999 }20000 var sig = messageToNativeBuffer({20001 message: options.signature,20002 encoding: 'binary'20003 });20004 if(sig.length !== ed25519.constants.SIGN_BYTE_LENGTH) {20005 throw new TypeError(20006 '"options.signature" must have a byte length of ' +20007 ed25519.constants.SIGN_BYTE_LENGTH);20008 }20009 var publicKey = messageToNativeBuffer({20010 message: options.publicKey,20011 encoding: 'binary'20012 });20013 if(publicKey.length !== ed25519.constants.PUBLIC_KEY_BYTE_LENGTH) {20014 throw new TypeError(20015 '"options.publicKey" must have a byte length of ' +20016 ed25519.constants.PUBLIC_KEY_BYTE_LENGTH);20017 }20018 var sm = new NativeBuffer(ed25519.constants.SIGN_BYTE_LENGTH + msg.length);20019 var m = new NativeBuffer(ed25519.constants.SIGN_BYTE_LENGTH + msg.length);20020 var i;20021 for(i = 0; i < ed25519.constants.SIGN_BYTE_LENGTH; ++i) {20022 sm[i] = sig[i];20023 }20024 for(i = 0; i < msg.length; ++i) {20025 sm[i + ed25519.constants.SIGN_BYTE_LENGTH] = msg[i];20026 }20027 return (crypto_sign_open(m, sm, sm.length, publicKey) >= 0);20028};20029function messageToNativeBuffer(options) {20030 var message = options.message;20031 if(message instanceof Uint8Array || message instanceof NativeBuffer) {20032 return message;20033 }20034 var encoding = options.encoding;20035 if(message === undefined) {20036 if(options.md) {20037 // TODO: more rigorous validation that `md` is a MessageDigest20038 message = options.md.digest().getBytes();20039 encoding = 'binary';20040 } else {20041 throw new TypeError('"options.message" or "options.md" not specified.');20042 }20043 }20044 if(typeof message === 'string' && !encoding) {20045 throw new TypeError('"options.encoding" must be "binary" or "utf8".');20046 }20047 if(typeof message === 'string') {20048 if(typeof Buffer !== 'undefined') {20049 return Buffer.from(message, encoding);20050 }20051 message = new ByteBuffer(message, encoding);20052 } else if(!(message instanceof ByteBuffer)) {20053 throw new TypeError(20054 '"options.message" must be a node.js Buffer, a Uint8Array, a forge ' +20055 'ByteBuffer, or a string with "options.encoding" specifying its ' +20056 'encoding.');20057 }20058 // convert to native buffer20059 var buffer = new NativeBuffer(message.length());20060 for(var i = 0; i < buffer.length; ++i) {20061 buffer[i] = message.at(i);20062 }20063 return buffer;20064}20065var gf0 = gf();20066var gf1 = gf([1]);20067var D = gf([20068 0x78a3, 0x1359, 0x4dca, 0x75eb, 0xd8ab, 0x4141, 0x0a4d, 0x0070,20069 0xe898, 0x7779, 0x4079, 0x8cc7, 0xfe73, 0x2b6f, 0x6cee, 0x5203]);20070var D2 = gf([20071 0xf159, 0x26b2, 0x9b94, 0xebd6, 0xb156, 0x8283, 0x149a, 0x00e0,20072 0xd130, 0xeef3, 0x80f2, 0x198e, 0xfce7, 0x56df, 0xd9dc, 0x2406]);20073var X = gf([20074 0xd51a, 0x8f25, 0x2d60, 0xc956, 0xa7b2, 0x9525, 0xc760, 0x692c,20075 0xdc5c, 0xfdd6, 0xe231, 0xc0a4, 0x53fe, 0xcd6e, 0x36d3, 0x2169]);20076var Y = gf([20077 0x6658, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666,20078 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666]);20079var L = new Float64Array([20080 0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58,20081 0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9, 0xde, 0x14,20082 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x10]);20083var I = gf([20084 0xa0b0, 0x4a0e, 0x1b27, 0xc4ee, 0xe478, 0xad2f, 0x1806, 0x2f43,20085 0xd7a7, 0x3dfb, 0x0099, 0x2b4d, 0xdf0b, 0x4fc1, 0x2480, 0x2b83]);20086// TODO: update forge buffer implementation to use `Buffer` or `Uint8Array`,20087// whichever is available, to improve performance20088function sha512(msg, msgLen) {20089 // Note: `out` and `msg` are NativeBuffer20090 var md = forge.md.sha512.create();20091 var buffer = new ByteBuffer(msg);20092 md.update(buffer.getBytes(msgLen), 'binary');20093 var hash = md.digest().getBytes();20094 if(typeof Buffer !== 'undefined') {20095 return Buffer.from(hash, 'binary');20096 }20097 var out = new NativeBuffer(ed25519.constants.HASH_BYTE_LENGTH);20098 for(var i = 0; i < 64; ++i) {20099 out[i] = hash.charCodeAt(i);20100 }20101 return out;20102}20103function crypto_sign_keypair(pk, sk) {20104 var p = [gf(), gf(), gf(), gf()];20105 var i;20106 var d = sha512(sk, 32);20107 d[0] &= 248;20108 d[31] &= 127;20109 d[31] |= 64;20110 scalarbase(p, d);20111 pack(pk, p);20112 for(i = 0; i < 32; ++i) {20113 sk[i + 32] = pk[i];20114 }20115 return 0;20116}20117// Note: difference from C - smlen returned, not passed as argument.20118function crypto_sign(sm, m, n, sk) {20119 var i, j, x = new Float64Array(64);20120 var p = [gf(), gf(), gf(), gf()];20121 var d = sha512(sk, 32);20122 d[0] &= 248;20123 d[31] &= 127;20124 d[31] |= 64;20125 var smlen = n + 64;20126 for(i = 0; i < n; ++i) {20127 sm[64 + i] = m[i];20128 }20129 for(i = 0; i < 32; ++i) {20130 sm[32 + i] = d[32 + i];20131 }20132 var r = sha512(sm.subarray(32), n + 32);20133 reduce(r);20134 scalarbase(p, r);20135 pack(sm, p);20136 for(i = 32; i < 64; ++i) {20137 sm[i] = sk[i];20138 }20139 var h = sha512(sm, n + 64);20140 reduce(h);20141 for(i = 32; i < 64; ++i) {20142 x[i] = 0;20143 }20144 for(i = 0; i < 32; ++i) {20145 x[i] = r[i];20146 }20147 for(i = 0; i < 32; ++i) {20148 for(j = 0; j < 32; j++) {20149 x[i + j] += h[i] * d[j];20150 }20151 }20152 modL(sm.subarray(32), x);20153 return smlen;20154}20155function crypto_sign_open(m, sm, n, pk) {20156 var i, mlen;20157 var t = new NativeBuffer(32);20158 var p = [gf(), gf(), gf(), gf()],20159 q = [gf(), gf(), gf(), gf()];20160 mlen = -1;20161 if(n < 64) {20162 return -1;20163 }20164 if(unpackneg(q, pk)) {20165 return -1;20166 }20167 for(i = 0; i < n; ++i) {20168 m[i] = sm[i];20169 }20170 for(i = 0; i < 32; ++i) {20171 m[i + 32] = pk[i];20172 }20173 var h = sha512(m, n);20174 reduce(h);20175 scalarmult(p, q, h);20176 scalarbase(q, sm.subarray(32));20177 add(p, q);20178 pack(t, p);20179 n -= 64;20180 if(crypto_verify_32(sm, 0, t, 0)) {20181 for(i = 0; i < n; ++i) {20182 m[i] = 0;20183 }20184 return -1;20185 }20186 for(i = 0; i < n; ++i) {20187 m[i] = sm[i + 64];20188 }20189 mlen = n;20190 return mlen;20191}20192function modL(r, x) {20193 var carry, i, j, k;20194 for(i = 63; i >= 32; --i) {20195 carry = 0;20196 for(j = i - 32, k = i - 12; j < k; ++j) {20197 x[j] += carry - 16 * x[i] * L[j - (i - 32)];20198 carry = (x[j] + 128) >> 8;20199 x[j] -= carry * 256;20200 }20201 x[j] += carry;20202 x[i] = 0;20203 }20204 carry = 0;20205 for(j = 0; j < 32; ++j) {20206 x[j] += carry - (x[31] >> 4) * L[j];20207 carry = x[j] >> 8;20208 x[j] &= 255;20209 }20210 for(j = 0; j < 32; ++j) {20211 x[j] -= carry * L[j];20212 }20213 for(i = 0; i < 32; ++i) {20214 x[i + 1] += x[i] >> 8;20215 r[i] = x[i] & 255;20216 }20217}20218function reduce(r) {20219 var x = new Float64Array(64);20220 for(var i = 0; i < 64; ++i) {20221 x[i] = r[i];20222 r[i] = 0;20223 }20224 modL(r, x);20225}20226function add(p, q) {20227 var a = gf(), b = gf(), c = gf(),20228 d = gf(), e = gf(), f = gf(),20229 g = gf(), h = gf(), t = gf();20230 Z(a, p[1], p[0]);20231 Z(t, q[1], q[0]);20232 M(a, a, t);20233 A(b, p[0], p[1]);20234 A(t, q[0], q[1]);20235 M(b, b, t);20236 M(c, p[3], q[3]);20237 M(c, c, D2);20238 M(d, p[2], q[2]);20239 A(d, d, d);20240 Z(e, b, a);20241 Z(f, d, c);20242 A(g, d, c);20243 A(h, b, a);20244 M(p[0], e, f);20245 M(p[1], h, g);20246 M(p[2], g, f);20247 M(p[3], e, h);20248}20249function cswap(p, q, b) {20250 for(var i = 0; i < 4; ++i) {20251 sel25519(p[i], q[i], b);20252 }20253}20254function pack(r, p) {20255 var tx = gf(), ty = gf(), zi = gf();20256 inv25519(zi, p[2]);20257 M(tx, p[0], zi);20258 M(ty, p[1], zi);20259 pack25519(r, ty);20260 r[31] ^= par25519(tx) << 7;20261}20262function pack25519(o, n) {20263 var i, j, b;20264 var m = gf(), t = gf();20265 for(i = 0; i < 16; ++i) {20266 t[i] = n[i];20267 }20268 car25519(t);20269 car25519(t);20270 car25519(t);20271 for(j = 0; j < 2; ++j) {20272 m[0] = t[0] - 0xffed;20273 for(i = 1; i < 15; ++i) {20274 m[i] = t[i] - 0xffff - ((m[i - 1] >> 16) & 1);20275 m[i-1] &= 0xffff;20276 }20277 m[15] = t[15] - 0x7fff - ((m[14] >> 16) & 1);20278 b = (m[15] >> 16) & 1;20279 m[14] &= 0xffff;20280 sel25519(t, m, 1 - b);20281 }20282 for (i = 0; i < 16; i++) {20283 o[2 * i] = t[i] & 0xff;20284 o[2 * i + 1] = t[i] >> 8;20285 }20286}20287function unpackneg(r, p) {20288 var t = gf(), chk = gf(), num = gf(),20289 den = gf(), den2 = gf(), den4 = gf(),20290 den6 = gf();20291 set25519(r[2], gf1);20292 unpack25519(r[1], p);20293 S(num, r[1]);20294 M(den, num, D);20295 Z(num, num, r[2]);20296 A(den, r[2], den);20297 S(den2, den);20298 S(den4, den2);20299 M(den6, den4, den2);20300 M(t, den6, num);20301 M(t, t, den);20302 pow2523(t, t);20303 M(t, t, num);20304 M(t, t, den);20305 M(t, t, den);20306 M(r[0], t, den);20307 S(chk, r[0]);20308 M(chk, chk, den);20309 if(neq25519(chk, num)) {20310 M(r[0], r[0], I);20311 }20312 S(chk, r[0]);20313 M(chk, chk, den);20314 if(neq25519(chk, num)) {20315 return -1;20316 }20317 if(par25519(r[0]) === (p[31] >> 7)) {20318 Z(r[0], gf0, r[0]);20319 }20320 M(r[3], r[0], r[1]);20321 return 0;20322}20323function unpack25519(o, n) {20324 var i;20325 for(i = 0; i < 16; ++i) {20326 o[i] = n[2 * i] + (n[2 * i + 1] << 8);20327 }20328 o[15] &= 0x7fff;20329}20330function pow2523(o, i) {20331 var c = gf();20332 var a;20333 for(a = 0; a < 16; ++a) {20334 c[a] = i[a];20335 }20336 for(a = 250; a >= 0; --a) {20337 S(c, c);20338 if(a !== 1) {20339 M(c, c, i);20340 }20341 }20342 for(a = 0; a < 16; ++a) {20343 o[a] = c[a];20344 }20345}20346function neq25519(a, b) {20347 var c = new NativeBuffer(32);20348 var d = new NativeBuffer(32);20349 pack25519(c, a);20350 pack25519(d, b);20351 return crypto_verify_32(c, 0, d, 0);20352}20353function crypto_verify_32(x, xi, y, yi) {20354 return vn(x, xi, y, yi, 32);20355}20356function vn(x, xi, y, yi, n) {20357 var i, d = 0;20358 for(i = 0; i < n; ++i) {20359 d |= x[xi + i] ^ y[yi + i];20360 }20361 return (1 & ((d - 1) >>> 8)) - 1;20362}20363function par25519(a) {20364 var d = new NativeBuffer(32);20365 pack25519(d, a);20366 return d[0] & 1;20367}20368function scalarmult(p, q, s) {20369 var b, i;20370 set25519(p[0], gf0);20371 set25519(p[1], gf1);20372 set25519(p[2], gf1);20373 set25519(p[3], gf0);20374 for(i = 255; i >= 0; --i) {20375 b = (s[(i / 8)|0] >> (i & 7)) & 1;20376 cswap(p, q, b);20377 add(q, p);20378 add(p, p);20379 cswap(p, q, b);20380 }20381}20382function scalarbase(p, s) {20383 var q = [gf(), gf(), gf(), gf()];20384 set25519(q[0], X);20385 set25519(q[1], Y);20386 set25519(q[2], gf1);20387 M(q[3], X, Y);20388 scalarmult(p, q, s);20389}20390function set25519(r, a) {20391 var i;20392 for(i = 0; i < 16; i++) {20393 r[i] = a[i] | 0;20394 }20395}20396function inv25519(o, i) {20397 var c = gf();20398 var a;20399 for(a = 0; a < 16; ++a) {20400 c[a] = i[a];20401 }20402 for(a = 253; a >= 0; --a) {20403 S(c, c);20404 if(a !== 2 && a !== 4) {20405 M(c, c, i);20406 }20407 }20408 for(a = 0; a < 16; ++a) {20409 o[a] = c[a];20410 }20411}20412function car25519(o) {20413 var i, v, c = 1;20414 for(i = 0; i < 16; ++i) {20415 v = o[i] + c + 65535;20416 c = Math.floor(v / 65536);20417 o[i] = v - c * 65536;20418 }20419 o[0] += c - 1 + 37 * (c - 1);20420}20421function sel25519(p, q, b) {20422 var t, c = ~(b - 1);20423 for(var i = 0; i < 16; ++i) {20424 t = c & (p[i] ^ q[i]);20425 p[i] ^= t;20426 q[i] ^= t;20427 }20428}20429function gf(init) {20430 var i, r = new Float64Array(16);20431 if(init) {20432 for(i = 0; i < init.length; ++i) {20433 r[i] = init[i];20434 }20435 }20436 return r;20437}20438function A(o, a, b) {20439 for(var i = 0; i < 16; ++i) {20440 o[i] = a[i] + b[i];20441 }20442}20443function Z(o, a, b) {20444 for(var i = 0; i < 16; ++i) {20445 o[i] = a[i] - b[i];20446 }20447}20448function S(o, a) {20449 M(o, a, a);20450}20451function M(o, a, b) {20452 var v, c,20453 t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0,20454 t8 = 0, t9 = 0, t10 = 0, t11 = 0, t12 = 0, t13 = 0, t14 = 0, t15 = 0,20455 t16 = 0, t17 = 0, t18 = 0, t19 = 0, t20 = 0, t21 = 0, t22 = 0, t23 = 0,20456 t24 = 0, t25 = 0, t26 = 0, t27 = 0, t28 = 0, t29 = 0, t30 = 0,20457 b0 = b[0],20458 b1 = b[1],20459 b2 = b[2],20460 b3 = b[3],20461 b4 = b[4],20462 b5 = b[5],...
validate.ts
Source:validate.ts
1import { Stream } from 'stream';2import { isArray, isArrayBuffer, isBoolean, isBuffer, isMap, isNil, isNumber, isObject, isSet, isString, isSymbol } from 'lodash';3/**4 * Determines whether the object contains the current attribute.5 *6 * @param obj The object to judge.7 * @param key The property of object.8 *9 * @publicApi10 */11export function isKeyof(obj: object, key: any): key is keyof typeof obj {12 return key in obj && Object.prototype.hasOwnProperty.call(obj, key);13}14/**15 * Checks if the data is non-empty.16 *17 * @param data The data to be check.18 *19 * @publicApi20 */21export function isValid(data: any): boolean {22 return !isNil(data);23}24/**25 * Checks if the data is non-empty string.26 *27 * @param data The data to be check.28 *29 * @publicApi30 */31export function isValidString(data: string): boolean {32 return isValid(data) && isString(data) && data.length > 0;33}34/**35 * Checks if the data is non-empty number (Also it will not be NAN or plus or minus infinity).36 *37 * @param data The data to be check.38 *39 * @publicApi40 */41export function isValidNumber(data: number): boolean {42 return isValid(data) && isNumber(data) && Number.isSafeInteger(data);43}44/**45 * Checks if the data is non-empty array.46 *47 * @param data The data to be check.48 *49 * @publicApi50 */51export function isValidArray(data: any[]): boolean {52 return isValid(data) && isArray(data) && data.length > 0;53}54/**55 * Checks if the data is non-empty object.56 *57 * @param data The data to be check.58 *59 * @publicApi60 */61export function isValidObject(data: any): boolean {62 return isValid(data) && isObject(data) && Object.keys(data).length > 0;63}64/**65 * Checks if the data is Stream.66 *67 * @param data The data to be check.68 *69 * @publicApi70 */71export function isValidStream(data: any) {72 return isValid(data) && data instanceof Stream;73}74/**75 * Checks if the data is Buffer.76 *77 * @param data The data to be check.78 *79 * @publicApi80 */81export function isValidBuffer(data: any) {82 return isValid(data) && isBuffer(data);83}84/**85 * Checks if the data is ArrayBuffer.86 *87 * @param data The data to be check.88 *89 * @publicApi90 */91export function isValidArrayBuffer(data: any) {92 return isValid(data) && isArrayBuffer(data);93}94/**95 * Checks whether the current object is a dictionary.96 *97 * Dictionary is not in (`Map`/`Set`/`Symbol`/`Array`/`String`/`Number`/`Boolean`).98 *99 * @param obj The object to judge.100 *101 * @publicApi102 */103export function isValidDict(obj: any) {104 return isValidObject(obj)105 && !isMap(obj)106 && !isSet(obj)107 && !isArray(obj)108 && !isSymbol(obj)109 && !isString(obj)110 && !isNumber(obj)111 && !isBoolean(obj);...
main.ts
Source:main.ts
1import * as core from '@actions/core'2import {parseCredential} from '@google-github-actions/actions-utils';3import getOptions, {Options, validateOptions} from './options'4import {TemplateProcessor} from './TemplateProcessor';5import {GoogleSecretManagerClient} from './gcp/GoogleSecretManagerClient';6const main = async () => {7 const options: Options = getOptions()8 if (!validateOptions(options)) {9 process.exit(1)10 }11 const credentials = options.gcpCredentialsJson ? parseCredential(options.gcpCredentialsJson) : undefined12 const client = new GoogleSecretManagerClient({credentials})13 const processor = new TemplateProcessor(client)14 if (options.templateFile) {15 await processor.processFile(options.templateFile, options.keyPrefix)16 }17 if (options.envFile) {18 const result = require('dotenv').config({path: options.envFile, override: true})19 if (result.error || !result.parsed) {20 core.setFailed(`failed to parse the env file: ${result.error}`)21 process.exit(1)22 }23 const secrets = await processor.extractSecrets(options.envFile, options.keyPrefix)24 for (const key in result.parsed) {25 core.exportVariable(key, processor.applySecretsInString(result.parsed[key], secrets))26 }27 await processor.processFile(options.envFile, options.keyPrefix)28 }29}30try {31 main()32} catch (error) {33 core.setFailed(`${error}`)...
request.js
Source:request.js
1import axios from 'axios'2import { MessageBox, Message } from 'element-ui'3import cookie from 'js-cookie'4// å建axioså®ä¾5const service = axios.create({6 // baseURL: 'http://127.0.0.1:10012/',7 baseURL: 'https://houduan.yituliu.site/',8 timeout: 150000 // 请æ±è¶
æ¶æ¶é´9})10// http request æ¦æªå¨11service.interceptors.request.use(12 config => {13 config.headers['Access-Control-Max-Age'] = 8640014 // token å
ä¸å¤çï¼åç»ä½¿ç¨æ¶å¨å®å15 return config16},17 err => {18 return Promise.reject(err)19})20// http response æ¦æªå¨21service.interceptors.response.use(22 response => {23 if (response.data.code !== 200) {24 Message({25 message: response.data.msg,26 type: 'error',27 duration: 5 * 100028 })29 return Promise.reject(response.data)30 } else {31 return response.data32 }33 },34 error => {35 return Promise.reject(error.response)36})...
building.js
Source:building.js
1import request from '@/api/request'2const api_name = `/tool`3export default {4 //ä¿åæç5 maaBuildingJsonCreated(data,id) {6 return request({7 url: `${api_name}/building/schedule/save?id=${id}`,8 method: 'post',9 data:data10 })11 },12 retrieveSchedule(id){13 return request({14 url: `${api_name}/building/schedule/retrieve/${id}`,15 method: 'get',16 17 })18 },19 ...
hello.js
Source:hello.js
1// Next.js API route support: https://nextjs.org/docs/api-routes/introduction2export default function handler(req, res) {3 res.status(200).json({ name: 'John Doe' })...
Using AI Code Generation
1const { S } = require('playwright');2(async () => {3 const browser = await S.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 await page.screenshot({ path: 'google.png' });7 await browser.close();8})();9const { S } = require('playwright');10(async () => {11 const browser = await S.launch();12 const context = await browser.newContext();13 const page = await context.newPage();14 await page.screenshot({ path: 'google.png' });15 await browser.close();16})();17const { S } = require('playwright');18(async () => {19 const browser = await S.launch();20 const context = await browser.newContext();21 const page = await context.newPage();22 await page.screenshot({ path: 'google.png' });23 await browser.close();24})();25const { S } = require('playwright');26(async () => {27 const browser = await S.launch();28 const context = await browser.newContext();29 const page = await context.newPage();30 await page.screenshot({ path: 'google.png' });31 await browser.close();32})();33const { S } = require('playwright');34(async () => {35 const browser = await S.launch();36 const context = await browser.newContext();37 const page = await context.newPage();38 await page.screenshot({ path: 'google.png' });39 await browser.close();40})();41const { S } = require('playwright');42(async () => {43 const browser = await S.launch();44 const context = await browser.newContext();45 const page = await context.newPage();
Using AI Code Generation
1const { S } = require('playwright-internal');2(async () => {3 const browser = await S.launch({4 });5 const page = await S.newPage();6 await page.close();7 await browser.close();8})();9### S.launch([options])
Using AI Code Generation
1const { S } = require('playwright-internal');2const { test } = S;3const { S } = require('playwright');4const { test } = S;5test.describe('My test suite', () => {6});7test.beforeAll(async ({ context, page }) => {8});9test.afterAll(async ({ context, page }) => {10});11test.beforeEach(async ({ context, page }) => {12});13test.afterEach(async ({ context, page }) => {14});15test('My test', async ({ context, page }) => {16});17* `context`: an instance of [`BrowserContext`](
Using AI Code Generation
1const { S } = require('playwright-internal');2const { test } = require('@playwright/test');3test('test', async ({ page }) => {4 await S(page).click('text=Get started');5 await S(page).click('text=API');6 await S(page).click('text=Playwright');
Using AI Code Generation
1const { S } = require('playwright');2const { S } = require('playwright');3S.test('My first test', async (t) => {4 const page = await t.newPage();5 await page.click('text=Get Started');6 await page.click('text=Docs');7 await page.click('text=API');8 await page.click('text=Selectors');9 await page.click('text=waitFor');10 await page.click('text=Examples');11 await page.click('text=Brows
Using AI Code Generation
1const { S } = require('@playwright/test');2const mySelector = S('div').withText('My text');3console.log(mySelector.toString());4const { S } = require('playwright-internal');5const mySelector = S('div').withText('My text');6console.log(mySelector.toString());7const { S } = require('@playwright/test');8const mySelector = S('div').withText('My text');9console.log(mySelector.toString());10This library was created by [Antonio Lopes](
LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.
Get 100 minutes of automation test minutes FREE!!