@acuity/directus-extension-acuity-backup 2.1.2 → 2.1.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +14 -6
- package/dist/api.js +1 -1
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -26,10 +26,10 @@ A powerful Directus bundle extension that provides full or selective backup of c
|
|
|
26
26
|
|
|
27
27
|
### Docker (Recommended)
|
|
28
28
|
|
|
29
|
-
On your server, inside the directory mounted to `/directus/extensions`, install the extension into **its own subfolder
|
|
29
|
+
On your server, inside the directory mounted to `/directus/extensions`, install the extension into **its own subfolder**. Use the package name as the folder name — **do not name the folder `acuity-backup`**, as that collides with the bundle's endpoint entry and corrupts Directus's extension registry:
|
|
30
30
|
|
|
31
31
|
```bash
|
|
32
|
-
mkdir acuity-backup && cd acuity-backup
|
|
32
|
+
mkdir directus-extension-acuity-backup && cd directus-extension-acuity-backup
|
|
33
33
|
npm pack @acuity/directus-extension-acuity-backup
|
|
34
34
|
tar -xzf *.tgz --strip-components=1
|
|
35
35
|
rm *.tgz
|
|
@@ -63,7 +63,7 @@ RUN pnpm install @acuity/directus-extension-acuity-backup
|
|
|
63
63
|
To upgrade to the latest published version, clear out the old files and re-extract the new package in the same subfolder:
|
|
64
64
|
|
|
65
65
|
```bash
|
|
66
|
-
cd /directus/extensions/acuity-backup
|
|
66
|
+
cd /directus/extensions/directus-extension-acuity-backup
|
|
67
67
|
rm -rf dist node_modules package.json package-lock.json icon.png *.tgz
|
|
68
68
|
npm pack @acuity/directus-extension-acuity-backup
|
|
69
69
|
tar -xzf *.tgz --strip-components=1
|
|
@@ -77,7 +77,15 @@ Then restart Directus to load the new version:
|
|
|
77
77
|
docker compose restart directus
|
|
78
78
|
```
|
|
79
79
|
|
|
80
|
-
To pin a specific version instead of the latest, append `@<version>` to the pack command, e.g. `npm pack @acuity/directus-extension-acuity-backup@2.1.
|
|
80
|
+
To pin a specific version instead of the latest, append `@<version>` to the pack command, e.g. `npm pack @acuity/directus-extension-acuity-backup@2.1.4`.
|
|
81
|
+
|
|
82
|
+
> **Upgrading from a release installed in a folder named `acuity-backup`?** Rename the folder to `directus-extension-acuity-backup` first — the old name collides with the bundle's endpoint entry and corrupts Directus's extension registry. If the **Settings → Extensions** page was already returning a 500, clear the stale rows once and restart:
|
|
83
|
+
>
|
|
84
|
+
> ```sql
|
|
85
|
+
> DELETE FROM directus_extensions WHERE folder IN ('acuity-backup', 'acuity-backup-module', 'backup-endpoint');
|
|
86
|
+
> ```
|
|
87
|
+
>
|
|
88
|
+
> Directus rebuilds clean rows from disk on the next boot.
|
|
81
89
|
|
|
82
90
|
### Dockerfile
|
|
83
91
|
|
|
@@ -91,10 +99,10 @@ docker compose up -d directus
|
|
|
91
99
|
Pin a version in the Dockerfile to control upgrades explicitly:
|
|
92
100
|
|
|
93
101
|
```dockerfile
|
|
94
|
-
RUN pnpm install @acuity/directus-extension-acuity-backup@2.1.
|
|
102
|
+
RUN pnpm install @acuity/directus-extension-acuity-backup@2.1.4
|
|
95
103
|
```
|
|
96
104
|
|
|
97
|
-
> Check the installed version anytime with `cat /directus/extensions/acuity-backup/package.json | grep version`, and compare against the [latest release on npm](https://www.npmjs.com/package/@acuity/directus-extension-acuity-backup).
|
|
105
|
+
> Check the installed version anytime with `cat /directus/extensions/directus-extension-acuity-backup/package.json | grep version`, and compare against the [latest release on npm](https://www.npmjs.com/package/@acuity/directus-extension-acuity-backup).
|
|
98
106
|
|
|
99
107
|
## Configuration
|
|
100
108
|
|
package/dist/api.js
CHANGED
|
@@ -46,4 +46,4 @@ import{readFileSync as t,existsSync as e,writeFileSync as r,mkdirSync as n,creat
|
|
|
46
46
|
* @ignore
|
|
47
47
|
* @license [MIT]{@link https://github.com/archiverjs/node-archiver/blob/master/LICENSE}
|
|
48
48
|
* @copyright (c) 2012-2014 Chris Talkington, contributors.
|
|
49
|
-
*/()),zl=r}(),lf=D(cf),ff={};function hf(){if(Zl)return Ql;Zl=1;const t=g;function e(){if(!(this instanceof e))return new e;t.Duplex.call(this,{decodeStrings:!1,objectMode:!0}),this.buffer=Buffer.from("");const r=this;r.on("finish",function(){r.finished=!0,r.emit("chunk",!1)})}return b.inherits(e,t.Duplex),e.prototype._write=function(t,e,r){this.buffer=Buffer.concat([this.buffer,t]),this.cb=r,this.emit("chunk")},e.prototype.stream=function(e,r){const n=t.PassThrough();let i;const o=this;function s(){if("function"==typeof o.cb){const t=o.cb;return o.cb=void 0,t()}}function a(){let t;if(o.buffer&&o.buffer.length){if("number"==typeof e)t=o.buffer.slice(0,e),o.buffer=o.buffer.slice(e),e-=t.length,i=i||!e;else{let n=o.buffer.indexOf(e);if(-1!==n)o.match=n,r&&(n+=e.length),t=o.buffer.slice(0,n),o.buffer=o.buffer.slice(n),i=!0;else{const r=o.buffer.length-e.length;r<=0?s():(t=o.buffer.slice(0,r),o.buffer=o.buffer.slice(r))}}t&&n.write(t,function(){(0===o.buffer.length||e.length&&o.buffer.length<=e.length)&&s()})}if(i)o.removeListener("chunk",a),n.end();else if(o.finished)return o.removeListener("chunk",a),void o.emit("error",new Error("FILE_ENDED"))}return o.on("chunk",a),a(),n},e.prototype.pull=function(e,r){if(0===e)return Promise.resolve("");if(!isNaN(e)&&this.buffer.length>e){const t=this.buffer.slice(0,e);return this.buffer=this.buffer.slice(e),Promise.resolve(t)}let n=Buffer.from("");const i=this,o=new t.Transform;let s,a;return o._transform=function(t,e,r){n=Buffer.concat([n,t]),r()},new Promise(function(t,u){if(s=u,a=function(t){i.__emittedError=t,u(t)},i.finished)return u(new Error("FILE_ENDED"));i.once("error",a),i.stream(e,r).on("error",u).pipe(o).on("finish",function(){t(n)}).on("error",u)}).finally(function(){i.removeListener("error",s),i.removeListener("error",a)})},e.prototype._read=function(){},Ql=e}function pf(){if(Xl)return Yl;Xl=1;const t=g;return Yl=function(e){return new Promise(function(r,n){const i=[],o=t.Transform().on("finish",function(){r(Buffer.concat(i))}).on("error",n);o._transform=function(t,e,r){i.push(t),r()},e.on("error",n).pipe(o)})},Yl}function df(){if(ef)return tf;ef=1;const t=function(t,e,r){let n;switch(r){case 1:n=t.readUInt8(e);break;case 2:n=t.readUInt16LE(e);break;case 4:n=t.readUInt32LE(e);break;case 8:n=Number(t.readBigUInt64LE(e));break;default:throw new Error("Unsupported UInt LE size!")}return n};return tf={parse:function(e,r){const n={};let i=0;for(const[o,s]of r)e.length>=i+s?n[o]=t(e,i,s):n[o]=null,i+=s;return n}}}function yf(){if(nf)return rf;nf=1;const t=df();return rf=function(e,r){let n;for(;!n&&e&&e.length;){const i=t.parse(e,[["signature",2],["partSize",2]]);if(1===i.signature){const i=[];4294967295===r.uncompressedSize&&i.push(["uncompressedSize",8]),4294967295===r.compressedSize&&i.push(["compressedSize",8]),4294967295===r.offsetToLocalFileHeader&&i.push(["offsetToLocalFileHeader",8]),n=t.parse(e.slice(4),i)}else e=e.slice(i.partSize+4)}return n=n||{},4294967295===r.compressedSize&&(r.compressedSize=n.compressedSize),4294967295===r.uncompressedSize&&(r.uncompressedSize=n.uncompressedSize),4294967295===r.offsetToLocalFileHeader&&(r.offsetToLocalFileHeader=n.offsetToLocalFileHeader),n}}function mf(){return sf?of:(sf=1,of=function(t,e){const r=31&t,n=t>>5&15,i=1980+(t>>9&127),o=e?2*(31&e):0,s=e?e>>5&63:0,a=e?e>>11:0;return new Date(Date.UTC(i,n-1,r,a,s,o))})}function gf(){if(uf)return af;uf=1;const t=b,e=S,r=g,n=hf(),i=function(){if(Jl)return Kl;Jl=1;const t=g;function e(){if(!(this instanceof e))return new e;t.Transform.call(this)}return b.inherits(e,t.Transform),e.prototype._transform=function(t,e,r){r()},Kl=e}(),o=pf(),s=yf(),a=mf(),u=r.pipeline,c=df(),l=Buffer.alloc(4);function f(t){if(!(this instanceof f))return new f(t);const e=this;e._opts=t||{verbose:!1},n.call(e,e._opts),e.on("finish",function(){e.emit("end"),e.emit("close")}),e._readRecord().catch(function(t){e.__emittedError&&e.__emittedError===t||e.emit("error",t)})}return l.writeUInt32LE(101010256,0),t.inherits(f,n),f.prototype._readRecord=function(){const t=this;return t.pull(4).then(function(e){if(0===e.length)return;const r=e.readUInt32LE(0);if(875721283===r)return t._readCrxHeader();if(67324752===r)return t._readFile();if(33639248===r)return t.reachedCD=!0,t._readCentralDirectoryFileHeader();if(101010256===r)return t._readEndOfCentralDirectoryRecord();if(t.reachedCD){const e=!0;return t.pull(l,e).then(function(){return t._readEndOfCentralDirectoryRecord()})}t.emit("error",new Error("invalid signature: 0x"+r.toString(16)))}).then(function(e){if(e)return t._readRecord()})},f.prototype._readCrxHeader=function(){const t=this;return t.pull(12).then(function(e){return t.crxHeader=c.parse(e,[["version",4],["pubKeyLength",4],["signatureLength",4]]),t.pull(t.crxHeader.pubKeyLength+t.crxHeader.signatureLength)}).then(function(e){return t.crxHeader.publicKey=e.slice(0,t.crxHeader.pubKeyLength),t.crxHeader.signature=e.slice(t.crxHeader.pubKeyLength),t.emit("crx-header",t.crxHeader),!0})},f.prototype._readFile=function(){const t=this;return t.pull(26).then(function(n){const l=c.parse(n,[["versionsNeededToExtract",2],["flags",2],["compressionMethod",2],["lastModifiedTime",2],["lastModifiedDate",2],["crc32",4],["compressedSize",4],["uncompressedSize",4],["fileNameLength",2],["extraFieldLength",2]]);return l.lastModifiedDateTime=a(l.lastModifiedDate,l.lastModifiedTime),t.crxHeader&&(l.crxHeader=t.crxHeader),t.pull(l.fileNameLength).then(function(n){const a=n.toString("utf8"),c=r.PassThrough();let f=!1;return c.autodrain=function(){f=!0;const t=c.pipe(i());return t.promise=function(){return new Promise(function(e,r){t.on("finish",e),t.on("error",r)})},t},c.buffer=function(){return o(c)},c.path=a,c.props={},c.props.path=a,c.props.pathBuffer=n,c.props.flags={isUnicode:!!(2048&l.flags)},c.type=0===l.uncompressedSize&&/[/\\]$/.test(a)?"Directory":"File",t._opts.verbose&&("Directory"===c.type?console.log(" creating:",a):"File"===c.type&&(0===l.compressionMethod?console.log(" extracting:",a):console.log(" inflating:",a))),t.pull(l.extraFieldLength).then(function(n){const i=s(n,l);c.vars=l,c.extra=i,t._opts.forceStream?t.push(c):(t.emit("entry",c),(t._readableState.pipesCount||t._readableState.pipes&&t._readableState.pipes.length)&&t.push(c)),t._opts.verbose&&console.log({filename:a,vars:l,extra:i});const o=!(8&l.flags)||l.compressedSize>0;let h;c.__autodraining=f;const p=l.compressionMethod&&!f?e.createInflateRaw():r.PassThrough();return o?(c.size=l.uncompressedSize,h=l.compressedSize):(h=Buffer.alloc(4),h.writeUInt32LE(134695760,0)),new Promise(function(e,r){u(t.stream(h),p,c,function(n){return n?r(n):o?e(o):t._processDataDescriptor(c).then(e).catch(r)})})})})})},f.prototype._processDataDescriptor=function(t){return this.pull(16).then(function(e){const r=c.parse(e,[["dataDescriptorSignature",4],["crc32",4],["compressedSize",4],["uncompressedSize",4]]);return t.size=r.uncompressedSize,!0})},f.prototype._readCentralDirectoryFileHeader=function(){const t=this;return t.pull(42).then(function(e){const r=c.parse(e,[["versionMadeBy",2],["versionsNeededToExtract",2],["flags",2],["compressionMethod",2],["lastModifiedTime",2],["lastModifiedDate",2],["crc32",4],["compressedSize",4],["uncompressedSize",4],["fileNameLength",2],["extraFieldLength",2],["fileCommentLength",2],["diskNumber",2],["internalFileAttributes",2],["externalFileAttributes",4],["offsetToLocalFileHeader",4]]);return t.pull(r.fileNameLength).then(function(e){return r.fileName=e.toString("utf8"),t.pull(r.extraFieldLength)}).then(function(){return t.pull(r.fileCommentLength)}).then(function(){return!0})})},f.prototype._readEndOfCentralDirectoryRecord=function(){const t=this;return t.pull(18).then(function(e){const r=c.parse(e,[["diskNumber",2],["diskStart",2],["numberOfRecordsOnDisk",2],["numberOfRecords",2],["sizeOfCentralDirectory",4],["offsetToStartOfCentralDirectory",4],["commentLength",2]]);return t.pull(r.commentLength).then(function(){t.end(),t.push(null)})})},f.prototype.promise=function(){const t=this;return new Promise(function(e,r){t.on("finish",e),t.on("error",r)})},af=f}var _f,bf,vf={exports:{}},wf={exports:{}};function Sf(){return bf?_f:(bf=1,_f=g)}var Ef,kf={exports:{}};function xf(){return Ef||(Ef=1,function(t,e){var r=w,n=r.Buffer;function i(t,e){for(var r in t)e[r]=t[r]}function o(t,e,r){return n(t,e,r)}n.from&&n.alloc&&n.allocUnsafe&&n.allocUnsafeSlow?t.exports=r:(i(r,e),e.Buffer=o),i(n,o),o.from=function(t,e,r){if("number"==typeof t)throw new TypeError("Argument must not be a number");return n(t,e,r)},o.alloc=function(t,e,r){if("number"!=typeof t)throw new TypeError("Argument must be a number");var i=n(t);return void 0!==e?"string"==typeof r?i.fill(e,r):i.fill(e):i.fill(0),i},o.allocUnsafe=function(t){if("number"!=typeof t)throw new TypeError("Argument must be a number");return n(t)},o.allocUnsafeSlow=function(t){if("number"!=typeof t)throw new TypeError("Argument must be a number");return r.SlowBuffer(t)}}(kf,kf.exports)),kf.exports}var Of,Tf,jf,Cf,Rf,Pf,Lf,Ff={exports:{}};function Af(){return Of||(Of=1,function(t){var e=xf().Buffer,r=b;function n(t,e,r){t.copy(e,r)}t.exports=function(){function t(){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.head=null,this.tail=null,this.length=0}return t.prototype.push=function(t){var e={data:t,next:null};this.length>0?this.tail.next=e:this.head=e,this.tail=e,++this.length},t.prototype.unshift=function(t){var e={data:t,next:this.head};0===this.length&&(this.tail=e),this.head=e,++this.length},t.prototype.shift=function(){if(0!==this.length){var t=this.head.data;return 1===this.length?this.head=this.tail=null:this.head=this.head.next,--this.length,t}},t.prototype.clear=function(){this.head=this.tail=null,this.length=0},t.prototype.join=function(t){if(0===this.length)return"";for(var e=this.head,r=""+e.data;e=e.next;)r+=t+e.data;return r},t.prototype.concat=function(t){if(0===this.length)return e.alloc(0);for(var r=e.allocUnsafe(t>>>0),i=this.head,o=0;i;)n(i.data,r,o),o+=i.data.length,i=i.next;return r},t}(),r&&r.inspect&&r.inspect.custom&&(t.exports.prototype[r.inspect.custom]=function(){var t=r.inspect({length:this.length});return this.constructor.name+" "+t})}(Ff)),Ff.exports}function If(){if(jf)return Tf;jf=1;var t=vr();function e(t,e){t.emit("error",e)}return Tf={destroy:function(r,n){var i=this,o=this._readableState&&this._readableState.destroyed,s=this._writableState&&this._writableState.destroyed;return o||s?(n?n(r):r&&(this._writableState?this._writableState.errorEmitted||(this._writableState.errorEmitted=!0,t.nextTick(e,this,r)):t.nextTick(e,this,r)),this):(this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(r||null,function(r){!n&&r?i._writableState?i._writableState.errorEmitted||(i._writableState.errorEmitted=!0,t.nextTick(e,i,r)):t.nextTick(e,i,r):n&&n(r)}),this)},undestroy:function(){this._readableState&&(this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1),this._writableState&&(this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finalCalled=!1,this._writableState.prefinished=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1)}}}function Df(){if(Rf)return Cf;Rf=1;var t=vr();function e(t){var e=this;this.next=null,this.entry=null,this.finish=function(){!function(t,e,r){var n=t.entry;t.entry=null;for(;n;){var i=n.callback;e.pendingcb--,i(r),n=n.next}e.corkedRequestsFree.next=t}(e,t)}}Cf=p;var r,n=!process.browser&&["v0.10","v0.9."].indexOf(process.version.slice(0,5))>-1?setImmediate:t.nextTick;p.WritableState=h;var i=Object.create(jr());i.inherits=Fr();var o={deprecate:Gr()},s=Sf(),a=xf().Buffer,u=(void 0!==I?I:"undefined"!=typeof window?window:"undefined"!=typeof self?self:{}).Uint8Array||function(){};var c,l=If();function f(){}function h(i,o){r=r||Mf(),i=i||{};var s=o instanceof r;this.objectMode=!!i.objectMode,s&&(this.objectMode=this.objectMode||!!i.writableObjectMode);var a=i.highWaterMark,u=i.writableHighWaterMark,c=this.objectMode?16:16384;this.highWaterMark=a||0===a?a:s&&(u||0===u)?u:c,this.highWaterMark=Math.floor(this.highWaterMark),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;var l=!1===i.decodeStrings;this.decodeStrings=!l,this.defaultEncoding=i.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(e){!function(e,r){var i=e._writableState,o=i.sync,s=i.writecb;if(function(t){t.writing=!1,t.writecb=null,t.length-=t.writelen,t.writelen=0}(i),r)!function(e,r,n,i,o){--r.pendingcb,n?(t.nextTick(o,i),t.nextTick(b,e,r),e._writableState.errorEmitted=!0,e.emit("error",i)):(o(i),e._writableState.errorEmitted=!0,e.emit("error",i),b(e,r))}(e,i,o,r,s);else{var a=g(i);a||i.corked||i.bufferProcessing||!i.bufferedRequest||m(e,i),o?n(y,e,i,a,s):y(e,i,a,s)}}(o,e)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.bufferedRequestCount=0,this.corkedRequestsFree=new e(this)}function p(t){if(r=r||Mf(),!(c.call(p,this)||this instanceof r))return new p(t);this._writableState=new h(t,this),this.writable=!0,t&&("function"==typeof t.write&&(this._write=t.write),"function"==typeof t.writev&&(this._writev=t.writev),"function"==typeof t.destroy&&(this._destroy=t.destroy),"function"==typeof t.final&&(this._final=t.final)),s.call(this)}function d(t,e,r,n,i,o,s){e.writelen=n,e.writecb=s,e.writing=!0,e.sync=!0,r?t._writev(i,e.onwrite):t._write(i,o,e.onwrite),e.sync=!1}function y(t,e,r,n){r||function(t,e){0===e.length&&e.needDrain&&(e.needDrain=!1,t.emit("drain"))}(t,e),e.pendingcb--,n(),b(t,e)}function m(t,r){r.bufferProcessing=!0;var n=r.bufferedRequest;if(t._writev&&n&&n.next){var i=r.bufferedRequestCount,o=new Array(i),s=r.corkedRequestsFree;s.entry=n;for(var a=0,u=!0;n;)o[a]=n,n.isBuf||(u=!1),n=n.next,a+=1;o.allBuffers=u,d(t,r,!0,r.length,o,"",s.finish),r.pendingcb++,r.lastBufferedRequest=null,s.next?(r.corkedRequestsFree=s.next,s.next=null):r.corkedRequestsFree=new e(r),r.bufferedRequestCount=0}else{for(;n;){var c=n.chunk,l=n.encoding,f=n.callback;if(d(t,r,!1,r.objectMode?1:c.length,c,l,f),n=n.next,r.bufferedRequestCount--,r.writing)break}null===n&&(r.lastBufferedRequest=null)}r.bufferedRequest=n,r.bufferProcessing=!1}function g(t){return t.ending&&0===t.length&&null===t.bufferedRequest&&!t.finished&&!t.writing}function _(t,e){t._final(function(r){e.pendingcb--,r&&t.emit("error",r),e.prefinished=!0,t.emit("prefinish"),b(t,e)})}function b(e,r){var n=g(r);return n&&(!function(e,r){r.prefinished||r.finalCalled||("function"==typeof e._final?(r.pendingcb++,r.finalCalled=!0,t.nextTick(_,e,r)):(r.prefinished=!0,e.emit("prefinish")))}(e,r),0===r.pendingcb&&(r.finished=!0,e.emit("finish"))),n}return i.inherits(p,s),h.prototype.getBuffer=function(){for(var t=this.bufferedRequest,e=[];t;)e.push(t),t=t.next;return e},function(){try{Object.defineProperty(h.prototype,"buffer",{get:o.deprecate(function(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")})}catch(t){}}(),"function"==typeof Symbol&&Symbol.hasInstance&&"function"==typeof Function.prototype[Symbol.hasInstance]?(c=Function.prototype[Symbol.hasInstance],Object.defineProperty(p,Symbol.hasInstance,{value:function(t){return!!c.call(this,t)||this===p&&(t&&t._writableState instanceof h)}})):c=function(t){return t instanceof this},p.prototype.pipe=function(){this.emit("error",new Error("Cannot pipe, not readable"))},p.prototype.write=function(e,r,n){var i,o=this._writableState,s=!1,c=!o.objectMode&&(i=e,a.isBuffer(i)||i instanceof u);return c&&!a.isBuffer(e)&&(e=function(t){return a.from(t)}(e)),"function"==typeof r&&(n=r,r=null),c?r="buffer":r||(r=o.defaultEncoding),"function"!=typeof n&&(n=f),o.ended?function(e,r){var n=new Error("write after end");e.emit("error",n),t.nextTick(r,n)}(this,n):(c||function(e,r,n,i){var o=!0,s=!1;return null===n?s=new TypeError("May not write null values to stream"):"string"==typeof n||void 0===n||r.objectMode||(s=new TypeError("Invalid non-string/buffer chunk")),s&&(e.emit("error",s),t.nextTick(i,s),o=!1),o}(this,o,e,n))&&(o.pendingcb++,s=function(t,e,r,n,i,o){if(!r){var s=function(t,e,r){t.objectMode||!1===t.decodeStrings||"string"!=typeof e||(e=a.from(e,r));return e}(e,n,i);n!==s&&(r=!0,i="buffer",n=s)}var u=e.objectMode?1:n.length;e.length+=u;var c=e.length<e.highWaterMark;c||(e.needDrain=!0);if(e.writing||e.corked){var l=e.lastBufferedRequest;e.lastBufferedRequest={chunk:n,encoding:i,isBuf:r,callback:o,next:null},l?l.next=e.lastBufferedRequest:e.bufferedRequest=e.lastBufferedRequest,e.bufferedRequestCount+=1}else d(t,e,!1,u,n,i,o);return c}(this,o,c,e,r,n)),s},p.prototype.cork=function(){this._writableState.corked++},p.prototype.uncork=function(){var t=this._writableState;t.corked&&(t.corked--,t.writing||t.corked||t.bufferProcessing||!t.bufferedRequest||m(this,t))},p.prototype.setDefaultEncoding=function(t){if("string"==typeof t&&(t=t.toLowerCase()),!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((t+"").toLowerCase())>-1))throw new TypeError("Unknown encoding: "+t);return this._writableState.defaultEncoding=t,this},Object.defineProperty(p.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),p.prototype._write=function(t,e,r){r(new Error("_write() is not implemented"))},p.prototype._writev=null,p.prototype.end=function(e,r,n){var i=this._writableState;"function"==typeof e?(n=e,e=null,r=null):"function"==typeof r&&(n=r,r=null),null!=e&&this.write(e,r),i.corked&&(i.corked=1,this.uncork()),i.ending||function(e,r,n){r.ending=!0,b(e,r),n&&(r.finished?t.nextTick(n):e.once("finish",n));r.ended=!0,e.writable=!1}(this,i,n)},Object.defineProperty(p.prototype,"destroyed",{get:function(){return void 0!==this._writableState&&this._writableState.destroyed},set:function(t){this._writableState&&(this._writableState.destroyed=t)}}),p.prototype.destroy=l.destroy,p.prototype._undestroy=l.undestroy,p.prototype._destroy=function(t,e){this.end(),e(t)},Cf}function Mf(){if(Lf)return Pf;Lf=1;var t=vr(),e=Object.keys||function(t){var e=[];for(var r in t)e.push(r);return e};Pf=u;var r=Object.create(jr());r.inherits=Fr();var n=Jf(),i=Df();r.inherits(u,n);for(var o=e(i.prototype),s=0;s<o.length;s++){var a=o[s];u.prototype[a]||(u.prototype[a]=i.prototype[a])}function u(t){if(!(this instanceof u))return new u(t);n.call(this,t),i.call(this,t),t&&!1===t.readable&&(this.readable=!1),t&&!1===t.writable&&(this.writable=!1),this.allowHalfOpen=!0,t&&!1===t.allowHalfOpen&&(this.allowHalfOpen=!1),this.once("end",c)}function c(){this.allowHalfOpen||this._writableState.ended||t.nextTick(l,this)}function l(t){t.end()}return Object.defineProperty(u.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),Object.defineProperty(u.prototype,"destroyed",{get:function(){return void 0!==this._readableState&&void 0!==this._writableState&&(this._readableState.destroyed&&this._writableState.destroyed)},set:function(t){void 0!==this._readableState&&void 0!==this._writableState&&(this._readableState.destroyed=t,this._writableState.destroyed=t)}}),u.prototype._destroy=function(e,r){this.push(null),this.end(),t.nextTick(r,e)},Pf}var Nf,Bf,Uf,zf,Wf,Hf,$f,qf,Gf,Vf,Qf,Zf={};function Kf(){if(Nf)return Zf;Nf=1;var t=xf().Buffer,e=t.isEncoding||function(t){switch((t=""+t)&&t.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};function r(r){var n;switch(this.encoding=function(r){var n=function(t){if(!t)return"utf8";for(var e;;)switch(t){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return t;default:if(e)return;t=(""+t).toLowerCase(),e=!0}}(r);if("string"!=typeof n&&(t.isEncoding===e||!e(r)))throw new Error("Unknown encoding: "+r);return n||r}(r),this.encoding){case"utf16le":this.text=o,this.end=s,n=4;break;case"utf8":this.fillLast=i,n=4;break;case"base64":this.text=a,this.end=u,n=3;break;default:return this.write=c,void(this.end=l)}this.lastNeed=0,this.lastTotal=0,this.lastChar=t.allocUnsafe(n)}function n(t){return t<=127?0:t>>5==6?2:t>>4==14?3:t>>3==30?4:t>>6==2?-1:-2}function i(t){var e=this.lastTotal-this.lastNeed,r=function(t,e){if(128!=(192&e[0]))return t.lastNeed=0,"�";if(t.lastNeed>1&&e.length>1){if(128!=(192&e[1]))return t.lastNeed=1,"�";if(t.lastNeed>2&&e.length>2&&128!=(192&e[2]))return t.lastNeed=2,"�"}}(this,t);return void 0!==r?r:this.lastNeed<=t.length?(t.copy(this.lastChar,e,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal)):(t.copy(this.lastChar,e,0,t.length),void(this.lastNeed-=t.length))}function o(t,e){if((t.length-e)%2==0){var r=t.toString("utf16le",e);if(r){var n=r.charCodeAt(r.length-1);if(n>=55296&&n<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=t[t.length-2],this.lastChar[1]=t[t.length-1],r.slice(0,-1)}return r}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=t[t.length-1],t.toString("utf16le",e,t.length-1)}function s(t){var e=t&&t.length?this.write(t):"";if(this.lastNeed){var r=this.lastTotal-this.lastNeed;return e+this.lastChar.toString("utf16le",0,r)}return e}function a(t,e){var r=(t.length-e)%3;return 0===r?t.toString("base64",e):(this.lastNeed=3-r,this.lastTotal=3,1===r?this.lastChar[0]=t[t.length-1]:(this.lastChar[0]=t[t.length-2],this.lastChar[1]=t[t.length-1]),t.toString("base64",e,t.length-r))}function u(t){var e=t&&t.length?this.write(t):"";return this.lastNeed?e+this.lastChar.toString("base64",0,3-this.lastNeed):e}function c(t){return t.toString(this.encoding)}function l(t){return t&&t.length?this.write(t):""}return Zf.StringDecoder=r,r.prototype.write=function(t){if(0===t.length)return"";var e,r;if(this.lastNeed){if(void 0===(e=this.fillLast(t)))return"";r=this.lastNeed,this.lastNeed=0}else r=0;return r<t.length?e?e+this.text(t,r):this.text(t,r):e||""},r.prototype.end=function(t){var e=t&&t.length?this.write(t):"";return this.lastNeed?e+"�":e},r.prototype.text=function(t,e){var r=function(t,e,r){var i=e.length-1;if(i<r)return 0;var o=n(e[i]);if(o>=0)return o>0&&(t.lastNeed=o-1),o;if(--i<r||-2===o)return 0;if(o=n(e[i]),o>=0)return o>0&&(t.lastNeed=o-2),o;if(--i<r||-2===o)return 0;if(o=n(e[i]),o>=0)return o>0&&(2===o?o=0:t.lastNeed=o-3),o;return 0}(this,t,e);if(!this.lastNeed)return t.toString("utf8",e);this.lastTotal=r;var i=t.length-(r-this.lastNeed);return t.copy(this.lastChar,0,i),t.toString("utf8",e,i)},r.prototype.fillLast=function(t){if(this.lastNeed<=t.length)return t.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);t.copy(this.lastChar,this.lastTotal-this.lastNeed,0,t.length),this.lastNeed-=t.length},Zf}function Jf(){if(Uf)return Bf;Uf=1;var t=vr();Bf=m;var e,r=wr();m.ReadableState=y,d.EventEmitter;var n=function(t,e){return t.listeners(e).length},i=Sf(),o=xf().Buffer,s=(void 0!==I?I:"undefined"!=typeof window?window:"undefined"!=typeof self?self:{}).Uint8Array||function(){};var a=Object.create(jr());a.inherits=Fr();var u=b,c=void 0;c=u&&u.debuglog?u.debuglog("stream"):function(){};var l,f=Af(),h=If();a.inherits(m,i);var p=["error","close","destroy","pause","resume"];function y(t,r){t=t||{};var n=r instanceof(e=e||Mf());this.objectMode=!!t.objectMode,n&&(this.objectMode=this.objectMode||!!t.readableObjectMode);var i=t.highWaterMark,o=t.readableHighWaterMark,s=this.objectMode?16:16384;this.highWaterMark=i||0===i?i:n&&(o||0===o)?o:s,this.highWaterMark=Math.floor(this.highWaterMark),this.buffer=new f,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.destroyed=!1,this.defaultEncoding=t.defaultEncoding||"utf8",this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,t.encoding&&(l||(l=Kf().StringDecoder),this.decoder=new l(t.encoding),this.encoding=t.encoding)}function m(t){if(e=e||Mf(),!(this instanceof m))return new m(t);this._readableState=new y(t,this),this.readable=!0,t&&("function"==typeof t.read&&(this._read=t.read),"function"==typeof t.destroy&&(this._destroy=t.destroy)),i.call(this)}function g(t,e,r,n,i){var a,u=t._readableState;null===e?(u.reading=!1,function(t,e){if(e.ended)return;if(e.decoder){var r=e.decoder.end();r&&r.length&&(e.buffer.push(r),e.length+=e.objectMode?1:r.length)}e.ended=!0,S(t)}(t,u)):(i||(a=function(t,e){var r;n=e,o.isBuffer(n)||n instanceof s||"string"==typeof e||void 0===e||t.objectMode||(r=new TypeError("Invalid non-string/buffer chunk"));var n;return r}(u,e)),a?t.emit("error",a):u.objectMode||e&&e.length>0?("string"==typeof e||u.objectMode||Object.getPrototypeOf(e)===o.prototype||(e=function(t){return o.from(t)}(e)),n?u.endEmitted?t.emit("error",new Error("stream.unshift() after end event")):_(t,u,e,!0):u.ended?t.emit("error",new Error("stream.push() after EOF")):(u.reading=!1,u.decoder&&!r?(e=u.decoder.write(e),u.objectMode||0!==e.length?_(t,u,e,!1):k(t,u)):_(t,u,e,!1))):n||(u.reading=!1));return function(t){return!t.ended&&(t.needReadable||t.length<t.highWaterMark||0===t.length)}(u)}function _(t,e,r,n){e.flowing&&0===e.length&&!e.sync?(t.emit("data",r),t.read(0)):(e.length+=e.objectMode?1:r.length,n?e.buffer.unshift(r):e.buffer.push(r),e.needReadable&&S(t)),k(t,e)}Object.defineProperty(m.prototype,"destroyed",{get:function(){return void 0!==this._readableState&&this._readableState.destroyed},set:function(t){this._readableState&&(this._readableState.destroyed=t)}}),m.prototype.destroy=h.destroy,m.prototype._undestroy=h.undestroy,m.prototype._destroy=function(t,e){this.push(null),e(t)},m.prototype.push=function(t,e){var r,n=this._readableState;return n.objectMode?r=!0:"string"==typeof t&&((e=e||n.defaultEncoding)!==n.encoding&&(t=o.from(t,e),e=""),r=!0),g(this,t,e,!1,r)},m.prototype.unshift=function(t){return g(this,t,null,!0,!1)},m.prototype.isPaused=function(){return!1===this._readableState.flowing},m.prototype.setEncoding=function(t){return l||(l=Kf().StringDecoder),this._readableState.decoder=new l(t),this._readableState.encoding=t,this};var v=8388608;function w(t,e){return t<=0||0===e.length&&e.ended?0:e.objectMode?1:t!=t?e.flowing&&e.length?e.buffer.head.data.length:e.length:(t>e.highWaterMark&&(e.highWaterMark=function(t){return t>=v?t=v:(t--,t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,t|=t>>>16,t++),t}(t)),t<=e.length?t:e.ended?e.length:(e.needReadable=!0,0))}function S(e){var r=e._readableState;r.needReadable=!1,r.emittedReadable||(c("emitReadable",r.flowing),r.emittedReadable=!0,r.sync?t.nextTick(E,e):E(e))}function E(t){c("emit readable"),t.emit("readable"),j(t)}function k(e,r){r.readingMore||(r.readingMore=!0,t.nextTick(x,e,r))}function x(t,e){for(var r=e.length;!e.reading&&!e.flowing&&!e.ended&&e.length<e.highWaterMark&&(c("maybeReadMore read 0"),t.read(0),r!==e.length);)r=e.length;e.readingMore=!1}function O(t){c("readable nexttick read 0"),t.read(0)}function T(t,e){e.reading||(c("resume read 0"),t.read(0)),e.resumeScheduled=!1,e.awaitDrain=0,t.emit("resume"),j(t),e.flowing&&!e.reading&&t.read(0)}function j(t){var e=t._readableState;for(c("flow",e.flowing);e.flowing&&null!==t.read(););}function C(t,e){return 0===e.length?null:(e.objectMode?r=e.buffer.shift():!t||t>=e.length?(r=e.decoder?e.buffer.join(""):1===e.buffer.length?e.buffer.head.data:e.buffer.concat(e.length),e.buffer.clear()):r=function(t,e,r){var n;t<e.head.data.length?(n=e.head.data.slice(0,t),e.head.data=e.head.data.slice(t)):n=t===e.head.data.length?e.shift():r?function(t,e){var r=e.head,n=1,i=r.data;t-=i.length;for(;r=r.next;){var o=r.data,s=t>o.length?o.length:t;if(s===o.length?i+=o:i+=o.slice(0,t),0===(t-=s)){s===o.length?(++n,r.next?e.head=r.next:e.head=e.tail=null):(e.head=r,r.data=o.slice(s));break}++n}return e.length-=n,i}(t,e):function(t,e){var r=o.allocUnsafe(t),n=e.head,i=1;n.data.copy(r),t-=n.data.length;for(;n=n.next;){var s=n.data,a=t>s.length?s.length:t;if(s.copy(r,r.length-t,0,a),0===(t-=a)){a===s.length?(++i,n.next?e.head=n.next:e.head=e.tail=null):(e.head=n,n.data=s.slice(a));break}++i}return e.length-=i,r}(t,e);return n}(t,e.buffer,e.decoder),r);var r}function R(e){var r=e._readableState;if(r.length>0)throw new Error('"endReadable()" called on non-empty stream');r.endEmitted||(r.ended=!0,t.nextTick(P,r,e))}function P(t,e){t.endEmitted||0!==t.length||(t.endEmitted=!0,e.readable=!1,e.emit("end"))}function L(t,e){for(var r=0,n=t.length;r<n;r++)if(t[r]===e)return r;return-1}return m.prototype.read=function(t){c("read",t),t=parseInt(t,10);var e=this._readableState,r=t;if(0!==t&&(e.emittedReadable=!1),0===t&&e.needReadable&&(e.length>=e.highWaterMark||e.ended))return c("read: emitReadable",e.length,e.ended),0===e.length&&e.ended?R(this):S(this),null;if(0===(t=w(t,e))&&e.ended)return 0===e.length&&R(this),null;var n,i=e.needReadable;return c("need readable",i),(0===e.length||e.length-t<e.highWaterMark)&&c("length less than watermark",i=!0),e.ended||e.reading?c("reading or ended",i=!1):i&&(c("do read"),e.reading=!0,e.sync=!0,0===e.length&&(e.needReadable=!0),this._read(e.highWaterMark),e.sync=!1,e.reading||(t=w(r,e))),null===(n=t>0?C(t,e):null)?(e.needReadable=!0,t=0):e.length-=t,0===e.length&&(e.ended||(e.needReadable=!0),r!==t&&e.ended&&R(this)),null!==n&&this.emit("data",n),n},m.prototype._read=function(t){this.emit("error",new Error("_read() is not implemented"))},m.prototype.pipe=function(e,i){var o=this,s=this._readableState;switch(s.pipesCount){case 0:s.pipes=e;break;case 1:s.pipes=[s.pipes,e];break;default:s.pipes.push(e)}s.pipesCount+=1,c("pipe count=%d opts=%j",s.pipesCount,i);var a=(!i||!1!==i.end)&&e!==process.stdout&&e!==process.stderr?l:_;function u(t,r){c("onunpipe"),t===o&&r&&!1===r.hasUnpiped&&(r.hasUnpiped=!0,c("cleanup"),e.removeListener("close",m),e.removeListener("finish",g),e.removeListener("drain",f),e.removeListener("error",y),e.removeListener("unpipe",u),o.removeListener("end",l),o.removeListener("end",_),o.removeListener("data",d),h=!0,!s.awaitDrain||e._writableState&&!e._writableState.needDrain||f())}function l(){c("onend"),e.end()}s.endEmitted?t.nextTick(a):o.once("end",a),e.on("unpipe",u);var f=function(t){return function(){var e=t._readableState;c("pipeOnDrain",e.awaitDrain),e.awaitDrain&&e.awaitDrain--,0===e.awaitDrain&&n(t,"data")&&(e.flowing=!0,j(t))}}(o);e.on("drain",f);var h=!1;var p=!1;function d(t){c("ondata"),p=!1,!1!==e.write(t)||p||((1===s.pipesCount&&s.pipes===e||s.pipesCount>1&&-1!==L(s.pipes,e))&&!h&&(c("false write response, pause",s.awaitDrain),s.awaitDrain++,p=!0),o.pause())}function y(t){c("onerror",t),_(),e.removeListener("error",y),0===n(e,"error")&&e.emit("error",t)}function m(){e.removeListener("finish",g),_()}function g(){c("onfinish"),e.removeListener("close",m),_()}function _(){c("unpipe"),o.unpipe(e)}return o.on("data",d),function(t,e,n){if("function"==typeof t.prependListener)return t.prependListener(e,n);t._events&&t._events[e]?r(t._events[e])?t._events[e].unshift(n):t._events[e]=[n,t._events[e]]:t.on(e,n)}(e,"error",y),e.once("close",m),e.once("finish",g),e.emit("pipe",o),s.flowing||(c("pipe resume"),o.resume()),e},m.prototype.unpipe=function(t){var e=this._readableState,r={hasUnpiped:!1};if(0===e.pipesCount)return this;if(1===e.pipesCount)return t&&t!==e.pipes||(t||(t=e.pipes),e.pipes=null,e.pipesCount=0,e.flowing=!1,t&&t.emit("unpipe",this,r)),this;if(!t){var n=e.pipes,i=e.pipesCount;e.pipes=null,e.pipesCount=0,e.flowing=!1;for(var o=0;o<i;o++)n[o].emit("unpipe",this,{hasUnpiped:!1});return this}var s=L(e.pipes,t);return-1===s||(e.pipes.splice(s,1),e.pipesCount-=1,1===e.pipesCount&&(e.pipes=e.pipes[0]),t.emit("unpipe",this,r)),this},m.prototype.on=function(e,r){var n=i.prototype.on.call(this,e,r);if("data"===e)!1!==this._readableState.flowing&&this.resume();else if("readable"===e){var o=this._readableState;o.endEmitted||o.readableListening||(o.readableListening=o.needReadable=!0,o.emittedReadable=!1,o.reading?o.length&&S(this):t.nextTick(O,this))}return n},m.prototype.addListener=m.prototype.on,m.prototype.resume=function(){var e=this._readableState;return e.flowing||(c("resume"),e.flowing=!0,function(e,r){r.resumeScheduled||(r.resumeScheduled=!0,t.nextTick(T,e,r))}(this,e)),this},m.prototype.pause=function(){return c("call pause flowing=%j",this._readableState.flowing),!1!==this._readableState.flowing&&(c("pause"),this._readableState.flowing=!1,this.emit("pause")),this},m.prototype.wrap=function(t){var e=this,r=this._readableState,n=!1;for(var i in t.on("end",function(){if(c("wrapped end"),r.decoder&&!r.ended){var t=r.decoder.end();t&&t.length&&e.push(t)}e.push(null)}),t.on("data",function(i){(c("wrapped data"),r.decoder&&(i=r.decoder.write(i)),r.objectMode&&null==i)||(r.objectMode||i&&i.length)&&(e.push(i)||(n=!0,t.pause()))}),t)void 0===this[i]&&"function"==typeof t[i]&&(this[i]=function(e){return function(){return t[e].apply(t,arguments)}}(i));for(var o=0;o<p.length;o++)t.on(p[o],this.emit.bind(this,p[o]));return this._read=function(e){c("wrapped _read",e),n&&(n=!1,t.resume())},this},Object.defineProperty(m.prototype,"readableHighWaterMark",{enumerable:!1,get:function(){return this._readableState.highWaterMark}}),m._fromList=C,Bf}function Yf(){if(Wf)return zf;Wf=1,zf=n;var t=Mf(),e=Object.create(jr());function r(t,e){var r=this._transformState;r.transforming=!1;var n=r.writecb;if(!n)return this.emit("error",new Error("write callback called multiple times"));r.writechunk=null,r.writecb=null,null!=e&&this.push(e),n(t);var i=this._readableState;i.reading=!1,(i.needReadable||i.length<i.highWaterMark)&&this._read(i.highWaterMark)}function n(e){if(!(this instanceof n))return new n(e);t.call(this,e),this._transformState={afterTransform:r.bind(this),needTransform:!1,transforming:!1,writecb:null,writechunk:null,writeencoding:null},this._readableState.needReadable=!0,this._readableState.sync=!1,e&&("function"==typeof e.transform&&(this._transform=e.transform),"function"==typeof e.flush&&(this._flush=e.flush)),this.on("prefinish",i)}function i(){var t=this;"function"==typeof this._flush?this._flush(function(e,r){o(t,e,r)}):o(this,null,null)}function o(t,e,r){if(e)return t.emit("error",e);if(null!=r&&t.push(r),t._writableState.length)throw new Error("Calling transform done when ws.length != 0");if(t._transformState.transforming)throw new Error("Calling transform done when still transforming");return t.push(null)}return e.inherits=Fr(),e.inherits(n,t),n.prototype.push=function(e,r){return this._transformState.needTransform=!1,t.prototype.push.call(this,e,r)},n.prototype._transform=function(t,e,r){throw new Error("_transform() is not implemented")},n.prototype._write=function(t,e,r){var n=this._transformState;if(n.writecb=r,n.writechunk=t,n.writeencoding=e,!n.transforming){var i=this._readableState;(n.needTransform||i.needReadable||i.length<i.highWaterMark)&&this._read(i.highWaterMark)}},n.prototype._read=function(t){var e=this._transformState;null!==e.writechunk&&e.writecb&&!e.transforming?(e.transforming=!0,this._transform(e.writechunk,e.writeencoding,e.afterTransform)):e.needTransform=!0},n.prototype._destroy=function(e,r){var n=this;t.prototype._destroy.call(this,e,function(t){r(t),n.emit("close")})},zf}function Xf(){return qf||(qf=1,t=wf,e=wf.exports,r=g,"disable"===process.env.READABLE_STREAM&&r?(t.exports=r,(e=t.exports=r.Readable).Readable=r.Readable,e.Writable=r.Writable,e.Duplex=r.Duplex,e.Transform=r.Transform,e.PassThrough=r.PassThrough,e.Stream=r):((e=t.exports=Jf()).Stream=r||e,e.Readable=e,e.Writable=Df(),e.Duplex=Mf(),e.Transform=Yf(),e.PassThrough=function(){if($f)return Hf;$f=1,Hf=r;var t=Yf(),e=Object.create(jr());function r(e){if(!(this instanceof r))return new r(e);t.call(this,e)}return e.inherits=Fr(),e.inherits(r,t),r.prototype._transform=function(t,e,r){r(null,t)},Hf}())),wf.exports;var t,e,r}function th(){if(Gf)return vf.exports;Gf=1;var t=Xf();function e(e,r,n){void 0===n&&(n=r,r=e,e=null),t.Duplex.call(this,e),"function"!=typeof n.read&&(n=new t.Readable(e).wrap(n)),this._writable=r,this._readable=n,this._waiting=!1;var i=this;r.once("finish",function(){i.end()}),this.once("finish",function(){r.end()}),n.on("readable",function(){i._waiting&&(i._waiting=!1,i._read())}),n.once("end",function(){i.push(null)}),e&&void 0!==e.bubbleErrors&&!e.bubbleErrors||(r.on("error",function(t){i.emit("error",t)}),n.on("error",function(t){i.emit("error",t)}))}return e.prototype=Object.create(t.Duplex.prototype,{constructor:{value:e}}),e.prototype._write=function(t,e,r){this._writable.write(t,e,r)},e.prototype._read=function(){for(var t,e=0;null!==(t=this._readable.read());)this.push(t),e++;0===e&&(this._waiting=!0)},vf.exports=function(t,r,n){return new e(t,r,n)},vf.exports.DuplexWrapper=e,vf.exports}var eh,rh,nh={},ih={};function oh(){return eh||(eh=1,ih.fromCallback=function(t){return Object.defineProperty(function(...e){if("function"!=typeof e[e.length-1])return new Promise((r,n)=>{e.push((t,e)=>null!=t?n(t):r(e)),t.apply(this,e)});t.apply(this,e)},"name",{value:t.name})},ih.fromPromise=function(t){return Object.defineProperty(function(...e){const r=e[e.length-1];if("function"!=typeof r)return t.apply(this,e);e.pop(),t.apply(this,e).then(t=>r(null,t),r)},"name",{value:t.name})}),ih}function sh(){return rh||(rh=1,function(t){const e=oh().fromCallback,r=hr(),n=["access","appendFile","chmod","chown","close","copyFile","cp","fchmod","fchown","fdatasync","fstat","fsync","ftruncate","futimes","glob","lchmod","lchown","lutimes","link","lstat","mkdir","mkdtemp","open","opendir","readdir","readFile","readlink","realpath","rename","rm","rmdir","stat","statfs","symlink","truncate","unlink","utimes","writeFile"].filter(t=>"function"==typeof r[t]);Object.assign(t,r),n.forEach(n=>{t[n]=e(r[n])}),t.exists=function(t,e){return"function"==typeof e?r.exists(t,e):new Promise(e=>r.exists(t,e))},t.read=function(t,e,n,i,o,s){return"function"==typeof s?r.read(t,e,n,i,o,s):new Promise((s,a)=>{r.read(t,e,n,i,o,(t,e,r)=>{if(t)return a(t);s({bytesRead:e,buffer:r})})})},t.write=function(t,e,...n){return"function"==typeof n[n.length-1]?r.write(t,e,...n):new Promise((i,o)=>{r.write(t,e,...n,(t,e,r)=>{if(t)return o(t);i({bytesWritten:e,buffer:r})})})},t.readv=function(t,e,...n){return"function"==typeof n[n.length-1]?r.readv(t,e,...n):new Promise((i,o)=>{r.readv(t,e,...n,(t,e,r)=>{if(t)return o(t);i({bytesRead:e,buffers:r})})})},t.writev=function(t,e,...n){return"function"==typeof n[n.length-1]?r.writev(t,e,...n):new Promise((i,o)=>{r.writev(t,e,...n,(t,e,r)=>{if(t)return o(t);i({bytesWritten:e,buffers:r})})})},"function"==typeof r.realpath.native?t.realpath.native=e(r.realpath.native):process.emitWarning("fs.realpath.native is not a function. Is fs being monkey-patched?","Warning","fs-extra-WARN0003")}(nh)),nh}var ah,uh,ch,lh,fh,hh,ph,dh,yh,mh,gh,_h,bh,vh,wh,Sh,Eh,kh,xh,Oh,Th,jh,Ch,Rh,Ph,Lh,Fh,Ah,Ih,Dh,Mh,Nh,Bh,Uh,zh,Wh,Hh,$h,qh,Gh,Vh,Qh,Zh,Kh,Jh,Yh,Xh,tp,ep,rp,np,ip,op,sp,ap,up,cp,lp,fp={},hp={};function pp(){if(uh)return fp;uh=1;const t=sh(),{checkPath:e}=function(){if(ah)return hp;ah=1;const t=y;return hp.checkPath=function(e){if("win32"===process.platform&&/[<>:"|?*]/.test(e.replace(t.parse(e).root,""))){const t=new Error(`Path contains invalid characters: ${e}`);throw t.code="EINVAL",t}},hp}(),r=t=>"number"==typeof t?t:{mode:511,...t}.mode;return fp.makeDir=async(n,i)=>(e(n),t.mkdir(n,{mode:r(i),recursive:!0})),fp.makeDirSync=(n,i)=>(e(n),t.mkdirSync(n,{mode:r(i),recursive:!0})),fp}function dp(){if(lh)return ch;lh=1;const t=oh().fromPromise,{makeDir:e,makeDirSync:r}=pp(),n=t(e);return ch={mkdirs:n,mkdirsSync:r,mkdirp:n,mkdirpSync:r,ensureDir:n,ensureDirSync:r}}function yp(){if(hh)return fh;hh=1;const t=oh().fromPromise,e=sh();return fh={pathExists:t(function(t){return e.access(t).then(()=>!0).catch(()=>!1)}),pathExistsSync:e.existsSync},fh}function mp(){if(dh)return ph;dh=1;const t=sh(),e=oh().fromPromise;return ph={utimesMillis:e(async function(e,r,n){const i=await t.open(e,"r+");let o=null;try{await t.futimes(i,r,n)}finally{try{await t.close(i)}catch(t){o=t}}if(o)throw o}),utimesMillisSync:function(e,r,n){const i=t.openSync(e,"r+");return t.futimesSync(i,r,n),t.closeSync(i)}},ph}function gp(){if(mh)return yh;mh=1;const t=sh(),e=y,r=oh().fromPromise;function n(t,e){return void 0!==e.ino&&void 0!==e.dev&&e.ino===t.ino&&e.dev===t.dev}function i(t,r){const n=e.resolve(t).split(e.sep).filter(t=>t),i=e.resolve(r).split(e.sep).filter(t=>t);return n.every((t,e)=>i[e]===t)}function o(t,e,r){return`Cannot ${r} '${t}' to a subdirectory of itself, '${e}'.`}return yh={checkPaths:r(async function(r,s,a,u){const{srcStat:c,destStat:l}=await function(e,r,n){const i=n.dereference?e=>t.stat(e,{bigint:!0}):e=>t.lstat(e,{bigint:!0});return Promise.all([i(e),i(r).catch(t=>{if("ENOENT"===t.code)return null;throw t})]).then(([t,e])=>({srcStat:t,destStat:e}))}(r,s,u);if(l){if(n(c,l)){const t=e.basename(r),n=e.basename(s);if("move"===a&&t!==n&&t.toLowerCase()===n.toLowerCase())return{srcStat:c,destStat:l,isChangingCase:!0};throw new Error("Source and destination must not be the same.")}if(c.isDirectory()&&!l.isDirectory())throw new Error(`Cannot overwrite non-directory '${s}' with directory '${r}'.`);if(!c.isDirectory()&&l.isDirectory())throw new Error(`Cannot overwrite directory '${s}' with non-directory '${r}'.`)}if(c.isDirectory()&&i(r,s))throw new Error(o(r,s,a));return{srcStat:c,destStat:l}}),checkPathsSync:function(r,s,a,u){const{srcStat:c,destStat:l}=function(e,r,n){let i;const o=n.dereference?e=>t.statSync(e,{bigint:!0}):e=>t.lstatSync(e,{bigint:!0}),s=o(e);try{i=o(r)}catch(t){if("ENOENT"===t.code)return{srcStat:s,destStat:null};throw t}return{srcStat:s,destStat:i}}(r,s,u);if(l){if(n(c,l)){const t=e.basename(r),n=e.basename(s);if("move"===a&&t!==n&&t.toLowerCase()===n.toLowerCase())return{srcStat:c,destStat:l,isChangingCase:!0};throw new Error("Source and destination must not be the same.")}if(c.isDirectory()&&!l.isDirectory())throw new Error(`Cannot overwrite non-directory '${s}' with directory '${r}'.`);if(!c.isDirectory()&&l.isDirectory())throw new Error(`Cannot overwrite directory '${s}' with non-directory '${r}'.`)}if(c.isDirectory()&&i(r,s))throw new Error(o(r,s,a));return{srcStat:c,destStat:l}},checkParentPaths:r(async function r(i,s,a,u){const c=e.resolve(e.dirname(i)),l=e.resolve(e.dirname(a));if(l===c||l===e.parse(l).root)return;let f;try{f=await t.stat(l,{bigint:!0})}catch(t){if("ENOENT"===t.code)return;throw t}if(n(s,f))throw new Error(o(i,a,u));return r(i,s,l,u)}),checkParentPathsSync:function r(i,s,a,u){const c=e.resolve(e.dirname(i)),l=e.resolve(e.dirname(a));if(l===c||l===e.parse(l).root)return;let f;try{f=t.statSync(l,{bigint:!0})}catch(t){if("ENOENT"===t.code)return;throw t}if(n(s,f))throw new Error(o(i,a,u));return r(i,s,l,u)},isSrcSubdir:i,areIdentical:n},yh}function _p(){if(vh)return bh;vh=1;const t=sh(),e=y,{mkdirs:r}=dp(),{pathExists:n}=yp(),{utimesMillis:i}=mp(),o=gp(),{asyncIteratorConcurrentProcess:s}=(_h||(_h=1,gh={asyncIteratorConcurrentProcess:async function(t,e){const r=[];for await(const n of t)r.push(e(n).then(()=>null,t=>t??new Error("unknown error")));await Promise.all(r.map(t=>t.then(t=>{if(null!==t)throw t})))}}),gh);async function a(t,e,r){return!r.filter||r.filter(t,e)}async function u(r,n,i,l){const f=l.dereference?t.stat:t.lstat,h=await f(n);if(h.isDirectory())return async function(r,n,i,c,l){n||await t.mkdir(c);await s(await t.opendir(i),async t=>{const r=e.join(i,t.name),n=e.join(c,t.name);if(await a(r,n,l)){const{destStat:t}=await o.checkPaths(r,n,"copy",l);await u(t,r,n,l)}}),n||await t.chmod(c,r.mode)}(h,r,n,i,l);if(h.isFile()||h.isCharacterDevice()||h.isBlockDevice())return async function(e,r,n,i,o){if(!r)return c(e,n,i,o);if(o.overwrite)return await t.unlink(i),c(e,n,i,o);if(o.errorOnExist)throw new Error(`'${i}' already exists`)}(h,r,n,i,l);if(h.isSymbolicLink())return async function(r,n,i,s){let a=await t.readlink(n);s.dereference&&(a=e.resolve(process.cwd(),a));if(!r)return t.symlink(a,i);let u=null;try{u=await t.readlink(i)}catch(e){if("EINVAL"===e.code||"UNKNOWN"===e.code)return t.symlink(a,i);throw e}s.dereference&&(u=e.resolve(process.cwd(),u));if(o.isSrcSubdir(a,u))throw new Error(`Cannot copy '${a}' to a subdirectory of itself, '${u}'.`);if(o.isSrcSubdir(u,a))throw new Error(`Cannot overwrite '${u}' with '${a}'.`);return await t.unlink(i),t.symlink(a,i)}(r,n,i,l);if(h.isSocket())throw new Error(`Cannot copy a socket file: ${n}`);if(h.isFIFO())throw new Error(`Cannot copy a FIFO pipe: ${n}`);throw new Error(`Unknown file: ${n}`)}async function c(e,r,n,o){if(await t.copyFile(r,n),o.preserveTimestamps){128&e.mode||await function(e,r){return t.chmod(e,128|r)}(n,e.mode);const o=await t.stat(r);await i(n,o.atime,o.mtime)}return t.chmod(n,e.mode)}return bh=async function(t,i,s={}){"function"==typeof s&&(s={filter:s}),s.clobber=!("clobber"in s)||!!s.clobber,s.overwrite="overwrite"in s?!!s.overwrite:s.clobber,s.preserveTimestamps&&"ia32"===process.arch&&process.emitWarning("Using the preserveTimestamps option in 32-bit node is not recommended;\n\n\tsee https://github.com/jprichardson/node-fs-extra/issues/269","Warning","fs-extra-WARN0001");const{srcStat:c,destStat:l}=await o.checkPaths(t,i,"copy",s);if(await o.checkParentPaths(t,c,i,"copy"),!await a(t,i,s))return;const f=e.dirname(i);await n(f)||await r(f),await u(l,t,i,s)}}function bp(){if(Sh)return wh;Sh=1;const t=hr(),e=y,r=dp().mkdirsSync,n=mp().utimesMillisSync,i=gp();function o(r,n,o,c){const l=(c.dereference?t.statSync:t.lstatSync)(n);if(l.isDirectory())return function(e,r,n,i,o){return r?u(n,i,o):function(e,r,n,i){return t.mkdirSync(n),u(r,n,i),a(n,e)}(e.mode,n,i,o)}(l,r,n,o,c);if(l.isFile()||l.isCharacterDevice()||l.isBlockDevice())return function(e,r,n,i,o){return r?function(e,r,n,i){if(i.overwrite)return t.unlinkSync(n),s(e,r,n,i);if(i.errorOnExist)throw new Error(`'${n}' already exists`)}(e,n,i,o):s(e,n,i,o)}(l,r,n,o,c);if(l.isSymbolicLink())return function(r,n,o,s){let a=t.readlinkSync(n);s.dereference&&(a=e.resolve(process.cwd(),a));if(r){let r;try{r=t.readlinkSync(o)}catch(e){if("EINVAL"===e.code||"UNKNOWN"===e.code)return t.symlinkSync(a,o);throw e}if(s.dereference&&(r=e.resolve(process.cwd(),r)),i.isSrcSubdir(a,r))throw new Error(`Cannot copy '${a}' to a subdirectory of itself, '${r}'.`);if(i.isSrcSubdir(r,a))throw new Error(`Cannot overwrite '${r}' with '${a}'.`);return function(e,r){return t.unlinkSync(r),t.symlinkSync(e,r)}(a,o)}return t.symlinkSync(a,o)}(r,n,o,c);if(l.isSocket())throw new Error(`Cannot copy a socket file: ${n}`);if(l.isFIFO())throw new Error(`Cannot copy a FIFO pipe: ${n}`);throw new Error(`Unknown file: ${n}`)}function s(e,r,i,o){return t.copyFileSync(r,i),o.preserveTimestamps&&function(e,r,i){(function(t){return!(128&t)})(e)&&function(t,e){a(t,128|e)}(i,e);(function(e,r){const i=t.statSync(e);n(r,i.atime,i.mtime)})(r,i)}(e.mode,r,i),a(i,e.mode)}function a(e,r){return t.chmodSync(e,r)}function u(e,r,n){const i=t.opendirSync(e);try{let t;for(;null!==(t=i.readSync());)c(t.name,e,r,n)}finally{i.closeSync()}}function c(t,r,n,s){const a=e.join(r,t),u=e.join(n,t);if(s.filter&&!s.filter(a,u))return;const{destStat:c}=i.checkPathsSync(a,u,"copy",s);return o(c,a,u,s)}return wh=function(n,s,a){"function"==typeof a&&(a={filter:a}),(a=a||{}).clobber=!("clobber"in a)||!!a.clobber,a.overwrite="overwrite"in a?!!a.overwrite:a.clobber,a.preserveTimestamps&&"ia32"===process.arch&&process.emitWarning("Using the preserveTimestamps option in 32-bit node is not recommended;\n\n\tsee https://github.com/jprichardson/node-fs-extra/issues/269","Warning","fs-extra-WARN0002");const{srcStat:u,destStat:c}=i.checkPathsSync(n,s,"copy",a);if(i.checkParentPathsSync(n,u,s,"copy"),a.filter&&!a.filter(n,s))return;const l=e.dirname(s);return t.existsSync(l)||r(l),o(c,n,s,a)}}function vp(){if(kh)return Eh;kh=1;const t=oh().fromPromise;return Eh={copy:t(_p()),copySync:bp()}}function wp(){if(Oh)return xh;Oh=1;const t=hr(),e=oh().fromCallback;return xh={remove:e(function(e,r){t.rm(e,{recursive:!0,force:!0},r)}),removeSync:function(e){t.rmSync(e,{recursive:!0,force:!0})}},xh}function Sp(){if(jh)return Th;jh=1;const t=oh().fromPromise,e=sh(),r=y,n=dp(),i=wp(),o=t(async function(t){let o;try{o=await e.readdir(t)}catch{return n.mkdirs(t)}return Promise.all(o.map(e=>i.remove(r.join(t,e))))});function s(t){let o;try{o=e.readdirSync(t)}catch{return n.mkdirsSync(t)}o.forEach(e=>{e=r.join(t,e),i.removeSync(e)})}return Th={emptyDirSync:s,emptydirSync:s,emptyDir:o,emptydir:o}}function Ep(){if(Nh)return Mh;Nh=1;const t=oh().fromPromise,e=y,r=sh(),{mkdirs:n,mkdirsSync:i}=dp(),{symlinkPaths:o,symlinkPathsSync:s}=function(){if(Ah)return Fh;Ah=1;const t=y,e=sh(),{pathExists:r}=yp(),n=oh().fromPromise;return Fh={symlinkPaths:n(async function(n,i){if(t.isAbsolute(n)){try{await e.lstat(n)}catch(t){throw t.message=t.message.replace("lstat","ensureSymlink"),t}return{toCwd:n,toDst:n}}const o=t.dirname(i),s=t.join(o,n);if(await r(s))return{toCwd:s,toDst:n};try{await e.lstat(n)}catch(t){throw t.message=t.message.replace("lstat","ensureSymlink"),t}return{toCwd:n,toDst:t.relative(o,n)}}),symlinkPathsSync:function(r,n){if(t.isAbsolute(r)){if(!e.existsSync(r))throw new Error("absolute srcpath does not exist");return{toCwd:r,toDst:r}}const i=t.dirname(n),o=t.join(i,r);if(e.existsSync(o))return{toCwd:o,toDst:r};if(!e.existsSync(r))throw new Error("relative srcpath does not exist");return{toCwd:r,toDst:t.relative(i,r)}}}}(),{symlinkType:a,symlinkTypeSync:u}=function(){if(Dh)return Ih;Dh=1;const t=sh(),e=oh().fromPromise;return Ih={symlinkType:e(async function(e,r){if(r)return r;let n;try{n=await t.lstat(e)}catch{return"file"}return n&&n.isDirectory()?"dir":"file"}),symlinkTypeSync:function(e,r){if(r)return r;let n;try{n=t.lstatSync(e)}catch{return"file"}return n&&n.isDirectory()?"dir":"file"}}}(),{pathExists:c}=yp(),{areIdentical:l}=gp();return Mh={createSymlink:t(async function(t,i,s){let u;try{u=await r.lstat(i)}catch{}if(u&&u.isSymbolicLink()){const[e,n]=await Promise.all([r.stat(t),r.stat(i)]);if(l(e,n))return}const f=await o(t,i);t=f.toDst;const h=await a(f.toCwd,s),p=e.dirname(i);return await c(p)||await n(p),r.symlink(t,i,h)}),createSymlinkSync:function(t,n,o){let a;try{a=r.lstatSync(n)}catch{}if(a&&a.isSymbolicLink()){const e=r.statSync(t),i=r.statSync(n);if(l(e,i))return}const c=s(t,n);t=c.toDst,o=u(c.toCwd,o);const f=e.dirname(n);return r.existsSync(f)||i(f),r.symlinkSync(t,n,o)}},Mh}function kp(){if(Uh)return Bh;Uh=1;const{createFile:t,createFileSync:e}=function(){if(Rh)return Ch;Rh=1;const t=oh().fromPromise,e=y,r=sh(),n=dp();return Ch={createFile:t(async function(t){let i;try{i=await r.stat(t)}catch{}if(i&&i.isFile())return;const o=e.dirname(t);let s=null;try{s=await r.stat(o)}catch(e){if("ENOENT"===e.code)return await n.mkdirs(o),void await r.writeFile(t,"");throw e}s.isDirectory()?await r.writeFile(t,""):await r.readdir(o)}),createFileSync:function(t){let i;try{i=r.statSync(t)}catch{}if(i&&i.isFile())return;const o=e.dirname(t);try{r.statSync(o).isDirectory()||r.readdirSync(o)}catch(t){if(!t||"ENOENT"!==t.code)throw t;n.mkdirsSync(o)}r.writeFileSync(t,"")}},Ch}(),{createLink:r,createLinkSync:n}=function(){if(Lh)return Ph;Lh=1;const t=oh().fromPromise,e=y,r=sh(),n=dp(),{pathExists:i}=yp(),{areIdentical:o}=gp();return Ph={createLink:t(async function(t,s){let a,u;try{a=await r.lstat(s)}catch{}try{u=await r.lstat(t)}catch(t){throw t.message=t.message.replace("lstat","ensureLink"),t}if(a&&o(u,a))return;const c=e.dirname(s);await i(c)||await n.mkdirs(c),await r.link(t,s)}),createLinkSync:function(t,i){let s;try{s=r.lstatSync(i)}catch{}try{const e=r.lstatSync(t);if(s&&o(e,s))return}catch(t){throw t.message=t.message.replace("lstat","ensureLink"),t}const a=e.dirname(i);return r.existsSync(a)||n.mkdirsSync(a),r.linkSync(t,i)}},Ph}(),{createSymlink:i,createSymlinkSync:o}=Ep();return Bh={createFile:t,createFileSync:e,ensureFile:t,ensureFileSync:e,createLink:r,createLinkSync:n,ensureLink:r,ensureLinkSync:n,createSymlink:i,createSymlinkSync:o,ensureSymlink:i,ensureSymlinkSync:o}}function xp(){if(Wh)return zh;return Wh=1,zh={stringify:function(t,{EOL:e="\n",finalEOL:r=!0,replacer:n=null,spaces:i}={}){const o=r?e:"";return JSON.stringify(t,n,i).replace(/\n/g,e)+o},stripBom:function(t){return Buffer.isBuffer(t)&&(t=t.toString("utf8")),t.replace(/^\uFEFF/,"")}}}function Op(){if(Gh)return qh;Gh=1;const t=function(){if($h)return Hh;let t;$h=1;try{t=hr()}catch(e){t=p}const e=oh(),{stringify:r,stripBom:n}=xp(),i=e.fromPromise(async function(r,i={}){"string"==typeof i&&(i={encoding:i});const o=i.fs||t,s=!("throws"in i)||i.throws;let a,u=await e.fromCallback(o.readFile)(r,i);u=n(u);try{a=JSON.parse(u,i?i.reviver:null)}catch(t){if(s)throw t.message=`${r}: ${t.message}`,t;return null}return a}),o=e.fromPromise(async function(n,i,o={}){const s=o.fs||t,a=r(i,o);await e.fromCallback(s.writeFile)(n,a,o)});return Hh={readFile:i,readFileSync:function(e,r={}){"string"==typeof r&&(r={encoding:r});const i=r.fs||t,o=!("throws"in r)||r.throws;try{let t=i.readFileSync(e,r);return t=n(t),JSON.parse(t,r.reviver)}catch(t){if(o)throw t.message=`${e}: ${t.message}`,t;return null}},writeFile:o,writeFileSync:function(e,n,i={}){const o=i.fs||t,s=r(n,i);return o.writeFileSync(e,s,i)}},Hh}();return qh={readJson:t.readFile,readJsonSync:t.readFileSync,writeJson:t.writeFile,writeJsonSync:t.writeFileSync}}function Tp(){if(Qh)return Vh;Qh=1;const t=oh().fromPromise,e=sh(),r=y,n=dp(),i=yp().pathExists;return Vh={outputFile:t(async function(t,o,s="utf-8"){const a=r.dirname(t);return await i(a)||await n.mkdirs(a),e.writeFile(t,o,s)}),outputFileSync:function(t,...i){const o=r.dirname(t);e.existsSync(o)||n.mkdirsSync(o),e.writeFileSync(t,...i)}},Vh}function jp(){if(tp)return Xh;tp=1;const t=oh().fromPromise,e=Op();return e.outputJson=t(function(){if(Kh)return Zh;Kh=1;const{stringify:t}=xp(),{outputFile:e}=Tp();return Zh=async function(r,n,i={}){const o=t(n,i);await e(r,o,i)},Zh}()),e.outputJsonSync=function(){if(Yh)return Jh;Yh=1;const{stringify:t}=xp(),{outputFileSync:e}=Tp();return Jh=function(r,n,i){const o=t(n,i);e(r,o,i)},Jh}(),e.outputJSON=e.outputJson,e.outputJSONSync=e.outputJsonSync,e.writeJSON=e.writeJson,e.writeJSONSync=e.writeJsonSync,e.readJSON=e.readJson,e.readJSONSync=e.readJsonSync,Xh=e}function Cp(){if(rp)return ep;rp=1;const t=sh(),e=y,{copy:r}=vp(),{remove:n}=wp(),{mkdirp:i}=dp(),{pathExists:o}=yp(),s=gp();return ep=async function(a,u,c={}){const l=c.overwrite||c.clobber||!1,{srcStat:f,isChangingCase:h=!1}=await s.checkPaths(a,u,"move",c);await s.checkParentPaths(a,f,u,"move");const p=e.dirname(u);return e.parse(p).root!==p&&await i(p),async function(e,i,s,a){if(!a)if(s)await n(i);else if(await o(i))throw new Error("dest already exists.");try{await t.rename(e,i)}catch(t){if("EXDEV"!==t.code)throw t;await async function(t,e,i){const o={overwrite:i,errorOnExist:!0,preserveTimestamps:!0};return await r(t,e,o),n(t)}(e,i,s)}}(a,u,l,h)}}function Rp(){if(ip)return np;ip=1;const t=hr(),e=y,r=vp().copySync,n=wp().removeSync,i=dp().mkdirpSync,o=gp();function s(e,i,o){try{t.renameSync(e,i)}catch(t){if("EXDEV"!==t.code)throw t;return function(t,e,i){const o={overwrite:i,errorOnExist:!0,preserveTimestamps:!0};return r(t,e,o),n(t)}(e,i,o)}}return np=function(r,a,u){const c=(u=u||{}).overwrite||u.clobber||!1,{srcStat:l,isChangingCase:f=!1}=o.checkPathsSync(r,a,"move",u);return o.checkParentPathsSync(r,l,a,"move"),function(t){const r=e.dirname(t),n=e.parse(r);return n.root===r}(a)||i(e.dirname(a)),function(e,r,i,o){if(o)return s(e,r,i);if(i)return n(r),s(e,r,i);if(t.existsSync(r))throw new Error("dest already exists.");return s(e,r,i)}(r,a,c,f)},np}function Pp(){if(sp)return op;sp=1;const t=oh().fromPromise;return op={move:t(Cp()),moveSync:Rp()}}function Lp(){return up?ap:(up=1,ap={...sh(),...vp(),...Sp(),...kp(),...jp(),...dp(),...Pp(),...Tp(),...yp(),...wp()})}var Fp,Ap,Ip,Dp,Mp,Np={exports:{}};function Bp(){if(Fp)return Np.exports;Fp=1;for(var t=4294967296,e=[],r=0;r<256;r++)e[r]=(r>15?"":"0")+r.toString(16);var n=Np.exports=function(t,e){t instanceof Buffer?(this.buffer=t,this.offset=e||0):"[object Uint8Array]"==Object.prototype.toString.call(t)?(this.buffer=new Buffer(t),this.offset=e||0):(this.buffer=this.buffer||new Buffer(8),this.offset=0,this.setValue.apply(this,arguments))};return n.MAX_INT=Math.pow(2,53),n.MIN_INT=-Math.pow(2,53),n.prototype={constructor:n,_2scomp:function(){for(var t=this.buffer,e=this.offset,r=1,n=e+7;n>=e;n--){var i=(255^t[n])+r;t[n]=255&i,r=i>>8}},setValue:function(e,r){var n=!1;if(1==arguments.length)if("number"==typeof e){if(n=e<0,r=(e=Math.abs(e))%t,(e/=t)>t)throw new RangeError(e+" is outside Int64 range");e|=0}else{if("string"!=typeof e)throw new Error(e+" must be a Number or String");r=(e=(e+"").replace(/^0x/,"")).substr(-8),e=e.length>8?e.substr(0,e.length-8):"",e=parseInt(e,16),r=parseInt(r,16)}for(var i=this.buffer,o=this.offset,s=7;s>=0;s--)i[o+s]=255&r,r=4==s?e:r>>>8;n&&this._2scomp()},toNumber:function(t){for(var e=this.buffer,r=this.offset,i=128&e[r],o=0,s=1,a=7,u=1;a>=0;a--,u*=256){var c=e[r+a];i&&(s=(c=(255^c)+s)>>8,c&=255),o+=c*u}return!t&&o>=n.MAX_INT?i?-1/0:1/0:i?-o:o},valueOf:function(){return this.toNumber(!1)},toString:function(t){return this.valueOf().toString(t||10)},toOctetString:function(t){for(var r=new Array(8),n=this.buffer,i=this.offset,o=0;o<8;o++)r[o]=e[n[i+o]];return r.join(t||"")},toBuffer:function(t){if(t&&0===this.offset)return this.buffer;var e=new Buffer(8);return this.buffer.copy(e,0,this.offset,this.offset+8),e},copy:function(t,e){this.buffer.copy(t,e||0,this.offset,this.offset+8)},compare:function(t){if((128&this.buffer[this.offset])!=(128&t.buffer[t.offset]))return t.buffer[t.offset]-this.buffer[this.offset];for(var e=0;e<8;e++)if(this.buffer[this.offset+e]!==t.buffer[t.offset+e])return this.buffer[this.offset+e]-t.buffer[t.offset+e];return 0},equals:function(t){return 0===this.compare(t)},inspect:function(){return"[Int64 value:"+this+" octets:"+this.toOctetString(" ")+"]"}},Np.exports}function Up(){if(Ip)return Ap;Ip=1;const t=Bp();let e,r=g;function n(t,r){e||function(){let t,r,n;for(e=[],r=0;r<256;r++){for(t=r,n=0;n<8;n++)t=1&t?3988292384^t>>>1:t>>>=1;e[r]=t>>>0}}(),t.charCodeAt&&(t=t.charCodeAt(0));return(r.readUInt32BE()>>8&16777215^e[255&(r.readUInt32BE()^t>>>0)])>>>0}function i(t,e){const r=65535&t,n=65535&e;return(((t>>16&65535)*n+r*(e>>16&65535)&65535)<<16>>>0)+r*n}function o(){if(!(this instanceof o))return new o;this.key0=Buffer.allocUnsafe(4),this.key1=Buffer.allocUnsafe(4),this.key2=Buffer.allocUnsafe(4),this.key0.writeUInt32BE(305419896,0),this.key1.writeUInt32BE(591751049,0),this.key2.writeUInt32BE(878082192,0)}return r.Writable&&r.Writable.prototype.destroy||(r=ws()),o.prototype.update=function(e){this.key0.writeUInt32BE(n(e,this.key0)),this.key1.writeUInt32BE((255&this.key0.readUInt32BE())+this.key1.readUInt32BE()>>>0);const r=new t(i(this.key1.readUInt32BE(),134775813)+1&4294967295),o=Buffer.alloc(8);r.copy(o,0),o.copy(this.key1,0,4,8),this.key2.writeUInt32BE(n((this.key1.readUInt32BE()>>24&255)>>>0,this.key2))},o.prototype.decryptByte=function(t){const e=(2|this.key2.readUInt32BE())>>>0;return t^=i(e,1^e)>>8&255,this.update(t),t},o.prototype.stream=function(){const t=r.Transform(),e=this;return t._transform=function(t,r,n){for(let r=0;r<t.length;r++)t[r]=e.decryptByte(t[r]);this.push(t),n()},t},Ap=o}function zp(){if(Mp)return Dp;Mp=1;const t=Up(),e=hf(),r=g,n=S,i=yf(),o=mf(),s=df();return Dp=function(a,u,c,l,f){const h=e(),p=r.PassThrough(),d=a.stream(u,f);return d.pipe(h).on("error",function(t){p.emit("error",t)}),p.vars=h.pull(30).then(function(e){let r=s.parse(e,[["signature",4],["versionsNeededToExtract",2],["flags",2],["compressionMethod",2],["lastModifiedTime",2],["lastModifiedDate",2],["crc32",4],["compressedSize",4],["uncompressedSize",4],["fileNameLength",2],["extraFieldLength",2]]);return r.lastModifiedDateTime=o(r.lastModifiedDate,r.lastModifiedTime),h.pull(r.fileNameLength).then(function(t){return r.fileName=t.toString("utf8"),h.pull(r.extraFieldLength)}).then(function(e){let n;return r.extra=i(e,r),l&&l.compressedSize&&(r=l),1&r.flags&&(n=h.pull(12).then(function(e){if(!c)throw new Error("MISSING_PASSWORD");const n=t();String(c).split("").forEach(function(t){n.update(t)});for(let t=0;t<e.length;t++)e[t]=n.decryptByte(e[t]);r.decrypt=n,r.compressedSize-=12;const i=8&r.flags?r.lastModifiedTime>>8&255:r.crc32>>24&255;if(e[11]!==i)throw new Error("BAD_PASSWORD");return r})),Promise.resolve(n).then(function(){return p.emit("vars",r),r})})}),p.vars.then(function(t){const e=!(8&t.flags)||t.compressedSize>0;let i;const o=t.compressionMethod?n.createInflateRaw():r.PassThrough();e?(p.size=t.uncompressedSize,i=t.compressedSize):(i=Buffer.alloc(4),i.writeUInt32LE(134695760,0));let s=h.stream(i);t.decrypt&&(s=s.pipe(t.decrypt.stream())),s.pipe(o).on("error",function(t){p.emit("error",t)}).pipe(p).on("finish",function(){d.destroy?d.destroy():d.abort?d.abort():d.close?d.close():d.push?d.push():console.log("warning - unable to close stream")})}).catch(function(t){p.emit("error",t)}),p},Dp}var Wp,Hp,$p,qp={exports:{}},Gp={exports:{}};function Vp(){if(Wp)return Gp.exports;Wp=1;var t=function(){return void 0===this}();if(t)Gp.exports={freeze:Object.freeze,defineProperty:Object.defineProperty,getDescriptor:Object.getOwnPropertyDescriptor,keys:Object.keys,names:Object.getOwnPropertyNames,getPrototypeOf:Object.getPrototypeOf,isArray:Array.isArray,isES5:t,propertyIsWritable:function(t,e){var r=Object.getOwnPropertyDescriptor(t,e);return!(r&&!r.writable&&!r.set)}};else{var e={}.hasOwnProperty,r={}.toString,n={}.constructor.prototype,i=function(t){var r=[];for(var n in t)e.call(t,n)&&r.push(n);return r};Gp.exports={isArray:function(t){try{return"[object Array]"===r.call(t)}catch(t){return!1}},keys:i,names:i,defineProperty:function(t,e,r){return t[e]=r.value,t},getDescriptor:function(t,e){return{value:t[e]}},freeze:function(t){return t},getPrototypeOf:function(t){try{return Object(t).constructor.prototype}catch(t){return n}},isES5:t,propertyIsWritable:function(){return!0}}}return Gp.exports}function Qp(){if($p)return Hp;$p=1;var t,e=Vp(),r="undefined"==typeof navigator,n={e:{}},i="undefined"!=typeof self?self:"undefined"!=typeof window?window:void 0!==I?I:void 0!==Hp?Hp:null;function o(){try{var e=t;return t=null,e.apply(this,arguments)}catch(t){return n.e=t,n}}function s(t){return null==t||!0===t||!1===t||"string"==typeof t||"number"==typeof t}function a(t,r,n){if(s(t))return t;var i={value:n,configurable:!0,enumerable:!1,writable:!0};return e.defineProperty(t,r,i),t}var u=function(){var t=[Array.prototype,Object.prototype,Function.prototype],r=function(e){for(var r=0;r<t.length;++r)if(t[r]===e)return!0;return!1};if(e.isES5){var n=Object.getOwnPropertyNames;return function(t){for(var i=[],o=Object.create(null);null!=t&&!r(t);){var s;try{s=n(t)}catch(t){return i}for(var a=0;a<s.length;++a){var u=s[a];if(!o[u]){o[u]=!0;var c=Object.getOwnPropertyDescriptor(t,u);null!=c&&null==c.get&&null==c.set&&i.push(u)}}t=e.getPrototypeOf(t)}return i}}var i={}.hasOwnProperty;return function(e){if(r(e))return[];var n=[];t:for(var o in e)if(i.call(e,o))n.push(o);else{for(var s=0;s<t.length;++s)if(i.call(t[s],o))continue t;n.push(o)}return n}}(),c=/this\s*\.\s*\S+\s*=/;var l=/^[a-z$_][a-z$_0-9]*$/i;function f(t){try{return t+""}catch(t){return"[no string representation]"}}function h(t){return t instanceof Error||null!==t&&"object"==typeof t&&"string"==typeof t.message&&"string"==typeof t.name}function p(t){return h(t)&&e.propertyIsWritable(t,"stack")}var d="stack"in new Error?function(t){return p(t)?t:new Error(f(t))}:function(t){if(p(t))return t;try{throw new Error(f(t))}catch(t){return t}};function y(t){return{}.toString.call(t)}var m=function(t){return e.isArray(t)?t:null};if("undefined"!=typeof Symbol&&Symbol.iterator){var g="function"==typeof Array.from?function(t){return Array.from(t)}:function(t){for(var e,r=[],n=t[Symbol.iterator]();!(e=n.next()).done;)r.push(e.value);return r};m=function(t){return e.isArray(t)?t:null!=t&&"function"==typeof t[Symbol.iterator]?g(t):null}}var _,b="undefined"!=typeof process&&"[object process]"===y(process).toLowerCase(),v="undefined"!=typeof process&&void 0!==process.env;var w,S={setReflectHandler:function(t){_=t},isClass:function(t){try{if("function"==typeof t){var r=e.names(t.prototype),n=e.isES5&&r.length>1,i=r.length>0&&!(1===r.length&&"constructor"===r[0]),o=c.test(t+"")&&e.names(t).length>0;if(n||i||o)return!0}return!1}catch(t){return!1}},isIdentifier:function(t){return l.test(t)},inheritedDataKeys:u,getDataPropertyOrDefault:function(t,r,n){if(!e.isES5)return{}.hasOwnProperty.call(t,r)?t[r]:void 0;var i=Object.getOwnPropertyDescriptor(t,r);return null!=i?null==i.get&&null==i.set?i.value:n:void 0},thrower:function(t){throw t},isArray:e.isArray,asArray:m,notEnumerableProp:a,isPrimitive:s,isObject:function(t){return"function"==typeof t||"object"==typeof t&&null!==t},isError:h,canEvaluate:r,errorObj:n,tryCatch:function(e){return t=e,o},inherits:function(t,e){var r={}.hasOwnProperty;function n(){for(var n in this.constructor=t,this.constructor$=e,e.prototype)r.call(e.prototype,n)&&"$"!==n.charAt(n.length-1)&&(this[n+"$"]=e.prototype[n])}return n.prototype=e.prototype,t.prototype=new n,t.prototype},withAppended:function(t,e){var r,n=t.length,i=new Array(n+1);for(r=0;r<n;++r)i[r]=t[r];return i[r]=e,i},maybeWrapAsError:function(t){return s(t)?new Error(f(t)):t},toFastProperties:function(t){function e(){}e.prototype=t;var r=new e;function n(){return typeof r.foo}return n(),n(),t},filledRange:function(t,e,r){for(var n=new Array(t),i=0;i<t;++i)n[i]=e+i+r;return n},toString:f,canAttachTrace:p,ensureErrorObject:d,originatesFromRejection:function(t){return null!=t&&(t instanceof Error.__BluebirdErrorTypes__.OperationalError||!0===t.isOperational)},markAsOriginatingFromRejection:function(t){try{a(t,"isOperational",!0)}catch(t){}},classString:y,copyDescriptors:function(t,r,n){for(var i=e.names(t),o=0;o<i.length;++o){var s=i[o];if(n(s))try{e.defineProperty(r,s,e.getDescriptor(t,s))}catch(t){}}},isNode:b,hasEnvVariables:v,env:function(t){return v?process.env[t]:void 0},global:i,getNativePromise:function(){if("function"==typeof Promise)try{if("[object Promise]"===y(new Promise(function(){})))return Promise}catch(t){}},contextBind:function(t,e){if(null===t||"function"!=typeof e||e===_)return e;null!==t.domain&&(e=t.domain.bind(e));var r=t.async;if(null!==r){var n=e;e=function(){for(var t=arguments.length+2,e=new Array(t),i=2;i<t;++i)e[i]=arguments[i-2];return e[0]=n,e[1]=this,r.runInAsyncScope.apply(r,e)}}return e}};S.isRecentNode=S.isNode&&(process.versions&&process.versions.node?w=process.versions.node.split(".").map(Number):process.version&&(w=process.version.split(".").map(Number)),0===w[0]&&w[1]>10||w[0]>0),S.nodeSupportsAsyncResource=S.isNode&&function(){var t=!1;try{t="function"==typeof require("async_hooks").AsyncResource.prototype.runInAsyncScope}catch(e){t=!1}return t}(),S.isNode&&S.toFastProperties(process);try{throw new Error}catch(t){S.lastLineError=t}return Hp=S}var Zp,Kp,Jp,Yp,Xp,td,ed,rd,nd,id,od,sd,ad,ud,cd,ld,fd,hd,pd,dd,yd,md,gd,_d,bd,vd,wd,Sd,Ed,kd,xd,Od,Td,jd,Cd,Rd,Pd,Ld,Fd,Ad,Id,Dd,Md,Nd,Bd,Ud,zd,Wd,Hd,$d,qd,Gd,Vd,Qd,Zd,Kd,Jd,Yd,Xd,ty,ey,ry,ny,iy,oy,sy,ay,uy,cy={exports:{}};function ly(){if(Kp)return Zp;Kp=1;var t,e=Qp(),r=e.getNativePromise();if(e.isNode&&"undefined"==typeof MutationObserver){var n=I.setImmediate,i=process.nextTick;t=e.isRecentNode?function(t){n.call(I,t)}:function(t){i.call(process,t)}}else if("function"==typeof r&&"function"==typeof r.resolve){var o=r.resolve();t=function(t){o.then(t)}}else t="undefined"==typeof MutationObserver||"undefined"!=typeof window&&window.navigator&&(window.navigator.standalone||window.cordova)||!("classList"in document.documentElement)?"undefined"!=typeof setImmediate?function(t){setImmediate(t)}:"undefined"!=typeof setTimeout?function(t){setTimeout(t,0)}:function(){throw new Error("No async scheduler available\n\n See http://goo.gl/MqrFmX\n")}:function(){var t=document.createElement("div"),e={attributes:!0},r=!1,n=document.createElement("div");new MutationObserver(function(){t.classList.toggle("foo"),r=!1}).observe(n,e);return function(i){var o=new MutationObserver(function(){o.disconnect(),i()});o.observe(t,e),r||(r=!0,n.classList.toggle("foo"))}}();return Zp=t}function fy(){if(Xp)return cy.exports;var t;Xp=1;try{throw new Error}catch(e){t=e}var e=ly(),r=function(){if(Yp)return Jp;function t(t){this._capacity=t,this._length=0,this._front=0}return Yp=1,t.prototype._willBeOverCapacity=function(t){return this._capacity<t},t.prototype._pushOne=function(t){var e=this.length();this._checkCapacity(e+1),this[this._front+e&this._capacity-1]=t,this._length=e+1},t.prototype.push=function(t,e,r){var n=this.length()+3;if(this._willBeOverCapacity(n))return this._pushOne(t),this._pushOne(e),void this._pushOne(r);var i=this._front+n-3;this._checkCapacity(n);var o=this._capacity-1;this[i+0&o]=t,this[i+1&o]=e,this[i+2&o]=r,this._length=n},t.prototype.shift=function(){var t=this._front,e=this[t];return this[t]=void 0,this._front=t+1&this._capacity-1,this._length--,e},t.prototype.length=function(){return this._length},t.prototype._checkCapacity=function(t){this._capacity<t&&this._resizeTo(this._capacity<<1)},t.prototype._resizeTo=function(t){var e=this._capacity;this._capacity=t,function(t,e,r,n,i){for(var o=0;o<i;++o)r[o+n]=t[o+e],t[o+e]=void 0}(this,0,this,e,this._front+this._length&e-1)},Jp=t}();function n(){this._customScheduler=!1,this._isTickUsed=!1,this._lateQueue=new r(16),this._normalQueue=new r(16),this._haveDrainedQueues=!1;var t=this;this.drainQueues=function(){t._drainQueues()},this._schedule=e}function i(t){for(;t.length()>0;)o(t)}function o(t){var e=t.shift();if("function"!=typeof e)e._settlePromises();else{var r=t.shift(),n=t.shift();e.call(r,n)}}return n.prototype.setScheduler=function(t){var e=this._schedule;return this._schedule=t,this._customScheduler=!0,e},n.prototype.hasCustomScheduler=function(){return this._customScheduler},n.prototype.haveItemsQueued=function(){return this._isTickUsed||this._haveDrainedQueues},n.prototype.fatalError=function(t,e){e?(process.stderr.write("Fatal "+(t instanceof Error?t.stack:t)+"\n"),process.exit(2)):this.throwLater(t)},n.prototype.throwLater=function(t,e){if(1===arguments.length&&(e=t,t=function(){throw e}),"undefined"!=typeof setTimeout)setTimeout(function(){t(e)},0);else try{this._schedule(function(){t(e)})}catch(t){throw new Error("No async scheduler available\n\n See http://goo.gl/MqrFmX\n")}},n.prototype.invokeLater=function(t,e,r){this._lateQueue.push(t,e,r),this._queueTick()},n.prototype.invoke=function(t,e,r){this._normalQueue.push(t,e,r),this._queueTick()},n.prototype.settlePromises=function(t){this._normalQueue._pushOne(t),this._queueTick()},n.prototype._drainQueues=function(){i(this._normalQueue),this._reset(),this._haveDrainedQueues=!0,i(this._lateQueue)},n.prototype._queueTick=function(){this._isTickUsed||(this._isTickUsed=!0,this._schedule(this.drainQueues))},n.prototype._reset=function(){this._isTickUsed=!1},cy.exports=n,cy.exports.firstLineError=t,cy.exports}function hy(){if(ed)return td;ed=1;var t,e,r=Vp(),n=r.freeze,i=Qp(),o=i.inherits,s=i.notEnumerableProp;function a(t,e){function r(n){if(!(this instanceof r))return new r(n);s(this,"message","string"==typeof n?n:e),s(this,"name",t),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):Error.call(this)}return o(r,Error),r}var u=a("Warning","warning"),c=a("CancellationError","cancellation error"),l=a("TimeoutError","timeout error"),f=a("AggregateError","aggregate error");try{t=TypeError,e=RangeError}catch(r){t=a("TypeError","type error"),e=a("RangeError","range error")}for(var h="join pop push shift unshift slice filter forEach some every map indexOf lastIndexOf reduce reduceRight sort reverse".split(" "),p=0;p<h.length;++p)"function"==typeof Array.prototype[h[p]]&&(f.prototype[h[p]]=Array.prototype[h[p]]);r.defineProperty(f.prototype,"length",{value:0,configurable:!1,writable:!0,enumerable:!0}),f.prototype.isOperational=!0;var d=0;function y(t){if(!(this instanceof y))return new y(t);s(this,"name","OperationalError"),s(this,"message",t),this.cause=t,this.isOperational=!0,t instanceof Error?(s(this,"message",t.message),s(this,"stack",t.stack)):Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}f.prototype.toString=function(){var t=Array(4*d+1).join(" "),e="\n"+t+"AggregateError of:\n";d++,t=Array(4*d+1).join(" ");for(var r=0;r<this.length;++r){for(var n=this[r]===this?"[Circular AggregateError]":this[r]+"",i=n.split("\n"),o=0;o<i.length;++o)i[o]=t+i[o];e+=(n=i.join("\n"))+"\n"}return d--,e},o(y,Error);var m=Error.__BluebirdErrorTypes__;return m||(m=n({CancellationError:c,TimeoutError:l,OperationalError:y,RejectionError:y,AggregateError:f}),r.defineProperty(Error,"__BluebirdErrorTypes__",{value:m,writable:!1,enumerable:!1,configurable:!1})),td={Error:Error,TypeError:t,RangeError:e,CancellationError:m.CancellationError,OperationalError:m.OperationalError,TimeoutError:m.TimeoutError,AggregateError:m.AggregateError,Warning:u}}function py(){return nd||(nd=1,rd=function(t,e){var r=Qp(),n=r.errorObj,i=r.isObject;var o={}.hasOwnProperty;return function(s,a){if(i(s)){if(s instanceof t)return s;var u=function(t){try{return function(t){return t.then}(t)}catch(t){return n.e=t,n}}(s);if(u===n){a&&a._pushContext();var c=t.reject(u.e);return a&&a._popContext(),c}if("function"==typeof u){if(function(t){try{return o.call(t,"_promise0")}catch(t){return!1}}(s)){c=new t(e);return s._then(c._fulfill,c._reject,void 0,c,null),c}return function(i,o,s){var a=new t(e),u=a;s&&s._pushContext();a._captureStackTrace(),s&&s._popContext();var c=!0,l=r.tryCatch(o).call(i,f,h);c=!1,a&&l===n&&(a._rejectCallback(l.e,!0,!0),a=null);function f(t){a&&(a._resolveCallback(t),a=null)}function h(t){a&&(a._rejectCallback(t,c,!0),a=null)}return u}(s,u,a)}}return s}}),rd}function dy(){return od||(od=1,id=function(t,e,r,n,i){var o=Qp();function s(r){var n=this._promise=new t(e);r instanceof t&&(n._propagateFrom(r,3),r.suppressUnhandledRejections()),n._setOnCancel(this),this._values=r,this._length=0,this._totalResolved=0,this._init(void 0,-2)}return o.isArray,o.inherits(s,i),s.prototype.length=function(){return this._length},s.prototype.promise=function(){return this._promise},s.prototype._init=function e(i,s){var a=r(this._values,this._promise);if(a instanceof t){var u=(a=a._target())._bitField;if(this._values=a,!(50397184&u))return this._promise._setAsyncGuaranteed(),a._then(e,this._reject,void 0,this,s);if(!(33554432&u))return 16777216&u?this._reject(a._reason()):this._cancel();a=a._value()}if(null!==(a=o.asArray(a)))0!==a.length?this._iterate(a):-5===s?this._resolveEmptyArray():this._resolve(function(t){switch(t){case-2:return[];case-3:return{};case-6:return new Map}}(s));else{var c=n("expecting an array or an iterable object but got "+o.classString(a)).reason();this._promise._rejectCallback(c,!1)}},s.prototype._iterate=function(e){var n=this.getActualLength(e.length);this._length=n,this._values=this.shouldCopyValues()?new Array(n):this._values;for(var i=this._promise,o=!1,s=null,a=0;a<n;++a){var u=r(e[a],i);s=u instanceof t?(u=u._target())._bitField:null,o?null!==s&&u.suppressUnhandledRejections():null!==s?50397184&s?o=33554432&s?this._promiseFulfilled(u._value(),a):16777216&s?this._promiseRejected(u._reason(),a):this._promiseCancelled(a):(u._proxy(this,a),this._values[a]=u):o=this._promiseFulfilled(u,a)}o||i._setAsyncGuaranteed()},s.prototype._isResolved=function(){return null===this._values},s.prototype._resolve=function(t){this._values=null,this._promise._fulfill(t)},s.prototype._cancel=function(){!this._isResolved()&&this._promise._isCancellable()&&(this._values=null,this._promise._cancel())},s.prototype._reject=function(t){this._values=null,this._promise._rejectCallback(t,!1)},s.prototype._promiseFulfilled=function(t,e){return this._values[e]=t,++this._totalResolved>=this._length&&(this._resolve(this._values),!0)},s.prototype._promiseCancelled=function(){return this._cancel(),!0},s.prototype._promiseRejected=function(t){return this._totalResolved++,this._reject(t),!0},s.prototype._resultCancelled=function(){if(!this._isResolved()){var e=this._values;if(this._cancel(),e instanceof t)e.cancel();else for(var r=0;r<e.length;++r)e[r]instanceof t&&e[r].cancel()}},s.prototype.shouldCopyValues=function(){return!0},s.prototype.getActualLength=function(t){return t},s}),id}function yy(){return cd||(cd=1,ud=function(t,e,r,n){var i,o,s,a,u=t._async,c=hy().Warning,l=Qp(),f=Vp(),h=l.canAttachTrace,p=/[\\\/]bluebird[\\\/]js[\\\/](release|debug|instrumented)/,d=/\((?:timers\.js):\d+:\d+\)/,y=/[\/<\(](.+?):(\d+):(\d+)\)?\s*$/,m=null,g=null,_=!1,b=!(0==l.env("BLUEBIRD_DEBUG")||!l.env("BLUEBIRD_DEBUG")&&"development"!==l.env("NODE_ENV")),v=!(0==l.env("BLUEBIRD_WARNINGS")||!b&&!l.env("BLUEBIRD_WARNINGS")),w=!(0==l.env("BLUEBIRD_LONG_STACK_TRACES")||!b&&!l.env("BLUEBIRD_LONG_STACK_TRACES")),S=0!=l.env("BLUEBIRD_W_FORGOTTEN_RETURN")&&(v||!!l.env("BLUEBIRD_W_FORGOTTEN_RETURN"));!function(){var e=[];function r(){for(var t=0;t<e.length;++t)e[t]._notifyUnhandledRejection();n()}function n(){e.length=0}a=function(t){e.push(t),setTimeout(r,1)},f.defineProperty(t,"_unhandledRejectionCheck",{value:r}),f.defineProperty(t,"_unhandledRejectionClear",{value:n})}(),t.prototype.suppressUnhandledRejections=function(){var t=this._target();t._bitField=-1048577&t._bitField|524288},t.prototype._ensurePossibleRejectionHandled=function(){524288&this._bitField||(this._setRejectionIsUnhandled(),a(this))},t.prototype._notifyUnhandledRejectionIsHandled=function(){G("rejectionHandled",i,void 0,this)},t.prototype._setReturnedNonUndefined=function(){this._bitField=268435456|this._bitField},t.prototype._returnedNonUndefined=function(){return!!(268435456&this._bitField)},t.prototype._notifyUnhandledRejection=function(){if(this._isRejectionUnhandled()){var t=this._settledValue();this._setUnhandledRejectionIsNotified(),G("unhandledRejection",o,t,this)}},t.prototype._setUnhandledRejectionIsNotified=function(){this._bitField=262144|this._bitField},t.prototype._unsetUnhandledRejectionIsNotified=function(){this._bitField=-262145&this._bitField},t.prototype._isUnhandledRejectionNotified=function(){return(262144&this._bitField)>0},t.prototype._setRejectionIsUnhandled=function(){this._bitField=1048576|this._bitField},t.prototype._unsetRejectionIsUnhandled=function(){this._bitField=-1048577&this._bitField,this._isUnhandledRejectionNotified()&&(this._unsetUnhandledRejectionIsNotified(),this._notifyUnhandledRejectionIsHandled())},t.prototype._isRejectionUnhandled=function(){return(1048576&this._bitField)>0},t.prototype._warn=function(t,e,r){return W(t,e,r||this)},t.onPossiblyUnhandledRejection=function(e){var r=t._getContext();o=l.contextBind(r,e)},t.onUnhandledRejectionHandled=function(e){var r=t._getContext();i=l.contextBind(r,e)};var E=function(){};t.longStackTraces=function(){if(u.haveItemsQueued()&&!tt.longStackTraces)throw new Error("cannot enable long stack traces after promises have been created\n\n See http://goo.gl/MqrFmX\n");if(!tt.longStackTraces&&Q()){var r=t.prototype._captureStackTrace,n=t.prototype._attachExtraTrace,i=t.prototype._dereferenceTrace;tt.longStackTraces=!0,E=function(){if(u.haveItemsQueued()&&!tt.longStackTraces)throw new Error("cannot enable long stack traces after promises have been created\n\n See http://goo.gl/MqrFmX\n");t.prototype._captureStackTrace=r,t.prototype._attachExtraTrace=n,t.prototype._dereferenceTrace=i,e.deactivateLongStackTraces(),tt.longStackTraces=!1},t.prototype._captureStackTrace=B,t.prototype._attachExtraTrace=U,t.prototype._dereferenceTrace=z,e.activateLongStackTraces()}},t.hasLongStackTraces=function(){return tt.longStackTraces&&Q()};var k={unhandledrejection:{before:function(){var t=l.global.onunhandledrejection;return l.global.onunhandledrejection=null,t},after:function(t){l.global.onunhandledrejection=t}},rejectionhandled:{before:function(){var t=l.global.onrejectionhandled;return l.global.onrejectionhandled=null,t},after:function(t){l.global.onrejectionhandled=t}}},x=function(){var t=function(t,e){if(!t)return!l.global.dispatchEvent(e);var r;try{return r=t.before(),!l.global.dispatchEvent(e)}finally{t.after(r)}};try{if("function"==typeof CustomEvent){var e=new CustomEvent("CustomEvent");return l.global.dispatchEvent(e),function(e,r){e=e.toLowerCase();var n=new CustomEvent(e,{detail:r,cancelable:!0});return f.defineProperty(n,"promise",{value:r.promise}),f.defineProperty(n,"reason",{value:r.reason}),t(k[e],n)}}if("function"==typeof Event){e=new Event("CustomEvent");return l.global.dispatchEvent(e),function(e,r){e=e.toLowerCase();var n=new Event(e,{cancelable:!0});return n.detail=r,f.defineProperty(n,"promise",{value:r.promise}),f.defineProperty(n,"reason",{value:r.reason}),t(k[e],n)}}return(e=document.createEvent("CustomEvent")).initCustomEvent("testingtheevent",!1,!0,{}),l.global.dispatchEvent(e),function(e,r){e=e.toLowerCase();var n=document.createEvent("CustomEvent");return n.initCustomEvent(e,!1,!0,r),t(k[e],n)}}catch(t){}return function(){return!1}}(),O=l.isNode?function(){return process.emit.apply(process,arguments)}:l.global?function(t){var e="on"+t.toLowerCase(),r=l.global[e];return!!r&&(r.apply(l.global,[].slice.call(arguments,1)),!0)}:function(){return!1};function T(t,e){return{promise:e}}var j={promiseCreated:T,promiseFulfilled:T,promiseRejected:T,promiseResolved:T,promiseCancelled:T,promiseChained:function(t,e,r){return{promise:e,child:r}},warning:function(t,e){return{warning:e}},unhandledRejection:function(t,e,r){return{reason:e,promise:r}},rejectionHandled:T},C=function(t){var e=!1;try{e=O.apply(null,arguments)}catch(t){u.throwLater(t),e=!0}var r=!1;try{r=x(t,j[t].apply(null,arguments))}catch(t){u.throwLater(t),r=!0}return r||e};function R(){return!1}function P(t,e,r){var n=this;try{t(e,r,function(t){if("function"!=typeof t)throw new TypeError("onCancel must be a function, got: "+l.toString(t));n._attachCancellationCallback(t)})}catch(t){return t}}function L(t){if(!this._isCancellable())return this;var e=this._onCancel();void 0!==e?l.isArray(e)?e.push(t):this._setOnCancel([e,t]):this._setOnCancel(t)}function F(){return this._onCancelField}function A(t){this._onCancelField=t}function I(){this._cancellationParent=void 0,this._onCancelField=void 0}function D(t,e){if(1&e){this._cancellationParent=t;var r=t._branchesRemainingToCancel;void 0===r&&(r=0),t._branchesRemainingToCancel=r+1}2&e&&t._isBound()&&this._setBoundTo(t._boundTo)}t.config=function(e){if("longStackTraces"in(e=Object(e))&&(e.longStackTraces?t.longStackTraces():!e.longStackTraces&&t.hasLongStackTraces()&&E()),"warnings"in e){var i=e.warnings;tt.warnings=!!i,S=tt.warnings,l.isObject(i)&&"wForgottenReturn"in i&&(S=!!i.wForgottenReturn)}if("cancellation"in e&&e.cancellation&&!tt.cancellation){if(u.haveItemsQueued())throw new Error("cannot enable cancellation after promises are in use");t.prototype._clearCancellationData=I,t.prototype._propagateFrom=D,t.prototype._onCancel=F,t.prototype._setOnCancel=A,t.prototype._attachCancellationCallback=L,t.prototype._execute=P,M=D,tt.cancellation=!0}if("monitoring"in e&&(e.monitoring&&!tt.monitoring?(tt.monitoring=!0,t.prototype._fireEvent=C):!e.monitoring&&tt.monitoring&&(tt.monitoring=!1,t.prototype._fireEvent=R)),"asyncHooks"in e&&l.nodeSupportsAsyncResource){var o=tt.asyncHooks,s=!!e.asyncHooks;o!==s&&(tt.asyncHooks=s,s?r():n())}return t},t.prototype._fireEvent=R,t.prototype._execute=function(t,e,r){try{t(e,r)}catch(t){return t}},t.prototype._onCancel=function(){},t.prototype._setOnCancel=function(t){},t.prototype._attachCancellationCallback=function(t){},t.prototype._captureStackTrace=function(){},t.prototype._attachExtraTrace=function(){},t.prototype._dereferenceTrace=function(){},t.prototype._clearCancellationData=function(){},t.prototype._propagateFrom=function(t,e){};var M=function(t,e){2&e&&t._isBound()&&this._setBoundTo(t._boundTo)};function N(){var e=this._boundTo;return void 0!==e&&e instanceof t?e.isFulfilled()?e.value():void 0:e}function B(){this._trace=new Y(this._peekContext())}function U(t,e){if(h(t)){var r=this._trace;if(void 0!==r&&e&&(r=r._parent),void 0!==r)r.attachExtraTrace(t);else if(!t.__stackCleaned__){var n=$(t);l.notEnumerableProp(t,"stack",n.message+"\n"+n.stack.join("\n")),l.notEnumerableProp(t,"__stackCleaned__",!0)}}}function z(){this._trace=void 0}function W(e,r,n){if(tt.warnings){var i,o=new c(e);if(r)n._attachExtraTrace(o);else if(tt.longStackTraces&&(i=t._peekContext()))i.attachExtraTrace(o);else{var s=$(o);o.stack=s.message+"\n"+s.stack.join("\n")}C("warning",o)||q(o,"",!0)}}function H(t){for(var e=[],r=0;r<t.length;++r){var n=t[r],i=" (No stack trace)"===n||m.test(n),o=i&&Z(n);i&&!o&&(_&&" "!==n.charAt(0)&&(n=" "+n),e.push(n))}return e}function $(t){var e=t.stack,r=t.toString();return e="string"==typeof e&&e.length>0?function(t){for(var e=t.stack.replace(/\s+$/g,"").split("\n"),r=0;r<e.length;++r){var n=e[r];if(" (No stack trace)"===n||m.test(n))break}return r>0&&"SyntaxError"!=t.name&&(e=e.slice(r)),e}(t):[" (No stack trace)"],{message:r,stack:"SyntaxError"==t.name?e:H(e)}}function q(t,e,r){if("undefined"!=typeof console){var n;if(l.isObject(t)){var i=t.stack;n=e+g(i,t)}else n=e+String(t);"function"==typeof s?s(n,r):"function"!=typeof console.log&&"object"!=typeof console.log||console.log(n)}}function G(t,e,r,n){var i=!1;try{"function"==typeof e&&(i=!0,"rejectionHandled"===t?e(n):e(r,n))}catch(t){u.throwLater(t)}"unhandledRejection"===t?C(t,r,n)||i||q(r,"Unhandled rejection "):C(t,n)}function V(t){var e;if("function"==typeof t)e="[function "+(t.name||"anonymous")+"]";else{e=t&&"function"==typeof t.toString?t.toString():l.toString(t);if(/\[object [a-zA-Z0-9$_]+\]/.test(e))try{e=JSON.stringify(t)}catch(t){}0===e.length&&(e="(empty array)")}return"(<"+function(t){var e=41;if(t.length<e)return t;return t.substr(0,e-3)+"..."}(e)+">, no stack trace)"}function Q(){return"function"==typeof X}var Z=function(){return!1},K=/[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/;function J(t){var e=t.match(K);if(e)return{fileName:e[1],line:parseInt(e[2],10)}}function Y(t){this._parent=t,this._promisesCreated=0;var e=this._length=1+(void 0===t?0:t._length);X(this,Y),e>32&&this.uncycle()}l.inherits(Y,Error),e.CapturedTrace=Y,Y.prototype.uncycle=function(){var t=this._length;if(!(t<2)){for(var e=[],r={},n=0,i=this;void 0!==i;++n)e.push(i),i=i._parent;for(n=(t=this._length=n)-1;n>=0;--n){var o=e[n].stack;void 0===r[o]&&(r[o]=n)}for(n=0;n<t;++n){var s=r[e[n].stack];if(void 0!==s&&s!==n){s>0&&(e[s-1]._parent=void 0,e[s-1]._length=1),e[n]._parent=void 0,e[n]._length=1;var a=n>0?e[n-1]:this;s<t-1?(a._parent=e[s+1],a._parent.uncycle(),a._length=a._parent._length+1):(a._parent=void 0,a._length=1);for(var u=a._length+1,c=n-2;c>=0;--c)e[c]._length=u,u++;return}}}},Y.prototype.attachExtraTrace=function(t){if(!t.__stackCleaned__){this.uncycle();for(var e=$(t),r=e.message,n=[e.stack],i=this;void 0!==i;)n.push(H(i.stack.split("\n"))),i=i._parent;!function(t){for(var e=t[0],r=1;r<t.length;++r){for(var n=t[r],i=e.length-1,o=e[i],s=-1,a=n.length-1;a>=0;--a)if(n[a]===o){s=a;break}for(a=s;a>=0;--a){var u=n[a];if(e[i]!==u)break;e.pop(),i--}e=n}}(n),function(t){for(var e=0;e<t.length;++e)(0===t[e].length||e+1<t.length&&t[e][0]===t[e+1][0])&&(t.splice(e,1),e--)}(n),l.notEnumerableProp(t,"stack",function(t,e){for(var r=0;r<e.length-1;++r)e[r].push("From previous event:"),e[r]=e[r].join("\n");return r<e.length&&(e[r]=e[r].join("\n")),t+"\n"+e.join("\n")}(r,n)),l.notEnumerableProp(t,"__stackCleaned__",!0)}};var X=function(){var t=/^\s*at\s*/,e=function(t,e){return"string"==typeof t?t:void 0!==e.name&&void 0!==e.message?e.toString():V(e)};if("number"==typeof Error.stackTraceLimit&&"function"==typeof Error.captureStackTrace){Error.stackTraceLimit+=6,m=t,g=e;var r=Error.captureStackTrace;return Z=function(t){return p.test(t)},function(t,e){Error.stackTraceLimit+=6,r(t,e),Error.stackTraceLimit-=6}}var n,i=new Error;if("string"==typeof i.stack&&i.stack.split("\n")[0].indexOf("stackDetection@")>=0)return m=/@/,g=e,_=!0,function(t){t.stack=(new Error).stack};try{throw new Error}catch(t){n="stack"in t}return!("stack"in i)&&n&&"number"==typeof Error.stackTraceLimit?(m=t,g=e,function(t){Error.stackTraceLimit+=6;try{throw new Error}catch(e){t.stack=e.stack}Error.stackTraceLimit-=6}):(g=function(t,e){return"string"==typeof t?t:"object"!=typeof e&&"function"!=typeof e||void 0===e.name||void 0===e.message?V(e):e.toString()},null)}();"undefined"!=typeof console&&void 0!==console.warn&&(s=function(t){console.warn(t)},l.isNode&&process.stderr.isTTY?s=function(t,e){var r=e?"[33m":"[31m";console.warn(r+t+"[0m\n")}:l.isNode||"string"!=typeof(new Error).stack||(s=function(t,e){console.warn("%c"+t,e?"color: darkorange":"color: red")}));var tt={warnings:v,longStackTraces:!1,cancellation:!1,monitoring:!1,asyncHooks:!1};return w&&t.longStackTraces(),{asyncHooks:function(){return tt.asyncHooks},longStackTraces:function(){return tt.longStackTraces},warnings:function(){return tt.warnings},cancellation:function(){return tt.cancellation},monitoring:function(){return tt.monitoring},propagateFromFunction:function(){return M},boundValueFunction:function(){return N},checkForgottenReturns:function(t,e,r,n,i){if(void 0===t&&null!==e&&S){if(void 0!==i&&i._returnedNonUndefined())return;if(!(65535&n._bitField))return;r&&(r+=" ");var o="",s="";if(e._trace){for(var a=e._trace.stack.split("\n"),u=H(a),c=u.length-1;c>=0;--c){var l=u[c];if(!d.test(l)){var f=l.match(y);f&&(o="at "+f[1]+":"+f[2]+":"+f[3]+" ");break}}if(u.length>0){var h=u[0];for(c=0;c<a.length;++c)if(a[c]===h){c>0&&(s="\n"+a[c-1]);break}}}var p="a promise was created in a "+r+"handler "+o+"but was not returned from it, see http://goo.gl/rRqMUw"+s;n._warn(p,!0,e)}},setBounds:function(t,e){if(Q()){for(var r,n,i=(t.stack||"").split("\n"),o=(e.stack||"").split("\n"),s=-1,a=-1,u=0;u<i.length;++u){if(c=J(i[u])){r=c.fileName,s=c.line;break}}for(u=0;u<o.length;++u){var c;if(c=J(o[u])){n=c.fileName,a=c.line;break}}s<0||a<0||!r||!n||r!==n||s>=a||(Z=function(t){if(p.test(t))return!0;var e=J(t);return!!(e&&e.fileName===r&&s<=e.line&&e.line<=a)})}},warn:W,deprecated:function(t,e){var r=t+" is deprecated and will be removed in a future version.";return e&&(r+=" Use "+e+" instead."),W(r)},CapturedTrace:Y,fireDomEvent:x,fireGlobalEvent:O}}),ud}function my(){return fd||(fd=1,ld=function(t){var e=Qp(),r=Vp().keys,n=e.tryCatch,i=e.errorObj;return function(o,s,a){return function(u){var c=a._boundValue();t:for(var l=0;l<o.length;++l){var f=o[l];if(f===Error||null!=f&&f.prototype instanceof Error){if(u instanceof f)return n(s).call(c,u)}else if("function"==typeof f){var h=n(f).call(c,u);if(h===i)return h;if(h)return n(s).call(c,u)}else if(e.isObject(u)){for(var p=r(f),d=0;d<p.length;++d){var y=p[d];if(f[y]!=u[y])continue t}return n(s).call(c,u)}}return t}}}),ld}function gy(){return pd||(pd=1,hd=function(t,e,r){var n=Qp(),i=t.CancellationError,o=n.errorObj,s=my()(r);function a(t,e,r){this.promise=t,this.type=e,this.handler=r,this.called=!1,this.cancelPromise=null}function u(t){this.finallyHandler=t}function c(t,e){return null!=t.cancelPromise&&(arguments.length>1?t.cancelPromise._reject(e):t.cancelPromise._cancel(),t.cancelPromise=null,!0)}function l(){return h.call(this,this.promise._target()._settledValue())}function f(t){if(!c(this,t))return o.e=t,o}function h(n){var s=this.promise,a=this.handler;if(!this.called){this.called=!0;var h=this.isFinallyHandler()?a.call(s._boundValue()):a.call(s._boundValue(),n);if(h===r)return h;if(void 0!==h){s._setReturnedNonUndefined();var p=e(h,s);if(p instanceof t){if(null!=this.cancelPromise){if(p._isCancelled()){var d=new i("late cancellation observer");return s._attachExtraTrace(d),o.e=d,o}p.isPending()&&p._attachCancellationCallback(new u(this))}return p._then(l,f,void 0,this,void 0)}}}return s.isRejected()?(c(this),o.e=n,o):(c(this),n)}return a.prototype.isFinallyHandler=function(){return 0===this.type},u.prototype._resultCancelled=function(){c(this.finallyHandler)},t.prototype._passThrough=function(t,e,r,n){return"function"!=typeof t?this.then():this._then(r,n,void 0,new a(this,e,t),void 0)},t.prototype.lastly=t.prototype.finally=function(t){return this._passThrough(t,0,h,h)},t.prototype.tap=function(t){return this._passThrough(t,1,h)},t.prototype.tapCatch=function(e){var r=arguments.length;if(1===r)return this._passThrough(e,1,void 0,h);var i,o=new Array(r-1),a=0;for(i=0;i<r-1;++i){var u=arguments[i];if(!n.isObject(u))return t.reject(new TypeError("tapCatch statement predicate: expecting an object but got "+n.classString(u)));o[a++]=u}o.length=a;var c=arguments[i];return this._passThrough(s(o,c,this),1,void 0,h)},a}),hd}function _y(){if(yd)return dd;yd=1;var t=Qp(),e=t.maybeWrapAsError,r=hy().OperationalError,n=Vp();var i=/^(?:name|message|stack|cause)$/;function o(e){var o;if(function(t){return t instanceof Error&&n.getPrototypeOf(t)===Error.prototype}(e)){(o=new r(e)).name=e.name,o.message=e.message,o.stack=e.stack;for(var s=n.keys(e),a=0;a<s.length;++a){var u=s[a];i.test(u)||(o[u]=e[u])}return o}return t.markAsOriginatingFromRejection(e),e}return dd=function(t,r){return function(n,i){if(null!==t){if(n){var s=o(e(n));t._attachExtraTrace(s),t._reject(s)}else if(r){for(var a=arguments.length,u=new Array(Math.max(a-1,0)),c=1;c<a;++c)u[c-1]=arguments[c];t._fulfill(u)}else t._fulfill(i);t=null}}},dd}function by(){return xd||(xd=1,kd=function(t){function e(t){void 0!==t?(t=t._target(),this._bitField=t._bitField,this._settledValueField=t._isFateSealed()?t._settledValue():void 0):(this._bitField=0,this._settledValueField=void 0)}e.prototype._settledValue=function(){return this._settledValueField};var r=e.prototype.value=function(){if(!this.isFulfilled())throw new TypeError("cannot get fulfillment value of a non-fulfilled promise\n\n See http://goo.gl/MqrFmX\n");return this._settledValue()},n=e.prototype.error=e.prototype.reason=function(){if(!this.isRejected())throw new TypeError("cannot get rejection reason of a non-rejected promise\n\n See http://goo.gl/MqrFmX\n");return this._settledValue()},i=e.prototype.isFulfilled=function(){return!!(33554432&this._bitField)},o=e.prototype.isRejected=function(){return!!(16777216&this._bitField)},s=e.prototype.isPending=function(){return!(50397184&this._bitField)},a=e.prototype.isResolved=function(){return!!(50331648&this._bitField)};e.prototype.isCancelled=function(){return!!(8454144&this._bitField)},t.prototype.__isCancelled=function(){return!(65536&~this._bitField)},t.prototype._isCancelled=function(){return this._target().__isCancelled()},t.prototype.isCancelled=function(){return!!(8454144&this._target()._bitField)},t.prototype.isPending=function(){return s.call(this._target())},t.prototype.isRejected=function(){return o.call(this._target())},t.prototype.isFulfilled=function(){return i.call(this._target())},t.prototype.isResolved=function(){return a.call(this._target())},t.prototype.value=function(){return r.call(this._target())},t.prototype.reason=function(){var t=this._target();return t._unsetRejectionIsUnhandled(),n.call(t)},t.prototype._value=function(){return this._settledValue()},t.prototype._reason=function(){return this._unsetRejectionIsUnhandled(),this._settledValue()},t.PromiseInspection=e}),kd}function vy(){return Pd||(Pd=1,Rd=function(t,e,r,n,i,o){var s=hy().TypeError,a=Qp(),u=a.errorObj,c=a.tryCatch,l=[];function f(e,n,i,s){if(o.cancellation()){var a=new t(r),u=this._finallyPromise=new t(r);this._promise=a.lastly(function(){return u}),a._captureStackTrace(),a._setOnCancel(this)}else{(this._promise=new t(r))._captureStackTrace()}this._stack=s,this._generatorFunction=e,this._receiver=n,this._generator=void 0,this._yieldHandlers="function"==typeof i?[i].concat(l):l,this._yieldedPromise=null,this._cancellationPhase=!1}a.inherits(f,i),f.prototype._isResolved=function(){return null===this._promise},f.prototype._cleanup=function(){this._promise=this._generator=null,o.cancellation()&&null!==this._finallyPromise&&(this._finallyPromise._fulfill(),this._finallyPromise=null)},f.prototype._promiseCancelled=function(){if(!this._isResolved()){var e;if(void 0!==this._generator.return)this._promise._pushContext(),e=c(this._generator.return).call(this._generator,void 0),this._promise._popContext();else{var r=new t.CancellationError("generator .return() sentinel");t.coroutine.returnSentinel=r,this._promise._attachExtraTrace(r),this._promise._pushContext(),e=c(this._generator.throw).call(this._generator,r),this._promise._popContext()}this._cancellationPhase=!0,this._yieldedPromise=null,this._continue(e)}},f.prototype._promiseFulfilled=function(t){this._yieldedPromise=null,this._promise._pushContext();var e=c(this._generator.next).call(this._generator,t);this._promise._popContext(),this._continue(e)},f.prototype._promiseRejected=function(t){this._yieldedPromise=null,this._promise._attachExtraTrace(t),this._promise._pushContext();var e=c(this._generator.throw).call(this._generator,t);this._promise._popContext(),this._continue(e)},f.prototype._resultCancelled=function(){if(this._yieldedPromise instanceof t){var e=this._yieldedPromise;this._yieldedPromise=null,e.cancel()}},f.prototype.promise=function(){return this._promise},f.prototype._run=function(){this._generator=this._generatorFunction.call(this._receiver),this._receiver=this._generatorFunction=void 0,this._promiseFulfilled(void 0)},f.prototype._continue=function(e){var r=this._promise;if(e===u)return this._cleanup(),this._cancellationPhase?r.cancel():r._rejectCallback(e.e,!1);var i=e.value;if(!0===e.done)return this._cleanup(),this._cancellationPhase?r.cancel():r._resolveCallback(i);var o=n(i,this._promise);if(o instanceof t||(o=function(e,r,i){for(var o=0;o<r.length;++o){i._pushContext();var s=c(r[o])(e);if(i._popContext(),s===u){i._pushContext();var a=t.reject(u.e);return i._popContext(),a}var l=n(s,i);if(l instanceof t)return l}return null}(o,this._yieldHandlers,this._promise),null!==o)){var a=(o=o._target())._bitField;50397184&a?33554432&a?t._async.invoke(this._promiseFulfilled,this,o._value()):16777216&a?t._async.invoke(this._promiseRejected,this,o._reason()):this._promiseCancelled():(this._yieldedPromise=o,o._proxy(this,null))}else this._promiseRejected(new s("A value %s was yielded that could not be treated as a promise\n\n See http://goo.gl/MqrFmX\n\n".replace("%s",String(i))+"From coroutine:\n"+this._stack.split("\n").slice(1,-7).join("\n")))},t.coroutine=function(t,e){if("function"!=typeof t)throw new s("generatorFunction must be a function\n\n See http://goo.gl/MqrFmX\n");var r=Object(e).yieldHandler,n=f,i=(new Error).stack;return function(){var e=t.apply(this,arguments),o=new n(void 0,void 0,r,i),s=o.promise();return o._generator=e,o._promiseFulfilled(void 0),s}},t.coroutine.addYieldHandler=function(t){if("function"!=typeof t)throw new s("expecting a function but got "+a.classString(t));l.push(t)},t.spawn=function(r){if(o.deprecated("Promise.spawn()","Promise.coroutine()"),"function"!=typeof r)return e("generatorFunction must be a function\n\n See http://goo.gl/MqrFmX\n");var n=new f(r,this),i=n.promise();return n._run(t.spawn),i}}),Rd}function wy(){return Fd||(Fd=1,Ld=function(t,e,r,n,i,o){var s=Qp(),a=s.tryCatch,u=s.errorObj,c=t._async;function l(e,r,n,o){this.constructor$(e),this._promise._captureStackTrace();var a=t._getContext();if(this._callback=s.contextBind(a,r),this._preservedValues=o===i?new Array(this.length()):null,this._limit=n,this._inFlight=0,this._queue=[],c.invoke(this._asyncInit,this,void 0),s.isArray(e))for(var u=0;u<e.length;++u){var l=e[u];l instanceof t&&l.suppressUnhandledRejections()}}function f(e,n,i,o){if("function"!=typeof n)return r("expecting a function but got "+s.classString(n));var a=0;if(void 0!==i){if("object"!=typeof i||null===i)return t.reject(new TypeError("options argument must be an object but it is "+s.classString(i)));if("number"!=typeof i.concurrency)return t.reject(new TypeError("'concurrency' must be a number but it is "+s.classString(i.concurrency)));a=i.concurrency}return new l(e,n,a="number"==typeof a&&isFinite(a)&&a>=1?a:0,o).promise()}s.inherits(l,e),l.prototype._asyncInit=function(){this._init$(void 0,-2)},l.prototype._init=function(){},l.prototype._promiseFulfilled=function(e,r){var i=this._values,s=this.length(),c=this._preservedValues,l=this._limit;if(r<0){if(i[r=-1*r-1]=e,l>=1&&(this._inFlight--,this._drainQueue(),this._isResolved()))return!0}else{if(l>=1&&this._inFlight>=l)return i[r]=e,this._queue.push(r),!1;null!==c&&(c[r]=e);var f=this._promise,h=this._callback,p=f._boundValue();f._pushContext();var d=a(h).call(p,e,r,s),y=f._popContext();if(o.checkForgottenReturns(d,y,null!==c?"Promise.filter":"Promise.map",f),d===u)return this._reject(d.e),!0;var m=n(d,this._promise);if(m instanceof t){var g=(m=m._target())._bitField;if(!(50397184&g))return l>=1&&this._inFlight++,i[r]=m,m._proxy(this,-1*(r+1)),!1;if(!(33554432&g))return 16777216&g?(this._reject(m._reason()),!0):(this._cancel(),!0);d=m._value()}i[r]=d}return++this._totalResolved>=s&&(null!==c?this._filter(i,c):this._resolve(i),!0)},l.prototype._drainQueue=function(){for(var t=this._queue,e=this._limit,r=this._values;t.length>0&&this._inFlight<e;){if(this._isResolved())return;var n=t.pop();this._promiseFulfilled(r[n],n)}},l.prototype._filter=function(t,e){for(var r=e.length,n=new Array(r),i=0,o=0;o<r;++o)t[o]&&(n[i++]=e[o]);n.length=i,this._resolve(n)},l.prototype.preservedValues=function(){return this._preservedValues},t.prototype.map=function(t,e){return f(this,t,e,null)},t.map=function(t,e,r,n){return f(t,e,r,n)}}),Ld}function Sy(){return Md||(Md=1,Dd=function(t,e){var r={},n=Qp(),i=_y(),o=n.withAppended,s=n.maybeWrapAsError,a=n.canEvaluate,u=hy().TypeError,c={__isPromisified__:!0},l=new RegExp("^(?:"+["arity","length","name","arguments","caller","callee","prototype","__isPromisified__"].join("|")+")$"),f=function(t){return n.isIdentifier(t)&&"_"!==t.charAt(0)&&"constructor"!==t};function h(t){return!l.test(t)}function p(t){try{return!0===t.__isPromisified__}catch(t){return!1}}function d(t,e,r){var i=n.getDataPropertyOrDefault(t,e+r,c);return!!i&&p(i)}function y(t,e,r,i){for(var o=n.inheritedDataKeys(t),s=[],a=0;a<o.length;++a){var c=o[a],l=t[c],h=i===f||f(c);"function"!=typeof l||p(l)||d(t,c,e)||!i(c,l,t,h)||s.push(c,l)}return function(t,e,r){for(var n=0;n<t.length;n+=2){var i=t[n];if(r.test(i))for(var o=i.replace(r,""),s=0;s<t.length;s+=2)if(t[s]===o)throw new u("Cannot promisify an API that has normal methods with '%s'-suffix\n\n See http://goo.gl/MqrFmX\n".replace("%s",e))}}(s,e,r),s}var m;m=function(a,u,c,l,f,h){var p=Math.max(0,function(t){return"number"==typeof t.length?Math.max(Math.min(t.length,1024),0):0}(l)-1),d=function(t){for(var e=[t],r=Math.max(0,t-1-3),n=t-1;n>=r;--n)e.push(n);for(n=t+1;n<=3;++n)e.push(n);return e}(p),y="string"==typeof a||u===r;function m(t){var e,r=(e=t,n.filledRange(e,"_arg","")).join(", "),i=t>0?", ":"";return(y?"ret = callback.call(this, {{args}}, nodeback); break;\n":void 0===u?"ret = callback({{args}}, nodeback); break;\n":"ret = callback.call(receiver, {{args}}, nodeback); break;\n").replace("{{args}}",r).replace(", ",i)}var g="string"==typeof a?"this != null ? this['"+a+"'] : fn":"fn",_="'use strict'; \n\t var ret = function (Parameters) { \n\t 'use strict'; \n\t var len = arguments.length; \n\t var promise = new Promise(INTERNAL); \n\t promise._captureStackTrace(); \n\t var nodeback = nodebackForPromise(promise, "+h+"); \n\t var ret; \n\t var callback = tryCatch([GetFunctionCode]); \n\t switch(len) { \n\t [CodeForSwitchCase] \n\t } \n\t if (ret === errorObj) { \n\t promise._rejectCallback(maybeWrapAsError(ret.e), true, true);\n\t } \n\t if (!promise._isFateSealed()) promise._setAsyncGuaranteed(); \n\t return promise; \n\t }; \n\t notEnumerableProp(ret, '__isPromisified__', true); \n\t return ret; \n\t ".replace("[CodeForSwitchCase]",function(){for(var t="",e=0;e<d.length;++e)t+="case "+d[e]+":"+m(d[e]);return t+=" \n\t default: \n\t var args = new Array(len + 1); \n\t var i = 0; \n\t for (var i = 0; i < len; ++i) { \n\t args[i] = arguments[i]; \n\t } \n\t args[i] = nodeback; \n\t [CodeForCall] \n\t break; \n\t ".replace("[CodeForCall]",y?"ret = callback.apply(this, args);\n":"ret = callback.apply(receiver, args);\n")}()).replace("[GetFunctionCode]",g);return _=_.replace("Parameters",function(t){return n.filledRange(Math.max(t,3),"_arg","")}(p)),new Function("Promise","fn","receiver","withAppended","maybeWrapAsError","nodebackForPromise","tryCatch","errorObj","notEnumerableProp","INTERNAL",_)(t,l,u,o,s,i,n.tryCatch,n.errorObj,n.notEnumerableProp,e)};var g=a?m:function(a,u,c,l,f,h){var p=function(){return this}(),d=a;function y(){var n=u;u===r&&(n=this);var c=new t(e);c._captureStackTrace();var l="string"==typeof d&&this!==p?this[d]:a,f=i(c,h);try{l.apply(n,o(arguments,f))}catch(t){c._rejectCallback(s(t),!0,!0)}return c._isFateSealed()||c._setAsyncGuaranteed(),c}return"string"==typeof d&&(a=l),n.notEnumerableProp(y,"__isPromisified__",!0),y};function _(t,e,i,o,s){for(var a=new RegExp(e.replace(/([$])/,"\\$")+"$"),u=y(t,e,a,i),c=0,l=u.length;c<l;c+=2){var f=u[c],h=u[c+1],p=f+e;if(o===g)t[p]=g(f,r,f,h,e,s);else{var d=o(h,function(){return g(f,r,f,h,e,s)});n.notEnumerableProp(d,"__isPromisified__",!0),t[p]=d}}return n.toFastProperties(t),t}t.promisify=function(t,e){if("function"!=typeof t)throw new u("expecting a function but got "+n.classString(t));if(p(t))return t;var i=function(t,e,r){return g(t,e,void 0,t,null,r)}(t,void 0===(e=Object(e)).context?r:e.context,!!e.multiArgs);return n.copyDescriptors(t,i,h),i},t.promisifyAll=function(t,e){if("function"!=typeof t&&"object"!=typeof t)throw new u("the target of promisifyAll must be an object or a function\n\n See http://goo.gl/MqrFmX\n");var r=!!(e=Object(e)).multiArgs,i=e.suffix;"string"!=typeof i&&(i="Async");var o=e.filter;"function"!=typeof o&&(o=f);var s=e.promisifier;if("function"!=typeof s&&(s=g),!n.isIdentifier(i))throw new RangeError("suffix must be a valid identifier\n\n See http://goo.gl/MqrFmX\n");for(var a=n.inheritedDataKeys(t),c=0;c<a.length;++c){var l=t[a[c]];"constructor"!==a[c]&&n.isClass(l)&&(_(l.prototype,i,o,s,r),_(l,i,o,s,r))}return _(t,i,o,s,r)}}),Dd}function Ey(){return Bd||(Bd=1,Nd=function(t,e,r,n){var i,o=Qp(),s=o.isObject,a=Vp();"function"==typeof Map&&(i=Map);var u=function(){var t=0,e=0;function r(r,n){this[t]=r,this[t+e]=n,t++}return function(n){e=n.size,t=0;var i=new Array(2*n.size);return n.forEach(r,i),i}}();function c(t){var e,r=!1;if(void 0!==i&&t instanceof i)e=u(t),r=!0;else{var n=a.keys(t),o=n.length;e=new Array(2*o);for(var s=0;s<o;++s){var c=n[s];e[s]=t[c],e[s+o]=c}}this.constructor$(e),this._isMap=r,this._init$(void 0,r?-6:-3)}function l(e){var i,o=r(e);return s(o)?(i=o instanceof t?o._then(t.props,void 0,void 0,void 0,void 0):new c(o).promise(),o instanceof t&&i._propagateFrom(o,2),i):n("cannot await properties of a non-object\n\n See http://goo.gl/MqrFmX\n")}o.inherits(c,e),c.prototype._init=function(){},c.prototype._promiseFulfilled=function(t,e){if(this._values[e]=t,++this._totalResolved>=this._length){var r;if(this._isMap)r=function(t){for(var e=new i,r=t.length/2|0,n=0;n<r;++n){var o=t[r+n],s=t[n];e.set(o,s)}return e}(this._values);else{r={};for(var n=this.length(),o=0,s=this.length();o<s;++o)r[this._values[o+n]]=this._values[o]}return this._resolve(r),!0}return!1},c.prototype.shouldCopyValues=function(){return!1},c.prototype.getActualLength=function(t){return t>>1},t.prototype.props=function(){return l(this)},t.props=function(t){return l(t)}}),Nd}function ky(){return zd||(zd=1,Ud=function(t,e,r,n){var i=Qp();function o(s,a){var u=r(s);if(u instanceof t)return function(t){return t.then(function(e){return o(e,t)})}(u);if(null===(s=i.asArray(s)))return n("expecting an array or an iterable object but got "+i.classString(s));var c=new t(e);void 0!==a&&c._propagateFrom(a,3);for(var l=c._fulfill,f=c._reject,h=0,p=s.length;h<p;++h){var d=s[h];(void 0!==d||h in s)&&t.cast(d)._then(l,f,void 0,c,null)}return c}t.race=function(t){return o(t,void 0)},t.prototype.race=function(){return o(this,void 0)}}),Ud}function xy(){return Zd||(Zd=1,Qd=function(t,e,r){var n=Qp(),i=t.TimeoutError;function o(t){this.handle=t}o.prototype._resultCancelled=function(){clearTimeout(this.handle)};var s=function(t){return a(+this).thenReturn(t)},a=t.delay=function(n,i){var a,u;return void 0!==i?(a=t.resolve(i)._then(s,null,null,n,void 0),r.cancellation()&&i instanceof t&&a._setOnCancel(i)):(a=new t(e),u=setTimeout(function(){a._fulfill()},+n),r.cancellation()&&a._setOnCancel(new o(u)),a._captureStackTrace()),a._setAsyncGuaranteed(),a};t.prototype.delay=function(t){return a(t,this)};function u(t){return clearTimeout(this.handle),t}function c(t){throw clearTimeout(this.handle),t}t.prototype.timeout=function(t,e){var s,a;t=+t;var l=new o(setTimeout(function(){s.isPending()&&function(t,e,r){var o;o="string"!=typeof e?e instanceof Error?e:new i("operation timed out"):new i(e),n.markAsOriginatingFromRejection(o),t._attachExtraTrace(o),t._reject(o),null!=r&&r.cancel()}(s,e,a)},t));return r.cancellation()?(a=this.then(),(s=a._then(u,c,void 0,l,void 0))._setOnCancel(l)):s=this._then(u,c,void 0,l,void 0),s}}),Qd}function Oy(){return Jd||(Jd=1,Kd=function(t,e,r,n,i,o){var s=Qp(),a=hy().TypeError,u=Qp().inherits,c=s.errorObj,l=s.tryCatch,f={};function h(t){setTimeout(function(){throw t},0)}function p(e,n){var o=0,s=e.length,a=new t(i);return function i(){if(o>=s)return a._fulfill();var u=function(t){var e=r(t);return e!==t&&"function"==typeof t._isDisposable&&"function"==typeof t._getDisposer&&t._isDisposable()&&e._setDisposable(t._getDisposer()),e}(e[o++]);if(u instanceof t&&u._isDisposable()){try{u=r(u._getDisposer().tryDispose(n),e.promise)}catch(t){return h(t)}if(u instanceof t)return u._then(i,h,null,null,null)}i()}(),a}function d(t,e,r){this._data=t,this._promise=e,this._context=r}function y(t,e,r){this.constructor$(t,e,r)}function m(t){return d.isDisposer(t)?(this.resources[this.index]._setDisposable(t),t.promise()):t}function g(t){this.length=t,this.promise=null,this[t-1]=null}d.prototype.data=function(){return this._data},d.prototype.promise=function(){return this._promise},d.prototype.resource=function(){return this.promise().isFulfilled()?this.promise().value():f},d.prototype.tryDispose=function(t){var e=this.resource(),r=this._context;void 0!==r&&r._pushContext();var n=e!==f?this.doDispose(e,t):null;return void 0!==r&&r._popContext(),this._promise._unsetDisposable(),this._data=null,n},d.isDisposer=function(t){return null!=t&&"function"==typeof t.resource&&"function"==typeof t.tryDispose},u(y,d),y.prototype.doDispose=function(t,e){return this.data().call(t,t,e)},g.prototype._resultCancelled=function(){for(var e=this.length,r=0;r<e;++r){var n=this[r];n instanceof t&&n.cancel()}},t.using=function(){var n=arguments.length;if(n<2)return e("you must pass at least 2 arguments to Promise.using");var i,a=arguments[n-1];if("function"!=typeof a)return e("expecting a function but got "+s.classString(a));var u=!0;2===n&&Array.isArray(arguments[0])?(n=(i=arguments[0]).length,u=!1):(i=arguments,n--);for(var f=new g(n),h=0;h<n;++h){var y=i[h];if(d.isDisposer(y)){var _=y;(y=y.promise())._setDisposable(_)}else{var b=r(y);b instanceof t&&(y=b._then(m,null,null,{resources:f,index:h},void 0))}f[h]=y}var v=new Array(f.length);for(h=0;h<v.length;++h)v[h]=t.resolve(f[h]).reflect();var w=t.all(v).then(function(t){for(var e=0;e<t.length;++e){var r=t[e];if(r.isRejected())return c.e=r.error(),c;if(!r.isFulfilled())return void w.cancel();t[e]=r.value()}S._pushContext(),a=l(a);var n=u?a.apply(void 0,t):a(t),i=S._popContext();return o.checkForgottenReturns(n,i,"Promise.using",S),n}),S=w.lastly(function(){var e=new t.PromiseInspection(w);return p(f,e)});return f.promise=S,S._setOnCancel(f),S},t.prototype._setDisposable=function(t){this._bitField=131072|this._bitField,this._disposer=t},t.prototype._isDisposable=function(){return(131072&this._bitField)>0},t.prototype._getDisposer=function(){return this._disposer},t.prototype._unsetDisposable=function(){this._bitField=-131073&this._bitField,this._disposer=void 0},t.prototype.disposer=function(t){if("function"==typeof t)return new y(t,this,n());throw new a}}),Kd}function Ty(){return iy||(iy=1,(t=qp).exports=function(){var e=function(){return new m("circular promise resolution chain\n\n See http://goo.gl/MqrFmX\n")},r=function(){return new L.PromiseInspection(this._target())},n=function(t){return L.reject(new m(t))};function i(){}var o={},s=Qp();s.setReflectHandler(r);var a=function(){var t=process.domain;return void 0===t?null:t},u=function(){return{domain:a(),async:null}},c=s.isNode&&s.nodeSupportsAsyncResource?E.AsyncResource:null,l=function(){return{domain:a(),async:new c("Bluebird::Promise")}},f=s.isNode?u:function(){return null};s.notEnumerableProp(L,"_getContext",f);var h=Vp(),p=fy(),d=new p;h.defineProperty(L,"_async",{value:d});var y=hy(),m=L.TypeError=y.TypeError;L.RangeError=y.RangeError;var g=L.CancellationError=y.CancellationError;L.TimeoutError=y.TimeoutError,L.OperationalError=y.OperationalError,L.RejectionError=y.OperationalError,L.AggregateError=y.AggregateError;var _=function(){},b={},v={},w=py()(L,_),S=dy()(L,_,w,n,i),k=(ad?sd:(ad=1,sd=function(t){var e=!1,r=[];function n(){this._trace=new n.CapturedTrace(i())}function i(){var t=r.length-1;if(t>=0)return r[t]}return t.prototype._promiseCreated=function(){},t.prototype._pushContext=function(){},t.prototype._popContext=function(){return null},t._peekContext=t.prototype._peekContext=function(){},n.prototype._pushContext=function(){void 0!==this._trace&&(this._trace._promiseCreated=null,r.push(this._trace))},n.prototype._popContext=function(){if(void 0!==this._trace){var t=r.pop(),e=t._promiseCreated;return t._promiseCreated=null,e}return null},n.CapturedTrace=null,n.create=function(){if(e)return new n},n.deactivateLongStackTraces=function(){},n.activateLongStackTraces=function(){var r=t.prototype._pushContext,o=t.prototype._popContext,s=t._peekContext,a=t.prototype._peekContext,u=t.prototype._promiseCreated;n.deactivateLongStackTraces=function(){t.prototype._pushContext=r,t.prototype._popContext=o,t._peekContext=s,t.prototype._peekContext=a,t.prototype._promiseCreated=u,e=!1},e=!0,t.prototype._pushContext=n.prototype._pushContext,t.prototype._popContext=n.prototype._popContext,t._peekContext=t.prototype._peekContext=i,t.prototype._promiseCreated=function(){var t=this._peekContext();t&&null==t._promiseCreated&&(t._promiseCreated=this)}},n}))(L),x=k.create,O=yy()(L,k,function(){f=l,s.notEnumerableProp(L,"_getContext",l)},function(){f=u,s.notEnumerableProp(L,"_getContext",u)});O.CapturedTrace;var T=gy()(L,w,v),j=my()(v),C=_y(),R=s.errorObj,P=s.tryCatch;function L(t){t!==_&&function(t,e){if(null==t||t.constructor!==L)throw new m("the promise constructor cannot be invoked directly\n\n See http://goo.gl/MqrFmX\n");if("function"!=typeof e)throw new m("expecting a function but got "+s.classString(e))}(this,t),this._bitField=0,this._fulfillmentHandler0=void 0,this._rejectionHandler0=void 0,this._promise0=void 0,this._receiver0=void 0,this._resolveFromExecutor(t),this._promiseCreated(),this._fireEvent("promiseCreated",this)}function F(t){this.promise._resolveCallback(t)}function A(t){this.promise._rejectCallback(t,!1)}function I(t){var e=new L(_);e._fulfillmentHandler0=t,e._rejectionHandler0=t,e._promise0=t,e._receiver0=t}return L.prototype.toString=function(){return"[object Promise]"},L.prototype.caught=L.prototype.catch=function(t){var e=arguments.length;if(e>1){var r,i=new Array(e-1),o=0;for(r=0;r<e-1;++r){var a=arguments[r];if(!s.isObject(a))return n("Catch statement predicate: expecting an object but got "+s.classString(a));i[o++]=a}if(i.length=o,"function"!=typeof(t=arguments[r]))throw new m("The last argument to .catch() must be a function, got "+s.toString(t));return this.then(void 0,j(i,t,this))}return this.then(void 0,t)},L.prototype.reflect=function(){return this._then(r,r,void 0,this,void 0)},L.prototype.then=function(t,e){if(O.warnings()&&arguments.length>0&&"function"!=typeof t&&"function"!=typeof e){var r=".then() only accepts functions but was passed: "+s.classString(t);arguments.length>1&&(r+=", "+s.classString(e)),this._warn(r)}return this._then(t,e,void 0,void 0,void 0)},L.prototype.done=function(t,e){this._then(t,e,void 0,void 0,void 0)._setIsFinal()},L.prototype.spread=function(t){return"function"!=typeof t?n("expecting a function but got "+s.classString(t)):this.all()._then(t,void 0,void 0,b,void 0)},L.prototype.toJSON=function(){var t={isFulfilled:!1,isRejected:!1,fulfillmentValue:void 0,rejectionReason:void 0};return this.isFulfilled()?(t.fulfillmentValue=this.value(),t.isFulfilled=!0):this.isRejected()&&(t.rejectionReason=this.reason(),t.isRejected=!0),t},L.prototype.all=function(){return arguments.length>0&&this._warn(".all() was passed arguments but it does not take any"),new S(this).promise()},L.prototype.error=function(t){return this.caught(s.originatesFromRejection,t)},L.getNewLibraryCopy=t.exports,L.is=function(t){return t instanceof L},L.fromNode=L.fromCallback=function(t){var e=new L(_);e._captureStackTrace();var r=arguments.length>1&&!!Object(arguments[1]).multiArgs,n=P(t)(C(e,r));return n===R&&e._rejectCallback(n.e,!0),e._isFateSealed()||e._setAsyncGuaranteed(),e},L.all=function(t){return new S(t).promise()},L.cast=function(t){var e=w(t);return e instanceof L||((e=new L(_))._captureStackTrace(),e._setFulfilled(),e._rejectionHandler0=t),e},L.resolve=L.fulfilled=L.cast,L.reject=L.rejected=function(t){var e=new L(_);return e._captureStackTrace(),e._rejectCallback(t,!0),e},L.setScheduler=function(t){if("function"!=typeof t)throw new m("expecting a function but got "+s.classString(t));return d.setScheduler(t)},L.prototype._then=function(t,e,r,n,i){var o=void 0!==i,a=o?i:new L(_),u=this._target(),c=u._bitField;o||(a._propagateFrom(this,3),a._captureStackTrace(),void 0===n&&2097152&this._bitField&&(n=50397184&c?this._boundValue():u===this?void 0:this._boundTo),this._fireEvent("promiseChained",this,a));var l=f();if(50397184&c){var h,p,y=u._settlePromiseCtx;33554432&c?(p=u._rejectionHandler0,h=t):16777216&c?(p=u._fulfillmentHandler0,h=e,u._unsetRejectionIsUnhandled()):(y=u._settlePromiseLateCancellationObserver,p=new g("late cancellation observer"),u._attachExtraTrace(p),h=e),d.invoke(y,u,{handler:s.contextBind(l,h),promise:a,receiver:n,value:p})}else u._addCallbacks(t,e,a,n,l);return a},L.prototype._length=function(){return 65535&this._bitField},L.prototype._isFateSealed=function(){return!!(117506048&this._bitField)},L.prototype._isFollowing=function(){return!(67108864&~this._bitField)},L.prototype._setLength=function(t){this._bitField=-65536&this._bitField|65535&t},L.prototype._setFulfilled=function(){this._bitField=33554432|this._bitField,this._fireEvent("promiseFulfilled",this)},L.prototype._setRejected=function(){this._bitField=16777216|this._bitField,this._fireEvent("promiseRejected",this)},L.prototype._setFollowing=function(){this._bitField=67108864|this._bitField,this._fireEvent("promiseResolved",this)},L.prototype._setIsFinal=function(){this._bitField=4194304|this._bitField},L.prototype._isFinal=function(){return(4194304&this._bitField)>0},L.prototype._unsetCancelled=function(){this._bitField=-65537&this._bitField},L.prototype._setCancelled=function(){this._bitField=65536|this._bitField,this._fireEvent("promiseCancelled",this)},L.prototype._setWillBeCancelled=function(){this._bitField=8388608|this._bitField},L.prototype._setAsyncGuaranteed=function(){if(!d.hasCustomScheduler()){var t=this._bitField;this._bitField=t|(536870912&t)>>2^134217728}},L.prototype._setNoAsyncGuarantee=function(){this._bitField=-134217729&this._bitField|536870912},L.prototype._receiverAt=function(t){var e=0===t?this._receiver0:this[4*t-4+3];if(e!==o)return void 0===e&&this._isBound()?this._boundValue():e},L.prototype._promiseAt=function(t){return this[4*t-4+2]},L.prototype._fulfillmentHandlerAt=function(t){return this[4*t-4+0]},L.prototype._rejectionHandlerAt=function(t){return this[4*t-4+1]},L.prototype._boundValue=function(){},L.prototype._migrateCallback0=function(t){t._bitField;var e=t._fulfillmentHandler0,r=t._rejectionHandler0,n=t._promise0,i=t._receiverAt(0);void 0===i&&(i=o),this._addCallbacks(e,r,n,i,null)},L.prototype._migrateCallbackAt=function(t,e){var r=t._fulfillmentHandlerAt(e),n=t._rejectionHandlerAt(e),i=t._promiseAt(e),s=t._receiverAt(e);void 0===s&&(s=o),this._addCallbacks(r,n,i,s,null)},L.prototype._addCallbacks=function(t,e,r,n,i){var o=this._length();if(o>=65531&&(o=0,this._setLength(0)),0===o)this._promise0=r,this._receiver0=n,"function"==typeof t&&(this._fulfillmentHandler0=s.contextBind(i,t)),"function"==typeof e&&(this._rejectionHandler0=s.contextBind(i,e));else{var a=4*o-4;this[a+2]=r,this[a+3]=n,"function"==typeof t&&(this[a+0]=s.contextBind(i,t)),"function"==typeof e&&(this[a+1]=s.contextBind(i,e))}return this._setLength(o+1),o},L.prototype._proxy=function(t,e){this._addCallbacks(void 0,void 0,e,t,null)},L.prototype._resolveCallback=function(t,r){if(!(117506048&this._bitField)){if(t===this)return this._rejectCallback(e(),!1);var n=w(t,this);if(!(n instanceof L))return this._fulfill(t);r&&this._propagateFrom(n,2);var i=n._target();if(i!==this){var o=i._bitField;if(50397184&o)if(33554432&o)this._fulfill(i._value());else if(16777216&o)this._reject(i._reason());else{var s=new g("late cancellation observer");i._attachExtraTrace(s),this._reject(s)}else{var a=this._length();a>0&&i._migrateCallback0(this);for(var u=1;u<a;++u)i._migrateCallbackAt(this,u);this._setFollowing(),this._setLength(0),this._setFollowee(n)}}else this._reject(e())}},L.prototype._rejectCallback=function(t,e,r){var n=s.ensureErrorObject(t),i=n===t;if(!i&&!r&&O.warnings()){var o="a promise was rejected with a non-error: "+s.classString(t);this._warn(o,!0)}this._attachExtraTrace(n,!!e&&i),this._reject(t)},L.prototype._resolveFromExecutor=function(t){if(t!==_){var e=this;this._captureStackTrace(),this._pushContext();var r=!0,n=this._execute(t,function(t){e._resolveCallback(t)},function(t){e._rejectCallback(t,r)});r=!1,this._popContext(),void 0!==n&&e._rejectCallback(n,!0)}},L.prototype._settlePromiseFromHandler=function(t,e,r,n){var i=n._bitField;if(!(65536&i)){var o;n._pushContext(),e===b?r&&"number"==typeof r.length?o=P(t).apply(this._boundValue(),r):(o=R).e=new m("cannot .spread() a non-array: "+s.classString(r)):o=P(t).call(e,r);var a=n._popContext();65536&(i=n._bitField)||(o===v?n._reject(r):o===R?n._rejectCallback(o.e,!1):(O.checkForgottenReturns(o,a,"",n,this),n._resolveCallback(o)))}},L.prototype._target=function(){for(var t=this;t._isFollowing();)t=t._followee();return t},L.prototype._followee=function(){return this._rejectionHandler0},L.prototype._setFollowee=function(t){this._rejectionHandler0=t},L.prototype._settlePromise=function(t,e,n,o){var s=t instanceof L,a=this._bitField,u=!!(134217728&a);65536&a?(s&&t._invokeInternalOnCancel(),n instanceof T&&n.isFinallyHandler()?(n.cancelPromise=t,P(e).call(n,o)===R&&t._reject(R.e)):e===r?t._fulfill(r.call(n)):n instanceof i?n._promiseCancelled(t):s||t instanceof S?t._cancel():n.cancel()):"function"==typeof e?s?(u&&t._setAsyncGuaranteed(),this._settlePromiseFromHandler(e,n,o,t)):e.call(n,o,t):n instanceof i?n._isResolved()||(33554432&a?n._promiseFulfilled(o,t):n._promiseRejected(o,t)):s&&(u&&t._setAsyncGuaranteed(),33554432&a?t._fulfill(o):t._reject(o))},L.prototype._settlePromiseLateCancellationObserver=function(t){var e=t.handler,r=t.promise,n=t.receiver,i=t.value;"function"==typeof e?r instanceof L?this._settlePromiseFromHandler(e,n,i,r):e.call(n,i,r):r instanceof L&&r._reject(i)},L.prototype._settlePromiseCtx=function(t){this._settlePromise(t.promise,t.handler,t.receiver,t.value)},L.prototype._settlePromise0=function(t,e,r){var n=this._promise0,i=this._receiverAt(0);this._promise0=void 0,this._receiver0=void 0,this._settlePromise(n,t,i,e)},L.prototype._clearCallbackDataAtIndex=function(t){var e=4*t-4;this[e+2]=this[e+3]=this[e+0]=this[e+1]=void 0},L.prototype._fulfill=function(t){var r=this._bitField;if(!((117506048&r)>>>16)){if(t===this){var n=e();return this._attachExtraTrace(n),this._reject(n)}this._setFulfilled(),this._rejectionHandler0=t,(65535&r)>0&&(134217728&r?this._settlePromises():d.settlePromises(this),this._dereferenceTrace())}},L.prototype._reject=function(t){var e=this._bitField;if(!((117506048&e)>>>16)){if(this._setRejected(),this._fulfillmentHandler0=t,this._isFinal())return d.fatalError(t,s.isNode);(65535&e)>0?d.settlePromises(this):this._ensurePossibleRejectionHandled()}},L.prototype._fulfillPromises=function(t,e){for(var r=1;r<t;r++){var n=this._fulfillmentHandlerAt(r),i=this._promiseAt(r),o=this._receiverAt(r);this._clearCallbackDataAtIndex(r),this._settlePromise(i,n,o,e)}},L.prototype._rejectPromises=function(t,e){for(var r=1;r<t;r++){var n=this._rejectionHandlerAt(r),i=this._promiseAt(r),o=this._receiverAt(r);this._clearCallbackDataAtIndex(r),this._settlePromise(i,n,o,e)}},L.prototype._settlePromises=function(){var t=this._bitField,e=65535&t;if(e>0){if(16842752&t){var r=this._fulfillmentHandler0;this._settlePromise0(this._rejectionHandler0,r,t),this._rejectPromises(e,r)}else{var n=this._rejectionHandler0;this._settlePromise0(this._fulfillmentHandler0,n,t),this._fulfillPromises(e,n)}this._setLength(0)}this._clearCancellationData()},L.prototype._settledValue=function(){var t=this._bitField;return 33554432&t?this._rejectionHandler0:16777216&t?this._fulfillmentHandler0:void 0},"undefined"!=typeof Symbol&&Symbol.toStringTag&&h.defineProperty(L.prototype,Symbol.toStringTag,{get:function(){return"Object"}}),L.defer=L.pending=function(){return O.deprecated("Promise.defer","new Promise"),{promise:new L(_),resolve:F,reject:A}},s.notEnumerableProp(L,"_makeSelfResolutionError",e),(gd||(gd=1,md=function(t,e,r,n,i){var o=Qp(),s=o.tryCatch;t.method=function(r){if("function"!=typeof r)throw new t.TypeError("expecting a function but got "+o.classString(r));return function(){var n=new t(e);n._captureStackTrace(),n._pushContext();var o=s(r).apply(this,arguments),a=n._popContext();return i.checkForgottenReturns(o,a,"Promise.method",n),n._resolveFromSyncValue(o),n}},t.attempt=t.try=function(r){if("function"!=typeof r)return n("expecting a function but got "+o.classString(r));var a,u=new t(e);if(u._captureStackTrace(),u._pushContext(),arguments.length>1){i.deprecated("calling Promise.try with more than 1 argument");var c=arguments[1],l=arguments[2];a=o.isArray(c)?s(r).apply(l,c):s(r).call(l,c)}else a=s(r)();var f=u._popContext();return i.checkForgottenReturns(a,f,"Promise.try",u),u._resolveFromSyncValue(a),u},t.prototype._resolveFromSyncValue=function(t){t===o.errorObj?this._rejectCallback(t.e,!1):this._resolveCallback(t,!0)}}),md)(L,_,w,n,O),(bd||(bd=1,_d=function(t,e,r,n){var i=!1,o=function(t,e){this._reject(e)},s=function(t,e){e.promiseRejectionQueued=!0,e.bindingPromise._then(o,o,null,this,t)},a=function(t,e){50397184&this._bitField||this._resolveCallback(e.target)},u=function(t,e){e.promiseRejectionQueued||this._reject(t)};t.prototype.bind=function(o){i||(i=!0,t.prototype._propagateFrom=n.propagateFromFunction(),t.prototype._boundValue=n.boundValueFunction());var c=r(o),l=new t(e);l._propagateFrom(this,1);var f=this._target();if(l._setBoundTo(c),c instanceof t){var h={promiseRejectionQueued:!1,promise:l,target:f,bindingPromise:c};f._then(e,s,void 0,l,h),c._then(a,u,void 0,l,h),l._setOnCancel(c)}else l._resolveCallback(f);return l},t.prototype._setBoundTo=function(t){void 0!==t?(this._bitField=2097152|this._bitField,this._boundTo=t):this._bitField=-2097153&this._bitField},t.prototype._isBound=function(){return!(2097152&~this._bitField)},t.bind=function(e,r){return t.resolve(r).bind(e)}}),_d)(L,_,w,O),(wd||(wd=1,vd=function(t,e,r,n){var i=Qp(),o=i.tryCatch,s=i.errorObj,a=t._async;t.prototype.break=t.prototype.cancel=function(){if(!n.cancellation())return this._warn("cancellation is disabled");for(var t=this,e=t;t._isCancellable();){if(!t._cancelBy(e)){e._isFollowing()?e._followee().cancel():e._cancelBranched();break}var r=t._cancellationParent;if(null==r||!r._isCancellable()){t._isFollowing()?t._followee().cancel():t._cancelBranched();break}t._isFollowing()&&t._followee().cancel(),t._setWillBeCancelled(),e=t,t=r}},t.prototype._branchHasCancelled=function(){this._branchesRemainingToCancel--},t.prototype._enoughBranchesHaveCancelled=function(){return void 0===this._branchesRemainingToCancel||this._branchesRemainingToCancel<=0},t.prototype._cancelBy=function(t){return t===this?(this._branchesRemainingToCancel=0,this._invokeOnCancel(),!0):(this._branchHasCancelled(),!!this._enoughBranchesHaveCancelled()&&(this._invokeOnCancel(),!0))},t.prototype._cancelBranched=function(){this._enoughBranchesHaveCancelled()&&this._cancel()},t.prototype._cancel=function(){this._isCancellable()&&(this._setCancelled(),a.invoke(this._cancelPromises,this,void 0))},t.prototype._cancelPromises=function(){this._length()>0&&this._settlePromises()},t.prototype._unsetOnCancel=function(){this._onCancelField=void 0},t.prototype._isCancellable=function(){return this.isPending()&&!this._isCancelled()},t.prototype.isCancellable=function(){return this.isPending()&&!this.isCancelled()},t.prototype._doInvokeOnCancel=function(t,e){if(i.isArray(t))for(var r=0;r<t.length;++r)this._doInvokeOnCancel(t[r],e);else if(void 0!==t)if("function"==typeof t){if(!e){var n=o(t).call(this._boundValue());n===s&&(this._attachExtraTrace(n.e),a.throwLater(n.e))}}else t._resultCancelled(this)},t.prototype._invokeOnCancel=function(){var t=this._onCancel();this._unsetOnCancel(),a.invoke(this._doInvokeOnCancel,this,t)},t.prototype._invokeInternalOnCancel=function(){this._isCancellable()&&(this._doInvokeOnCancel(this._onCancel(),!0),this._unsetOnCancel())},t.prototype._resultCancelled=function(){this.cancel()}}),vd)(L,S,n,O),(Ed||(Ed=1,Sd=function(t){function e(){return this.value}function r(){throw this.reason}t.prototype.return=t.prototype.thenReturn=function(r){return r instanceof t&&r.suppressUnhandledRejections(),this._then(e,void 0,void 0,{value:r},void 0)},t.prototype.throw=t.prototype.thenThrow=function(t){return this._then(r,void 0,void 0,{reason:t},void 0)},t.prototype.catchThrow=function(t){if(arguments.length<=1)return this._then(void 0,r,void 0,{reason:t},void 0);var e=arguments[1];return this.caught(t,function(){throw e})},t.prototype.catchReturn=function(r){if(arguments.length<=1)return r instanceof t&&r.suppressUnhandledRejections(),this._then(void 0,e,void 0,{value:r},void 0);var n=arguments[1];return n instanceof t&&n.suppressUnhandledRejections(),this.caught(r,function(){return n})}}),Sd)(L),by()(L),(Td||(Td=1,Od=function(t,e,r,n,i){var o,s=Qp(),a=s.canEvaluate,u=s.tryCatch,c=s.errorObj;if(a){for(var l=function(t){return new Function("value","holder"," \n\t 'use strict'; \n\t holder.pIndex = value; \n\t holder.checkFulfillment(this); \n\t ".replace(/Index/g,t))},f=function(t){return new Function("promise","holder"," \n\t 'use strict'; \n\t holder.pIndex = promise; \n\t ".replace(/Index/g,t))},h=function(e){for(var r=new Array(e),n=0;n<r.length;++n)r[n]="this.p"+(n+1);var o=r.join(" = ")+" = null;",s="var promise;\n"+r.map(function(t){return" \n\t promise = "+t+"; \n\t if (promise instanceof Promise) { \n\t promise.cancel(); \n\t } \n\t "}).join("\n"),a=r.join(", "),l="Holder$"+e,f="return function(tryCatch, errorObj, Promise, async) { \n\t 'use strict'; \n\t function [TheName](fn) { \n\t [TheProperties] \n\t this.fn = fn; \n\t this.asyncNeeded = true; \n\t this.now = 0; \n\t } \n\t \n\t [TheName].prototype._callFunction = function(promise) { \n\t promise._pushContext(); \n\t var ret = tryCatch(this.fn)([ThePassedArguments]); \n\t promise._popContext(); \n\t if (ret === errorObj) { \n\t promise._rejectCallback(ret.e, false); \n\t } else { \n\t promise._resolveCallback(ret); \n\t } \n\t }; \n\t \n\t [TheName].prototype.checkFulfillment = function(promise) { \n\t var now = ++this.now; \n\t if (now === [TheTotal]) { \n\t if (this.asyncNeeded) { \n\t async.invoke(this._callFunction, this, promise); \n\t } else { \n\t this._callFunction(promise); \n\t } \n\t \n\t } \n\t }; \n\t \n\t [TheName].prototype._resultCancelled = function() { \n\t [CancellationCode] \n\t }; \n\t \n\t return [TheName]; \n\t }(tryCatch, errorObj, Promise, async); \n\t ";return f=f.replace(/\[TheName\]/g,l).replace(/\[TheTotal\]/g,e).replace(/\[ThePassedArguments\]/g,a).replace(/\[TheProperties\]/g,o).replace(/\[CancellationCode\]/g,s),new Function("tryCatch","errorObj","Promise","async",f)(u,c,t,i)},p=[],d=[],y=[],m=0;m<8;++m)p.push(h(m+1)),d.push(l(m+1)),y.push(f(m+1));o=function(t){this._reject(t)}}t.join=function(){var i,u=arguments.length-1;if(u>0&&"function"==typeof arguments[u]&&(i=arguments[u],u<=8&&a)){(w=new t(n))._captureStackTrace();for(var c=new(0,p[u-1])(i),l=d,f=0;f<u;++f){var h=r(arguments[f],w);if(h instanceof t){var m=(h=h._target())._bitField;50397184&m?33554432&m?l[f].call(w,h._value(),c):16777216&m?w._reject(h._reason()):w._cancel():(h._then(l[f],o,void 0,w,c),y[f](h,c),c.asyncNeeded=!1)}else l[f].call(w,h,c)}if(!w._isFateSealed()){if(c.asyncNeeded){var g=t._getContext();c.fn=s.contextBind(g,c.fn)}w._setAsyncGuaranteed(),w._setOnCancel(c)}return w}for(var _=arguments.length,b=new Array(_),v=0;v<_;++v)b[v]=arguments[v];i&&b.pop();var w=new e(b).promise();return void 0!==i?w.spread(i):w}}),Od)(L,S,w,_,d),L.Promise=L,L.version="3.7.2",function(){if(Cd)return jd;Cd=1;var t=Object.create;if(t){var e=t(null),r=t(null);e[" size"]=r[" size"]=0}return jd=function(t){var n,i,o=Qp(),s=o.canEvaluate,a=o.isIdentifier,u=function(t){return new Function("ensureMethod"," \n\t return function(obj) { \n\t 'use strict' \n\t var len = this.length; \n\t ensureMethod(obj, 'methodName'); \n\t switch(len) { \n\t case 1: return obj.methodName(this[0]); \n\t case 2: return obj.methodName(this[0], this[1]); \n\t case 3: return obj.methodName(this[0], this[1], this[2]); \n\t case 0: return obj.methodName(); \n\t default: \n\t return obj.methodName.apply(obj, this); \n\t } \n\t }; \n\t ".replace(/methodName/g,t))(f)},c=function(t){return new Function("obj"," \n\t 'use strict'; \n\t return obj.propertyName; \n\t ".replace("propertyName",t))},l=function(t,e,r){var n=r[t];if("function"!=typeof n){if(!a(t))return null;if(n=e(t),r[t]=n,r[" size"]++,r[" size"]>512){for(var i=Object.keys(r),o=0;o<256;++o)delete r[i[o]];r[" size"]=i.length-256}}return n};function f(e,r){var n;if(null!=e&&(n=e[r]),"function"!=typeof n){var i="Object "+o.classString(e)+" has no method '"+o.toString(r)+"'";throw new t.TypeError(i)}return n}function h(t){return f(t,this.pop()).apply(t,this)}function p(t){return t[this]}function d(t){var e=+this;return e<0&&(e=Math.max(0,e+t.length)),t[e]}n=function(t){return l(t,u,e)},i=function(t){return l(t,c,r)},t.prototype.call=function(t){for(var e=arguments.length,r=new Array(Math.max(e-1,0)),i=1;i<e;++i)r[i-1]=arguments[i];if(s){var o=n(t);if(null!==o)return this._then(o,void 0,void 0,r,void 0)}return r.push(t),this._then(h,void 0,void 0,r,void 0)},t.prototype.get=function(t){var e;if("number"==typeof t)e=d;else if(s){var r=i(t);e=null!==r?r:p}else e=p;return this._then(e,void 0,void 0,t,void 0)}},jd}()(L),vy()(L,n,_,w,i,O),wy()(L,S,n,w,_,O),(Id||(Id=1,Ad=function(t){var e=Qp(),r=t._async,n=e.tryCatch,i=e.errorObj;function o(t,o){if(!e.isArray(t))return s.call(this,t,o);var a=n(o).apply(this._boundValue(),[null].concat(t));a===i&&r.throwLater(a.e)}function s(t,e){var o=this._boundValue(),s=void 0===t?n(e).call(o,null):n(e).call(o,null,t);s===i&&r.throwLater(s.e)}function a(t,e){if(!t){var o=new Error(t+"");o.cause=t,t=o}var s=n(e).call(this._boundValue(),t);s===i&&r.throwLater(s.e)}t.prototype.asCallback=t.prototype.nodeify=function(t,e){if("function"==typeof t){var r=s;void 0!==e&&Object(e).spread&&(r=o),this._then(r,a,void 0,this,t)}return this}}),Ad)(L),Sy()(L,_),Ey()(L,S,w,n),ky()(L,_,w,n),(Hd||(Hd=1,Wd=function(t,e,r,n,i,o){var s=Qp(),a=s.tryCatch;function u(e,r,n,o){this.constructor$(e);var a=t._getContext();this._fn=s.contextBind(a,r),void 0!==n&&(n=t.resolve(n))._attachCancellationCallback(this),this._initialValue=n,this._currentCancellable=null,this._eachValues=o===i?Array(this._length):0===o?null:void 0,this._promise._captureStackTrace(),this._init$(void 0,-5)}function c(t,e){this.isFulfilled()?e._resolve(t):e._reject(t)}function l(t,e,n,i){return"function"!=typeof e?r("expecting a function but got "+s.classString(e)):new u(t,e,n,i).promise()}function f(e){this.accum=e,this.array._gotAccum(e);var r=n(this.value,this.array._promise);return r instanceof t?(this.array._currentCancellable=r,r._then(h,void 0,void 0,this,void 0)):h.call(this,r)}function h(e){var r,n=this.array,i=n._promise,s=a(n._fn);i._pushContext(),(r=void 0!==n._eachValues?s.call(i._boundValue(),e,this.index,this.length):s.call(i._boundValue(),this.accum,e,this.index,this.length))instanceof t&&(n._currentCancellable=r);var u=i._popContext();return o.checkForgottenReturns(r,u,void 0!==n._eachValues?"Promise.each":"Promise.reduce",i),r}s.inherits(u,e),u.prototype._gotAccum=function(t){void 0!==this._eachValues&&null!==this._eachValues&&t!==i&&this._eachValues.push(t)},u.prototype._eachComplete=function(t){return null!==this._eachValues&&this._eachValues.push(t),this._eachValues},u.prototype._init=function(){},u.prototype._resolveEmptyArray=function(){this._resolve(void 0!==this._eachValues?this._eachValues:this._initialValue)},u.prototype.shouldCopyValues=function(){return!1},u.prototype._resolve=function(t){this._promise._resolveCallback(t),this._values=null},u.prototype._resultCancelled=function(e){if(e===this._initialValue)return this._cancel();this._isResolved()||(this._resultCancelled$(),this._currentCancellable instanceof t&&this._currentCancellable.cancel(),this._initialValue instanceof t&&this._initialValue.cancel())},u.prototype._iterate=function(e){var r,n;this._values=e;var i=e.length;void 0!==this._initialValue?(r=this._initialValue,n=0):(r=t.resolve(e[0]),n=1),this._currentCancellable=r;for(var o=n;o<i;++o){var s=e[o];s instanceof t&&s.suppressUnhandledRejections()}if(!r.isRejected())for(;n<i;++n){var a={accum:null,value:e[n],index:n,length:i,array:this};r=r._then(f,void 0,void 0,a,void 0),127&n||r._setNoAsyncGuarantee()}void 0!==this._eachValues&&(r=r._then(this._eachComplete,void 0,void 0,this,void 0)),r._then(c,c,void 0,r,this)},t.prototype.reduce=function(t,e){return l(this,t,e,null)},t.reduce=function(t,e,r,n){return l(t,e,r,n)}}),Wd)(L,S,n,w,_,O),(qd||(qd=1,$d=function(t,e,r){var n=t.PromiseInspection;function i(t){this.constructor$(t)}Qp().inherits(i,e),i.prototype._promiseResolved=function(t,e){return this._values[t]=e,++this._totalResolved>=this._length&&(this._resolve(this._values),!0)},i.prototype._promiseFulfilled=function(t,e){var r=new n;return r._bitField=33554432,r._settledValueField=t,this._promiseResolved(e,r)},i.prototype._promiseRejected=function(t,e){var r=new n;return r._bitField=16777216,r._settledValueField=t,this._promiseResolved(e,r)},t.settle=function(t){return r.deprecated(".settle()",".reflect()"),new i(t).promise()},t.allSettled=function(t){return new i(t).promise()},t.prototype.settle=function(){return t.settle(this)}}),$d)(L,S,O),(Vd||(Vd=1,Gd=function(t,e,r){var n=Qp(),i=hy().RangeError,o=hy().AggregateError,s=n.isArray,a={};function u(t){this.constructor$(t),this._howMany=0,this._unwrap=!1,this._initialized=!1}function c(t,e){if((0|e)!==e||e<0)return r("expecting a positive integer\n\n See http://goo.gl/MqrFmX\n");var n=new u(t),i=n.promise();return n.setHowMany(e),n.init(),i}n.inherits(u,e),u.prototype._init=function(){if(this._initialized)if(0!==this._howMany){this._init$(void 0,-5);var t=s(this._values);!this._isResolved()&&t&&this._howMany>this._canPossiblyFulfill()&&this._reject(this._getRangeError(this.length()))}else this._resolve([])},u.prototype.init=function(){this._initialized=!0,this._init()},u.prototype.setUnwrap=function(){this._unwrap=!0},u.prototype.howMany=function(){return this._howMany},u.prototype.setHowMany=function(t){this._howMany=t},u.prototype._promiseFulfilled=function(t){return this._addFulfilled(t),this._fulfilled()===this.howMany()&&(this._values.length=this.howMany(),1===this.howMany()&&this._unwrap?this._resolve(this._values[0]):this._resolve(this._values),!0)},u.prototype._promiseRejected=function(t){return this._addRejected(t),this._checkOutcome()},u.prototype._promiseCancelled=function(){return this._values instanceof t||null==this._values?this._cancel():(this._addRejected(a),this._checkOutcome())},u.prototype._checkOutcome=function(){if(this.howMany()>this._canPossiblyFulfill()){for(var t=new o,e=this.length();e<this._values.length;++e)this._values[e]!==a&&t.push(this._values[e]);return t.length>0?this._reject(t):this._cancel(),!0}return!1},u.prototype._fulfilled=function(){return this._totalResolved},u.prototype._rejected=function(){return this._values.length-this.length()},u.prototype._addRejected=function(t){this._values.push(t)},u.prototype._addFulfilled=function(t){this._values[this._totalResolved++]=t},u.prototype._canPossiblyFulfill=function(){return this.length()-this._rejected()},u.prototype._getRangeError=function(t){var e="Input array must contain at least "+this._howMany+" items but contains only "+t+" items";return new i(e)},u.prototype._resolveEmptyArray=function(){this._reject(this._getRangeError(0))},t.some=function(t,e){return c(t,e)},t.prototype.some=function(t){return c(this,t)},t._SomePromiseArray=u}),Gd)(L,S,n),xy()(L,_,O),Oy()(L,n,w,x,_,O),(Xd||(Xd=1,Yd=function(t){var e=t._SomePromiseArray;function r(t){var r=new e(t),n=r.promise();return r.setHowMany(1),r.setUnwrap(),r.init(),n}t.any=function(t){return r(t)},t.prototype.any=function(){return r(this)}}),Yd)(L),(ey?ty:(ey=1,ty=function(t,e){var r=t.reduce,n=t.all;function i(){return n(this)}t.prototype.each=function(t){return r(this,t,e,0)._then(i,void 0,void 0,this,void 0)},t.prototype.mapSeries=function(t){return r(this,t,e,e)},t.each=function(t,n){return r(t,n,e,0)._then(i,void 0,void 0,t,void 0)},t.mapSeries=function(t,n){return r(t,n,e,e)}}))(L,_),(ny?ry:(ny=1,ry=function(t,e){var r=t.map;t.prototype.filter=function(t,n){return r(this,t,n,e)},t.filter=function(t,n,i){return r(t,n,i,e)}}))(L,_),s.toFastProperties(L),s.toFastProperties(L.prototype),I({a:1}),I({b:2}),I({c:3}),I(1),I(function(){}),I(void 0),I(!1),I(new L(_)),O.setBounds(p.firstLineError,s.lastLineError),L}),qp.exports;var t}function jy(){if(uy)return ay;uy=1;const t=hf(),e=zp(),r=pf(),n=yf(),i=y,o=Lp(),s=mf(),a=df(),u=function(){if(sy)return oy;var t;sy=1,"undefined"!=typeof Promise&&(t=Promise);var e=Ty()();return e.noConflict=function(){try{Promise===e&&(Promise=t)}catch(t){}return e},oy=e}(),c=Buffer.alloc(4);return c.writeUInt32LE(101010256,0),ay=function(l,f){const h=t(),p=t(),d=f&&f.tailSize||80;let y,m,g,_;return f&&f.crx&&(m=function(e){const r=e.stream(0).pipe(t());return r.pull(4).then(function(t){if(875721283===t.readUInt32LE(0)){let t;return r.pull(12).then(function(e){t=a.parse(e,[["version",4],["pubKeyLength",4],["signatureLength",4]])}).then(function(){return r.pull(t.pubKeyLength+t.signatureLength)}).then(function(e){return t.publicKey=e.slice(0,t.pubKeyLength),t.signature=e.slice(t.pubKeyLength),t.size=16+t.pubKeyLength+t.signatureLength,t})}})}(l)),l.size().then(function(t){return y=t,l.stream(Math.max(0,t-d)).on("error",function(t){h.emit("error",t)}).pipe(h),h.pull(c)}).then(function(){return u.props({directory:h.pull(22),crxHeader:m})}).then(function(e){const r=e.directory;if(g=e.crxHeader&&e.crxHeader.size||0,_=a.parse(r,[["signature",4],["diskNumber",2],["diskStart",2],["numberOfRecordsOnDisk",2],["numberOfRecords",2],["sizeOfCentralDirectory",4],["offsetToStartOfCentralDirectory",4],["commentLength",2]]),65535==_.diskNumber||65535==_.numberOfRecords||4294967295==_.offsetToStartOfCentralDirectory){const e=20,r=y-(d-h.match+e),n=t();return l.stream(r).pipe(n),n.pull(e).then(function(e){return function(e,r){const n=a.parse(r,[["signature",4],["diskNumber",4],["offsetToStartOfCentralDirectory",8],["numberOfDisks",4]]);if(117853008!=n.signature)throw new Error("invalid zip64 end of central dir locator signature (0x07064b50): 0x"+n.signature.toString(16));const i=t();return e.stream(n.offsetToStartOfCentralDirectory).pipe(i),i.pull(56)}(l,e)}).then(function(t){_=function(t){const e=a.parse(t,[["signature",4],["sizeOfCentralDirectory",8],["version",2],["versionsNeededToExtract",2],["diskNumber",4],["diskStart",4],["numberOfRecordsOnDisk",8],["numberOfRecords",8],["sizeOfCentralDirectory",8],["offsetToStartOfCentralDirectory",8]]);if(101075792!=e.signature)throw new Error("invalid zip64 end of central dir locator signature (0x06064b50): 0x0"+e.signature.toString(16));return e}(t)})}_.offsetToStartOfCentralDirectory+=g}).then(function(){if(_.commentLength)return h.pull(_.commentLength).then(function(t){_.comment=t.toString("utf8")})}).then(function(){return l.stream(_.offsetToStartOfCentralDirectory).pipe(p),_.extract=function(t){if(!t||!t.path)throw new Error("PATH_MISSING");return t.path=i.resolve(i.normalize(t.path)),_.files.then(function(e){return u.map(e,async function(e){const r=i.join(t.path,e.path);if(0!=r.indexOf(t.path))return;if("Directory"==e.type)return void await o.ensureDir(r);await o.ensureDir(i.dirname(r));const n=t.getWriter?t.getWriter({path:r}):o.createWriteStream(r);return new Promise(function(r,i){e.stream(t.password).on("error",i).pipe(n).on("close",r).on("error",i)})},{concurrency:t.concurrency>1?t.concurrency:1})})},_.files=u.mapSeries(Array(_.numberOfRecords),function(){return p.pull(46).then(function(t){const i=a.parse(t,[["signature",4],["versionMadeBy",2],["versionsNeededToExtract",2],["flags",2],["compressionMethod",2],["lastModifiedTime",2],["lastModifiedDate",2],["crc32",4],["compressedSize",4],["uncompressedSize",4],["fileNameLength",2],["extraFieldLength",2],["fileCommentLength",2],["diskNumber",2],["internalFileAttributes",2],["externalFileAttributes",4],["offsetToLocalFileHeader",4]]);return i.offsetToLocalFileHeader+=g,i.lastModifiedDateTime=s(i.lastModifiedDate,i.lastModifiedTime),p.pull(i.fileNameLength).then(function(t){return i.pathBuffer=t,i.path=t.toString("utf8"),i.isUnicode=!!(2048&i.flags),p.pull(i.extraFieldLength)}).then(function(t){return i.extra=n(t,i),p.pull(i.fileCommentLength)}).then(function(t){i.comment=t,i.type=0===i.uncompressedSize&&/[/\\]$/.test(i.path)?"Directory":"File";const n=f&&f.padding||1e3;return i.stream=function(t){const r=30+n+(i.extraFieldLength||0)+(i.fileNameLength||0)+i.compressedSize;return e(l,i.offsetToLocalFileHeader,t,i,r)},i.buffer=function(t){return r(i.stream(t))},i})})}),u.props(_)})},ay}var Cy,Ry,Py,Ly=M(Object.freeze({__proto__:null,default:{}}));var Fy=(Py||(Py=1,ff.Parse=gf(),ff.ParseOne=function(){if(Qf)return Vf;Qf=1;const t=g,e=gf(),r=th(),n=pf();return Vf=function(i,o){const s=t.PassThrough({objectMode:!0}),a=t.PassThrough(),u=t.Transform({objectMode:!0}),c=i instanceof RegExp?i:i&&new RegExp(i);let l;u._transform=function(t,e,r){if(l||c&&!c.exec(t.path))return t.autodrain(),r();l=!0,f.emit("entry",t),t.on("error",function(t){a.emit("error",t)}),t.pipe(a).on("error",function(t){r(t)}).on("finish",function(t){r(null,t)})},s.pipe(e(o)).on("error",function(t){a.emit("error",t)}).pipe(u).on("error",Object).on("finish",function(){l?a.end():a.emit("error",new Error("PATTERN_NOT_FOUND"))});const f=r(s,a);return f.buffer=function(){return n(a)},f},Vf}(),ff.Extract=function(){if(lp)return cp;lp=1,cp=function(o){o.path=r.resolve(r.normalize(o.path));const s=new t(o),a=new n.Writable({objectMode:!0});a._write=async function(t,n,i){const s=r.join(o.path,t.path.replace(/\\/g,"/"));if(0!=s.indexOf(o.path))return i();if("Directory"==t.type)return await e.ensureDir(s),i();await e.ensureDir(r.dirname(s));const a=o.getWriter?o.getWriter({path:s}):e.createWriteStream(s);t.pipe(a).on("error",i).on("close",i)};const u=i(s,a);return s.once("crx-header",function(t){u.crxHeader=t}),s.pipe(a).on("finish",function(){u.emit("close")}),u.promise=function(){return new Promise(function(t,e){u.on("close",t),u.on("error",e)})},u};const t=gf(),e=Lp(),r=y,n=g,i=th();return cp}(),ff.Open=function(){if(Ry)return Cy;Ry=1;const t=hr(),e=jy(),r=g;return Cy={buffer:function(t,n){const i={stream:function(e,n){const i=r.PassThrough(),o=n?e+n:void 0;return i.end(t.slice(e,o)),i},size:function(){return Promise.resolve(t.length)}};return e(i,n)},file:function(r,n){const i={stream:function(e,n){const i=n?e+n:void 0;return t.createReadStream(r,{start:e,end:i})},size:function(){return new Promise(function(e,n){t.stat(r,function(t,r){t?n(t):e(r.size)})})}};return e(i,n)},url:function(t,r,n){if("string"==typeof r&&(r={url:r}),!r.url)throw"URL missing";r.headers=r.headers||{};const i={stream:function(e,n){const i=Object.create(r),o=n?e+n:"";return i.headers=Object.create(r.headers),i.headers.range="bytes="+e+"-"+o,t(i)},size:function(){return new Promise(function(e,n){const i=t(r);i.on("response",function(t){i.abort(),t.headers["content-length"]?e(t.headers["content-length"]):n(new Error("Missing content length header"))}).on("error",n)})}};return e(i,n)},s3:function(t,r,n){const i={size:function(){return new Promise(function(e,n){t.headObject(r,function(t,r){t?n(t):e(r.ContentLength)})})},stream:function(e,n){const i={};for(const t in r)i[t]=r[t];const o=n?e+n:"";return i.Range="bytes="+e+"-"+o,t.getObject(i).createReadStream()}};return e(i,n)},s3_v3:function(t,n,i){const{GetObjectCommand:o,HeadObjectCommand:s}=Ly,a={size:async()=>{const e=await t.send(new s({Bucket:n.Bucket,Key:n.Key}));return e.ContentLength?e.ContentLength:0},stream:(e,i)=>{const s=r.PassThrough(),a=i?e+i:"";return t.send(new o({Bucket:n.Bucket,Key:n.Key,Range:`bytes=${e}-${a}`})).then(t=>{t.Body.pipe(s)}).catch(t=>{s.emit("error",t)}),s}};return e(a,i)},custom:function(t,r){return e(t,r)}},Cy}()),ff),Ay=D(Fy);const Iy=new Map,Dy=new Map;function My(t,e){const r={sessionId:e,backupId:t,status:"pending",phase:"Initializing backup restore",progressPercentage:0,progressCurrent:0,progressTotal:0,startTime:(new Date).toISOString(),elapsedSeconds:0,errors:[]};Iy.set(e,r),function(t){const e=setInterval(()=>{const r=Iy.get(t);if(!r)return void clearInterval(e);const n=new Date(r.startTime).getTime(),i=Math.floor((Date.now()-n)/1e3);r.elapsedSeconds=i,"running"!==r.status&&clearInterval(e)},1e3)}(e)}function Ny(t,e){const r=Iy.get(t);if(!r)return;const n="completed"===r.status||"failed"===r.status;Object.assign(r,e),n||(r.status="running")}function By(t,e){const r=Iy.get(t);r&&r.errors.push({...e,timestamp:(new Date).toISOString()})}function Uy(t){return Iy.get(t)??null}function zy(t,e){const r=Iy.get(t);if(!r)return;r.status=e,r.phase="completed"===e?"Restore completed":"Restore failed",r.progressPercentage=100;const n=setTimeout(()=>{Iy.delete(t),Dy.delete(t)},6e4);Dy.set(t,n)}function Wy(){return l(process.env.BACKUP_PATH??"/directus/backups","restore-logs")}function Hy(){const t=Wy();e(t)||n(t,{recursive:!0})}const $y=new Set(["directus_access","directus_activity","directus_collections","directus_comments","directus_dashboards","directus_extensions","directus_fields","directus_files","directus_flows","directus_folders","directus_migrations","directus_notifications","directus_operations","directus_panels","directus_permissions","directus_policies","directus_presets","directus_relations","directus_revisions","directus_roles","directus_sessions","directus_settings","directus_shares","directus_translations","directus_users","directus_versions","directus_webhooks"]);function qy(){return process.env.BACKUP_PATH??"/directus/backups"}function Gy(){const t=qy();e(t)||n(t,{recursive:!0})}let Vy=null;function Qy(){return l(qy(),"schedule.json")}function Zy(){const r=Qy();if(!e(r))return{enabled:!1,cronExpression:"0 2 * * *"};try{const e=t(r,"utf-8");return JSON.parse(e)}catch{return{enabled:!1,cronExpression:"0 2 * * *"}}}function Ky(t){Gy(),r(Qy(),JSON.stringify(t,null,2),"utf-8")}function Jy(t){null!==Vy&&clearInterval(Vy),Vy=setInterval(async()=>{try{const e=Zy();if(!e.enabled)return;const r=new Date,n=new Date(r.getFullYear(),r.getMonth(),r.getDate(),r.getHours(),r.getMinutes());if(!function(t,e){const r=t.trim().split(/\s+/);if(5!==r.length)return!1;function n(t,e){if("*"===t)return!0;if(t.includes("/")){const[,r]=t.split("/"),n=parseInt(r??"1",10);return e%n===0}if(t.includes(","))return t.split(",").some(t=>parseInt(t,10)===e);if(t.includes("-")){const[r,n]=t.split("-"),i=parseInt(r??"0",10),o=parseInt(n??"0",10);return e>=i&&e<=o}return parseInt(t,10)===e}const[i,o,s,a,u]=r;return n(i,e.getMinutes())&&n(o,e.getHours())&&n(s,e.getDate())&&n(a,e.getMonth()+1)&&n(u,e.getDay())}(e.cronExpression,n))return;if(e.lastRun){const t=new Date(e.lastRun);if(new Date(t.getFullYear(),t.getMonth(),t.getDate(),t.getHours(),t.getMinutes()).getTime()===n.getTime())return}t.logger.info("[acuity-backup] Scheduled backup triggered"),await tm(t,{type:"full",includeMedia:!0}),Ky({...e,lastRun:r.toISOString()})}catch(e){t.logger.error("[acuity-backup] Scheduled backup failed:",e)}},6e4)}async function Yy(t){const{CollectionsService:e}=t.services,r=new e({schema:await t.getSchema(),accountability:null});return(await r.readByQuery()).filter(t=>!$y.has(t.collection)&&!t.collection.startsWith("directus_")).map(t=>t.collection)}async function Xy(t,e){const{ItemsService:r}=t.services,n=new r(e,{schema:await t.getSchema(),accountability:null});return await n.readByQuery({limit:-1,fields:["*"]})}async function tm(n,s){const a=await async function(t,n){Gy();const i=(new Date).toISOString().replace(/[:.]/g,"-"),s=k(),a=`backup-${i}-${s}.zip`,c=l(qy(),a),f=await t.getSchema(),{RelationsService:h}=t.services,p="full"===n.type?await Yy(t):n.collections??[],d={};let y=0;for(const e of p)try{const r=await Xy(t,e);d[e]=r,y+=r.length}catch(r){t.logger.warn(`[acuity-backup] Failed to export collection "${e}":`,r),d[e]=[]}const m=new h({schema:f,accountability:null}),g=await m.readAll(),_=await async function(t,e){const r=await t.getSchema(),{ItemsService:n}=t.services;let i=[];try{const t=new n("directus_fields",{schema:r,accountability:null});i=(await t.readByQuery({limit:-1,filter:{collection:{_in:e}},fields:["collection","field","group"]})).filter(t=>null!==t.group&&void 0!==t.group).map(t=>({collection:t.collection,field:t.field,group:t.group}))}catch(e){t.logger.warn("[acuity-backup] Failed to export field groups:",e)}let o=[];try{const t=new n("directus_collections",{schema:r,accountability:null});o=(await t.readByQuery({limit:-1,filter:{collection:{_in:e}},fields:["*"]})).map(t=>{const{collection:e,...r}=t;return{collection:t.collection,display:null,display_template:t.display_template??null,sort_field:t.sort_field??null,hidden:t.hidden??!1,sort:t.sort??null,icon:t.icon??null,note:t.note??null,meta:r}})}catch(e){t.logger.warn("[acuity-backup] Failed to export collection views:",e)}return{schemaVersion:"1.0",fieldGroups:i,collectionViews:o}}(t,p);let b=[];try{const{ItemsService:e}=t.services,r=new e("directus_fields",{schema:f,accountability:null});b=await r.readByQuery({limit:-1,filter:{collection:{_in:p}},fields:["*"]})}catch(e){t.logger.warn("[acuity-backup] Failed to export field metadata:",e)}let v=[];try{const{ItemsService:e}=t.services,r=new e("directus_presets",{schema:f,accountability:null});v=await r.readByQuery({limit:-1,filter:{collection:{_in:p}},fields:["*"]})}catch(e){t.logger.warn("[acuity-backup] Failed to export collection presets:",e)}let w=[];if(n.includeMedia)try{const{ItemsService:e}=t.services,r=new e("directus_files",{schema:f,accountability:null});w=await r.readByQuery({limit:-1,fields:["*"]})}catch(e){t.logger.warn("[acuity-backup] Failed to list media files:",e)}const S={timestamp:(new Date).toISOString(),version:"1.2.0",type:n.type,collections:p,includeMedia:n.includeMedia,totalItems:y,fileSize:0,includesViewsAndGroups:!0};await new Promise((r,i)=>{const s=o(c),a=lf("zip",{zlib:{level:6}});s.on("close",r),a.on("error",i),a.pipe(s),a.append(JSON.stringify(f,null,2),{name:"schema.json"}),a.append(JSON.stringify(g,null,2),{name:"relations.json"}),a.append(JSON.stringify(_,null,2),{name:"views.json"}),a.append(JSON.stringify(b,null,2),{name:"fields-meta.json"}),a.append(JSON.stringify(v,null,2),{name:"presets.json"}),a.append(JSON.stringify(S,null,2),{name:"manifest.json"});for(const[t,e]of Object.entries(d))a.append(JSON.stringify(e,null,2),{name:`collections/${t}.json`});if(n.includeMedia&&w.length>0){const r=process.env.STORAGE_LOCAL_ROOT||"./uploads";for(const n of w){a.append(JSON.stringify(n,null,2),{name:`files/${n.id}.meta.json`});const i=l(r,n.filename_disk);e(i)?a.file(i,{name:`files/${n.id}.bin`}):t.logger.warn(`[acuity-backup] Binary file not found on disk: ${i}`)}}a.finalize()});try{const t=await u(c);S.fileSize=t.size;const e=c.replace(/\.zip$/,".meta.json"),n={id:s,filename:a,timestamp:S.timestamp,type:S.type,collections:S.collections,includeMedia:S.includeMedia,fileSize:S.fileSize};r(e,JSON.stringify(n,null,2),"utf-8")}catch{}return c}(n,s),c=f(a),h=a.replace(/\.zip$/,".meta.json");let p;p=e(h)?JSON.parse(t(h,"utf-8")):{id:k(),filename:c,timestamp:(new Date).toISOString(),type:s.type,collections:s.collections??[],includeMedia:s.includeMedia,fileSize:0};try{const{FilesService:t}=n.services,e=new t({schema:await n.getSchema(),accountability:null}),o=i(a),s=await e.uploadOne(o,{storage:process.env.STORAGE_DEFAULT??process.env.STORAGE_LOCATIONS?.split(",")[0]?.trim()??"local",filename_download:c,type:"application/zip",title:`Backup ${p.timestamp}`});p.directusFileId=String(s),r(h,JSON.stringify(p,null,2),"utf-8")}catch(t){n.logger.warn("[acuity-backup] Failed to upload backup to Directus Files:",t)}return p}async function em(){Gy();const e=qy();let r;try{r=await s(e)}catch{return[]}const n=r.filter(t=>t.endsWith(".meta.json")),i=[];for(const r of n)try{const n=t(l(e,r),"utf-8");i.push(JSON.parse(n))}catch{}return i.sort((t,e)=>new Date(e.timestamp).getTime()-new Date(t.timestamp).getTime())}async function rm(t,n,i){const o=qy(),{backupId:a,truncateCollections:u=!1,collections:c,adminUserId:f}=n;i&&(My(a,i),Ny(i,{phase:"Finding backup archive",progressPercentage:5}));let h,p=null;try{h=await s(o)}catch{throw new Error("Backup directory is not accessible")}for(const t of h)if(t.endsWith(".zip")&&t.includes(a)){p=l(o,t);break}if(!p||!e(p))throw new Error(`Backup with id "${a}" not found`);i&&Ny(i,{phase:"Extracting ZIP archive",progressPercentage:10}),t.logger.info("[acuity-backup] Opening ZIP: "+p);const{ItemsService:d}=t.services,y={},m={},g={},_=await Ay.Open.file(p);for(const t of _.files){const e=t.path;if(e.startsWith("collections/")||"manifest.json"===e||"schema.json"===e||"relations.json"===e||"views.json"===e||"fields-meta.json"===e||"presets.json"===e||e.startsWith("files/")&&e.endsWith(".meta.json")||e.startsWith("files/")&&e.endsWith(".bin")){const r=await t.buffer();e.startsWith("collections/")?y[e]=r:e.endsWith(".bin")?g[e]=r:m[e]=r}}t.logger.info(`[acuity-backup] ZIP extracted: ${Object.keys(y).length} collection files, ${Object.keys(m).length} meta files, ${Object.keys(g).length} binary files`),i&&Ny(i,{phase:"Extraction complete",progressPercentage:20});const b=m["manifest.json"];if(!b)throw new Error("Invalid backup archive: manifest.json not found");const v=JSON.parse(b.toString("utf-8"));let w={},S=[],E=null;const k=m["schema.json"];if(k)try{w=JSON.parse(k.toString("utf-8"))}catch(e){t.logger.warn("[acuity-backup] Failed to parse schema.json:",e)}const x=m["relations.json"];if(x)try{S=JSON.parse(x.toString("utf-8"))}catch(e){t.logger.warn("[acuity-backup] Failed to parse relations.json:",e)}const O=m["views.json"];if(O)try{E=JSON.parse(O.toString("utf-8"))}catch{}let T=[];const j=m["fields-meta.json"];if(j)try{T=JSON.parse(j.toString("utf-8"))}catch(e){t.logger.warn("[acuity-backup] Failed to parse fields-meta.json:",e)}let C=[];const R=m["presets.json"];if(R)try{C=JSON.parse(R.toString("utf-8"))}catch(e){t.logger.warn("[acuity-backup] Failed to parse presets.json:",e)}const P=new Map;for(const t of S){const e=t;"directus_files"===e.related_collection&&e.collection&&e.field&&(P.has(e.collection)||P.set(e.collection,new Set),P.get(e.collection).add(e.field))}for(const t of T){const e=t.special;if(e&&Array.isArray(e)&&e.includes("file")){const e=t.collection,r=t.field;P.has(e)||P.set(e,new Set),P.get(e).add(r)}}const L=new Map;for(const t of S){const e=t;e.collection&&e.field&&(L.has(e.collection)||L.set(e.collection,new Set),L.get(e.collection).add(e.field))}for(const t of T){const e=t.special;if(e&&Array.isArray(e)&&(e.includes("m2o")||e.includes("file")||e.includes("user-created")||e.includes("user-updated"))){const e=t.collection,r=t.field;L.has(e)||L.set(e,new Set),L.get(e).add(r)}}const F=new Map;for(const t of T){const e=t.special;if(e&&Array.isArray(e)&&(e.includes("user-created")||e.includes("user-updated"))){const e=t.collection,r=t.field;F.has(e)||F.set(e,new Set),F.get(e).add(r)}}for(const t of S){const e=t;"directus_users"===e.related_collection&&e.collection&&e.field&&(F.has(e.collection)||F.set(e.collection,new Set),F.get(e.collection).add(e.field))}F.size>0&&t.logger.info(`[acuity-backup] Will remap user references in ${F.size} collections to admin user ${f??"(null)"}`);const A=c??v.collections,I=[];let D=0,M=0,N=0;await async function(t,e,r,n,i,o){const s=await t.getSchema(),{CollectionsService:a,RelationsService:u}=t.services,c=[];let l=0;const f=e?.collections??{},h=new Map;for(const t of o){const e=`${t.collection}.${t.field}`;h.set(e,t)}const p=new a({schema:s,accountability:null});if(i){const e=[];for(const t of i.collectionViews){const r=t.collection;f[r]||n.includes(r)&&e.push(t)}const r=new Set(e.map(t=>t.collection)),o=[],s=new Set,a=t=>{if(s.has(t.collection))return;s.add(t.collection);const n=t.meta?.group;if(n&&r.has(n)){const t=e.find(t=>t.collection===n);t&&a(t)}o.push(t)};for(const t of e)a(t);for(const e of o){const r=e.collection,n=e.meta??{},{id:i,collection:o,...s}=n;s.icon=e.icon??s.icon??null,s.note=e.note??s.note??null,s.sort=e.sort??s.sort??null;try{await p.readOne(r);try{await p.updateOne(r,{meta:s}),t.logger.info(`[acuity-backup] Updated virtual folder "${r}" meta`)}catch{}continue}catch{}try{await p.createOne({collection:r,schema:null,meta:s}),c.push(r),t.logger.info(`[acuity-backup] Created virtual folder collection "${r}"`)}catch(e){t.logger.warn(`[acuity-backup] Failed to create virtual folder "${r}":`,e)}}}const d=n.filter(t=>!s.collections[t]&&!c.includes(t));if(0===d.length&&0===c.length&&0===r.length)return{createdCollections:c,createdRelations:l};d.length>0&&t.logger.info(`[acuity-backup] Need to create ${d.length} missing collection(s): ${d.join(", ")}`);for(const e of d){const r=f[e];if(!r){t.logger.warn(`[acuity-backup] Collection "${e}" not found in backup schema — cannot recreate`);continue}const n=[],o=r.fields??{};for(const[t,i]of Object.entries(o)){const o=t===r.primary,s=`${e}.${t}`,a=h.get(s);if(i.alias){const e={field:i.field??t,type:"alias",schema:null,meta:a?{interface:a.interface,special:a.special??i.special??["alias","no-data"],options:a.options??null,display:a.display??null,display_options:a.display_options??null,width:a.width??"full",sort:a.sort??null,note:a.note??null,group:a.group??null,hidden:a.hidden??!1,required:a.required??!1}:{special:i.special??["alias","no-data"]}};n.push(e);continue}const u={special:i.special??[],hidden:!!o||(a?.hidden??!1),readonly:!!o||(a?.readonly??!1)};a&&(u.interface=a.interface,u.display=a.display??null,u.display_options=a.display_options??null,u.options=a.options??null,u.width=a.width??"full",u.sort=a.sort??null,u.note=a.note??null,u.required=a.required??!1,u.group=a.group??null,a.special&&(u.special=a.special));const c={field:i.field??t,type:i.type,schema:{is_nullable:!o&&!1!==i.nullable,default_value:i.defaultValue??null,is_primary_key:o,has_auto_increment:o&&("integer"===i.type||!0===i.generated)},meta:u};i.maxLength&&(c.schema.max_length=i.maxLength),n.push(c)}let s={};if(i){const t=i.collectionViews.find(t=>t.collection===e);if(t?.meta){const{collection:e,id:r,group:n,...i}=t.meta;s=i}}try{await p.createOne({collection:e,schema:{name:e},meta:{...s,singleton:r.singleton??!1,sort_field:r.sortField??null},fields:n}),c.push(e),t.logger.info(`[acuity-backup] Created collection "${e}" with ${n.length} fields`)}catch(r){t.logger.error(`[acuity-backup] Failed to create collection "${e}":`,r)}}if(r.length>0&&c.length>0){const e=await t.getSchema(),n=new u({schema:e,accountability:null});for(const i of r){const r=i;if((!r.collection?.startsWith("directus_")||!r.related_collection?.startsWith("directus_"))&&(c.includes(r.collection)||null!=r.related_collection&&c.includes(r.related_collection)))if(!e.collections[r.collection]||r.related_collection&&!e.collections[r.related_collection])t.logger.warn(`[acuity-backup] Skipping relation ${r.collection}.${r.field}: one or both collections missing`);else try{const e={...r.meta??{}};delete e.id,await n.createOne({collection:r.collection,field:r.field,related_collection:r.related_collection,meta:e,schema:r.schema??null}),l++,t.logger.info(`[acuity-backup] Created relation: ${r.collection}.${r.field} → ${r.related_collection}`)}catch(e){t.logger.warn(`[acuity-backup] Failed to create relation ${r.collection}.${r.field}:`,e)}}}return{createdCollections:c,createdRelations:l}}(t,w,S,A,E,T);let B=await t.getSchema(),U=0;if(T.length>0){i&&Ny(i,{phase:"Restoring field metadata",progressPercentage:22});const{FieldsService:e}=t.services,r=new e({schema:B,accountability:null}),n=new Map;for(const t of T){const e=`${t.collection}.${t.field}`;n.set(e,t)}for(const e of T){const n=e.collection,i=e.field;if(!A.includes(n))continue;const{id:o,collection:s,field:a,...u}=e;try{await r.updateField(n,i,{meta:u}),U++}catch{const o=e.special;if(o&&Array.isArray(o)&&o.includes("alias"))try{await r.createField(n,{field:i,type:"alias",schema:null,meta:u}),U++}catch(e){t.logger.warn(`[acuity-backup] Failed to create alias field "${n}.${i}":`,e)}}}t.logger.info(`[acuity-backup] Restored metadata for ${U} fields`),B=await t.getSchema()}i&&Ny(i,{phase:"Restoring media files",progressPercentage:25});let z=0;const W={};if(v.includeMedia){const e=new d("directus_files",{schema:B,accountability:null});for(const[n,o]of Object.entries(m))if(n.startsWith("files/")&&n.endsWith(".meta.json"))try{const n=JSON.parse(o.toString("utf-8")),s=n.id;f&&n.uploaded_by?n.uploaded_by=f:n.uploaded_by&&(n.uploaded_by=null),f&&n.modified_by?n.modified_by=f:n.modified_by&&(n.modified_by=null);try{let t=null;try{t=await e.readOne(s)}catch{}if(t){const{id:t,...r}=n;await e.updateOne(s,r),W[s]=s}else{const t=await e.createOne(n);W[s]=String(t)}const i=`files/${s}.bin`;if(g[i]&&n.filename_disk){const t=process.env.STORAGE_LOCAL_ROOT||"./uploads",e=l(t,n.filename_disk);r(e,g[i])}z++}catch(e){t.logger.warn(`[acuity-backup] Failed to restore file record "${s}":`,e),i&&By(i,{message:`Failed to restore file: ${s}`})}}catch{}}t.logger.info(`[acuity-backup] Restored ${z} media file records`),i&&Ny(i,{phase:"Media files restored",progressPercentage:35});const H=new Map,$=new Set(A);for(const t of S){const e=t;e.collection&&e.related_collection&&$.has(e.collection)&&$.has(e.related_collection)&&e.collection!==e.related_collection&&(H.has(e.collection)||H.set(e.collection,new Set),H.get(e.collection).add(e.related_collection))}const q=[],G=new Set,V=new Set,Q=t=>{if(G.has(t))return;if(V.has(t))return;V.add(t);const e=H.get(t);if(e)for(const t of e)$.has(t)&&Q(t);V.delete(t),G.add(t),q.push(t)};for(const t of A)Q(t);t.logger.info(`[acuity-backup] Collection restore order: ${q.join(", ")}`);for(let e=0;e<q.length;e++){const r=q[e],n=`collections/${r}.json`,o=y[n];if(!o){t.logger.warn(`[acuity-backup] Collection file not found in archive: ${n}`),M++,i&&By(i,{collection:r,message:"Collection file not found in archive"});continue}let s;try{s=JSON.parse(o.toString("utf-8"))}catch{t.logger.warn(`[acuity-backup] Failed to parse collection JSON: ${n}`),M++,i&&By(i,{collection:r,message:"Failed to parse collection JSON"});continue}if(!Array.isArray(s)||0===s.length){if(I.push(r),D++,i){const t=35+30*(e+1)/q.length;Ny(i,{phase:`Restoring collections (${e+1}/${q.length})`,progressPercentage:Math.round(t),progressCurrent:e+1,progressTotal:q.length})}continue}const a=L.get(r);if(a)for(const t of s)for(const e of a){const r=t[e];if(null!==r&&"object"==typeof r&&!Array.isArray(r)){const n=r;void 0!==n.id&&(t[e]=n.id)}}const c=P.get(r);if(c&&Object.keys(W).length>0)for(const t of s)for(const e of c){const r=t[e];"string"==typeof r&&W[r]&&W[r]!==r&&(t[e]=W[r])}if(F.has(r)){const t=F.get(r);for(const e of s)for(const r of t)void 0!==e[r]&&null!==e[r]&&(e[r]=f??null)}const l=new d(r,{schema:B,accountability:null});try{if(u){const t=await l.readByQuery({limit:-1,fields:["id"]});if(t.length>0){const e=t.map(t=>t.id);await l.deleteMany(e)}}if(await l.upsertMany(s),I.push(r),D++,N+=s.length,i){const t=35+30*(e+1)/q.length;Ny(i,{phase:`Restoring collections (${e+1}/${q.length})`,progressPercentage:Math.round(t),progressCurrent:e+1,progressTotal:q.length})}}catch(e){t.logger.error(`[acuity-backup] Failed to restore collection "${r}":`,e),M++,i&&By(i,{collection:r,message:String(e)})}}let Z=0,K=0;if(i&&Ny(i,{phase:"Restoring field groups and view settings",progressPercentage:75}),E&&!1!==v.includesViewsAndGroups){const{FieldsService:e,CollectionsService:r}=t.services,n=await t.getSchema();if(E.fieldGroups.length>0){const r=new e({schema:n,accountability:null});for(const e of E.fieldGroups)if(A.includes(e.collection))try{await r.updateField(e.collection,e.field,{group:e.group}),Z++}catch(r){t.logger.warn(`[acuity-backup] Failed to restore group for field "${e.collection}.${e.field}":`,r),i&&By(i,{message:`Failed to restore field group for ${e.collection}.${e.field}`})}}if(E.collectionViews.length>0){const e=new r({schema:n,accountability:null}),o=E.collectionViews.filter(t=>A.includes(t.collection)),s=new Set(o.map(t=>t.collection)),a=[],u=new Set,c=t=>{if(u.has(t.collection))return;u.add(t.collection);const e=t.meta?.group;if(e&&s.has(e)){const t=o.find(t=>t.collection===e);t&&c(t)}a.push(t)};for(const t of o)c(t);for(const r of a){const n=r.meta??{},{id:o,collection:s,...a}=n,u={...a,display:r.display,display_template:r.display_template,sort_field:r.sort_field,hidden:r.hidden,sort:r.sort,icon:r.icon,note:r.note};try{await e.updateOne(r.collection,{meta:u}),K++}catch(e){t.logger.warn(`[acuity-backup] Failed to restore view settings for collection "${r.collection}":`,e),i&&By(i,{collection:r.collection,message:"Failed to restore view settings"})}}}}let J=0;if(i&&Ny(i,{phase:"Restoring collection layout presets",progressPercentage:85}),C.length>0){const{ItemsService:e}=t.services,r=new e("directus_presets",{schema:await t.getSchema(),accountability:null}),n=C.filter(t=>t.collection&&A.includes(t.collection));for(const e of n)try{const{id:t,user:n,...i}=e,o=await r.readByQuery({limit:1,filter:{collection:{_eq:i.collection},user:{_null:!0},...i.bookmark?{bookmark:{_eq:i.bookmark}}:{bookmark:{_null:!0}},...i.role?{role:{_eq:i.role}}:{role:{_null:!0}}},fields:["id"]});o.length>0?await r.updateOne(o[0].id,i):await r.createOne(i),J++}catch(r){t.logger.warn(`[acuity-backup] Failed to restore preset for collection "${e.collection}":`,r),i&&By(i,{collection:e.collection,message:"Failed to restore layout preset"})}}const Y={restoredCollections:I,restoredFiles:z,restoredFieldGroups:Z,restoredCollectionViews:K,restoredPresets:J,errors:[]};if(i){const t=Uy(i);if(t){const e=function(t,e){const r=new Date(t.startTime).getTime(),n=Date.now()-r;return{id:t.sessionId,sessionId:t.sessionId,backupId:t.backupId,timestamp:t.startTime,duration:n,status:"completed"===t.status?0===t.errors.length?"success":"partial":"failed",summary:e,errors:t.errors}}(t,{collectionsAttempted:A.length,collectionsSuccess:D,collectionsFailed:M,itemsRestored:N,mediaFilesRestored:z,fieldGroupsRestored:Z,collectionViewsRestored:K,presetsRestored:J});!function(t){Hy();const e=l(Wy(),`${t.sessionId}.json`);r(e,JSON.stringify(t,null,2),"utf-8")}(e),zy(i,(t.errors.length,"completed"))}Ny(i,{phase:"Restore completed",progressPercentage:100})}return Y}function nm(t,e,r){const n=t.accountability;n?.admin?r():e.status(403).json({errors:[{message:"Forbidden: admin access required",extensions:{code:"FORBIDDEN"}}]})}const im=[],om=[{name:"acuity-backup",config:(n,f)=>{Jy(f),n.get("/collections",nm,async(t,e)=>{try{const t=await Yy(f),{CollectionsService:r}=f.services,n=new r({schema:await f.getSchema(),accountability:null}),i=(await n.readByQuery()).filter(e=>t.includes(e.collection)).map(t=>({collection:t.collection,icon:t.meta?.icon??null,note:t.meta?.note??null,singleton:t.meta?.singleton??!1}));e.json({data:i})}catch(t){f.logger.error("[acuity-backup] GET /collections error:",t),e.status(500).json({errors:[{message:String(t)}]})}}),n.get("/list",nm,async(t,e)=>{try{const t=await em();e.json({data:t})}catch(t){f.logger.error("[acuity-backup] GET /list error:",t),e.status(500).json({errors:[{message:String(t)}]})}}),n.post("/run",nm,async(t,e)=>{try{const r=t.body,n="selective"===r.type?"selective":"full",i=!1!==r.includeMedia,o="selective"===n?r.collections??[]:void 0;if("selective"===n&&(!o||0===o.length))return void e.status(400).json({errors:[{message:'Selective backup requires at least one collection in the "collections" array.'}]});const s=await tm(f,{type:n,collections:o,includeMedia:i});e.status(201).json({data:s})}catch(t){f.logger.error("[acuity-backup] POST /run error:",t),e.status(500).json({errors:[{message:String(t)}]})}}),n.get("/schedule",nm,(t,e)=>{try{const t=Zy();e.json({data:t})}catch(t){f.logger.error("[acuity-backup] GET /schedule error:",t),e.status(500).json({errors:[{message:String(t)}]})}}),n.post("/schedule",nm,(t,e)=>{try{const r=t.body;if("boolean"!=typeof r.enabled)return void e.status(400).json({errors:[{message:'"enabled" must be a boolean'}]});if("string"!=typeof r.cronExpression||!r.cronExpression.trim())return void e.status(400).json({errors:[{message:'"cronExpression" must be a non-empty string'}]});if(5!==r.cronExpression.trim().split(/\s+/).length)return void e.status(400).json({errors:[{message:'"cronExpression" must be a valid 5-field cron expression (minute hour dom month dow)'}]});const n={...Zy(),enabled:r.enabled,cronExpression:r.cronExpression.trim()};Ky(n),e.json({data:n})}catch(t){f.logger.error("[acuity-backup] POST /schedule error:",t),e.status(500).json({errors:[{message:String(t)}]})}}),n.get("/restore/:id",nm,async(t,e)=>{try{const{id:r}=t.params,n=(await em()).find(t=>t.id===r);if(!n)return void e.status(404).json({errors:[{message:`Backup "${r}" not found`}]});e.json({data:n})}catch(t){f.logger.error("[acuity-backup] GET /restore/:id error:",t),e.status(500).json({errors:[{message:String(t)}]})}}),n.post("/restore",nm,async(t,e)=>{try{const r=t.body;if(!r.backupId||"string"!=typeof r.backupId)return void e.status(400).json({errors:[{message:'"backupId" is required'}]});const n=t.accountability,i=n?.user??null,o=k(),s={backupId:r.backupId,truncateCollections:r.truncateCollections??!1,collections:r.collections,sessionId:o,adminUserId:i};e.json({data:{sessionId:o,message:"Restore started. Poll /acuity-backup/status/:sessionId for progress."}}),(async()=>{try{await rm(f,s,o)}catch(t){f.logger.error("[acuity-backup] Background restore error:",t);Uy(o)&&(By(o,{message:String(t)}),zy(o,"failed"))}})()}catch(t){f.logger.error("[acuity-backup] POST /restore error:",t),e.status(500).json({errors:[{message:String(t)}]})}}),n.delete("/:id",nm,async(t,r)=>{try{const{id:n}=t.params,i=(await em()).find(t=>t.id===n);if(!i)return void r.status(404).json({errors:[{message:`Backup "${n}" not found`}]});const o=l(qy(),i.filename),s=o.replace(/\.zip$/,".meta.json"),u=[];e(o)&&u.push(a(o)),e(s)&&u.push(a(s)),await Promise.all(u),r.json({data:{success:!0,id:n}})}catch(t){f.logger.error("[acuity-backup] DELETE /:id error:",t),r.status(500).json({errors:[{message:String(t)}]})}}),n.get("/status/:sessionId",nm,(t,e)=>{try{const{sessionId:r}=t.params,n=Uy(r);if(!n)return void e.status(404).json({errors:[{message:`Session "${r}" not found`}]});e.json({data:n})}catch(t){f.logger.error("[acuity-backup] GET /status/:sessionId error:",t),e.status(500).json({errors:[{message:String(t)}]})}}),n.get("/restore-logs",nm,async(e,r)=>{try{const e=await async function(){Hy();const e=Wy();try{const r=await s(e),n=[];for(const i of r){if(!i.endsWith(".json"))continue;const r=l(e,i);try{const e=t(r,"utf-8"),i=JSON.parse(e);n.push(i)}catch{}}return n.sort((t,e)=>new Date(e.timestamp).getTime()-new Date(t.timestamp).getTime()),n}catch{return[]}}();r.json({data:e})}catch(t){f.logger.error("[acuity-backup] GET /restore-logs error:",t),r.status(500).json({errors:[{message:String(t)}]})}}),n.get("/restore-logs/:logId",nm,(r,n)=>{try{const{logId:i}=r.params,o=function(r){Hy();const n=l(Wy(),`${r}.json`);if(!e(n))return null;try{const e=t(n,"utf-8");return JSON.parse(e)}catch{return null}}(i);if(!o)return void n.status(404).json({errors:[{message:`Restore log "${i}" not found`}]});n.json({data:o})}catch(t){f.logger.error("[acuity-backup] GET /restore-logs/:logId error:",t),n.status(500).json({errors:[{message:String(t)}]})}}),n.delete("/restore-logs/:logId",nm,async(t,r)=>{try{const{logId:n}=t.params;await async function(t){const r=l(Wy(),`${t}.json`);e(r)&&await a(r)}(n),r.json({data:{success:!0,logId:n}})}catch(t){f.logger.error("[acuity-backup] DELETE /restore-logs/:logId error:",t),r.status(500).json({errors:[{message:String(t)}]})}}),n.get("/download/:id",nm,async(t,r)=>{try{const{id:n}=t.params,o=(await em()).find(t=>t.id===n);if(!o)return void r.status(404).json({errors:[{message:`Backup "${n}" not found`}]});const s=l(qy(),o.filename);if(!e(s))return void r.status(404).json({errors:[{message:`Backup file "${o.filename}" not found on disk`}]});r.setHeader("Content-Type","application/zip"),r.setHeader("Content-Disposition",`attachment; filename="${o.filename}"`);i(s).pipe(r)}catch(t){f.logger.error("[acuity-backup] GET /download/:id error:",t),r.status(500).json({errors:[{message:String(t)}]})}}),n.post("/upload",nm,async(t,n)=>{try{const{fileId:s}=t.body;if(!s||"string"!=typeof s)return void n.status(400).json({errors:[{message:'"fileId" is required. Upload the ZIP via POST /files first.'}]});const{ItemsService:p}=f.services,d=new p("directus_files",{schema:await f.getSchema(),accountability:null});let y;try{y=await d.readOne(s)}catch{return void n.status(404).json({errors:[{message:`File "${s}" not found in Directus.`}]})}const m=process.env.STORAGE_LOCAL_ROOT||"./uploads",g=y.filename_disk,_=l(m,g);if(!e(_))return void n.status(400).json({errors:[{message:"Uploaded file not found on disk. Only local storage is currently supported for backup uploads."}]});const b=await u(_);if(b.size>524288e3)return void n.status(413).json({errors:[{message:`Upload too large (${Math.round(b.size/1024/1024)} MB). Maximum is 500 MB.`}]});Gy();const v=qy(),w=k(),S=l(v,`upload-temp-${w}.zip`);let E;await h(i(_),o(S));try{const t=(await Ay.Open.file(S)).files.find(t=>"manifest.json"===t.path);if(!t)return await a(S),void n.status(400).json({errors:[{message:"Invalid backup: ZIP does not contain a manifest.json file."}]});const e=await t.buffer();E=JSON.parse(e.toString("utf-8"))}catch(t){return await a(S),void n.status(400).json({errors:[{message:"Invalid or corrupted ZIP file: "+String(t)}]})}const x=k(),O=E.timestamp||(new Date).toISOString(),T=`backup-${O.replace(/[:.]/g,"-").replace("T","_").slice(0,19)}-${x}.zip`,j=l(v,T);await c(S,j);const C={id:x,filename:T,timestamp:O,type:E.type??"full",collections:E.collections??[],includeMedia:E.includeMedia??!1,fileSize:b.size},R=j.replace(/\.zip$/,".meta.json");r(R,JSON.stringify(C,null,2),"utf-8");try{await d.deleteOne(s)}catch{}f.logger.info(`[acuity-backup] Uploaded backup: ${T} (${Math.round(b.size/1024)} KB)`),n.json({data:C})}catch(t){f.logger.error("[acuity-backup] POST /upload error:",t),n.status(500).json({errors:[{message:String(t)}]})}}),async function(){Hy();const t=Wy(),e=Date.now()-7776e6;let r=0;try{const n=await s(t);for(const i of n){if(!i.endsWith(".json"))continue;const n=l(t,i);try{(await u(n)).mtime.getTime()<e&&(await a(n),r++)}catch{}}}catch{}return r}().then(t=>{t>0&&f.logger.info(`[acuity-backup] Cleaned up ${t} restore logs older than 90 days`)})}}],sm=[];export{om as endpoints,im as hooks,sm as operations};
|
|
49
|
+
*/()),zl=r}(),lf=D(cf),ff={};function hf(){if(Zl)return Ql;Zl=1;const t=g;function e(){if(!(this instanceof e))return new e;t.Duplex.call(this,{decodeStrings:!1,objectMode:!0}),this.buffer=Buffer.from("");const r=this;r.on("finish",function(){r.finished=!0,r.emit("chunk",!1)})}return b.inherits(e,t.Duplex),e.prototype._write=function(t,e,r){this.buffer=Buffer.concat([this.buffer,t]),this.cb=r,this.emit("chunk")},e.prototype.stream=function(e,r){const n=t.PassThrough();let i;const o=this;function s(){if("function"==typeof o.cb){const t=o.cb;return o.cb=void 0,t()}}function a(){let t;if(o.buffer&&o.buffer.length){if("number"==typeof e)t=o.buffer.slice(0,e),o.buffer=o.buffer.slice(e),e-=t.length,i=i||!e;else{let n=o.buffer.indexOf(e);if(-1!==n)o.match=n,r&&(n+=e.length),t=o.buffer.slice(0,n),o.buffer=o.buffer.slice(n),i=!0;else{const r=o.buffer.length-e.length;r<=0?s():(t=o.buffer.slice(0,r),o.buffer=o.buffer.slice(r))}}t&&n.write(t,function(){(0===o.buffer.length||e.length&&o.buffer.length<=e.length)&&s()})}if(i)o.removeListener("chunk",a),n.end();else if(o.finished)return o.removeListener("chunk",a),void o.emit("error",new Error("FILE_ENDED"))}return o.on("chunk",a),a(),n},e.prototype.pull=function(e,r){if(0===e)return Promise.resolve("");if(!isNaN(e)&&this.buffer.length>e){const t=this.buffer.slice(0,e);return this.buffer=this.buffer.slice(e),Promise.resolve(t)}let n=Buffer.from("");const i=this,o=new t.Transform;let s,a;return o._transform=function(t,e,r){n=Buffer.concat([n,t]),r()},new Promise(function(t,u){if(s=u,a=function(t){i.__emittedError=t,u(t)},i.finished)return u(new Error("FILE_ENDED"));i.once("error",a),i.stream(e,r).on("error",u).pipe(o).on("finish",function(){t(n)}).on("error",u)}).finally(function(){i.removeListener("error",s),i.removeListener("error",a)})},e.prototype._read=function(){},Ql=e}function pf(){if(Xl)return Yl;Xl=1;const t=g;return Yl=function(e){return new Promise(function(r,n){const i=[],o=t.Transform().on("finish",function(){r(Buffer.concat(i))}).on("error",n);o._transform=function(t,e,r){i.push(t),r()},e.on("error",n).pipe(o)})},Yl}function df(){if(ef)return tf;ef=1;const t=function(t,e,r){let n;switch(r){case 1:n=t.readUInt8(e);break;case 2:n=t.readUInt16LE(e);break;case 4:n=t.readUInt32LE(e);break;case 8:n=Number(t.readBigUInt64LE(e));break;default:throw new Error("Unsupported UInt LE size!")}return n};return tf={parse:function(e,r){const n={};let i=0;for(const[o,s]of r)e.length>=i+s?n[o]=t(e,i,s):n[o]=null,i+=s;return n}}}function yf(){if(nf)return rf;nf=1;const t=df();return rf=function(e,r){let n;for(;!n&&e&&e.length;){const i=t.parse(e,[["signature",2],["partSize",2]]);if(1===i.signature){const i=[];4294967295===r.uncompressedSize&&i.push(["uncompressedSize",8]),4294967295===r.compressedSize&&i.push(["compressedSize",8]),4294967295===r.offsetToLocalFileHeader&&i.push(["offsetToLocalFileHeader",8]),n=t.parse(e.slice(4),i)}else e=e.slice(i.partSize+4)}return n=n||{},4294967295===r.compressedSize&&(r.compressedSize=n.compressedSize),4294967295===r.uncompressedSize&&(r.uncompressedSize=n.uncompressedSize),4294967295===r.offsetToLocalFileHeader&&(r.offsetToLocalFileHeader=n.offsetToLocalFileHeader),n}}function mf(){return sf?of:(sf=1,of=function(t,e){const r=31&t,n=t>>5&15,i=1980+(t>>9&127),o=e?2*(31&e):0,s=e?e>>5&63:0,a=e?e>>11:0;return new Date(Date.UTC(i,n-1,r,a,s,o))})}function gf(){if(uf)return af;uf=1;const t=b,e=S,r=g,n=hf(),i=function(){if(Jl)return Kl;Jl=1;const t=g;function e(){if(!(this instanceof e))return new e;t.Transform.call(this)}return b.inherits(e,t.Transform),e.prototype._transform=function(t,e,r){r()},Kl=e}(),o=pf(),s=yf(),a=mf(),u=r.pipeline,c=df(),l=Buffer.alloc(4);function f(t){if(!(this instanceof f))return new f(t);const e=this;e._opts=t||{verbose:!1},n.call(e,e._opts),e.on("finish",function(){e.emit("end"),e.emit("close")}),e._readRecord().catch(function(t){e.__emittedError&&e.__emittedError===t||e.emit("error",t)})}return l.writeUInt32LE(101010256,0),t.inherits(f,n),f.prototype._readRecord=function(){const t=this;return t.pull(4).then(function(e){if(0===e.length)return;const r=e.readUInt32LE(0);if(875721283===r)return t._readCrxHeader();if(67324752===r)return t._readFile();if(33639248===r)return t.reachedCD=!0,t._readCentralDirectoryFileHeader();if(101010256===r)return t._readEndOfCentralDirectoryRecord();if(t.reachedCD){const e=!0;return t.pull(l,e).then(function(){return t._readEndOfCentralDirectoryRecord()})}t.emit("error",new Error("invalid signature: 0x"+r.toString(16)))}).then(function(e){if(e)return t._readRecord()})},f.prototype._readCrxHeader=function(){const t=this;return t.pull(12).then(function(e){return t.crxHeader=c.parse(e,[["version",4],["pubKeyLength",4],["signatureLength",4]]),t.pull(t.crxHeader.pubKeyLength+t.crxHeader.signatureLength)}).then(function(e){return t.crxHeader.publicKey=e.slice(0,t.crxHeader.pubKeyLength),t.crxHeader.signature=e.slice(t.crxHeader.pubKeyLength),t.emit("crx-header",t.crxHeader),!0})},f.prototype._readFile=function(){const t=this;return t.pull(26).then(function(n){const l=c.parse(n,[["versionsNeededToExtract",2],["flags",2],["compressionMethod",2],["lastModifiedTime",2],["lastModifiedDate",2],["crc32",4],["compressedSize",4],["uncompressedSize",4],["fileNameLength",2],["extraFieldLength",2]]);return l.lastModifiedDateTime=a(l.lastModifiedDate,l.lastModifiedTime),t.crxHeader&&(l.crxHeader=t.crxHeader),t.pull(l.fileNameLength).then(function(n){const a=n.toString("utf8"),c=r.PassThrough();let f=!1;return c.autodrain=function(){f=!0;const t=c.pipe(i());return t.promise=function(){return new Promise(function(e,r){t.on("finish",e),t.on("error",r)})},t},c.buffer=function(){return o(c)},c.path=a,c.props={},c.props.path=a,c.props.pathBuffer=n,c.props.flags={isUnicode:!!(2048&l.flags)},c.type=0===l.uncompressedSize&&/[/\\]$/.test(a)?"Directory":"File",t._opts.verbose&&("Directory"===c.type?console.log(" creating:",a):"File"===c.type&&(0===l.compressionMethod?console.log(" extracting:",a):console.log(" inflating:",a))),t.pull(l.extraFieldLength).then(function(n){const i=s(n,l);c.vars=l,c.extra=i,t._opts.forceStream?t.push(c):(t.emit("entry",c),(t._readableState.pipesCount||t._readableState.pipes&&t._readableState.pipes.length)&&t.push(c)),t._opts.verbose&&console.log({filename:a,vars:l,extra:i});const o=!(8&l.flags)||l.compressedSize>0;let h;c.__autodraining=f;const p=l.compressionMethod&&!f?e.createInflateRaw():r.PassThrough();return o?(c.size=l.uncompressedSize,h=l.compressedSize):(h=Buffer.alloc(4),h.writeUInt32LE(134695760,0)),new Promise(function(e,r){u(t.stream(h),p,c,function(n){return n?r(n):o?e(o):t._processDataDescriptor(c).then(e).catch(r)})})})})})},f.prototype._processDataDescriptor=function(t){return this.pull(16).then(function(e){const r=c.parse(e,[["dataDescriptorSignature",4],["crc32",4],["compressedSize",4],["uncompressedSize",4]]);return t.size=r.uncompressedSize,!0})},f.prototype._readCentralDirectoryFileHeader=function(){const t=this;return t.pull(42).then(function(e){const r=c.parse(e,[["versionMadeBy",2],["versionsNeededToExtract",2],["flags",2],["compressionMethod",2],["lastModifiedTime",2],["lastModifiedDate",2],["crc32",4],["compressedSize",4],["uncompressedSize",4],["fileNameLength",2],["extraFieldLength",2],["fileCommentLength",2],["diskNumber",2],["internalFileAttributes",2],["externalFileAttributes",4],["offsetToLocalFileHeader",4]]);return t.pull(r.fileNameLength).then(function(e){return r.fileName=e.toString("utf8"),t.pull(r.extraFieldLength)}).then(function(){return t.pull(r.fileCommentLength)}).then(function(){return!0})})},f.prototype._readEndOfCentralDirectoryRecord=function(){const t=this;return t.pull(18).then(function(e){const r=c.parse(e,[["diskNumber",2],["diskStart",2],["numberOfRecordsOnDisk",2],["numberOfRecords",2],["sizeOfCentralDirectory",4],["offsetToStartOfCentralDirectory",4],["commentLength",2]]);return t.pull(r.commentLength).then(function(){t.end(),t.push(null)})})},f.prototype.promise=function(){const t=this;return new Promise(function(e,r){t.on("finish",e),t.on("error",r)})},af=f}var _f,bf,vf={exports:{}},wf={exports:{}};function Sf(){return bf?_f:(bf=1,_f=g)}var Ef,kf={exports:{}};function xf(){return Ef||(Ef=1,function(t,e){var r=w,n=r.Buffer;function i(t,e){for(var r in t)e[r]=t[r]}function o(t,e,r){return n(t,e,r)}n.from&&n.alloc&&n.allocUnsafe&&n.allocUnsafeSlow?t.exports=r:(i(r,e),e.Buffer=o),i(n,o),o.from=function(t,e,r){if("number"==typeof t)throw new TypeError("Argument must not be a number");return n(t,e,r)},o.alloc=function(t,e,r){if("number"!=typeof t)throw new TypeError("Argument must be a number");var i=n(t);return void 0!==e?"string"==typeof r?i.fill(e,r):i.fill(e):i.fill(0),i},o.allocUnsafe=function(t){if("number"!=typeof t)throw new TypeError("Argument must be a number");return n(t)},o.allocUnsafeSlow=function(t){if("number"!=typeof t)throw new TypeError("Argument must be a number");return r.SlowBuffer(t)}}(kf,kf.exports)),kf.exports}var Of,Tf,jf,Cf,Rf,Pf,Lf,Ff={exports:{}};function Af(){return Of||(Of=1,function(t){var e=xf().Buffer,r=b;function n(t,e,r){t.copy(e,r)}t.exports=function(){function t(){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.head=null,this.tail=null,this.length=0}return t.prototype.push=function(t){var e={data:t,next:null};this.length>0?this.tail.next=e:this.head=e,this.tail=e,++this.length},t.prototype.unshift=function(t){var e={data:t,next:this.head};0===this.length&&(this.tail=e),this.head=e,++this.length},t.prototype.shift=function(){if(0!==this.length){var t=this.head.data;return 1===this.length?this.head=this.tail=null:this.head=this.head.next,--this.length,t}},t.prototype.clear=function(){this.head=this.tail=null,this.length=0},t.prototype.join=function(t){if(0===this.length)return"";for(var e=this.head,r=""+e.data;e=e.next;)r+=t+e.data;return r},t.prototype.concat=function(t){if(0===this.length)return e.alloc(0);for(var r=e.allocUnsafe(t>>>0),i=this.head,o=0;i;)n(i.data,r,o),o+=i.data.length,i=i.next;return r},t}(),r&&r.inspect&&r.inspect.custom&&(t.exports.prototype[r.inspect.custom]=function(){var t=r.inspect({length:this.length});return this.constructor.name+" "+t})}(Ff)),Ff.exports}function If(){if(jf)return Tf;jf=1;var t=vr();function e(t,e){t.emit("error",e)}return Tf={destroy:function(r,n){var i=this,o=this._readableState&&this._readableState.destroyed,s=this._writableState&&this._writableState.destroyed;return o||s?(n?n(r):r&&(this._writableState?this._writableState.errorEmitted||(this._writableState.errorEmitted=!0,t.nextTick(e,this,r)):t.nextTick(e,this,r)),this):(this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(r||null,function(r){!n&&r?i._writableState?i._writableState.errorEmitted||(i._writableState.errorEmitted=!0,t.nextTick(e,i,r)):t.nextTick(e,i,r):n&&n(r)}),this)},undestroy:function(){this._readableState&&(this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1),this._writableState&&(this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finalCalled=!1,this._writableState.prefinished=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1)}}}function Df(){if(Rf)return Cf;Rf=1;var t=vr();function e(t){var e=this;this.next=null,this.entry=null,this.finish=function(){!function(t,e,r){var n=t.entry;t.entry=null;for(;n;){var i=n.callback;e.pendingcb--,i(r),n=n.next}e.corkedRequestsFree.next=t}(e,t)}}Cf=p;var r,n=!process.browser&&["v0.10","v0.9."].indexOf(process.version.slice(0,5))>-1?setImmediate:t.nextTick;p.WritableState=h;var i=Object.create(jr());i.inherits=Fr();var o={deprecate:Gr()},s=Sf(),a=xf().Buffer,u=(void 0!==I?I:"undefined"!=typeof window?window:"undefined"!=typeof self?self:{}).Uint8Array||function(){};var c,l=If();function f(){}function h(i,o){r=r||Mf(),i=i||{};var s=o instanceof r;this.objectMode=!!i.objectMode,s&&(this.objectMode=this.objectMode||!!i.writableObjectMode);var a=i.highWaterMark,u=i.writableHighWaterMark,c=this.objectMode?16:16384;this.highWaterMark=a||0===a?a:s&&(u||0===u)?u:c,this.highWaterMark=Math.floor(this.highWaterMark),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;var l=!1===i.decodeStrings;this.decodeStrings=!l,this.defaultEncoding=i.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(e){!function(e,r){var i=e._writableState,o=i.sync,s=i.writecb;if(function(t){t.writing=!1,t.writecb=null,t.length-=t.writelen,t.writelen=0}(i),r)!function(e,r,n,i,o){--r.pendingcb,n?(t.nextTick(o,i),t.nextTick(b,e,r),e._writableState.errorEmitted=!0,e.emit("error",i)):(o(i),e._writableState.errorEmitted=!0,e.emit("error",i),b(e,r))}(e,i,o,r,s);else{var a=g(i);a||i.corked||i.bufferProcessing||!i.bufferedRequest||m(e,i),o?n(y,e,i,a,s):y(e,i,a,s)}}(o,e)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.bufferedRequestCount=0,this.corkedRequestsFree=new e(this)}function p(t){if(r=r||Mf(),!(c.call(p,this)||this instanceof r))return new p(t);this._writableState=new h(t,this),this.writable=!0,t&&("function"==typeof t.write&&(this._write=t.write),"function"==typeof t.writev&&(this._writev=t.writev),"function"==typeof t.destroy&&(this._destroy=t.destroy),"function"==typeof t.final&&(this._final=t.final)),s.call(this)}function d(t,e,r,n,i,o,s){e.writelen=n,e.writecb=s,e.writing=!0,e.sync=!0,r?t._writev(i,e.onwrite):t._write(i,o,e.onwrite),e.sync=!1}function y(t,e,r,n){r||function(t,e){0===e.length&&e.needDrain&&(e.needDrain=!1,t.emit("drain"))}(t,e),e.pendingcb--,n(),b(t,e)}function m(t,r){r.bufferProcessing=!0;var n=r.bufferedRequest;if(t._writev&&n&&n.next){var i=r.bufferedRequestCount,o=new Array(i),s=r.corkedRequestsFree;s.entry=n;for(var a=0,u=!0;n;)o[a]=n,n.isBuf||(u=!1),n=n.next,a+=1;o.allBuffers=u,d(t,r,!0,r.length,o,"",s.finish),r.pendingcb++,r.lastBufferedRequest=null,s.next?(r.corkedRequestsFree=s.next,s.next=null):r.corkedRequestsFree=new e(r),r.bufferedRequestCount=0}else{for(;n;){var c=n.chunk,l=n.encoding,f=n.callback;if(d(t,r,!1,r.objectMode?1:c.length,c,l,f),n=n.next,r.bufferedRequestCount--,r.writing)break}null===n&&(r.lastBufferedRequest=null)}r.bufferedRequest=n,r.bufferProcessing=!1}function g(t){return t.ending&&0===t.length&&null===t.bufferedRequest&&!t.finished&&!t.writing}function _(t,e){t._final(function(r){e.pendingcb--,r&&t.emit("error",r),e.prefinished=!0,t.emit("prefinish"),b(t,e)})}function b(e,r){var n=g(r);return n&&(!function(e,r){r.prefinished||r.finalCalled||("function"==typeof e._final?(r.pendingcb++,r.finalCalled=!0,t.nextTick(_,e,r)):(r.prefinished=!0,e.emit("prefinish")))}(e,r),0===r.pendingcb&&(r.finished=!0,e.emit("finish"))),n}return i.inherits(p,s),h.prototype.getBuffer=function(){for(var t=this.bufferedRequest,e=[];t;)e.push(t),t=t.next;return e},function(){try{Object.defineProperty(h.prototype,"buffer",{get:o.deprecate(function(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")})}catch(t){}}(),"function"==typeof Symbol&&Symbol.hasInstance&&"function"==typeof Function.prototype[Symbol.hasInstance]?(c=Function.prototype[Symbol.hasInstance],Object.defineProperty(p,Symbol.hasInstance,{value:function(t){return!!c.call(this,t)||this===p&&(t&&t._writableState instanceof h)}})):c=function(t){return t instanceof this},p.prototype.pipe=function(){this.emit("error",new Error("Cannot pipe, not readable"))},p.prototype.write=function(e,r,n){var i,o=this._writableState,s=!1,c=!o.objectMode&&(i=e,a.isBuffer(i)||i instanceof u);return c&&!a.isBuffer(e)&&(e=function(t){return a.from(t)}(e)),"function"==typeof r&&(n=r,r=null),c?r="buffer":r||(r=o.defaultEncoding),"function"!=typeof n&&(n=f),o.ended?function(e,r){var n=new Error("write after end");e.emit("error",n),t.nextTick(r,n)}(this,n):(c||function(e,r,n,i){var o=!0,s=!1;return null===n?s=new TypeError("May not write null values to stream"):"string"==typeof n||void 0===n||r.objectMode||(s=new TypeError("Invalid non-string/buffer chunk")),s&&(e.emit("error",s),t.nextTick(i,s),o=!1),o}(this,o,e,n))&&(o.pendingcb++,s=function(t,e,r,n,i,o){if(!r){var s=function(t,e,r){t.objectMode||!1===t.decodeStrings||"string"!=typeof e||(e=a.from(e,r));return e}(e,n,i);n!==s&&(r=!0,i="buffer",n=s)}var u=e.objectMode?1:n.length;e.length+=u;var c=e.length<e.highWaterMark;c||(e.needDrain=!0);if(e.writing||e.corked){var l=e.lastBufferedRequest;e.lastBufferedRequest={chunk:n,encoding:i,isBuf:r,callback:o,next:null},l?l.next=e.lastBufferedRequest:e.bufferedRequest=e.lastBufferedRequest,e.bufferedRequestCount+=1}else d(t,e,!1,u,n,i,o);return c}(this,o,c,e,r,n)),s},p.prototype.cork=function(){this._writableState.corked++},p.prototype.uncork=function(){var t=this._writableState;t.corked&&(t.corked--,t.writing||t.corked||t.bufferProcessing||!t.bufferedRequest||m(this,t))},p.prototype.setDefaultEncoding=function(t){if("string"==typeof t&&(t=t.toLowerCase()),!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((t+"").toLowerCase())>-1))throw new TypeError("Unknown encoding: "+t);return this._writableState.defaultEncoding=t,this},Object.defineProperty(p.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),p.prototype._write=function(t,e,r){r(new Error("_write() is not implemented"))},p.prototype._writev=null,p.prototype.end=function(e,r,n){var i=this._writableState;"function"==typeof e?(n=e,e=null,r=null):"function"==typeof r&&(n=r,r=null),null!=e&&this.write(e,r),i.corked&&(i.corked=1,this.uncork()),i.ending||function(e,r,n){r.ending=!0,b(e,r),n&&(r.finished?t.nextTick(n):e.once("finish",n));r.ended=!0,e.writable=!1}(this,i,n)},Object.defineProperty(p.prototype,"destroyed",{get:function(){return void 0!==this._writableState&&this._writableState.destroyed},set:function(t){this._writableState&&(this._writableState.destroyed=t)}}),p.prototype.destroy=l.destroy,p.prototype._undestroy=l.undestroy,p.prototype._destroy=function(t,e){this.end(),e(t)},Cf}function Mf(){if(Lf)return Pf;Lf=1;var t=vr(),e=Object.keys||function(t){var e=[];for(var r in t)e.push(r);return e};Pf=u;var r=Object.create(jr());r.inherits=Fr();var n=Jf(),i=Df();r.inherits(u,n);for(var o=e(i.prototype),s=0;s<o.length;s++){var a=o[s];u.prototype[a]||(u.prototype[a]=i.prototype[a])}function u(t){if(!(this instanceof u))return new u(t);n.call(this,t),i.call(this,t),t&&!1===t.readable&&(this.readable=!1),t&&!1===t.writable&&(this.writable=!1),this.allowHalfOpen=!0,t&&!1===t.allowHalfOpen&&(this.allowHalfOpen=!1),this.once("end",c)}function c(){this.allowHalfOpen||this._writableState.ended||t.nextTick(l,this)}function l(t){t.end()}return Object.defineProperty(u.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),Object.defineProperty(u.prototype,"destroyed",{get:function(){return void 0!==this._readableState&&void 0!==this._writableState&&(this._readableState.destroyed&&this._writableState.destroyed)},set:function(t){void 0!==this._readableState&&void 0!==this._writableState&&(this._readableState.destroyed=t,this._writableState.destroyed=t)}}),u.prototype._destroy=function(e,r){this.push(null),this.end(),t.nextTick(r,e)},Pf}var Nf,Bf,Uf,zf,Wf,Hf,$f,qf,Gf,Vf,Qf,Zf={};function Kf(){if(Nf)return Zf;Nf=1;var t=xf().Buffer,e=t.isEncoding||function(t){switch((t=""+t)&&t.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};function r(r){var n;switch(this.encoding=function(r){var n=function(t){if(!t)return"utf8";for(var e;;)switch(t){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return t;default:if(e)return;t=(""+t).toLowerCase(),e=!0}}(r);if("string"!=typeof n&&(t.isEncoding===e||!e(r)))throw new Error("Unknown encoding: "+r);return n||r}(r),this.encoding){case"utf16le":this.text=o,this.end=s,n=4;break;case"utf8":this.fillLast=i,n=4;break;case"base64":this.text=a,this.end=u,n=3;break;default:return this.write=c,void(this.end=l)}this.lastNeed=0,this.lastTotal=0,this.lastChar=t.allocUnsafe(n)}function n(t){return t<=127?0:t>>5==6?2:t>>4==14?3:t>>3==30?4:t>>6==2?-1:-2}function i(t){var e=this.lastTotal-this.lastNeed,r=function(t,e){if(128!=(192&e[0]))return t.lastNeed=0,"�";if(t.lastNeed>1&&e.length>1){if(128!=(192&e[1]))return t.lastNeed=1,"�";if(t.lastNeed>2&&e.length>2&&128!=(192&e[2]))return t.lastNeed=2,"�"}}(this,t);return void 0!==r?r:this.lastNeed<=t.length?(t.copy(this.lastChar,e,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal)):(t.copy(this.lastChar,e,0,t.length),void(this.lastNeed-=t.length))}function o(t,e){if((t.length-e)%2==0){var r=t.toString("utf16le",e);if(r){var n=r.charCodeAt(r.length-1);if(n>=55296&&n<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=t[t.length-2],this.lastChar[1]=t[t.length-1],r.slice(0,-1)}return r}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=t[t.length-1],t.toString("utf16le",e,t.length-1)}function s(t){var e=t&&t.length?this.write(t):"";if(this.lastNeed){var r=this.lastTotal-this.lastNeed;return e+this.lastChar.toString("utf16le",0,r)}return e}function a(t,e){var r=(t.length-e)%3;return 0===r?t.toString("base64",e):(this.lastNeed=3-r,this.lastTotal=3,1===r?this.lastChar[0]=t[t.length-1]:(this.lastChar[0]=t[t.length-2],this.lastChar[1]=t[t.length-1]),t.toString("base64",e,t.length-r))}function u(t){var e=t&&t.length?this.write(t):"";return this.lastNeed?e+this.lastChar.toString("base64",0,3-this.lastNeed):e}function c(t){return t.toString(this.encoding)}function l(t){return t&&t.length?this.write(t):""}return Zf.StringDecoder=r,r.prototype.write=function(t){if(0===t.length)return"";var e,r;if(this.lastNeed){if(void 0===(e=this.fillLast(t)))return"";r=this.lastNeed,this.lastNeed=0}else r=0;return r<t.length?e?e+this.text(t,r):this.text(t,r):e||""},r.prototype.end=function(t){var e=t&&t.length?this.write(t):"";return this.lastNeed?e+"�":e},r.prototype.text=function(t,e){var r=function(t,e,r){var i=e.length-1;if(i<r)return 0;var o=n(e[i]);if(o>=0)return o>0&&(t.lastNeed=o-1),o;if(--i<r||-2===o)return 0;if(o=n(e[i]),o>=0)return o>0&&(t.lastNeed=o-2),o;if(--i<r||-2===o)return 0;if(o=n(e[i]),o>=0)return o>0&&(2===o?o=0:t.lastNeed=o-3),o;return 0}(this,t,e);if(!this.lastNeed)return t.toString("utf8",e);this.lastTotal=r;var i=t.length-(r-this.lastNeed);return t.copy(this.lastChar,0,i),t.toString("utf8",e,i)},r.prototype.fillLast=function(t){if(this.lastNeed<=t.length)return t.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);t.copy(this.lastChar,this.lastTotal-this.lastNeed,0,t.length),this.lastNeed-=t.length},Zf}function Jf(){if(Uf)return Bf;Uf=1;var t=vr();Bf=m;var e,r=wr();m.ReadableState=y,d.EventEmitter;var n=function(t,e){return t.listeners(e).length},i=Sf(),o=xf().Buffer,s=(void 0!==I?I:"undefined"!=typeof window?window:"undefined"!=typeof self?self:{}).Uint8Array||function(){};var a=Object.create(jr());a.inherits=Fr();var u=b,c=void 0;c=u&&u.debuglog?u.debuglog("stream"):function(){};var l,f=Af(),h=If();a.inherits(m,i);var p=["error","close","destroy","pause","resume"];function y(t,r){t=t||{};var n=r instanceof(e=e||Mf());this.objectMode=!!t.objectMode,n&&(this.objectMode=this.objectMode||!!t.readableObjectMode);var i=t.highWaterMark,o=t.readableHighWaterMark,s=this.objectMode?16:16384;this.highWaterMark=i||0===i?i:n&&(o||0===o)?o:s,this.highWaterMark=Math.floor(this.highWaterMark),this.buffer=new f,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.destroyed=!1,this.defaultEncoding=t.defaultEncoding||"utf8",this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,t.encoding&&(l||(l=Kf().StringDecoder),this.decoder=new l(t.encoding),this.encoding=t.encoding)}function m(t){if(e=e||Mf(),!(this instanceof m))return new m(t);this._readableState=new y(t,this),this.readable=!0,t&&("function"==typeof t.read&&(this._read=t.read),"function"==typeof t.destroy&&(this._destroy=t.destroy)),i.call(this)}function g(t,e,r,n,i){var a,u=t._readableState;null===e?(u.reading=!1,function(t,e){if(e.ended)return;if(e.decoder){var r=e.decoder.end();r&&r.length&&(e.buffer.push(r),e.length+=e.objectMode?1:r.length)}e.ended=!0,S(t)}(t,u)):(i||(a=function(t,e){var r;n=e,o.isBuffer(n)||n instanceof s||"string"==typeof e||void 0===e||t.objectMode||(r=new TypeError("Invalid non-string/buffer chunk"));var n;return r}(u,e)),a?t.emit("error",a):u.objectMode||e&&e.length>0?("string"==typeof e||u.objectMode||Object.getPrototypeOf(e)===o.prototype||(e=function(t){return o.from(t)}(e)),n?u.endEmitted?t.emit("error",new Error("stream.unshift() after end event")):_(t,u,e,!0):u.ended?t.emit("error",new Error("stream.push() after EOF")):(u.reading=!1,u.decoder&&!r?(e=u.decoder.write(e),u.objectMode||0!==e.length?_(t,u,e,!1):k(t,u)):_(t,u,e,!1))):n||(u.reading=!1));return function(t){return!t.ended&&(t.needReadable||t.length<t.highWaterMark||0===t.length)}(u)}function _(t,e,r,n){e.flowing&&0===e.length&&!e.sync?(t.emit("data",r),t.read(0)):(e.length+=e.objectMode?1:r.length,n?e.buffer.unshift(r):e.buffer.push(r),e.needReadable&&S(t)),k(t,e)}Object.defineProperty(m.prototype,"destroyed",{get:function(){return void 0!==this._readableState&&this._readableState.destroyed},set:function(t){this._readableState&&(this._readableState.destroyed=t)}}),m.prototype.destroy=h.destroy,m.prototype._undestroy=h.undestroy,m.prototype._destroy=function(t,e){this.push(null),e(t)},m.prototype.push=function(t,e){var r,n=this._readableState;return n.objectMode?r=!0:"string"==typeof t&&((e=e||n.defaultEncoding)!==n.encoding&&(t=o.from(t,e),e=""),r=!0),g(this,t,e,!1,r)},m.prototype.unshift=function(t){return g(this,t,null,!0,!1)},m.prototype.isPaused=function(){return!1===this._readableState.flowing},m.prototype.setEncoding=function(t){return l||(l=Kf().StringDecoder),this._readableState.decoder=new l(t),this._readableState.encoding=t,this};var v=8388608;function w(t,e){return t<=0||0===e.length&&e.ended?0:e.objectMode?1:t!=t?e.flowing&&e.length?e.buffer.head.data.length:e.length:(t>e.highWaterMark&&(e.highWaterMark=function(t){return t>=v?t=v:(t--,t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,t|=t>>>16,t++),t}(t)),t<=e.length?t:e.ended?e.length:(e.needReadable=!0,0))}function S(e){var r=e._readableState;r.needReadable=!1,r.emittedReadable||(c("emitReadable",r.flowing),r.emittedReadable=!0,r.sync?t.nextTick(E,e):E(e))}function E(t){c("emit readable"),t.emit("readable"),j(t)}function k(e,r){r.readingMore||(r.readingMore=!0,t.nextTick(x,e,r))}function x(t,e){for(var r=e.length;!e.reading&&!e.flowing&&!e.ended&&e.length<e.highWaterMark&&(c("maybeReadMore read 0"),t.read(0),r!==e.length);)r=e.length;e.readingMore=!1}function O(t){c("readable nexttick read 0"),t.read(0)}function T(t,e){e.reading||(c("resume read 0"),t.read(0)),e.resumeScheduled=!1,e.awaitDrain=0,t.emit("resume"),j(t),e.flowing&&!e.reading&&t.read(0)}function j(t){var e=t._readableState;for(c("flow",e.flowing);e.flowing&&null!==t.read(););}function C(t,e){return 0===e.length?null:(e.objectMode?r=e.buffer.shift():!t||t>=e.length?(r=e.decoder?e.buffer.join(""):1===e.buffer.length?e.buffer.head.data:e.buffer.concat(e.length),e.buffer.clear()):r=function(t,e,r){var n;t<e.head.data.length?(n=e.head.data.slice(0,t),e.head.data=e.head.data.slice(t)):n=t===e.head.data.length?e.shift():r?function(t,e){var r=e.head,n=1,i=r.data;t-=i.length;for(;r=r.next;){var o=r.data,s=t>o.length?o.length:t;if(s===o.length?i+=o:i+=o.slice(0,t),0===(t-=s)){s===o.length?(++n,r.next?e.head=r.next:e.head=e.tail=null):(e.head=r,r.data=o.slice(s));break}++n}return e.length-=n,i}(t,e):function(t,e){var r=o.allocUnsafe(t),n=e.head,i=1;n.data.copy(r),t-=n.data.length;for(;n=n.next;){var s=n.data,a=t>s.length?s.length:t;if(s.copy(r,r.length-t,0,a),0===(t-=a)){a===s.length?(++i,n.next?e.head=n.next:e.head=e.tail=null):(e.head=n,n.data=s.slice(a));break}++i}return e.length-=i,r}(t,e);return n}(t,e.buffer,e.decoder),r);var r}function R(e){var r=e._readableState;if(r.length>0)throw new Error('"endReadable()" called on non-empty stream');r.endEmitted||(r.ended=!0,t.nextTick(P,r,e))}function P(t,e){t.endEmitted||0!==t.length||(t.endEmitted=!0,e.readable=!1,e.emit("end"))}function L(t,e){for(var r=0,n=t.length;r<n;r++)if(t[r]===e)return r;return-1}return m.prototype.read=function(t){c("read",t),t=parseInt(t,10);var e=this._readableState,r=t;if(0!==t&&(e.emittedReadable=!1),0===t&&e.needReadable&&(e.length>=e.highWaterMark||e.ended))return c("read: emitReadable",e.length,e.ended),0===e.length&&e.ended?R(this):S(this),null;if(0===(t=w(t,e))&&e.ended)return 0===e.length&&R(this),null;var n,i=e.needReadable;return c("need readable",i),(0===e.length||e.length-t<e.highWaterMark)&&c("length less than watermark",i=!0),e.ended||e.reading?c("reading or ended",i=!1):i&&(c("do read"),e.reading=!0,e.sync=!0,0===e.length&&(e.needReadable=!0),this._read(e.highWaterMark),e.sync=!1,e.reading||(t=w(r,e))),null===(n=t>0?C(t,e):null)?(e.needReadable=!0,t=0):e.length-=t,0===e.length&&(e.ended||(e.needReadable=!0),r!==t&&e.ended&&R(this)),null!==n&&this.emit("data",n),n},m.prototype._read=function(t){this.emit("error",new Error("_read() is not implemented"))},m.prototype.pipe=function(e,i){var o=this,s=this._readableState;switch(s.pipesCount){case 0:s.pipes=e;break;case 1:s.pipes=[s.pipes,e];break;default:s.pipes.push(e)}s.pipesCount+=1,c("pipe count=%d opts=%j",s.pipesCount,i);var a=(!i||!1!==i.end)&&e!==process.stdout&&e!==process.stderr?l:_;function u(t,r){c("onunpipe"),t===o&&r&&!1===r.hasUnpiped&&(r.hasUnpiped=!0,c("cleanup"),e.removeListener("close",m),e.removeListener("finish",g),e.removeListener("drain",f),e.removeListener("error",y),e.removeListener("unpipe",u),o.removeListener("end",l),o.removeListener("end",_),o.removeListener("data",d),h=!0,!s.awaitDrain||e._writableState&&!e._writableState.needDrain||f())}function l(){c("onend"),e.end()}s.endEmitted?t.nextTick(a):o.once("end",a),e.on("unpipe",u);var f=function(t){return function(){var e=t._readableState;c("pipeOnDrain",e.awaitDrain),e.awaitDrain&&e.awaitDrain--,0===e.awaitDrain&&n(t,"data")&&(e.flowing=!0,j(t))}}(o);e.on("drain",f);var h=!1;var p=!1;function d(t){c("ondata"),p=!1,!1!==e.write(t)||p||((1===s.pipesCount&&s.pipes===e||s.pipesCount>1&&-1!==L(s.pipes,e))&&!h&&(c("false write response, pause",s.awaitDrain),s.awaitDrain++,p=!0),o.pause())}function y(t){c("onerror",t),_(),e.removeListener("error",y),0===n(e,"error")&&e.emit("error",t)}function m(){e.removeListener("finish",g),_()}function g(){c("onfinish"),e.removeListener("close",m),_()}function _(){c("unpipe"),o.unpipe(e)}return o.on("data",d),function(t,e,n){if("function"==typeof t.prependListener)return t.prependListener(e,n);t._events&&t._events[e]?r(t._events[e])?t._events[e].unshift(n):t._events[e]=[n,t._events[e]]:t.on(e,n)}(e,"error",y),e.once("close",m),e.once("finish",g),e.emit("pipe",o),s.flowing||(c("pipe resume"),o.resume()),e},m.prototype.unpipe=function(t){var e=this._readableState,r={hasUnpiped:!1};if(0===e.pipesCount)return this;if(1===e.pipesCount)return t&&t!==e.pipes||(t||(t=e.pipes),e.pipes=null,e.pipesCount=0,e.flowing=!1,t&&t.emit("unpipe",this,r)),this;if(!t){var n=e.pipes,i=e.pipesCount;e.pipes=null,e.pipesCount=0,e.flowing=!1;for(var o=0;o<i;o++)n[o].emit("unpipe",this,{hasUnpiped:!1});return this}var s=L(e.pipes,t);return-1===s||(e.pipes.splice(s,1),e.pipesCount-=1,1===e.pipesCount&&(e.pipes=e.pipes[0]),t.emit("unpipe",this,r)),this},m.prototype.on=function(e,r){var n=i.prototype.on.call(this,e,r);if("data"===e)!1!==this._readableState.flowing&&this.resume();else if("readable"===e){var o=this._readableState;o.endEmitted||o.readableListening||(o.readableListening=o.needReadable=!0,o.emittedReadable=!1,o.reading?o.length&&S(this):t.nextTick(O,this))}return n},m.prototype.addListener=m.prototype.on,m.prototype.resume=function(){var e=this._readableState;return e.flowing||(c("resume"),e.flowing=!0,function(e,r){r.resumeScheduled||(r.resumeScheduled=!0,t.nextTick(T,e,r))}(this,e)),this},m.prototype.pause=function(){return c("call pause flowing=%j",this._readableState.flowing),!1!==this._readableState.flowing&&(c("pause"),this._readableState.flowing=!1,this.emit("pause")),this},m.prototype.wrap=function(t){var e=this,r=this._readableState,n=!1;for(var i in t.on("end",function(){if(c("wrapped end"),r.decoder&&!r.ended){var t=r.decoder.end();t&&t.length&&e.push(t)}e.push(null)}),t.on("data",function(i){(c("wrapped data"),r.decoder&&(i=r.decoder.write(i)),r.objectMode&&null==i)||(r.objectMode||i&&i.length)&&(e.push(i)||(n=!0,t.pause()))}),t)void 0===this[i]&&"function"==typeof t[i]&&(this[i]=function(e){return function(){return t[e].apply(t,arguments)}}(i));for(var o=0;o<p.length;o++)t.on(p[o],this.emit.bind(this,p[o]));return this._read=function(e){c("wrapped _read",e),n&&(n=!1,t.resume())},this},Object.defineProperty(m.prototype,"readableHighWaterMark",{enumerable:!1,get:function(){return this._readableState.highWaterMark}}),m._fromList=C,Bf}function Yf(){if(Wf)return zf;Wf=1,zf=n;var t=Mf(),e=Object.create(jr());function r(t,e){var r=this._transformState;r.transforming=!1;var n=r.writecb;if(!n)return this.emit("error",new Error("write callback called multiple times"));r.writechunk=null,r.writecb=null,null!=e&&this.push(e),n(t);var i=this._readableState;i.reading=!1,(i.needReadable||i.length<i.highWaterMark)&&this._read(i.highWaterMark)}function n(e){if(!(this instanceof n))return new n(e);t.call(this,e),this._transformState={afterTransform:r.bind(this),needTransform:!1,transforming:!1,writecb:null,writechunk:null,writeencoding:null},this._readableState.needReadable=!0,this._readableState.sync=!1,e&&("function"==typeof e.transform&&(this._transform=e.transform),"function"==typeof e.flush&&(this._flush=e.flush)),this.on("prefinish",i)}function i(){var t=this;"function"==typeof this._flush?this._flush(function(e,r){o(t,e,r)}):o(this,null,null)}function o(t,e,r){if(e)return t.emit("error",e);if(null!=r&&t.push(r),t._writableState.length)throw new Error("Calling transform done when ws.length != 0");if(t._transformState.transforming)throw new Error("Calling transform done when still transforming");return t.push(null)}return e.inherits=Fr(),e.inherits(n,t),n.prototype.push=function(e,r){return this._transformState.needTransform=!1,t.prototype.push.call(this,e,r)},n.prototype._transform=function(t,e,r){throw new Error("_transform() is not implemented")},n.prototype._write=function(t,e,r){var n=this._transformState;if(n.writecb=r,n.writechunk=t,n.writeencoding=e,!n.transforming){var i=this._readableState;(n.needTransform||i.needReadable||i.length<i.highWaterMark)&&this._read(i.highWaterMark)}},n.prototype._read=function(t){var e=this._transformState;null!==e.writechunk&&e.writecb&&!e.transforming?(e.transforming=!0,this._transform(e.writechunk,e.writeencoding,e.afterTransform)):e.needTransform=!0},n.prototype._destroy=function(e,r){var n=this;t.prototype._destroy.call(this,e,function(t){r(t),n.emit("close")})},zf}function Xf(){return qf||(qf=1,t=wf,e=wf.exports,r=g,"disable"===process.env.READABLE_STREAM&&r?(t.exports=r,(e=t.exports=r.Readable).Readable=r.Readable,e.Writable=r.Writable,e.Duplex=r.Duplex,e.Transform=r.Transform,e.PassThrough=r.PassThrough,e.Stream=r):((e=t.exports=Jf()).Stream=r||e,e.Readable=e,e.Writable=Df(),e.Duplex=Mf(),e.Transform=Yf(),e.PassThrough=function(){if($f)return Hf;$f=1,Hf=r;var t=Yf(),e=Object.create(jr());function r(e){if(!(this instanceof r))return new r(e);t.call(this,e)}return e.inherits=Fr(),e.inherits(r,t),r.prototype._transform=function(t,e,r){r(null,t)},Hf}())),wf.exports;var t,e,r}function th(){if(Gf)return vf.exports;Gf=1;var t=Xf();function e(e,r,n){void 0===n&&(n=r,r=e,e=null),t.Duplex.call(this,e),"function"!=typeof n.read&&(n=new t.Readable(e).wrap(n)),this._writable=r,this._readable=n,this._waiting=!1;var i=this;r.once("finish",function(){i.end()}),this.once("finish",function(){r.end()}),n.on("readable",function(){i._waiting&&(i._waiting=!1,i._read())}),n.once("end",function(){i.push(null)}),e&&void 0!==e.bubbleErrors&&!e.bubbleErrors||(r.on("error",function(t){i.emit("error",t)}),n.on("error",function(t){i.emit("error",t)}))}return e.prototype=Object.create(t.Duplex.prototype,{constructor:{value:e}}),e.prototype._write=function(t,e,r){this._writable.write(t,e,r)},e.prototype._read=function(){for(var t,e=0;null!==(t=this._readable.read());)this.push(t),e++;0===e&&(this._waiting=!0)},vf.exports=function(t,r,n){return new e(t,r,n)},vf.exports.DuplexWrapper=e,vf.exports}var eh,rh,nh={},ih={};function oh(){return eh||(eh=1,ih.fromCallback=function(t){return Object.defineProperty(function(...e){if("function"!=typeof e[e.length-1])return new Promise((r,n)=>{e.push((t,e)=>null!=t?n(t):r(e)),t.apply(this,e)});t.apply(this,e)},"name",{value:t.name})},ih.fromPromise=function(t){return Object.defineProperty(function(...e){const r=e[e.length-1];if("function"!=typeof r)return t.apply(this,e);e.pop(),t.apply(this,e).then(t=>r(null,t),r)},"name",{value:t.name})}),ih}function sh(){return rh||(rh=1,function(t){const e=oh().fromCallback,r=hr(),n=["access","appendFile","chmod","chown","close","copyFile","cp","fchmod","fchown","fdatasync","fstat","fsync","ftruncate","futimes","glob","lchmod","lchown","lutimes","link","lstat","mkdir","mkdtemp","open","opendir","readdir","readFile","readlink","realpath","rename","rm","rmdir","stat","statfs","symlink","truncate","unlink","utimes","writeFile"].filter(t=>"function"==typeof r[t]);Object.assign(t,r),n.forEach(n=>{t[n]=e(r[n])}),t.exists=function(t,e){return"function"==typeof e?r.exists(t,e):new Promise(e=>r.exists(t,e))},t.read=function(t,e,n,i,o,s){return"function"==typeof s?r.read(t,e,n,i,o,s):new Promise((s,a)=>{r.read(t,e,n,i,o,(t,e,r)=>{if(t)return a(t);s({bytesRead:e,buffer:r})})})},t.write=function(t,e,...n){return"function"==typeof n[n.length-1]?r.write(t,e,...n):new Promise((i,o)=>{r.write(t,e,...n,(t,e,r)=>{if(t)return o(t);i({bytesWritten:e,buffer:r})})})},t.readv=function(t,e,...n){return"function"==typeof n[n.length-1]?r.readv(t,e,...n):new Promise((i,o)=>{r.readv(t,e,...n,(t,e,r)=>{if(t)return o(t);i({bytesRead:e,buffers:r})})})},t.writev=function(t,e,...n){return"function"==typeof n[n.length-1]?r.writev(t,e,...n):new Promise((i,o)=>{r.writev(t,e,...n,(t,e,r)=>{if(t)return o(t);i({bytesWritten:e,buffers:r})})})},"function"==typeof r.realpath.native?t.realpath.native=e(r.realpath.native):process.emitWarning("fs.realpath.native is not a function. Is fs being monkey-patched?","Warning","fs-extra-WARN0003")}(nh)),nh}var ah,uh,ch,lh,fh,hh,ph,dh,yh,mh,gh,_h,bh,vh,wh,Sh,Eh,kh,xh,Oh,Th,jh,Ch,Rh,Ph,Lh,Fh,Ah,Ih,Dh,Mh,Nh,Bh,Uh,zh,Wh,Hh,$h,qh,Gh,Vh,Qh,Zh,Kh,Jh,Yh,Xh,tp,ep,rp,np,ip,op,sp,ap,up,cp,lp,fp={},hp={};function pp(){if(uh)return fp;uh=1;const t=sh(),{checkPath:e}=function(){if(ah)return hp;ah=1;const t=y;return hp.checkPath=function(e){if("win32"===process.platform&&/[<>:"|?*]/.test(e.replace(t.parse(e).root,""))){const t=new Error(`Path contains invalid characters: ${e}`);throw t.code="EINVAL",t}},hp}(),r=t=>"number"==typeof t?t:{mode:511,...t}.mode;return fp.makeDir=async(n,i)=>(e(n),t.mkdir(n,{mode:r(i),recursive:!0})),fp.makeDirSync=(n,i)=>(e(n),t.mkdirSync(n,{mode:r(i),recursive:!0})),fp}function dp(){if(lh)return ch;lh=1;const t=oh().fromPromise,{makeDir:e,makeDirSync:r}=pp(),n=t(e);return ch={mkdirs:n,mkdirsSync:r,mkdirp:n,mkdirpSync:r,ensureDir:n,ensureDirSync:r}}function yp(){if(hh)return fh;hh=1;const t=oh().fromPromise,e=sh();return fh={pathExists:t(function(t){return e.access(t).then(()=>!0).catch(()=>!1)}),pathExistsSync:e.existsSync},fh}function mp(){if(dh)return ph;dh=1;const t=sh(),e=oh().fromPromise;return ph={utimesMillis:e(async function(e,r,n){const i=await t.open(e,"r+");let o=null;try{await t.futimes(i,r,n)}finally{try{await t.close(i)}catch(t){o=t}}if(o)throw o}),utimesMillisSync:function(e,r,n){const i=t.openSync(e,"r+");return t.futimesSync(i,r,n),t.closeSync(i)}},ph}function gp(){if(mh)return yh;mh=1;const t=sh(),e=y,r=oh().fromPromise;function n(t,e){return void 0!==e.ino&&void 0!==e.dev&&e.ino===t.ino&&e.dev===t.dev}function i(t,r){const n=e.resolve(t).split(e.sep).filter(t=>t),i=e.resolve(r).split(e.sep).filter(t=>t);return n.every((t,e)=>i[e]===t)}function o(t,e,r){return`Cannot ${r} '${t}' to a subdirectory of itself, '${e}'.`}return yh={checkPaths:r(async function(r,s,a,u){const{srcStat:c,destStat:l}=await function(e,r,n){const i=n.dereference?e=>t.stat(e,{bigint:!0}):e=>t.lstat(e,{bigint:!0});return Promise.all([i(e),i(r).catch(t=>{if("ENOENT"===t.code)return null;throw t})]).then(([t,e])=>({srcStat:t,destStat:e}))}(r,s,u);if(l){if(n(c,l)){const t=e.basename(r),n=e.basename(s);if("move"===a&&t!==n&&t.toLowerCase()===n.toLowerCase())return{srcStat:c,destStat:l,isChangingCase:!0};throw new Error("Source and destination must not be the same.")}if(c.isDirectory()&&!l.isDirectory())throw new Error(`Cannot overwrite non-directory '${s}' with directory '${r}'.`);if(!c.isDirectory()&&l.isDirectory())throw new Error(`Cannot overwrite directory '${s}' with non-directory '${r}'.`)}if(c.isDirectory()&&i(r,s))throw new Error(o(r,s,a));return{srcStat:c,destStat:l}}),checkPathsSync:function(r,s,a,u){const{srcStat:c,destStat:l}=function(e,r,n){let i;const o=n.dereference?e=>t.statSync(e,{bigint:!0}):e=>t.lstatSync(e,{bigint:!0}),s=o(e);try{i=o(r)}catch(t){if("ENOENT"===t.code)return{srcStat:s,destStat:null};throw t}return{srcStat:s,destStat:i}}(r,s,u);if(l){if(n(c,l)){const t=e.basename(r),n=e.basename(s);if("move"===a&&t!==n&&t.toLowerCase()===n.toLowerCase())return{srcStat:c,destStat:l,isChangingCase:!0};throw new Error("Source and destination must not be the same.")}if(c.isDirectory()&&!l.isDirectory())throw new Error(`Cannot overwrite non-directory '${s}' with directory '${r}'.`);if(!c.isDirectory()&&l.isDirectory())throw new Error(`Cannot overwrite directory '${s}' with non-directory '${r}'.`)}if(c.isDirectory()&&i(r,s))throw new Error(o(r,s,a));return{srcStat:c,destStat:l}},checkParentPaths:r(async function r(i,s,a,u){const c=e.resolve(e.dirname(i)),l=e.resolve(e.dirname(a));if(l===c||l===e.parse(l).root)return;let f;try{f=await t.stat(l,{bigint:!0})}catch(t){if("ENOENT"===t.code)return;throw t}if(n(s,f))throw new Error(o(i,a,u));return r(i,s,l,u)}),checkParentPathsSync:function r(i,s,a,u){const c=e.resolve(e.dirname(i)),l=e.resolve(e.dirname(a));if(l===c||l===e.parse(l).root)return;let f;try{f=t.statSync(l,{bigint:!0})}catch(t){if("ENOENT"===t.code)return;throw t}if(n(s,f))throw new Error(o(i,a,u));return r(i,s,l,u)},isSrcSubdir:i,areIdentical:n},yh}function _p(){if(vh)return bh;vh=1;const t=sh(),e=y,{mkdirs:r}=dp(),{pathExists:n}=yp(),{utimesMillis:i}=mp(),o=gp(),{asyncIteratorConcurrentProcess:s}=(_h||(_h=1,gh={asyncIteratorConcurrentProcess:async function(t,e){const r=[];for await(const n of t)r.push(e(n).then(()=>null,t=>t??new Error("unknown error")));await Promise.all(r.map(t=>t.then(t=>{if(null!==t)throw t})))}}),gh);async function a(t,e,r){return!r.filter||r.filter(t,e)}async function u(r,n,i,l){const f=l.dereference?t.stat:t.lstat,h=await f(n);if(h.isDirectory())return async function(r,n,i,c,l){n||await t.mkdir(c);await s(await t.opendir(i),async t=>{const r=e.join(i,t.name),n=e.join(c,t.name);if(await a(r,n,l)){const{destStat:t}=await o.checkPaths(r,n,"copy",l);await u(t,r,n,l)}}),n||await t.chmod(c,r.mode)}(h,r,n,i,l);if(h.isFile()||h.isCharacterDevice()||h.isBlockDevice())return async function(e,r,n,i,o){if(!r)return c(e,n,i,o);if(o.overwrite)return await t.unlink(i),c(e,n,i,o);if(o.errorOnExist)throw new Error(`'${i}' already exists`)}(h,r,n,i,l);if(h.isSymbolicLink())return async function(r,n,i,s){let a=await t.readlink(n);s.dereference&&(a=e.resolve(process.cwd(),a));if(!r)return t.symlink(a,i);let u=null;try{u=await t.readlink(i)}catch(e){if("EINVAL"===e.code||"UNKNOWN"===e.code)return t.symlink(a,i);throw e}s.dereference&&(u=e.resolve(process.cwd(),u));if(o.isSrcSubdir(a,u))throw new Error(`Cannot copy '${a}' to a subdirectory of itself, '${u}'.`);if(o.isSrcSubdir(u,a))throw new Error(`Cannot overwrite '${u}' with '${a}'.`);return await t.unlink(i),t.symlink(a,i)}(r,n,i,l);if(h.isSocket())throw new Error(`Cannot copy a socket file: ${n}`);if(h.isFIFO())throw new Error(`Cannot copy a FIFO pipe: ${n}`);throw new Error(`Unknown file: ${n}`)}async function c(e,r,n,o){if(await t.copyFile(r,n),o.preserveTimestamps){128&e.mode||await function(e,r){return t.chmod(e,128|r)}(n,e.mode);const o=await t.stat(r);await i(n,o.atime,o.mtime)}return t.chmod(n,e.mode)}return bh=async function(t,i,s={}){"function"==typeof s&&(s={filter:s}),s.clobber=!("clobber"in s)||!!s.clobber,s.overwrite="overwrite"in s?!!s.overwrite:s.clobber,s.preserveTimestamps&&"ia32"===process.arch&&process.emitWarning("Using the preserveTimestamps option in 32-bit node is not recommended;\n\n\tsee https://github.com/jprichardson/node-fs-extra/issues/269","Warning","fs-extra-WARN0001");const{srcStat:c,destStat:l}=await o.checkPaths(t,i,"copy",s);if(await o.checkParentPaths(t,c,i,"copy"),!await a(t,i,s))return;const f=e.dirname(i);await n(f)||await r(f),await u(l,t,i,s)}}function bp(){if(Sh)return wh;Sh=1;const t=hr(),e=y,r=dp().mkdirsSync,n=mp().utimesMillisSync,i=gp();function o(r,n,o,c){const l=(c.dereference?t.statSync:t.lstatSync)(n);if(l.isDirectory())return function(e,r,n,i,o){return r?u(n,i,o):function(e,r,n,i){return t.mkdirSync(n),u(r,n,i),a(n,e)}(e.mode,n,i,o)}(l,r,n,o,c);if(l.isFile()||l.isCharacterDevice()||l.isBlockDevice())return function(e,r,n,i,o){return r?function(e,r,n,i){if(i.overwrite)return t.unlinkSync(n),s(e,r,n,i);if(i.errorOnExist)throw new Error(`'${n}' already exists`)}(e,n,i,o):s(e,n,i,o)}(l,r,n,o,c);if(l.isSymbolicLink())return function(r,n,o,s){let a=t.readlinkSync(n);s.dereference&&(a=e.resolve(process.cwd(),a));if(r){let r;try{r=t.readlinkSync(o)}catch(e){if("EINVAL"===e.code||"UNKNOWN"===e.code)return t.symlinkSync(a,o);throw e}if(s.dereference&&(r=e.resolve(process.cwd(),r)),i.isSrcSubdir(a,r))throw new Error(`Cannot copy '${a}' to a subdirectory of itself, '${r}'.`);if(i.isSrcSubdir(r,a))throw new Error(`Cannot overwrite '${r}' with '${a}'.`);return function(e,r){return t.unlinkSync(r),t.symlinkSync(e,r)}(a,o)}return t.symlinkSync(a,o)}(r,n,o,c);if(l.isSocket())throw new Error(`Cannot copy a socket file: ${n}`);if(l.isFIFO())throw new Error(`Cannot copy a FIFO pipe: ${n}`);throw new Error(`Unknown file: ${n}`)}function s(e,r,i,o){return t.copyFileSync(r,i),o.preserveTimestamps&&function(e,r,i){(function(t){return!(128&t)})(e)&&function(t,e){a(t,128|e)}(i,e);(function(e,r){const i=t.statSync(e);n(r,i.atime,i.mtime)})(r,i)}(e.mode,r,i),a(i,e.mode)}function a(e,r){return t.chmodSync(e,r)}function u(e,r,n){const i=t.opendirSync(e);try{let t;for(;null!==(t=i.readSync());)c(t.name,e,r,n)}finally{i.closeSync()}}function c(t,r,n,s){const a=e.join(r,t),u=e.join(n,t);if(s.filter&&!s.filter(a,u))return;const{destStat:c}=i.checkPathsSync(a,u,"copy",s);return o(c,a,u,s)}return wh=function(n,s,a){"function"==typeof a&&(a={filter:a}),(a=a||{}).clobber=!("clobber"in a)||!!a.clobber,a.overwrite="overwrite"in a?!!a.overwrite:a.clobber,a.preserveTimestamps&&"ia32"===process.arch&&process.emitWarning("Using the preserveTimestamps option in 32-bit node is not recommended;\n\n\tsee https://github.com/jprichardson/node-fs-extra/issues/269","Warning","fs-extra-WARN0002");const{srcStat:u,destStat:c}=i.checkPathsSync(n,s,"copy",a);if(i.checkParentPathsSync(n,u,s,"copy"),a.filter&&!a.filter(n,s))return;const l=e.dirname(s);return t.existsSync(l)||r(l),o(c,n,s,a)}}function vp(){if(kh)return Eh;kh=1;const t=oh().fromPromise;return Eh={copy:t(_p()),copySync:bp()}}function wp(){if(Oh)return xh;Oh=1;const t=hr(),e=oh().fromCallback;return xh={remove:e(function(e,r){t.rm(e,{recursive:!0,force:!0},r)}),removeSync:function(e){t.rmSync(e,{recursive:!0,force:!0})}},xh}function Sp(){if(jh)return Th;jh=1;const t=oh().fromPromise,e=sh(),r=y,n=dp(),i=wp(),o=t(async function(t){let o;try{o=await e.readdir(t)}catch{return n.mkdirs(t)}return Promise.all(o.map(e=>i.remove(r.join(t,e))))});function s(t){let o;try{o=e.readdirSync(t)}catch{return n.mkdirsSync(t)}o.forEach(e=>{e=r.join(t,e),i.removeSync(e)})}return Th={emptyDirSync:s,emptydirSync:s,emptyDir:o,emptydir:o}}function Ep(){if(Nh)return Mh;Nh=1;const t=oh().fromPromise,e=y,r=sh(),{mkdirs:n,mkdirsSync:i}=dp(),{symlinkPaths:o,symlinkPathsSync:s}=function(){if(Ah)return Fh;Ah=1;const t=y,e=sh(),{pathExists:r}=yp(),n=oh().fromPromise;return Fh={symlinkPaths:n(async function(n,i){if(t.isAbsolute(n)){try{await e.lstat(n)}catch(t){throw t.message=t.message.replace("lstat","ensureSymlink"),t}return{toCwd:n,toDst:n}}const o=t.dirname(i),s=t.join(o,n);if(await r(s))return{toCwd:s,toDst:n};try{await e.lstat(n)}catch(t){throw t.message=t.message.replace("lstat","ensureSymlink"),t}return{toCwd:n,toDst:t.relative(o,n)}}),symlinkPathsSync:function(r,n){if(t.isAbsolute(r)){if(!e.existsSync(r))throw new Error("absolute srcpath does not exist");return{toCwd:r,toDst:r}}const i=t.dirname(n),o=t.join(i,r);if(e.existsSync(o))return{toCwd:o,toDst:r};if(!e.existsSync(r))throw new Error("relative srcpath does not exist");return{toCwd:r,toDst:t.relative(i,r)}}}}(),{symlinkType:a,symlinkTypeSync:u}=function(){if(Dh)return Ih;Dh=1;const t=sh(),e=oh().fromPromise;return Ih={symlinkType:e(async function(e,r){if(r)return r;let n;try{n=await t.lstat(e)}catch{return"file"}return n&&n.isDirectory()?"dir":"file"}),symlinkTypeSync:function(e,r){if(r)return r;let n;try{n=t.lstatSync(e)}catch{return"file"}return n&&n.isDirectory()?"dir":"file"}}}(),{pathExists:c}=yp(),{areIdentical:l}=gp();return Mh={createSymlink:t(async function(t,i,s){let u;try{u=await r.lstat(i)}catch{}if(u&&u.isSymbolicLink()){const[e,n]=await Promise.all([r.stat(t),r.stat(i)]);if(l(e,n))return}const f=await o(t,i);t=f.toDst;const h=await a(f.toCwd,s),p=e.dirname(i);return await c(p)||await n(p),r.symlink(t,i,h)}),createSymlinkSync:function(t,n,o){let a;try{a=r.lstatSync(n)}catch{}if(a&&a.isSymbolicLink()){const e=r.statSync(t),i=r.statSync(n);if(l(e,i))return}const c=s(t,n);t=c.toDst,o=u(c.toCwd,o);const f=e.dirname(n);return r.existsSync(f)||i(f),r.symlinkSync(t,n,o)}},Mh}function kp(){if(Uh)return Bh;Uh=1;const{createFile:t,createFileSync:e}=function(){if(Rh)return Ch;Rh=1;const t=oh().fromPromise,e=y,r=sh(),n=dp();return Ch={createFile:t(async function(t){let i;try{i=await r.stat(t)}catch{}if(i&&i.isFile())return;const o=e.dirname(t);let s=null;try{s=await r.stat(o)}catch(e){if("ENOENT"===e.code)return await n.mkdirs(o),void await r.writeFile(t,"");throw e}s.isDirectory()?await r.writeFile(t,""):await r.readdir(o)}),createFileSync:function(t){let i;try{i=r.statSync(t)}catch{}if(i&&i.isFile())return;const o=e.dirname(t);try{r.statSync(o).isDirectory()||r.readdirSync(o)}catch(t){if(!t||"ENOENT"!==t.code)throw t;n.mkdirsSync(o)}r.writeFileSync(t,"")}},Ch}(),{createLink:r,createLinkSync:n}=function(){if(Lh)return Ph;Lh=1;const t=oh().fromPromise,e=y,r=sh(),n=dp(),{pathExists:i}=yp(),{areIdentical:o}=gp();return Ph={createLink:t(async function(t,s){let a,u;try{a=await r.lstat(s)}catch{}try{u=await r.lstat(t)}catch(t){throw t.message=t.message.replace("lstat","ensureLink"),t}if(a&&o(u,a))return;const c=e.dirname(s);await i(c)||await n.mkdirs(c),await r.link(t,s)}),createLinkSync:function(t,i){let s;try{s=r.lstatSync(i)}catch{}try{const e=r.lstatSync(t);if(s&&o(e,s))return}catch(t){throw t.message=t.message.replace("lstat","ensureLink"),t}const a=e.dirname(i);return r.existsSync(a)||n.mkdirsSync(a),r.linkSync(t,i)}},Ph}(),{createSymlink:i,createSymlinkSync:o}=Ep();return Bh={createFile:t,createFileSync:e,ensureFile:t,ensureFileSync:e,createLink:r,createLinkSync:n,ensureLink:r,ensureLinkSync:n,createSymlink:i,createSymlinkSync:o,ensureSymlink:i,ensureSymlinkSync:o}}function xp(){if(Wh)return zh;return Wh=1,zh={stringify:function(t,{EOL:e="\n",finalEOL:r=!0,replacer:n=null,spaces:i}={}){const o=r?e:"";return JSON.stringify(t,n,i).replace(/\n/g,e)+o},stripBom:function(t){return Buffer.isBuffer(t)&&(t=t.toString("utf8")),t.replace(/^\uFEFF/,"")}}}function Op(){if(Gh)return qh;Gh=1;const t=function(){if($h)return Hh;let t;$h=1;try{t=hr()}catch(e){t=p}const e=oh(),{stringify:r,stripBom:n}=xp(),i=e.fromPromise(async function(r,i={}){"string"==typeof i&&(i={encoding:i});const o=i.fs||t,s=!("throws"in i)||i.throws;let a,u=await e.fromCallback(o.readFile)(r,i);u=n(u);try{a=JSON.parse(u,i?i.reviver:null)}catch(t){if(s)throw t.message=`${r}: ${t.message}`,t;return null}return a}),o=e.fromPromise(async function(n,i,o={}){const s=o.fs||t,a=r(i,o);await e.fromCallback(s.writeFile)(n,a,o)});return Hh={readFile:i,readFileSync:function(e,r={}){"string"==typeof r&&(r={encoding:r});const i=r.fs||t,o=!("throws"in r)||r.throws;try{let t=i.readFileSync(e,r);return t=n(t),JSON.parse(t,r.reviver)}catch(t){if(o)throw t.message=`${e}: ${t.message}`,t;return null}},writeFile:o,writeFileSync:function(e,n,i={}){const o=i.fs||t,s=r(n,i);return o.writeFileSync(e,s,i)}},Hh}();return qh={readJson:t.readFile,readJsonSync:t.readFileSync,writeJson:t.writeFile,writeJsonSync:t.writeFileSync}}function Tp(){if(Qh)return Vh;Qh=1;const t=oh().fromPromise,e=sh(),r=y,n=dp(),i=yp().pathExists;return Vh={outputFile:t(async function(t,o,s="utf-8"){const a=r.dirname(t);return await i(a)||await n.mkdirs(a),e.writeFile(t,o,s)}),outputFileSync:function(t,...i){const o=r.dirname(t);e.existsSync(o)||n.mkdirsSync(o),e.writeFileSync(t,...i)}},Vh}function jp(){if(tp)return Xh;tp=1;const t=oh().fromPromise,e=Op();return e.outputJson=t(function(){if(Kh)return Zh;Kh=1;const{stringify:t}=xp(),{outputFile:e}=Tp();return Zh=async function(r,n,i={}){const o=t(n,i);await e(r,o,i)},Zh}()),e.outputJsonSync=function(){if(Yh)return Jh;Yh=1;const{stringify:t}=xp(),{outputFileSync:e}=Tp();return Jh=function(r,n,i){const o=t(n,i);e(r,o,i)},Jh}(),e.outputJSON=e.outputJson,e.outputJSONSync=e.outputJsonSync,e.writeJSON=e.writeJson,e.writeJSONSync=e.writeJsonSync,e.readJSON=e.readJson,e.readJSONSync=e.readJsonSync,Xh=e}function Cp(){if(rp)return ep;rp=1;const t=sh(),e=y,{copy:r}=vp(),{remove:n}=wp(),{mkdirp:i}=dp(),{pathExists:o}=yp(),s=gp();return ep=async function(a,u,c={}){const l=c.overwrite||c.clobber||!1,{srcStat:f,isChangingCase:h=!1}=await s.checkPaths(a,u,"move",c);await s.checkParentPaths(a,f,u,"move");const p=e.dirname(u);return e.parse(p).root!==p&&await i(p),async function(e,i,s,a){if(!a)if(s)await n(i);else if(await o(i))throw new Error("dest already exists.");try{await t.rename(e,i)}catch(t){if("EXDEV"!==t.code)throw t;await async function(t,e,i){const o={overwrite:i,errorOnExist:!0,preserveTimestamps:!0};return await r(t,e,o),n(t)}(e,i,s)}}(a,u,l,h)}}function Rp(){if(ip)return np;ip=1;const t=hr(),e=y,r=vp().copySync,n=wp().removeSync,i=dp().mkdirpSync,o=gp();function s(e,i,o){try{t.renameSync(e,i)}catch(t){if("EXDEV"!==t.code)throw t;return function(t,e,i){const o={overwrite:i,errorOnExist:!0,preserveTimestamps:!0};return r(t,e,o),n(t)}(e,i,o)}}return np=function(r,a,u){const c=(u=u||{}).overwrite||u.clobber||!1,{srcStat:l,isChangingCase:f=!1}=o.checkPathsSync(r,a,"move",u);return o.checkParentPathsSync(r,l,a,"move"),function(t){const r=e.dirname(t),n=e.parse(r);return n.root===r}(a)||i(e.dirname(a)),function(e,r,i,o){if(o)return s(e,r,i);if(i)return n(r),s(e,r,i);if(t.existsSync(r))throw new Error("dest already exists.");return s(e,r,i)}(r,a,c,f)},np}function Pp(){if(sp)return op;sp=1;const t=oh().fromPromise;return op={move:t(Cp()),moveSync:Rp()}}function Lp(){return up?ap:(up=1,ap={...sh(),...vp(),...Sp(),...kp(),...jp(),...dp(),...Pp(),...Tp(),...yp(),...wp()})}var Fp,Ap,Ip,Dp,Mp,Np={exports:{}};function Bp(){if(Fp)return Np.exports;Fp=1;for(var t=4294967296,e=[],r=0;r<256;r++)e[r]=(r>15?"":"0")+r.toString(16);var n=Np.exports=function(t,e){t instanceof Buffer?(this.buffer=t,this.offset=e||0):"[object Uint8Array]"==Object.prototype.toString.call(t)?(this.buffer=new Buffer(t),this.offset=e||0):(this.buffer=this.buffer||new Buffer(8),this.offset=0,this.setValue.apply(this,arguments))};return n.MAX_INT=Math.pow(2,53),n.MIN_INT=-Math.pow(2,53),n.prototype={constructor:n,_2scomp:function(){for(var t=this.buffer,e=this.offset,r=1,n=e+7;n>=e;n--){var i=(255^t[n])+r;t[n]=255&i,r=i>>8}},setValue:function(e,r){var n=!1;if(1==arguments.length)if("number"==typeof e){if(n=e<0,r=(e=Math.abs(e))%t,(e/=t)>t)throw new RangeError(e+" is outside Int64 range");e|=0}else{if("string"!=typeof e)throw new Error(e+" must be a Number or String");r=(e=(e+"").replace(/^0x/,"")).substr(-8),e=e.length>8?e.substr(0,e.length-8):"",e=parseInt(e,16),r=parseInt(r,16)}for(var i=this.buffer,o=this.offset,s=7;s>=0;s--)i[o+s]=255&r,r=4==s?e:r>>>8;n&&this._2scomp()},toNumber:function(t){for(var e=this.buffer,r=this.offset,i=128&e[r],o=0,s=1,a=7,u=1;a>=0;a--,u*=256){var c=e[r+a];i&&(s=(c=(255^c)+s)>>8,c&=255),o+=c*u}return!t&&o>=n.MAX_INT?i?-1/0:1/0:i?-o:o},valueOf:function(){return this.toNumber(!1)},toString:function(t){return this.valueOf().toString(t||10)},toOctetString:function(t){for(var r=new Array(8),n=this.buffer,i=this.offset,o=0;o<8;o++)r[o]=e[n[i+o]];return r.join(t||"")},toBuffer:function(t){if(t&&0===this.offset)return this.buffer;var e=new Buffer(8);return this.buffer.copy(e,0,this.offset,this.offset+8),e},copy:function(t,e){this.buffer.copy(t,e||0,this.offset,this.offset+8)},compare:function(t){if((128&this.buffer[this.offset])!=(128&t.buffer[t.offset]))return t.buffer[t.offset]-this.buffer[this.offset];for(var e=0;e<8;e++)if(this.buffer[this.offset+e]!==t.buffer[t.offset+e])return this.buffer[this.offset+e]-t.buffer[t.offset+e];return 0},equals:function(t){return 0===this.compare(t)},inspect:function(){return"[Int64 value:"+this+" octets:"+this.toOctetString(" ")+"]"}},Np.exports}function Up(){if(Ip)return Ap;Ip=1;const t=Bp();let e,r=g;function n(t,r){e||function(){let t,r,n;for(e=[],r=0;r<256;r++){for(t=r,n=0;n<8;n++)t=1&t?3988292384^t>>>1:t>>>=1;e[r]=t>>>0}}(),t.charCodeAt&&(t=t.charCodeAt(0));return(r.readUInt32BE()>>8&16777215^e[255&(r.readUInt32BE()^t>>>0)])>>>0}function i(t,e){const r=65535&t,n=65535&e;return(((t>>16&65535)*n+r*(e>>16&65535)&65535)<<16>>>0)+r*n}function o(){if(!(this instanceof o))return new o;this.key0=Buffer.allocUnsafe(4),this.key1=Buffer.allocUnsafe(4),this.key2=Buffer.allocUnsafe(4),this.key0.writeUInt32BE(305419896,0),this.key1.writeUInt32BE(591751049,0),this.key2.writeUInt32BE(878082192,0)}return r.Writable&&r.Writable.prototype.destroy||(r=ws()),o.prototype.update=function(e){this.key0.writeUInt32BE(n(e,this.key0)),this.key1.writeUInt32BE((255&this.key0.readUInt32BE())+this.key1.readUInt32BE()>>>0);const r=new t(i(this.key1.readUInt32BE(),134775813)+1&4294967295),o=Buffer.alloc(8);r.copy(o,0),o.copy(this.key1,0,4,8),this.key2.writeUInt32BE(n((this.key1.readUInt32BE()>>24&255)>>>0,this.key2))},o.prototype.decryptByte=function(t){const e=(2|this.key2.readUInt32BE())>>>0;return t^=i(e,1^e)>>8&255,this.update(t),t},o.prototype.stream=function(){const t=r.Transform(),e=this;return t._transform=function(t,r,n){for(let r=0;r<t.length;r++)t[r]=e.decryptByte(t[r]);this.push(t),n()},t},Ap=o}function zp(){if(Mp)return Dp;Mp=1;const t=Up(),e=hf(),r=g,n=S,i=yf(),o=mf(),s=df();return Dp=function(a,u,c,l,f){const h=e(),p=r.PassThrough(),d=a.stream(u,f);return d.pipe(h).on("error",function(t){p.emit("error",t)}),p.vars=h.pull(30).then(function(e){let r=s.parse(e,[["signature",4],["versionsNeededToExtract",2],["flags",2],["compressionMethod",2],["lastModifiedTime",2],["lastModifiedDate",2],["crc32",4],["compressedSize",4],["uncompressedSize",4],["fileNameLength",2],["extraFieldLength",2]]);return r.lastModifiedDateTime=o(r.lastModifiedDate,r.lastModifiedTime),h.pull(r.fileNameLength).then(function(t){return r.fileName=t.toString("utf8"),h.pull(r.extraFieldLength)}).then(function(e){let n;return r.extra=i(e,r),l&&l.compressedSize&&(r=l),1&r.flags&&(n=h.pull(12).then(function(e){if(!c)throw new Error("MISSING_PASSWORD");const n=t();String(c).split("").forEach(function(t){n.update(t)});for(let t=0;t<e.length;t++)e[t]=n.decryptByte(e[t]);r.decrypt=n,r.compressedSize-=12;const i=8&r.flags?r.lastModifiedTime>>8&255:r.crc32>>24&255;if(e[11]!==i)throw new Error("BAD_PASSWORD");return r})),Promise.resolve(n).then(function(){return p.emit("vars",r),r})})}),p.vars.then(function(t){const e=!(8&t.flags)||t.compressedSize>0;let i;const o=t.compressionMethod?n.createInflateRaw():r.PassThrough();e?(p.size=t.uncompressedSize,i=t.compressedSize):(i=Buffer.alloc(4),i.writeUInt32LE(134695760,0));let s=h.stream(i);t.decrypt&&(s=s.pipe(t.decrypt.stream())),s.pipe(o).on("error",function(t){p.emit("error",t)}).pipe(p).on("finish",function(){d.destroy?d.destroy():d.abort?d.abort():d.close?d.close():d.push?d.push():console.log("warning - unable to close stream")})}).catch(function(t){p.emit("error",t)}),p},Dp}var Wp,Hp,$p,qp={exports:{}},Gp={exports:{}};function Vp(){if(Wp)return Gp.exports;Wp=1;var t=function(){return void 0===this}();if(t)Gp.exports={freeze:Object.freeze,defineProperty:Object.defineProperty,getDescriptor:Object.getOwnPropertyDescriptor,keys:Object.keys,names:Object.getOwnPropertyNames,getPrototypeOf:Object.getPrototypeOf,isArray:Array.isArray,isES5:t,propertyIsWritable:function(t,e){var r=Object.getOwnPropertyDescriptor(t,e);return!(r&&!r.writable&&!r.set)}};else{var e={}.hasOwnProperty,r={}.toString,n={}.constructor.prototype,i=function(t){var r=[];for(var n in t)e.call(t,n)&&r.push(n);return r};Gp.exports={isArray:function(t){try{return"[object Array]"===r.call(t)}catch(t){return!1}},keys:i,names:i,defineProperty:function(t,e,r){return t[e]=r.value,t},getDescriptor:function(t,e){return{value:t[e]}},freeze:function(t){return t},getPrototypeOf:function(t){try{return Object(t).constructor.prototype}catch(t){return n}},isES5:t,propertyIsWritable:function(){return!0}}}return Gp.exports}function Qp(){if($p)return Hp;$p=1;var t,e=Vp(),r="undefined"==typeof navigator,n={e:{}},i="undefined"!=typeof self?self:"undefined"!=typeof window?window:void 0!==I?I:void 0!==Hp?Hp:null;function o(){try{var e=t;return t=null,e.apply(this,arguments)}catch(t){return n.e=t,n}}function s(t){return null==t||!0===t||!1===t||"string"==typeof t||"number"==typeof t}function a(t,r,n){if(s(t))return t;var i={value:n,configurable:!0,enumerable:!1,writable:!0};return e.defineProperty(t,r,i),t}var u=function(){var t=[Array.prototype,Object.prototype,Function.prototype],r=function(e){for(var r=0;r<t.length;++r)if(t[r]===e)return!0;return!1};if(e.isES5){var n=Object.getOwnPropertyNames;return function(t){for(var i=[],o=Object.create(null);null!=t&&!r(t);){var s;try{s=n(t)}catch(t){return i}for(var a=0;a<s.length;++a){var u=s[a];if(!o[u]){o[u]=!0;var c=Object.getOwnPropertyDescriptor(t,u);null!=c&&null==c.get&&null==c.set&&i.push(u)}}t=e.getPrototypeOf(t)}return i}}var i={}.hasOwnProperty;return function(e){if(r(e))return[];var n=[];t:for(var o in e)if(i.call(e,o))n.push(o);else{for(var s=0;s<t.length;++s)if(i.call(t[s],o))continue t;n.push(o)}return n}}(),c=/this\s*\.\s*\S+\s*=/;var l=/^[a-z$_][a-z$_0-9]*$/i;function f(t){try{return t+""}catch(t){return"[no string representation]"}}function h(t){return t instanceof Error||null!==t&&"object"==typeof t&&"string"==typeof t.message&&"string"==typeof t.name}function p(t){return h(t)&&e.propertyIsWritable(t,"stack")}var d="stack"in new Error?function(t){return p(t)?t:new Error(f(t))}:function(t){if(p(t))return t;try{throw new Error(f(t))}catch(t){return t}};function y(t){return{}.toString.call(t)}var m=function(t){return e.isArray(t)?t:null};if("undefined"!=typeof Symbol&&Symbol.iterator){var g="function"==typeof Array.from?function(t){return Array.from(t)}:function(t){for(var e,r=[],n=t[Symbol.iterator]();!(e=n.next()).done;)r.push(e.value);return r};m=function(t){return e.isArray(t)?t:null!=t&&"function"==typeof t[Symbol.iterator]?g(t):null}}var _,b="undefined"!=typeof process&&"[object process]"===y(process).toLowerCase(),v="undefined"!=typeof process&&void 0!==process.env;var w,S={setReflectHandler:function(t){_=t},isClass:function(t){try{if("function"==typeof t){var r=e.names(t.prototype),n=e.isES5&&r.length>1,i=r.length>0&&!(1===r.length&&"constructor"===r[0]),o=c.test(t+"")&&e.names(t).length>0;if(n||i||o)return!0}return!1}catch(t){return!1}},isIdentifier:function(t){return l.test(t)},inheritedDataKeys:u,getDataPropertyOrDefault:function(t,r,n){if(!e.isES5)return{}.hasOwnProperty.call(t,r)?t[r]:void 0;var i=Object.getOwnPropertyDescriptor(t,r);return null!=i?null==i.get&&null==i.set?i.value:n:void 0},thrower:function(t){throw t},isArray:e.isArray,asArray:m,notEnumerableProp:a,isPrimitive:s,isObject:function(t){return"function"==typeof t||"object"==typeof t&&null!==t},isError:h,canEvaluate:r,errorObj:n,tryCatch:function(e){return t=e,o},inherits:function(t,e){var r={}.hasOwnProperty;function n(){for(var n in this.constructor=t,this.constructor$=e,e.prototype)r.call(e.prototype,n)&&"$"!==n.charAt(n.length-1)&&(this[n+"$"]=e.prototype[n])}return n.prototype=e.prototype,t.prototype=new n,t.prototype},withAppended:function(t,e){var r,n=t.length,i=new Array(n+1);for(r=0;r<n;++r)i[r]=t[r];return i[r]=e,i},maybeWrapAsError:function(t){return s(t)?new Error(f(t)):t},toFastProperties:function(t){function e(){}e.prototype=t;var r=new e;function n(){return typeof r.foo}return n(),n(),t},filledRange:function(t,e,r){for(var n=new Array(t),i=0;i<t;++i)n[i]=e+i+r;return n},toString:f,canAttachTrace:p,ensureErrorObject:d,originatesFromRejection:function(t){return null!=t&&(t instanceof Error.__BluebirdErrorTypes__.OperationalError||!0===t.isOperational)},markAsOriginatingFromRejection:function(t){try{a(t,"isOperational",!0)}catch(t){}},classString:y,copyDescriptors:function(t,r,n){for(var i=e.names(t),o=0;o<i.length;++o){var s=i[o];if(n(s))try{e.defineProperty(r,s,e.getDescriptor(t,s))}catch(t){}}},isNode:b,hasEnvVariables:v,env:function(t){return v?process.env[t]:void 0},global:i,getNativePromise:function(){if("function"==typeof Promise)try{if("[object Promise]"===y(new Promise(function(){})))return Promise}catch(t){}},contextBind:function(t,e){if(null===t||"function"!=typeof e||e===_)return e;null!==t.domain&&(e=t.domain.bind(e));var r=t.async;if(null!==r){var n=e;e=function(){for(var t=arguments.length+2,e=new Array(t),i=2;i<t;++i)e[i]=arguments[i-2];return e[0]=n,e[1]=this,r.runInAsyncScope.apply(r,e)}}return e}};S.isRecentNode=S.isNode&&(process.versions&&process.versions.node?w=process.versions.node.split(".").map(Number):process.version&&(w=process.version.split(".").map(Number)),0===w[0]&&w[1]>10||w[0]>0),S.nodeSupportsAsyncResource=S.isNode&&function(){var t=!1;try{t="function"==typeof require("async_hooks").AsyncResource.prototype.runInAsyncScope}catch(e){t=!1}return t}(),S.isNode&&S.toFastProperties(process);try{throw new Error}catch(t){S.lastLineError=t}return Hp=S}var Zp,Kp,Jp,Yp,Xp,td,ed,rd,nd,id,od,sd,ad,ud,cd,ld,fd,hd,pd,dd,yd,md,gd,_d,bd,vd,wd,Sd,Ed,kd,xd,Od,Td,jd,Cd,Rd,Pd,Ld,Fd,Ad,Id,Dd,Md,Nd,Bd,Ud,zd,Wd,Hd,$d,qd,Gd,Vd,Qd,Zd,Kd,Jd,Yd,Xd,ty,ey,ry,ny,iy,oy,sy,ay,uy,cy={exports:{}};function ly(){if(Kp)return Zp;Kp=1;var t,e=Qp(),r=e.getNativePromise();if(e.isNode&&"undefined"==typeof MutationObserver){var n=I.setImmediate,i=process.nextTick;t=e.isRecentNode?function(t){n.call(I,t)}:function(t){i.call(process,t)}}else if("function"==typeof r&&"function"==typeof r.resolve){var o=r.resolve();t=function(t){o.then(t)}}else t="undefined"==typeof MutationObserver||"undefined"!=typeof window&&window.navigator&&(window.navigator.standalone||window.cordova)||!("classList"in document.documentElement)?"undefined"!=typeof setImmediate?function(t){setImmediate(t)}:"undefined"!=typeof setTimeout?function(t){setTimeout(t,0)}:function(){throw new Error("No async scheduler available\n\n See http://goo.gl/MqrFmX\n")}:function(){var t=document.createElement("div"),e={attributes:!0},r=!1,n=document.createElement("div");new MutationObserver(function(){t.classList.toggle("foo"),r=!1}).observe(n,e);return function(i){var o=new MutationObserver(function(){o.disconnect(),i()});o.observe(t,e),r||(r=!0,n.classList.toggle("foo"))}}();return Zp=t}function fy(){if(Xp)return cy.exports;var t;Xp=1;try{throw new Error}catch(e){t=e}var e=ly(),r=function(){if(Yp)return Jp;function t(t){this._capacity=t,this._length=0,this._front=0}return Yp=1,t.prototype._willBeOverCapacity=function(t){return this._capacity<t},t.prototype._pushOne=function(t){var e=this.length();this._checkCapacity(e+1),this[this._front+e&this._capacity-1]=t,this._length=e+1},t.prototype.push=function(t,e,r){var n=this.length()+3;if(this._willBeOverCapacity(n))return this._pushOne(t),this._pushOne(e),void this._pushOne(r);var i=this._front+n-3;this._checkCapacity(n);var o=this._capacity-1;this[i+0&o]=t,this[i+1&o]=e,this[i+2&o]=r,this._length=n},t.prototype.shift=function(){var t=this._front,e=this[t];return this[t]=void 0,this._front=t+1&this._capacity-1,this._length--,e},t.prototype.length=function(){return this._length},t.prototype._checkCapacity=function(t){this._capacity<t&&this._resizeTo(this._capacity<<1)},t.prototype._resizeTo=function(t){var e=this._capacity;this._capacity=t,function(t,e,r,n,i){for(var o=0;o<i;++o)r[o+n]=t[o+e],t[o+e]=void 0}(this,0,this,e,this._front+this._length&e-1)},Jp=t}();function n(){this._customScheduler=!1,this._isTickUsed=!1,this._lateQueue=new r(16),this._normalQueue=new r(16),this._haveDrainedQueues=!1;var t=this;this.drainQueues=function(){t._drainQueues()},this._schedule=e}function i(t){for(;t.length()>0;)o(t)}function o(t){var e=t.shift();if("function"!=typeof e)e._settlePromises();else{var r=t.shift(),n=t.shift();e.call(r,n)}}return n.prototype.setScheduler=function(t){var e=this._schedule;return this._schedule=t,this._customScheduler=!0,e},n.prototype.hasCustomScheduler=function(){return this._customScheduler},n.prototype.haveItemsQueued=function(){return this._isTickUsed||this._haveDrainedQueues},n.prototype.fatalError=function(t,e){e?(process.stderr.write("Fatal "+(t instanceof Error?t.stack:t)+"\n"),process.exit(2)):this.throwLater(t)},n.prototype.throwLater=function(t,e){if(1===arguments.length&&(e=t,t=function(){throw e}),"undefined"!=typeof setTimeout)setTimeout(function(){t(e)},0);else try{this._schedule(function(){t(e)})}catch(t){throw new Error("No async scheduler available\n\n See http://goo.gl/MqrFmX\n")}},n.prototype.invokeLater=function(t,e,r){this._lateQueue.push(t,e,r),this._queueTick()},n.prototype.invoke=function(t,e,r){this._normalQueue.push(t,e,r),this._queueTick()},n.prototype.settlePromises=function(t){this._normalQueue._pushOne(t),this._queueTick()},n.prototype._drainQueues=function(){i(this._normalQueue),this._reset(),this._haveDrainedQueues=!0,i(this._lateQueue)},n.prototype._queueTick=function(){this._isTickUsed||(this._isTickUsed=!0,this._schedule(this.drainQueues))},n.prototype._reset=function(){this._isTickUsed=!1},cy.exports=n,cy.exports.firstLineError=t,cy.exports}function hy(){if(ed)return td;ed=1;var t,e,r=Vp(),n=r.freeze,i=Qp(),o=i.inherits,s=i.notEnumerableProp;function a(t,e){function r(n){if(!(this instanceof r))return new r(n);s(this,"message","string"==typeof n?n:e),s(this,"name",t),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):Error.call(this)}return o(r,Error),r}var u=a("Warning","warning"),c=a("CancellationError","cancellation error"),l=a("TimeoutError","timeout error"),f=a("AggregateError","aggregate error");try{t=TypeError,e=RangeError}catch(r){t=a("TypeError","type error"),e=a("RangeError","range error")}for(var h="join pop push shift unshift slice filter forEach some every map indexOf lastIndexOf reduce reduceRight sort reverse".split(" "),p=0;p<h.length;++p)"function"==typeof Array.prototype[h[p]]&&(f.prototype[h[p]]=Array.prototype[h[p]]);r.defineProperty(f.prototype,"length",{value:0,configurable:!1,writable:!0,enumerable:!0}),f.prototype.isOperational=!0;var d=0;function y(t){if(!(this instanceof y))return new y(t);s(this,"name","OperationalError"),s(this,"message",t),this.cause=t,this.isOperational=!0,t instanceof Error?(s(this,"message",t.message),s(this,"stack",t.stack)):Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}f.prototype.toString=function(){var t=Array(4*d+1).join(" "),e="\n"+t+"AggregateError of:\n";d++,t=Array(4*d+1).join(" ");for(var r=0;r<this.length;++r){for(var n=this[r]===this?"[Circular AggregateError]":this[r]+"",i=n.split("\n"),o=0;o<i.length;++o)i[o]=t+i[o];e+=(n=i.join("\n"))+"\n"}return d--,e},o(y,Error);var m=Error.__BluebirdErrorTypes__;return m||(m=n({CancellationError:c,TimeoutError:l,OperationalError:y,RejectionError:y,AggregateError:f}),r.defineProperty(Error,"__BluebirdErrorTypes__",{value:m,writable:!1,enumerable:!1,configurable:!1})),td={Error:Error,TypeError:t,RangeError:e,CancellationError:m.CancellationError,OperationalError:m.OperationalError,TimeoutError:m.TimeoutError,AggregateError:m.AggregateError,Warning:u}}function py(){return nd||(nd=1,rd=function(t,e){var r=Qp(),n=r.errorObj,i=r.isObject;var o={}.hasOwnProperty;return function(s,a){if(i(s)){if(s instanceof t)return s;var u=function(t){try{return function(t){return t.then}(t)}catch(t){return n.e=t,n}}(s);if(u===n){a&&a._pushContext();var c=t.reject(u.e);return a&&a._popContext(),c}if("function"==typeof u){if(function(t){try{return o.call(t,"_promise0")}catch(t){return!1}}(s)){c=new t(e);return s._then(c._fulfill,c._reject,void 0,c,null),c}return function(i,o,s){var a=new t(e),u=a;s&&s._pushContext();a._captureStackTrace(),s&&s._popContext();var c=!0,l=r.tryCatch(o).call(i,f,h);c=!1,a&&l===n&&(a._rejectCallback(l.e,!0,!0),a=null);function f(t){a&&(a._resolveCallback(t),a=null)}function h(t){a&&(a._rejectCallback(t,c,!0),a=null)}return u}(s,u,a)}}return s}}),rd}function dy(){return od||(od=1,id=function(t,e,r,n,i){var o=Qp();function s(r){var n=this._promise=new t(e);r instanceof t&&(n._propagateFrom(r,3),r.suppressUnhandledRejections()),n._setOnCancel(this),this._values=r,this._length=0,this._totalResolved=0,this._init(void 0,-2)}return o.isArray,o.inherits(s,i),s.prototype.length=function(){return this._length},s.prototype.promise=function(){return this._promise},s.prototype._init=function e(i,s){var a=r(this._values,this._promise);if(a instanceof t){var u=(a=a._target())._bitField;if(this._values=a,!(50397184&u))return this._promise._setAsyncGuaranteed(),a._then(e,this._reject,void 0,this,s);if(!(33554432&u))return 16777216&u?this._reject(a._reason()):this._cancel();a=a._value()}if(null!==(a=o.asArray(a)))0!==a.length?this._iterate(a):-5===s?this._resolveEmptyArray():this._resolve(function(t){switch(t){case-2:return[];case-3:return{};case-6:return new Map}}(s));else{var c=n("expecting an array or an iterable object but got "+o.classString(a)).reason();this._promise._rejectCallback(c,!1)}},s.prototype._iterate=function(e){var n=this.getActualLength(e.length);this._length=n,this._values=this.shouldCopyValues()?new Array(n):this._values;for(var i=this._promise,o=!1,s=null,a=0;a<n;++a){var u=r(e[a],i);s=u instanceof t?(u=u._target())._bitField:null,o?null!==s&&u.suppressUnhandledRejections():null!==s?50397184&s?o=33554432&s?this._promiseFulfilled(u._value(),a):16777216&s?this._promiseRejected(u._reason(),a):this._promiseCancelled(a):(u._proxy(this,a),this._values[a]=u):o=this._promiseFulfilled(u,a)}o||i._setAsyncGuaranteed()},s.prototype._isResolved=function(){return null===this._values},s.prototype._resolve=function(t){this._values=null,this._promise._fulfill(t)},s.prototype._cancel=function(){!this._isResolved()&&this._promise._isCancellable()&&(this._values=null,this._promise._cancel())},s.prototype._reject=function(t){this._values=null,this._promise._rejectCallback(t,!1)},s.prototype._promiseFulfilled=function(t,e){return this._values[e]=t,++this._totalResolved>=this._length&&(this._resolve(this._values),!0)},s.prototype._promiseCancelled=function(){return this._cancel(),!0},s.prototype._promiseRejected=function(t){return this._totalResolved++,this._reject(t),!0},s.prototype._resultCancelled=function(){if(!this._isResolved()){var e=this._values;if(this._cancel(),e instanceof t)e.cancel();else for(var r=0;r<e.length;++r)e[r]instanceof t&&e[r].cancel()}},s.prototype.shouldCopyValues=function(){return!0},s.prototype.getActualLength=function(t){return t},s}),id}function yy(){return cd||(cd=1,ud=function(t,e,r,n){var i,o,s,a,u=t._async,c=hy().Warning,l=Qp(),f=Vp(),h=l.canAttachTrace,p=/[\\\/]bluebird[\\\/]js[\\\/](release|debug|instrumented)/,d=/\((?:timers\.js):\d+:\d+\)/,y=/[\/<\(](.+?):(\d+):(\d+)\)?\s*$/,m=null,g=null,_=!1,b=!(0==l.env("BLUEBIRD_DEBUG")||!l.env("BLUEBIRD_DEBUG")&&"development"!==l.env("NODE_ENV")),v=!(0==l.env("BLUEBIRD_WARNINGS")||!b&&!l.env("BLUEBIRD_WARNINGS")),w=!(0==l.env("BLUEBIRD_LONG_STACK_TRACES")||!b&&!l.env("BLUEBIRD_LONG_STACK_TRACES")),S=0!=l.env("BLUEBIRD_W_FORGOTTEN_RETURN")&&(v||!!l.env("BLUEBIRD_W_FORGOTTEN_RETURN"));!function(){var e=[];function r(){for(var t=0;t<e.length;++t)e[t]._notifyUnhandledRejection();n()}function n(){e.length=0}a=function(t){e.push(t),setTimeout(r,1)},f.defineProperty(t,"_unhandledRejectionCheck",{value:r}),f.defineProperty(t,"_unhandledRejectionClear",{value:n})}(),t.prototype.suppressUnhandledRejections=function(){var t=this._target();t._bitField=-1048577&t._bitField|524288},t.prototype._ensurePossibleRejectionHandled=function(){524288&this._bitField||(this._setRejectionIsUnhandled(),a(this))},t.prototype._notifyUnhandledRejectionIsHandled=function(){G("rejectionHandled",i,void 0,this)},t.prototype._setReturnedNonUndefined=function(){this._bitField=268435456|this._bitField},t.prototype._returnedNonUndefined=function(){return!!(268435456&this._bitField)},t.prototype._notifyUnhandledRejection=function(){if(this._isRejectionUnhandled()){var t=this._settledValue();this._setUnhandledRejectionIsNotified(),G("unhandledRejection",o,t,this)}},t.prototype._setUnhandledRejectionIsNotified=function(){this._bitField=262144|this._bitField},t.prototype._unsetUnhandledRejectionIsNotified=function(){this._bitField=-262145&this._bitField},t.prototype._isUnhandledRejectionNotified=function(){return(262144&this._bitField)>0},t.prototype._setRejectionIsUnhandled=function(){this._bitField=1048576|this._bitField},t.prototype._unsetRejectionIsUnhandled=function(){this._bitField=-1048577&this._bitField,this._isUnhandledRejectionNotified()&&(this._unsetUnhandledRejectionIsNotified(),this._notifyUnhandledRejectionIsHandled())},t.prototype._isRejectionUnhandled=function(){return(1048576&this._bitField)>0},t.prototype._warn=function(t,e,r){return W(t,e,r||this)},t.onPossiblyUnhandledRejection=function(e){var r=t._getContext();o=l.contextBind(r,e)},t.onUnhandledRejectionHandled=function(e){var r=t._getContext();i=l.contextBind(r,e)};var E=function(){};t.longStackTraces=function(){if(u.haveItemsQueued()&&!tt.longStackTraces)throw new Error("cannot enable long stack traces after promises have been created\n\n See http://goo.gl/MqrFmX\n");if(!tt.longStackTraces&&Q()){var r=t.prototype._captureStackTrace,n=t.prototype._attachExtraTrace,i=t.prototype._dereferenceTrace;tt.longStackTraces=!0,E=function(){if(u.haveItemsQueued()&&!tt.longStackTraces)throw new Error("cannot enable long stack traces after promises have been created\n\n See http://goo.gl/MqrFmX\n");t.prototype._captureStackTrace=r,t.prototype._attachExtraTrace=n,t.prototype._dereferenceTrace=i,e.deactivateLongStackTraces(),tt.longStackTraces=!1},t.prototype._captureStackTrace=B,t.prototype._attachExtraTrace=U,t.prototype._dereferenceTrace=z,e.activateLongStackTraces()}},t.hasLongStackTraces=function(){return tt.longStackTraces&&Q()};var k={unhandledrejection:{before:function(){var t=l.global.onunhandledrejection;return l.global.onunhandledrejection=null,t},after:function(t){l.global.onunhandledrejection=t}},rejectionhandled:{before:function(){var t=l.global.onrejectionhandled;return l.global.onrejectionhandled=null,t},after:function(t){l.global.onrejectionhandled=t}}},x=function(){var t=function(t,e){if(!t)return!l.global.dispatchEvent(e);var r;try{return r=t.before(),!l.global.dispatchEvent(e)}finally{t.after(r)}};try{if("function"==typeof CustomEvent){var e=new CustomEvent("CustomEvent");return l.global.dispatchEvent(e),function(e,r){e=e.toLowerCase();var n=new CustomEvent(e,{detail:r,cancelable:!0});return f.defineProperty(n,"promise",{value:r.promise}),f.defineProperty(n,"reason",{value:r.reason}),t(k[e],n)}}if("function"==typeof Event){e=new Event("CustomEvent");return l.global.dispatchEvent(e),function(e,r){e=e.toLowerCase();var n=new Event(e,{cancelable:!0});return n.detail=r,f.defineProperty(n,"promise",{value:r.promise}),f.defineProperty(n,"reason",{value:r.reason}),t(k[e],n)}}return(e=document.createEvent("CustomEvent")).initCustomEvent("testingtheevent",!1,!0,{}),l.global.dispatchEvent(e),function(e,r){e=e.toLowerCase();var n=document.createEvent("CustomEvent");return n.initCustomEvent(e,!1,!0,r),t(k[e],n)}}catch(t){}return function(){return!1}}(),O=l.isNode?function(){return process.emit.apply(process,arguments)}:l.global?function(t){var e="on"+t.toLowerCase(),r=l.global[e];return!!r&&(r.apply(l.global,[].slice.call(arguments,1)),!0)}:function(){return!1};function T(t,e){return{promise:e}}var j={promiseCreated:T,promiseFulfilled:T,promiseRejected:T,promiseResolved:T,promiseCancelled:T,promiseChained:function(t,e,r){return{promise:e,child:r}},warning:function(t,e){return{warning:e}},unhandledRejection:function(t,e,r){return{reason:e,promise:r}},rejectionHandled:T},C=function(t){var e=!1;try{e=O.apply(null,arguments)}catch(t){u.throwLater(t),e=!0}var r=!1;try{r=x(t,j[t].apply(null,arguments))}catch(t){u.throwLater(t),r=!0}return r||e};function R(){return!1}function P(t,e,r){var n=this;try{t(e,r,function(t){if("function"!=typeof t)throw new TypeError("onCancel must be a function, got: "+l.toString(t));n._attachCancellationCallback(t)})}catch(t){return t}}function L(t){if(!this._isCancellable())return this;var e=this._onCancel();void 0!==e?l.isArray(e)?e.push(t):this._setOnCancel([e,t]):this._setOnCancel(t)}function F(){return this._onCancelField}function A(t){this._onCancelField=t}function I(){this._cancellationParent=void 0,this._onCancelField=void 0}function D(t,e){if(1&e){this._cancellationParent=t;var r=t._branchesRemainingToCancel;void 0===r&&(r=0),t._branchesRemainingToCancel=r+1}2&e&&t._isBound()&&this._setBoundTo(t._boundTo)}t.config=function(e){if("longStackTraces"in(e=Object(e))&&(e.longStackTraces?t.longStackTraces():!e.longStackTraces&&t.hasLongStackTraces()&&E()),"warnings"in e){var i=e.warnings;tt.warnings=!!i,S=tt.warnings,l.isObject(i)&&"wForgottenReturn"in i&&(S=!!i.wForgottenReturn)}if("cancellation"in e&&e.cancellation&&!tt.cancellation){if(u.haveItemsQueued())throw new Error("cannot enable cancellation after promises are in use");t.prototype._clearCancellationData=I,t.prototype._propagateFrom=D,t.prototype._onCancel=F,t.prototype._setOnCancel=A,t.prototype._attachCancellationCallback=L,t.prototype._execute=P,M=D,tt.cancellation=!0}if("monitoring"in e&&(e.monitoring&&!tt.monitoring?(tt.monitoring=!0,t.prototype._fireEvent=C):!e.monitoring&&tt.monitoring&&(tt.monitoring=!1,t.prototype._fireEvent=R)),"asyncHooks"in e&&l.nodeSupportsAsyncResource){var o=tt.asyncHooks,s=!!e.asyncHooks;o!==s&&(tt.asyncHooks=s,s?r():n())}return t},t.prototype._fireEvent=R,t.prototype._execute=function(t,e,r){try{t(e,r)}catch(t){return t}},t.prototype._onCancel=function(){},t.prototype._setOnCancel=function(t){},t.prototype._attachCancellationCallback=function(t){},t.prototype._captureStackTrace=function(){},t.prototype._attachExtraTrace=function(){},t.prototype._dereferenceTrace=function(){},t.prototype._clearCancellationData=function(){},t.prototype._propagateFrom=function(t,e){};var M=function(t,e){2&e&&t._isBound()&&this._setBoundTo(t._boundTo)};function N(){var e=this._boundTo;return void 0!==e&&e instanceof t?e.isFulfilled()?e.value():void 0:e}function B(){this._trace=new Y(this._peekContext())}function U(t,e){if(h(t)){var r=this._trace;if(void 0!==r&&e&&(r=r._parent),void 0!==r)r.attachExtraTrace(t);else if(!t.__stackCleaned__){var n=$(t);l.notEnumerableProp(t,"stack",n.message+"\n"+n.stack.join("\n")),l.notEnumerableProp(t,"__stackCleaned__",!0)}}}function z(){this._trace=void 0}function W(e,r,n){if(tt.warnings){var i,o=new c(e);if(r)n._attachExtraTrace(o);else if(tt.longStackTraces&&(i=t._peekContext()))i.attachExtraTrace(o);else{var s=$(o);o.stack=s.message+"\n"+s.stack.join("\n")}C("warning",o)||q(o,"",!0)}}function H(t){for(var e=[],r=0;r<t.length;++r){var n=t[r],i=" (No stack trace)"===n||m.test(n),o=i&&Z(n);i&&!o&&(_&&" "!==n.charAt(0)&&(n=" "+n),e.push(n))}return e}function $(t){var e=t.stack,r=t.toString();return e="string"==typeof e&&e.length>0?function(t){for(var e=t.stack.replace(/\s+$/g,"").split("\n"),r=0;r<e.length;++r){var n=e[r];if(" (No stack trace)"===n||m.test(n))break}return r>0&&"SyntaxError"!=t.name&&(e=e.slice(r)),e}(t):[" (No stack trace)"],{message:r,stack:"SyntaxError"==t.name?e:H(e)}}function q(t,e,r){if("undefined"!=typeof console){var n;if(l.isObject(t)){var i=t.stack;n=e+g(i,t)}else n=e+String(t);"function"==typeof s?s(n,r):"function"!=typeof console.log&&"object"!=typeof console.log||console.log(n)}}function G(t,e,r,n){var i=!1;try{"function"==typeof e&&(i=!0,"rejectionHandled"===t?e(n):e(r,n))}catch(t){u.throwLater(t)}"unhandledRejection"===t?C(t,r,n)||i||q(r,"Unhandled rejection "):C(t,n)}function V(t){var e;if("function"==typeof t)e="[function "+(t.name||"anonymous")+"]";else{e=t&&"function"==typeof t.toString?t.toString():l.toString(t);if(/\[object [a-zA-Z0-9$_]+\]/.test(e))try{e=JSON.stringify(t)}catch(t){}0===e.length&&(e="(empty array)")}return"(<"+function(t){var e=41;if(t.length<e)return t;return t.substr(0,e-3)+"..."}(e)+">, no stack trace)"}function Q(){return"function"==typeof X}var Z=function(){return!1},K=/[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/;function J(t){var e=t.match(K);if(e)return{fileName:e[1],line:parseInt(e[2],10)}}function Y(t){this._parent=t,this._promisesCreated=0;var e=this._length=1+(void 0===t?0:t._length);X(this,Y),e>32&&this.uncycle()}l.inherits(Y,Error),e.CapturedTrace=Y,Y.prototype.uncycle=function(){var t=this._length;if(!(t<2)){for(var e=[],r={},n=0,i=this;void 0!==i;++n)e.push(i),i=i._parent;for(n=(t=this._length=n)-1;n>=0;--n){var o=e[n].stack;void 0===r[o]&&(r[o]=n)}for(n=0;n<t;++n){var s=r[e[n].stack];if(void 0!==s&&s!==n){s>0&&(e[s-1]._parent=void 0,e[s-1]._length=1),e[n]._parent=void 0,e[n]._length=1;var a=n>0?e[n-1]:this;s<t-1?(a._parent=e[s+1],a._parent.uncycle(),a._length=a._parent._length+1):(a._parent=void 0,a._length=1);for(var u=a._length+1,c=n-2;c>=0;--c)e[c]._length=u,u++;return}}}},Y.prototype.attachExtraTrace=function(t){if(!t.__stackCleaned__){this.uncycle();for(var e=$(t),r=e.message,n=[e.stack],i=this;void 0!==i;)n.push(H(i.stack.split("\n"))),i=i._parent;!function(t){for(var e=t[0],r=1;r<t.length;++r){for(var n=t[r],i=e.length-1,o=e[i],s=-1,a=n.length-1;a>=0;--a)if(n[a]===o){s=a;break}for(a=s;a>=0;--a){var u=n[a];if(e[i]!==u)break;e.pop(),i--}e=n}}(n),function(t){for(var e=0;e<t.length;++e)(0===t[e].length||e+1<t.length&&t[e][0]===t[e+1][0])&&(t.splice(e,1),e--)}(n),l.notEnumerableProp(t,"stack",function(t,e){for(var r=0;r<e.length-1;++r)e[r].push("From previous event:"),e[r]=e[r].join("\n");return r<e.length&&(e[r]=e[r].join("\n")),t+"\n"+e.join("\n")}(r,n)),l.notEnumerableProp(t,"__stackCleaned__",!0)}};var X=function(){var t=/^\s*at\s*/,e=function(t,e){return"string"==typeof t?t:void 0!==e.name&&void 0!==e.message?e.toString():V(e)};if("number"==typeof Error.stackTraceLimit&&"function"==typeof Error.captureStackTrace){Error.stackTraceLimit+=6,m=t,g=e;var r=Error.captureStackTrace;return Z=function(t){return p.test(t)},function(t,e){Error.stackTraceLimit+=6,r(t,e),Error.stackTraceLimit-=6}}var n,i=new Error;if("string"==typeof i.stack&&i.stack.split("\n")[0].indexOf("stackDetection@")>=0)return m=/@/,g=e,_=!0,function(t){t.stack=(new Error).stack};try{throw new Error}catch(t){n="stack"in t}return!("stack"in i)&&n&&"number"==typeof Error.stackTraceLimit?(m=t,g=e,function(t){Error.stackTraceLimit+=6;try{throw new Error}catch(e){t.stack=e.stack}Error.stackTraceLimit-=6}):(g=function(t,e){return"string"==typeof t?t:"object"!=typeof e&&"function"!=typeof e||void 0===e.name||void 0===e.message?V(e):e.toString()},null)}();"undefined"!=typeof console&&void 0!==console.warn&&(s=function(t){console.warn(t)},l.isNode&&process.stderr.isTTY?s=function(t,e){var r=e?"[33m":"[31m";console.warn(r+t+"[0m\n")}:l.isNode||"string"!=typeof(new Error).stack||(s=function(t,e){console.warn("%c"+t,e?"color: darkorange":"color: red")}));var tt={warnings:v,longStackTraces:!1,cancellation:!1,monitoring:!1,asyncHooks:!1};return w&&t.longStackTraces(),{asyncHooks:function(){return tt.asyncHooks},longStackTraces:function(){return tt.longStackTraces},warnings:function(){return tt.warnings},cancellation:function(){return tt.cancellation},monitoring:function(){return tt.monitoring},propagateFromFunction:function(){return M},boundValueFunction:function(){return N},checkForgottenReturns:function(t,e,r,n,i){if(void 0===t&&null!==e&&S){if(void 0!==i&&i._returnedNonUndefined())return;if(!(65535&n._bitField))return;r&&(r+=" ");var o="",s="";if(e._trace){for(var a=e._trace.stack.split("\n"),u=H(a),c=u.length-1;c>=0;--c){var l=u[c];if(!d.test(l)){var f=l.match(y);f&&(o="at "+f[1]+":"+f[2]+":"+f[3]+" ");break}}if(u.length>0){var h=u[0];for(c=0;c<a.length;++c)if(a[c]===h){c>0&&(s="\n"+a[c-1]);break}}}var p="a promise was created in a "+r+"handler "+o+"but was not returned from it, see http://goo.gl/rRqMUw"+s;n._warn(p,!0,e)}},setBounds:function(t,e){if(Q()){for(var r,n,i=(t.stack||"").split("\n"),o=(e.stack||"").split("\n"),s=-1,a=-1,u=0;u<i.length;++u){if(c=J(i[u])){r=c.fileName,s=c.line;break}}for(u=0;u<o.length;++u){var c;if(c=J(o[u])){n=c.fileName,a=c.line;break}}s<0||a<0||!r||!n||r!==n||s>=a||(Z=function(t){if(p.test(t))return!0;var e=J(t);return!!(e&&e.fileName===r&&s<=e.line&&e.line<=a)})}},warn:W,deprecated:function(t,e){var r=t+" is deprecated and will be removed in a future version.";return e&&(r+=" Use "+e+" instead."),W(r)},CapturedTrace:Y,fireDomEvent:x,fireGlobalEvent:O}}),ud}function my(){return fd||(fd=1,ld=function(t){var e=Qp(),r=Vp().keys,n=e.tryCatch,i=e.errorObj;return function(o,s,a){return function(u){var c=a._boundValue();t:for(var l=0;l<o.length;++l){var f=o[l];if(f===Error||null!=f&&f.prototype instanceof Error){if(u instanceof f)return n(s).call(c,u)}else if("function"==typeof f){var h=n(f).call(c,u);if(h===i)return h;if(h)return n(s).call(c,u)}else if(e.isObject(u)){for(var p=r(f),d=0;d<p.length;++d){var y=p[d];if(f[y]!=u[y])continue t}return n(s).call(c,u)}}return t}}}),ld}function gy(){return pd||(pd=1,hd=function(t,e,r){var n=Qp(),i=t.CancellationError,o=n.errorObj,s=my()(r);function a(t,e,r){this.promise=t,this.type=e,this.handler=r,this.called=!1,this.cancelPromise=null}function u(t){this.finallyHandler=t}function c(t,e){return null!=t.cancelPromise&&(arguments.length>1?t.cancelPromise._reject(e):t.cancelPromise._cancel(),t.cancelPromise=null,!0)}function l(){return h.call(this,this.promise._target()._settledValue())}function f(t){if(!c(this,t))return o.e=t,o}function h(n){var s=this.promise,a=this.handler;if(!this.called){this.called=!0;var h=this.isFinallyHandler()?a.call(s._boundValue()):a.call(s._boundValue(),n);if(h===r)return h;if(void 0!==h){s._setReturnedNonUndefined();var p=e(h,s);if(p instanceof t){if(null!=this.cancelPromise){if(p._isCancelled()){var d=new i("late cancellation observer");return s._attachExtraTrace(d),o.e=d,o}p.isPending()&&p._attachCancellationCallback(new u(this))}return p._then(l,f,void 0,this,void 0)}}}return s.isRejected()?(c(this),o.e=n,o):(c(this),n)}return a.prototype.isFinallyHandler=function(){return 0===this.type},u.prototype._resultCancelled=function(){c(this.finallyHandler)},t.prototype._passThrough=function(t,e,r,n){return"function"!=typeof t?this.then():this._then(r,n,void 0,new a(this,e,t),void 0)},t.prototype.lastly=t.prototype.finally=function(t){return this._passThrough(t,0,h,h)},t.prototype.tap=function(t){return this._passThrough(t,1,h)},t.prototype.tapCatch=function(e){var r=arguments.length;if(1===r)return this._passThrough(e,1,void 0,h);var i,o=new Array(r-1),a=0;for(i=0;i<r-1;++i){var u=arguments[i];if(!n.isObject(u))return t.reject(new TypeError("tapCatch statement predicate: expecting an object but got "+n.classString(u)));o[a++]=u}o.length=a;var c=arguments[i];return this._passThrough(s(o,c,this),1,void 0,h)},a}),hd}function _y(){if(yd)return dd;yd=1;var t=Qp(),e=t.maybeWrapAsError,r=hy().OperationalError,n=Vp();var i=/^(?:name|message|stack|cause)$/;function o(e){var o;if(function(t){return t instanceof Error&&n.getPrototypeOf(t)===Error.prototype}(e)){(o=new r(e)).name=e.name,o.message=e.message,o.stack=e.stack;for(var s=n.keys(e),a=0;a<s.length;++a){var u=s[a];i.test(u)||(o[u]=e[u])}return o}return t.markAsOriginatingFromRejection(e),e}return dd=function(t,r){return function(n,i){if(null!==t){if(n){var s=o(e(n));t._attachExtraTrace(s),t._reject(s)}else if(r){for(var a=arguments.length,u=new Array(Math.max(a-1,0)),c=1;c<a;++c)u[c-1]=arguments[c];t._fulfill(u)}else t._fulfill(i);t=null}}},dd}function by(){return xd||(xd=1,kd=function(t){function e(t){void 0!==t?(t=t._target(),this._bitField=t._bitField,this._settledValueField=t._isFateSealed()?t._settledValue():void 0):(this._bitField=0,this._settledValueField=void 0)}e.prototype._settledValue=function(){return this._settledValueField};var r=e.prototype.value=function(){if(!this.isFulfilled())throw new TypeError("cannot get fulfillment value of a non-fulfilled promise\n\n See http://goo.gl/MqrFmX\n");return this._settledValue()},n=e.prototype.error=e.prototype.reason=function(){if(!this.isRejected())throw new TypeError("cannot get rejection reason of a non-rejected promise\n\n See http://goo.gl/MqrFmX\n");return this._settledValue()},i=e.prototype.isFulfilled=function(){return!!(33554432&this._bitField)},o=e.prototype.isRejected=function(){return!!(16777216&this._bitField)},s=e.prototype.isPending=function(){return!(50397184&this._bitField)},a=e.prototype.isResolved=function(){return!!(50331648&this._bitField)};e.prototype.isCancelled=function(){return!!(8454144&this._bitField)},t.prototype.__isCancelled=function(){return!(65536&~this._bitField)},t.prototype._isCancelled=function(){return this._target().__isCancelled()},t.prototype.isCancelled=function(){return!!(8454144&this._target()._bitField)},t.prototype.isPending=function(){return s.call(this._target())},t.prototype.isRejected=function(){return o.call(this._target())},t.prototype.isFulfilled=function(){return i.call(this._target())},t.prototype.isResolved=function(){return a.call(this._target())},t.prototype.value=function(){return r.call(this._target())},t.prototype.reason=function(){var t=this._target();return t._unsetRejectionIsUnhandled(),n.call(t)},t.prototype._value=function(){return this._settledValue()},t.prototype._reason=function(){return this._unsetRejectionIsUnhandled(),this._settledValue()},t.PromiseInspection=e}),kd}function vy(){return Pd||(Pd=1,Rd=function(t,e,r,n,i,o){var s=hy().TypeError,a=Qp(),u=a.errorObj,c=a.tryCatch,l=[];function f(e,n,i,s){if(o.cancellation()){var a=new t(r),u=this._finallyPromise=new t(r);this._promise=a.lastly(function(){return u}),a._captureStackTrace(),a._setOnCancel(this)}else{(this._promise=new t(r))._captureStackTrace()}this._stack=s,this._generatorFunction=e,this._receiver=n,this._generator=void 0,this._yieldHandlers="function"==typeof i?[i].concat(l):l,this._yieldedPromise=null,this._cancellationPhase=!1}a.inherits(f,i),f.prototype._isResolved=function(){return null===this._promise},f.prototype._cleanup=function(){this._promise=this._generator=null,o.cancellation()&&null!==this._finallyPromise&&(this._finallyPromise._fulfill(),this._finallyPromise=null)},f.prototype._promiseCancelled=function(){if(!this._isResolved()){var e;if(void 0!==this._generator.return)this._promise._pushContext(),e=c(this._generator.return).call(this._generator,void 0),this._promise._popContext();else{var r=new t.CancellationError("generator .return() sentinel");t.coroutine.returnSentinel=r,this._promise._attachExtraTrace(r),this._promise._pushContext(),e=c(this._generator.throw).call(this._generator,r),this._promise._popContext()}this._cancellationPhase=!0,this._yieldedPromise=null,this._continue(e)}},f.prototype._promiseFulfilled=function(t){this._yieldedPromise=null,this._promise._pushContext();var e=c(this._generator.next).call(this._generator,t);this._promise._popContext(),this._continue(e)},f.prototype._promiseRejected=function(t){this._yieldedPromise=null,this._promise._attachExtraTrace(t),this._promise._pushContext();var e=c(this._generator.throw).call(this._generator,t);this._promise._popContext(),this._continue(e)},f.prototype._resultCancelled=function(){if(this._yieldedPromise instanceof t){var e=this._yieldedPromise;this._yieldedPromise=null,e.cancel()}},f.prototype.promise=function(){return this._promise},f.prototype._run=function(){this._generator=this._generatorFunction.call(this._receiver),this._receiver=this._generatorFunction=void 0,this._promiseFulfilled(void 0)},f.prototype._continue=function(e){var r=this._promise;if(e===u)return this._cleanup(),this._cancellationPhase?r.cancel():r._rejectCallback(e.e,!1);var i=e.value;if(!0===e.done)return this._cleanup(),this._cancellationPhase?r.cancel():r._resolveCallback(i);var o=n(i,this._promise);if(o instanceof t||(o=function(e,r,i){for(var o=0;o<r.length;++o){i._pushContext();var s=c(r[o])(e);if(i._popContext(),s===u){i._pushContext();var a=t.reject(u.e);return i._popContext(),a}var l=n(s,i);if(l instanceof t)return l}return null}(o,this._yieldHandlers,this._promise),null!==o)){var a=(o=o._target())._bitField;50397184&a?33554432&a?t._async.invoke(this._promiseFulfilled,this,o._value()):16777216&a?t._async.invoke(this._promiseRejected,this,o._reason()):this._promiseCancelled():(this._yieldedPromise=o,o._proxy(this,null))}else this._promiseRejected(new s("A value %s was yielded that could not be treated as a promise\n\n See http://goo.gl/MqrFmX\n\n".replace("%s",String(i))+"From coroutine:\n"+this._stack.split("\n").slice(1,-7).join("\n")))},t.coroutine=function(t,e){if("function"!=typeof t)throw new s("generatorFunction must be a function\n\n See http://goo.gl/MqrFmX\n");var r=Object(e).yieldHandler,n=f,i=(new Error).stack;return function(){var e=t.apply(this,arguments),o=new n(void 0,void 0,r,i),s=o.promise();return o._generator=e,o._promiseFulfilled(void 0),s}},t.coroutine.addYieldHandler=function(t){if("function"!=typeof t)throw new s("expecting a function but got "+a.classString(t));l.push(t)},t.spawn=function(r){if(o.deprecated("Promise.spawn()","Promise.coroutine()"),"function"!=typeof r)return e("generatorFunction must be a function\n\n See http://goo.gl/MqrFmX\n");var n=new f(r,this),i=n.promise();return n._run(t.spawn),i}}),Rd}function wy(){return Fd||(Fd=1,Ld=function(t,e,r,n,i,o){var s=Qp(),a=s.tryCatch,u=s.errorObj,c=t._async;function l(e,r,n,o){this.constructor$(e),this._promise._captureStackTrace();var a=t._getContext();if(this._callback=s.contextBind(a,r),this._preservedValues=o===i?new Array(this.length()):null,this._limit=n,this._inFlight=0,this._queue=[],c.invoke(this._asyncInit,this,void 0),s.isArray(e))for(var u=0;u<e.length;++u){var l=e[u];l instanceof t&&l.suppressUnhandledRejections()}}function f(e,n,i,o){if("function"!=typeof n)return r("expecting a function but got "+s.classString(n));var a=0;if(void 0!==i){if("object"!=typeof i||null===i)return t.reject(new TypeError("options argument must be an object but it is "+s.classString(i)));if("number"!=typeof i.concurrency)return t.reject(new TypeError("'concurrency' must be a number but it is "+s.classString(i.concurrency)));a=i.concurrency}return new l(e,n,a="number"==typeof a&&isFinite(a)&&a>=1?a:0,o).promise()}s.inherits(l,e),l.prototype._asyncInit=function(){this._init$(void 0,-2)},l.prototype._init=function(){},l.prototype._promiseFulfilled=function(e,r){var i=this._values,s=this.length(),c=this._preservedValues,l=this._limit;if(r<0){if(i[r=-1*r-1]=e,l>=1&&(this._inFlight--,this._drainQueue(),this._isResolved()))return!0}else{if(l>=1&&this._inFlight>=l)return i[r]=e,this._queue.push(r),!1;null!==c&&(c[r]=e);var f=this._promise,h=this._callback,p=f._boundValue();f._pushContext();var d=a(h).call(p,e,r,s),y=f._popContext();if(o.checkForgottenReturns(d,y,null!==c?"Promise.filter":"Promise.map",f),d===u)return this._reject(d.e),!0;var m=n(d,this._promise);if(m instanceof t){var g=(m=m._target())._bitField;if(!(50397184&g))return l>=1&&this._inFlight++,i[r]=m,m._proxy(this,-1*(r+1)),!1;if(!(33554432&g))return 16777216&g?(this._reject(m._reason()),!0):(this._cancel(),!0);d=m._value()}i[r]=d}return++this._totalResolved>=s&&(null!==c?this._filter(i,c):this._resolve(i),!0)},l.prototype._drainQueue=function(){for(var t=this._queue,e=this._limit,r=this._values;t.length>0&&this._inFlight<e;){if(this._isResolved())return;var n=t.pop();this._promiseFulfilled(r[n],n)}},l.prototype._filter=function(t,e){for(var r=e.length,n=new Array(r),i=0,o=0;o<r;++o)t[o]&&(n[i++]=e[o]);n.length=i,this._resolve(n)},l.prototype.preservedValues=function(){return this._preservedValues},t.prototype.map=function(t,e){return f(this,t,e,null)},t.map=function(t,e,r,n){return f(t,e,r,n)}}),Ld}function Sy(){return Md||(Md=1,Dd=function(t,e){var r={},n=Qp(),i=_y(),o=n.withAppended,s=n.maybeWrapAsError,a=n.canEvaluate,u=hy().TypeError,c={__isPromisified__:!0},l=new RegExp("^(?:"+["arity","length","name","arguments","caller","callee","prototype","__isPromisified__"].join("|")+")$"),f=function(t){return n.isIdentifier(t)&&"_"!==t.charAt(0)&&"constructor"!==t};function h(t){return!l.test(t)}function p(t){try{return!0===t.__isPromisified__}catch(t){return!1}}function d(t,e,r){var i=n.getDataPropertyOrDefault(t,e+r,c);return!!i&&p(i)}function y(t,e,r,i){for(var o=n.inheritedDataKeys(t),s=[],a=0;a<o.length;++a){var c=o[a],l=t[c],h=i===f||f(c);"function"!=typeof l||p(l)||d(t,c,e)||!i(c,l,t,h)||s.push(c,l)}return function(t,e,r){for(var n=0;n<t.length;n+=2){var i=t[n];if(r.test(i))for(var o=i.replace(r,""),s=0;s<t.length;s+=2)if(t[s]===o)throw new u("Cannot promisify an API that has normal methods with '%s'-suffix\n\n See http://goo.gl/MqrFmX\n".replace("%s",e))}}(s,e,r),s}var m;m=function(a,u,c,l,f,h){var p=Math.max(0,function(t){return"number"==typeof t.length?Math.max(Math.min(t.length,1024),0):0}(l)-1),d=function(t){for(var e=[t],r=Math.max(0,t-1-3),n=t-1;n>=r;--n)e.push(n);for(n=t+1;n<=3;++n)e.push(n);return e}(p),y="string"==typeof a||u===r;function m(t){var e,r=(e=t,n.filledRange(e,"_arg","")).join(", "),i=t>0?", ":"";return(y?"ret = callback.call(this, {{args}}, nodeback); break;\n":void 0===u?"ret = callback({{args}}, nodeback); break;\n":"ret = callback.call(receiver, {{args}}, nodeback); break;\n").replace("{{args}}",r).replace(", ",i)}var g="string"==typeof a?"this != null ? this['"+a+"'] : fn":"fn",_="'use strict'; \n\t var ret = function (Parameters) { \n\t 'use strict'; \n\t var len = arguments.length; \n\t var promise = new Promise(INTERNAL); \n\t promise._captureStackTrace(); \n\t var nodeback = nodebackForPromise(promise, "+h+"); \n\t var ret; \n\t var callback = tryCatch([GetFunctionCode]); \n\t switch(len) { \n\t [CodeForSwitchCase] \n\t } \n\t if (ret === errorObj) { \n\t promise._rejectCallback(maybeWrapAsError(ret.e), true, true);\n\t } \n\t if (!promise._isFateSealed()) promise._setAsyncGuaranteed(); \n\t return promise; \n\t }; \n\t notEnumerableProp(ret, '__isPromisified__', true); \n\t return ret; \n\t ".replace("[CodeForSwitchCase]",function(){for(var t="",e=0;e<d.length;++e)t+="case "+d[e]+":"+m(d[e]);return t+=" \n\t default: \n\t var args = new Array(len + 1); \n\t var i = 0; \n\t for (var i = 0; i < len; ++i) { \n\t args[i] = arguments[i]; \n\t } \n\t args[i] = nodeback; \n\t [CodeForCall] \n\t break; \n\t ".replace("[CodeForCall]",y?"ret = callback.apply(this, args);\n":"ret = callback.apply(receiver, args);\n")}()).replace("[GetFunctionCode]",g);return _=_.replace("Parameters",function(t){return n.filledRange(Math.max(t,3),"_arg","")}(p)),new Function("Promise","fn","receiver","withAppended","maybeWrapAsError","nodebackForPromise","tryCatch","errorObj","notEnumerableProp","INTERNAL",_)(t,l,u,o,s,i,n.tryCatch,n.errorObj,n.notEnumerableProp,e)};var g=a?m:function(a,u,c,l,f,h){var p=function(){return this}(),d=a;function y(){var n=u;u===r&&(n=this);var c=new t(e);c._captureStackTrace();var l="string"==typeof d&&this!==p?this[d]:a,f=i(c,h);try{l.apply(n,o(arguments,f))}catch(t){c._rejectCallback(s(t),!0,!0)}return c._isFateSealed()||c._setAsyncGuaranteed(),c}return"string"==typeof d&&(a=l),n.notEnumerableProp(y,"__isPromisified__",!0),y};function _(t,e,i,o,s){for(var a=new RegExp(e.replace(/([$])/,"\\$")+"$"),u=y(t,e,a,i),c=0,l=u.length;c<l;c+=2){var f=u[c],h=u[c+1],p=f+e;if(o===g)t[p]=g(f,r,f,h,e,s);else{var d=o(h,function(){return g(f,r,f,h,e,s)});n.notEnumerableProp(d,"__isPromisified__",!0),t[p]=d}}return n.toFastProperties(t),t}t.promisify=function(t,e){if("function"!=typeof t)throw new u("expecting a function but got "+n.classString(t));if(p(t))return t;var i=function(t,e,r){return g(t,e,void 0,t,null,r)}(t,void 0===(e=Object(e)).context?r:e.context,!!e.multiArgs);return n.copyDescriptors(t,i,h),i},t.promisifyAll=function(t,e){if("function"!=typeof t&&"object"!=typeof t)throw new u("the target of promisifyAll must be an object or a function\n\n See http://goo.gl/MqrFmX\n");var r=!!(e=Object(e)).multiArgs,i=e.suffix;"string"!=typeof i&&(i="Async");var o=e.filter;"function"!=typeof o&&(o=f);var s=e.promisifier;if("function"!=typeof s&&(s=g),!n.isIdentifier(i))throw new RangeError("suffix must be a valid identifier\n\n See http://goo.gl/MqrFmX\n");for(var a=n.inheritedDataKeys(t),c=0;c<a.length;++c){var l=t[a[c]];"constructor"!==a[c]&&n.isClass(l)&&(_(l.prototype,i,o,s,r),_(l,i,o,s,r))}return _(t,i,o,s,r)}}),Dd}function Ey(){return Bd||(Bd=1,Nd=function(t,e,r,n){var i,o=Qp(),s=o.isObject,a=Vp();"function"==typeof Map&&(i=Map);var u=function(){var t=0,e=0;function r(r,n){this[t]=r,this[t+e]=n,t++}return function(n){e=n.size,t=0;var i=new Array(2*n.size);return n.forEach(r,i),i}}();function c(t){var e,r=!1;if(void 0!==i&&t instanceof i)e=u(t),r=!0;else{var n=a.keys(t),o=n.length;e=new Array(2*o);for(var s=0;s<o;++s){var c=n[s];e[s]=t[c],e[s+o]=c}}this.constructor$(e),this._isMap=r,this._init$(void 0,r?-6:-3)}function l(e){var i,o=r(e);return s(o)?(i=o instanceof t?o._then(t.props,void 0,void 0,void 0,void 0):new c(o).promise(),o instanceof t&&i._propagateFrom(o,2),i):n("cannot await properties of a non-object\n\n See http://goo.gl/MqrFmX\n")}o.inherits(c,e),c.prototype._init=function(){},c.prototype._promiseFulfilled=function(t,e){if(this._values[e]=t,++this._totalResolved>=this._length){var r;if(this._isMap)r=function(t){for(var e=new i,r=t.length/2|0,n=0;n<r;++n){var o=t[r+n],s=t[n];e.set(o,s)}return e}(this._values);else{r={};for(var n=this.length(),o=0,s=this.length();o<s;++o)r[this._values[o+n]]=this._values[o]}return this._resolve(r),!0}return!1},c.prototype.shouldCopyValues=function(){return!1},c.prototype.getActualLength=function(t){return t>>1},t.prototype.props=function(){return l(this)},t.props=function(t){return l(t)}}),Nd}function ky(){return zd||(zd=1,Ud=function(t,e,r,n){var i=Qp();function o(s,a){var u=r(s);if(u instanceof t)return function(t){return t.then(function(e){return o(e,t)})}(u);if(null===(s=i.asArray(s)))return n("expecting an array or an iterable object but got "+i.classString(s));var c=new t(e);void 0!==a&&c._propagateFrom(a,3);for(var l=c._fulfill,f=c._reject,h=0,p=s.length;h<p;++h){var d=s[h];(void 0!==d||h in s)&&t.cast(d)._then(l,f,void 0,c,null)}return c}t.race=function(t){return o(t,void 0)},t.prototype.race=function(){return o(this,void 0)}}),Ud}function xy(){return Zd||(Zd=1,Qd=function(t,e,r){var n=Qp(),i=t.TimeoutError;function o(t){this.handle=t}o.prototype._resultCancelled=function(){clearTimeout(this.handle)};var s=function(t){return a(+this).thenReturn(t)},a=t.delay=function(n,i){var a,u;return void 0!==i?(a=t.resolve(i)._then(s,null,null,n,void 0),r.cancellation()&&i instanceof t&&a._setOnCancel(i)):(a=new t(e),u=setTimeout(function(){a._fulfill()},+n),r.cancellation()&&a._setOnCancel(new o(u)),a._captureStackTrace()),a._setAsyncGuaranteed(),a};t.prototype.delay=function(t){return a(t,this)};function u(t){return clearTimeout(this.handle),t}function c(t){throw clearTimeout(this.handle),t}t.prototype.timeout=function(t,e){var s,a;t=+t;var l=new o(setTimeout(function(){s.isPending()&&function(t,e,r){var o;o="string"!=typeof e?e instanceof Error?e:new i("operation timed out"):new i(e),n.markAsOriginatingFromRejection(o),t._attachExtraTrace(o),t._reject(o),null!=r&&r.cancel()}(s,e,a)},t));return r.cancellation()?(a=this.then(),(s=a._then(u,c,void 0,l,void 0))._setOnCancel(l)):s=this._then(u,c,void 0,l,void 0),s}}),Qd}function Oy(){return Jd||(Jd=1,Kd=function(t,e,r,n,i,o){var s=Qp(),a=hy().TypeError,u=Qp().inherits,c=s.errorObj,l=s.tryCatch,f={};function h(t){setTimeout(function(){throw t},0)}function p(e,n){var o=0,s=e.length,a=new t(i);return function i(){if(o>=s)return a._fulfill();var u=function(t){var e=r(t);return e!==t&&"function"==typeof t._isDisposable&&"function"==typeof t._getDisposer&&t._isDisposable()&&e._setDisposable(t._getDisposer()),e}(e[o++]);if(u instanceof t&&u._isDisposable()){try{u=r(u._getDisposer().tryDispose(n),e.promise)}catch(t){return h(t)}if(u instanceof t)return u._then(i,h,null,null,null)}i()}(),a}function d(t,e,r){this._data=t,this._promise=e,this._context=r}function y(t,e,r){this.constructor$(t,e,r)}function m(t){return d.isDisposer(t)?(this.resources[this.index]._setDisposable(t),t.promise()):t}function g(t){this.length=t,this.promise=null,this[t-1]=null}d.prototype.data=function(){return this._data},d.prototype.promise=function(){return this._promise},d.prototype.resource=function(){return this.promise().isFulfilled()?this.promise().value():f},d.prototype.tryDispose=function(t){var e=this.resource(),r=this._context;void 0!==r&&r._pushContext();var n=e!==f?this.doDispose(e,t):null;return void 0!==r&&r._popContext(),this._promise._unsetDisposable(),this._data=null,n},d.isDisposer=function(t){return null!=t&&"function"==typeof t.resource&&"function"==typeof t.tryDispose},u(y,d),y.prototype.doDispose=function(t,e){return this.data().call(t,t,e)},g.prototype._resultCancelled=function(){for(var e=this.length,r=0;r<e;++r){var n=this[r];n instanceof t&&n.cancel()}},t.using=function(){var n=arguments.length;if(n<2)return e("you must pass at least 2 arguments to Promise.using");var i,a=arguments[n-1];if("function"!=typeof a)return e("expecting a function but got "+s.classString(a));var u=!0;2===n&&Array.isArray(arguments[0])?(n=(i=arguments[0]).length,u=!1):(i=arguments,n--);for(var f=new g(n),h=0;h<n;++h){var y=i[h];if(d.isDisposer(y)){var _=y;(y=y.promise())._setDisposable(_)}else{var b=r(y);b instanceof t&&(y=b._then(m,null,null,{resources:f,index:h},void 0))}f[h]=y}var v=new Array(f.length);for(h=0;h<v.length;++h)v[h]=t.resolve(f[h]).reflect();var w=t.all(v).then(function(t){for(var e=0;e<t.length;++e){var r=t[e];if(r.isRejected())return c.e=r.error(),c;if(!r.isFulfilled())return void w.cancel();t[e]=r.value()}S._pushContext(),a=l(a);var n=u?a.apply(void 0,t):a(t),i=S._popContext();return o.checkForgottenReturns(n,i,"Promise.using",S),n}),S=w.lastly(function(){var e=new t.PromiseInspection(w);return p(f,e)});return f.promise=S,S._setOnCancel(f),S},t.prototype._setDisposable=function(t){this._bitField=131072|this._bitField,this._disposer=t},t.prototype._isDisposable=function(){return(131072&this._bitField)>0},t.prototype._getDisposer=function(){return this._disposer},t.prototype._unsetDisposable=function(){this._bitField=-131073&this._bitField,this._disposer=void 0},t.prototype.disposer=function(t){if("function"==typeof t)return new y(t,this,n());throw new a}}),Kd}function Ty(){return iy||(iy=1,(t=qp).exports=function(){var e=function(){return new m("circular promise resolution chain\n\n See http://goo.gl/MqrFmX\n")},r=function(){return new L.PromiseInspection(this._target())},n=function(t){return L.reject(new m(t))};function i(){}var o={},s=Qp();s.setReflectHandler(r);var a=function(){var t=process.domain;return void 0===t?null:t},u=function(){return{domain:a(),async:null}},c=s.isNode&&s.nodeSupportsAsyncResource?E.AsyncResource:null,l=function(){return{domain:a(),async:new c("Bluebird::Promise")}},f=s.isNode?u:function(){return null};s.notEnumerableProp(L,"_getContext",f);var h=Vp(),p=fy(),d=new p;h.defineProperty(L,"_async",{value:d});var y=hy(),m=L.TypeError=y.TypeError;L.RangeError=y.RangeError;var g=L.CancellationError=y.CancellationError;L.TimeoutError=y.TimeoutError,L.OperationalError=y.OperationalError,L.RejectionError=y.OperationalError,L.AggregateError=y.AggregateError;var _=function(){},b={},v={},w=py()(L,_),S=dy()(L,_,w,n,i),k=(ad?sd:(ad=1,sd=function(t){var e=!1,r=[];function n(){this._trace=new n.CapturedTrace(i())}function i(){var t=r.length-1;if(t>=0)return r[t]}return t.prototype._promiseCreated=function(){},t.prototype._pushContext=function(){},t.prototype._popContext=function(){return null},t._peekContext=t.prototype._peekContext=function(){},n.prototype._pushContext=function(){void 0!==this._trace&&(this._trace._promiseCreated=null,r.push(this._trace))},n.prototype._popContext=function(){if(void 0!==this._trace){var t=r.pop(),e=t._promiseCreated;return t._promiseCreated=null,e}return null},n.CapturedTrace=null,n.create=function(){if(e)return new n},n.deactivateLongStackTraces=function(){},n.activateLongStackTraces=function(){var r=t.prototype._pushContext,o=t.prototype._popContext,s=t._peekContext,a=t.prototype._peekContext,u=t.prototype._promiseCreated;n.deactivateLongStackTraces=function(){t.prototype._pushContext=r,t.prototype._popContext=o,t._peekContext=s,t.prototype._peekContext=a,t.prototype._promiseCreated=u,e=!1},e=!0,t.prototype._pushContext=n.prototype._pushContext,t.prototype._popContext=n.prototype._popContext,t._peekContext=t.prototype._peekContext=i,t.prototype._promiseCreated=function(){var t=this._peekContext();t&&null==t._promiseCreated&&(t._promiseCreated=this)}},n}))(L),x=k.create,O=yy()(L,k,function(){f=l,s.notEnumerableProp(L,"_getContext",l)},function(){f=u,s.notEnumerableProp(L,"_getContext",u)});O.CapturedTrace;var T=gy()(L,w,v),j=my()(v),C=_y(),R=s.errorObj,P=s.tryCatch;function L(t){t!==_&&function(t,e){if(null==t||t.constructor!==L)throw new m("the promise constructor cannot be invoked directly\n\n See http://goo.gl/MqrFmX\n");if("function"!=typeof e)throw new m("expecting a function but got "+s.classString(e))}(this,t),this._bitField=0,this._fulfillmentHandler0=void 0,this._rejectionHandler0=void 0,this._promise0=void 0,this._receiver0=void 0,this._resolveFromExecutor(t),this._promiseCreated(),this._fireEvent("promiseCreated",this)}function F(t){this.promise._resolveCallback(t)}function A(t){this.promise._rejectCallback(t,!1)}function I(t){var e=new L(_);e._fulfillmentHandler0=t,e._rejectionHandler0=t,e._promise0=t,e._receiver0=t}return L.prototype.toString=function(){return"[object Promise]"},L.prototype.caught=L.prototype.catch=function(t){var e=arguments.length;if(e>1){var r,i=new Array(e-1),o=0;for(r=0;r<e-1;++r){var a=arguments[r];if(!s.isObject(a))return n("Catch statement predicate: expecting an object but got "+s.classString(a));i[o++]=a}if(i.length=o,"function"!=typeof(t=arguments[r]))throw new m("The last argument to .catch() must be a function, got "+s.toString(t));return this.then(void 0,j(i,t,this))}return this.then(void 0,t)},L.prototype.reflect=function(){return this._then(r,r,void 0,this,void 0)},L.prototype.then=function(t,e){if(O.warnings()&&arguments.length>0&&"function"!=typeof t&&"function"!=typeof e){var r=".then() only accepts functions but was passed: "+s.classString(t);arguments.length>1&&(r+=", "+s.classString(e)),this._warn(r)}return this._then(t,e,void 0,void 0,void 0)},L.prototype.done=function(t,e){this._then(t,e,void 0,void 0,void 0)._setIsFinal()},L.prototype.spread=function(t){return"function"!=typeof t?n("expecting a function but got "+s.classString(t)):this.all()._then(t,void 0,void 0,b,void 0)},L.prototype.toJSON=function(){var t={isFulfilled:!1,isRejected:!1,fulfillmentValue:void 0,rejectionReason:void 0};return this.isFulfilled()?(t.fulfillmentValue=this.value(),t.isFulfilled=!0):this.isRejected()&&(t.rejectionReason=this.reason(),t.isRejected=!0),t},L.prototype.all=function(){return arguments.length>0&&this._warn(".all() was passed arguments but it does not take any"),new S(this).promise()},L.prototype.error=function(t){return this.caught(s.originatesFromRejection,t)},L.getNewLibraryCopy=t.exports,L.is=function(t){return t instanceof L},L.fromNode=L.fromCallback=function(t){var e=new L(_);e._captureStackTrace();var r=arguments.length>1&&!!Object(arguments[1]).multiArgs,n=P(t)(C(e,r));return n===R&&e._rejectCallback(n.e,!0),e._isFateSealed()||e._setAsyncGuaranteed(),e},L.all=function(t){return new S(t).promise()},L.cast=function(t){var e=w(t);return e instanceof L||((e=new L(_))._captureStackTrace(),e._setFulfilled(),e._rejectionHandler0=t),e},L.resolve=L.fulfilled=L.cast,L.reject=L.rejected=function(t){var e=new L(_);return e._captureStackTrace(),e._rejectCallback(t,!0),e},L.setScheduler=function(t){if("function"!=typeof t)throw new m("expecting a function but got "+s.classString(t));return d.setScheduler(t)},L.prototype._then=function(t,e,r,n,i){var o=void 0!==i,a=o?i:new L(_),u=this._target(),c=u._bitField;o||(a._propagateFrom(this,3),a._captureStackTrace(),void 0===n&&2097152&this._bitField&&(n=50397184&c?this._boundValue():u===this?void 0:this._boundTo),this._fireEvent("promiseChained",this,a));var l=f();if(50397184&c){var h,p,y=u._settlePromiseCtx;33554432&c?(p=u._rejectionHandler0,h=t):16777216&c?(p=u._fulfillmentHandler0,h=e,u._unsetRejectionIsUnhandled()):(y=u._settlePromiseLateCancellationObserver,p=new g("late cancellation observer"),u._attachExtraTrace(p),h=e),d.invoke(y,u,{handler:s.contextBind(l,h),promise:a,receiver:n,value:p})}else u._addCallbacks(t,e,a,n,l);return a},L.prototype._length=function(){return 65535&this._bitField},L.prototype._isFateSealed=function(){return!!(117506048&this._bitField)},L.prototype._isFollowing=function(){return!(67108864&~this._bitField)},L.prototype._setLength=function(t){this._bitField=-65536&this._bitField|65535&t},L.prototype._setFulfilled=function(){this._bitField=33554432|this._bitField,this._fireEvent("promiseFulfilled",this)},L.prototype._setRejected=function(){this._bitField=16777216|this._bitField,this._fireEvent("promiseRejected",this)},L.prototype._setFollowing=function(){this._bitField=67108864|this._bitField,this._fireEvent("promiseResolved",this)},L.prototype._setIsFinal=function(){this._bitField=4194304|this._bitField},L.prototype._isFinal=function(){return(4194304&this._bitField)>0},L.prototype._unsetCancelled=function(){this._bitField=-65537&this._bitField},L.prototype._setCancelled=function(){this._bitField=65536|this._bitField,this._fireEvent("promiseCancelled",this)},L.prototype._setWillBeCancelled=function(){this._bitField=8388608|this._bitField},L.prototype._setAsyncGuaranteed=function(){if(!d.hasCustomScheduler()){var t=this._bitField;this._bitField=t|(536870912&t)>>2^134217728}},L.prototype._setNoAsyncGuarantee=function(){this._bitField=-134217729&this._bitField|536870912},L.prototype._receiverAt=function(t){var e=0===t?this._receiver0:this[4*t-4+3];if(e!==o)return void 0===e&&this._isBound()?this._boundValue():e},L.prototype._promiseAt=function(t){return this[4*t-4+2]},L.prototype._fulfillmentHandlerAt=function(t){return this[4*t-4+0]},L.prototype._rejectionHandlerAt=function(t){return this[4*t-4+1]},L.prototype._boundValue=function(){},L.prototype._migrateCallback0=function(t){t._bitField;var e=t._fulfillmentHandler0,r=t._rejectionHandler0,n=t._promise0,i=t._receiverAt(0);void 0===i&&(i=o),this._addCallbacks(e,r,n,i,null)},L.prototype._migrateCallbackAt=function(t,e){var r=t._fulfillmentHandlerAt(e),n=t._rejectionHandlerAt(e),i=t._promiseAt(e),s=t._receiverAt(e);void 0===s&&(s=o),this._addCallbacks(r,n,i,s,null)},L.prototype._addCallbacks=function(t,e,r,n,i){var o=this._length();if(o>=65531&&(o=0,this._setLength(0)),0===o)this._promise0=r,this._receiver0=n,"function"==typeof t&&(this._fulfillmentHandler0=s.contextBind(i,t)),"function"==typeof e&&(this._rejectionHandler0=s.contextBind(i,e));else{var a=4*o-4;this[a+2]=r,this[a+3]=n,"function"==typeof t&&(this[a+0]=s.contextBind(i,t)),"function"==typeof e&&(this[a+1]=s.contextBind(i,e))}return this._setLength(o+1),o},L.prototype._proxy=function(t,e){this._addCallbacks(void 0,void 0,e,t,null)},L.prototype._resolveCallback=function(t,r){if(!(117506048&this._bitField)){if(t===this)return this._rejectCallback(e(),!1);var n=w(t,this);if(!(n instanceof L))return this._fulfill(t);r&&this._propagateFrom(n,2);var i=n._target();if(i!==this){var o=i._bitField;if(50397184&o)if(33554432&o)this._fulfill(i._value());else if(16777216&o)this._reject(i._reason());else{var s=new g("late cancellation observer");i._attachExtraTrace(s),this._reject(s)}else{var a=this._length();a>0&&i._migrateCallback0(this);for(var u=1;u<a;++u)i._migrateCallbackAt(this,u);this._setFollowing(),this._setLength(0),this._setFollowee(n)}}else this._reject(e())}},L.prototype._rejectCallback=function(t,e,r){var n=s.ensureErrorObject(t),i=n===t;if(!i&&!r&&O.warnings()){var o="a promise was rejected with a non-error: "+s.classString(t);this._warn(o,!0)}this._attachExtraTrace(n,!!e&&i),this._reject(t)},L.prototype._resolveFromExecutor=function(t){if(t!==_){var e=this;this._captureStackTrace(),this._pushContext();var r=!0,n=this._execute(t,function(t){e._resolveCallback(t)},function(t){e._rejectCallback(t,r)});r=!1,this._popContext(),void 0!==n&&e._rejectCallback(n,!0)}},L.prototype._settlePromiseFromHandler=function(t,e,r,n){var i=n._bitField;if(!(65536&i)){var o;n._pushContext(),e===b?r&&"number"==typeof r.length?o=P(t).apply(this._boundValue(),r):(o=R).e=new m("cannot .spread() a non-array: "+s.classString(r)):o=P(t).call(e,r);var a=n._popContext();65536&(i=n._bitField)||(o===v?n._reject(r):o===R?n._rejectCallback(o.e,!1):(O.checkForgottenReturns(o,a,"",n,this),n._resolveCallback(o)))}},L.prototype._target=function(){for(var t=this;t._isFollowing();)t=t._followee();return t},L.prototype._followee=function(){return this._rejectionHandler0},L.prototype._setFollowee=function(t){this._rejectionHandler0=t},L.prototype._settlePromise=function(t,e,n,o){var s=t instanceof L,a=this._bitField,u=!!(134217728&a);65536&a?(s&&t._invokeInternalOnCancel(),n instanceof T&&n.isFinallyHandler()?(n.cancelPromise=t,P(e).call(n,o)===R&&t._reject(R.e)):e===r?t._fulfill(r.call(n)):n instanceof i?n._promiseCancelled(t):s||t instanceof S?t._cancel():n.cancel()):"function"==typeof e?s?(u&&t._setAsyncGuaranteed(),this._settlePromiseFromHandler(e,n,o,t)):e.call(n,o,t):n instanceof i?n._isResolved()||(33554432&a?n._promiseFulfilled(o,t):n._promiseRejected(o,t)):s&&(u&&t._setAsyncGuaranteed(),33554432&a?t._fulfill(o):t._reject(o))},L.prototype._settlePromiseLateCancellationObserver=function(t){var e=t.handler,r=t.promise,n=t.receiver,i=t.value;"function"==typeof e?r instanceof L?this._settlePromiseFromHandler(e,n,i,r):e.call(n,i,r):r instanceof L&&r._reject(i)},L.prototype._settlePromiseCtx=function(t){this._settlePromise(t.promise,t.handler,t.receiver,t.value)},L.prototype._settlePromise0=function(t,e,r){var n=this._promise0,i=this._receiverAt(0);this._promise0=void 0,this._receiver0=void 0,this._settlePromise(n,t,i,e)},L.prototype._clearCallbackDataAtIndex=function(t){var e=4*t-4;this[e+2]=this[e+3]=this[e+0]=this[e+1]=void 0},L.prototype._fulfill=function(t){var r=this._bitField;if(!((117506048&r)>>>16)){if(t===this){var n=e();return this._attachExtraTrace(n),this._reject(n)}this._setFulfilled(),this._rejectionHandler0=t,(65535&r)>0&&(134217728&r?this._settlePromises():d.settlePromises(this),this._dereferenceTrace())}},L.prototype._reject=function(t){var e=this._bitField;if(!((117506048&e)>>>16)){if(this._setRejected(),this._fulfillmentHandler0=t,this._isFinal())return d.fatalError(t,s.isNode);(65535&e)>0?d.settlePromises(this):this._ensurePossibleRejectionHandled()}},L.prototype._fulfillPromises=function(t,e){for(var r=1;r<t;r++){var n=this._fulfillmentHandlerAt(r),i=this._promiseAt(r),o=this._receiverAt(r);this._clearCallbackDataAtIndex(r),this._settlePromise(i,n,o,e)}},L.prototype._rejectPromises=function(t,e){for(var r=1;r<t;r++){var n=this._rejectionHandlerAt(r),i=this._promiseAt(r),o=this._receiverAt(r);this._clearCallbackDataAtIndex(r),this._settlePromise(i,n,o,e)}},L.prototype._settlePromises=function(){var t=this._bitField,e=65535&t;if(e>0){if(16842752&t){var r=this._fulfillmentHandler0;this._settlePromise0(this._rejectionHandler0,r,t),this._rejectPromises(e,r)}else{var n=this._rejectionHandler0;this._settlePromise0(this._fulfillmentHandler0,n,t),this._fulfillPromises(e,n)}this._setLength(0)}this._clearCancellationData()},L.prototype._settledValue=function(){var t=this._bitField;return 33554432&t?this._rejectionHandler0:16777216&t?this._fulfillmentHandler0:void 0},"undefined"!=typeof Symbol&&Symbol.toStringTag&&h.defineProperty(L.prototype,Symbol.toStringTag,{get:function(){return"Object"}}),L.defer=L.pending=function(){return O.deprecated("Promise.defer","new Promise"),{promise:new L(_),resolve:F,reject:A}},s.notEnumerableProp(L,"_makeSelfResolutionError",e),(gd||(gd=1,md=function(t,e,r,n,i){var o=Qp(),s=o.tryCatch;t.method=function(r){if("function"!=typeof r)throw new t.TypeError("expecting a function but got "+o.classString(r));return function(){var n=new t(e);n._captureStackTrace(),n._pushContext();var o=s(r).apply(this,arguments),a=n._popContext();return i.checkForgottenReturns(o,a,"Promise.method",n),n._resolveFromSyncValue(o),n}},t.attempt=t.try=function(r){if("function"!=typeof r)return n("expecting a function but got "+o.classString(r));var a,u=new t(e);if(u._captureStackTrace(),u._pushContext(),arguments.length>1){i.deprecated("calling Promise.try with more than 1 argument");var c=arguments[1],l=arguments[2];a=o.isArray(c)?s(r).apply(l,c):s(r).call(l,c)}else a=s(r)();var f=u._popContext();return i.checkForgottenReturns(a,f,"Promise.try",u),u._resolveFromSyncValue(a),u},t.prototype._resolveFromSyncValue=function(t){t===o.errorObj?this._rejectCallback(t.e,!1):this._resolveCallback(t,!0)}}),md)(L,_,w,n,O),(bd||(bd=1,_d=function(t,e,r,n){var i=!1,o=function(t,e){this._reject(e)},s=function(t,e){e.promiseRejectionQueued=!0,e.bindingPromise._then(o,o,null,this,t)},a=function(t,e){50397184&this._bitField||this._resolveCallback(e.target)},u=function(t,e){e.promiseRejectionQueued||this._reject(t)};t.prototype.bind=function(o){i||(i=!0,t.prototype._propagateFrom=n.propagateFromFunction(),t.prototype._boundValue=n.boundValueFunction());var c=r(o),l=new t(e);l._propagateFrom(this,1);var f=this._target();if(l._setBoundTo(c),c instanceof t){var h={promiseRejectionQueued:!1,promise:l,target:f,bindingPromise:c};f._then(e,s,void 0,l,h),c._then(a,u,void 0,l,h),l._setOnCancel(c)}else l._resolveCallback(f);return l},t.prototype._setBoundTo=function(t){void 0!==t?(this._bitField=2097152|this._bitField,this._boundTo=t):this._bitField=-2097153&this._bitField},t.prototype._isBound=function(){return!(2097152&~this._bitField)},t.bind=function(e,r){return t.resolve(r).bind(e)}}),_d)(L,_,w,O),(wd||(wd=1,vd=function(t,e,r,n){var i=Qp(),o=i.tryCatch,s=i.errorObj,a=t._async;t.prototype.break=t.prototype.cancel=function(){if(!n.cancellation())return this._warn("cancellation is disabled");for(var t=this,e=t;t._isCancellable();){if(!t._cancelBy(e)){e._isFollowing()?e._followee().cancel():e._cancelBranched();break}var r=t._cancellationParent;if(null==r||!r._isCancellable()){t._isFollowing()?t._followee().cancel():t._cancelBranched();break}t._isFollowing()&&t._followee().cancel(),t._setWillBeCancelled(),e=t,t=r}},t.prototype._branchHasCancelled=function(){this._branchesRemainingToCancel--},t.prototype._enoughBranchesHaveCancelled=function(){return void 0===this._branchesRemainingToCancel||this._branchesRemainingToCancel<=0},t.prototype._cancelBy=function(t){return t===this?(this._branchesRemainingToCancel=0,this._invokeOnCancel(),!0):(this._branchHasCancelled(),!!this._enoughBranchesHaveCancelled()&&(this._invokeOnCancel(),!0))},t.prototype._cancelBranched=function(){this._enoughBranchesHaveCancelled()&&this._cancel()},t.prototype._cancel=function(){this._isCancellable()&&(this._setCancelled(),a.invoke(this._cancelPromises,this,void 0))},t.prototype._cancelPromises=function(){this._length()>0&&this._settlePromises()},t.prototype._unsetOnCancel=function(){this._onCancelField=void 0},t.prototype._isCancellable=function(){return this.isPending()&&!this._isCancelled()},t.prototype.isCancellable=function(){return this.isPending()&&!this.isCancelled()},t.prototype._doInvokeOnCancel=function(t,e){if(i.isArray(t))for(var r=0;r<t.length;++r)this._doInvokeOnCancel(t[r],e);else if(void 0!==t)if("function"==typeof t){if(!e){var n=o(t).call(this._boundValue());n===s&&(this._attachExtraTrace(n.e),a.throwLater(n.e))}}else t._resultCancelled(this)},t.prototype._invokeOnCancel=function(){var t=this._onCancel();this._unsetOnCancel(),a.invoke(this._doInvokeOnCancel,this,t)},t.prototype._invokeInternalOnCancel=function(){this._isCancellable()&&(this._doInvokeOnCancel(this._onCancel(),!0),this._unsetOnCancel())},t.prototype._resultCancelled=function(){this.cancel()}}),vd)(L,S,n,O),(Ed||(Ed=1,Sd=function(t){function e(){return this.value}function r(){throw this.reason}t.prototype.return=t.prototype.thenReturn=function(r){return r instanceof t&&r.suppressUnhandledRejections(),this._then(e,void 0,void 0,{value:r},void 0)},t.prototype.throw=t.prototype.thenThrow=function(t){return this._then(r,void 0,void 0,{reason:t},void 0)},t.prototype.catchThrow=function(t){if(arguments.length<=1)return this._then(void 0,r,void 0,{reason:t},void 0);var e=arguments[1];return this.caught(t,function(){throw e})},t.prototype.catchReturn=function(r){if(arguments.length<=1)return r instanceof t&&r.suppressUnhandledRejections(),this._then(void 0,e,void 0,{value:r},void 0);var n=arguments[1];return n instanceof t&&n.suppressUnhandledRejections(),this.caught(r,function(){return n})}}),Sd)(L),by()(L),(Td||(Td=1,Od=function(t,e,r,n,i){var o,s=Qp(),a=s.canEvaluate,u=s.tryCatch,c=s.errorObj;if(a){for(var l=function(t){return new Function("value","holder"," \n\t 'use strict'; \n\t holder.pIndex = value; \n\t holder.checkFulfillment(this); \n\t ".replace(/Index/g,t))},f=function(t){return new Function("promise","holder"," \n\t 'use strict'; \n\t holder.pIndex = promise; \n\t ".replace(/Index/g,t))},h=function(e){for(var r=new Array(e),n=0;n<r.length;++n)r[n]="this.p"+(n+1);var o=r.join(" = ")+" = null;",s="var promise;\n"+r.map(function(t){return" \n\t promise = "+t+"; \n\t if (promise instanceof Promise) { \n\t promise.cancel(); \n\t } \n\t "}).join("\n"),a=r.join(", "),l="Holder$"+e,f="return function(tryCatch, errorObj, Promise, async) { \n\t 'use strict'; \n\t function [TheName](fn) { \n\t [TheProperties] \n\t this.fn = fn; \n\t this.asyncNeeded = true; \n\t this.now = 0; \n\t } \n\t \n\t [TheName].prototype._callFunction = function(promise) { \n\t promise._pushContext(); \n\t var ret = tryCatch(this.fn)([ThePassedArguments]); \n\t promise._popContext(); \n\t if (ret === errorObj) { \n\t promise._rejectCallback(ret.e, false); \n\t } else { \n\t promise._resolveCallback(ret); \n\t } \n\t }; \n\t \n\t [TheName].prototype.checkFulfillment = function(promise) { \n\t var now = ++this.now; \n\t if (now === [TheTotal]) { \n\t if (this.asyncNeeded) { \n\t async.invoke(this._callFunction, this, promise); \n\t } else { \n\t this._callFunction(promise); \n\t } \n\t \n\t } \n\t }; \n\t \n\t [TheName].prototype._resultCancelled = function() { \n\t [CancellationCode] \n\t }; \n\t \n\t return [TheName]; \n\t }(tryCatch, errorObj, Promise, async); \n\t ";return f=f.replace(/\[TheName\]/g,l).replace(/\[TheTotal\]/g,e).replace(/\[ThePassedArguments\]/g,a).replace(/\[TheProperties\]/g,o).replace(/\[CancellationCode\]/g,s),new Function("tryCatch","errorObj","Promise","async",f)(u,c,t,i)},p=[],d=[],y=[],m=0;m<8;++m)p.push(h(m+1)),d.push(l(m+1)),y.push(f(m+1));o=function(t){this._reject(t)}}t.join=function(){var i,u=arguments.length-1;if(u>0&&"function"==typeof arguments[u]&&(i=arguments[u],u<=8&&a)){(w=new t(n))._captureStackTrace();for(var c=new(0,p[u-1])(i),l=d,f=0;f<u;++f){var h=r(arguments[f],w);if(h instanceof t){var m=(h=h._target())._bitField;50397184&m?33554432&m?l[f].call(w,h._value(),c):16777216&m?w._reject(h._reason()):w._cancel():(h._then(l[f],o,void 0,w,c),y[f](h,c),c.asyncNeeded=!1)}else l[f].call(w,h,c)}if(!w._isFateSealed()){if(c.asyncNeeded){var g=t._getContext();c.fn=s.contextBind(g,c.fn)}w._setAsyncGuaranteed(),w._setOnCancel(c)}return w}for(var _=arguments.length,b=new Array(_),v=0;v<_;++v)b[v]=arguments[v];i&&b.pop();var w=new e(b).promise();return void 0!==i?w.spread(i):w}}),Od)(L,S,w,_,d),L.Promise=L,L.version="3.7.2",function(){if(Cd)return jd;Cd=1;var t=Object.create;if(t){var e=t(null),r=t(null);e[" size"]=r[" size"]=0}return jd=function(t){var n,i,o=Qp(),s=o.canEvaluate,a=o.isIdentifier,u=function(t){return new Function("ensureMethod"," \n\t return function(obj) { \n\t 'use strict' \n\t var len = this.length; \n\t ensureMethod(obj, 'methodName'); \n\t switch(len) { \n\t case 1: return obj.methodName(this[0]); \n\t case 2: return obj.methodName(this[0], this[1]); \n\t case 3: return obj.methodName(this[0], this[1], this[2]); \n\t case 0: return obj.methodName(); \n\t default: \n\t return obj.methodName.apply(obj, this); \n\t } \n\t }; \n\t ".replace(/methodName/g,t))(f)},c=function(t){return new Function("obj"," \n\t 'use strict'; \n\t return obj.propertyName; \n\t ".replace("propertyName",t))},l=function(t,e,r){var n=r[t];if("function"!=typeof n){if(!a(t))return null;if(n=e(t),r[t]=n,r[" size"]++,r[" size"]>512){for(var i=Object.keys(r),o=0;o<256;++o)delete r[i[o]];r[" size"]=i.length-256}}return n};function f(e,r){var n;if(null!=e&&(n=e[r]),"function"!=typeof n){var i="Object "+o.classString(e)+" has no method '"+o.toString(r)+"'";throw new t.TypeError(i)}return n}function h(t){return f(t,this.pop()).apply(t,this)}function p(t){return t[this]}function d(t){var e=+this;return e<0&&(e=Math.max(0,e+t.length)),t[e]}n=function(t){return l(t,u,e)},i=function(t){return l(t,c,r)},t.prototype.call=function(t){for(var e=arguments.length,r=new Array(Math.max(e-1,0)),i=1;i<e;++i)r[i-1]=arguments[i];if(s){var o=n(t);if(null!==o)return this._then(o,void 0,void 0,r,void 0)}return r.push(t),this._then(h,void 0,void 0,r,void 0)},t.prototype.get=function(t){var e;if("number"==typeof t)e=d;else if(s){var r=i(t);e=null!==r?r:p}else e=p;return this._then(e,void 0,void 0,t,void 0)}},jd}()(L),vy()(L,n,_,w,i,O),wy()(L,S,n,w,_,O),(Id||(Id=1,Ad=function(t){var e=Qp(),r=t._async,n=e.tryCatch,i=e.errorObj;function o(t,o){if(!e.isArray(t))return s.call(this,t,o);var a=n(o).apply(this._boundValue(),[null].concat(t));a===i&&r.throwLater(a.e)}function s(t,e){var o=this._boundValue(),s=void 0===t?n(e).call(o,null):n(e).call(o,null,t);s===i&&r.throwLater(s.e)}function a(t,e){if(!t){var o=new Error(t+"");o.cause=t,t=o}var s=n(e).call(this._boundValue(),t);s===i&&r.throwLater(s.e)}t.prototype.asCallback=t.prototype.nodeify=function(t,e){if("function"==typeof t){var r=s;void 0!==e&&Object(e).spread&&(r=o),this._then(r,a,void 0,this,t)}return this}}),Ad)(L),Sy()(L,_),Ey()(L,S,w,n),ky()(L,_,w,n),(Hd||(Hd=1,Wd=function(t,e,r,n,i,o){var s=Qp(),a=s.tryCatch;function u(e,r,n,o){this.constructor$(e);var a=t._getContext();this._fn=s.contextBind(a,r),void 0!==n&&(n=t.resolve(n))._attachCancellationCallback(this),this._initialValue=n,this._currentCancellable=null,this._eachValues=o===i?Array(this._length):0===o?null:void 0,this._promise._captureStackTrace(),this._init$(void 0,-5)}function c(t,e){this.isFulfilled()?e._resolve(t):e._reject(t)}function l(t,e,n,i){return"function"!=typeof e?r("expecting a function but got "+s.classString(e)):new u(t,e,n,i).promise()}function f(e){this.accum=e,this.array._gotAccum(e);var r=n(this.value,this.array._promise);return r instanceof t?(this.array._currentCancellable=r,r._then(h,void 0,void 0,this,void 0)):h.call(this,r)}function h(e){var r,n=this.array,i=n._promise,s=a(n._fn);i._pushContext(),(r=void 0!==n._eachValues?s.call(i._boundValue(),e,this.index,this.length):s.call(i._boundValue(),this.accum,e,this.index,this.length))instanceof t&&(n._currentCancellable=r);var u=i._popContext();return o.checkForgottenReturns(r,u,void 0!==n._eachValues?"Promise.each":"Promise.reduce",i),r}s.inherits(u,e),u.prototype._gotAccum=function(t){void 0!==this._eachValues&&null!==this._eachValues&&t!==i&&this._eachValues.push(t)},u.prototype._eachComplete=function(t){return null!==this._eachValues&&this._eachValues.push(t),this._eachValues},u.prototype._init=function(){},u.prototype._resolveEmptyArray=function(){this._resolve(void 0!==this._eachValues?this._eachValues:this._initialValue)},u.prototype.shouldCopyValues=function(){return!1},u.prototype._resolve=function(t){this._promise._resolveCallback(t),this._values=null},u.prototype._resultCancelled=function(e){if(e===this._initialValue)return this._cancel();this._isResolved()||(this._resultCancelled$(),this._currentCancellable instanceof t&&this._currentCancellable.cancel(),this._initialValue instanceof t&&this._initialValue.cancel())},u.prototype._iterate=function(e){var r,n;this._values=e;var i=e.length;void 0!==this._initialValue?(r=this._initialValue,n=0):(r=t.resolve(e[0]),n=1),this._currentCancellable=r;for(var o=n;o<i;++o){var s=e[o];s instanceof t&&s.suppressUnhandledRejections()}if(!r.isRejected())for(;n<i;++n){var a={accum:null,value:e[n],index:n,length:i,array:this};r=r._then(f,void 0,void 0,a,void 0),127&n||r._setNoAsyncGuarantee()}void 0!==this._eachValues&&(r=r._then(this._eachComplete,void 0,void 0,this,void 0)),r._then(c,c,void 0,r,this)},t.prototype.reduce=function(t,e){return l(this,t,e,null)},t.reduce=function(t,e,r,n){return l(t,e,r,n)}}),Wd)(L,S,n,w,_,O),(qd||(qd=1,$d=function(t,e,r){var n=t.PromiseInspection;function i(t){this.constructor$(t)}Qp().inherits(i,e),i.prototype._promiseResolved=function(t,e){return this._values[t]=e,++this._totalResolved>=this._length&&(this._resolve(this._values),!0)},i.prototype._promiseFulfilled=function(t,e){var r=new n;return r._bitField=33554432,r._settledValueField=t,this._promiseResolved(e,r)},i.prototype._promiseRejected=function(t,e){var r=new n;return r._bitField=16777216,r._settledValueField=t,this._promiseResolved(e,r)},t.settle=function(t){return r.deprecated(".settle()",".reflect()"),new i(t).promise()},t.allSettled=function(t){return new i(t).promise()},t.prototype.settle=function(){return t.settle(this)}}),$d)(L,S,O),(Vd||(Vd=1,Gd=function(t,e,r){var n=Qp(),i=hy().RangeError,o=hy().AggregateError,s=n.isArray,a={};function u(t){this.constructor$(t),this._howMany=0,this._unwrap=!1,this._initialized=!1}function c(t,e){if((0|e)!==e||e<0)return r("expecting a positive integer\n\n See http://goo.gl/MqrFmX\n");var n=new u(t),i=n.promise();return n.setHowMany(e),n.init(),i}n.inherits(u,e),u.prototype._init=function(){if(this._initialized)if(0!==this._howMany){this._init$(void 0,-5);var t=s(this._values);!this._isResolved()&&t&&this._howMany>this._canPossiblyFulfill()&&this._reject(this._getRangeError(this.length()))}else this._resolve([])},u.prototype.init=function(){this._initialized=!0,this._init()},u.prototype.setUnwrap=function(){this._unwrap=!0},u.prototype.howMany=function(){return this._howMany},u.prototype.setHowMany=function(t){this._howMany=t},u.prototype._promiseFulfilled=function(t){return this._addFulfilled(t),this._fulfilled()===this.howMany()&&(this._values.length=this.howMany(),1===this.howMany()&&this._unwrap?this._resolve(this._values[0]):this._resolve(this._values),!0)},u.prototype._promiseRejected=function(t){return this._addRejected(t),this._checkOutcome()},u.prototype._promiseCancelled=function(){return this._values instanceof t||null==this._values?this._cancel():(this._addRejected(a),this._checkOutcome())},u.prototype._checkOutcome=function(){if(this.howMany()>this._canPossiblyFulfill()){for(var t=new o,e=this.length();e<this._values.length;++e)this._values[e]!==a&&t.push(this._values[e]);return t.length>0?this._reject(t):this._cancel(),!0}return!1},u.prototype._fulfilled=function(){return this._totalResolved},u.prototype._rejected=function(){return this._values.length-this.length()},u.prototype._addRejected=function(t){this._values.push(t)},u.prototype._addFulfilled=function(t){this._values[this._totalResolved++]=t},u.prototype._canPossiblyFulfill=function(){return this.length()-this._rejected()},u.prototype._getRangeError=function(t){var e="Input array must contain at least "+this._howMany+" items but contains only "+t+" items";return new i(e)},u.prototype._resolveEmptyArray=function(){this._reject(this._getRangeError(0))},t.some=function(t,e){return c(t,e)},t.prototype.some=function(t){return c(this,t)},t._SomePromiseArray=u}),Gd)(L,S,n),xy()(L,_,O),Oy()(L,n,w,x,_,O),(Xd||(Xd=1,Yd=function(t){var e=t._SomePromiseArray;function r(t){var r=new e(t),n=r.promise();return r.setHowMany(1),r.setUnwrap(),r.init(),n}t.any=function(t){return r(t)},t.prototype.any=function(){return r(this)}}),Yd)(L),(ey?ty:(ey=1,ty=function(t,e){var r=t.reduce,n=t.all;function i(){return n(this)}t.prototype.each=function(t){return r(this,t,e,0)._then(i,void 0,void 0,this,void 0)},t.prototype.mapSeries=function(t){return r(this,t,e,e)},t.each=function(t,n){return r(t,n,e,0)._then(i,void 0,void 0,t,void 0)},t.mapSeries=function(t,n){return r(t,n,e,e)}}))(L,_),(ny?ry:(ny=1,ry=function(t,e){var r=t.map;t.prototype.filter=function(t,n){return r(this,t,n,e)},t.filter=function(t,n,i){return r(t,n,i,e)}}))(L,_),s.toFastProperties(L),s.toFastProperties(L.prototype),I({a:1}),I({b:2}),I({c:3}),I(1),I(function(){}),I(void 0),I(!1),I(new L(_)),O.setBounds(p.firstLineError,s.lastLineError),L}),qp.exports;var t}function jy(){if(uy)return ay;uy=1;const t=hf(),e=zp(),r=pf(),n=yf(),i=y,o=Lp(),s=mf(),a=df(),u=function(){if(sy)return oy;var t;sy=1,"undefined"!=typeof Promise&&(t=Promise);var e=Ty()();return e.noConflict=function(){try{Promise===e&&(Promise=t)}catch(t){}return e},oy=e}(),c=Buffer.alloc(4);return c.writeUInt32LE(101010256,0),ay=function(l,f){const h=t(),p=t(),d=f&&f.tailSize||80;let y,m,g,_;return f&&f.crx&&(m=function(e){const r=e.stream(0).pipe(t());return r.pull(4).then(function(t){if(875721283===t.readUInt32LE(0)){let t;return r.pull(12).then(function(e){t=a.parse(e,[["version",4],["pubKeyLength",4],["signatureLength",4]])}).then(function(){return r.pull(t.pubKeyLength+t.signatureLength)}).then(function(e){return t.publicKey=e.slice(0,t.pubKeyLength),t.signature=e.slice(t.pubKeyLength),t.size=16+t.pubKeyLength+t.signatureLength,t})}})}(l)),l.size().then(function(t){return y=t,l.stream(Math.max(0,t-d)).on("error",function(t){h.emit("error",t)}).pipe(h),h.pull(c)}).then(function(){return u.props({directory:h.pull(22),crxHeader:m})}).then(function(e){const r=e.directory;if(g=e.crxHeader&&e.crxHeader.size||0,_=a.parse(r,[["signature",4],["diskNumber",2],["diskStart",2],["numberOfRecordsOnDisk",2],["numberOfRecords",2],["sizeOfCentralDirectory",4],["offsetToStartOfCentralDirectory",4],["commentLength",2]]),65535==_.diskNumber||65535==_.numberOfRecords||4294967295==_.offsetToStartOfCentralDirectory){const e=20,r=y-(d-h.match+e),n=t();return l.stream(r).pipe(n),n.pull(e).then(function(e){return function(e,r){const n=a.parse(r,[["signature",4],["diskNumber",4],["offsetToStartOfCentralDirectory",8],["numberOfDisks",4]]);if(117853008!=n.signature)throw new Error("invalid zip64 end of central dir locator signature (0x07064b50): 0x"+n.signature.toString(16));const i=t();return e.stream(n.offsetToStartOfCentralDirectory).pipe(i),i.pull(56)}(l,e)}).then(function(t){_=function(t){const e=a.parse(t,[["signature",4],["sizeOfCentralDirectory",8],["version",2],["versionsNeededToExtract",2],["diskNumber",4],["diskStart",4],["numberOfRecordsOnDisk",8],["numberOfRecords",8],["sizeOfCentralDirectory",8],["offsetToStartOfCentralDirectory",8]]);if(101075792!=e.signature)throw new Error("invalid zip64 end of central dir locator signature (0x06064b50): 0x0"+e.signature.toString(16));return e}(t)})}_.offsetToStartOfCentralDirectory+=g}).then(function(){if(_.commentLength)return h.pull(_.commentLength).then(function(t){_.comment=t.toString("utf8")})}).then(function(){return l.stream(_.offsetToStartOfCentralDirectory).pipe(p),_.extract=function(t){if(!t||!t.path)throw new Error("PATH_MISSING");return t.path=i.resolve(i.normalize(t.path)),_.files.then(function(e){return u.map(e,async function(e){const r=i.join(t.path,e.path);if(0!=r.indexOf(t.path))return;if("Directory"==e.type)return void await o.ensureDir(r);await o.ensureDir(i.dirname(r));const n=t.getWriter?t.getWriter({path:r}):o.createWriteStream(r);return new Promise(function(r,i){e.stream(t.password).on("error",i).pipe(n).on("close",r).on("error",i)})},{concurrency:t.concurrency>1?t.concurrency:1})})},_.files=u.mapSeries(Array(_.numberOfRecords),function(){return p.pull(46).then(function(t){const i=a.parse(t,[["signature",4],["versionMadeBy",2],["versionsNeededToExtract",2],["flags",2],["compressionMethod",2],["lastModifiedTime",2],["lastModifiedDate",2],["crc32",4],["compressedSize",4],["uncompressedSize",4],["fileNameLength",2],["extraFieldLength",2],["fileCommentLength",2],["diskNumber",2],["internalFileAttributes",2],["externalFileAttributes",4],["offsetToLocalFileHeader",4]]);return i.offsetToLocalFileHeader+=g,i.lastModifiedDateTime=s(i.lastModifiedDate,i.lastModifiedTime),p.pull(i.fileNameLength).then(function(t){return i.pathBuffer=t,i.path=t.toString("utf8"),i.isUnicode=!!(2048&i.flags),p.pull(i.extraFieldLength)}).then(function(t){return i.extra=n(t,i),p.pull(i.fileCommentLength)}).then(function(t){i.comment=t,i.type=0===i.uncompressedSize&&/[/\\]$/.test(i.path)?"Directory":"File";const n=f&&f.padding||1e3;return i.stream=function(t){const r=30+n+(i.extraFieldLength||0)+(i.fileNameLength||0)+i.compressedSize;return e(l,i.offsetToLocalFileHeader,t,i,r)},i.buffer=function(t){return r(i.stream(t))},i})})}),u.props(_)})},ay}var Cy,Ry,Py,Ly=M(Object.freeze({__proto__:null,default:{}}));var Fy=(Py||(Py=1,ff.Parse=gf(),ff.ParseOne=function(){if(Qf)return Vf;Qf=1;const t=g,e=gf(),r=th(),n=pf();return Vf=function(i,o){const s=t.PassThrough({objectMode:!0}),a=t.PassThrough(),u=t.Transform({objectMode:!0}),c=i instanceof RegExp?i:i&&new RegExp(i);let l;u._transform=function(t,e,r){if(l||c&&!c.exec(t.path))return t.autodrain(),r();l=!0,f.emit("entry",t),t.on("error",function(t){a.emit("error",t)}),t.pipe(a).on("error",function(t){r(t)}).on("finish",function(t){r(null,t)})},s.pipe(e(o)).on("error",function(t){a.emit("error",t)}).pipe(u).on("error",Object).on("finish",function(){l?a.end():a.emit("error",new Error("PATTERN_NOT_FOUND"))});const f=r(s,a);return f.buffer=function(){return n(a)},f},Vf}(),ff.Extract=function(){if(lp)return cp;lp=1,cp=function(o){o.path=r.resolve(r.normalize(o.path));const s=new t(o),a=new n.Writable({objectMode:!0});a._write=async function(t,n,i){const s=r.join(o.path,t.path.replace(/\\/g,"/"));if(0!=s.indexOf(o.path))return i();if("Directory"==t.type)return await e.ensureDir(s),i();await e.ensureDir(r.dirname(s));const a=o.getWriter?o.getWriter({path:s}):e.createWriteStream(s);t.pipe(a).on("error",i).on("close",i)};const u=i(s,a);return s.once("crx-header",function(t){u.crxHeader=t}),s.pipe(a).on("finish",function(){u.emit("close")}),u.promise=function(){return new Promise(function(t,e){u.on("close",t),u.on("error",e)})},u};const t=gf(),e=Lp(),r=y,n=g,i=th();return cp}(),ff.Open=function(){if(Ry)return Cy;Ry=1;const t=hr(),e=jy(),r=g;return Cy={buffer:function(t,n){const i={stream:function(e,n){const i=r.PassThrough(),o=n?e+n:void 0;return i.end(t.slice(e,o)),i},size:function(){return Promise.resolve(t.length)}};return e(i,n)},file:function(r,n){const i={stream:function(e,n){const i=n?e+n:void 0;return t.createReadStream(r,{start:e,end:i})},size:function(){return new Promise(function(e,n){t.stat(r,function(t,r){t?n(t):e(r.size)})})}};return e(i,n)},url:function(t,r,n){if("string"==typeof r&&(r={url:r}),!r.url)throw"URL missing";r.headers=r.headers||{};const i={stream:function(e,n){const i=Object.create(r),o=n?e+n:"";return i.headers=Object.create(r.headers),i.headers.range="bytes="+e+"-"+o,t(i)},size:function(){return new Promise(function(e,n){const i=t(r);i.on("response",function(t){i.abort(),t.headers["content-length"]?e(t.headers["content-length"]):n(new Error("Missing content length header"))}).on("error",n)})}};return e(i,n)},s3:function(t,r,n){const i={size:function(){return new Promise(function(e,n){t.headObject(r,function(t,r){t?n(t):e(r.ContentLength)})})},stream:function(e,n){const i={};for(const t in r)i[t]=r[t];const o=n?e+n:"";return i.Range="bytes="+e+"-"+o,t.getObject(i).createReadStream()}};return e(i,n)},s3_v3:function(t,n,i){const{GetObjectCommand:o,HeadObjectCommand:s}=Ly,a={size:async()=>{const e=await t.send(new s({Bucket:n.Bucket,Key:n.Key}));return e.ContentLength?e.ContentLength:0},stream:(e,i)=>{const s=r.PassThrough(),a=i?e+i:"";return t.send(new o({Bucket:n.Bucket,Key:n.Key,Range:`bytes=${e}-${a}`})).then(t=>{t.Body.pipe(s)}).catch(t=>{s.emit("error",t)}),s}};return e(a,i)},custom:function(t,r){return e(t,r)}},Cy}()),ff),Ay=D(Fy);const Iy=new Map,Dy=new Map;function My(t,e){const r={sessionId:e,backupId:t,status:"pending",phase:"Initializing backup restore",progressPercentage:0,progressCurrent:0,progressTotal:0,startTime:(new Date).toISOString(),elapsedSeconds:0,errors:[]};Iy.set(e,r),function(t){const e=setInterval(()=>{const r=Iy.get(t);if(!r)return void clearInterval(e);const n=new Date(r.startTime).getTime(),i=Math.floor((Date.now()-n)/1e3);r.elapsedSeconds=i,"running"!==r.status&&clearInterval(e)},1e3)}(e)}function Ny(t,e){const r=Iy.get(t);if(!r)return;const n="completed"===r.status||"failed"===r.status;Object.assign(r,e),n||(r.status="running")}function By(t,e){const r=Iy.get(t);r&&r.errors.push({...e,timestamp:(new Date).toISOString()})}function Uy(t){return Iy.get(t)??null}function zy(t,e){const r=Iy.get(t);if(!r)return;r.status=e,r.phase="completed"===e?"Restore completed":"Restore failed",r.progressPercentage=100;const n=setTimeout(()=>{Iy.delete(t),Dy.delete(t)},6e4);Dy.set(t,n)}function Wy(){return l(process.env.BACKUP_PATH??"/directus/backups","restore-logs")}function Hy(){const t=Wy();e(t)||n(t,{recursive:!0})}const $y=new Set(["directus_access","directus_activity","directus_collections","directus_comments","directus_dashboards","directus_extensions","directus_fields","directus_files","directus_flows","directus_folders","directus_migrations","directus_notifications","directus_operations","directus_panels","directus_permissions","directus_policies","directus_presets","directus_relations","directus_revisions","directus_roles","directus_sessions","directus_settings","directus_shares","directus_translations","directus_users","directus_versions","directus_webhooks"]);function qy(){return process.env.BACKUP_PATH??"/directus/backups"}function Gy(){const t=qy();e(t)||n(t,{recursive:!0})}let Vy=null;function Qy(){return l(qy(),"schedule.json")}function Zy(){const r=Qy();if(!e(r))return{enabled:!1,cronExpression:"0 2 * * *"};try{const e=t(r,"utf-8");return JSON.parse(e)}catch{return{enabled:!1,cronExpression:"0 2 * * *"}}}function Ky(t){Gy(),r(Qy(),JSON.stringify(t,null,2),"utf-8")}function Jy(t){null!==Vy&&clearInterval(Vy),Vy=setInterval(async()=>{try{const e=Zy();if(!e.enabled)return;const r=new Date,n=new Date(r.getFullYear(),r.getMonth(),r.getDate(),r.getHours(),r.getMinutes());if(!function(t,e){const r=t.trim().split(/\s+/);if(5!==r.length)return!1;function n(t,e){if("*"===t)return!0;if(t.includes("/")){const[,r]=t.split("/"),n=parseInt(r??"1",10);return e%n===0}if(t.includes(","))return t.split(",").some(t=>parseInt(t,10)===e);if(t.includes("-")){const[r,n]=t.split("-"),i=parseInt(r??"0",10),o=parseInt(n??"0",10);return e>=i&&e<=o}return parseInt(t,10)===e}const[i,o,s,a,u]=r;return n(i,e.getMinutes())&&n(o,e.getHours())&&n(s,e.getDate())&&n(a,e.getMonth()+1)&&n(u,e.getDay())}(e.cronExpression,n))return;if(e.lastRun){const t=new Date(e.lastRun);if(new Date(t.getFullYear(),t.getMonth(),t.getDate(),t.getHours(),t.getMinutes()).getTime()===n.getTime())return}t.logger.info("[acuity-backup] Scheduled backup triggered"),await tm(t,{type:"full",includeMedia:!0}),Ky({...e,lastRun:r.toISOString()})}catch(e){t.logger.error("[acuity-backup] Scheduled backup failed:",e)}},6e4)}async function Yy(t){const{CollectionsService:e}=t.services,r=new e({schema:await t.getSchema(),accountability:null});return(await r.readByQuery()).filter(t=>!$y.has(t.collection)&&!t.collection.startsWith("directus_")).map(t=>t.collection)}async function Xy(t,e){const{ItemsService:r}=t.services,n=new r(e,{schema:await t.getSchema(),accountability:null});return await n.readByQuery({limit:-1,fields:["*"]})}async function tm(n,s){const a=await async function(t,n){Gy();const i=(new Date).toISOString().replace(/[:.]/g,"-"),s=k(),a=`backup-${i}-${s}.zip`,c=l(qy(),a),f=await t.getSchema(),{RelationsService:h}=t.services,p="full"===n.type?await Yy(t):n.collections??[],d={};let y=0;for(const e of p)try{const r=await Xy(t,e);d[e]=r,y+=r.length}catch(r){t.logger.warn(`[acuity-backup] Failed to export collection "${e}":`,r),d[e]=[]}const m=new h({schema:f,accountability:null}),g=await m.readAll(),_=await async function(t,e){const r=await t.getSchema(),{ItemsService:n}=t.services;let i=[];try{const t=new n("directus_fields",{schema:r,accountability:null});i=(await t.readByQuery({limit:-1,filter:{collection:{_in:e}},fields:["collection","field","group"]})).filter(t=>null!==t.group&&void 0!==t.group).map(t=>({collection:t.collection,field:t.field,group:t.group}))}catch(e){t.logger.warn("[acuity-backup] Failed to export field groups:",e)}let o=[];try{const t=new n("directus_collections",{schema:r,accountability:null});o=(await t.readByQuery({limit:-1,filter:{collection:{_in:e}},fields:["*"]})).map(t=>{const{collection:e,...r}=t;return{collection:t.collection,display:null,display_template:t.display_template??null,sort_field:t.sort_field??null,hidden:t.hidden??!1,sort:t.sort??null,icon:t.icon??null,note:t.note??null,meta:r}})}catch(e){t.logger.warn("[acuity-backup] Failed to export collection views:",e)}return{schemaVersion:"1.0",fieldGroups:i,collectionViews:o}}(t,p);let b=[];try{const{ItemsService:e}=t.services,r=new e("directus_fields",{schema:f,accountability:null});b=await r.readByQuery({limit:-1,filter:{collection:{_in:p}},fields:["*"]})}catch(e){t.logger.warn("[acuity-backup] Failed to export field metadata:",e)}let v=[];try{const{ItemsService:e}=t.services,r=new e("directus_presets",{schema:f,accountability:null});v=await r.readByQuery({limit:-1,filter:{collection:{_in:p}},fields:["*"]})}catch(e){t.logger.warn("[acuity-backup] Failed to export collection presets:",e)}let w=[];if(n.includeMedia)try{const{ItemsService:e}=t.services,r=new e("directus_files",{schema:f,accountability:null});w=await r.readByQuery({limit:-1,fields:["*"]})}catch(e){t.logger.warn("[acuity-backup] Failed to list media files:",e)}const S={timestamp:(new Date).toISOString(),version:"1.2.0",type:n.type,collections:p,includeMedia:n.includeMedia,totalItems:y,fileSize:0,includesViewsAndGroups:!0};await new Promise((r,i)=>{const s=o(c),a=lf("zip",{zlib:{level:6}});s.on("close",r),a.on("error",i),a.pipe(s),a.append(JSON.stringify(f,null,2),{name:"schema.json"}),a.append(JSON.stringify(g,null,2),{name:"relations.json"}),a.append(JSON.stringify(_,null,2),{name:"views.json"}),a.append(JSON.stringify(b,null,2),{name:"fields-meta.json"}),a.append(JSON.stringify(v,null,2),{name:"presets.json"}),a.append(JSON.stringify(S,null,2),{name:"manifest.json"});for(const[t,e]of Object.entries(d))a.append(JSON.stringify(e,null,2),{name:`collections/${t}.json`});if(n.includeMedia&&w.length>0){const r=process.env.STORAGE_LOCAL_ROOT||"./uploads";for(const n of w){a.append(JSON.stringify(n,null,2),{name:`files/${n.id}.meta.json`});const i=l(r,n.filename_disk);e(i)?a.file(i,{name:`files/${n.id}.bin`}):t.logger.warn(`[acuity-backup] Binary file not found on disk: ${i}`)}}a.finalize()});try{const t=await u(c);S.fileSize=t.size;const e=c.replace(/\.zip$/,".meta.json"),n={id:s,filename:a,timestamp:S.timestamp,type:S.type,collections:S.collections,includeMedia:S.includeMedia,fileSize:S.fileSize};r(e,JSON.stringify(n,null,2),"utf-8")}catch{}return c}(n,s),c=f(a),h=a.replace(/\.zip$/,".meta.json");let p;p=e(h)?JSON.parse(t(h,"utf-8")):{id:k(),filename:c,timestamp:(new Date).toISOString(),type:s.type,collections:s.collections??[],includeMedia:s.includeMedia,fileSize:0};try{const{FilesService:t}=n.services,e=new t({schema:await n.getSchema(),accountability:null}),o=i(a),s=await e.uploadOne(o,{storage:process.env.STORAGE_DEFAULT??process.env.STORAGE_LOCATIONS?.split(",")[0]?.trim()??"local",filename_download:c,type:"application/zip",title:`Backup ${p.timestamp}`});p.directusFileId=String(s),r(h,JSON.stringify(p,null,2),"utf-8")}catch(t){n.logger.warn("[acuity-backup] Failed to upload backup to Directus Files:",t)}return p}async function em(){Gy();const e=qy();let r;try{r=await s(e)}catch{return[]}const n=r.filter(t=>t.endsWith(".meta.json")),i=[];for(const r of n)try{const n=t(l(e,r),"utf-8");i.push(JSON.parse(n))}catch{}return i.sort((t,e)=>new Date(e.timestamp).getTime()-new Date(t.timestamp).getTime())}async function rm(t,n,i){const o=qy(),{backupId:a,truncateCollections:u=!1,collections:c,adminUserId:f}=n;i&&(My(a,i),Ny(i,{phase:"Finding backup archive",progressPercentage:5}));let h,p=null;try{h=await s(o)}catch{throw new Error("Backup directory is not accessible")}for(const t of h)if(t.endsWith(".zip")&&t.includes(a)){p=l(o,t);break}if(!p||!e(p))throw new Error(`Backup with id "${a}" not found`);i&&Ny(i,{phase:"Extracting ZIP archive",progressPercentage:10}),t.logger.info("[acuity-backup] Opening ZIP: "+p);const{ItemsService:d}=t.services,y={},m={},g={},_=await Ay.Open.file(p);for(const t of _.files){const e=t.path;if(e.startsWith("collections/")||"manifest.json"===e||"schema.json"===e||"relations.json"===e||"views.json"===e||"fields-meta.json"===e||"presets.json"===e||e.startsWith("files/")&&e.endsWith(".meta.json")||e.startsWith("files/")&&e.endsWith(".bin")){const r=await t.buffer();e.startsWith("collections/")?y[e]=r:e.endsWith(".bin")?g[e]=r:m[e]=r}}t.logger.info(`[acuity-backup] ZIP extracted: ${Object.keys(y).length} collection files, ${Object.keys(m).length} meta files, ${Object.keys(g).length} binary files`),i&&Ny(i,{phase:"Extraction complete",progressPercentage:20});const b=m["manifest.json"];if(!b)throw new Error("Invalid backup archive: manifest.json not found");const v=JSON.parse(b.toString("utf-8"));let w={},S=[],E=null;const k=m["schema.json"];if(k)try{w=JSON.parse(k.toString("utf-8"))}catch(e){t.logger.warn("[acuity-backup] Failed to parse schema.json:",e)}const x=m["relations.json"];if(x)try{S=JSON.parse(x.toString("utf-8"))}catch(e){t.logger.warn("[acuity-backup] Failed to parse relations.json:",e)}const O=m["views.json"];if(O)try{E=JSON.parse(O.toString("utf-8"))}catch{}let T=[];const j=m["fields-meta.json"];if(j)try{T=JSON.parse(j.toString("utf-8"))}catch(e){t.logger.warn("[acuity-backup] Failed to parse fields-meta.json:",e)}let C=[];const R=m["presets.json"];if(R)try{C=JSON.parse(R.toString("utf-8"))}catch(e){t.logger.warn("[acuity-backup] Failed to parse presets.json:",e)}const P=new Map;for(const t of S){const e=t;"directus_files"===e.related_collection&&e.collection&&e.field&&(P.has(e.collection)||P.set(e.collection,new Set),P.get(e.collection).add(e.field))}for(const t of T){const e=t.special;if(e&&Array.isArray(e)&&e.includes("file")){const e=t.collection,r=t.field;P.has(e)||P.set(e,new Set),P.get(e).add(r)}}const L=new Map;for(const t of S){const e=t;e.collection&&e.field&&(L.has(e.collection)||L.set(e.collection,new Set),L.get(e.collection).add(e.field))}for(const t of T){const e=t.special;if(e&&Array.isArray(e)&&(e.includes("m2o")||e.includes("file")||e.includes("user-created")||e.includes("user-updated"))){const e=t.collection,r=t.field;L.has(e)||L.set(e,new Set),L.get(e).add(r)}}const F=new Map;for(const t of T){const e=t.special;if(e&&Array.isArray(e)&&(e.includes("user-created")||e.includes("user-updated"))){const e=t.collection,r=t.field;F.has(e)||F.set(e,new Set),F.get(e).add(r)}}for(const t of S){const e=t;"directus_users"===e.related_collection&&e.collection&&e.field&&(F.has(e.collection)||F.set(e.collection,new Set),F.get(e.collection).add(e.field))}F.size>0&&t.logger.info(`[acuity-backup] Will remap user references in ${F.size} collections to admin user ${f??"(null)"}`);const A=c??v.collections,I=[];let D=0,M=0,N=0;await async function(t,e,r,n,i,o){const s=await t.getSchema(),{CollectionsService:a,RelationsService:u}=t.services,c=[];let l=0;const f=e?.collections??{},h=new Map;for(const t of o){const e=`${t.collection}.${t.field}`;h.set(e,t)}const p=new a({schema:s,accountability:null});if(i){const e=[];for(const t of i.collectionViews){const r=t.collection;f[r]||n.includes(r)&&e.push(t)}const r=new Set(e.map(t=>t.collection)),o=[],s=new Set,a=t=>{if(s.has(t.collection))return;s.add(t.collection);const n=t.meta?.group;if(n&&r.has(n)){const t=e.find(t=>t.collection===n);t&&a(t)}o.push(t)};for(const t of e)a(t);for(const e of o){const r=e.collection,n=e.meta??{},{id:i,collection:o,...s}=n;s.icon=e.icon??s.icon??null,s.note=e.note??s.note??null,s.sort=e.sort??s.sort??null;try{await p.readOne(r);try{await p.updateOne(r,{meta:s}),t.logger.info(`[acuity-backup] Updated virtual folder "${r}" meta`)}catch{}continue}catch{}try{await p.createOne({collection:r,schema:null,meta:s}),c.push(r),t.logger.info(`[acuity-backup] Created virtual folder collection "${r}"`)}catch(e){t.logger.warn(`[acuity-backup] Failed to create virtual folder "${r}":`,e)}}}const d=n.filter(t=>!s.collections[t]&&!c.includes(t));if(0===d.length&&0===c.length&&0===r.length)return{createdCollections:c,createdRelations:l};d.length>0&&t.logger.info(`[acuity-backup] Need to create ${d.length} missing collection(s): ${d.join(", ")}`);for(const e of d){const r=f[e];if(!r){t.logger.warn(`[acuity-backup] Collection "${e}" not found in backup schema — cannot recreate`);continue}const n=[],o=r.fields??{};for(const[t,i]of Object.entries(o)){const o=t===r.primary,s=`${e}.${t}`,a=h.get(s);if(i.alias){const e={field:i.field??t,type:"alias",schema:null,meta:a?{interface:a.interface,special:a.special??i.special??["alias","no-data"],options:a.options??null,display:a.display??null,display_options:a.display_options??null,width:a.width??"full",sort:a.sort??null,note:a.note??null,group:a.group??null,hidden:a.hidden??!1,required:a.required??!1}:{special:i.special??["alias","no-data"]}};n.push(e);continue}const u={special:i.special??[],hidden:!!o||(a?.hidden??!1),readonly:!!o||(a?.readonly??!1)};a&&(u.interface=a.interface,u.display=a.display??null,u.display_options=a.display_options??null,u.options=a.options??null,u.width=a.width??"full",u.sort=a.sort??null,u.note=a.note??null,u.required=a.required??!1,u.group=a.group??null,a.special&&(u.special=a.special));const c={field:i.field??t,type:i.type,schema:{is_nullable:!o&&!1!==i.nullable,default_value:i.defaultValue??null,is_primary_key:o,has_auto_increment:o&&("integer"===i.type||!0===i.generated)},meta:u};i.maxLength&&(c.schema.max_length=i.maxLength),n.push(c)}let s={};if(i){const t=i.collectionViews.find(t=>t.collection===e);if(t?.meta){const{collection:e,id:r,group:n,...i}=t.meta;s=i}}try{await p.createOne({collection:e,schema:{name:e},meta:{...s,singleton:r.singleton??!1,sort_field:r.sortField??null},fields:n}),c.push(e),t.logger.info(`[acuity-backup] Created collection "${e}" with ${n.length} fields`)}catch(r){t.logger.error(`[acuity-backup] Failed to create collection "${e}":`,r)}}if(r.length>0&&c.length>0){const e=await t.getSchema(),n=new u({schema:e,accountability:null});for(const i of r){const r=i;if((!r.collection?.startsWith("directus_")||!r.related_collection?.startsWith("directus_"))&&(c.includes(r.collection)||null!=r.related_collection&&c.includes(r.related_collection)))if(!e.collections[r.collection]||r.related_collection&&!e.collections[r.related_collection])t.logger.warn(`[acuity-backup] Skipping relation ${r.collection}.${r.field}: one or both collections missing`);else try{const e={...r.meta??{}};delete e.id,await n.createOne({collection:r.collection,field:r.field,related_collection:r.related_collection,meta:e,schema:r.schema??null}),l++,t.logger.info(`[acuity-backup] Created relation: ${r.collection}.${r.field} → ${r.related_collection}`)}catch(e){t.logger.warn(`[acuity-backup] Failed to create relation ${r.collection}.${r.field}:`,e)}}}return{createdCollections:c,createdRelations:l}}(t,w,S,A,E,T);let B=await t.getSchema(),U=0;if(T.length>0){i&&Ny(i,{phase:"Restoring field metadata",progressPercentage:22});const{FieldsService:e}=t.services,r=new e({schema:B,accountability:null}),n=new Map;for(const t of T){const e=`${t.collection}.${t.field}`;n.set(e,t)}for(const e of T){const n=e.collection,i=e.field;if(!A.includes(n))continue;const{id:o,collection:s,field:a,...u}=e;try{await r.updateField(n,i,{meta:u}),U++}catch{const o=e.special;if(o&&Array.isArray(o)&&o.includes("alias"))try{await r.createField(n,{field:i,type:"alias",schema:null,meta:u}),U++}catch(e){t.logger.warn(`[acuity-backup] Failed to create alias field "${n}.${i}":`,e)}}}t.logger.info(`[acuity-backup] Restored metadata for ${U} fields`),B=await t.getSchema()}i&&Ny(i,{phase:"Restoring media files",progressPercentage:25});let z=0;const W={};if(v.includeMedia){const e=new d("directus_files",{schema:B,accountability:null});for(const[n,o]of Object.entries(m))if(n.startsWith("files/")&&n.endsWith(".meta.json"))try{const n=JSON.parse(o.toString("utf-8")),s=n.id;f&&n.uploaded_by?n.uploaded_by=f:n.uploaded_by&&(n.uploaded_by=null),f&&n.modified_by?n.modified_by=f:n.modified_by&&(n.modified_by=null);try{let t=null;try{t=await e.readOne(s)}catch{}if(t){const{id:t,...r}=n;await e.updateOne(s,r),W[s]=s}else{const t=await e.createOne(n);W[s]=String(t)}const i=`files/${s}.bin`;if(g[i]&&n.filename_disk){const t=process.env.STORAGE_LOCAL_ROOT||"./uploads",e=l(t,n.filename_disk);r(e,g[i])}z++}catch(e){t.logger.warn(`[acuity-backup] Failed to restore file record "${s}":`,e),i&&By(i,{message:`Failed to restore file: ${s}`})}}catch{}}t.logger.info(`[acuity-backup] Restored ${z} media file records`),i&&Ny(i,{phase:"Media files restored",progressPercentage:35});const H=new Map,$=new Set(A);for(const t of S){const e=t;e.collection&&e.related_collection&&$.has(e.collection)&&$.has(e.related_collection)&&e.collection!==e.related_collection&&(H.has(e.collection)||H.set(e.collection,new Set),H.get(e.collection).add(e.related_collection))}const q=[],G=new Set,V=new Set,Q=t=>{if(G.has(t))return;if(V.has(t))return;V.add(t);const e=H.get(t);if(e)for(const t of e)$.has(t)&&Q(t);V.delete(t),G.add(t),q.push(t)};for(const t of A)Q(t);t.logger.info(`[acuity-backup] Collection restore order: ${q.join(", ")}`);for(let e=0;e<q.length;e++){const r=q[e],n=`collections/${r}.json`,o=y[n];if(!o){t.logger.warn(`[acuity-backup] Collection file not found in archive: ${n}`),M++,i&&By(i,{collection:r,message:"Collection file not found in archive"});continue}let s;try{s=JSON.parse(o.toString("utf-8"))}catch{t.logger.warn(`[acuity-backup] Failed to parse collection JSON: ${n}`),M++,i&&By(i,{collection:r,message:"Failed to parse collection JSON"});continue}if(!Array.isArray(s)||0===s.length){if(I.push(r),D++,i){const t=35+30*(e+1)/q.length;Ny(i,{phase:`Restoring collections (${e+1}/${q.length})`,progressPercentage:Math.round(t),progressCurrent:e+1,progressTotal:q.length})}continue}const a=L.get(r);if(a)for(const t of s)for(const e of a){const r=t[e];if(null!==r&&"object"==typeof r&&!Array.isArray(r)){const n=r;void 0!==n.id&&(t[e]=n.id)}}const c=P.get(r);if(c&&Object.keys(W).length>0)for(const t of s)for(const e of c){const r=t[e];"string"==typeof r&&W[r]&&W[r]!==r&&(t[e]=W[r])}if(F.has(r)){const t=F.get(r);for(const e of s)for(const r of t)void 0!==e[r]&&null!==e[r]&&(e[r]=f??null)}const l=new d(r,{schema:B,accountability:null});try{if(u){const t=await l.readByQuery({limit:-1,fields:["id"]});if(t.length>0){const e=t.map(t=>t.id);await l.deleteMany(e)}}if(await l.upsertMany(s),I.push(r),D++,N+=s.length,i){const t=35+30*(e+1)/q.length;Ny(i,{phase:`Restoring collections (${e+1}/${q.length})`,progressPercentage:Math.round(t),progressCurrent:e+1,progressTotal:q.length})}}catch(e){t.logger.error(`[acuity-backup] Failed to restore collection "${r}":`,e),M++,i&&By(i,{collection:r,message:String(e)})}}let Z=0,K=0;if(i&&Ny(i,{phase:"Restoring field groups and view settings",progressPercentage:75}),E&&!1!==v.includesViewsAndGroups){const{FieldsService:e,CollectionsService:r}=t.services,n=await t.getSchema();if(E.fieldGroups.length>0){const r=new e({schema:n,accountability:null});for(const e of E.fieldGroups)if(A.includes(e.collection))try{await r.updateField(e.collection,e.field,{group:e.group}),Z++}catch(r){t.logger.warn(`[acuity-backup] Failed to restore group for field "${e.collection}.${e.field}":`,r),i&&By(i,{message:`Failed to restore field group for ${e.collection}.${e.field}`})}}if(E.collectionViews.length>0){const e=new r({schema:n,accountability:null}),o=E.collectionViews.filter(t=>A.includes(t.collection)),s=new Set(o.map(t=>t.collection)),a=[],u=new Set,c=t=>{if(u.has(t.collection))return;u.add(t.collection);const e=t.meta?.group;if(e&&s.has(e)){const t=o.find(t=>t.collection===e);t&&c(t)}a.push(t)};for(const t of o)c(t);for(const r of a){const n=r.meta??{},{id:o,collection:s,...a}=n,u={...a,display:r.display,display_template:r.display_template,sort_field:r.sort_field,hidden:r.hidden,sort:r.sort,icon:r.icon,note:r.note};try{await e.updateOne(r.collection,{meta:u}),K++}catch(e){t.logger.warn(`[acuity-backup] Failed to restore view settings for collection "${r.collection}":`,e),i&&By(i,{collection:r.collection,message:"Failed to restore view settings"})}}}}let J=0;if(i&&Ny(i,{phase:"Restoring collection layout presets",progressPercentage:85}),C.length>0){const{ItemsService:e}=t.services,r=new e("directus_presets",{schema:await t.getSchema(),accountability:null}),n=C.filter(t=>t.collection&&A.includes(t.collection));for(const e of n)try{const{id:t,user:n,...i}=e,o=await r.readByQuery({limit:1,filter:{collection:{_eq:i.collection},user:{_null:!0},...i.bookmark?{bookmark:{_eq:i.bookmark}}:{bookmark:{_null:!0}},...i.role?{role:{_eq:i.role}}:{role:{_null:!0}}},fields:["id"]});o.length>0?await r.updateOne(o[0].id,i):await r.createOne(i),J++}catch(r){t.logger.warn(`[acuity-backup] Failed to restore preset for collection "${e.collection}":`,r),i&&By(i,{collection:e.collection,message:"Failed to restore layout preset"})}}const Y={restoredCollections:I,restoredFiles:z,restoredFieldGroups:Z,restoredCollectionViews:K,restoredPresets:J,errors:[]};if(i){const t=Uy(i);if(t){const e=function(t,e){const r=new Date(t.startTime).getTime(),n=Date.now()-r;return{id:t.sessionId,sessionId:t.sessionId,backupId:t.backupId,timestamp:t.startTime,duration:n,status:"completed"===t.status?0===t.errors.length?"success":"partial":"failed",summary:e,errors:t.errors}}(t,{collectionsAttempted:A.length,collectionsSuccess:D,collectionsFailed:M,itemsRestored:N,mediaFilesRestored:z,fieldGroupsRestored:Z,collectionViewsRestored:K,presetsRestored:J});!function(t){Hy();const e=l(Wy(),`${t.sessionId}.json`);r(e,JSON.stringify(t,null,2),"utf-8")}(e),zy(i,(t.errors.length,"completed"))}Ny(i,{phase:"Restore completed",progressPercentage:100})}return Y}function nm(t,e,r){const n=t.accountability;n?.admin?r():e.status(403).json({errors:[{message:"Forbidden: admin access required",extensions:{code:"FORBIDDEN"}}]})}var im={id:"acuity-backup",handler:(n,f)=>{Jy(f),n.get("/collections",nm,async(t,e)=>{try{const t=await Yy(f),{CollectionsService:r}=f.services,n=new r({schema:await f.getSchema(),accountability:null}),i=(await n.readByQuery()).filter(e=>t.includes(e.collection)).map(t=>({collection:t.collection,icon:t.meta?.icon??null,note:t.meta?.note??null,singleton:t.meta?.singleton??!1}));e.json({data:i})}catch(t){f.logger.error("[acuity-backup] GET /collections error:",t),e.status(500).json({errors:[{message:String(t)}]})}}),n.get("/list",nm,async(t,e)=>{try{const t=await em();e.json({data:t})}catch(t){f.logger.error("[acuity-backup] GET /list error:",t),e.status(500).json({errors:[{message:String(t)}]})}}),n.post("/run",nm,async(t,e)=>{try{const r=t.body,n="selective"===r.type?"selective":"full",i=!1!==r.includeMedia,o="selective"===n?r.collections??[]:void 0;if("selective"===n&&(!o||0===o.length))return void e.status(400).json({errors:[{message:'Selective backup requires at least one collection in the "collections" array.'}]});const s=await tm(f,{type:n,collections:o,includeMedia:i});e.status(201).json({data:s})}catch(t){f.logger.error("[acuity-backup] POST /run error:",t),e.status(500).json({errors:[{message:String(t)}]})}}),n.get("/schedule",nm,(t,e)=>{try{const t=Zy();e.json({data:t})}catch(t){f.logger.error("[acuity-backup] GET /schedule error:",t),e.status(500).json({errors:[{message:String(t)}]})}}),n.post("/schedule",nm,(t,e)=>{try{const r=t.body;if("boolean"!=typeof r.enabled)return void e.status(400).json({errors:[{message:'"enabled" must be a boolean'}]});if("string"!=typeof r.cronExpression||!r.cronExpression.trim())return void e.status(400).json({errors:[{message:'"cronExpression" must be a non-empty string'}]});if(5!==r.cronExpression.trim().split(/\s+/).length)return void e.status(400).json({errors:[{message:'"cronExpression" must be a valid 5-field cron expression (minute hour dom month dow)'}]});const n={...Zy(),enabled:r.enabled,cronExpression:r.cronExpression.trim()};Ky(n),e.json({data:n})}catch(t){f.logger.error("[acuity-backup] POST /schedule error:",t),e.status(500).json({errors:[{message:String(t)}]})}}),n.get("/restore/:id",nm,async(t,e)=>{try{const{id:r}=t.params,n=(await em()).find(t=>t.id===r);if(!n)return void e.status(404).json({errors:[{message:`Backup "${r}" not found`}]});e.json({data:n})}catch(t){f.logger.error("[acuity-backup] GET /restore/:id error:",t),e.status(500).json({errors:[{message:String(t)}]})}}),n.post("/restore",nm,async(t,e)=>{try{const r=t.body;if(!r.backupId||"string"!=typeof r.backupId)return void e.status(400).json({errors:[{message:'"backupId" is required'}]});const n=t.accountability,i=n?.user??null,o=k(),s={backupId:r.backupId,truncateCollections:r.truncateCollections??!1,collections:r.collections,sessionId:o,adminUserId:i};e.json({data:{sessionId:o,message:"Restore started. Poll /acuity-backup/status/:sessionId for progress."}}),(async()=>{try{await rm(f,s,o)}catch(t){f.logger.error("[acuity-backup] Background restore error:",t);Uy(o)&&(By(o,{message:String(t)}),zy(o,"failed"))}})()}catch(t){f.logger.error("[acuity-backup] POST /restore error:",t),e.status(500).json({errors:[{message:String(t)}]})}}),n.delete("/:id",nm,async(t,r)=>{try{const{id:n}=t.params,i=(await em()).find(t=>t.id===n);if(!i)return void r.status(404).json({errors:[{message:`Backup "${n}" not found`}]});const o=l(qy(),i.filename),s=o.replace(/\.zip$/,".meta.json"),u=[];e(o)&&u.push(a(o)),e(s)&&u.push(a(s)),await Promise.all(u),r.json({data:{success:!0,id:n}})}catch(t){f.logger.error("[acuity-backup] DELETE /:id error:",t),r.status(500).json({errors:[{message:String(t)}]})}}),n.get("/status/:sessionId",nm,(t,e)=>{try{const{sessionId:r}=t.params,n=Uy(r);if(!n)return void e.status(404).json({errors:[{message:`Session "${r}" not found`}]});e.json({data:n})}catch(t){f.logger.error("[acuity-backup] GET /status/:sessionId error:",t),e.status(500).json({errors:[{message:String(t)}]})}}),n.get("/restore-logs",nm,async(e,r)=>{try{const e=await async function(){Hy();const e=Wy();try{const r=await s(e),n=[];for(const i of r){if(!i.endsWith(".json"))continue;const r=l(e,i);try{const e=t(r,"utf-8"),i=JSON.parse(e);n.push(i)}catch{}}return n.sort((t,e)=>new Date(e.timestamp).getTime()-new Date(t.timestamp).getTime()),n}catch{return[]}}();r.json({data:e})}catch(t){f.logger.error("[acuity-backup] GET /restore-logs error:",t),r.status(500).json({errors:[{message:String(t)}]})}}),n.get("/restore-logs/:logId",nm,(r,n)=>{try{const{logId:i}=r.params,o=function(r){Hy();const n=l(Wy(),`${r}.json`);if(!e(n))return null;try{const e=t(n,"utf-8");return JSON.parse(e)}catch{return null}}(i);if(!o)return void n.status(404).json({errors:[{message:`Restore log "${i}" not found`}]});n.json({data:o})}catch(t){f.logger.error("[acuity-backup] GET /restore-logs/:logId error:",t),n.status(500).json({errors:[{message:String(t)}]})}}),n.delete("/restore-logs/:logId",nm,async(t,r)=>{try{const{logId:n}=t.params;await async function(t){const r=l(Wy(),`${t}.json`);e(r)&&await a(r)}(n),r.json({data:{success:!0,logId:n}})}catch(t){f.logger.error("[acuity-backup] DELETE /restore-logs/:logId error:",t),r.status(500).json({errors:[{message:String(t)}]})}}),n.get("/download/:id",nm,async(t,r)=>{try{const{id:n}=t.params,o=(await em()).find(t=>t.id===n);if(!o)return void r.status(404).json({errors:[{message:`Backup "${n}" not found`}]});const s=l(qy(),o.filename);if(!e(s))return void r.status(404).json({errors:[{message:`Backup file "${o.filename}" not found on disk`}]});r.setHeader("Content-Type","application/zip"),r.setHeader("Content-Disposition",`attachment; filename="${o.filename}"`);i(s).pipe(r)}catch(t){f.logger.error("[acuity-backup] GET /download/:id error:",t),r.status(500).json({errors:[{message:String(t)}]})}}),n.post("/upload",nm,async(t,n)=>{try{const{fileId:s}=t.body;if(!s||"string"!=typeof s)return void n.status(400).json({errors:[{message:'"fileId" is required. Upload the ZIP via POST /files first.'}]});const{ItemsService:p}=f.services,d=new p("directus_files",{schema:await f.getSchema(),accountability:null});let y;try{y=await d.readOne(s)}catch{return void n.status(404).json({errors:[{message:`File "${s}" not found in Directus.`}]})}const m=process.env.STORAGE_LOCAL_ROOT||"./uploads",g=y.filename_disk,_=l(m,g);if(!e(_))return void n.status(400).json({errors:[{message:"Uploaded file not found on disk. Only local storage is currently supported for backup uploads."}]});const b=await u(_);if(b.size>524288e3)return void n.status(413).json({errors:[{message:`Upload too large (${Math.round(b.size/1024/1024)} MB). Maximum is 500 MB.`}]});Gy();const v=qy(),w=k(),S=l(v,`upload-temp-${w}.zip`);let E;await h(i(_),o(S));try{const t=(await Ay.Open.file(S)).files.find(t=>"manifest.json"===t.path);if(!t)return await a(S),void n.status(400).json({errors:[{message:"Invalid backup: ZIP does not contain a manifest.json file."}]});const e=await t.buffer();E=JSON.parse(e.toString("utf-8"))}catch(t){return await a(S),void n.status(400).json({errors:[{message:"Invalid or corrupted ZIP file: "+String(t)}]})}const x=k(),O=E.timestamp||(new Date).toISOString(),T=`backup-${O.replace(/[:.]/g,"-").replace("T","_").slice(0,19)}-${x}.zip`,j=l(v,T);await c(S,j);const C={id:x,filename:T,timestamp:O,type:E.type??"full",collections:E.collections??[],includeMedia:E.includeMedia??!1,fileSize:b.size},R=j.replace(/\.zip$/,".meta.json");r(R,JSON.stringify(C,null,2),"utf-8");try{await d.deleteOne(s)}catch{}f.logger.info(`[acuity-backup] Uploaded backup: ${T} (${Math.round(b.size/1024)} KB)`),n.json({data:C})}catch(t){f.logger.error("[acuity-backup] POST /upload error:",t),n.status(500).json({errors:[{message:String(t)}]})}}),async function(){Hy();const t=Wy(),e=Date.now()-7776e6;let r=0;try{const n=await s(t);for(const i of n){if(!i.endsWith(".json"))continue;const n=l(t,i);try{(await u(n)).mtime.getTime()<e&&(await a(n),r++)}catch{}}}catch{}return r}().then(t=>{t>0&&f.logger.info(`[acuity-backup] Cleaned up ${t} restore logs older than 90 days`)})}};const om=[],sm=[{name:"backup-endpoint",config:im}],am=[];export{sm as endpoints,om as hooks,am as operations};
|
package/package.json
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"name": "@acuity/directus-extension-acuity-backup",
|
|
3
3
|
"description": "Backup Directus collections, schema, and media files to ZIP archives. Provided free, courtesy of Acuity Consulting Inc. — we help companies build smarter systems, automate workflows with AI, and scale with confidence.",
|
|
4
4
|
"icon": "icon.png",
|
|
5
|
-
"version": "2.1.
|
|
5
|
+
"version": "2.1.4",
|
|
6
6
|
"license": "MIT",
|
|
7
7
|
"author": {
|
|
8
8
|
"name": "Acuity Consulting Inc.",
|
|
@@ -41,7 +41,7 @@
|
|
|
41
41
|
"entries": [
|
|
42
42
|
{
|
|
43
43
|
"type": "endpoint",
|
|
44
|
-
"name": "
|
|
44
|
+
"name": "backup-endpoint",
|
|
45
45
|
"source": "src/backup-endpoint/index.ts"
|
|
46
46
|
},
|
|
47
47
|
{
|